diff --git a/.deepsource.toml b/.deepsource.toml deleted file mode 100644 index e68653328f..0000000000 --- a/.deepsource.toml +++ /dev/null @@ -1,7 +0,0 @@ -version = 1 - -test_patterns = ["zarr/tests/test_*.py"] - -[[analyzers]] -name = "python" -enabled = true diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 29281f5be9..9503f3df8a 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -1,4 +1,4 @@ Contributing ============ -Please see the [project documentation](https://zarr.readthedocs.io/en/stable/contributing.html) for information about contributing to Zarr. +Please see the [project documentation](https://zarr.readthedocs.io/en/stable/developers/contributing.html) for information about contributing to Zarr. diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index ba05f23fcc..e765e3136e 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -1,5 +1,5 @@ -name: πŸ› File a bug report -description: X's behavior is deviating from its documented behavior. +name: Bug Report +description: Report incorrect behaviour in the library. labels: ["bug"] body: - type: markdown @@ -27,7 +27,7 @@ body: attributes: label: Python Version description: Version of Python interpreter - placeholder: 3.8.5, 3.9, 3.10, etc. + placeholder: 3.10, 3.11, 3.12 etc. validations: required: true - type: input @@ -57,7 +57,22 @@ body: id: reproduce attributes: label: Steps to reproduce - description: Minimal, reproducible code sample, a copy-pastable example if possible. + description: Minimal, reproducible code sample. Must list dependencies in [inline script metadata](https://packaging.python.org/en/latest/specifications/inline-script-metadata/#example). When put in a file named `issue.py` calling `uv run issue.py` should show the issue. + value: | + ```python + # /// script + # requires-python = ">=3.12" + # dependencies = [ + # "zarr@git+https://github.com/zarr-developers/zarr-python.git@main", + # ] + # /// + # + # This script automatically imports the development branch of zarr to check for issues + + import zarr + # your reproducer code + # zarr.print_debug_info() + ``` validations: required: true - type: textarea diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 9cb5ec9a78..d219a73737 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,11 +1,11 @@ blank_issues_enabled: true contact_links: - - name: ✨ Propose a new major feature + - name: Propose a new Zarr specification feature url: https://github.com/zarr-developers/zarr-specs - about: A new major feature should be discussed in the Zarr specifications repository. - - name: ❓ Discuss something on gitter - url: https://gitter.im/zarr-developers/community - about: For questions like "How do I do X with Zarr?", you can move to our Gitter channel. - - name: ❓ Discuss something on GitHub Discussions + about: A new feature for the Zarr storage specification should be opened on the zarr-specs repository. + - name: Discuss something on ZulipChat + url: https://ossci.zulipchat.com/ + about: For questions like "How do I do X with Zarr?", consider posting your question to our developer chat. + - name: Discuss something on GitHub Discussions url: https://github.com/zarr-developers/zarr-python/discussions about: For questions like "How do I do X with Zarr?", you can move to GitHub Discussions. diff --git a/.github/ISSUE_TEMPLATE/documentation.yml b/.github/ISSUE_TEMPLATE/documentation.yml new file mode 100644 index 0000000000..c240666d1f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/documentation.yml @@ -0,0 +1,18 @@ +name: Documentation Improvement +description: Report missing or wrong documentation. Alternatively, you can just open a pull request with the suggested change. +title: "DOC: " +labels: [documentation, help wanted] + +body: +- type: textarea + attributes: + label: Describe the issue linked to the documentation + description: > + Please provide a description of what documentation you believe needs to be fixed/improved. + validations: + required: true +- type: textarea + attributes: + label: Suggested fix for documentation + description: > + Please explain the suggested fix and why it's better than the existing documentation. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000000..f067655f22 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,11 @@ +name: Feature Request +description: Request a new feature for zarr-python +# labels: [] +body: +- type: textarea + attributes: + label: Describe the new feature you'd like + description: > + Please provide a description of what new feature or functionality you'd like to see in zarr-python. + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/release-checklist.md b/.github/ISSUE_TEMPLATE/release-checklist.md new file mode 100644 index 0000000000..309c76b4dc --- /dev/null +++ b/.github/ISSUE_TEMPLATE/release-checklist.md @@ -0,0 +1,53 @@ +--- +name: Zarr-Python release checklist +about: Checklist for a new Zarr-Python release. [For project maintainers only!] +title: Release Zarr-Python vX.Y.Z +labels: release-checklist +assignees: '' + +--- + +**Release**: [v3.x.x](https://github.com/zarr-developers/zarr-python/milestones/?) +**Scheduled Date**: 20YY/MM/DD + +**Priority PRs/issues to complete prior to release** + +- [ ] Priority pull request #X + +**Before release**: + +- [ ] Check [SPEC 0](https://scientific-python.org/specs/spec-0000/#support-window) to see if the minimum supported version of Python or NumPy needs bumping. +- [ ] Verify that the latest CI workflows on `main` are passing: [Tests](https://github.com/zarr-developers/zarr-python/actions/workflows/test.yml), [GPU Tests](https://github.com/zarr-developers/zarr-python/actions/workflows/gpu_test.yml), [Hypothesis](https://github.com/zarr-developers/zarr-python/actions/workflows/hypothesis.yaml), [Docs](https://github.com/zarr-developers/zarr-python/actions/workflows/docs.yml), [Lint](https://github.com/zarr-developers/zarr-python/actions/workflows/lint.yml), [Wheels](https://github.com/zarr-developers/zarr-python/actions/workflows/releases.yml). +- [ ] Run the [downstream tests](https://github.com/zarr-developers/zarr-python/actions/workflows/downstream.yml) against `main`: go to the workflow page, click "Run workflow", and select the `main` branch. Verify that the Xarray and numcodecs integration tests pass. +- [ ] Open a release PR with the changelog entries for the upcoming release, generated with `uv run --only-group release towncrier build --version x.y.z`. +- [ ] Review the release PR and verify the changelog in `docs/release-notes.md` looks correct. +- [ ] Merge the release PR. + +**Release**: + +- [ ] [Draft a new GitHub Release](https://github.com/zarr-developers/zarr-python/releases/new) with tag `vX.Y.Z` targeting `main`. Use "Generate release notes" for the description. +- [ ] Verify the release is published on [PyPI](https://pypi.org/project/zarr/) and [ReadTheDocs](https://zarr.readthedocs.io/en/stable/). + +**After release**: + +- [ ] Review and merge the pull request on the conda-forge [zarr-feedstock](https://github.com/conda-forge/zarr-feedstock) that will be automatically generated. + +--- + +- [ ] Party :tada: + +--- + +
+Releasing from a branch other than main + +In rare cases (e.g. patch releases for an older minor version), you may need to release from a dedicated release branch (e.g. `3.1.x`): + +- Create the release branch from the appropriate tag if it doesn't already exist. +- Cherry-pick or backport the necessary commits onto the branch. +- Run `towncrier build --version x.y.z` and open the release PR against the release branch instead of `main`. +- Run the downstream tests against the release branch instead of `main`. +- When drafting the GitHub Release, set the target to the release branch instead of `main`. +- After the release, ensure any relevant changelog updates are also reflected on `main`. + +
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index a0d41f9841..47adb4b19e 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,9 +1,27 @@ -[Description of PR] + + +## Summary + +[Describe what this PR changes and why, in your own words.] + +## For reviewers + +[What would you most value a second look at? What are you already confident in? For a refactor, say whether behavior is meant to be unchanged.] + +## Author attestation + +- [ ] I am a human, these are my changes, and I have reviewed and understood every change and can explain why each is correct. + + + +## TODO -TODO: * [ ] Add unit tests and/or doctests in docstrings * [ ] Add docstrings and API docs for any new/modified user-facing classes and functions -* [ ] New/modified features documented in docs/tutorial.rst -* [ ] Changes documented in docs/release.rst +* [ ] New/modified features documented in `docs/user-guide/*.md` +* [ ] Changes documented as a new file in `changes/` * [ ] GitHub Actions have all passed * [ ] Test coverage is 100% (Codecov passes) diff --git a/.github/codecov.yml b/.github/codecov.yml deleted file mode 100644 index e9b99c8214..0000000000 --- a/.github/codecov.yml +++ /dev/null @@ -1,15 +0,0 @@ -coverage: - status: - project: - default: - target: 100 - threshold: 0.1 - patch: - default: - target: 100 -comment: - layout: "diff, files" - behavior: default - require_changes: true # if true: only post the comment if coverage changes - branches: # branch names that can post comment - - "main" diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 52fe24c7a7..0c794d9b08 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,19 +1,33 @@ --- version: 2 updates: - - package-ecosystem: "pip" + # Updates for main + - package-ecosystem: "github-actions" directory: "/" schedule: - interval: "daily" + interval: "weekly" groups: actions: patterns: - "*" - - package-ecosystem: "github-actions" + cooldown: + default-days: 7 + # Keep the pinned dev tooling in pyproject.toml's [dependency-groups] and the + # uv.lock current. Without this the exact pins (e.g. pytest) would never be + # bumped automatically and would silently rot. + # + # `allow: dependency-type: direct` restricts updates to dependencies declared + # in pyproject.toml. Transitive deps in uv.lock are then only updated as a + # side effect of a direct bump, never via a standalone PR. + - package-ecosystem: "uv" directory: "/" + allow: + - dependency-type: "direct" schedule: interval: "weekly" groups: - actions: + python-dependencies: patterns: - "*" + cooldown: + default-days: 7 diff --git a/.github/labeler.yml b/.github/labeler.yml index dbc3b95333..7eb74211ea 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -1,2 +1,4 @@ needs release notes: -- all: ['!docs/release.rst'] + - all: + - changed-files: + - all-globs-to-all-files: '!changes/*.md' diff --git a/.github/workflows/check_changelogs.yml b/.github/workflows/check_changelogs.yml new file mode 100644 index 0000000000..c391f63738 --- /dev/null +++ b/.github/workflows/check_changelogs.yml @@ -0,0 +1,37 @@ +name: Check changelog entries + +on: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + check-changelogs: + name: Check changelog entries + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 #Β v7.0.1 + with: + persist-credentials: false + + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + + - name: Check zarr-python changelog entries + run: uv run --no-sync python ci/check_changelog_entries.py + + - name: Check zarr-metadata changelog entries + run: uv run --no-sync python ci/check_changelog_entries.py packages/zarr-metadata/changes + + - name: Check zarr-indexing changelog entries + run: uv run --no-sync python ci/check_changelog_entries.py packages/zarr-indexing/changes + + - name: Check zarr-http-server changelog entries + run: uv run --no-sync python ci/check_changelog_entries.py packages/zarr-http-server/changes diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml deleted file mode 100644 index bb3d433629..0000000000 --- a/.github/workflows/codeql-analysis.yml +++ /dev/null @@ -1,72 +0,0 @@ -# For most projects, this workflow file will not need changing; you simply need -# to commit it to your repository. -# -# You may wish to alter this file to override the set of languages analyzed, -# or to provide custom queries or build logic. -# -# ******** NOTE ******** -# We have attempted to detect the languages in your repository. Please check -# the `language` matrix defined below to confirm you have the correct set of -# supported CodeQL languages. -# -name: "CodeQL" - -on: - push: - branches: [ "main" ] - pull_request: - # The branches below must be a subset of the branches above - branches: [ "main" ] - schedule: - - cron: '29 0 * * 1' - -jobs: - analyze: - name: Analyze - runs-on: ubuntu-latest - permissions: - actions: read - contents: read - security-events: write - - strategy: - fail-fast: false - matrix: - language: [ 'python' ] - # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] - # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support - - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v3 - with: - languages: ${{ matrix.language }} - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. - - # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs - # queries: security-extended,security-and-quality - - - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: github/codeql-action/autobuild@v3 - - # ℹ️ Command-line programs to run using the OS shell. - # πŸ“š See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun - - # If the Autobuild fails above, remove it and uncomment the following three lines. - # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. - - # - run: | - # echo "Run, Build Application using script" - # ./location_of_script_within_repo/buildscript.sh - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v3 diff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.yml new file mode 100644 index 0000000000..f36fbff233 --- /dev/null +++ b/.github/workflows/codspeed.yml @@ -0,0 +1,40 @@ +name: CodSpeed Benchmarks + +on: + schedule: + - cron: '0 9 * * 1' # Every Monday at 9am UTC + pull_request: + types: [labeled] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + benchmarks: + name: Run benchmarks + runs-on: codspeed-macro + if: | + github.event_name == 'schedule' || + github.event_name == 'workflow_dispatch' || + (github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'benchmark')) + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + - name: Install Hatch + uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc + with: + version: '1.16.5' + - name: Run the benchmarks + uses: CodSpeedHQ/action@0ca9cbbf4623b599a6c3ed4fc8a922942705d9f1 # v5.0.2 + env: + ZARR_BENCHMARK_CLEAR_CACHE: '1' + with: + mode: walltime + run: hatch run test.py3.12-minimal:pytest tests/benchmarks --codspeed diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000000..792ee431ab --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,40 @@ +name: Docs + +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + docs: + name: Check docs + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + - run: uv sync --group docs + # Fast source-level guards that need no built site, so they run before the (slower) + # build for a quick failure: every public export is in the API reference, and no + # docstring/Markdown carries reStructuredText markup that MkDocs won't render. + - run: uv run python ci/check_documented_exports.py docs/api + - run: uv run python ci/lint_docs.py + # --strict turns warnings into errors, so a docs code block that fails to execute + # at build time (e.g. a non-exec python fence disrupting a later exec="true" block) + # fails CI instead of merging as a silent warning. + - run: uv run mkdocs build --strict + env: + DISABLE_MKDOCS_2_WARNING: "true" + NO_MKDOCS_2_WARNING: "true" + - run: uv run python ci/check_unlinked_types.py + continue-on-error: true diff --git a/.github/workflows/downstream.yml b/.github/workflows/downstream.yml new file mode 100644 index 0000000000..98cd0fee3f --- /dev/null +++ b/.github/workflows/downstream.yml @@ -0,0 +1,129 @@ +name: Downstream + +on: + workflow_dispatch: + pull_request: + types: [labeled, synchronize, opened, reopened] + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + xarray: + name: Xarray zarr backend tests + if: | + github.event_name == 'workflow_dispatch' + || contains(github.event.pull_request.labels.*.name, 'run-downstream') + runs-on: ubuntu-latest + steps: + - name: Check out zarr-python + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Check out xarray + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: pydata/xarray + path: xarray + persist-credentials: false + + # We install xarray with plain pip/uv rather than pixi. pixi solves + # xarray's entire manifest (it has no committed lockfile), which drags in + # the `mypy-upstream` environment; that environment sources numcodecs from + # git and fails to build under newer pixi with + # `meson-python: error: Unknown option "pixi-conda-environment"`, breaking + # the job before any test runs. Tests that need a backend we don't install + # are skipped via xarray's `requires_*` markers, not failed. + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: '3.13' + + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + + - name: Install xarray and test dependencies + working-directory: xarray + run: | + uv venv + # xarray's pytest tooling lives in the PEP 735 `dev` dependency group; + # the zarr-relevant backends come from the `io` and `parallel` extras. + uv pip install --group dev ".[io,parallel,accel]" + + - name: Override zarr-python with branch version + working-directory: xarray + run: uv pip install --no-deps .. + + - name: Show versions + working-directory: xarray + run: | + uv run python -c " + import zarr; print(f'zarr {zarr.__version__}') + import xarray; print(f'xarray {xarray.__version__}') + " + + - name: Run xarray zarr backend tests + working-directory: xarray + run: | + uv run python -m pytest --no-header -q \ + xarray/tests/test_backends.py \ + xarray/tests/test_backends_api.py \ + xarray/tests/test_backends_datatree.py + + numcodecs: + name: numcodecs zarr3 codec tests + if: | + github.event_name == 'workflow_dispatch' + || contains(github.event.pull_request.labels.*.name, 'run-downstream') + runs-on: ubuntu-latest + steps: + - name: Check out zarr-python + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Check out numcodecs + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: zarr-developers/numcodecs + fetch-depth: 0 + path: numcodecs + submodules: recursive + persist-credentials: false + + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: '3.13' + + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + + - name: Install numcodecs with test-zarr-main group + working-directory: numcodecs + run: | + uv venv + uv pip install --group dev + uv sync --group dev --group test-zarr-main + uv pip install --no-build-isolation -e . + + - name: Override zarr-python with branch version + working-directory: numcodecs + run: uv pip install --no-deps .. + + - name: Show versions + working-directory: numcodecs + run: | + uv run python -c " + import zarr; print(f'zarr {zarr.__version__}') + import numcodecs; print(f'numcodecs {numcodecs.__version__}') + " + + - name: Run numcodecs zarr3 tests + working-directory: numcodecs + run: uv run python -m pytest -x --no-header -q tests/test_zarr3.py diff --git a/.github/workflows/gpu_test.yml b/.github/workflows/gpu_test.yml new file mode 100644 index 0000000000..bf8700400e --- /dev/null +++ b/.github/workflows/gpu_test.yml @@ -0,0 +1,87 @@ +# This workflow will install Python dependencies, run tests and lint with a variety of Python versions +# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions + +name: GPU Test + +on: + push: + branches: [ main, 3.1.x ] + pull_request: + branches: [ main, 3.1.x ] + workflow_dispatch: + +env: + LD_LIBRARY_PATH: /usr/local/cuda/extras/CUPTI/lib64:/usr/local/cuda/lib64 + # Use the uv from astral-sh/setup-uv instead of hatch's bundled (pyapp) uv. + HATCH_ENV_TYPE_VIRTUAL_UV_PATH: uv + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: py=${{ matrix.python-version }} + environment: + name: codecov-upload + deployment: false + runs-on: gpu-runner + strategy: + matrix: + python-version: ['3.12'] + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 # grab all branches and tags + persist-credentials: false + # - name: cuda-toolkit + # uses: Jimver/cuda-toolkit@v0.2.16 + # id: cuda-toolkit + # with: + # cuda: '12.4.1' + - name: Set up CUDA + run: | + wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-keyring_1.1-1_all.deb + sudo dpkg -i cuda-keyring_1.1-1_all.deb + sudo apt-get update + sudo apt-get -y install cuda-toolkit-12-6 + echo "/usr/local/cuda/bin" >> $GITHUB_PATH + - name: GPU check + run: | + nvidia-smi + echo $PATH + echo $LD_LIBRARY_PATH + nvcc -V + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: ${{ matrix.python-version }} + cache: 'pip' + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + - name: Install Hatch + uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc + with: + version: '1.16.5' + - name: Set Up Hatch Env + env: + HATCH_ENV: gputest.py${{ matrix.python-version }} + run: | + hatch env create "$HATCH_ENV" + hatch env run -e "$HATCH_ENV" list-env + - name: Run Tests + env: + HATCH_ENV: gputest.py${{ matrix.python-version }} + run: | + hatch env run --env "$HATCH_ENV" run-coverage + + - name: Upload coverage + uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 + with: + token: ${{ secrets.CODECOV_TOKEN }} + flags: gpu + verbose: true # optional (default = false) diff --git a/.github/workflows/hypothesis.yaml b/.github/workflows/hypothesis.yaml index c5a239c274..f463397c85 100644 --- a/.github/workflows/hypothesis.yaml +++ b/.github/workflows/hypothesis.yaml @@ -1,25 +1,36 @@ name: Slow Hypothesis CI on: push: - branches: - - "main" - - "v3" + branches: [main, 3.1.x] pull_request: - branches: - - "main" - - "v3" + branches: [main, 3.1.x] types: [opened, reopened, synchronize, labeled] schedule: - cron: "0 0 * * *" # Daily β€œAt 00:00” UTC workflow_dispatch: # allows you to trigger manually +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + env: FORCE_COLOR: 3 + # Use the uv from astral-sh/setup-uv instead of hatch's bundled (pyapp) uv. + HATCH_ENV_TYPE_VIRTUAL_UV_PATH: uv jobs: hypothesis: name: Slow Hypothesis Tests + permissions: + contents: read + issues: write + environment: + name: codecov-upload + deployment: false runs-on: "ubuntu-latest" defaults: run: @@ -27,29 +38,43 @@ jobs: strategy: matrix: - python-version: ['3.11'] - numpy-version: ['1.26'] + python-version: ['3.12'] dependency-set: ["optional"] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set HYPOTHESIS_PROFILE based on trigger + env: + EVENT_NAME: ${{ github.event_name }} + run: | + if [[ "$EVENT_NAME" == "schedule" || "$EVENT_NAME" == "workflow_dispatch" ]]; then + echo "HYPOTHESIS_PROFILE=nightly" >> $GITHUB_ENV + else + echo "HYPOTHESIS_PROFILE=ci" >> $GITHUB_ENV + fi - name: Set up Python - uses: actions/setup-python@v5 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: ${{ matrix.python-version }} cache: 'pip' + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 - name: Install Hatch - run: | - python -m pip install --upgrade pip - pip install hatch + uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc + with: + version: '1.16.5' - name: Set Up Hatch Env + env: + HATCH_ENV: test.py${{ matrix.python-version }}-${{ matrix.dependency-set }} run: | - hatch env create test.py${{ matrix.python-version }}-${{ matrix.numpy-version }}-${{ matrix.dependency-set }} - hatch env run -e test.py${{ matrix.python-version }}-${{ matrix.numpy-version }}-${{ matrix.dependency-set }} list-env + hatch env create "$HATCH_ENV" + hatch env run -e "$HATCH_ENV" list-env # https://github.com/actions/cache/blob/main/tips-and-workarounds.md#update-a-cache - name: Restore cached hypothesis directory id: restore-hypothesis-cache - uses: actions/cache/restore@v4 + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: .hypothesis/ key: cache-hypothesis-${{ runner.os }}-${{ github.run_id }} @@ -59,26 +84,37 @@ jobs: - name: Run slow Hypothesis tests if: success() id: status + env: + HATCH_ENV: test.py${{ matrix.python-version }}-${{ matrix.dependency-set }} + PYTEST_ADDOPTS: "--report-log=output-${{ matrix.python-version }}-log.jsonl" run: | - hatch env run --env test.py${{ matrix.python-version }}-${{ matrix.numpy-version }}-${{ matrix.dependency-set }} run-hypothesis + echo "Using Hypothesis profile: $HYPOTHESIS_PROFILE" + hatch env run --env "$HATCH_ENV" run-hypothesis # explicitly save the cache so it gets updated, also do this even if it fails. - name: Save cached hypothesis directory id: save-hypothesis-cache if: always() && steps.status.outcome != 'skipped' - uses: actions/cache/save@v4 + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: .hypothesis/ key: cache-hypothesis-${{ runner.os }}-${{ github.run_id }} + - name: Upload coverage + uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 + with: + token: ${{ secrets.CODECOV_TOKEN }} + flags: tests + verbose: true # optional (default = false) + - name: Generate and publish the report if: | failure() && steps.status.outcome == 'failure' && github.event_name == 'schedule' && github.repository_owner == 'zarr-developers' - uses: xarray-contrib/issue-from-pytest-log@v1 + uses: scientific-python/issue-from-pytest-log-action@35b4e0a9e06f8e7e261778289cf4b968b722662d # v1.6.2 with: log-path: output-${{ matrix.python-version }}-log.jsonl issue-title: "Nightly Hypothesis tests failed" - issue-label: "topic-hypothesis" + issue-label: "automated issue" diff --git a/.github/workflows/issue-metrics.yml b/.github/workflows/issue-metrics.yml index 34bda59ff6..adbd2748a0 100644 --- a/.github/workflows/issue-metrics.yml +++ b/.github/workflows/issue-metrics.yml @@ -7,13 +7,17 @@ on: permissions: contents: read +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + jobs: build: name: issue metrics runs-on: ubuntu-latest permissions: - issues: write - pull-requests: read + issues: write # Required to create the metrics report issue + pull-requests: read # Required to read PR metrics steps: - name: Get dates for last month shell: bash @@ -29,13 +33,13 @@ jobs: echo "last_month=$first_day..$last_day" >> "$GITHUB_ENV" - name: Run issue-metrics tool - uses: github/issue-metrics@v3 + uses: github-community-projects/issue-metrics@df8c49d20958f9345281fa2124858bd0ad227e1f # v5.0.0 env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} SEARCH_QUERY: 'repo:zarr-developers/zarr-python is:issue created:${{ env.last_month }} -reason:"not planned"' - name: Create issue - uses: peter-evans/create-issue-from-file@v5 + uses: peter-evans/create-issue-from-file@fca9117c27cdc29c6c4db3b86c48e4115a786710 # v6.0.0 with: title: Monthly issue metrics report token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/links.yml b/.github/workflows/links.yml new file mode 100644 index 0000000000..d52639a708 --- /dev/null +++ b/.github/workflows/links.yml @@ -0,0 +1,32 @@ +name: Check links + +on: + repository_dispatch: + workflow_dispatch: + # pull_request: + schedule: + - cron: "00 18 * * 1" # weekly, Mondays at 18:00 UTC + +jobs: + linkChecker: + runs-on: ubuntu-latest + permissions: + issues: write # required for peter-evans/create-issue-from-file + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Link Checker + id: lychee + uses: lycheeverse/lychee-action@e7477775783ea5526144ba13e8db5eec57747ce8 # v2.9.0 + with: + fail: false + + - name: Create Issue From File + if: steps.lychee.outputs.exit_code != 0 + uses: peter-evans/create-issue-from-file@fca9117c27cdc29c6c4db3b86c48e4115a786710 # v6.0.0 + with: + title: Link Checker Report + content-filepath: ./lychee/out.md + labels: report, automated issue diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000000..83cc0a1b3e --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,33 @@ +name: Lint + +on: + push: + branches: [main, 3.1.x] + pull_request: + branches: [main, 3.1.x] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.12" + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - uses: j178/prek-action@4e14d07f9231acabce116ccfca13b13dd9755ece # v3.0.0 diff --git a/.github/workflows/needs_release_notes.yml b/.github/workflows/needs_release_notes.yml index d81ee0bdc4..e001e8cd43 100644 --- a/.github/workflows/needs_release_notes.yml +++ b/.github/workflows/needs_release_notes.yml @@ -1,14 +1,27 @@ name: "Pull Request Labeler" on: - - pull_request_target + # pull_request_target is needed to label PRs from forks. + # This workflow only runs actions/labeler (no code checkout), so it's safe. + pull_request_target: # zizmor: ignore[dangerous-triggers] + types: [opened, reopened, synchronize] + +permissions: {} + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number }} + cancel-in-progress: true jobs: - triage: - if: ${{ github.event.pull_request.user.login != 'dependabot[bot]' }} && ${{ github.event.pull_request.user.login != 'pre-commit-ci[bot]' }} + labeler: + name: Label pull request + if: ${{ github.event.pull_request.user.login != 'dependabot[bot]' && github.event.pull_request.user.login != 'pre-commit-ci[bot]' }} + permissions: + contents: read # Required to read label configuration + pull-requests: write # Required to add labels to PRs runs-on: ubuntu-latest steps: - - uses: actions/labeler@main + - uses: actions/labeler@bf12e9b00b37c5c0ca2b87b79b2daf7891dbda13 # v7.0.0 with: repo-token: ${{ secrets.GITHUB_TOKEN }} sync-labels: true diff --git a/.github/workflows/nightly_wheels.yml b/.github/workflows/nightly_wheels.yml new file mode 100644 index 0000000000..5b99c523a1 --- /dev/null +++ b/.github/workflows/nightly_wheels.yml @@ -0,0 +1,48 @@ +name: Nightly Wheels + +on: + schedule: + # Run nightly at 2 AM UTC + - cron: '0 2 * * *' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build_and_upload_nightly: + name: Build and upload nightly wheels + environment: + name: nightly-wheel-upload + deployment: false + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + submodules: true + fetch-depth: 0 + persist-credentials: false + + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + name: Install Python + with: + python-version: '3.14' + + - name: Install Hatch + uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc + with: + version: '1.16.5' + + - name: Build wheel and sdist + run: hatch build + + - name: Upload nightly wheels + uses: scientific-python/upload-nightly-action@e76cfec8a4611fd02808a801b0ff5a7d7c1b2d99 + with: + artifacts_path: dist + anaconda_nightly_upload_token: ${{ secrets.ANACONDA_ORG_UPLOAD_TOKEN }} diff --git a/.github/workflows/releases.yml b/.github/workflows/releases.yml index b54cbe48b3..a08d5a6d3f 100644 --- a/.github/workflows/releases.yml +++ b/.github/workflows/releases.yml @@ -1,6 +1,21 @@ name: Wheels -on: [push, pull_request] +on: + release: + types: + - published + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true jobs: @@ -11,32 +26,34 @@ jobs: fail-fast: false steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: submodules: true fetch-depth: 0 + persist-credentials: false - - uses: actions/setup-python@v5 + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 name: Install Python with: - python-version: '3.11' + python-version: '3.12' - - name: Install PyBuild - run: | - python -m pip install --upgrade pip - pip install hatch + - name: Install Hatch + uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc + with: + version: '1.16.5' - name: Build wheel and sdist run: hatch build - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: releases path: dist test_dist_pypi: + name: Test distribution artifacts needs: [build_artifacts] runs-on: ubuntu-latest steps: - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: name: releases path: dist @@ -47,16 +64,25 @@ jobs: ls dist upload_pypi: - needs: [build_artifacts] + name: Upload to PyPI + needs: [build_artifacts, test_dist_pypi] runs-on: ubuntu-latest - if: github.event_name == 'push' && startsWith(github.event.ref, 'refs/tags/v') + if: github.event_name == 'release' + environment: + name: releases + url: https://pypi.org/p/zarr + permissions: + id-token: write # Required for OIDC trusted publishing to PyPI + attestations: write # Required for artifact attestation + artifact-metadata: write # Required for artifact attestation metadata steps: - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: name: releases path: dist - - uses: pypa/gh-action-pypi-publish@v1.9.0 + - name: Generate artifact attestation + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 with: - user: __token__ - password: ${{ secrets.pypi_password }} - # To test: repository_url: https://test.pypi.org/legacy/ + subject-path: dist/* + - name: Publish package to PyPI + uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 48e579711b..50bb85ff5c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,45 +1,205 @@ # This workflow will install Python dependencies, run tests and lint with a variety of Python versions # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions -name: Test V3 +name: Test on: push: - branches: [ v3 ] + branches: [ main, 3.1.x ] pull_request: - branches: [ v3 ] + branches: [ main, 3.1.x ] workflow_dispatch: +permissions: + contents: read + +env: + # Use the uv from astral-sh/setup-uv; without an explicit path hatch + # bootstraps its own (pyapp) uv, which fails on non-3.12 runners. + HATCH_ENV_TYPE_VIRTUAL_UV_PATH: uv + concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: test: - name: py=${{ matrix.python-version }}, np=${{ matrix.numpy-version }}, deps=${{ matrix.dependency-set }} + name: os=${{ matrix.os }}, py=${{ matrix.python-version }}, deps=${{ matrix.dependency-set }} + environment: + name: codecov-upload + deployment: false + defaults: + run: + shell: bash - runs-on: ubuntu-latest strategy: matrix: - python-version: ['3.10', '3.11', '3.12'] - numpy-version: ['1.24', '1.26', '2.0'] + python-version: ['3.12', '3.13', '3.14'] dependency-set: ["minimal", "optional"] + os: ["ubuntu-latest"] + include: + - python-version: '3.12' + dependency-set: 'optional' + os: 'macos-latest' + + - python-version: '3.14' + dependency-set: 'optional' + os: 'macos-latest' + + - python-version: '3.12' + dependency-set: 'optional' + os: 'windows-latest' + + - python-version: '3.14' + dependency-set: 'optional' + os: 'windows-latest' + runs-on: ${{ matrix.os }} + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 # grab all branches and tags + persist-credentials: false + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: ${{ matrix.python-version }} + cache: 'pip' + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + - name: Install Hatch + run: python -m pip install hatch==1.16.5 + - name: Set Up Hatch Env + env: + HATCH_ENV: test.py${{ matrix.python-version }}-${{ matrix.dependency-set }} + run: | + hatch env create "$HATCH_ENV" + hatch env run -e "$HATCH_ENV" list-env + - name: Run Tests + env: + HYPOTHESIS_PROFILE: ci + HATCH_ENV: test.py${{ matrix.python-version }}-${{ matrix.dependency-set }} + run: | + hatch env run --env "$HATCH_ENV" run-coverage + - name: Upload coverage + if: ${{ matrix.dependency-set == 'optional' && matrix.os == 'ubuntu-latest' }} + uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 + with: + token: ${{ secrets.CODECOV_TOKEN }} + flags: tests + verbose: true # optional (default = false) + test-upstream-and-min-deps: + name: py=${{ matrix.python-version }}-${{ matrix.dependency-set }} + environment: + name: codecov-upload + deployment: false + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ['3.12', "3.14"] + dependency-set: ["upstream", "min_deps"] + exclude: + - python-version: "3.14" + dependency-set: min_deps + - python-version: "3.12" + dependency-set: upstream steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false - name: Set up Python - uses: actions/setup-python@v5 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: ${{ matrix.python-version }} cache: 'pip' + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 - name: Install Hatch + run: python -m pip install hatch==1.16.5 + - name: Set Up Hatch Env + env: + HATCH_ENV: ${{ matrix.dependency-set }} run: | - python -m pip install --upgrade pip - pip install hatch + hatch env create "$HATCH_ENV" + hatch env run -e "$HATCH_ENV" list-env + - name: Run Tests + env: + HATCH_ENV: ${{ matrix.dependency-set }} + run: | + hatch env run --env "$HATCH_ENV" run-coverage + - name: Upload coverage + uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 + with: + token: ${{ secrets.CODECOV_TOKEN }} + flags: tests + verbose: true # optional (default = false) + + doctests: + name: doctests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 # required for hatch version discovery, which is needed for numcodecs.zarr3 + persist-credentials: false + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: '3.13' + cache: 'pip' + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + - name: Install Hatch + run: python -m pip install hatch==1.16.5 - name: Set Up Hatch Env run: | - hatch env create test.py${{ matrix.python-version }}-${{ matrix.numpy-version }}-${{ matrix.dependency-set }} - hatch env run -e test.py${{ matrix.python-version }}-${{ matrix.numpy-version }}-${{ matrix.dependency-set }} list-env + hatch run doctest:pip list - name: Run Tests run: | - hatch env run --env test.py${{ matrix.python-version }}-${{ matrix.numpy-version }}-${{ matrix.dependency-set }} run + hatch run doctest:test + + benchmarks: + name: Benchmark smoke test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: '3.13' + cache: 'pip' + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + - name: Install Hatch + run: python -m pip install hatch==1.16.5 + - name: Run Benchmarks + env: + ZARR_BENCHMARK_CLEAR_CACHE: '1' + run: | + hatch env run --env "test.py3.13-minimal" run-benchmark + + test-complete: + name: Test complete + + needs: + [ + test, + test-upstream-and-min-deps, + doctests, + benchmarks + ] + if: always() + runs-on: ubuntu-latest + steps: + - name: Check failure + if: | + contains(needs.*.result, 'failure') || + contains(needs.*.result, 'cancelled') + run: exit 1 + - name: Success + run: echo Success! diff --git a/.github/workflows/zarr-http-server-release.yml b/.github/workflows/zarr-http-server-release.yml new file mode 100644 index 0000000000..b78fa29ab7 --- /dev/null +++ b/.github/workflows/zarr-http-server-release.yml @@ -0,0 +1,117 @@ +name: zarr-http-server release + +on: + workflow_dispatch: + push: + tags: + - 'zarr_http_server-v*' + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +jobs: + build: + name: Build wheel and sdist + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-http-server + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 0 # hatch-vcs needs full history + tags + + - name: Install Hatch + uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc + with: + version: '1.16.5' + + - name: Build + run: hatch build + + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: zarr-http-server-dist + path: packages/zarr-http-server/dist + + test_artifacts: + name: Test built artifacts + needs: [build] + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-http-server-dist + path: dist + + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: false + + - name: Set up Python + run: uv python install 3.12 + + - name: Install built wheel and run import smoke test + run: | + wheel=$(ls dist/*.whl) + uv run --with "${wheel}" --python 3.12 --no-project \ + python -c "import zarr_http_server; print('zarr_http_server', zarr_http_server.__version__)" + + upload_pypi: + name: Upload to PyPI + needs: [build, test_artifacts] + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/zarr_http_server-v') + runs-on: ubuntu-latest + environment: + name: zarr-http-server-releases + url: https://pypi.org/p/zarr-http-server + permissions: + id-token: write # required for OIDC trusted publishing + attestations: write # required for artifact attestations + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-http-server-dist + path: dist + + - name: Generate artifact attestation + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-path: dist/* + + - name: Publish package to PyPI + uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + + upload_testpypi: + name: Upload to TestPyPI + needs: [build, test_artifacts] + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + environment: + name: zarr-http-server-releases-test + url: https://test.pypi.org/p/zarr-http-server + permissions: + id-token: write + attestations: write + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-http-server-dist + path: dist + + - name: Generate artifact attestation + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-path: dist/* + + - name: Publish package to TestPyPI + uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + with: + repository-url: https://test.pypi.org/legacy/ diff --git a/.github/workflows/zarr-http-server.yml b/.github/workflows/zarr-http-server.yml new file mode 100644 index 0000000000..16589f0d7d --- /dev/null +++ b/.github/workflows/zarr-http-server.yml @@ -0,0 +1,139 @@ +name: zarr-http-server + +# Job steps delegate to packages/zarr-http-server/justfile, the single source +# of truth for this package's verbs; CI owns only the python matrix and +# caching. Keeping the commands in one place is what makes `just check` +# locally mean the same thing as a green run here. + +on: + push: + branches: [main] + paths: + - 'packages/zarr-http-server/**' + - '.github/workflows/zarr-http-server.yml' + # The package resolves zarr from the repo root for its own tests, so a + # core change can break it. Run this suite when core changes too. + - 'src/zarr/**' + pull_request: + paths: + - 'packages/zarr-http-server/**' + - '.github/workflows/zarr-http-server.yml' + # The package resolves zarr from the repo root for its own tests, so a + # core change can break it. Run this suite when core changes too. + - 'src/zarr/**' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: pytest py=${{ matrix.python-version }} + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-http-server + strategy: + fail-fast: false + matrix: + python-version: ['3.12', '3.13', '3.14'] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Set up Python ${{ matrix.python-version }} + run: uv python install ${{ matrix.python-version }} + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Sync test dependency groups + # The examples group carries the deps the README examples need, so the + # test that reads a served array back with a zarr client runs here + # instead of silently skipping. + run: uv sync --group test --group examples --python ${{ matrix.python-version }} + - name: Run pytest + run: just test + + ruff: + name: ruff + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-http-server + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Run ruff + run: just lint + + mypy: + name: mypy + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-http-server + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Set up Python + run: uv python install 3.12 + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Sync test dependency group + run: uv sync --group test --python 3.12 + - name: Run mypy + run: just typecheck + + docs: + name: docs + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-http-server + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Build docs + run: just docs-check + + zarr-http-server-complete: + name: zarr-http-server complete + needs: [test, ruff, mypy, docs] + if: always() + runs-on: ubuntu-latest + steps: + - name: Check failure + if: | + contains(needs.*.result, 'failure') || + contains(needs.*.result, 'cancelled') + run: exit 1 + - name: Success + run: echo Success! diff --git a/.github/workflows/zarr-indexing-release.yml b/.github/workflows/zarr-indexing-release.yml new file mode 100644 index 0000000000..2c35abad9f --- /dev/null +++ b/.github/workflows/zarr-indexing-release.yml @@ -0,0 +1,117 @@ +name: zarr-indexing release + +on: + workflow_dispatch: + push: + tags: + - 'zarr_indexing-v*' + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +jobs: + build: + name: Build wheel and sdist + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-indexing + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 0 # hatch-vcs needs full history + tags + + - name: Install Hatch + uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc + with: + version: '1.16.5' + + - name: Build + run: hatch build + + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: zarr-indexing-dist + path: packages/zarr-indexing/dist + + test_artifacts: + name: Test built artifacts + needs: [build] + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-indexing-dist + path: dist + + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: false + + - name: Set up Python + run: uv python install 3.12 + + - name: Install built wheel and run import smoke test + run: | + wheel=$(ls dist/*.whl) + uv run --with "${wheel}" --python 3.12 --no-project \ + python -c "import zarr_indexing; print('zarr_indexing', zarr_indexing.__version__)" + + upload_pypi: + name: Upload to PyPI + needs: [build, test_artifacts] + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/zarr_indexing-v') + runs-on: ubuntu-latest + environment: + name: zarr-indexing-releases + url: https://pypi.org/p/zarr-indexing + permissions: + id-token: write # required for OIDC trusted publishing + attestations: write # required for artifact attestations + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-indexing-dist + path: dist + + - name: Generate artifact attestation + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-path: dist/* + + - name: Publish package to PyPI + uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + + upload_testpypi: + name: Upload to TestPyPI + needs: [build, test_artifacts] + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + environment: + name: zarr-indexing-releases-test + url: https://test.pypi.org/p/zarr-indexing + permissions: + id-token: write + attestations: write + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-indexing-dist + path: dist + + - name: Generate artifact attestation + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-path: dist/* + + - name: Publish package to TestPyPI + uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + with: + repository-url: https://test.pypi.org/legacy/ diff --git a/.github/workflows/zarr-indexing.yml b/.github/workflows/zarr-indexing.yml new file mode 100644 index 0000000000..61776df913 --- /dev/null +++ b/.github/workflows/zarr-indexing.yml @@ -0,0 +1,136 @@ +name: zarr-indexing + +on: + push: + branches: [main] + paths: + - 'packages/zarr-indexing/**' + - '.github/workflows/zarr-indexing.yml' + pull_request: + paths: + - 'packages/zarr-indexing/**' + - '.github/workflows/zarr-indexing.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: pytest py=${{ matrix.python-version }} + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-indexing + strategy: + fail-fast: false + matrix: + python-version: ['3.12', '3.13', '3.14'] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Set up Python ${{ matrix.python-version }} + run: uv python install ${{ matrix.python-version }} + # The transform tests exercise chunk resolution against zarr's ChunkGrid, + # so they run against the repo-root environment (which provides `zarr`) + # with this package as an editable overlay rather than in package + # isolation. The recipes carry that invocation; this step only fixes the + # interpreter the matrix asked for. + - name: Sync test dependency group + run: uv sync --project ../.. --group test --python ${{ matrix.python-version }} + - name: Run pytest + # Suites and invocation live in packages/zarr-indexing/justfile. + run: just test + - name: Run pytest (tensorstore parity) + run: just test-tensorstore + + ruff: + name: ruff + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-indexing + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Run ruff + # The ruff version pin lives in packages/zarr-indexing/justfile. + run: just lint + + pyright: + name: pyright + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-indexing + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Set up Python + run: uv python install 3.12 + - name: Sync test dependency group + run: uv sync --group test --python 3.12 + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Run pyright + # The pyright invocation lives in packages/zarr-indexing/justfile. + run: just typecheck + + docs: + name: docs + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-indexing + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Build docs + # The strict mkdocs build lives in packages/zarr-indexing/justfile. + run: just docs-check + + zarr-indexing-complete: + name: zarr-indexing complete + needs: [test, ruff, pyright, docs] + if: always() + runs-on: ubuntu-latest + steps: + - name: Check failure + if: | + contains(needs.*.result, 'failure') || + contains(needs.*.result, 'cancelled') + run: exit 1 + - name: Success + run: echo Success! diff --git a/.github/workflows/zarr-metadata-release.yml b/.github/workflows/zarr-metadata-release.yml new file mode 100644 index 0000000000..17c285ded6 --- /dev/null +++ b/.github/workflows/zarr-metadata-release.yml @@ -0,0 +1,117 @@ +name: zarr-metadata release + +on: + workflow_dispatch: + push: + tags: + - 'zarr_metadata-v*' + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +jobs: + build: + name: Build wheel and sdist + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-metadata + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 0 # hatch-vcs needs full history + tags + + - name: Install Hatch + uses: pypa/hatch@257e27e51a6a5616ed08a39a408a21c35c9931bc + with: + version: '1.16.5' + + - name: Build + run: hatch build + + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: zarr-metadata-dist + path: packages/zarr-metadata/dist + + test_artifacts: + name: Test built artifacts + needs: [build] + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-metadata-dist + path: dist + + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: false + + - name: Set up Python + run: uv python install 3.12 + + - name: Install built wheel and run import smoke test + run: | + wheel=$(ls dist/*.whl) + uv run --with "${wheel}" --python 3.12 --no-project \ + python -c "import zarr_metadata; print('zarr_metadata', zarr_metadata.__version__)" + + upload_pypi: + name: Upload to PyPI + needs: [build, test_artifacts] + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/zarr_metadata-v') + runs-on: ubuntu-latest + environment: + name: zarr-metadata-releases + url: https://pypi.org/p/zarr-metadata + permissions: + id-token: write # required for OIDC trusted publishing + attestations: write # required for artifact attestations + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-metadata-dist + path: dist + + - name: Generate artifact attestation + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-path: dist/* + + - name: Publish package to PyPI + uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + + upload_testpypi: + name: Upload to TestPyPI + needs: [build, test_artifacts] + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + environment: + name: zarr-metadata-releases-test + url: https://test.pypi.org/p/zarr-metadata + permissions: + id-token: write + attestations: write + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: zarr-metadata-dist + path: dist + + - name: Generate artifact attestation + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-path: dist/* + + - name: Publish package to TestPyPI + uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + with: + repository-url: https://test.pypi.org/legacy/ diff --git a/.github/workflows/zarr-metadata.yml b/.github/workflows/zarr-metadata.yml new file mode 100644 index 0000000000..5b3b83b0e0 --- /dev/null +++ b/.github/workflows/zarr-metadata.yml @@ -0,0 +1,125 @@ +name: zarr-metadata + +# Job steps delegate to packages/zarr-metadata/justfile, the single source of +# truth for this package's verbs; CI owns only the python matrix and caching. + +on: + push: + branches: [main] + paths: + - 'packages/zarr-metadata/**' + - '.github/workflows/zarr-metadata.yml' + pull_request: + paths: + - 'packages/zarr-metadata/**' + - '.github/workflows/zarr-metadata.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: pytest py=${{ matrix.python-version }} + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-metadata + strategy: + fail-fast: false + matrix: + python-version: ['3.11', '3.12', '3.13', '3.14'] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Set up Python ${{ matrix.python-version }} + run: uv python install ${{ matrix.python-version }} + - name: Sync test dependency group + run: uv sync --group test --python ${{ matrix.python-version }} + - name: Run pytest + run: just test + + ruff: + name: ruff + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-metadata + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Run ruff + run: just lint + + pyright: + name: pyright + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-metadata + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Run pyright + # The pyright version and interpreter pins live in the justfile. + run: just typecheck + + docs: + name: docs + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-metadata + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + - name: Build docs + run: just docs-check + + zarr-metadata-complete: + name: zarr-metadata complete + needs: [test, ruff, pyright, docs] + if: always() + runs-on: ubuntu-latest + steps: + - name: Check failure + if: | + contains(needs.*.result, 'failure') || + contains(needs.*.result, 'cancelled') + run: exit 1 + - name: Success + run: echo Success! diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml new file mode 100644 index 0000000000..c90ba718f6 --- /dev/null +++ b/.github/workflows/zizmor.yml @@ -0,0 +1,35 @@ +name: GitHub Actions Security Analysis + +on: + push: + branches: [main] + paths: + - '.github/workflows/**' + - '.github/actions/**' + pull_request: + branches: ["**"] + paths: + - '.github/workflows/**' + - '.github/actions/**' + workflow_dispatch: + +permissions: {} + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + zizmor: + name: Run zizmor + runs-on: ubuntu-latest + permissions: + security-events: write # Required by zizmor-action to upload SARIF files + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Run zizmor + uses: zizmorcore/zizmor-action@3dc1ecc9bcb9e94e9b2c709687979e1298497054 # v0.6.2 diff --git a/.gitignore b/.gitignore index 84bcb00ffb..59b6632a3c 100644 --- a/.gitignore +++ b/.gitignore @@ -49,8 +49,12 @@ coverage.xml # Django stuff: *.log -# Sphinx documentation +# Documentation +site/ docs/_build/ +docs/data +data +data.zip # PyBuilder target/ @@ -79,7 +83,18 @@ src/zarr/_version.py data/* src/fixture/ fixture/ +junit.xml .DS_Store tests/.hypothesis .hypothesis/ + +zarr/version.py +zarr.egg-info/ + +# Local agent / planning notes (not versioned) +.claude/ +CLAUDE.md +docs/superpowers/ +# zarr-metadata package lockfile (a library, not an app) +packages/zarr-metadata/uv.lock diff --git a/.markdownlint-cli2.jsonc b/.markdownlint-cli2.jsonc new file mode 100644 index 0000000000..3dfdf96856 --- /dev/null +++ b/.markdownlint-cli2.jsonc @@ -0,0 +1,54 @@ +// markdownlint-cli2 configuration for zarr-python docs. +// +// We keep the rules that catch real rendering/structure problems and disable those that +// are pure style, conflict with house conventions, or fire false positives against our +// MkDocs/mkdocstrings + pymdownx toolchain. Complementary, not overlapping, with +// ci/lint_docs.py (RST residue + list-breaking fences) and `mkdocs build --strict`. +{ + "config": { + "default": true, + + // House style: Markdown paragraphs are single unwrapped lines, so line length is not + // a meaningful constraint. + "MD013": false, + + // Purely stylistic marker/emphasis choices -- not worth the churn across existing docs. + "MD004": false, // ul bullet style (-, *, +) + "MD007": false, // ul indentation width + "MD050": false, // strong (bold) style + "MD035": false, // hr style + + // False positives from our toolchain: + // mkdocstrings cross-refs `[`X`][zarr.X]` read as undefined reference links (MD052); + // pymdownx.magiclink auto-links bare URLs (MD034); + // md_in_html lets us embed intentional raw HTML (MD033); + // generated/included files (api stubs, snippets) need not open with an H1 (MD041). + "MD052": false, + "MD034": false, + "MD033": false, + "MD041": false, + + // Duplicate headings are legitimate under different sections (e.g. repeated + // "Documentation"); only flag true sibling duplicates. + "MD024": { "siblings_only": true }, + + // Opinionated table/link/command rules with low value for these docs. + "MD055": false, // table pipe style + "MD060": false, // table column style + "MD059": false, // "descriptive" link text (no "click here") + "MD014": false, // $ before commands without shown output + + // markdownlint does not understand MkDocs `!!!` admonitions, so it reads their + // 4-space-indented bodies as indented code blocks and flags them (and, via inferred + // file style, flags real fenced blocks too). Cannot coexist with our admonitions. + "MD046": false // code block style (fenced vs indented) + // Kept on (structural / real rendering bugs): MD012 (multiple blanks), MD022/MD031/MD032 + // (blanks around headings/fences/lists), MD025 (single H1), MD029 (ordered-list prefix), + // MD040 (fenced code language), MD042 (empty links), + // MD047 (trailing newline), MD056 (table column count), among others. + }, + "globs": ["docs/**/*.md"], + "ignores": [ + "docs/api/**" // mkdocstrings stubs (`::: zarr.X`) + ] +} diff --git a/.pep8speaks.yml b/.pep8speaks.yml deleted file mode 100644 index a000ded163..0000000000 --- a/.pep8speaks.yml +++ /dev/null @@ -1,4 +0,0 @@ -pycodestyle: - max-line-length: 100 - exclude: - - docs diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8abb9fddd3..54345c819e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,42 +1,98 @@ ci: autoupdate_commit_msg: "chore: update pre-commit hooks" - autofix_commit_msg: "style: pre-commit fixes" + autoupdate_schedule: "monthly" autofix_prs: false -default_stages: [commit, push] + # Both of these are `language: system` hooks that shell out to the local + # toolchain β€” `uv` for mypy, `uv` and `just` for the docs build β€” and need + # the repo checkout to resolve their environments from `uv.lock`. Neither is + # available on pre-commit.ci's runners. Each is covered instead by a GitHub + # Actions job (Lint for mypy, zarr-http-server for the docs build) and by + # local prek runs. + skip: [mypy, zarr-http-server-docs] + +default_stages: [pre-commit, pre-push] + default_language_version: - python: python3 + python: python3.12 + repos: - repo: https://github.com/astral-sh/ruff-pre-commit - rev: 'v0.5.6' + rev: v0.16.0 hooks: - - id: ruff - args: ["--fix", "--show-fixes"] - - id: ruff-format + - id: ruff-check + args: ["--fix", "--show-fixes"] + - id: ruff-format - repo: https://github.com/codespell-project/codespell - rev: v2.3.0 + rev: v2.4.2 hooks: - id: codespell - args: ["-L", "ba,ihs,kake,nd,noe,nwo,te,fo,zar", "-S", "fixture"] + args: ["-L", "fo,ihs,kake,te", "-S", "fixture"] - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.6.0 + rev: v6.0.0 hooks: - - id: check-yaml - - repo: https://github.com/pre-commit/mirrors-mypy - rev: v1.11.1 + - id: check-yaml + exclude: mkdocs.yml + - id: trailing-whitespace + - repo: https://github.com/DavidAnson/markdownlint-cli2 + rev: v0.22.1 + hooks: + # Markdown structure/hygiene. Rule selection and ignores are in + # .markdownlint-cli2.jsonc; complements ci/lint_docs.py (RST residue, + # list-breaking fences) and `mkdocs build --strict`. Scoped to docs/ to + # match the config's globs (pre-commit passes filenames, which would + # otherwise override that scoping and lint all repo Markdown). + - id: markdownlint-cli2 + files: ^docs/ + - repo: local hooks: - id: mypy - files: src - additional_dependencies: - # Package dependencies - - asciitree - - crc32c - - donfig - - fasteners - - numcodecs - - numpy - - typing_extensions - - zstandard - # Tests - - pytest - # Zarr v2 - - types-redis + name: mypy + language: system + entry: uv run --frozen mypy + pass_filenames: false + always_run: true + types_or: [python, pyi] + # Builds the zarr-http-server docs site with warnings as errors, which + # catches a dead cross-reference or a nav entry pointing at a file that + # no longer exists before it reaches CI. + # + # `stages: [pre-push]` overrides the default of running on every commit: + # this is a whole-site build, too slow to pay per commit and only + # actionable before the code leaves the machine. `files:` limits it to + # changes that touch the package, and `pass_filenames: false` because + # mkdocs builds the site, not a list of files. Delegating to the + # justfile keeps one definition of the build shared with CI. + - id: zarr-http-server-docs + name: zarr-http-server docs build + language: system + entry: >- + just --justfile packages/zarr-http-server/justfile + --working-directory packages/zarr-http-server docs-check + pass_filenames: false + files: ^packages/zarr-http-server/ + stages: [pre-push] + - repo: https://github.com/scientific-python/cookie + rev: 2026.06.18 + hooks: + - id: sp-repo-review + - repo: https://github.com/numpy/numpydoc + rev: v1.11.0rc0 + hooks: + - id: numpydoc-validation + - repo: local + hooks: + - id: ban-lstrip-rstrip + name: ban lstrip/rstrip + language: pygrep + # Matches .lstrip() or .rstrip() where the string argument is 2+ characters. + entry: "\\.(lstrip|rstrip)\\([\"'][^\"']{2,}[\"']\\)" + types: [python] + files: ^(src|tests)/ + - repo: https://github.com/zizmorcore/zizmor-pre-commit + rev: v1.26.1 + hooks: + - id: zizmor + - repo: https://github.com/twisted/towncrier + rev: 25.8.0 + hooks: + - id: towncrier-check diff --git a/.python-version b/.python-version new file mode 100644 index 0000000000..e4fba21835 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.12 diff --git a/.readthedocs.yaml b/.readthedocs.yaml index cae58c064a..dddf8449a4 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -3,17 +3,31 @@ version: 2 build: os: ubuntu-22.04 tools: - python: "3.10" - -sphinx: - configuration: docs/conf.py - fail_on_warning: true - -formats: all - -python: - install: - - method: pip - path: . - extra_requirements: - - docs + python: "3.12" + jobs: + post_checkout: + # Cancel pull request builds whose changes are confined to the packages + # that have their own Read the Docs projects. Exit code 183 cancels the + # build and reports success to the Git provider. Scoped to PR builds + # ("external" versions) because origin/main is only a meaningful diff + # base there. Read the Docs strips shell quoting from commands, so the + # exclude pathspecs must use the quote-free :! form, not ':(exclude)'. + - | + if [ "$READTHEDOCS_VERSION_TYPE" = "external" ] && git diff --quiet origin/main -- :!packages/zarr-metadata :!packages/zarr-indexing; + then + exit 183; + fi + install: + - pip install --upgrade pip + - pip install .[remote] --group docs + pre_build: + - | + if [ "$READTHEDOCS_VERSION_TYPE" != "tag" ]; + then + towncrier build --version Unreleased --yes; + fi + build: + html: + - mkdocs build --strict --site-dir $READTHEDOCS_OUTPUT/html +mkdocs: + configuration: mkdocs.yml diff --git a/LICENSE.txt b/LICENSE.txt index 850a0d8772..1e8da4d242 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2015-2023 Zarr Developers +Copyright (c) 2015-2025 Zarr Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README-v3.md b/README-v3.md deleted file mode 100644 index 8348038e5a..0000000000 --- a/README-v3.md +++ /dev/null @@ -1,49 +0,0 @@ -# V3 Contributor Guide - -A bare-bones guide to contributing to V3. - -Developed for the Feb. 2024 Zarr Sprint. - -## Clone V3 branch - -[Fork](https://github.com/zarr-developers/zarr-python/fork) zarr-python and clone it locally. - -``` -git clone {your remote} -git remote add upstream https://github.com/zarr-developers/zarr-python -git fetch upstream -git checkout --track upstream/v3 -``` - -## Set up your environment - -Zarr uses [hatch](https://hatch.pypa.io/) for its build system. - -``` -mamba install hatch -``` - -or - -``` -pip install hatch -``` - -Then - -``` -hatch env create test -``` - -## Run the Tests - -``` -hatch run test:run -``` - -or - -``` -hatch -e test shell -pytest -v -``` \ No newline at end of file diff --git a/README.md b/README.md index b035ffa597..330c1da5ea 100644 --- a/README.md +++ b/README.md @@ -4,103 +4,28 @@ # Zarr - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Latest Release - - latest release - -
- - latest release - -
Package Status - - status - -
License - - license - -
Build Status - - build status - -
Pre-commit Status - - pre-commit status - -
Coverage - - coverage - -
Downloads - - pypi downloads - -
Gitter - - - -
Citation - - DOI - -
+[![Latest Release](https://badge.fury.io/py/zarr.svg)](https://pypi.org/project/zarr/) +[![CondaForge](https://anaconda.org/conda-forge/zarr/badges/version.svg)](https://anaconda.org/anaconda/zarr/) +[![Package Status](https://img.shields.io/pypi/status/zarr.svg)](https://pypi.org/project/zarr/) +[![License](https://img.shields.io/pypi/l/zarr.svg)](https://github.com/zarr-developers/zarr-python/blob/main/LICENSE.txt) +[![Coverage](https://codecov.io/gh/zarr-developers/zarr-python/branch/main/graph/badge.svg)](https://app.codecov.io/gh/zarr-developers/zarr-python) +[![Downloads](https://static.pepy.tech/badge/zarr)](https://zarr.readthedocs.io/en/stable/) +[![Developer Chat](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://ossci.zulipchat.com/#narrow/channel/423692-Zarr-Python) +[![Citation](https://zenodo.org/badge/DOI/10.5281/zenodo.3773450.svg)](https://doi.org/10.5281/zenodo.3773450) ## What is it? -Zarr is a Python package providing an implementation of compressed, chunked, N-dimensional arrays, designed for use in parallel computing. See the [documentation](https://zarr.readthedocs.io) for more information. +The `zarr` library is a Python implementation of the [Zarr storage format](https://zarr.dev/). `zarr` delivers compressed, chunked, N-dimensional arrays that work well for parallel computing and object storage. See the [documentation](https://zarr.readthedocs.io/en/stable/) for more information. ## Main Features -- [**Create**](https://zarr.readthedocs.io/en/stable/tutorial.html#creating-an-array) N-dimensional arrays with any NumPy `dtype`. -- [**Chunk arrays**](https://zarr.readthedocs.io/en/stable/tutorial.html#chunk-optimizations) along any dimension. -- [**Compress**](https://zarr.readthedocs.io/en/stable/tutorial.html#compressors) and/or filter chunks using any NumCodecs codec. -- [**Store arrays**](https://zarr.readthedocs.io/en/stable/tutorial.html#tutorial-storage) in memory, on disk, inside a zip file, on S3, etc... -- [**Read**](https://zarr.readthedocs.io/en/stable/tutorial.html#reading-and-writing-data) an array [**concurrently**](https://zarr.readthedocs.io/en/stable/tutorial.html#parallel-computing-and-synchronization) from multiple threads or processes. -- Write to an array concurrently from multiple threads or processes. -- Organize arrays into hierarchies via [**groups**](https://zarr.readthedocs.io/en/stable/tutorial.html#groups). +- [**Create**](https://zarr.readthedocs.io/en/stable/user-guide/arrays/#creating-an-array) N-dimensional arrays with NumPy-compatible `dtype`s. +- [**Chunk arrays**](https://zarr.readthedocs.io/en/stable/user-guide/performance/#chunk-optimizations) along any dimension. +- [**Encode**](https://zarr.readthedocs.io/en/stable/user-guide/arrays/#compressors) chunks using a variety of useful encodings (e.g., compression). +- [**Store arrays**](https://zarr.readthedocs.io/en/stable/user-guide/storage/) in memory, on disk, inside a zip file, on S3, etc... +- [**Read**](https://zarr.readthedocs.io/en/stable/user-guide/arrays/#reading-and-writing-data) an array [**concurrently**](https://zarr.readthedocs.io/en/stable/user-guide/performance/#parallel-computing-and-synchronization) from multiple threads or processes. +- [**Write**](https://zarr.readthedocs.io/en/stable/user-guide/arrays/#reading-and-writing-data) to an array concurrently from multiple threads or processes. +- Organize arrays into hierarchies via [**groups**](https://zarr.readthedocs.io/en/stable/quick-start/#hierarchical-groups). ## Where to get it @@ -116,4 +41,12 @@ or via `conda`: conda install -c conda-forge zarr ``` -For more details, including how to install from source, see the [installation documentation](https://zarr.readthedocs.io/en/stable/index.html#installation). +For more details, including how to install from source, see the [installation documentation](https://zarr.readthedocs.io/en/stable/#installation). + +## Repository sub-packages + +In addition to the primary `zarr` implementation, this repository contains other packages that provide specialized functionality with minimal dependencies: + +- [`zarr-metadata`](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-metadata): Tools for Zarr metadata. Install with `pip install zarr-metadata`. +- [`zarr-indexing`](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-indexing): Tools for lazily indexing chunked arrays. Install with `pip install zarr-indexing`. +- [`zarr-http-server`](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-http-server): An HTTP server implementation targeting Zarr data. Install with `pip install zarr-http-server`. diff --git a/TEAM.md b/TEAM.md new file mode 100644 index 0000000000..ce9de1d486 --- /dev/null +++ b/TEAM.md @@ -0,0 +1,31 @@ +## Active core-developers +- @joshmoore (Josh Moore) +- @jni (Juan Nunez-Iglesias) +- @rabernat (Ryan Abernathey) +- @jhamman (Joe Hamman) +- @d-v-b (Davis Bennett) +- @jakirkham (jakirkham) +- @martindurant (Martin Durant) +- @normanrz (Norman Rzepka) +- @dstansby (David Stansby) +- @dcherian (Deepak Cherian) +- @TomAugspurger (Tom Augspurger) +- @maxrjones (Max Jones) +- @ilan-gold (Ilan Gold) + +## Emeritus core-developers +- @alimanfoo (Alistair Miles) +- @shoyer (Stephan Hoyer) +- @ryan-williams (Ryan Williams) +- @jrbourbeau (James Bourbeau) +- @mzjp2 (Zain Patel) +- @grlee77 (Gregory Lee) + +## Former core-developers +- @jeromekelleher (Jerome Kelleher) +- @tjcrone (Tim Crone) +- @funkey (Jan Funke) +- @shikharsg +- @Carreau (Matthias Bussonnier) +- @dazzag24 +- @WardF (Ward Fisher) diff --git a/bench/compress_normal.py b/bench/compress_normal.py index 608cfe8dce..64204cd1e5 100644 --- a/bench/compress_normal.py +++ b/bench/compress_normal.py @@ -1,11 +1,11 @@ import sys import timeit +import blosc import line_profiler import numpy as np import zarr -from zarr import blosc if __name__ == "__main__": sys.path.insert(0, "..") @@ -16,7 +16,7 @@ a, chunks=1000000, compression="blosc", - compression_opts=dict(cname="lz4", clevel=5, shuffle=2), + compression_opts={"cname": "lz4", "clevel": 5, "shuffle": 2}, ) print(z) diff --git a/bench/compress_normal.txt b/bench/compress_normal.txt index d527cf03d4..e5d6be6aeb 100644 --- a/bench/compress_normal.txt +++ b/bench/compress_normal.txt @@ -19,7 +19,7 @@ Line # Hits Time Per Hit % Time Line Contents ============================================================== 137 def compress(source, char* cname, int clevel, int shuffle): 138 """Compress data in a numpy array. - 139 + 139 140 Parameters 141 ---------- 142 source : array-like @@ -30,14 +30,14 @@ Line # Hits Time Per Hit % Time Line Contents 147 Compression level. 148 shuffle : int 149 Shuffle filter. - 150 + 150 151 Returns 152 ------- 153 dest : bytes-like 154 Compressed data. - 155 + 155 156 """ - 157 + 157 158 cdef: 159 char *source_ptr 160 char *dest_ptr @@ -45,18 +45,18 @@ Line # Hits Time Per Hit % Time Line Contents 162 size_t nbytes, cbytes, itemsize 163 200 506 2.5 0.2 array.array char_array_template = array.array('b', []) 164 array.array dest - 165 + 165 166 # setup source buffer 167 200 458 2.3 0.2 PyObject_GetBuffer(source, &source_buffer, PyBUF_ANY_CONTIGUOUS) 168 200 119 0.6 0.0 source_ptr = source_buffer.buf - 169 + 169 170 # setup destination 171 200 239 1.2 0.1 nbytes = source_buffer.len 172 200 103 0.5 0.0 itemsize = source_buffer.itemsize 173 200 2286 11.4 0.8 dest = array.clone(char_array_template, nbytes + BLOSC_MAX_OVERHEAD, 174 zero=False) 175 200 129 0.6 0.0 dest_ptr = dest.data.as_voidptr - 176 + 176 177 # perform compression 178 200 1734 8.7 0.6 if _get_use_threads(): 179 # allow blosc to use threads internally @@ -67,24 +67,24 @@ Line # Hits Time Per Hit % Time Line Contents 184 cbytes = blosc_compress(clevel, shuffle, itemsize, nbytes, 185 source_ptr, dest_ptr, 186 nbytes + BLOSC_MAX_OVERHEAD) - 187 + 187 188 else: 189 with nogil: 190 cbytes = blosc_compress_ctx(clevel, shuffle, itemsize, nbytes, 191 source_ptr, dest_ptr, 192 nbytes + BLOSC_MAX_OVERHEAD, cname, 193 0, 1) - 194 + 194 195 # release source buffer 196 200 616 3.1 0.2 PyBuffer_Release(&source_buffer) - 197 + 197 198 # check compression was successful 199 200 120 0.6 0.0 if cbytes <= 0: 200 raise RuntimeError('error during blosc compression: %d' % cbytes) - 201 + 201 202 # resize after compression 203 200 1896 9.5 0.6 array.resize(dest, cbytes) - 204 + 204 205 200 186 0.9 0.1 return dest ******************************************************************************* @@ -100,19 +100,19 @@ Line # Hits Time Per Hit % Time Line Contents ============================================================== 75 def decompress(source, dest): 76 """Decompress data. - 77 + 77 78 Parameters 79 ---------- 80 source : bytes-like 81 Compressed data, including blosc header. 82 dest : array-like 83 Object to decompress into. - 84 + 84 85 Notes 86 ----- 87 Assumes that the size of the destination buffer is correct for the size of 88 the uncompressed data. - 89 + 89 90 """ 91 cdef: 92 int ret @@ -122,7 +122,7 @@ Line # Hits Time Per Hit % Time Line Contents 96 array.array source_array 97 Py_buffer dest_buffer 98 size_t nbytes - 99 + 99 100 # setup source buffer 101 200 573 2.9 0.2 if PY2 and isinstance(source, array.array): 102 # workaround fact that array.array does not support new-style buffer @@ -134,13 +134,13 @@ Line # Hits Time Per Hit % Time Line Contents 108 200 112 0.6 0.0 release_source_buffer = True 109 200 144 0.7 0.1 PyObject_GetBuffer(source, &source_buffer, PyBUF_ANY_CONTIGUOUS) 110 200 98 0.5 0.0 source_ptr = source_buffer.buf - 111 + 111 112 # setup destination buffer 113 200 552 2.8 0.2 PyObject_GetBuffer(dest, &dest_buffer, 114 PyBUF_ANY_CONTIGUOUS | PyBUF_WRITEABLE) 115 200 100 0.5 0.0 dest_ptr = dest_buffer.buf 116 200 84 0.4 0.0 nbytes = dest_buffer.len - 117 + 117 118 # perform decompression 119 200 1856 9.3 0.8 if _get_use_threads(): 120 # allow blosc to use threads internally @@ -149,12 +149,12 @@ Line # Hits Time Per Hit % Time Line Contents 123 else: 124 with nogil: 125 ret = blosc_decompress_ctx(source_ptr, dest_ptr, nbytes, 1) - 126 + 126 127 # release buffers 128 200 754 3.8 0.3 if release_source_buffer: 129 200 326 1.6 0.1 PyBuffer_Release(&source_buffer) 130 200 165 0.8 0.1 PyBuffer_Release(&dest_buffer) - 131 + 131 132 # handle errors 133 200 128 0.6 0.1 if ret <= 0: 134 raise RuntimeError('error during blosc decompression: %d' % ret) diff --git a/changes/.gitignore b/changes/.gitignore new file mode 100644 index 0000000000..f935021a8f --- /dev/null +++ b/changes/.gitignore @@ -0,0 +1 @@ +!.gitignore diff --git a/changes/3285.feature.md b/changes/3285.feature.md new file mode 100644 index 0000000000..3809c0ab02 --- /dev/null +++ b/changes/3285.feature.md @@ -0,0 +1,13 @@ +JSON metadata validation now delegates to ``msgspec.convert`` for the type +coercions it supports (``Literal`` membership, ``int`` / ``bool`` strictness, +list-to-tuple), replacing the per-field hand-written ``parse_*`` logic. A small +fallback validates the recursive JSON values msgspec cannot, now with an +explicit nesting-depth limit, and a latent generator-exhaustion bug in +``parse_storage_transformers`` is fixed. See #3285. + +As a result some metadata inputs are now parsed more strictly. The previous +per-field checks compared values with ``==``, which accepts any numerically +equal object, so a float such as ``2.0`` was accepted as ``zarr_format``; it is +now rejected because it is not an ``int``. Booleans are likewise no longer +accepted where an ``int`` is expected, since ``bool`` is an ``int`` subclass. +Metadata that conforms to the Zarr specification is unaffected. diff --git a/changes/4149.doc.md b/changes/4149.doc.md new file mode 100644 index 0000000000..8a473acac9 --- /dev/null +++ b/changes/4149.doc.md @@ -0,0 +1 @@ +Added a Roadmap page to the documentation outlining future plans and intended changes to the library. diff --git a/changes/4189.bugfix.md b/changes/4189.bugfix.md new file mode 100644 index 0000000000..76ef7e7a5e --- /dev/null +++ b/changes/4189.bugfix.md @@ -0,0 +1 @@ +Allow `Group.require_array` to accept a `ZDType` for `dtype`, matching the other array creation methods. Previously an existing array could only be required with a string or NumPy dtype. diff --git a/changes/4193.doc.md b/changes/4193.doc.md new file mode 100644 index 0000000000..0972e8be2c --- /dev/null +++ b/changes/4193.doc.md @@ -0,0 +1,4 @@ +Converted remaining reStructuredText-style double-backtick markup to Markdown +single backticks in the docstrings of `zarr.api.asynchronous`, +`zarr.api.synchronous`, `zarr.core.array`, `zarr.registry`, and +`zarr.storage._common`. No functional changes. diff --git a/changes/4213.misc.md b/changes/4213.misc.md new file mode 100644 index 0000000000..150e60b57b --- /dev/null +++ b/changes/4213.misc.md @@ -0,0 +1 @@ +Updated ruff to 0.16.0 and fixed the violations surfaced by its expanded default rule set: narrowed a blind `except Exception` in `StorePath.__eq__` to `AttributeError`, removed unnecessary `global` declarations in `zarr.core.sync`, made `subprocess.run` calls in tests pass `check=False` explicitly, and applied automatic fixes (`None` moved to the end of type unions, unused `noqa` directives removed). diff --git a/changes/4227.bugfix.md b/changes/4227.bugfix.md new file mode 100644 index 0000000000..18293178bd --- /dev/null +++ b/changes/4227.bugfix.md @@ -0,0 +1 @@ +Consolidated metadata is now reconstructed independently of the order the keys appear in on disk. Previously, sibling subtrees whose keys were not adjacent in the persisted mapping lost their children, which made nodes unreachable through consolidated metadata -- most visibly for sibling groups whose names differ only by case. diff --git a/changes/4239.bugfix.md b/changes/4239.bugfix.md new file mode 100644 index 0000000000..b5bc92f18b --- /dev/null +++ b/changes/4239.bugfix.md @@ -0,0 +1 @@ +`FsspecStore.from_mapper` and `FsspecStore.from_url` no longer fail when converting a synchronous instance of an async-capable filesystem whose storage options contain objects that cannot be serialized to JSON (e.g. an `azure.identity.DefaultAzureCredential`). The async instance is now constructed from the original filesystem arguments instead of a JSON round-trip. diff --git a/changes/4247.doc.md b/changes/4247.doc.md new file mode 100644 index 0000000000..6dbca1d3d6 --- /dev/null +++ b/changes/4247.doc.md @@ -0,0 +1,5 @@ +Added a "Related Projects" page to the documentation listing the companion +packages developed in this repository β€” `zarr-metadata` and `zarr-indexing` β€” +and linked it from the landing page. Links to those packages now use the +canonical `https://zarr.readthedocs.io/projects/...` URLs, and each companion +package's documentation links back to the `zarr-python` docs. diff --git a/changes/4257.bugfix.md b/changes/4257.bugfix.md new file mode 100644 index 0000000000..6f2740ccb4 --- /dev/null +++ b/changes/4257.bugfix.md @@ -0,0 +1 @@ +Numpy integers are accepted as chunk sizes again. Since 3.3.0 a per-dimension chunk size that was a numpy integer (e.g. `chunks=(np.int64(2), np.int64(2))`, as produced by any computed chunk shape) raised `TypeError: 'numpy.int64' object is not iterable`, because the scalar chunk path narrowed on `int` while its caller dispatched on `numbers.Integral`. Numpy arrays are now also accepted as chunk specifications, and a chunk specification that is neither an integer nor iterable now reports the offending value instead of failing with an opaque iteration error. diff --git a/changes/4260.bugfix.md b/changes/4260.bugfix.md new file mode 100644 index 0000000000..b703c47a35 --- /dev/null +++ b/changes/4260.bugfix.md @@ -0,0 +1 @@ +The `cast_value` codec now requires `cast-value-rs>=0.4.2`. Earlier versions of that backend silently corrupted data when handed an array that was not row-major β€” the layout the `transpose` codec produces β€” so a `cast_value` codec next to a `transpose` codec would either write transposed values with no error or fail with `ValueError: Input array must be contiguous`. The minimum version is enforced at runtime as well as in the package metadata, so an environment that already has an older `cast-value-rs` installed now raises `ImportError` when the codec is used, instead of corrupting data. diff --git a/changes/4261.misc.md b/changes/4261.misc.md new file mode 100644 index 0000000000..ca2a3fbb1e --- /dev/null +++ b/changes/4261.misc.md @@ -0,0 +1 @@ +The contents of the `zarr` source distribution are now defined by an explicit allowlist rather than a blocklist. Previously the sdist bundled the whole `packages/` tree β€” `zarr-indexing`, `zarr-metadata` and `zarr-http-server`, which are released as their own distributions β€” along with CI configuration and other repository files. The sdist also now ships `docs/`, so the test suite it carries can be collected and run from an unpacked sdist. diff --git a/changes/4265.bugfix.md b/changes/4265.bugfix.md new file mode 100644 index 0000000000..6daf0fc7d0 --- /dev/null +++ b/changes/4265.bugfix.md @@ -0,0 +1,13 @@ +Accept [universal-pathlib](https://github.com/fsspec/universal_pathlib) `UPath` objects wherever +zarr accepts a `StoreLike` value. A remote `UPath` now creates an `FsspecStore` using the +filesystem and storage options the `UPath` already carries, and a local `UPath` creates a +`LocalStore`, so that `UPath('/data')` and `Path('/data')` behave the same. + +Previously this worked only by accident: in universal-pathlib < 0.3 every `UPath` subclassed +`pathlib.Path` and implemented `__fspath__`, so remote paths were either converted to a URI string +by the caller or wrapped in a `LocalStore` that happened to dispatch through fsspec. Since +universal-pathlib 0.3 remote paths do neither, and passing one raised +`TypeError: Unsupported type for store_like`. + +`FsspecStore.from_upath` also now converts the `UPath`'s filesystem to async mode, instead of +raising `TypeError` for synchronous filesystems and warning for sync-mode instances of async ones. diff --git a/changes/4279.bugfix.md b/changes/4279.bugfix.md new file mode 100644 index 0000000000..7d99a49ccf --- /dev/null +++ b/changes/4279.bugfix.md @@ -0,0 +1 @@ +A `scale_offset` codec configured with a string-valued zero scale is now rejected. `scale` accepts strings, and no string is ever equal to `0`, so `"0"`, `"0.0"` and the hex form `"0x0000000000000000"` skipped the "scale must be non-zero" check that the numeric `0` triggers. On float data types the array was created, every chunk was written as zero and read back as `nan` with no error, and the zero scale was persisted to the metadata so reopening the store reproduced it; on integer data types the codec raised `ZeroDivisionError` instead of `ValueError`. The check now runs on the parsed scalar rather than the value as supplied. diff --git a/changes/README.md b/changes/README.md new file mode 100644 index 0000000000..889a52baa4 --- /dev/null +++ b/changes/README.md @@ -0,0 +1,14 @@ +Writing a changelog entry +------------------------- + +Please put a new file in this directory named `xxxx..md`, where + +- `xxxx` is the pull request number associated with this entry +- `` is one of: + - feature + - bugfix + - doc + - removal + - misc + +Inside the file, please write a short description of what you have changed, and how it impacts users of `zarr-python`. diff --git a/ci/check_changelog_entries.py b/ci/check_changelog_entries.py new file mode 100644 index 0000000000..42d7cc1708 --- /dev/null +++ b/ci/check_changelog_entries.py @@ -0,0 +1,70 @@ +""" +Check changelog entries have the correct filename structure. + +Usage: + python check_changelog_entries.py [DIRECTORY] + +DIRECTORY defaults to the repo-root `changes/`. +""" + +import sys +from pathlib import Path + +VALID_CHANGELOG_TYPES = ["feature", "bugfix", "doc", "removal", "misc"] +REPO_ROOT = Path(__file__).parent.parent.resolve() +DEFAULT_DIRECTORY = REPO_ROOT / "changes" + + +def is_int(s: str) -> bool: + try: + int(s) + except ValueError: + return False + else: + return True + + +def check(directory: Path) -> int: + print(f"Looking for changelog entries in {directory}") + entries = list(directory.glob("*")) + entries = [e for e in entries if e.name not in [".gitignore", "README.md"]] + print(f"Found {len(entries)} entries") + print() + + bad_suffix = [e for e in entries if e.suffix != ".md"] + bad_issue_no = [e for e in entries if not is_int(e.name.split(".")[0])] + # Only flag bad_type for files that have already passed the prior two + # checks; otherwise `e.name.split(".")[1]` may raise IndexError on a + # malformed name like `notes.md`. + bad_type = [ + e + for e in entries + if e.suffix == ".md" + and is_int(e.name.split(".")[0]) + and e.name.split(".")[1] not in VALID_CHANGELOG_TYPES + ] + + if bad_suffix or bad_issue_no or bad_type: + if bad_suffix: + print("Changelog entries without .md suffix") + print("-------------------------------------") + print("\n".join(p.name for p in bad_suffix)) + print() + if bad_issue_no: + print("Changelog entries without integer issue number") + print("----------------------------------------------") + print("\n".join(p.name for p in bad_issue_no)) + print() + if bad_type: + print("Changelog entries without valid type") + print("------------------------------------") + print("\n".join(p.name for p in bad_type)) + print(f"Valid types are: {VALID_CHANGELOG_TYPES}") + print() + return 1 + return 0 + + +if __name__ == "__main__": + directory = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else DEFAULT_DIRECTORY + sys.exit(check(directory)) diff --git a/ci/check_documented_exports.py b/ci/check_documented_exports.py new file mode 100644 index 0000000000..0772954399 --- /dev/null +++ b/ci/check_documented_exports.py @@ -0,0 +1,161 @@ +"""Check that every public top-level export is in the API reference. + +The API reference is authored as explicit mkdocstrings directives (``::: target``) +under ``docs/api/`` -- one per documented symbol -- rather than autodoc, so a newly +added ``zarr.__all__`` entry will not appear in the docs until someone writes a page +for it (or it becomes a rendered member of an already-documented module). This script +catches that gap: it resolves every ``:::`` target, expands module directives into the +members they render (honoring ``members: false``), and asserts each name in +``zarr.__all__`` resolves to a documented object. + +Usage: + python ci/check_documented_exports.py [API_DOCS_DIR] + +API_DOCS_DIR defaults to the repo-root ``docs/api``. Exits non-zero (and prints the +undocumented exports to stderr) if any public export is missing from the reference. +""" + +from __future__ import annotations + +import importlib +import re +import sys +from pathlib import Path +from types import ModuleType +from typing import TYPE_CHECKING, Any + +import zarr + +if TYPE_CHECKING: + from collections.abc import Iterator + +REPO_ROOT = Path(__file__).parent.parent.resolve() +DEFAULT_API_DOCS_ROOT = REPO_ROOT / "docs" / "api" + +# Names in zarr.__all__ that are intentionally absent from the API reference. +# Keep this list short and justified -- it is the only escape hatch from the guard. +EXEMPT_EXPORTS = { + "__version__", # version string, not an API symbol + "print_debug_info", # debugging helper, deliberately not in the reference +} + +# A mkdocstrings autodoc directive: `::: some.dotted.target` at the start of a line. +DIRECTIVE_RE = re.compile(r"^:::[ \t]+(?P\S+)") +# `members: false` (or `members: []`) within a directive's option block disables +# rendering of a module's members. +MEMBERS_DISABLED_RE = re.compile(r"^\s+members:\s*(false|\[\s*\])\s*$") + + +def resolve(target: str) -> Any: + """Resolve a `:::` target (a dotted path) to the Python object it documents.""" + try: + return importlib.import_module(target) + except ImportError: + pass + module_path, _, attr = target.rpartition(".") + try: + return getattr(importlib.import_module(module_path), attr) + except (ImportError, AttributeError): + return None + + +def iter_directives(text: str) -> Iterator[tuple[str, bool]]: + """Yield ``(target, members_enabled)`` for each ``:::`` directive in ``text``. + + The file is split into lines once; for each directive we scan its indented option + block -- stopping at the first non-indented line, which ends the block -- so options + belonging to a later directive are never consulted. ``members_enabled`` is False when + that block sets ``members: false`` (or ``members: []``).""" + lines = text.splitlines() + i = 0 + while i < len(lines): + match = DIRECTIVE_RE.match(lines[i]) + if match is None: + i += 1 + continue + members_enabled = True + i += 1 + while i < len(lines): + line = lines[i] + if line.strip() == "": + i += 1 + continue + if not line.startswith((" ", "\t")): + break # non-indented line: end of this directive's option block + if MEMBERS_DISABLED_RE.match(line): + members_enabled = False + i += 1 + yield match.group("target"), members_enabled + + +def module_member_ids(module: ModuleType) -> Iterator[int]: + """Yield the id() of each public member a module directive renders. + + The rendered members are the module's ``__all__`` if defined, else its public + (non-underscore) attributes.""" + member_names = getattr(module, "__all__", None) or [ + name for name in dir(module) if not name.startswith("_") + ] + for name in member_names: + member = getattr(module, name, None) + if member is not None: + yield id(member) + + +def documented_object_ids(api_docs_root: Path) -> set[int]: + """Collect the id()s of every object rendered by a `:::` directive under api_docs_root. + + A directive pointing at an object documents that object. A directive pointing at a + module documents the module's public members unless the directive sets + ``members: false``.""" + documented: set[int] = set() + for md_file in sorted(api_docs_root.rglob("*.md")): + for target, members_enabled in iter_directives(md_file.read_text(encoding="utf-8")): + obj = resolve(target) + if obj is None: + continue + documented.add(id(obj)) + if isinstance(obj, ModuleType) and members_enabled: + documented.update(module_member_ids(obj)) + return documented + + +def find_undocumented_exports(api_docs_root: Path) -> list[str]: + documented = documented_object_ids(api_docs_root) + return sorted( + name + for name in zarr.__all__ + if name not in EXEMPT_EXPORTS and id(getattr(zarr, name)) not in documented + ) + + +def main() -> int: + args = sys.argv[1:] + api_docs_root = Path(args[0]).resolve() if args else DEFAULT_API_DOCS_ROOT + if not api_docs_root.exists(): + print(f"{api_docs_root} does not exist.", file=sys.stderr) + return 1 + + missing = find_undocumented_exports(api_docs_root) + if not missing: + print(f"All {len(zarr.__all__)} public exports are documented.") + return 0 + + print( + f"Found {len(missing)} public export(s) in zarr.__all__ missing from the API " + "reference (docs/api/):\n", + file=sys.stderr, + ) + for name in missing: + print(f" - zarr.{name}", file=sys.stderr) + print( + "\nAdd a `::: zarr.` page under docs/api/zarr/ (and register it in " + "mkdocs.yml and docs/api/zarr/index.md), or -- if the export is intentionally " + "undocumented -- add it to EXEMPT_EXPORTS in this script with a reason.", + file=sys.stderr, + ) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ci/check_unlinked_types.py b/ci/check_unlinked_types.py new file mode 100644 index 0000000000..3ccfaab397 --- /dev/null +++ b/ci/check_unlinked_types.py @@ -0,0 +1,88 @@ +"""Check for unlinked type annotations in built documentation. + +mkdocstrings renders resolved types as links and unresolved +types as Name without an anchor. +This script finds all such unlinked types in the built HTML and reports them. + +Usage: + python ci/check_unlinked_types.py [site_dir] + +Raises ValueError if unlinked types are found. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +# Matches the griffe/mkdocstrings pattern for unlinked cross-references: +# Name +UNLINKED_PATTERN = re.compile( + r'(?P[^<]+)' +) + +# Patterns to exclude from the report +EXCLUDE_PATTERNS = [ + # TypeVars and type parameters (single brackets like Foo[T]) + re.compile(r"\[.+\]$"), + # Dataclass field / namedtuple field references (contain parens) + re.compile(r"\("), + # Private names + re.compile(r"\._"), + # Dunder attributes + re.compile(r"\.__\w+__$"), + # Testing utilities + re.compile(r"^zarr\.testing\."), + # Third-party types (hypothesis, pytest, etc.) + re.compile(r"^(hypothesis|pytest|typing_extensions|builtins|dataclasses)\."), +] + + +def should_exclude(qualname: str) -> bool: + return any(p.search(qualname) for p in EXCLUDE_PATTERNS) + + +def find_unlinked_types(site_dir: Path) -> dict[str, set[str]]: + """Find all unlinked types in built HTML files. + + Returns a dict mapping qualified type names to the set of pages where they appear. + """ + api_dir = site_dir / "api" + if not api_dir.exists(): + raise FileNotFoundError(f"{api_dir} does not exist. Run 'mkdocs build' first.") + + unlinked: dict[str, set[str]] = {} + for html_file in api_dir.rglob("*.html"): + content = html_file.read_text(errors="replace") + rel_path = str(html_file.relative_to(site_dir)) + for match in UNLINKED_PATTERN.finditer(content): + qualname = match.group("qualname") + if not should_exclude(qualname): + unlinked.setdefault(qualname, set()).add(rel_path) + + return unlinked + + +def main() -> None: + site_dir = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("site") + unlinked = find_unlinked_types(site_dir) + + if not unlinked: + print("No unlinked types found.") + return + + lines = [f"Found {len(unlinked)} unlinked types:\n"] + for qualname in sorted(unlinked): + pages = sorted(unlinked[qualname]) + lines.append(f" {qualname}") + lines.extend(f" - {page}" for page in pages) + + all_pages = {p for ps in unlinked.values() for p in ps} + lines.append(f"\nTotal: {len(unlinked)} unlinked types across {len(all_pages)} pages") + report = "\n".join(lines) + raise ValueError(report) + + +if __name__ == "__main__": + main() diff --git a/ci/lint_docs.py b/ci/lint_docs.py new file mode 100644 index 0000000000..a847e8aa9d --- /dev/null +++ b/ci/lint_docs.py @@ -0,0 +1,341 @@ +"""Lint docstrings and Markdown for reStructuredText markup that won't render. + +This project renders API docs with mkdocstrings (``docstring_style: numpy``) and prose +with MkDocs + Markdown -- not Sphinx/reStructuredText. RST constructs that survive from +older docstrings (or muscle memory) are not interpreted: a Sphinx role passes through as +literal text instead of becoming a link, an ``.. note::`` directive renders as a stray +line, and a ``:param:`` field list never becomes a documented parameter. + +Crucially, none of this is caught by the rest of the docs CI. ``mkdocs build --strict`` +sees the residue as ordinary prose (no warning), and ``ci/check_unlinked_types.py`` only +finds cross-references mkdocstrings *attempted* to resolve -- a raw ``:class:`` role is +never attempted, so it leaves no unlinked-type span. This linter fills that gap with a +fast, source-level check that needs no docs build. + +Checks fall into two groups -- RST markup that silently fails under MkDocs/mkdocstrings, +and Markdown structural problems that render as valid-but-wrong HTML (so `mkdocs build` +emits no warning): + + sphinx-role :class:`X`, :func:`X`, :py:meth:`X` -> [`X`][zarr.X] + rst-directive .. note:: / .. code-block:: python -> MkDocs admonition / fenced code + rst-field :param x:, :returns:, :rtype: -> numpydoc Parameters/Returns/Raises + rst-link `text `_ -> [text](https://example) + list-break unindented code fence between list items -> indent the fence under its item + list-indent continuation block indented < 4 spaces -> indent it 4 spaces + list-blank list item directly after indented block -> blank line before the item + +The ``list-break`` check catches a fenced code block at column 0 placed *between* two list +items: because the fence is not indented into the preceding item, Markdown ends the list at +the fence and the following item starts a fresh list -- renumbering an ordered list (1, 1, 2 +instead of 1, 2, 3) or breaking the grouping/spacing of any list. markdownlint's MD029 only +notices this for sequentially-numbered ordered lists; lazily-numbered (1., 1.) and unordered +lists slip past it, so this structural check covers the gap. + +The ``list-indent`` and ``list-blank`` checks catch the two halves of Python-Markdown's +strict list-continuation rules, which differ from CommonMark. A blank-line-separated +block (paragraph, nested list, table) belongs to a list item only when indented at least +4 spaces; at the 2-space indent other renderers accept, Python-Markdown ends the list and +the block escapes to the top level (``list-indent``). And a new list item can not start +directly after an indented continuation block: without a blank line first, the ``- `` line +is lazily absorbed into the preceding paragraph as literal text (``list-blank``). Both +produced silently-broken changelog rendering in ``docs/release-notes.md``. + +Usage: + python ci/lint_docs.py [PATH ...] + +PATH defaults to the repo-root ``src/zarr`` and ``docs``. Each PATH may be a file or a +directory (directories are searched for ``*.py`` and ``*.md``). Exits non-zero if any +issues are found. +""" + +from __future__ import annotations + +import ast +import re +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import NamedTuple + +REPO_ROOT = Path(__file__).parent.parent.resolve() +DEFAULT_PATHS = (REPO_ROOT / "src" / "zarr", REPO_ROOT / "docs") + +# A Sphinx interpreted-text role: an optional domain, a role name, then a backtick +# target -- e.g. :class:`Foo` or :py:meth:`Foo.bar`. Requires the trailing backtick so +# plain "::" (RST literal markers, time strings, mkdocs-material :icon: shortcodes) and +# URLs ("https://") never match. +SPHINX_ROLE = re.compile(r":[a-zA-Z_]\w*(?::[a-zA-Z_]\w*)?:`[^`\n]+`") + +# An RST directive line: ".. name::" (with or without an argument after it). RST hyperlink +# targets (".. _label:") and comments (".. text") lack the "::" and are not flagged. +RST_DIRECTIVE = re.compile(r"^\s*\.\.[ \t]+[\w-]+::") + +# An RST field-list entry used for docstring fields. The role names above (class, func, +# ...) are deliberately excluded so a role is reported as a role, not a field. +RST_FIELD = re.compile( + r"^\s*:(param|parameter|arg|argument|key|keyword|kwarg|type|returns?|rtype" + r"|raises?|except|exception|yields?|ytype|var|cvar|ivar)\b[^:]*:" +) + +# An RST external hyperlink: `text `_ +RST_LINK = re.compile(r"`[^`\n]+\n]+>`_") + +# A list item at column 0: an ordered marker (1. / 1)) or a bullet (-, *, +) followed by +# whitespace and content. Leading-whitespace (nested/continuation) lines are intentionally +# not matched -- the list-break check only fires on top-level items. +LIST_ITEM = re.compile(r"^(?:\d+[.)]|[-*+])\s+\S") + + +class Check(NamedTuple): + """One docs-residue check: its category, the line pattern that flags it (None for a + structural check matched outside ``_scan_line``), and the user-facing remediation + shown by ``main()``. Keeping ``example``/``fix`` here makes this the single source for + the help text, so adding a check can't leave the help out of date.""" + + category: str + pattern: re.Pattern[str] | None + example: str + fix: str + + +# The ``list-*`` checks carry no pattern -- they are detected structurally, not by scanning +# a single line -- but they appear here so they share the remediation help. +CHECKS = ( + Check("sphinx-role", SPHINX_ROLE, ":class:`X`", "[`X`][zarr.X]"), + Check("rst-directive", RST_DIRECTIVE, ".. note::", "MkDocs admonition (!!! note)"), + Check("rst-field", RST_FIELD, ":param x:", "numpydoc Parameters/Returns/Raises section"), + Check("rst-link", RST_LINK, "`text `_", "[text](url)"), + Check("list-break", None, "fence between items", "indent the fence 4 spaces to nest it"), + Check("list-indent", None, "2-space continuation", "indent the block 4 spaces under its item"), + Check("list-blank", None, "item after indented block", "add a blank line before the item"), +) + + +@dataclass(frozen=True) +class Finding: + path: Path + line: int + category: str + snippet: str + + def format(self) -> str: + try: + location: Path | str = self.path.relative_to(REPO_ROOT) + except ValueError: + location = self.path + return f" {location}:{self.line}: [{self.category}] {self.snippet.strip()}" + + +def _scan_line(text: str) -> list[str]: + """Return every RST-residue category found in a single line (a line can carry more + than one, e.g. a role and an external link).""" + return [c.category for c in CHECKS if c.pattern is not None and c.pattern.search(text)] + + +def lint_python(path: Path) -> list[Finding]: + """Scan the docstrings (module, classes, functions) of a Python file. + + Only docstrings are checked -- they are what mkdocstrings renders -- so RST-looking + text inside ordinary code or string literals is never misreported.""" + source = path.read_text(encoding="utf-8") + try: + tree = ast.parse(source) + except SyntaxError as exc: # pragma: no cover - surfaced, not silently skipped + return [Finding(path, exc.lineno or 0, "syntax-error", str(exc.msg))] + + doc_nodes = (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef) + # node.body[0].value is the docstring literal; its lineno is the line the string opens + # on, so content line i maps to source line (start + i). + docstrings = [ + (docstring, node.body[0].value.lineno) # type: ignore[attr-defined] + for node in ast.walk(tree) + if isinstance(node, doc_nodes) + if (docstring := ast.get_docstring(node, clean=False)) + ] + return [ + Finding(path, start + offset, category, line) + for docstring, start in docstrings + for offset, line in enumerate(docstring.splitlines()) + for category in _scan_line(line) + ] + + +class Fence(NamedTuple): + """A fenced code block, by 0-based line index. ``terminated`` is False when the fence + has no closing delimiter before EOF, in which case ``close`` is the last line.""" + + open: int + close: int + terminated: bool + + +def fenced_blocks(lines: list[str]) -> list[Fence]: + """Index every fenced code block in ``lines``. + + An unterminated fence is malformed Markdown that `mkdocs build` surfaces anyway; it is + still returned (with ``terminated=False``, ``close`` at the last line) so callers that + skip code can skip to EOF.""" + blocks: list[Fence] = [] + fence: str | None = None + open_idx = -1 + for i, line in enumerate(lines): + stripped = line.lstrip() + if fence is None: + if stripped.startswith(("```", "~~~")): + fence, open_idx = stripped[:3], i + elif stripped.startswith(fence): + blocks.append(Fence(open_idx, i, terminated=True)) + fence = None + if fence is not None: + blocks.append(Fence(open_idx, len(lines) - 1, terminated=False)) + return blocks + + +def find_list_breaking_fences(lines: list[str], blocks: list[Fence]) -> list[tuple[int, str]]: + """Return ``(lineno, snippet)`` for each fenced code block at column 0 that splits a + list -- i.e. one whose nearest non-blank neighbours on both sides are top-level list + items. Such a fence is not indented into the preceding item, so Markdown closes the + list at the fence and the following item starts a new one. The fix is to indent the + fence (4 spaces) so it nests inside its list item. See the module docstring. + + Conservative on purpose: it requires a list item *directly* before and after (a + continuation line or paragraph in between is not matched), keeping false positives low + for a check that fails CI. Unterminated fences are ignored.""" + + def neighbour(start: int, step: int) -> str | None: + j = start + step + while 0 <= j < len(lines): + if lines[j].strip(): + return lines[j] + j += step + return None + + def splits_a_list(open_i: int, close_i: int) -> bool: + if lines[open_i][:1].isspace(): + return False # indented fence: already nested in the list item, not a break + before = neighbour(open_i, -1) + after = neighbour(close_i, +1) + return bool(before and after and LIST_ITEM.match(before) and LIST_ITEM.match(after)) + + return [ + (fence.open + 1, lines[fence.open]) + for fence in blocks + if fence.terminated and splits_a_list(fence.open, fence.close) + ] + + +def find_list_continuation_issues( + lines: list[str], in_code: set[int] +) -> list[tuple[int, str, str]]: + """Return ``(lineno, category, snippet)`` for list continuations Python-Markdown will + mis-render (see the module docstring): + + - ``list-indent``: a blank-line-separated block inside a list item indented 1-3 + spaces. Python-Markdown requires 4; at less, the block escapes the list. + - ``list-blank``: a top-level list item directly after a line indented 4+ spaces. + Without a blank line in between, the item is absorbed into the preceding paragraph + as literal ``- `` text. + + Lazy continuations (an indented line with no blank line before it) are valid at any + indent and are not flagged. Fenced-code lines are opaque: never flagged themselves, + but they keep the item scope open and their indent feeds the ``list-blank`` check so + an item directly after an indented fence is still caught.""" + findings: list[tuple[int, str, str]] = [] + in_item = False # inside a top-level list item's scope + prev_blank = True + prev_indent = 0 + for i, line in enumerate(lines): + stripped = line.strip() + if not stripped: + prev_blank = True + continue + indent = len(line) - len(line.lstrip(" ")) + if i not in in_code: + if indent == 0: + is_item = bool(LIST_ITEM.match(line)) + if is_item and in_item and not prev_blank and prev_indent >= 4: + findings.append((i + 1, "list-blank", line)) + in_item = is_item + elif in_item and prev_blank and indent < 4: + findings.append((i + 1, "list-indent", line)) + prev_blank = False + prev_indent = indent + return findings + + +def lint_markdown(path: Path) -> list[Finding]: + """Scan a Markdown file: RST residue in prose (skipping fenced code blocks), plus + list-structure problems (see find_list_breaking_fences and + find_list_continuation_issues).""" + lines = path.read_text(encoding="utf-8").splitlines() + blocks = fenced_blocks(lines) + in_code = {i for fence in blocks for i in range(fence.open, fence.close + 1)} + + prose = [ + Finding(path, lineno, category, line) + for lineno, line in enumerate(lines, start=1) + if lineno - 1 not in in_code + for category in _scan_line(line) + ] + breaks = [ + Finding(path, lineno, "list-break", snippet) + for lineno, snippet in find_list_breaking_fences(lines, blocks) + ] + continuations = [ + Finding(path, lineno, category, snippet) + for lineno, category, snippet in find_list_continuation_issues(lines, in_code) + ] + return prose + breaks + continuations + + +def iter_files(paths: tuple[Path, ...]) -> list[Path]: + files: list[Path] = [] + for path in paths: + if path.is_file(): + files.append(path) + elif path.is_dir(): + files.extend(sorted(path.rglob("*.py"))) + files.extend(sorted(path.rglob("*.md"))) + else: + raise FileNotFoundError(f"{path} does not exist") + return files + + +LINTERS = {".py": lint_python, ".md": lint_markdown} + + +def lint(paths: tuple[Path, ...]) -> list[Finding]: + return [ + finding + for file in iter_files(paths) + if file.suffix in LINTERS + for finding in LINTERS[file.suffix](file) + ] + + +def main() -> int: + args = sys.argv[1:] + paths = tuple(Path(a).resolve() for a in args) if args else DEFAULT_PATHS + findings = lint(paths) + + if not findings: + print("No reStructuredText residue or list-breaking fences found in docs.") + return 0 + + print( + f"Found {len(findings)} docs issue(s) -- RST markup that will not render under " + "MkDocs/mkdocstrings, or Markdown that renders as valid-but-wrong HTML:\n", + file=sys.stderr, + ) + for finding in findings: + print(finding.format(), file=sys.stderr) + remediation = "\n".join(f" {c.category:<13} {c.example:<19} -> {c.fix}" for c in CHECKS) + print( + f"\nFix each issue (see ci/lint_docs.py header):\n{remediation}", + file=sys.stderr, + ) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 0000000000..a3783cc39a --- /dev/null +++ b/codecov.yml @@ -0,0 +1,34 @@ +coverage: + status: + patch: + default: + target: auto + informational: true + project: + default: + target: auto + threshold: 0.1 + flags: + - tests +flags: + tests: + paths: + - src/ + carryforward: true + gpu: + paths: + - src/ + carryforward: true +codecov: + notify: + # 6 = test.yml: 3 (optional+ubuntu) + 2 (upstream + min_deps), hypothesis: 1 + after_n_builds: 6 + wait_for_ci: yes +comment: + layout: "diff, files" + behavior: default + require_changes: true # if true: only post the comment if coverage changes + branches: # branch names that can post comment + - "main" +github_checks: + annotations: false diff --git a/data/donotdelete b/data/donotdelete deleted file mode 100644 index b0c96f7ee5..0000000000 --- a/data/donotdelete +++ /dev/null @@ -1 +0,0 @@ -This directory is used for data files created during testing. diff --git a/design/chunk-grid.md b/design/chunk-grid.md new file mode 100644 index 0000000000..0f12e35c4b --- /dev/null +++ b/design/chunk-grid.md @@ -0,0 +1,720 @@ +# Unified Chunk Grid + +Version: 6 + +Design document for adding rectilinear (variable) chunk grid support to **zarr-python**, conforming to the [rectilinear chunk grid extension spec](https://github.com/zarr-developers/zarr-extensions/pull/25). + +**Related:** + +- [#3750](https://github.com/zarr-developers/zarr-python/issues/3750) (single ChunkGrid proposal) +- [#3534](https://github.com/zarr-developers/zarr-python/pull/3534) (rectilinear implementation) +- [#3735](https://github.com/zarr-developers/zarr-python/pull/3735) (chunk grid module/registry) +- [ZEP0003](https://github.com/zarr-developers/zeps/blob/main/draft/ZEP0003.md) (variable chunking spec) +- [zarr-specs#370](https://github.com/zarr-developers/zarr-specs/pull/370) (sharding v1.1: non-divisible subchunks) +- [zarr-extensions#25](https://github.com/zarr-developers/zarr-extensions/pull/25) (rectilinear extension) +- [zarr-extensions#34](https://github.com/zarr-developers/zarr-extensions/issues/34) (sharding + rectilinear) + +## Problem + +Chunk grids form a hierarchy β€” the rectilinear grid is strictly more general than the regular grid. Any regular grid is expressible as a rectilinear grid. There is no known chunk grid that is both (a) more general than rectilinear and (b) retains the axis-aligned tessellation properties Zarr assumes. All known grids are special cases: + +| Grid type | Description | Example | +|---|---|---| +| Regular | Uniform chunk size, boundary chunks padded with fill_value | `[10, 10, 10, 10]` | +| Regular-bounded (zarrs) | Uniform chunk size, boundary chunks trimmed to array extent | `[10, 10, 10, 5]` | +| HPC boundary-padded | Regular interior, larger boundary chunks ([VirtualiZarr#217](https://github.com/zarr-developers/VirtualiZarr/issues/217)) | `[10, 8, 8, 8, 10]` | +| Fully variable | Arbitrary per-chunk sizes | `[5, 12, 3, 20]` | + +Prior iterations on the chunk grid design were based on the Zarr V3 spec's definition of chunk grids as an extension point alongside codecs, dtypes, etc. Therefore, we started designing the chunk grid implementation following a similar registry-based approach. However, in practice chunk grids are fundamentally different than codecs. Codecs are independent; supporting `zstd` tells you nothing about `gzip`. Chunk grids are not: every regular grid is a valid rectilinear grid. A registry-based plugin system makes sense for codecs but adds complexity without clear benefit for chunk grids. Here we start from some basic goals and propose a more fitting design for supporting different chunk grids in zarr-python. + +## Goals + +1. **Follow the zarr extension proposal.** The implementation should conform to the [rectilinear chunk grid spec](https://github.com/zarr-developers/zarr-extensions/tree/main/chunk-grids/rectilinear), not innovate on the metadata format. +2. **Minimize changes to the public API.** Users creating regular arrays should see no difference. Rectilinear is additive. +3. **Maintain backwards compatibility.** Existing code using `.chunks`, `isinstance` checks, or importing `RegularChunkGrid`/`RectilinearChunkGrid` from `zarr.core.chunk_grids` should continue to work where practical (with deprecation warnings where appropriate). Internal code paths/imports may be broken with justification. +4. **Design for future iteration.** The internal architecture should allow refactoring (e.g., metadata/array separation, new dimension types) without breaking the public API. +5. **Minimize downstream changes.** xarray, VirtualiZarr, Icechunk, Cubed, etc. should need minimal updates. +6. **Minimize time to stable release.** Ship behind a feature flag, stabilize through real-world usage, promote to stable API. +7. **The new API should be useful.** `read_chunk_sizes`/`write_chunk_sizes`, `ChunkGrid.__getitem__`, `is_regular` β€” these should solve real problems, not just expose internals. +8. **Extensible for other serialization structures.** The per-dimension design should support future encodings (tile, temporal) without changes to indexing or codecs. + +## Design + +### Design choices + +1. **A chunk grid is a concrete arrangement of chunks.** Not an abstract tiling pattern. This means that the chunk grid is bound to specific array dimensions, which enables the chunk grid to answer any question about any chunk (offset, size, count) without external parameters. +2. **One implementation, multiple serialization forms.** A single `ChunkGrid` class handles all chunking logic. The serialization format (`"regular"` vs `"rectilinear"`) is chosen by the metadata layer, not the grid. +3. **No chunk grid registry.** Simple name-based dispatch in the metadata layer's `parse_chunk_grid()`. +4. **Fixed vs Varying per dimension.** `FixedDimension(size, extent)` for uniform chunks; `VaryingDimension(edges, extent)` for per-chunk edge lengths with precomputed prefix sums. Avoids expanding regular dimensions into lists of identical values. +5. **Transparent transitions.** Operations like `resize()` can move an array from regular to rectilinear chunking. + +### Internal representation + +```python +@dataclass(frozen=True) +class FixedDimension: + """Uniform chunk size. Boundary chunks contain less data but are + encoded at full size by the codec pipeline.""" + size: int # chunk edge length (>= 0) + extent: int # array dimension length + + def __post_init__(self) -> None: + # validates size >= 0 and extent >= 0 + + @property + def nchunks(self) -> int: + if self.size == 0: + return 0 + return ceildiv(self.extent, self.size) + + def index_to_chunk(self, idx: int) -> int: + return idx // self.size # raises IndexError if OOB + def chunk_offset(self, chunk_ix: int) -> int: + return chunk_ix * self.size # raises IndexError if OOB + def chunk_size(self, chunk_ix: int) -> int: + return self.size # always uniform; raises IndexError if OOB + def data_size(self, chunk_ix: int) -> int: + return max(0, min(self.size, self.extent - chunk_ix * self.size)) # raises IndexError if OOB + @property + def unique_edge_lengths(self) -> Iterable[int]: + return (self.size,) # O(1) + def indices_to_chunks(self, indices: NDArray) -> NDArray: + return indices // self.size + def with_extent(self, new_extent: int) -> FixedDimension: + return FixedDimension(size=self.size, extent=new_extent) + def resize(self, new_extent: int) -> FixedDimension: + return FixedDimension(size=self.size, extent=new_extent) + +@dataclass(frozen=True) +class VaryingDimension: + """Explicit per-chunk sizes. The last chunk may extend past the array + extent (extent < sum(edges)), in which case data_size clips to the + valid region while chunk_size returns the full edge length for codec + processing. This underflow is allowed to match how regular grids + handle boundary chunks, and to support shrinking an array without + rewriting chunk edges (the spec allows trailing edges beyond the extent).""" + edges: tuple[int, ...] # per-chunk edge lengths (all > 0) + cumulative: tuple[int, ...] # prefix sums for O(log n) lookup + extent: int # array dimension length (may be < sum(edges)) + + def __init__(self, edges: Sequence[int], extent: int) -> None: + # validates edges non-empty, all > 0, extent >= 0, extent <= sum(edges) + # computes cumulative via itertools.accumulate + # uses object.__setattr__ for frozen dataclass + + @property + def nchunks(self) -> int: + # number of chunks that overlap [0, extent) + if extent == 0: + return 0 + return bisect.bisect_left(self.cumulative, extent) + 1 + + @property + def ngridcells(self) -> int: + return len(self.edges) + + def index_to_chunk(self, idx: int) -> int: + return bisect.bisect_right(self.cumulative, idx) # raises IndexError if OOB + def chunk_offset(self, chunk_ix: int) -> int: + return self.cumulative[chunk_ix - 1] if chunk_ix > 0 else 0 # raises IndexError if OOB + def chunk_size(self, chunk_ix: int) -> int: + return self.edges[chunk_ix] # raises IndexError if OOB + def data_size(self, chunk_ix: int) -> int: + offset = self.chunk_offset(chunk_ix) + return max(0, min(self.edges[chunk_ix], self.extent - offset)) # raises IndexError if OOB + @property + def unique_edge_lengths(self) -> Iterable[int]: + # lazy generator: yields unseen values, short-circuits deduplication + def indices_to_chunks(self, indices: NDArray) -> NDArray: + return np.searchsorted(self.cumulative, indices, side='right') + def with_extent(self, new_extent: int) -> VaryingDimension: + # validates cumulative[-1] >= new_extent (O(1)), re-binds extent + return VaryingDimension(self.edges, extent=new_extent) + def resize(self, new_extent: int) -> VaryingDimension: + # grow past edge sum: append chunk of size (new_extent - sum(edges)) + # shrink or grow within edge sum: preserve all edges, re-bind extent +``` + +Both types implement the `DimensionGrid` protocol: `nchunks`, `extent`, `index_to_chunk`, `chunk_offset`, `chunk_size`, `data_size`, `indices_to_chunks`, `unique_edge_lengths`, `with_extent`, `resize`. Memory usage scales with the number of *varying* dimensions, not total chunks. + +All per-chunk methods (`chunk_offset`, `chunk_size`, `data_size`) raise `IndexError` for out-of-bounds chunk indices, providing consistent fail-fast behavior across both dimension types. + +The two size methods serve different consumers: + +| Method | Returns | Consumer | +|---|---|---| +| `chunk_size` | Buffer size for codec processing | Codec pipeline (`ArraySpec.shape`) | +| `data_size` | Valid data region within the buffer | Indexing pipeline (`chunk_selection` slicing) | + +For `FixedDimension`, these differ only at the boundary. For `VaryingDimension`, these differ only when the last chunk extends past the extent (i.e., `extent < sum(edges)`). This matches current zarr-python behavior: `get_chunk_spec` passes the full `chunk_shape` to the codec for all chunks, and the indexer generates a `chunk_selection` that clips the decoded buffer. + +### DimensionGrid Protocol + +```python +@runtime_checkable +class DimensionGrid(Protocol): + """Structural interface shared by FixedDimension and VaryingDimension.""" + + @property + def nchunks(self) -> int: ... + @property + def ngridcells(self) -> int: ... + @property + def extent(self) -> int: ... + def index_to_chunk(self, idx: int) -> int: ... + def chunk_offset(self, chunk_ix: int) -> int: ... # raises IndexError if OOB + def chunk_size(self, chunk_ix: int) -> int: ... # raises IndexError if OOB + def data_size(self, chunk_ix: int) -> int: ... # raises IndexError if OOB + def indices_to_chunks(self, indices: NDArray[np.intp]) -> NDArray[np.intp]: ... + @property + def unique_edge_lengths(self) -> Iterable[int]: ... + def with_extent(self, new_extent: int) -> DimensionGrid: ... + def resize(self, new_extent: int) -> DimensionGrid: ... +``` + +The protocol is `@runtime_checkable`, enabling polymorphic handling of both dimension types without `isinstance` checks. + +`nchunks` and `ngridcells` differ when `extent < sum(edges)`: `nchunks` counts only chunks that overlap `[0, extent)`, while `ngridcells` counts total defined grid cells (i.e., `len(edges)`). For `FixedDimension`, both are equal. For `VaryingDimension`, they differ after a resize that shrinks the extent below the edge sum. + +### ChunkSpec + +```python +@dataclass(frozen=True) +class ChunkSpec: + slices: tuple[slice, ...] # valid data region in array coordinates + codec_shape: tuple[int, ...] # buffer shape for codec processing + + @property + def shape(self) -> tuple[int, ...]: + return tuple(s.stop - s.start for s in self.slices) + + @property + def is_boundary(self) -> bool: + return self.shape != self.codec_shape +``` + +For interior chunks, `shape == codec_shape`. For boundary chunks of a regular grid, `codec_shape` is the full declared chunk size while `shape` is clipped. For rectilinear grids, `shape == codec_shape` unless the last chunk extends past the extent. + +### API + +```python +# Creating arrays +arr = zarr.create_array(shape=(100, 200), chunks=(10, 20)) # regular +arr = zarr.create_array(shape=(60, 100), chunks=[[10, 20, 30], [25, 25, 25, 25]]) # rectilinear + +# ChunkGrid as a collection +grid = arr._chunk_grid # ChunkGrid (bound to array shape) +grid.grid_shape # (10, 10) β€” number of chunks per dimension +grid.ndim # 2 +grid.is_regular # True if all dimensions are Fixed + +spec = grid[0, 1] # ChunkSpec for chunk at grid position (0, 1) +spec.slices # (slice(0, 10), slice(20, 40)) +spec.shape # (10, 20) β€” data shape +spec.codec_shape # (10, 20) β€” same for interior chunks + +boundary = grid[9, 0] # boundary chunk (extent=100, size=10) +boundary.shape # (10, 20) β€” data shape +boundary.codec_shape # (10, 20) β€” codec sees full buffer + +grid[99, 99] # None β€” out of bounds + +for spec in grid: # iterate all chunks + ... + +# .chunks property: retained for regular grids, raises NotImplementedError for rectilinear +arr.chunks # (10, 20) + +# .read_chunk_sizes / .write_chunk_sizes: works for all grids (dask-style) +arr.write_chunk_sizes # ((10, 10, ..., 10), (20, 20, ..., 20)) +``` + +`ChunkGrid.__getitem__` constructs `ChunkSpec` using `chunk_size` for `codec_shape` and `data_size` for `slices`: + +```python +def __getitem__(self, coords: int | tuple[int, ...]) -> ChunkSpec | None: + if isinstance(coords, int): + coords = (coords,) + slices = [] + codec_shape = [] + for dim, ix in zip(self.dimensions, coords): + if ix < 0 or ix >= dim.nchunks: + return None + offset = dim.chunk_offset(ix) + slices.append(slice(offset, offset + dim.data_size(ix))) + codec_shape.append(dim.chunk_size(ix)) + return ChunkSpec(tuple(slices), tuple(codec_shape)) +``` + +#### Construction + +`from_sizes` requires `array_shape`, binding the extent per dimension at construction time. This is a core design choice: a chunk grid is a concrete arrangement for a specific array, not an abstract tiling pattern. + +```python +# Regular grid β€” all FixedDimension +grid = ChunkGrid.from_sizes(array_shape=(100, 200), chunk_sizes=(10, 20)) + +# Rectilinear grid β€” extent = sum(edges) when shape matches +grid = ChunkGrid.from_sizes(array_shape=(60, 100), chunk_sizes=[[10, 20, 30], [25, 25, 25, 25]]) + +# Rectilinear grid with boundary clipping β€” last chunk extends past array extent +# e.g., shape=(55, 90) but edges sum to (60, 100): data_size clips at extent +grid = ChunkGrid.from_sizes(array_shape=(55, 90), chunk_sizes=[[10, 20, 30], [25, 25, 25, 25]]) + +# Direct construction +grid = ChunkGrid(dimensions=(FixedDimension(10, 100), VaryingDimension([10, 20, 30], 55))) +``` + +When `extent < sum(edges)`, the dimension is always stored as `VaryingDimension` (even if all edges are identical) to preserve the explicit edge count. The last chunk's `chunk_size` returns the full declared edge (codec buffer) while `data_size` clips to the extent. This mirrors how `FixedDimension` handles boundary chunks in regular grids. + +#### Serialization + +```python +# Regular grid: +{"name": "regular", "configuration": {"chunk_shape": [10, 20]}} + +# Rectilinear grid (with RLE compression and "kind" field): +{ + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[10, 20, 30], [[25, 4]]]}, +} +``` + +Both names deserialize to the same `ChunkGrid` class. The serialized form does not include the array extent β€” that comes from `shape` in array metadata and is combined with the chunk grid when constructing a `ChunkGrid` via `ChunkGrid.from_metadata()`. + +**The `ChunkGrid` does not serialize itself.** The format choice (`"regular"` vs `"rectilinear"`) belongs to `ArrayV3Metadata`. Serialization and deserialization are handled by the metadata-layer chunk grid classes (`RegularChunkGridMetadata` and `RectilinearChunkGridMetadata` in `metadata/v3.py`), which provide `to_dict()` and `from_dict()` methods. + +For `create_array`, the format is inferred from the `chunks` argument: a flat tuple produces `"regular"`, a nested list produces `"rectilinear"`. The `_is_rectilinear_chunks()` helper detects nested sequences like `[[10, 20], [5, 5]]`. + +##### Rectilinear spec compliance + +The rectilinear format requires `"kind": "inline"` (validated by `validate_rectilinear_kind()`). Per the spec, each element of `chunk_shapes` can be: + +- A bare integer `m`: repeated until `sum >= array_extent` +- A list of bare integers: explicit per-chunk sizes +- A mixed array of bare integers and `[value, count]` RLE pairs + +RLE compression is used when serializing: runs of identical sizes become `[value, count]` pairs, singletons stay as bare integers. + +```python +# compress_rle([10, 10, 10, 5]) -> [[10, 3], 5] +# expand_rle([[10, 3], 5]) -> [10, 10, 10, 5] +``` + +For a single-element `chunk_shapes` tuple like `(10,)`, `RectilinearChunkGridMetadata.to_dict()` serializes it as a bare integer `10`. Per the rectilinear spec, a bare integer is repeated until the sum >= extent, preserving the full codec buffer size for boundary chunks. + +**Zero-extent handling:** Regular grids serialize zero-extent dimensions without issue (the format encodes only `chunk_shape`, no edges). Rectilinear grids cannot represent zero-extent dimensions because the spec requires at least one positive-integer edge length per axis. + +#### read_chunk_sizes / write_chunk_sizes + +The `read_chunk_sizes` and `write_chunk_sizes` properties provide universal access to per-dimension chunk data sizes, matching the dask `Array.chunks` convention. They work for both regular and rectilinear grids: + +- `write_chunk_sizes`: always returns outer (storage) chunk sizes +- `read_chunk_sizes`: returns inner chunk sizes when sharding is used, otherwise same as `write_chunk_sizes` + +```python +>>> arr = zarr.create_array(store, shape=(100, 80), chunks=(30, 40)) +>>> arr.write_chunk_sizes +((30, 30, 30, 10), (40, 40)) + +>>> arr = zarr.create_array(store, shape=(60, 100), chunks=[[10, 20, 30], [50, 50]]) +>>> arr.write_chunk_sizes +((10, 20, 30), (50, 50)) +``` + +The underlying `ChunkGrid.chunk_sizes` property (on the grid, not the array) returns the same as `write_chunk_sizes`. + +#### Resize + +```python +arr.resize((80, 100)) # re-binds extent; FixedDimension stays fixed +arr.resize((200, 100)) # VaryingDimension grows by appending a new chunk +arr.resize((30, 100)) # VaryingDimension shrinks: preserves all edges, re-binds extent +``` + +Resize uses `ChunkGrid.update_shape(new_shape)`, which delegates to each dimension's `.resize()` method: +- `FixedDimension.resize()`: simply re-binds the extent (identical to `with_extent`) +- `VaryingDimension.resize()`: grow past `sum(edges)` appends a chunk covering the gap; shrink or grow within `sum(edges)` preserves all edges and re-binds the extent (the spec allows trailing edges beyond the array extent) + +**Known limitation (deferred):** When growing a `VaryingDimension`, the current implementation always appends a single chunk covering the new region. For example, `[10, 10, 10]` resized from 30 to 45 produces `[10, 10, 10, 15]` instead of the more natural `[10, 10, 10, 10, 10]`. A future improvement should add an optional `chunks` parameter to `resize()` that controls how the new region is partitioned, with a sane default (e.g., repeating the last chunk size). This is safely deferrable because: +- `FixedDimension` already handles resize correctly (regular grids stay regular) +- The single-chunk default produces valid state, just suboptimal chunk layout +- Rectilinear arrays are behind an experimental feature flag +- Adding an optional parameter is backwards-compatible + +Open design questions for the `chunks` parameter: +- Does it describe the new region only, or the entire post-resize array? +- Must the overlapping portion agree with existing chunks (no rechunking)? +- What is the type? Same as `chunks` in `create_array`? + +#### from_array + +The `from_array()` function handles both regular and rectilinear source arrays: + +```python +src = zarr.create_array(store, shape=(60, 100), chunks=[[10, 20, 30], [50, 50]]) +new = zarr.from_array(data=src, store=new_store, chunks="keep") +# Preserves rectilinear structure: new.write_chunk_sizes == ((10, 20, 30), (50, 50)) +``` + +When `chunks="keep"`, the logic checks `data._chunk_grid.is_regular`: +- Regular: extracts `data.chunks` (flat tuple) and preserves shards +- Rectilinear: extracts `data.write_chunk_sizes` (nested tuples) and forces shards to None + +### Indexing + +The indexing pipeline is coupled to regular grid assumptions β€” every per-dimension indexer takes a scalar `dim_chunk_len: int` and uses `//` and `*`: + +```python +dim_chunk_ix = self.dim_sel // self.dim_chunk_len # IntDimIndexer +dim_offset = dim_chunk_ix * self.dim_chunk_len # SliceDimIndexer +``` + +Replace `dim_chunk_len: int` with the dimension object (`FixedDimension | VaryingDimension`). The shared interface means the indexer code structure stays the same β€” `dim_sel // dim_chunk_len` becomes `dim_grid.index_to_chunk(dim_sel)`. O(1) for regular, binary search for varying. + +### Codec pipeline + +Today, `get_chunk_spec()` returns the same `ArraySpec(shape=chunk_grid.chunk_shape)` for every chunk. For rectilinear grids, each chunk has a different codec shape: + +```python +def get_chunk_spec(self, chunk_coords, array_config, prototype) -> ArraySpec: + spec = self._chunk_grid[chunk_coords] + return ArraySpec(shape=spec.codec_shape, ...) +``` + +Note `spec.codec_shape`, not `spec.shape`. For regular grids, `codec_shape` is uniform (preserving current behavior). The boundary clipping flow is unchanged: + +``` +Write: user data β†’ pad to codec_shape with fill_value β†’ encode β†’ store +Read: store β†’ decode to codec_shape β†’ slice via chunk_selection β†’ user data +``` + +### Sharding + +The `ShardingCodec` constructs a `ChunkGrid` per shard using the shard shape as extent and the subchunk shape as `FixedDimension`. Each shard is self-contained β€” it doesn't need to know whether the outer grid is regular or rectilinear. Validation checks that every unique edge length per dimension is divisible by the inner chunk size, using `dim.unique_edge_lengths` for efficient polymorphic iteration (O(1) for fixed dimensions, lazy-deduplicated for varying). + +``` +Level 1 β€” Outer chunk grid (shard boundaries): regular or rectilinear +Level 2 β€” Inner subchunk grid (within each shard): always regular +Level 3 β€” Shard index: ceil(shard_dim / subchunk_dim) entries per dimension +``` + +[zarr-specs#370](https://github.com/zarr-developers/zarr-specs/pull/370) lifts the requirement that subchunk shapes evenly divide the shard shape. With the proposed `ChunkGrid`, this just means removing the `shard_shape % subchunk_shape == 0` validation β€” `FixedDimension` already handles boundary clipping via `data_size`. + +| Outer grid | Subchunk divisibility | Required change | +|---|---|---| +| Regular | Evenly divides (v1.0) | None | +| Regular | Non-divisible (v1.1) | Remove divisibility validation | +| Rectilinear | Evenly divides | Remove "sharding incompatible" guard | +| Rectilinear | Non-divisible | Both changes | + +### What this replaces + +| Current | Proposed | +|---|---| +| `ChunkGrid` ABC + `RegularChunkGrid` subclass | Single concrete `ChunkGrid` with `is_regular` | +| `RectilinearChunkGrid` (#3534) | Same `ChunkGrid` class | +| Chunk grid registry + entrypoints (#3735) | Direct name dispatch | +| `arr.chunks` | Retained for regular; `arr.read_chunk_sizes`/`arr.write_chunk_sizes` for general use | +| `get_chunk_shape(shape, coord)` | `grid[coord].codec_shape` or `grid[coord].shape` | + +## Design decisions + +### Why store the extent in ChunkGrid? + +The chunk grid is a concrete arrangement, not an abstract tiling pattern. A finite collection naturally has an extent. Storing it enables `__getitem__`, eliminates `dim_len` parameters from every method, and makes the grid self-describing. + +This does *not* mean `ArrayV3Metadata.shape` should delegate to the grid. The array shape remains an independent field in metadata. The extent is passed into the grid at construction time so it can answer boundary questions without external parameters. It is **not** serialized as part of the chunk grid JSON β€” it comes from the `shape` field in array metadata and is combined with the chunk grid configuration in `ChunkGrid.from_metadata()`. + +### Why distinguish chunk_size from data_size? + +A chunk in a regular grid has two sizes. `chunk_size` is the buffer size the codec processes β€” always `size` for `FixedDimension`, even at the boundary (padded with `fill_value`). `data_size` is the valid data region β€” clipped to `extent % size` at the boundary. The indexing layer uses `data_size` to generate `chunk_selection` slices. + +This matches current zarr-python behavior and matters for: +1. **Backward compatibility.** Existing stores have boundary chunks encoded at full `chunk_shape`. +2. **Codec simplicity.** Codecs assume uniform input shapes for regular grids. +3. **Shard index correctness.** The index assumes `subchunk_dim`-sized entries. + +For `VaryingDimension`, `chunk_size == data_size` when `extent == sum(edges)`. When `extent < sum(edges)` (e.g., after a resize that keeps the last chunk oversized), `data_size` clips the last chunk. This is the fundamental difference: `FixedDimension` has a declared size plus an extent that clips data; `VaryingDimension` has explicit sizes that normally *are* the extent but can also extend past it. + +### Why not a chunk grid registry? + +There is no known chunk grid outside the rectilinear family that retains the tessellation properties zarr-python assumes. A `match` on the grid name is sufficient. + +### Why a single ChunkGrid class instead of RegularChunkGrid + RectilinearChunkGrid? + +[Discussed in #3534.](https://github.com/zarr-developers/zarr-python/pull/3534) @d-v-b argued that `RegularChunkGrid` is unnecessary since rectilinear is more general; @dcherian argued that downstream libraries need a fast way to detect regular grids without inspecting potentially millions of chunk edges (see [xarray#9808](https://github.com/pydata/xarray/pull/9808)). + +The resolution: a single `ChunkGrid` class with an `is_regular` property (O(1), cached at construction). This gives downstream code the fast-path detection @dcherian needed without the class hierarchy complexity @d-v-b wanted to avoid. The metadata document's `name` field (`"regular"` vs `"rectilinear"`) is also available for clients who inspect JSON directly. + +A backwards-compatibility shim in `chunk_grids.py` preserves the old `RegularChunkGrid` / `RectilinearChunkGrid` import paths with deprecation warnings β€” see [Backwards compatibility](#backwards-compatibility). + +### Why is ChunkGrid a concrete class instead of a Protocol/ABC? + +The old design had `ChunkGrid` as an ABC with `RegularChunkGrid` as its only subclass. #3534 added `RectilinearChunkGrid` as a second subclass. This branch makes `ChunkGrid` a single concrete class instead, with separate metadata DTOs (`RegularChunkGridMetadata` and `RectilinearChunkGridMetadata` in `metadata/v3.py`) for serialization. + +All known grids are special cases of rectilinear, so there's no need for a class hierarchy at the grid level. A `ChunkGrid` Protocol/ABC would mean every caller programs against an abstract interface and adding a grid type requires implementing ~15 methods. A single class is simpler. + +Note: the *dimension* types (`FixedDimension`, `VaryingDimension`) do use a `DimensionGrid` Protocol β€” that's where the polymorphism lives. The grid-level class is concrete; the dimension-level types are polymorphic. If a genuinely novel grid type emerges that can't be expressed as a combination of per-dimension types, a grid-level Protocol can be extracted. + +### Why `.chunks` raises for rectilinear grids + +[Debated in #3534.](https://github.com/zarr-developers/zarr-python/pull/3534) @d-v-b suggested making `.chunks` return `tuple[tuple[int, ...], ...]` (dask-style) for all grids. @dcherian strongly objected: every downstream consumer expects `tuple[int, ...]`, and silently returning a different type would be worse than raising. Materializing O(10M) chunk edges into a Python tuple is also a real performance risk ([xarray#8902](https://github.com/pydata/xarray/issues/8902#issuecomment-2546127373)). + +The resolution: +- `.chunks` is retained for regular grids (returns `tuple[int, ...]` as before) +- `.chunks` raises `NotImplementedError` for rectilinear grids with a message pointing to `.read_chunk_sizes`/`.write_chunk_sizes` +- `.read_chunk_sizes` and `.write_chunk_sizes` return `tuple[tuple[int, ...], ...]` (dask convention) for all grids + +@maxrjones noted in review that deprecating `.chunks` for regular grids was not desirable. The current branch does not deprecate it. + +### User control over grid serialization format + +@d-v-b raised in #3534 that users need a way to say "these chunks are regular, but serialize as rectilinear" (e.g., to allow future append/extend workflows without format changes). @jhamman initially made nested-list input always produce `RectilinearChunkGridMetadata`. + +The current branch resolves this via the metadata-layer chunk grid classes. When metadata is deserialized, the original name (from `{"name": "regular"}` or `{"name": "rectilinear"}`) determines which metadata class is instantiated (`RegularChunkGridMetadata` or `RectilinearChunkGridMetadata`), and that class handles serialization via `to_dict()`. Current inference behavior for `create_array`: +- `chunks=(10, 20)` (flat tuple) β†’ infers `"regular"` +- `chunks=[[10, 20], [5, 5]]` (nested lists with varying sizes) β†’ infers `"rectilinear"` +- `chunks=[[10, 10], [20, 20]]` (nested lists with uniform sizes) β†’ `from_sizes` collapses to `FixedDimension`, so `is_regular=True` and infers `"regular"` + +**Open question:** Should uniform nested lists preserve `"rectilinear"` to support future append workflows without a format change? This could be addressed by checking the input form before collapsing, or by allowing users to pass `chunk_grid_name` explicitly through the `create_array` API. + +### Deferred: Tiled/periodic chunk patterns + +[#3750 discussion](https://github.com/zarr-developers/zarr-python/issues/3750) identified periodic chunk patterns as a use case not efficiently served by RLE alone. RLE compresses runs of identical values (`np.repeat`), but periodic patterns like days-per-month (`[31, 28, 31, 30, ...]` repeated 30 years) need a tile encoding (`np.tile`). Real-world examples include: + +- **Oceanographic models** (ROMS): HPC boundary-padded chunks like `[10, 8, 8, 8, 10]` β€” handled by RLE +- **Temporal axes**: days-per-month, hours-per-day β€” need tile encoding for compact metadata +- **Temporal-aware grids**: date/time-aware chunk grids that layer over other axes (raised by @LDeakin) + +A `TiledDimension` prototype was built ([commit 9c0f582](https://github.com/maxrjones/zarr-python/commit/9c0f582f)) demonstrating that the per-dimension design supports this without changes to indexing or the codec pipeline. However, it was intentionally excluded from this release because: + +1. **Metadata format must come first.** Tile encoding requires a new `kind` value in the rectilinear spec (currently only `"inline"` is defined). This should go through [zarr-extensions#25](https://github.com/zarr-developers/zarr-extensions/pull/25), not zarr-python unilaterally. +2. **The per-dimension architecture doesn't preclude it.** A future `TiledDimension` can implement the `DimensionGrid` protocol alongside `FixedDimension` and `VaryingDimension` with no changes to indexing, codecs, or the `ChunkGrid` class. +3. **RLE covers the MVP.** Most real-world variable chunk patterns (HPC boundaries, irregular partitions) are efficiently encoded with RLE. Tile encoding is an optimization for a specific (temporal) subset. + +### Metadata / Array separation (partially implemented) + +An earlier design doc proposed decoupling `ChunkGrid` (runtime) from `ArrayV3Metadata` (serialization), so that metadata would store only a plain dict and the array layer would construct the `ChunkGrid`. + +The current implementation partially realizes this separation: + +- **Metadata DTOs** (`RegularChunkGridMetadata`, `RectilinearChunkGridMetadata` in `metadata/v3.py`): Pure data, frozen dataclasses, no array shape. These live on `ArrayV3Metadata.chunk_grid` and represent only what goes into `zarr.json`. +- **`ChunkGrid`** (`chunk_grids.py`): Shape-bound, supports indexing, iteration, and chunk specs. Lives on `AsyncArray._chunk_grid`, constructed from metadata + `shape` via `ChunkGrid.from_metadata()`. + +This means `ArrayV3Metadata.chunk_grid` is now a `ChunkGridMetadata` (the DTO union type), **not** the runtime `ChunkGrid`. Code that previously accessed runtime methods on `metadata.chunk_grid` (e.g., `all_chunk_coords()`, `__getitem__`) must now use the grid from the array layer instead. + +The name controls serialization format; each metadata DTO class provides its own `to_dict()` method for serialization. The `ChunkGrid` handles all runtime queries. + +## Prior art + +**zarrs (Rust):** Three independent grid types behind a `ChunkGridTraits` trait. Key patterns adopted: Fixed vs Varying per dimension, prefix sums + binary search, `Option` for out-of-bounds, `NonZeroU64` for chunk dimensions, separate subchunk grid per shard, array shape at construction. + +**TensorStore (C++):** Stores only `chunk_shape` β€” boundary clipping via `valid_data_bounds` at query time. Both `RegularGridRef` and `IrregularGrid` internally. No registry. + +## Migration + +### Public API compatibility + +The user-facing API is fully backward-compatible. Existing code that creates, opens, reads, and writes zarr arrays continues to work without changes: + +- `zarr.create_array`, `zarr.open`, `zarr.open_array`, `zarr.open_group` -- unchanged signatures. The `chunks` parameter type is *widened* (now also accepts nested sequences for rectilinear grids), but all existing call patterns still work. +- `arr.chunks` -- returns `tuple[int, ...]` for regular arrays, same as before. +- `arr.shape`, `arr.dtype`, `arr.ndim`, `arr.shards` -- unchanged. +- Top-level `zarr` exports -- unchanged. +- Rectilinear chunks are gated behind `zarr.config.set({'array.rectilinear_chunks': True})`, so they cannot be created accidentally. + +New additions (purely additive): `arr.read_chunk_sizes`, `arr.write_chunk_sizes`, `zarr.experimental.ChunkGrid`, `zarr.experimental.ChunkSpec`. + +The breaking changes discussed below are confined to **internal modules** (`zarr.core.chunk_grids`, `zarr.core.metadata.v3`, `zarr.core.indexing`) that downstream libraries like cubed and VirtualiZarr access directly. + +### Internal API compatibility trade-off analysis + +This section analyzes the internal breaking changes from the metadata/array separation and evaluates two strategies: (A) add backward-compatibility shims in zarr-python, vs. (B) require downstream packages to update. The baseline is **no shims at all**. + +#### What breaks without any shims + +Three API changes affect downstream code: + +1. **`RegularChunkGrid` class removed from `zarr.core.chunk_grids`.** On `main`, `RegularChunkGrid` is defined in `chunk_grids.py` as a `Metadata` subclass. This branch replaces it with `RegularChunkGridMetadata` in `metadata/v3.py`. Without a shim, `from zarr.core.chunk_grids import RegularChunkGrid` raises `ImportError`. + +2. **`RegularChunkGrid` no longer available from `zarr.core.metadata.v3`.** On `main`, `v3.py` imports `RegularChunkGrid` from `chunk_grids.py` for internal use. VirtualiZarr imports it from this location (`from zarr.core.metadata.v3 import RegularChunkGrid`). Without the internal import, this raises `ImportError`. + +3. **`OrthogonalIndexer` constructor expects `ChunkGrid`, not `RegularChunkGrid`/`RegularChunkGridMetadata`.** Even if the import shims above resolve to `RegularChunkGridMetadata`, the indexer constructors access `chunk_grid._dimensions`, which only exists on the runtime `ChunkGrid` class. Cubed constructs `OrthogonalIndexer(selection, shape, RegularChunkGrid(chunk_shape=chunks))` directly. + +#### Downstream impact without shims + +**VirtualiZarr** (5 line changes across 2 files): + +```python +# manifests/array.py (line 6): import +- from zarr.core.metadata.v3 import ArrayV3Metadata, RegularChunkGrid ++ from zarr.core.metadata.v3 import ArrayV3Metadata, RegularChunkGridMetadata + +# manifests/array.py (line 53): isinstance check +- if not isinstance(_metadata.chunk_grid, RegularChunkGrid): ++ if not isinstance(_metadata.chunk_grid, RegularChunkGridMetadata): + +# parsers/zarr.py (line 16): import +- from zarr.core.chunk_grids import RegularChunkGrid ++ from zarr.core.metadata.v3 import RegularChunkGridMetadata + +# parsers/zarr.py (line 270): isinstance check +- if not isinstance(array_v3_metadata.chunk_grid, RegularChunkGrid): ++ if not isinstance(array_v3_metadata.chunk_grid, RegularChunkGridMetadata): + +# parsers/zarr.py (line 390): cast +- cast(RegularChunkGrid, metadata.chunk_grid).chunk_shape ++ cast(RegularChunkGridMetadata, metadata.chunk_grid).chunk_shape +``` + +The `manifests/array.py` import is from `zarr.core.metadata.v3` (never a documented export; VirtualiZarr relied on a transitive import). The `parsers/zarr.py` import is from `zarr.core.chunk_grids` (the canonical location on `main`). Both are straightforward renames. The `.chunk_shape` attribute is unchanged on the new class. + +If VirtualiZarr needs to support both old and new zarr-python, a version-conditional import adds ~5 more lines. + +**Cubed** (3 line changes in 1 file): + +```python +# core/ops.py (lines 626-631) +def _create_zarr_indexer(selection, shape, chunks): + if zarr.__version__[0] == "3": +- from zarr.core.chunk_grids import RegularChunkGrid ++ from zarr.core.chunk_grids import ChunkGrid + from zarr.core.indexing import OrthogonalIndexer +- return OrthogonalIndexer(selection, shape, RegularChunkGrid(chunk_shape=chunks)) ++ return OrthogonalIndexer(selection, shape, ChunkGrid.from_sizes(shape, chunks)) +``` + +Note that `ChunkGrid` is *not* a renamed class. `RegularChunkGrid(chunk_shape=chunks)` took only chunk sizes; `ChunkGrid.from_sizes(shape, chunks)` also requires the array shape. The `shape` parameter is already available at this call site. + +If cubed needs to support both old and new zarr-python: + +```python +def _create_zarr_indexer(selection, shape, chunks): + if zarr.__version__[0] == "3": + from zarr.core.indexing import OrthogonalIndexer + + try: + from zarr.core.chunk_grids import ChunkGrid + + return OrthogonalIndexer(selection, shape, ChunkGrid.from_sizes(shape, chunks)) + except ImportError: + from zarr.core.chunk_grids import RegularChunkGrid + + return OrthogonalIndexer(selection, shape, RegularChunkGrid(chunk_shape=chunks)) + else: + from zarr.indexing import OrthogonalIndexer + + return OrthogonalIndexer(selection, ZarrArrayIndexingAdaptor(shape, chunks)) +``` + +#### What shims can cover + +**Shim 1: `__getattr__` in `chunk_grids.py`** (~15 lines) + +Maps `RegularChunkGrid` to `RegularChunkGridMetadata` with a deprecation warning. Covers: +- The `from zarr.core.chunk_grids import RegularChunkGrid` import pattern (used by cubed and VirtualiZarr's `parsers/zarr.py`) +- `isinstance(x, RegularChunkGrid)` checks (because the name resolves to the actual class) +- `RegularChunkGrid(chunk_shape=(...))` construction (because `RegularChunkGridMetadata` accepts the same arguments) + +Does **not** cover: passing the result to `OrthogonalIndexer`, because `RegularChunkGridMetadata` lacks `._dimensions`. + +**Shim 2: `__getattr__` in `metadata/v3.py`** (~12 lines) + +Same pattern, covers VirtualiZarr's import from `zarr.core.metadata.v3`. Mirrors Shim 1 for a different import path. + +**Shim 3: Auto-coerce `ChunkGridMetadata` in indexer constructors** (~30 lines) + +A helper function + 1-line insertion in each of `BasicIndexer`, `OrthogonalIndexer`, `CoordinateIndexer`, and `MaskIndexer`: + +```python +def _resolve_chunk_grid(chunk_grid, shape): + """Coerce ChunkGridMetadata to runtime ChunkGrid if needed.""" + from zarr.core.chunk_grids import ChunkGrid as _ChunkGrid + from zarr.core.metadata.v3 import ChunkGridMetadata + + if isinstance(chunk_grid, _ChunkGrid): + return chunk_grid + if isinstance(chunk_grid, ChunkGridMetadata): + warnings.warn( + "Passing ChunkGridMetadata to indexers is deprecated. " + "Use ChunkGrid.from_sizes() instead.", + DeprecationWarning, + stacklevel=2, + ) + if hasattr(chunk_grid, "chunk_shape"): + return _ChunkGrid.from_sizes(shape, tuple(chunk_grid.chunk_shape)) + return _ChunkGrid.from_sizes(shape, chunk_grid.chunk_shapes) + raise TypeError(f"Expected ChunkGrid or ChunkGridMetadata, got {type(chunk_grid)}") +``` + +This covers cubed's `OrthogonalIndexer(selection, shape, RegularChunkGrid(...))` pattern end-to-end (combined with Shim 1). + +#### Comparison + +| | No shims | Shims 1+2 only | Shims 1+2+3 | +|---|---|---|---| +| **zarr-python additions** | 0 lines | ~27 lines | ~57 lines | +| **VirtualiZarr changes** | 5 lines | 0 lines | 0 lines | +| **Cubed changes** | 3 lines | 3 lines | 0 lines | +| **Maintenance burden** | None | Low (deprecation shims are well-understood) | Medium (indexer coercion blurs metadata/runtime boundary) | +| **API clarity** | Clean (metadata DTOs and runtime types are distinct) | Good (old names redirect to new names) | Weaker (indexers implicitly accept two type families) | + +With Shims 1+2 only, VirtualiZarr's `manifests/array.py` import from `zarr.core.metadata.v3` is covered by Shim 2, and the `parsers/zarr.py` import from `zarr.core.chunk_grids` is covered by Shim 1. The `isinstance` checks work because both shims resolve to `RegularChunkGridMetadata`. The `cast` works because `.chunk_shape` is unchanged. So VirtualiZarr needs 0 changes with Shims 1+2. The 3 lines for cubed remain because Shim 1 resolves the import but `OrthogonalIndexer` still needs a runtime `ChunkGrid`. + +### Downstream migration + +Migration from `main` (where only `RegularChunkGrid` and the abstract `ChunkGrid` ABC exist): + +| Old pattern (on `main`) | New pattern | +|---|---| +| `from zarr.core.chunk_grids import RegularChunkGrid` | `from zarr.core.metadata.v3 import RegularChunkGridMetadata` | +| `from zarr.core.chunk_grids import ChunkGrid` (ABC) | `from zarr.core.chunk_grids import ChunkGrid` (concrete class, different API) | +| `isinstance(cg, RegularChunkGrid)` | `isinstance(cg, RegularChunkGridMetadata)` or `grid.is_regular` on the runtime `ChunkGrid` | +| `cg.chunk_shape` on `RegularChunkGrid` | `cg.chunk_shape` on `RegularChunkGridMetadata` (unchanged) | +| `ChunkGrid.from_dict(data)` | `parse_chunk_grid(data)` from `zarr.core.metadata.v3` | +| `chunk_grid.all_chunk_coords(array_shape)` | `chunk_grid.all_chunk_coords()` (shape now stored in grid) | +| `chunk_grid.get_nchunks(array_shape)` | `chunk_grid.get_nchunks()` (shape now stored in grid) | + +During the earlier [#3534](https://github.com/zarr-developers/zarr-python/pull/3534) effort (which used separate `RegularChunkGrid`/`RectilinearChunkGrid` classes), downstream PRs and issues were opened to explore compatibility: + +- xarray ([#10880](https://github.com/pydata/xarray/pull/10880)), VirtualiZarr ([#877](https://github.com/zarr-developers/VirtualiZarr/pull/877)), Icechunk ([#1338](https://github.com/earth-mover/icechunk/issues/1338)), cubed ([#876](https://github.com/cubed-dev/cubed/issues/876)) + +These target #3534's API, not this branch's unified `ChunkGrid` design. New downstream POC branches for this design are linked in [Proofs of concepts](#proofs-of-concepts). + +### Credits + +This implementation builds on prior work: + +- **[#3534](https://github.com/zarr-developers/zarr-python/pull/3534)** (@jhamman) β€” RLE helpers, validation logic, test cases, and the review discussion that shaped the architecture. +- **[#3737](https://github.com/zarr-developers/zarr-python/pull/3737)** β€” extent-in-grid idea (adopted per-dimension). +- **[#1483](https://github.com/zarr-developers/zarr-python/pull/1483)** β€” original variable chunking POC. +- **[#3736](https://github.com/zarr-developers/zarr-python/pull/3736)** β€” resolved by storing extent per-dimension. + + +## Open questions + +1. **Resize defaults (deferred):** When growing a rectilinear array, should `resize()` accept an optional `chunks` parameter? See the [Resize section](#resize) for details and open design questions. Regular arrays already stay regular on resize. +2. **`ChunkSpec` complexity:** `ChunkSpec` carries both `slices` and `codec_shape`. Should the grid expose separate methods for codec vs data queries instead? +3. **`__getitem__` with slices:** Should `grid[0, :]` or `grid[0:3, :]` return a sub-grid or an iterator of `ChunkSpec`s? +4. **Uniform nested lists:** Should `chunks=[[10, 10], [20, 20]]` serialize as `"rectilinear"` (preserving user intent for future append) or `"regular"` (current behavior, collapses uniform edges)? See [User control over grid serialization format](#user-control-over-grid-serialization-format). +5. **`zarr.open` with rectilinear:** @tomwhite noted in #3534 that `zarr.open(mode="w")` doesn't support rectilinear chunks directly. This could be addressed in a follow-up. + +## Proofs of concepts + +- Zarr-Python: + - branch - https://github.com/maxrjones/zarr-python/tree/poc/unified-chunk-grid + - diff - https://github.com/zarr-developers/zarr-python/compare/main...maxrjones:zarr-python:poc/unified-chunk-grid?expand=1 +- Xarray: + - branch - https://github.com/maxrjones/xarray/tree/poc/unified-zarr-chunk-grid + - diff - https://github.com/pydata/xarray/compare/main...maxrjones:xarray:poc/unified-zarr-chunk-grid?expand=1 +- VirtualiZarr: + - branch - https://github.com/maxrjones/VirtualiZarr/tree/poc/unified-chunk-grid + - diff - https://github.com/zarr-developers/VirtualiZarr/compare/main...maxrjones:VirtualiZarr:poc/unified-chunk-grid?expand=1 +- Virtual TIFF: + - branch - https://github.com/virtual-zarr/virtual-tiff/tree/poc/unified-chunk-grid + - diff - https://github.com/virtual-zarr/virtual-tiff/compare/main...poc/unified-chunk-grid?expand=1 +- Cubed: + - branch - https://github.com/maxrjones/cubed/tree/poc/unified-chunk-grid +- Microbenchmarks: + - https://github.com/maxrjones/zarr-chunk-grid-tests/tree/unified-chunk-grid diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index e6adc1ca8c..0000000000 --- a/docs/Makefile +++ /dev/null @@ -1,230 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -W --keep-going -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = _build - -# User-friendly check for sphinx-build -ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) - $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don\'t have Sphinx installed, grab it from https://www.sphinx-doc.org/) -endif - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . -# the i18n builder cannot share the environment and doctrees with the others -I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . - -.PHONY: help -help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " singlehtml to make a single large HTML file" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " applehelp to make an Apple Help Book" - @echo " devhelp to make HTML files and a Devhelp project" - @echo " epub to make an epub" - @echo " epub3 to make an epub3" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run them through pdflatex" - @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" - @echo " text to make text files" - @echo " man to make manual pages" - @echo " texinfo to make Texinfo files" - @echo " info to make Texinfo files and run them through makeinfo" - @echo " gettext to make PO message catalogs" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " xml to make Docutils-native XML files" - @echo " pseudoxml to make pseudoxml-XML files for display purposes" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - @echo " coverage to run coverage check of the documentation (if enabled)" - @echo " dummy to check syntax errors of document sources" - -.PHONY: clean -clean: - rm -rf $(BUILDDIR)/* - -.PHONY: html -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -.PHONY: dirhtml -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -.PHONY: singlehtml -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml - @echo - @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." - -.PHONY: pickle -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -.PHONY: json -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -.PHONY: htmlhelp -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -.PHONY: qthelp -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/zarr.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/zarr.qhc" - -.PHONY: applehelp -applehelp: - $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp - @echo - @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." - @echo "N.B. You won't be able to view it unless you put it in" \ - "~/Library/Documentation/Help or install it in your application" \ - "bundle." - -.PHONY: devhelp -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/zarr" - @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/zarr" - @echo "# devhelp" - -.PHONY: epub -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub - @echo - @echo "Build finished. The epub file is in $(BUILDDIR)/epub." - -.PHONY: epub3 -epub3: - $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 - @echo - @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." - -.PHONY: latex -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make' in that directory to run these through (pdf)latex" \ - "(use \`make latexpdf' here to do that automatically)." - -.PHONY: latexpdf -latexpdf: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through pdflatex..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -.PHONY: latexpdfja -latexpdfja: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through platex and dvipdfmx..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -.PHONY: text -text: - $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text - @echo - @echo "Build finished. The text files are in $(BUILDDIR)/text." - -.PHONY: man -man: - $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man - @echo - @echo "Build finished. The manual pages are in $(BUILDDIR)/man." - -.PHONY: texinfo -texinfo: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo - @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." - @echo "Run \`make' in that directory to run these through makeinfo" \ - "(use \`make info' here to do that automatically)." - -.PHONY: info -info: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo "Running Texinfo files through makeinfo..." - make -C $(BUILDDIR)/texinfo info - @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." - -.PHONY: gettext -gettext: - $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale - @echo - @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." - -.PHONY: changes -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." - -.PHONY: linkcheck -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." - -.PHONY: doctest -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." - -.PHONY: coverage -coverage: - $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage - @echo "Testing of coverage in the sources finished, look at the " \ - "results in $(BUILDDIR)/coverage/python.txt." - -.PHONY: xml -xml: - $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml - @echo - @echo "Build finished. The XML files are in $(BUILDDIR)/xml." - -.PHONY: pseudoxml -pseudoxml: - $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml - @echo - @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." - -.PHONY: dummy -dummy: - $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy - @echo - @echo "Build finished. Dummy builder generates no files." diff --git a/docs/_static/custom.css b/docs/_static/custom.css deleted file mode 100644 index 87dd70e347..0000000000 --- a/docs/_static/custom.css +++ /dev/null @@ -1,123 +0,0 @@ -@import url('https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,400;0,700;0,900;1,400;1,700;1,900&family=Open+Sans:ital,wght@0,400;0,600;1,400;1,600&display=swap'); - -.navbar-brand img { - height: 75px; -} -.navbar-brand { - height: 75px; -} - -body { - font-family: 'Open Sans', sans-serif; -} - -pre, code { - font-size: 100%; - line-height: 155%; -} - -/* Style the active version button. - -- dev: orange -- stable: green -- old, PR: red - -Colors from: - -Wong, B. Points of view: Color blindness. -Nat Methods 8, 441 (2011). https://doi.org/10.1038/nmeth.1618 -*/ - -/* If the active version has the name "dev", style it orange */ -#version_switcher_button[data-active-version-name*="dev"] { - background-color: #E69F00; - border-color: #E69F00; - color:#000000; -} - -/* green for `stable` */ -#version_switcher_button[data-active-version-name*="stable"] { - background-color: #009E73; - border-color: #009E73; -} - -/* red for `old` */ -#version_switcher_button:not([data-active-version-name*="stable"], [data-active-version-name*="dev"], [data-active-version-name=""]) { - background-color: #980F0F; - border-color: #980F0F; -} - -/* Main page overview cards */ - -.sd-card { - background: #fff; - border-radius: 0; - padding: 30px 10px 20px 10px; - margin: 10px 0px; -} - -.sd-card .sd-card-header { - text-align: center; -} - -.sd-card .sd-card-header .sd-card-text { - margin: 0px; -} - -.sd-card .sd-card-img-top { - height: 52px; - width: 52px; - margin-left: auto; - margin-right: auto; -} - -.sd-card .sd-card-header { - border: none; - background-color: white; - color: #150458 !important; - font-size: var(--pst-font-size-h5); - font-weight: bold; - padding: 2.5rem 0rem 0.5rem 0rem; -} - -.sd-card .sd-card-footer { - border: none; - background-color: white; -} - -.sd-card .sd-card-footer .sd-card-text { - max-width: 220px; - margin-left: auto; - margin-right: auto; -} - -/* Dark theme tweaking */ -html[data-theme=dark] .sd-card img[src*='.svg'] { - filter: invert(0.82) brightness(0.8) contrast(1.2); -} - -/* Main index page overview cards */ -html[data-theme=dark] .sd-card { - background-color:var(--pst-color-background); -} - -html[data-theme=dark] .sd-shadow-sm { - box-shadow: 0 .1rem 1rem rgba(250, 250, 250, .6) !important -} - -html[data-theme=dark] .sd-card .sd-card-header { - background-color:var(--pst-color-background); - color: #150458 !important; -} - -html[data-theme=dark] .sd-card .sd-card-footer { - background-color:var(--pst-color-background); -} - -html[data-theme=dark] h1 { - color: var(--pst-color-primary); -} - -html[data-theme=dark] h3 { - color: #0a6774; -} diff --git a/docs/_static/custom.js b/docs/_static/custom.js deleted file mode 100644 index dcb584ecd5..0000000000 --- a/docs/_static/custom.js +++ /dev/null @@ -1,18 +0,0 @@ -// handle redirects -(() => { - let anchorMap = { - "installation": "installation.html", - "getting-started": "getting_started.html#getting-started", - "highlights": "getting_started.html#highlights", - "contributing": "contributing.html", - "projects-using-zarr": "getting_started.html#projects-using-zarr", - "acknowledgments": "acknowledgments.html", - "contents": "getting_started.html#contents", - "indices-and-tables": "api.html#indices-and-tables" - } - - let hash = window.location.hash.substring(1); - if (hash && hash in anchorMap) { - window.location.replace(anchorMap[hash]); - } -})(); diff --git a/docs/_static/favicon-96x96.png b/docs/_static/favicon-96x96.png new file mode 100644 index 0000000000..e77977ccf4 Binary files /dev/null and b/docs/_static/favicon-96x96.png differ diff --git a/docs/_static/index_api.svg b/docs/_static/index_api.svg deleted file mode 100644 index 69f7ba1d2d..0000000000 --- a/docs/_static/index_api.svg +++ /dev/null @@ -1,97 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - diff --git a/docs/_static/index_contribute.svg b/docs/_static/index_contribute.svg deleted file mode 100644 index de3d902379..0000000000 --- a/docs/_static/index_contribute.svg +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/docs/_static/index_getting_started.svg b/docs/_static/index_getting_started.svg deleted file mode 100644 index 2d36622cb7..0000000000 --- a/docs/_static/index_getting_started.svg +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - - - - diff --git a/docs/_static/index_user_guide.svg b/docs/_static/index_user_guide.svg deleted file mode 100644 index bd17053517..0000000000 --- a/docs/_static/index_user_guide.svg +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - - - - diff --git a/docs/_static/logo_bw.png b/docs/_static/logo_bw.png new file mode 100644 index 0000000000..df1979d3cc Binary files /dev/null and b/docs/_static/logo_bw.png differ diff --git a/docs/_static/logo_horizontal.svg b/docs/_static/logo_horizontal.svg new file mode 100644 index 0000000000..90fa4bc3a8 --- /dev/null +++ b/docs/_static/logo_horizontal.svg @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/acknowledgments.rst b/docs/acknowledgments.rst deleted file mode 100644 index 4fce1e8ae4..0000000000 --- a/docs/acknowledgments.rst +++ /dev/null @@ -1,76 +0,0 @@ -Acknowledgments -=============== - -The following people have contributed to the development of Zarr by contributing code, -documentation, code reviews, comments and/or ideas: - -* :user:`Alistair Miles ` -* :user:`Altay Sansal ` -* :user:`Anderson Banihirwe ` -* :user:`Andrew Fulton ` -* :user:`Andrew Thomas ` -* :user:`Anthony Scopatz ` -* :user:`Attila Bergou ` -* :user:`BGCMHou ` -* :user:`Ben Jeffery ` -* :user:`Ben Williams ` -* :user:`Boaz Mohar ` -* :user:`Charles Noyes ` -* :user:`Chris Barnes ` -* :user:`David Baddeley ` -* :user:`Davis Bennett ` -* :user:`Dimitri Papadopoulos Orfanos ` -* :user:`Eduardo Gonzalez ` -* :user:`Elliott Sales de Andrade ` -* :user:`Eric Prestat ` -* :user:`Eric Younkin ` -* :user:`Francesc Alted ` -* :user:`Greggory Lee ` -* :user:`Gregory R. Lee ` -* :user:`Ian Hunt-Isaak ` -* :user:`James Bourbeau ` -* :user:`Jan Funke ` -* :user:`Jerome Kelleher ` -* :user:`Joe Hamman ` -* :user:`Joe Jevnik ` -* :user:`John Kirkham ` -* :user:`Josh Moore ` -* :user:`Juan Nunez-Iglesias ` -* :user:`Justin Swaney ` -* :user:`Mads R. B. Kristensen ` -* :user:`Mamy Ratsimbazafy ` -* :user:`Martin Durant ` -* :user:`Matthew Rocklin ` -* :user:`Matthias Bussonnier ` -* :user:`Mattia Almansi ` -* :user:`Noah D Brenowitz ` -* :user:`Oren Watson ` -* :user:`Pavithra Eswaramoorthy ` -* :user:`Poruri Sai Rahul ` -* :user:`Prakhar Goel ` -* :user:`Raphael Dussin ` -* :user:`Ray Bell ` -* :user:`Richard Scott ` -* :user:`Richard Shaw ` -* :user:`Ryan Abernathey ` -* :user:`Ryan Williams ` -* :user:`Saransh Chopra ` -* :user:`Sebastian Grill ` -* :user:`Shikhar Goenka ` -* :user:`Shivank Chaudhary ` -* :user:`Stephan Hoyer ` -* :user:`Stephan Saalfeld ` -* :user:`Tarik Onalan ` -* :user:`Tim Crone ` -* :user:`Tobias KΓΆlling ` -* :user:`Tom Augspurger ` -* :user:`Tom White ` -* :user:`Tommy Tran ` -* :user:`Trevor Manz ` -* :user:`Vincent Schut ` -* :user:`Vyas Ramasubramani ` -* :user:`Zain Patel ` -* :user:`gsakkis` -* :user:`hailiangzhang ` -* :user:`pmav99 ` -* :user:`sbalmer ` diff --git a/docs/api/index.rst b/docs/api/index.rst deleted file mode 100644 index 58ea531905..0000000000 --- a/docs/api/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -============= - -.. toctree:: - :maxdepth: 1 - - zarr diff --git a/docs/api/zarr.rst b/docs/api/zarr.rst deleted file mode 100644 index 8a9216f19e..0000000000 --- a/docs/api/zarr.rst +++ /dev/null @@ -1,5 +0,0 @@ -zarr -==== - -.. autoapimodule:: zarr - :members: diff --git a/docs/api/zarr/abc/buffer.md b/docs/api/zarr/abc/buffer.md new file mode 100644 index 0000000000..d1ace2c899 --- /dev/null +++ b/docs/api/zarr/abc/buffer.md @@ -0,0 +1,12 @@ +--- +title: buffer +--- + +::: zarr.abc + options: + show_root_heading: true + show_root_toc_entry: true + members: false + + +::: zarr.abc.buffer diff --git a/docs/api/zarr/abc/codec.md b/docs/api/zarr/abc/codec.md new file mode 100644 index 0000000000..d4eaecabe9 --- /dev/null +++ b/docs/api/zarr/abc/codec.md @@ -0,0 +1,5 @@ +--- +title: codec +--- + +::: zarr.abc.codec diff --git a/docs/api/zarr/abc/index.md b/docs/api/zarr/abc/index.md new file mode 100644 index 0000000000..7e15cb2a51 --- /dev/null +++ b/docs/api/zarr/abc/index.md @@ -0,0 +1,13 @@ +--- +title: zarr.abc +--- + +# zarr.abc + +Abstract base classes for extending Zarr-Python. + +- **[zarr.abc.buffer](./buffer.md)** - Providing access to underlying memory via [buffers](https://docs.python.org/3/c-api/buffer.html) +- **[zarr.abc.codec](./codec.md)** - Expressing [zarr codecs](https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#chunk-encoding) +- **[zarr.abc.metadata](./metadata.md)** - Creating metadata classes compatible with the Zarr API +- **[zarr.abc.numcodec](./numcodec.md)** - Protocols and classes for modeling codec interface used by numcodecs +- **[zarr.abc.store](./store.md)** - ABC for implementing Zarr stores and managing getting and setting bytes in a store diff --git a/docs/api/zarr/abc/metadata.md b/docs/api/zarr/abc/metadata.md new file mode 100644 index 0000000000..7cc1e00662 --- /dev/null +++ b/docs/api/zarr/abc/metadata.md @@ -0,0 +1,5 @@ +--- +title: metadata +--- + +::: zarr.abc.metadata diff --git a/docs/api/zarr/abc/numcodec.md b/docs/api/zarr/abc/numcodec.md new file mode 100644 index 0000000000..ffbca600cc --- /dev/null +++ b/docs/api/zarr/abc/numcodec.md @@ -0,0 +1,5 @@ +--- +title: numcodec +--- + +::: zarr.abc.numcodec diff --git a/docs/api/zarr/abc/store.md b/docs/api/zarr/abc/store.md new file mode 100644 index 0000000000..f711448541 --- /dev/null +++ b/docs/api/zarr/abc/store.md @@ -0,0 +1,5 @@ +--- +title: store +--- + +::: zarr.abc.store diff --git a/docs/api/zarr/api/asynchronous.md b/docs/api/zarr/api/asynchronous.md new file mode 100644 index 0000000000..f5df894134 --- /dev/null +++ b/docs/api/zarr/api/asynchronous.md @@ -0,0 +1,5 @@ +--- +title: asynchronous +--- + +::: zarr.api.asynchronous \ No newline at end of file diff --git a/docs/api/zarr/api/index.md b/docs/api/zarr/api/index.md new file mode 100644 index 0000000000..7fac5e766a --- /dev/null +++ b/docs/api/zarr/api/index.md @@ -0,0 +1,7 @@ +--- +title: zarr.api +--- + +# zarr.api + +Zarr provides both an [async](./asynchronous.md) and a [sync](./synchronous.md) API. See those pages for more details. diff --git a/docs/api/zarr/api/synchronous.md b/docs/api/zarr/api/synchronous.md new file mode 100644 index 0000000000..63a4aec537 --- /dev/null +++ b/docs/api/zarr/api/synchronous.md @@ -0,0 +1,11 @@ +--- +title: synchronous +--- + +::: zarr.api + options: + show_root_heading: true + show_root_toc_entry: true + members: false + +::: zarr.api.synchronous \ No newline at end of file diff --git a/docs/api/zarr/array.md b/docs/api/zarr/array.md new file mode 100644 index 0000000000..ff61cb1fe2 --- /dev/null +++ b/docs/api/zarr/array.md @@ -0,0 +1,2 @@ +::: zarr.Array +::: zarr.AsyncArray diff --git a/docs/api/zarr/buffer/cpu.md b/docs/api/zarr/buffer/cpu.md new file mode 100644 index 0000000000..9d4726d3ea --- /dev/null +++ b/docs/api/zarr/buffer/cpu.md @@ -0,0 +1 @@ +::: zarr.buffer.cpu diff --git a/docs/api/zarr/buffer/gpu.md b/docs/api/zarr/buffer/gpu.md new file mode 100644 index 0000000000..e2276d8d82 --- /dev/null +++ b/docs/api/zarr/buffer/gpu.md @@ -0,0 +1 @@ +::: zarr.buffer.gpu diff --git a/docs/api/zarr/buffer/index.md b/docs/api/zarr/buffer/index.md new file mode 100644 index 0000000000..ebbb9e1c99 --- /dev/null +++ b/docs/api/zarr/buffer/index.md @@ -0,0 +1,7 @@ +--- +title: zarr.buffer +--- + +Zarr provides buffer classes for both the [cpu](./cpu.md) and [gpu](./gpu.md). Generic buffer functionality is also detailed below. + +::: zarr.buffer diff --git a/docs/api/zarr/codecs.md b/docs/api/zarr/codecs.md new file mode 100644 index 0000000000..c5a0f046ed --- /dev/null +++ b/docs/api/zarr/codecs.md @@ -0,0 +1,5 @@ +--- +title: codecs +--- + +::: zarr.codecs diff --git a/docs/api/zarr/codecs/numcodecs.md b/docs/api/zarr/codecs/numcodecs.md new file mode 100644 index 0000000000..ce2a7de145 --- /dev/null +++ b/docs/api/zarr/codecs/numcodecs.md @@ -0,0 +1,5 @@ +--- +title: numcodecs +--- + +::: zarr.codecs.numcodecs diff --git a/docs/api/zarr/config.md b/docs/api/zarr/config.md new file mode 100644 index 0000000000..30803918f5 --- /dev/null +++ b/docs/api/zarr/config.md @@ -0,0 +1,5 @@ +--- +title: config +--- + +::: zarr.config diff --git a/docs/api/zarr/dtype.md b/docs/api/zarr/dtype.md new file mode 100644 index 0000000000..c08910b97f --- /dev/null +++ b/docs/api/zarr/dtype.md @@ -0,0 +1,5 @@ +--- +title: dtype +--- + +::: zarr.dtype diff --git a/docs/api/zarr/errors.md b/docs/api/zarr/errors.md new file mode 100644 index 0000000000..2ba2213071 --- /dev/null +++ b/docs/api/zarr/errors.md @@ -0,0 +1,5 @@ +--- +title: errors +--- + +::: zarr.errors \ No newline at end of file diff --git a/docs/api/zarr/experimental.md b/docs/api/zarr/experimental.md new file mode 100644 index 0000000000..60f1f987b5 --- /dev/null +++ b/docs/api/zarr/experimental.md @@ -0,0 +1,9 @@ +--- +title: experimental +--- + +Experimental functionality is not stable and may change or be removed at any point. + +## Classes + +::: zarr.experimental.cache_store diff --git a/docs/api/zarr/functions/array.md b/docs/api/zarr/functions/array.md new file mode 100644 index 0000000000..ff7242005c --- /dev/null +++ b/docs/api/zarr/functions/array.md @@ -0,0 +1,5 @@ +--- +title: zarr.array +--- + +::: zarr.array diff --git a/docs/api/zarr/functions/consolidate_metadata.md b/docs/api/zarr/functions/consolidate_metadata.md new file mode 100644 index 0000000000..946531f028 --- /dev/null +++ b/docs/api/zarr/functions/consolidate_metadata.md @@ -0,0 +1,5 @@ +--- +title: zarr.consolidate_metadata +--- + +::: zarr.consolidate_metadata diff --git a/docs/api/zarr/functions/create.md b/docs/api/zarr/functions/create.md new file mode 100644 index 0000000000..b43094eaba --- /dev/null +++ b/docs/api/zarr/functions/create.md @@ -0,0 +1,5 @@ +--- +title: zarr.create +--- + +::: zarr.create diff --git a/docs/api/zarr/functions/create_array.md b/docs/api/zarr/functions/create_array.md new file mode 100644 index 0000000000..a9f4a24bd0 --- /dev/null +++ b/docs/api/zarr/functions/create_array.md @@ -0,0 +1,5 @@ +--- +title: zarr.create_array +--- + +::: zarr.create_array diff --git a/docs/api/zarr/functions/create_group.md b/docs/api/zarr/functions/create_group.md new file mode 100644 index 0000000000..50beb0674c --- /dev/null +++ b/docs/api/zarr/functions/create_group.md @@ -0,0 +1,5 @@ +--- +title: zarr.create_group +--- + +::: zarr.create_group diff --git a/docs/api/zarr/functions/create_hierarchy.md b/docs/api/zarr/functions/create_hierarchy.md new file mode 100644 index 0000000000..38938ffee2 --- /dev/null +++ b/docs/api/zarr/functions/create_hierarchy.md @@ -0,0 +1,5 @@ +--- +title: zarr.create_hierarchy +--- + +::: zarr.create_hierarchy diff --git a/docs/api/zarr/functions/empty.md b/docs/api/zarr/functions/empty.md new file mode 100644 index 0000000000..aff67bb9ed --- /dev/null +++ b/docs/api/zarr/functions/empty.md @@ -0,0 +1,5 @@ +--- +title: zarr.empty +--- + +::: zarr.empty diff --git a/docs/api/zarr/functions/empty_like.md b/docs/api/zarr/functions/empty_like.md new file mode 100644 index 0000000000..9e2fbd26a5 --- /dev/null +++ b/docs/api/zarr/functions/empty_like.md @@ -0,0 +1,5 @@ +--- +title: zarr.empty_like +--- + +::: zarr.empty_like diff --git a/docs/api/zarr/functions/from_array.md b/docs/api/zarr/functions/from_array.md new file mode 100644 index 0000000000..7ab8179b05 --- /dev/null +++ b/docs/api/zarr/functions/from_array.md @@ -0,0 +1,5 @@ +--- +title: zarr.from_array +--- + +::: zarr.from_array diff --git a/docs/api/zarr/functions/full.md b/docs/api/zarr/functions/full.md new file mode 100644 index 0000000000..d6c60de2d5 --- /dev/null +++ b/docs/api/zarr/functions/full.md @@ -0,0 +1,5 @@ +--- +title: zarr.full +--- + +::: zarr.full diff --git a/docs/api/zarr/functions/full_like.md b/docs/api/zarr/functions/full_like.md new file mode 100644 index 0000000000..eb5c162f76 --- /dev/null +++ b/docs/api/zarr/functions/full_like.md @@ -0,0 +1,5 @@ +--- +title: zarr.full_like +--- + +::: zarr.full_like diff --git a/docs/api/zarr/functions/group.md b/docs/api/zarr/functions/group.md new file mode 100644 index 0000000000..3048218f6b --- /dev/null +++ b/docs/api/zarr/functions/group.md @@ -0,0 +1,5 @@ +--- +title: zarr.group +--- + +::: zarr.group diff --git a/docs/api/zarr/functions/load.md b/docs/api/zarr/functions/load.md new file mode 100644 index 0000000000..aa004076ab --- /dev/null +++ b/docs/api/zarr/functions/load.md @@ -0,0 +1,5 @@ +--- +title: zarr.load +--- + +::: zarr.load diff --git a/docs/api/zarr/functions/ones.md b/docs/api/zarr/functions/ones.md new file mode 100644 index 0000000000..b7757da1bc --- /dev/null +++ b/docs/api/zarr/functions/ones.md @@ -0,0 +1,5 @@ +--- +title: zarr.ones +--- + +::: zarr.ones diff --git a/docs/api/zarr/functions/ones_like.md b/docs/api/zarr/functions/ones_like.md new file mode 100644 index 0000000000..cffccb10ef --- /dev/null +++ b/docs/api/zarr/functions/ones_like.md @@ -0,0 +1,5 @@ +--- +title: zarr.ones_like +--- + +::: zarr.ones_like diff --git a/docs/api/zarr/functions/open.md b/docs/api/zarr/functions/open.md new file mode 100644 index 0000000000..3d75977395 --- /dev/null +++ b/docs/api/zarr/functions/open.md @@ -0,0 +1,5 @@ +--- +title: zarr.open +--- + +::: zarr.open diff --git a/docs/api/zarr/functions/open_array.md b/docs/api/zarr/functions/open_array.md new file mode 100644 index 0000000000..f40da1bd5d --- /dev/null +++ b/docs/api/zarr/functions/open_array.md @@ -0,0 +1,5 @@ +--- +title: zarr.open_array +--- + +::: zarr.open_array diff --git a/docs/api/zarr/functions/open_consolidated.md b/docs/api/zarr/functions/open_consolidated.md new file mode 100644 index 0000000000..de71cf7662 --- /dev/null +++ b/docs/api/zarr/functions/open_consolidated.md @@ -0,0 +1,5 @@ +--- +title: zarr.open_consolidated +--- + +::: zarr.open_consolidated diff --git a/docs/api/zarr/functions/open_group.md b/docs/api/zarr/functions/open_group.md new file mode 100644 index 0000000000..4944e94e06 --- /dev/null +++ b/docs/api/zarr/functions/open_group.md @@ -0,0 +1,5 @@ +--- +title: zarr.open_group +--- + +::: zarr.open_group diff --git a/docs/api/zarr/functions/open_like.md b/docs/api/zarr/functions/open_like.md new file mode 100644 index 0000000000..1aea075a81 --- /dev/null +++ b/docs/api/zarr/functions/open_like.md @@ -0,0 +1,5 @@ +--- +title: zarr.open_like +--- + +::: zarr.open_like diff --git a/docs/api/zarr/functions/print_debug_info.md b/docs/api/zarr/functions/print_debug_info.md new file mode 100644 index 0000000000..c98329f893 --- /dev/null +++ b/docs/api/zarr/functions/print_debug_info.md @@ -0,0 +1,5 @@ +--- +title: zarr.print_debug_info +--- + +::: zarr.print_debug_info diff --git a/docs/api/zarr/functions/save.md b/docs/api/zarr/functions/save.md new file mode 100644 index 0000000000..6c8eae410f --- /dev/null +++ b/docs/api/zarr/functions/save.md @@ -0,0 +1,5 @@ +--- +title: zarr.save +--- + +::: zarr.save diff --git a/docs/api/zarr/functions/save_array.md b/docs/api/zarr/functions/save_array.md new file mode 100644 index 0000000000..58a6d5143d --- /dev/null +++ b/docs/api/zarr/functions/save_array.md @@ -0,0 +1,5 @@ +--- +title: zarr.save_array +--- + +::: zarr.save_array diff --git a/docs/api/zarr/functions/save_group.md b/docs/api/zarr/functions/save_group.md new file mode 100644 index 0000000000..ba66a70563 --- /dev/null +++ b/docs/api/zarr/functions/save_group.md @@ -0,0 +1,5 @@ +--- +title: zarr.save_group +--- + +::: zarr.save_group diff --git a/docs/api/zarr/functions/zeros.md b/docs/api/zarr/functions/zeros.md new file mode 100644 index 0000000000..d43e8d913b --- /dev/null +++ b/docs/api/zarr/functions/zeros.md @@ -0,0 +1,5 @@ +--- +title: zarr.zeros +--- + +::: zarr.zeros diff --git a/docs/api/zarr/functions/zeros_like.md b/docs/api/zarr/functions/zeros_like.md new file mode 100644 index 0000000000..5adf1a23b3 --- /dev/null +++ b/docs/api/zarr/functions/zeros_like.md @@ -0,0 +1,5 @@ +--- +title: zarr.zeros_like +--- + +::: zarr.zeros_like diff --git a/docs/api/zarr/group.md b/docs/api/zarr/group.md new file mode 100644 index 0000000000..0cf9372de2 --- /dev/null +++ b/docs/api/zarr/group.md @@ -0,0 +1,2 @@ +::: zarr.Group +::: zarr.AsyncGroup diff --git a/docs/api/zarr/index.md b/docs/api/zarr/index.md new file mode 100644 index 0000000000..f691c4599a --- /dev/null +++ b/docs/api/zarr/index.md @@ -0,0 +1,62 @@ +# API Reference + +Complete reference documentation for the Zarr-Python API. + +::: zarr + options: + show_root_heading: true + show_root_toc_entry: true + members: false + +## Core API + +### Essential Classes and Functions + +- **[Array](array.md)** - The main Zarr array class for N-dimensional data +- **[Group](group.md)** - Hierarchical organization of arrays and subgroups +- **[create_array](functions/create_array.md)** and **[create_group](functions/create_group.md)** - Creating new arrays and groups +- **[open](functions/open.md)**, **[open_array](functions/open_array.md)**, and **[open_group](functions/open_group.md)** - Opening existing Zarr stores, arrays, and groups + +### Data Operations + +- **[load](functions/load.md)** - Loading data from Zarr stores +- **[save](functions/save.md)** - Saving data to Zarr format + +### Data Types and Configuration + +- **[Data Types](dtype.md)** - Supported NumPy data types and type handling +- **[Configuration](config.md)** - Runtime configuration and settings + +## Storage and Compression + +- **[Codecs](codecs.md)** - Compression and filtering codecs +- **[Storage](storage.md)** - Storage backend implementations and interfaces +- **[Registry](registry.md)** - Codec and storage backend registry + +## API Variants + +Zarr-Python provides both synchronous and asynchronous APIs: + +- **[Async API](./api/asynchronous.md)** - Asynchronous operations for concurrent access +- **[Sync API](./api/synchronous.md)** - Synchronous operations for simple usage + +## Abstract Base Classes + +The ABC module defines interfaces for extending Zarr: + +- **[Codec ABC](abc/codec.md)** - Interface for custom compression codecs +- **[Metadata ABC](abc/metadata.md)** - Interface for metadata handling +- **[Store ABC](abc/store.md)** - Interface for custom storage backends + +## Utilities + +- **[Errors](errors.md)** - Exception classes and error handling +- **[Testing](testing/index.md)** - Utilities for testing Zarr-based code + + +## Getting Help + +- Check the [User Guide](../../user-guide/index.md) for tutorials and examples +- Browse function signatures and docstrings in the API reference +- Report issues on [GitHub](https://github.com/zarr-developers/zarr-python) +- Join discussions on the [Zarr community forum](https://github.com/zarr-developers/community) diff --git a/docs/api/zarr/metadata.md b/docs/api/zarr/metadata.md new file mode 100644 index 0000000000..12eb909086 --- /dev/null +++ b/docs/api/zarr/metadata.md @@ -0,0 +1,6 @@ +--- +title: metadata +--- + +::: zarr.metadata +::: zarr.metadata.migrate_v3 diff --git a/docs/api/zarr/registry.md b/docs/api/zarr/registry.md new file mode 100644 index 0000000000..d2c3769596 --- /dev/null +++ b/docs/api/zarr/registry.md @@ -0,0 +1,5 @@ +--- +title: registry +--- + +::: zarr.registry \ No newline at end of file diff --git a/docs/api/zarr/storage.md b/docs/api/zarr/storage.md new file mode 100644 index 0000000000..33580d1d8a --- /dev/null +++ b/docs/api/zarr/storage.md @@ -0,0 +1,11 @@ +--- +title: storage +--- + +## Attributes + +::: zarr.storage.StoreLike + +## Classes + +::: zarr.storage diff --git a/docs/api/zarr/testing/buffer.md b/docs/api/zarr/testing/buffer.md new file mode 100644 index 0000000000..e0ae5e5dfd --- /dev/null +++ b/docs/api/zarr/testing/buffer.md @@ -0,0 +1,3 @@ +## Buffer + +::: zarr.testing.buffer diff --git a/docs/api/zarr/testing/index.md b/docs/api/zarr/testing/index.md new file mode 100644 index 0000000000..2b48ad349f --- /dev/null +++ b/docs/api/zarr/testing/index.md @@ -0,0 +1,13 @@ +--- +title: zarr.testing +--- + +# zarr.testing + +See the following sub-modules: + +- [zarr.testing.buffer](./buffer.md) +- [zarr.testing.stateful](./stateful.md) +- [zarr.testing.store](./store.md) +- [zarr.testing.strategies](./strategies.md) +- [zarr.testing.utils](./utils.md) diff --git a/docs/api/zarr/testing/stateful.md b/docs/api/zarr/testing/stateful.md new file mode 100644 index 0000000000..53c51b11ec --- /dev/null +++ b/docs/api/zarr/testing/stateful.md @@ -0,0 +1,3 @@ +## Stateful + +::: zarr.testing.stateful diff --git a/docs/api/zarr/testing/store.md b/docs/api/zarr/testing/store.md new file mode 100644 index 0000000000..f190c65f95 --- /dev/null +++ b/docs/api/zarr/testing/store.md @@ -0,0 +1,4 @@ + +## Store + +::: zarr.testing.store diff --git a/docs/api/zarr/testing/strategies.md b/docs/api/zarr/testing/strategies.md new file mode 100644 index 0000000000..dd6d546165 --- /dev/null +++ b/docs/api/zarr/testing/strategies.md @@ -0,0 +1,4 @@ + +## Strategies + +::: zarr.testing.strategies diff --git a/docs/api/zarr/testing/utils.md b/docs/api/zarr/testing/utils.md new file mode 100644 index 0000000000..61202ac4b2 --- /dev/null +++ b/docs/api/zarr/testing/utils.md @@ -0,0 +1,3 @@ +## Utils + +::: zarr.testing.utils diff --git a/docs/blog/.authors.yml b/docs/blog/.authors.yml new file mode 100644 index 0000000000..10ce423cfc --- /dev/null +++ b/docs/blog/.authors.yml @@ -0,0 +1,6 @@ +authors: + d-v-b: + name: Davis Bennett + description: Core developer + avatar: https://github.com/d-v-b.png + url: https://github.com/d-v-b diff --git a/docs/blog/index.md b/docs/blog/index.md new file mode 100644 index 0000000000..fca29e2578 --- /dev/null +++ b/docs/blog/index.md @@ -0,0 +1,3 @@ +# Blog + +News, release highlights, and design notes from the Zarr-Python developers. diff --git a/docs/blog/posts/3.3.0-release.md b/docs/blog/posts/3.3.0-release.md new file mode 100644 index 0000000000..13368848ae --- /dev/null +++ b/docs/blog/posts/3.3.0-release.md @@ -0,0 +1,169 @@ +--- +date: 2026-07-30 +authors: + - d-v-b +categories: + - Release +--- + +# Zarr-Python 3.3.0 + +We're happy to announce the release of version 3.3.0 of Zarr-Python. It's been a while since our last release ([3.2.1](https://github.com/zarr-developers/zarr-python/releases/tag/v3.2.1) dropped in May of this year), +and we're bringing some exciting additions to the latest version. For the full release notes, see the [3.3.0 release notes](../../release-notes.md), otherwise stick around for an overview of two performance-centric highlights of this release. + + + +## Faster low-latency storage + +Relevant issues and pull requests: + +- [#3524](https://github.com/zarr-developers/zarr-python/issues/3524) -- the performance report that started this work +- [#3885](https://github.com/zarr-developers/zarr-python/pull/3885) -- synchronous codec APIs and the `FusedCodecPipeline` + +### The cost of async overhead + +Zarr-Python 3.x uses async routines for fetching data and decoding chunks. In terms of code, this means our store (data fetching) and codec (chunk decoding) APIs are both async. This makes +I/O against high-latency storage backends like cloud object storage efficient. But for *low-latency* storage, like in-process memory or the file system, async routines add measurable overhead and offer no benefit. Async only adds value when there's work to be done while waiting for I/O to complete, but when I/O latency is low, it completes too quickly to run anything while waiting, and we are left paying the performance bill for obligatory async task scheduling that offered no value. + +This performance problem became acute when Zarr-Python users reported that in-memory array indexing workloads ran *slower* in Zarr-Python 3.1.3 relative to Zarr-Python 2.18.7 ([#3524](https://github.com/zarr-developers/zarr-python/issues/3524)). Fortunately this performance regression had a straightforward fix (I don't say "easy" because it was a lot of work). + +### Synchronous execution restores performance + +If async overhead makes low-latency storage slow, does *removing* that overhead restore performance? Yes, it does! + +In [#3885](https://github.com/zarr-developers/zarr-python/pull/3885) we defined synchronous versions of our storage and codec APIs -- the `SyncByteGetter` and `SyncByteSetter` protocols, plus a `get_ranges_sync` method on the `Store` ABC -- and then combined them in a new codec orchestration class called `FusedCodecPipeline`. The `FusedCodecPipeline` is an opt-in alternative to the default (the `BatchedCodecPipeline`) that gives large speedups for low-latency storage. It is currently marked [experimental](../../user-guide/experimental.md), so we may change it as we learn more; the default pipeline is untouched, and existing code keeps working unless you opt in. + +The win here is *not* a faster compressor. It is the removal of async scheduling overhead (including some [nasty `asyncio.to_thread` overhead](https://github.com/python/cpython/issues/136084)), plus a few vectorized fast paths for dense, uncompressed shards. And we only expect this new pipeline to accelerate workloads targeting a subset of storage backends, namely any store with methods that advertise low latency. + +On this author's 10-core Apple M4 laptop, the `FusedCodecPipeline` delivers the following results against memory-backed arrays: + +- uncompressed writes are *~4 times faster* +- uncompressed reads are *~5 times faster* +- compressed writes are *~2 times faster* +- compressed reads are *~2 times faster* + +These numbers came from a [runnable example](../../user-guide/examples/codec_pipeline_performance.md) that ships with the documentation. Run it yourself to get a sense of how the `FusedCodecPipeline` behaves on your system -- when and how you use it depends on your hardware, your array layout, and how your chunks are compressed. What's certain is that for in-memory arrays, and arrays saved to the local file system, the `FusedCodecPipeline` is worth a try. + +Getting good numbers requires choosing the right level of thread-based parallelism for your workload, which is part of the configuration of the `FusedCodecPipeline`. For uncompressed chunks there's no CPU-bound work to do after fetching a chunk and so +thread-based parallelism is worse than useless and slows things down. But for compressed chunks, threading offers a substantial payoff. + +### How to use it + +Select the pipeline through the [runtime configuration](../../user-guide/config.md) by setting `codec_pipeline.path`. Set it globally to affect every array created or opened afterwards: + +```python exec="true" session="blog-330" source="above" +import zarr + +zarr.config.set( + {"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"} +) +``` + +Or scope it to a block of code by using `zarr.config.set` as a context manager, which is the safer choice if you only want the new pipeline for part of your program: + +```python exec="true" session="blog-330" source="above" result="ansi" +import numpy as np +import zarr +from zarr.storage import MemoryStore + +with zarr.config.set( + {"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"} +): + arr = zarr.create_array( + store=MemoryStore(), + shape=(1000, 1000), + chunks=(100, 100), + shards=(1000, 1000), + dtype="float32", + ) + arr[:] = np.random.random((1000, 1000)).astype("float32") + result = arr[:] + +print(result.shape) +``` + +Thread-based parallelism is configured separately, via `codec_pipeline.max_workers`. It defaults to `None`, meaning a pool sized to `os.cpu_count()`. Note that this setting is read *only* by the `FusedCodecPipeline` -- the default `BatchedCodecPipeline` ignores it, so tuning it without opting in above does nothing. + +As noted, memory-backed and uncompressed workloads often do better with a single worker, which runs everything inline on the calling thread: + +```python exec="true" session="blog-330" source="above" +import zarr + +# No thread pool: run codec compute inline. Often best for uncompressed, +# memory-backed arrays, where there's no CPU-bound work to overlap. +zarr.config.set({"codec_pipeline.max_workers": 1}) + +# A fixed-size thread pool, which pays off once compression is in play. +zarr.config.set({"codec_pipeline.max_workers": 8}) + +# Or back to the default, sized to the number of CPUs. +zarr.config.set({"codec_pipeline.max_workers": None}) +``` + +To return to the default pipeline, set `codec_pipeline.path` back to the batched implementation: + +```python exec="true" session="blog-330" source="above" +import zarr + +zarr.config.set( + {"codec_pipeline.path": "zarr.core.codec_pipeline.BatchedCodecPipeline"} +) +``` + +## Faster sharded reads + +Relevant issues and pull requests: + +- [#3004](https://github.com/zarr-developers/zarr-python/pull/3004) -- optimize partial shard reads +- [#3925](https://github.com/zarr-developers/zarr-python/pull/3925) -- `Store.get_ranges` for concurrent, coalesced multi-range reads +- [#3987](https://github.com/zarr-developers/zarr-python/pull/3987) -- control coalescing through `ArrayConfig` and the runtime config + +### How sharding works + +Chunks encoded with the `sharding_indexed` codec contain a secondary level of chunking, called subchunks. For example, if the `chunk_grid` field of the array metadata declares an "outer chunk" size of, say `(10, 10)`, a `sharding_indexed` codec in the `codecs` field could declare an "inner chunk" size of `(5, 5)`. Readers accessing such a chunk will observe a stored object (a stream of bytes) that decodes to an array with size `(10, 10)` (the "outer chunk"), which is comprised of four separate, contiguous byte ranges that each decode to a `(5, 5)` inner chunk. Each inner chunk occupies its own byte range in the outer chunk. + +A reader can satisfy a request for all four inner chunks by issuing four separate byte-range requests, or by making a *single* request for a byte range that spans all four inner chunks. The latter option is nice because it cuts down on the number of requests we need. Historically Zarr-Python used this optimization when reading entire outer chunks; in 3.3.0, we use this optimization in more cases, resulting in more efficient I/O patterns for sharded reads. + +### Interval equivalence + +Byte ranges, being intervals, obey some combination rules: the values in two half-open intervals `[a, b), [b, c)` can be captured by the single interval `[a, c)`. That means a reader can get multiple inner chunks with *one* byte-range request by requesting a range of bytes starting with the first byte of the first subchunk and ending with the last byte of the last subchunk. When individual requests are expensive, this kind of optimization is worth a lot. + +The requested inner chunks are not necessarily contiguous -- there might be a byte range gap between them. As long as that gap is not too big, its often efficient to fetch the entire byte range, gap included, and pick out the inner chunk byte ranges after I/O is done. + +### Byte range coalescing + +We call this procedure -- merging adjacent byte ranges -- "byte range coalescing", and it's a new performance optimization shipping in Zarr-Python 3.3.0. Unlike the `FusedCodecPipeline`, this one is on by default with base settings we think are good, so most users won't need to tune anything. + +Two knobs control it, both documented in the [runtime configuration guide](../../user-guide/config.md). Nearby byte ranges in the same shard are merged into a single request when the gap between them is no larger than `array.sharding_coalesce_max_gap_bytes` (default 1 MiB) and the merged read stays within `array.sharding_coalesce_max_bytes` (default 16 MiB). The gap threshold is what trades wasted bytes against saved requests: raising it reads more data you didn't ask for, in exchange for fewer requests. + +For a runnable demonstration -- counting the store requests saved and timing them against a store with simulated latency -- see the [sharded read coalescing example](../../user-guide/examples/sharding_coalescing.md). + +You can set them globally, or per array by passing `config={...}` to [`zarr.create_array`][]: + +```python exec="true" session="blog-330" source="above" result="ansi" +import zarr +from zarr.storage import MemoryStore + +arr = zarr.create_array( + store=MemoryStore(), + shape=(1000, 1000), + chunks=(100, 100), + shards=(1000, 1000), + dtype="float32", + config={ + "sharding_coalesce_max_gap_bytes": 4 * 1024**2, # 4 MiB + "sharding_coalesce_max_bytes": 64 * 1024**2, # 64 MiB + }, +) +print(arr.shape) +``` + +## Tell us what you think + +We hope these new features are helpful, and we would appreciate any feedback that helps us improve them, or any other aspect of Zarr-Python. + +## Going faster + +The updates in this release are just the first step of a larger performance-oriented direction for Zarr-Python. Landing these two enhancements taught us a *lot* about the performance-sensitive areas of the library. We can and will invest more time in performance tuning, e.g. by adding or changing abstractions, writing code for special cases, etc. + +We plan to consider including compiled code that should enable significant performance improvements. The [`zarrs`](https://zarrs.dev/) project is an ecosystem of Zarr tools written in Rust, with [extremely high performance](https://book.zarrs.dev/#-zarrs-is-fast-). Is there a `zarrs` binding in Zarr-Python's future? I hope so! We are keenly observing development of [`zarrista`](https://developmentseed.org/zarrista/latest/) as a proof-of-concept for what a Python-`zarrs` binding layer might look like. Stay tuned! diff --git a/docs/conf.py b/docs/conf.py deleted file mode 100644 index 35afa60577..0000000000 --- a/docs/conf.py +++ /dev/null @@ -1,351 +0,0 @@ -#!/usr/bin/env python3 -# -# zarr documentation build configuration file, created by -# sphinx-quickstart on Mon May 2 21:40:09 2016. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - - -import os -import sys -from typing import Any - -import sphinx.application - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -import zarr -import sphinx - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.append(os.path.abspath("..")) - - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -# needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.viewcode", - "sphinx.ext.intersphinx", - 'autoapi.extension', - "numpydoc", - "sphinx_issues", - "sphinx_copybutton", - "sphinx_design", -] - -issues_github_path = "zarr-developers/zarr-python" - -autoapi_dirs = ['../src/zarr'] -autoapi_add_toctree_entry = False -autoapi_generate_api_docs = False -autoapi_member_order = "groupwise" -autoapi_root = "api" - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# source_suffix = ['.rst', '.md'] -source_suffix = ".rst" - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The main toctree document. -main_doc = "index" - -# General information about the project. -project = "zarr" -copyright = "2023, Zarr Developers" -author = "Zarr Developers" - -version = zarr.__version__ -# The full version, including alpha/beta/rc tags. -release = zarr.__version__ - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = "en" - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -# This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", "talks"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = False - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "pydata_sphinx_theme" - -html_favicon = "_static/logo1.png" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "github_url": "https://github.com/zarr-developers/zarr-python", - "twitter_url": "https://twitter.com/zarr_dev", - "icon_links": [ - { - "name": "Zarr Dev", - "url": "https://zarr.dev/", - "icon": "_static/logo1.png", - "type": "local", - }, - ], - "collapse_navigation": True, - "navigation_with_keys": False, -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. -# " v documentation" by default. -# html_title = 'zarr v@@' - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -html_logo = "_static/logo1.png" - - -def setup(app: sphinx.application.Sphinx) -> None: - app.add_css_file("custom.css") - - -# The name of an image file (relative to this directory) to use as a favicon of -# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] -html_js_files = [ - "custom.js", -] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not None, a 'Last updated on:' timestamp is inserted at every page -# bottom, using the given strftime format. -# The empty string is equivalent to '%b %d, %Y'. -# html_last_updated_fmt = None - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# 'ja' uses this config value. -# 'zh' user can custom change `jieba` dictionary path. -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "zarrdoc" - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - #'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - #'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - #'preamble': '', - # Latex figure (float) alignment - #'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - (main_doc, "zarr.tex", "Zarr-Python", author, "manual"), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [(main_doc, "zarr", "Zarr-Python", [author], 1)] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - main_doc, - "zarr", - "Zarr-Python", - author, - "zarr", - "One line description of project.", - "Miscellaneous", - ), -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -# use in refs e.g: -# :ref:`comparison manual ` -intersphinx_mapping = { - "python": ("https://docs.python.org/", None), - "numpy": ("https://numpy.org/doc/stable/", None), - "numcodecs": ("https://numcodecs.readthedocs.io/en/stable/", None), -} - - -# sphinx-copybutton configuration -copybutton_prompt_text = r">>> |\.\.\. |\$ |In \[\d*\]: | {2,5}\.\.\.: | {5,8}: " -copybutton_line_continuation_character = "\\" -copybutton_prompt_is_regexp = True diff --git a/docs/contributing.md b/docs/contributing.md new file mode 100644 index 0000000000..dea7256c36 --- /dev/null +++ b/docs/contributing.md @@ -0,0 +1,422 @@ +# Contributing + +Zarr is a community maintained project. We welcome contributions in the form of bug reports, bug fixes, documentation, enhancement proposals and more. This page provides information on how best to contribute. + +## Asking for help + +If you have a question about how to use Zarr, please post your question on StackOverflow using the ["zarr" tag](https://stackoverflow.com/questions/tagged/zarr). If you don't get a response within a day or two, feel free to raise a [GitHub issue](https://github.com/zarr-developers/zarr-python/issues/new) including a link to your StackOverflow question. We will try to respond to questions as quickly as possible, but please bear in mind that there may be periods where we have limited time to answer questions due to other commitments. + +## Bug reports + +If you find a bug, please raise a [GitHub issue](https://github.com/zarr-developers/zarr-python/issues/new). Please include the following items in a bug report: + +1. A minimal, self-contained snippet of Python code reproducing the problem. You can format the code nicely using markdown, e.g.: + + ```python exec="false" reason="illustrative pseudocode with a '# etc.' placeholder, not runnable" + import zarr + g = zarr.group() + # etc. + ``` + +2. An explanation of why the current behavior is wrong/not desired, and what you expect instead. + +3. Information about the version of Zarr, along with versions of dependencies and the Python interpreter, and installation information. The version of Zarr can be obtained from the `zarr.__version__` attribute. Please also state how Zarr was installed, e.g., "installed via pip into a virtual environment", or "installed using conda". Information about other packages installed can be obtained by executing `pip freeze` (if using pip to install packages) or `conda env export` (if using conda to install packages) from the operating system command prompt. The version of the Python interpreter can be obtained by running a Python interactive session, e.g.: + + ```console + python + ``` + + ```ansi + Python 3.12.7 | packaged by conda-forge | (main, Oct 4 2024, 15:57:01) [Clang 17.0.6 ] on darwin + ``` + +## Enhancement proposals + +If you have an idea about a new feature or some other improvement to Zarr, please raise a [GitHub issue](https://github.com/zarr-developers/zarr-python/issues/new) first to discuss. + +We very much welcome ideas and suggestions for how to improve Zarr, but please bear in mind that we are likely to be conservative in accepting proposals for new features. The reasons for this are that we would like to keep the Zarr code base lean and focused on a core set of functionalities, and available time for development, review and maintenance of new features is limited. But if you have a great idea, please don't let that stop you from posting it on GitHub, just please don't be offended if we respond cautiously. + +## AI-assisted contributions + +AI coding tools are increasingly common in open source development. These tools are welcome in Zarr-Python, but the same standards apply to all contributions regardless of how they were produced β€” whether written by hand, with AI assistance, or generated entirely by an AI tool. + +### You are responsible for your changes + +If you submit a pull request, you are responsible for understanding and having fully reviewed the changes. You must be able to explain why each change is correct and how it fits into the project. + +### Communication must be your own + +PR descriptions, issue comments, and review responses must be in your own words. The substance and reasoning must come from you. Using AI to polish grammar or phrasing is fine, but do not paste AI-generated text as comments or review responses. + +### Review every line + +You must have personally reviewed and understood all changes before submitting. If you used AI to generate code, you are expected to have read it critically and tested it. The PR description should explain the approach and reasoning β€” do not leave it to reviewers to figure out what the code does and why. + +### Keep PRs reviewable + +Generating code with AI is fast; reviewing it is not. A large diff shifts the burden from the contributor to the reviewer. PRs that cannot be reviewed in reasonable time with reasonable effort may be closed, regardless of their potential usefulness or correctness. Use AI tools not only to write code but to prepare better, more reviewable PRs β€” well-structured commits, clear descriptions, and minimal scope. + +If you are planning a large AI-assisted contribution (e.g., a significant refactor or a new subsystem), **open an issue first** to discuss the scope and approach with maintainers. Maintainers may also request that large changes be broken into smaller, reviewable pieces. + +### Documentation + +The same principles apply to documentation. Zarr has domain-specific semantics (chunked storage, codec pipelines, Zarr v2/v3 format details) that AI tools frequently get wrong. Do not submit documentation that you haven't carefully read and verified. + +## Contributing code and/or documentation + +### Forking the repository + +The Zarr source code is hosted on GitHub at the following location: + +* [https://github.com/zarr-developers/zarr-python](https://github.com/zarr-developers/zarr-python) + +You will need your own fork to work on the code. Go to the link above and hit the ["Fork"](https://github.com/zarr-developers/zarr-python/fork) button. Then clone your fork to your local machine: + +```bash +git clone git@github.com:your-user-name/zarr-python.git +cd zarr-python +git remote add upstream git@github.com:zarr-developers/zarr-python.git +``` + +### Creating a development environment + +To work with the Zarr source code, it is recommended to use [hatch](https://hatch.pypa.io/latest/index.html) to create and manage development environments. Hatch will automatically install all Zarr dependencies using the same versions as are used by the core developers and continuous integration services. Assuming you have a Python 3 interpreter already installed, and you have cloned the Zarr source code and your current working directory is the root of the repository, you can do something like the following: + +```bash +pip install hatch +hatch env show # list all available environments +``` + +To verify that your development environment is working, you can run the unit tests for one of the test environments, e.g.: + +```bash +hatch env run --env test.py3.12-optional run +``` + +### Creating a branch + +Before you do any new work or submit a pull request, please open an issue on GitHub to report the bug or propose the feature you'd like to add. + +It's best to synchronize your fork with the upstream repository, then create a new, separate branch for each piece of work you want to do. E.g.: + +```bash +git checkout main +git fetch upstream +git checkout -b shiny-new-feature upstream/main +git push -u origin shiny-new-feature +``` + +This changes your working directory to the 'shiny-new-feature' branch. Keep any changes in this branch specific to one bug or feature so it is clear what the branch brings to Zarr. + +To update this branch with latest code from Zarr, you can retrieve the changes from the main branch and perform a rebase: + +```bash +git fetch upstream +git rebase upstream/main +``` + +This will replay your commits on top of the latest Zarr git main. If this leads to merge conflicts, these need to be resolved before submitting a pull request. Alternatively, you can merge the changes in from upstream/main instead of rebasing, which can be simpler: + +```bash +git pull upstream main +``` + +Again, any conflicts need to be resolved before submitting a pull request. + +### Running the test suite + +Zarr includes a suite of unit tests. The simplest way to run the unit tests is to activate your development environment (see [creating a development environment](#creating-a-development-environment) above) and invoke: + +```bash +hatch env run --env test.py3.12-optional run +``` + +All tests are automatically run via GitHub Actions for every pull request and must pass before code can be accepted. Test coverage is also collected automatically via the Codecov service. + +### Code standards - using prek + +All code must conform to the PEP8 standard. Regarding line length, lines up to 100 characters are allowed, although please try to keep under 90 wherever possible. + +`Zarr` uses a set of git hooks managed by [`prek`](https://github.com/j178/prek), a fast, Rust-based pre-commit hook manager that is fully compatible with `.pre-commit-config.yaml` files. `prek` can be installed locally by running: + +```bash +uv tool install prek +``` + +or: + +```bash +pip install prek +``` + +The hooks can be installed locally by running: + +```bash +prek install +``` + +This will run the checks every time a commit is created locally. The checks will by default only run on the files modified by a commit, but the checks can be triggered for all the files by running: + +```bash +prek run --all-files +``` + +You can also run hooks only for files in a specific directory: + +```bash +prek run --directory src/zarr +``` + +Or run hooks for files changed in the last commit: + +```bash +prek run --last-commit +``` + +To list all available hooks: + +```bash +prek list +``` + +If you would like to skip the failing checks and push the code for further discussion, use the `--no-verify` option with `git commit`. + +### Test coverage + +> **Note:** Test coverage for Zarr-Python 3 is currently not at 100%. This is a known issue and help is welcome to bring test coverage back to 100%. See issue #2613 for more details. + +Zarr strives to maintain 100% test coverage under the latest Python stable release. Both unit tests and docstring doctests are included when computing coverage. Running: + +```bash +hatch env run --env test.py3.12-optional run-coverage +``` + +will automatically run the test suite with coverage and produce an XML coverage report. This should be 100% before code can be accepted into the main code base. + +You can also generate an HTML coverage report by running: + +```bash +hatch env run --env test.py3.12-optional run-coverage-html +``` + +When submitting a pull request, coverage will also be collected across all supported Python versions via the Codecov service, and will be reported back within the pull request. Codecov coverage must also be 100% before code can be accepted. + +### Documentation + +Docstrings for user-facing classes and functions should follow the [numpydoc](https://numpydoc.readthedocs.io/en/stable/format.html#docstring-standard) standard, including sections for Parameters and Examples. All examples should run and pass as doctests under Python 3.12. + +Zarr uses mkdocs for documentation, hosted on readthedocs.org. Documentation is written in the Markdown markup language (.md files) in the `docs` folder. The documentation consists both of prose and API documentation. All user-facing classes and functions are included in the API documentation, under the `docs/api` folder using the [mkdocstrings](https://mkdocstrings.github.io/) extension. Add any new public functions or classes to the relevant markdown file in `docs/api/*.md`. Any new features or important usage information should be included in the user-guide (`docs/user-guide`). Any changes should also be included as a new file in the `changes` directory. + +The documentation can be built locally by running: + +```bash +hatch --env docs run build +``` + +The resulting built documentation will be available in the `site` folder. + +Hatch can also be used to serve continuously updating version of the documentation during development at [http://127.0.0.1:8000/](http://127.0.0.1:8000/). This can be done by running: + +```bash +hatch --env docs run serve +``` + +#### Adding executable code blocks in the documentation + +Zarr uses [Markdown Exec](https://pawamoy.github.io/markdown-exec/usage/) to execute code blocks in Markdown files. Add `exec="true"` to a code block header for it to be executed when the docs are built. For example: + +````md +```python exec="true" +print("Hello world") +``` +```` + +Below are other useful options that can be added to the code block. See [Markdown Exec's documentation](https://pawamoy.github.io/markdown-exec/usage/#options-summary) for a full list: + + - `source="above"` makes sure the code within the code block is also rendered in the documentation (rather than just the output). + - `session=""` executes code blocks in a named session reusing previously defined variables. + - `result="ansi"` or `result="html"` to render the output. If the code does not produce output, you should leave off the `result` option to prevent an empty cell from rendering in the docs. + +For example: + +````md +```python exec="true" session="contributing" source="above" result="ansi" +print("Hello world") +``` +```` + +renders as: + +```python exec="true" session="contributing" source="above" result="ansi" +print("Hello world") +``` + +#### Validating code blocks: `exec` vs `test` + +Every Python code block in the documentation is checked by a test +(`tests/test_docs.py`) so that examples cannot quietly rot β€” the bug that motivated +this was an example calling `zarr.create_array(..., mode="w")`, an argument that does +not exist, which went unnoticed because nothing ran it. A block declares *how* it is +validated using one of two independent attributes: + + - **`exec="true"`** β€” Markdown Exec runs the block **at docs-build time to render its + output** into the page. This is the attribute described above; it is also what the + test suite executes. Use it for ordinary examples whose output should appear in the + docs. + - **`test="true"`** β€” the block is **run by the test suite only**, *not* at build time. + Use this for an example that should be validated but cannot run in the docs-build + environment β€” for example one that needs a GPU or a cloud backend. Markdown Exec + leaves a `test="true"` block as a static, syntax-highlighted snippet (it never + executes it), while the test suite still runs it (see the marker note below). + +A block may carry both (`exec="true" test="true"`), though in practice `exec="true"` +already implies it is tested, so you rarely need `test="true"` alongside it. + +The two attributes are kept separate on purpose: `exec=` controls *build-time rendering* +and `test=` controls *test-time validation*. Tagging a GPU/cloud example `exec="true"` +would make `mkdocs build` try to run it on a machine without that infrastructure and fail +the build; `test="true"` lets it be validated without being built. + +##### Opting a block out of validation + +A handful of blocks genuinely cannot run and are not executable Python β€” a REPL +transcript, a deliberately-incorrect "before" snippet, a `--8<--` file include. Mark +these explicitly by opening the fence with +`exec="false" reason="REPL output transcript, not executable source"` (supply a reason +that fits the block). + +`exec="false"` with a non-empty `reason` is an explicit, greppable opt-out. A test +(`test_no_unvalidated_blocks`) requires **every** Python block to be either `exec="true"`, +`test="true"`, or `exec="false"` with a reason β€” so a block can never silently skip +validation. A bare ` ```python ` fence, or a typo like `exec="on"`, fails that test. + +Markdown Exec only renders `exec="true"` fences; the `mkdocs_hooks.py` hook at the +repository root makes `test="true"` and `exec="false"` fences render as ordinary +highlighted code blocks. Without it, these fences would fail superfences parsing and +their contents would spill into the page as raw markdown. + +##### Marker-bound blocks (GPU, S3) + +A `test="true"` block that needs special infrastructure declares a pytest marker with +`markers="..."`, which binds it to that infrastructure in the test suite: + + - `markers="gpu"` β€” run only under `pytest -m gpu` (the GPU CI environment); skipped + elsewhere via `importorskip("cupy")`. + - `markers="s3"` β€” run against a mock S3 (moto) backend supplied by a test fixture, so + the example can use a bare `s3://…` URL with no test-only connection details on show. + +##### Placement of `test="true"` blocks + +Because Markdown Exec does not execute a `test="true"` (or `exec="false"`) block, placing +one *before* an `exec="true"` block on the same page can disrupt the build-time execution +of that later block. Put `test="true"` blocks **after** all `exec="true"` blocks on the +page (or on a page where they are the only Python block). The `test_test_only_blocks_come_last` +test enforces this, and the CI docs build runs with `--strict` so any such breakage fails +the build rather than passing as a warning. + +#### Building documentation without executing code blocks + +Sometimes, you may want the documentation to build quicker. You can disable code block execution by commenting out the [markdown-exec plugin](https://github.com/zarr-developers/zarr-python/blob/884a8c91afcc3efe28b3da952be3b85125c453cb/mkdocs.yml#L132) in the mkdocs configuration file. This will make code blocks and cross references render incorrectly (i.e., expect build warnings), but also reduces build time by ~3x. Be sure to undo the commenting out before opening your pull request. + +### Changelog + +zarr-python uses [towncrier](https://towncrier.readthedocs.io/en/stable/tutorial.html) to manage release notes. Most pull requests should include at least one news fragment describing the changes. To add a release note, you'll need the GitHub issue or pull request number and the type of your change (`feature`, `bugfix`, `doc`, `removal`, `misc`). With that, run `towncrier create` with your development environment, which will prompt you for the issue number, change type, and the news text: + +```bash +towncrier create +``` + +Alternatively, you can manually create the files in the `changes` directory using the naming convention `{issue-number}.{change-type}.md`. + +See the [towncrier](https://towncrier.readthedocs.io/en/stable/tutorial.html) docs for more. + +## Project governance + +This section documents the processes that core developers follow to maintain the project. The current core developers are listed in [`TEAM.md`](https://github.com/zarr-developers/zarr-python/blob/main/TEAM.md). + +### Merging pull requests + +Pull requests submitted by an external contributor should be reviewed and approved by at least one core developer before being merged. Ideally, pull requests submitted by a core developer should be reviewed and approved by at least one other core developer before being merged. + +Pull requests should not be merged until all CI checks have passed (GitHub Actions, Codecov) against code that has had the latest main merged in. + +Before merging, the milestone must be set to decide whether a PR will be in the next patch, minor, or major release. The next section explains which types of changes go in each release. + +### Self-merging pull requests + +The default is that a pull request opened by a core developer is reviewed and approved by at least one other core developer before it is merged. We trust core developers to use their judgment, though, and we would rather bias toward action than make routine changes wait on review they do not really need. + +So a core developer may merge their own pull request whenever they judge the change to be low-risk, provided the standard merge requirements are met β€” CI is green against code that has had the latest `main` merged in, a changelog fragment has been added, and the milestone is set β€” and other core developers have had a fair chance to weigh in. As a rule of thumb, leave the pull request open for a few days before self-merging, unless it is genuinely trivial or time-sensitive. If you are confident a change is fine, merge it; if you have real doubts, ask for a review. It is generally advisable to ping another developer in the PR description for awareness about the direction, even if you choose not to request a formal review. + +Some changes warrant more caution, and a second reviewer is usually worth seeking even when you could self-merge: changes to the public API, anything touching data-format or on-disk compatibility, and performance-sensitive code. These are the most expensive to get wrong and the hardest to reverse. Reverts, by contrast, are cheap β€” if a self-merged change turns out to be a mistake, reverting it is itself a low-risk change that any core developer can make, and the reworked version can go through normal review. When something recently merged is actively causing harm β€” a broken `main`, a release blocker, or data corruption β€” fix it fast and request review after the fact rather than waiting. + +This policy exists to lower the cost of routine work and to help newer core developers grow comfortable merging changes. It is not a license to merge past an unresolved objection: if another core developer asks to review a change, give them that chance. + +### Release procedure + +To give the release visibility and a single place to track progress, open an issue on GitHub announcing the release using the [release checklist template](https://github.com/zarr-developers/zarr-python/issues/new?template=release-checklist.md). The release checklist includes all steps necessary for the release. + +## Compatibility and versioning policies + +### Versioning + +Versions of this library are identified by a triplet of integers with the form `..`, for example `3.0.4`. A release of `zarr-python` is associated with a new version identifier. That new identifier is generated by incrementing exactly one of the components of the previous version identifier by 1. When incrementing the `major` component of the version identifier, the `minor` and `patch` components are reset to 0. When incrementing the minor component, the patch component is reset to 0. + +Releases are classified by the library changes contained in that release. This classification determines which component of the version identifier is incremented on release. + +* **major** releases (for example, `2.18.0` -> `3.0.0`) are for changes that will require extensive adaptation efforts from many users and downstream projects. For example, breaking changes to widely-used user-facing APIs should only be applied in a major release. + + Users and downstream projects should carefully consider the impact of a major release before adopting it. In advance of a major release, developers should communicate the scope of the upcoming changes, and help users prepare for them. + +* **minor** releases (for example, `3.0.0` -> `3.1.0`) are for changes that do not require significant effort from most users or downstream projects to respond to. API changes are possible in minor releases if the burden on users imposed by those changes is sufficiently small. + + For example, a recently released API may need fixes or refinements that are breaking, but low impact due to the recency of the feature. Such API changes are permitted in a minor release. + + Minor releases are safe for most users and downstream projects to adopt. + +* **patch** releases (for example, `3.1.0` -> `3.1.1`) are for changes that contain no breaking or behavior changes for downstream projects or users. Examples of changes suitable for a patch release are bugfixes and documentation improvements. + + Users should always feel safe upgrading to the latest patch release. + +Note that this versioning scheme is not consistent with [Semantic Versioning](https://semver.org/). Contrary to SemVer, the Zarr library may release breaking changes in `minor` releases, or even `patch` releases under exceptional circumstances. But we should strive to avoid doing so. + +A better model for our versioning scheme is [Intended Effort Versioning](https://jacobtomlinson.dev/effver/), or "EffVer". The guiding principle of EffVer is to categorize releases based on the *expected effort required to upgrade to that release*. + +Zarr developers should make changes as smooth as possible for users. This means making backwards-compatible changes wherever possible. When a backwards-incompatible change is necessary, users should be notified well in advance, e.g. via informative deprecation warnings. + +### Data format compatibility + +The Zarr library is an implementation of a file format standard defined externally -- see the [Zarr specifications website](https://zarr-specs.readthedocs.io) for the list of Zarr file format specifications. + +If an existing Zarr format version changes, or a new version of the Zarr format is released, then the Zarr library will generally require changes. It is very likely that a new Zarr format will require extensive breaking changes to the Zarr library, and so support for a new Zarr format in the Zarr library will almost certainly come in a new `major` release. When the Zarr library adds support for a new Zarr format, there may be a period of accelerated changes as developers refine newly added APIs and deprecate old APIs. In such a transitional phase breaking changes may be more frequent than usual. + +## Experimental API policy + +The `zarr.experimental` namespace contains features that are under active development and may change without notice. When contributing to or depending on experimental features, please keep the following in mind: + +### For contributors + +When adding a new feature to `zarr.experimental`: + +1. Place the feature under `src/zarr/experimental/` and export it from `src/zarr/experimental/__init__.py`. +2. Document the feature in `docs/user-guide/experimental.md` and note clearly that it is experimental. +3. Add a changelog entry categorized as `feature`. + +We aim to either **promote** or **remove** experimental features within **6 months** of their addition. To promote a feature to stable: + +1. Move it from `zarr.experimental` to the appropriate stable module. +2. Keep a deprecated re-export in `zarr.experimental` for one minor release. +3. Update the documentation to reflect the stable location. + +### For users + +Features in `zarr.experimental` carry no stability guarantees. They may be changed or removed in any release, including patch releases. If you depend on an experimental feature, pin your `zarr-python` version accordingly. + +## Benchmarks + +Zarr uses [pytest-benchmark](https://pytest-benchmark.readthedocs.io/en/latest/) for running +performance benchmarks as part of our test suite. The benchmarks are found in `tests/benchmarks`. +By default pytest is configured to run these benchmarks as plain tests (i.e., no benchmarking). To run +a benchmark with timing measurements, use the `--benchmark-enable` when invoking `pytest`. + +The benchmarks are run as part of the continuous integration suite through [codspeed](https://app.codspeed.io/zarr-developers/zarr-python). diff --git a/docs/contributing.rst b/docs/contributing.rst deleted file mode 100644 index a65b3d104d..0000000000 --- a/docs/contributing.rst +++ /dev/null @@ -1,391 +0,0 @@ -Contributing to Zarr -==================== - -Zarr is a community maintained project. We welcome contributions in the form of bug -reports, bug fixes, documentation, enhancement proposals and more. This page provides -information on how best to contribute. - -Asking for help ---------------- - -If you have a question about how to use Zarr, please post your question on -StackOverflow using the `"zarr" tag `_. -If you don't get a response within a day or two, feel free to raise a `GitHub issue -`_ including a link to your StackOverflow -question. We will try to respond to questions as quickly as possible, but please bear -in mind that there may be periods where we have limited time to answer questions -due to other commitments. - -Bug reports ------------ - -If you find a bug, please raise a `GitHub issue -`_. Please include the following items in -a bug report: - -1. A minimal, self-contained snippet of Python code reproducing the problem. You can - format the code nicely using markdown, e.g.:: - - - ```python - import zarr - g = zarr.group() - # etc. - ``` - -2. An explanation of why the current behaviour is wrong/not desired, and what you - expect instead. - -3. Information about the version of Zarr, along with versions of dependencies and the - Python interpreter, and installation information. The version of Zarr can be obtained - from the ``zarr.__version__`` property. Please also state how Zarr was installed, - e.g., "installed via pip into a virtual environment", or "installed using conda". - Information about other packages installed can be obtained by executing ``pip freeze`` - (if using pip to install packages) or ``conda env export`` (if using conda to install - packages) from the operating system command prompt. The version of the Python - interpreter can be obtained by running a Python interactive session, e.g.:: - - $ python - Python 3.6.1 (default, Mar 22 2017, 06:17:05) - [GCC 6.3.0 20170321] on linux - -Enhancement proposals ---------------------- - -If you have an idea about a new feature or some other improvement to Zarr, please raise a -`GitHub issue `_ first to discuss. - -We very much welcome ideas and suggestions for how to improve Zarr, but please bear in -mind that we are likely to be conservative in accepting proposals for new features. The -reasons for this are that we would like to keep the Zarr code base lean and focused on -a core set of functionalities, and available time for development, review and maintenance -of new features is limited. But if you have a great idea, please don't let that stop -you from posting it on GitHub, just please don't be offended if we respond cautiously. - -Contributing code and/or documentation --------------------------------------- - -Forking the repository -~~~~~~~~~~~~~~~~~~~~~~ - -The Zarr source code is hosted on GitHub at the following location: - -* `https://github.com/zarr-developers/zarr-python `_ - -You will need your own fork to work on the code. Go to the link above and hit -the "Fork" button. Then clone your fork to your local machine:: - - $ git clone git@github.com:your-user-name/zarr-python.git - $ cd zarr-python - $ git remote add upstream git@github.com:zarr-developers/zarr-python.git - -Creating a development environment -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To work with the Zarr source code, it is recommended to set up a Python virtual -environment and install all Zarr dependencies using the same versions as are used by -the core developers and continuous integration services. Assuming you have a Python -3 interpreter already installed, and you have cloned the Zarr source code and your -current working directory is the root of the repository, you can do something like -the following:: - - $ mkdir -p ~/pyenv/zarr-dev - $ python -m venv ~/pyenv/zarr-dev - $ source ~/pyenv/zarr-dev/bin/activate - $ pip install -r requirements_dev_minimal.txt -r requirements_dev_numpy.txt - $ pip install -e .[docs] - -To verify that your development environment is working, you can run the unit tests:: - - $ python -m pytest -v zarr - -Creating a branch -~~~~~~~~~~~~~~~~~ - -Before you do any new work or submit a pull request, please open an issue on GitHub to -report the bug or propose the feature you'd like to add. - -It's best to synchronize your fork with the upstream repository, then create a -new, separate branch for each piece of work you want to do. E.g.:: - - git checkout main - git fetch upstream - git rebase upstream/main - git push - git checkout -b shiny-new-feature - git push -u origin shiny-new-feature - -This changes your working directory to the 'shiny-new-feature' branch. Keep any changes in -this branch specific to one bug or feature so it is clear what the branch brings to -Zarr. - -To update this branch with latest code from Zarr, you can retrieve the changes from -the main branch and perform a rebase:: - - git fetch upstream - git rebase upstream/main - -This will replay your commits on top of the latest Zarr git main. If this leads to -merge conflicts, these need to be resolved before submitting a pull request. -Alternatively, you can merge the changes in from upstream/main instead of rebasing, -which can be simpler:: - - git fetch upstream - git merge upstream/main - -Again, any conflicts need to be resolved before submitting a pull request. - -Running the test suite -~~~~~~~~~~~~~~~~~~~~~~ - -Zarr includes a suite of unit tests, as well as doctests included in -function and class docstrings and in the tutorial and storage -spec. The simplest way to run the unit tests is to activate your -development environment (see `creating a development environment`_ above) -and invoke:: - - $ python -m pytest -v zarr - -Some tests require optional dependencies to be installed, otherwise -the tests will be skipped. To install all optional dependencies, run:: - - $ pip install -r requirements_dev_optional.txt - -To also run the doctests within docstrings (requires optional -dependencies to be installed), run:: - - $ python -m pytest -v --doctest-plus zarr - -To run the doctests within the tutorial and storage spec (requires -optional dependencies to be installed), run:: - - $ python -m doctest -o NORMALIZE_WHITESPACE -o ELLIPSIS docs/tutorial.rst docs/spec/v2.rst - -Note that some tests also require storage services to be running -locally. To run the Azure Blob Service storage tests, run an Azure -storage emulator (e.g., azurite) and set the environment variable -``ZARR_TEST_ABS=1``. If you're using Docker to run azurite, start the service with:: - - docker run --rm -p 10000:10000 mcr.microsoft.com/azure-storage/azurite azurite-blob --loose --blobHost 0.0.0.0 - -To run the Mongo DB storage tests, run a Mongo -server locally and set the environment variable ``ZARR_TEST_MONGO=1``. -To run the Redis storage tests, run a Redis server locally on port -6379 and set the environment variable ``ZARR_TEST_REDIS=1``. - -All tests are automatically run via GitHub Actions for every pull -request and must pass before code can be accepted. Test coverage is -also collected automatically via the Codecov service, and total -coverage over all builds must be 100% (although individual builds -may be lower due to Python 2/3 or other differences). - -Code standards - using pre-commit -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -All code must conform to the PEP8 standard. Regarding line length, lines up to 100 -characters are allowed, although please try to keep under 90 wherever possible. - -``Zarr`` uses a set of ``pre-commit`` hooks and the ``pre-commit`` bot to format, -type-check, and prettify the codebase. ``pre-commit`` can be installed locally by -running:: - - $ python -m pip install pre-commit - -The hooks can be installed locally by running:: - - $ pre-commit install - -This would run the checks every time a commit is created locally. These checks will also run -on every commit pushed to an open PR, resulting in some automatic styling fixes by the -``pre-commit`` bot. The checks will by default only run on the files modified by a commit, -but the checks can be triggered for all the files by running:: - - $ pre-commit run --all-files - -If you would like to skip the failing checks and push the code for further discussion, use -the ``--no-verify`` option with ``git commit``. - - - -Test coverage -~~~~~~~~~~~~~ - -Zarr maintains 100% test coverage under the latest Python stable release (currently -Python 3.8). Both unit tests and docstring doctests are included when computing -coverage. Running:: - - $ python -m pytest -v --cov=zarr --cov-config=pyproject.toml zarr - -will automatically run the test suite with coverage and produce a coverage report. -This should be 100% before code can be accepted into the main code base. - -When submitting a pull request, coverage will also be collected across all supported -Python versions via the Codecov service, and will be reported back within the pull -request. Codecov coverage must also be 100% before code can be accepted. - -Documentation -~~~~~~~~~~~~~ - -Docstrings for user-facing classes and functions should follow the -`numpydoc -`_ -standard, including sections for Parameters and Examples. All examples -should run and pass as doctests under Python 3.8. To run doctests, -activate your development environment, install optional requirements, -and run:: - - $ python -m pytest -v --doctest-plus zarr - -Zarr uses Sphinx for documentation, hosted on readthedocs.org. Documentation is -written in the RestructuredText markup language (.rst files) in the ``docs`` folder. -The documentation consists both of prose and API documentation. All user-facing classes -and functions should be included in the API documentation, under the ``docs/api`` -folder. Any new features or important usage information should be included in the -tutorial (``docs/tutorial.rst``). Any changes should also be included in the release -notes (``docs/release.rst``). - -The documentation can be built locally by running:: - - $ cd docs - $ make clean; make html - $ open _build/html/index.html - -The resulting built documentation will be available in the ``docs/_build/html`` folder. - -Development best practices, policies and procedures ---------------------------------------------------- - -The following information is mainly for core developers, but may also be of interest to -contributors. - -Merging pull requests -~~~~~~~~~~~~~~~~~~~~~ - -Pull requests submitted by an external contributor should be reviewed and approved by at least -one core developers before being merged. Ideally, pull requests submitted by a core developer -should be reviewed and approved by at least one other core developers before being merged. - -Pull requests should not be merged until all CI checks have passed (GitHub Actions -Codecov) against code that has had the latest main merged in. - -Compatibility and versioning policies -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Because Zarr is a data storage library, there are two types of compatibility to -consider: API compatibility and data format compatibility. - -API compatibility -""""""""""""""""" - -All functions, classes and methods that are included in the API -documentation (files under ``docs/api/*.rst``) are considered as part of the Zarr **public API**, -except if they have been documented as an experimental feature, in which case they are part of -the **experimental API**. - -Any change to the public API that does **not** break existing third party -code importing Zarr, or cause third party code to behave in a different way, is a -**backwards-compatible API change**. For example, adding a new function, class or method is usually -a backwards-compatible change. However, removing a function, class or method; removing an argument -to a function or method; adding a required argument to a function or method; or changing the -behaviour of a function or method, are examples of **backwards-incompatible API changes**. - -If a release contains no changes to the public API (e.g., contains only bug fixes or -other maintenance work), then the micro version number should be incremented (e.g., -2.2.0 -> 2.2.1). If a release contains public API changes, but all changes are -backwards-compatible, then the minor version number should be incremented -(e.g., 2.2.1 -> 2.3.0). If a release contains any backwards-incompatible public API changes, -the major version number should be incremented (e.g., 2.3.0 -> 3.0.0). - -Backwards-incompatible changes to the experimental API can be included in a minor release, -although this should be minimised if possible. I.e., it would be preferable to save up -backwards-incompatible changes to the experimental API to be included in a major release, and to -stabilise those features at the same time (i.e., move from experimental to public API), rather than -frequently tinkering with the experimental API in minor releases. - -Data format compatibility -""""""""""""""""""""""""" - -The data format used by Zarr is defined by a specification document, which should be -platform-independent and contain sufficient detail to construct an interoperable -software library to read and/or write Zarr data using any programming language. The -latest version of the specification document is available from the :ref:`spec` page. - -Here, **data format compatibility** means that all software libraries that implement a -particular version of the Zarr storage specification are interoperable, in the sense -that data written by any one library can be read by all others. It is obviously -desirable to maintain data format compatibility wherever possible. However, if a change -is needed to the storage specification, and that change would break data format -compatibility in any way, then the storage specification version number should be -incremented (e.g., 2 -> 3). - -The versioning of the Zarr software library is related to the versioning of the storage -specification as follows. A particular version of the Zarr library will -implement a particular version of the storage specification. For example, Zarr version -2.2.0 implements the Zarr storage specification version 2. If a release of the Zarr -library implements a different version of the storage specification, then the major -version number of the Zarr library should be incremented. E.g., if Zarr version 2.2.0 -implements the storage spec version 2, and the next release of the Zarr library -implements storage spec version 3, then the next library release should have version -number 3.0.0. Note however that the major version number of the Zarr library may not -always correspond to the spec version number. For example, Zarr versions 2.x, 3.x, and -4.x might all implement the same version of the storage spec and thus maintain data -format compatibility, although they will not maintain API compatibility. The version number -of the storage specification that is currently implemented is stored under the -``zarr.meta.ZARR_FORMAT`` variable. - -Note that the Zarr test suite includes a data fixture and tests to try and ensure that -data format compatibility is not accidentally broken. See the -:func:`test_format_compatibility` function in the :mod:`tests.test_storage` module -for details. - -When to make a release -~~~~~~~~~~~~~~~~~~~~~~ - -Ideally, any bug fixes that don't change the public API should be released as soon as -possible. It is fine for a micro release to contain only a single bug fix. - -When to make a minor release is at the discretion of the core developers. There are no -hard-and-fast rules, e.g., it is fine to make a minor release to make a single new -feature available; equally, it is fine to make a minor release that includes a number of -changes. - -Major releases obviously need to be given careful consideration, and should be done as -infrequently as possible, as they will break existing code and/or affect data -compatibility in some way. - -Release procedure -~~~~~~~~~~~~~~~~~ - -.. note:: - - Most of the release process is now handled by github workflow which should - automatically push a release to PyPI if a tag is pushed. - -Before releasing, make sure that all pull requests which will be -included in the release have been properly documented in -`docs/release.rst`. - -To make a new release, go to -https://github.com/zarr-developers/zarr-python/releases and -click "Draft a new release". Choose a version number prefixed -with a `v` (e.g. `v0.0.0`). For pre-releases, include the -appropriate suffix (e.g. `v0.0.0a1` or `v0.0.0rc2`). - - -Set the description of the release to:: - - See release notes https://zarr.readthedocs.io/en/stable/release.html#release-0-0-0 - -replacing the correct version numbers. For pre-release versions, -the URL should omit the pre-release suffix, e.g. "a1" or "rc1". - -Click on "Generate release notes" to auto-file the description. - -After creating the release, the documentation will be built on -https://readthedocs.io. Full releases will be available under -`/stable `_ while -pre-releases will be available under -`/latest `_. - -Also review and merge the https://github.com/conda-forge/zarr-feedstock -pull request that will be automatically generated. diff --git a/docs/getting_started.rst b/docs/getting_started.rst deleted file mode 100644 index 77d45325e4..0000000000 --- a/docs/getting_started.rst +++ /dev/null @@ -1,46 +0,0 @@ -Getting Started -=============== - -Zarr is a format for the storage of chunked, compressed, N-dimensional arrays -inspired by `HDF5 `_, `h5py -`_ and `bcolz `_. - -The project is fiscally sponsored by `NumFOCUS `_, a US -501(c)(3) public charity, and development is supported by the -`MRC Centre for Genomics and Global Health `_ -and the `Chan Zuckerberg Initiative `_. - -These documents describe the Zarr Python implementation. More information -about the Zarr format can be found on the `main website `_. - -Highlights ----------- - -* Create N-dimensional arrays with any NumPy dtype. -* Chunk arrays along any dimension. -* Compress and/or filter chunks using any NumCodecs_ codec. -* Store arrays in memory, on disk, inside a Zip file, on S3, ... -* Read an array concurrently from multiple threads or processes. -* Write to an array concurrently from multiple threads or processes. -* Organize arrays into hierarchies via groups. - -Contributing ------------- - -Feedback and bug reports are very welcome, please get in touch via -the `GitHub issue tracker `_. See -:doc:`contributing` for further information about contributing to Zarr. - -Projects using Zarr -------------------- - -If you are using Zarr, we would `love to hear about it -`_. - -.. toctree:: - :caption: Getting Started - :hidden: - - installation - -.. _NumCodecs: https://numcodecs.readthedocs.io/ diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000000..eb3b6a5000 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,92 @@ +# Zarr-Python + +**Useful links**: +[Source Repository](https://github.com/zarr-developers/zarr-python) | +[Issue Tracker](https://github.com/zarr-developers/zarr-python/issues) | +[Developer Chat](https://ossci.zulipchat.com/) | +[Zarr specifications](https://zarr-specs.readthedocs.io) + +Zarr is a powerful library for storage of n-dimensional arrays, supporting chunking, +compression, and various backends, making it a versatile choice for scientific and +large-scale data. + +Zarr-Python is a Python library for reading and writing Zarr groups and arrays. Highlights include: + +* Specification support for both Zarr format 2 and 3. +* Create and read from N-dimensional arrays using NumPy-like semantics. +* Flexible storage enables reading and writing from local, cloud and in-memory stores. +* High performance: Enables fast I/O with support for asynchronous I/O and multi-threading. +* Extensible: Customizable with user-defined codecs and stores. + +## Installation + +Zarr requires Python 3.12 or higher. You can install it via `pip`: + +```bash +pip install zarr +``` + +or `conda`: + +```bash +conda install -c conda-forge zarr +``` + +## Navigating the documentation + +
+ +- [:material-clock-fast:{ .lg .middle } __Quick start__](quick-start.md) + + --- + + New to Zarr? Check out the quick start guide. It contains a brief + introduction to Zarr's main concepts and links to additional tutorials. + +- [:material-book-open:{ .lg .middle } __User guide__](user-guide/index.md) + + --- + + A detailed guide for how to use Zarr-Python. + +- [:material-api:{ .lg .middle } __API Reference__](api/zarr/index.md) + + --- + + The reference guide contains a detailed description of the functions, modules, + and objects included in Zarr. The reference describes how the methods work and + which parameters can be used. It assumes that you have an understanding of the + key concepts. + +- [:material-package-variant:{ .lg .middle } __Related projects__](subprojects.md) + + --- + + Companion packages developed in the zarr-python repository and released + independently, such as `zarr-metadata` and `zarr-indexing`, plus pointers to + the wider Zarr ecosystem. + +- [:material-account-group:{ .lg .middle } __Contributor's Guide__](contributing.md) + + --- + + Want to contribute to Zarr? We welcome contributions in the form of bug reports, + bug fixes, documentation, enhancement proposals and more. The contributing guidelines + will guide you through the process of improving Zarr. + +
+ +## Project Status + +More information about the Zarr format can be found on the [main website](https://zarr.dev). + +If you are using Zarr-Python, we would [love to hear about it](https://github.com/zarr-developers/community/issues/19). + +### Funding and Support + +The project is fiscally sponsored by [NumFOCUS](https://numfocus.org/), a US +501(c)(3) public charity, and development has been supported by the +[MRC Centre for Genomics and Global Health](https://github.com/cggh/) +and the [Chan Zuckerberg Initiative](https://chanzuckerberg.com/). + +[Donate to Zarr](https://numfocus.org/donate-to-zarr) to support the project! diff --git a/docs/index.rst b/docs/index.rst deleted file mode 100644 index 92f9a3df18..0000000000 --- a/docs/index.rst +++ /dev/null @@ -1,105 +0,0 @@ -.. _zarr_docs_mainpage: - -*********** -Zarr-Python -*********** - -.. toctree:: - :maxdepth: 1 - :hidden: - - getting_started - tutorial - api/index - spec - release - license - acknowledgments - contributing - -**Version**: |version| - -**Download documentation**: `PDF/Zipped HTML/EPUB `_ - -**Useful links**: -`Installation `_Β | -`Source Repository `_Β | -`Issue Tracker `_Β | -`Gitter `_ - -Zarr is a file storage format for chunked, compressed, N-dimensional arrays based on an open-source specification. - -.. grid:: 2 - - .. grid-item-card:: - :img-top: _static/index_getting_started.svg - - Getting Started - ^^^^^^^^^^^^^^^ - - New to Zarr? Check out the getting started guide. It contains an - introduction to Zarr's main concepts and links to additional tutorials. - - +++ - - .. button-ref:: getting_started - :expand: - :color: dark - :click-parent: - - To the getting started guide - - .. grid-item-card:: - :img-top: _static/index_user_guide.svg - - Tutorial - ^^^^^^^^ - - The tutorial provides working examples of Zarr classes and functions. - - +++ - - .. button-ref:: tutorial - :ref-type: ref - :expand: - :color: dark - :click-parent: - - To the Tutorial - - .. grid-item-card:: - :img-top: _static/index_api.svg - - API Reference - ^^^^^^^^^^^^^ - - The reference guide contains a detailed description of the functions, - modules, and objects included in Zarr. The reference describes how the - methods work and which parameters can be used. It assumes that you have an - understanding of the key concepts. - - +++ - - .. button-ref:: api/index - :expand: - :color: dark - :click-parent: - - To the api reference guide - - .. grid-item-card:: - :img-top: _static/index_contribute.svg - - Contributor's Guide - ^^^^^^^^^^^^^^^^^^^ - - Want to contribute to Zarr? We welcome contributions in the form of bug reports, bug fixes, documentation, enhancement proposals and more. The contributing guidelines will guide you through the process of improving Zarr. - - +++ - - .. button-ref:: contributing - :expand: - :color: dark - :click-parent: - - To the contributor's guide diff --git a/docs/installation.rst b/docs/installation.rst deleted file mode 100644 index 3d4ac41072..0000000000 --- a/docs/installation.rst +++ /dev/null @@ -1,22 +0,0 @@ -Installation -============ - -Zarr depends on NumPy. It is generally best to `install NumPy -`_ first using whatever method is most -appropriate for your operating system and Python distribution. Other dependencies should be -installed automatically if using one of the installation methods below. - -Install Zarr from PyPI:: - - $ pip install zarr - -Alternatively, install Zarr via conda:: - - $ conda install -c conda-forge zarr - -To install the latest development version of Zarr, you can use pip with the -latest GitHub main:: - - $ pip install git+https://github.com/zarr-developers/zarr-python.git - -To work with Zarr source code in development, see `Contributing `_. \ No newline at end of file diff --git a/docs/license.rst b/docs/license.rst deleted file mode 100644 index 8f93aa7d66..0000000000 --- a/docs/license.rst +++ /dev/null @@ -1,4 +0,0 @@ -License -======= - -.. include:: ../LICENSE.txt diff --git a/docs/overrides/main.html b/docs/overrides/main.html new file mode 100644 index 0000000000..d61a1f54dc --- /dev/null +++ b/docs/overrides/main.html @@ -0,0 +1,9 @@ + +{% extends "base.html" %} + +{% block outdated %} + You're not viewing the latest version. +
+ Click here to go to latest. + +{% endblock %} diff --git a/docs/overrides/stylesheets/extra.css b/docs/overrides/stylesheets/extra.css new file mode 100644 index 0000000000..6cb7c74e8d --- /dev/null +++ b/docs/overrides/stylesheets/extra.css @@ -0,0 +1,209 @@ +:root { + --gradient-start: #e58077; + --gradient-mid-1: #e57a77; + --gradient-mid-2: #e46876; + --gradient-mid-3: #e34b75; + --gradient-mid-4: #e12374; + --gradient-mid-5: #e01073; + --gradient-end: #bb1085; + + /* Primary theme colors + --md-primary-fg-color: #e34b75; + --md-primary-fg-color--light: #e57a77; + --md-primary-fg-color--dark: #bb1085; + + /* Accent colors */ + --md-accent-fg-color: #e01073; + --md-accent-fg-color--transparent: rgba(224, 16, 115, 0.1); + + /* Text colors that work well with the palette */ + --md-text-color: #333333; + --md-text-color--light: #666666; +} + +/* Dark mode color adjustments */ +[data-md-color-scheme="slate"] { + --md-primary-fg-color: #e57a77; + --md-primary-fg-color--light: #e58077; + --md-primary-fg-color--dark: #bb1085; + --md-accent-fg-color: #e46876; + --md-accent-fg-color--transparent: rgba(228, 104, 118, 0.1); +} + +/* Header styling with gradient background */ +.md-header { + background: linear-gradient( + 135deg, + var(--gradient-start) 0%, + var(--gradient-mid-1) 16.66%, + var(--gradient-mid-2) 33.33%, + var(--gradient-mid-3) 50%, + var(--gradient-mid-4) 66.66%, + var(--gradient-mid-5) 83.33%, + var(--gradient-end) 100% + ); + box-shadow: 0 2px 8px rgba(187, 16, 133, 0.15); +} + +/* Ensure header text is readable over gradient */ +.md-header__title, +.md-header__button, +.md-header .md-icon { + color: white; +} + +/* Search box styling in the header */ +.md-header .md-search__input { + background-color: rgba(255, 255, 255, 0.15); + border: 1px solid rgba(255, 255, 255, 0.2); +} + +/* Navigation tabs */ +.md-tabs { + background: linear-gradient( + 90deg, + var(--gradient-mid-3) 0%, + var(--gradient-mid-4) 50%, + var(--gradient-mid-5) 100% + ); +} + +.md-tabs__link { + color: rgba(255, 255, 255, 0.9); +} + +.md-tabs__link--active, +.md-tabs__link:hover { + color: white; + opacity: 1; +} + +/* Sidebar navigation */ +.md-nav__link--active { + color: var(--md-primary-fg-color); + font-weight: 500; +} + +.md-nav__link:hover { + color: var(--md-accent-fg-color); +} + +/* Code blocks */ +.highlight { + border-left: 4px solid var(--md-accent-fg-color); + background-color: rgba(228, 104, 118, 0.05); +} + +/* Admonitions */ +.md-typeset .admonition.note { + border-color: var(--md-primary-fg-color); +} + +.md-typeset .admonition.note > .admonition-title { + background-color: rgba(227, 75, 117, 0.1); + border-color: var(--md-primary-fg-color); +} + +.md-typeset .admonition.tip { + border-color: var(--gradient-mid-1); +} + +.md-typeset .admonition.tip > .admonition-title { + background-color: rgba(229, 122, 119, 0.1); + border-color: var(--gradient-mid-1); +} + +.md-typeset .admonition.warning { + border-color: var(--gradient-end); +} + +.md-typeset .admonition.warning > .admonition-title { + background-color: rgba(187, 16, 133, 0.1); + border-color: var(--gradient-end); +} + +/* Links */ +.md-content a { + color: var(--md-accent-fg-color); +} + +.md-content a:hover { + color: var(--gradient-end); +} + +/* Table of contents */ +.md-nav--secondary .md-nav__link--active { + color: var(--md-accent-fg-color); + border-left: 2px solid var(--md-accent-fg-color); + padding-left: calc(1rem - 2px); +} + +/* Footer */ +.md-footer { + background-color: var(--gradient-end); +} + +/* Buttons and interactive elements */ +.md-button { + background: linear-gradient(135deg, var(--md-primary-fg-color), var(--md-accent-fg-color)); + border: none; + color: white; + transition: all 0.3s ease; +} + +.md-button:hover { + transform: translateY(-2px); + box-shadow: 0 4px 12px rgba(187, 16, 133, 0.3); +} + +/* Scrollbar styling */ +::-webkit-scrollbar { + width: 8px; +} + +::-webkit-scrollbar-track { + background: rgba(187, 16, 133, 0.1); +} + +::-webkit-scrollbar-thumb { + background: linear-gradient( + 180deg, + var(--md-primary-fg-color), + var(--md-accent-fg-color) + ); + border-radius: 4px; +} + +::-webkit-scrollbar-thumb:hover { + background: linear-gradient( + 180deg, + var(--md-accent-fg-color), + var(--gradient-end) + ); +} + +/* Search results highlighting */ +.md-search-result__title { + color: var(--md-primary-fg-color); +} + +.md-search-result__teaser mark { + background-color: rgba(224, 16, 115, 0.2); + color: var(--gradient-end); +} + +.md-header__button.md-logo img, +.md-header__button.md-logo svg { + height: 42px !important; /* Increase from default ~24px */ + width: auto !important; + max-height: none !important; + padding: 0 0 0 16px !important; /* Keep left padding, remove others */ + margin: 0 !important; /* Remove any margin */ +} + +/* Also remove padding from the logo button container except left */ +.md-header__button.md-logo { + padding: 0 0 0 8px !important; /* Keep some left padding on container */ + margin: 0 !important; + min-width: auto !important; +} diff --git a/docs/quick-start.md b/docs/quick-start.md new file mode 100644 index 0000000000..123f05d5e9 --- /dev/null +++ b/docs/quick-start.md @@ -0,0 +1,191 @@ +# Quick start + +This page will help you get up and running with +the Zarr library in Python to efficiently manage and analyze multi-dimensional arrays. +Zarr must be installed first -- see the [installation guide](user-guide/installation.md) +if you have not installed it yet. + +## Creating an Array + +To get started, you can create a simple Zarr array: + +```python exec="true" session="quickstart" +import shutil +shutil.rmtree('data', ignore_errors=True) +import numpy as np +from pprint import pprint +import io +import warnings + +warnings.filterwarnings( + "ignore", + message="Numcodecs codecs are not in the Zarr version 3 specification*", + category=UserWarning +) +np.random.seed(0) +``` + +```python exec="true" session="quickstart" source="above" result="ansi" +import zarr +import numpy as np + +# Create a 2D Zarr array +z = zarr.create_array( + store="data/example-1.zarr", + shape=(100, 100), + chunks=(10, 10), + dtype="f4" +) + +# Assign data to the array +z[:, :] = np.random.random((100, 100)) +print(z.info) +``` + +Here, we created a 2D array of shape `(100, 100)`, chunked into blocks of +`(10, 10)`, and filled it with random floating-point data. This array was +written to a `LocalStore` in the `data/example-1.zarr` directory. + +### Compression and Filters + +Zarr supports data compression and filters. For example, to use Blosc compression: + +```python exec="true" session="quickstart" source="above" result="ansi" + +# Create a 2D Zarr array with Blosc compression +z = zarr.create_array( + store="data/example-2.zarr", + shape=(100, 100), + chunks=(10, 10), + dtype="f4", + compressors=zarr.codecs.BloscCodec( + cname="zstd", + clevel=3, + shuffle="shuffle" + ) +) + +# Assign data to the array +z[:, :] = np.random.random((100, 100)) +print(z.info) +``` + +This compresses the data using the Blosc codec with shuffle enabled for better compression. + +## Hierarchical Groups + +Zarr allows you to create hierarchical groups, similar to directories: + +```python exec="true" session="quickstart" source="above" result="ansi" + +# Create nested groups and add arrays +root = zarr.group("data/example-3.zarr") +foo = root.create_group(name="foo") +bar = root.create_array( + name="bar", shape=(100, 10), chunks=(10, 10), dtype="f4" +) +spam = foo.create_array(name="spam", shape=(10,), dtype="i4") + +# Assign values +bar[:, :] = np.random.random((100, 10)) +spam[:] = np.arange(10) + +# print the hierarchy +print(root.tree()) +``` + +This creates a group hierarchy with a group (`foo`) and two arrays (`bar` and `spam`). + +### Batch Hierarchy Creation + +Zarr provides tools for creating a collection of arrays and groups with a single function call. +Suppose we want to copy existing groups and arrays into a new storage backend: + +```python exec="true" session="quickstart" source="above" result="code" + +# Create nested groups and add arrays +root = zarr.group("data/example-4.zarr", attributes={'name': 'root'}) +foo = root.create_group(name="foo") +bar = root.create_array( + name="bar", shape=(100, 10), chunks=(10, 10), dtype="f4" +) +nodes = {'': root.metadata} | {k: v.metadata for k,v in root.members()} +# Report nodes +output = io.StringIO() +pprint(nodes, stream=output, width=60, depth=3) +result = output.getvalue() +print(result) +# Create new hierarchy from nodes +new_nodes = dict(zarr.create_hierarchy(store=zarr.storage.MemoryStore(), nodes=nodes)) +new_root = new_nodes[''] +assert new_root.attrs == root.attrs +``` + +Note that [`zarr.create_hierarchy`][] will only initialize arrays and groups -- copying array data must +be done in a separate step. + +## Persistent Storage + +Zarr supports persistent storage to disk or cloud-compatible backends. While examples above +utilized a [`zarr.storage.LocalStore`][], a number of other storage options are available. + +A single-file store can also be created using the [`zarr.storage.ZipStore`][]: + +```python exec="true" session="quickstart" source="above" + +# Store the array in a ZIP file +store = zarr.storage.ZipStore("data/example-5.zip", mode="w") + +z = zarr.create_array( + store=store, + shape=(100, 100), + chunks=(10, 10), + dtype="f4" +) + +# write to the array +z[:, :] = np.random.random((100, 100)) + +# the ZipStore must be explicitly closed +store.close() +``` + +To open an existing array from a ZIP file: + +```python exec="true" session="quickstart" source="above" result="ansi" + +# Open the ZipStore in read-only mode +store = zarr.storage.ZipStore("data/example-5.zip", read_only=True) + +z = zarr.open_array(store, mode='r') + +# read the data as a NumPy Array +print(z[:]) +``` + +Zarr also integrates seamlessly with cloud object storage such as Amazon S3 and Google +Cloud Storage using external libraries like [s3fs](https://s3fs.readthedocs.io/en/latest/) or +[gcsfs](https://gcsfs.readthedocs.io/en/latest/). Remote storage support requires the `remote` +optional dependencies (`pip install "zarr[remote]"`) as well as a filesystem library +for your storage service, such as `s3fs` for S3: + +```python test="true" session="s3demo" markers="s3" source="above" +import zarr +import numpy as np + +z = zarr.create_array( + "s3://example-bucket/foo", shape=(100, 100), chunks=(10, 10), dtype="f4" +) +z[:, :] = np.random.random((100, 100)) +``` + +See the [Remote Store](user-guide/storage.md#remote-store) section of the storage guide +for more detail, including how to configure the underlying filesystem with `storage_options`. + +## Next steps + +This page only scratches the surface. Continue with the [User Guide](user-guide/index.md), in particular: + +- **[Arrays](user-guide/arrays.md)** - creating, reading, and writing arrays in depth +- **[Groups](user-guide/groups.md)** - organizing arrays into hierarchies +- **[Storage](user-guide/storage.md)** - the full range of local, remote, and in-memory storage options diff --git a/docs/release-notes.md b/docs/release-notes.md new file mode 100644 index 0000000000..3b54ea993a --- /dev/null +++ b/docs/release-notes.md @@ -0,0 +1,866 @@ +# Release notes + + + + + +## 3.3.0 (2026-07-30) + +### Features + +- Optimizes reading multiple chunks from a shard. Serial calls to `Store.get()` + in the sharding codec have been replaced with a single call to + `Store.get_ranges()`, which coalesces nearby byte ranges and fetches them + concurrently. ([#3004](https://github.com/zarr-developers/zarr-python/pull/3004)) +- Added a `subchunk_write_order` option to `ShardingCodec` to control the physical order of subchunks within a shard. Supported values are `morton`, `unordered`, `lexicographic`, and `colexicographic`. `unordered` makes no guarantee about subchunk layout. This setting affects only on-disk layout, not the data read back, and is not persisted in array metadata: it applies per codec instance and is not recovered when reopening a sharded array. ([#3826](https://github.com/zarr-developers/zarr-python/pull/3826)) +- Added `SyncByteGetter` and `SyncByteSetter` runtime-checkable protocols and a `get_ranges_sync` method on the `Store` ABC. These let custom byte getters/setters opt into the synchronous codec pipeline's fast path for in-memory IO, which the sharding codec uses for its inner chunks. ([#3885](https://github.com/zarr-developers/zarr-python/pull/3885)) +- Added `FusedCodecPipeline`, an opt-in codec pipeline that runs codec compute synchronously and in bulk (avoiding the per-chunk async scheduling overhead of the default `BatchedCodecPipeline`), giving large speedups for sharded arrays. The default `BatchedCodecPipeline` is unchanged for standard configurations, so existing code keeps working unless you opt in; enable the new pipeline with `zarr.config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"})`. ([#3885](https://github.com/zarr-developers/zarr-python/pull/3885)) +- Add `zarr.abc.store.Store.get_ranges` for concurrent, coalesced multi-range reads from a single key. The method is defined on the `Store` ABC with a default implementation built on `Store.get`, so every store inherits a working version; stores with native multi-range backends (e.g. `FsspecStore`) can override for efficiency. Coalescing knobs (`max_concurrency`, `max_gap_bytes`, `max_coalesced_bytes`) are passed as keyword arguments to `get_ranges`. Failures from underlying fetches surface as a `BaseExceptionGroup` (PEP 654); callers should use `except*` to filter for specific exception types such as `FileNotFoundError`. ([#3925](https://github.com/zarr-developers/zarr-python/pull/3925)) +- Two new fields on `ArrayConfig` control how the sharding codec coalesces partial-shard reads: `sharding_coalesce_max_gap_bytes` (default 1 MiB) and `sharding_coalesce_max_bytes` (default 16 MiB). When reading multiple chunks from the same shard, nearby byte ranges are merged into a single request to the store if separated by no more than `sharding_coalesce_max_gap_bytes` and the merged read stays within `sharding_coalesce_max_bytes`. Defaults are seeded from the matching `array.sharding_coalesce_max_gap_bytes` / `array.sharding_coalesce_max_bytes` keys in [`zarr.config`][] at array-creation time, and can be overridden per array by passing `config={...}` to [`zarr.create_array`][]. ([#3987](https://github.com/zarr-developers/zarr-python/pull/3987)) + +- Added `Group.get_array`, `Group.get_group`, `AsyncGroup.get_array`, and `AsyncGroup.get_group`: type-safe accessors that return the child array or group at a given path, raising `ArrayNotFoundError` / `GroupNotFoundError` if no node exists there, and `ContainsGroupError` / `ContainsArrayError` if the node is not of the requested kind. Unlike `Group.__getitem__`, which returns `Array | Group`, these methods have precise return types. Nested paths like `"subgroup/subarray"` are supported. ([#4128](https://github.com/zarr-developers/zarr-python/pull/4128)) +- `ZipStore` now accepts an open binary file-like object in place of a path, enabling + zip archives on remote storage (e.g. a file opened with `fsspec` or an + `obstore.ReadableFile`). Operations that require a filesystem location + (`clear`, `move`) raise `NotImplementedError` for file-object-backed stores. ([#4187](https://github.com/zarr-developers/zarr-python/pull/4187)) + +### Bugfixes + +- Stop emitting an `UnstableSpecificationWarning` when serializing the `struct` data type to Zarr V3 metadata. The `struct` data type now has a stable Zarr V3 specification. The legacy `structured` alias and the unspecified `null_terminated_bytes`, `raw_bytes`, and `variable_length_bytes` data types continue to warn. ([#4100](https://github.com/zarr-developers/zarr-python/pull/4100)) +- Fix equality comparison of `ArrayV2Metadata` and `ArrayV3Metadata` objects with a + `NaN` fill value. Such objects are now compared by their JSON-serialized form, so two + otherwise-identical metadata objects with a `NaN` (or infinite) fill value compare equal. ([#2929](https://github.com/zarr-developers/zarr-python/issues/2929)) +- Fixed `BytesCodec.from_dict` so that `BytesCodec` instances roundtrip to / from + their dict representation. `BytesCodec.from_dict` now interprets a missing + `endian` configuration as `endian=None` (matching what `BytesCodec.to_dict` + emits), instead of falling back to the system's native byte order. ([#3417](https://github.com/zarr-developers/zarr-python/pull/3417)) +- Fixed `save_array`, `Group.__setitem__`, and `load` for 0-dimensional arrays. ([#3469](https://github.com/zarr-developers/zarr-python/issues/3469)) +- Fixed inner-codec spec evolution for sharded arrays. The sharding codec now threads the array spec through its inner codec chain when evolving codecs, so a codec that changes the dtype upstream of `BytesCodec` no longer leaves the inner chain evolved against the wrong spec (which previously failed at decode time). This runs on the default `BatchedCodecPipeline` as well. Standard inner chains (`[BytesCodec]`, `[BytesCodec, ZstdCodec]`, transpose + bytes) are byte-identical to before. Restores the behavior of #2179. ([#3885](https://github.com/zarr-developers/zarr-python/pull/3885)) +- Make chunk normalization properly handle `-1` as a compact representation of the + length of an entire axis. Reject several previously-accepted but ill-defined + chunk specifications: `chunks=True` (previously silently produced size-1 chunks), + chunk tuples shorter than the array's number of dimensions (previously padded to + the array's shape), and `None` as a per-dimension chunk size. These all now + raise informative errors. Also fix chunk handling for 0-length array dimensions, + and add explicit rejection of 0-length chunks. ([#3899](https://github.com/zarr-developers/zarr-python/pull/3899)) +- Handle missing consolidated metadata in leaf Group nodes. ([#3954](https://github.com/zarr-developers/zarr-python/issues/3954)) +- Corrected the JSON type definitions for the `numpy.datetime64` and + `numpy.timedelta64` data types in Zarr V3 metadata: the `configuration` object + (holding `unit` and `scale_factor`) is now required, matching the published + specifications for these data types. Also updated the specification links in + the docstrings to point to the zarr-extensions repository. ([#3955](https://github.com/zarr-developers/zarr-python/pull/3955)) +- Fixed writing to 0-dimensional arrays that use the sharding codec. Previously + assigning to a 0-dimensional sharded array raised an error. ([#3966](https://github.com/zarr-developers/zarr-python/pull/3966)) +- Fix flaky stateful test bookkeeping when `delete_dir` matches string prefixes instead of true directory descendants. Previously a path such as `6/faNT…` could be incorrectly removed when deleting `6/f`. (See [issue #3977](https://github.com/zarr-developers/zarr-python/issues/3977).) ([#3977](https://github.com/zarr-developers/zarr-python/issues/3977)) +- `FsspecStore.close()` no longer closes the underlying fsspec filesystem or its + network session. fsspec caches and shares filesystem instances across callers, + so the store cannot know whether it is the only user, and closing a shared + session would break other stores; the filesystem's lifecycle belongs to + whoever created it. ([#4165](https://github.com/zarr-developers/zarr-python/pull/4165)) + +- Fixed an invalid `zarr.create_array` example in the quick-start documentation (it passed an unsupported `mode` argument) and made the cloud-storage example execute against a mock S3 backend in CI. Added a test ensuring every Python code block in the documentation is either executed or explicitly opted out with a documented reason, so an invalid example can no longer go untested. ([#4016](https://github.com/zarr-developers/zarr-python/issues/4016)) +- Fixed `ObjectStore.list_dir` for object-store listings that include a directory-marker object matching the requested non-root prefix. ([#4032](https://github.com/zarr-developers/zarr-python/issues/4032)) +- Prevents mutation of the attributes dict provided by the user by copying them instead of keeping the reference ([#4059](https://github.com/zarr-developers/zarr-python/issues/4059)) +- Fixed several storage and codec bugs: + + - Reading a value with a `SuffixByteRequest` larger than the value now correctly returns the whole value (matching HTTP `bytes=-N` suffix-range semantics), instead of silently returning incorrect data for `MemoryStore`. + - `LoggingStore.get_partial_values` and `FsspecStore.get_partial_values` no longer return empty results when `key_ranges` is passed as a one-shot iterable (e.g. a generator). + - `Store.getsize_prefix` no longer over-counts sibling keys that merely share a string prefix (e.g. `getsize_prefix("foo")` no longer includes keys under `foobar/`). + - `ZipStore.close()` no longer raises `AttributeError` when the store was created but never opened (including when used as a context manager without any I/O). + - `codecs_from_list` now raises a descriptive `TypeError` when a `BytesBytesCodec` immediately follows an `ArrayArrayCodec`, instead of a misleading "Required ArrayBytesCodec was not found" `ValueError`. + + ([#4074](https://github.com/zarr-developers/zarr-python/pull/4074)) + +- Fixed writing Fortran-ordered (F-contiguous) arrays through the variable-length string and bytes codecs and through numcodecs array-array filters such as `Delta`, `FixedScaleOffset` and `PackBits`. Chunks are now passed to numcodecs as C-contiguous arrays, so elements are no longer stored in transposed order. ([#4116](https://github.com/zarr-developers/zarr-python/pull/4116)) +- Fix silent byte-order corruption for structured dtypes with the `bytes` codec: multi-byte fields are now byte-swapped to the codec's configured `endian` on write and decoded honoring it on read, so non-native-endian structured data (e.g. big-endian fields, as produced by virtual references to external data) round-trips correctly. ([#4141](https://github.com/zarr-developers/zarr-python/issues/4141)) + +- Fix `zarr.api.asynchronous.open_like` so it can create a new array by default when the + target path does not already exist. It now defaults to `mode="a"`; when using a read-only + store to open an existing array, pass `mode="r"` explicitly. ([#3352](https://github.com/zarr-developers/zarr-python/pull/3352)) +- `MemoryStore` now copies buffers as they are written, so it never retains the + caller's memory. Previously an uncompressed write handed the store a zero-copy + view of the user's array, and mutating that array afterwards would silently + rewrite chunks already committed to the store. + + Only `MemoryStore` is affected: stores that serialize on write, such as + `LocalStore` and `ZipStore`, never aliased the caller's memory. Uncompressed + writes to a `MemoryStore` are correspondingly slower, since the copy that makes + the stored data independent is now actually performed; compressed writes are + unchanged. Buffers supplied through the `store_dict` argument remain the + caller's responsibility and are stored as-is. ([#4157](https://github.com/zarr-developers/zarr-python/pull/4157)) + +- Fixed the opt-in `FusedCodecPipeline` for sharded arrays whose inner or index codec chain contains a codec implementing only the async codec interface (no `SupportsSyncCodec`). Such arrays previously raised `TypeError: All codecs must implement SupportsSyncCodec` on both read and write; the pipeline now declines its synchronous fast path for them and falls back to the async path, matching the behavior of the default `BatchedCodecPipeline`. Fully sync-capable codec chains keep the fast path unchanged. ([#4179](https://github.com/zarr-developers/zarr-python/pull/4179)) +- Fixed `TypeError: unhashable type: 'writeable void-scalar'` when writing to sharded arrays whose fill value is a `np.void` scalar, e.g. arrays with a structured dtype. + + `ArraySpec` equality and hashing now compare the fill value by its byte representation rather than numeric equality. As a result, two specs with a `NaN` (or `NaT`) fill value now compare equal, while fill values of `-0.0` and `0.0` now compare unequal. This also restores the sharding codec's per-chunk spec cache, which had been disabled because of this bug. ([#4183](https://github.com/zarr-developers/zarr-python/pull/4183)) + +- `FusedCodecPipeline` no longer runs chunk IO and codec compute on the thread + driving zarr's internal event loop. Previously each read/write executed its + synchronous fast path inline on that loop thread, and because every sync-API + call from every user thread is serviced by the same loop, concurrent + operations serialized behind each other's codec work β€” reported as the fused + pipeline being slower than `BatchedCodecPipeline` for zstd-compressed data + under multi-threaded (e.g. dask) access. The synchronous batch now runs on a + worker thread (one hop per batch, not per chunk), keeping the loop free. + Multi-threaded single-chunk reads of compressed data now scale with reader + threads; single-threaded performance is unchanged. ([#4194](https://github.com/zarr-developers/zarr-python/pull/4194)) +- The end-to-end benchmarks no longer invoke `sudo` to drop the OS page cache during a regular `pytest` run. Cache clearing is now opt-in via the `ZARR_BENCHMARK_CLEAR_CACHE` environment variable, which the benchmark CI jobs set. ([#4199](https://github.com/zarr-developers/zarr-python/pull/4199)) +- Fixed the opt-in `FusedCodecPipeline` for serializers that advertise the partial-decode/encode mixins with only the documented async partial methods: the partial dispatch previously asserted on the private `_decode_partial_sync`/`_encode_partial_sync` hooks (an `AssertionError`, or an `AttributeError` mid-IO under `python -O`); such codecs now take the full-chunk sync path. ([#4201](https://github.com/zarr-developers/zarr-python/pull/4201)) +- Fixed `FusedCodecPipeline` (the opt-in synchronous pipeline) silently skipping + array-array/bytes-bytes codecs placed outside a sharding serializer on its + partial-decode/partial-encode fast paths. With an outer compressor (e.g. + `compressors=[GzipCodec()]` around a `ShardingCodec` serializer), the fused + pipeline wrote non-conforming stored bytes that `BatchedCodecPipeline` (and any + other conforming reader) could not read, and could fail to read data that + `BatchedCodecPipeline` had written. With an outer array-array codec (e.g. + `TransposeCodec`), it silently returned wrong data in both directions with no + error. Only the opt-in `FusedCodecPipeline` was affected; the default + `BatchedCodecPipeline` was never impacted. ([#4202](https://github.com/zarr-developers/zarr-python/pull/4202)) +- Fixed silent data corruption in the experimental `FusedCodecPipeline`: reordering or duplicating fancy-index reads (e.g. `arr[perm, :]`, `arr.oindex[[0, 0, 1], :]`) on uncompressed, crc-free sharded arrays could return the shard in natural order because the vectorized whole-shard decode accepted any selection whose output shape matched the shard shape. The bulk decode now fires only for identity full-shard reads, declines structured dtypes (whose byte-order handling it lacks), and requires shard-index offsets to exactly tile the data section, so corrupt indexes with overlapping or out-of-range offsets can no longer be served as array data. ([#4203](https://github.com/zarr-developers/zarr-python/pull/4203)) +- `ManagedMemoryStore.get_sync`/`set_sync`/`delete_sync` now apply the store's + `path` prefix, matching the async `get`/`set`/`delete` methods. Previously the + sync methods were inherited unchanged from `MemoryStore` and used the raw key, + so code that takes the sync fast path (e.g. `FusedCodecPipeline`) would read + and write chunks outside the store's `path` prefix, silently returning fill + values when the data was re-read through a fresh handle. `GpuMemoryStore.set_sync` + now converts its value to a `gpu.Buffer`, matching `set`, so writes through the + sync API keep the store's all-values-are-GPU invariant. Also fixed + `ManagedMemoryStore.get_partial_values` applying its `path` prefix twice + whenever `path` is non-empty, which made it always return `None` for every + requested key. + + The shared store test suite (`zarr.testing.store.StoreTests`) gained + sync/async parity checks β€” comparing sync and async observations of the same + key on the same store instance, including with a `byte_range` β€” so every + store subclass now exercises this invariant. The suite's former + `test_get_bytes`/`test_get_json` methods (and their `_sync` variants) were + folded into these parity tests and no longer exist as separate methods. ([#4204](https://github.com/zarr-developers/zarr-python/pull/4204)) + +- Fixed several small correctness issues from the codec-pipeline performance work: construction-time + codec warnings (e.g. sharding's "disables partial reads" warning) no longer fire twice per array + open β€” including for `FusedCodecPipeline`, which previously re-warned via its own codec-chain + reconstruction and, on the async fallback path, on every decode/encode call; `concurrent_iter` now + schedules its tasks eagerly, matching its documented contract; an invalid + `codec_pipeline.max_workers` config/environment value now warns and falls back to the default + instead of raising mid-read; and `FusedCodecPipeline`'s async fallback helpers now cancel + already-spawned fetch/decode/write tasks instead of abandoning them in the background when one + fails. ([#4205](https://github.com/zarr-developers/zarr-python/pull/4205)) +- Fixed `FusedCodecPipeline`'s gating of its synchronous fast paths: stores exposing only part of the sync surface (e.g. `set_sync` without `get_sync`) now fall back cleanly to the async path instead of failing mid-write, and `WrapperStore` now forwards `get_sync`/`set_sync`/`delete_sync` to the wrapped store so wrapped sync-capable stores keep the fast path. The capability decision uses a private, interim convention (`zarr.abc.store._store_supports_sync_io`) rather than new public API, pending a formal sync/async store architecture. Also fixed `LatencyStore`: synchronous reads and writes now pay the configured latency, `get_ranges`/`get_partial_values` no longer bypass latency injection, and derived stores (e.g. from `with_read_only`) keep a stochastic `(loc, scale)` latency configuration instead of freezing a single sample. ([#4206](https://github.com/zarr-developers/zarr-python/pull/4206)) +- `DefaultChunkKeyEncoding.decode_chunk_key` now validates that a chunk key + starts with the configured `c` prefix and raises `ValueError` for + malformed keys, instead of silently decoding them incorrectly. ([#4219](https://github.com/zarr-developers/zarr-python/pull/4219)) + +### Improved Documentation + +- Document the changes to `zarr.errors` in the 3.0 migration guide, including the removal of v2 exception classes and the introduction of `NodeNotFoundError`. ([#3009](https://github.com/zarr-developers/zarr-python/issues/3009)) +- Clarify the difference between `zarr.load` and `zarr.open` in their docstrings. + `load` eagerly reads data into an in-memory array, while `open` returns a + lazy `Array` or `Group` backed by the store, with `See Also` cross-references + linking the two. ([#3984](https://github.com/zarr-developers/zarr-python/pull/3984)) +- Updated the custom dtype example in `examples/custom_dtype/custom_dtype.py` to + use only the public API, eliminating all non-public imports, illustrating what + users should do. + + To better support this, the following types and functions were made available + from public modules: + + | Type/Function | Non-public module | Public module | + | ------------------------- | ------------------------ | ------------- | + | `DataTypeValidationError` | `zarr.core.dtype.common` | `zarr.errors` | + | `JSON` | `zarr.core.common` | `zarr.types` | + | `ZarrFormat` | `zarr.core.common` | `zarr.types` | + | `DTypeConfig_V2` | `zarr.core.dtype.common` | `zarr.types` | + | `DTypeJSON` | `zarr.core.dtype.common` | `zarr.types` | + | `DTypeSpec_V2` | `zarr.core.dtype.common` | `zarr.dtype` | + | `check_dtype_spec_v2` | `zarr.core.dtype.common` | `zarr.dtype` | + + `DataTypeValidationError` was *moved* to `zarr.errors`. Importing it from + `zarr.core.dtype.common` (its original location), `zarr.core.dtype`, or + `zarr.dtype` still works but now raises a `ZarrDeprecationWarning`. The remaining + types and functions are simply re-exported from the listed public module. ([#4052](https://github.com/zarr-developers/zarr-python/pull/4052)) + +- Document a self-merge policy in the contributor guide, describing when a core developer may merge their own pull request without a second reviewer and which changes warrant more caution. ([#4053](https://github.com/zarr-developers/zarr-python/pull/4053)) +- Fixed many documentation errors found in a full review of the user guide, including + prose contradicted by rendered example output on the performance page, invisible + code blocks, an incorrect S3 example, stale "not yet implemented" claims in the + v3 migration guide, and undocumented optional dependency groups. Also improved + navigation order, cross-linking between pages, and coverage of group member + enumeration, bulk attribute updates, and the `use_consolidated` keyword. ([#4132](https://github.com/zarr-developers/zarr-python/pull/4132)) +- Fixed the documented default of ``max_age_seconds`` in the ``CacheStore`` docstring: the default is ``"infinity"`` (no expiration), not ``None``, which is rejected. Also noted that ``cache_store`` must support deletes. ([#4133](https://github.com/zarr-developers/zarr-python/pull/4133)) + +- Added a blog section to the documentation, with a post covering two performance + highlights of the 3.3.0 release: the opt-in `FusedCodecPipeline` and byte-range + coalescing for partial reads of sharded arrays. + + Added two runnable examples that accompany the post: + `examples/codec_pipeline_performance` compares the `BatchedCodecPipeline` and + `FusedCodecPipeline` on a sharded array across two stores and two codec + regimes, showing when the fused pipeline's thread pool helps and when it does + not, and `examples/sharding_coalescing` demonstrates how read coalescing + reduces the number of store requests when reading subregions of a sharded + array. + + Also removed the hardware-specific speedup figures from the `FusedCodecPipeline` + release note, since they depend on the array layout, codec, and machine. ([#4191](https://github.com/zarr-developers/zarr-python/pull/4191)) + +### Deprecations and Removals + +- The ``BloscShuffle`` and ``BloscCname`` enums (``zarr.codecs.BloscShuffle``, + ``zarr.codecs.BloscCname``) are now deprecated. Pass the equivalent literal + string (e.g. ``"zstd"``, ``"bitshuffle"``) when constructing a ``BloscCodec``. + The enum classes remain importable but emit ``DeprecationWarning`` on member + access, and will be removed in a future release. They are no longer ``Enum`` + subclasses: constructor calls (e.g. ``BloscCname("zstd")``), iteration, and + ``.value`` access no longer work. ``BloscCodec.cname`` and + ``BloscCodec.shuffle`` are now plain strings rather than enum members. + + Additional renames in ``zarr.codecs.blosc`` from the same change: the type + aliases ``Shuffle`` and ``CName`` are now ``BloscShuffleLiteral`` and + ``BloscCnameLiteral``, the constant ``SHUFFLE`` is now ``BLOSC_SHUFFLE`` + (with a new ``BLOSC_CNAME`` alongside it), and ``BloscShuffle.from_int`` + now returns a literal string rather than an enum member. ([#3963](https://github.com/zarr-developers/zarr-python/pull/3963)) + +- The ``Endian`` (``zarr.codecs.bytes.Endian``) and ``ShardingCodecIndexLocation`` + (``zarr.codecs.ShardingCodecIndexLocation``) enums are now deprecated. Pass the + equivalent literal string instead (e.g. ``"little"`` / ``"big"``, ``"start"`` / + ``"end"``). The enum classes remain importable but emit ``DeprecationWarning`` + on member access, and will be removed in a future release. ``BytesCodec.endian`` + and ``ShardingCodec.index_location`` are now plain strings rather than enum + members. + + Two follow-on changes from this deprecation: + + - ``NDBuffer.byteorder`` now returns a literal string (``"little"`` or + ``"big"``) rather than an ``Endian`` member. Subclasses overriding this + property should update their return type. + - The module-level binding ``zarr.codecs.bytes.default_system_endian`` was + removed. ``BytesCodec()`` continues to default to ``sys.byteorder``; + external callers that imported ``default_system_endian`` should use + ``sys.byteorder`` directly. + + Additionally, the module-level function ``zarr.codecs.sharding.parse_index_location`` + was made private as part of this change. + + ([#3968](https://github.com/zarr-developers/zarr-python/pull/3968)) + +- Removed the NumPy 1.x implementation of the `VariableLengthUTF8` data type because NumPy 1.x is no longer supported under [SPEC0](https://scientific-python.org/specs/spec-0000/). ([#3973](https://github.com/zarr-developers/zarr-python/pull/3973)) + +### Misc + +- [#4139](https://github.com/zarr-developers/zarr-python/pull/4139), [#4140](https://github.com/zarr-developers/zarr-python/pull/4140), [#3908](https://github.com/zarr-developers/zarr-python/pull/3908), [#3972](https://github.com/zarr-developers/zarr-python/pull/3972), [#3975](https://github.com/zarr-developers/zarr-python/pull/3975), [#3979](https://github.com/zarr-developers/zarr-python/pull/3979), [#3990](https://github.com/zarr-developers/zarr-python/pull/3990), [#3998](https://github.com/zarr-developers/zarr-python/pull/3998), [#4000](https://github.com/zarr-developers/zarr-python/pull/4000), [#4001](https://github.com/zarr-developers/zarr-python/pull/4001), [#4012](https://github.com/zarr-developers/zarr-python/pull/4012), [#4046](https://github.com/zarr-developers/zarr-python/pull/4046), [#4054](https://github.com/zarr-developers/zarr-python/pull/4054), [#4073](https://github.com/zarr-developers/zarr-python/issues/4073), [#4086](https://github.com/zarr-developers/zarr-python/issues/4086), [#4138](https://github.com/zarr-developers/zarr-python/pull/4138) + +- [#4172](https://github.com/zarr-developers/zarr-python/pull/4172) + +## 3.2.1 (2026-05-05) + +### Bugfixes + +- Fixed a `CastValue` validation bug where the "can we use an out-of-range mode" check + inspected the source dtype instead of the target dtype. This meant arrays with a + float source dtype and an integer target dtype incorrectly raised a `ValueError` + when configured with a `wrap` out-of-range mode. ([#3938](https://github.com/zarr-developers/zarr-python/pull/3938)) +- Fixed a bug where the codec pipeline evolved each codec against the original + array spec instead of the spec produced by upstream array-to-array codecs. This + caused failures whenever an upstream codec changed the dtype between codec + boundaries β€” e.g. arrays using `CastValue` to convert a single-byte source dtype + (`int8`) to a multi-byte target dtype (`int16`) raised a `ValueError` from + `BytesCodec` about a missing `endian` configuration. ([#3941](https://github.com/zarr-developers/zarr-python/pull/3941)) +- Fixed breakage in existing fsspec-dependent workflows caused by associating the "memory" URL scheme with +instances of `ManagedMemoryStore` instead of fsspec's memory-backed store. After this change, store URLs with a "memory" scheme are handled differently when `fsspec` is installed: +with `fsspec`, a `FsspecStore` backed by a `MemoryFileSystem` is used. Without `fsspec`, +a `ManagedMemoryStore` is used. ([#3944](https://github.com/zarr-developers/zarr-python/pull/3944)) + +## 3.2.0 (2026-04-30) + +### Features + +- Adds a new in-memory storage backend called `ManagedMemoryStore`. Instances of `ManagedMemoryStore` + function similarly to `MemoryStore`, but instances of `ManagedMemoryStore` can be constructed from + a URL like `memory://store`. ([#3679](https://github.com/zarr-developers/zarr-python/pull/3679)) +- Added `array.read_missing_chunks` configuration option. When set to `False`, reading missing chunks raises a `ChunkNotFoundError` instead of filling them with the array's fill value. ([#3748](https://github.com/zarr-developers/zarr-python/pull/3748)) +- Added `Struct` class (subclass of `Structured`) implementing the zarr-extensions `struct` dtype spec. Uses object-style field format and dict fill values. Legacy `Structured` remains available for backward compatibility. ([#3781](https://github.com/zarr-developers/zarr-python/pull/3781)) +- Add support for rectilinear (variable-sized) chunk grids. This feature is experimental and + must be explicitly enabled via `zarr.config.set({'array.rectilinear_chunks': True})`. + + Rectilinear chunks can be used through: + + - **Creating arrays**: Pass nested sequences (e.g., `[[10, 20, 30], [50, 50]]`) to `chunks` + in `zarr.create_array`, `zarr.from_array`, `zarr.zeros`, `zarr.ones`, `zarr.full`, + `zarr.open`, and related functions, or to `chunk_shape` in `zarr.create`. + - **Opening existing arrays**: Arrays stored with the `rectilinear` chunk grid are read + transparently via `zarr.open` and `zarr.open_array`. + - **Rectilinear sharding**: Shard boundaries can be rectilinear while inner chunks remain regular. + + **Breaking change**: The `validate` method on `BaseCodec` and `CodecPipeline` now receives + a `ChunkGridMetadata` instance instead of a `ChunkGrid` instance for the `chunk_grid` + parameter. Third-party codecs that override `validate` and inspect the chunk grid will need to + update their type annotations. No known downstream packages were using this parameter. ([#3802](https://github.com/zarr-developers/zarr-python/pull/3802)) + +- Add `cast_value` and `scale_offset` codecs. ([#3874](https://github.com/zarr-developers/zarr-python/pull/3874)) + +### Bugfixes + +- Fix `SyncError` raised when assigning a `zarr.Array` as the value in a `__setitem__` call (e.g. `dst[:] = src` where `src` is a zarr array). The source array is now converted to a NumPy array before entering the async codec pipeline. ([#3611](https://github.com/zarr-developers/zarr-python/issues/3611)) +- Fix an issue that prevents the correct parsing of special NumPy `uint32` dtypes resulting e.g. + from bit wise operations on `uint32` arrays on Windows. ([#3797](https://github.com/zarr-developers/zarr-python/pull/3797)) +- Fix `ZipStore.list()`, `list_dir()`, and `exists()` to auto-open the zip file when called before `open()`, consistent with the existing behavior of `get()` and `set()`. ([#3846](https://github.com/zarr-developers/zarr-python/issues/3846)) +- Fix handling of `NaT` default fill values for `datetime64` and `timedelta64` data types. Equality checks now use `numpy.isnat` so that the default fill value compares correctly against `NaT`. ([#3863](https://github.com/zarr-developers/zarr-python/pull/3863)) +- Use the unit associated with the `Datetime64` data type when creating the default `Nat` scalar value. ([#3920](https://github.com/zarr-developers/zarr-python/pull/3920)) + +### Improved Documentation + +- Document removal of `zarr.storage.init_group` in v3 migration guide, with replacement using `zarr.open_group`/`zarr.create_group`. ([#2720](https://github.com/zarr-developers/zarr-python/issues/2720)) +- Document the `threading.max_workers` configuration option in the performance guide. ([#3492](https://github.com/zarr-developers/zarr-python/issues/3492)) +- Corrects the type annotation reported for the `batch_info` parameter in the `CodecPipeline.write` + method docstring. ([#3836](https://github.com/zarr-developers/zarr-python/pull/3836)) +- Remove result="ansi" from code blocks in the user guide that were causing empty output cells in the rendered documentation. ([#3845](https://github.com/zarr-developers/zarr-python/pull/3845)) + +### Deprecations and Removals + +- Remove deprecated `zarr.convenience` and `zarr.creation` modules. ([#3900](https://github.com/zarr-developers/zarr-python/pull/3900)) +- Remove the deprecated `zarr_version` parameter from several functions and methods. That parameter is replaced with `zarr_format`. ([#3901](https://github.com/zarr-developers/zarr-python/pull/3901)) +- Remove deprecated `Group` methods `array`, `require_dataset`, and `create_dataset`. ([#3902](https://github.com/zarr-developers/zarr-python/pull/3902)) +- Remove deprecated `AsyncArray.create` and `Array.create` methods. ([#3903](https://github.com/zarr-developers/zarr-python/pull/3903)) + +### Misc + +- [#3546](https://github.com/zarr-developers/zarr-python/issues/3546), [#3793](https://github.com/zarr-developers/zarr-python/pull/3793), [#3800](https://github.com/zarr-developers/zarr-python/pull/3800), [#3828](https://github.com/zarr-developers/zarr-python/pull/3828), [#3830](https://github.com/zarr-developers/zarr-python/pull/3830), [#3833](https://github.com/zarr-developers/zarr-python/pull/3833), [#3837](https://github.com/zarr-developers/zarr-python/pull/3837), [#3897](https://github.com/zarr-developers/zarr-python/pull/3897) + + +## 3.1.6 (2026-03-19) + +### Features + +- Exposes the array runtime configuration as an attribute called `config` on the `Array` and + `AsyncArray` classes. The previous `AsyncArray._config` attribute is now a deprecated alias for `AsyncArray.config`. ([#3668](https://github.com/zarr-developers/zarr-python/pull/3668)) +- Adds a method for creating a new `Array` / `AsyncArray` instance with a new runtime configuration, and fixes inaccurate documentation about the `write_empty_chunks` configuration parameter. ([#3668](https://github.com/zarr-developers/zarr-python/pull/3668)) +- Adds synchronous methods to stores that do not benefit from an async event loop. The shape of these methods is defined by protocol classes to support structural subtyping. ([#3725](https://github.com/zarr-developers/zarr-python/pull/3725)) +- Fix near-miss penalty in `_morton_order` with hybrid ceiling+argsort strategy. ([#3718](https://github.com/zarr-developers/zarr-python/pull/3718)) + +### Bugfixes + +- Correct the target bytes number for auto-chunking when auto-sharding. ([#3603](https://github.com/zarr-developers/zarr-python/pull/3603)) +- Fixed a bug in the sharding codec that prevented nested shard reads in certain cases. ([#3655](https://github.com/zarr-developers/zarr-python/pull/3655)) +- Fix obstore `_transform_list_dir` implementation to correctly relativize paths (removing `lstrip` usage). ([#3657](https://github.com/zarr-developers/zarr-python/pull/3657)) +- Raise error when trying to encode `numpy.dtypes.StringDType` with `na_object` set. ([#3695](https://github.com/zarr-developers/zarr-python/pull/3695)) +- `CacheStore`, `LoggingStore` and `LatencyStore` now support with_read_only. ([#3700](https://github.com/zarr-developers/zarr-python/pull/3700)) +- Skip chunk coordinate enumeration in resize when the array is only growing, avoiding unbounded memory usage for large arrays. ([#3702](https://github.com/zarr-developers/zarr-python/pull/3702)) +- Fix a performance bug in morton curve generation. ([#3705](https://github.com/zarr-developers/zarr-python/pull/3705)) +- Add a dedicated in-memory cache for byte-range requests to the experimental `CacheStore`. ([#3710](https://github.com/zarr-developers/zarr-python/pull/3710)) +- `BaseFloat._check_scalar` rejects invalid string values. ([#3586](https://github.com/zarr-developers/zarr-python/issues/3586)) +- Apply drop_axes squeeze in partial decode path for sharding. ([#3763](https://github.com/zarr-developers/zarr-python/pull/3763)) +- Set `copy=False` in reshape operation. ([#3649](https://github.com/zarr-developers/zarr-python/pull/3649)) +- Validate that dask-style chunks have regular shapes. ([#3779](https://github.com/zarr-developers/zarr-python/pull/3779)) + +### Improved Documentation + +- Add documentation example for creating uncompressed arrays in the Compression section of the user guide. ([#3464](https://github.com/zarr-developers/zarr-python/issues/3464)) +- Add AI-assisted code policy to the contributing guide. ([#3769](https://github.com/zarr-developers/zarr-python/pull/3769)) +- Added a glossary. ([#3767](https://github.com/zarr-developers/zarr-python/pull/3767)) + +### Misc + +- [#3562](https://github.com/zarr-developers/zarr-python/pull/3562), [#3605](https://github.com/zarr-developers/zarr-python/pull/3605), [#3619](https://github.com/zarr-developers/zarr-python/pull/3619), [#3623](https://github.com/zarr-developers/zarr-python/pull/3623), [#3636](https://github.com/zarr-developers/zarr-python/pull/3636), [#3648](https://github.com/zarr-developers/zarr-python/pull/3648), [#3656](https://github.com/zarr-developers/zarr-python/pull/3656), [#3658](https://github.com/zarr-developers/zarr-python/pull/3658), [#3673](https://github.com/zarr-developers/zarr-python/pull/3673), [#3704](https://github.com/zarr-developers/zarr-python/pull/3704), [#3706](https://github.com/zarr-developers/zarr-python/pull/3706), [#3708](https://github.com/zarr-developers/zarr-python/pull/3708), [#3712](https://github.com/zarr-developers/zarr-python/pull/3712), [#3713](https://github.com/zarr-developers/zarr-python/pull/3713), [#3717](https://github.com/zarr-developers/zarr-python/pull/3717), [#3721](https://github.com/zarr-developers/zarr-python/pull/3721), [#3728](https://github.com/zarr-developers/zarr-python/pull/3728), [#3778](https://github.com/zarr-developers/zarr-python/pull/3778) + + +## 3.1.5 (2025-11-21) + +### Bugfixes + +- Fix formatting errors in the release notes section of the docs. ([#3594](https://github.com/zarr-developers/zarr-python/pull/3594)) + + +## 3.1.4 (2025-11-20) + +### Features + +- The `Array` class can now also be parametrized in the same manner as the `AsyncArray` class, allowing Zarr format v2 and v3 `Array`s to be distinguished. + New types have been added to `zarr.types` to help with this. ([#3304](https://github.com/zarr-developers/zarr-python/pull/3304)) +- Adds `zarr.experimental.cache_store.CacheStore`, a `Store` that implements caching by combining two other `Store` instances. See the [docs page](https://zarr.readthedocs.io/en/latest/user-guide/experimental#cachestore) for more information about this feature. ([#3366](https://github.com/zarr-developers/zarr-python/pull/3366)) +- Adds a `zarr.experimental` module for unstable user-facing features. ([#3490](https://github.com/zarr-developers/zarr-python/pull/3490)) +- Add a `array.target_shard_size_bytes` to [`zarr.config`][] to allow users to set a maximum number of bytes per-shard when `shards="auto"` in, for example, [`zarr.create_array`][]. ([#3547](https://github.com/zarr-developers/zarr-python/pull/3547)) +- Make `async_array` on the [`zarr.Array`][] class public (`_async_array` will remain untouched, but its stability is not guaranteed). ([#3556](https://github.com/zarr-developers/zarr-python/pull/3556)) + +### Bugfixes + +- Fix a bug that prevented `PCodec` from being properly resolved when loading arrays using that compressor. ([#3483](https://github.com/zarr-developers/zarr-python/pull/3483)) +- Fixed a bug that prevented Zarr Python from opening Zarr V3 array metadata documents that contained + extra keys with permissible values (dicts with a `"must_understand"` key set to `"false"`). ([#3530](https://github.com/zarr-developers/zarr-python/pull/3530)) +- Fixed a bug where the `"consolidated_metadata"` key was written to metadata documents even when + consolidated metadata was not used, resulting in invalid metadata documents. ([#3535](https://github.com/zarr-developers/zarr-python/pull/3535)) +- Improve write performance to large shards by up to 10x. ([#3560](https://github.com/zarr-developers/zarr-python/issues/3560)) + +### Improved Documentation + +- Use mkdocs-material for Zarr-Python documentation ([#3118](https://github.com/zarr-developers/zarr-python/pull/3118)) +- Document different values of StoreLike with examples in the user guide. ([#3303](https://github.com/zarr-developers/zarr-python/issues/3303)) +- Reorganize the top-level `examples` directory to give each example its own sub-directory. Adds content to the docs for each example. ([#3502](https://github.com/zarr-developers/zarr-python/pull/3502)) +- Updated 3.0 Migration Guide to include function signature change to zarr.Array.resize function. ([#3536](https://github.com/zarr-developers/zarr-python/issues/3536)) + +### Misc + +- [#3515](https://github.com/zarr-developers/zarr-python/pull/3515), [#3532](https://github.com/zarr-developers/zarr-python/pull/3532), [#3533](https://github.com/zarr-developers/zarr-python/pull/3533), [#3553](https://github.com/zarr-developers/zarr-python/pull/3553) + + +## 3.1.3 (2025-09-18) + +### Features + +- Add a command-line interface to migrate v2 Zarr metadata to v3. Corresponding functions are also provided under zarr.metadata. ([#1798](https://github.com/zarr-developers/zarr-python/issues/1798)) +- Add obstore implementation of delete_dir. ([#3310](https://github.com/zarr-developers/zarr-python/pull/3310)) +- Adds a registry for chunk key encodings for extensibility. This allows users to implement a custom `ChunkKeyEncoding`, which can be registered via `register_chunk_key_encoding` or as an entry point under `zarr.chunk_key_encoding`. ([#3436](https://github.com/zarr-developers/zarr-python/pull/3436)) +- Trying to open a group at a path where an array already exists now raises a helpful error. ([#3444](https://github.com/zarr-developers/zarr-python/pull/3444)) + +### Bugfixes + +- Prevents creation of groups (.create_group) or arrays (.create_array) as children of an existing array. ([#2582](https://github.com/zarr-developers/zarr-python/issues/2582)) +- Fix a bug preventing `ones_like`, `full_like`, `empty_like`, `zeros_like` and `open_like` functions from accepting an explicit specification of array attributes like shape, dtype, chunks etc. The functions `full_like`, `empty_like`, and `open_like` now also more consistently infer a `fill_value` parameter from the provided array. ([#2992](https://github.com/zarr-developers/zarr-python/pull/2992)) +- LocalStore now uses atomic writes, which should prevent some cases of corrupted data. ([#3411](https://github.com/zarr-developers/zarr-python/issues/3411)) +- Fix a potential race condition when using `zarr.create_array` with the `data` parameter set to a NumPy array. Previously Zarr was iterating over the newly created array with a granularity that was too low. Now Zarr chooses a granularity that matches the size of the stored objects for that array. ([#3422](https://github.com/zarr-developers/zarr-python/pull/3422)) +- Fix ChunkGrid definition (broken in 3.1.2) ([#3425](https://github.com/zarr-developers/zarr-python/pull/3425)) +- Ensure syntax like `root['/subgroup']` works equivalently to `root['subgroup']` when using consolidated metadata. ([#3428](https://github.com/zarr-developers/zarr-python/pull/3428)) +- Creating a new group with `zarr.group` no longer errors. This fixes a regression introduced in version 3.1.2. ([#3431](https://github.com/zarr-developers/zarr-python/pull/3431)) +- Setting `fill_value` to a float like `0.0` when the data type of the array is an integer is a common mistake. This change lets Zarr Python read arrays with this erroneous metadata, although Zarr Python will not create such arrays. ([#3448](https://github.com/zarr-developers/zarr-python/pull/3448)) + +### Deprecations and Removals + +- The `Store.set_partial_writes` method, which was not used by Zarr-Python, has been removed. `store.supports_partial_writes` is now always `False`. ([#2859](https://github.com/zarr-developers/zarr-python/issues/2859)) + +### Misc + +- [#3376](https://github.com/zarr-developers/zarr-python/pull/3376), [#3390](https://github.com/zarr-developers/zarr-python/pull/3390), [#3403](https://github.com/zarr-developers/zarr-python/pull/3403), [#3449](https://github.com/zarr-developers/zarr-python/pull/3449) + +## 3.1.2 (2025-08-25) + +### Features + +- Added support for async vectorized and orthogonal indexing. ([#3083](https://github.com/zarr-developers/zarr-python/pull/3083)) +- Make config param optional in init_array ([#3391](https://github.com/zarr-developers/zarr-python/pull/3391)) + +### Bugfixes + +- Ensure that -0.0 is not considered equal to 0.0 when checking if all the values in a chunk are equal to an array's fill value. ([#3144](https://github.com/zarr-developers/zarr-python/issues/3144)) +- Fix a bug in `create_array` caused by iterating over chunk-aligned regions instead of shard-aligned regions when writing data. Additionally, the behavior of `nchunks_initialized` has been adjusted. This function consistently reports the number of chunks present in stored objects, even when the array uses the sharding codec. ([#3299](https://github.com/zarr-developers/zarr-python/pull/3299)) +- Opening an array or group with `mode="r+"` will no longer create new arrays or groups. ([#3307](https://github.com/zarr-developers/zarr-python/pull/3307)) +- Added `zarr.errors.ArrayNotFoundError`, which is raised when attempting to open a zarr array that does not exist, and `zarr.errors.NodeNotFoundError`, which is raised when failing to open an array or a group in a context where either an array or a group was expected. ([#3367](https://github.com/zarr-developers/zarr-python/pull/3367)) +- Ensure passing `config` is handled properly when `open`ing an existing array. ([#3378](https://github.com/zarr-developers/zarr-python/pull/3378)) +- Raise a Zarr-specific error class when a codec can't be found by name when deserializing the given codecs. This avoids hiding this error behind a "not part of a zarr hierarchy" warning. ([#3395](https://github.com/zarr-developers/zarr-python/pull/3395)) + +### Misc + +- [#3098](https://github.com/zarr-developers/zarr-python/pull/3098), [#3288](https://github.com/zarr-developers/zarr-python/pull/3288), [#3318](https://github.com/zarr-developers/zarr-python/pull/3318), [#3368](https://github.com/zarr-developers/zarr-python/issues/3368), [#3371](https://github.com/zarr-developers/zarr-python/pull/3371), [#3372](https://github.com/zarr-developers/zarr-python/pull/3372), [#3374](https://github.com/zarr-developers/zarr-python/pull/3374) + +## 3.1.1 (2025-07-28) + +### Features + +- Add lightweight implementations of `.getsize()` and `.getsize_prefix()` for ObjectStore. ([#3227](https://github.com/zarr-developers/zarr-python/pull/3227)) + +### Bugfixes + +- Creating a Zarr format 2 array with the `order` keyword argument no longer raises a warning. ([#3112](https://github.com/zarr-developers/zarr-python/pull/3112)) +- Fixed the error message when passing both `config` and `write_empty_chunks` arguments to reflect the current behaviour (`write_empty_chunks` takes precedence). ([#3112](https://github.com/zarr-developers/zarr-python/pull/3112)) +- Creating a Zarr format 3 array with the `order` argument now consistently ignores this argument and raises a warning. ([#3112](https://github.com/zarr-developers/zarr-python/pull/3112)) +- When using [`from_array`][zarr.api.asynchronous.from_array] to copy a Zarr format 2 array to a Zarr format 3 array, if the memory order of the input array is `"F"` a warning is raised and the order ignored. This is because Zarr format 3 arrays are always stored in "C" order. ([#3112](https://github.com/zarr-developers/zarr-python/pull/3112)) +- The `config` argument to [`zarr.create`][zarr.create] (and functions that create arrays) is now used - previously it had no effect. ([#3112](https://github.com/zarr-developers/zarr-python/pull/3112)) +- Ensure that all abstract methods of [`ZDType`][zarr.core.dtype.ZDType] raise a `NotImplementedError` when invoked. ([#3251](https://github.com/zarr-developers/zarr-python/pull/3251)) +- Register 'gpu' marker with pytest for downstream StoreTests. ([#3258](https://github.com/zarr-developers/zarr-python/pull/3258)) +- Expand the range of types accepted by `parse_data_type` to include strings and Sequences. +- Move the functionality of `zarr.core.dtype.parse_data_type` to a new function called `zarr.dtype.parse_dtype`. This change ensures that nomenclature is consistent across the codebase. `zarr.core.dtype.parse_data_type` remains, so this change is not breaking. ([#3264](https://github.com/zarr-developers/zarr-python/pull/3264)) +- Fix a regression introduced in 3.1.0 that prevented `inf`, `-inf`, and `nan` values from being stored in `attributes`. ([#3280](https://github.com/zarr-developers/zarr-python/pull/3280)) +- Fixes [`Group.nmembers()`][zarr.Group.nmembers] ignoring depth when using consolidated metadata. ([#3287](https://github.com/zarr-developers/zarr-python/pull/3287)) + +### Improved Documentation + +- Expand the data type docs to include a demonstration of the `parse_data_type` function. Expand the docstring for the `parse_data_type` function. ([#3249](https://github.com/zarr-developers/zarr-python/pull/3249)) +- Add a section on codecs to the migration guide. ([#3273](https://github.com/zarr-developers/zarr-python/pull/3273)) + +### Misc + +- Remove warnings about vlen-utf8 and vlen-bytes codecs ([#3268](https://github.com/zarr-developers/zarr-python/pull/3268)) + +## 3.1.0 (2025-07-14) + +### Features + +- Ensure that invocations of `create_array` use consistent keyword arguments, with consistent defaults. + + [`zarr.api.synchronous.create_array`][] now takes a `write_data` keyword argument + The `Group.create_array` method takes `data` and `write_data` keyword arguments. + The functions [`zarr.api.asynchronous.create`][], [`zarr.api.asynchronous.create_array`] + and the methods `Group.create_array`, `Group.array`, had the default + `fill_value` changed from `0` to the `DEFAULT_FILL_VALUE` value, which instructs Zarr to + use the default scalar value associated with the array's data type as the fill value. These are + all functions or methods for array creation that mirror, wrap or are wrapped by, another function + that already has a default `fill_value` set to `DEFAULT_FILL_VALUE`. This change is necessary + to make these functions consistent across the entire codebase, but as this changes default values, + new data might have a different fill value than expected after this change. + + For data types where 0 is meaningful, like integers or floats, the default scalar is 0, so this + change should not be noticeable. For data types where 0 is ambiguous, like fixed-length unicode + strings, the default fill value might be different after this change. Users who were relying on how + Zarr interpreted `0` as a non-numeric scalar value should set their desired fill value explicitly + after this change. + +- Added public API for Buffer ABCs and implementations. + + Use `zarr.buffer` to access buffer implementations, and + `zarr.abc.buffer` for the interface to implement new buffer types. + + Users previously importing buffer from `zarr.core.buffer` should update their + imports to use `zarr.buffer`. As a reminder, all of `zarr.core` is + considered a private API that's not covered by zarr-python's versioning policy. ([#2871](https://github.com/zarr-developers/zarr-python/issues/2871)) + +- Adds zarr-specific data type classes. + + This change adds a `ZDType` base class for Zarr V2 and Zarr V3 data types. Child classes are + defined for each NumPy data type. Each child class defines routines for `JSON` serialization. + New data types can be created and registered dynamically. + + Prior to this change, Zarr Python had two streams for handling data types. For Zarr V2 arrays, + we used NumPy data type identifiers. For Zarr V3 arrays, we used a fixed set of string enums. Both + of these systems proved hard to extend. + + This change is largely internal, but it does change the type of the `dtype` and `data_type` + fields on the `ArrayV2Metadata` and `ArrayV3Metadata` classes. Previously, `ArrayV2Metadata.dtype` + was a NumPy `dtype` object, and `ArrayV3Metadata.data_type` was an internally-defined `enum`. + After this change, both `ArrayV2Metadata.dtype` and `ArrayV3Metadata.data_type` are instances of + `ZDType`. A NumPy data type can be generated from a `ZDType` via the `ZDType.to_native_dtype()` + method. The internally-defined Zarr V3 `enum` class is gone entirely, but the `ZDType.to_json(zarr_format=3)` + method can be used to generate either a string, or dictionary that has a string `name` field, that + represents the string value previously associated with that `enum`. + + For more on this new feature, see the [documentation](user-guide/data_types.md) ([#2874](https://github.com/zarr-developers/zarr-python/pull/2874)) + +- Added `NDBuffer.empty` method for faster ndbuffer initialization. ([#3191](https://github.com/zarr-developers/zarr-python/pull/3191)) + +- The minimum version of NumPy has increased to 1.26. ([#3226](https://github.com/zarr-developers/zarr-python/pull/3226)) + +- Add an alternate `from_array_metadata_and_store` constructor to `CodecPipeline`. ([#3233](https://github.com/zarr-developers/zarr-python/pull/3233)) + +### Bugfixes + +- Fixes a variety of issues related to string data types. + + - Brings the `VariableLengthUTF8` data type Zarr V3 identifier in alignment with Zarr Python 3.0.8 + - Disallows creation of 0-length fixed-length data types + - Adds a regression test for the `VariableLengthUTF8` data type that checks against version 3.0.8 + - Allows users to request the `VariableLengthUTF8` data type with `str`, `"str"`, or `"string"`. ([#3170](https://github.com/zarr-developers/zarr-python/pull/3170)) + +- Add human readable size for No. bytes stored to `info_complete` ([#3190](https://github.com/zarr-developers/zarr-python/pull/3190)) + +- Restores the ability to create a Zarr V2 array with a `null` fill value by introducing a new + class `DefaultFillValue`, and setting the default value of the `fill_value` parameter in array + creation routines to an instance of `DefaultFillValue`. For Zarr V3 arrays, `None` will act as an + alias for a `DefaultFillValue` instance, thus preserving compatibility with existing code. ([#3198](https://github.com/zarr-developers/zarr-python/pull/3198)) + +- Fix the type of `ArrayV2Metadata.codec` to constrain it to `numcodecs.abc.Codec | None`. + Previously the type was more permissive, allowing objects that can be parsed into Codecs (e.g., the codec name). + The constructor of `ArrayV2Metadata` still allows the permissive input when creating new objects. ([#3232](https://github.com/zarr-developers/zarr-python/pull/3232)) + +### Improved Documentation + +- Add a self-contained example of data type extension to the `examples` directory, and expanded + the documentation for data types. ([#3157](https://github.com/zarr-developers/zarr-python/pull/3157)) + +- Add a description on how to create a RemoteStore of a specific filesystem to the `Remote Store` section in `docs/user-guide/storage.md`. + State in the docstring of `FsspecStore.from_url` that the filesystem type is inferred from the URL scheme. + + It should help a user handling the case when the type of FsspecStore doesn't match the URL scheme. ([#3212](https://github.com/zarr-developers/zarr-python/pull/3212)) + +### Deprecations and Removals + +- Removes default chunk encoding settings (filters, serializer, compressors) from the global + configuration object. + + This removal is justified on the basis that storing chunk encoding settings in the config required + a brittle, confusing, and inaccurate categorization of array data types, which was particularly + unsuitable after the recent addition of new data types that didn't fit naturally into the + pre-existing categories. + + The default chunk encoding is the same (Zstandard compression, and the required object codecs for + variable length data types), but the chunk encoding is now generated by functions that cannot be + reconfigured at runtime. Users who relied on setting the default chunk encoding via the global configuration object should + instead specify the desired chunk encoding explicitly when creating an array. + + This change also adds an extra validation step to the creation of Zarr V2 arrays, which ensures that + arrays with a `VariableLengthUTF8` or `VariableLengthBytes` data type cannot be created without the + correct "object codec". ([#3228](https://github.com/zarr-developers/zarr-python/pull/3228)) + +- Removes support for passing keyword-only arguments positionally to the following functions and methods: + `save_array`, `open`, `group`, `open_group`, `create`, `get_basic_selection`, `set_basic_selection`, + `get_orthogonal_selection`, `set_orthogonal_selection`, `get_mask_selection`, `set_mask_selection`, + `get_coordinate_selection`, `set_coordinate_selection`, `get_block_selection`, `set_block_selection`, + `Group.create_array`, `Group.empty`, `Group.zeroes`, `Group.ones`, `Group.empty_like`, `Group.full`, + `Group.zeros_like`, `Group.ones_like`, `Group.full_like`, `Group.array`. Prior to this change, + passing a keyword-only argument positionally to one of these functions or methods would raise a + deprecation warning. That warning is now gone. Passing keyword-only arguments to these functions + and methods positionally is now an error. + +## 3.0.10 (2025-07-03) + +### Bugfixes + +- Removed an unnecessary check from `_fsspec._make_async` that would raise an exception when + creating a read-only store backed by a local file system with `auto_mkdir` set to `False`. ([#3193](https://github.com/zarr-developers/zarr-python/pull/3193)) + +- Add missing import for AsyncFileSystemWrapper for _make_async in _fsspec.py ([#3195](https://github.com/zarr-developers/zarr-python/pull/3195)) + +## 3.0.9 (2025-06-30) + +### Features + +- Add `zarr.storage.FsspecStore.from_mapper()` so that `zarr.open()` supports stores of type `fsspec.mapping.FSMap`. ([#2774](https://github.com/zarr-developers/zarr-python/pull/2774)) + +- Implemented `move` for `LocalStore` and `ZipStore`. This allows users to move the store to a different root path. ([#3021](https://github.com/zarr-developers/zarr-python/pull/3021)) + +- Added `zarr.errors.GroupNotFoundError`, which is raised when attempting to open a group that does not exist. ([#3066](https://github.com/zarr-developers/zarr-python/pull/3066)) + +- Adds `fill_value` to the list of attributes displayed in the output of the `AsyncArray.info()` method. ([#3081](https://github.com/zarr-developers/zarr-python/pull/3081)) + +- Use `numpy.zeros` instead of `np.full` for a performance speedup when creating a `zarr.core.buffer.NDBuffer` with `fill_value=0`. ([#3082](https://github.com/zarr-developers/zarr-python/pull/3082)) + +- Port more stateful testing actions from [Icechunk](https://icechunk.io/en/stable/). ([#3130](https://github.com/zarr-developers/zarr-python/pull/3130)) + +- Adds a `with_read_only` convenience method to the `Store` abstract base class (raises `NotImplementedError`) and implementations to the `MemoryStore`, `ObjectStore`, `LocalStore`, and `FsspecStore` classes. ([#3138](https://github.com/zarr-developers/zarr-python/pull/3138)) + +### Bugfixes + +- Ignore stale child metadata when reconsolidating metadata. ([#2921](https://github.com/zarr-developers/zarr-python/issues/2921)) + +- For Zarr format 2, allow fixed-length string arrays to be created without automatically inserting a + `Vlen-UT8` codec in the array of filters. Fixed-length string arrays do not need this codec. This + change fixes a regression where fixed-length string arrays created with Zarr Python 3 could not be read with Zarr Python 2.18. ([#3100](https://github.com/zarr-developers/zarr-python/pull/3100)) + +- When creating arrays without explicitly specifying a chunk size using `zarr.create` and other + array creation routines, the chunk size will now set automatically instead of defaulting to the data shape. + For large arrays this will result in smaller default chunk sizes. + To retain previous behaviour, explicitly set the chunk shape to the data shape. + + This fix matches the existing chunking behaviour of + `zarr.save_array` and `zarr.api.asynchronous.AsyncArray.create`. ([#3103](https://github.com/zarr-developers/zarr-python/pull/3103)) + +- When `zarr.save` has an argument `path=some/path/` and multiple arrays in `args`, the path resulted in `some/path/some/path` due to using the `path` + argument twice while building the array path. This is now fixed. ([#3127](https://github.com/zarr-developers/zarr-python/pull/3127)) + +- Fix `zarr.open` default for argument `mode` when `store` is `read_only` ([#3128](https://github.com/zarr-developers/zarr-python/pull/3128)) + +- Suppress `FileNotFoundError` when deleting non-existent keys in the `obstore` adapter. + + When writing empty chunks (i.e. chunks where all values are equal to the array's fill value) to a zarr array, zarr + will delete those chunks from the underlying store. For zarr arrays backed by the `obstore` adapter, this will potentially + raise a `FileNotFoundError` if the chunk doesn't already exist. + Since whether or not a delete of a non-existing object raises an error depends on the behavior of the underlying store, + suppressing the error in all cases results in consistent behavior across stores, and is also what `zarr` seems to expect + from the store. ([#3140](https://github.com/zarr-developers/zarr-python/pull/3140)) + +- Trying to open a StorePath/Array with `mode='r'` when the store is not read-only creates a read-only copy of the store. ([#3156](https://github.com/zarr-developers/zarr-python/pull/3156)) + +## 3.0.8 (2025-05-19) + +!!! warning + + In versions 3.0.0 to 3.0.7 opening arrays or groups with `mode='a'` (the default for many builtin functions) would cause any existing paths in the store to be deleted. This is fixed in 3.0.8, and we recommend all users upgrade to avoid this bug that could cause unintentional data loss. + +### Features + +- Added a `print_debug_info` function for bug reports. ([#2913](https://github.com/zarr-developers/zarr-python/pull/2913)) + +### Bugfixes + +- Fix a bug that prevented the number of initialized chunks being counted properly. ([#2862](https://github.com/zarr-developers/zarr-python/pull/2862)) +- Fixed sharding with GPU buffers. ([#2978](https://github.com/zarr-developers/zarr-python/pull/2978)) +- Fix structured `dtype` fill value serialization for consolidated metadata ([#2998](https://github.com/zarr-developers/zarr-python/issues/2998)) +- It is now possible to specify no compressor when creating a zarr format 2 array. + This can be done by passing `compressor=None` to the various array creation routines. + + The default behaviour of automatically choosing a suitable default compressor remains if the compressor argument is not given. + To reproduce the behaviour in previous zarr-python versions when `compressor=None` was passed, pass `compressor='auto'` instead. ([#3039](https://github.com/zarr-developers/zarr-python/pull/3039)) + +- Fixed the typing of `dimension_names` arguments throughout so that it now accepts iterables that contain `None` alongside `str`. ([#3045](https://github.com/zarr-developers/zarr-python/pull/3045)) +- Using various functions to open data with `mode='a'` no longer deletes existing data in the store. ([#3062](https://github.com/zarr-developers/zarr-python/pull/3062)) +- Internally use `typesize` constructor parameter for `numcodecs.blosc.Blosc` to improve compression ratios back to the v2-package levels. ([#2962](https://github.com/zarr-developers/zarr-python/pull/2962)) +- Specifying the memory order of Zarr format 2 arrays using the `order` keyword argument has been fixed. ([#2950](https://github.com/zarr-developers/zarr-python/issues/2950)) + +### Misc + +- [#2972](https://github.com/zarr-developers/zarr-python/pull/2972), [#3027](https://github.com/zarr-developers/zarr-python/pull/3027), [#3049](https://github.com/zarr-developers/zarr-python/pull/3049) + +## 3.0.7 (2025-04-22) + +### Features + +- Add experimental ObjectStore storage class based on obstore. ([#1661](https://github.com/zarr-developers/zarr-python/pull/1661)) +- Add `zarr.from_array` using concurrent streaming of source data ([#2622](https://github.com/zarr-developers/zarr-python/pull/2622)) + +### Bugfixes + +- 0-dimensional arrays are now returning a scalar. Therefore, the return type of `__getitem__` changed + to NDArrayLikeOrScalar. This change is to make the behavior of 0-dimensional arrays consistent with + `numpy` scalars. ([#2718](https://github.com/zarr-developers/zarr-python/pull/2718)) +- Fix `fill_value` serialization for `NaN` in `ArrayV2Metadata` and add property-based testing of round-trip serialization ([#2802](https://github.com/zarr-developers/zarr-python/pull/2802)) +- Fixes `ConsolidatedMetadata` serialization of `nan`, `inf`, and `-inf` to be + consistent with the behavior of `ArrayMetadata`. ([#2996](https://github.com/zarr-developers/zarr-python/pull/2996)) + +### Improved Documentation + +- Updated the 3.0 migration guide to include the removal of "." syntax for getting group members. ([#2991](https://github.com/zarr-developers/zarr-python/issues/2991), [#2997](https://github.com/zarr-developers/zarr-python/pull/2997)) + +### Misc + +- Define a new versioning policy based on Effective Effort Versioning. This replaces the old Semantic + Versioning-based policy. ([#2924](https://github.com/zarr-developers/zarr-python/issues/2924), [#2910](https://github.com/zarr-developers/zarr-python/pull/2910)) +- Make warning filters in the tests more specific, so warnings emitted by tests added in the future + are more likely to be caught instead of ignored. ([#2714](https://github.com/zarr-developers/zarr-python/pull/2714)) +- Avoid an unnecessary memory copy when writing Zarr to a local file ([#2944](https://github.com/zarr-developers/zarr-python/pull/2944)) + +## 3.0.6 (2025-03-20) + +### Bugfixes + +- Restore functionality of `del z.attrs['key']` to actually delete the key. ([#2908](https://github.com/zarr-developers/zarr-python/pull/2908)) + +## 3.0.5 (2025-03-07) + +### Bugfixes + +- Fixed a bug where `StorePath` creation would not apply standard path normalization to the `path` parameter, + which led to the creation of arrays and groups with invalid keys. ([#2850](https://github.com/zarr-developers/zarr-python/pull/2850)) +- Prevent update_attributes calls from deleting old attributes ([#2870](https://github.com/zarr-developers/zarr-python/pull/2870)) + +### Misc + +- [#2796](https://github.com/zarr-developers/zarr-python/pull/2796) + +## 3.0.4 (2025-02-23) + +### Features + +- Adds functions for concurrently creating multiple arrays and groups. ([#2665](https://github.com/zarr-developers/zarr-python/pull/2665)) + +### Bugfixes + +- Fixed a bug where `ArrayV2Metadata` could save `filters` as an empty array. ([#2847](https://github.com/zarr-developers/zarr-python/pull/2847)) +- Fix a bug when setting values of a smaller last chunk. ([#2851](https://github.com/zarr-developers/zarr-python/pull/2851)) + +### Misc + +- [#2828](https://github.com/zarr-developers/zarr-python/pull/2828) + +## 3.0.3 (2025-02-14) + +### Features + +- Improves performance of FsspecStore.delete_dir for remote filesystems supporting concurrent/batched deletes, e.g., s3fs. ([#2661](https://github.com/zarr-developers/zarr-python/pull/2661)) +- Added `zarr.config.enable_gpu` to update Zarr's configuration to use GPUs. ([#2751](https://github.com/zarr-developers/zarr-python/pull/2751)) +- Avoid reading chunks during writes where possible. [#757](https://github.com/zarr-developers/zarr-python/issues/757) ([#2784](https://github.com/zarr-developers/zarr-python/pull/2784)) +- `LocalStore` learned to `delete_dir`. This makes array and group deletes more efficient. ([#2804](https://github.com/zarr-developers/zarr-python/pull/2804)) +- Add `zarr.testing.strategies.array_metadata` to generate ArrayV2Metadata and ArrayV3Metadata instances. ([#2813](https://github.com/zarr-developers/zarr-python/pull/2813)) +- Add arbitrary `shards` to Hypothesis strategy for generating arrays. ([#2822](https://github.com/zarr-developers/zarr-python/pull/2822)) + +### Bugfixes + +- Fixed bug with Zarr using device memory, instead of host memory, for storing metadata when using GPUs. ([#2751](https://github.com/zarr-developers/zarr-python/pull/2751)) +- The array returned by `zarr.empty` and an empty `zarr.core.buffer.cpu.NDBuffer` will now be filled with the + specified fill value, or with zeros if no fill value is provided. + This fixes a bug where Zarr format 2 data with no fill value was written with un-predictable chunk sizes. ([#2755](https://github.com/zarr-developers/zarr-python/pull/2755)) +- Fix zip-store path checking for stores with directories listed as files. ([#2758](https://github.com/zarr-developers/zarr-python/pull/2758)) +- Use removeprefix rather than replace when removing filename prefixes in `FsspecStore.list` ([#2778](https://github.com/zarr-developers/zarr-python/pull/2778)) +- Enable automatic removal of `needs release notes` with labeler action ([#2781](https://github.com/zarr-developers/zarr-python/pull/2781)) +- Use the proper label config ([#2785](https://github.com/zarr-developers/zarr-python/pull/2785)) +- Alters the behavior of `create_array` to ensure that any groups implied by the array's name are created if they do not already exist. Also simplifies the type signature for any function that takes an ArrayConfig-like object. ([#2795](https://github.com/zarr-developers/zarr-python/pull/2795)) +- Enitialise empty chunks to the default fill value during writing and add default fill values for datetime, timedelta, structured, and other (void* fixed size) data types ([#2799](https://github.com/zarr-developers/zarr-python/pull/2799)) +- Ensure utf8 compliant strings are used to construct numpy arrays in property-based tests ([#2801](https://github.com/zarr-developers/zarr-python/pull/2801)) +- Fix pickling for ZipStore ([#2807](https://github.com/zarr-developers/zarr-python/pull/2807)) +- Update numcodecs to not overwrite codec configuration ever. Closes [#2800](https://github.com/zarr-developers/zarr-python/issues/2800). ([#2811](https://github.com/zarr-developers/zarr-python/pull/2811)) +- Fix fancy indexing (e.g. arr[5, [0, 1]]) with the sharding codec ([#2817](https://github.com/zarr-developers/zarr-python/pull/2817)) + +### Improved Documentation + +- Added new user guide on GPU. ([#2751](https://github.com/zarr-developers/zarr-python/pull/2751)) + +## 3.0.2 (2025-01-31) + +### Features + +- Test `getsize()` and `getsize_prefix()` in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Test that a `ValueError` is raised for invalid byte range syntax in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Separate instantiating and opening a store in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Add a test for using Stores as context managers in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Implemented `LoggingStore.open()`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- `LoggingStore` is now a generic class. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Change StoreTest's `test_store_repr`, `test_store_supports_writes`, + `test_store_supports_partial_writes`, and `test_store_supports_listing` + to be implemented using `@abstractmethod`, rather than raising `NotImplementedError`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Test the error raised for invalid buffer arguments in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Test that data can be written to a store that's not yet open using the store.set method in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Adds a new function `init_array` for initializing an array in storage, and refactors `create_array` + to use `init_array`. `create_array` takes two new parameters: `data`, an optional array-like object, and `write_data`, a bool which defaults to `True`. + If `data` is given to `create_array`, then the `dtype` and `shape` attributes of `data` are used to define the + corresponding attributes of the resulting Zarr array. Additionally, if `data` is given and `write_data` is `True`, + then the values in `data` will be written to the newly created array. ([#2761](https://github.com/zarr-developers/zarr-python/pull/2761)) + +### Bugfixes + +- Wrap sync fsspec filesystems with `AsyncFileSystemWrapper`. ([#2533](https://github.com/zarr-developers/zarr-python/pull/2533)) +- Added backwards compatibility for Zarr format 2 structured arrays. ([#2681](https://github.com/zarr-developers/zarr-python/pull/2681)) +- Update equality for `LoggingStore` and `WrapperStore` such that 'other' must also be a `LoggingStore` or `WrapperStore` respectively, rather than only checking the types of the stores they wrap. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Ensure that `ZipStore` is open before getting or setting any values. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Use stdout rather than stderr as the default stream for `LoggingStore`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Match the errors raised by read only stores in `StoreTests`. ([#2693](https://github.com/zarr-developers/zarr-python/pull/2693)) +- Fixed `ZipStore` to make sure the correct attributes are saved when instances are pickled. + This fixes a previous bug that prevented using `ZipStore` with a `ProcessPoolExecutor`. ([#2762](https://github.com/zarr-developers/zarr-python/pull/2762)) +- Updated the optional test dependencies to include `botocore` and `fsspec`. ([#2768](https://github.com/zarr-developers/zarr-python/pull/2768)) +- Fixed the fsspec tests to skip if `botocore` is not installed. + Previously they would have failed with an import error. ([#2768](https://github.com/zarr-developers/zarr-python/pull/2768)) +- Optimize full chunk writes. ([#2782](https://github.com/zarr-developers/zarr-python/pull/2782)) + +### Improved Documentation + +- Changed the machinery for creating changelog entries. + Now individual entries should be added as files to the `changes` directory in the `zarr-python` repository, instead of directly to the changelog file. ([#2736](https://github.com/zarr-developers/zarr-python/pull/2736)) + +### Other + +- Created a type alias `ChunkKeyEncodingLike` to model the union of `ChunkKeyEncoding` instances and the dict form of the + parameters of those instances. `ChunkKeyEncodingLike` should be used by high-level functions to provide a convenient + way for creating `ChunkKeyEncoding` objects. ([#2763](https://github.com/zarr-developers/zarr-python/pull/2763)) + +## 3.0.1 (2025-01-17) + +* Implement `zarr.from_array` using concurrent streaming ([#2622](https://github.com/zarr-developers/zarr-python/pull/2622)). + +### Bug fixes + +* Fixes `order` argument for Zarr format 2 arrays ([#2679](https://github.com/zarr-developers/zarr-python/pull/2679)). +* Fixes a bug that prevented reading Zarr format 2 data with consolidated + metadata written using `zarr-python` version 2 ([#2694](https://github.com/zarr-developers/zarr-python/issues/2694)). +* Ensure that compressor=None results in no compression when writing Zarr + format 2 data ([#2708](https://github.com/zarr-developers/zarr-python/issues/2708)). +* Fix for empty consolidated metadata dataset: backwards compatibility with + Zarr-Python 2 ([#2695](https://github.com/zarr-developers/zarr-python/pull/2695)). + +### Documentation + +* Add v3.0.0 release announcement banner ([#2677](https://github.com/zarr-developers/zarr-python/pull/2677)). +* Quickstart guide alignment with V3 API ([#2697](https://github.com/zarr-developers/zarr-python/pull/2697)). +* Fix doctest failures related to numcodecs 0.15 ([#2727](https://github.com/zarr-developers/zarr-python/pull/2727)). + +### Other + +* Removed some unnecessary files from the source distribution + to reduce its size. ([#2686](https://github.com/zarr-developers/zarr-python/pull/2686)). +* Enable codecov in GitHub actions ([#2682](https://github.com/zarr-developers/zarr-python/pull/2682)). +* Speed up hypothesis tests ([#2650](https://github.com/zarr-developers/zarr-python/pull/2650)). +* Remove multiple imports for an import name ([#2723](https://github.com/zarr-developers/zarr-python/pull/2723)). + +## 3.0.0 (2025-01-09) + +3.0.0 is a new major release of Zarr-Python, with many breaking changes. +See the [v3 migration guide](user-guide/v3_migration.md) for a listing of what's changed. + +Normal release note service will resume with further releases in the 3.0.0 +series. + +Release notes for the zarr-python 2.x and 1.x releases can be found here: +https://zarr.readthedocs.io/en/support-v2/release.html diff --git a/docs/release.rst b/docs/release.rst deleted file mode 100644 index dbf390a800..0000000000 --- a/docs/release.rst +++ /dev/null @@ -1,2277 +0,0 @@ -Release notes -============= - -.. - # Copy the warning statement _under_ the latest release version - # and unindent for pre-releases. - - .. warning:: - Pre-release! Use :command:`pip install --pre zarr` to evaluate this release. - -.. - # Unindent the section between releases in order - # to document your changes. On releases it will be - # re-indented so that it does not show up in the notes. - -.. note:: - Zarr-Python 2.18.* is expected be the final release in the 2.* series. Work on Zarr-Python 3.0 is underway. - See `GH1777 `_ for more details on the upcoming - 3.0 release. - -.. release_3.0.0-alpha: - -3.0.0-alpha ------------ - -.. warning:: - Zarr-Python 3.0.0-alpha is a pre-release of the upcoming 3.0 release. This release is not feature complete or - expected to be ready for production applications. - -.. note:: - The complete release notes for 3.0 have not been added to this document yet. See the - `3.0.0-alpha `_ release on GitHub - for a record of changes included in this release. - -Enhancements -~~~~~~~~~~~~ - -* Implement listing of the sub-arrays and sub-groups for a V3 ``Group``. - By :user:`Davis Bennett ` :issue:`1726`. - -* Bootstrap v3 branch with zarrita. - By :user:`Joe Hamman ` :issue:`1584`. - -* Extensible codecs for V3. - By :user:`Norman Rzepka ` :issue:`1588`. - -* Don't import from tests. - By :user:`Davis Bennett ` :issue:`1601`. - -* Listable V3 Stores. - By :user:`Joe Hamman ` :issue:`1634`. - -* Codecs without array metadata. - By :user:`Norman Rzepka ` :issue:`1632`. - -* fix sync group class methods. - By :user:`Joe Hamman ` :issue:`1652`. - -* implement eq for LocalStore. - By :user:`Charoula Kyriakides ` :issue:`1792`. - -* V3 reorg. - By :user:`Joe Hamman ` :issue:`1809`. - -* [v3] Sync with futures. - By :user:`Davis Bennett ` :issue:`1804`. - -* implement group.members. - By :user:`Davis Bennett ` :issue:`1726`. - -* Remove implicit groups. - By :user:`Joe Hamman ` :issue:`1827`. - -* feature(store): ``list_*`` -> AsyncGenerators. - By :user:`Joe Hamman ` :issue:`1844`. - -* Test codec entrypoints. - By :user:`Norman Rzepka ` :issue:`1835`. - -* Remove extra v3 sync module. - By :user:`Max Jones ` :issue:`1856`. - -* Use donfig for V3 configuration. - By :user:`Max Jones ` :issue:`1655`. - -* groundwork for V3 group tests. - By :user:`Davis Bennett ` :issue:`1743`. - -* [v3] First step to generalizes ndarray and bytes. - By :user:`Mads R. B. Kristensen ` :issue:`1826`. - -* Reworked codec pipelines. - By :user:`Norman Rzepka ` :issue:`1670`. - -* Followup on codecs. - By :user:`Norman Rzepka ` :issue:`1889`. - -* Protocols for Buffer and NDBuffer. - By :user:`Mads R. B. Kristensen ` :issue:`1899`. - -* [V3] Expand store tests. - By :user:`Davis Bennett ` :issue:`1900`. - -* [v3] Feature: Store open mode. - By :user:`Joe Hamman ` :issue:`1911`. - -* fix(types): Group.info -> NotImplementedError. - By :user:`Joe Hamman ` :issue:`1936`. - -* feature(typing): add py.typed file to package root. - By :user:`Joe Hamman ` :issue:`1935`. - -* Support all indexing variants. - By :user:`Norman Rzepka ` :issue:`1917`. - -* Feature: group and array name properties. - By :user:`Joe Hamman ` :issue:`1940`. - -* implement .chunks on v3 arrays. - By :user:`Ryan Abernathey ` :issue:`1929`. - -* Fixes bug in transpose. - By :user:`Norman Rzepka ` :issue:`1949`. - -* Buffer Prototype Argument. - By :user:`Mads R. B. Kristensen ` :issue:`1910`. - -* Feature: Top level V3 API. - By :user:`Joe Hamman ` :issue:`1884`. - -* Basic working FsspecStore. - By :user:`Martin Durant `; :issue:`1785`. - -Typing -~~~~~~ - -* Resolve Mypy errors in v3 branch. - By :user:`Daniel Jahn ` :issue:`1692`. - -* Allow dmypy to be run on v3 branch. - By :user:`David Stansby ` :issue:`1780`. - -* Remove unused typing ignore comments. - By :user:`David Stansby ` :issue:`1781`. - -* Check untyped defs on v3. - By :user:`David Stansby ` :issue:`1784`. - -* [v3] Enable some more strict mypy options. - By :user:`David Stansby ` :issue:`1793`. - -* [v3] Disallow generic Any typing. - By :user:`David Stansby ` :issue:`1794`. - -* Disallow incomplete type definitions. - By :user:`David Stansby ` :issue:`1814`. - -* Disallow untyped calls. - By :user:`David Stansby ` :issue:`1811`. - -* Fix some untyped calls. - By :user:`David Stansby ` :issue:`1865`. - -* Disallow untyped defs. - By :user:`David Stansby ` :issue:`1834`. - -* Add more typing to zarr.group. - By :user:`David Stansby ` :issue:`1870`. - -* Fix any generics in zarr.array. - By :user:`David Stansby ` :issue:`1861`. - -* Remove some unused mypy overrides. - By :user:`David Stansby ` :issue:`1894`. - -* Finish typing zarr.metadata. - By :user:`David Stansby ` :issue:`1880`. - -* Disallow implicit re-exports. - By :user:`David Stansby ` :issue:`1908`. - -* Make typing strict. - By :user:`David Stansby ` :issue:`1879`. - -* Enable extra mypy error codes. - By :user:`David Stansby ` :issue:`1909`. - -* Enable warn_unreachable for mypy. - By :user:`David Stansby ` :issue:`1937`. - -* Fix final typing errors. - By :user:`David Stansby ` :issue:`1939`. - -Maintenance -~~~~~~~~~~~ - -* Remedy a situation where ``zarr-python`` was importing ``DummyStorageTransformer`` from the test suite. - The dependency relationship is now reversed: the test suite imports this class from ``zarr-python``. - By :user:`Davis Bennett ` :issue:`1601`. - -* [V3] Update minimum supported Python and Numpy versions. - By :user:`Joe Hamman ` :issue:`1638` - -* use src layout and use hatch for packaging. - By :user:`Davis Bennett ` :issue:`1592`. - -* temporarily disable mypy in v3 directory. - By :user:`Joe Hamman ` :issue:`1649`. - -* create hatch test env. - By :user:`Ryan Abernathey ` :issue:`1650`. - -* removed unused environments and workflows. - By :user:`Ryan Abernathey ` :issue:`1651`. - -* Add env variables to sprint setup instructions. - By :user:`Max Jones ` :issue:`1654`. - -* Add test matrix for V3. - By :user:`Max Jones ` :issue:`1656`. - -* Remove attrs. - By :user:`Davis Bennett ` :issue:`1660`. - -* Specify hatch envs using GitHub actions matrix for v3 tests. - By :user:`Max Jones ` :issue:`1728`. - -* black -> ruff format + cleanup. - By :user:`Saransh Chopra ` :issue:`1639`. - -* Remove old v3. - By :user:`Davis Bennett ` :issue:`1742`. - -* V3 update pre commit. - By :user:`Joe Hamman ` :issue:`1808`. - -* remove windows testing on v3 branch. - By :user:`Joe Hamman ` :issue:`1817`. - -* fix: add mypy to test dependencies. - By :user:`Davis Bennett ` :issue:`1789`. - -* chore(ci): add numpy 2 release candidate to test matrix. - By :user:`Joe Hamman ` :issue:`1828`. - -* fix dependencies. - By :user:`Norman Rzepka ` :issue:`1840`. - -* Add pytest to mypy dependencies. - By :user:`David Stansby ` :issue:`1846`. - -* chore(pre-commit): update pre-commit versions and remove attrs dep mypy section. - By :user:`Joe Hamman ` :issue:`1848`. - -* Enable some ruff rules (RUF) and fix issues. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1869`. - -* Configure Ruff to apply flake8-bugbear/isort/pyupgrade. - By :user:`Norman Rzepka ` :issue:`1890`. - -* chore(ci): remove mypy from test action in favor of pre-commit action. - By :user:`Joe Hamman ` :issue:`1887`. - -* Enable ruff/flake8-raise rules (RSE) and fix issues. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1872`. - -* Apply assorted ruff/refurb rules (FURB). - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1873`. - -* Enable ruff/flake8-implicit-str-concat rules (ISC) and fix issues. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1868`. - -* Add numpy to mypy pre-commit check env. - By :user:`David Stansby ` :issue:`1893`. - -* remove fixture files from src. - By :user:`Davis Bennett ` :issue:`1897`. - -* Fix list of packages in mypy pre-commit environment. - By :user:`David Stansby ` :issue:`1907`. - -* Run sphinx directly on readthedocs. - By :user:`David Stansby ` :issue:`1919`. - -* Apply preview ruff rules. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1942`. - -* Enable and apply ruff rule RUF009. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1941`. - -Documentation -~~~~~~~~~~~~~ - -* Specify docs hatch env for v3 branch. - By :user:`Max Jones ` :issue:`1655`. - -* Development installation/contributing docs updates. - By :user:`Alden Keefe Sampson ` :issue:`1643`. - -* chore: update project settings per scientific python repo-review. - By :user:`Joe Hamman ` :issue:`1863`. - -* doc: update release notes for 3.0.0.alpha. - By :user:`Joe Hamman ` :issue:`1959`. - -.. _release_2.18.2: - -2.18.2 ------- - -Enhancements -~~~~~~~~~~~~ - -* Add Zstd codec to old V3 code path. - By :user:`Ryan Abernathey ` - -.. _release_2.18.1: - -2.18.1 ------- - -Maintenance -~~~~~~~~~~~ -* Fix a regression when getting or setting a single value from arrays with size-1 chunks. - By :user:`Deepak Cherian ` :issue:`1874` - -.. _release_2.18.0: - -2.18.0 ------- - -Enhancements -~~~~~~~~~~~~ -* Performance improvement for reading and writing chunks if any of the dimensions is size 1. - By :user:`Deepak Cherian ` :issue:`1730`. - -Maintenance -~~~~~~~~~~~ -* Enable ruff/bugbear rules (B) and fix issues. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1702`. - -* Minor updates to use `np.inf` instead of `np.PINF` / `np.NINF` in preparation for NumPy 2.0.0 release. - By :user:`Joe Hamman ` :issue:`1842`. - -Deprecations -~~~~~~~~~~~~ - -* Deprecate experimental v3 support by issuing a `FutureWarning`. - Also updated docs to warn about using the experimental v3 version. - By :user:`Joe Hamman ` :issue:`1802` and :issue:`1807`. - -* Deprecate the following stores: :class:`zarr.storage.DBMStore`, :class:`zarr.storage.LMDBStore`, - :class:`zarr.storage.SQLiteStore`, :class:`zarr.storage.MongoDBStore`, :class:`zarr.storage.RedisStore`, - and :class:`zarr.storage.ABSStore`. These stores are slated to be removed from Zarr-Python in version 3.0. - By :user:`Joe Hamman ` :issue:`1801`. - -.. _release_2.17.2: - -2.17.2 ------- - -Enhancements -~~~~~~~~~~~~ - -* [v3] Dramatically reduce number of ``__contains__`` requests in favor of optimistically calling `__getitem__` - and handling any error that may arise. - By :user:`Deepak Cherian ` :issue:`1741`. - -* [v3] Reuse the downloaded array metadata when creating an ``Array``. - By :user:`Deepak Cherian ` :issue:`1734`. - -* Optimize ``Array.info`` so that it calls `getsize` only once. - By :user:`Deepak Cherian ` :issue:`1733`. - -* Override IPython ``_repr_*_`` methods to avoid expensive lookups against object stores. - By :user:`Deepak Cherian ` :issue:`1716`. - -* FSStore now raises rather than return bad data. - By :user:`Martin Durant ` and :user:`Ian Carroll ` :issue:`1604`. - -* Avoid redundant ``__contains__``. - By :user:`Deepak Cherian ` :issue:`1739`. - -Docs -~~~~ - -* Fix link to GCSMap in ``tutorial.rst``. - By :user:`Daniel Jahn ` :issue:`1689`. - -* Endorse `SPEC0000 `_ and state version support policy in ``installation.rst``. - By :user:`Sanket Verma ` :issue:`1665`. - -* Migrate v1 and v2 specification to `Zarr-Specs `_. - By :user:`Sanket Verma ` :issue:`1582`. - -Maintenance -~~~~~~~~~~~ - -* Add CI test environment for Python 3.12 - By :user:`Joe Hamman ` :issue:`1719`. - -* Bump minimum supported NumPy version to 1.23 (per spec 0000) - By :user:`Joe Hamman ` :issue:`1719`. - -* Minor fixes: Using ``is`` instead of ``type`` and removing unnecessary ``None``. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1737`. - -* Fix tests failure related to Pytest 8. - By :user:`David Stansby ` :issue:`1714`. - -.. _release_2.17.1: - -2.17.1 ------- - -Enhancements -~~~~~~~~~~~~ - -* Change occurrences of % and format() to f-strings. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1423`. - -* Proper argument for numpy.reshape. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1425`. - -* Add typing to dimension separator arguments. - By :user:`David Stansby ` :issue:`1620`. - -Docs -~~~~ - -* ZIP related tweaks. - By :user:`Davis Bennett ` :issue:`1641`. - -Maintenance -~~~~~~~~~~~ - -* Update config.yml with Zulip. - By :user:`Josh Moore `. - -* Replace Gitter with the new Zulip Chat link. - By :user:`Sanket Verma ` :issue:`1685`. - -* Fix RTD build. - By :user:`Sanket Verma ` :issue:`1694`. - -.. _release_2.17.0: - -2.17.0 ------- - -Enhancements -~~~~~~~~~~~~ - -* Added type hints to ``zarr.creation.create()``. - By :user:`David Stansby ` :issue:`1536`. - -* Pyodide support: Don't require fasteners on Emscripten. - By :user:`Hood Chatham ` :issue:`1663`. - -Docs -~~~~ - -* Minor correction and changes in documentation. - By :user:`Sanket Verma ` :issue:`1509`. - -* Fix typo in documentation. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1554` - -* The documentation build now fails if there are any warnings. - By :user:`David Stansby ` :issue:`1548`. - -* Add links to ``numcodecs`` docs in the tutorial. - By :user:`David Stansby ` :issue:`1535`. - -* Enable offline formats for documentation builds. - By :user:`Sanket Verma ` :issue:`1551`. - -* Minor tweak to advanced indexing tutorial examples. - By :user:`Ross Barnowski ` :issue:`1550`. - -* Automatically document array members using sphinx-automodapi. - By :user:`David Stansby ` :issue:`1547`. - -* Add a markdown file documenting the current and former core-developer team. - By :user:`Joe Hamman ` :issue:`1628`. - -* Add Norman Rzepka to core-dev team. - By :user:`Joe Hamman ` :issue:`1630`. - -* Added section about accessing ZIP archives on s3. - By :user:`Jeff Peck ` :issue:`1613`, :issue:`1615`, and :user:`Davis Bennett ` :issue:`1641`. - -* Add V3 roadmap and design document. - By :user:`Joe Hamman ` :issue:`1583`. - -Maintenance -~~~~~~~~~~~ - -* Drop Python 3.8 and NumPy 1.20 - By :user:`Josh Moore `; :issue:`1557`. - -* Cache result of ``FSStore._fsspec_installed()``. - By :user:`Janick Martinez Esturo ` :issue:`1581`. - -* Extend copyright notice to 2023. - By :user:`Jack Kelly ` :issue:`1528`. - -* Change occurrence of ``io.open()`` into ``open()``. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1421`. - -* Preserve ``dimension_separator`` when resizing arrays. - By :user:`Ziwen Liu ` :issue:`1533`. - -* Initialise some sets in tests with set literals instead of list literals. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1534`. - -* Allow ``black`` code formatter to be run with any Python version. - By :user:`David Stansby ` :issue:`1549`. - -* Remove ``sphinx-rtd-theme`` dependency from ``pyproject.toml``. - By :user:`Sanket Verma ` :issue:`1563`. - -* Remove ``CODE_OF_CONDUCT.md`` file from the Zarr-Python repository. - By :user:`Sanket Verma ` :issue:`1572`. - -* Bump version of black in pre-commit. - By :user:`David Stansby ` :issue:`1559`. - -* Use list comprehension where applicable. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1555`. - -* Use format specification mini-language to format string. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1558`. - -* Single startswith() call instead of multiple ones. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1556`. - -* Move codespell options around. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1196`. - -* Remove unused mypy ignore comments. - By :user:`David Stansby ` :issue:`1602`. - -.. _release_2.16.1: - -2.16.1 ------- - -Maintenance -~~~~~~~~~~~ - -* Require ``setuptools_scm`` version ``1.5.4``\+ - By :user:`John A. Kirkham ` :issue:`1477`. - -* Add ``docs`` requirements to ``pyproject.toml`` - By :user:`John A. Kirkham ` :issue:`1494`. - -* Fixed caching issue in ``LRUStoreCache``. - By :user:`Mads R. B. Kristensen ` :issue:`1499`. - -.. _release_2.16.0: - -2.16.0 ------- - -Enhancements -~~~~~~~~~~~~ - -* Allow for partial codec specification in V3 array metadata. - By :user:`Joe Hamman ` :issue:`1443`. - -* Add ``__contains__`` method to ``KVStore``. - By :user:`Christoph Gohlke ` :issue:`1454`. - -* **Block Indexing**: Implemented blockwise (chunk blocks) indexing to ``zarr.Array``. - By :user:`Altay Sansal ` :issue:`1428` - -Maintenance -~~~~~~~~~~~ - -* Refactor the core array tests to reduce code duplication. - By :user:`Davis Bennett ` :issue:`1462`. - -* Style the codebase with ``ruff`` and ``black``. - By :user:`Davis Bennett ` :issue:`1459` - -* Ensure that chunks is tuple of ints upon array creation. - By :user:`Philipp Hanslovsky ` :issue:`1461` - -.. _release_2.15.0: - -2.15.0 ------- - -Enhancements -~~~~~~~~~~~~ - -* Implement more extensive fallback of getitem/setitem for orthogonal indexing. - By :user:`Andreas Albert ` :issue:`1029`. - -* Getitems supports ``meta_array``. - By :user:`Mads R. B. Kristensen ` :issue:`1131`. - -* ``open_array()`` now takes the ``meta_array`` argument. - By :user:`Mads R. B. Kristensen ` :issue:`1396`. - -Maintenance -~~~~~~~~~~~ - -* Remove ``codecov`` from GitHub actions. - By :user:`John A. Kirkham ` :issue:`1391`. - -* Replace ``np.product`` with ``np.prod`` due to deprecation. - By :user:`James Bourbeau ` :issue:`1405`. - -* Activate Py 3.11 builds. - By :user:`Joe Hamman ` :issue:`1415`. - -Documentation -~~~~~~~~~~~~~ - -* Add API reference for V3 Implementation in the docs. - By :user:`Sanket Verma ` :issue:`1345`. - -Bug fixes -~~~~~~~~~ - -* Fix the conda-forge error. Read :issue:`1347` for detailed info. - By :user:`Josh Moore ` :issue:`1364` and :issue:`1367`. - -* Fix ``ReadOnlyError`` when opening V3 store via fsspec reference file system. - By :user:`Joe Hamman ` :issue:`1383`. - -* Fix ``normalize_fill_value`` for structured arrays. - By :user:`Alan Du ` :issue:`1397`. - -.. _release_2.14.2: - -2.14.2 ------- - -Bug fixes -~~~~~~~~~ - -* Ensure ``zarr.group`` uses writeable mode to fix issue with :issue:`1304`. - By :user:`Brandur Thorgrimsson ` :issue:`1354`. - -.. _release_2.14.1: - -2.14.1 ------- - -Documentation -~~~~~~~~~~~~~ - -* Fix API links. - By :user:`Josh Moore ` :issue:`1346`. - -* Fix unit tests which prevented the conda-forge release. - By :user:`Josh Moore ` :issue:`1348`. - -.. _release_2.14.0: - -2.14.0 ------- - -Major changes -~~~~~~~~~~~~~ - -* Improve Zarr V3 support, adding partial store read/write and storage transformers. - Add new features from the `v3 spec `_: - - * storage transformers - * `get_partial_values` and `set_partial_values` - * efficient `get_partial_values` implementation for `FSStoreV3` - * sharding storage transformer - - By :user:`Jonathan Striebel `; :issue:`1096`, :issue:`1111`. - -* N5 nows supports Blosc. - Remove warnings emitted when using N5Store or N5FSStore with a blosc-compressed array. - By :user:`Davis Bennett `; :issue:`1331`. - -Bug fixes -~~~~~~~~~ - -* Allow reading utf-8 encoded json files - By :user:`Nathan Zimmerberg ` :issue:`1308`. - -* Ensure contiguous data is give to ``FSStore``. Only copying if needed. - By :user:`Mads R. B. Kristensen ` :issue:`1285`. - -* NestedDirectoryStore.listdir now returns chunk keys with the correct '/' dimension_separator. - By :user:`Brett Graham ` :issue:`1334`. - -* N5Store/N5FSStore dtype returns zarr Stores readable dtype. - By :user:`Marwan Zouinkhi ` :issue:`1339`. - -.. _release_2.13.6: - -2.13.6 ------- - -Maintenance -~~~~~~~~~~~ - -* Bump gh-action-pypi-publish to 1.6.4. - By :user:`Josh Moore ` :issue:`1320`. - -.. _release_2.13.5: - -2.13.5 ------- - -Bug fixes -~~~~~~~~~ - -* Ensure ``zarr.create`` uses writeable mode to fix issue with :issue:`1304`. - By :user:`James Bourbeau ` :issue:`1309`. - -.. _release_2.13.4: - -2.13.4 ------- - -Appreciation -~~~~~~~~~~~~~ - -Special thanks to Outreachy participants for contributing to most of the -maintenance PRs. Please read the blog post summarising the contribution phase -and welcoming new Outreachy interns: -https://zarr.dev/blog/welcoming-outreachy-2022-interns/ - - -Enhancements -~~~~~~~~~~~~ - -* Handle fsspec.FSMap using FSStore store. - By :user:`Rafal Wojdyla ` :issue:`1304`. - -Bug fixes -~~~~~~~~~ - -* Fix bug that caused double counting of groups in ``groups()`` and ``group_keys()`` methods with V3 stores. - By :user:`Ryan Abernathey ` :issue:`1228`. - -* Remove unnecessary calling of `contains_array` for key that ended in `.array.json`. - By :user:`Joe Hamman ` :issue:`1149`. - -* Fix bug that caused double counting of groups in ``groups()`` and ``group_keys()`` - methods with V3 stores. - By :user:`Ryan Abernathey ` :issue:`1228`. - -Documentation -~~~~~~~~~~~~~ - -* Fix minor indexing errors in tutorial and specification examples of documentation. - By :user:`Kola Babalola ` :issue:`1277`. - -* Add `requirements_rtfd.txt` in `contributing.rst`. - By :user:`AWA BRANDON AWA ` :issue:`1243`. - -* Add documentation for find/findall using visit. - By :user:`Weddy Gikunda ` :issue:`1241`. - -* Refresh of the main landing page. - By :user:`Josh Moore ` :issue:`1173`. - -Maintenance -~~~~~~~~~~~ - -* Migrate to ``pyproject.toml`` and remove redundant infrastructure. - By :user:`Saransh Chopra ` :issue:`1158`. - -* Require ``setuptools`` 64.0.0+ - By :user:`Saransh Chopra ` :issue:`1193`. - -* Pin action versions (pypi-publish, setup-miniconda) for dependabot - By :user:`Saransh Chopra ` :issue:`1205`. - -* Remove ``tox`` support - By :user:`Saransh Chopra ` :issue:`1219`. - -* Add workflow to label PRs with "needs release notes". - By :user:`Saransh Chopra ` :issue:`1239`. - -* Simplify if/else statement. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1227`. - -* Get coverage up to 100%. - By :user:`John Kirkham ` :issue:`1264`. - -* Migrate coverage to ``pyproject.toml``. - By :user:`John Kirkham ` :issue:`1250`. - -* Use ``conda-incubator/setup-miniconda@v2.2.0``. - By :user:`John Kirkham ` :issue:`1263`. - -* Delete unused files. - By :user:`John Kirkham ` :issue:`1251`. - -* Skip labeller for bot PRs. - By :user:`Saransh Chopra ` :issue:`1271`. - -* Restore Flake8 configuration. - By :user:`John Kirkham ` :issue:`1249`. - -* Add missing newline at EOF. - By :user:`Dimitri Papadopoulos` :issue:`1253`. - -* Add `license_files` to `pyproject.toml`. - By :user:`John Kirkham ` :issue:`1247`. - -* Adding `pyupgrade` suggestions. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1225`. - -* Fixed some linting errors. - By :user:`Weddy Gikunda ` :issue:`1226`. - -* Added the link to main website in readthedocs sidebar. - By :user:`Stephanie_nkwatoh ` :issue:`1216`. - -* Remove redundant wheel dependency in `pyproject.toml`. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1233`. - -* Turned on `isloated_build` in `tox.ini` file. - By :user:`AWA BRANDON AWA ` :issue:`1210`. - -* Fixed `flake8` alert and avoid duplication of `Zarr Developers`. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1203`. - -* Bump to NumPy 1.20+ in `environment.yml`. - By :user:`John Kirkham ` :issue:`1201`. - -* Bump to NumPy 1.20 in `pyproject.toml`. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1192`. - -* Remove LGTM (`.lgtm.yml`) configuration file. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1191`. - -* Codespell will skip `fixture` in pre-commit. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1197`. - -* Add msgpack in `requirements_rtfd.txt`. - By :user:`Emmanuel Bolarinwa ` :issue:`1188`. - -* Added license to docs fixed a typo from `_spec_v2` to `_spec_v3`. - By :user:`AWA BRANDON AWA ` :issue:`1182`. - -* Fixed installation link in `README.md`. - By :user:`AWA BRANDON AWA ` :issue:`1177`. - -* Fixed typos in `installation.rst` and `release.rst`. - By :user:`Chizoba Nweke ` :issue:`1178`. - -* Set `docs/conf.py` language to `en`. - By :user:`AWA BRANDON AWA ` :issue:`1174`. - -* Added `installation.rst` to the docs. - By :user:`AWA BRANDON AWA ` :issue:`1170`. - -* Adjustment of year to `2015-2018` to `2015-2022` in the docs. - By :user:`Emmanuel Bolarinwa ` :issue:`1165`. - -* Updated `Forking the repository` section in `contributing.rst`. - By :user:`AWA BRANDON AWA ` :issue:`1171`. - -* Updated GitHub actions. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1134`. - -* Update web links: `http:// β†’ https://`. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1313`. - -.. _release_2.13.3: - -2.13.3 ------- - -* Improve performance of slice selections with steps by omitting chunks with no relevant - data. - By :user:`Richard Shaw ` :issue:`843`. - -.. _release_2.13.2: - -2.13.2 ------- - -* Fix test failure on conda-forge builds (again). - By :user:`Josh Moore `; see - `zarr-feedstock#65 `_. - -.. _release_2.13.1: - -2.13.1 ------- - -* Fix test failure on conda-forge builds. - By :user:`Josh Moore `; see - `zarr-feedstock#65 `_. - -.. _release_2.13.0: - -2.13.0 ------- - -Major changes -~~~~~~~~~~~~~ - -* **Support of alternative array classes** by introducing a new argument, - meta_array, that specifies the type/class of the underlying array. The - meta_array argument can be any class instance that can be used as the like - argument in NumPy (see `NEP 35 - `_). - enabling support for CuPy through, for example, the creation of a CuPy CPU - compressor. - By :user:`Mads R. B. Kristensen ` :issue:`934`. - -* **Remove support for Python 3.7** in concert with NumPy dependency. - By :user:`Davis Bennett ` :issue:`1067`. - -* **Zarr v3: add support for the default root path** rather than requiring - that all API users pass an explicit path. - By :user:`Gregory R. Lee ` :issue:`1085`, :issue:`1142`. - - -Bug fixes -~~~~~~~~~ - -* Remove/relax erroneous "meta" path check (**regression**). - By :user:`Gregory R. Lee ` :issue:`1123`. - -* Cast all attribute keys to strings (and issue deprecation warning). - By :user:`Mattia Almansi ` :issue:`1066`. - -* Fix bug in N5 storage that prevented arrays located in the root of the hierarchy from - bearing the `n5` keyword. Along with fixing this bug, new tests were added for N5 routines - that had previously been excluded from testing, and type annotations were added to the N5 codebase. - By :user:`Davis Bennett ` :issue:`1092`. - -* Fix bug in LRUEStoreCache in which the current size wasn't reset on invalidation. - By :user:`BGCMHou ` and :user:`Josh Moore ` :issue:`1076`, :issue:`1077`. - -* Remove erroneous check that disallowed array keys starting with "meta". - By :user:`Gregory R. Lee ` :issue:`1105`. - -Documentation -~~~~~~~~~~~~~ - -* Typo fixes to close quotes. By :user:`Pavithra Eswaramoorthy ` - -* Added copy button to documentation. - By :user:`Altay Sansal ` :issue:`1124`. - -Maintenance -~~~~~~~~~~~ - -* Simplify release docs. - By :user:`Josh Moore ` :issue:`1119`. - -* Pin werkzeug to prevent test hangs. - By :user:`Davis Bennett ` :issue:`1098`. - -* Fix a few DeepSource.io alerts - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`1080`. - -* Fix URLs. - By :user:`Dimitri Papadopoulos Orfanos `, :issue:`1074`. - -* Fix spelling. - By :user:`Dimitri Papadopoulos Orfanos `, :issue:`1073`. - -* Update GitHub issue templates with `YAML` format. - By :user:`Saransh Chopra ` :issue:`1079`. - -* Remove option to return None from _ensure_store. - By :user:`Gregory Lee ` :issue:`1068`. - -* Fix a typo of "integers". - By :user:`Richard Scott ` :issue:`1056`. - -.. _release_2.12.0: - -2.12.0 ------- - -Enhancements -~~~~~~~~~~~~ - -* **Add support for reading and writing Zarr V3.** The new `zarr._store.v3` - package has the necessary classes and functions for evaluating Zarr V3. - Since the format is not yet finalized, the classes and functions are not - automatically imported into the regular `zarr` name space. Setting the - `ZARR_V3_EXPERIMENTAL_API` environment variable will activate them. - By :user:`Gregory Lee `; :issue:`898`, :issue:`1006`, and :issue:`1007` - as well as by :user:`Josh Moore ` :issue:`1032`. - -* **Create FSStore from an existing fsspec filesystem**. If you have created - an fsspec filesystem outside of Zarr, you can now pass it as a keyword - argument to ``FSStore``. - By :user:`Ryan Abernathey `; :issue:`911`. - -* Add numpy encoder class for json.dumps - By :user:`Eric Prestat `; :issue:`933`. - -* Appending performance improvement to Zarr arrays, e.g., when writing to S3. - By :user:`hailiangzhang `; :issue:`1014`. - -* Add number encoder for ``json.dumps`` to support numpy integers in - ``chunks`` arguments. By :user:`Eric Prestat ` :issue:`697`. - -Bug fixes -~~~~~~~~~ - -* Fix bug that made it impossible to create an ``FSStore`` on unlistable filesystems - (e.g. some HTTP servers). - By :user:`Ryan Abernathey `; :issue:`993`. - - -Documentation -~~~~~~~~~~~~~ - -* Update resize doc to clarify surprising behavior. - By :user:`hailiangzhang `; :issue:`1022`. - -Maintenance -~~~~~~~~~~~ - -* Added Pre-commit configuration, incl. Yaml Check. - By :user:`Shivank Chaudhary `; :issue:`1015`, :issue:`1016`. - -* Fix URL to renamed file in Blosc repo. - By :user:`Andrew Thomas ` :issue:`1028`. - -* Activate Py 3.10 builds. - By :user:`Josh Moore ` :issue:`1027`. - -* Make all unignored zarr warnings errors. - By :user:`Josh Moore ` :issue:`1021`. - - -.. _release_2.11.3: - -2.11.3 ------- - -Bug fixes -~~~~~~~~~ - -* Fix missing case to fully revert change to default write_empty_chunks. - By :user:`Tom White `; :issue:`1005`. - - -.. _release_2.11.2: - -2.11.2 ------- - -Bug fixes -~~~~~~~~~ - -* Changes the default value of ``write_empty_chunks`` to ``True`` to prevent - unanticipated data losses when the data types do not have a proper default - value when empty chunks are read back in. - By :user:`Vyas Ramasubramani `; :issue:`965`, :issue:`1001`. - -.. _release_2.11.1: - -2.11.1 ------- - -Bug fixes -~~~~~~~~~ - -* Fix bug where indexing with a scalar numpy value returned a single-value array. - By :user:`Ben Jeffery ` :issue:`967`. - -* Removed `clobber` argument from `normalize_store_arg`. This enables to change - data within an opened consolidated group using mode `"r+"` (i.e region write). - By :user:`Tobias KΓΆlling ` :issue:`975`. - -.. _release_2.11.0: - -2.11.0 ------- - -Enhancements -~~~~~~~~~~~~ - -* **Sparse changes with performance impact!** One of the advantages of the Zarr - format is that it is sparse, which means that chunks with no data (more - precisely, with data equal to the fill value, which is usually 0) don't need - to be written to disk at all. They will simply be assumed to be empty at read - time. However, until this release, the Zarr library would write these empty - chunks to disk anyway. This changes in this version: a small performance - penalty at write time leads to significant speedups at read time and in - filesystem operations in the case of sparse arrays. To revert to the old - behavior, pass the argument ``write_empty_chunks=True`` to the array creation - function. By :user:`Juan Nunez-Iglesias `; :issue:`853` and - :user:`Davis Bennett `; :issue:`738`. - -* **Fancy indexing**. Zarr arrays now support NumPy-style fancy indexing with - arrays of integer coordinates. This is equivalent to using zarr.Array.vindex. - Mixing slices and integer arrays is not supported. - By :user:`Juan Nunez-Iglesias `; :issue:`725`. - -* **New base class**. This release of Zarr Python introduces a new - ``BaseStore`` class that all provided store classes implemented in Zarr - Python now inherit from. This is done as part of refactoring to enable future - support of the Zarr version 3 spec. Existing third-party stores that are a - MutableMapping (e.g. dict) can be converted to a new-style key/value store - inheriting from ``BaseStore`` by passing them as the argument to the new - ``zarr.storage.KVStore`` class. For backwards compatibility, various - higher-level array creation and convenience functions still accept plain - Python dicts or other mutable mappings for the ``store`` argument, but will - internally convert these to a ``KVStore``. - By :user:`Gregory Lee `; :issue:`839`, :issue:`789`, and :issue:`950`. - -* Allow to assign array ``fill_values`` and update metadata accordingly. - By :user:`Ryan Abernathey `, :issue:`662`. - -* Allow to update array fill_values - By :user:`Matthias Bussonnier ` :issue:`665`. - -Bug fixes -~~~~~~~~~ - -* Fix bug where the checksum of zipfiles is wrong - By :user:`Oren Watson ` :issue:`930`. - -* Fix consolidate_metadata with FSStore. - By :user:`Joe Hamman ` :issue:`916`. - -* Unguarded next inside generator. - By :user:`Dimitri Papadopoulos Orfanos ` :issue:`889`. - -Documentation -~~~~~~~~~~~~~ - -* Update docs creation of dev env. - By :user:`Ray Bell ` :issue:`921`. - -* Update docs to use ``python -m pytest``. - By :user:`Ray Bell ` :issue:`923`. - -* Fix versionadded tag in zarr.core.Array docstring. - By :user:`Juan Nunez-Iglesias ` :issue:`852`. - -* Doctest seem to be stricter now, updating tostring() to tobytes(). - By :user:`John Kirkham ` :issue:`907`. - -* Minor doc fix. - By :user:`Mads R. B. Kristensen ` :issue:`937`. - -Maintenance -~~~~~~~~~~~ - -* Upgrade MongoDB in test env. - By :user:`Joe Hamman ` :issue:`939`. - -* Pass dimension_separator on fixture generation. - By :user:`Josh Moore ` :issue:`858`. - -* Activate Python 3.9 in GitHub Actions. - By :user:`Josh Moore ` :issue:`859`. - -* Drop shortcut ``fsspec[s3]`` for dependency. - By :user:`Josh Moore ` :issue:`920`. - -* and a swath of code-linting improvements by :user:`Dimitri Papadopoulos Orfanos `: - - - Unnecessary comprehension (:issue:`899`) - - - Unnecessary ``None`` provided as default (:issue:`900`) - - - use an if ``expression`` instead of `and`/`or` (:issue:`888`) - - - Remove unnecessary literal (:issue:`891`) - - - Decorate a few method with `@staticmethod` (:issue:`885`) - - - Drop unneeded ``return`` (:issue:`884`) - - - Drop explicit ``object`` inheritance from ``class``-es (:issue:`886`) - - - Unnecessary comprehension (:issue:`883`) - - - Codespell configuration (:issue:`882`) - - - Fix typos found by codespell (:issue:`880`) - - - Proper C-style formatting for integer (:issue:`913`) - - - Add LGTM.com / DeepSource.io configuration files (:issue:`909`) - -.. _release_2.10.3: - -2.10.3 ------- - -Bug fixes -~~~~~~~~~ - -* N5 keywords now emit UserWarning instead of raising a ValueError. - By :user:`Boaz Mohar `; :issue:`860`. - -* blocks_to_decompress not used in read_part function. - By :user:`Boaz Mohar `; :issue:`861`. - -* defines blocksize for array, updates hexdigest values. - By :user:`Andrew Fulton `; :issue:`867`. - -* Fix test failure on Debian and conda-forge builds. - By :user:`Josh Moore `; :issue:`871`. - -.. _release_2.10.2: - -2.10.2 ------- - -Bug fixes -~~~~~~~~~ - -* Fix NestedDirectoryStore datasets without dimension_separator metadata. - By :user:`Josh Moore `; :issue:`850`. - -.. _release_2.10.1: - -2.10.1 ------- - -Bug fixes -~~~~~~~~~ - -* Fix regression by setting normalize_keys=False in fsstore constructor. - By :user:`Davis Bennett `; :issue:`842`. - -.. _release_2.10.0: - -2.10.0 ------- - -Enhancements -~~~~~~~~~~~~ - -* Add N5FSStore. - By :user:`Davis Bennett `; :issue:`793`. - -Bug fixes -~~~~~~~~~ - -* Ignore None dim_separators in save_array. - By :user:`Josh Moore `; :issue:`831`. - -.. _release_2.9.5: - -2.9.5 ------ - -Bug fixes -~~~~~~~~~ - -* Fix FSStore.listdir behavior for nested directories. - By :user:`Gregory Lee `; :issue:`802`. - -.. _release_2.9.4: - -2.9.4 ------ - -Bug fixes -~~~~~~~~~ - -* Fix structured arrays that contain objects - By :user: `Attila Bergou `; :issue: `806` - -.. _release_2.9.3: - -2.9.3 ------ - -Maintenance -~~~~~~~~~~~ - -* Mark the fact that some tests that require ``fsspec``, without compromising the code coverage score. - By :user:`Ben Williams `; :issue:`823`. - -* Only inspect alternate node type if desired isn't present. - By :user:`Trevor Manz `; :issue:`696`. - -.. _release_2.9.2: - -2.9.2 ------ - -Maintenance -~~~~~~~~~~~ - -* Correct conda-forge deployment of Zarr by fixing some Zarr tests. - By :user:`Ben Williams `; :issue:`821`. - -.. _release_2.9.1: - -2.9.1 ------ - -Maintenance -~~~~~~~~~~~ - -* Correct conda-forge deployment of Zarr. - By :user:`Josh Moore `; :issue:`819`. - -.. _release_2.9.0: - -2.9.0 ------ - -This release of Zarr Python is the first release of Zarr to not support Python 3.6. - -Enhancements -~~~~~~~~~~~~ - -* Update ABSStore for compatibility with newer `azure.storage.blob`. - By :user:`Tom Augspurger `; :issue:`759`. - -* Pathlib support. - By :user:`Chris Barnes `; :issue:`768`. - -Documentation -~~~~~~~~~~~~~ - -* Clarify that arbitrary key/value pairs are OK for attributes. - By :user:`Stephan Hoyer `; :issue:`751`. - -* Clarify how to manually convert a DirectoryStore to a ZipStore. - By :user:`pmav99 `; :issue:`763`. - -Bug fixes -~~~~~~~~~ - -* Fix dimension_separator support. - By :user:`Josh Moore `; :issue:`775`. - -* Extract ABSStore to zarr._storage.absstore. - By :user:`Josh Moore `; :issue:`781`. - -* avoid NumPy 1.21.0 due to https://github.com/numpy/numpy/issues/19325 - By :user:`Gregory Lee `; :issue:`791`. - -Maintenance -~~~~~~~~~~~ - -* Drop 3.6 builds. - By :user:`Josh Moore `; :issue:`774`, :issue:`778`. - -* Fix build with Sphinx 4. - By :user:`Elliott Sales de Andrade `; :issue:`799`. - -* TST: add missing assert in test_hexdigest. - By :user:`Gregory Lee `; :issue:`801`. - -.. _release_2.8.3: - -2.8.3 ------ - -Bug fixes -~~~~~~~~~ - -* FSStore: default to normalize_keys=False - By :user:`Josh Moore `; :issue:`755`. -* ABSStore: compatibility with ``azure.storage.python>=12`` - By :user:`Tom Augspurger `; :issue:`618` - - -.. _release_2.8.2: - -2.8.2 ------ - -Documentation -~~~~~~~~~~~~~ - -* Add section on rechunking to tutorial - By :user:`David Baddeley `; :issue:`730`. - -Bug fixes -~~~~~~~~~ - -* Expand FSStore tests and fix implementation issues - By :user:`Davis Bennett `; :issue:`709`. - -Maintenance -~~~~~~~~~~~ - -* Updated ipytree warning for jlab3 - By :user:`Ian Hunt-Isaak `; :issue:`721`. - -* b170a48a - (issue-728, copy-nested) Updated ipytree warning for jlab3 (#721) (3 weeks ago) -* Activate dependabot - By :user:`Josh Moore `; :issue:`734`. - -* Update Python classifiers (Zarr is stable!) - By :user:`Josh Moore `; :issue:`731`. - -.. _release_2.8.1: - -2.8.1 ------ - -Bug fixes -~~~~~~~~~ - -* raise an error if create_dataset's dimension_separator is inconsistent - By :user:`Gregory R. Lee `; :issue:`724`. - -.. _release_2.8.0: - -2.8.0 ------ - -V2 Specification Update -~~~~~~~~~~~~~~~~~~~~~~~ - -* Introduce optional dimension_separator .zarray key for nested chunks. - By :user:`Josh Moore `; :issue:`715`, :issue:`716`. - -.. _release_2.7.1: - -2.7.1 ------ - -Bug fixes -~~~~~~~~~ - -* Update Array to respect FSStore's key_separator (#718) - By :user:`Gregory R. Lee `; :issue:`718`. - -.. _release_2.7.0: - -2.7.0 ------ - -Enhancements -~~~~~~~~~~~~ - -* Start stop for iterator (`islice()`) - By :user:`Sebastian Grill `; :issue:`621`. - -* Add capability to partially read and decompress chunks - By :user:`Andrew Fulton `; :issue:`667`. - -Bug fixes -~~~~~~~~~ - -* Make DirectoryStore __setitem__ resilient against antivirus file locking - By :user:`Eric Younkin `; :issue:`698`. - -* Compare test data's content generally - By :user:`John Kirkham `; :issue:`436`. - -* Fix dtype usage in zarr/meta.py - By :user:`Josh Moore `; :issue:`700`. - -* Fix FSStore key_seperator usage - By :user:`Josh Moore `; :issue:`669`. - -* Simplify text handling in DB Store - By :user:`John Kirkham `; :issue:`670`. - -* GitHub Actions migration - By :user:`Matthias Bussonnier `; - :issue:`641`, :issue:`671`, :issue:`674`, :issue:`676`, :issue:`677`, :issue:`678`, - :issue:`679`, :issue:`680`, :issue:`682`, :issue:`684`, :issue:`685`, :issue:`686`, - :issue:`687`, :issue:`695`, :issue:`706`. - -.. _release_2.6.1: - -2.6.1 ------ - -* Minor build fix - By :user:`Matthias Bussonnier `; :issue:`666`. - -.. _release_2.6.0: - -2.6.0 ------ - -This release of Zarr Python is the first release of Zarr to not support Python 3.5. - -* End Python 3.5 support. - By :user:`Chris Barnes `; :issue:`602`. - -* Fix ``open_group/open_array`` to allow opening of read-only store with - ``mode='r'`` :issue:`269` - -* Add `Array` tests for FSStore. - By :user:`Andrew Fulton `; :issue: `644`. - -* fix a bug in which ``attrs`` would not be copied on the root when using ``copy_all``; :issue:`613` - -* Fix ``FileNotFoundError`` with dask/s3fs :issue:`649` - -* Fix flaky fixture in test_storage.py :issue:`652` - -* Fix FSStore getitems fails with arrays that have a 0 length shape dimension :issue:`644` - -* Use async to fetch/write result concurrently when possible. :issue:`536`, See `this comment - `_ for some performance analysis - showing order of magnitude faster response in some benchmark. - -See `this link `_ -for the full list of closed and merged PR tagged with the 2.6 milestone. - -* Add ability to partially read and decompress arrays, see :issue:`667`. It is - only available to chunks stored using fsspec and using Blosc as a compressor. - - For certain analysis case when only a small portion of chunks is needed it can - be advantageous to only access and decompress part of the chunks. Doing - partial read and decompression add high latency to many of the operation so - should be used only when the subset of the data is small compared to the full - chunks and is stored contiguously (that is to say either last dimensions for C - layout, firsts for F). Pass ``partial_decompress=True`` as argument when - creating an ``Array``, or when using ``open_array``. No option exists yet to - apply partial read and decompress on a per-operation basis. - -.. _release_2.5.0: - -2.5.0 ------ - -This release will be the last to support Python 3.5, next version of Zarr will be Python 3.6+. - -* `DirectoryStore` now uses `os.scandir`, which should make listing large store - faster, :issue:`563` - -* Remove a few remaining Python 2-isms. - By :user:`Poruri Sai Rahul `; :issue:`393`. - -* Fix minor bug in `N5Store`. - By :user:`gsakkis`, :issue:`550`. - -* Improve error message in Jupyter when trying to use the ``ipytree`` widget - without ``ipytree`` installed. - By :user:`Zain Patel `; :issue:`537` - -* Add typing information to many of the core functions :issue:`589` - -* Explicitly close stores during testing. - By :user:`Elliott Sales de Andrade `; :issue:`442` - -* Many of the convenience functions to emit errors (``err_*`` from - ``zarr.errors`` have been replaced by ``ValueError`` subclasses. The corresponding - ``err_*`` function have been removed. :issue:`590`, :issue:`614`) - -* Improve consistency of terminology regarding arrays and datasets in the - documentation. - By :user:`Josh Moore `; :issue:`571`. - -* Added support for generic URL opening by ``fsspec``, where the URLs have the - form "protocol://[server]/path" or can be chained URls with "::" separators. - The additional argument ``storage_options`` is passed to the backend, see - the ``fsspec`` docs. - By :user:`Martin Durant `; :issue:`546` - -* Added support for fetching multiple items via ``getitems`` method of a - store, if it exists. This allows for concurrent fetching of data blocks - from stores that implement this; presently HTTP, S3, GCS. Currently only - applies to reading. - By :user:`Martin Durant `; :issue:`606` - -* Efficient iteration expanded with option to pass start and stop index via - ``array.islice``. - By :user:`Sebastian Grill `, :issue:`615`. - -.. _release_2.4.0: - -2.4.0 ------ - -Enhancements -~~~~~~~~~~~~ - -* Add key normalization option for ``DirectoryStore``, ``NestedDirectoryStore``, - ``TempStore``, and ``N5Store``. - By :user:`James Bourbeau `; :issue:`459`. - -* Add ``recurse`` keyword to ``Group.array_keys`` and ``Group.arrays`` methods. - By :user:`James Bourbeau `; :issue:`458`. - -* Use uniform chunking for all dimensions when specifying ``chunks`` as an integer. - Also adds support for specifying ``-1`` to chunk across an entire dimension. - By :user:`James Bourbeau `; :issue:`456`. - -* Rename ``DictStore`` to ``MemoryStore``. - By :user:`James Bourbeau `; :issue:`455`. - -* Rewrite ``.tree()`` pretty representation to use ``ipytree``. - Allows it to work in both the Jupyter Notebook and JupyterLab. - By :user:`John Kirkham `; :issue:`450`. - -* Do not rename Blosc parameters in n5 backend and add `blocksize` parameter, - compatible with n5-blosc. By :user:`axtimwalde`, :issue:`485`. - -* Update ``DirectoryStore`` to create files with more permissive permissions. - By :user:`Eduardo Gonzalez ` and :user:`James Bourbeau `; :issue:`493` - -* Use ``math.ceil`` for scalars. - By :user:`John Kirkham `; :issue:`500`. - -* Ensure contiguous data using ``astype``. - By :user:`John Kirkham `; :issue:`513`. - -* Refactor out ``_tofile``/``_fromfile`` from ``DirectoryStore``. - By :user:`John Kirkham `; :issue:`503`. - -* Add ``__enter__``/``__exit__`` methods to ``Group`` for ``h5py.File`` compatibility. - By :user:`Chris Barnes `; :issue:`509`. - -Bug fixes -~~~~~~~~~ - -* Fix Sqlite Store Wrong Modification. - By :user:`Tommy Tran `; :issue:`440`. - -* Add intermediate step (using ``zipfile.ZipInfo`` object) to write - inside ``ZipStore`` to solve too restrictive permission issue. - By :user:`Raphael Dussin `; :issue:`505`. - -* Fix '/' prepend bug in ``ABSStore``. - By :user:`Shikhar Goenka `; :issue:`525`. - -Documentation -~~~~~~~~~~~~~ -* Fix hyperlink in ``README.md``. - By :user:`Anderson Banihirwe `; :issue:`531`. - -* Replace "nuimber" with "number". - By :user:`John Kirkham `; :issue:`512`. - -* Fix azure link rendering in tutorial. - By :user:`James Bourbeau `; :issue:`507`. - -* Update ``README`` file to be more detailed. - By :user:`Zain Patel `; :issue:`495`. - -* Import blosc from numcodecs in tutorial. - By :user:`James Bourbeau `; :issue:`491`. - -* Adds logo to docs. - By :user:`James Bourbeau `; :issue:`462`. - -* Fix N5 link in tutorial. - By :user:`James Bourbeau `; :issue:`480`. - -* Fix typo in code snippet. - By :user:`Joe Jevnik `; :issue:`461`. - -* Fix URLs to point to zarr-python - By :user:`John Kirkham `; :issue:`453`. - -Maintenance -~~~~~~~~~~~ - -* Add documentation build to CI. - By :user:`James Bourbeau `; :issue:`516`. - -* Use ``ensure_ndarray`` in a few more places. - By :user:`John Kirkham `; :issue:`506`. - -* Support Python 3.8. - By :user:`John Kirkham `; :issue:`499`. - -* Require Numcodecs 0.6.4+ to use text handling functionality from it. - By :user:`John Kirkham `; :issue:`497`. - -* Updates tests to use ``pytest.importorskip``. - By :user:`James Bourbeau `; :issue:`492` - -* Removed support for Python 2. - By :user:`jhamman`; :issue:`393`, :issue:`470`. - -* Upgrade dependencies in the test matrices and resolve a - compatibility issue with testing against the Azure Storage - Emulator. By :user:`alimanfoo`; :issue:`468`, :issue:`467`. - -* Use ``unittest.mock`` on Python 3. - By :user:`Elliott Sales de Andrade `; :issue:`426`. - -* Drop ``decode`` from ``ConsolidatedMetadataStore``. - By :user:`John Kirkham `; :issue:`452`. - - -.. _release_2.3.2: - -2.3.2 ------ - -Enhancements -~~~~~~~~~~~~ - -* Use ``scandir`` in ``DirectoryStore``'s ``getsize`` method. - By :user:`John Kirkham `; :issue:`431`. - -Bug fixes -~~~~~~~~~ - -* Add and use utility functions to simplify reading and writing JSON. - By :user:`John Kirkham `; :issue:`429`, :issue:`430`. - -* Fix ``collections``'s ``DeprecationWarning``\ s. - By :user:`John Kirkham `; :issue:`432`. - -* Fix tests on big endian machines. - By :user:`Elliott Sales de Andrade `; :issue:`427`. - - -.. _release_2.3.1: - -2.3.1 ------ - -Bug fixes -~~~~~~~~~ - -* Makes ``azure-storage-blob`` optional for testing. - By :user:`John Kirkham `; :issue:`419`, :issue:`420`. - - -.. _release_2.3.0: - -2.3.0 ------ - -Enhancements -~~~~~~~~~~~~ - -* New storage backend, backed by Azure Blob Storage, class :class:`zarr.storage.ABSStore`. - All data is stored as block blobs. By :user:`Shikhar Goenka `, - :user:`Tim Crone ` and :user:`Zain Patel `; :issue:`345`. - -* Add "consolidated" metadata as an experimental feature: use - :func:`zarr.convenience.consolidate_metadata` to copy all metadata from the various - metadata keys within a dataset hierarchy under a single key, and - :func:`zarr.convenience.open_consolidated` to use this single key. This can greatly - cut down the number of calls to the storage backend, and so remove a lot of overhead - for reading remote data. - By :user:`Martin Durant `, :user:`Alistair Miles `, - :user:`Ryan Abernathey `, :issue:`268`, :issue:`332`, :issue:`338`. - -* Support has been added for structured arrays with sub-array shape and/or nested fields. By - :user:`Tarik Onalan `, :issue:`111`, :issue:`296`. - -* Adds the SQLite-backed :class:`zarr.storage.SQLiteStore` class enabling an - SQLite database to be used as the backing store for an array or group. - By :user:`John Kirkham `, :issue:`368`, :issue:`365`. - -* Efficient iteration over arrays by decompressing chunkwise. - By :user:`Jerome Kelleher `, :issue:`398`, :issue:`399`. - -* Adds the Redis-backed :class:`zarr.storage.RedisStore` class enabling a - Redis database to be used as the backing store for an array or group. - By :user:`Joe Hamman `, :issue:`299`, :issue:`372`. - -* Adds the MongoDB-backed :class:`zarr.storage.MongoDBStore` class enabling a - MongoDB database to be used as the backing store for an array or group. - By :user:`Noah D Brenowitz `, :user:`Joe Hamman `, - :issue:`299`, :issue:`372`, :issue:`401`. - -* **New storage class for N5 containers**. The :class:`zarr.n5.N5Store` has been - added, which uses :class:`zarr.storage.NestedDirectoryStore` to support - reading and writing from and to N5 containers. - By :user:`Jan Funke ` and :user:`John Kirkham `. - -Bug fixes -~~~~~~~~~ - -* The implementation of the :class:`zarr.storage.DirectoryStore` class has been modified to - ensure that writes are atomic and there are no race conditions where a chunk might appear - transiently missing during a write operation. By :user:`sbalmer `, :issue:`327`, - :issue:`263`. - -* Avoid raising in :class:`zarr.storage.DirectoryStore`'s ``__setitem__`` when file already exists. - By :user:`Justin Swaney `, :issue:`272`, :issue:`318`. - -* The required version of the `Numcodecs`_ package has been upgraded - to 0.6.2, which has enabled some code simplification and fixes a failing test involving - msgpack encoding. By :user:`John Kirkham `, :issue:`361`, :issue:`360`, :issue:`352`, - :issue:`355`, :issue:`324`. - -* Failing tests related to pickling/unpickling have been fixed. By :user:`Ryan Williams `, - :issue:`273`, :issue:`308`. - -* Corrects handling of ``NaT`` in ``datetime64`` and ``timedelta64`` in various - compressors (by :user:`John Kirkham `; :issue:`344`). - -* Ensure ``DictStore`` contains only ``bytes`` to facilitate comparisons and protect against writes. - By :user:`John Kirkham `, :issue:`350`. - -* Test and fix an issue (w.r.t. fill values) when storing complex data to ``Array``. - By :user:`John Kirkham `, :issue:`363`. - -* Always use a ``tuple`` when indexing a NumPy ``ndarray``. - By :user:`John Kirkham `, :issue:`376`. - -* Ensure when ``Array`` uses a ``dict``-based chunk store that it only contains - ``bytes`` to facilitate comparisons and protect against writes. Drop the copy - for the no filter/compressor case as this handles that case. - By :user:`John Kirkham `, :issue:`359`. - -Maintenance -~~~~~~~~~~~ - -* Simplify directory creation and removal in ``DirectoryStore.rename``. - By :user:`John Kirkham `, :issue:`249`. - -* CI and test environments have been upgraded to include Python 3.7, drop Python 3.4, and - upgrade all pinned package requirements. :user:`Alistair Miles `, :issue:`308`. - -* Start using pyup.io to maintain dependencies. - :user:`Alistair Miles `, :issue:`326`. - -* Configure flake8 line limit generally. - :user:`John Kirkham `, :issue:`335`. - -* Add missing coverage pragmas. - :user:`John Kirkham `, :issue:`343`, :issue:`355`. - -* Fix missing backslash in docs. - :user:`John Kirkham `, :issue:`254`, :issue:`353`. - -* Include tests for stores' ``popitem`` and ``pop`` methods. - By :user:`John Kirkham `, :issue:`378`, :issue:`380`. - -* Include tests for different compressors, endianness, and attributes. - By :user:`John Kirkham `, :issue:`378`, :issue:`380`. - -* Test validity of stores' contents. - By :user:`John Kirkham `, :issue:`359`, :issue:`408`. - - -.. _release_2.2.0: - -2.2.0 ------ - -Enhancements -~~~~~~~~~~~~ - -* **Advanced indexing**. The ``Array`` class has several new methods and - properties that enable a selection of items in an array to be retrieved or - updated. See the :ref:`tutorial_indexing` tutorial section for more - information. There is also a `notebook - `_ - with extended examples and performance benchmarks. :issue:`78`, :issue:`89`, - :issue:`112`, :issue:`172`. - -* **New package for compressor and filter codecs**. The classes previously - defined in the :mod:`zarr.codecs` module have been factored out into a - separate package called `Numcodecs`_. The `Numcodecs`_ package also includes - several new codec classes not previously available in Zarr, including - compressor codecs for Zstd and LZ4. This change is backwards-compatible with - existing code, as all codec classes defined by Numcodecs are imported into the - :mod:`zarr.codecs` namespace. However, it is recommended to import codecs from - the new package, see the tutorial sections on :ref:`tutorial_compress` and - :ref:`tutorial_filters` for examples. With contributions by - :user:`John Kirkham `; :issue:`74`, :issue:`102`, :issue:`120`, - :issue:`123`, :issue:`139`. - -* **New storage class for DBM-style databases**. The - :class:`zarr.storage.DBMStore` class enables any DBM-style database such as gdbm, - ndbm or Berkeley DB, to be used as the backing store for an array or group. See the - tutorial section on :ref:`tutorial_storage` for some examples. :issue:`133`, - :issue:`186`. - -* **New storage class for LMDB databases**. The :class:`zarr.storage.LMDBStore` class - enables an LMDB "Lightning" database to be used as the backing store for an array or - group. :issue:`192`. - -* **New storage class using a nested directory structure for chunk files**. The - :class:`zarr.storage.NestedDirectoryStore` has been added, which is similar to - the existing :class:`zarr.storage.DirectoryStore` class but nests chunk files - for multidimensional arrays into sub-directories. :issue:`155`, :issue:`177`. - -* **New tree() method for printing hierarchies**. The ``Group`` class has a new - :func:`zarr.hierarchy.Group.tree` method which enables a tree representation of - a group hierarchy to be printed. Also provides an interactive tree - representation when used within a Jupyter notebook. See the - :ref:`tutorial_diagnostics` tutorial section for examples. By - :user:`John Kirkham `; :issue:`82`, :issue:`140`, :issue:`184`. - -* **Visitor API**. The ``Group`` class now implements the h5py visitor API, see - docs for the :func:`zarr.hierarchy.Group.visit`, - :func:`zarr.hierarchy.Group.visititems` and - :func:`zarr.hierarchy.Group.visitvalues` methods. By - :user:`John Kirkham `, :issue:`92`, :issue:`122`. - -* **Viewing an array as a different dtype**. The ``Array`` class has a new - :func:`zarr.core.Array.astype` method, which is a convenience that enables an - array to be viewed as a different dtype. By :user:`John Kirkham `, - :issue:`94`, :issue:`96`. - -* **New open(), save(), load() convenience functions**. The function - :func:`zarr.convenience.open` provides a convenient way to open a persistent - array or group, using either a ``DirectoryStore`` or ``ZipStore`` as the backing - store. The functions :func:`zarr.convenience.save` and - :func:`zarr.convenience.load` are also available and provide a convenient way to - save an entire NumPy array to disk and load back into memory later. See the - tutorial section :ref:`tutorial_persist` for examples. :issue:`104`, - :issue:`105`, :issue:`141`, :issue:`181`. - -* **IPython completions**. The ``Group`` class now implements ``__dir__()`` and - ``_ipython_key_completions_()`` which enables tab-completion for group members - to be used in any IPython interactive environment. :issue:`170`. - -* **New info property; changes to __repr__**. The ``Group`` and - ``Array`` classes have a new ``info`` property which can be used to print - diagnostic information, including compression ratio where available. See the - tutorial section on :ref:`tutorial_diagnostics` for examples. The string - representation (``__repr__``) of these classes has been simplified to ensure - it is cheap and quick to compute in all circumstances. :issue:`83`, - :issue:`115`, :issue:`132`, :issue:`148`. - -* **Chunk options**. When creating an array, ``chunks=False`` can be specified, - which will result in an array with a single chunk only. Alternatively, - ``chunks=True`` will trigger an automatic chunk shape guess. See - :ref:`tutorial_chunks` for more on the ``chunks`` parameter. :issue:`106`, - :issue:`107`, :issue:`183`. - -* **Zero-dimensional arrays** and are now supported; by - :user:`Prakhar Goel `, :issue:`154`, :issue:`161`. - -* **Arrays with one or more zero-length dimensions** are now fully supported; by - :user:`Prakhar Goel `, :issue:`150`, :issue:`154`, :issue:`160`. - -* **The .zattrs key is now optional** and will now only be created when the first - custom attribute is set; :issue:`121`, :issue:`200`. - -* **New Group.move() method** supports moving a sub-group or array to a different - location within the same hierarchy. By :user:`John Kirkham `, - :issue:`191`, :issue:`193`, :issue:`196`. - -* **ZipStore is now thread-safe**; :issue:`194`, :issue:`192`. - -* **New Array.hexdigest() method** computes an ``Array``'s hash with ``hashlib``. - By :user:`John Kirkham `, :issue:`98`, :issue:`203`. - -* **Improved support for object arrays**. In previous versions of Zarr, - creating an array with ``dtype=object`` was possible but could under certain - circumstances lead to unexpected errors and/or segmentation faults. To make it easier - to properly configure an object array, a new ``object_codec`` parameter has been - added to array creation functions. See the tutorial section on :ref:`tutorial_objects` - for more information and examples. Also, runtime checks have been added in both Zarr - and Numcodecs so that segmentation faults are no longer possible, even with a badly - configured array. This API change is backwards compatible and previous code that created - an object array and provided an object codec via the ``filters`` parameter will - continue to work, however a warning will be raised to encourage use of the - ``object_codec`` parameter. :issue:`208`, :issue:`212`. - -* **Added support for datetime64 and timedelta64 data types**; - :issue:`85`, :issue:`215`. - -* **Array and group attributes are now cached by default** to improve performance with - slow stores, e.g., stores accessing data via the network; :issue:`220`, :issue:`218`, - :issue:`204`. - -* **New LRUStoreCache class**. The class :class:`zarr.storage.LRUStoreCache` has been - added and provides a means to locally cache data in memory from a store that may be - slow, e.g., a store that retrieves data from a remote server via the network; - :issue:`223`. - -* **New copy functions**. The new functions :func:`zarr.convenience.copy` and - :func:`zarr.convenience.copy_all` provide a way to copy groups and/or arrays - between HDF5 and Zarr, or between two Zarr groups. The - :func:`zarr.convenience.copy_store` provides a more efficient way to copy - data directly between two Zarr stores. :issue:`87`, :issue:`113`, - :issue:`137`, :issue:`217`. - -Bug fixes -~~~~~~~~~ - -* Fixed bug where ``read_only`` keyword argument was ignored when creating an - array; :issue:`151`, :issue:`179`. - -* Fixed bugs when using a ``ZipStore`` opened in 'w' mode; :issue:`158`, - :issue:`182`. - -* Fill values can now be provided for fixed-length string arrays; :issue:`165`, - :issue:`176`. - -* Fixed a bug where the number of chunks initialized could be counted - incorrectly; :issue:`97`, :issue:`174`. - -* Fixed a bug related to the use of an ellipsis (...) in indexing statements; - :issue:`93`, :issue:`168`, :issue:`172`. - -* Fixed a bug preventing use of other integer types for indexing; :issue:`143`, - :issue:`147`. - -Documentation -~~~~~~~~~~~~~ - -* Some changes have been made to the Zarr Specification v2 document to clarify - ambiguities and add some missing information. These changes do not break compatibility - with any of the material as previously implemented, and so the changes have been made - in-place in the document without incrementing the document version number. See the - section on changes in the specification document for more information. -* A new :ref:`tutorial_indexing` section has been added to the tutorial. -* A new :ref:`tutorial_strings` section has been added to the tutorial - (:issue:`135`, :issue:`175`). -* The :ref:`tutorial_chunks` tutorial section has been reorganised and updated. -* The :ref:`tutorial_persist` and :ref:`tutorial_storage` tutorial sections have - been updated with new examples (:issue:`100`, :issue:`101`, :issue:`103`). -* A new tutorial section on :ref:`tutorial_pickle` has been added (:issue:`91`). -* A new tutorial section on :ref:`tutorial_datetime` has been added. -* A new tutorial section on :ref:`tutorial_diagnostics` has been added. -* The tutorial sections on :ref:`tutorial_sync` and :ref:`tutorial_tips_blosc` have been - updated to provide information about how to avoid program hangs when using the Blosc - compressor with multiple processes (:issue:`199`, :issue:`201`). - -Maintenance -~~~~~~~~~~~ - -* A data fixture has been included in the test suite to ensure data format - compatibility is maintained; :issue:`83`, :issue:`146`. -* The test suite has been migrated from nosetests to pytest; :issue:`189`, :issue:`225`. -* Various continuous integration updates and improvements; :issue:`118`, :issue:`124`, - :issue:`125`, :issue:`126`, :issue:`109`, :issue:`114`, :issue:`171`. -* Bump numcodecs dependency to 0.5.3, completely remove nose dependency, :issue:`237`. -* Fix compatibility issues with NumPy 1.14 regarding fill values for structured arrays, - :issue:`222`, :issue:`238`, :issue:`239`. - -Acknowledgments -~~~~~~~~~~~~~~~ - -Code was contributed to this release by :user:`Alistair Miles `, :user:`John -Kirkham ` and :user:`Prakhar Goel `. - -Documentation was contributed to this release by :user:`Mamy Ratsimbazafy ` -and :user:`Charles Noyes `. - -Thank you to :user:`John Kirkham `, :user:`Stephan Hoyer `, -:user:`Francesc Alted `, and :user:`Matthew Rocklin ` for code -reviews and/or comments on pull requests. - -.. _release_2.1.4: - -2.1.4 ------ - -* Resolved an issue where calling ``hasattr`` on a ``Group`` object erroneously - returned a ``KeyError``. By :user:`Vincent Schut `; :issue:`88`, - :issue:`95`. - -.. _release_2.1.3: - -2.1.3 ------ - -* Resolved an issue with :func:`zarr.creation.array` where dtype was given as - None (:issue:`80`). - -.. _release_2.1.2: - -2.1.2 ------ - -* Resolved an issue when no compression is used and chunks are stored in memory - (:issue:`79`). - -.. _release_2.1.1: - -2.1.1 ------ - -Various minor improvements, including: ``Group`` objects support member access -via dot notation (``__getattr__``); fixed metadata caching for ``Array.shape`` -property and derivatives; added ``Array.ndim`` property; fixed -``Array.__array__`` method arguments; fixed bug in pickling ``Array`` state; -fixed bug in pickling ``ThreadSynchronizer``. - -.. _release_2.1.0: - -2.1.0 ------ - -* Group objects now support member deletion via ``del`` statement - (:issue:`65`). -* Added :class:`zarr.storage.TempStore` class for convenience to provide - storage via a temporary directory - (:issue:`59`). -* Fixed performance issues with :class:`zarr.storage.ZipStore` class - (:issue:`66`). -* The Blosc extension has been modified to return bytes instead of array - objects from compress and decompress function calls. This should - improve compatibility and also provides a small performance increase for - compressing high compression ratio data - (:issue:`55`). -* Added ``overwrite`` keyword argument to array and group creation methods - on the :class:`zarr.hierarchy.Group` class - (:issue:`71`). -* Added ``cache_metadata`` keyword argument to array creation methods. -* The functions :func:`zarr.creation.open_array` and - :func:`zarr.hierarchy.open_group` now accept any store as first argument - (:issue:`56`). - -.. _release_2.0.1: - -2.0.1 ------ - -The bundled Blosc library has been upgraded to version 1.11.1. - -.. _release_2.0.0: - -2.0.0 ------ - -Hierarchies -~~~~~~~~~~~ - -Support has been added for organizing arrays into hierarchies via groups. See -the tutorial section on :ref:`tutorial_groups` and the :mod:`zarr.hierarchy` -API docs for more information. - -Filters -~~~~~~~ - -Support has been added for configuring filters to preprocess chunk data prior -to compression. See the tutorial section on :ref:`tutorial_filters` and the -:mod:`zarr.codecs` API docs for more information. - -Other changes -~~~~~~~~~~~~~ - -To accommodate support for hierarchies and filters, the Zarr metadata format -has been modified. See the :ref:`spec_v2` for more information. To migrate an -array stored using Zarr version 1.x, use the :func:`zarr.storage.migrate_1to2` -function. - -The bundled Blosc library has been upgraded to version 1.11.0. - -Acknowledgments -~~~~~~~~~~~~~~~ - -Thanks to :user:`Matthew Rocklin `, :user:`Stephan Hoyer ` and -:user:`Francesc Alted ` for contributions and comments. - -.. _release_1.1.0: - -1.1.0 ------ - -* The bundled Blosc library has been upgraded to version 1.10.0. The 'zstd' - internal compression library is now available within Blosc. See the tutorial - section on :ref:`tutorial_compress` for an example. -* When using the Blosc compressor, the default internal compression library - is now 'lz4'. -* The default number of internal threads for the Blosc compressor has been - increased to a maximum of 8 (previously 4). -* Added convenience functions :func:`zarr.blosc.list_compressors` and - :func:`zarr.blosc.get_nthreads`. - -.. _release_1.0.0: - -1.0.0 ------ - -This release includes a complete re-organization of the code base. The -major version number has been bumped to indicate that there have been -backwards-incompatible changes to the API and the on-disk storage -format. However, Zarr is still in an early stage of development, so -please do not take the version number as an indicator of maturity. - -Storage -~~~~~~~ - -The main motivation for re-organizing the code was to create an -abstraction layer between the core array logic and data storage (:issue:`21`). -In this release, any -object that implements the ``MutableMapping`` interface can be used as -an array store. See the tutorial sections on :ref:`tutorial_persist` -and :ref:`tutorial_storage`, the :ref:`spec_v1`, and the -:mod:`zarr.storage` module documentation for more information. - -Please note also that the file organization and file name conventions -used when storing a Zarr array in a directory on the file system have -changed. Persistent Zarr arrays created using previous versions of the -software will not be compatible with this version. See the -:mod:`zarr.storage` API docs and the :ref:`spec_v1` for more -information. - -Compression -~~~~~~~~~~~ - -An abstraction layer has also been created between the core array -logic and the code for compressing and decompressing array -chunks. This release still bundles the c-blosc library and uses Blosc -as the default compressor, however other compressors including zlib, -BZ2 and LZMA are also now supported via the Python standard -library. New compressors can also be dynamically registered for use -with Zarr. See the tutorial sections on :ref:`tutorial_compress` and -:ref:`tutorial_tips_blosc`, the :ref:`spec_v1`, and the -:mod:`zarr.compressors` module documentation for more information. - -Synchronization -~~~~~~~~~~~~~~~ - -The synchronization code has also been refactored to create a layer of -abstraction, enabling Zarr arrays to be used in parallel computations -with a number of alternative synchronization methods. For more -information see the tutorial section on :ref:`tutorial_sync` and the -:mod:`zarr.sync` module documentation. - -Changes to the Blosc extension -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -NumPy is no longer a build dependency for the :mod:`zarr.blosc` Cython -extension, so setup.py will run even if NumPy is not already -installed, and should automatically install NumPy as a runtime -dependency. Manual installation of NumPy prior to installing Zarr is -still recommended, however, as the automatic installation of NumPy may -fail or be sub-optimal on some platforms. - -Some optimizations have been made within the :mod:`zarr.blosc` -extension to avoid unnecessary memory copies, giving a ~10-20% -performance improvement for multi-threaded compression operations. - -The :mod:`zarr.blosc` extension now automatically detects whether it -is running within a single-threaded or multi-threaded program and -adapts its internal behaviour accordingly (:issue:`27`). There is no need for -the user to make any API calls to switch Blosc between contextual and -non-contextual (global lock) mode. See also the tutorial section on -:ref:`tutorial_tips_blosc`. - -Other changes -~~~~~~~~~~~~~ - -The internal code for managing chunks has been rewritten to be more -efficient. Now no state is maintained for chunks outside of the array -store, meaning that chunks do not carry any extra memory overhead not -accounted for by the store. This negates the need for the "lazy" -option present in the previous release, and this has been removed. - -The memory layout within chunks can now be set as either "C" -(row-major) or "F" (column-major), which can help to provide better -compression for some data (:issue:`7`). See the tutorial -section on :ref:`tutorial_chunks_order` for more information. - -A bug has been fixed within the ``__getitem__`` and ``__setitem__`` -machinery for slicing arrays, to properly handle getting and setting -partial slices. - -Acknowledgments -~~~~~~~~~~~~~~~ - -Thanks to :user:`Matthew Rocklin `, :user:`Stephan Hoyer `, -:user:`Francesc Alted `, :user:`Anthony Scopatz ` and -:user:`Martin Durant ` for contributions and comments. - -.. _release_0.4.0: - -0.4.0 ------ - -See `v0.4.0 release notes on GitHub -`_. - -.. _release_0.3.0: - -0.3.0 ------ - -See `v0.3.0 release notes on GitHub -`_. - -.. _Numcodecs: https://numcodecs.readthedocs.io/ diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000000..4b5dbc4599 --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,189 @@ +# Roadmap + +This page describes where Zarr-Python is headed: the goals for the next major +cycle of work, the changes we intend to make, and how those changes will be +released. It is a living document; discussion and counter-proposals are welcome +on the +[Zarr-Python issue tracker](https://github.com/zarr-developers/zarr-python/issues). + +*The history of this roadmap, including the detailed technical proposals it +was distilled from, can be traced in the +[zarr-python-planning](https://github.com/zarr-developers/zarr-python-planning) +repository.* + +!!! note + + This roadmap reflects the current thinking of the core developers. It is a + statement of direction, not a schedule. We don't know how long these changes + will take, only that we are committed to moving the project in the direction outlined + here. + +## Where we are + +The [3.0 release](https://github.com/zarr-developers/zarr-python/releases/tag/v3.0.0) +was a total redesign of the library's internals, with three goals: full support +for the Zarr V2 and V3 storage formats, storage APIs that are ergonomic for high-latency +storage (such as cloud storage), and backwards compatibility with Zarr-Python 2.x where +possible. Those goals were largely achieved! Going by the content of issues and pull requests +submitted to the library, few users are grappling with 2.x β†’ 3.x migration issues. Instead, we see +users asking for things like better APIs, where "better" usually means faster. + +The 3.x redesign was carried out under hard backwards-compatibility +constraints, and it inherited many structural patterns from the 2.x +implementation it replaced. The library has never had a release cycle whose +primary goal was the *shape* of the internals. The next body of work β€” which we +call **"v4"** β€” is that overdue investment. We think iterating on the internals of +the library will make it *much* easier to bring faster, more expressive APIs to Zarr-Python +users. + +## Goals + +If the 3.0 goals could be sloganized as "migrate to Zarr V3, and improve cloud +storage support", the slogan for the v4 goals is: +**"a frictionless Zarr-based Python ecosystem for chunked arrays"**. Zarr-Python +should be *foundational* for the growing number of Python packages that work +with data in the Zarr format. Concretely, that means pushing in these +directions: + +- Deliver excellent performance, out of the box, while retaining maintainability. +- Make Zarr-Python APIs ergonomic and useful for developers. +- Expand our scope to cover vital quality-of-life routines like data copying, + rechunking, and the like. +- Ease the growth of Python tools across all levels of the Zarr stack. +- Accelerate the implementation of new codecs, chunk grids, chunk key + encodings, etc. + +An important design input: [`zarrs`](https://github.com/zarrs/zarrs) (Rust) and +[TensorStore](https://github.com/google/tensorstore) (C++) are two independent +Zarr implementations that use architectural patterns we want to learn from. +We see them as complementary rather than competitive. + +!!! note + + Many of the features in this roadmap will not require breaking public 3.x APIs. We can and will + ship those features in 3.x releases; at the same time, we consider it clarifying to frame the + coherent development direction as vectored at a 4.0 milestone. + +## The Zarr stack + +Different applications need different levels of Zarr support: a convention +validator only needs to read metadata documents; a visualization tool may only +need read-only array access; other tools need everything. We think of this as a +"Zarr stack", from most abstract to most concrete: + +1. **Conventions** β€” application and/or domain-specific schemas built on top of Zarr (OME-NGFF, + GeoZarr, anndata-zarr, multiscales). +2. **Groups** β€” Zarr hierarchies, traversal, group-level attributes. +3. **Arrays** β€” the user-facing array object, plus indexing and slicing. +4. **Chunk decoding** β€” the codec pipeline. +5. **Chunk addressing** β€” chunk grids and key encodings that map array + coordinates to store keys. +6. **Stores** β€” the key-value layer. +7. **Metadata** β€” pure data documents describing arrays and groups. + +Today, Zarr-Python is a monolith that serves every level: a consumer who only +needs metadata handling has to install the full dependency footprint of the +whole library, and a faster chunk-decoding implementation cannot plug in +without re-implementing the layers above it. The v4 direction is to re-shape +Zarr-Python around the stack, so that each level is something you can depend +on, conform to, or replace, without buying every other level. + +We plan to "stackify" Zarr-Python by spinning core functionality out into separate Python packages, e.g. `zarr-metadata`, `zarr-indexing`, `zarr-storage`, +`zarr-codec`, `zarr-dtype`, each with narrow scope, all composed in the `zarr` package. The Rust `zarrs` library +successfully uses a structure like this, and we are keen to share the benefits of a more modular, maintainable codebase. Two of these subpackages, +[`zarr-metadata`](https://zarr.readthedocs.io/projects/zarr-metadata/en/latest/) and [`zarr-indexing`](https://zarr.readthedocs.io/projects/zarr-indexing/en/latest/), are already +published. + +## What we intend to change + +The following section details how we want to evolve the internal logic that drives Zarr-Python. + +### Foundation: swappable backends + +We propose to refactor Zarr-Python internals around a *swappable engine* β€” a protocol, or protocols, +that define the core routines a Zarr implementation must support. Zarr-Python becomes one user-facing +API that can be driven by multiple backends, including externally defined backends. We think this will allow users on many different platforms to get the best performance for their particular environment while retaining a familiar API. + +#### Rust bindings + +We want a Python backend (i.e., the status quo), but also a Rust-based backend, via bindings to the +[`zarrs`](https://docs.rs/zarrs/latest/zarrs/) crate. The [zarrs-python](https://zarrs-python.readthedocs.io/en/latest/) project demonstrates that +bridging `zarrs` and Zarr-Python buys a *lot* of performance in the specific case of chunk encoding. But zarrs-python is constrained today by limited +modularity in Zarr-Python internals. Refactoring our internals around swappable backends should address this limitation. + +Any Python package that interfaces with `zarrs` will need Pythonic bindings to the Rust library. So we are *very* excited about the [zarrista](https://developmentseed.org/zarrista/latest/) package, which aims to provide complete Python bindings for `zarrs`. + +#### Sync / Async partitioning + +Internally we will branch over two kinds of backends: synchronous and asynchronous. The synchronous backend is suitable for arrays and groups persisted to low-latency storage like in-memory stores or local file systems, where async scheduling is pure friction. The asynchronous backend will use Python's `async` support and will provide concurrent APIs where it helps: for arrays and groups persisted to high-latency storage. + +### Lazy indexing + +The Zarr-Python Array API was initially designed to mirror NumPy, with eager +array indexing syntax. `Array.__getitem__` performs IO eagerly and returns a NumPy array. +That was helpful to the dominant use-case at the time of its creation, but it +means deferred IO and computation currently require an external library +such as Dask. It means there is no built-in support for representing multi-step +reads as a single deferred plan. Further, it means that every chained +selection round-trips to storage independently. + +We can fix this by introducing an API for lazy indexing. Under this model, an array indexing operation +like `array[::2]` desugars to a declarative state like `(array, selection)`. Chained selections like +`array[10:100][::2]` are fused immediately, and we defer actual IO for the time when the result of +indexing is needed. [TensorStore](https://google.github.io/tensorstore/) is an excellent role model +for Zarr-Python here, and we can deliver this functionality without breaking ordinary indexing behavior. +See this [discussion](https://github.com/zarr-developers/zarr-python/discussions/1603) for more +background. + +### Data types + +First-class support for ML-specific dtypes β€” `bfloat16`, the `float8` +variants, packed `int4`/`uint4` β€” via +[`ml_dtypes`](https://github.com/jax-ml/ml_dtypes). These data types have specifications written up in `zarr-extensions`, but there's no simple to get them integrated in Zarr-Python today. + +### Device-agnostic IO + +Make Zarr-Python's IO surfaces device-agnostic rather than adding GPU support +as a bolted-on feature: stores and codecs grow APIs for writing into a +caller-provided buffer (`read_into`, `decode_into`), and the `Array` facade +returns array-like objects in the user's chosen Array API namespace. GPU +support falls out once the assumption of CPU destinations is removed, and CPU +paths get faster too, because pre-allocated output buffers eliminate per-chunk +allocation. + +### Configuration, registries, and plugins + +Move configuration from "global mutable state read implicitly" to "typed data +passed explicitly": a typed config object replacing the untyped global `donfig` +dict, array-scoped runtime config passed at open time, a registry redesign that +addresses implementations by stable identity and resolves plugin name-conflicts +deliberately, and named profiles replacing global mutators. + +### Coordinated and distributed writes + +This area is actually an unfinished aspect of the 2.x β†’ 3.0 migration: Zarr-Python 2.x supported +synchronization logic via file-based locks, and we have not implemented equivalent functionality in +3.x. We don't have *concrete* plans for closing this gap. Re-implementing simple object-based locking, for +backends that support it, is a direct solution we should consider. But a transactional storage model, +where a sequence of basic storage operations like reading and writing could be submitted in a batch and +executed serially, with rollbacks under failure, is also quite appealing. +As with array indexing, TensorStore is the trailblazer here, and we can learn from its example. + +We can also avoid the need for synchronization mechanisms entirely with better planning. +Many users of the 2.x synchronization tooling needed to simply write values from one chunked source +to another, without worrying about chunk alignment. This can be addressed e.g. by creating a write +plan that partitions the input chunks into batches within which writes cannot race. + +## How to get involved + +- **Discuss the plans.** Comments and counter-proposals on any of the themes + above are welcome on the + [issue tracker](https://github.com/zarr-developers/zarr-python/issues) and in + the [developer chat](https://ossci.zulipchat.com/). +- **Review in-flight work.** The `IndexTransform` algebra that lazy indexing is + built on is in review at + [#3906](https://github.com/zarr-developers/zarr-python/pull/3906). +- **Weigh in as a downstream maintainer.** If your project's use of + Zarr-Python would be affected by the codec API rewrite, the stores rewrite, + or the lazy-indexing work, the planning phase is the time to surface + workloads or patterns that don't fit. diff --git a/docs/spec.rst b/docs/spec.rst deleted file mode 100644 index 8aca0bbd80..0000000000 --- a/docs/spec.rst +++ /dev/null @@ -1,11 +0,0 @@ -.. _spec: - -Specifications -============== - -.. toctree:: - :maxdepth: 1 - - spec/v3 - spec/v2 - spec/v1 diff --git a/docs/spec/v1.rst b/docs/spec/v1.rst deleted file mode 100644 index 13f68ef36e..0000000000 --- a/docs/spec/v1.rst +++ /dev/null @@ -1,270 +0,0 @@ -.. _spec_v1: - -Zarr Storage Specification Version 1 -==================================== - -This document provides a technical specification of the protocol and -format used for storing a Zarr array. The key words "MUST", "MUST -NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", -"RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be -interpreted as described in `RFC 2119 -`_. - -Status ------- - -This specification is deprecated. See :ref:`spec` for the latest version. - -Storage -------- - -A Zarr array can be stored in any storage system that provides a -key/value interface, where a key is an ASCII string and a value is an -arbitrary sequence of bytes, and the supported operations are read -(get the sequence of bytes associated with a given key), write (set -the sequence of bytes associated with a given key) and delete (remove -a key/value pair). - -For example, a directory in a file system can provide this interface, -where keys are file names, values are file contents, and files can be -read, written or deleted via the operating system. Equally, an S3 -bucket can provide this interface, where keys are resource names, -values are resource contents, and resources can be read, written or -deleted via HTTP. - -Below an "array store" refers to any system implementing this -interface. - -Metadata --------- - -Each array requires essential configuration metadata to be stored, -enabling correct interpretation of the stored data. This metadata is -encoded using JSON and stored as the value of the 'meta' key within an -array store. - -The metadata resource is a JSON object. The following keys MUST be -present within the object: - -zarr_format - An integer defining the version of the storage specification to which the - array store adheres. -shape - A list of integers defining the length of each dimension of the array. -chunks - A list of integers defining the length of each dimension of a chunk of the - array. Note that all chunks within a Zarr array have the same shape. -dtype - A string or list defining a valid data type for the array. See also - the subsection below on data type encoding. -compression - A string identifying the primary compression library used to compress - each chunk of the array. -compression_opts - An integer, string or dictionary providing options to the primary - compression library. -fill_value - A scalar value providing the default value to use for uninitialized - portions of the array. -order - Either 'C' or 'F', defining the layout of bytes within each chunk of the - array. 'C' means row-major order, i.e., the last dimension varies fastest; - 'F' means column-major order, i.e., the first dimension varies fastest. - -Other keys MAY be present within the metadata object however they MUST -NOT alter the interpretation of the required fields defined above. - -For example, the JSON object below defines a 2-dimensional array of -64-bit little-endian floating point numbers with 10000 rows and 10000 -columns, divided into chunks of 1000 rows and 1000 columns (so there -will be 100 chunks in total arranged in a 10 by 10 grid). Within each -chunk the data are laid out in C contiguous order, and each chunk is -compressed using the Blosc compression library:: - - { - "chunks": [ - 1000, - 1000 - ], - "compression": "blosc", - "compression_opts": { - "clevel": 5, - "cname": "lz4", - "shuffle": 1 - }, - "dtype": "`_. The -format consists of 3 parts: a character describing the byteorder of -the data (``<``: little-endian, ``>``: big-endian, ``|``: -not-relevant), a character code giving the basic type of the array, -and an integer providing the number of bytes the type uses. The byte -order MUST be specified. E.g., ``"i4"``, ``"|b1"`` and -``"|S12"`` are valid data types. - -Structure data types (i.e., with multiple named fields) are encoded as -a list of two-element lists, following `NumPy array protocol type -descriptions (descr) -`_. -For example, the JSON list ``[["r", "|u1"], ["g", "|u1"], ["b", -"|u1"]]`` defines a data type composed of three single-byte unsigned -integers labelled 'r', 'g' and 'b'. - -Chunks ------- - -Each chunk of the array is compressed by passing the raw bytes for the -chunk through the primary compression library to obtain a new sequence -of bytes comprising the compressed chunk data. No header is added to -the compressed bytes or any other modification made. The internal -structure of the compressed bytes will depend on which primary -compressor was used. For example, the `Blosc compressor -`_ -produces a sequence of bytes that begins with a 16-byte header -followed by compressed data. - -The compressed sequence of bytes for each chunk is stored under a key -formed from the index of the chunk within the grid of chunks -representing the array. To form a string key for a chunk, the indices -are converted to strings and concatenated with the period character -('.') separating each index. For example, given an array with shape -(10000, 10000) and chunk shape (1000, 1000) there will be 100 chunks -laid out in a 10 by 10 grid. The chunk with indices (0, 0) provides -data for rows 0-999 and columns 0-999 and is stored under the key -'0.0'; the chunk with indices (2, 4) provides data for rows 2000-2999 -and columns 4000-4999 and is stored under the key '2.4'; etc. - -There is no need for all chunks to be present within an array -store. If a chunk is not present then it is considered to be in an -uninitialized state. An uninitialized chunk MUST be treated as if it -was uniformly filled with the value of the 'fill_value' field in the -array metadata. If the 'fill_value' field is ``null`` then the -contents of the chunk are undefined. - -Note that all chunks in an array have the same shape. If the length of -any array dimension is not exactly divisible by the length of the -corresponding chunk dimension then some chunks will overhang the edge -of the array. The contents of any chunk region falling outside the -array are undefined. - -Attributes ----------- - -Each array can also be associated with custom attributes, which are -simple key/value items with application-specific meaning. Custom -attributes are encoded as a JSON object and stored under the 'attrs' -key within an array store. Even if the attributes are empty, the -'attrs' key MUST be present within an array store. - -For example, the JSON object below encodes three attributes named -'foo', 'bar' and 'baz':: - - { - "foo": 42, - "bar": "apples", - "baz": [1, 2, 3, 4] - } - -Example -------- - -Below is an example of storing a Zarr array, using a directory on the -local file system as storage. - -Initialize the store:: - - >>> import zarr - >>> store = zarr.DirectoryStore('example.zarr') - >>> zarr.init_store(store, shape=(20, 20), chunks=(10, 10), - ... dtype='i4', fill_value=42, compression='zlib', - ... compression_opts=1, overwrite=True) - -No chunks are initialized yet, so only the 'meta' and 'attrs' keys -have been set:: - - >>> import os - >>> sorted(os.listdir('example.zarr')) - ['attrs', 'meta'] - -Inspect the array metadata:: - - >>> print(open('example.zarr/meta').read()) - { - "chunks": [ - 10, - 10 - ], - "compression": "zlib", - "compression_opts": 1, - "dtype": ">> print(open('example.zarr/attrs').read()) - {} - -Set some data:: - - >>> z = zarr.Array(store) - >>> z[0:10, 0:10] = 1 - >>> sorted(os.listdir('example.zarr')) - ['0.0', 'attrs', 'meta'] - -Set some more data:: - - >>> z[0:10, 10:20] = 2 - >>> z[10:20, :] = 3 - >>> sorted(os.listdir('example.zarr')) - ['0.0', '0.1', '1.0', '1.1', 'attrs', 'meta'] - -Manually decompress a single chunk for illustration:: - - >>> import zlib - >>> b = zlib.decompress(open('example.zarr/0.0', 'rb').read()) - >>> import numpy as np - >>> a = np.frombuffer(b, dtype='>> a - array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32) - -Modify the array attributes:: - - >>> z.attrs['foo'] = 42 - >>> z.attrs['bar'] = 'apples' - >>> z.attrs['baz'] = [1, 2, 3, 4] - >>> print(open('example.zarr/attrs').read()) - { - "bar": "apples", - "baz": [ - 1, - 2, - 3, - 4 - ], - "foo": 42 - } diff --git a/docs/spec/v2.rst b/docs/spec/v2.rst deleted file mode 100644 index c1e12e1218..0000000000 --- a/docs/spec/v2.rst +++ /dev/null @@ -1,565 +0,0 @@ -.. _spec_v2: - -Zarr Storage Specification Version 2 -==================================== - -This document provides a technical specification of the protocol and format -used for storing Zarr arrays. The key words "MUST", "MUST NOT", "REQUIRED", -"SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and -"OPTIONAL" in this document are to be interpreted as described in `RFC 2119 -`_. - -Status ------- - -This specification is the latest version. See :ref:`spec` for previous -versions. - -.. _spec_v2_storage: - -Storage -------- - -A Zarr array can be stored in any storage system that provides a key/value -interface, where a key is an ASCII string and a value is an arbitrary sequence -of bytes, and the supported operations are read (get the sequence of bytes -associated with a given key), write (set the sequence of bytes associated with -a given key) and delete (remove a key/value pair). - -For example, a directory in a file system can provide this interface, where -keys are file names, values are file contents, and files can be read, written -or deleted via the operating system. Equally, an S3 bucket can provide this -interface, where keys are resource names, values are resource contents, and -resources can be read, written or deleted via HTTP. - -Below an "array store" refers to any system implementing this interface. - -.. _spec_v2_array: - -Arrays ------- - -.. _spec_v2_array_metadata: - -Metadata -~~~~~~~~ - -Each array requires essential configuration metadata to be stored, enabling -correct interpretation of the stored data. This metadata is encoded using JSON -and stored as the value of the ".zarray" key within an array store. - -The metadata resource is a JSON object. The following keys MUST be present -within the object: - -zarr_format - An integer defining the version of the storage specification to which the - array store adheres. -shape - A list of integers defining the length of each dimension of the array. -chunks - A list of integers defining the length of each dimension of a chunk of the - array. Note that all chunks within a Zarr array have the same shape. -dtype - A string or list defining a valid data type for the array. See also - the subsection below on data type encoding. -compressor - A JSON object identifying the primary compression codec and providing - configuration parameters, or ``null`` if no compressor is to be used. - The object MUST contain an ``"id"`` key identifying the codec to be used. -fill_value - A scalar value providing the default value to use for uninitialized - portions of the array, or ``null`` if no fill_value is to be used. -order - Either "C" or "F", defining the layout of bytes within each chunk of the - array. "C" means row-major order, i.e., the last dimension varies fastest; - "F" means column-major order, i.e., the first dimension varies fastest. -filters - A list of JSON objects providing codec configurations, or ``null`` if no - filters are to be applied. Each codec configuration object MUST contain a - ``"id"`` key identifying the codec to be used. - -The following keys MAY be present within the object: - -dimension_separator - If present, either the string ``"."`` or ``"/"`` defining the separator placed - between the dimensions of a chunk. If the value is not set, then the - default MUST be assumed to be ``"."``, leading to chunk keys of the form "0.0". - Arrays defined with ``"/"`` as the dimension separator can be considered to have - nested, or hierarchical, keys of the form "0/0" that SHOULD where possible - produce a directory-like structure. - -Other keys SHOULD NOT be present within the metadata object and SHOULD be -ignored by implementations. - -For example, the JSON object below defines a 2-dimensional array of 64-bit -little-endian floating point numbers with 10000 rows and 10000 columns, divided -into chunks of 1000 rows and 1000 columns (so there will be 100 chunks in total -arranged in a 10 by 10 grid). Within each chunk the data are laid out in C -contiguous order. Each chunk is encoded using a delta filter and compressed -using the Blosc compression library prior to storage:: - - { - "chunks": [ - 1000, - 1000 - ], - "compressor": { - "id": "blosc", - "cname": "lz4", - "clevel": 5, - "shuffle": 1 - }, - "dtype": "`. The format -consists of 3 parts: - -* One character describing the byteorder of the data (``"<"``: little-endian; - ``">"``: big-endian; ``"|"``: not-relevant) -* One character code giving the basic type of the array (``"b"``: Boolean (integer - type where all values are only True or False); ``"i"``: integer; ``"u"``: unsigned - integer; ``"f"``: floating point; ``"c"``: complex floating point; ``"m"``: timedelta; - ``"M"``: datetime; ``"S"``: string (fixed-length sequence of char); ``"U"``: unicode - (fixed-length sequence of Py_UNICODE); ``"V"``: other (void * – each item is a - fixed-size chunk of memory)) -* An integer specifying the number of bytes the type uses. - -The byte order MUST be specified. E.g., ``"i4"``, ``"|b1"`` and -``"|S12"`` are valid data type encodings. - -For datetime64 ("M") and timedelta64 ("m") data types, these MUST also include the -units within square brackets. A list of valid units and their definitions are given in -the :ref:`NumPy documentation on Datetimes and Timedeltas -`. -For example, ``"`. Each -sub-list has the form ``[fieldname, datatype, shape]`` where ``shape`` -is optional. ``fieldname`` is a string, ``datatype`` is a string -specifying a simple data type (see above), and ``shape`` is a list of -integers specifying subarray shape. For example, the JSON list below -defines a data type composed of three single-byte unsigned integer -fields named "r", "g" and "b":: - - [["r", "|u1"], ["g", "|u1"], ["b", "|u1"]] - -For example, the JSON list below defines a data type composed of three -fields named "x", "y" and "z", where "x" and "y" each contain 32-bit -floats, and each item in "z" is a 2 by 2 array of floats:: - - [["x", "`_ -produces a sequence of bytes that begins with a 16-byte header followed by -compressed data. - -The compressed sequence of bytes for each chunk is stored under a key formed -from the index of the chunk within the grid of chunks representing the array. -To form a string key for a chunk, the indices are converted to strings and -concatenated with the period character (".") separating each index. For -example, given an array with shape (10000, 10000) and chunk shape (1000, 1000) -there will be 100 chunks laid out in a 10 by 10 grid. The chunk with indices -(0, 0) provides data for rows 0-999 and columns 0-999 and is stored under the -key "0.0"; the chunk with indices (2, 4) provides data for rows 2000-2999 and -columns 4000-4999 and is stored under the key "2.4"; etc. - -There is no need for all chunks to be present within an array store. If a chunk -is not present then it is considered to be in an uninitialized state. An -uninitialized chunk MUST be treated as if it was uniformly filled with the value -of the "fill_value" field in the array metadata. If the "fill_value" field is -``null`` then the contents of the chunk are undefined. - -Note that all chunks in an array have the same shape. If the length of any -array dimension is not exactly divisible by the length of the corresponding -chunk dimension then some chunks will overhang the edge of the array. The -contents of any chunk region falling outside the array are undefined. - -.. _spec_v2_array_filters: - -Filters -~~~~~~~ - -Optionally a sequence of one or more filters can be used to transform chunk -data prior to compression. When storing data, filters are applied in the order -specified in array metadata to encode data, then the encoded data are passed to -the primary compressor. When retrieving data, stored chunk data are -decompressed by the primary compressor then decoded using filters in the -reverse order. - -.. _spec_v2_hierarchy: - -Hierarchies ------------ - -.. _spec_v2_hierarchy_paths: - -Logical storage paths -~~~~~~~~~~~~~~~~~~~~~ - -Multiple arrays can be stored in the same array store by associating each array -with a different logical path. A logical path is simply an ASCII string. The -logical path is used to form a prefix for keys used by the array. For example, -if an array is stored at logical path "foo/bar" then the array metadata will be -stored under the key "foo/bar/.zarray", the user-defined attributes will be -stored under the key "foo/bar/.zattrs", and the chunks will be stored under -keys like "foo/bar/0.0", "foo/bar/0.1", etc. - -To ensure consistent behaviour across different storage systems, logical paths -MUST be normalized as follows: - -* Replace all backward slash characters ("\\\\") with forward slash characters - ("/") -* Strip any leading "/" characters -* Strip any trailing "/" characters -* Collapse any sequence of more than one "/" character into a single "/" - character - -The key prefix is then obtained by appending a single "/" character to the -normalized logical path. - -After normalization, if splitting a logical path by the "/" character results -in any path segment equal to the string "." or the string ".." then an error -MUST be raised. - -N.B., how the underlying array store processes requests to store values under -keys containing the "/" character is entirely up to the store implementation -and is not constrained by this specification. E.g., an array store could simply -treat all keys as opaque ASCII strings; equally, an array store could map -logical paths onto some kind of hierarchical storage (e.g., directories on a -file system). - -.. _spec_v2_hierarchy_groups: - -Groups -~~~~~~ - -Arrays can be organized into groups which can also contain other groups. A -group is created by storing group metadata under the ".zgroup" key under some -logical path. E.g., a group exists at the root of an array store if the -".zgroup" key exists in the store, and a group exists at logical path "foo/bar" -if the "foo/bar/.zgroup" key exists in the store. - -If the user requests a group to be created under some logical path, then groups -MUST also be created at all ancestor paths. E.g., if the user requests group -creation at path "foo/bar" then groups MUST be created at path "foo" and the -root of the store, if they don't already exist. - -If the user requests an array to be created under some logical path, then -groups MUST also be created at all ancestor paths. E.g., if the user requests -array creation at path "foo/bar/baz" then groups must be created at path -"foo/bar", path "foo", and the root of the store, if they don't already exist. - -The group metadata resource is a JSON object. The following keys MUST be present -within the object: - -zarr_format - An integer defining the version of the storage specification to which the - array store adheres. - -Other keys MUST NOT be present within the metadata object. - -The members of a group are arrays and groups stored under logical paths that -are direct children of the parent group's logical path. E.g., if groups exist -under the logical paths "foo" and "foo/bar" and an array exists at logical path -"foo/baz" then the members of the group at path "foo" are the group at path -"foo/bar" and the array at path "foo/baz". - -.. _spec_v2_attrs: - -Attributes ----------- - -An array or group can be associated with custom attributes, which are arbitrary -key/value pairs with application-specific meaning. Custom attributes are encoded -as a JSON object and stored under the ".zattrs" key within an array store. The -".zattrs" key does not have to be present, and if it is absent the attributes -should be treated as empty. - -For example, the JSON object below encodes three attributes named -"foo", "bar" and "baz":: - - { - "foo": 42, - "bar": "apples", - "baz": [1, 2, 3, 4] - } - -.. _spec_v2_examples: - -Examples --------- - -Storing a single array -~~~~~~~~~~~~~~~~~~~~~~ - -Below is an example of storing a Zarr array, using a directory on the -local file system as storage. - -Create an array:: - - >>> import zarr - >>> store = zarr.DirectoryStore('data/example.zarr') - >>> a = zarr.create(shape=(20, 20), chunks=(10, 10), dtype='i4', - ... fill_value=42, compressor=zarr.Zlib(level=1), - ... store=store, overwrite=True) - -No chunks are initialized yet, so only the ".zarray" and ".zattrs" keys -have been set in the store:: - - >>> import os - >>> sorted(os.listdir('data/example.zarr')) - ['.zarray'] - -Inspect the array metadata:: - - >>> print(open('data/example.zarr/.zarray').read()) - { - "chunks": [ - 10, - 10 - ], - "compressor": { - "id": "zlib", - "level": 1 - }, - "dtype": ">> a[0:10, 0:10] = 1 - >>> sorted(os.listdir('data/example.zarr')) - ['.zarray', '0.0'] - -Set some more data:: - - >>> a[0:10, 10:20] = 2 - >>> a[10:20, :] = 3 - >>> sorted(os.listdir('data/example.zarr')) - ['.zarray', '0.0', '0.1', '1.0', '1.1'] - -Manually decompress a single chunk for illustration:: - - >>> import zlib - >>> buf = zlib.decompress(open('data/example.zarr/0.0', 'rb').read()) - >>> import numpy as np - >>> chunk = np.frombuffer(buf, dtype='>> chunk - array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32) - -Modify the array attributes:: - - >>> a.attrs['foo'] = 42 - >>> a.attrs['bar'] = 'apples' - >>> a.attrs['baz'] = [1, 2, 3, 4] - >>> sorted(os.listdir('data/example.zarr')) - ['.zarray', '.zattrs', '0.0', '0.1', '1.0', '1.1'] - >>> print(open('data/example.zarr/.zattrs').read()) - { - "bar": "apples", - "baz": [ - 1, - 2, - 3, - 4 - ], - "foo": 42 - } - -Storing multiple arrays in a hierarchy -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Below is an example of storing multiple Zarr arrays organized into a group -hierarchy, using a directory on the local file system as storage. This storage -implementation maps logical paths onto directory paths on the file system, -however this is an implementation choice and is not required. - -Setup the store:: - - >>> import zarr - >>> store = zarr.DirectoryStore('data/group.zarr') - -Create the root group:: - - >>> root_grp = zarr.group(store, overwrite=True) - -The metadata resource for the root group has been created:: - - >>> import os - >>> sorted(os.listdir('data/group.zarr')) - ['.zgroup'] - -Inspect the group metadata:: - - >>> print(open('data/group.zarr/.zgroup').read()) - { - "zarr_format": 2 - } - -Create a sub-group:: - - >>> sub_grp = root_grp.create_group('foo') - -What has been stored:: - - >>> sorted(os.listdir('data/group.zarr')) - ['.zgroup', 'foo'] - >>> sorted(os.listdir('data/group.zarr/foo')) - ['.zgroup'] - -Create an array within the sub-group:: - - >>> a = sub_grp.create_dataset('bar', shape=(20, 20), chunks=(10, 10)) - >>> a[:] = 42 - -Set a custom attributes:: - - >>> a.attrs['comment'] = 'answer to life, the universe and everything' - -What has been stored:: - - >>> sorted(os.listdir('data/group.zarr')) - ['.zgroup', 'foo'] - >>> sorted(os.listdir('data/group.zarr/foo')) - ['.zgroup', 'bar'] - >>> sorted(os.listdir('data/group.zarr/foo/bar')) - ['.zarray', '.zattrs', '0.0', '0.1', '1.0', '1.1'] - -Here is the same example using a Zip file as storage:: - - >>> store = zarr.ZipStore('data/group.zip', mode='w') - >>> root_grp = zarr.group(store) - >>> sub_grp = root_grp.create_group('foo') - >>> a = sub_grp.create_dataset('bar', shape=(20, 20), chunks=(10, 10)) - >>> a[:] = 42 - >>> a.attrs['comment'] = 'answer to life, the universe and everything' - >>> store.close() - -What has been stored:: - - >>> import zipfile - >>> zf = zipfile.ZipFile('data/group.zip', mode='r') - >>> for name in sorted(zf.namelist()): - ... print(name) - .zgroup - foo/.zgroup - foo/bar/.zarray - foo/bar/.zattrs - foo/bar/0.0 - foo/bar/0.1 - foo/bar/1.0 - foo/bar/1.1 - -.. _spec_v2_changes: - -Changes -------- - -Version 2 clarifications -~~~~~~~~~~~~~~~~~~~~~~~~ - -The following changes have been made to the version 2 specification since it was -initially published to clarify ambiguities and add some missing information. - -* The specification now describes how bytes fill values should be encoded and - decoded for arrays with a fixed-length byte string data type (:issue:`165`, - :issue:`176`). - -* The specification now clarifies that units must be specified for datetime64 and - timedelta64 data types (:issue:`85`, :issue:`215`). - -* The specification now clarifies that the '.zattrs' key does not have to be present for - either arrays or groups, and if absent then custom attributes should be treated as - empty. - -* The specification now describes how structured datatypes with - subarray shapes and/or with nested structured data types are encoded - in array metadata (:issue:`111`, :issue:`296`). - -* Clarified the key/value pairs of custom attributes as "arbitrary" rather than - "simple". - -Changes from version 1 to version 2 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The following changes were made between version 1 and version 2 of this specification: - -* Added support for storing multiple arrays in the same store and organising - arrays into hierarchies using groups. -* Array metadata is now stored under the ".zarray" key instead of the "meta" - key. -* Custom attributes are now stored under the ".zattrs" key instead of the - "attrs" key. -* Added support for filters. -* Changed encoding of "fill_value" field within array metadata. -* Changed encoding of compressor information within array metadata to be - consistent with representation of filter information. diff --git a/docs/spec/v3.rst b/docs/spec/v3.rst deleted file mode 100644 index bd8852707b..0000000000 --- a/docs/spec/v3.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. _spec_v3: - -Zarr Storage Specification Version 3 -======================================================= - -The V3 Specification has been migrated to its website β†’ -https://zarr-specs.readthedocs.io/. diff --git a/docs/subprojects.md b/docs/subprojects.md new file mode 100644 index 0000000000..9f7951e836 --- /dev/null +++ b/docs/subprojects.md @@ -0,0 +1,45 @@ +# Subprojects + +Alongside `zarr` itself, the +[zarr-python repository](https://github.com/zarr-developers/zarr-python) hosts a +small number of companion packages. Each one is developed in the same repository +but versioned, released, and documented independently, so you can depend on it +without taking on `zarr` as a dependency. + +
+ +- [:material-code-json:{ .lg .middle } __zarr-metadata__](https://zarr.readthedocs.io/projects/zarr-metadata/) + + --- + + Spec-defined metadata types, models, and validators for Zarr v2 and v3, with + minimal dependencies. Useful if your software reads or writes Zarr metadata + documents but does not need a full Zarr implementation. + + ```bash + pip install zarr-metadata + ``` + +- [:material-vector-polyline:{ .lg .middle } __zarr-indexing__](https://zarr.readthedocs.io/projects/zarr-indexing/) + + --- + + Composable, lazy coordinate transforms for Zarr array indexing. Makes the + mapping from requested coordinates to stored coordinates a first-class, + composable value, and resolves which chunks a selection touches. + + ```bash + pip install zarr-indexing + ``` + +- [:material-server:{ .lg .middle } __zarr-http-server__](https://zarr.readthedocs.io/projects/zarr-http-server/) + + --- + + HTTP server for Zarr stores, arrays, and groups. + + ```bash + pip install zarr-http-server + ``` + +
diff --git a/docs/talks/scipy2019/submission.rst b/docs/talks/scipy2019/submission.rst deleted file mode 100644 index 57fd925b1f..0000000000 --- a/docs/talks/scipy2019/submission.rst +++ /dev/null @@ -1,144 +0,0 @@ -Zarr - scalable storage of tensor data for use in parallel and distributed computing -==================================================================================== - -SciPy 2019 submission. - - -Short summary -------------- - -Many scientific problems involve computing over large N-dimensional -typed arrays of data, and reading or writing data is often the major -bottleneck limiting speed or scalability. The Zarr project is -developing a simple, scalable approach to storage of such data in a -way that is compatible with a range of approaches to distributed and -parallel computing. We describe the Zarr protocol and data storage -format, and the current state of implementations for various -programming languages including Python. We also describe current uses -of Zarr in malaria genomics, the Human Cell Atlas, and the Pangeo -project. - - -Abstract --------- - -Background -~~~~~~~~~~ - -Across a broad range of scientific disciplines, data are naturally -represented and stored as N-dimensional typed arrays, also known as -tensors. The volume of data being generated is outstripping our -ability to analyse it, and scientific communities are looking for ways -to leverage modern multi-core CPUs and distributed computing -platforms, including cloud computing. Retrieval and storage of data is -often the major bottleneck, and new approaches to data storage are -needed to accelerate distributed computations and enable them to scale -on a variety of platforms. - -Methods -~~~~~~~ - -We have designed a new storage format and protocol for tensor data -[1_], and have released an open source Python implementation [2_, -3_]. Our approach builds on data storage concepts from HDF5 [4_], -particularly chunking and compression, and hierarchical organisation -of datasets. Key design goals include: a simple protocol and format -that can be implemented in other programming languages; support for -multiple concurrent readers or writers; support for a variety of -parallel computing environments, from multi-threaded execution on a -single CPU to multi-process execution across a multi-node cluster; -pluggable storage subsystem with support for file systems, key-value -databases and cloud object stores; pluggable encoding subsystem with -support for a variety of modern compressors. - -Results -~~~~~~~ - -We illustrate the use of Zarr with examples from several scientific -domains. Zarr is being used within the Pangeo project [5_], which is -building a community platform for big data geoscience. The Pangeo -community have converted a number of existing climate modelling and -satellite observation datasets to Zarr [6_], and have demonstrated -their use in computations using HPC and cloud computing -environments. Within the MalariaGEN project [7_], Zarr is used to -store genome variation data from next-generation sequencing of natural -populations of malaria parasites and mosquitoes [8_] and these data -are used as input to analyses of the evolution of these organisms in -response to selective pressure from anti-malarial drugs and -insecticides. Zarr is being used within the Human Cell Atlas (HCA) -project [9_], which is building a reference atlas of healthy human -cell types. This project hopes to leverage this information to better -understand the dysregulation of cellular states that underly human -disease. The Human Cell Atlas uses Zarr as the output data format -because it enables the project to easily generate matrices containing -user-selected subsets of cells. - -Conclusions -~~~~~~~~~~~ - -Zarr is generating interest across a range of scientific domains, and -work is ongoing to establish a community process to support further -development of the specifications and implementations in other -programming languages [10_, 11_, 12_] and building interoperability -with a similar project called N5 [13_]. Other packages within the -PyData ecosystem, notably Dask [14_], Xarray [15_] and Intake [16_], -have added capability to read and write Zarr, and together these -packages provide a compelling solution for large scale data science -using Python [17_]. Zarr has recently been presented in several -venues, including a webinar for the ESIP Federation tech dive series -[18_], and a talk at the AGU Fall Meeting 2018 [19_]. - - -References -~~~~~~~~~~ - -.. _1: https://zarr.readthedocs.io/en/stable/spec/v2.html -.. _2: https://github.com/zarr-developers/zarr-python -.. _3: https://github.com/zarr-developers/numcodecs -.. _4: https://www.hdfgroup.org/solutions/hdf5/ -.. _5: https://pangeo.io/ -.. _6: https://pangeo.io/catalog.html -.. _7: https://www.malariagen.net/ -.. _8: http://alimanfoo.github.io/2016/09/21/genotype-compression-benchmark.html -.. _9: https://www.humancellatlas.org/ -.. _10: https://github.com/constantinpape/z5 -.. _11: https://github.com/lasersonlab/ndarray.scala -.. _12: https://github.com/meggart/ZarrNative.jl -.. _13: https://github.com/saalfeldlab/n5 -.. _14: http://docs.dask.org/en/latest/array-creation.html -.. _15: http://xarray.pydata.org/en/stable/io.html -.. _16: https://github.com/ContinuumIO/intake-xarray -.. _17: http://matthewrocklin.com/blog/work/2018/01/22/pangeo-2 -.. _18: http://wiki.esipfed.org/index.php/Interoperability_and_Technology/Tech_Dive_Webinar_Series#8_March.2C_2018:_.22Zarr:_A_simple.2C_open.2C_scalable_solution_for_big_NetCDF.2FHDF_data_on_the_Cloud.22:_Alistair_Miles.2C_University_of_Oxford. -.. _19: https://agu.confex.com/agu/fm18/meetingapp.cgi/Paper/390015 - - -Authors -------- - -Project contributors are listed in alphabetical order by surname. - -* `Ryan Abernathey `_, Columbia University -* `Stephan Balmer `_, Meteotest -* `Ambrose Carr `_, Chan Zuckerberg Initiative -* `Tim Crone `_, Columbia University -* `Martin Durant `_, Anaconda, inc. -* `Jan Funke `_, HHMI Janelia -* `Darren Gallagher `_, Satavia -* `Fabian Gans `_, Max Planck Institute for Biogeochemistry -* `Shikhar Goenka `_, Satavia -* `Joe Hamman `_, NCAR -* `Stephan Hoyer `_, Google -* `Jerome Kelleher `_, University of Oxford -* `John Kirkham `_, HHMI Janelia -* `Alistair Miles `_, University of Oxford -* `Josh Moore `_, University of Dundee -* `Charles Noyes `_, University of Southern California -* `Tarik Onalan `_ -* `Constantin Pape `_, University of Heidelberg -* `Zain Patel `_, University of Cambridge -* `Matthew Rocklin `_, NVIDIA -* `Stephan Saafeld `_, HHMI Janelia -* `Vincent Schut `_, Satelligence -* `Justin Swaney `_, MIT -* `Ryan Williams `_, Chan Zuckerberg Initiative diff --git a/docs/tutorial.rst b/docs/tutorial.rst deleted file mode 100644 index 4099bac1c8..0000000000 --- a/docs/tutorial.rst +++ /dev/null @@ -1,1690 +0,0 @@ -.. _tutorial: - -Tutorial -======== - -Zarr provides classes and functions for working with N-dimensional arrays that -behave like NumPy arrays but whose data is divided into chunks and each chunk is -compressed. If you are already familiar with HDF5 then Zarr arrays provide -similar functionality, but with some additional flexibility. - -.. _tutorial_create: - -Creating an array ------------------ - -Zarr has several functions for creating arrays. For example:: - - >>> import zarr - >>> z = zarr.zeros((10000, 10000), chunks=(1000, 1000), dtype='i4') - >>> z - - -The code above creates a 2-dimensional array of 32-bit integers with 10000 rows -and 10000 columns, divided into chunks where each chunk has 1000 rows and 1000 -columns (and so there will be 100 chunks in total). - -For a complete list of array creation routines see the :mod:`zarr.creation` -module documentation. - -.. _tutorial_array: - -Reading and writing data ------------------------- - -Zarr arrays support a similar interface to NumPy arrays for reading and writing -data. For example, the entire array can be filled with a scalar value:: - - >>> z[:] = 42 - -Regions of the array can also be written to, e.g.:: - - >>> import numpy as np - >>> z[0, :] = np.arange(10000) - >>> z[:, 0] = np.arange(10000) - -The contents of the array can be retrieved by slicing, which will load the -requested region into memory as a NumPy array, e.g.:: - - >>> z[0, 0] - 0 - >>> z[-1, -1] - 42 - >>> z[0, :] - array([ 0, 1, 2, ..., 9997, 9998, 9999], dtype=int32) - >>> z[:, 0] - array([ 0, 1, 2, ..., 9997, 9998, 9999], dtype=int32) - >>> z[:] - array([[ 0, 1, 2, ..., 9997, 9998, 9999], - [ 1, 42, 42, ..., 42, 42, 42], - [ 2, 42, 42, ..., 42, 42, 42], - ..., - [9997, 42, 42, ..., 42, 42, 42], - [9998, 42, 42, ..., 42, 42, 42], - [9999, 42, 42, ..., 42, 42, 42]], dtype=int32) - -.. _tutorial_persist: - -Persistent arrays ------------------ - -In the examples above, compressed data for each chunk of the array was stored in -main memory. Zarr arrays can also be stored on a file system, enabling -persistence of data between sessions. For example:: - - >>> z1 = zarr.open('data/example.zarr', mode='w', shape=(10000, 10000), - ... chunks=(1000, 1000), dtype='i4') - -The array above will store its configuration metadata and all compressed chunk -data in a directory called 'data/example.zarr' relative to the current working -directory. The :func:`zarr.convenience.open` function provides a convenient way -to create a new persistent array or continue working with an existing -array. Note that although the function is called "open", there is no need to -close an array: data are automatically flushed to disk, and files are -automatically closed whenever an array is modified. - -Persistent arrays support the same interface for reading and writing data, -e.g.:: - - >>> z1[:] = 42 - >>> z1[0, :] = np.arange(10000) - >>> z1[:, 0] = np.arange(10000) - -Check that the data have been written and can be read again:: - - >>> z2 = zarr.open('data/example.zarr', mode='r') - >>> np.all(z1[:] == z2[:]) - True - -If you are just looking for a fast and convenient way to save NumPy arrays to -disk then load back into memory later, the functions -:func:`zarr.convenience.save` and :func:`zarr.convenience.load` may be -useful. E.g.:: - - >>> a = np.arange(10) - >>> zarr.save('data/example.zarr', a) - >>> zarr.load('data/example.zarr') - array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) - -Please note that there are a number of other options for persistent array -storage, see the section on :ref:`tutorial_storage` below. - -.. _tutorial_resize: - -Resizing and appending ----------------------- - -A Zarr array can be resized, which means that any of its dimensions can be -increased or decreased in length. For example:: - - >>> z = zarr.zeros(shape=(10000, 10000), chunks=(1000, 1000)) - >>> z[:] = 42 - >>> z.resize(20000, 10000) - >>> z.shape - (20000, 10000) - -Note that when an array is resized, the underlying data are not rearranged in -any way. If one or more dimensions are shrunk, any chunks falling outside the -new array shape will be deleted from the underlying store. - -For convenience, Zarr arrays also provide an ``append()`` method, which can be -used to append data to any axis. E.g.:: - - >>> a = np.arange(10000000, dtype='i4').reshape(10000, 1000) - >>> z = zarr.array(a, chunks=(1000, 100)) - >>> z.shape - (10000, 1000) - >>> z.append(a) - (20000, 1000) - >>> z.append(np.vstack([a, a]), axis=1) - (20000, 2000) - >>> z.shape - (20000, 2000) - -.. _tutorial_compress: - -Compressors ------------ - -A number of different compressors can be used with Zarr. A separate package -called NumCodecs_ is available which provides a common interface to various -compressor libraries including Blosc, Zstandard, LZ4, Zlib, BZ2 and -LZMA. Different compressors can be provided via the ``compressor`` keyword -argument accepted by all array creation functions. For example:: - - >>> from numcodecs import Blosc - >>> compressor = Blosc(cname='zstd', clevel=3, shuffle=Blosc.BITSHUFFLE) - >>> data = np.arange(100000000, dtype='i4').reshape(10000, 10000) - >>> z = zarr.array(data, chunks=(1000, 1000), compressor=compressor) - >>> z.compressor - Blosc(cname='zstd', clevel=3, shuffle=BITSHUFFLE, blocksize=0) - -This array above will use Blosc as the primary compressor, using the Zstandard -algorithm (compression level 3) internally within Blosc, and with the -bit-shuffle filter applied. - -When using a compressor, it can be useful to get some diagnostics on the -compression ratio. Zarr arrays provide a ``info`` property which can be used to -print some diagnostics, e.g.:: - - >>> z.info - Type : zarr.core.Array - Data type : int32 - Shape : (10000, 10000) - Chunk shape : (1000, 1000) - Order : C - Read-only : False - Compressor : Blosc(cname='zstd', clevel=3, shuffle=BITSHUFFLE, - : blocksize=0) - Store type : zarr.storage.KVStore - No. bytes : 400000000 (381.5M) - No. bytes stored : 3379344 (3.2M) - Storage ratio : 118.4 - Chunks initialized : 100/100 - -If you don't specify a compressor, by default Zarr uses the Blosc -compressor. Blosc is generally very fast and can be configured in a variety of -ways to improve the compression ratio for different types of data. Blosc is in -fact a "meta-compressor", which means that it can use a number of different -compression algorithms internally to compress the data. Blosc also provides -highly optimized implementations of byte- and bit-shuffle filters, which can -improve compression ratios for some data. A list of the internal compression -libraries available within Blosc can be obtained via:: - - >>> from numcodecs import blosc - >>> blosc.list_compressors() - ['blosclz', 'lz4', 'lz4hc', 'snappy', 'zlib', 'zstd'] - -In addition to Blosc, other compression libraries can also be used. For example, -here is an array using Zstandard compression, level 1:: - - >>> from numcodecs import Zstd - >>> z = zarr.array(np.arange(100000000, dtype='i4').reshape(10000, 10000), - ... chunks=(1000, 1000), compressor=Zstd(level=1)) - >>> z.compressor - Zstd(level=1) - -Here is an example using LZMA with a custom filter pipeline including LZMA's -built-in delta filter:: - - >>> import lzma - >>> lzma_filters = [dict(id=lzma.FILTER_DELTA, dist=4), - ... dict(id=lzma.FILTER_LZMA2, preset=1)] - >>> from numcodecs import LZMA - >>> compressor = LZMA(filters=lzma_filters) - >>> z = zarr.array(np.arange(100000000, dtype='i4').reshape(10000, 10000), - ... chunks=(1000, 1000), compressor=compressor) - >>> z.compressor - LZMA(format=1, check=-1, preset=None, filters=[{'dist': 4, 'id': 3}, {'id': 33, 'preset': 1}]) - -The default compressor can be changed by setting the value of the -``zarr.storage.default_compressor`` variable, e.g.:: - - >>> import zarr.storage - >>> from numcodecs import Zstd, Blosc - >>> # switch to using Zstandard - ... zarr.storage.default_compressor = Zstd(level=1) - >>> z = zarr.zeros(100000000, chunks=1000000) - >>> z.compressor - Zstd(level=1) - >>> # switch back to Blosc defaults - ... zarr.storage.default_compressor = Blosc() - -To disable compression, set ``compressor=None`` when creating an array, e.g.:: - - >>> z = zarr.zeros(100000000, chunks=1000000, compressor=None) - >>> z.compressor is None - True - -.. _tutorial_filters: - -Filters -------- - -In some cases, compression can be improved by transforming the data in some -way. For example, if nearby values tend to be correlated, then shuffling the -bytes within each numerical value or storing the difference between adjacent -values may increase compression ratio. Some compressors provide built-in filters -that apply transformations to the data prior to compression. For example, the -Blosc compressor has built-in implementations of byte- and bit-shuffle filters, -and the LZMA compressor has a built-in implementation of a delta -filter. However, to provide additional flexibility for implementing and using -filters in combination with different compressors, Zarr also provides a -mechanism for configuring filters outside of the primary compressor. - -Here is an example using a delta filter with the Blosc compressor:: - - >>> from numcodecs import Blosc, Delta - >>> filters = [Delta(dtype='i4')] - >>> compressor = Blosc(cname='zstd', clevel=1, shuffle=Blosc.SHUFFLE) - >>> data = np.arange(100000000, dtype='i4').reshape(10000, 10000) - >>> z = zarr.array(data, chunks=(1000, 1000), filters=filters, compressor=compressor) - >>> z.info - Type : zarr.core.Array - Data type : int32 - Shape : (10000, 10000) - Chunk shape : (1000, 1000) - Order : C - Read-only : False - Filter [0] : Delta(dtype='`_ documentation. - -.. _tutorial_groups: - -Groups ------- - -Zarr supports hierarchical organization of arrays via groups. As with arrays, -groups can be stored in memory, on disk, or via other storage systems that -support a similar interface. - -To create a group, use the :func:`zarr.group` function:: - - >>> root = zarr.group() - >>> root - - -Groups have a similar API to the Group class from `h5py -`_. For example, groups can contain other groups:: - - >>> foo = root.create_group('foo') - >>> bar = foo.create_group('bar') - -Groups can also contain arrays, e.g.:: - - >>> z1 = bar.zeros('baz', shape=(10000, 10000), chunks=(1000, 1000), dtype='i4') - >>> z1 - - -Arrays are known as "datasets" in HDF5 terminology. For compatibility with h5py, -Zarr groups also implement the ``create_dataset()`` and ``require_dataset()`` -methods, e.g.:: - - >>> z = bar.create_dataset('quux', shape=(10000, 10000), chunks=(1000, 1000), dtype='i4') - >>> z - - -Members of a group can be accessed via the suffix notation, e.g.:: - - >>> root['foo'] - - -The '/' character can be used to access multiple levels of the hierarchy in one -call, e.g.:: - - >>> root['foo/bar'] - - >>> root['foo/bar/baz'] - - -The :func:`zarr.hierarchy.Group.tree` method can be used to print a tree -representation of the hierarchy, e.g.:: - - >>> root.tree() - / - └── foo - └── bar - β”œβ”€β”€ baz (10000, 10000) int32 - └── quux (10000, 10000) int32 - -The :func:`zarr.convenience.open` function provides a convenient way to create or -re-open a group stored in a directory on the file-system, with sub-groups stored in -sub-directories, e.g.:: - - >>> root = zarr.open('data/group.zarr', mode='w') - >>> root - - >>> z = root.zeros('foo/bar/baz', shape=(10000, 10000), chunks=(1000, 1000), dtype='i4') - >>> z - - -Groups can be used as context managers (in a ``with`` statement). -If the underlying store has a ``close`` method, it will be called on exit. - -For more information on groups see the :mod:`zarr.hierarchy` and -:mod:`zarr.convenience` API docs. - -.. _tutorial_diagnostics: - -Array and group diagnostics ---------------------------- - -Diagnostic information about arrays and groups is available via the ``info`` -property. E.g.:: - - >>> root = zarr.group() - >>> foo = root.create_group('foo') - >>> bar = foo.zeros('bar', shape=1000000, chunks=100000, dtype='i8') - >>> bar[:] = 42 - >>> baz = foo.zeros('baz', shape=(1000, 1000), chunks=(100, 100), dtype='f4') - >>> baz[:] = 4.2 - >>> root.info - Name : / - Type : zarr.hierarchy.Group - Read-only : False - Store type : zarr.storage.MemoryStore - No. members : 1 - No. arrays : 0 - No. groups : 1 - Groups : foo - - >>> foo.info - Name : /foo - Type : zarr.hierarchy.Group - Read-only : False - Store type : zarr.storage.MemoryStore - No. members : 2 - No. arrays : 2 - No. groups : 0 - Arrays : bar, baz - - >>> bar.info - Name : /foo/bar - Type : zarr.core.Array - Data type : int64 - Shape : (1000000,) - Chunk shape : (100000,) - Order : C - Read-only : False - Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0) - Store type : zarr.storage.MemoryStore - No. bytes : 8000000 (7.6M) - No. bytes stored : 33240 (32.5K) - Storage ratio : 240.7 - Chunks initialized : 10/10 - - >>> baz.info - Name : /foo/baz - Type : zarr.core.Array - Data type : float32 - Shape : (1000, 1000) - Chunk shape : (100, 100) - Order : C - Read-only : False - Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0) - Store type : zarr.storage.MemoryStore - No. bytes : 4000000 (3.8M) - No. bytes stored : 23943 (23.4K) - Storage ratio : 167.1 - Chunks initialized : 100/100 - -Groups also have the :func:`zarr.hierarchy.Group.tree` method, e.g.:: - - >>> root.tree() - / - └── foo - β”œβ”€β”€ bar (1000000,) int64 - └── baz (1000, 1000) float32 - -If you're using Zarr within a Jupyter notebook (requires -`ipytree `_), calling ``tree()`` will generate an -interactive tree representation, see the `repr_tree.ipynb notebook -`_ -for more examples. - -.. _tutorial_attrs: - -User attributes ---------------- - -Zarr arrays and groups support custom key/value attributes, which can be useful for -storing application-specific metadata. For example:: - - >>> root = zarr.group() - >>> root.attrs['foo'] = 'bar' - >>> z = root.zeros('zzz', shape=(10000, 10000)) - >>> z.attrs['baz'] = 42 - >>> z.attrs['qux'] = [1, 4, 7, 12] - >>> sorted(root.attrs) - ['foo'] - >>> 'foo' in root.attrs - True - >>> root.attrs['foo'] - 'bar' - >>> sorted(z.attrs) - ['baz', 'qux'] - >>> z.attrs['baz'] - 42 - >>> z.attrs['qux'] - [1, 4, 7, 12] - -Internally Zarr uses JSON to store array attributes, so attribute values must be -JSON serializable. - -.. _tutorial_indexing: - -Advanced indexing ------------------ - -As of version 2.2, Zarr arrays support several methods for advanced or "fancy" -indexing, which enable a subset of data items to be extracted or updated in an -array without loading the entire array into memory. - -Note that although this functionality is similar to some of the advanced -indexing capabilities available on NumPy arrays and on h5py datasets, **the Zarr -API for advanced indexing is different from both NumPy and h5py**, so please -read this section carefully. For a complete description of the indexing API, -see the documentation for the :class:`zarr.core.Array` class. - -Indexing with coordinate arrays -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Items from a Zarr array can be extracted by providing an integer array of -coordinates. E.g.:: - - >>> z = zarr.array(np.arange(10) ** 2) - >>> z[:] - array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81]) - >>> z.get_coordinate_selection([2, 5]) - array([ 4, 25]) - -Coordinate arrays can also be used to update data, e.g.:: - - >>> z.set_coordinate_selection([2, 5], [-1, -2]) - >>> z[:] - array([ 0, 1, -1, 9, 16, -2, 36, 49, 64, 81]) - -For multidimensional arrays, coordinates must be provided for each dimension, -e.g.:: - - >>> z = zarr.array(np.arange(15).reshape(3, 5)) - >>> z[:] - array([[ 0, 1, 2, 3, 4], - [ 5, 6, 7, 8, 9], - [10, 11, 12, 13, 14]]) - >>> z.get_coordinate_selection(([0, 2], [1, 3])) - array([ 1, 13]) - >>> z.set_coordinate_selection(([0, 2], [1, 3]), [-1, -2]) - >>> z[:] - array([[ 0, -1, 2, 3, 4], - [ 5, 6, 7, 8, 9], - [10, 11, 12, -2, 14]]) - -For convenience, coordinate indexing is also available via the ``vindex`` -property, as well as the square bracket operator, e.g.:: - - >>> z.vindex[[0, 2], [1, 3]] - array([-1, -2]) - >>> z.vindex[[0, 2], [1, 3]] = [-3, -4] - >>> z[:] - array([[ 0, -3, 2, 3, 4], - [ 5, 6, 7, 8, 9], - [10, 11, 12, -4, 14]]) - >>> z[[0, 2], [1, 3]] - array([-3, -4]) - -When the indexing arrays have different shapes, they are broadcast together. -That is, the following two calls are equivalent:: - - >>> z[1, [1, 3]] - array([6, 8]) - >>> z[[1, 1], [1, 3]] - array([6, 8]) - -Indexing with a mask array -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Items can also be extracted by providing a Boolean mask. E.g.:: - - >>> z = zarr.array(np.arange(10) ** 2) - >>> z[:] - array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81]) - >>> sel = np.zeros_like(z, dtype=bool) - >>> sel[2] = True - >>> sel[5] = True - >>> z.get_mask_selection(sel) - array([ 4, 25]) - >>> z.set_mask_selection(sel, [-1, -2]) - >>> z[:] - array([ 0, 1, -1, 9, 16, -2, 36, 49, 64, 81]) - -Here's a multidimensional example:: - - >>> z = zarr.array(np.arange(15).reshape(3, 5)) - >>> z[:] - array([[ 0, 1, 2, 3, 4], - [ 5, 6, 7, 8, 9], - [10, 11, 12, 13, 14]]) - >>> sel = np.zeros_like(z, dtype=bool) - >>> sel[0, 1] = True - >>> sel[2, 3] = True - >>> z.get_mask_selection(sel) - array([ 1, 13]) - >>> z.set_mask_selection(sel, [-1, -2]) - >>> z[:] - array([[ 0, -1, 2, 3, 4], - [ 5, 6, 7, 8, 9], - [10, 11, 12, -2, 14]]) - -For convenience, mask indexing is also available via the ``vindex`` property, -e.g.:: - - >>> z.vindex[sel] - array([-1, -2]) - >>> z.vindex[sel] = [-3, -4] - >>> z[:] - array([[ 0, -3, 2, 3, 4], - [ 5, 6, 7, 8, 9], - [10, 11, 12, -4, 14]]) - -Mask indexing is conceptually the same as coordinate indexing, and is -implemented internally via the same machinery. Both styles of indexing allow -selecting arbitrary items from an array, also known as point selection. - -Orthogonal indexing -~~~~~~~~~~~~~~~~~~~ - -Zarr arrays also support methods for orthogonal indexing, which allows -selections to be made along each dimension of an array independently. For -example, this allows selecting a subset of rows and/or columns from a -2-dimensional array. E.g.:: - - >>> z = zarr.array(np.arange(15).reshape(3, 5)) - >>> z[:] - array([[ 0, 1, 2, 3, 4], - [ 5, 6, 7, 8, 9], - [10, 11, 12, 13, 14]]) - >>> z.get_orthogonal_selection(([0, 2], slice(None))) # select first and third rows - array([[ 0, 1, 2, 3, 4], - [10, 11, 12, 13, 14]]) - >>> z.get_orthogonal_selection((slice(None), [1, 3])) # select second and fourth columns - array([[ 1, 3], - [ 6, 8], - [11, 13]]) - >>> z.get_orthogonal_selection(([0, 2], [1, 3])) # select rows [0, 2] and columns [1, 4] - array([[ 1, 3], - [11, 13]]) - -Data can also be modified, e.g.:: - - >>> z.set_orthogonal_selection(([0, 2], [1, 3]), [[-1, -2], [-3, -4]]) - >>> z[:] - array([[ 0, -1, 2, -2, 4], - [ 5, 6, 7, 8, 9], - [10, -3, 12, -4, 14]]) - -For convenience, the orthogonal indexing functionality is also available via the -``oindex`` property, e.g.:: - - >>> z = zarr.array(np.arange(15).reshape(3, 5)) - >>> z.oindex[[0, 2], :] # select first and third rows - array([[ 0, 1, 2, 3, 4], - [10, 11, 12, 13, 14]]) - >>> z.oindex[:, [1, 3]] # select second and fourth columns - array([[ 1, 3], - [ 6, 8], - [11, 13]]) - >>> z.oindex[[0, 2], [1, 3]] # select rows [0, 2] and columns [1, 4] - array([[ 1, 3], - [11, 13]]) - >>> z.oindex[[0, 2], [1, 3]] = [[-1, -2], [-3, -4]] - >>> z[:] - array([[ 0, -1, 2, -2, 4], - [ 5, 6, 7, 8, 9], - [10, -3, 12, -4, 14]]) - -Any combination of integer, slice, 1D integer array and/or 1D Boolean array can -be used for orthogonal indexing. - -If the index contains at most one iterable, and otherwise contains only slices and integers, -orthogonal indexing is also available directly on the array: - - >>> z = zarr.array(np.arange(15).reshape(3, 5)) - >>> all(z.oindex[[0, 2], :] == z[[0, 2], :]) - True - -Block Indexing -~~~~~~~~~~~~~~ - -As of version 2.16.0, Zarr also support block indexing, which allows -selections of whole chunks based on their logical indices along each dimension -of an array. For example, this allows selecting a subset of chunk aligned rows and/or -columns from a 2-dimensional array. E.g.:: - - >>> import zarr - >>> import numpy as np - >>> z = zarr.array(np.arange(100).reshape(10, 10), chunks=(3, 3)) - -Retrieve items by specifying their block coordinates:: - - >>> z.get_block_selection(1) - array([[30, 31, 32, 33, 34, 35, 36, 37, 38, 39], - [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], - [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]) - -Equivalent slicing:: - - >>> z[3:6] - array([[30, 31, 32, 33, 34, 35, 36, 37, 38, 39], - [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], - [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]) - - -For convenience, the block selection functionality is also available via the -`blocks` property, e.g.:: - - >>> z.blocks[1] - array([[30, 31, 32, 33, 34, 35, 36, 37, 38, 39], - [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], - [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]) - -Block index arrays may be multidimensional to index multidimensional arrays. -For example:: - - >>> z.blocks[0, 1:3] - array([[ 3, 4, 5, 6, 7, 8], - [13, 14, 15, 16, 17, 18], - [23, 24, 25, 26, 27, 28]]) - -Data can also be modified. Let's start by a simple 2D array:: - - >>> import zarr - >>> import numpy as np - >>> z = zarr.zeros((6, 6), dtype=int, chunks=2) - -Set data for a selection of items:: - - >>> z.set_block_selection((1, 0), 1) - >>> z[...] - array([[0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0]]) - -For convenience, this functionality is also available via the ``blocks`` property. -E.g.:: - - >>> z.blocks[:, 2] = 7 - >>> z[...] - array([[0, 0, 0, 0, 7, 7], - [0, 0, 0, 0, 7, 7], - [1, 1, 0, 0, 7, 7], - [1, 1, 0, 0, 7, 7], - [0, 0, 0, 0, 7, 7], - [0, 0, 0, 0, 7, 7]]) - -Any combination of integer and slice can be used for block indexing:: - - >>> z.blocks[2, 1:3] - array([[0, 0, 7, 7], - [0, 0, 7, 7]]) - -Indexing fields in structured arrays -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -All selection methods support a ``fields`` parameter which allows retrieving or -replacing data for a specific field in an array with a structured dtype. E.g.:: - - >>> a = np.array([(b'aaa', 1, 4.2), - ... (b'bbb', 2, 8.4), - ... (b'ccc', 3, 12.6)], - ... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')]) - >>> z = zarr.array(a) - >>> z['foo'] - array([b'aaa', b'bbb', b'ccc'], - dtype='|S3') - >>> z['baz'] - array([ 4.2, 8.4, 12.6]) - >>> z.get_basic_selection(slice(0, 2), fields='bar') - array([1, 2], dtype=int32) - >>> z.get_coordinate_selection([0, 2], fields=['foo', 'baz']) - array([(b'aaa', 4.2), (b'ccc', 12.6)], - dtype=[('foo', 'S3'), ('baz', '>> z = zarr.open('data/example.zarr', mode='w', shape=1000000, dtype='i4') - -...is short-hand for:: - - >>> store = zarr.DirectoryStore('data/example.zarr') - >>> z = zarr.create(store=store, overwrite=True, shape=1000000, dtype='i4') - -...and the following code:: - - >>> root = zarr.open('data/example.zarr', mode='w') - -...is short-hand for:: - - >>> store = zarr.DirectoryStore('data/example.zarr') - >>> root = zarr.group(store=store, overwrite=True) - -Any other compatible storage class could be used in place of -:class:`zarr.storage.DirectoryStore` in the code examples above. For example, -here is an array stored directly into a Zip file, via the -:class:`zarr.storage.ZipStore` class:: - - >>> store = zarr.ZipStore('data/example.zip', mode='w') - >>> root = zarr.group(store=store) - >>> z = root.zeros('foo/bar', shape=(1000, 1000), chunks=(100, 100), dtype='i4') - >>> z[:] = 42 - >>> store.close() - -Re-open and check that data have been written:: - - >>> store = zarr.ZipStore('data/example.zip', mode='r') - >>> root = zarr.group(store=store) - >>> z = root['foo/bar'] - >>> z[:] - array([[42, 42, 42, ..., 42, 42, 42], - [42, 42, 42, ..., 42, 42, 42], - [42, 42, 42, ..., 42, 42, 42], - ..., - [42, 42, 42, ..., 42, 42, 42], - [42, 42, 42, ..., 42, 42, 42], - [42, 42, 42, ..., 42, 42, 42]], dtype=int32) - >>> store.close() - -Note that there are some limitations on how Zip files can be used, because items -within a Zip file cannot be updated in place. This means that data in the array -should only be written once and write operations should be aligned with chunk -boundaries. Note also that the ``close()`` method must be called after writing -any data to the store, otherwise essential records will not be written to the -underlying zip file. - -Another storage alternative is the :class:`zarr.storage.DBMStore` class, added -in Zarr version 2.2. This class allows any DBM-style database to be used for -storing an array or group. Here is an example using a Berkeley DB B-tree -database for storage (requires `bsddb3 -`_ to be installed):: - - >>> import bsddb3 - >>> store = zarr.DBMStore('data/example.bdb', open=bsddb3.btopen) - >>> root = zarr.group(store=store, overwrite=True) - >>> z = root.zeros('foo/bar', shape=(1000, 1000), chunks=(100, 100), dtype='i4') - >>> z[:] = 42 - >>> store.close() - -Also added in Zarr version 2.2 is the :class:`zarr.storage.LMDBStore` class which -enables the lightning memory-mapped database (LMDB) to be used for storing an array or -group (requires `lmdb `_ to be installed):: - - >>> store = zarr.LMDBStore('data/example.lmdb') - >>> root = zarr.group(store=store, overwrite=True) - >>> z = root.zeros('foo/bar', shape=(1000, 1000), chunks=(100, 100), dtype='i4') - >>> z[:] = 42 - >>> store.close() - -In Zarr version 2.3 is the :class:`zarr.storage.SQLiteStore` class which -enables the SQLite database to be used for storing an array or group (requires -Python is built with SQLite support):: - - >>> store = zarr.SQLiteStore('data/example.sqldb') - >>> root = zarr.group(store=store, overwrite=True) - >>> z = root.zeros('foo/bar', shape=(1000, 1000), chunks=(100, 100), dtype='i4') - >>> z[:] = 42 - >>> store.close() - -Also added in Zarr version 2.3 are two storage classes for interfacing with server-client -databases. The :class:`zarr.storage.RedisStore` class interfaces `Redis `_ -(an in memory data structure store), and the :class:`zarr.storage.MongoDB` class interfaces -with `MongoDB `_ (an object oriented NoSQL database). These stores -respectively require the `redis-py `_ and -`pymongo `_ packages to be installed. - -For compatibility with the `N5 `_ data format, Zarr also provides -an N5 backend (this is currently an experimental feature). Similar to the zip storage class, an -:class:`zarr.n5.N5Store` can be instantiated directly:: - - >>> store = zarr.N5Store('data/example.n5') - >>> root = zarr.group(store=store) - >>> z = root.zeros('foo/bar', shape=(1000, 1000), chunks=(100, 100), dtype='i4') - >>> z[:] = 42 - -For convenience, the N5 backend will automatically be chosen when the filename -ends with `.n5`:: - - >>> root = zarr.open('data/example.n5', mode='w') - -Distributed/cloud storage -~~~~~~~~~~~~~~~~~~~~~~~~~ - -It is also possible to use distributed storage systems. The Dask project has -implementations of the ``MutableMapping`` interface for Amazon S3 (`S3Map -`_), Hadoop -Distributed File System (`HDFSMap -`_) and -Google Cloud Storage (`GCSMap -`_), which -can be used with Zarr. - -Here is an example using S3Map to read an array created previously:: - - >>> import s3fs - >>> import zarr - >>> s3 = s3fs.S3FileSystem(anon=True, client_kwargs=dict(region_name='eu-west-2')) - >>> store = s3fs.S3Map(root='zarr-demo/store', s3=s3, check=False) - >>> root = zarr.group(store=store) - >>> z = root['foo/bar/baz'] - >>> z - - >>> z.info - Name : /foo/bar/baz - Type : zarr.core.Array - Data type : |S1 - Shape : (21,) - Chunk shape : (7,) - Order : C - Read-only : False - Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0) - Store type : zarr.storage.KVStore - No. bytes : 21 - No. bytes stored : 382 - Storage ratio : 0.1 - Chunks initialized : 3/3 - >>> z[:] - array([b'H', b'e', b'l', b'l', b'o', b' ', b'f', b'r', b'o', b'm', b' ', - b't', b'h', b'e', b' ', b'c', b'l', b'o', b'u', b'd', b'!'], - dtype='|S1') - >>> z[:].tobytes() - b'Hello from the cloud!' - -Zarr now also has a builtin storage backend for Azure Blob Storage. -The class is :class:`zarr.storage.ABSStore` (requires -`azure-storage-blob `_ -to be installed):: - - >>> import azure.storage.blob - >>> container_client = azure.storage.blob.ContainerClient(...) # doctest: +SKIP - >>> store = zarr.ABSStore(client=container_client, prefix='zarr-testing') # doctest: +SKIP - >>> root = zarr.group(store=store, overwrite=True) # doctest: +SKIP - >>> z = root.zeros('foo/bar', shape=(1000, 1000), chunks=(100, 100), dtype='i4') # doctest: +SKIP - >>> z[:] = 42 # doctest: +SKIP - -When using an actual storage account, provide ``account_name`` and -``account_key`` arguments to :class:`zarr.storage.ABSStore`, the -above client is just testing against the emulator. Please also note -that this is an experimental feature. - -Note that retrieving data from a remote service via the network can be significantly -slower than retrieving data from a local file system, and will depend on network latency -and bandwidth between the client and server systems. If you are experiencing poor -performance, there are several things you can try. One option is to increase the array -chunk size, which will reduce the number of chunks and thus reduce the number of network -round-trips required to retrieve data for an array (and thus reduce the impact of network -latency). Another option is to try to increase the compression ratio by changing -compression options or trying a different compressor (which will reduce the impact of -limited network bandwidth). - -As of version 2.2, Zarr also provides the :class:`zarr.storage.LRUStoreCache` -which can be used to implement a local in-memory cache layer over a remote -store. E.g.:: - - >>> s3 = s3fs.S3FileSystem(anon=True, client_kwargs=dict(region_name='eu-west-2')) - >>> store = s3fs.S3Map(root='zarr-demo/store', s3=s3, check=False) - >>> cache = zarr.LRUStoreCache(store, max_size=2**28) - >>> root = zarr.group(store=cache) - >>> z = root['foo/bar/baz'] - >>> from timeit import timeit - >>> # first data access is relatively slow, retrieved from store - ... timeit('print(z[:].tobytes())', number=1, globals=globals()) # doctest: +SKIP - b'Hello from the cloud!' - 0.1081731989979744 - >>> # second data access is faster, uses cache - ... timeit('print(z[:].tobytes())', number=1, globals=globals()) # doctest: +SKIP - b'Hello from the cloud!' - 0.0009490990014455747 - -If you are still experiencing poor performance with distributed/cloud storage, -please raise an issue on the GitHub issue tracker with any profiling data you -can provide, as there may be opportunities to optimise further either within -Zarr or within the mapping interface to the storage. - -IO with ``fsspec`` -~~~~~~~~~~~~~~~~~~ - -As of version 2.5, zarr supports passing URLs directly to `fsspec`_, -and having it create the "mapping" instance automatically. This means, that -for all of the backend storage implementations `supported by fsspec`_, -you can skip importing and configuring the storage explicitly. -For example:: - - >>> g = zarr.open_group("s3://zarr-demo/store", storage_options={'anon': True}) # doctest: +SKIP - >>> g['foo/bar/baz'][:].tobytes() # doctest: +SKIP - b'Hello from the cloud!' - -The provision of the protocol specifier "s3://" will select the correct backend. -Notice the kwargs ``storage_options``, used to pass parameters to that backend. - -As of version 2.6, write mode and complex URLs are also supported, such as:: - - >>> g = zarr.open_group("simplecache::s3://zarr-demo/store", - ... storage_options={"s3": {'anon': True}}) # doctest: +SKIP - >>> g['foo/bar/baz'][:].tobytes() # downloads target file # doctest: +SKIP - b'Hello from the cloud!' - >>> g['foo/bar/baz'][:].tobytes() # uses cached file # doctest: +SKIP - b'Hello from the cloud!' - -The second invocation here will be much faster. Note that the ``storage_options`` -have become more complex here, to account for the two parts of the supplied -URL. - -It is also possible to initialize the filesystem outside of Zarr and then pass -it through. This requires creating an :class:`zarr.storage.FSStore` object -explicitly. For example:: - - >>> import s3fs # doctest: +SKIP - >>> fs = s3fs.S3FileSystem(anon=True) # doctest: +SKIP - >>> store = zarr.storage.FSStore('/zarr-demo/store', fs=fs) # doctest: +SKIP - >>> g = zarr.open_group(store) # doctest: +SKIP - -This is useful in cases where you want to also use the same fsspec filesystem object -separately from Zarr. - -.. _fsspec: https://filesystem-spec.readthedocs.io/en/latest/ - -.. _supported by fsspec: https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations - -.. _tutorial_copy: - -Consolidating metadata -~~~~~~~~~~~~~~~~~~~~~~ - -Since there is a significant overhead for every connection to a cloud object -store such as S3, the pattern described in the previous section may incur -significant latency while scanning the metadata of the array hierarchy, even -though each individual metadata object is small. For cases such as these, once -the data are static and can be regarded as read-only, at least for the -metadata/structure of the array hierarchy, the many metadata objects can be -consolidated into a single one via -:func:`zarr.convenience.consolidate_metadata`. Doing this can greatly increase -the speed of reading the array metadata, e.g.:: - - >>> zarr.consolidate_metadata(store) # doctest: +SKIP - -This creates a special key with a copy of all of the metadata from all of the -metadata objects in the store. - -Later, to open a Zarr store with consolidated metadata, use -:func:`zarr.convenience.open_consolidated`, e.g.:: - - >>> root = zarr.open_consolidated(store) # doctest: +SKIP - -This uses the special key to read all of the metadata in a single call to the -backend storage. - -Note that, the hierarchy could still be opened in the normal way and altered, -causing the consolidated metadata to become out of sync with the real state of -the array hierarchy. In this case, -:func:`zarr.convenience.consolidate_metadata` would need to be called again. - -To protect against consolidated metadata accidentally getting out of sync, the -root group returned by :func:`zarr.convenience.open_consolidated` is read-only -for the metadata, meaning that no new groups or arrays can be created, and -arrays cannot be resized. However, data values with arrays can still be updated. - -Copying/migrating data ----------------------- - -If you have some data in an HDF5 file and would like to copy some or all of it -into a Zarr group, or vice-versa, the :func:`zarr.convenience.copy` and -:func:`zarr.convenience.copy_all` functions can be used. Here's an example -copying a group named 'foo' from an HDF5 file to a Zarr group:: - - >>> import h5py - >>> import zarr - >>> import numpy as np - >>> source = h5py.File('data/example.h5', mode='w') - >>> foo = source.create_group('foo') - >>> baz = foo.create_dataset('bar/baz', data=np.arange(100), chunks=(50,)) - >>> spam = source.create_dataset('spam', data=np.arange(100, 200), chunks=(30,)) - >>> zarr.tree(source) - / - β”œβ”€β”€ foo - β”‚ └── bar - β”‚ └── baz (100,) int64 - └── spam (100,) int64 - >>> dest = zarr.open_group('data/example.zarr', mode='w') - >>> from sys import stdout - >>> zarr.copy(source['foo'], dest, log=stdout) - copy /foo - copy /foo/bar - copy /foo/bar/baz (100,) int64 - all done: 3 copied, 0 skipped, 800 bytes copied - (3, 0, 800) - >>> dest.tree() # N.B., no spam - / - └── foo - └── bar - └── baz (100,) int64 - >>> source.close() - -If rather than copying a single group or array you would like to copy all -groups and arrays, use :func:`zarr.convenience.copy_all`, e.g.:: - - >>> source = h5py.File('data/example.h5', mode='r') - >>> dest = zarr.open_group('data/example2.zarr', mode='w') - >>> zarr.copy_all(source, dest, log=stdout) - copy /foo - copy /foo/bar - copy /foo/bar/baz (100,) int64 - copy /spam (100,) int64 - all done: 4 copied, 0 skipped, 1,600 bytes copied - (4, 0, 1600) - >>> dest.tree() - / - β”œβ”€β”€ foo - β”‚ └── bar - β”‚ └── baz (100,) int64 - └── spam (100,) int64 - -If you need to copy data between two Zarr groups, the -:func:`zarr.convenience.copy` and :func:`zarr.convenience.copy_all` functions can -be used and provide the most flexibility. However, if you want to copy data -in the most efficient way possible, without changing any configuration options, -the :func:`zarr.convenience.copy_store` function can be used. This function -copies data directly between the underlying stores, without any decompression or -re-compression, and so should be faster. E.g.:: - - >>> import zarr - >>> import numpy as np - >>> store1 = zarr.DirectoryStore('data/example.zarr') - >>> root = zarr.group(store1, overwrite=True) - >>> baz = root.create_dataset('foo/bar/baz', data=np.arange(100), chunks=(50,)) - >>> spam = root.create_dataset('spam', data=np.arange(100, 200), chunks=(30,)) - >>> root.tree() - / - β”œβ”€β”€ foo - β”‚ └── bar - β”‚ └── baz (100,) int64 - └── spam (100,) int64 - >>> from sys import stdout - >>> store2 = zarr.ZipStore('data/example.zip', mode='w') - >>> zarr.copy_store(store1, store2, log=stdout) - copy .zgroup - copy foo/.zgroup - copy foo/bar/.zgroup - copy foo/bar/baz/.zarray - copy foo/bar/baz/0 - copy foo/bar/baz/1 - copy spam/.zarray - copy spam/0 - copy spam/1 - copy spam/2 - copy spam/3 - all done: 11 copied, 0 skipped, 1,138 bytes copied - (11, 0, 1138) - >>> new_root = zarr.group(store2) - >>> new_root.tree() - / - β”œβ”€β”€ foo - β”‚ └── bar - β”‚ └── baz (100,) int64 - └── spam (100,) int64 - >>> new_root['foo/bar/baz'][:] - array([ 0, 1, 2, ..., 97, 98, 99]) - >>> store2.close() # zip stores need to be closed - -.. _tutorial_strings: - -String arrays -------------- - -There are several options for storing arrays of strings. - -If your strings are all ASCII strings, and you know the maximum length of the string in -your array, then you can use an array with a fixed-length bytes dtype. E.g.:: - - >>> z = zarr.zeros(10, dtype='S6') - >>> z - - >>> z[0] = b'Hello' - >>> z[1] = b'world!' - >>> z[:] - array([b'Hello', b'world!', b'', b'', b'', b'', b'', b'', b'', b''], - dtype='|S6') - -A fixed-length unicode dtype is also available, e.g.:: - - >>> greetings = ['Β‘Hola mundo!', 'Hej VΓ€rlden!', 'Servus Woid!', 'Hei maailma!', - ... 'Xin chΓ o thαΊΏ giα»›i', 'Njatjeta BotΓ«!', 'ΓΡια σου ΞΊΟŒΟƒΞΌΞ΅!', - ... 'γ“γ‚“γ«γ‘γ―δΈ–η•Œ', 'δΈ–η•ŒοΌŒδ½ ε₯½οΌ', 'HellΓ³, vilΓ‘g!', 'Zdravo svete!', - ... 'ΰΉ€ΰΈΰΈ₯ΰΉ‚ΰΈ₯ΰΉ€ΰΈ§ΰΈ΄ΰΈ₯ΰΈ”ΰΉŒ'] - >>> text_data = greetings * 10000 - >>> z = zarr.array(text_data, dtype='U20') - >>> z - - >>> z[:] - array(['Β‘Hola mundo!', 'Hej VΓ€rlden!', 'Servus Woid!', ..., - 'HellΓ³, vilΓ‘g!', 'Zdravo svete!', 'ΰΉ€ΰΈΰΈ₯ΰΉ‚ΰΈ₯ΰΉ€ΰΈ§ΰΈ΄ΰΈ₯ΰΈ”ΰΉŒ'], - dtype='>> import numcodecs - >>> z = zarr.array(text_data, dtype=object, object_codec=numcodecs.VLenUTF8()) - >>> z - - >>> z.filters - [VLenUTF8()] - >>> z[:] - array(['Β‘Hola mundo!', 'Hej VΓ€rlden!', 'Servus Woid!', ..., - 'HellΓ³, vilΓ‘g!', 'Zdravo svete!', 'ΰΉ€ΰΈΰΈ₯ΰΉ‚ΰΈ₯ΰΉ€ΰΈ§ΰΈ΄ΰΈ₯ΰΈ”ΰΉŒ'], dtype=object) - -As a convenience, ``dtype=str`` (or ``dtype=unicode`` on Python 2.7) can be used, which -is a short-hand for ``dtype=object, object_codec=numcodecs.VLenUTF8()``, e.g.:: - - >>> z = zarr.array(text_data, dtype=str) - >>> z - - >>> z.filters - [VLenUTF8()] - >>> z[:] - array(['Β‘Hola mundo!', 'Hej VΓ€rlden!', 'Servus Woid!', ..., - 'HellΓ³, vilΓ‘g!', 'Zdravo svete!', 'ΰΉ€ΰΈΰΈ₯ΰΉ‚ΰΈ₯ΰΉ€ΰΈ§ΰΈ΄ΰΈ₯ΰΈ”ΰΉŒ'], dtype=object) - -Variable-length byte strings are also supported via ``dtype=object``. Again an -``object_codec`` is required, which can be one of :class:`numcodecs.vlen.VLenBytes` or -:class:`numcodecs.pickles.Pickle`. For convenience, ``dtype=bytes`` (or ``dtype=str`` on Python -2.7) can be used as a short-hand for ``dtype=object, object_codec=numcodecs.VLenBytes()``, -e.g.:: - - >>> bytes_data = [g.encode('utf-8') for g in greetings] * 10000 - >>> z = zarr.array(bytes_data, dtype=bytes) - >>> z - - >>> z.filters - [VLenBytes()] - >>> z[:] - array([b'\xc2\xa1Hola mundo!', b'Hej V\xc3\xa4rlden!', b'Servus Woid!', - ..., b'Hell\xc3\xb3, vil\xc3\xa1g!', b'Zdravo svete!', - b'\xe0\xb9\x80\xe0\xb8\xae\xe0\xb8\xa5\xe0\xb9\x82\xe0\xb8\xa5\xe0\xb9\x80\xe0\xb8\xa7\xe0\xb8\xb4\xe0\xb8\xa5\xe0\xb8\x94\xe0\xb9\x8c'], dtype=object) - -If you know ahead of time all the possible string values that can occur, you could -also use the :class:`numcodecs.categorize.Categorize` codec to encode each unique string value as an -integer. E.g.:: - - >>> categorize = numcodecs.Categorize(greetings, dtype=object) - >>> z = zarr.array(text_data, dtype=object, object_codec=categorize) - >>> z - - >>> z.filters - [Categorize(dtype='|O', astype='|u1', labels=['Β‘Hola mundo!', 'Hej VΓ€rlden!', 'Servus Woid!', ...])] - >>> z[:] - array(['Β‘Hola mundo!', 'Hej VΓ€rlden!', 'Servus Woid!', ..., - 'HellΓ³, vilΓ‘g!', 'Zdravo svete!', 'ΰΉ€ΰΈΰΈ₯ΰΉ‚ΰΈ₯ΰΉ€ΰΈ§ΰΈ΄ΰΈ₯ΰΈ”ΰΉŒ'], dtype=object) - - -.. _tutorial_objects: - -Object arrays -------------- - -Zarr supports arrays with an "object" dtype. This allows arrays to contain any type of -object, such as variable length unicode strings, or variable length arrays of numbers, or -other possibilities. When creating an object array, a codec must be provided via the -``object_codec`` argument. This codec handles encoding (serialization) of Python objects. -The best codec to use will depend on what type of objects are present in the array. - -At the time of writing there are three codecs available that can serve as a general -purpose object codec and support encoding of a mixture of object types: -:class:`numcodecs.json.JSON`, :class:`numcodecs.msgpacks.MsgPack`. and :class:`numcodecs.pickles.Pickle`. - -For example, using the JSON codec:: - - >>> z = zarr.empty(5, dtype=object, object_codec=numcodecs.JSON()) - >>> z[0] = 42 - >>> z[1] = 'foo' - >>> z[2] = ['bar', 'baz', 'qux'] - >>> z[3] = {'a': 1, 'b': 2.2} - >>> z[:] - array([42, 'foo', list(['bar', 'baz', 'qux']), {'a': 1, 'b': 2.2}, None], dtype=object) - -Not all codecs support encoding of all object types. The -:class:`numcodecs.pickles.Pickle` codec is the most flexible, supporting encoding any type -of Python object. However, if you are sharing data with anyone other than yourself, then -Pickle is not recommended as it is a potential security risk. This is because malicious -code can be embedded within pickled data. The JSON and MsgPack codecs do not have any -security issues and support encoding of unicode strings, lists and dictionaries. -MsgPack is usually faster for both encoding and decoding. - -Ragged arrays -~~~~~~~~~~~~~ - -If you need to store an array of arrays, where each member array can be of any length -and stores the same primitive type (a.k.a. a ragged array), the -:class:`numcodecs.vlen.VLenArray` codec can be used, e.g.:: - - >>> z = zarr.empty(4, dtype=object, object_codec=numcodecs.VLenArray(int)) - >>> z - - >>> z.filters - [VLenArray(dtype='>> z[0] = np.array([1, 3, 5]) - >>> z[1] = np.array([4]) - >>> z[2] = np.array([7, 9, 14]) - >>> z[:] - array([array([1, 3, 5]), array([4]), array([ 7, 9, 14]), - array([], dtype=int64)], dtype=object) - -As a convenience, ``dtype='array:T'`` can be used as a short-hand for -``dtype=object, object_codec=numcodecs.VLenArray('T')``, where 'T' can be any NumPy -primitive dtype such as 'i4' or 'f8'. E.g.:: - - >>> z = zarr.empty(4, dtype='array:i8') - >>> z - - >>> z.filters - [VLenArray(dtype='>> z[0] = np.array([1, 3, 5]) - >>> z[1] = np.array([4]) - >>> z[2] = np.array([7, 9, 14]) - >>> z[:] - array([array([1, 3, 5]), array([4]), array([ 7, 9, 14]), - array([], dtype=int64)], dtype=object) - -.. _tutorial_chunks: - -Chunk optimizations -------------------- - -.. _tutorial_chunks_shape: - -Chunk size and shape -~~~~~~~~~~~~~~~~~~~~ - -In general, chunks of at least 1 megabyte (1M) uncompressed size seem to provide -better performance, at least when using the Blosc compression library. - -The optimal chunk shape will depend on how you want to access the data. E.g., -for a 2-dimensional array, if you only ever take slices along the first -dimension, then chunk across the second dimension. If you know you want to chunk -across an entire dimension you can use ``None`` or ``-1`` within the ``chunks`` -argument, e.g.:: - - >>> z1 = zarr.zeros((10000, 10000), chunks=(100, None), dtype='i4') - >>> z1.chunks - (100, 10000) - -Alternatively, if you only ever take slices along the second dimension, then -chunk across the first dimension, e.g.:: - - >>> z2 = zarr.zeros((10000, 10000), chunks=(None, 100), dtype='i4') - >>> z2.chunks - (10000, 100) - -If you require reasonable performance for both access patterns then you need to -find a compromise, e.g.:: - - >>> z3 = zarr.zeros((10000, 10000), chunks=(1000, 1000), dtype='i4') - >>> z3.chunks - (1000, 1000) - -If you are feeling lazy, you can let Zarr guess a chunk shape for your data by -providing ``chunks=True``, although please note that the algorithm for guessing -a chunk shape is based on simple heuristics and may be far from optimal. E.g.:: - - >>> z4 = zarr.zeros((10000, 10000), chunks=True, dtype='i4') - >>> z4.chunks - (625, 625) - -If you know you are always going to be loading the entire array into memory, you -can turn off chunks by providing ``chunks=False``, in which case there will be -one single chunk for the array:: - - >>> z5 = zarr.zeros((10000, 10000), chunks=False, dtype='i4') - >>> z5.chunks - (10000, 10000) - -.. _tutorial_chunks_order: - -Chunk memory layout -~~~~~~~~~~~~~~~~~~~ - -The order of bytes **within each chunk** of an array can be changed via the -``order`` keyword argument, to use either C or Fortran layout. For -multi-dimensional arrays, these two layouts may provide different compression -ratios, depending on the correlation structure within the data. E.g.:: - - >>> a = np.arange(100000000, dtype='i4').reshape(10000, 10000).T - >>> c = zarr.array(a, chunks=(1000, 1000)) - >>> c.info - Type : zarr.core.Array - Data type : int32 - Shape : (10000, 10000) - Chunk shape : (1000, 1000) - Order : C - Read-only : False - Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0) - Store type : zarr.storage.KVStore - No. bytes : 400000000 (381.5M) - No. bytes stored : 6696010 (6.4M) - Storage ratio : 59.7 - Chunks initialized : 100/100 - >>> f = zarr.array(a, chunks=(1000, 1000), order='F') - >>> f.info - Type : zarr.core.Array - Data type : int32 - Shape : (10000, 10000) - Chunk shape : (1000, 1000) - Order : F - Read-only : False - Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0) - Store type : zarr.storage.KVStore - No. bytes : 400000000 (381.5M) - No. bytes stored : 4684636 (4.5M) - Storage ratio : 85.4 - Chunks initialized : 100/100 - -In the above example, Fortran order gives a better compression ratio. This is an -artificial example but illustrates the general point that changing the order of -bytes within chunks of an array may improve the compression ratio, depending on -the structure of the data, the compression algorithm used, and which compression -filters (e.g., byte-shuffle) have been applied. - -.. _tutorial_chunks_empty_chunks: - -Empty chunks -~~~~~~~~~~~~ - -As of version 2.11, it is possible to configure how Zarr handles the storage of -chunks that are "empty" (i.e., every element in the chunk is equal to the array's fill value). -When creating an array with ``write_empty_chunks=False``, -Zarr will check whether a chunk is empty before compression and storage. If a chunk is empty, -then Zarr does not store it, and instead deletes the chunk from storage -if the chunk had been previously stored. - -This optimization prevents storing redundant objects and can speed up reads, but the cost is -added computation during array writes, since the contents of -each chunk must be compared to the fill value, and these advantages are contingent on the content of the array. -If you know that your data will form chunks that are almost always non-empty, then there is no advantage to the optimization described above. -In this case, creating an array with ``write_empty_chunks=True`` (the default) will instruct Zarr to write every chunk without checking for emptiness. - -The following example illustrates the effect of the ``write_empty_chunks`` flag on -the time required to write an array with different values.:: - - >>> import zarr - >>> import numpy as np - >>> import time - >>> from tempfile import TemporaryDirectory - >>> def timed_write(write_empty_chunks): - ... """ - ... Measure the time required and number of objects created when writing - ... to a Zarr array with random ints or fill value. - ... """ - ... chunks = (8192,) - ... shape = (chunks[0] * 1024,) - ... data = np.random.randint(0, 255, shape) - ... dtype = 'uint8' - ... - ... with TemporaryDirectory() as store: - ... arr = zarr.open(store, - ... shape=shape, - ... chunks=chunks, - ... dtype=dtype, - ... write_empty_chunks=write_empty_chunks, - ... fill_value=0, - ... mode='w') - ... # initialize all chunks - ... arr[:] = 100 - ... result = [] - ... for value in (data, arr.fill_value): - ... start = time.time() - ... arr[:] = value - ... elapsed = time.time() - start - ... result.append((elapsed, arr.nchunks_initialized)) - ... - ... return result - >>> for write_empty_chunks in (True, False): - ... full, empty = timed_write(write_empty_chunks) - ... print(f'\nwrite_empty_chunks={write_empty_chunks}:\n\tRandom Data: {full[0]:.4f}s, {full[1]} objects stored\n\t Empty Data: {empty[0]:.4f}s, {empty[1]} objects stored\n') - - write_empty_chunks=True: - Random Data: 0.1252s, 1024 objects stored - Empty Data: 0.1060s, 1024 objects stored - - - write_empty_chunks=False: - Random Data: 0.1359s, 1024 objects stored - Empty Data: 0.0301s, 0 objects stored - -In this example, writing random data is slightly slower with ``write_empty_chunks=True``, -but writing empty data is substantially faster and generates far fewer objects in storage. - -.. _tutorial_rechunking: - -Changing chunk shapes (rechunking) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Sometimes you are not free to choose the initial chunking of your input data, or -you might have data saved with chunking which is not optimal for the analysis you -have planned. In such cases it can be advantageous to re-chunk the data. For small -datasets, or when the mismatch between input and output chunks is small -such that only a few chunks of the input dataset need to be read to create each -chunk in the output array, it is sufficient to simply copy the data to a new array -with the desired chunking, e.g. :: - - >>> a = zarr.zeros((10000, 10000), chunks=(100,100), dtype='uint16', store='a.zarr') - >>> b = zarr.array(a, chunks=(100, 200), store='b.zarr') - -If the chunk shapes mismatch, however, a simple copy can lead to non-optimal data -access patterns and incur a substantial performance hit when using -file based stores. One of the most pathological examples is -switching from column-based chunking to row-based chunking e.g. :: - - >>> a = zarr.zeros((10000,10000), chunks=(10000, 1), dtype='uint16', store='a.zarr') - >>> b = zarr.array(a, chunks=(1,10000), store='b.zarr') - -which will require every chunk in the input data set to be repeatedly read when creating -each output chunk. If the entire array will fit within memory, this is simply resolved -by forcing the entire input array into memory as a numpy array before converting -back to zarr with the desired chunking. :: - - >>> a = zarr.zeros((10000,10000), chunks=(10000, 1), dtype='uint16', store='a.zarr') - >>> b = a[...] - >>> c = zarr.array(b, chunks=(1,10000), store='c.zarr') - -For data sets which have mismatched chunks and which do not fit in memory, a -more sophisticated approach to rechunking, such as offered by the -`rechunker `_ package and discussed -`here `_ -may offer a substantial improvement in performance. - -.. _tutorial_sync: - -Parallel computing and synchronization --------------------------------------- - -Zarr arrays have been designed for use as the source or sink for data in -parallel computations. By data source we mean that multiple concurrent read -operations may occur. By data sink we mean that multiple concurrent write -operations may occur, with each writer updating a different region of the -array. Zarr arrays have **not** been designed for situations where multiple -readers and writers are concurrently operating on the same array. - -Both multi-threaded and multi-process parallelism are possible. The bottleneck -for most storage and retrieval operations is compression/decompression, and the -Python global interpreter lock (GIL) is released wherever possible during these -operations, so Zarr will generally not block other Python threads from running. - -When using a Zarr array as a data sink, some synchronization (locking) may be -required to avoid data loss, depending on how data are being updated. If each -worker in a parallel computation is writing to a separate region of the array, -and if region boundaries are perfectly aligned with chunk boundaries, then no -synchronization is required. However, if region and chunk boundaries are not -perfectly aligned, then synchronization is required to avoid two workers -attempting to modify the same chunk at the same time, which could result in data -loss. - -To give a simple example, consider a 1-dimensional array of length 60, ``z``, -divided into three chunks of 20 elements each. If three workers are running and -each attempts to write to a 20 element region (i.e., ``z[0:20]``, ``z[20:40]`` -and ``z[40:60]``) then each worker will be writing to a separate chunk and no -synchronization is required. However, if two workers are running and each -attempts to write to a 30 element region (i.e., ``z[0:30]`` and ``z[30:60]``) -then it is possible both workers will attempt to modify the middle chunk at the -same time, and synchronization is required to prevent data loss. - -Zarr provides support for chunk-level synchronization. E.g., create an array -with thread synchronization:: - - >>> z = zarr.zeros((10000, 10000), chunks=(1000, 1000), dtype='i4', - ... synchronizer=zarr.ThreadSynchronizer()) - >>> z - - -This array is safe to read or write within a multi-threaded program. - -Zarr also provides support for process synchronization via file locking, -provided that all processes have access to a shared file system, and provided -that the underlying file system supports file locking (which is not the case for -some networked file systems). E.g.:: - - >>> synchronizer = zarr.ProcessSynchronizer('data/example.sync') - >>> z = zarr.open_array('data/example', mode='w', shape=(10000, 10000), - ... chunks=(1000, 1000), dtype='i4', - ... synchronizer=synchronizer) - >>> z - - -This array is safe to read or write from multiple processes. - -When using multiple processes to parallelize reads or writes on arrays using the Blosc -compression library, it may be necessary to set ``numcodecs.blosc.use_threads = False``, -as otherwise Blosc may share incorrect global state amongst processes causing programs -to hang. See also the section on :ref:`tutorial_tips_blosc` below. - -Please note that support for parallel computing is an area of ongoing research -and development. If you are using Zarr for parallel computing, we welcome -feedback, experience, discussion, ideas and advice, particularly about issues -related to data integrity and performance. - -.. _tutorial_pickle: - -Pickle support --------------- - -Zarr arrays and groups can be pickled, as long as the underlying store object can be -pickled. Instances of any of the storage classes provided in the :mod:`zarr.storage` -module can be pickled, as can the built-in ``dict`` class which can also be used for -storage. - -Note that if an array or group is backed by an in-memory store like a ``dict`` or -:class:`zarr.storage.MemoryStore`, then when it is pickled all of the store data will be -included in the pickled data. However, if an array or group is backed by a persistent -store like a :class:`zarr.storage.DirectoryStore`, :class:`zarr.storage.ZipStore` or -:class:`zarr.storage.DBMStore` then the store data **are not** pickled. The only thing -that is pickled is the necessary parameters to allow the store to re-open any -underlying files or databases upon being unpickled. - -E.g., pickle/unpickle an in-memory array:: - - >>> import pickle - >>> z1 = zarr.array(np.arange(100000)) - >>> s = pickle.dumps(z1) - >>> len(s) > 5000 # relatively large because data have been pickled - True - >>> z2 = pickle.loads(s) - >>> z1 == z2 - True - >>> np.all(z1[:] == z2[:]) - True - -E.g., pickle/unpickle an array stored on disk:: - - >>> z3 = zarr.open('data/walnuts.zarr', mode='w', shape=100000, dtype='i8') - >>> z3[:] = np.arange(100000) - >>> s = pickle.dumps(z3) - >>> len(s) < 200 # small because no data have been pickled - True - >>> z4 = pickle.loads(s) - >>> z3 == z4 - True - >>> np.all(z3[:] == z4[:]) - True - -.. _tutorial_datetime: - -Datetimes and timedeltas ------------------------- - -NumPy's ``datetime64`` ('M8') and ``timedelta64`` ('m8') dtypes are supported for Zarr -arrays, as long as the units are specified. E.g.:: - - >>> z = zarr.array(['2007-07-13', '2006-01-13', '2010-08-13'], dtype='M8[D]') - >>> z - - >>> z[:] - array(['2007-07-13', '2006-01-13', '2010-08-13'], dtype='datetime64[D]') - >>> z[0] - numpy.datetime64('2007-07-13') - >>> z[0] = '1999-12-31' - >>> z[:] - array(['1999-12-31', '2006-01-13', '2010-08-13'], dtype='datetime64[D]') - -.. _tutorial_tips: - -Usage tips ----------- - -.. _tutorial_tips_copy: - -Copying large arrays -~~~~~~~~~~~~~~~~~~~~ - -Data can be copied between large arrays without needing much memory, e.g.:: - - >>> z1 = zarr.empty((10000, 10000), chunks=(1000, 1000), dtype='i4') - >>> z1[:] = 42 - >>> z2 = zarr.empty_like(z1) - >>> z2[:] = z1 - -Internally the example above works chunk-by-chunk, extracting only the data from -``z1`` required to fill each chunk in ``z2``. The source of the data (``z1``) -could equally be an h5py Dataset. - -.. _tutorial_tips_blosc: - -Configuring Blosc -~~~~~~~~~~~~~~~~~ - -The Blosc compressor is able to use multiple threads internally to accelerate -compression and decompression. By default, Blosc uses up to 8 -internal threads. The number of Blosc threads can be changed to increase or -decrease this number, e.g.:: - - >>> from numcodecs import blosc - >>> blosc.set_nthreads(2) # doctest: +SKIP - 8 - -When a Zarr array is being used within a multi-threaded program, Zarr -automatically switches to using Blosc in a single-threaded -"contextual" mode. This is generally better as it allows multiple -program threads to use Blosc simultaneously and prevents CPU thrashing -from too many active threads. If you want to manually override this -behaviour, set the value of the ``blosc.use_threads`` variable to -``True`` (Blosc always uses multiple internal threads) or ``False`` -(Blosc always runs in single-threaded contextual mode). To re-enable -automatic switching, set ``blosc.use_threads`` to ``None``. - -Please note that if Zarr is being used within a multi-process program, Blosc may not -be safe to use in multi-threaded mode and may cause the program to hang. If using Blosc -in a multi-process program then it is recommended to set ``blosc.use_threads = False``. diff --git a/docs/user-guide/arrays.md b/docs/user-guide/arrays.md new file mode 100644 index 0000000000..a192845f9e --- /dev/null +++ b/docs/user-guide/arrays.md @@ -0,0 +1,767 @@ +# Working with arrays + +## Creating an array + +Zarr has several functions for creating arrays. For example: + +```python exec="true" session="arrays" +import shutil +shutil.rmtree('data', ignore_errors=True) +import numpy as np +``` + +```python exec="true" session="arrays" source="above" result="ansi" +import zarr +z = zarr.create_array(store="memory://arrays-demo", shape=(10000, 10000), chunks=(1000, 1000), dtype='int32') +print(z) +``` + +The code above creates a 2-dimensional array of 32-bit integers with 10000 rows +and 10000 columns, divided into chunks where each chunk has 1000 rows and 1000 +columns (and so there will be 100 chunks in total). The data is written to an +in-memory store: when `fsspec` is installed, a `memory://` URL resolves to a +[`zarr.storage.FsspecStore`][] backed by fsspec's in-memory filesystem; otherwise a +[`zarr.storage.ManagedMemoryStore`][] is used. See the [Storage guide](storage.md) +for more details on stores, and +[Persistent arrays](#persistent-arrays) for details on storing arrays in other stores. +See [Data types](data_types.md) for an in-depth look at the data types supported +by Zarr, and [Chunk size and shape](performance.md#chunk-size-and-shape) in the +performance guide for guidance on choosing chunk shapes. + +See the [`zarr.create_array`][] API documentation for more detailed information about +creating arrays. + +## Reading and writing data + +Zarr arrays support a similar interface to [NumPy](https://numpy.org/doc/stable/) +arrays for reading and writing data. For example, the entire array can be filled +with a scalar value: + +```python exec="true" session="arrays" source="above" +z[:] = 42 +``` + +Regions of the array can also be written to, e.g.: + +```python exec="true" session="arrays" source="above" +import numpy as np + +z[0, :] = np.arange(10000) +z[:, 0] = np.arange(10000) +``` + +The contents of the array can be retrieved by slicing, which will load the +requested region into memory as a NumPy array, e.g.: + +```python exec="true" session="arrays" source="above" result="ansi" +print(z[0, 0]) +``` + +```python exec="true" session="arrays" source="above" result="ansi" +print(z[-1, -1]) +``` + +```python exec="true" session="arrays" source="above" result="ansi" +print(z[0, :]) +``` + +```python exec="true" session="arrays" source="above" result="ansi" +print(z[:, 0]) +``` + +```python exec="true" session="arrays" source="above" result="ansi" +print(z[:]) +``` + +More information about NumPy-style indexing can be found in the +[NumPy documentation](https://numpy.org/doc/stable/user/basics.indexing.html). + +## Persistent arrays + +In the examples above, compressed data for each chunk of the array was stored in +main memory. Zarr arrays can also be stored on a file system, enabling +persistence of data between sessions. To do this, we can change the store +argument to point to a filesystem path: + +```python exec="true" session="arrays" source="above" +z1 = zarr.create_array(store='data/example-1.zarr', shape=(10000, 10000), chunks=(1000, 1000), dtype='int32') +``` + +The array above will store its configuration metadata and all compressed chunk +data in a directory called `'data/example-1.zarr'` relative to the current working +directory. The [`zarr.create_array`][] function provides a convenient way +to create a new persistent array or continue working with an existing +array. Note, there is no need to close an array: data are automatically +flushed to disk, and files are automatically closed whenever an array is modified. + +Persistent arrays support the same interface for reading and writing data, +e.g.: + +```python exec="true" session="arrays" source="above" +z1[:] = 42 +z1[0, :] = np.arange(10000) +z1[:, 0] = np.arange(10000) +``` + +Check that the data have been written and can be read again: + +```python exec="true" session="arrays" source="above" result="ansi" +z2 = zarr.open_array('data/example-1.zarr', mode='r') +print(np.all(z1[:] == z2[:])) +``` + +If you are just looking for a fast and convenient way to save NumPy arrays to +disk then load back into memory later, the functions +[`zarr.save`][] and [`zarr.load`][] may be +useful. E.g.: + +```python exec="true" session="arrays" source="above" result="ansi" +a = np.arange(10) +zarr.save('data/example-2.zarr', a) +print(zarr.load('data/example-2.zarr')) +``` + +Please note that there are a number of other options for persistent array +storage, see the [Storage Guide](storage.md) for more details. + +## Resizing and appending + +A Zarr array can be resized, which means that any of its dimensions can be +increased or decreased in length. For example: + +```python exec="true" session="arrays" source="above" result="ansi" +z = zarr.create_array(store='data/example-3.zarr', shape=(10000, 10000), dtype='int32', chunks=(1000, 1000)) +z[:] = 42 +print(f"Original shape: {z.shape}") +z.resize((20000, 10000)) +print(f"New shape: {z.shape}") +``` + +Note that when an array is resized, the underlying data are not rearranged in +any way. If one or more dimensions are shrunk, any chunks falling outside the +new array shape will be deleted from the underlying store. + +[`zarr.Array.append`][] is provided as a convenience function, which can be +used to append data to any axis. E.g.: + +```python exec="true" session="arrays" source="above" result="ansi" +a = np.arange(10000000, dtype='int32').reshape(10000, 1000) +z = zarr.create_array(store='data/example-4.zarr', shape=a.shape, dtype=a.dtype, chunks=(1000, 100)) +z[:] = a +print(f"Original shape: {z.shape}") +z.append(a) +print(f"Shape after first append: {z.shape}") +z.append(np.vstack([a, a]), axis=1) +print(f"Shape after second append: {z.shape}") +``` + +## Runtime configuration + +Zarr arrays are parametrized with a configuration that determines certain aspects of array behavior. + +We currently support five configuration options for arrays: `order`, `write_empty_chunks`, `read_missing_chunks`, `sharding_coalesce_max_gap_bytes`, and `sharding_coalesce_max_bytes`. + +| field | type | default | description | +| - | - | - | - | +| `order` | `Literal["C", "F"]` | `"C"` | The memory layout of arrays returned when reading data from the store. +| `write_empty_chunks` | `bool` | `False` | Controls whether empty chunks are written to storage. See [Empty chunks](performance.md#empty-chunks). +| `read_missing_chunks` | `bool` | `True` | Controls whether missing chunks are filled with the array's fill value on read. If `False`, reading missing chunks raises a [`ChunkNotFoundError`][zarr.errors.ChunkNotFoundError]. +| `sharding_coalesce_max_gap_bytes` | `int` | `1048576` (1 MiB) | When reading multiple chunks from the same shard, nearby byte ranges separated by no more than this many bytes are coalesced into a single request to the store. +| `sharding_coalesce_max_bytes` | `int` | `16777216` (16 MiB) | Requests will not be coalesced if doing so would exceed this byte size. + +!!! info + The Zarr V3 spec states that readers should interpret an uninitialized chunk as containing the + array's `fill_value`. By default, Zarr-Python follows this behavior: a missing chunk is treated + as uninitialized and filled with the array's `fill_value`. However, if you know that all chunks + have been written (i.e., are initialized), you may want to treat a missing chunk as an error. Set + `read_missing_chunks=False` to raise a [`ChunkNotFoundError`][zarr.errors.ChunkNotFoundError] instead. + +!!! note + `write_empty_chunks=False` skips writing chunks that are entirely the array's fill value. + If `read_missing_chunks=False`, attempting to read these missing chunks will raise a [`ChunkNotFoundError`][zarr.errors.ChunkNotFoundError]. + +You can specify the configuration when you create an array with the `config` keyword argument. +`config` can be passed as either a `dict` or an `ArrayConfig` object. + +```python exec="true" session="arrays" source="above" result="ansi" +arr = zarr.create_array({}, shape=(10,), dtype='int8', config={"write_empty_chunks": True}) +print(arr.config) +``` + +To get an array view with a different config, use the `with_config` method. + +```python exec="true" session="arrays" source="above" result="ansi" +arr_f = arr.with_config({"order": "F"}) +print(arr_f.config) +``` + +## Compressors + +A number of different compressors can be used with Zarr. Zarr includes Blosc, +Zstandard and Gzip compressors. Additional compressors are available through +a separate package called [NumCodecs](https://numcodecs.readthedocs.io/en/stable/) which provides various +compressor libraries including LZ4, Zlib, BZ2 and LZMA. +Different compressors can be provided via the `compressors` keyword +argument accepted by all array creation functions. For example: + +```python exec="true" session="arrays" source="above" result="ansi" +compressors = zarr.codecs.BloscCodec(cname='zstd', clevel=3, shuffle='bitshuffle') +data = np.arange(100000000, dtype='int32').reshape(10000, 10000) +z = zarr.create_array(store='data/example-5.zarr', shape=data.shape, dtype=data.dtype, chunks=(1000, 1000), compressors=compressors) +z[:] = data +print(z.compressors) +``` + +This array above will use Blosc as the primary compressor, using the Zstandard +algorithm (compression level 3) internally within Blosc, and with the +bit-shuffle filter applied. + +When using a compressor, it can be useful to get some diagnostics on the +compression ratio. Zarr arrays provide the [`zarr.Array.info`][] property +which can be used to print useful diagnostics, e.g.: + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.info) +``` + +The [`zarr.Array.info_complete`][] method inspects the underlying store and +prints additional diagnostics, e.g.: + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.info_complete()) +``` + +!!! note + [`zarr.Array.info_complete`][] will inspect the underlying store and may + be slow for large arrays. Use [`zarr.Array.info`][] if detailed storage + statistics are not needed. + +If you don't specify a compressor, by default Zarr uses the Zstandard +compressor. + +To create an array without any compression, set `compressors=None`: + +```python exec="true" session="arrays" source="above" result="ansi" +z_no_compress = zarr.create_array(store='data/example-uncompressed.zarr', shape=(10000, 10000), chunks=(1000, 1000), dtype='int32', compressors=None) +print(f"Compressors: {z_no_compress.compressors}") +``` + +In addition to Blosc and Zstandard, other compression libraries can also be used. For example, +here is an array using Gzip compression, level 1: + +```python exec="true" session="arrays" source="above" result="ansi" +data = np.arange(100000000, dtype='int32').reshape(10000, 10000) +z = zarr.create_array(store='data/example-6.zarr', shape=data.shape, dtype=data.dtype, chunks=(1000, 1000), compressors=zarr.codecs.GzipCodec(level=1)) +z[:] = data +print(f"Compressors: {z.compressors}") +``` + +Here is an example using LZMA from [NumCodecs](https://numcodecs.readthedocs.io/en/stable/) with a custom filter pipeline including LZMA's +built-in delta filter: + +```python exec="true" session="arrays" source="above" result="ansi" +import lzma +from zarr.codecs.numcodecs import LZMA + +lzma_filters = [dict(id=lzma.FILTER_DELTA, dist=4), dict(id=lzma.FILTER_LZMA2, preset=1)] +compressors = LZMA(filters=lzma_filters) +data = np.arange(100000000, dtype='int32').reshape(10000, 10000) +z = zarr.create_array(store='data/example-7.zarr', shape=data.shape, dtype=data.dtype, chunks=(1000, 1000), compressors=compressors) +print(f"Compressors: {z.compressors}") +``` + +## Filters + +In some cases, compression can be improved by transforming the data in some +way. For example, if nearby values tend to be correlated, then shuffling the +bytes within each numerical value or storing the difference between adjacent +values may increase compression ratio. Some compressors provide built-in filters +that apply transformations to the data prior to compression. For example, the +Blosc compressor has built-in implementations of byte- and bit-shuffle filters, +and the LZMA compressor has a built-in implementation of a delta +filter. However, to provide additional flexibility for implementing and using +filters in combination with different compressors, Zarr also provides a +mechanism for configuring filters outside of the primary compressor. + +Here is an example using a delta filter with the Blosc compressor: + +```python exec="true" session="arrays" source="above" result="ansi" +from zarr.codecs.numcodecs import Delta + +filters = [Delta(dtype='int32')] +compressors = zarr.codecs.BloscCodec(cname='zstd', clevel=1, shuffle='shuffle') +data = np.arange(100000000, dtype='int32').reshape(10000, 10000) +z = zarr.create_array(store='data/example-9.zarr', shape=data.shape, dtype=data.dtype, chunks=(1000, 1000), filters=filters, compressors=compressors) +print(z.info_complete()) +``` + +For more information about available filter codecs, see the [Numcodecs](https://numcodecs.readthedocs.io/en/stable/) documentation. + +## Advanced indexing + +Zarr arrays support several methods for advanced or "fancy" +indexing, which enable a subset of data items to be extracted or updated in an +array without loading the entire array into memory. + +Note that although this functionality is similar to some of the advanced +indexing capabilities available on NumPy arrays and on h5py datasets, **the Zarr +API for advanced indexing is different from both NumPy and h5py**, so please +read this section carefully. For a complete description of the indexing API, +see the documentation for the [`zarr.Array`][] class. + +### Indexing with coordinate arrays + +Items from a Zarr array can be extracted by providing an integer array of +coordinates. E.g.: + +```python exec="true" session="arrays" source="above" result="ansi" +data = np.arange(10) ** 2 +z = zarr.create_array(store='data/example-10.zarr', shape=data.shape, dtype=data.dtype) +z[:] = data +print(z[:]) +print(z.get_coordinate_selection([2, 5])) +``` + +Coordinate arrays can also be used to update data, e.g.: + +```python exec="true" session="arrays" source="above" result="ansi" +z.set_coordinate_selection([2, 5], [-1, -2]) +print(z[:]) +``` + +For multidimensional arrays, coordinates must be provided for each dimension, +e.g.: + +```python exec="true" session="arrays" source="above" result="ansi" +data = np.arange(15).reshape(3, 5) +z = zarr.create_array(store='data/example-11.zarr', shape=data.shape, dtype=data.dtype) +z[:] = data +print(z[:]) +``` + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.get_coordinate_selection(([0, 2], [1, 3]))) +``` + +```python exec="true" session="arrays" source="above" result="ansi" +z.set_coordinate_selection(([0, 2], [1, 3]), [-1, -2]) +print(z[:]) +``` + +For convenience, coordinate indexing is also available via the `vindex` +property, as well as the square bracket operator, e.g.: + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.vindex[[0, 2], [1, 3]]) +z.vindex[[0, 2], [1, 3]] = [-3, -4] +``` + +```python exec="true" session="arrays" source="above" result="ansi" +print(z[:]) +``` + +```python exec="true" session="arrays" source="above" result="ansi" +print(z[[0, 2], [1, 3]]) +``` + +When the indexing arrays have different shapes, they are broadcast together. +That is, the following two calls are equivalent: + +```python exec="true" session="arrays" source="above" result="ansi" +print(z[1, [1, 3]]) +print(z[[1, 1], [1, 3]]) +``` + +### Indexing with a mask array + +Items can also be extracted by providing a Boolean mask. E.g.: + +```python exec="true" session="arrays" source="above" result="ansi" +data = np.arange(10) ** 2 +z = zarr.create_array(store='data/example-12.zarr', shape=data.shape, dtype=data.dtype) +z[:] = data +print(z[:]) +``` + +```python exec="true" session="arrays" source="above" result="ansi" +sel = np.zeros_like(z, dtype=bool) +sel[2] = True +sel[5] = True +print(z.get_mask_selection(sel)) +``` + +```python exec="true" session="arrays" source="above" result="ansi" +z.set_mask_selection(sel, [-1, -2]) +print(z[:]) +``` + +Here's a multidimensional example: + +```python exec="true" session="arrays" source="above" result="ansi" +data = np.arange(15).reshape(3, 5) +z = zarr.create_array(store='data/example-13.zarr', shape=data.shape, dtype=data.dtype) +z[:] = data +print(z[:]) +``` + +```python exec="true" session="arrays" source="above" result="ansi" +sel = np.zeros_like(z, dtype=bool) +sel[0, 1] = True +sel[2, 3] = True +print(z.get_mask_selection(sel)) +``` + +```python exec="true" session="arrays" source="above" result="ansi" +z.set_mask_selection(sel, [-1, -2]) +print(z[:]) +``` + +For convenience, mask indexing is also available via the `vindex` property, +e.g.: + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.vindex[sel]) +``` + +```python exec="true" session="arrays" source="above" result="ansi" + +z.vindex[sel] = [-3, -4] +print(z[:]) +``` + +Mask indexing is conceptually the same as coordinate indexing, and is +implemented internally via the same machinery. Both styles of indexing allow +selecting arbitrary items from an array, also known as point selection. + +### Orthogonal indexing + +Zarr arrays also support methods for orthogonal indexing, which allows +selections to be made along each dimension of an array independently. For +example, this allows selecting a subset of rows and/or columns from a +2-dimensional array. E.g.: + +```python exec="true" session="arrays" source="above" result="ansi" +data = np.arange(15).reshape(3, 5) +z = zarr.create_array(store='data/example-14.zarr', shape=data.shape, dtype=data.dtype) +z[:] = data +print(z[:]) +``` + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.get_orthogonal_selection(([0, 2], slice(None)))) # select first and third rows +``` + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.get_orthogonal_selection((slice(None), [1, 3]))) # select second and fourth columns +``` + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.get_orthogonal_selection(([0, 2], [1, 3]))) # select rows [0, 2] and columns [1, 3] +``` + +Data can also be modified, e.g.: + +```python exec="true" session="arrays" source="above" +z.set_orthogonal_selection(([0, 2], [1, 3]), [[-1, -2], [-3, -4]]) +``` + +For convenience, the orthogonal indexing functionality is also available via the +`oindex` property, e.g.: + +```python exec="true" session="arrays" source="above" result="ansi" +data = np.arange(15).reshape(3, 5) +z = zarr.create_array(store='data/example-15.zarr', shape=data.shape, dtype=data.dtype) +z[:] = data +print(z.oindex[[0, 2], :]) # select first and third rows +``` + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.oindex[:, [1, 3]]) # select second and fourth columns +``` + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.oindex[[0, 2], [1, 3]]) # select rows [0, 2] and columns [1, 3] +``` + +```python exec="true" session="arrays" source="above" result="ansi" +z.oindex[[0, 2], [1, 3]] = [[-1, -2], [-3, -4]] +print(z[:]) +``` + +Any combination of integer, slice, 1D integer array and/or 1D Boolean array can +be used for orthogonal indexing. + +If the index contains at most one iterable, and otherwise contains only slices and integers, +orthogonal indexing is also available directly on the array: + +```python exec="true" session="arrays" source="above" result="ansi" +data = np.arange(15).reshape(3, 5) +z = zarr.create_array(store='data/example-16.zarr', shape=data.shape, dtype=data.dtype) +z[:] = data +print(np.all(z.oindex[[0, 2], :] == z[[0, 2], :])) +``` + +### Block indexing + +Zarr also supports block indexing, which allows selections of whole chunks based on their +logical indices along each dimension of an array. For example, this allows selecting +a subset of chunk aligned rows and/or columns from a 2-dimensional array. E.g.: + +```python exec="true" session="arrays" source="above" +data = np.arange(100).reshape(10, 10) +z = zarr.create_array(store='data/example-17.zarr', shape=data.shape, dtype=data.dtype, chunks=(3, 3)) +z[:] = data +``` + +Retrieve items by specifying their block coordinates: + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.get_block_selection(1)) +``` + +Equivalent slicing: + +```python exec="true" session="arrays" source="above" result="ansi" +print(z[3:6]) +``` + +For convenience, the block selection functionality is also available via the +`blocks` property, e.g.: + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.blocks[1]) +``` + +Block index arrays may be multidimensional to index multidimensional arrays. +For example: + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.blocks[0, 1:3]) +``` + +Data can also be modified. Let's start by a simple 2D array: + +```python exec="true" session="arrays" source="above" +z = zarr.create_array(store='data/example-18.zarr', shape=(6, 6), dtype=int, chunks=(2, 2)) +``` + +Set data for a selection of items: + +```python exec="true" session="arrays" source="above" result="ansi" +z.set_block_selection((1, 0), 1) +print(z[...]) +``` + +For convenience, this functionality is also available via the `blocks` property. +E.g.: + +```python exec="true" session="arrays" source="above" result="ansi" +z.blocks[:, 2] = 7 +print(z[...]) +``` + +Any combination of integer and slice can be used for block indexing: + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.blocks[2, 1:3]) +``` + +## Sharding + +Using small chunk shapes in very large arrays can lead to a very large number of chunks. +This can become a performance issue for file systems and object storage. +With Zarr format 3, a new sharding feature has been added to address this issue. + +With sharding, multiple chunks can be stored in a single storage object (e.g. a file). +Within a shard, chunks are compressed and serialized separately. +This allows individual chunks to be read independently. +However, when writing data, a full shard must be written in one go for optimal +performance and to avoid concurrency issues. +That means that shards are the units of writing and chunks are the units of reading. +Users need to configure the chunk and shard shapes accordingly. For guidance on +choosing chunk and shard shapes, see [Sharding](performance.md#sharding) in the +performance guide. + +Sharded arrays can be created by providing the `shards` parameter to [`zarr.create_array`][]. + +```python exec="true" session="arrays" source="above" result="ansi" +a = zarr.create_array('data/example-20.zarr', shape=(10000, 10000), shards=(1000, 1000), chunks=(100, 100), dtype='uint8') +a[:] = (np.arange(10000 * 10000) % 256).astype('uint8').reshape(10000, 10000) +print(a.info_complete()) +``` + +In this example a shard shape of (1000, 1000) and a chunk shape of (100, 100) is used. +This means that `10*10` chunks are stored in each shard, and there are `10*10` shards in total. +Without the `shards` argument, there would be 10,000 chunks stored as individual files. + +## Rectilinear (variable) chunk grids + +!!! warning "Experimental" + Rectilinear chunk grids are an experimental feature and may change in + future releases. This feature is expected to stabilize in Zarr version 3.3. + + Because the feature is still stabilizing, it is disabled by default and + must be explicitly enabled: + + ```python exec="true" session="arrays" source="above" + import zarr + zarr.config.set({"array.rectilinear_chunks": True}) + ``` + + Or via the environment variable `ZARR_ARRAY__RECTILINEAR_CHUNKS=True`. + + The examples below assume this config has been set. + +By default, Zarr arrays use a regular chunk grid where every chunk along a +given dimension has the same size (except possibly the final boundary chunk). +Rectilinear chunk grids allow each chunk along a dimension to have a different +size. This is useful when the natural partitioning of the data is not uniform β€” +for example, satellite swaths of varying width, time series with irregular +intervals, or spatial tiles of different extents. + +### Creating arrays with rectilinear chunks + +To create an array with rectilinear chunks, pass a nested list to the `chunks` +parameter where each inner list gives the chunk sizes along one dimension: + +```python exec="true" session="arrays" source="above" result="ansi" +z = zarr.create_array( + store=zarr.storage.MemoryStore(), + shape=(60, 100), + chunks=[[10, 20, 30], [50, 50]], + dtype='int32', +) +print(z.info) +``` + +In this example the first dimension is split into three chunks of sizes 10, 20, +and 30, while the second dimension is split into two equal chunks of size 50. + +### Reading and writing data + +Rectilinear arrays support the same indexing interface as regular arrays. +Reads and writes that cross chunk boundaries of different sizes are handled +automatically: + +```python exec="true" session="arrays" source="above" result="ansi" +import numpy as np +data = np.arange(60 * 100, dtype='int32').reshape(60, 100) +z[:] = data +# Read a slice that spans the first two chunks (sizes 10 and 20) along axis 0 +print(z[5:25, 0:5]) +``` + +### Inspecting chunk sizes + +The `.write_chunk_sizes` property returns the actual data size of each storage +chunk along every dimension. It works for both regular and rectilinear arrays +and returns a tuple of tuples (matching the dask `Array.chunks` convention). +When sharding is used, `.read_chunk_sizes` returns the inner chunk sizes instead: + +```python exec="true" session="arrays" source="above" result="ansi" +print(z.write_chunk_sizes) +``` + +For regular arrays, this includes the boundary chunk: + +```python exec="true" session="arrays" source="above" result="ansi" +z_regular = zarr.create_array( + store=zarr.storage.MemoryStore(), + shape=(100, 80), + chunks=(30, 40), + dtype='int32', +) +print(z_regular.write_chunk_sizes) +``` + +Note that the `.chunks` property is only available for regular chunk grids. For +rectilinear arrays, use `.write_chunk_sizes` (or `.read_chunk_sizes`) instead. + +### Resizing and appending + +Rectilinear arrays can be resized. When growing past the current edge sum, a +new chunk is appended covering the additional extent. When shrinking, the chunk +edges are preserved and the extent is re-bound (chunks beyond the new extent +simply become inactive): + +```python exec="true" session="arrays" source="above" result="ansi" +z = zarr.create_array( + store=zarr.storage.MemoryStore(), + shape=(30,), + chunks=[[10, 20]], + dtype='float64', +) +z[:] = np.arange(30, dtype='float64') +print(f"Before resize: chunk_sizes={z.write_chunk_sizes}") +z.resize((50,)) +print(f"After resize: chunk_sizes={z.write_chunk_sizes}") +``` + +The `append` method also works with rectilinear arrays: + +```python exec="true" session="arrays" source="above" result="ansi" +z.append(np.arange(10, dtype='float64')) +print(f"After append: shape={z.shape}, chunk_sizes={z.write_chunk_sizes}") +``` + +### Compressors and filters + +Rectilinear arrays work with all codecs β€” compressors, filters, and checksums. +Since each chunk may have a different size, the codec pipeline processes each +chunk independently: + +```python exec="true" session="arrays" source="above" result="ansi" +z = zarr.create_array( + store=zarr.storage.MemoryStore(), + shape=(60, 100), + chunks=[[10, 20, 30], [50, 50]], + dtype='float64', + filters=[zarr.codecs.TransposeCodec(order=(1, 0))], + compressors=[zarr.codecs.BloscCodec(cname='zstd', clevel=3)], +) +z[:] = np.arange(60 * 100, dtype='float64').reshape(60, 100) +np.testing.assert_array_equal(z[:], np.arange(60 * 100, dtype='float64').reshape(60, 100)) +print("Roundtrip OK") +``` + +### Rectilinear shard boundaries + +Rectilinear chunk grids can also be used for shard boundaries when combined +with sharding. In this case, the outer grid (shards) is rectilinear while the +inner chunks remain regular. Each shard dimension must be divisible by the +corresponding inner chunk size: + +```python exec="true" session="arrays" source="above" result="ansi" +z = zarr.create_array( + store=zarr.storage.MemoryStore(), + shape=(120, 100), + chunks=(10, 10), + shards=[[60, 40, 20], [50, 50]], + dtype='int32', +) +z[:] = np.arange(120 * 100, dtype='int32').reshape(120, 100) +print(z[50:70, 40:60]) +``` + +Note that rectilinear inner chunks with sharding are not supported β€” only the +shard boundaries can be rectilinear. + +### Metadata format + +Rectilinear chunk grid metadata uses run-length encoding (RLE) for compact +serialization. When reading metadata, both bare integers and `[value, count]` +pairs are accepted: + +- `[10, 20, 30]` β€” three chunks with explicit sizes +- `[[10, 3]]` β€” three chunks of size 10 (RLE shorthand) +- `[[10, 3], 5]` β€” three chunks of size 10, then one chunk of size 5 + +When writing, Zarr automatically compresses repeated values into RLE format. + +## Features not yet ported to Zarr-Python 3 + +The following Zarr-Python 2 features are not yet available in Zarr-Python 3. + +### Copying and migrating data + +See the Zarr-Python 2 documentation on [Copying and migrating data](https://zarr.readthedocs.io/en/support-v2/tutorial.html#copying-migrating-data) for more details. diff --git a/docs/user-guide/attributes.md b/docs/user-guide/attributes.md new file mode 100644 index 0000000000..8c11c853f1 --- /dev/null +++ b/docs/user-guide/attributes.md @@ -0,0 +1,61 @@ +# Working with attributes + +Zarr arrays and groups support custom key/value attributes, which can be useful for +storing application-specific metadata. For example: + +```python exec="true" session="attributes" source="above" result="ansi" +import zarr +root = zarr.create_group(store="memory://attributes-demo") +root.attrs['foo'] = 'bar' +z = root.create_array(name='zzz', shape=(10000, 10000), dtype='int32') +z.attrs['baz'] = 42 +z.attrs['qux'] = [1, 4, 7, 12] +print(sorted(root.attrs)) +``` + +```python exec="true" session="attributes" source="above" result="ansi" +print('foo' in root.attrs) +``` + +```python exec="true" session="attributes" source="above" result="ansi" +print(root.attrs['foo']) +``` + +```python exec="true" session="attributes" source="above" result="ansi" +print(sorted(z.attrs)) +``` + +```python exec="true" session="attributes" source="above" result="ansi" +print(z.attrs['baz']) +``` + +```python exec="true" session="attributes" source="above" result="ansi" +print(z.attrs['qux']) +``` + +Attributes can be deleted with the `del` operator: + +```python exec="true" session="attributes" source="above" result="ansi" +del z.attrs['baz'] +print(sorted(z.attrs)) +``` + +Note that each attribute assignment or deletion writes the node's metadata +document back to the store. To change several attributes in a single write, +use [`zarr.Array.update_attributes`][] (or [`zarr.Group.update_attributes`][] +for groups), which merges the given dict into the existing attributes and +returns the updated array or group: + +```python exec="true" session="attributes" source="above" result="ansi" +z = z.update_attributes({'baz': 43, 'quux': True}) +print(sorted(z.attrs)) +``` + +Internally Zarr uses JSON to store array and group attributes, so attribute +values must be JSON serializable. + +When working with hierarchies that contain many arrays and groups, reading the +attributes of each node separately can be slow. See +[Consolidated metadata](consolidated_metadata.md) for a way to store the +metadata (including attributes) of all nodes in a hierarchy in a single +document. diff --git a/docs/user-guide/cli.md b/docs/user-guide/cli.md new file mode 100644 index 0000000000..77f50f5eaf --- /dev/null +++ b/docs/user-guide/cli.md @@ -0,0 +1,133 @@ +# Command-line interface + +Zarr-Python provides a command-line interface that enables: + +- migration of Zarr v2 metadata to v3 (see the [3.0 Migration Guide](v3_migration.md) for + migrating your *code* from the Zarr-Python 2 API to the Zarr-Python 3 API) +- removal of v2 or v3 metadata + +## Installation + +The command-line interface requires the `cli` optional dependencies. Install them with: + +```bash +pip install "zarr[cli]" +``` + +Without this extra, running `zarr` in a terminal will fail with `ModuleNotFoundError`. + +## Getting help + +To see available commands run the following in a terminal: + +```bash +zarr --help +``` + +or to get help on individual commands: + +```bash +zarr migrate --help + +zarr remove-metadata --help +``` + +## Migrate metadata from v2 to v3 + +### Migrate to a separate location + +To migrate a Zarr array/group's metadata from v2 to v3 run: + +```bash +zarr migrate v3 path/to/input.zarr path/to/output.zarr +``` + +This will write new `zarr.json` files to `output.zarr`, leaving `input.zarr` un-touched. +Note - this will migrate the entire Zarr hierarchy, so if `input.zarr` contains multiple groups/arrays, +new `zarr.json` will be made for all of them. + +### Migrate in-place + +If you'd prefer to migrate the metadata in-place run: + +```bash +zarr migrate v3 path/to/input.zarr +``` + +This will write new `zarr.json` files to `input.zarr`, leaving the existing v2 metadata un-touched. + +To open the array/group using the new metadata use: + +```python exec="true" session="cli-open" source="above" +import zarr + +# create a small array to open (stands in for the migrated store) +zarr.create_array("data/cli-demo.zarr", shape=(4, 4), chunks=(2, 2), dtype="i4", overwrite=True) + +zarr_with_v3_metadata = zarr.open("data/cli-demo.zarr", zarr_format=3) +``` + +Once you are happy with the conversion, you can run the following to remove the old v2 metadata: + +```bash +zarr remove-metadata v2 path/to/input.zarr +``` + +Note there is also a shortcut to migrate and remove v2 metadata in one step: + +```bash +zarr migrate v3 path/to/input.zarr --remove-v2-metadata +``` + +## Remove metadata + +Remove v2 metadata using: + +```bash +zarr remove-metadata v2 path/to/input.zarr +``` + +or v3 with: + +```bash +zarr remove-metadata v3 path/to/input.zarr +``` + +By default, this will only allow removal of metadata if a valid alternative exists. For example, you can't +remove v2 metadata unless v3 metadata exists at that location. + +To override this behavior use `--force`: + +```bash +zarr remove-metadata v3 path/to/input.zarr --force +``` + +## Dry run + +All commands provide a `--dry-run` option that will log changes that would be made on a real run, without creating +or modifying any files. + +```bash +zarr migrate v3 path/to/input.zarr --dry-run + +Dry run enabled - no new files will be created or changed. Log of files that would be created on a real run: +Saving metadata to file://path/to/input.zarr/zarr.json +``` + +## Verbose + +You can also add `--verbose` **before** any command, to see a full log of its actions: + +```bash +zarr --verbose migrate v3 path/to/input.zarr + +zarr --verbose remove-metadata v2 path/to/input.zarr +``` + +## Equivalent functions + +All features of the command-line interface are also available as functions in the +`zarr.metadata.migrate_v3` module: +[`migrate_v2_to_v3`][zarr.metadata.migrate_v3.migrate_v2_to_v3] and +[`remove_metadata`][zarr.metadata.migrate_v3.remove_metadata]. +See the [`zarr.metadata` API reference](../api/zarr/metadata.md) for details. diff --git a/docs/user-guide/config.md b/docs/user-guide/config.md new file mode 100644 index 0000000000..d1a70a14b0 --- /dev/null +++ b/docs/user-guide/config.md @@ -0,0 +1,61 @@ +# Runtime configuration + +[`zarr.config`][] is responsible for managing the configuration of zarr and +is based on the [donfig](https://github.com/pytroll/donfig) Python library. + +Configuration values can be set using code like the following: + +```python exec="true" session="config" source="above" result="ansi" +import zarr + +zarr.config.set({'array.order': 'F'}) + +print(zarr.config.get('array.order')) +``` + +`zarr.config.set` can also be used as a context manager, which restores the +previous configuration on exit, and `zarr.config.reset` restores the default +configuration: + +```python exec="true" session="config" source="above" result="ansi" +zarr.config.reset() + +with zarr.config.set({'array.order': 'F'}): + print(zarr.config.get('array.order')) + +print(zarr.config.get('array.order')) +``` + +Alternatively, configuration values can be set using environment variables, e.g. +`ZARR_ARRAY__ORDER=F`. + +The configuration can also be read from a YAML file in standard locations. +For more information, see the +[donfig documentation](https://donfig.readthedocs.io/en/latest/). + +Configuration options include the following: + +- Default Zarr format `default_zarr_format` +- Default array order in memory `array.order` +- Whether empty chunks are written to storage `array.write_empty_chunks` +- Enable experimental rectilinear chunks `array.rectilinear_chunks` +- Whether missing chunks are filled with the array's fill value on read `array.read_missing_chunks` (default `True`). Set to `False` to raise a [`ChunkNotFoundError`][zarr.errors.ChunkNotFoundError] instead. +- Async and threading options, e.g. `async.concurrency` and `threading.max_workers` +- Selections of implementations of codecs, codec pipelines and buffers +- Enabling GPU support with `zarr.config.enable_gpu()`. See [GPU support](gpu.md) for more. +- Control request merging when reading multiple chunks from the same shard with `array.sharding_coalesce_max_gap_bytes` and `array.sharding_coalesce_max_bytes`. Reads of nearby chunks are coalesced into a single request to the store when separated by at most `sharding_coalesce_max_gap_bytes` and the resulting merged read is no larger than `sharding_coalesce_max_bytes`. + +For selecting custom implementations of codecs, pipelines, buffers and ndbuffers, +first register the implementations in the registry and then select them in the config. +For example, an implementation of the bytes codec in a class `'custompackage.NewBytesCodec'`, +requires the value of `codecs.bytes` to be `'custompackage.NewBytesCodec'`. + +This is the current default configuration: + +```python exec="true" session="config" source="above" result="ansi" +from pprint import pprint +import io +output = io.StringIO() +zarr.config.pprint(stream=output, width=60) +print(output.getvalue()) +``` diff --git a/docs/user-guide/consolidated_metadata.md b/docs/user-guide/consolidated_metadata.md new file mode 100644 index 0000000000..9cb4d87c89 --- /dev/null +++ b/docs/user-guide/consolidated_metadata.md @@ -0,0 +1,139 @@ +# Consolidated metadata + +!!! warning + The Consolidated Metadata feature in Zarr-Python is considered experimental for v3 + stores. [zarr-specs#309](https://github.com/zarr-developers/zarr-specs/pull/309) + has proposed a formal extension to the v3 specification to support consolidated metadata. + +Zarr-Python implements the Consolidated Metadata feature for both the v2 and v3 formats. +Consolidated metadata can reduce the time needed to load the metadata for an +entire hierarchy, especially when the metadata is being served over a network. +Consolidated metadata essentially stores all the metadata for a hierarchy in the +metadata of the root Group. + +## Usage + +If consolidated metadata is present in a Zarr Group's metadata then it is used +by default. The initial read to open the group will need to communicate with +the store (reading from a file for a [`zarr.storage.LocalStore`][], making a +network request for a [`zarr.storage.FsspecStore`][]). After that, any subsequent +metadata reads to get child Group or Array nodes will *not* require reads from the store. + +In Python, the consolidated metadata is available on the `.consolidated_metadata` +attribute of the `GroupMetadata` object. + +```python exec="true" session="consolidated_metadata" source="above" result="ansi" +import zarr +import warnings + +warnings.filterwarnings("ignore", category=UserWarning) +group = zarr.create_group(store="memory://consolidated-metadata-demo") +print(group) +array = group.create_array(shape=(1,), name='a', dtype='float64') +print(array) +``` + +```python exec="true" session="consolidated_metadata" source="above" result="ansi" +array = group.create_array(shape=(2, 2), name='b', dtype='float64') +print(array) +``` + +```python exec="true" session="consolidated_metadata" source="above" result="ansi" +array = group.create_array(shape=(3, 3, 3), name='c', dtype='float64') +print(array) +``` + +```python exec="true" session="consolidated_metadata" source="above" result="ansi" +result = zarr.consolidate_metadata("memory://consolidated-metadata-demo") +print(result) +``` + +If we open that group, the Group's metadata includes a `ConsolidatedMetadata` object +holding the metadata for every child node, which can be used: + +```python exec="true" session="consolidated_metadata" source="above" result="ansi" +from pprint import pprint +import io + +consolidated = zarr.open_group(store="memory://consolidated-metadata-demo") +consolidated_metadata = consolidated.metadata.consolidated_metadata.metadata + +output = io.StringIO() +pprint(dict(sorted(consolidated_metadata.items())), stream=output, width=60) +print(output.getvalue()) +``` + +Operations on the group to get children automatically use the consolidated metadata: + +```python exec="true" session="consolidated_metadata" source="above" result="ansi" +print(consolidated['a']) # no read / HTTP request to the Store is required +``` + +With nested groups, the consolidated metadata is available on the children, recursively: + +```python exec="true" session="consolidated_metadata" source="above" result="ansi" +child = group.create_group('child', attributes={'kind': 'child'}) +grandchild = child.create_group('grandchild', attributes={'kind': 'grandchild'}) +consolidated = zarr.consolidate_metadata("memory://consolidated-metadata-demo") + +output = io.StringIO() +pprint(consolidated['child'].metadata.consolidated_metadata, stream=output, width=60) +print(output.getvalue()) +``` + +!!! info "Added in version 3.1.1" + The keys in the consolidated metadata are sorted prior to writing. Keys are + sorted in ascending order by path depth, where a path is defined as a sequence + of strings joined by `"/"`. For keys with the same path length, lexicographic + order is used to break the tie. This behavior ensures deterministic metadata + output for a given group. + +### Controlling the use of consolidated metadata + +By default, [`zarr.open_group`][] uses consolidated metadata if it is present, and +falls back to reading metadata from the store otherwise. This behavior can be +controlled with the `use_consolidated` keyword. Pass `use_consolidated=False` to +ignore consolidated metadata and always read the metadata of child nodes directly +from the store: + +```python exec="true" session="consolidated_metadata" source="above" result="ansi" +group = zarr.open_group(store="memory://consolidated-metadata-demo", use_consolidated=False) +print(group.metadata.consolidated_metadata) +``` + +Passing `use_consolidated=True` instead raises an error if consolidated metadata is +not found, which is useful when reading over a network, where relying on many +per-node metadata requests would be slow. + +## Synchronization and Concurrency + +Consolidated metadata is intended for read-heavy use cases on slowly changing +hierarchies. For hierarchies where new nodes are constantly being added, +removed, or modified, consolidated metadata may not be desirable. + +1. It will add some overhead to each update operation, since the metadata + would need to be re-consolidated to keep it in sync with the store. +2. Readers using consolidated metadata will regularly see a "past" version + of the metadata, at the time they read the root node with its consolidated + metadata. Readers who need the latest view of a changing hierarchy can pass + `use_consolidated=False` to [`zarr.open_group`][] to always read child + metadata directly from the store. + +## Stores Without Support for Consolidated Metadata + +Some stores may want to opt out of the consolidated metadata mechanism. This +may be for several reasons like: + +* They want to maintain read-write consistency, which is challenging with + consolidated metadata. +* They have their own consolidated metadata mechanism. +* They offer good enough performance without need for consolidation. + +This type of store can declare it doesn't want consolidation by implementing +`Store.supports_consolidated_metadata` and returning `False`. For stores that don't support +consolidation, Zarr will: + +* Raise an error on `consolidate_metadata` calls, maintaining the store in + its unconsolidated state. +* Raise an error in `AsyncGroup.open(..., use_consolidated=True)` +* Not use consolidated metadata in `AsyncGroup.open(..., use_consolidated=None)` diff --git a/docs/user-guide/data_types.md b/docs/user-guide/data_types.md new file mode 100644 index 0000000000..91f828a738 --- /dev/null +++ b/docs/user-guide/data_types.md @@ -0,0 +1,456 @@ +# Array data types + +## Zarr's data type model + +Zarr is designed for interoperability with NumPy, so if you are familiar with NumPy or any other +N-dimensional array library, Zarr's model for array data types should seem familiar. However, Zarr +data types have some unique features that are described in this document. + +Zarr arrays operate under an essential design constraint: unlike NumPy arrays, Zarr arrays +are designed to be stored and accessed by other Zarr implementations. This means that, among other things, +Zarr data types must be serializable to metadata documents in accordance with the Zarr specifications, +which adds some unique aspects to the Zarr data type model. + +The following sections explain Zarr's data type model in greater detail and demonstrate the +Zarr Python APIs for working with Zarr data types. + +### Array data types + +Every Zarr array has a data type, which defines the meaning of the array's elements. An array's data +type is encoded in the JSON metadata for the array. This means that the data type of an array must be +JSON-serializable. + +In Zarr V2, the data type of an array is stored in the `dtype` field in array metadata. +Zarr V3 changed the name of this field to `data_type` and also defined new rules for the values +that can be assigned to the `data_type` field. + +For example, in Zarr V2, the boolean array data type was represented in array metadata as the +string `"|b1"`. In Zarr V3, the same type is represented as the string `"bool"`. + +### Scalars + +Zarr also specifies how array elements, i.e., scalars, are encoded in array metadata. This is necessary +because Zarr uses a field in array metadata to define a default value for chunks that are not stored. +This field, called `fill_value` in both Zarr V2 and Zarr V3 metadata documents, contains a +JSON value that can be decoded to a scalar value compatible with the array's data type. + +For the boolean data type, the scalar encoding is simpleβ€”booleans are natively supported by +JSON, so Zarr saves booleans as JSON booleans. Other scalars, like floats or raw bytes, have +more elaborate encoding schemes, and in some cases, this scheme depends on the Zarr format version. + +## Data types in Zarr version 2 + +Version 2 of the Zarr format defined its data types relative to +[NumPy's data types](https://numpy.org/doc/stable/reference/arrays.dtypes.html#data-type-objects-dtype), +and added a few non-NumPy data types as well. With one exception ([structured data types](#structured-data-type)), the Zarr +V2 JSON identifier for a data type is just the NumPy `str` attribute of that data type: + +```python exec="true" session="data_types" source="above" result="ansi" +import zarr +import numpy as np +import json + +store = {} +np_dtype = np.dtype('int64') +print(np_dtype.str) +``` + +```python exec="true" session="data_types" source="above" result="ansi" +z = zarr.create_array(store=store, shape=(1,), dtype=np_dtype, zarr_format=2) +dtype_meta = json.loads(store['.zarray'].to_bytes())["dtype"] +print(dtype_meta) +``` + +!!! note + + The `<` character in the data type metadata encodes the + [endianness](https://numpy.org/doc/stable/reference/generated/numpy.dtype.byteorder.html), + or "byte order," of the data type. As per the NumPy model, + in Zarr version 2 each data type has an endianness where applicable. + However, Zarr version 3 data types do not store endianness information. + +There are two special cases to consider: ["structured" data types](#structured-data-type), and +["object"](#object-data-type) data types. + +### Structured data type + +NumPy allows the construction of a so-called "structured" data types comprised of ordered collections +of named fields, where each field is itself a distinct NumPy data type. See the NumPy documentation +[here](https://numpy.org/doc/stable/user/basics.rec.html). + +Crucially, NumPy does not use a special data type for structured data typesβ€”instead, NumPy +implements structured data types as an optional feature of the so-called "Void" data type, which models +arbitrary fixed-size byte strings. The `str` attribute of a regular NumPy void +data type is the same as the `str` of a NumPy structured data type. This means that the `str` +attribute does not convey information about the fields contained in a structured data type. +For these reasons, Zarr V2 uses a special data type encoding for structured data types. +They are stored in JSON as lists of pairs, where the first element is a string, and the second +element is a Zarr V2 data type specification. This representation supports recursion. + +For example: + +```python exec="true" session="data_types" source="above" result="ansi" +store = {} +np_dtype = np.dtype([('field_a', '>i2'), ('field_b', [('subfield_c', '>f4'), ('subfield_d', 'i2')])]) +print(np_dtype.str) +``` + +```python exec="true" session="data_types" source="above" result="ansi" +z = zarr.create_array(store=store, shape=(1,), dtype=np_dtype, zarr_format=2) +dtype_meta = json.loads(store['.zarray'].to_bytes())["dtype"] +print(dtype_meta) +``` + +### Object data type + +The NumPy "object" type is essentially an array of references to arbitrary Python objects. +It can model arrays of variable-length UTF-8 strings, arrays of variable-length byte strings, or +even arrays of variable-length arrays, each with a distinct data type. This makes the "object" data +type expressive, but also complicated to store. + +Zarr Python cannot persistently store references to arbitrary Python objects. But if each of those Python +objects has a consistent type, then we can use a special encoding procedure to store the array. This +is how Zarr Python stores variable-length UTF-8 strings, or variable-length byte strings. + +Although these are separate data types in this library, they are both "object" arrays in NumPy, which means +they have the *same* Zarr V2 string representation: `"|O"`. + +So for Zarr V2 we have to disambiguate different "object" data type arrays on the basis of their +encoding procedure, i.e., the codecs declared in the `filters` and `compressor` attributes of array +metadata. + +If an array with data type "object" used the `"vlen-utf8"` codec, then it was interpreted as an +array of variable-length strings. If an array with data type "object" used the `"vlen-bytes"` +codec, then it was interpreted as an array of variable-length byte strings. + +This all means that the `dtype` field alone does not fully specify a data type in Zarr V2. +The name of the object codec used, if one was used, is also required. +Although this fact can be ignored for many simple numeric data types, any comprehensive approach to +Zarr V2 data types must either reject the "object" data types or include the "object codec" +identifier in the JSON form of the basic data type model. + +## Data types in Zarr version 3 + +The NumPy-based Zarr V2 data type representation was effective for simple data types but struggled +with more complex data types, like "object" and "structured" data types. To address these limitations, +Zarr V3 introduced several key changes to how data types are represented: + +- Instead of copying NumPy character codecs, Zarr V3 defines an identifier for each data type. + The basic data types are identified by strings like `"int8"`, `"int16"`, etc., and data types + that require a configuration can be identified by a JSON object. + + For example, this JSON object declares a datetime data type: + + ```json + { + "name": "numpy.datetime64", + "configuration": { + "unit": "s", + "scale_factor": 10 + } + } + ``` + +- Zarr V3 data types do not have endianness. This is a departure from Zarr V2, where multi-byte + data types are defined with endianness information. Instead, Zarr V3 requires that the endianness + of encoded array chunks is specified in the `codecs` attribute of array metadata. The Zarr + V3 specification leaves the in-memory endianness of decoded array chunks as an implementation detail. + +For more about data types in Zarr V3, see the +[V3 specification](https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html). + +## Data types in Zarr Python + +The two Zarr formats that Zarr Python supports specify data types in different ways: data types in +Zarr version 2 are encoded as NumPy-compatible strings (or lists, in the case of structured data +types), while data types in Zarr V3 are encoded as either strings or JSON objects. Zarr V3 data +types do not have any associated endianness information, unlike Zarr V2 data types. + +Zarr Python needs to support both Zarr V2 and V3, which means we need to abstract over these differences. +We do this with an abstract Zarr data type class: [ZDType][zarr.dtype.ZDType] +which provides Zarr V2 and Zarr V3 compatibility routines for "native" data types. + +In this context, a "native" data type is a Python class, typically defined in another library, that +models an array's data type. For example, [`numpy.dtypes.UInt8DType`][] is a native data type defined in NumPy. +Zarr Python wraps the NumPy `uint8` with a [ZDType][zarr.dtype.ZDType] instance called +[UInt8][zarr.dtype.UInt8]. + +As of this writing, the only native data types Zarr Python supports are NumPy data types. We could +avoid the "native data type" jargon and just say "NumPy data type," but we do not want to rule out the +possibility of using non-NumPy array backends in the future. + +Each data type supported by Zarr Python is modeled by a [ZDType][zarr.dtype.ZDType] subclass, which provides an +API for the following operations: + +- Encoding and decoding a native data type +- Encoding and decoding a data type to and from Zarr V2 and Zarr V3 array metadata +- Encoding and decoding a scalar value to and from Zarr V2 and Zarr V3 array metadata +- Casting a Python object to a scalar value consistent with the data type + +### List of data types + +The following section lists the data types built in to Zarr Python. With a few exceptions, Zarr +Python supports nearly all of the data types in NumPy. If you need a data type that is not listed +here, it's possible to create it yourself: see [Adding new data types](#adding-new-data-types). + +#### Boolean + +- [Boolean][zarr.dtype.Bool] + +#### Integral + +- [Signed 8-bit integer][zarr.dtype.Int8] +- [Signed 16-bit integer][zarr.dtype.Int16] +- [Signed 32-bit integer][zarr.dtype.Int32] +- [Signed 64-bit integer][zarr.dtype.Int64] +- [Unsigned 8-bit integer][zarr.dtype.UInt8] +- [Unsigned 16-bit integer][zarr.dtype.UInt16] +- [Unsigned 32-bit integer][zarr.dtype.UInt32] +- [Unsigned 64-bit integer][zarr.dtype.UInt64] + +#### Floating-point + +- [16-bit floating-point][zarr.dtype.Float16] +- [32-bit floating-point][zarr.dtype.Float32] +- [64-bit floating-point][zarr.dtype.Float64] +- [64-bit complex floating-point][zarr.dtype.Complex64] +- [128-bit complex floating-point][zarr.dtype.Complex128] + +#### String + +- [Fixed-length UTF-32 string][zarr.dtype.FixedLengthUTF32] +- [Variable-length UTF-8 string][zarr.dtype.VariableLengthUTF8] + +#### Bytes + +- [Fixed-length null-terminated bytes][zarr.dtype.NullTerminatedBytes] +- [Fixed-length raw bytes][zarr.dtype.RawBytes] +- [Variable-length bytes][zarr.dtype.VariableLengthBytes] + +#### Temporal + +- [DateTime64][zarr.dtype.DateTime64] +- [TimeDelta64][zarr.dtype.TimeDelta64] + +#### Struct-like + +- [Structured][zarr.dtype.Structured] + +!!! note "Zarr V3 Structured Data Types" + + In Zarr V3, structured data types are specified using the `struct` extension defined in the + [zarr-extensions repository](https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/struct). + The JSON representation uses an object format for fields: + + ```json + { + "name": "struct", + "configuration": { + "fields": [ + {"name": "x", "data_type": "float32"}, + {"name": "y", "data_type": "int64"} + ] + } + } + ``` + + For backward compatibility, Zarr Python also accepts the legacy `structured` name with + tuple-format fields when reading existing data. + + Fill values for structured types are represented as JSON objects mapping field names to values: + + ```json + {"x": 1.5, "y": 42} + ``` + + When using structured types with multi-byte fields, the `bytes` codec must specify an + explicit `endian` parameter. If omitted, Zarr Python assumes little-endian for legacy + compatibility but emits a warning. + +### Example usage + +This section will demonstrate the basic usage of Zarr data types. + +Create a `ZDType` from a native data type: + +```python exec="true" session="data_types" source="above" +from zarr.dtype import Int8 +import numpy as np +int8 = Int8.from_native_dtype(np.dtype('int8')) +``` + +Convert back to a native data type: + +```python exec="true" session="data_types" source="above" +native_dtype = int8.to_native_dtype() +assert native_dtype == np.dtype('int8') +``` + +Get the default scalar value for the data type: + +```python exec="true" session="data_types" source="above" +default_value = int8.default_scalar() +assert default_value == np.int8(0) +``` + +Serialize to JSON for Zarr V2: + +```python exec="true" session="data_types" source="above" result="ansi" +json_v2 = int8.to_json(zarr_format=2) +print(json_v2) +``` + +!!! note + + The representation returned by `to_json(zarr_format=2)` is more abstract than the literal contents + of Zarr V2 array metadata, because the JSON representation used by the `ZDType` classes must be + distinct across different data types. As noted [earlier](#object-data-type), Zarr V2 identifies + multiple distinct data types with the "object" data type identifier `"|O"`. Extra information + is needed to disambiguate these data types from one another. That's the reason for the + `object_codec_id` field you see here. + +And for V3: + +```python exec="true" session="data_types" source="above" result="ansi" +json_v3 = int8.to_json(zarr_format=3) +print(json_v3) +``` + +Serialize a scalar value to JSON: + +```python exec="true" session="data_types" source="above" result="ansi" +json_value = int8.to_json_scalar(42, zarr_format=3) +print(json_value) +``` + +Deserialize a scalar value from JSON: + +```python exec="true" session="data_types" source="above" +scalar_value = int8.from_json_scalar(42, zarr_format=3) +assert scalar_value == np.int8(42) +``` + +### Adding new data types + +Each Zarr data type is a separate Python class that inherits from +[ZDType][zarr.dtype.ZDType]. You can define a custom data type by +writing your own subclass of [ZDType][zarr.dtype.ZDType] and adding +your data type to the data type registry. To see an executable demonstration +of this process, see the [`custom_dtype` example](../user-guide/examples/custom_dtype.md). + +### Data type resolution + +Although Zarr Python uses a different data type model from NumPy, you can still define a Zarr array +with a NumPy data type object: + +```python exec="true" session="data_types" source="above" result="ansi" +from zarr import create_array +import numpy as np +a = create_array({}, shape=(10,), dtype=np.dtype('int')) +print(a) +``` + +Or a string representation of a NumPy data type: + +```python exec="true" session="data_types" source="above" result="ansi" +a = create_array({}, shape=(10,), dtype=' +``` + +This example illustrates a general problem Zarr Python has to solve: how can we allow users to +specify a data type as a string or a NumPy `dtype` object, and produce the right Zarr data type +from that input? We call this process "data type resolution." Zarr Python also performs data type +resolution when reading stored arrays, although in this case the input is a JSON value instead +of a NumPy data type. + +For simple data types like `int`, the solution could be extremely simple: just +maintain a lookup table that maps a NumPy data type to the Zarr data type equivalent. But not all +data types are so simple. Consider this case: + +```python exec="true" session="data_types" source="above" result="ansi" +from zarr import create_array +import numpy as np +a = create_array({}, shape=(10,), dtype=[('a', 'f8'), ('b', 'i8')]) +print(a.dtype) # this is the NumPy data type +``` + +```python exec="true" session="data_types" source="above" result="ansi" +print(a.metadata.data_type) # this is the Zarr data type +``` + +In this example, we created a +[NumPy structured data type](https://numpy.org/doc/stable/user/basics.rec.html#structured-datatypes). +This data type is a container that can hold any NumPy data type, which makes it recursive. It is +not possible to make a lookup table that relates all NumPy structured data types to their Zarr +equivalents, as there is a nearly unbounded number of different structured data types. So instead of +a static lookup table, Zarr Python relies on a dynamic approach to data type resolution. + +Zarr Python defines a collection of Zarr data types. This collection, called a "data type registry," +is essentially a dictionary where the keys are strings (a canonical name for each data type), and the +values are the data type classes themselves. Dynamic data type resolution entails iterating over +these data type classes, invoking that class' [from_native_dtype][zarr.dtype.ZDType.from_native_dtype] +method, and returning a concrete data type instance if and only if exactly one of those constructor +invocations is successful. + +In plain language, we take some user input, like a NumPy data type, offer it to all the +known data type classes, and return an instance of the one data type class that can accept that user input. + +We want to avoid a situation where the same native data type matches multiple Zarr data types; that is, +a NumPy data type should *uniquely* specify a single Zarr data type. But data type resolution is +dynamic, so it's not possible to statically guarantee this uniqueness constraint. Therefore, we +attempt data type resolution against *every* data type class, and if, for some reason, a native data +type matches multiple Zarr data types, we treat this as an error and raise an exception. + +If you have a NumPy data type and you want to get the corresponding `ZDType` instance, you can use +the `parse_dtype` function, which will use the dynamic resolution described above. `parse_dtype` +handles a range of input types: + +- NumPy data types: + + ```python exec="true" session="data_types" source="above" result="ansi" + import numpy as np + from zarr.dtype import parse_dtype + my_dtype = np.dtype('>M8[10s]') + print(parse_dtype(my_dtype, zarr_format=2)) + ``` + +- NumPy data type-compatible strings: + + ```python exec="true" session="data_types" source="above" result="ansi" + dtype_str = '>M8[10s]' + print(parse_dtype(dtype_str, zarr_format=2)) + ``` + +- `ZDType` instances: + + ```python exec="true" session="data_types" source="above" result="ansi" + from zarr.dtype import DateTime64 + zdt = DateTime64(endianness='big', scale_factor=10, unit='s') + print(parse_dtype(zdt, zarr_format=2)) # Use a ZDType (this is a no-op) + ``` + +- Python dictionaries (requires `zarr_format=3`). These dictionaries must be consistent with the + `JSON` form of the data type: + + ```python exec="true" session="data_types" source="above" result="ansi" + dt_dict = {"name": "numpy.datetime64", "configuration": {"unit": "s", "scale_factor": 10}} + print(parse_dtype(dt_dict, zarr_format=3)) + ``` + + ```python exec="true" session="data_types" source="above" result="ansi" + print(parse_dtype(dt_dict, zarr_format=3).to_json(zarr_format=3)) + ``` diff --git a/docs/user-guide/examples/codec_pipeline_performance.md b/docs/user-guide/examples/codec_pipeline_performance.md new file mode 100644 index 0000000000..f21e31636e --- /dev/null +++ b/docs/user-guide/examples/codec_pipeline_performance.md @@ -0,0 +1,7 @@ +--8<-- "examples/codec_pipeline_performance/README.md" + +## Source Code + +```python exec="false" reason="pymdownx snippet include directive, not python source" +--8<-- "examples/codec_pipeline_performance/codec_pipeline_performance.py" +``` diff --git a/docs/user-guide/examples/custom_dtype.md b/docs/user-guide/examples/custom_dtype.md new file mode 100644 index 0000000000..391407b822 --- /dev/null +++ b/docs/user-guide/examples/custom_dtype.md @@ -0,0 +1,7 @@ +--8<-- "examples/custom_dtype/README.md" + +## Source Code + +```python exec="false" reason="pymdownx snippet include directive, not python source" +--8<-- "examples/custom_dtype/custom_dtype.py" +``` diff --git a/docs/user-guide/examples/rectilinear_chunks.md b/docs/user-guide/examples/rectilinear_chunks.md new file mode 100644 index 0000000000..098cdf1e2f --- /dev/null +++ b/docs/user-guide/examples/rectilinear_chunks.md @@ -0,0 +1,173 @@ +# Rectilinear Chunk Grids + +This example demonstrates rectilinear (variable-sized) chunk grids, introduced in +[#3802](https://github.com/zarr-developers/zarr-python/pull/3802). Rectilinear grids +allow different chunk sizes along each dimension, which is useful for data that +doesn't partition evenly β€” for example, sparse HEALPix cells grouped by parent tile, +boundary-padded HPC arrays, or ingesting existing variable-chunked datasets via +VirtualiZarr. See [Rectilinear (variable) chunk grids](../arrays.md#rectilinear-variable-chunk-grids) +in the arrays guide for an introduction to the feature. + +The example chunks a HEALPix dataset by parent tile, writes it as a Zarr v3 array +with a rectilinear chunk grid, and verifies the round trip through +[Xarray](https://xarray.dev). + +!!! warning "Experimental" + Rectilinear chunk grids are an experimental feature and may change in future + releases. In addition, this example currently requires + [a fork of Xarray](https://github.com/maxrjones/xarray/tree/poc/unified-zarr-chunk-grid) + with rectilinear chunk grid support (this will ideally be incorporated into a + future Xarray release), as well as the `dask`, `healpix-geo`, and `obstore` + packages, and it reads an example dataset from a remote server. For these + reasons the code on this page is not executed when the documentation is built; + the outputs shown were captured from a live run. + +## Setup + +Rectilinear chunk grids are disabled by default and must be explicitly enabled via +the `array.rectilinear_chunks` configuration option: + +```python exec="false" reason="requires an xarray fork with rectilinear chunk grid support and remote example data" +import json +import tempfile +from pathlib import Path + +import numpy as np +import xarray as xr +from healpix_geo import nested +from obstore.store import HTTPStore + +import zarr +from zarr.storage import ObjectStore + +# Increase concurrency for better performance with obstore +zarr.config.set({'async.concurrency': 128}) +# Opt in to rectilinear chunks +zarr.config.set({'array.rectilinear_chunks': True}) +``` + +## Inspect the HEALPix dataset + +Load the remote Zarr store to understand the data structure before chunking it: + +```python exec="false" reason="requires an xarray fork with rectilinear chunk grid support and remote example data" +ob_store = HTTPStore.from_url("https://data-taos.ifremer.fr/GRID4EARTH/no_chunk_healpix.zarr") +store = ObjectStore(ob_store) +g = zarr.open_group(store, mode="r", zarr_format=2, use_consolidated=True) +arr = g['da'] + +print("Members:", list(g.members())) +print("Attrs:", dict(g.attrs)) +print("Write chunk sizes:", arr.write_chunk_sizes) +``` + +```text +Members: [('cell_ids', ), ('da', )] +Attrs: {} +Write chunk sizes: ((55611, 55611, 55611, 55609),) +``` + +## HEALPix-style variable chunking + +Inspired by [this use case](https://github.com/zarr-developers/zarr-python/pull/3534#issuecomment-3848669859): +HEALPix grids where cells are grouped by parent tile at a coarser resolution level, +producing variable-sized chunks along the cell dimension when accounting for sparsity. + +```python exec="false" reason="requires an xarray fork with rectilinear chunk grid support and remote example data" +da = xr.open_zarr( + store, + zarr_format=2, + consolidated=True, +) + +depth = da.cell_ids.attrs['level'] +new_depth = depth - 6 +parents = nested.zoom_to(da.cell_ids, depth=depth, new_depth=new_depth) +_, chunk_sizes = np.unique(parents, return_counts=True) +print(chunk_sizes) +``` + +```text +[ 25 645 1510 2363 3203 74 769 3963 4096 233 1603 2450 4096 4096 + 3327 4047 4096 4096 1278 2113 4096 3879 4096 3842 2173 983 4046 2187 + 4095 1369 4096 4096 4096 4096 3515 1395 4096 3622 4096 4096 3875 4096 + 4096 4096 4096 4096 2034 4096 358 3991 4096 4096 4096 4096 2714 1210 + 4096 4096 4096 4096 92 3826 4096 2629 4096 1438 4096 353 4078 3410 + 2407 226 132 2738 1223 23] +``` + +Rechunk the dataset with these variable-sized chunks: + +```python exec="false" reason="requires an xarray fork with rectilinear chunk grid support and remote example data" +da = da.chunk({"cell_ids": tuple(chunk_sizes.tolist())}) +print(da.chunks) +``` + +```text +Frozen({'cell_ids': (25, 645, 1510, 2363, 3203, 74, 769, 3963, 4096, 233, 1603, 2450, 4096, 4096, 3327, 4047, 4096, 4096, 1278, 2113, 4096, 3879, 4096, 3842, 2173, 983, 4046, 2187, 4095, 1369, 4096, 4096, 4096, 4096, 3515, 1395, 4096, 3622, 4096, 4096, 3875, 4096, 4096, 4096, 4096, 4096, 2034, 4096, 358, 3991, 4096, 4096, 4096, 4096, 2714, 1210, 4096, 4096, 4096, 4096, 92, 3826, 4096, 2629, 4096, 1438, 4096, 353, 4078, 3410, 2407, 226, 132, 2738, 1223, 23)}) +``` + +## Write as rectilinear Zarr v3 + +Write the variable-chunked dataset to a local Zarr v3 store with rectilinear chunk +grids enabled: + +```python exec="false" reason="requires an xarray fork with rectilinear chunk grid support and remote example data" +output_path = Path(tempfile.mkdtemp()) / "healpix_rectilinear.zarr" + +encoding = { + "da": {"chunks": [chunk_sizes.tolist()]}, + "cell_ids": {"chunks": [chunk_sizes.tolist()]}, +} + +da.to_zarr(output_path, zarr_format=3, mode="w", encoding=encoding, consolidated=False) + +print(f"Written to: {output_path}") +``` + +```text +Written to: /var/folders/.../T/tmp6dibcrho/healpix_rectilinear.zarr +``` + +## Verify the rectilinear metadata + +Inspect the output store to confirm the chunk grid is serialized as `"rectilinear"` +in `zarr.json`, following the +[rectilinear chunk grid extension spec](https://github.com/zarr-developers/zarr-extensions/tree/main/chunk-grids/rectilinear). + +Key things to look for in `chunk_grid`: + +- **`name`**: `"rectilinear"` (the extension identifier) +- **`configuration.kind`**: `"inline"` (edge lengths stored directly in metadata) +- **`configuration.chunk_shapes`**: one entry per dimension β€” here a single list for + the 1D `cell_ids` axis. Each element is either: + - a **bare integer** for a unique edge length (e.g., `25`, `645`) + - a **`[value, count]` array** using + [run-length encoding](https://github.com/zarr-developers/zarr-extensions/tree/main/chunk-grids/rectilinear#run-length-encoding) + for consecutive repeated sizes (e.g., `[4096, 4]` means four consecutive chunks + of size 4096) + +```python exec="false" reason="requires an xarray fork with rectilinear chunk grid support and remote example data" +# Read the zarr.json for the 'da' array +da_meta_path = output_path / "da" / "zarr.json" +meta = json.loads(da_meta_path.read_text()) +print(meta['chunk_grid']) +``` + +```text +{'name': 'rectilinear', 'configuration': {'kind': 'inline', 'chunk_shapes': [[25, 645, 1510, 2363, 3203, 74, 769, 3963, 4096, 233, 1603, 2450, [4096, 2], 3327, 4047, [4096, 2], 1278, 2113, 4096, 3879, 4096, 3842, 2173, 983, 4046, 2187, 4095, 1369, [4096, 4], 3515, 1395, 4096, 3622, [4096, 2], 3875, [4096, 5], 2034, 4096, 358, 3991, [4096, 4], 2714, 1210, [4096, 4], 92, 3826, 4096, 2629, 4096, 1438, 4096, 353, 4078, 3410, 2407, 226, 132, 2738, 1223, 23]]}} +``` + +## Round-trip verification + +Read the rectilinear store back and confirm the chunk sizes are preserved: + +```python exec="false" reason="requires an xarray fork with rectilinear chunk grid support and remote example data" +roundtrip = xr.open_zarr(output_path, zarr_format=3, consolidated=False) + +print("Round-trip chunk sizes:", roundtrip.chunks) +``` + +```text +Round-trip chunk sizes: Frozen({'cell_ids': (25, 645, 1510, 2363, 3203, 74, 769, 3963, 4096, 233, 1603, 2450, 4096, 4096, 3327, 4047, 4096, 4096, 1278, 2113, 4096, 3879, 4096, 3842, 2173, 983, 4046, 2187, 4095, 1369, 4096, 4096, 4096, 4096, 3515, 1395, 4096, 3622, 4096, 4096, 3875, 4096, 4096, 4096, 4096, 4096, 2034, 4096, 358, 3991, 4096, 4096, 4096, 4096, 2714, 1210, 4096, 4096, 4096, 4096, 92, 3826, 4096, 2629, 4096, 1438, 4096, 353, 4078, 3410, 2407, 226, 132, 2738, 1223, 23)}) +``` diff --git a/docs/user-guide/examples/sharding_coalescing.md b/docs/user-guide/examples/sharding_coalescing.md new file mode 100644 index 0000000000..8b2e054af5 --- /dev/null +++ b/docs/user-guide/examples/sharding_coalescing.md @@ -0,0 +1,7 @@ +--8<-- "examples/sharding_coalescing/README.md" + +## Source Code + +```python exec="false" reason="pymdownx snippet include directive, not python source" +--8<-- "examples/sharding_coalescing/sharding_coalescing.py" +``` diff --git a/docs/user-guide/experimental.md b/docs/user-guide/experimental.md new file mode 100644 index 0000000000..e14146610c --- /dev/null +++ b/docs/user-guide/experimental.md @@ -0,0 +1,360 @@ +# Experimental features + +This section contains documentation for experimental Zarr Python features. The features described here are exciting and potentially useful, but also volatile -- we might change them at any time. Take this into account if you consider depending on these features. See the +[experimental API policy](../contributing.md#experimental-api-policy) for the stability +guarantees (or lack thereof) that apply to everything documented on this page. + +## `FusedCodecPipeline` + +A *codec pipeline* is the machinery that turns chunks of array data into stored bytes and back, by running the configured codecs (filters, serializer, compressors) and performing the storage IO. +The default pipeline, `BatchedCodecPipeline`, schedules both the IO and codec work asynchronously -- roughly one coroutine per chunk operation. + +`FusedCodecPipeline` is an experimental alternative that runs codec compute and synchronous IO *synchronously*, avoiding that per-chunk async scheduling overhead and nasty [`asyncio.to_thread` overhead](https://github.com/python/cpython/issues/136084). +On real workloads the scheduling cost can dominate the actual codec work, so removing it is a significant speedup -- especially for **sharded arrays**, where a single shard read or write involves many inner chunks. + +> **Note:** The win is *not* a faster compressor or a different on-disk format -- the bytes written are +> identical. It is purely the removal of async scheduling overhead, plus a few vectorized fast paths +> for dense, uncompressed shards i.e., removing compute where it is not needed. + +### When it helps + +There are two main benefits in this new pipeline: + +1. When storage IO is fast enough that the *scheduling* overhead, not the IO itself, is the bottleneck. That means **low-latency stores** that are themselves synchronous -- in particular [`zarr.storage.MemoryStore`][] and [`zarr.storage.LocalStore`][]. + +2. Whenever codec work that is truly synchronous will not need the overhead of `async` scheduling i.e., inner-chunk codec work in sharding using something like `zstd`. We also now make use of `asyncio.as_completed` so that IO from asynchronous sources can begin decompression immediately. + +### Opting in + +`FusedCodecPipeline` is opt-in: the default pipeline is unchanged, so existing code behaves exactly as +before. Select it through the [runtime configuration](config.md), by setting `codec_pipeline.path`: + +```python exec="true" session="experimental-fused" source="above" result="ansi" +import zarr + +zarr.config.set( + {"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"} +) +``` + +You can set this globally as above (affecting every array created or opened afterwards), or scope it to +a block of code using `zarr.config.set` as a context manager: + +```python exec="true" session="experimental-fused" source="above" +import numpy as np +import zarr +from zarr.storage import MemoryStore + +with zarr.config.set( + {"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"} +): + # A sharded array on an in-memory store -- the low-latency case the + # synchronous pipeline targets. + arr = zarr.create_array( + store=MemoryStore(), + shape=(1000, 1000), + chunks=(100, 100), + shards=(1000, 1000), + dtype="float32", + ) + arr[:] = np.random.random((1000, 1000)).astype("float32") + result = arr[:] + +print(result.shape) +``` + +To return to the default pipeline, set `codec_pipeline.path` back to the batched implementation: + +```python exec="true" session="experimental-fused" source="above" +import zarr + +zarr.config.set( + {"codec_pipeline.path": "zarr.core.codec_pipeline.BatchedCodecPipeline"} +) +``` + +### Threading + +By default the synchronous pipeline runs fully threaded i.e., `os.cpu_count()`. +For memory-backed workflows, you may find that setting `max_workers` to 1 helps (since requests for data from the store are GIL-locked, unlike, say, file-backed i/o). + +```python exec="true" session="experimental-fused" source="above" +import zarr + +# Use a fixed-size thread pool for codec compute. +zarr.config.set({"codec_pipeline.max_workers": 8}) + +# Or "auto", sized to the number of CPUs. +zarr.config.set({"codec_pipeline.max_workers": None}) +``` + +On many-core nodes a pool sized to `cpu_count` can oversubscribe workloads that already parallelize at a higher level (e.g. Dask). +`codec_pipeline.max_workers` only affects `FusedCodecPipeline`; the default `BatchedCodecPipeline` ignores it. + +## `CacheStore` + +Zarr Python 3.1.4 adds [`zarr.experimental.cache_store.CacheStore`][], which provides a dual-store caching implementation +that can be wrapped around any Zarr store to improve performance for repeated data access. +This is particularly useful when working with remote stores (e.g., S3, HTTP) where network +latency can significantly impact data access speed. + +The CacheStore implements a cache that uses a separate Store instance as the cache backend, +providing persistent caching capabilities with time-based expiration, size-based eviction, +and flexible cache storage options. It automatically evicts the least recently used items +when the cache reaches its maximum size. + +Because the `CacheStore` uses an ordinary Zarr `Store` object as the caching layer, you can reuse the data stored in the cache later. + +!!! note + The CacheStore is a wrapper store that maintains compatibility with the full + `zarr.abc.store.Store` API while adding transparent caching functionality. + +### Basic Usage + +Creating a CacheStore requires both a source store and a cache store. The cache store +can be any Store implementation, providing flexibility in cache persistence: + +```python exec="true" session="experimental" source="above" +import zarr +from zarr.storage import LocalStore +import numpy as np +from tempfile import mkdtemp +from zarr.experimental.cache_store import CacheStore + +# Create a local store and a separate cache store +local_store_path = mkdtemp(suffix='.zarr') +source_store = LocalStore(local_store_path) +cache_store = zarr.storage.MemoryStore() # In-memory cache +cached_store = CacheStore( + store=source_store, + cache_store=cache_store, + max_size=256*1024*1024 # 256MB cache +) + +# Create an array using the cached store +zarr_array = zarr.zeros((100, 100), chunks=(10, 10), dtype='f8', store=cached_store, mode='w') + +# Write some data to force chunk creation +zarr_array[:] = np.random.random((100, 100)) +``` + +The dual-store architecture allows you to use different store types for source and cache, +such as a remote store for source data and a local store for persistent caching. + +### Performance Benefits + +The CacheStore provides significant performance improvements for repeated data access: + +```python exec="true" session="experimental" source="above" +import time + +# Benchmark reading with cache +start = time.time() +for _ in range(100): + _ = zarr_array[:] +elapsed_cache = time.time() - start + +# Compare with direct store access (without cache) +zarr_array_nocache = zarr.open(local_store_path, mode='r') +start = time.time() +for _ in range(100): + _ = zarr_array_nocache[:] +elapsed_nocache = time.time() - start + +# Cache provides speedup for repeated access +speedup = elapsed_nocache / elapsed_cache +print(f"Speedup is {speedup}") +``` + +Cache effectiveness is particularly pronounced with repeated access to the same data chunks. + +### Cache Configuration + +The CacheStore can be configured with several parameters: + +**max_size**: Controls the maximum size of cached data in bytes. The +[Basic Usage](#basic-usage) example above sets a 256MB limit with +`max_size=256*1024*1024`: + +```python exec="true" session="experimental" source="above" +# Unlimited cache size (use with caution) +cache = CacheStore( + store=source_store, + cache_store=cache_store, + max_size=None +) +``` + +**max_age_seconds**: Controls time-based cache expiration + +```python exec="true" session="experimental" source="above" +# Cache expires after 1 hour +cache = CacheStore( + store=source_store, + cache_store=cache_store, + max_age_seconds=3600 +) + +# Cache never expires +cache = CacheStore( + store=source_store, + cache_store=cache_store, + max_age_seconds="infinity" +) +``` + +**cache_set_data**: Controls whether written data is cached + +```python exec="true" session="experimental" source="above" +# Cache data when writing (default) +cache = CacheStore( + store=source_store, + cache_store=cache_store, + cache_set_data=True +) + +# Don't cache written data (read-only cache) +cache = CacheStore( + store=source_store, + cache_store=cache_store, + cache_set_data=False +) +``` + +### Cache Statistics + +The CacheStore provides statistics to monitor cache performance and state: + +```python exec="true" session="experimental" source="above" +# Access some data to generate cache activity +# (these chunks were already cached by the reads above, so both accesses are cache hits) +data = zarr_array[0:50, 0:50] +data = zarr_array[0:50, 0:50] + +# Get comprehensive cache information +info = cached_store.cache_info() +print(info['cache_store_type']) # e.g., 'MemoryStore' +print(info['max_age_seconds']) +print(info['max_size']) +print(info['current_size']) +print(info['tracked_keys']) +print(info['cached_keys']) +print(info['cache_set_data']) +``` + +The `cache_info()` method returns a dictionary with detailed information about the cache state. + +### Cache Management + +The CacheStore provides methods for manual cache management: + +```python exec="true" session="experimental" source="above" +# Clear all cached data and tracking information +import asyncio +asyncio.run(cached_store.clear_cache()) + +# Check cache info after clearing +info = cached_store.cache_info() +assert info['tracked_keys'] == 0 +assert info['current_size'] == 0 +``` + +The `clear_cache()` method is an async method that clears both the cache store +(if it supports the `clear` method) and all internal tracking data. + +### Best Practices + +1. **Choose appropriate cache store**: Use MemoryStore for fast temporary caching or LocalStore for persistent caching +2. **Size the cache appropriately**: Set `max_size` based on available storage and expected data access patterns +3. **Use with remote stores**: The cache provides the most benefit when wrapping slow remote stores +4. **Monitor cache statistics**: Use `cache_info()` to tune cache size and access patterns +5. **Consider data locality**: Group related data accesses together to improve cache efficiency +6. **Set appropriate expiration**: Use `max_age_seconds` for time-sensitive data or "infinity" for static data + +### Working with Different Store Types + +The CacheStore can wrap any store that implements the `zarr.abc.store.Store` interface +and use any store type for the cache backend: + +#### Local Store with Memory Cache + +```python exec="true" session="experimental-memory-cache" source="above" +from zarr.storage import LocalStore, MemoryStore +from zarr.experimental.cache_store import CacheStore +from tempfile import mkdtemp + +local_store_path = mkdtemp(suffix='.zarr') +source_store = LocalStore(local_store_path) +cache_store = MemoryStore() +cached_store = CacheStore( + store=source_store, + cache_store=cache_store, + max_size=128*1024*1024 +) +``` + +#### Memory Store with Persistent Cache + +```python exec="true" session="experimental-local-cache" source="above" +from tempfile import mkdtemp +from zarr.storage import MemoryStore, LocalStore +from zarr.experimental.cache_store import CacheStore + +memory_store = MemoryStore() +local_store_path = mkdtemp(suffix='.zarr') +persistent_cache = LocalStore(local_store_path) +cached_store = CacheStore( + store=memory_store, + cache_store=persistent_cache, + max_size=256*1024*1024 +) +``` + +The dual-store architecture provides flexibility in choosing the best combination +of source and cache stores for your specific use case. + +### Examples from Real Usage + +Here's a complete example demonstrating cache effectiveness: + +```python exec="true" session="experimental-final" source="above" +import numpy as np +import time +from tempfile import mkdtemp +import zarr +import zarr.storage +from zarr.experimental.cache_store import CacheStore + +# Create test data with dual-store cache +local_store_path = mkdtemp(suffix='.zarr') +source_store = zarr.storage.LocalStore(local_store_path) +cache_store = zarr.storage.MemoryStore() +cached_store = CacheStore( + store=source_store, + cache_store=cache_store, + max_size=256*1024*1024 +) +zarr_array = zarr.zeros((100, 100), chunks=(10, 10), dtype='f8', store=cached_store, mode='w') +zarr_array[:] = np.random.random((100, 100)) + +# Demonstrate cache effectiveness with repeated access +start = time.time() +data = zarr_array[20:30, 20:30] # First access (cache miss) +first_access = time.time() - start +print(f"First access took {first_access}") + +start = time.time() +data = zarr_array[20:30, 20:30] # Second access (cache hit) +second_access = time.time() - start +print(f"Second access took {second_access}") + +# Check cache statistics +info = cached_store.cache_info() +assert info['cached_keys'] > 0 # Should have cached keys +assert info['current_size'] > 0 # Should have cached data +print(f"Cache contains {info['cached_keys']} keys with {info['current_size']} bytes") +``` + +This example shows how the CacheStore can significantly reduce access times for repeated +data reads, particularly important when working with remote data sources. The dual-store +architecture allows for flexible cache persistence and management. diff --git a/docs/user-guide/extending.md b/docs/user-guide/extending.md new file mode 100644 index 0000000000..f852f9105e --- /dev/null +++ b/docs/user-guide/extending.md @@ -0,0 +1,99 @@ +# Extending Zarr + +Zarr-Python 3 was designed to be extensible. This means that you can extend +the library by writing custom classes and plugins. Currently, Zarr can be extended +in the following ways: + +## Custom codecs + +!!! note + This section explains how custom codecs can be created for Zarr format 3 arrays. For Zarr + format 2, codecs should subclass the + [numcodecs.abc.Codec](https://numcodecs.readthedocs.io/en/stable/abc.html#numcodecs.abc.Codec) + base class and register through + [numcodecs.registry.register_codec](https://numcodecs.readthedocs.io/en/stable/registry.html#numcodecs.registry.register_codec). + +There are three types of codecs in Zarr: + +- array-to-array +- array-to-bytes +- bytes-to-bytes + +Array-to-array codecs are used to transform the array data before serializing +to bytes. Examples include delta encoding or scaling codecs. Array-to-bytes codecs are used +for serializing the array data to bytes. In Zarr, the main codec to use for numeric arrays +is the [`zarr.codecs.BytesCodec`][]. Bytes-to-bytes codecs transform the serialized bytestreams +of the array data. Examples include compression codecs, such as +[`zarr.codecs.GzipCodec`][], [`zarr.codecs.BloscCodec`][] or +[`zarr.codecs.ZstdCodec`][], and codecs that add a checksum to the bytestream, such as +[`zarr.codecs.Crc32cCodec`][]. + +Custom codecs for Zarr are implemented by subclassing the relevant base class, see +[`zarr.abc.codec.ArrayArrayCodec`][], [`zarr.abc.codec.ArrayBytesCodec`][] and +[`zarr.abc.codec.BytesBytesCodec`][]. Most custom codecs should implement the +`_encode_single` and `_decode_single` methods. These methods operate on single chunks +of the array data. Alternatively, custom codecs can implement the `encode` and `decode` +methods, which operate on batches of chunks, in case the codec is intended to implement +its own batch processing. + +Custom codecs should also implement the following methods: + +- `compute_encoded_size`, which returns the byte size of the encoded data given the byte + size of the original data. It should raise `NotImplementedError` for codecs with + variable-sized outputs, such as compression codecs. +- `validate` (optional), which can be used to check that the codec metadata is compatible with the + array metadata. It should raise errors if not. +- `resolve_metadata` (optional), which is important for codecs that change the shape, + dtype or fill value of a chunk. +- `evolve_from_array_spec` (optional), which can be useful for automatically filling in + codec configuration metadata from the array metadata. + +To use custom codecs in Zarr, they need to be registered using the +[entrypoint mechanism](https://packaging.python.org/en/latest/specifications/entry-points/). +Commonly, entrypoints are declared in the `pyproject.toml` of your package under the +`[project.entry-points."zarr.codecs"]` section. Zarr will automatically discover +all codecs registered via the entrypoint mechanism in installed packages. + +```toml +[project.entry-points."zarr.codecs"] +"custompackage.fancy_codec" = "custompackage:FancyCodec" +``` + +New codecs need to have their own unique identifier. To avoid naming collisions, it is +strongly recommended to prefix the codec identifier with a unique name. For example, +the codecs from `numcodecs` are prefixed with `numcodecs.`, e.g. `numcodecs.delta`. + +!!! note + Note that the extension mechanism for the Zarr format 3 is still under development. + Requirements for custom codecs including the choice of codec identifiers might + change in the future. + +It is also possible to register codecs as replacements for existing codecs. This might be +useful for providing specialized implementations, such as GPU-based codecs. In case of +multiple codecs, the [`zarr.config`][] mechanism can be used to select the preferred +implementation. + +## Custom stores + +Custom stores can be created by implementing the [`zarr.abc.store.Store`][] interface. +See [developing custom stores](storage.md#developing-custom-stores) for more information. + +## Custom array buffers + +Zarr-python provides control over where and how arrays are stored in memory through +[`zarr.abc.buffer.Buffer`][]. Currently both CPU (the default) and GPU implementations are +provided (see [Using GPUs with Zarr](gpu.md) for more information). You can implement your own buffer +classes by implementing the interface defined in [`zarr.abc.buffer.BufferPrototype`][]. +Like codecs, custom buffer implementations can be registered via entrypoints, using the +`zarr.buffer` and `zarr.ndbuffer` entrypoint groups. + +## Custom data types + +Zarr supports user-defined data types. See the +[data types documentation](data_types.md) for an explanation of how Zarr Python +models data types and how to write your own, and the +[custom data type example](examples/custom_dtype.md) for a complete worked example. + +## Other extensions + +In the future, Zarr will support writing custom chunk grids. diff --git a/docs/user-guide/glossary.md b/docs/user-guide/glossary.md new file mode 100644 index 0000000000..dde08388a1 --- /dev/null +++ b/docs/user-guide/glossary.md @@ -0,0 +1,146 @@ +# Glossary + +This page defines key terms used throughout the zarr-python documentation and API. + +## Array Structure + +### Array + +An N-dimensional typed array stored in a Zarr [store](#store). An array's +[metadata](#metadata) defines its shape, data type, chunk layout, and codecs. + +### Group + +A container for [arrays](#array) and other groups, enabling hierarchical +organization of data β€” similar to directories in a file system, or groups in +HDF5. Like arrays, each group has its own [metadata](#metadata) and +[attributes](#attributes). See the [groups documentation](groups.md). + +### Chunk + +The fundamental unit of data in a Zarr array. An array is divided into chunks +along each dimension according to the [chunk grid](#chunk-grid). Each chunk is +independently compressed and encoded through the array's [codec](#codec) pipeline. + +When [sharding](#shard) is used, "chunk" refers to the inner chunks within each +shard, because those are the compressible units. The chunks are the smallest units +that can be read independently. + +!!! warning "Convention specific to zarr-python" + The use of "chunk" to mean the inner sub-chunk within a shard is a convention + adopted by zarr-python's `Array` API. In the Zarr V3 specification and in other + Zarr implementations, "chunk" may refer to the top-level grid cells (which + zarr-python calls "shards" when the sharding codec is used). Be aware of this + distinction when working across libraries. + +**API**: [`Array.chunks`][zarr.Array.chunks] returns the chunk shape. When +sharding is used, this is the inner chunk shape. + +### Chunk Grid + +The partitioning of an array's elements into [chunks](#chunk). In Zarr V3, the +chunk grid is defined in the array [metadata](#metadata) and determines the +boundaries of each storage object. + +Zarr V3 supports two chunk grid types: + +- **Regular**: All chunks have the same shape (the last chunk along each + dimension may be smaller than the declared size). +- **Rectilinear** *(experimental)*: Each dimension can have different chunk + sizes, specified as a list of edge lengths per dimension. Enable with + `zarr.config.set({'array.rectilinear_chunks': True})`. + +When sharding is used, the chunk grid defines the [shard](#shard) boundaries, +not the inner chunk boundaries. The inner chunk shape is defined within the +[sharding codec](#shard). + +**API**: The `chunk_grid` field in array metadata contains the storage-level +grid. [`Array.chunks`][zarr.Array.chunks] returns the chunk shape for regular +grids. For all grid types, `Array.read_chunk_sizes` and `Array.write_chunk_sizes` +return the per-dimension chunk sizes in dask-style `tuple[tuple[int, ...], ...]` +format. Note that while the chunk grid is a public concept of the Zarr format, +the classes zarr-python uses to model chunk grids are currently private API. + +### Shard + +A storage object that contains one or more [chunks](#chunk). Sharding reduces the +number of objects in a [store](#store) by grouping chunks together, which +improves performance on file systems and object storage. + +Within each shard, chunks are compressed independently and can be read +individually. However, writing requires updating the full shard for consistency, +making shards the unit of writing and chunks the unit of reading. + +Sharding is implemented as a [codec](#codec) (the sharding indexed codec). +When sharding is used: + +- The [chunk grid](#chunk-grid) in metadata defines the shard boundaries +- The sharding codec's `chunk_shape` defines the inner chunk size +- Each shard contains `shard_shape / chunk_shape` chunks per dimension + +**API**: [`Array.shards`][zarr.Array.shards] returns the shard shape, or `None` +if sharding is not used. [`Array.chunks`][zarr.Array.chunks] returns the inner +chunk shape. + +## Storage + +### Store + +A key-value storage backend that holds Zarr data and metadata. Stores implement +the [`zarr.abc.store.Store`][] interface. Examples include local file systems, +cloud object storage (S3, GCS, Azure), zip files, and in-memory dictionaries. + +Each [chunk](#chunk) or [shard](#shard) is stored as a single value (object or +file) in the store, addressed by a key derived from its grid coordinates. + +### Metadata + +The JSON document that describes an [array](#array) or [group](#group). In Zarr +format 3 this is a single `zarr.json` document; Zarr format 2 stores the +equivalent information in separate `.zarray`, `.zgroup`, and `.zattrs` documents. +For arrays, metadata includes the shape, data type, [chunk grid](#chunk-grid), fill +value, and [codec](#codec) pipeline. Metadata is stored alongside the data in +the [store](#store). Zarr-Python does not yet expose its internal metadata +representation as part of its public API. + +### Attributes + +User-defined key-value pairs (any JSON-serializable values) attached to an +[array](#array) or [group](#group). Attributes are stored in the +[metadata](#metadata) document. See the +[attributes documentation](attributes.md). + +### Consolidated Metadata + +A copy of the [metadata](#metadata) of every array and group in a hierarchy, +stored in the metadata of the root group so that the entire hierarchy can be +inspected with a single read from the [store](#store). See the +[consolidated metadata documentation](consolidated_metadata.md). + +## Codecs + +### Codec + +A transformation applied to array data during reading and writing. Codecs are +chained into a pipeline and come in three types: + +- **Array-to-array**: Transforms like transpose that rearrange array elements +- **Array-to-bytes**: Serialization that converts an array to a byte sequence + (exactly one required) +- **Bytes-to-bytes**: Compression or checksums applied to the serialized bytes + +The [sharding indexed codec](#shard) is a special array-to-bytes codec that +groups multiple [chunks](#chunk) into a single storage object. + +## API Properties + +The following properties are available on [`zarr.Array`][]: + +| Property | Description | +|----------|-------------| +| `.chunks` | Chunk shape β€” the inner chunk shape when sharding is used. Raises for rectilinear grids | +| `.shards` | Shard shape, or `None` if no sharding | +| `.read_chunk_sizes` | Per-dimension chunk data sizes (`tuple[tuple[int, ...], ...]`). Works for all grid types | +| `.write_chunk_sizes` | Per-dimension storage chunk sizes (`tuple[tuple[int, ...], ...]`). Works for all grid types | +| `.nchunks` | Total number of independently compressible units across the array | +| `.cdata_shape` | Number of independently compressible units per dimension | diff --git a/docs/user-guide/gpu.md b/docs/user-guide/gpu.md new file mode 100644 index 0000000000..26d1c114b0 --- /dev/null +++ b/docs/user-guide/gpu.md @@ -0,0 +1,60 @@ +# Using GPUs with Zarr + +Zarr can use GPUs to accelerate your workload by running `zarr.config.enable_gpu()`. + +!!! note + `zarr-python` currently supports reading the ndarray data into device (GPU) + memory as the final stage of the codec pipeline. Data will still be read into + or copied to host (CPU) memory for encoding and decoding. + + In the future, codecs will be available for compressing and decompressing data on + the GPU, avoiding the need to move data between the host and device for + compression and decompression. + +## Installation + +Zarr's GPU support requires [CuPy](https://cupy.dev), which in turn requires a +CUDA-compatible NVIDIA GPU. CuPy can be installed alongside Zarr with the `gpu` +extra (see [Installation](installation.md) for the other optional dependency groups): + +```console +pip install "zarr[gpu]" +``` + +This installs the `cupy-cuda12x` package. If you need a CuPy build for a different +CUDA version, see the [CuPy installation guide](https://docs.cupy.dev/en/stable/install.html) +and install the appropriate package yourself. + +## Reading data into device memory + +Calling `zarr.config.enable_gpu()` configures Zarr to use GPU memory for the data +buffers used internally by Zarr: + +```python test="true" session="gpu-demo" markers="gpu" source="above" +import zarr +import cupy as cp + +zarr.config.enable_gpu() +z = zarr.create_array( + store="memory://gpu-demo", shape=(100, 100), chunks=(10, 10), dtype="float32", +) +assert isinstance(z[:10, :10], cp.ndarray) +``` + +Note that the arrays returned by reads are of type `cupy.ndarray` rather than +NumPy arrays. + +`zarr.config.enable_gpu()` returns a [donfig](https://donfig.readthedocs.io/en/latest/) +`ConfigSet`, which can be used as a context manager to enable GPU support for a +limited scope: + +```python test="true" session="gpu-demo" markers="gpu" source="above" +with zarr.config.enable_gpu(): + data = z[:10, :10] +assert isinstance(data, cp.ndarray) +``` + +Under the hood, `enable_gpu()` selects the GPU-backed buffer classes +`zarr.buffer.gpu.Buffer` and `zarr.buffer.gpu.NDBuffer` via the `buffer` and +`ndbuffer` configuration keys. See [Custom array buffers](extending.md#custom-array-buffers) +for more on Zarr's buffer classes, including how to implement your own. diff --git a/docs/user-guide/groups.md b/docs/user-guide/groups.md new file mode 100644 index 0000000000..7429a03847 --- /dev/null +++ b/docs/user-guide/groups.md @@ -0,0 +1,199 @@ +# Working with groups + +Zarr supports hierarchical organization of arrays via groups. As with arrays, +groups can be stored in memory, on disk, or via other storage systems that +support a similar interface. + +To create a group, use the [`zarr.create_group`][] function: + +```python exec="true" session="groups" source="above" result="ansi" +import zarr +root = zarr.create_group(store="memory://groups-demo") +print(root) +``` + +Zarr-Python provides three related functions for making groups: +[`zarr.create_group`][] creates a new group; [`zarr.open_group`][] creates or +re-opens a group depending on its `mode` argument (see below); and +[`zarr.group`][], which is kept for compatibility with Zarr-Python 2, is +equivalent to calling [`zarr.open_group`][] with `mode='a'` (or `mode='w'` +when `overwrite=True`). + +Groups have a similar API to the Group class from [h5py](https://www.h5py.org/). For example, groups can contain other groups: + +```python exec="true" session="groups" source="above" +foo = root.create_group('foo') +bar = foo.create_group('bar') +``` + +Groups can also contain arrays, e.g.: + +```python exec="true" session="groups" source="above" result="ansi" +z1 = bar.create_array(name='baz', shape=(10000, 10000), chunks=(1000, 1000), dtype='int32') +print(z1) +``` + +Members of a group can be accessed with square-bracket item access, like a +Python `dict`, e.g.: + +```python exec="true" session="groups" source="above" result="ansi" +print(root['foo']) +``` + +The '/' character can be used to access multiple levels of the hierarchy in one +call, e.g.: + +```python exec="true" session="groups" source="above" result="ansi" +print(root['foo/bar']) +``` + +```python exec="true" session="groups" source="above" result="ansi" +print(root['foo/bar/baz']) +``` + +Accessing a member with `[]` returns either an [`zarr.Array`][] or a [`zarr.Group`][], depending on +what is stored at the given path. When you expect a node of a particular kind, use +[`zarr.Group.get_array`][] or [`zarr.Group.get_group`][] instead. These methods accept the same +paths as `[]`, but they have precise return types and raise an error if no node exists at the +given path, or if the node is not of the expected kind: + +```python exec="true" session="groups" source="above" result="ansi" +print(root.get_group('foo')) +``` + +```python exec="true" session="groups" source="above" result="ansi" +print(root.get_array('foo/bar/baz')) +``` + +```python exec="true" session="groups" source="above" result="ansi" +from zarr.errors import ContainsGroupError + +try: + root.get_array('foo') +except ContainsGroupError as e: + print(e) +``` + +The [`zarr.Group.tree`][] method can be used to print a tree +representation of the hierarchy, e.g.: + +```python exec="true" session="groups" source="above" result="ansi" +print(root.tree()) +``` + +The [`zarr.open_group`][] function provides a convenient way to create or +re-open a group stored in a directory on the file-system, with sub-groups stored in +sub-directories, e.g.: + +```python exec="true" session="groups" source="above" result="ansi" +root = zarr.open_group('data/group.zarr', mode='w') +print(root) +``` + +```python exec="true" session="groups" source="above" result="ansi" +z = root.create_array(name='foo/bar/baz', shape=(10000, 10000), chunks=(1000, 1000), dtype='int32') +print(z) +``` + +For more information on groups see the [`zarr.Group` API docs](../api/zarr/group.md). + +## Exploring group contents + +Groups also support a dict-like interface for enumerating their contents. The +[`zarr.Group.keys`][] method iterates over member names, and the `in` operator +tests for membership: + +```python exec="true" session="groups" source="above" result="ansi" +print(list(root.keys())) +print('foo' in root) +``` + +The [`zarr.Group.members`][] method returns `(name, member)` pairs for the +arrays and groups contained in a group: + +```python exec="true" session="groups" source="above" result="ansi" +for name, member in root.members(): + print(name, member) +``` + +By default only immediate members are returned. Pass `max_depth=None` to +recursively traverse the whole hierarchy below a group: + +```python exec="true" session="groups" source="above" result="ansi" +for name, member in root.members(max_depth=None): + print(name, member) +``` + +Members can be deleted with the `del` operator, which removes the member's +metadata and data from the store: + +```python exec="true" session="groups" source="above" result="ansi" +del root['foo/bar/baz'] +for name, member in root.members(max_depth=None): + print(name, member) +``` + +## Batch group creation + +You can also create multiple groups concurrently with a single function call. [`zarr.create_hierarchy`][] takes +a [`Store`](../api/zarr/storage.md) instance and a dict of `key : metadata` pairs, parses that dict, and +writes metadata documents to storage: + +```python exec="true" session="groups" source="above" result="ansi" +from zarr import create_hierarchy +from zarr.core.group import GroupMetadata +from zarr.storage import LocalStore + +from pprint import pprint +import io + +node_spec = {'a/b/c': GroupMetadata()} +nodes_created = dict(create_hierarchy(store=LocalStore(root='data'), nodes=node_spec)) +# Report nodes (pprint is used for cleaner rendering in the docs) +output = io.StringIO() +pprint(nodes_created, stream=output, width=60) +print(output.getvalue()) +``` + +Note that we only specified a single group named `a/b/c`, but 4 groups were created. These additional groups +were created to ensure that the desired node `a/b/c` is connected to the root group `''` by a sequence +of intermediate groups. [`zarr.create_hierarchy`][] normalizes the `nodes` keyword argument to +ensure that the resulting hierarchy is complete, i.e. all groups or arrays are connected to the root +of the hierarchy via intermediate groups. + +Because [`zarr.create_hierarchy`][] concurrently creates metadata documents, it's more efficient +than repeated calls to [`create_group`][zarr.create_group] or [`create_array`][zarr.create_array], provided you can statically define +the metadata for the groups and arrays you want to create. + +## Array and group diagnostics + +Diagnostic information about arrays and groups is available via the `info` +property. E.g.: + +```python exec="true" session="groups" source="above" result="ansi" +root = zarr.group(store="memory://diagnostics-demo") +foo = root.create_group('foo') +bar = foo.create_array(name='bar', shape=1000000, chunks=100000, dtype='int64') +bar[:] = 42 +baz = foo.create_array(name='baz', shape=(1000, 1000), chunks=(100, 100), dtype='float32') +baz[:] = 4.2 +print(root.info) +``` + +```python exec="true" session="groups" source="above" result="ansi" +print(foo.info) +``` + +```python exec="true" session="groups" source="above" result="ansi" +print(bar.info_complete()) +``` + +```python exec="true" session="groups" source="above" result="ansi" +print(baz.info) +``` + +Groups also have the [`zarr.Group.tree`][] method, e.g.: + +```python exec="true" session="groups" source="above" result="ansi" +print(root.tree()) +``` diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md new file mode 100644 index 0000000000..6b9a547776 --- /dev/null +++ b/docs/user-guide/index.md @@ -0,0 +1,54 @@ +# User Guide + +Welcome to the user guide, where you can learn more about using Zarr-Python! + +## Getting Started + +New to Zarr-Python? Start here: + +- **[Installation](installation.md)** - Install Zarr-Python +- **[Quick start](../quick-start.md)** - Quick overview of core functionality + +## Core Concepts + +Learn the essential building blocks: + +- **[Arrays](arrays.md)** - Learn the fundamentals of working with arrays +- **[Groups](groups.md)** - Organize your data with groups +- **[Attributes](attributes.md)** - Attach metadata to your arrays and groups +- **[Storage](storage.md)** - Learn how data is stored and accessed + +## Configuration & Setup + +Customize your experience: + +- **[Runtime Configuration](config.md)** - Configure Zarr-Python for your needs +- **[Command-Line Interface](cli.md)** - Migrate and manage Zarr metadata from the terminal +- **[V3 Migration](v3_migration.md)** - Upgrading from version 2 to version 3 + +## Advanced Topics + +Take your skills to the next level: + +- **[Data Types](data_types.md)** - Learn about supported and extensible data types +- **[Performance](performance.md)** - Optimize for speed and efficiency +- **[GPU](gpu.md)** - Leverage GPU acceleration +- **[Extending](extending.md)** - Extend functionality with custom code +- **[Consolidated Metadata](consolidated_metadata.md)** - Advanced metadata management +- **[Experimental Features](experimental.md)** - Preview features that may change at any time + +## Examples + +Worked, end-to-end examples: + +- **[Custom Data Type](examples/custom_dtype.md)** - Extend Zarr-Python with a user-defined data type +- **[Rectilinear Chunk Grids](examples/rectilinear_chunks.md)** - Use variable-sized chunks along each dimension + +## Reference + +- **[Glossary](glossary.md)** - Definitions of key terms (chunks, shards, codecs, etc.) + +## Need Help? + +- Browse the [API Reference](../api/zarr/index.md) for detailed function documentation +- Report issues on [GitHub](https://github.com/zarr-developers/zarr-python/issues?q=sort%3Aupdated-desc+is%3Aissue+is%3Aopen) diff --git a/docs/user-guide/installation.md b/docs/user-guide/installation.md new file mode 100644 index 0000000000..a7487e83c8 --- /dev/null +++ b/docs/user-guide/installation.md @@ -0,0 +1,62 @@ +# Installation + +## Required dependencies + +Required dependencies include: + +- [Python](https://docs.python.org/3/) (3.12 or later) +- [packaging](https://packaging.pypa.io/en/stable/) (22.0 or later) +- [numpy](https://numpy.org) (2.0 or later) +- [numcodecs](https://numcodecs.readthedocs.io/en/stable/) (0.14 or later) +- [google-crc32c](https://github.com/googleapis/python-crc32c) (1.5 or later) +- [typing_extensions](https://typing-extensions.readthedocs.io/en/latest/) (4.14 or later) +- [donfig](https://donfig.readthedocs.io/en/latest/) (0.8 or later) + +## pip + +Zarr is available on [PyPI](https://pypi.org/project/zarr/). Install it using `pip`: + +```console +pip install zarr +``` + +There are a number of optional dependency groups you can install for extra functionality. +These can be installed using `pip install "zarr[]"`, e.g. `pip install "zarr[gpu]"` + +- `remote`: support for reading/writing to remote data stores (fsspec, obstore) +- `gpu`: support for GPUs (cupy) +- `cli`: support for the `zarr` [command-line interface](cli.md) (typer) +- `optional`: support for path-like access to local and remote stores (universal-pathlib) +- `cast-value-rs`: support for the `cast_value` codec (cast-value-rs) + +## conda + +Zarr is also published to [conda-forge](https://conda-forge.org). Install it using `conda`: + +```console +conda install -c conda-forge zarr +``` + +Conda does not support optional dependencies, so you will have to manually install any packages +needed to enable extra functionality. + +## Nightly wheels + +Development wheels are built nightly and published to the [scientific-python-nightly-wheels](https://anaconda.org/scientific-python-nightly-wheels) index. To install the latest nightly build: + +```console +pip install --pre --extra-index-url https://pypi.anaconda.org/scientific-python-nightly-wheels/simple zarr +``` + +Note that nightly wheels may be unstable and are intended for testing purposes. + +## Dependency support + +Zarr has endorsed [Scientific-Python SPEC 0](https://scientific-python.org/specs/spec-0000/) and now follows the version support window as outlined below: + +- Python: 36 months after initial release +- Core package dependencies (e.g. NumPy): 24 months after initial release + +## Development + +To install the latest development version of Zarr, see the [contributing guide](../contributing.md). diff --git a/docs/user-guide/performance.md b/docs/user-guide/performance.md new file mode 100644 index 0000000000..52c1cf0d71 --- /dev/null +++ b/docs/user-guide/performance.md @@ -0,0 +1,333 @@ +# Optimizing performance + +## Chunk optimizations + +### Chunk size and shape + +In general, chunks of at least 1 megabyte (1M) uncompressed size seem to provide +better performance, at least when using the Blosc compression library. + +The optimal chunk shape will depend on how you want to access the data. E.g., +for a 2-dimensional array, if you only ever take slices along the first +dimension, then chunk across the second dimension. If you know you want to chunk +across an entire dimension you can use the full size of that dimension within the +`chunks` argument, e.g.: + +```python exec="true" session="performance" source="above" result="ansi" +import zarr +z1 = zarr.create_array(store={}, shape=(10000, 10000), chunks=(100, 10000), dtype='int32') +print(z1.chunks) +``` + +Alternatively, if you only ever take slices along the second dimension, then +chunk across the first dimension, e.g.: + +```python exec="true" session="performance" source="above" result="ansi" +z2 = zarr.create_array(store={}, shape=(10000, 10000), chunks=(10000, 100), dtype='int32') +print(z2.chunks) +``` + +If you require reasonable performance for both access patterns then you need to +find a compromise, e.g.: + +```python exec="true" session="performance" source="above" result="ansi" +z3 = zarr.create_array(store={}, shape=(10000, 10000), chunks=(1000, 1000), dtype='int32') +print(z3.chunks) +``` + +If you are feeling lazy, you can let Zarr guess a chunk shape for your data by +providing `chunks='auto'`, although please note that the algorithm for guessing +a chunk shape is based on simple heuristics and may be far from optimal. E.g.: + +```python exec="true" session="performance" source="above" result="ansi" +z4 = zarr.create_array(store={}, shape=(10000, 10000), chunks='auto', dtype='int32') +print(z4.chunks) +``` + +If you know you are always going to be loading the entire array into memory, you +can turn off chunks by providing `chunks` equal to `shape`, in which case there +will be one single chunk for the array: + +```python exec="true" session="performance" source="above" result="ansi" +z5 = zarr.create_array(store={}, shape=(10000, 10000), chunks=(10000, 10000), dtype='int32') +print(z5.chunks) +``` + +### Sharding + +If you have large arrays but need small chunks to efficiently access the data, you can +use sharding. Sharding provides a mechanism to store multiple chunks in a single +storage object or file. This can be useful because traditional file systems and object +storage systems may have performance issues storing and accessing many files. +Additionally, small files can be inefficient to store if they are smaller than the +block size of the file system. + +Picking a good combination of chunk shape and shard shape is important for performance. +The chunk shape determines what unit of your data can be read independently, while the +shard shape determines what unit of your data can be written efficiently. + +For an example, consider you have a 100 GB array and need to read small chunks of 1 MB. +Without sharding, each chunk would be one file resulting in 100,000 files. That can +already cause performance issues on some file systems. +With sharding, you could use a shard size of 1 GB. This would result in 1000 chunks per +file and 100 files in total, which seems manageable for most storage systems. +You would still be able to read each 1 MB chunk independently, but you would need to +write your data in 1 GB increments. + +To use sharding, you need to specify the `shards` parameter when creating the array. + +```python exec="true" session="performance" source="above" result="ansi" +z6 = zarr.create_array(store={}, shape=(10000, 10000, 1000), shards=(1000, 1000, 1000), chunks=(100, 100, 100), dtype='uint8') +print(z6.info) +``` + +`shards` can be `"auto"` as well, in which case Zarr chooses a shard shape for you. +The `array.target_shard_size_bytes` configuration setting controls this choice: the +cumulative uncompressed size of the chunks within each shard will be as close as +possible to, without exceeding, that target. If the setting is `None` (the default), +Zarr falls back to a built-in heuristic for choosing the shard shape. + +### Chunk memory layout + +The memory layout of the in-memory arrays that Zarr produces and consumes can be +changed via the `order` config option, to use either C or Fortran layout. This can +matter for performance when the data is passed to other libraries that expect a +particular memory layout. E.g.: + +```python exec="true" session="performance" source="above" result="ansi" +import numpy as np + +c = zarr.create_array(store={}, shape=(10000, 10000), chunks=(1000, 1000), dtype='int32', config={'order': 'C'}) +print(c[:100, :100].flags.c_contiguous) +``` + +```python exec="true" session="performance" source="above" result="ansi" +with zarr.config.set({'array.order': 'F'}): + f = zarr.create_array(store={}, shape=(10000, 10000), chunks=(1000, 1000), dtype='int32') +print(f[:100, :100].flags.f_contiguous) +``` + +Note that for Zarr format 3 arrays the `order` option only affects the in-memory +layout: the bytes written to storage are identical for both settings. The layout of +the serialized data is instead determined by the array's codecs (e.g. the transpose +codec), which can change how well the data compresses depending on the correlation +structure within the data and which compression filters (e.g., byte-shuffle) have +been applied. + +### Subchunk memory layout + +The order of chunks **within each shard** can be changed via the `subchunk_write_order` parameter of the `ShardingCodec`. That parameter is a string which must be one of `["morton", "unordered", "lexicographic", "colexicographic"]`. + +By default [`morton`](https://en.wikipedia.org/wiki/Z-order_curve) order provides good spatial locality. [`lexicographic` (i.e., row-major)](https://en.wikipedia.org/wiki/Row-_and_column-major_order), for example, may be better suited to "batched" workflows where some form of sequential reading through a fixed number of outer dimensions is desired, and `colexicographic` is its reverse. `unordered` makes no guarantee about the order in which subchunks are laid out within a shard. + +### Empty chunks + +It is possible to configure how Zarr handles the storage of chunks that are "empty" +(i.e., every element in the chunk is equal to the array's fill value). When creating +an array with `write_empty_chunks=False`, Zarr will check whether a chunk is empty before compression and storage. If a chunk is empty, +then Zarr does not store it, and instead deletes the chunk from storage +if the chunk had been previously stored. + +This optimization prevents storing redundant objects and can speed up reads, but the cost is +added computation during array writes, since the contents of +each chunk must be compared to the fill value, and these advantages are contingent on the content of the array. +If you know that your data will form chunks that are almost always non-empty, then there is no advantage to the optimization described above. +In this case, creating an array with `write_empty_chunks=True` will instruct Zarr to write every chunk without checking for emptiness. + +The default value of `write_empty_chunks` is `False`: + +```python exec="true" session="performance" source="above" result="ansi" +arr = zarr.create_array(store={}, shape=(1,), dtype='uint8') +assert arr.config.write_empty_chunks == False +``` + +The following example illustrates the effect of the `write_empty_chunks` flag on +the time required to write an array with different values: + +```python exec="true" session="performance" source="above" result="ansi" +import zarr +import numpy as np +import time + +def timed_write(write_empty_chunks): + """ + Measure the time required and number of objects created when writing + to a Zarr array with random ints or fill value. + """ + chunks = (8192,) + shape = (chunks[0] * 1024,) + data = np.random.randint(0, 255, shape) + dtype = 'uint8' + arr = zarr.create_array( + f'data/example-{write_empty_chunks}.zarr', + shape=shape, + chunks=chunks, + dtype=dtype, + fill_value=0, + config={'write_empty_chunks': write_empty_chunks} + ) + # initialize all chunks + arr[:] = 100 + result = [] + for value in (data, arr.fill_value): + start = time.time() + arr[:] = value + elapsed = time.time() - start + result.append((elapsed, arr.nchunks_initialized)) + return result + +# log results +for write_empty_chunks in (True, False): + full, empty = timed_write(write_empty_chunks) + print(f'\nwrite_empty_chunks={write_empty_chunks}:\n\tRandom Data: {full[0]:.4f}s, {full[1]} objects stored\n\t Empty Data: {empty[0]:.4f}s, {empty[1]} objects stored\n') +``` + +In this example, writing random data is slightly slower with `write_empty_chunks=False`, +because every chunk must be checked for emptiness before it is stored. Writing empty +data with `write_empty_chunks=False` is substantially faster, however, and stores no +objects at all. + +### Changing chunk shapes (rechunking) + +Zarr-Python does not yet provide a built-in way to change the chunk shape of an +existing array in place. Arrays can, however, be resized and appended to along any +dimension β€” see [Resizing and appending](arrays.md#resizing-and-appending) β€” and data +can be copied to a new array created with the desired chunk shape. + +## Parallel computing and synchronization + +Zarr is designed to support parallel computing and enables concurrent reads and writes to arrays. +This section covers how to optimize Zarr's concurrency settings for different parallel computing +scenarios. + +### Concurrent I/O operations + +Zarr uses asynchronous I/O internally to enable concurrent reads and writes across multiple chunks. +The level of concurrency is controlled by the `async.concurrency` configuration setting, which +determines the maximum number of concurrent I/O operations. + +The default value is 10, which is a conservative value. You may get improved performance by tuning +the concurrency limit. You can adjust this value based on your specific needs: + +```python exec="true" session="perf-concurrency" source="above" +import zarr + +# Set concurrency for the current session +zarr.config.set({'async.concurrency': 128}) + +# Or use environment variable +# export ZARR_ASYNC_CONCURRENCY=128 +``` + +Higher concurrency values can improve throughput when: + +- Working with remote storage (e.g., S3, GCS) where network latency is high +- Reading/writing many small chunks in parallel +- The storage backend can handle many concurrent requests + +Lower concurrency values may be beneficial when: + +- Working with local storage with limited I/O bandwidth +- Memory is constrained (each concurrent operation requires buffer space) +- Using Zarr within a parallel computing framework (see below) + +### Thread pool size (`threading.max_workers`) + +When synchronous Zarr code calls async operations internally, Zarr uses a +`ThreadPoolExecutor` to run those coroutines. The `threading.max_workers` +configuration option controls the maximum number of worker threads in that pool. +By default it is `None`, which lets Python choose the pool size (typically +`min(32, os.cpu_count() + 4)`). + +You can set it explicitly when you want more predictable resource usage: + +```python exec="true" session="perf-workers" source="above" +import zarr + +zarr.config.set({'threading.max_workers': 8}) +``` + +Reducing this value can help avoid overloading the event loop when Zarr is used +inside a parallel computing framework such as Dask that already manages its own +thread pool (see the Dask section below). Increasing it may improve throughput +in CPU-bound workloads where many synchronous-to-async dispatches happen +concurrently. + +### Using Zarr with Dask + +[Dask](https://www.dask.org/) is a popular parallel computing library that works well with Zarr for processing large arrays. When using Zarr with Dask, it's important to consider the interaction between Dask's thread pool and Zarr's concurrency settings. + +**Important**: When using many Dask threads, you may need to reduce both Zarr's `async.concurrency` and `threading.max_workers` settings to avoid creating too many concurrent operations. The total number of concurrent I/O operations can be roughly estimated as: + +```text +total_concurrency β‰ˆ dask_threads Γ— zarr_async_concurrency +``` + +For example, if you're running Dask with 10 threads and Zarr's default concurrency of 10, you could potentially have up to 100 concurrent operations, which may overwhelm your storage system or cause memory issues. + +**Recommendation**: When using Dask with many threads, configure Zarr's concurrency settings: + +```python exec="false" reason="requires dask, which is not in the docs test environment" +import zarr +import dask.array as da + +# If using Dask with many threads (e.g., 8-16), reduce Zarr's concurrency settings +zarr.config.set({ + 'async.concurrency': 4, # Limit concurrent async operations + 'threading.max_workers': 4, # Limit Zarr's internal thread pool +}) + +# Open Zarr array +z = zarr.open_array('data/large_array.zarr', mode='r') + +# Create Dask array from Zarr array +arr = da.from_array(z, chunks=z.chunks) + +# Process with Dask +result = arr.mean(axis=0).compute() +``` + +**Configuration guidelines for Dask workloads**: + +- `async.concurrency`: Controls the maximum number of concurrent async I/O operations. Start with a lower value (e.g., 4-8) when using many Dask threads. +- `threading.max_workers`: Controls Zarr's internal thread pool size for blocking operations (defaults to `None`, letting Python choose the pool size). Reduce this to avoid thread contention with Dask's scheduler. + +You may need to experiment with different values to find the optimal balance for your workload. Monitor your system's resource usage and adjust these settings based on whether your storage system or CPU is the bottleneck. + +### Thread safety and process safety + +Zarr arrays are designed to be thread-safe for concurrent reads and writes from multiple threads within the same process. However, proper synchronization is required when writing to overlapping regions from multiple threads. + +For multi-process parallelism, Zarr provides safe concurrent writes as long as: + +- Different processes write to different chunks +- The storage backend supports atomic writes (most do) + +When writing to the same chunks from multiple processes, you should use external synchronization mechanisms or ensure that writes are coordinated to avoid race conditions. + +## Pickle support + +Zarr arrays and groups can be pickled, as long as the underlying store object can be +pickled. All of the storage classes provided in the `zarr.storage` module can be pickled. + +If an array or group is backed by a persistent store such as a `zarr.storage.LocalStore`, +`zarr.storage.ZipStore` or `zarr.storage.FsspecStore` then the store data +**are not** pickled. The only thing that is pickled is the necessary parameters to allow the store +to re-open any underlying files or databases upon being unpickled. + +Note that pickling a `zarr.storage.MemoryStore` copies the data it holds into the +pickle stream: unpickling produces an independent in-memory copy, so a `MemoryStore` +cannot be used to share data between processes. + +E.g., pickle/unpickle a local store array: + +```python exec="true" session="performance" source="above" result="ansi" +import pickle +data = np.arange(100000) +z1 = zarr.create_array(store='data/perf-example-2.zarr', shape=data.shape, chunks=data.shape, dtype=data.dtype) +z1[:] = data +s = pickle.dumps(z1) +z2 = pickle.loads(s) +assert z1 == z2 +print(np.all(z1[:] == z2[:])) +``` diff --git a/docs/user-guide/storage.md b/docs/user-guide/storage.md new file mode 100644 index 0000000000..a34e2e2874 --- /dev/null +++ b/docs/user-guide/storage.md @@ -0,0 +1,230 @@ +# Storage guide + +Zarr-Python supports multiple storage backends, including: local file systems, +Zip files, remote stores via [fsspec](https://filesystem-spec.readthedocs.io/en/latest/) (S3, HTTP, etc.), and in-memory stores. In +Zarr-Python 3, stores must implement the abstract store API from +[`zarr.abc.store.Store`][]. + +!!! note + Unlike Zarr-Python 2 where the store interface was built around a generic `MutableMapping` + API, Zarr-Python 3 utilizes a custom store API that utilizes Python's AsyncIO library. + +## Implicit Store Creation + +In most cases, it is not required to create a `Store` object explicitly. Passing a string +(or other [StoreLike value](#user-guide-store-like)) to Zarr's top level API will result in the store +being created automatically: + +```python exec="true" session="storage" source="above" result="ansi" +import zarr + +# Implicitly creates a writable LocalStore +group = zarr.create_group(store='data/foo/bar') +print(group) +``` + +```python exec="true" session="storage" source="above" result="ansi" +# Implicitly creates a read-only FsspecStore +# Note: requires s3fs to be installed +group = zarr.open_group( + store='s3://noaa-nwm-retro-v2-zarr-pds', + mode='r', + storage_options={'anon': True} +) +print(group) +``` + +```python exec="true" session="storage" source="above" result="ansi" +# Implicitly creates a MemoryStore +data = {} +group = zarr.create_group(store=data) +print(group) +``` + +### StoreLike {#user-guide-store-like} + +`StoreLike` values can be: + +- a `Path` or string indicating a location on the local file system. + This will create a [local store](#local-store): + + ```python exec="true" session="storage" source="above" result="ansi" + group = zarr.open_group(store='data/foo/bar') + print(group) + ``` + + ```python exec="true" session="storage" source="above" result="ansi" + from pathlib import Path + group = zarr.open_group(store=Path('data/foo/bar')) + print(group) + ``` + +- an FSSpec URI string, indicating a [remote store](#remote-store) location: + + ```python exec="true" session="storage" source="above" result="ansi" + # Note: requires s3fs to be installed + group = zarr.open_group( + store='s3://noaa-nwm-retro-v2-zarr-pds', + mode='r', + storage_options={'anon': True} + ) + print(group) + ``` + +- an empty dictionary or None, which will create a new [memory store](#memory-store): + + ```python exec="true" session="storage" source="above" result="ansi" + group = zarr.create_group(store={}) + print(group) + ``` + + ```python exec="true" session="storage" source="above" result="ansi" + group = zarr.create_group(store=None) + print(group) + ``` + +- a dictionary of string to [`Buffer`][zarr.abc.buffer.Buffer] mappings. This will + create a [memory store](#memory-store), using this dictionary as the + [`store_dict` argument][zarr.storage.MemoryStore]. + +- an FSSpec [FSMap object](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.FSMap), + which will create an [FsspecStore](#remote-store). + +- a [universal-pathlib](https://github.com/fsspec/universal_pathlib) `UPath`, which will create an + [FsspecStore](#remote-store), or a [local store](#local-store) if the `UPath` is local. Put your + storage options on the `UPath` itself; passing a separate `storage_options` argument alongside + one raises `TypeError`. + + ```python exec="false" reason="requires universal-pathlib, which is not in the docs environment" + from upath import UPath + group = zarr.open_group(UPath('s3://noaa-nwm-retro-v2-zarr-pds', anon=True), mode='r') + ``` + +- a [`Store`][zarr.abc.store.Store] or [`StorePath`][zarr.storage.StorePath] - + see explicit store creation below. + +## Explicit Store Creation + +In some cases, it may be helpful to create a store instance directly. Zarr-Python offers +built-in stores: [`zarr.storage.LocalStore`][], [`zarr.storage.FsspecStore`][], +[`zarr.storage.ZipStore`][], [`zarr.storage.MemoryStore`][], and [`zarr.storage.ObjectStore`][]. + +### Local Store + +The [`zarr.storage.LocalStore`][] stores data in a nested set of directories on a local +filesystem: + +```python exec="true" session="storage" source="above" result="ansi" +store = zarr.storage.LocalStore('data/foo/bar', read_only=True) +group = zarr.open_group(store=store, mode='r') +print(group) +``` + +### Zip Store + +The [`zarr.storage.ZipStore`][] stores the contents of a Zarr hierarchy in a single +Zip file. The [Zip Store specification](https://github.com/zarr-developers/zarr-specs/pull/311) is currently in draft form: + +```python exec="true" session="storage" source="above" result="ansi" +store = zarr.storage.ZipStore('data.zip', mode='w') +array = zarr.create_array(store=store, shape=(2,), dtype='float64') +print(array) +``` + +In place of a path, `ZipStore` also accepts an open binary file object (for +example a file opened with `fsspec`, or an `obstore` reader), enabling zip +archives on remote storage. The file must stay open for as long as the store +is in use: + +```python exec="true" session="storage" source="above" result="ansi" +store.close() +f = open('data.zip', mode='rb') # must stay open while the store is used +array = zarr.open_array(store=zarr.storage.ZipStore(f), mode='r') +print(array[:]) +f.close() +``` + +### Remote Store + +The [`zarr.storage.FsspecStore`][] stores the contents of a Zarr hierarchy following the same +logical layout as the [`LocalStore`][zarr.storage.LocalStore], except the store is assumed to be on a remote storage system +such as cloud object storage (e.g. AWS S3, Google Cloud Storage, Azure Blob Store). The +[`zarr.storage.FsspecStore`][] is backed by [fsspec](https://filesystem-spec.readthedocs.io/en/latest/) and can support any backend +that implements the [AbstractFileSystem](https://filesystem-spec.readthedocs.io/en/stable/api.html#fsspec.spec.AbstractFileSystem) +API. `storage_options` can be used to configure the fsspec backend: + +```python exec="true" session="storage" source="above" result="ansi" +# Note: requires s3fs to be installed +store = zarr.storage.FsspecStore.from_url( + 's3://noaa-nwm-retro-v2-zarr-pds', + read_only=True, + storage_options={'anon': True} +) +group = zarr.open_group(store=store, mode='r') +print(group) +``` + +The type of filesystem (e.g. S3, https, etc..) is inferred from the scheme of the url (e.g. s3 for "**s3**://noaa-nwm-retro-v2-zarr-pds"). +In case a specific filesystem is needed, one can explicitly create it. For example to create an S3 filesystem +(note that the filesystem must be created with `asynchronous=True`): + +```python exec="true" session="storage" source="above" result="ansi" +# Note: requires s3fs to be installed +import fsspec +fs = fsspec.filesystem('s3', anon=True, asynchronous=True) +store = zarr.storage.FsspecStore(fs, path='noaa-nwm-retro-v2-zarr-pds', read_only=True) +print(store) +``` + +When using an S3-compatible service other than AWS, pass the service endpoint to the +filesystem via `client_kwargs={'endpoint_url': 'https://...'}`. + +### Memory Store + +The [`zarr.storage.MemoryStore`][] stores Zarr data (metadata and chunks) in an +in-memory dictionary: + +```python exec="true" session="storage" source="above" result="ansi" +data = {} +store = zarr.storage.MemoryStore(data) +array = zarr.create_array(store=store, shape=(2,), dtype='float64') +print(array) +``` + +### Object Store + +[`zarr.storage.ObjectStore`][] stores the contents of the Zarr hierarchy using any ObjectStore +[storage implementation](https://developmentseed.org/obstore/latest/api/store/), including AWS S3 ([`obstore.store.S3Store`][]), Google Cloud Storage ([`obstore.store.GCSStore`][]), and Azure Blob Storage ([`obstore.store.AzureStore`][]). This store is backed by [obstore](https://developmentseed.org/obstore/latest/), which +builds on the production quality Rust library [object_store](https://docs.rs/object_store/latest/object_store/). + +```python exec="true" session="storage" source="above" result="ansi" +from zarr.storage import ObjectStore +from obstore.store import MemoryStore + +store = ObjectStore(MemoryStore()) +array = zarr.create_array(store=store, shape=(2,), dtype='float64') +print(array) +``` + +Here's an example of using ObjectStore for accessing remote data: + +```python exec="true" session="storage" source="above" result="ansi" +from zarr.storage import ObjectStore +from obstore.store import S3Store + +s3_store = S3Store('noaa-nwm-retro-v2-zarr-pds', skip_signature=True, region="us-west-2") +store = zarr.storage.ObjectStore(store=s3_store, read_only=True) +group = zarr.open_group(store=store, mode='r') +print(group.info) +``` + +!!! warning + The [`zarr.storage.ObjectStore`][] class is experimental. + +## Developing custom stores + +Zarr-Python [`zarr.abc.store.Store`][] API is meant to be extended. The Store Abstract Base +Class includes all of the methods needed to be a fully operational store in Zarr Python. +Zarr also provides a test harness for custom stores: [`zarr.testing.store.StoreTests`][]. +See the [Custom stores](extending.md#custom-stores) section of the extending guide for +more on implementing your own store. diff --git a/docs/user-guide/v3_migration.md b/docs/user-guide/v3_migration.md new file mode 100644 index 0000000000..4d97963be2 --- /dev/null +++ b/docs/user-guide/v3_migration.md @@ -0,0 +1,244 @@ +# 3.0 Migration Guide + +Zarr-Python 3 represents a major refactor of the Zarr-Python codebase. Some of the +goals motivating this refactor included: + +* adding support for the Zarr format 3 specification (along with the Zarr format 2 specification) +* cleaning up internal and user facing APIs +* improving performance (particularly in high latency storage environments like + cloud object stores) + +To accommodate this, Zarr-Python 3 introduces a number of changes to the API, including a number +of significant breaking changes and deprecations. + +This page provides a guide explaining breaking changes and deprecations to help you +migrate your code from version 2 to version 3. If we have missed anything, please +open a [GitHub issue](https://github.com/zarr-developers/zarr-python/issues/new) +so we can improve this guide. + +!!! tip + This page is about migrating your *code* from the Zarr-Python 2 API to the + Zarr-Python 3 API. If you want to migrate the *metadata* of stored data from + Zarr format 2 to Zarr format 3, see the `zarr migrate` command described in + the [command-line interface documentation](cli.md). + +## Compatibility target + +The goals described above necessitated some breaking changes to the API (hence the +major version update), but where possible we have maintained backwards compatibility +in the most widely used parts of the API. This includes the [`zarr.Array`][] and +[`zarr.Group`][] classes and the "top-level API" (e.g. [`zarr.open_array`][] and +[`zarr.open_group`][]). + +## Getting ready for 3.0 + +Before migrating to Zarr-Python 3, we suggest projects that depend on Zarr-Python take +the following actions in order: + +1. Pin the supported Zarr-Python version to `zarr>=2,<3`. This is a best practice + and will protect your users from any incompatibilities that may arise during the + release of Zarr-Python 3. This pin can be removed after migrating to Zarr-Python 3. +2. Limit your imports from the Zarr-Python package. Most of the primary API `zarr.*` + will be compatible in Zarr-Python 3. However, the following breaking API changes are + planned: + + - `numcodecs.*` will no longer be available in `zarr.*`. To migrate, import codecs + directly from `numcodecs`: + + ```python exec="false" reason="intentionally shows the old/incorrect import for contrast" + from numcodecs import Blosc + # instead of: + # from zarr import Blosc + ``` + + - The `zarr.v3_api_available` feature flag is being removed. In Zarr-Python 3 + the v3 API is always available, so you shouldn't need to use this flag. + - `zarr.errors` has been consolidated. Several exception classes from + Zarr-Python 2 (such as `zarr.errors.PathNotFoundError`) have been removed + or replaced. For example, missing nodes now raise `zarr.errors.NodeNotFoundError` + (which subclasses both `BaseZarrError` and `FileNotFoundError`) instead of + `zarr.errors.PathNotFoundError`. Review any code that catches exceptions + from `zarr.errors` after migrating. + - The following internal modules are being removed or significantly changed. If + your application relies on imports from any of the below modules, you will need + to either a) modify your application to no longer rely on these imports or b) + vendor the parts of the specific modules that you need. + + * `zarr.attrs` has gone, with no replacement + * `zarr.codecs` has changed, see "Codecs" section below for more information + * `zarr.context` has gone, with no replacement + * `zarr.core` remains but should be considered private API + * `zarr.hierarchy` has gone, with no replacement (use `zarr.Group` in place of `zarr.hierarchy.Group`) + * `zarr.indexing` has gone, with no replacement + * `zarr.meta` has gone, with no replacement + * `zarr.meta_v1` has gone, with no replacement + * `zarr.sync` has gone, with no replacement + * `zarr.types` has gone, with no replacement + * `zarr.util` has gone, with no replacement + * `zarr.n5` has gone, see below for an alternative N5 option + +3. Test that your package works with version 3. +4. Update the pin to include `zarr>=3,<4`. + +## Zarr-Python 2 support window + +Zarr-Python 2.x is still available, though we recommend migrating to Zarr-Python 3 for +its performance improvements and new features. Security and bug fixes were made to +the 2.x series for six months following the first Zarr-Python 3 release (January 2025); +the 2.x series is no longer actively maintained. +If you need to use the latest Zarr-Python 2 release, you can install it with: + +```console +$ pip install "zarr==2.*" +``` + +!!! note + Development and maintenance of the 2.x release series has moved to the + [support/v2](https://github.com/zarr-developers/zarr-python/tree/support/v2) branch. + Issues and pull requests related to this branch are tagged with the + [V2](https://github.com/zarr-developers/zarr-python/labels/V2) label. + +## Migrating to Zarr-Python 3 + +The following sections provide details on breaking changes in Zarr-Python 3. + +### The Array class + +1. Disallow direct construction - the signature for initializing the `Array` class has changed + significantly. Please use [`zarr.create_array`][] or [`zarr.open_array`][] instead of + directly constructing the [`zarr.Array`][] class. + +2. Defaulting to `zarr_format=3` - newly created arrays will use the version 3 of the + Zarr specification. To continue using version 2, set `zarr_format=2` when creating arrays + or set `default_zarr_format=2` in Zarr's runtime configuration. + +3. Function signature change to [`zarr.Array.resize`][] - the `resize` function now takes a + `zarr.core.common.ShapeLike` input rather than separate arguments for each dimension. + Use `resize((10,10))` in place of `resize(10,10)`. + +### The Group class + +1. Disallow direct construction - use [`zarr.open_group`][] or [`zarr.create_group`][] + instead of directly constructing the `zarr.Group` class. +2. The h5py compatibility methods `create_dataset` and `require_dataset` have been removed. + Use the following replacements: + + - [`zarr.Group.create_array`][] in place of `Group.create_dataset` + - [`zarr.Group.require_array`][] in place of `Group.require_dataset` + +3. Disallow "." syntax for getting group members. To get a member of a group named `foo`, + use `group["foo"]` in place of `group.foo`. +4. The `zarr.storage.init_group` low-level helper function has been removed. Use + [`zarr.open_group`][] or [`zarr.create_group`][] instead: + + ```diff + - from zarr.storage import init_group + - init_group(store, overwrite=True, path="my/path") + + import zarr + + zarr.open_group(store, mode="w", path="my/path") + ``` + +### The Store class + +The Store API has changed significantly in Zarr-Python 3. + +#### The base store class + +The `MutableMapping` base class has been replaced in favor of a custom abstract base class ([`zarr.abc.store.Store`][]). +An asynchronous interface is used for all store methods that use I/O. +This change ensures that these store methods are non-blocking and are as performant as possible. + +#### Store implementations + +Store implementations have moved from the top-level module to `zarr.storage`: + +```diff title="Store import changes from v2 to v3" +# Before (v2) +- from zarr import MemoryStore ++ from zarr.storage import MemoryStore +``` + +The following stores have been renamed or changed: + +| v2 | v3 | +|------------------------|------------------------------------| +| `DirectoryStore` | [`zarr.storage.LocalStore`][] | +| `FSStore` | [`zarr.storage.FsspecStore`][] | +| `TempStore` | Use [`tempfile.TemporaryDirectory`][] with [`LocalStore`][zarr.storage.LocalStore] | + +A number of deprecated stores were also removed. +See [issue #1274](https://github.com/zarr-developers/zarr-python/issues/1274) for more details on the removal of these stores. + +- `N5Store` - see https://github.com/zarr-developers/n5py for an alternative interface to + N5 formatted data. +- `ABSStore` - use the [`zarr.storage.FsspecStore`][] instead along with fsspec's + [adlfs backend](https://github.com/fsspec/adlfs). +- `DBMStore` +- `LMDBStore` +- `SQLiteStore` +- `MongoDBStore` +- `RedisStore` + +The latter five stores in this list do not have an equivalent in Zarr-Python 3. +If you are interested in developing a custom store that targets these backends, see +[developing custom stores](storage.md#developing-custom-stores) or open an +[issue](https://github.com/zarr-developers/zarr-python/issues) to discuss your use case. + +### Codecs + +Codecs defined in ``numcodecs`` (and also imported into the ``zarr.codecs`` namespace in Zarr-Python 2) +should still be used when creating Zarr format 2 arrays. + +Codecs for creating Zarr format 3 arrays are available in two locations: + +- `zarr.codecs` contains Zarr format 3 codecs that are defined in the [codecs section of the Zarr format 3 specification](https://zarr-specs.readthedocs.io/en/latest/v3/codecs/index.html). +- `numcodecs.zarr3` contains codecs from `numcodecs` that can be used to create Zarr format 3 arrays, but are not necessarily part of the Zarr format 3 specification. + +### Dependencies + +When installing using `pip`: + +- The new `remote` dependency group can be used to install a supported version of + `fsspec`, required for remote data access. +- The new `gpu` dependency group can be used to install a supported version of + `cuda`, required for GPU functionality. +- The `jupyter` optional dependency group has been removed, since v3 contains no + jupyter specific functionality. + +### Miscellaneous + +- The keyword argument `zarr_version` in most creation functions in `zarr` + (e.g. [`zarr.create`][], [`zarr.open`][], [`zarr.group`][], [`zarr.array`][]) has + been removed. Use `zarr_format` instead. + +## Unimplemented Zarr-Python 2 features + +A few features of Zarr-Python 2 remain unimplemented in Zarr-Python 3. +If any of the features listed below are important to your use case +of Zarr-Python, please open (or comment on) a +[GitHub issue](https://github.com/zarr-developers/zarr-python/issues/new). + +The following functions / methods have not been ported to Zarr-Python 3: + +- `zarr.copy` ([issue #2407](https://github.com/zarr-developers/zarr-python/issues/2407)) +- `zarr.copy_all` ([issue #2407](https://github.com/zarr-developers/zarr-python/issues/2407)) +- `zarr.copy_store` ([issue #2407](https://github.com/zarr-developers/zarr-python/issues/2407)) + +The following features (corresponding to function arguments to functions in + `zarr`) have not been ported to Zarr-Python 3. Using these features + will raise a warning or a `NotImplementedError`: + +- `cache_attrs` +- `cache_metadata` +- `chunk_store` ([issue #2495](https://github.com/zarr-developers/zarr-python/issues/2495)) +- `meta_array` +- `object_codec` ([issue #2617](https://github.com/zarr-developers/zarr-python/issues/2617)) +- `synchronizer` ([issue #1596](https://github.com/zarr-developers/zarr-python/issues/1596)) + +The following features that were supported by Zarr-Python 2 have not been ported + to Zarr-Python 3: + +- Object dtypes ([issue #2616](https://github.com/zarr-developers/zarr-python/issues/2616)) +- Ragged arrays ([issue #2618](https://github.com/zarr-developers/zarr-python/issues/2618)) +- Groups and Arrays do not implement `__enter__` and `__exit__` protocols ([issue #2619](https://github.com/zarr-developers/zarr-python/issues/2619)) +- Default filters for object dtypes for Zarr format 2 arrays ([issue #2627](https://github.com/zarr-developers/zarr-python/issues/2627)) diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000000..a6b5fa2179 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,44 @@ +# Zarr Python Examples + +This directory contains complete, runnable examples demonstrating various features and use cases of Zarr Python. + +## Directory Structure + +Each example is organized in its own subdirectory with the following structure: + +``` +examples/ +β”œβ”€β”€ example_name/ +β”‚ β”œβ”€β”€ README.md # Documentation for the example +β”‚ └── example_name.py # Python source code +└── ... +``` + +## Adding New Examples + +To add a new example: + +1. Create a new subdirectory: `examples/my_example/` +2. Add your Python code: `examples/my_example/my_example.py` +3. Create documentation: `examples/my_example/README.md` +4. Create a documentation page at `docs/user-guide/examples/my_example.md`. The documentation page should simply link to the `README.md` and the source code, e.g.: + + ```` + # docs/user-guide/examples/my_example.md + --8<-- "examples/my_example/README.md" + + ## Source Code + + ```python + --8<-- "examples/my_example/my_example.py" + ``` + ```` +5. Update `mkdocs.yml` to include the new example in the navigation. + +### Example README.md Format + +Your README.md should include: + +- A title (`# Example Name`) +- Description of what the example demonstrates +- Instructions for running the example diff --git a/examples/codec_pipeline_performance/README.md b/examples/codec_pipeline_performance/README.md new file mode 100644 index 0000000000..5d85412c29 --- /dev/null +++ b/examples/codec_pipeline_performance/README.md @@ -0,0 +1,59 @@ +# Codec Pipeline Performance + +This example compares the default `BatchedCodecPipeline` against the opt-in +`FusedCodecPipeline` on a sharded array, across two stores (memory and local) +and two codec regimes (uncompressed and gzip), at one worker and at `cpu_count`. + +A *codec pipeline* turns chunks of array data into stored bytes and back, running +the configured codecs and performing the storage IO. The default +`BatchedCodecPipeline` schedules both asynchronously -- roughly one coroutine per +chunk operation. That model pays off for high-latency stores, where there is +useful work to do while waiting on IO. For low-latency stores (in-process memory, +the local filesystem) the IO completes too quickly for the overlap to be worth +its cost, and the async scheduling becomes pure overhead. + +`FusedCodecPipeline` runs codec compute and synchronous IO synchronously, +removing that overhead. It is +[experimental](https://zarr.readthedocs.io/en/stable/user-guide/experimental/) +and opt-in; the default pipeline is unchanged. + +## What it shows + +- How to select a pipeline with `zarr.config.set`, and why the array must be + *created* inside the config block: the pipeline class is resolved at array + construction time and then travels with the array. +- That the benefit depends strongly on layout and on whether compression is in + play. Some configurations are slower under the fused pipeline -- the script + reports speedups below 1.00x rather than hiding them. +- That `codec_pipeline.max_workers` is read only by `FusedCodecPipeline`; the + default pipeline ignores it entirely. + +## Running + +```bash +uv run codec_pipeline_performance.py +``` + +The script has no arguments and writes only to an in-memory store. + +## Interpreting the output + +The numbers are specific to your CPU, your Python build, and the workload chosen +here. They are a measurement of your machine, not a published benchmark -- treat +a single run as indicative and re-measure against your own data and store before +switching pipelines in production. + +Two effects are worth watching for: + +- **The two codec regimes tell opposite stories about `max_workers`.** + Uncompressed IO is dominated by per-chunk *scheduling*, so `Fused (1 worker)` + is already fastest and a thread pool only adds overhead. gzip is genuinely + CPU-bound: a single worker compresses chunk after chunk sequentially and can + be *slower than the default*, while a thread pool spreads that compression + over cores and reclaims the win. That flip is why the fused pipeline is + threaded by default, and why pinning `max_workers=1` is worth it for + memory-backed uncompressed data. +- **Chunk size decides whether threading can help at all.** The 64Γ—64 inner + chunks here are small enough that per-chunk scheduling dominates uncompressed + IO, yet large enough that per-chunk gzip is real work to parallelize. Much + coarser chunks leave the pool with too few items to spread. diff --git a/examples/codec_pipeline_performance/codec_pipeline_performance.py b/examples/codec_pipeline_performance/codec_pipeline_performance.py new file mode 100644 index 0000000000..b821f3e6a7 --- /dev/null +++ b/examples/codec_pipeline_performance/codec_pipeline_performance.py @@ -0,0 +1,214 @@ +# /// script +# requires-python = ">=3.11" +# dependencies = [ +# "zarr @ git+https://github.com/zarr-developers/zarr-python.git@main", +# "numpy", +# ] +# /// + +""" +Compare the `BatchedCodecPipeline` and the `FusedCodecPipeline`. + +The default `BatchedCodecPipeline` schedules storage IO and codec compute +asynchronously -- roughly one coroutine per chunk operation. For a *sharded* +array that means one coroutine per inner chunk inside every shard. That is the +right model for high-latency stores, where there is useful work to do while +waiting for IO. For low-latency stores (in-process memory, the local +filesystem) the IO completes too quickly for the overlap to pay for itself, and +the scheduling becomes pure overhead. + +The `FusedCodecPipeline` runs codec compute and synchronous IO synchronously, +removing that overhead. Whether it wins, and whether its thread pool helps, +depends on which resource is actually scarce: + + * Uncompressed IO is dominated by per-chunk *scheduling*, not compute. There + is nothing for a thread pool to parallelize, so a single worker is already + fastest and extra workers only add overhead. + * gzip is genuinely CPU-bound. A single worker compresses every chunk + sequentially and can be *slower than the default*, while a thread pool + spreads that compression across cores and reclaims the win. This is when + `max_workers > 1` earns its keep. + +Run it with: + + uv run codec_pipeline_performance.py + +Numbers are hardware-, layout-, and codec-dependent. Treat the output as a +measurement of *your* machine, not as a published benchmark. +""" + +from __future__ import annotations + +import operator +import os +import statistics +import tempfile +import timeit +from pathlib import Path +from typing import TYPE_CHECKING + +import numpy as np + +import zarr +from zarr.storage import LocalStore, MemoryStore + +if TYPE_CHECKING: + from collections.abc import Callable + + from zarr.abc.store import Store + +BATCHED = "zarr.core.codec_pipeline.BatchedCodecPipeline" +FUSED = "zarr.core.codec_pipeline.FusedCodecPipeline" + +# gzip is CPU-bound to encode, which is exactly the regime where the thread +# pool matters. Level 6 is gzip's own default. +GZIP = {"name": "gzip", "configuration": {"level": 6}} + +# 4096x4096 int32 = 64 MiB, split into 16 shards of 1024x1024, each holding +# 16x16 = 256 inner chunks of 64x64 -> 4096 inner chunks in total. The chunks +# are small enough that per-chunk coroutine scheduling dominates uncompressed +# IO, yet large enough that per-chunk gzip is real work to spread over cores. +SHAPE = (4096, 4096) +SHARDS = (1024, 1024) +CHUNKS = (64, 64) +DTYPE = "int32" + +CONFIGS: tuple[tuple[str, dict[str, object]], ...] = ( + ("Batched (default)", {"codec_pipeline.path": BATCHED}), + ("Fused (1 worker)", {"codec_pipeline.path": FUSED, "codec_pipeline.max_workers": 1}), + ("Fused (cpu_count)", {"codec_pipeline.path": FUSED, "codec_pipeline.max_workers": None}), +) + + +def time_call(fn: Callable[[], object], repeat: int = 3) -> float: + """Median wall-clock seconds for one call to `fn`. + + `timeit.Timer` supplies `perf_counter` and disables the cyclic garbage + collector during each run, so a collection triggered by earlier work cannot + land inside a measurement. `number=1` because a single call here already + moves 64 MiB -- the per-call overhead `timeit` amortizes is irrelevant at + this scale. + """ + return statistics.median(timeit.Timer(fn).repeat(repeat=repeat, number=1)) + + +def measure( + settings: dict[str, object], + store: Store, + data: np.ndarray, + compressors: object, +) -> tuple[float, float]: + """Time one full write and one full read of `data` under `settings`. + + The whole operation runs inside `zarr.config.set`, not just the array + construction. The pipeline class is resolved when the array is built, but + `codec_pipeline.max_workers` is read *per operation*, so a timed call made + outside the config block would silently use whatever worker count was + globally in effect -- which makes every configuration look identical. + """ + everything = slice(None) + + def write_once() -> None: + with zarr.config.set(settings): + array = zarr.create_array( + store=store, + shape=SHAPE, + chunks=CHUNKS, + shards=SHARDS, + dtype=DTYPE, + compressors=compressors, + fill_value=0, + overwrite=True, + ) + operator.setitem(array, everything, data) + + write = time_call(write_once) + + # The bytes on disk are identical whichever pipeline wrote them, so reading + # back what we just wrote isolates read performance on the same data. + def read_once() -> object: + with zarr.config.set(settings): + return zarr.open_array(store=store, mode="r")[everything] + + read = time_call(read_once) + + if not np.array_equal(read_once(), data): + raise AssertionError("round trip mismatch") + return write, read + + +def make_store(kind: str, tmp: Path) -> Store: + if kind == "memory": + return MemoryStore() + return LocalStore(tmp / f"demo_{kind}_{os.getpid()}.zarr") + + +def main() -> None: + n_cpu = os.cpu_count() or 1 + + # Each regime gets the data that actually exercises it. `arange` is + # trivially compressible, which is fine when nothing compresses it, but it + # would make gzip finish almost instantly and hide the CPU-bound behavior + # this example is about. The noisy array keeps gzip genuinely busy. + n = int(np.prod(SHAPE)) + plain_data = np.arange(n, dtype=DTYPE).reshape(SHAPE) + noisy_data = np.random.default_rng(0).integers(0, 2**24, size=SHAPE, dtype=DTYPE) + + n_shards = int(np.prod([s // c for s, c in zip(SHAPE, SHARDS, strict=True)])) + per_shard = int(np.prod([s // c for s, c in zip(SHARDS, CHUNKS, strict=True)])) + print(f"zarr {zarr.__version__} | {n_cpu} CPUs") + print( + f"array {SHAPE} {DTYPE} = {plain_data.nbytes / 2**20:.0f} MiB | " + f"{n_shards} shards x {per_shard} inner chunks = {n_shards * per_shard} chunks\n" + ) + + with tempfile.TemporaryDirectory() as tmp: + for store_kind in ("memory", "local"): + for codec_label, compressors, data in ( + ("uncompressed", None, plain_data), + ("gzip-6 (CPU-bound)", GZIP, noisy_data), + ): + print(f"=== {store_kind} store / {codec_label} ===") + print( + f"{'pipeline':<22}{'write (s)':>11}{'vs base':>10}" + f"{'read (s)':>12}{'vs base':>10}" + ) + results: dict[str, tuple[float, float]] = {} + for label, settings in CONFIGS: + store = make_store(store_kind, Path(tmp)) + results[label] = measure(settings, store, data, compressors) + + base_write, base_read = results[CONFIGS[0][0]] + for label, (write, read) in results.items(): + print( + f"{label:<22}{write:>10.3f}{base_write / write:>9.1f}x" + f"{read:>11.3f}{base_read / read:>9.1f}x" + ) + + # The headline comparison: does the thread pool earn its keep? + single_write, single_read = results["Fused (1 worker)"] + pool_write, pool_read = results["Fused (cpu_count)"] + print( + f" workers (cpu_count vs 1 worker): " + f"write {single_write / pool_write:.1f}x " + f"read {single_read / pool_read:.1f}x" + ) + print() + + print( + "Reading it:\n" + " * Uncompressed IO is scheduling-bound, so Fused (1 worker) is already\n" + " fastest -- a thread pool has nothing to parallelize and only adds\n" + " overhead.\n" + " * gzip is CPU-bound, so Fused (1 worker) can be *slower* than the\n" + " default, while Fused (cpu_count) spreads compression across cores\n" + " and reclaims the win. That flip is why the fused pipeline is\n" + " threaded by default, and why pinning max_workers=1 is worth it for\n" + " memory-backed uncompressed data.\n" + " * `codec_pipeline.max_workers` is read only by the FusedCodecPipeline;\n" + " the default BatchedCodecPipeline ignores it." + ) + + +if __name__ == "__main__": + main() diff --git a/examples/custom_dtype/README.md b/examples/custom_dtype/README.md new file mode 100644 index 0000000000..266f398ca8 --- /dev/null +++ b/examples/custom_dtype/README.md @@ -0,0 +1,27 @@ +# Custom Data Type + +This example demonstrates how to extend Zarr Python by defining a new data type. + +The example shows how to: + +- Define a custom `ZDType` class for the `int2` data type from [`ml_dtypes`](https://pypi.org/project/ml-dtypes/) +- Implement all required methods for serialization and deserialization +- Register the custom data type with Zarr's registry +- Create and use arrays with the custom data type in both Zarr v2 and v3 formats + +## Running the Example + +The script declares its dependencies inline +([PEP 723](https://peps.python.org/pep-0723/)), so the easiest way to run it is +with [uv](https://docs.astral.sh/uv/), which installs them automatically: + +```bash +uv run examples/custom_dtype/custom_dtype.py +``` + +Alternatively, run it with plain Python, in which case you must first install +`zarr`, `ml_dtypes`, and `pytest` yourself: + +```bash +python examples/custom_dtype/custom_dtype.py +``` diff --git a/examples/custom_dtype/custom_dtype.py b/examples/custom_dtype/custom_dtype.py new file mode 100644 index 0000000000..53acb70f52 --- /dev/null +++ b/examples/custom_dtype/custom_dtype.py @@ -0,0 +1,255 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "zarr @ git+https://github.com/zarr-developers/zarr-python.git@main", +# "ml_dtypes==0.5.4", +# "pytest==8.4.1" +# ] +# /// +# + +""" +Demonstrate how to extend Zarr Python by defining a new data type +""" + +import json +import sys +from pathlib import Path +from typing import ClassVar, Literal, Self, TypeGuard, overload + +import ml_dtypes # necessary to add extra dtypes to NumPy +import numpy as np +import pytest + +import zarr +from zarr.dtype import ZDType, check_dtype_spec_v2, data_type_registry +from zarr.errors import DataTypeValidationError +from zarr.types import JSON, DTypeConfig_V2, DTypeJSON, ZarrFormat + +# This is the int2 array data type +int2_dtype_cls = type(np.dtype("int2")) + +# This is the int2 scalar type +int2_scalar_cls = ml_dtypes.int2 + + +class Int2(ZDType[int2_dtype_cls, int2_scalar_cls]): + """ + This class provides a Zarr compatibility layer around the int2 data type (the ``dtype`` of a + NumPy array of type int2) and the int2 scalar type (the ``dtype`` of the scalar value inside an int2 array). + """ + + # This field is as the key for the data type in the internal data type registry, and also + # as the identifier for the data type when serializaing the data type to disk for zarr v3 + _zarr_v3_name: ClassVar[Literal["int2"]] = "int2" + # this field will be used internally + _zarr_v2_name: ClassVar[Literal["int2"]] = "int2" + + # we bind a class variable to the native data type class so we can create instances of it + dtype_cls = int2_dtype_cls + + @classmethod + def from_native_dtype(cls, dtype: np.dtype) -> Self: + """Create an instance of this ZDType from a native dtype.""" + if cls._check_native_dtype(dtype): + return cls() + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self: Self) -> int2_dtype_cls: + """Create an int2 dtype instance from this ZDType""" + return self.dtype_cls() + + @classmethod + def _check_json_v2(cls, data: DTypeJSON) -> TypeGuard[DTypeConfig_V2[Literal["|b1"], None]]: + """ + Type check for Zarr v2-flavored JSON. + + This will check that the input is a dict like this: + .. code-block:: json + + { + "name": "int2", + "object_codec_id": None + } + + Note that this representation differs from the ``dtype`` field looks like in zarr v2 metadata. + Specifically, whatever goes into the ``dtype`` field in metadata is assigned to the ``name`` field here. + + See the Zarr docs for more information about the JSON encoding for data types. + """ + return ( + check_dtype_spec_v2(data) and data["name"] == "int2" and data["object_codec_id"] is None + ) + + @classmethod + def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[Literal["int2"]]: + """ + Type check for Zarr V3-flavored JSON. + + Checks that the input is the string "int2". + """ + return data == cls._zarr_v3_name + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this ZDType from Zarr V3-flavored JSON. + """ + if cls._check_json_v2(data): + return cls() + # This first does a type check on the input, and if that passes we create an instance of the ZDType. + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v2_name!r}" + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls: type[Self], data: DTypeJSON) -> Self: + """ + Create an instance of this ZDType from Zarr V3-flavored JSON. + + This first does a type check on the input, and if that passes we create an instance of the ZDType. + """ + if cls._check_json_v3(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[Literal["int2"], None]: ... + + @overload + def to_json(self, zarr_format: Literal[3]) -> Literal["int2"]: ... + + def to_json( + self, zarr_format: ZarrFormat + ) -> DTypeConfig_V2[Literal["int2"], None] | Literal["int2"]: + """ + Serialize this ZDType to v2- or v3-flavored JSON + + If the zarr_format is 2, then return a dict like this: + .. code-block:: json + + { + "name": "int2", + "object_codec_id": None + } + + If the zarr_format is 3, then return the string "int2" + + """ + if zarr_format == 2: + return {"name": "int2", "object_codec_id": None} + if zarr_format == 3: + return self._zarr_v3_name + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + def _check_scalar(self, data: object) -> TypeGuard[int | ml_dtypes.int2]: + """ + Check if a python object is a valid int2-compatible scalar + + The strictness of this type check is an implementation degree of freedom. + You could be strict here, and only accept int2 values, or be open and accept any integer + or any object and rely on exceptions from the int2 constructor that will be called in + cast_scalar. + """ + return isinstance(data, (int, int2_scalar_cls)) + + def cast_scalar(self, data: object) -> ml_dtypes.int2: + """ + Attempt to cast a python object to an int2. + + We first perform a type check to ensure that the input type is appropriate, and if that + passes we call the int2 scalar constructor. + """ + if self._check_scalar(data): + return ml_dtypes.int2(data) + msg = ( + f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the " + f"data type {self}." + ) + raise TypeError(msg) + + def default_scalar(self) -> ml_dtypes.int2: + """ + Get the default scalar value. This will be used when automatically selecting a fill value. + """ + return ml_dtypes.int2(0) + + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> int: + """ + Convert a python object to a JSON representation of an int2 scalar. + This is necessary for taking user input for the ``fill_value`` attribute in array metadata. + + In this implementation, we optimistically convert the input to an int, + and then check that it lies in the acceptable range for this data type. + """ + # We could add a type check here, but we don't need to for this example + val: int = int(data) # type: ignore[call-overload] + + if val in {-2, -1, 0, 1}: + return val + + raise ValueError("Invalid value. Expected -2, -1, 0, or 1.") + + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> ml_dtypes.int2: + """ + Read a JSON-serializable value as an int2 scalar. + + We first perform a type check to ensure that the JSON value is well-formed, then call the + int2 scalar constructor. + + The base definition of this method requires that it take a zarr_format parameter because + other data types serialize scalars differently in zarr v2 and v3, but we don't use this here. + + """ + if self._check_scalar(data): + return ml_dtypes.int2(data) + raise TypeError(f"Invalid type: {data}. Expected an int.") + + +# after defining dtype class, it must be registered with the data type registry so zarr can use it +data_type_registry.register(Int2._zarr_v3_name, Int2) + + +# this parametrized function will create arrays in zarr v2 and v3 using our new data type +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_custom_dtype(tmp_path: Path, zarr_format: ZarrFormat) -> None: + # create array and write values + z_w = zarr.create_array( + store=tmp_path, + shape=(4,), + dtype="int2", + zarr_format=zarr_format, + compressors=None, + ) + z_w[:] = [-1, -2, 0, 1] + + # open the array + z_r = zarr.open_array(tmp_path, mode="r") + + print(z_r.info_complete()) + + # look at the array metadata + meta_file = tmp_path / (".zarray" if zarr_format == 2 else "zarr.json") + print(json.dumps(json.loads(meta_file.read_text()), indent=2)) + + +if __name__ == "__main__": + # Run the example with printed output, and a dummy pytest configuration file specified. + # Without the dummy configuration file, at test time pytest will attempt to use the + # configuration file in the project root, which will error because Zarr is using some + # plugins that are not installed in this example. + sys.exit( + pytest.main( + [ + "-s", + __file__, + f"-c {__file__}", + # Suppress: "PytestAssertRewriteWarning: Module already imported so + # cannot be rewritten; zarr" + "-W", + "ignore::pytest.PytestAssertRewriteWarning", + ] + ) + ) diff --git a/examples/sharding_coalescing/README.md b/examples/sharding_coalescing/README.md new file mode 100644 index 0000000000..29ba08c9ce --- /dev/null +++ b/examples/sharding_coalescing/README.md @@ -0,0 +1,63 @@ +# Sharded Read Coalescing + +This example demonstrates byte-range coalescing for partial reads of sharded +arrays, a performance optimization added in Zarr-Python 3.3.0 and enabled by +default. + +A shard is one stored object containing many inner chunks, each occupying its own +byte range. Reading N inner chunks could mean N separate byte-range requests. +Because byte ranges are intervals, nearby ranges can be merged: `[a, b)` and +`[b, c)` together cover `[a, c)`, so a single request can serve both. Merging +trades reading some bytes you did not ask for against issuing fewer requests -- +worthwhile whenever a request is expensive, as with object storage. + +## What it shows + +- Reading scattered inner chunks from one shard with coalescing **off** issues + one store request per inner chunk; with the **default** settings the same read + collapses to a single request. +- The resulting wall-clock difference against a store with simulated latency. +- That coalescing changes only *how* data is fetched, never *what* is returned -- + the script asserts both configurations produce identical arrays. +- A case where coalescing changes nothing: a contiguous selection already has + adjacent byte ranges, so it merges under any setting. + +## Running + +```bash +uv run sharding_coalescing.py +``` + +## How the comparison is set up + +Two details make the effect observable, and both are worth understanding if you +adapt this script: + +- **The selection must have gaps.** A contiguous read produces adjacent byte + ranges that merge regardless of configuration. The strided selections skip + inner chunks, creating the gaps that the `sharding_coalesce_max_gap_bytes` + budget decides whether to bridge. +- **Latency must be charged per merged fetch.** The example defines a small + `WrapperStore` subclass that sleeps in `get`. It deliberately does *not* keep + `WrapperStore.get_ranges`, which forwards straight to the wrapped store and + would bypass the latency entirely; inheriting the `Store` ABC's `get_ranges` + instead runs the coalescer over its own `get`, so each merged fetch pays once. + + `zarr.testing.store` ships a ready-made `LatencyStore`, but importing it pulls + in `pytest`. Defining the wrapper inline keeps the example runnable with only + `zarr` and `numpy` installed. + +## Configuration + +Two settings control the behavior, both settable globally via `zarr.config` or +per array via `config=` on `zarr.create_array` / `Array.with_config`: + +| Setting | Default | Meaning | +| --- | --- | --- | +| `sharding_coalesce_max_gap_bytes` | 1 MiB | Merge two ranges only if the gap between them is no larger than this | +| `sharding_coalesce_max_bytes` | 16 MiB | Never let a merged read exceed this size | + +Setting the gap to `0` merges only exactly-adjacent ranges, which approximates +the pre-3.3.0 behavior; that is how the example emulates the old path. Raising +the gap reads more unwanted bytes in exchange for fewer round trips -- the right +value depends on how expensive a request is against how fast your link is. diff --git a/examples/sharding_coalescing/sharding_coalescing.py b/examples/sharding_coalescing/sharding_coalescing.py new file mode 100644 index 0000000000..5da62ed806 --- /dev/null +++ b/examples/sharding_coalescing/sharding_coalescing.py @@ -0,0 +1,226 @@ +# /// script +# requires-python = ">=3.11" +# dependencies = [ +# "zarr @ git+https://github.com/zarr-developers/zarr-python.git@main", +# "numpy", +# ] +# /// + +""" +Demonstrate byte-range coalescing for partial reads of sharded arrays. + +A shard is a single stored object holding many inner chunks, each occupying +its own byte range. Reading N inner chunks could mean issuing N separate +byte-range requests to the store. Because byte ranges are intervals, a reader +can instead merge nearby ranges: `[a, b)` and `[b, c)` together cover +`[a, c)`, so one request can serve both. Merging trades reading some bytes you +did not ask for against issuing fewer requests -- a good trade whenever a +request is expensive, which is the normal case for object storage. + +Zarr-Python 3.3.0 does this automatically. Two settings control it: + + * `sharding_coalesce_max_gap_bytes` (default 1 MiB) -- merge two ranges only + if the gap between them is no larger than this. + * `sharding_coalesce_max_bytes` (default 16 MiB) -- never let a merged read + exceed this size. + +Setting the gap to 0 disables merging of non-adjacent ranges, which +approximates the pre-3.3.0 behavior. This script compares the two, counting +store requests and measuring wall-clock time against a store with simulated +latency. + +Run it with: + + uv run sharding_coalescing.py +""" + +from __future__ import annotations + +import asyncio +import operator +import statistics +import timeit +from contextlib import contextmanager +from functools import partial +from typing import TYPE_CHECKING + +import numpy as np + +import zarr +import zarr.core._coalesce as coalesce_module +from zarr.abc.store import ByteRequest, RangeByteRequest, Store +from zarr.storage import MemoryStore, WrapperStore + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, Sequence + + from zarr.core.buffer import Buffer, BufferPrototype + +# Emulates the pre-3.3.0 behavior: with a zero gap budget, only ranges that are +# exactly adjacent get merged, so scattered inner chunks are fetched one by one. +NO_COALESCING = {"sharding_coalesce_max_gap_bytes": 0} + +# The shipped defaults. Spelled out here so the comparison is explicit rather +# than relying on whatever the global config happens to be. +DEFAULT_COALESCING = { + "sharding_coalesce_max_gap_bytes": 1 << 20, # 1 MiB + "sharding_coalesce_max_bytes": 16 << 20, # 16 MiB +} + +GET_LATENCY_S = 0.005 # 5 ms per request, a modest stand-in for object storage + + +class PerRequestLatencyStore(WrapperStore[Store]): + """Wraps a store, charging a fixed latency per byte-range fetch. + + `zarr.testing.store` ships a `LatencyStore`, but importing it pulls in + `pytest`; defining the wrapper here keeps this example runnable with only + zarr and numpy installed. + + Two details matter for the measurement: + + * The latency is applied in `get`, which is what an individual fetch costs. + * `get_ranges` is explicitly *not* overridden to forward to the wrapped + store. `WrapperStore.get_ranges` does forward, which would skip this + class's `get` entirely and make every configuration look identical. + Inheriting the `Store` ABC's implementation instead runs the coalescer + over `self.get`, so each *merged* fetch pays the latency once -- which is + exactly the cost coalescing exists to reduce. + """ + + get_ranges = Store.get_ranges + + def __init__(self, store: Store, *, get_latency: float) -> None: + super().__init__(store) + self.get_latency = get_latency + + def _with_store(self, store: Store) -> PerRequestLatencyStore: + # `WrapperStore` rebuilds the wrapper when opening read-only, so the + # latency setting has to be carried across. + return type(self)(store, get_latency=self.get_latency) + + async def get( + self, + key: str, + prototype: BufferPrototype, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + await asyncio.sleep(self.get_latency) + return await self._store.get(key, prototype, byte_range) + + +@contextmanager +def counting_requests() -> Iterator[Callable[[], int]]: + """Count the store fetches issued inside the block. + + Wraps the coalescing planner rather than the store: every merged group it + returns, plus every range it declined to merge, becomes exactly one fetch. + Counting here rather than at the store means the number reported is the + planner's decision, which is precisely what the settings control. + """ + original = coalesce_module.coalesce_ranges + total = 0 + + def counting_coalesce_ranges( + byte_ranges: Sequence[ByteRequest | None], + *, + max_gap_bytes: int, + max_coalesced_bytes: int, + ) -> tuple[ + list[list[tuple[int, RangeByteRequest]]], + list[tuple[int, ByteRequest | None]], + ]: + nonlocal total + groups, uncoalescable = original( + byte_ranges, + max_gap_bytes=max_gap_bytes, + max_coalesced_bytes=max_coalesced_bytes, + ) + total += len(groups) + len(uncoalescable) + return groups, uncoalescable + + coalesce_module.coalesce_ranges = counting_coalesce_ranges + try: + yield lambda: total + finally: + coalesce_module.coalesce_ranges = original + + +def measure_read(array: zarr.Array, selection: slice) -> tuple[int, float]: + """Return (store fetches, median seconds) for reading `selection`.""" + read = partial(operator.getitem, array, selection) + + with counting_requests() as fetches: + result = read() + requests = fetches() + + # `timeit.Timer` supplies the loop, `perf_counter`, and GC handling. The + # median of several runs keeps one unlucky run from dominating. + elapsed = statistics.median(timeit.Timer(read).repeat(repeat=5, number=1)) + + assert result.size > 0 # a read that returned nothing would time as "fast" + return requests, elapsed + + +def main() -> None: + n = 8192 + chunk = 64 + inner_chunks = n // chunk + + base = MemoryStore() + source = (np.arange(n, dtype="uint64") % 251).astype("uint8") + + # One shard holding every inner chunk, uncompressed so inner-chunk byte + # offsets stay predictable and the demonstration is easy to reason about. + writable = zarr.create_array( + store=base, shape=(n,), chunks=(chunk,), shards=(n,), dtype="uint8", compressors=None + ) + writable[:] = source + + store = PerRequestLatencyStore(base, get_latency=GET_LATENCY_S) + + print(f"zarr {zarr.__version__}") + print(f"array: {n} uint8 values, {inner_chunks} inner chunks of {chunk} in a single shard") + print(f"store: MemoryStore wrapped with {GET_LATENCY_S * 1000:.0f} ms of latency per request\n") + + # A strided selection touches inner chunks with unread chunks in between, + # so there are real gaps for the coalescer to bridge. A contiguous + # selection would merge under any setting, since its ranges are adjacent. + selections = { + "every 2nd inner chunk": slice(None, None, chunk * 2), + "every 4th inner chunk": slice(None, None, chunk * 4), + "contiguous quarter": slice(0, n // 4), + } + + header = f"{'selection':<24} {'coalescing':<12} {'requests':>9} {'time':>10}" + print(header) + print("-" * len(header)) + + for label, selection in selections.items(): + results = {} + for mode, config in (("off", NO_COALESCING), ("default", DEFAULT_COALESCING)): + array = zarr.open_array(store=store, mode="r").with_config(config) + requests, elapsed = measure_read(array, selection) + results[mode] = (requests, elapsed) + print(f"{label:<24} {mode:<12} {requests:>9} {elapsed * 1000:>9.1f}ms") + + off_requests, off_time = results["off"] + on_requests, on_time = results["default"] + if on_requests < off_requests: + print( + f"{'':<24} {'->':<12} " + f"{off_requests // on_requests:>8}x fewer {off_time / on_time:>9.1f}x faster" + ) + else: + print(f"{'':<24} {'->':<12} {'no change (ranges already adjacent)':>30}") + print() + + # Correctness is the point: coalescing must not change what you read back. + for mode, config in (("off", NO_COALESCING), ("default", DEFAULT_COALESCING)): + array = zarr.open_array(store=store, mode="r").with_config(config) + assert np.array_equal(array[::128], source[::128]), mode + print("Both configurations return identical data; coalescing only changes how it is fetched.") + + +if __name__ == "__main__": + main() diff --git a/lychee.toml b/lychee.toml new file mode 100644 index 0000000000..54a5b49b8d --- /dev/null +++ b/lychee.toml @@ -0,0 +1,25 @@ +# Configuration for the lychee link checker (https://lychee.cli.rs/). +# Auto-discovered as ./lychee.toml by the lychee GitHub Action. + +# Treat redirect status codes as success rather than failures. +accept = ["200..=299"] + +# Files lychee should not scan for links. +exclude_path = [ + # mkdocs-material theme overrides: hrefs are Jinja expressions like + # `{{ '../' ~ base_url }}`, not real URLs, so lychee cannot resolve them. + "docs/overrides", + # Design notes: working records that point at transient artifacts (commits, + # fork branches, compare URLs) which are expected to disappear over time. + "design", +] + +# URL patterns to ignore (regex, matched against the full URL). +exclude = [ + # Local docs preview server shown in the contributing guide ("hatch run serve"), + # documentation of a command rather than a reachable link. + '^https?://0\.0\.0\.0', + '^https?://(localhost|127\.0\.0\.1)(:\d+)?', + # SPEC 0 page times out but is valid. + '^https://scientific-python\.org/specs/spec-0000', +] diff --git a/mkdocs.yml b/mkdocs.yml new file mode 100644 index 0000000000..4d06701a87 --- /dev/null +++ b/mkdocs.yml @@ -0,0 +1,301 @@ +# Based on https://github.com/developmentseed/obspec/blob/main/mkdocs.yml +site_name: zarr-python +repo_name: zarr-developers/zarr-python +repo_url: https://github.com/zarr-developers/zarr-python +site_description: An implementation of chunked, compressed, N-dimensional arrays for Python. +site_author: Alistair Miles +site_url: !ENV [READTHEDOCS_CANONICAL_URL, 'https://zarr.readthedocs.io/'] +docs_dir: docs +use_directory_urls: true + +nav: + - "index.md" + - "quick-start.md" + - User Guide: + - user-guide/index.md + - user-guide/installation.md + - user-guide/arrays.md + - user-guide/groups.md + - user-guide/attributes.md + - user-guide/data_types.md + - user-guide/storage.md + - user-guide/config.md + - user-guide/performance.md + - user-guide/cli.md + - user-guide/extending.md + - user-guide/gpu.md + - user-guide/consolidated_metadata.md + - user-guide/experimental.md + - user-guide/v3_migration.md + - user-guide/glossary.md + - Examples: + - user-guide/examples/custom_dtype.md + - user-guide/examples/rectilinear_chunks.md + - user-guide/examples/codec_pipeline_performance.md + - user-guide/examples/sharding_coalescing.md + - subprojects.md + - API Reference: + - api/zarr/index.md + - 'Β zarr.abc': + - api/zarr/abc/index.md + - 'Β zarr.abc.buffer': api/zarr/abc/buffer.md + - 'Β zarr.abc.codec': api/zarr/abc/codec.md + - 'Β zarr.abc.metadata': api/zarr/abc/metadata.md + - 'Β zarr.abc.numcodec': api/zarr/abc/numcodec.md + - 'Β zarr.abc.store': api/zarr/abc/store.md + - 'Β zarr.api': + - api/zarr/api/index.md + - 'Β zarr.api.asynchronous': api/zarr/api/asynchronous.md + - 'Β zarr.api.synchronous': api/zarr/api/synchronous.md + - 'Β zarr.Array': api/zarr/array.md + - 'Β zarr.array': api/zarr/functions/array.md + - 'Β zarr.buffer': + - api/zarr/buffer/index.md + - 'Β zarr.buffer.cpu': api/zarr/buffer/cpu.md + - 'Β zarr.buffer.gpu': api/zarr/buffer/gpu.md + - 'Β zarr.codecs': api/zarr/codecs.md + - 'Β zarr.codecs.numcodecs': api/zarr/codecs/numcodecs.md + - 'Β zarr.config': api/zarr/config.md + - 'Β zarr.consolidate_metadata': api/zarr/functions/consolidate_metadata.md + - 'Β zarr.create': api/zarr/functions/create.md + - 'Β zarr.create_array': api/zarr/functions/create_array.md + - 'Β zarr.create_group': api/zarr/functions/create_group.md + - 'Β zarr.create_hierarchy': api/zarr/functions/create_hierarchy.md + - 'Β zarr.dtype': api/zarr/dtype.md + - 'Β zarr.empty': api/zarr/functions/empty.md + - 'Β zarr.empty_like': api/zarr/functions/empty_like.md + - 'Β zarr.errors': api/zarr/errors.md + - 'Β zarr.experimental': api/zarr/experimental.md + - 'Β zarr.from_array': api/zarr/functions/from_array.md + - 'Β zarr.full': api/zarr/functions/full.md + - 'Β zarr.full_like': api/zarr/functions/full_like.md + - 'Β zarr.Group': api/zarr/group.md + - 'Β zarr.group': api/zarr/functions/group.md + - 'Β zarr.load': api/zarr/functions/load.md + - 'Β zarr.metadata': api/zarr/metadata.md + - 'Β zarr.ones': api/zarr/functions/ones.md + - 'Β zarr.ones_like': api/zarr/functions/ones_like.md + - 'Β zarr.open': api/zarr/functions/open.md + - 'Β zarr.open_array': api/zarr/functions/open_array.md + - 'Β zarr.open_consolidated': api/zarr/functions/open_consolidated.md + - 'Β zarr.open_group': api/zarr/functions/open_group.md + - 'Β zarr.open_like': api/zarr/functions/open_like.md + - 'Β zarr.print_debug_info': api/zarr/functions/print_debug_info.md + - 'Β zarr.registry': api/zarr/registry.md + - 'Β zarr.save': api/zarr/functions/save.md + - 'Β zarr.save_array': api/zarr/functions/save_array.md + - 'Β zarr.save_group': api/zarr/functions/save_group.md + - 'Β zarr.storage': api/zarr/storage.md + - 'Β zarr.testing': + - api/zarr/testing/index.md + - 'Β zarr.testing.buffer': api/zarr/testing/buffer.md + - 'Β zarr.testing.stateful': api/zarr/testing/stateful.md + - 'Β zarr.testing.store': api/zarr/testing/store.md + - 'Β zarr.testing.strategies': api/zarr/testing/strategies.md + - 'Β zarr.testing.utils': api/zarr/testing/utils.md + - 'Β zarr.zeros': api/zarr/functions/zeros.md + - 'Β zarr.zeros_like': api/zarr/functions/zeros_like.md + # The companion packages are Read the Docs subprojects of this one; link + # to the /projects/ paths Read the Docs advertises as canonical rather + # than to their standalone *.readthedocs.io domains, so following one + # keeps the reader on this site's domain. + - 'zarr-metadata β†ͺ': https://zarr.readthedocs.io/projects/zarr-metadata/ + - 'zarr-indexing β†ͺ': https://zarr.readthedocs.io/projects/zarr-indexing/ + - release-notes.md + - roadmap.md + - contributing.md + - Blog: + - blog/index.md +hooks: + - mkdocs_hooks.py + +watch: + - src/zarr + - docs + +theme: + language: en + name: material + custom_dir: docs/overrides + logo: _static/logo_bw.png + favicon: _static/favicon-96x96.png + + palette: + # Light mode + - media: "(prefers-color-scheme: light)" + scheme: default + primary: custom + accent: custom + toggle: + icon: material/brightness-7 + name: Switch to dark mode + + # Dark mode + - media: "(prefers-color-scheme: dark)" + scheme: slate + primary: custom + accent: custom + toggle: + icon: material/brightness-4 + name: Switch to light mode + + font: + text: Roboto + code: Roboto Mono + + features: + - content.code.annotate + - content.code.copy + - navigation.indexes + - navigation.instant + - navigation.tracking + - search.suggest + - search.share + +extra: + social: + - icon: fontawesome/brands/mastodon + link: https://fosstodon.org/@zarr + - icon: fontawesome/brands/bluesky + link: https://bsky.app/profile/zarr.dev + +extra_css: + - overrides/stylesheets/extra.css + +plugins: + - autorefs + - blog: + blog_dir: blog + post_dir: "{blog}/posts" + post_url_format: "{slug}" + # The blog is a simple reverse-chronological list of posts; the archive + # and category indexes add navigation we don't have the volume to justify. + archive: false + categories: false + - search + - markdown-exec + - mkdocstrings: + enable_inventory: true + handlers: + python: + paths: [src/zarr] + options: + allow_inspection: true + docstring_section_style: list + docstring_style: numpy + inherited_members: true + line_length: 60 + separate_signature: true + show_root_heading: true + show_signature_annotations: true + show_source: true + show_symbol_type_toc: true + signature_crossrefs: true + show_if_no_docstring: true + extensions: + - griffe_inherited_docstrings + + inventories: + - https://docs.python.org/3/objects.inv + - https://docs.xarray.dev/en/stable/objects.inv + - https://numpy.org/doc/stable/objects.inv + - https://numcodecs.readthedocs.io/en/stable/objects.inv + - https://msgspec.dev/objects.inv + - https://developmentseed.org/obstore/latest/objects.inv + - https://filesystem-spec.readthedocs.io/en/latest/objects.inv + - https://requests.readthedocs.io/en/latest/objects.inv + - https://docs.aiohttp.org/en/stable/objects.inv + - https://s3fs.readthedocs.io/en/latest/objects.inv + - https://docs.h5py.org/en/stable/objects.inv + - https://icechunk.io/en/stable/objects.inv + - https://lithops-cloud.github.io/docs/objects.inv + - https://docs.dask.org/en/stable/objects.inv + - redirects: + redirect_maps: + 'spec/index.md': 'https://zarr-specs.readthedocs.io' + 'spec/v1.md': 'https://zarr-specs.readthedocs.io/en/latest/v1/v1.0.html' + 'spec/v2.md': 'https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html' + 'spec/v3.md': 'https://zarr-specs.readthedocs.io/en/latest/v3/core/v3.0.html' + 'license.md': 'https://github.com/zarr-developers/zarr-python/blob/main/LICENSE.txt' + 'genindex.html.md': 'index.md' + 'py-modindex.html.md': 'index.md' + 'search.html.md': 'index.md' + 'tutorial.md': 'user-guide/installation.md' + 'getting-started.md': 'quick-start.md' + 'installation.md': 'user-guide/installation.md' + 'release.md': 'release-notes.md' + 'about.html.md': 'index.md' + 'arrays.html.md': 'user-guide/arrays.md' + 'attributes.html.md': 'user-guide/attributes.md' + 'cli.html.md': 'user-guide/cli.md' + 'config.html.md': 'user-guide/config.md' + 'consolidated_metadata.html.md': 'user-guide/consolidated_metadata.md' + 'data_types.html.md': 'user-guide/data_types.md' + 'extending.html.md': 'user-guide/extending.md' + 'gpu.html.md': 'user-guide/gpu.md' + 'groups.html.md': 'user-guide/groups.md' + 'installation.html.md': 'user-guide/installation.md' + 'performance.html.md': 'user-guide/performance.md' + 'quickstart.html.md': 'quick-start.md' + 'release-notes.html.md': 'release-notes.md' + 'storage.html.md': 'user-guide/storage.md' + 'v3_migration.html.md': 'user-guide/v3_migration.md' + 'user-guide/arrays.html.md': 'user-guide/arrays.md' + 'user-guide/attributes.html.md': 'user-guide/attributes.md' + 'user-guide/cli.html.md': 'user-guide/cli.md' + 'user-guide/config.html.md': 'user-guide/config.md' + 'user-guide/consolidated_metadata.html.md': 'user-guide/consolidated_metadata.md' + 'user-guide/data_types.html.md': 'user-guide/data_types.md' + 'user-guide/extending.html.md': 'user-guide/extending.md' + 'user-guide/gpu.html.md': 'user-guide/gpu.md' + 'user-guide/groups.html.md': 'user-guide/groups.md' + 'user-guide/installation.html.md': 'user-guide/installation.md' + 'user-guide/performance.html.md': 'user-guide/performance.md' + 'user-guide/storage.html.md': 'user-guide/storage.md' + 'user-guide/v3_migration.html.md': 'user-guide/v3_migration.md' + 'developers/contributing.html.md': 'contributing.md' + 'developers/index.html.md': 'contributing.md' + 'developers/roadmap.html.md': 'https://zarr.readthedocs.io/en/v3.0.8/developers/roadmap.html' + 'api.md': 'api/zarr/index.md' + 'api/zarr/create.md': 'api/zarr/functions/create.md' + 'api/zarr/open.md': 'api/zarr/functions/open.md' + 'api/zarr/save.md': 'api/zarr/functions/save.md' + 'api/zarr/load.md': 'api/zarr/functions/load.md' + 'api/zarr/metadata/migrate_v3.md': 'api/zarr/metadata.md' + +# Based on https://github.com/developmentseed/titiler/blob/50934c929cca2fa8d3c408d239015f8da429c6a8/docs/mkdocs.yml#L115-L140 +markdown_extensions: + - admonition + - attr_list + - codehilite: + guess_lang: false + - def_list + - footnotes + - md_in_html + - pymdownx.arithmatex + - pymdownx.betterem + - pymdownx.caret: + insert: false + - pymdownx.details + - pymdownx.escapeall: + hardbreak: true + nbsp: true + - pymdownx.magiclink: + hide_protocol: true + repo_url_shortener: true + - pymdownx.smartsymbols + - pymdownx.superfences + - pymdownx.tasklist: + custom_checkbox: true + - pymdownx.tilde + - pymdownx.emoji: + emoji_index: !!python/name:material.extensions.emoji.twemoji + emoji_generator: !!python/name:material.extensions.emoji.to_svg + - toc: + permalink: true + - pymdownx.highlight: + anchor_linenums: true + line_spans: __span + pygments_lang_class: true + - pymdownx.inlinehilite + - pymdownx.snippets diff --git a/mkdocs_hooks.py b/mkdocs_hooks.py new file mode 100644 index 0000000000..88368926b9 --- /dev/null +++ b/mkdocs_hooks.py @@ -0,0 +1,82 @@ +"""MkDocs hook that renders validation-marked code fences as ordinary code blocks. + +The docs validation convention (see ``tests/test_docs.py`` and the contributing +guide) requires every python fence to carry ``exec="true"``, ``test="true"``, or +``exec="false" reason="..."``. Markdown Exec's superfences fence only claims +``exec="true"`` blocks; without this hook the remaining marked fences fail +superfences validation and their contents spill into the page as raw markdown +(e.g. the PEP 723 header of the custom dtype example rendered as headings). + +This hook registers a second ``python`` fence, tried when Markdown Exec's +declines, that strips the validation attributes and delegates to the standard +superfences highlighter so the block renders exactly like a plain code fence. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from markdown import Markdown + from mkdocs.config.defaults import MkDocsConfig + +# Mirrors markdown_exec's _to_bool: everything but these means "true". +_FALSY = {"", "no", "off", "false", "0"} + + +def _validator( + language: str, + inputs: dict[str, str], + options: dict[str, Any], + attrs: dict[str, Any], + md: Markdown, +) -> bool: + """Claim fences marked test="true" or exec="false"; leave the rest alone.""" + if "exec" not in inputs and "test" not in inputs: + # Plain fence: let the default superfences pathway highlight it. + return False + if str(inputs.get("exec", "false")).lower() not in _FALSY: + # Executable fence: Markdown Exec's own custom fence handles it. + return False + # Consume the validation attributes so they don't leak into the output. + inputs.clear() + return True + + +def _formatter( + source: str, + language: str, + css_class: str, + options: dict[str, Any], + md: Markdown, + classes: list[str] | None = None, + id_value: str = "", + attrs: dict[str, Any] | None = None, + **kwargs: Any, +) -> str: + """Render with the same highlighter superfences uses for plain fences.""" + fenced = md.preprocessors["fenced_code_block"] + fenced.get_hl_settings() + return fenced.highlight( + src=source, + language=language, + options={}, + md=md, + classes=classes, + id_value=id_value, + attrs=attrs or {}, + ) + + +def on_config(config: MkDocsConfig) -> MkDocsConfig: + superfences = config.setdefault("mdx_configs", {}).setdefault("pymdownx.superfences", {}) + custom_fences = superfences.setdefault("custom_fences", []) + custom_fences.append( + { + "name": "python", + "class": "python", + "validator": _validator, + "format": _formatter, + } + ) + return config diff --git a/notebooks/advanced_indexing.ipynb b/notebooks/advanced_indexing.ipynb deleted file mode 100644 index eba6b5880b..0000000000 --- a/notebooks/advanced_indexing.ipynb +++ /dev/null @@ -1,2798 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Advanced indexing" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'2.1.5.dev144'" - ] - }, - "execution_count": 1, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import sys\n", - "sys.path.insert(0, '..')\n", - "import zarr\n", - "import numpy as np\n", - "np.random.seed(42)\n", - "import cProfile\n", - "zarr.__version__" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Functionality and API" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Indexing a 1D array with a Boolean (mask) array\n", - "\n", - "Supported via ``get/set_mask_selection()`` and ``.vindex[]``. Also supported via ``get/set_orthogonal_selection()`` and ``.oindex[]``." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "a = np.arange(10)\n", - "za = zarr.array(a, chunks=2)\n", - "ix = [False, True, False, True, False, True, False, True, False, True]" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([1, 3, 5, 7, 9])" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# get items\n", - "za.vindex[ix]" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([1, 3, 5, 7, 9])" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# get items\n", - "za.oindex[ix]" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([ 0, 10, 2, 30, 4, 50, 6, 70, 8, 90])" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# set items\n", - "za.vindex[ix] = a[ix] * 10\n", - "za[:]" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([ 0, 100, 2, 300, 4, 500, 6, 700, 8, 900])" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# set items\n", - "za.oindex[ix] = a[ix] * 100\n", - "za[:]" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([1, 3, 5, 7, 9])" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# if using .oindex, indexing array can be any array-like, e.g., Zarr array\n", - "zix = zarr.array(ix, chunks=2)\n", - "za = zarr.array(a, chunks=2)\n", - "za.oindex[zix] # will not load all zix into memory" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Indexing a 1D array with a 1D integer (coordinate) array\n", - "\n", - "Supported via ``get/set_coordinate_selection()`` and ``.vindex[]``. Also supported via ``get/set_orthogonal_selection()`` and ``.oindex[]``." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "a = np.arange(10)\n", - "za = zarr.array(a, chunks=2)\n", - "ix = [1, 3, 5, 7, 9]" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([1, 3, 5, 7, 9])" - ] - }, - "execution_count": 9, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# get items\n", - "za.vindex[ix]" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([1, 3, 5, 7, 9])" - ] - }, - "execution_count": 10, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# get items\n", - "za.oindex[ix]" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([ 0, 10, 2, 30, 4, 50, 6, 70, 8, 90])" - ] - }, - "execution_count": 11, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# set items\n", - "za.vindex[ix] = a[ix] * 10\n", - "za[:]" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([ 0, 100, 2, 300, 4, 500, 6, 700, 8, 900])" - ] - }, - "execution_count": 12, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# set items\n", - "za.oindex[ix] = a[ix] * 100\n", - "za[:]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Indexing a 1D array with a multi-dimensional integer (coordinate) array\n", - "\n", - "Supported via ``get/set_coordinate_selection()`` and ``.vindex[]``." - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [], - "source": [ - "a = np.arange(10)\n", - "za = zarr.array(a, chunks=2)\n", - "ix = np.array([[1, 3, 5], [2, 4, 6]])" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[1, 3, 5],\n", - " [2, 4, 6]])" - ] - }, - "execution_count": 14, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# get items\n", - "za.vindex[ix]" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([ 0, 10, 20, 30, 40, 50, 60, 7, 8, 9])" - ] - }, - "execution_count": 15, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# set items\n", - "za.vindex[ix] = a[ix] * 10\n", - "za[:]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Slicing a 1D array with step > 1\n", - "\n", - "Slices with step > 1 are supported via ``get/set_basic_selection()``, ``get/set_orthogonal_selection()``, ``__getitem__`` and ``.oindex[]``. Negative steps are not supported." - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [], - "source": [ - "a = np.arange(10)\n", - "za = zarr.array(a, chunks=2)" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([1, 3, 5, 7, 9])" - ] - }, - "execution_count": 17, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# get items\n", - "za[1::2]" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([ 0, 10, 2, 30, 4, 50, 6, 70, 8, 90])" - ] - }, - "execution_count": 18, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# set items\n", - "za.oindex[1::2] = a[1::2] * 10\n", - "za[:]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Orthogonal (outer) indexing of multi-dimensional arrays\n", - "\n", - "Orthogonal (a.k.a. outer) indexing is supported with either Boolean or integer arrays, in combination with integers and slices. This functionality is provided via the ``get/set_orthogonal_selection()`` methods. For convenience, this functionality is also available via the ``.oindex[]`` property." - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 0, 1, 2],\n", - " [ 3, 4, 5],\n", - " [ 6, 7, 8],\n", - " [ 9, 10, 11],\n", - " [12, 13, 14]])" - ] - }, - "execution_count": 19, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = np.arange(15).reshape(5, 3)\n", - "za = zarr.array(a, chunks=(3, 2))\n", - "za[:]" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 3, 5],\n", - " [ 9, 11]])" - ] - }, - "execution_count": 20, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# orthogonal indexing with Boolean arrays\n", - "ix0 = [False, True, False, True, False]\n", - "ix1 = [True, False, True]\n", - "za.get_orthogonal_selection((ix0, ix1))" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 3, 5],\n", - " [ 9, 11]])" - ] - }, - "execution_count": 21, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# alternative API\n", - "za.oindex[ix0, ix1]" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 3, 5],\n", - " [ 9, 11]])" - ] - }, - "execution_count": 22, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# orthogonal indexing with integer arrays\n", - "ix0 = [1, 3]\n", - "ix1 = [0, 2]\n", - "za.get_orthogonal_selection((ix0, ix1))" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 3, 5],\n", - " [ 9, 11]])" - ] - }, - "execution_count": 23, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# alternative API\n", - "za.oindex[ix0, ix1]" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 3, 4, 5],\n", - " [ 9, 10, 11]])" - ] - }, - "execution_count": 24, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# combine with slice\n", - "za.oindex[[1, 3], :]" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 0, 2],\n", - " [ 3, 5],\n", - " [ 6, 8],\n", - " [ 9, 11],\n", - " [12, 14]])" - ] - }, - "execution_count": 25, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# combine with slice\n", - "za.oindex[:, [0, 2]]" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 0, 1, 2],\n", - " [42, 4, 42],\n", - " [ 6, 7, 8],\n", - " [42, 10, 42],\n", - " [12, 13, 14]])" - ] - }, - "execution_count": 26, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# set items via Boolean selection\n", - "ix0 = [False, True, False, True, False]\n", - "ix1 = [True, False, True]\n", - "selection = ix0, ix1\n", - "value = 42\n", - "za.set_orthogonal_selection(selection, value)\n", - "za[:]" - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 0, 1, 2],\n", - " [44, 4, 44],\n", - " [ 6, 7, 8],\n", - " [44, 10, 44],\n", - " [12, 13, 14]])" - ] - }, - "execution_count": 27, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# alternative API\n", - "za.oindex[ix0, ix1] = 44\n", - "za[:]" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 0, 1, 2],\n", - " [46, 4, 46],\n", - " [ 6, 7, 8],\n", - " [46, 10, 46],\n", - " [12, 13, 14]])" - ] - }, - "execution_count": 28, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# set items via integer selection\n", - "ix0 = [1, 3]\n", - "ix1 = [0, 2]\n", - "selection = ix0, ix1\n", - "value = 46\n", - "za.set_orthogonal_selection(selection, value)\n", - "za[:]" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 0, 1, 2],\n", - " [48, 4, 48],\n", - " [ 6, 7, 8],\n", - " [48, 10, 48],\n", - " [12, 13, 14]])" - ] - }, - "execution_count": 29, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# alternative API\n", - "za.oindex[ix0, ix1] = 48\n", - "za[:]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Coordinate indexing of multi-dimensional arrays\n", - "\n", - "Selecting arbitrary points from a multi-dimensional array by indexing with integer (coordinate) arrays is supported. This functionality is provided via the ``get/set_coordinate_selection()`` methods. For convenience, this functionality is also available via the ``.vindex[]`` property." - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 0, 1, 2],\n", - " [ 3, 4, 5],\n", - " [ 6, 7, 8],\n", - " [ 9, 10, 11],\n", - " [12, 13, 14]])" - ] - }, - "execution_count": 30, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = np.arange(15).reshape(5, 3)\n", - "za = zarr.array(a, chunks=(3, 2))\n", - "za[:]" - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([ 3, 11])" - ] - }, - "execution_count": 31, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# get items\n", - "ix0 = [1, 3]\n", - "ix1 = [0, 2]\n", - "za.get_coordinate_selection((ix0, ix1))" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([ 3, 11])" - ] - }, - "execution_count": 32, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# alternative API\n", - "za.vindex[ix0, ix1]" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 0, 1, 2],\n", - " [42, 4, 5],\n", - " [ 6, 7, 8],\n", - " [ 9, 10, 42],\n", - " [12, 13, 14]])" - ] - }, - "execution_count": 33, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# set items\n", - "za.set_coordinate_selection((ix0, ix1), 42)\n", - "za[:]" - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 0, 1, 2],\n", - " [44, 4, 5],\n", - " [ 6, 7, 8],\n", - " [ 9, 10, 44],\n", - " [12, 13, 14]])" - ] - }, - "execution_count": 34, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# alternative API\n", - "za.vindex[ix0, ix1] = 44\n", - "za[:]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Mask indexing of multi-dimensional arrays\n", - "\n", - "Selecting arbitrary points from a multi-dimensional array by a Boolean array is supported. This functionality is provided via the ``get/set_mask_selection()`` methods. For convenience, this functionality is also available via the ``.vindex[]`` property." - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 0, 1, 2],\n", - " [ 3, 4, 5],\n", - " [ 6, 7, 8],\n", - " [ 9, 10, 11],\n", - " [12, 13, 14]])" - ] - }, - "execution_count": 35, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = np.arange(15).reshape(5, 3)\n", - "za = zarr.array(a, chunks=(3, 2))\n", - "za[:]" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([ 3, 11])" - ] - }, - "execution_count": 36, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ix = np.zeros_like(a, dtype=bool)\n", - "ix[1, 0] = True\n", - "ix[3, 2] = True\n", - "za.get_mask_selection(ix)" - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([ 3, 11])" - ] - }, - "execution_count": 37, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "za.vindex[ix]" - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 0, 1, 2],\n", - " [42, 4, 5],\n", - " [ 6, 7, 8],\n", - " [ 9, 10, 42],\n", - " [12, 13, 14]])" - ] - }, - "execution_count": 38, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "za.set_mask_selection(ix, 42)\n", - "za[:]" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([[ 0, 1, 2],\n", - " [44, 4, 5],\n", - " [ 6, 7, 8],\n", - " [ 9, 10, 44],\n", - " [12, 13, 14]])" - ] - }, - "execution_count": 39, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "za.vindex[ix] = 44\n", - "za[:]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Selecting fields from arrays with a structured dtype\n", - "\n", - "All ``get/set_selection_...()`` methods support a ``fields`` argument which allows retrieving/replacing data for a specific field or fields. Also h5py-like API is supported where fields can be provided within ``__getitem__``, ``.oindex[]`` and ``.vindex[]``." - ] - }, - { - "cell_type": "code", - "execution_count": 42, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([(b'aaa', 1, 4.2), (b'bbb', 2, 8.4), (b'ccc', 3, 12.6)],\n", - " dtype=[('foo', 'S3'), ('bar', '\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0ma\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'foo'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'baz'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[0;31mIndexError\u001b[0m: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices" - ] - } - ], - "source": [ - "a['foo', 'baz']" - ] - }, - { - "cell_type": "code", - "execution_count": 52, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([(b'aaa', 4.2), (b'bbb', 8.4), (b'ccc', 12.6)],\n", - " dtype=[('foo', 'S3'), ('baz', '", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mza\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'foo'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'baz'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36m__getitem__\u001b[0;34m(self, selection)\u001b[0m\n\u001b[1;32m 537\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 538\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mselection\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mpop_fields\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mselection\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 539\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_basic_selection\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mselection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfields\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 540\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 541\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mget_basic_selection\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mselection\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mEllipsis\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mout\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36mget_basic_selection\u001b[0;34m(self, selection, out, fields)\u001b[0m\n\u001b[1;32m 661\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_get_basic_selection_zd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mselection\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mselection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mout\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mout\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfields\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 662\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 663\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_get_basic_selection_nd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mselection\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mselection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mout\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mout\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfields\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 664\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 665\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m_get_basic_selection_zd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mselection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mout\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36m_get_basic_selection_nd\u001b[0;34m(self, selection, out, fields)\u001b[0m\n\u001b[1;32m 701\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 702\u001b[0m \u001b[0;31m# setup indexer\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 703\u001b[0;31m \u001b[0mindexer\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mBasicIndexer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mselection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 704\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 705\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_get_selection\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mindexer\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mindexer\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mout\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mout\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfields\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/indexing.py\u001b[0m in \u001b[0;36m__init__\u001b[0;34m(self, selection, array)\u001b[0m\n\u001b[1;32m 275\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 276\u001b[0m raise IndexError('unsupported selection item for basic indexing; expected integer '\n\u001b[0;32m--> 277\u001b[0;31m 'or slice, got {!r}'.format(type(dim_sel)))\n\u001b[0m\u001b[1;32m 278\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 279\u001b[0m \u001b[0mdim_indexers\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdim_indexer\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mIndexError\u001b[0m: unsupported selection item for basic indexing; expected integer or slice, got " - ] - } - ], - "source": [ - "za[['foo', 'baz']]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 1D Benchmarking" - ] - }, - { - "cell_type": "code", - "execution_count": 53, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "800000000" - ] - }, - "execution_count": 53, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "c = np.arange(100000000)\n", - "c.nbytes" - ] - }, - { - "cell_type": "code", - "execution_count": 54, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 480 ms, sys: 16 ms, total: 496 ms\n", - "Wall time: 141 ms\n" - ] - }, - { - "data": { - "text/html": [ - "
Typezarr.core.Array
Data typeint64
Shape(100000000,)
Chunk shape(97657,)
OrderC
Read-onlyFalse
CompressorBlosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store typebuiltins.dict
No. bytes800000000 (762.9M)
No. bytes stored11854081 (11.3M)
Storage ratio67.5
Chunks initialized1024/1024
" - ], - "text/plain": [ - "Type : zarr.core.Array\n", - "Data type : int64\n", - "Shape : (100000000,)\n", - "Chunk shape : (97657,)\n", - "Order : C\n", - "Read-only : False\n", - "Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)\n", - "Store type : builtins.dict\n", - "No. bytes : 800000000 (762.9M)\n", - "No. bytes stored : 11854081 (11.3M)\n", - "Storage ratio : 67.5\n", - "Chunks initialized : 1024/1024" - ] - }, - "execution_count": 54, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "%time zc = zarr.array(c)\n", - "zc.info" - ] - }, - { - "cell_type": "code", - "execution_count": 55, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "121 ms Β± 1.49 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit c.copy()" - ] - }, - { - "cell_type": "code", - "execution_count": 56, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "254 ms Β± 942 Β΅s per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit zc[:]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### bool dense selection" - ] - }, - { - "cell_type": "code", - "execution_count": 57, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "9997476" - ] - }, - "execution_count": 57, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# relatively dense selection - 10%\n", - "ix_dense_bool = np.random.binomial(1, 0.1, size=c.shape[0]).astype(bool)\n", - "np.count_nonzero(ix_dense_bool)" - ] - }, - { - "cell_type": "code", - "execution_count": 58, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "243 ms Β± 5.8 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit c[ix_dense_bool]" - ] - }, - { - "cell_type": "code", - "execution_count": 59, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "433 ms Β± 6.49 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit zc.oindex[ix_dense_bool]" - ] - }, - { - "cell_type": "code", - "execution_count": 60, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "548 ms Β± 5.2 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit zc.vindex[ix_dense_bool]" - ] - }, - { - "cell_type": "code", - "execution_count": 61, - "metadata": {}, - "outputs": [], - "source": [ - "import tempfile\n", - "import cProfile\n", - "import pstats\n", - "\n", - "def profile(statement, sort='time', restrictions=(7,)):\n", - " with tempfile.NamedTemporaryFile() as f:\n", - " cProfile.run(statement, filename=f.name)\n", - " pstats.Stats(f.name).sort_stats(sort).print_stats(*restrictions)\n" - ] - }, - { - "cell_type": "code", - "execution_count": 62, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Wed Nov 8 17:17:48 2017 /tmp/tmpruua2rs_\n", - "\n", - " 98386 function calls in 0.483 seconds\n", - "\n", - " Ordered by: internal time\n", - " List reduced from 83 to 7 due to restriction <7>\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - " 1025 0.197 0.000 0.197 0.000 {method 'nonzero' of 'numpy.ndarray' objects}\n", - " 1024 0.149 0.000 0.159 0.000 ../zarr/core.py:1028(_decode_chunk)\n", - " 1024 0.044 0.000 0.231 0.000 ../zarr/core.py:849(_chunk_getitem)\n", - " 1024 0.009 0.000 0.009 0.000 {built-in method numpy.core.multiarray.count_nonzero}\n", - " 1025 0.007 0.000 0.238 0.000 ../zarr/indexing.py:541(__iter__)\n", - " 1024 0.006 0.000 0.207 0.000 /home/aliman/pyenv/zarr_20171023/lib/python3.6/site-packages/numpy/lib/index_tricks.py:26(ix_)\n", - " 2048 0.005 0.000 0.005 0.000 ../zarr/core.py:337()\n", - "\n", - "\n" - ] - } - ], - "source": [ - "profile('zc.oindex[ix_dense_bool]')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Method ``nonzero`` is being called internally within numpy to convert bool to int selections, no way to avoid." - ] - }, - { - "cell_type": "code", - "execution_count": 63, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Wed Nov 8 17:18:06 2017 /tmp/tmp7_bautep\n", - "\n", - " 52382 function calls in 0.592 seconds\n", - "\n", - " Ordered by: internal time\n", - " List reduced from 88 to 7 due to restriction <7>\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - " 2 0.219 0.110 0.219 0.110 {method 'nonzero' of 'numpy.ndarray' objects}\n", - " 1024 0.096 0.000 0.101 0.000 ../zarr/core.py:1028(_decode_chunk)\n", - " 2 0.094 0.047 0.094 0.047 ../zarr/indexing.py:630()\n", - " 1024 0.044 0.000 0.167 0.000 ../zarr/core.py:849(_chunk_getitem)\n", - " 1 0.029 0.029 0.029 0.029 {built-in method numpy.core.multiarray.ravel_multi_index}\n", - " 1 0.023 0.023 0.023 0.023 {built-in method numpy.core.multiarray.bincount}\n", - " 1 0.021 0.021 0.181 0.181 ../zarr/indexing.py:603(__init__)\n", - "\n", - "\n" - ] - } - ], - "source": [ - "profile('zc.vindex[ix_dense_bool]')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "``.vindex[]`` is a bit slower, possibly because internally it converts to a coordinate array first." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### int dense selection" - ] - }, - { - "cell_type": "code", - "execution_count": 64, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "10000000" - ] - }, - "execution_count": 64, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ix_dense_int = np.random.choice(c.shape[0], size=c.shape[0]//10, replace=True)\n", - "ix_dense_int_sorted = ix_dense_int.copy()\n", - "ix_dense_int_sorted.sort()\n", - "len(ix_dense_int)" - ] - }, - { - "cell_type": "code", - "execution_count": 65, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "62.2 ms Β± 2.36 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit c[ix_dense_int_sorted]" - ] - }, - { - "cell_type": "code", - "execution_count": 66, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "355 ms Β± 3.53 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit zc.oindex[ix_dense_int_sorted]" - ] - }, - { - "cell_type": "code", - "execution_count": 67, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "351 ms Β± 3.51 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit zc.vindex[ix_dense_int_sorted]" - ] - }, - { - "cell_type": "code", - "execution_count": 68, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "128 ms Β± 137 Β΅s per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit c[ix_dense_int]" - ] - }, - { - "cell_type": "code", - "execution_count": 69, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1.71 s Β± 5.1 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit zc.oindex[ix_dense_int]" - ] - }, - { - "cell_type": "code", - "execution_count": 70, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1.68 s Β± 3.87 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit zc.vindex[ix_dense_int]" - ] - }, - { - "cell_type": "code", - "execution_count": 71, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Wed Nov 8 17:19:09 2017 /tmp/tmpgmu5btr_\n", - "\n", - " 95338 function calls in 0.424 seconds\n", - "\n", - " Ordered by: internal time\n", - " List reduced from 89 to 7 due to restriction <7>\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - " 1 0.141 0.141 0.184 0.184 ../zarr/indexing.py:369(__init__)\n", - " 1024 0.099 0.000 0.106 0.000 ../zarr/core.py:1028(_decode_chunk)\n", - " 1024 0.046 0.000 0.175 0.000 ../zarr/core.py:849(_chunk_getitem)\n", - " 1025 0.027 0.000 0.027 0.000 ../zarr/indexing.py:424(__iter__)\n", - " 1 0.023 0.023 0.023 0.023 {built-in method numpy.core.multiarray.bincount}\n", - " 1 0.010 0.010 0.010 0.010 /home/aliman/pyenv/zarr_20171023/lib/python3.6/site-packages/numpy/lib/function_base.py:1848(diff)\n", - " 1025 0.006 0.000 0.059 0.000 ../zarr/indexing.py:541(__iter__)\n", - "\n", - "\n" - ] - } - ], - "source": [ - "profile('zc.oindex[ix_dense_int_sorted]')" - ] - }, - { - "cell_type": "code", - "execution_count": 72, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Wed Nov 8 17:19:13 2017 /tmp/tmpay1gvnx8\n", - "\n", - " 52362 function calls in 0.398 seconds\n", - "\n", - " Ordered by: internal time\n", - " List reduced from 85 to 7 due to restriction <7>\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - " 2 0.107 0.054 0.107 0.054 ../zarr/indexing.py:630()\n", - " 1024 0.091 0.000 0.096 0.000 ../zarr/core.py:1028(_decode_chunk)\n", - " 1024 0.041 0.000 0.160 0.000 ../zarr/core.py:849(_chunk_getitem)\n", - " 1 0.040 0.040 0.213 0.213 ../zarr/indexing.py:603(__init__)\n", - " 1 0.029 0.029 0.029 0.029 {built-in method numpy.core.multiarray.ravel_multi_index}\n", - " 1 0.023 0.023 0.023 0.023 {built-in method numpy.core.multiarray.bincount}\n", - " 2048 0.011 0.000 0.011 0.000 ../zarr/indexing.py:695()\n", - "\n", - "\n" - ] - } - ], - "source": [ - "profile('zc.vindex[ix_dense_int_sorted]')" - ] - }, - { - "cell_type": "code", - "execution_count": 73, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Wed Nov 8 17:19:20 2017 /tmp/tmpngsf6zpp\n", - "\n", - " 120946 function calls in 1.793 seconds\n", - "\n", - " Ordered by: internal time\n", - " List reduced from 92 to 7 due to restriction <7>\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - " 1 1.128 1.128 1.128 1.128 {method 'argsort' of 'numpy.ndarray' objects}\n", - " 1024 0.139 0.000 0.285 0.000 ../zarr/core.py:849(_chunk_getitem)\n", - " 1 0.132 0.132 1.422 1.422 ../zarr/indexing.py:369(__init__)\n", - " 1 0.120 0.120 0.120 0.120 {method 'take' of 'numpy.ndarray' objects}\n", - " 1024 0.116 0.000 0.123 0.000 ../zarr/core.py:1028(_decode_chunk)\n", - " 1025 0.034 0.000 0.034 0.000 ../zarr/indexing.py:424(__iter__)\n", - " 1 0.023 0.023 0.023 0.023 {built-in method numpy.core.multiarray.bincount}\n", - "\n", - "\n" - ] - } - ], - "source": [ - "profile('zc.oindex[ix_dense_int]')" - ] - }, - { - "cell_type": "code", - "execution_count": 74, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Wed Nov 8 17:19:22 2017 /tmp/tmpbskhj8de\n", - "\n", - " 50320 function calls in 1.730 seconds\n", - "\n", - " Ordered by: internal time\n", - " List reduced from 86 to 7 due to restriction <7>\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - " 1 1.116 1.116 1.116 1.116 {method 'argsort' of 'numpy.ndarray' objects}\n", - " 1024 0.133 0.000 0.275 0.000 ../zarr/core.py:849(_chunk_getitem)\n", - " 2 0.121 0.060 0.121 0.060 ../zarr/indexing.py:654()\n", - " 1024 0.113 0.000 0.119 0.000 ../zarr/core.py:1028(_decode_chunk)\n", - " 2 0.100 0.050 0.100 0.050 ../zarr/indexing.py:630()\n", - " 1 0.030 0.030 0.030 0.030 {built-in method numpy.core.multiarray.ravel_multi_index}\n", - " 1 0.024 0.024 1.427 1.427 ../zarr/indexing.py:603(__init__)\n", - "\n", - "\n" - ] - } - ], - "source": [ - "profile('zc.vindex[ix_dense_int]')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "When indices are not sorted, zarr needs to partially sort them so the occur in chunk order, so we only have to visit each chunk once. This sorting dominates the processing time and is unavoidable AFAIK." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### bool sparse selection" - ] - }, - { - "cell_type": "code", - "execution_count": 75, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "9932" - ] - }, - "execution_count": 75, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# relatively sparse selection\n", - "ix_sparse_bool = np.random.binomial(1, 0.0001, size=c.shape[0]).astype(bool)\n", - "np.count_nonzero(ix_sparse_bool)" - ] - }, - { - "cell_type": "code", - "execution_count": 76, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "15.7 ms Β± 38.5 Β΅s per loop (mean Β± std. dev. of 7 runs, 100 loops each)\n" - ] - } - ], - "source": [ - "%timeit c[ix_sparse_bool]" - ] - }, - { - "cell_type": "code", - "execution_count": 77, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "156 ms Β± 2.1 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit zc.oindex[ix_sparse_bool]" - ] - }, - { - "cell_type": "code", - "execution_count": 78, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "133 ms Β± 2.76 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit zc.vindex[ix_sparse_bool]" - ] - }, - { - "cell_type": "code", - "execution_count": 79, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Wed Nov 8 17:20:09 2017 /tmp/tmpb7nqc9ax\n", - "\n", - " 98386 function calls in 0.191 seconds\n", - "\n", - " Ordered by: internal time\n", - " List reduced from 83 to 7 due to restriction <7>\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - " 1024 0.093 0.000 0.098 0.000 ../zarr/core.py:1028(_decode_chunk)\n", - " 1025 0.017 0.000 0.017 0.000 {method 'nonzero' of 'numpy.ndarray' objects}\n", - " 1024 0.007 0.000 0.007 0.000 {built-in method numpy.core.multiarray.count_nonzero}\n", - " 1024 0.007 0.000 0.129 0.000 ../zarr/core.py:849(_chunk_getitem)\n", - " 1025 0.005 0.000 0.052 0.000 ../zarr/indexing.py:541(__iter__)\n", - " 1024 0.005 0.000 0.025 0.000 /home/aliman/pyenv/zarr_20171023/lib/python3.6/site-packages/numpy/lib/index_tricks.py:26(ix_)\n", - " 2048 0.004 0.000 0.004 0.000 ../zarr/core.py:337()\n", - "\n", - "\n" - ] - } - ], - "source": [ - "profile('zc.oindex[ix_sparse_bool]')" - ] - }, - { - "cell_type": "code", - "execution_count": 80, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Wed Nov 8 17:20:09 2017 /tmp/tmphsko8nvh\n", - "\n", - " 52382 function calls in 0.160 seconds\n", - "\n", - " Ordered by: internal time\n", - " List reduced from 88 to 7 due to restriction <7>\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - " 1024 0.093 0.000 0.098 0.000 ../zarr/core.py:1028(_decode_chunk)\n", - " 2 0.017 0.008 0.017 0.008 {method 'nonzero' of 'numpy.ndarray' objects}\n", - " 1025 0.008 0.000 0.014 0.000 ../zarr/indexing.py:674(__iter__)\n", - " 1024 0.006 0.000 0.127 0.000 ../zarr/core.py:849(_chunk_getitem)\n", - " 2048 0.004 0.000 0.004 0.000 ../zarr/indexing.py:695()\n", - " 2054 0.003 0.000 0.003 0.000 ../zarr/core.py:337()\n", - " 1024 0.002 0.000 0.005 0.000 /home/aliman/pyenv/zarr_20171023/lib/python3.6/site-packages/numpy/core/arrayprint.py:381(wrapper)\n", - "\n", - "\n" - ] - } - ], - "source": [ - "profile('zc.vindex[ix_sparse_bool]')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### int sparse selection" - ] - }, - { - "cell_type": "code", - "execution_count": 81, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "10000" - ] - }, - "execution_count": 81, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ix_sparse_int = np.random.choice(c.shape[0], size=c.shape[0]//10000, replace=True)\n", - "ix_sparse_int_sorted = ix_sparse_int.copy()\n", - "ix_sparse_int_sorted.sort()\n", - "len(ix_sparse_int)" - ] - }, - { - "cell_type": "code", - "execution_count": 82, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "18.9 Β΅s Β± 392 ns per loop (mean Β± std. dev. of 7 runs, 10000 loops each)\n" - ] - } - ], - "source": [ - "%timeit c[ix_sparse_int_sorted]" - ] - }, - { - "cell_type": "code", - "execution_count": 83, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "20.3 Β΅s Β± 155 ns per loop (mean Β± std. dev. of 7 runs, 10000 loops each)\n" - ] - } - ], - "source": [ - "%timeit c[ix_sparse_int]" - ] - }, - { - "cell_type": "code", - "execution_count": 84, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "125 ms Β± 296 Β΅s per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit zc.oindex[ix_sparse_int_sorted]" - ] - }, - { - "cell_type": "code", - "execution_count": 85, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "109 ms Β± 428 Β΅s per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit zc.vindex[ix_sparse_int_sorted]" - ] - }, - { - "cell_type": "code", - "execution_count": 86, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "132 ms Β± 489 Β΅s per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit zc.oindex[ix_sparse_int]" - ] - }, - { - "cell_type": "code", - "execution_count": 87, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "108 ms Β± 579 Β΅s per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit zc.vindex[ix_sparse_int]" - ] - }, - { - "cell_type": "code", - "execution_count": 88, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Wed Nov 8 17:21:12 2017 /tmp/tmp0b0o2quo\n", - "\n", - " 120946 function calls in 0.196 seconds\n", - "\n", - " Ordered by: internal time\n", - " List reduced from 92 to 7 due to restriction <7>\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - " 1024 0.105 0.000 0.111 0.000 ../zarr/core.py:1028(_decode_chunk)\n", - " 2048 0.006 0.000 0.013 0.000 /home/aliman/pyenv/zarr_20171023/lib/python3.6/site-packages/numpy/lib/index_tricks.py:26(ix_)\n", - " 1025 0.006 0.000 0.051 0.000 ../zarr/indexing.py:541(__iter__)\n", - " 1024 0.006 0.000 0.141 0.000 ../zarr/core.py:849(_chunk_getitem)\n", - " 2048 0.005 0.000 0.005 0.000 ../zarr/core.py:337()\n", - " 15373 0.004 0.000 0.010 0.000 {built-in method builtins.isinstance}\n", - " 1025 0.004 0.000 0.005 0.000 ../zarr/indexing.py:424(__iter__)\n", - "\n", - "\n" - ] - } - ], - "source": [ - "profile('zc.oindex[ix_sparse_int]')" - ] - }, - { - "cell_type": "code", - "execution_count": 89, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Wed Nov 8 17:21:19 2017 /tmp/tmpdwju98kn\n", - "\n", - " 50320 function calls in 0.167 seconds\n", - "\n", - " Ordered by: internal time\n", - " List reduced from 86 to 7 due to restriction <7>\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - " 1024 0.105 0.000 0.111 0.000 ../zarr/core.py:1028(_decode_chunk)\n", - " 1025 0.009 0.000 0.017 0.000 ../zarr/indexing.py:674(__iter__)\n", - " 1024 0.006 0.000 0.142 0.000 ../zarr/core.py:849(_chunk_getitem)\n", - " 2048 0.005 0.000 0.005 0.000 ../zarr/indexing.py:695()\n", - " 2054 0.004 0.000 0.004 0.000 ../zarr/core.py:337()\n", - " 1 0.003 0.003 0.162 0.162 ../zarr/core.py:591(_get_selection)\n", - " 1027 0.003 0.000 0.003 0.000 {method 'reshape' of 'numpy.ndarray' objects}\n", - "\n", - "\n" - ] - } - ], - "source": [ - "profile('zc.vindex[ix_sparse_int]')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For sparse selections, processing time is dominated by decompression, so we can't do any better." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### sparse bool selection as zarr array" - ] - }, - { - "cell_type": "code", - "execution_count": 90, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
Typezarr.core.Array
Data typebool
Shape(100000000,)
Chunk shape(390625,)
OrderC
Read-onlyFalse
CompressorBlosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store typebuiltins.dict
No. bytes100000000 (95.4M)
No. bytes stored507131 (495.2K)
Storage ratio197.2
Chunks initialized256/256
" - ], - "text/plain": [ - "Type : zarr.core.Array\n", - "Data type : bool\n", - "Shape : (100000000,)\n", - "Chunk shape : (390625,)\n", - "Order : C\n", - "Read-only : False\n", - "Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)\n", - "Store type : builtins.dict\n", - "No. bytes : 100000000 (95.4M)\n", - "No. bytes stored : 507131 (495.2K)\n", - "Storage ratio : 197.2\n", - "Chunks initialized : 256/256" - ] - }, - "execution_count": 90, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "zix_sparse_bool = zarr.array(ix_sparse_bool)\n", - "zix_sparse_bool.info" - ] - }, - { - "cell_type": "code", - "execution_count": 91, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "387 ms Β± 5.47 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit zc.oindex[zix_sparse_bool]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### slice with step" - ] - }, - { - "cell_type": "code", - "execution_count": 92, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "80.3 ms Β± 377 Β΅s per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit np.array(c[::2])" - ] - }, - { - "cell_type": "code", - "execution_count": 93, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "168 ms Β± 837 Β΅s per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit zc[::2]" - ] - }, - { - "cell_type": "code", - "execution_count": 94, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "136 ms Β± 1.56 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit zc[::10]" - ] - }, - { - "cell_type": "code", - "execution_count": 95, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "104 ms Β± 1.86 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit zc[::100]" - ] - }, - { - "cell_type": "code", - "execution_count": 96, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "100 ms Β± 1.47 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit zc[::1000]" - ] - }, - { - "cell_type": "code", - "execution_count": 97, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Wed Nov 8 17:22:44 2017 /tmp/tmpg9dxqcpg\n", - "\n", - " 49193 function calls in 0.211 seconds\n", - "\n", - " Ordered by: internal time\n", - " List reduced from 55 to 7 due to restriction <7>\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - " 1024 0.104 0.000 0.110 0.000 ../zarr/core.py:1028(_decode_chunk)\n", - " 1024 0.067 0.000 0.195 0.000 ../zarr/core.py:849(_chunk_getitem)\n", - " 1025 0.005 0.000 0.013 0.000 ../zarr/indexing.py:278(__iter__)\n", - " 2048 0.004 0.000 0.004 0.000 ../zarr/core.py:337()\n", - " 2050 0.003 0.000 0.003 0.000 ../zarr/indexing.py:90(ceildiv)\n", - " 1025 0.003 0.000 0.006 0.000 ../zarr/indexing.py:109(__iter__)\n", - " 1024 0.003 0.000 0.003 0.000 {method 'reshape' of 'numpy.ndarray' objects}\n", - "\n", - "\n" - ] - } - ], - "source": [ - "profile('zc[::2]')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 2D Benchmarking" - ] - }, - { - "cell_type": "code", - "execution_count": 99, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(100000000,)" - ] - }, - "execution_count": 99, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "c.shape" - ] - }, - { - "cell_type": "code", - "execution_count": 100, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(100000, 1000)" - ] - }, - "execution_count": 100, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "d = c.reshape(-1, 1000)\n", - "d.shape" - ] - }, - { - "cell_type": "code", - "execution_count": 101, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
Typezarr.core.Array
Data typeint64
Shape(100000, 1000)
Chunk shape(3125, 32)
OrderC
Read-onlyFalse
CompressorBlosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store typebuiltins.dict
No. bytes800000000 (762.9M)
No. bytes stored39228864 (37.4M)
Storage ratio20.4
Chunks initialized1024/1024
" - ], - "text/plain": [ - "Type : zarr.core.Array\n", - "Data type : int64\n", - "Shape : (100000, 1000)\n", - "Chunk shape : (3125, 32)\n", - "Order : C\n", - "Read-only : False\n", - "Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)\n", - "Store type : builtins.dict\n", - "No. bytes : 800000000 (762.9M)\n", - "No. bytes stored : 39228864 (37.4M)\n", - "Storage ratio : 20.4\n", - "Chunks initialized : 1024/1024" - ] - }, - "execution_count": 101, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "zd = zarr.array(d)\n", - "zd.info" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### bool orthogonal selection" - ] - }, - { - "cell_type": "code", - "execution_count": 102, - "metadata": {}, - "outputs": [], - "source": [ - "ix0 = np.random.binomial(1, 0.5, size=d.shape[0]).astype(bool)\n", - "ix1 = np.random.binomial(1, 0.5, size=d.shape[1]).astype(bool)" - ] - }, - { - "cell_type": "code", - "execution_count": 103, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "101 ms Β± 577 Β΅s per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit d[np.ix_(ix0, ix1)]" - ] - }, - { - "cell_type": "code", - "execution_count": 104, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "373 ms Β± 5.45 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit zd.oindex[ix0, ix1]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### int orthogonal selection" - ] - }, - { - "cell_type": "code", - "execution_count": 105, - "metadata": {}, - "outputs": [], - "source": [ - "ix0 = np.random.choice(d.shape[0], size=int(d.shape[0] * .5), replace=True)\n", - "ix1 = np.random.choice(d.shape[1], size=int(d.shape[1] * .5), replace=True)" - ] - }, - { - "cell_type": "code", - "execution_count": 106, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "174 ms Β± 4.13 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each)\n" - ] - } - ], - "source": [ - "%timeit d[np.ix_(ix0, ix1)]" - ] - }, - { - "cell_type": "code", - "execution_count": 107, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "566 ms Β± 12.9 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit zd.oindex[ix0, ix1]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### coordinate (point) selection" - ] - }, - { - "cell_type": "code", - "execution_count": 108, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "10000000" - ] - }, - "execution_count": 108, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "n = int(d.size * .1)\n", - "ix0 = np.random.choice(d.shape[0], size=n, replace=True)\n", - "ix1 = np.random.choice(d.shape[1], size=n, replace=True)\n", - "n" - ] - }, - { - "cell_type": "code", - "execution_count": 109, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "243 ms Β± 3.37 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit d[ix0, ix1]" - ] - }, - { - "cell_type": "code", - "execution_count": 110, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "2.03 s Β± 17 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit zd.vindex[ix0, ix1]" - ] - }, - { - "cell_type": "code", - "execution_count": 111, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Wed Nov 8 17:24:31 2017 /tmp/tmp7c68z70p\n", - "\n", - " 62673 function calls in 2.065 seconds\n", - "\n", - " Ordered by: internal time\n", - " List reduced from 88 to 7 due to restriction <7>\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - " 1 1.112 1.112 1.112 1.112 {method 'argsort' of 'numpy.ndarray' objects}\n", - " 3 0.244 0.081 0.244 0.081 ../zarr/indexing.py:654()\n", - " 3 0.193 0.064 0.193 0.064 ../zarr/indexing.py:630()\n", - " 1024 0.170 0.000 0.350 0.000 ../zarr/core.py:849(_chunk_getitem)\n", - " 1024 0.142 0.000 0.151 0.000 ../zarr/core.py:1028(_decode_chunk)\n", - " 1 0.044 0.044 0.044 0.044 {built-in method numpy.core.multiarray.ravel_multi_index}\n", - " 1 0.043 0.043 1.676 1.676 ../zarr/indexing.py:603(__init__)\n", - "\n", - "\n" - ] - } - ], - "source": [ - "profile('zd.vindex[ix0, ix1]')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Points need to be partially sorted so all points in the same chunk are grouped and processed together. This requires ``argsort`` which dominates time." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## h5py comparison\n", - "\n", - "N.B., not really fair because using slower compressor, but for interest..." - ] - }, - { - "cell_type": "code", - "execution_count": 65, - "metadata": {}, - "outputs": [], - "source": [ - "import h5py\n", - "import tempfile" - ] - }, - { - "cell_type": "code", - "execution_count": 78, - "metadata": {}, - "outputs": [], - "source": [ - "h5f = h5py.File(tempfile.mktemp(), driver='core', backing_store=False)" - ] - }, - { - "cell_type": "code", - "execution_count": 79, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 79, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "hc = h5f.create_dataset('c', data=c, compression='gzip', compression_opts=1, chunks=zc.chunks, shuffle=True)\n", - "hc" - ] - }, - { - "cell_type": "code", - "execution_count": 80, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 1.16 s, sys: 172 ms, total: 1.33 s\n", - "Wall time: 1.32 s\n" - ] - }, - { - "data": { - "text/plain": [ - "array([ 0, 1, 2, ..., 99999997, 99999998, 99999999])" - ] - }, - "execution_count": 80, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "%time hc[:]" - ] - }, - { - "cell_type": "code", - "execution_count": 81, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 1.11 s, sys: 0 ns, total: 1.11 s\n", - "Wall time: 1.11 s\n" - ] - }, - { - "data": { - "text/plain": [ - "array([ 1063, 28396, 37229, ..., 99955875, 99979354, 99995791])" - ] - }, - "execution_count": 81, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "%time hc[ix_sparse_bool]" - ] - }, - { - "cell_type": "code", - "execution_count": 82, - "metadata": {}, - "outputs": [], - "source": [ - "# # this is pathological, takes minutes \n", - "# %time hc[ix_dense_bool]" - ] - }, - { - "cell_type": "code", - "execution_count": 83, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 38.3 s, sys: 136 ms, total: 38.4 s\n", - "Wall time: 38.1 s\n" - ] - }, - { - "data": { - "text/plain": [ - "array([ 0, 1000, 2000, ..., 99997000, 99998000, 99999000])" - ] - }, - "execution_count": 83, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# this is pretty slow\n", - "%time hc[::1000]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/notebooks/blosc_microbench.ipynb b/notebooks/blosc_microbench.ipynb deleted file mode 100644 index 9361d8e95b..0000000000 --- a/notebooks/blosc_microbench.ipynb +++ /dev/null @@ -1,200 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "'2.0.1'" - ] - }, - "execution_count": 1, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import numpy as np\n", - "import zarr\n", - "zarr.__version__" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "10 loops, best of 3: 110 ms per loop\n", - "1 loop, best of 3: 235 ms per loop\n", - "Array((100000000,), int64, chunks=(200000,), order=C)\n", - " nbytes: 762.9M; nbytes_stored: 11.2M; ratio: 67.8; initialized: 500/500\n", - " compressor: Blosc(cname='lz4', clevel=5, shuffle=1)\n", - " store: dict\n" - ] - } - ], - "source": [ - "z = zarr.empty(shape=100000000, chunks=200000, dtype='i8')\n", - "data = np.arange(100000000, dtype='i8')\n", - "%timeit z[:] = data\n", - "%timeit z[:]\n", - "print(z)\n", - "assert np.all(z[:] == data)" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 loop, best of 3: 331 ms per loop\n", - "1 loop, best of 3: 246 ms per loop\n", - "Array((100000000,), float64, chunks=(200000,), order=C)\n", - " nbytes: 762.9M; nbytes_stored: 724.8M; ratio: 1.1; initialized: 500/500\n", - " compressor: Blosc(cname='lz4', clevel=5, shuffle=1)\n", - " store: dict\n" - ] - } - ], - "source": [ - "z = zarr.empty(shape=100000000, chunks=200000, dtype='f8')\n", - "data = np.random.normal(size=100000000)\n", - "%timeit z[:] = data\n", - "%timeit z[:]\n", - "print(z)\n", - "assert np.all(z[:] == data)" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "'2.0.2.dev0+dirty'" - ] - }, - "execution_count": 1, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import numpy as np\n", - "import sys\n", - "sys.path.insert(0, '..')\n", - "import zarr\n", - "zarr.__version__" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "10 loops, best of 3: 92.7 ms per loop\n", - "1 loop, best of 3: 230 ms per loop\n", - "Array((100000000,), int64, chunks=(200000,), order=C)\n", - " nbytes: 762.9M; nbytes_stored: 11.2M; ratio: 67.8; initialized: 500/500\n", - " compressor: Blosc(cname='lz4', clevel=5, shuffle=1)\n", - " store: dict\n" - ] - } - ], - "source": [ - "z = zarr.empty(shape=100000000, chunks=200000, dtype='i8')\n", - "data = np.arange(100000000, dtype='i8')\n", - "%timeit z[:] = data\n", - "%timeit z[:]\n", - "print(z)\n", - "assert np.all(z[:] == data)" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 loop, best of 3: 338 ms per loop\n", - "1 loop, best of 3: 253 ms per loop\n", - "Array((100000000,), float64, chunks=(200000,), order=C)\n", - " nbytes: 762.9M; nbytes_stored: 724.8M; ratio: 1.1; initialized: 500/500\n", - " compressor: Blosc(cname='lz4', clevel=5, shuffle=1)\n", - " store: dict\n" - ] - } - ], - "source": [ - "z = zarr.empty(shape=100000000, chunks=200000, dtype='f8')\n", - "data = np.random.normal(size=100000000)\n", - "%timeit z[:] = data\n", - "%timeit z[:]\n", - "print(z)\n", - "assert np.all(z[:] == data)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.5.1" - } - }, - "nbformat": 4, - "nbformat_minor": 1 -} diff --git a/notebooks/dask_2d_subset.ipynb b/notebooks/dask_2d_subset.ipynb deleted file mode 100644 index 6e88b510d5..0000000000 --- a/notebooks/dask_2d_subset.ipynb +++ /dev/null @@ -1,869 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This notebook has some profiling of Dask used to make a selection along both first and second axes of a large-ish multidimensional array. The use case is making selections of genotype data, e.g., as required for making a web-browser for genotype data as in www.malariagen.net/apps/ag1000g." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "zarr 2.1.1\n", - "dask 0.11.0\n" - ] - } - ], - "source": [ - "import zarr; print('zarr', zarr.__version__)\n", - "import dask; print('dask', dask.__version__)\n", - "import dask.array as da\n", - "import numpy as np" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Real data" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "Group(/, 8)\n", - " arrays: 1; samples\n", - " groups: 7; 2L, 2R, 3L, 3R, UNKN, X, Y_unplaced\n", - " store: DirectoryStore" - ] - }, - "execution_count": 2, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# here's the real data\n", - "callset = zarr.open_group('/kwiat/2/coluzzi/ag1000g/data/phase1/release/AR3.1/variation/main/zarr2/zstd/ag1000g.phase1.ar3',\n", - " mode='r')\n", - "callset" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "Array(/3R/calldata/genotype, (22632425, 765, 2), int8, chunks=(13107, 40, 2), order=C)\n", - " nbytes: 32.2G; nbytes_stored: 1.0G; ratio: 31.8; initialized: 34540/34540\n", - " compressor: Blosc(cname='zstd', clevel=1, shuffle=2)\n", - " store: DirectoryStore" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# here's the array we're going to work with\n", - "g = callset['3R/calldata/genotype']\n", - "g" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 4 ms, sys: 0 ns, total: 4 ms\n", - "Wall time: 5.13 ms\n" - ] - }, - { - "data": { - "text/plain": [ - "dask.array" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# wrap as dask array with very simple chunking of first dim only\n", - "%time gd = da.from_array(g, chunks=(g.chunks[0], None, None))\n", - "gd" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "((22632425,), dtype('bool'), 13167162)" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# load condition used to make selection on first axis\n", - "dim0_condition = callset['3R/variants/FILTER_PASS'][:]\n", - "dim0_condition.shape, dim0_condition.dtype, np.count_nonzero(dim0_condition)" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "# invent a random selection for second axis\n", - "dim1_indices = sorted(np.random.choice(765, size=100, replace=False))" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 15.3 s, sys: 256 ms, total: 15.5 s\n", - "Wall time: 15.5 s\n" - ] - }, - { - "data": { - "text/plain": [ - "dask.array" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# setup the 2D selection - this is the slow bit\n", - "%time gd_sel = gd[dim0_condition][:, dim1_indices]\n", - "gd_sel" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 1.21 s, sys: 152 ms, total: 1.36 s\n", - "Wall time: 316 ms\n" - ] - }, - { - "data": { - "text/plain": [ - "array([[[0, 0],\n", - " [0, 0],\n", - " [0, 0],\n", - " ..., \n", - " [0, 0],\n", - " [0, 0],\n", - " [0, 0]],\n", - "\n", - " [[0, 0],\n", - " [0, 0],\n", - " [0, 0],\n", - " ..., \n", - " [0, 0],\n", - " [0, 0],\n", - " [0, 0]],\n", - "\n", - " [[0, 0],\n", - " [0, 0],\n", - " [0, 0],\n", - " ..., \n", - " [0, 0],\n", - " [0, 0],\n", - " [0, 0]],\n", - "\n", - " ..., \n", - " [[0, 0],\n", - " [0, 0],\n", - " [0, 0],\n", - " ..., \n", - " [0, 1],\n", - " [0, 0],\n", - " [0, 0]],\n", - "\n", - " [[0, 0],\n", - " [0, 0],\n", - " [0, 0],\n", - " ..., \n", - " [0, 0],\n", - " [0, 0],\n", - " [0, 0]],\n", - "\n", - " [[0, 0],\n", - " [0, 0],\n", - " [0, 0],\n", - " ..., \n", - " [0, 0],\n", - " [0, 0],\n", - " [0, 0]]], dtype=int8)" - ] - }, - "execution_count": 23, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# now load a slice from this new selection - quick!\n", - "%time gd_sel[1000000:1100000].compute(optimize_graph=False)" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - " 105406881 function calls (79072145 primitive calls) in 26.182 seconds\n", - "\n", - " Ordered by: internal time\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - "13167268/6 6.807 0.000 9.038 1.506 slicing.py:623(check_index)\n", - " 2 4.713 2.356 5.831 2.916 slicing.py:398(partition_by_size)\n", - "13167270/2 4.470 0.000 8.763 4.382 slicing.py:540(posify_index)\n", - " 52669338 4.118 0.000 4.119 0.000 {built-in method builtins.isinstance}\n", - " 2 2.406 1.203 8.763 4.382 slicing.py:563()\n", - " 1 0.875 0.875 0.875 0.875 slicing.py:44()\n", - " 13182474 0.600 0.000 0.600 0.000 {built-in method builtins.len}\n", - " 2 0.527 0.264 0.527 0.264 slicing.py:420(issorted)\n", - " 13189168 0.520 0.000 0.520 0.000 {method 'append' of 'list' objects}\n", - " 2 0.271 0.136 0.271 0.136 slicing.py:479()\n", - " 2 0.220 0.110 0.220 0.110 {built-in method builtins.sorted}\n", - " 1 0.162 0.162 0.162 0.162 {method 'tolist' of 'numpy.ndarray' objects}\n", - " 2 0.113 0.056 26.071 13.035 core.py:1024(__getitem__)\n", - " 2 0.112 0.056 6.435 3.217 slicing.py:441(take_sorted)\n", - " 1 0.111 0.111 26.182 26.182 :1()\n", - " 2 0.060 0.030 24.843 12.422 slicing.py:142(slice_with_newaxes)\n", - " 106/3 0.039 0.000 1.077 0.359 slicing.py:15(sanitize_index)\n", - " 3 0.037 0.012 0.037 0.012 {built-in method _hashlib.openssl_md5}\n", - " 6726 0.012 0.000 0.017 0.000 slicing.py:567(insert_many)\n", - " 3364 0.004 0.000 0.021 0.000 slicing.py:156()\n", - " 20178 0.003 0.000 0.003 0.000 {method 'pop' of 'list' objects}\n", - " 8 0.000 0.000 0.000 0.000 {method 'update' of 'dict' objects}\n", - " 2 0.000 0.000 25.920 12.960 slicing.py:60(slice_array)\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:162()\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:464()\n", - " 106/4 0.000 0.000 0.037 0.009 utils.py:502(__call__)\n", - " 100 0.000 0.000 0.000 0.000 arrayprint.py:340(array2string)\n", - " 2 0.000 0.000 0.037 0.019 base.py:343(tokenize)\n", - " 100 0.000 0.000 0.000 0.000 {built-in method builtins.repr}\n", - " 2 0.000 0.000 24.763 12.381 slicing.py:170(slice_wrap_lists)\n", - " 108 0.000 0.000 0.000 0.000 abc.py:178(__instancecheck__)\n", - " 2 0.000 0.000 6.962 3.481 slicing.py:487(take)\n", - " 1 0.000 0.000 26.182 26.182 {built-in method builtins.exec}\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:465()\n", - " 1 0.000 0.000 0.037 0.037 base.py:314(normalize_array)\n", - " 2/1 0.000 0.000 0.000 0.000 base.py:270(normalize_seq)\n", - " 116 0.000 0.000 0.000 0.000 _weakrefset.py:70(__contains__)\n", - " 100 0.000 0.000 0.000 0.000 numeric.py:1835(array_str)\n", - " 1 0.000 0.000 0.000 0.000 slicing.py:47()\n", - " 6 0.000 0.000 0.000 0.000 {built-in method builtins.sum}\n", - " 2 0.000 0.000 0.000 0.000 exceptions.py:15(merge)\n", - " 100 0.000 0.000 0.000 0.000 inspect.py:441(getmro)\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:475()\n", - " 4 0.000 0.000 0.000 0.000 dicttoolz.py:19(merge)\n", - " 4 0.000 0.000 0.000 0.000 functoolz.py:217(__call__)\n", - " 2 0.000 0.000 0.000 0.000 core.py:1455(normalize_chunks)\n", - " 4 0.000 0.000 0.000 0.000 dicttoolz.py:11(_get_factory)\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:467()\n", - " 100 0.000 0.000 0.000 0.000 {method 'item' of 'numpy.ndarray' objects}\n", - " 2 0.000 0.000 0.000 0.000 core.py:794(__init__)\n", - " 8 0.000 0.000 0.000 0.000 {built-in method builtins.all}\n", - " 8 0.000 0.000 0.000 0.000 slicing.py:197()\n", - " 8 0.000 0.000 0.000 0.000 slicing.py:183()\n", - " 5 0.000 0.000 0.000 0.000 core.py:1043()\n", - " 7 0.000 0.000 0.000 0.000 {built-in method builtins.hasattr}\n", - " 5 0.000 0.000 0.000 0.000 slicing.py:125()\n", - " 1 0.000 0.000 0.000 0.000 {method 'view' of 'numpy.ndarray' objects}\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:192()\n", - " 3 0.000 0.000 0.000 0.000 {method 'hexdigest' of '_hashlib.HASH' objects}\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:606(replace_ellipsis)\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:613()\n", - " 1 0.000 0.000 0.000 0.000 {method 'ravel' of 'numpy.ndarray' objects}\n", - " 4 0.000 0.000 0.000 0.000 {method 'items' of 'dict' objects}\n", - " 2 0.000 0.000 0.000 0.000 {method 'encode' of 'str' objects}\n", - " 8 0.000 0.000 0.000 0.000 slicing.py:207()\n", - " 2 0.000 0.000 0.000 0.000 core.py:826(_get_chunks)\n", - " 2 0.000 0.000 0.000 0.000 core.py:1452()\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:149()\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:150()\n", - " 1 0.000 0.000 0.000 0.000 functoolz.py:11(identity)\n", - " 4 0.000 0.000 0.000 0.000 {method 'pop' of 'dict' objects}\n", - " 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n", - " 2 0.000 0.000 0.000 0.000 {method 'count' of 'tuple' objects}\n", - "\n", - "\n" - ] - } - ], - "source": [ - "# what's taking so long?\n", - "import cProfile\n", - "cProfile.run('gd[dim0_condition][:, dim1_indices]', sort='time')" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - " 105406881 function calls (79072145 primitive calls) in 25.630 seconds\n", - "\n", - " Ordered by: cumulative time\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - " 1 0.000 0.000 25.630 25.630 {built-in method builtins.exec}\n", - " 1 0.107 0.107 25.630 25.630 :1()\n", - " 2 0.102 0.051 25.523 12.761 core.py:1024(__getitem__)\n", - " 2 0.001 0.000 25.381 12.691 slicing.py:60(slice_array)\n", - " 2 0.049 0.024 24.214 12.107 slicing.py:142(slice_with_newaxes)\n", - " 2 0.000 0.000 24.147 12.073 slicing.py:170(slice_wrap_lists)\n", - "13167268/6 6.664 0.000 8.855 1.476 slicing.py:623(check_index)\n", - "13167270/2 4.354 0.000 8.466 4.233 slicing.py:540(posify_index)\n", - " 2 2.277 1.139 8.465 4.233 slicing.py:563()\n", - " 2 0.000 0.000 6.826 3.413 slicing.py:487(take)\n", - " 2 0.111 0.056 6.331 3.165 slicing.py:441(take_sorted)\n", - " 2 4.628 2.314 5.704 2.852 slicing.py:398(partition_by_size)\n", - " 52669338 4.026 0.000 4.026 0.000 {built-in method builtins.isinstance}\n", - " 106/3 0.071 0.001 1.167 0.389 slicing.py:15(sanitize_index)\n", - " 1 0.943 0.943 0.943 0.943 slicing.py:44()\n", - " 13182474 0.581 0.000 0.581 0.000 {built-in method builtins.len}\n", - " 13189168 0.497 0.000 0.497 0.000 {method 'append' of 'list' objects}\n", - " 2 0.495 0.248 0.495 0.248 slicing.py:420(issorted)\n", - " 2 0.281 0.141 0.281 0.141 slicing.py:479()\n", - " 2 0.234 0.117 0.234 0.117 {built-in method builtins.sorted}\n", - " 1 0.152 0.152 0.152 0.152 {method 'tolist' of 'numpy.ndarray' objects}\n", - " 2 0.000 0.000 0.039 0.020 base.py:343(tokenize)\n", - " 106/4 0.000 0.000 0.039 0.010 utils.py:502(__call__)\n", - " 1 0.000 0.000 0.039 0.039 base.py:314(normalize_array)\n", - " 3 0.039 0.013 0.039 0.013 {built-in method _hashlib.openssl_md5}\n", - " 3364 0.003 0.000 0.019 0.000 slicing.py:156()\n", - " 6726 0.012 0.000 0.016 0.000 slicing.py:567(insert_many)\n", - " 20178 0.003 0.000 0.003 0.000 {method 'pop' of 'list' objects}\n", - " 4 0.000 0.000 0.000 0.000 dicttoolz.py:19(merge)\n", - " 8 0.000 0.000 0.000 0.000 {method 'update' of 'dict' objects}\n", - " 4 0.000 0.000 0.000 0.000 functoolz.py:217(__call__)\n", - " 2 0.000 0.000 0.000 0.000 exceptions.py:15(merge)\n", - " 2/1 0.000 0.000 0.000 0.000 base.py:270(normalize_seq)\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:162()\n", - " 100 0.000 0.000 0.000 0.000 {built-in method builtins.repr}\n", - " 1 0.000 0.000 0.000 0.000 slicing.py:47()\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:464()\n", - " 100 0.000 0.000 0.000 0.000 numeric.py:1835(array_str)\n", - " 100 0.000 0.000 0.000 0.000 arrayprint.py:340(array2string)\n", - " 108 0.000 0.000 0.000 0.000 abc.py:178(__instancecheck__)\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:465()\n", - " 8 0.000 0.000 0.000 0.000 {built-in method builtins.all}\n", - " 2 0.000 0.000 0.000 0.000 core.py:794(__init__)\n", - " 116 0.000 0.000 0.000 0.000 _weakrefset.py:70(__contains__)\n", - " 2 0.000 0.000 0.000 0.000 core.py:1455(normalize_chunks)\n", - " 6 0.000 0.000 0.000 0.000 {built-in method builtins.sum}\n", - " 8 0.000 0.000 0.000 0.000 slicing.py:183()\n", - " 100 0.000 0.000 0.000 0.000 {method 'item' of 'numpy.ndarray' objects}\n", - " 100 0.000 0.000 0.000 0.000 inspect.py:441(getmro)\n", - " 2 0.000 0.000 0.000 0.000 {method 'encode' of 'str' objects}\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:606(replace_ellipsis)\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:475()\n", - " 5 0.000 0.000 0.000 0.000 slicing.py:125()\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:467()\n", - " 3 0.000 0.000 0.000 0.000 {method 'hexdigest' of '_hashlib.HASH' objects}\n", - " 1 0.000 0.000 0.000 0.000 {method 'view' of 'numpy.ndarray' objects}\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:192()\n", - " 4 0.000 0.000 0.000 0.000 dicttoolz.py:11(_get_factory)\n", - " 5 0.000 0.000 0.000 0.000 core.py:1043()\n", - " 7 0.000 0.000 0.000 0.000 {built-in method builtins.hasattr}\n", - " 8 0.000 0.000 0.000 0.000 slicing.py:207()\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:613()\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:149()\n", - " 1 0.000 0.000 0.000 0.000 {method 'ravel' of 'numpy.ndarray' objects}\n", - " 8 0.000 0.000 0.000 0.000 slicing.py:197()\n", - " 2 0.000 0.000 0.000 0.000 core.py:826(_get_chunks)\n", - " 2 0.000 0.000 0.000 0.000 core.py:1452()\n", - " 4 0.000 0.000 0.000 0.000 {method 'pop' of 'dict' objects}\n", - " 4 0.000 0.000 0.000 0.000 {method 'items' of 'dict' objects}\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:150()\n", - " 2 0.000 0.000 0.000 0.000 {method 'count' of 'tuple' objects}\n", - " 1 0.000 0.000 0.000 0.000 functoolz.py:11(identity)\n", - " 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n", - "\n", - "\n" - ] - } - ], - "source": [ - "cProfile.run('gd[dim0_condition][:, dim1_indices]', sort='cumtime')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Synthetic data" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "Array((20000000, 200, 2), int8, chunks=(10000, 100, 2), order=C)\n", - " nbytes: 7.5G; nbytes_stored: 2.7G; ratio: 2.8; initialized: 4000/4000\n", - " compressor: Blosc(cname='zstd', clevel=1, shuffle=2)\n", - " store: dict" - ] - }, - "execution_count": 22, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# create a synthetic dataset for profiling\n", - "a = zarr.array(np.random.randint(-1, 4, size=(20000000, 200, 2), dtype='i1'),\n", - " chunks=(10000, 100, 2), compressor=zarr.Blosc(cname='zstd', clevel=1, shuffle=2))\n", - "a" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# create a synthetic selection for first axis\n", - "c = np.random.randint(0, 2, size=a.shape[0], dtype=bool)" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# create a synthetic selection for second axis\n", - "s = sorted(np.random.choice(a.shape[1], size=100, replace=False))" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 208 ms, sys: 0 ns, total: 208 ms\n", - "Wall time: 206 ms\n" - ] - }, - { - "data": { - "text/plain": [ - "dask.array" - ] - }, - "execution_count": 26, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "%time d = da.from_array(a, chunks=(a.chunks[0], None, None))\n", - "d" - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 12 s, sys: 200 ms, total: 12.2 s\n", - "Wall time: 12.2 s\n" - ] - } - ], - "source": [ - "%time ds = d[c][:, s]" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - " 80095589 function calls (60091843 primitive calls) in 19.467 seconds\n", - "\n", - " Ordered by: internal time\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - "10001773/6 4.872 0.000 6.456 1.076 slicing.py:623(check_index)\n", - " 2 3.517 1.758 4.357 2.179 slicing.py:398(partition_by_size)\n", - "10001775/2 3.354 0.000 6.484 3.242 slicing.py:540(posify_index)\n", - " 40007358 2.965 0.000 2.965 0.000 {built-in method builtins.isinstance}\n", - " 2 1.749 0.875 6.484 3.242 slicing.py:563()\n", - " 1 0.878 0.878 0.878 0.878 slicing.py:44()\n", - " 10019804 0.451 0.000 0.451 0.000 {built-in method builtins.len}\n", - " 10027774 0.392 0.000 0.392 0.000 {method 'append' of 'list' objects}\n", - " 2 0.363 0.181 0.363 0.181 slicing.py:420(issorted)\n", - " 2 0.270 0.135 4.786 2.393 slicing.py:441(take_sorted)\n", - " 1 0.207 0.207 0.207 0.207 {method 'tolist' of 'numpy.ndarray' objects}\n", - " 2 0.158 0.079 0.158 0.079 {built-in method builtins.sorted}\n", - " 1 0.094 0.094 19.467 19.467 :1()\n", - " 2 0.079 0.040 19.373 9.686 core.py:1024(__getitem__)\n", - " 2 0.035 0.017 18.147 9.074 slicing.py:142(slice_with_newaxes)\n", - " 3 0.033 0.011 0.033 0.011 {built-in method _hashlib.openssl_md5}\n", - " 106/3 0.028 0.000 1.112 0.371 slicing.py:15(sanitize_index)\n", - " 8002 0.015 0.000 0.020 0.000 slicing.py:567(insert_many)\n", - " 4002 0.004 0.000 0.023 0.000 slicing.py:156()\n", - " 24006 0.003 0.000 0.003 0.000 {method 'pop' of 'list' objects}\n", - " 8 0.001 0.000 0.001 0.000 {method 'update' of 'dict' objects}\n", - " 2 0.001 0.000 0.001 0.000 slicing.py:479()\n", - " 2 0.000 0.000 19.259 9.630 slicing.py:60(slice_array)\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:162()\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:464()\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:465()\n", - " 106/4 0.000 0.000 0.034 0.008 utils.py:502(__call__)\n", - " 2 0.000 0.000 18.089 9.044 slicing.py:170(slice_wrap_lists)\n", - " 100 0.000 0.000 0.000 0.000 arrayprint.py:340(array2string)\n", - " 100 0.000 0.000 0.000 0.000 {built-in method builtins.repr}\n", - " 108 0.000 0.000 0.000 0.000 abc.py:178(__instancecheck__)\n", - " 2 0.000 0.000 5.149 2.574 slicing.py:487(take)\n", - " 2 0.000 0.000 0.034 0.017 base.py:343(tokenize)\n", - " 1 0.000 0.000 0.033 0.033 base.py:314(normalize_array)\n", - " 116 0.000 0.000 0.000 0.000 _weakrefset.py:70(__contains__)\n", - " 2/1 0.000 0.000 0.000 0.000 base.py:270(normalize_seq)\n", - " 6 0.000 0.000 0.000 0.000 {built-in method builtins.sum}\n", - " 100 0.000 0.000 0.000 0.000 numeric.py:1835(array_str)\n", - " 1 0.000 0.000 0.000 0.000 slicing.py:47()\n", - " 1 0.000 0.000 19.467 19.467 {built-in method builtins.exec}\n", - " 100 0.000 0.000 0.000 0.000 inspect.py:441(getmro)\n", - " 8 0.000 0.000 0.000 0.000 {built-in method builtins.all}\n", - " 4 0.000 0.000 0.001 0.000 dicttoolz.py:19(merge)\n", - " 2 0.000 0.000 0.000 0.000 core.py:1455(normalize_chunks)\n", - " 100 0.000 0.000 0.000 0.000 {method 'item' of 'numpy.ndarray' objects}\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:475()\n", - " 2 0.000 0.000 0.000 0.000 core.py:794(__init__)\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:467()\n", - " 3 0.000 0.000 0.000 0.000 {method 'hexdigest' of '_hashlib.HASH' objects}\n", - " 2 0.000 0.000 0.001 0.000 exceptions.py:15(merge)\n", - " 7 0.000 0.000 0.000 0.000 {built-in method builtins.hasattr}\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:606(replace_ellipsis)\n", - " 4 0.000 0.000 0.001 0.000 functoolz.py:217(__call__)\n", - " 8 0.000 0.000 0.000 0.000 slicing.py:183()\n", - " 4 0.000 0.000 0.000 0.000 dicttoolz.py:11(_get_factory)\n", - " 5 0.000 0.000 0.000 0.000 core.py:1043()\n", - " 2 0.000 0.000 0.000 0.000 {method 'encode' of 'str' objects}\n", - " 1 0.000 0.000 0.000 0.000 {method 'view' of 'numpy.ndarray' objects}\n", - " 8 0.000 0.000 0.000 0.000 slicing.py:197()\n", - " 5 0.000 0.000 0.000 0.000 slicing.py:125()\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:192()\n", - " 8 0.000 0.000 0.000 0.000 slicing.py:207()\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:613()\n", - " 2 0.000 0.000 0.000 0.000 {method 'count' of 'tuple' objects}\n", - " 1 0.000 0.000 0.000 0.000 {method 'ravel' of 'numpy.ndarray' objects}\n", - " 1 0.000 0.000 0.000 0.000 functoolz.py:11(identity)\n", - " 4 0.000 0.000 0.000 0.000 {method 'pop' of 'dict' objects}\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:150()\n", - " 2 0.000 0.000 0.000 0.000 core.py:826(_get_chunks)\n", - " 2 0.000 0.000 0.000 0.000 core.py:1452()\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:149()\n", - " 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n", - " 4 0.000 0.000 0.000 0.000 {method 'items' of 'dict' objects}\n", - "\n", - "\n" - ] - } - ], - "source": [ - "cProfile.run('d[c][:, s]', sort='time')" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 452 ms, sys: 8 ms, total: 460 ms\n", - "Wall time: 148 ms\n" - ] - }, - { - "data": { - "text/plain": [ - "array([[[ 2, -1],\n", - " [ 2, 3],\n", - " [ 3, 0],\n", - " ..., \n", - " [ 1, 3],\n", - " [-1, -1],\n", - " [ 1, 1]],\n", - "\n", - " [[ 1, -1],\n", - " [ 2, 2],\n", - " [-1, 2],\n", - " ..., \n", - " [ 2, -1],\n", - " [ 1, 3],\n", - " [-1, -1]],\n", - "\n", - " [[ 1, -1],\n", - " [ 2, 0],\n", - " [ 0, 3],\n", - " ..., \n", - " [ 2, 2],\n", - " [ 3, 2],\n", - " [ 0, 2]],\n", - "\n", - " ..., \n", - " [[ 1, 2],\n", - " [ 3, -1],\n", - " [ 2, 1],\n", - " ..., \n", - " [ 1, 2],\n", - " [ 1, 0],\n", - " [ 2, 0]],\n", - "\n", - " [[ 1, 2],\n", - " [ 1, 0],\n", - " [ 2, 3],\n", - " ..., \n", - " [-1, 2],\n", - " [ 3, 3],\n", - " [ 1, -1]],\n", - "\n", - " [[-1, 3],\n", - " [ 2, 2],\n", - " [ 1, 1],\n", - " ..., \n", - " [ 3, 3],\n", - " [ 0, 0],\n", - " [ 0, 2]]], dtype=int8)" - ] - }, - "execution_count": 29, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "%time ds[1000000:1100000].compute(optimize_graph=False)" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - " 80055494 function calls (60052157 primitive calls) in 19.425 seconds\n", - "\n", - " Ordered by: internal time\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - "10001670/3 5.032 0.000 6.671 2.224 slicing.py:623(check_index)\n", - " 1 3.459 3.459 4.272 4.272 slicing.py:398(partition_by_size)\n", - "10001671/1 3.287 0.000 6.378 6.378 slicing.py:540(posify_index)\n", - " 40006704 2.999 0.000 2.999 0.000 {built-in method builtins.isinstance}\n", - " 1 1.731 1.731 6.378 6.378 slicing.py:563()\n", - " 1 0.849 0.849 0.849 0.849 slicing.py:44()\n", - " 10011685 0.433 0.000 0.433 0.000 {built-in method builtins.len}\n", - " 10015670 0.381 0.000 0.381 0.000 {method 'append' of 'list' objects}\n", - " 1 0.355 0.355 0.355 0.355 slicing.py:420(issorted)\n", - " 1 0.196 0.196 0.196 0.196 {method 'tolist' of 'numpy.ndarray' objects}\n", - " 1 0.193 0.193 0.193 0.193 slicing.py:479()\n", - " 1 0.157 0.157 0.157 0.157 {built-in method builtins.sorted}\n", - " 1 0.085 0.085 4.707 4.707 slicing.py:441(take_sorted)\n", - " 1 0.085 0.085 19.425 19.425 :1()\n", - " 1 0.079 0.079 19.341 19.341 core.py:1024(__getitem__)\n", - " 1 0.034 0.034 18.157 18.157 slicing.py:142(slice_with_newaxes)\n", - " 2 0.033 0.017 0.033 0.017 {built-in method _hashlib.openssl_md5}\n", - " 1 0.026 0.026 1.071 1.071 slicing.py:15(sanitize_index)\n", - " 4001 0.007 0.000 0.009 0.000 slicing.py:567(insert_many)\n", - " 2001 0.002 0.000 0.011 0.000 slicing.py:156()\n", - " 12003 0.001 0.000 0.001 0.000 {method 'pop' of 'list' objects}\n", - " 4 0.000 0.000 0.000 0.000 {method 'update' of 'dict' objects}\n", - " 1 0.000 0.000 19.228 19.228 slicing.py:60(slice_array)\n", - " 1 0.000 0.000 0.000 0.000 slicing.py:464()\n", - " 1 0.000 0.000 0.000 0.000 slicing.py:162()\n", - " 1 0.000 0.000 0.033 0.033 base.py:314(normalize_array)\n", - " 1 0.000 0.000 18.111 18.111 slicing.py:170(slice_wrap_lists)\n", - " 1 0.000 0.000 0.000 0.000 slicing.py:465()\n", - " 1 0.000 0.000 5.062 5.062 slicing.py:487(take)\n", - " 1 0.000 0.000 0.033 0.033 base.py:343(tokenize)\n", - " 1 0.000 0.000 19.425 19.425 {built-in method builtins.exec}\n", - " 2 0.000 0.000 0.000 0.000 functoolz.py:217(__call__)\n", - " 3 0.000 0.000 0.000 0.000 {built-in method builtins.sum}\n", - " 2 0.000 0.000 0.000 0.000 abc.py:178(__instancecheck__)\n", - " 1 0.000 0.000 0.000 0.000 core.py:1455(normalize_chunks)\n", - " 2 0.000 0.000 0.000 0.000 dicttoolz.py:19(merge)\n", - " 4 0.000 0.000 0.000 0.000 _weakrefset.py:70(__contains__)\n", - " 2 0.000 0.000 0.000 0.000 dicttoolz.py:11(_get_factory)\n", - " 1 0.000 0.000 0.000 0.000 exceptions.py:15(merge)\n", - " 1 0.000 0.000 0.000 0.000 core.py:794(__init__)\n", - " 4 0.000 0.000 0.000 0.000 {built-in method builtins.all}\n", - " 1 0.000 0.000 0.000 0.000 slicing.py:467()\n", - " 1 0.000 0.000 0.000 0.000 {method 'view' of 'numpy.ndarray' objects}\n", - " 4 0.000 0.000 0.000 0.000 slicing.py:183()\n", - " 2 0.000 0.000 0.000 0.000 {method 'hexdigest' of '_hashlib.HASH' objects}\n", - " 1 0.000 0.000 0.000 0.000 slicing.py:606(replace_ellipsis)\n", - " 1 0.000 0.000 0.000 0.000 slicing.py:192()\n", - " 4 0.000 0.000 0.000 0.000 slicing.py:207()\n", - " 1 0.000 0.000 0.000 0.000 slicing.py:475()\n", - " 2 0.000 0.000 0.033 0.017 utils.py:502(__call__)\n", - " 2 0.000 0.000 0.000 0.000 slicing.py:125()\n", - " 2 0.000 0.000 0.000 0.000 core.py:1043()\n", - " 4 0.000 0.000 0.000 0.000 slicing.py:197()\n", - " 1 0.000 0.000 0.000 0.000 core.py:826(_get_chunks)\n", - " 2 0.000 0.000 0.000 0.000 {built-in method builtins.hasattr}\n", - " 1 0.000 0.000 0.000 0.000 {method 'ravel' of 'numpy.ndarray' objects}\n", - " 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n", - " 1 0.000 0.000 0.000 0.000 {method 'encode' of 'str' objects}\n", - " 1 0.000 0.000 0.000 0.000 slicing.py:613()\n", - " 1 0.000 0.000 0.000 0.000 core.py:1452()\n", - " 1 0.000 0.000 0.000 0.000 slicing.py:149()\n", - " 2 0.000 0.000 0.000 0.000 {method 'pop' of 'dict' objects}\n", - " 2 0.000 0.000 0.000 0.000 {method 'items' of 'dict' objects}\n", - " 1 0.000 0.000 0.000 0.000 slicing.py:150()\n", - " 1 0.000 0.000 0.000 0.000 {method 'count' of 'tuple' objects}\n", - "\n", - "\n" - ] - } - ], - "source": [ - "# problem is in fact just the dim0 selection\n", - "cProfile.run('d[c]', sort='time')" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.5.2" - } - }, - "nbformat": 4, - "nbformat_minor": 1 -} diff --git a/notebooks/dask_copy.ipynb b/notebooks/dask_copy.ipynb deleted file mode 100644 index ba4391737a..0000000000 --- a/notebooks/dask_copy.ipynb +++ /dev/null @@ -1,1518 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Profile array copy via dask threaded scheduler" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This notebook profiles a very simple array copy operation, using synthetic data." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "zarr 1.0.1.dev18+dirty\n" - ] - }, - { - "data": { - "text/html": [ - "\n", - "
\n", - " \n", - " Loading BokehJS ...\n", - "
" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "application/javascript": [ - "\n", - "(function(global) {\n", - " function now() {\n", - " return new Date();\n", - " }\n", - "\n", - " if (typeof (window._bokeh_onload_callbacks) === \"undefined\") {\n", - " window._bokeh_onload_callbacks = [];\n", - " }\n", - "\n", - " function run_callbacks() {\n", - " window._bokeh_onload_callbacks.forEach(function(callback) { callback() });\n", - " delete window._bokeh_onload_callbacks\n", - " console.info(\"Bokeh: all callbacks have finished\");\n", - " }\n", - "\n", - " function load_libs(js_urls, callback) {\n", - " window._bokeh_onload_callbacks.push(callback);\n", - " if (window._bokeh_is_loading > 0) {\n", - " console.log(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n", - " return null;\n", - " }\n", - " if (js_urls == null || js_urls.length === 0) {\n", - " run_callbacks();\n", - " return null;\n", - " }\n", - " console.log(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n", - " window._bokeh_is_loading = js_urls.length;\n", - " for (var i = 0; i < js_urls.length; i++) {\n", - " var url = js_urls[i];\n", - " var s = document.createElement('script');\n", - " s.src = url;\n", - " s.async = false;\n", - " s.onreadystatechange = s.onload = function() {\n", - " window._bokeh_is_loading--;\n", - " if (window._bokeh_is_loading === 0) {\n", - " console.log(\"Bokeh: all BokehJS libraries loaded\");\n", - " run_callbacks()\n", - " }\n", - " };\n", - " s.onerror = function() {\n", - " console.warn(\"failed to load library \" + url);\n", - " };\n", - " console.log(\"Bokeh: injecting script tag for BokehJS library: \", url);\n", - " document.getElementsByTagName(\"head\")[0].appendChild(s);\n", - " }\n", - " };\n", - "\n", - " var js_urls = ['https://cdn.pydata.org/bokeh/release/bokeh-0.12.0.min.js', 'https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.0.min.js', 'https://cdn.pydata.org/bokeh/release/bokeh-compiler-0.12.0.min.js'];\n", - "\n", - " var inline_js = [\n", - " function(Bokeh) {\n", - " Bokeh.set_log_level(\"info\");\n", - " },\n", - " \n", - " function(Bokeh) {\n", - " Bokeh.$(\"#d4821cb3-378c-411d-a941-d0708c0c532b\").text(\"BokehJS successfully loaded\");\n", - " },\n", - " function(Bokeh) {\n", - " console.log(\"Bokeh: injecting CSS: https://cdn.pydata.org/bokeh/release/bokeh-0.12.0.min.css\");\n", - " Bokeh.embed.inject_css(\"https://cdn.pydata.org/bokeh/release/bokeh-0.12.0.min.css\");\n", - " console.log(\"Bokeh: injecting CSS: https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.0.min.css\");\n", - " Bokeh.embed.inject_css(\"https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.0.min.css\");\n", - " }\n", - " ];\n", - "\n", - " function run_inline_js() {\n", - " for (var i = 0; i < inline_js.length; i++) {\n", - " inline_js[i](window.Bokeh);\n", - " }\n", - " }\n", - "\n", - " if (window._bokeh_is_loading === 0) {\n", - " console.log(\"Bokeh: BokehJS loaded, going straight to plotting\");\n", - " run_inline_js();\n", - " } else {\n", - " load_libs(js_urls, function() {\n", - " console.log(\"Bokeh: BokehJS plotting callback run at\", now());\n", - " run_inline_js();\n", - " });\n", - " }\n", - "}(this));" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "import sys\n", - "sys.path.insert(0, '..')\n", - "import zarr\n", - "print('zarr', zarr.__version__)\n", - "from zarr import blosc\n", - "import numpy as np\n", - "import h5py\n", - "import bcolz\n", - "# don't let bcolz use multiple threads internally, we want to \n", - "# see whether dask can make good use of multiple CPUs\n", - "bcolz.set_nthreads(1)\n", - "import multiprocessing\n", - "import dask\n", - "import dask.array as da\n", - "from dask.diagnostics import Profiler, ResourceProfiler, CacheProfiler\n", - "from dask.diagnostics.profile_visualize import visualize\n", - "from cachey import nbytes\n", - "import bokeh\n", - "from bokeh.io import output_notebook\n", - "output_notebook()" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import tempfile\n", - "import operator\n", - "from functools import reduce\n", - "from zarr.util import human_readable_size\n", - "\n", - "\n", - "def h5fmem(**kwargs):\n", - " \"\"\"Convenience function to create an in-memory HDF5 file.\"\"\"\n", - "\n", - " # need a file name even tho nothing is ever written\n", - " fn = tempfile.mktemp()\n", - "\n", - " # file creation args\n", - " kwargs['mode'] = 'w'\n", - " kwargs['driver'] = 'core'\n", - " kwargs['backing_store'] = False\n", - "\n", - " # open HDF5 file\n", - " h5f = h5py.File(fn, **kwargs)\n", - "\n", - " return h5f\n", - "\n", - "\n", - "def h5d_diagnostics(d):\n", - " \"\"\"Print some diagnostics on an HDF5 dataset.\"\"\"\n", - " \n", - " print(d)\n", - " nbytes = reduce(operator.mul, d.shape) * d.dtype.itemsize\n", - " cbytes = d._id.get_storage_size()\n", - " if cbytes > 0:\n", - " ratio = nbytes / cbytes\n", - " else:\n", - " ratio = np.inf\n", - " r = ' compression: %s' % d.compression\n", - " r += '; compression_opts: %s' % d.compression_opts\n", - " r += '; shuffle: %s' % d.shuffle\n", - " r += '\\n nbytes: %s' % human_readable_size(nbytes)\n", - " r += '; nbytes_stored: %s' % human_readable_size(cbytes)\n", - " r += '; ratio: %.1f' % ratio\n", - " r += '; chunks: %s' % str(d.chunks)\n", - " print(r)\n", - " " - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "def profile_dask_copy(src, dst, chunks, num_workers=multiprocessing.cpu_count(), dt=0.1, lock=True):\n", - " dsrc = da.from_array(src, chunks=chunks)\n", - " with Profiler() as prof, ResourceProfiler(dt=dt) as rprof:\n", - " da.store(dsrc, dst, num_workers=num_workers, lock=lock)\n", - " visualize([prof, rprof], min_border_top=60, min_border_bottom=60)\n", - " " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## NumPy arrays" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "array([1314, 2727, 2905, ..., 1958, 1325, 1971], dtype=uint16)" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# a1 = np.arange(400000000, dtype='i4')\n", - "a1 = np.random.normal(2000, 1000, size=200000000).astype('u2')\n", - "a1" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "'381.5M'" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "human_readable_size(a1.nbytes)" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "a2 = np.empty_like(a1)" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "chunks = 2**20, # 4M" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 56 ms, sys: 36 ms, total: 92 ms\n", - "Wall time: 91.7 ms\n" - ] - } - ], - "source": [ - "%time a2[:] = a1" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "\n", - "
\n", - "
\n", - "
\n", - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "profile_dask_copy(a1, a2, chunks, lock=True, dt=.01)" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "\n", - "
\n", - "
\n", - "
\n", - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "profile_dask_copy(a1, a2, chunks, lock=False, dt=.01)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Zarr arrays (in-memory)" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "zarr.core.Array((200000000,), uint16, chunks=(1048576,), order=C)\n", - " compression: blosc; compression_opts: {'clevel': 1, 'cname': 'lz4', 'shuffle': 2}\n", - " nbytes: 381.5M; nbytes_stored: 318.2M; ratio: 1.2; initialized: 191/191\n", - " store: builtins.dict" - ] - }, - "execution_count": 11, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "z1 = zarr.array(a1, chunks=chunks, compression='blosc', \n", - " compression_opts=dict(cname='lz4', clevel=1, shuffle=2))\n", - "z1" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "zarr.core.Array((200000000,), uint16, chunks=(1048576,), order=C)\n", - " compression: blosc; compression_opts: {'clevel': 1, 'cname': 'lz4', 'shuffle': 2}\n", - " nbytes: 381.5M; nbytes_stored: 294; ratio: 1360544.2; initialized: 0/191\n", - " store: builtins.dict" - ] - }, - "execution_count": 12, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "z2 = zarr.empty_like(z1)\n", - "z2" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "\n", - "
\n", - "
\n", - "
\n", - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "profile_dask_copy(z1, z2, chunks, lock=True, dt=.02)" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "\n", - "
\n", - "
\n", - "
\n", - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "profile_dask_copy(z1, z2, chunks, lock=False, dt=0.02)" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "3 loops, best of 5: 251 ms per loop\n" - ] - } - ], - "source": [ - "# for comparison, using blosc internal threads\n", - "%timeit -n3 -r5 z2[:] = z1" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - " " - ] - } - ], - "source": [ - "%prun z2[:] = z1" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Without the dask lock, we get better CPU utilisation. " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## HDF5 datasets (in-memory)" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 16, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "h5f = h5fmem()\n", - "h5f" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - " compression: lzf; compression_opts: None; shuffle: True\n", - " nbytes: 381.5M; nbytes_stored: 357.4M; ratio: 1.1; chunks: (1048576,)\n" - ] - } - ], - "source": [ - "h1 = h5f.create_dataset('h1', data=a1, chunks=chunks, compression='lzf', shuffle=True)\n", - "h5d_diagnostics(h1)" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - " compression: lzf; compression_opts: None; shuffle: True\n", - " nbytes: 762.9M; nbytes_stored: 0; ratio: inf; chunks: (1048576,)\n" - ] - } - ], - "source": [ - "h2 = h5f.create_dataset('h2', shape=h1.shape, chunks=h1.chunks, \n", - " compression=h1.compression, compression_opts=h1.compression_opts, \n", - " shuffle=h1.shuffle)\n", - "h5d_diagnostics(h2)" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "\n", - "
\n", - "
\n", - "
\n", - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "profile_dask_copy(h1, h2, chunks, lock=True, dt=0.1)" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "\n", - "
\n", - "
\n", - "
\n", - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "profile_dask_copy(h1, h2, chunks, lock=False, dt=0.1)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Bcolz carrays (in-memory)" - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "carray((200000000,), uint16)\n", - " nbytes := 381.47 MB; cbytes := 318.98 MB; ratio: 1.20\n", - " cparams := cparams(clevel=1, shuffle=2, cname='lz4', quantize=0)\n", - " chunklen := 1048576; chunksize: 2097152; blocksize: 16384\n", - "[1314 2727 2905 ..., 1958 1325 1971]" - ] - }, - "execution_count": 27, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "c1 = bcolz.carray(a1, chunklen=chunks[0],\n", - " cparams=bcolz.cparams(cname='lz4', clevel=1, shuffle=2))\n", - "c1" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "carray((200000000,), uint16)\n", - " nbytes := 381.47 MB; cbytes := 2.00 MB; ratio: 190.73\n", - " cparams := cparams(clevel=1, shuffle=2, cname='lz4', quantize=0)\n", - " chunklen := 1048576; chunksize: 2097152; blocksize: 4096\n", - "[0 0 0 ..., 0 0 0]" - ] - }, - "execution_count": 28, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "c2 = bcolz.zeros(a1.shape, chunklen=chunks[0], dtype=a1.dtype, \n", - " cparams=bcolz.cparams(cname='lz4', clevel=1, shuffle=2))\n", - "c2" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "\n", - "
\n", - "
\n", - "
\n", - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "profile_dask_copy(c1, c2, chunks, lock=True, dt=0.05)" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "\n", - "
\n", - "
\n", - "
\n", - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "# not sure it's safe to use bcolz without a lock, but what the heck...\n", - "profile_dask_copy(c1, c2, chunks, lock=False, dt=0.05)" - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "3 loops, best of 5: 649 ms per loop\n" - ] - } - ], - "source": [ - "# for comparison\n", - "%timeit -n3 -r5 c2[:] = c1" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "3 loops, best of 5: 557 ms per loop\n" - ] - } - ], - "source": [ - "# for comparison\n", - "%timeit -n3 -r5 c1.copy()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.5.1" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} diff --git a/notebooks/dask_count_alleles.ipynb b/notebooks/dask_count_alleles.ipynb deleted file mode 100644 index 8b9b7cec6e..0000000000 --- a/notebooks/dask_count_alleles.ipynb +++ /dev/null @@ -1,648 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Profile allele count from genotype data via dask.array" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "zarr 1.0.1.dev18+dirty\n" - ] - }, - { - "data": { - "text/html": [ - "\n", - "
\n", - " \n", - " Loading BokehJS ...\n", - "
" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "application/javascript": [ - "\n", - "(function(global) {\n", - " function now() {\n", - " return new Date();\n", - " }\n", - "\n", - " if (typeof (window._bokeh_onload_callbacks) === \"undefined\") {\n", - " window._bokeh_onload_callbacks = [];\n", - " }\n", - "\n", - " function run_callbacks() {\n", - " window._bokeh_onload_callbacks.forEach(function(callback) { callback() });\n", - " delete window._bokeh_onload_callbacks\n", - " console.info(\"Bokeh: all callbacks have finished\");\n", - " }\n", - "\n", - " function load_libs(js_urls, callback) {\n", - " window._bokeh_onload_callbacks.push(callback);\n", - " if (window._bokeh_is_loading > 0) {\n", - " console.log(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n", - " return null;\n", - " }\n", - " if (js_urls == null || js_urls.length === 0) {\n", - " run_callbacks();\n", - " return null;\n", - " }\n", - " console.log(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n", - " window._bokeh_is_loading = js_urls.length;\n", - " for (var i = 0; i < js_urls.length; i++) {\n", - " var url = js_urls[i];\n", - " var s = document.createElement('script');\n", - " s.src = url;\n", - " s.async = false;\n", - " s.onreadystatechange = s.onload = function() {\n", - " window._bokeh_is_loading--;\n", - " if (window._bokeh_is_loading === 0) {\n", - " console.log(\"Bokeh: all BokehJS libraries loaded\");\n", - " run_callbacks()\n", - " }\n", - " };\n", - " s.onerror = function() {\n", - " console.warn(\"failed to load library \" + url);\n", - " };\n", - " console.log(\"Bokeh: injecting script tag for BokehJS library: \", url);\n", - " document.getElementsByTagName(\"head\")[0].appendChild(s);\n", - " }\n", - " };\n", - "\n", - " var js_urls = ['https://cdn.pydata.org/bokeh/release/bokeh-0.12.0.min.js', 'https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.0.min.js', 'https://cdn.pydata.org/bokeh/release/bokeh-compiler-0.12.0.min.js'];\n", - "\n", - " var inline_js = [\n", - " function(Bokeh) {\n", - " Bokeh.set_log_level(\"info\");\n", - " },\n", - " \n", - " function(Bokeh) {\n", - " Bokeh.$(\"#b153ad5f-436a-4afb-945c-87790add89c8\").text(\"BokehJS successfully loaded\");\n", - " },\n", - " function(Bokeh) {\n", - " console.log(\"Bokeh: injecting CSS: https://cdn.pydata.org/bokeh/release/bokeh-0.12.0.min.css\");\n", - " Bokeh.embed.inject_css(\"https://cdn.pydata.org/bokeh/release/bokeh-0.12.0.min.css\");\n", - " console.log(\"Bokeh: injecting CSS: https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.0.min.css\");\n", - " Bokeh.embed.inject_css(\"https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.0.min.css\");\n", - " }\n", - " ];\n", - "\n", - " function run_inline_js() {\n", - " for (var i = 0; i < inline_js.length; i++) {\n", - " inline_js[i](window.Bokeh);\n", - " }\n", - " }\n", - "\n", - " if (window._bokeh_is_loading === 0) {\n", - " console.log(\"Bokeh: BokehJS loaded, going straight to plotting\");\n", - " run_inline_js();\n", - " } else {\n", - " load_libs(js_urls, function() {\n", - " console.log(\"Bokeh: BokehJS plotting callback run at\", now());\n", - " run_inline_js();\n", - " });\n", - " }\n", - "}(this));" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "import sys\n", - "sys.path.insert(0, '..')\n", - "import zarr\n", - "print('zarr', zarr.__version__)\n", - "from zarr import blosc\n", - "import numpy as np\n", - "import h5py\n", - "import multiprocessing\n", - "import dask\n", - "import dask.array as da\n", - "from dask.diagnostics import Profiler, ResourceProfiler, CacheProfiler\n", - "from dask.diagnostics.profile_visualize import visualize\n", - "from cachey import nbytes\n", - "import bokeh\n", - "from bokeh.io import output_notebook\n", - "output_notebook()\n", - "from functools import reduce\n", - "import operator\n", - "import allel" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "callset = h5py.File('/data/coluzzi/ag1000g/data/phase1/release/AR3/variation/main/hdf5/ag1000g.phase1.ar3.pass.h5',\n", - " mode='r')\n", - "genotype = callset['3R/calldata/genotype']\n", - "genotype" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "zarr.core.Array((13167162, 765, 2), int8, chunks=(6553, 200, 2), order=C)\n", - " compression: blosc; compression_opts: {'clevel': 1, 'cname': 'lz4', 'shuffle': 2}\n", - " nbytes: 18.8G; nbytes_stored: 683.2M; ratio: 28.1; initialized: 8040/8040\n", - " store: builtins.dict" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# copy into a zarr array\n", - "# N.B., chunks in HDF5 are too small really, use something bigger\n", - "chunks = (genotype.chunks[0], genotype.chunks[1] * 20, genotype.chunks[2])\n", - "genotype_zarr = zarr.array(genotype, chunks=chunks, compression='blosc',\n", - " compression_opts=dict(cname='lz4', clevel=1, shuffle=2))\n", - "genotype_zarr" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We want to perform an allele count. Compare serial and parallel implementations, and compare working direct from HDF5 versus from Zarr." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 1min 50s, sys: 512 ms, total: 1min 51s\n", - "Wall time: 1min 50s\n" - ] - }, - { - "data": { - "text/html": [ - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
AlleleCountsChunkedArray((13167162, 4), int32, chunks=(65536, 4))
nbytes: 200.9M; cbytes: 38.3M; cratio: 5.2;
compression: blosc; compression_opts: cparams(clevel=5, shuffle=1, cname='lz4', quantize=0);
data: bcolz.carray_ext.carray
0123
01523500
11527100
21527100
31527100
41527100
\n", - "

...

" - ], - "text/plain": [ - "AlleleCountsChunkedArray((13167162, 4), int32, chunks=(65536, 4))\n", - " nbytes: 200.9M; cbytes: 38.3M; cratio: 5.2;\n", - " compression: blosc; compression_opts: cparams(clevel=5, shuffle=1, cname='lz4', quantize=0);\n", - " data: bcolz.carray_ext.carray" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "%%time\n", - "# linear implementation from HDF5 on disk\n", - "allel.GenotypeChunkedArray(genotype).count_alleles()" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 2min 27s, sys: 2.14 s, total: 2min 29s\n", - "Wall time: 1min 23s\n" - ] - }, - { - "data": { - "text/html": [ - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
AlleleCountsChunkedArray((13167162, 4), int32, chunks=(65536, 4))
nbytes: 200.9M; cbytes: 38.3M; cratio: 5.2;
compression: blosc; compression_opts: cparams(clevel=5, shuffle=1, cname='lz4', quantize=0);
data: bcolz.carray_ext.carray
0123
01523500
11527100
21527100
31527100
41527100
\n", - "

...

" - ], - "text/plain": [ - "AlleleCountsChunkedArray((13167162, 4), int32, chunks=(65536, 4))\n", - " nbytes: 200.9M; cbytes: 38.3M; cratio: 5.2;\n", - " compression: blosc; compression_opts: cparams(clevel=5, shuffle=1, cname='lz4', quantize=0);\n", - " data: bcolz.carray_ext.carray" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "%%time\n", - "# linear implementation from zarr in memory\n", - "# (although blosc can use multiple threads internally)\n", - "allel.GenotypeChunkedArray(genotype_zarr).count_alleles()" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "\n", - "
\n", - "
\n", - "
\n", - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "# multi-threaded implementation from HDF5 on disk\n", - "gd = allel.model.dask.GenotypeDaskArray.from_array(genotype, chunks=chunks)\n", - "ac = gd.count_alleles(max_allele=3)\n", - "with Profiler() as prof, ResourceProfiler(dt=1) as rprof:\n", - " ac.compute(num_workers=8)\n", - "visualize([prof, rprof], min_border_bottom=60, min_border_top=60);" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "\n", - "
\n", - "
\n", - "
\n", - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "# multi-threaded implementation from zarr in memory\n", - "gdz = allel.model.dask.GenotypeDaskArray.from_array(genotype_zarr, chunks=chunks)\n", - "acz = gdz.count_alleles(max_allele=3)\n", - "with Profiler() as prof, ResourceProfiler(dt=1) as rprof:\n", - " acz.compute(num_workers=8)\n", - "visualize([prof, rprof], min_border_bottom=60, min_border_top=60);" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.5.1" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} diff --git a/notebooks/genotype_benchmark_compressors.ipynb b/notebooks/genotype_benchmark_compressors.ipynb deleted file mode 100644 index b262e63fa0..0000000000 --- a/notebooks/genotype_benchmark_compressors.ipynb +++ /dev/null @@ -1,548 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "zarr 1.1.1.dev7+dirty\n", - "blosc ('1.10.0.dev', '$Date:: 2016-07-20 #$')\n" - ] - } - ], - "source": [ - "import sys\n", - "sys.path.insert(0, '..')\n", - "import functools\n", - "import timeit\n", - "import zarr\n", - "print('zarr', zarr.__version__)\n", - "from zarr import blosc\n", - "print('blosc', blosc.version())\n", - "import numpy as np\n", - "import h5py\n", - "%matplotlib inline\n", - "import matplotlib.pyplot as plt" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 2, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "callset = h5py.File('/data/coluzzi/ag1000g/data/phase1/release/AR3/variation/main/hdf5/ag1000g.phase1.ar3.pass.h5',\n", - " mode='r')\n", - "genotype = callset['3R/calldata/genotype']\n", - "genotype" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "n_variants = 500000" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "(500000, 765, 2)" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "genotype_sample = genotype[1000000:1000000+n_variants, ...]\n", - "genotype_sample.shape" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "765000000" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "nbytes = genotype_sample.nbytes\n", - "nbytes" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "(685, 765, 2)" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# 1M chunks of first dimension\n", - "chunks = (int(2**20 / (genotype_sample.shape[1] * genotype_sample.shape[2])), \n", - " genotype_sample.shape[1], \n", - " genotype_sample.shape[2])\n", - "chunks" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "8" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "blosc.get_nthreads()" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "zarr.core.Array((500000, 765, 2), int8, chunks=(685, 765, 2), order=C)\n", - " compression: blosc; compression_opts: {'cname': 'lz4', 'clevel': 1, 'shuffle': 2}\n", - " nbytes: 729.6M; nbytes_stored: 23.0M; ratio: 31.7; initialized: 730/730\n", - " store: builtins.dict" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "zarr.array(genotype_sample, chunks=chunks, compression_opts=dict(cname='lz4', clevel=1, shuffle=2))" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "zarr.core.Array((500000, 765, 2), int8, chunks=(685, 765, 2), order=C)\n", - " compression: blosc; compression_opts: {'cname': 'zstd', 'clevel': 1, 'shuffle': 2}\n", - " nbytes: 729.6M; nbytes_stored: 12.0M; ratio: 60.7; initialized: 730/730\n", - " store: builtins.dict" - ] - }, - "execution_count": 9, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "zarr.array(genotype_sample, chunks=chunks, compression_opts=dict(cname='zstd', clevel=1, shuffle=2))" - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "compression_configs = (\n", - " (None, None),\n", - " ('zlib', 1),\n", - " ('bz2', 1),\n", - " ('lzma', dict(preset=1)),\n", - " ('blosc', dict(cname='snappy', clevel=0, shuffle=0)),\n", - " ('blosc', dict(cname='snappy', clevel=0, shuffle=2)),\n", - " ('blosc', dict(cname='snappy', clevel=9, shuffle=0)),\n", - " ('blosc', dict(cname='snappy', clevel=9, shuffle=2)),\n", - " ('blosc', dict(cname='blosclz', clevel=1, shuffle=0)),\n", - " ('blosc', dict(cname='blosclz', clevel=1, shuffle=2)),\n", - " ('blosc', dict(cname='blosclz', clevel=5, shuffle=0)),\n", - " ('blosc', dict(cname='blosclz', clevel=5, shuffle=2)),\n", - " ('blosc', dict(cname='blosclz', clevel=9, shuffle=0)),\n", - " ('blosc', dict(cname='blosclz', clevel=9, shuffle=2)),\n", - " ('blosc', dict(cname='lz4', clevel=1, shuffle=0)),\n", - " ('blosc', dict(cname='lz4', clevel=1, shuffle=2)),\n", - " ('blosc', dict(cname='lz4', clevel=5, shuffle=0)),\n", - " ('blosc', dict(cname='lz4', clevel=5, shuffle=2)),\n", - " ('blosc', dict(cname='lz4', clevel=9, shuffle=0)),\n", - " ('blosc', dict(cname='lz4', clevel=9, shuffle=2)),\n", - " ('blosc', dict(cname='lz4hc', clevel=1, shuffle=0)),\n", - " ('blosc', dict(cname='lz4hc', clevel=1, shuffle=2)),\n", - " ('blosc', dict(cname='lz4hc', clevel=3, shuffle=0)),\n", - " ('blosc', dict(cname='lz4hc', clevel=3, shuffle=2)),\n", - " ('blosc', dict(cname='zstd', clevel=1, shuffle=0)),\n", - " ('blosc', dict(cname='zstd', clevel=1, shuffle=2)),\n", - " ('blosc', dict(cname='zstd', clevel=3, shuffle=0)),\n", - " ('blosc', dict(cname='zstd', clevel=3, shuffle=2)),\n", - " ('blosc', dict(cname='zstd', clevel=5, shuffle=0)),\n", - " ('blosc', dict(cname='zstd', clevel=5, shuffle=2)),\n", - " ('blosc', dict(cname='zlib', clevel=1, shuffle=0)),\n", - " ('blosc', dict(cname='zlib', clevel=1, shuffle=2)),\n", - " ('blosc', dict(cname='zlib', clevel=3, shuffle=0)),\n", - " ('blosc', dict(cname='zlib', clevel=3, shuffle=2)),\n", - " ('blosc', dict(cname='zlib', clevel=5, shuffle=0)),\n", - " ('blosc', dict(cname='zlib', clevel=5, shuffle=2)),\n", - ")" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "def log(*msg):\n", - " print(*msg, file=sys.stdout)\n", - " sys.stdout.flush()" - ] - }, - { - "cell_type": "code", - "execution_count": 40, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "@functools.lru_cache(maxsize=None)\n", - "def compression_ratios():\n", - " x = list()\n", - " for compression, compression_opts in compression_configs:\n", - " z = zarr.array(genotype_sample, chunks=chunks, compression=compression, \n", - " compression_opts=compression_opts)\n", - " ratio = z.nbytes / z.nbytes_stored\n", - " x.append(ratio)\n", - " log(compression, compression_opts, ratio)\n", - " return x\n" - ] - }, - { - "cell_type": "code", - "execution_count": 43, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "image/png": "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\n0j1Hiu9dwG/T+zlK8+Rq7LsNMCwi/hM4E5hUq2j6+XtgoqSBKY8H1Cif32eDiHgZWJ2G91ViqHXO\noniHkvWyfS3Xo5zfPozsd2K0G1cbq6PVAfQTHa0OoJ/oaHUA/URHqwPoFzxnphznqRznqXm92cB6\nBDhF0gqyh0v8MK0PgNQIOofsX8fFwAMRcRswGuiQtBi4KpUBOJbsgQxLgXuAkT2I6VGg8LHkaUjf\nt8gaeYuBylyeWj1xc4G9UjxHAysLyhTtX3E+WW/SMmWPWf9mdQFJ0yTVnFNT4CxgD2UPuVgkqdHw\nwlqxXQAMV/bI8MVUjcFIQ9UmAC/UPHDE82TDG29Ox7i2oNjpwJ7KHrCxHDgxt+16sl7Ca0uW70bS\niTVysC+wVNKidJ4TcsMDJwHP1DnstsDP0nX/FXBGWl94n0TE0+kcy1NdFlWXqfO+4mjgeGUP1VgO\nHFpdoE5dTyW7Vufl7osRue1DgbURUfdhGWZmZmbWM4po9RO0N50032mHqse0W5PSfJ4vRMTZrY6l\nN0naFrgiIraY74VKwx1nRUTRExkrZaL1T9Y3M2sFsTl/LjKz3iWJiOg2Imlzb2BNAH4MrI+Ig1sc\njllLSTqLrJfw4oi4pk65zfcfBTOzOkaOHMuaNb9rdRhm1k9skQ0sM2uepPC/C411dHT4yUolOE/l\nOE/lOE/lOE/lOE/lOE+11Wpg9eYcLDMzMzMzsy2ae7DMrAv3YJmZmZk15h4sMzMzMzOzTcwNLDOz\nHvD3gpTjPJXjPJXjPJXjPJXjPJXjPDXPDSwzMzMzM7Ne4jlYZtaF52CZmZmZNVZrDtZftSIYM+vb\npG7/VphZHzNy9EjWPL2m1WGYmVkV92CZWReSghmtjqIfWA2Mb3UQ/YDzVE5P8jQDtrT/w/19POU4\nT+U4T+U4T7X5KYJmZmZmZmabWK80sCSNlfRQjW3tkqb2xnmaJWmMpEWS7sitW92KWGqRtL+k2SXK\nrU4/a+a6qvy2kp6S9N38MSQNbyK2hrlK13dMne3HSfpe2XOWjOu4Sr0kTZd0bIPye0lanF5LJX26\nxDlmS9qvwfbDm4x7X0nL0z35NkkXS3pI0j+nepzZYP+GdU3l/lHSbyWtlPTR3PqzJD1Spv5Wgntl\nynGeynGeSvFf0ctxnspxnspxnprXmz1YfXGcwmHAvIg4OLeuL8ZZJqaosVzL+cD8HpxnY8pv6uP0\n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\naxJjAAAAAElFTkSuQmCC\n", - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "ratios = compression_ratios() \n", - "labels = ['%s - %s' % (c, o)\n", - " for c, o in compression_configs]\n", - "\n", - "fig = plt.figure(figsize=(12, len(compression_configs)*.3))\n", - "fig.suptitle('Compression ratio', fontsize=14, y=1.01)\n", - "ax = fig.add_subplot(1, 1, 1)\n", - "\n", - "y = [i for i, (c, o) in enumerate(compression_configs) if c == 'blosc' and o['shuffle'] == 2]\n", - "x = [ratios[i] for i in y]\n", - "ax.barh(bottom=np.array(y)+.2, width=np.array(x), height=.6, label='bit shuffle', color='b')\n", - "\n", - "y = [i for i, (c, o) in enumerate(compression_configs) if c != 'blosc' or o['shuffle'] == 0]\n", - "x = [ratios[i] for i in y]\n", - "ax.barh(bottom=np.array(y)+.2, width=np.array(x), height=.6, label='no shuffle', color='g')\n", - "\n", - "ax.set_yticks(np.arange(len(labels))+.5)\n", - "ax.set_yticklabels(labels, rotation=0)\n", - "\n", - "ax.set_xlim(0, max(ratios)+3)\n", - "ax.set_ylim(0, len(ratios))\n", - "ax.set_xlabel('compression ratio')\n", - "ax.grid(axis='x')\n", - "ax.legend(loc='upper right')\n", - "\n", - "fig.tight_layout();\n" - ] - }, - { - "cell_type": "code", - "execution_count": 56, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "@functools.lru_cache(maxsize=None)\n", - "def compression_decompression_times(repeat=3, number=1):\n", - " c = list()\n", - " d = list()\n", - " for compression, compression_opts in compression_configs:\n", - " \n", - " def compress():\n", - " zarr.array(genotype_sample, chunks=chunks, compression=compression, \n", - " compression_opts=compression_opts)\n", - " \n", - " t = timeit.Timer(stmt=compress, globals=locals())\n", - " compress_times = t.repeat(repeat=repeat, number=number)\n", - " c.append(compress_times)\n", - " \n", - " z = zarr.array(genotype_sample, chunks=chunks, compression=compression, \n", - " compression_opts=compression_opts)\n", - " \n", - " def decompress():\n", - " z[:]\n", - " \n", - " t = timeit.Timer(stmt=decompress, globals=locals())\n", - " decompress_times = t.repeat(repeat=repeat, number=number)\n", - " d.append(decompress_times)\n", - " \n", - " log(compression, compression_opts, compress_times, decompress_times)\n", - " \n", - " return c, d\n", - " " - ] - }, - { - "cell_type": "code", - "execution_count": 59, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "image/png": "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\nj2A1RJOBPor90LCrzsweN7Pf1nc76pqZLTGza+q7HaUiaTxwDfCfBeSuk61t20Kf/bHr29XWBjQk\nHttkeFyT4XFNjsc2OX/605+YMWMGK1asYPny5fziFzt+UjQ1avTggw/SqVMnpk2bxkcffcQ119S8\nxRo/fjz7778/GzZs4L333mPcuHHV0h977DGeeuopVq1axaJFi7j//vtr1JP+vqKigmuvvZZhw4bx\n0UcfcckllzB9+nQ6dOjARx99xH333VejHRdccAFNmzZl5cqVLFiwgBkzZvCf/1nA7VGBdvsOlpmt\nMLPvWJEPEnDuq8bMrjazo83s6QLy1sm2fv3qEpyZc84555L0k5/8hA4dOtCqVSuuu+46Hnnkkax5\no4GdzJo0acI777zDqlWrKCsro0+fPtXSR40aRdu2bWnVqhWnn346CxdmfxB2rnpyeffdd5k+fTr/\n8R//QbNmzdh333254oorcp5TsXb7DpZzzpWCrw1Ijsc2GR7XZHhck+OxTc5+++23/XXnzp23Pzii\nWD/72c/o1q0bJ598Mt/85je57bbbqqW3bbvjcQrNmzdny5YttWtwDmvXruWLL76gffv2tGnThtat\nW3PppZfywQcf1Fkdpf4dLOecc84559xXyJtvvrn99Zo1a+jQoUPGfPme1NeiRQtuv/12br/9dpYu\nXcrxxx/P0UcfzfHHH5/3uE8//XT7+/Xr19f6qYD7778/zZo1Y8OGDYk9WdBHsJxzrgR8bUByPLbJ\n8Lgmw+OaHI9tcu666y7WrVvHxo0bGTduHMOGDcuYr127dqxcuTJrOY8//jgrVkS/IrPXXnvRuHFj\nysrK8tbfs2dPlixZwuLFi9m6dWvWH/jNJTWlsF27dpx88slceeWVfPzxx5gZK1eu5Nlnny26zGy8\ng+Wcc84551wDEz0oqm4eOrUzD6KSxDnnnLN9Wt+BBx7IddddlzHv6NGjuemmm2jTpg133HFHjfTX\nX3+dE088kb322os+ffrw4x//mH79+m2vJ5sDDzyQG2+8kYEDB9K9e3e+853vFNT29PNIefDBB/n8\n88855JBDaNOmDWeddRbr16/PcXSRddV2gZhzbtckyfzfBeecc650JNX6oQ0uedk+n7C/Rs/QR7Cc\nc84555xzro54B8s5V4Okndra7deuvk+hwfG1Acnx2CbD45oMj2tyPLauofCnCDrnaqrYucPfrXi3\nTprhnHPOOfdV42uwnHPVSLKd7WBRUfsfAHTOOed2N74Gq2FrsGuwJHWW9HKWtFmSykvVlrS6O0ma\nL2l6bN+q+mhLNpL6S5pYQL6c7Zb0cfjbXtKk8PoCSb+pTXkF1jlG0lX5yilGvExJEyX1y5O/v6TN\n4XOeL+n6AuqYJalTnvSirllJQyQtlfR0eP+IpIWSRoXzODPP8XnPNeT7taTXQ9mHx/aPl7REUv9i\n2u2cc8455wpX6jVYDbFrPhh4ysxOje1riO0spE358hiAmb1jZkMLOK4u6mwonjWz8rD9op7aMBK4\n2MwGSmoHHGlmh5vZnXVVgaRTgW5mdiDwI+B3qTQzuxr4OXBRXdXnCudrA5LjsU2GxzUZHtfkeGxd\nQ1HqDlYTSQ+Fb/EnSWqWnkHScEmLw3Zr2NcofHu/WNIiSaPC/m6SZoRv6l+S1LUWbWoFvJe27/1Y\ne84PdS6Q9EDYN1HSnZKel/RGauRBUgtJM0NbFkkaFPZ3lrQsHLdc0sOSTgrHL5d0ZMjXXNIESXMk\nzZN0emjG58CHBZzL+6GcsaG98yW9JWlC6nRi7YmPJnYKIzLLJd2YKQ756swWqzhJB0iaLulFSbMl\ndZfUUtLqWJ7mktZKKsuUP0P9m4nik0+xP9W9AdiW7doLhkr6u6RXJfUJ7a82IihpqqR+km4A+gIT\nJP0SeBLoGD6jvtUaKpVLqgznPV1S2yLO9QzgQQAz+zuwd+x4gPVE17xzzjnnnEtAqR9ycRBwoZnN\nCTf9lwHbf4VMUnvgVqAX0c3kjNBJeQvoaGY9Qr6W4ZCHgXFmNkVSU2rXYSwDquI7zOyYUM8hwLXA\nsWa2SVL8xrSdmfWRdDAwBZgMfAYMNrMtkvYB5oQ0gG7AD8xsqaSXgGHh+EGhjjOB64CnzWykpL2B\nuZJmmtkLwAuhTUcAPzKzS9JPJNVuMxsDjAllPAukbvjjo03x10cBh4b2vyhpmpnNT5WXS4GxSrk3\ntH2FpKOBe8JozgJJ/c1sNnAa8ISZbZNUIz8wMK3+K1OvJY0FXjSzaRnqPlbSQmAd8FMzW5rnvIaE\nMsvJfO0BlJnZMWHUqAI4KXV4hvJuknQCcJWZLZB0FzDVzMpDuSPD38ZEn9cgM9sgaSgwDhhZ4Ll2\nBN6MvV8X9qWeOlFFdM3nNiv2ugtQm68uXDUDBgyo7ybssjy2yfC4JsPjmhyPrUtaZWVlQSOlpR7B\nWmtmc8Lrh4i+0Y87CphlZhvNrIqoA9UPWAl0DaNG3wU+lrQn0MHMpgCY2edm9lkxjZEkoCdRBy6T\nE4DHzGxTqGNzLO2vYd8y4BupIoFbJC0CZgIdJKXSVsVu6peEdICXiW5hAU4GRktaAFQCTYFq64DM\nbF6mzlUWDwF3mNnCPPlmmNnmEL/J1PxcCpErVkhqARwHPBbO7/dAamRlEnB2eD0MeDRP/ozMbEyW\nztU8oJOZHQ78lvDZFajGtRdLmxwrv7CfQ88/knYQcBjRlwsLiDrdHdIz5TjXfNYB3SV9LWeu42Ob\nd66cc865kmu3X7ud/tmUXFtD+kmV448/nvvuu6/Wx1944YW0adOG3r17A3DPPffQrl07WrZsycaN\nG2nUqBErV67c6XYOGDCAioqK7Vs2pR7BSv9mP9P6nRo3oGa2WVJP4LvApcBZwBWZ8lYrSLoM+GGo\n55/MbH0srRHRzfNW4PEiziFla4Y2jwD2BXqZWZWiB0A0y5C/Kva+ih2fg4hGuV6vRXuqkVRB1KGt\nMVUvg0I+l53VCNiUGrFJMwW4WVJroBx4BtgzR/6imNmW2Ovpku6W1MbMNhZwbKZr7+KQnPoMt7Hj\nM/yS6l9c1JgGm4eAV8ysT5HHpawD9o+93y/sA8DMVkpaBqyRNNDMltSyHlekyspK/3Y1IR7bZHhc\nk+FxTc6uFtt317270z+bkrP8XeQnVZ577jmefvpp3n77bZo1a8aXX37J1Vdfzdy5cznssMOA6Gl/\npVTqEazOklLTzs4B/i8tfS7QT1IbSWXAcGB2mG5XZmZ/Aa4HysNN85uSzgCQ1FTSHvHCzOxuM+sV\nHmywPi2tysy6AC+xY/Qk3TPAWZLahDpaZ8mX+tT2Bt4LnavjqT6qUcgn+yRw+fYDYk+AK4aitVsn\nAqPSk7IccpKkViF+g4HnM5S5LE+1OWNlZh8DqyQNiZXZI6R9QvQ53AlMs0jW/MWKr0EKUw2V6lwp\nWjPXPsexNa69bFnD39XA4YrsDxydq2kZ9i0Hvi6pd6i/cZh+WagpwPnh2N7AZjPb/i9oiGFXotFf\n71w555xz7itt9erVdOnShWbNou+0169fz9atWzn44IO35yn1I/BL3cF6FfixpKVEC+1TTzhLPd1u\nPTCaaHrcAqI1JlOJ1pBUhilTfwx5ILqRvDxMyXuePFPIsngNaJMpIUzpu5mok7cAGB9vbzxr+Psw\ncFRoz7nAsgx5Mh2fchPRg0AWK3oIxc/TM0g6IqxNyuVKomllLyp6iEJFnnrnEk13W0g0zW9+Wp37\n5KkvV6zizgVGKnooySvAoFjao0QjgH+O7RuRI38Nih7ucVqGpCGSXgnt+hXRNMTUFNFuQK6RrGzX\nXsZrwMyeJ+pkLQl1zUvPk+V96vgvgCHAbYrWjC0Aji30XM3sf4k6pm8QTau8LC1La2B1mILrSmhX\n+la1ofHYJsPjmgyPa3I8tsno2rUr48ePp2fPnrRu3Zrhw4fz+ec7nrn1hz/8gQMPPJB9992XwYMH\n884772QsZ+vWrZx33nnsu+++tG7dmmOOOYb339/xPLXVq1fTt29fWrZsySmnnMLGjdHt2ezZs9l/\n//2rldW1a1eeeeYZ7rvvPn74wx/ywgsv0LJlS0aMGMG3vvUtAFq3bs2JJ55Yox2ff/4511xzDZ07\nd6Z9+/ZcdtllbN26tUa+nbHb/9CwpJ8C+5jZ6LyZd1OSvgd0NbPf1ndb6pKkQ4keunJNfbelVBQ9\nNOP7ZjY8Rx7/oWHnnHOuhJThh2wlJTpFsND/V3ft2pW2bdvyP//zP3zta1/juOOO44orruCSSy7h\nmWee4eyzz2bmzJkccsghXH311SxatIjZs2fXKOfee+/l8ccfZ9KkSTRt2pSFCxdy4IEHsueee3L8\n8cfz1ltv8cQTT7DffvtxyimncOyxxzJu3Dhmz57Neeedx9q1a6u1acKECZxwwgk88MADTJgwgWef\nfRaANWvWcMABB/Dll19unxrYqFEj3njjDQ444ACuvPJKVq1axQMPPEDjxo0555xzOOyww7j55puz\nxiDT5xPbX2NGUqnXYDVEk4H7JU1P+y0sF5hZbdaoNXhhitzu1LkaD3wH+Le8mSt2rq62HWszmLxr\n29XWBjQkHttkeFyT4XFNjsc2OaNGjaJt2+j/7aeffjoLF0bPT/vTn/7EyJEj6dmzJwC33HILrVu3\nZu3atXTqVO05bTRp0oQNGzbw2muv8e1vf5tevXpVS7/wwgvp1q0bAEOHDmXq1Kk71WYzy7j26g9/\n+AMvv/wye++9NwCjR49mxIgROTtYxdrtO1hmtoLoptO5XVr4oeFC8ybZFOecc859haQ6VwDNmzff\nPg3w7bff5ogjjtie1qJFC/bZZx/WrVtXo4N1/vnn89ZbbzFs2DA+/PBDRowYwbhx4ygri349pl27\ndtXq2LJlC3Xt/fff59NPP63W5qqqqjq/7yn1GiznnNst+beqyfHYJsPjmgyPa3I8tqXXoUMH1qxZ\ns/39J5/ThHwuAAAgAElEQVR8woYNG+jYsWONvGVlZdxwww0sWbKEv/3tb0ybNo0HH3wwbx0tWrTg\n008/3f5+27Zt1dZuFWPfffelefPmLFmyhI0bN7Jx40Y2b97Mhx9+WKvysvEOlnPOOeecc65ow4cP\nZ+LEiSxevJitW7dy7bXX0rt37xqjVxBN4XzllVeoqqpizz33pEmTJttHr3Lp3r07n332GdOnT+fL\nL7/kF7/4RbWHbGSSbURKEj/84Q+54oortnfS1q1bx1NPPVXA2RZut58i6JxzpeBrA5LjsU2GxzUZ\nHtfk7GqxbduxbaK/VVXoeulcvyE1cOBAbrrpJs4880w2b97Mcccdx5///OeMedevX8+ll17KunXr\n2HPPPRk2bBjnnntu3jpatmzJ3XffzciRI6mqquJnP/sZ++23X1Ftjr+/7bbbGDt2LL17994+2vYv\n//IvnHzyyTnLLMZu/xRB51x1ksz/Xah7u9r/+BsSj20yPK7J8Lgm56sc22xPqXMNQ7FPEfQOlnOu\nGu9gOeecc6XlHayGrdgOlq/Bcs4555xzzrk64h0s51wNknaJrV27LvUdyu0qKyvruwm7LI9tMjyu\nyfC4Jsdj6xoKf8iFcy6DXWOawrvvZl8065xzzjmXBF+D5ZyrRpLtKh0s8DntzjnnGj5fg9WwNdg1\nWJI6S3o5S9osSeWlakta3Z0kzZc0PbZvVX20JRtJ/SVNLCBfznZL+jj8bS9pUnh9gaTf1Ka8Ausc\nI+mqfOUUI16mpImS+uXJP0jSIkkLJL0k6YQC6pglqeaPOFRPL+qalTRE0lJJT4f3j0haKGlUOI8z\n8xxfyLmeE851kaTnJPWIpY2XtERS/2La7Zxzzrlkde7cud6n1fuWfevcuXNRn2ep12A1xK75YOAp\nMzs1tq8htrOQNuXLYwBm9o6ZDS3guLqosyGYaWY9zawXcCFwbz21YyRwsZkNlNQOONLMDjezO+uw\njpVAPzPrCfyC2Lma2dXAz4GL6rA+VyBfG5Acj20yPK7J8Lgm56sc29WrV2NmDXKbNWtWvbehvrfV\nq1cX9XmWuoPVRNJD4Vv8SZKapWeQNFzS4rDdGvY1Ct/eLw7fzI8K+7tJmqFoFOAlSV1r0aZWwHtp\n+96Pted87Rj9eCDsmyjpTknPS3pDYeRBUgtJM0NbFkkaFPZ3lrQsHLdc0sOSTgrHL5d0ZMjXXNIE\nSXMkzZN0emjG58CHBZzL+6GcsaG98yW9JWlC6nRi7YmPJnZSNCKzXNKNmeKQr85ssYqTdICk6ZJe\nlDRbUndJLSWtjuVpLmmtpLJM+TPUv5koPlmZ2aext3sCHxRwXhuAbdmuvWCopL9LelVSn9D+aiOC\nkqZK6ifpBqAvMEHSL4EngY7hM+qbFqdySZXhvKdLSv0SYCHnOsfMUtfKHKBjWpb1RNe8c84555xL\nQKkfcnEQcKGZzQk3/ZcBd6QSJbUHbgV6Ed1MzgidlLeAjmbWI+RrGQ55GBhnZlMkNaV2HcYyoCq+\nw8yOCfUcAlwLHGtmmyTFb0zbmVkfSQcDU4DJwGfAYDPbImkfohvcKSF/N+AHZrZU0kvAsHD8oFDH\nmcB1wNNmNlLS3sBcSTPN7AXghdCmI4Afmdkl6SeSareZjQHGhDKeBVI3/PHRpvjro4BDQ/tflDTN\nzOanysulwFil3BvavkLS0cA9Fo3mLJDU38xmA6cBT5jZNkk18gMD0+q/MvVa0ljgRTObll6xpMHA\nLUA74LsFnNeQcFw5ma89gDIzO0bSqUAFcFLq8Azl3aRoauJVZrZA0l3AVDMrD+WODH8bE31eg8xs\ng6ShwDhgZKHnGnMxMD1tXxXRNZ9HRez1gLC5nfFV/fHLrwKPbTI8rsnwuCbHY5sMj+sOlZWVBY2U\nlrqDtdbM5oTXDwE/IdbBIrrRn2VmGwEkPQz0I5rq1FXSncD/Ak9J2hPoYGZTAMws5zf7mUgS0DO0\nJZMTgMfMbFOoY3Ms7a9h3zJJ30gVCdyiaJ1MFdAhlrbKzJaG10uAmeH1y0CX8Ppk4HRJPw3vmwKd\ngOWpSs1sHlCjc5XFQ8AdZrYwT74ZqXOTNJlopGV+gXWk5IoVkloAxwGPhbgDNAl/JwFnA7OBYcBd\nefJnFDqW2dL+Cvw1jBb9kaizX4iVpF17sbTJ4e88oNDJufkea3cQcBjRlwsi+tLg7fRMuc4VQNLx\nRNMh+6YlrQO6S/qamW3NXkJFnmY655xzzu1eBgwYUK3DOXbs2Iz56nsNVqb1OzVuQMPNek+gErgU\n+EO2vNUKki6LTZVrl5bWCFgFHAw8XlDrq4vfnKbaMQLYF+hl0Xqf94BmGfJXxd5XsaOjK6JRrl5h\n62pmy6kFSRVEHdoaU/UyKORz2VmNgE1mVh47v8NC2hTgFEmtgXLgmTz5a83MngMahxHGQvJnu/Zg\nx2e4jR2f4ZdU/++qxjTYPAS8EjvvnlZ9fWD+AqIHW9xLNAq2KZ5mZiuBZcAaSYcW2Ta3E77KawMa\nOo9tMjyuyfC4JsdjmwyPa/FK3cHqLCk17ewc4P/S0ucC/SS1kVQGDAdmh5vhMjP7C3A9UG5mW4A3\nJZ0BIKmppD3ihZnZ3eEmtdzM1qelVZlZF+AlotGTTJ4BzpLUJtTROku+VAdrb+A9M6sKIwidM+TJ\n5Ung8u0HSIcXcEzNxkRrt04ERqUnZTnkJEmtQvwGA89nKHNZnmpzxsrMPgZWSRoSK7NHSPuE6HO4\nE5hmkaz5iyWpW+x1eahzQ3g/M0xNzXZsjWsvW9bwdzVwuCL7A0fnalqGfcuBr0vqHepvHKZfFkTR\nkw//GzjPzFZkSO8BdCUa/V1SaLnOOeecc64wpe5gvQr8WNJSooX2vwv7U0+3Ww+MJhotWEC0xmQq\n0UL9SkkLiKZ3jQ7HnQ9cLmkRUacg9TCAYrwGtMmUEKb03UzUyVsAjI+3N541/H0YOCq051yikYL0\nPJmOT7mJ6EEgixU9hOLn6RkkHRHWJuVyJdCBaD3V/DCalaveuUTT3RYSTfOrNj2wkNGeHLGKOxcY\nqeihJK8Ag2JpjxKNAP45tm9Ejvw1KHq4x2kZkn4g6RVJ84k6ccNCfhGtjduYo9hs117Ga8DMnifq\nZC0BfkU0fZBcx6Qd/wUwBLhN0kKi/w6OLeJcbyC6nu8Oo7dz09JbA6vNrKrmoS5JPoc9OR7bZHhc\nk+FxTY7HNhke1+Lt9j80HNY77WNmo/Nm3k1J+h7Q1cx+W99tqUthityFZnZNfbelVMJDM75vZsNz\n5PEfGnbOOeecy0P1/UPDDdhkoI9iPzTsqjOzx3e1zhWAmS3ZzTpX44FrgP+s77bsjnwOe3I8tsnw\nuCbD45ocj20yPK7FK/VTBBucsE7lO/XdDueSZtEPDReokCWDDV/btsX98rpzzjnn3M7a7acIOueq\nk2T+74JzzjnnXG4+RdA555xzzjnnEuYdLOecKwGfw54cj20yPK7J8Lgmx2ObDI9r8byD5Zxzzjnn\nnHN1xNdgOeeq8TVYzjnnnHP5+Ros55xzzjnnnEuYd7Ccc64EfA57cjy2yfC4JsPjmhyPbTI8rsXb\n7X8HyzlXk/TV/B2sth3bsv6t9fXdDOecc87txnwNlnOuGklGRX23opYqwP9Nc84551wp+Bos55xz\nzjnnnEtYyTpYkjpLejlL2ixJ5aVqS1rdnSTNlzQ9tm9VfbQlG0n9JU0sIF/Odkv6OPxtL2lSeH2B\npN/UprwC6xwj6ap85RQjXqakiZL65ck/SNIiSQskvSTphALqmCWpU570oq5ZSUMkLZX0dHj/iKSF\nkkaF8zgzz/F5zzXk+7Wk10PZh8f2j5e0RFL/Ytrt6obPYU+OxzYZHtdkeFyT47FNhse1eKVeg9UQ\n5+4MBp4ys9GxfQ2xnYW0KV8eAzCzd4ChBRxXF3U2BDPNbAqApG8DfwG+WQ/tGAlcbGZ/k9QOONLM\nDgztytuBLoSkU4FuZnagpGOA3wG9AczsaklzgYuA2XVRn3POOeecq67UUwSbSHoofIs/SVKz9AyS\nhktaHLZbw75G4dv7xWEkYlTY303SjPBN/UuSutaiTa2A99L2vR9rz/mx0Y8Hwr6Jku6U9LykN1Ij\nD5JaSJoZ2rJI0qCwv7OkZeG45ZIelnRSOH65pCNDvuaSJkiaI2mepNNDMz4HPizgXN4P5YwN7Z0v\n6S1JE1KnE2tPfDSxUxiRWS7pxkxxyFdntljFSTpA0nRJL0qaLam7pJaSVsfyNJe0VlJZpvwZ6t9M\nFJ+szOzT2Ns9gQ8KOK8NwLZs114wVNLfJb0qqU9of7URQUlTJfWTdAPQF5gg6ZfAk0DH8Bn1TYtT\nuaTKcN7TJbUt9FyBM4AHw3n/Hdg7djzAeqJr3pXYgAED6rsJuyyPbTI8rsnwuCbHY5sMj2vxSj2C\ndRBwoZnNCTf9lwF3pBIltQduBXoR3UzOCJ2Ut4COZtYj5GsZDnkYGGdmUyQ1pXYdxjKgKr7DzI4J\n9RwCXAsca2abJMVvTNuZWR9JBwNTgMnAZ8BgM9siaR9gTkgD6Ab8wMyWSnoJGBaOHxTqOBO4Dnja\nzEZK2huYK2mmmb0AvBDadATwIzO7JP1EUu02szHAmFDGs0Dqhj8+2hR/fRRwaGj/i5Kmmdn8VHm5\nFBirlHtD21dIOhq4x8wGhg5ZfzObDZwGPGFm2yTVyA8MTKv/ytRrSWOBF81sWnrFkgYDtwDtgO8W\ncF5DwnHlZL72AMrM7BhFo0YVwEmpwzOUd5OiqYlXmdkCSXcBU82sPJQ7MvxtTPR5DTKzDZKGAuOA\nkQWea0fgzdj7dWHfu+F9FdE1n9us2OsuQG2+unDOOeec24VUVlYWNGWy1CNYa81sTnj9ENE3+nFH\nAbPMbKOZVRF1oPoBK4GuYdTou8DHkvYEOqSmfpnZ52b2WTGNkSSgJ1EHLpMTgMfMbFOoY3Ms7a9h\n3zLgG6kigVskLQJmAh0kpdJWmdnS8HpJSAd4megWFuBkYLSkBUAl0BSotg7IzOZl6lxl8RBwh5kt\nzJNvhpltDvGbTM3PpRC5YoWkFsBxwGPh/H4PpEZWJgFnh9fDgEfz5M/IzMZk6lyFtL+a2cHA6cAf\nizivGtdeLG1y+DsP6Fxgefmef34QcBjRlwsLiDrdHdIz5TrXPNYB3SV9LWeu42Obd67qhM9hT47H\nNhke12R4XJPjsU2Gx3WHAQMGUFFRsX3Lpr7XYGVav1PjBtTMNkvqSTTycClwFnBFprzVCpIuA34Y\n6vknM1sfS2tEdPO8FXi8iHNI2ZqhzSOAfYFeZlal6AEQzTLkr4q9r2LH5yCiUa7Xa9GeaiRVEHVo\na0zVy6CQz2VnNQI2pUZs0kwBbpbUGigHniGaypctf62Z2XOSGkvax8w2FJA/07V3cUhOfYbb2PEZ\nfkn1Ly5qTIPNQ8ArZtanyONS1gH7x97vF/YBYGYrJS0D1kgaaGZLalmPc84555zLoNQjWJ0VLbwH\nOAf4v7T0uUA/SW0klQHDgdlhul2Zmf0FuB4oN7MtwJuSzgCQ1FTSHvHCzOxuM+tlZuXxzlVIqzKz\nLsBL7Bg9SfcMcJakNqGO1lnypTpYewPvhc7V8VQf1Sjkl1ufBC7ffkDsCXDFULR260RgVHpSlkNO\nktQqxG8w8HyGMpflqTZnrMzsY2CVpCGxMnuEtE+IPoc7gWkWyZq/WJK6xV6Xhzo3hPczw9TUbMfW\nuPayZQ1/VwOHK7I/cHSupmXYtxz4uqTeof7GYfploaYA54djewObzSw1PTAVw65Eo7/euSohn8Oe\nHI9tMjyuyfC4JsdjmwyPa/FK3cF6FfixpKVEC+1/F/annm63HhhNND1uAdEak6lEa0gqw5SpP4Y8\nEN1IXh6m5D1PnilkWbwGtMmUEKb03UzUyVsAjI+3N541/H0YOCq051xgWYY8mY5PuYnoQSCLFT2E\n4ufpGSQdEdYm5XIl0bSyF8NDFCry1DuXaLrbQqJpfvPT6twnT325YhV3LjBS0UNJXgEGxdIeJRoB\n/HNs34gc+WtQ9HCP0zIk/UDSK5LmE3XihoX8IlobtzFHsdmuvYzXgJk9T9TJWgL8imj6ILmOSTv+\nC2AIcJukhUT/HRxb6Lma2f8SdUzfIJpWeVlaltbA6jAF1znnnHPO1TGZfRWesp0cST8F9kl7TLuL\nkfQ9oKuZ/ba+21KXJB1K9NCVa+q7LaUSHprxfTMbniOPUVG6NtWpCmio/6ZVVlb6t4AJ8dgmw+Oa\nDI9rcjy2yfC4ZicJM6sxI6nUa7AaosnA/ZKmm9mp9d2YhsjMarNGrcELU+R2p87VeOA7wL/lzVyR\ndGuS0bZjbQaxnXPOOefqzm4/guWcq06S+b8LzjnnnHO5ZRvBKvUaLOecc84555zbZXkHyznnSsB/\nRyQ5HttkeFyT4XFNjsc2GR7X4nkHyznnnHPOOefqiK/Bcs5V42uwnHPOOefy8zVYzjnnnHPOOZcw\n72A551wJ+Bz25Hhsk+FxTYbHNTke22R4XIvnv4PlnKtBqjHavUtq27Yz69evru9mOOecc24X4muw\nnHPVSDLYXf5dEP5voHPOOedqw9dgOeecc84551zCStbBktRZ0stZ0mZJKi9VW9Lq7iRpvqTpsX2r\n6qMt2UjqL2liAflytlvSx+Fve0mTwusLJP2mNuUVWOcYSVflK6cY8TIlTZTUL0/+gyT9TdJnhbYl\nXJOd8qQXdc1KGiJpqaSnw/tHJC2UNCqcx5l5ji/kXM+RtChsz0nqEUsbL2mJpP7FtNvVDZ/DnhyP\nbTI8rsnwuCbHY5sMj2vxSr0GqyHOxRkMPGVmo2P7GmI7C2lTvjwGYGbvAEMLOK4u6mwINgA/Ifqs\n69NI4GIz+5ukdsCRZnYgRJ2nOqpjJdDPzD6UdApwL9AbwMyuljQXuAiYXUf1Oeecc865mFJPEWwi\n6aHwLf4kSc3SM0gaLmlx2G4N+xqFb+8Xh2/mR4X93STNCKMAL0nqWos2tQLeS9v3fqw954c6F0h6\nIOybKOlOSc9LeiM18iCphaSZoS2LJA0K+ztLWhaOWy7pYUknheOXSzoy5GsuaYKkOZLmSTo9NONz\n4MMCzuX9UM7Y0N75kt6SNCF1OrH2xEcTO4URmeWSbswUh3x1ZotVnKQDJE2X9KKk2ZK6S2opaXUs\nT3NJayWVZcqfof7NRPHJysw+MLN5wJcFnE/KBmBbtmsvGCrp75JeldQntL/aiKCkqZL6SboB6AtM\nkPRL4EmgY/iM+qbFqVxSZTjv6ZLaFnGuc8wsda3MATqmZVlPdM27EhswYEB9N2GX5bFNhsc1GR7X\n5Hhsk+FxLV6pR7AOAi40sznhpv8y4I5UoqT2wK1AL6KbyRmhk/IW0NHMeoR8LcMhDwPjzGyKpKbU\nrsNYBlTFd5jZMaGeQ4BrgWPNbJOk+I1pOzPrI+lgYAowGfgMGGxmWyTtQ3SDOyXk7wb8wMyWSnoJ\nGBaOHxTqOBO4DnjazEZK2huYK2mmmb0AvBDadATwIzO7JP1EUu02szHAmFDGs0Dqhj8+2hR/fRRw\naGj/i5Kmmdn8VHm5FBirlHtD21dIOhq4x8wGhg5ZfzObDZwGPGFm2yTVyA8MTKv/ytRrSWOBF81s\nWr52F3BeQ0KZ5WS+9gDKzOwYSacCFcBJqcMzlHeTpBOAq8xsgaS7gKlmVh7KHRn+Nib6vAaZ2QZJ\nQ4FxwMhanOvFwPS0fVVE13weFbHXA8LmnHPOObf7qqysLGjKZKlHsNaa2Zzw+iGib/TjjgJmmdlG\nM6si6kD1I5r21DWMGn0X+FjSnkAHM5sCYGafm9lnxTRGkoCeRB24TE4AHjOzTaGOzbG0v4Z9y4Bv\npIoEbpG0CJgJdJCUSltlZkvD6yUhHeBloEt4fTIwWtICoBJoClRbB2Rm8zJ1rrJ4CLjDzBbmyTfD\nzDaH+E2m5udSiFyxQlIL4DjgsXB+vwdSIzOTgLPD62HAo3nyZ2RmY+qic5WmxrUXS5sc/s4DOhdY\nXr7nnx8EHEb05cICok53h/RM+c5V0vHAhcC/piWtA7pL+lruZlTEtgF5muwK4XPYk+OxTYbHNRke\n1+R4bJPhcd1hwIABVFRUbN+yqe81WJnW79S4ATWzzZJ6At8FLgXOAq7IlLdaQdJlwA9DPf9kZutj\naY2Ibp63Ao8XcQ4pWzO0eQSwL9DLzKoUPQCiWYb8VbH3Vez4HEQ0yvV6LdpTjaQKog5tjal6GRTy\nueysRsCm1IhNminAzZJaA+XAM8CeOfKXTJZr7+KQnPoMt7HjM/yS6l9c1JgGm4eAV8ysT+1aDIoe\nbHEvcEqqw5tiZislLQPWSBpoZktqW49zzjnnnKup1CNYnSWlpp2dA/xfWvpcoJ+kNpLKgOHA7DDd\nrszM/gJcD5Sb2RbgTUlnAEhqKmmPeGFmdreZ9TKz8njnKqRVmVkX4CV2jJ6kewY4S1KbUEfrLPlS\nHay9gfdC5+p4qo9qFPLLrU8Cl28/QDq8gGNqNiZau3UiMCo9KcshJ0lqFeI3GHg+Q5nL8lSbM1Zm\n9jGwStKQWJk9QtonRJ/DncA0i2TNv5OqxUDRmrn2WTNnuPbylLsaOFyR/YGjC21LsBz4uqTeof7G\nYfplQRQ9+fC/gfPMbEWG9B5AV6LRX+9clZDPYU+OxzYZHtdkeFyT47FNhse1eKXuYL0K/FjSUqKF\n9r8L+1NPt1sPjCaaHreAaI3JVKKF+pVhytQfQx6A84HLw5S858kzhSyL14A2mRLClL6biTp5C4Dx\n8fbGs4a/DwNHhfacCyzLkCfT8Sk3ET0IZLGih1D8PD2DpCPC2qRcriSaVvZieIhCRZ565xJNd1tI\nNM1vflqd++SpL1es4s4FRip6KMkrwKBY2qNEI4B/ju0bkSN/DYoe7nFahv1tJb1JFJfrFD1EY88w\nRbQbsDFHsdmuvYzXgJk9T9TJWgL8imj6ILmOSTv+C2AIcJukhUT/HRxb6LkCNxBdz3eHtW1z09Jb\nA6vDFFznnHPOOVfHZPZVeMp2ciT9FNgn7THtLkbS94CuZvbb+m5LXZJ0KNFDV66p77aUSnhoxvfN\nbHiOPPbVePp+XRCl+jewsrLSvwVMiMc2GR7XZHhck+OxTYbHNTtJmFmNGUmlXoPVEE0G7pc03cxO\nre/GNERmVps1ag1emCK3O3WuxgPfAf6tgNxJN6dBaNu20GeTOOecc84VZrcfwXLOVSfJ/N8F55xz\nzrncso1glXoNlnPOOeecc87tsryD5ZxzJeC/I5Icj20yPK7J8Lgmx2ObDI9r8byD5ZxzzjnnnHN1\nxNdgOeeq8TVYzjnnnHP5+Ros55xzzjnnnEuYd7Ccc64EfA57cjy2yfC4JsPjmhyPbTI8rsXz38Fy\nztUg7R6/gxXXtmNb1r+1vr6b4ZxzzrmvOF+D5ZyrRpJRUd+tqAcV4P8eOuecc65QvgbLOeecc845\n5xJWsg6WpM6SXs6SNktSeanaklZ3J0nzJU2P7VtVH23JRlJ/SRMLyJez3ZI+Dn/bS5oUXl8g6Te1\nKa/AOsdIuipfOcWIlylpoqR+efIfJOlvkj4rtC3hmuyUJ72oa1bSEElLJT0d3j8iaaGkUeE8zsxz\nfN5zDfl+Len1UPbhsf3jJS2R1L+Ydru64XPYk+OxTYbHNRke1+R4bJPhcS1eqddgNcT5N4OBp8xs\ndGxfQ2xnIW3Kl8cAzOwdYGgBx9VFnQ3BBuAnRJ91fRoJXGxmf5PUDjjSzA6EqPNUFxVIOhXoZmYH\nSjoG+B3QG8DMrpY0F7gImF0X9TnnnHPOuepKPUWwiaSHwrf4kyQ1S88gabikxWG7NexrFL69Xyxp\nkaRRYX83STPCN/UvSepaiza1At5L2/d+rD3nhzoXSHog7Jso6U5Jz0t6IzXyIKmFpJmhLYskDQr7\nO0taFo5bLulhSSeF45dLOjLkay5pgqQ5kuZJOj0043PgwwLO5f1QztjQ3vmS3pI0IXU6sfbERxM7\nhRGZ5ZJuzBSHfHVmi1WcpAMkTZf0oqTZkrpLailpdSxPc0lrJZVlyp+h/s1E8cnKzD4ws3nAlwWc\nT8oGYFu2ay8YKunvkl6V1Ce0v9qIoKSpkvpJugHoC0yQ9EvgSaBj+Iz6psWpXFJlOO/pktoWeq7A\nGcCD4bz/DuwdOx5gPdE170pswIAB9d2EXZbHNhke12R4XJPjsU2Gx7V4pR7BOgi40MzmhJv+y4A7\nUomS2gO3Ar2IbiZnhE7KW0BHM+sR8rUMhzwMjDOzKZKaUrsOYxlQFd9hZseEeg4BrgWONbNNkuI3\npu3MrI+kg4EpwGTgM2CwmW2RtA8wJ6QBdAN+YGZLJb0EDAvHDwp1nAlcBzxtZiMl7Q3MlTTTzF4A\nXghtOgL4kZldkn4iqXab2RhgTCjjWSB1wx8fbYq/Pgo4NLT/RUnTzGx+qrxcCoxVyr2h7SskHQ3c\nY2YDQ4esv5nNBk4DnjCzbZJq5AcGptV/Zeq1pLHAi2Y2LV+7CzivIaHMcjJfewBlZnaMolGjCuCk\n1OEZyrtJ0gnAVWa2QNJdwFQzKw/ljgx/GxN9XoPMbIOkocA4YGSB59oReDP2fl3Y9254X0V0zec2\nK/a6C1Cbry6cc84553YhlZWVBU2ZLPUI1tr/z97dB1lV3fn+f39AGUVRwQcezIiG0hhujIpRY3S0\n9RcxMdF4URIfMliJo0lhqZiYKn6Z3HSjRIzGRJ0px2gcEgVrkHtJBjWKQLodRRGE5kFB1AkasYJ6\no6hMER3le/9Y3wO7T5/d54He3QjfV1VX77P32nt993fvA2edtdZuM1voy9NI3+hnHQu0mtlbZraZ\n1IA6GfgjcIj3Gp0BvCdpT2CYmc0GMLMPzOyv9QQjScCRpAZcJacBM83sba9jQ2bb73zdauCA0iGB\nKZKWA/OAYZJK29aa2Spffs63A6wkfYQFGA1MlNQOtAH9gA7zgMxsSaXGVY5pwM/NbFmVcnPNbIPn\nbxUygQ8AACAASURBVBadr0stusoVkvYAvgDM9PP7JVDqWbkf+IYvnw/MqFK+IjNr7o7GVZlO915m\n2yz/vQQYXuPxqj3//FPAZ0hfLrSTGt3Dygttw7m+Bhwm6W+6LHVq5icaV90ixrAXJ3JbjMhrMSKv\nxYncFiPyulVTUxMtLS1bfvL09hysSvN3On0ANbMNko4EzgC+C4wFJlQq2+FA0njgUq/nTDNbn9nW\nh/Th+X3goTrOoeT9CjFfBOwHHG1mm5UeALFbhfKbM683s/U6iNTL9WID8XQgqYXUoO00VK+CWq7L\ntuoDvF3qsSkzG/iJpIHAKOAPwJ5dlO8xOffeP/jm0jX8iK3X8EM6fnHRaRhsFQKeNbMTG4uY14C/\nzbz+hK8DwMz+KGk18Iqk/8/MnmuwnhBCCCGEUEFP92ANV5p4D3Ah8HjZ9kXAyZIGSeoLXAA85sPt\n+prZb4EfAaPMbCPwqqSvAUjqJ2n37MHM7HYzO9rMRmUbV75ts5kdDDzD1t6Tcn8Axkoa5HUMzClX\namDtDbzhjatT6dirUctfbp0DXLllh8wT4OqhNHfri8BV5Ztydjld0j6ev3OABRWOubpKtV3mysze\nA9ZKOi9zzM/6tv8iXYdbgQctyS2/jTrkQGnO3NDcwhXuvSrHfRk4SsnfAsfVGotbA+wv6fNe/y4+\n/LJWs4Fxvu/ngQ1mVhoeWMrhIaTe32hc9aAYw16cyG0xIq/FiLwWJ3JbjMhr/Xq6gfU8cLmkVaSJ\n9nf4+tLT7dYDE0nD49pJc0weIM0hafMhU/d6GUgfJK/0IXkLqDKELMcLwKBKG3xI309Ijbx24OZs\nvNmi/ns6cKzH801gdYUylfYvuY70IJAVSg+huLa8gKRjfG5SV64mDStb7A9RaKlS7yLScLdlpGF+\nS8vq3LdKfV3lKuubwCVKDyV5Fjg7s20GqQfw3zLrLuqifCdKD/f4aoX1gyW9SsrLPyo9RGNPHyI6\nAniri8Pm3XsV7wEzW0BqZD0H3EIaPkhX+5Tt/9/AecBPJS0jvQ9OqPVczez3pIbpS6RhlePLigwE\nXvYhuCGEEEIIoZvJ7OPwlO3iSPoBsG/ZY9pDhqSvAIeY2T/3dizdSdL/ID105ZrejqWn+EMz/qeZ\nXdBFGaOl52LabrRAkf8etrW1xbeABYncFiPyWozIa3Eit8WIvOaThJl1GpHU03OwtkezgF9LetjM\nvtzbwWyPzKyROWrbPR8itzM1rm4G/g74/6sWbik6mu3P4AMb6QAPIYQQQuhop+/BCiF0JMni34UQ\nQgghhK7l9WD19BysEEIIIYQQQthhRQMrhBB6QPwdkeJEbosReS1G5LU4kdtiRF7rFw2sEEIIIYQQ\nQugmMQcrhNBBzMEKIYQQQqgu5mCFEEIIIYQQQsGigRVCCD0gxrAXJ3JbjMhrMSKvxYncFiPyWr9o\nYIUQOpFU2M+QIQf39umFEEIIIRQm5mCFEDqQZFDkvwsi/t0JIYQQwsddzMEKIYQQQgghhIIV2sCS\nNFzSypxtrZJGFVl/HkkHSVoq6eHMurW9EUseSadImlpDubrjlnSVpN1ytl0s6TZfbpY0rsqxLpbU\nXKXMe/XGWE3pmH6PtdZQvlXS85La/drvV6V8l/n37Q/UGXM/SXO9/rGSTpL0rL8+PO+9ktm/6rlK\n2l3Sg5JWS1op6frMtsO8vhn1xB26R4xhL07kthiR12JEXosTuS1G5LV+PdGDtT2OBToHeNTMvpxZ\ntz3GWUtMjcQ9AejfwH6NxlBEbi1nuSsXmNnRZjbKzP5vnXU0sr3cKMC8/pnARcD1ZjYK2FTj8Wop\nc5OZfRo4GjhJ0hmkil8ws88AR0g6pM7YQwghhBBCDXqigbWrpGmSVkm6v1LPiaQLJK3wnxt8XR9J\nU33dcklX+foR3guwTNIzDX5Q3Ad4o2zdm5l4xnmd7ZJ+4+umSrpV0gJJL0ka4+v3kDTPY1ku6Wxf\nP9x7EaZKWiNpuqTTff81kj7n5fpLulvSQklLJJ3lYXwAvFPDubzpx5mU6Z1Z58fs770Z7Z7HsZKu\nAIYBrZLm+77f8pgWAidmjr2R9MG/K5u8HJIOkDTLr027pM+XUprJ7TWSFnmZZl83RdL4TJlmSd/L\nK1/mI+CtGvIE9d3vW/LvvVWl3C6RtIeXGSBppl/nezPxr5U0yJeP8d6z/YF7gWP9OJcBXweuy+7r\n+/SRdKOkp/28L631XM1sk5k95ssfAkuBT5QVe530Hgg9qKmpqbdD2GFFbosReS1G5LU4kdtiRF7r\nt0sP1PEp4FtmtlDS3cB44OeljZKGAjeQvm3fAMz1Rso64EAz+6yX28t3mU761n+2pH401kjsC2zO\nrjCz472ekcAPgRPM7G1J2Q+iQ8zsREmfBmYDs4C/AueY2UZJ+wILfRvACOBcM1sl6RngfN//bK9j\nDPCPwHwzu0TS3sAiSfPM7CngKY/pGOA7ZnZZ+YmU4jazZqDZj/EfwD8DXwJeM7Ov+nEGmNl7kq4G\nmvz8hgAtpPy/C7SRPpRjZjdXS6SZ3Z95eRvQZmZjJAnYs1TM6z8dONTMjvPtsyWdBMwAbgFu9/Jf\nB0bnlTezJ/BGm5mtA87z4w8F7iqdbwW/lvTfwCwzm1zlvLbkH/g+MN7MnpLUn3TNAY4CRgLrgQWS\nvmBmT9K5l8nM7E1J/wB838xKjfATgAfMbJak4ZnylwAbzOx4v8cXSHrUzF6p41zxe/csUm6zNpPe\nA11oySw3+U8IIYQQws6rra2tpiGTPdGD9SczW+jL04CTyrYfC7Sa2VtmtpnUgDoZ+CNwiPcanQG8\nJ2lPYJiZzQYwsw/M7K/UwT+oH0lqwFVyGjDTzN72OjZktv3O160GDigdEpgiaTkwDxgmqbRtrZmt\n8uXnfDvASuBgXx4NTJTUTmrc9AMOygZkZksqNa5yTANuNrN2r+d07yE6ycxKc6HE1l6l49ma/w9J\njZ1GnQb8i8dsmfpKRns8S0mNuE+RGlDLgP0lDZH0WeAtM3str3xe5Wb25y4aHBea2RHA3wF/J+mb\ndZzXAuAX3vs30O9TgEVepwHL2HpNOz1Npk6jgXF+TzwNDKLsvKucK5L6AvcBt5jZy2Wb15HeA11o\nyfw01R55yBVj2IsTuS1G5LUYkdfiRG6LEXndqqmpiZaWli0/eXqiB6vTt/kVynT6QGpmGyQdCZwB\nfBcYS5o71OWHVx9qdqnXc6aZrc9s60NquL0PPFTHOZS8XyHmi4D9gKPNbLPSQyd2q1B+c+b1Zrbm\nXqRerhcbiKcDSS2kBu09AGb2otKDRM4EJnvPWKWem21tEJRUmx8kYIqZ3VVh20zSNR7C1kZeV+Xr\nmv9kZn/23/8l6T7gOFJjtJZ9fyrpQeArpN6k0b4pe30/Yus1/ZCtX15UfJhIFQKuMLO5Dexbciew\nxsz+qcK2XwJzJB1nZt/ZhjpCCCGEEEKZnujBGi7peF++EHi8bPsi4GRJg/xb9wuAx3y4XV8z+y3w\nI2CUmW0EXpX0NdjyVLbdswczs9szDzJYX7Zts5kdDDwDfCMn3j8AYzNzaAbmlCs1SvYG3vDG1anA\n8AplujIHuHLLDtJRNezTOZg0d+uLwFWZdUOBTWZ2H3AT6SELkIYCloZcPk3K/0BJu5IaOZWOf3l2\nnlSO+aQhoKV5RANKu/vvOcC3S3OYJA3zuUkA9wPnA+eSGlt55fcrO2ZVkvr6/YSf41eBZ/31Oco8\naS9n/0+a2XNmdiOwGDi8SpVrgWN8+dxa48yYA4yXtIvXf2j5fV4l3snAXmZ2dU6Ra4BLonHVs2IM\ne3Eit8WIvBYj8lqcyG0xIq/164kG1vPA5ZJWkSbW3+HrDcAbQRNJw+PagcVm9gBwINDmw6Tu9TIA\n44ArfUjeAmBwAzG9QBp21YkP6fsJqZHXDpTmIeX1xE0nPbhgOfBNYHWFMpX2L7mO9CCQFUqP6b62\nvIA/KOHOLs4H4GrSwysW+0MUWoAjSHO62oEfA6Xeq7uARyTN9/xPIs0dexxY1enIyeHAX6rEMAE4\nVdIKUiN2pK8vXeu5pGFrT3mZmfg8Lc/7AGCdmb3eRfkB2WNmSRrqPU3l/obUY7OMNNRwnecA0jy5\nag8TmaD0yPPlpIdfPFyhTDaea4HbJC0i9WblybsnfkW6Dkv9nriDst7mvHOVdCBpft9IbX0wx7fL\nig0EXuoirhBCCCGE0CCl6SM7F0k/APY1s4lVCwcAJM0Gxvg8rR2GpHuAq82sWuNxh+BzEFcA55nZ\nmpwyVuxfLRA74787bW1t8S1gQSK3xYi8FiPyWpzIbTEir/kkYWadRlX1RA/W9mgWcKIyf2g4dM3M\nzt7RGlcAZjZuJ2pcHUbqJW4n9eKGEEIIIYRutlP2YIUQ8qUerOIMHjyc9etfLrKKEEIIIYTC5fVg\n9cRTBEMIHzPxxUsIIYQQQmN21iGCIYTQo+LviBQncluMyGsxIq/FidwWI/Jav2hghRBCCCGEEEI3\niTlYIYQOJFn8uxBCCCGE0LV4imAIIYQQQgghFCwaWCGE0ANiDHtxIrfFiLwWI/JanMhtMSKv9YsG\nVgghhBBCCCF0k5iDFULooLv+DtbgAwezft367jhUCCGEEMJ2J28OVjSwQggdSDJauuFALfH3tEII\nIYSw44qHXIQQQi+KMezFidwWI/JajMhrcSK3xYi81q/QBpak4ZJW5mxrlTSqyPrzSDpI0lJJD2fW\nre2NWPJIOkXS1BrK1R23pKsk7Zaz7WJJt/lys6RxVY51saTmKmXeqzfGakrH9HustYbyrZKel9Tu\n136/KuW7zL9vf6DOmPtJmuv1j5V0kqRn/fXhee+VzP61nusoSSskvSDplsz6w7y+GfXEHUIIIYQQ\natcTPVjb4xihc4BHzezLmXXbY5y1xNRI3BOA/g3s12gMReTWcpa7coGZHW1mo8zs/9ZZRyPby40C\nzOufCVwEXG9mo4BNNR6vljL/AlxiZocBh0k6g1TxC2b2GeAISYfUGXvYRk1NTb0dwg4rcluMyGsx\nIq/FidwWI/Jav55oYO0qaZqkVZLur9RzIukC/8Z9haQbfF0fSVN93XJJV/n6Ed4LsEzSMw1+UNwH\neKNs3ZuZeMZ5ne2SfuPrpkq6VdICSS9JGuPr95A0z2NZLulsXz9c0mrfb42k6ZJO9/3XSPqcl+sv\n6W5JCyUtkXSWh/EB8E4N5/KmH2dSpndmnR+zv6QHff0K7zW5AhgGtEqa7/t+y2NaCJyYOfZG0gf/\nrmzyckg6QNIsvzbtkj5fSmkmt9dIWuRlmn3dFEnjM2WaJX0vr3yZj4C3asgT1He/b8m/91aVcrtE\n0h5eZoCkmX6d783Ev1bSIF8+xnvP9gfuBY7141wGfB24Lruv79NH0o2SnvbzvrTWc5U0BBhgZot9\n1T2kLxSyXie9B0IIIYQQQjfbpQfq+BTwLTNbKOluYDzw89JGSUOBG4CjgQ3AXG+krAMONLPPerm9\nfJfppG/9Z0vqR2ONxL7A5uwKMzve6xkJ/BA4wczelpT9IDrEzE6U9GlgNjAL+CtwjpltlLQvsNC3\nAYwAzjWzVZKeAc73/c/2OsYA/wjMN7NLJO0NLJI0z8yeAp7ymI4BvmNml5WfSCluM2sGmv0Y/wH8\nM/Al4DUz+6ofZ4CZvSfpaqDJz28I0ELK/7tAG7DUj3lztUSa2f2Zl7cBbWY2RpKAPUvFvP7TgUPN\n7DjfPlvSScAM4Bbgdi//dWB0XnkzewJvtJnZOuA8P/5Q4K7S+Vbwa0n/Dcwys8lVzmtL/oHvA+PN\n7ClJ/UnXHOAoYCSwHlgg6Qtm9iSde5nMzN6U9A/A982s1Ag/AXjAzGZJGp4pfwmwwcyO93t8gaRH\nzeyVGs71QNJ7p2Sdr8vaTHoP5MsORDwYiP6ubdbW1hbfAhYkcluMyGsxIq/FidwWI/K6VVtbW01z\n0nqigfUnM1voy9OAK8g0sIBjgVYzewtA0nTgZGAycIikW4HfA49K2hMYZmazAczsg3qD8Q/qR3os\nlZwGzDSzt72ODZltv/N1qyUdUDokMEXSyaQPrsMy29aa2Spffg6Y58srSR9bAUYDZ0n6gb/uBxwE\nrClVamZLgE6NqxzTgJvNrF3SRuBnkqYAD3nDpBRzqVfpeDrmfwZwaI11lTsN+HuP2YDyuVejgdMl\nLfX69yA1oKZK2t8bewcAb5nZa5ImVCoPPEEFZvZnIK9xdaGZ/dl7n2ZJ+qaZ5d0D5RYAv/B7c5bH\nBrDI60TSMtI1fZJMj12DRpOG8Y3113uRzvuVUoEq51rNOtJ74JncEqc2eOQQQgghhB1UU1NTh8bm\npEmTKpbriQZWp2/zK5Tp9IHUzDZIOhI4A/guMJY0d6jLD68+1OxSr+dMM1uf2dYH+CPwPvBQHedQ\n8n6FmC8C9gOONrPNSg+d2K1C+c2Z15vZmnuRerlebCCeDiS1kBq09wCY2YtKDxI5E5jsPWOVem62\ntUFQUm1+kIApZnZXhW0zSdd4CKlHq1r5uuY/lRpCZvZfku4DjiO/kV2+708lPQh8hdSbNNo3Za/v\nR2y9ph+ytWe14sNEqhBwhZnNbWDf14C/zbz+hK/L+iUwR9JxZvadBuoIDYhv/4oTuS1G5LUYkdfi\nRG6LEXmtX0/MwRou6XhfvhB4vGz7IuBkSYMk9QUuAB7z4XZ9zey3wI+AUWa2EXhV0tdgy1PZds8e\nzMxuzzzIYH3Zts1mdjDpm/tv5MT7B2BsZg7NwJxypUbJ3sAb3rg6FRheoUxX5gBXbtlBOqqGfToH\nk+ZufRG4KrNuKLDJzO4DbiI9ZAHSUMDSkMunSfkfKGlXUiOn0vEvz86TyjGfNAS0NI9oQGl3/z0H\n+HZpDpOkYT43CeB+4HzgXFJjK6/8fmXHrEpSX7+f8HP8KvCsvz5H0vVV9v+kmT1nZjcCi4HDq1S5\nFjjGl8+tNc6MOcB4Sbt4/YeW3+d5/J5/R1JpWOU44N/Lil1DeghGNK5CCCGEELpZTzSwngcul7SK\nNLH+Dl9vsOUD4UTS3J92YLGZPUCaN9ImqZ30cICJvt844EpJy0lDtwY3ENMLwKBKG3xI309Ijbx2\noDQPKa8nbjrpwQXLgW8CqyuUqbR/yXWkB4GsUHpM97XlBZQelHBnF+cDcDXp4RWLlR6i0AIcQZrT\n1Q78mDTsEuAu4BFJ8z3/k0hzxx4HVnU6cnI48JcqMUwATpW0gtSIHenrS9d6LnAf8JSXmYnP0/K8\nDwDWmdnrXZQfkD1mlqSh3tNU7m9IPTbLSPPL1nkOIM2Tq/YwkQmSVvo1/gB4uEKZbDzXArdJWkTq\nzcqTd0/8inQdlvo9cQdlvc1dnCvA5cDdpPv8RTN7pGz7QOClLuIKBYi/I1KcyG0xIq/FiLwWJ3Jb\njMhr/ZSmyuxcfL7TvmY2sWrhAICk2cAYM+uqwfCxI+ke4Gozq9Z43CF4r9YK4DwzW5NTxmjphspa\nYGf89yVPTBIuTuS2GJHXYkReixO5LUbkNZ8kzKzTqKqdtYE1Avg1sLHsb2GFsMOSdBhpKOYK4GLL\nefNL6pZ/FAYfOJj169ZXLxhCCCGE8DEUDawQQk0k5bW9QgghhBCCy2tg9cQcrBBC2OnFGPbiRG6L\nEXktRuS1OJHbYkRe6xcNrBBCCCGEEELoJjFEMITQQQwRDCGEEEKoLoYIhhBCCCGEEELBooEVQgg9\nIMawFydyW4zIazEir8WJ3BYj8lq/aGCFEEIIIYQQQjeJOVghhA666+9g7QgGDx7O+vUv93YYIYQQ\nQtgOxd/BCiHUJDWw4t+FRMS/kSGEEEKoJB5yEUIIvSjGsBcncluMyGsxIq/FidwWI/Jav0IbWJKG\nS1qZs61V0qgi688j6SBJSyU9nFm3tjdiySPpFElTayhXd9ySrpK0W862iyXd5svNksZVOdbFkpqr\nlHmv3hirKR3T77HWGso/LKld0rOSfiVplyrlu8y/b3+gzpj7SZrr995YSSd5PEslHZ73XsnsX/Vc\nJe0u6UFJqyWtlHR9ZtthXt+MeuIOIYQQQgi164kerO1xfM05wKNm9uXMuu0xzlpiaiTuCUD/BvZr\nNIYicms5y3nGmtnRZvYZYB/gG3XW0cj2cqMAM7NRZjYTuAi43sxGAZtqPF4tZW4ys08DRwMnSTqD\nVPELfv5HSDqkztjDNmpqaurtEHZYkdtiRF6LEXktTuS2GJHX+vVEA2tXSdMkrZJ0f6WeE0kXSFrh\nPzf4uj6Spvq65ZKu8vUjvBdgmaRnGvyguA/wRtm6NzPxjPM62yX9xtdNlXSrpAWSXpI0xtfvIWme\nx7Jc0tm+frj3IkyVtEbSdEmn+/5rJH3Oy/WXdLekhZKWSDrLw/gAeKeGc3nTjzPJ410qaZ0fs7/3\nZrR7HsdKugIYBrRKmu/7fstjWgicmDn2RtIH/65s8nJIOkDSLL827ZI+X0ppJrfXSFrkZZp93RRJ\n4zNlmiV9L698mY+At6olycxKMe4K9AP+UmWXLfn33qpSbpdI2sPLDJA006/zvZn410oa5MvHKPXW\n7g/cCxzrx7kM+DpwXXZf36ePpBslPe3nfWmt52pmm8zsMV/+EFgKfKKs2Ouk90AIIYQQQuhuZlbY\nDzAc2Ax83l/fDXzPl1tJ3+gPBV4BBpEafPOBs33bo5lj7eW/FwJn+3I/YLcG4poETMjZNhJ4Hhjo\nr/fx31OBGb78aeBFX+4L7OnL+2bWDyd9SB/pr58B7vbls4FZvvwT4EJf3htYA+xeFtMxwJ01ntve\nwHJS78UY4JeZbQP89x8z5zckk/9dgCeA2xq83v8GXOnLytT3rv8+vRSPb38AOAk4CmjLHOc54MC8\n8v76vQr1DwUe7CK+R0gNqxl1ntds4ARf7u/36SnA216ngCeBL2TyOyhz7f7gy6cAszPHnQqMydwv\nK3z5UuCHmXt8MTC8nnMt3bvAfwIHl62fD3yui/0MmjM/rQa2k/5g3aW1tbXbjhU6itwWI/JajMhr\ncSK3xYi8btXa2mrNzc1bfvxzQqfPUl3OQ+kmfzKzhb48DbgC+Hlm+7FAq5m9BSBpOnAyMBk4RNKt\nwO+BRyXtCQwzs9mkM/qg3mAkCTjSY6nkNGCmmb3tdWzIbPudr1st6YDSIYEpkk4mNSaHZbatNbNV\nvvwcMM+XVwIH+/Jo4CxJP/DX/YCDSA0tvL4lwGU1nuI04GYza5e0EfiZpCnAQ2b2RCbmUq/S8XTM\n/wzg0BrrKnca8PceswHlc69GA6dLWur17wEcamZTJe0vaQhwAPCWmb0maUKl8qRGYCdm9mfgq3nB\nmdmXJPUD7pc0zszuqfG8FgC/8HtzlscGsMjrRNIy0jV9kkyPXYNGk4bxjfXXe5HO+5XMuXR5rpL6\nAvcBt5jZy2Wb15HeA8/kh9BSf9QhhBBCCDuwpqamDkMmJ02aVLFcTzSwyueMVJpD0ukDqZltkHQk\ncAbwXWAsae5Qlx9efajZpV7PmWa2PrOtD6l34X3goTrOoeT9CjFfBOwHHG1mm5UeOrFbhfKbM683\nszX3As41sxcbiKcDSS2kBu09AGb2otKDRM4EJkuaZ2aTK+26rXW7Ste2vJ4pZnZXhW0zSdd4CDCj\nhvLV6qocoNkHkv4PcBxQUwPLzH4q6UHgK8ACSaN9U/b6fsTWa/ohW4ffVnyYSBUCrjCzuQ3sW3In\nsMbM/qnCtl8CcyQdZ2bf2YY6Qh1iDHtxIrfFiLwWI/JanMhtMSKv9euJOVjDJR3vyxcCj5dtXwSc\nLGmQf+t+AfCYpH2Bvmb2W+BHwChL82helfQ12PJUtt2zBzOz2y09zGBUtnHl2zab2cGkb+7zHnLw\nB2BsZg7NwJxypUbJ3sAb3rg6lTTUq7xMV+YAV27ZQTqqhn06B5Pmbn0RuCqzbiiwyczuA24iDbsE\neJfUKwLwNCn/A31+0lgqkHR5dp5UjvnAeC/fR9KA0u7+ew7w7dIcJknDfG4SwP3A+cC5pMZWXvn9\nyo5ZldI8uSG+vAupobTMX5+jzJP2cvb/pJk9Z2Y3kobrHV6lyrWkoYH4+dRrDjDeY0XSoeX3eZV4\nJ5OG1F6dU+Qa4JJoXIUQQgghdL+eaGA9D1wuaRVpTsgdvj5N9kiNoIlAG9AOLDazB0hzcNoktZMe\nDjDR9xsHXClpOWno1uAGYnqBNOeoEx/S9xNSI68duDkbb7ao/55OenDBcuCbwOoKZSrtX3Id6UEg\nK5Qe031teQF/UMKdXZwPwNWkh1cs9ocotABHAIv8PH5MGnYJcBfwiKT5nv9JpLltjwOrOh05OZzq\nD4aYAJwqaQWpETvS15eu9VzSsLWnvMxMYE/ftgoYAKwzs9e7KD8ge8wsSUO9p6ncHsBsH8a3BHgV\n+FffNoLqDxOZoPTI8+WkeXUPVyiTjeda4DZJi0i9WXny7olfka7DUr8n7qCstznvXCUdCPwQGJl5\nMMe3y4oNBF7qIq5QgPg7IsWJ3BYj8lqMyGtxIrfFiLzWT2mqzM7F5zvta2YTqxYOAEiaTXogQ1cN\nho8dSfcAV5tZtcbjDsHnIK4AzjOzNTllbPv8qwW9QXTXv5FtbW0xzKIgkdtiRF6LEXktTuS2GJHX\nfJIws06jqnbWBtYI4NfARuv4t7BC2GFJOow0FHMFcLHlvPlTAysADB48nPXrX+7tMEIIIYSwHYoG\nVgihJpLy2l4hhBBCCMHlNbB6Yg5WCCHs9GIMe3Eit8WIvBYj8lqcyG0xIq/1iwZWCCGEEEIIIXST\nGCIYQugghgiGEEIIIVQXQwRDCCGEEEIIoWDRwAohhB4QY9iLE7ktRuS1GJHX4kRuixF5rV80sEII\nIYQQQgihm8QcrBBCBzvj38EafOBg1q9b39thhBBCCOFjJP4OVgihJpKMlt6Oooe1QPxbGEIIIYR6\nxEMuQgihF8UY9uJEbosReS1G5LU4kdtiRF7rV2gDS9JwSStztrVKGlVk/XkkHSRpqaSHM+vW0G7j\nMgAAIABJREFU9kYseSSdImlqDeXqjlvSVZJ2y9l2saTbfLlZ0rgqx7pYUnOVMu/VG2M1pWP6PdZa\nQ/mHJbVLelbSryTtUqV8l/n37Q/UGXM/SXP93hsr6SSPZ6mkw/PeK5n9az3XUZJWSHpB0i2Z9Yd5\nfTPqiTuEEEIIIdSuJ3qwtsdxN+cAj5rZlzPrtsc4a4mpkbgnAP0b2K/RGIrIreUs5xlrZkeb2WeA\nfYBv1FlHI9vLjQLMzEaZ2UzgIuB6MxsFbKrxeLWU+RfgEjM7DDhM0hmkil/w8z9C0iF1xh62UVNT\nU2+HsMOK3BYj8lqMyGtxIrfFiLzWrycaWLtKmiZplaT7K/WcSLrAv3FfIekGX9dH0lRft1zSVb5+\nhPcCLJP0TIMfFPcB3ihb92YmnnFeZ7uk3/i6qZJulbRA0kuSxvj6PSTN81iWSzrb1w+XtNr3WyNp\nuqTTff81kj7n5fpLulvSQklLJJ3lYXwAvFPDubzpx5nk8S6VtM6P2V/Sg75+hfeaXAEMA1olzfd9\nv+UxLQROzBx7I+mDf1c2eTkkHSBpll+bdkmfL6U0k9trJC3yMs2+boqk8ZkyzZK+l1e+zEfAW9WS\nZGalGHcF+gF/qbLLlvx7b1Upt0sk7eFlBkia6df53kz8ayUN8uVjlHpr9wfuBY7141wGfB24Lruv\n79NH0o2SnvbzvrTWc5U0BBhgZot91T2kLxSyXie9B0IIIYQQQjfrcphUN/kU8C0zWyjpbmA88PPS\nRklDgRuAo4ENwFxvpKwDDjSzz3q5vXyX6aRv/WdL6kdjjcS+wObsCjM73usZCfwQOMHM3paU/SA6\nxMxOlPRpYDYwC/grcI6ZbZS0L7DQtwGMAM41s1WSngHO9/3P9jrGAP8IzDezSyTtDSySNM/MngKe\n8piOAb5jZpeVn0gpbjNrBpr9GP8B/DPwJeA1M/uqH2eAmb0n6Wqgyc9vCNBCyv+7QBuw1I95c7VE\nmtn9mZe3AW1mNkaSgD1Lxbz+04FDzew43z5b0knADOAW4HYv/3VgdF55M3sCb7SZ2TrgPD/+UOCu\n0vmWk/QIcCwwz8weqXJeW/IPfB8Yb2ZPSepPuuYARwEjgfXAAklfMLMn6dzLZGb2pqR/AL5vZqVG\n+AnAA2Y2S9LwTPlLgA1mdrzf4wskPWpmr9RwrgeS3jsl63xd1mbSeyBfdiDiwUD0d22ztra2+Baw\nIJHbYkReixF5LU7kthiR163a2tpqmpPWEw2sP5nZQl+eBlxBpoFF+sDbamZvAUiaDpwMTAYOkXQr\n8HvgUUl7AsPMbDaAmX1QbzD+Qf1Ij6WS04CZZva217Ehs+13vm61pANKhwSmSDqZ9MF1WGbbWjNb\n5cvPAfN8eSXpYyvAaOAsST/w1/2Ag4A1pUrNbAnQqXGVYxpws5m1S9oI/EzSFOAhb5iUYi71Kh1P\nx/zPAA6tsa5ypwF/7zEbUD73ajRwuqSlXv8epAbUVEn7e2PvAOAtM3tN0oRK5YEnqMDM/gxUbFz5\n9i95g+V+SePM7J4az2sB8Au/N2d5bACLvE4kLSNd0yfJ9Ng1aDRpGN9Yf70X6bxfyZxLl+daxTrS\ne+CZ3BKnNnjkEEIIIYQdVFNTU4fG5qRJkyqW64kGVqdv8yuU6fSB1Mw2SDoSOAP4LjCWNHeoyw+v\nPtTsUq/nTDNbn9nWB/gj8D7wUB3nUPJ+hZgvAvYDjjazzUoPnditQvnNmdeb2Zp7kXq5Xmwgng4k\ntZAatPcAmNmLSg8SOROY7D1jkyvtuq11u2rzgwRMMbO7KmybSbrGQ0g9WtXKNzSvy8w+kPR/gONI\nw+dq2eenkh4EvkLqTRrtm7LX9yO2XtMP2dqzWvFhIlUIuMLM5jaw72vA32Zef8LXZf0SmCPpODP7\nTgN1hAbEt3/FidwWI/JajMhrcSK3xYi81q8n5mANl3S8L18IPF62fRFwsqRBkvoCFwCP+XC7vmb2\nW+BHwCifR/OqpK/Blqey7Z49mJnd7g8zGJVtXPm2zWZ2MOmb+7yHHPwBGJuZQzMwp1ypUbI38IY3\nrk4Fhlco05U5wJVbdpCOqmGfzsGkuVtfBK7KrBsKbDKz+4CbSA9ZgDQUsDTk8mlS/gf6/KSxVCDp\n8uw8qRzzSUNAS/OIBpR2999zgG+X5jBJGuZzkwDuB84HziU1tvLK71d2zKqU5skN8eVdSA2lZf76\nHEnXV9n/k2b2nJndCCwGDq9S5VrgGF8+t9Y4M+YA4z1WJB1afp/n8Xv+HUmlYZXjgH8vK3YN6SEY\n0bgKIYQQQuhmPdHAeh64XNIq0sT6O3y9wZYPhBNJc3/agcVm9gBp3kibpHbSwwEm+n7jgCslLScN\n3RrcQEwvAIMqbfAhfT8hNfLagdI8pLyeuOmkBxcsB74JrK5QptL+JdeRHgSyQukx3deWF1B6UMKd\nXZwPwNWkh1csVnqIQgtwBGlOVzvwY9KwS4C7gEckzff8TyLNHXscWNXpyMnhVH8wxATgVEkrSI3Y\nkb6+dK3nAvcBT3mZmfg8Lc/7AGCdmb3eRfkB2WNmSRrqPU3l9iDN31oGLAFeBf7Vt42g+sNEJkha\n6df4A+DhCmWy8VwL3CZpEak3K0/ePfEr0nVY6vfEHZT1NndxrgCXA3eT7vMXK8w3Gwi81EVcoQDx\nd0SKE7ktRuS1GJHX4kRuixF5rZ/SVJmdi8932tfMJlYtHACQNBsYY2ZdNRg+diTdA1xtZtUajzsE\n79VaAZxnZmtyyhgtPRpW72uBov8tjEnCxYncFiPyWozIa3Eit8WIvOaThJl1GlW1szawRgC/BjaW\n/S2sEHZYkg4jDcVcAVxsOW9+STvdPwqDDxzM+nXrqxcMIYQQQnDRwAoh1ERSXtsrhBBCCCG4vAZW\nT8zBCiGEnV6MYS9O5LYYkddiRF6LE7ktRuS1ftHACiGEEEIIIYRuEkMEQwgdxBDBEEIIIYTqYohg\nCCGEEEIIIRQsGlghhNADYgx7cSK3xYi8FiPyWpzIbTEir/WLBlYIIYQQQgghdJOYgxVC6GBn/DtY\nYccxePBw1q9/ubfDCCGEsBOIv4MVQqhJamDFvwvh40rE/2shhBB6QjzkIoQQelVbbwewA2vr7QB2\nSDHvohiR1+JEbosRea1foQ0sScMlrczZ1ippVJH155F0kKSlkh7OrFvbG7HkkXSKpKk1lKs7bklX\nSdotZ9vFkm7z5WZJ46oc62JJzVXKvFdvjNWUjun3WGsN5SdL+pOkd2s8fpf59+0P1B4xSOonaa7f\ne2MlnSTpWX99eN57JbN/1XOVtLukByWtlrRS0vWZbYd5fTPqiTuEEEIIIdSuJ3qwtsexGucAj5rZ\nlzPrtsc4a4mpkbgnAP0b2K/RGIrIreUs55kNHLsNdTSyvdwowMxslJnNBC4CrjezUcCmGo9XS5mb\nzOzTwNHASZLOIFX8gpl9BjhC0iF1xh62WVNvB7ADa+rtAHZITU1NvR3CDinyWpzIbTEir/XriQbW\nrpKmSVol6f5KPSeSLpC0wn9u8HV9JE31dcslXeXrR3gvwDJJzzT4QXEf4I2ydW9m4hnndbZL+o2v\nmyrpVkkLJL0kaYyv30PSPI9luaSzff1w70WYKmmNpOmSTvf910j6nJfrL+luSQslLZF0lofxAfBO\nDefyph9nkse7VNI6P2Z/781o9zyOlXQFMAxolTTf9/2Wx7QQODFz7I2kD/5d2eTlkHSApFl+bdol\nfb6U0kxur5G0yMs0+7opksZnyjRL+l5e+TIfAW9VS5KZLTKz16uVy9iSf++tKuV2iaQ9vMwASTP9\nOt+biX+tpEG+fIxSb+3+wL3AsX6cy4CvA9dl9/V9+ki6UdLTft6X1nquZrbJzB7z5Q+BpcAnyoq9\nTnoPhBBCCCGE7mZmhf0Aw4HNwOf99d3A93y5lfSN/lDgFWAQqcE3Hzjbtz2aOdZe/nshcLYv9wN2\nayCuScCEnG0jgeeBgf56H/89FZjhy58GXvTlvsCevrxvZv1w0of0kf76GeBuXz4bmOXLPwEu9OW9\ngTXA7mUxHQPcWeO57Q0sJ/VejAF+mdk2wH//MXN+QzL53wV4Aritwev9b8CVvqxMfe/679NL8fj2\nB4CTgKOAtsxxngMOzCvvr9+rUP9Q4MEqMb7bwHnNBk7w5f5+n54CvO11CngS+EImv4My1+4PvnwK\nMDtz3KnAmMz9ssKXLwV+mLnHFwPDGzjXfYD/BA4uWz8f+FwX+xk0Z35aDSx+tvkn8tgzucVC92ht\nbe3tEHZIkdfiRG6LEXndqrW11Zqbm7f8+P85lP/sQvH+ZGYLfXkacAXw88z2Y4FWM3sLQNJ04GRg\nMnCIpFuB3wOPStoTGGZms0ln9EG9wUgScKTHUslpwEwze9vr2JDZ9jtft1rSAaVDAlMknUxqTA7L\nbFtrZqt8+Tlgni+vBA725dHAWZJ+4K/7AQeRGlp4fUuAy2o8xWnAzWbWLmkj8DNJU4CHzOyJTMyl\nXqXj6Zj/GcChNdZV7jTg7z1mA8rnXo0GTpe01OvfAzjUzKZK2l/SEOAA4C0ze03ShErlSY3ATszs\nz8BXG4y9KwuAX/i9OctjA1jkdSJpGemaPkmmx65Bo0nD+Mb6671I5/1KqUC1c5XUF7gPuMXMXi7b\nvI70HngmP4SW+qMOIYQQQtiBNTU1dRgyOWnSpIrleqKBZVVeQ4UPpGa2QdKRwBnAd4GxpLlDXX54\n9aFml3o9Z5rZ+sy2PqTehfeBh+o4h5L3K8R8EbAfcLSZbVZ66MRuFcpvzrzezNbcCzjXzF5sIJ4O\nJLWQGrT3AJjZi0oPEjkTmCxpnplNrrTrttbtKl3b8nqmmNldFbbNJF3jIcCMGspXq6vbmNlPJT0I\nfAVYIGm0b8pe34/Yek0/ZOvw24oPE6lCwBVmNreReN2dwBoz+6cK234JzJF0nJl9ZxvqCHVp6u0A\ndmBNvR3ADinmXRQj8lqcyG0xIq/164k5WMMlHe/LFwKPl21fBJwsaZB/634B8JikfYG+ZvZb4EfA\nKDPbCLwq6Wuw5alsu2cPZma3m9nRlh4ksL5s22YzO5j0zf03cuL9AzA2M4dmYE65UqNkb+ANb1yd\nShrqVV6mK3OAK7fsIB1Vwz6dg0lzt74IXJVZNxTYZGb3ATeRhl0CvEvqFQF4mpT/gZJ2JTVyKh3/\n8uw8qRzzgfFevo+kAaXd/fcc4NulOUyShvncJID7gfOBc0mNrbzy+5Uds14d9pN0jjJP2qu4g/RJ\nM3vOzG4kDdc7vEoda0lDAyGdT73mAOMl7eL1H1p+n1eJdzJpSO3VOUWuAS6JxlUIIYQQQvfriQbW\n88DlklaR5oTc4esNwBtBE0l/yKQdWGxmD5Dm4LRJaic9HGCi7zcOuFLSctLQrcENxPQCac5RJz6k\n7yekRl47cHM23mxR/z2d9OCC5cA3gdUVylTav+Q60oNAVig9pvva8gL+oIQ7uzgfgKtJD69Y7A9R\naAGOABb5efyYNOwS4C7gEUnzPf+TSHPbHgdWdTpycjjwlyoxTABOlbSC1Igd6etL13ouadjaU15m\nJrCnb1sFDADWmT+MIqf8gOwxsyQN9Z6mTiT9VNKrwO5Kj2v/sW8aQfWHiUxQeuT5ctK8uocrlMnG\ncy1wm6RFpN6sPHn3xK9I12Gp3xN3UNbbnHeukg4EfgiMzDyY49tlxQYCL3URVyhEW28HsANr6+0A\ndkjxt2+KEXktTuS2GJHX+ilNldm5+Hynfc1sYtXCAQBJs0kPZOiqwfCxI+ke4Gozq9Z43CH4HMQV\nwHlmtianjPXgCMydSBsxlK0obWzNrdgZ/18rQltbWwwNKkDktTiR22JEXvNJwsw6jaraWRtYI4Bf\nAxut49/CCmGHJekw0lDMFcDFlvPmjwZW+HiLBlYIIYSeEQ2sEEJNUgMrhI+nwYOHs379y70dRggh\nhJ1AXgOrJ+ZghRA+Zir9TYf42baf1tbWXo9hR/3J5jYaV90n5l0UI/JanMhtMSKv9YsGVgghhBBC\nCCF0kxgiGELoQJLFvwshhBBCCF2LIYIhhBBCCCGEULBoYIUQQg+IMezFidwWI/JajMhrcSK3xYi8\n1i8aWCGEEEIIIYTQTWIOVgihg5iDFUIIIYRQXd4crF16I5gQwvZN6vRvRQg7ncEHDmb9uvW9HUYI\nIYSPmejBCiF0IMlo6e0odkBrgUN6O4gdVFG5bUl/E25n1dbWRlNTU2+HscOJvBYncluMyGu+eIpg\nCCGEEEIIIRSs0AaWpOGSVuZsa5U0qsj680g6SNJSSQ9n1q3tjVjySDpF0tQaytUdt6SrJO2Ws+1i\nSbf5crOkcVWOdbGk5ipl3qs3xmpKx/R7rLWG8pMl/UnSuzUev8v8+/YHao8YJPWTNNfvvbGSTpL0\nrL8+PO+9ktm/1nMdJWmFpBck3ZJZf5jXN6OeuEM3id6r4kRuCxHfWBcj8lqcyG0xIq/164kerO1x\nfMU5wKNm9uXMuu0xzlpiaiTuCUD/BvZrNIYicms5y3lmA8duQx2NbC83CjAzG2VmM4GLgOvNbBSw\nqcbj1VLmX4BLzOww4DBJZ5AqfsHMPgMcISk+koYQQgghFKAnGli7SpomaZWk+yv1nEi6wL9xXyHp\nBl/XR9JUX7dc0lW+foT3AiyT9EyDHxT3Ad4oW/dmJp5xXme7pN/4uqmSbpW0QNJLksb4+j0kzfNY\nlks629cPl7Ta91sjabqk033/NZI+5+X6S7pb0kJJSySd5WF8ALxTw7m86ceZ5PEulbTOj9lf0oO+\nfoX3mlwBDANaJc33fb/lMS0ETswceyPpg39XNnk5JB0gaZZfm3ZJny+lNJPbayQt8jLNvm6KpPGZ\nMs2SvpdXvsxHwFvVkmRmi8zs9WrlMrbk33urSrldImkPLzNA0ky/zvdm4l8raZAvH6PUW7s/cC9w\nrB/nMuDrwHXZfX2fPpJulPS0n/eltZ6rpCHAADNb7KvuIX2hkPU66T0QetJ21Ue+g4ncFiL+9k0x\nIq/FidwWI/Jav554iuCngG+Z2UJJdwPjgZ+XNkoaCtwAHA1sAOZ6I2UdcKCZfdbL7eW7TCd96z9b\nUj8aayT2BTZnV5jZ8V7PSOCHwAlm9rak7AfRIWZ2oqRPk3pEZgF/Bc4xs42S9gUW+jaAEcC5ZrZK\n0jPA+b7/2V7HGOAfgflmdomkvYFFkuaZ2VPAUx7TMcB3zOyy8hMpxW1mzUCzH+M/gH8GvgS8ZmZf\n9eMMMLP3JF0NNPn5DQFaSPl/F2gDlvoxb66WSDO7P/PyNqDNzMZIErBnqZjXfzpwqJkd59tnSzoJ\nmAHcAtzu5b8OjM4rb2ZP4I02M1sHnOfHHwrcVTrfbZHNP/B9YLyZPSWpP+maAxwFjATWAwskfcHM\nnqRzL5OZ2ZuS/gH4vpmVGuEnAA+Y2SxJwzPlLwE2mNnxfo8vkPSomb1Sw7keSHrvlKzzdVmbSe+B\nfNmBiAcTQ7BCCCGEsNNra2urqcHZEw2sP5nZQl+eBlxBpoFFGrbVamZvAUiaDpwMTAYOkXQr8Hvg\nUUl7AsPMbDaAmX1QbzD+Qf1Ij6WS04CZZva217Ehs+13vm61pANKhwSmSDqZ9MF1WGbbWjNb5cvP\nAfN8eSXpYyvAaOAsST/w1/2Ag4A1pUrNbAnQqXGVYxpws5m1S9oI/EzSFOAhb5iUYi71Kh1Px/zP\nAA6tsa5ypwF/7zEbUD73ajRwuqSlXv8epAbUVEn7e2PvAOAtM3tN0oRK5YEnqMDM/gxsc+OqggXA\nL/zenOWxASzyOpG0jHRNnyTTY9eg0aRhfGP99V6k836lVGAbz3Ud6T3wTG6JUxs8csgXjdTiRG4L\nEfMuihF5LU7kthiR162ampo65GPSpEkVy/VEA6vTt/kVynT6QGpmGyQdCZwBfBcYS5o71OWHVx9q\ndqnXc6aZrc9s6wP8EXgfeKiOcyh5v0LMFwH7AUeb2Walh07sVqH85szrzWzNvUi9XC82EE8HklpI\nDdp7AMzsRaUHiZwJTPaescmVdt3Wul21+UECppjZXRW2zSRd4yGkHq1q5XtszpyZ/VTSg8BXSL1J\no31T9vp+xNZr+iFbe1YrPkykCgFXmNncBvZ9DfjbzOtP+LqsXwJzJB1nZt9poI4QQgghhJCjJ+Zg\nDZd0vC9fCDxetn0RcLKkQZL6AhcAj/lwu75m9lvgR8AoM9sIvCrpa7DlqWy7Zw9mZreb2dH+IIH1\nZds2m9nBpG/uv5ET7x+AsZk5NANzypUaJXsDb3jj6lRgeIUyXZkDXLllB+moGvbpHEyau/VF4KrM\nuqHAJjO7D7iJ9JAFSEMBS0Munyblf6CkXUmNnErHvzw7TyrHfNIQ0NI8ogGl3f33HODbpTlMkob5\n3CSA+4HzgXNJja288vuVHbNeHfaTdI6k67vcQfqkmT1nZjcCi4HDq9SxFjjGl89tIMY5wHhJu3j9\nh5bf53n8nn9HUmlY5Tjg38uKXUN6CEY0rnpSzBMqTuS2EDHvohiR1+JEbosRea1fTzSwngcul7SK\nNLH+Dl9vsOUD4UTS3J92YLGZPUCaN9ImqZ30cICJvt844EpJy0lDtwY3ENMLwKBKG3xI309Ijbx2\noDQPKa8nbjrpwQXLgW8CqyuUqbR/yXWkB4GsUHpM97XlBfxBCXd2cT4AV5MeXrHYH6LQAhxBmtPV\nDvyYNOwS4C7gEUnzPf+TSHPHHgdWdTpycjjwlyoxTABOlbSC1Igd6etL13oucB/wlJeZic/T8rwP\nANaVHkaRU35A9phZkoZ6T1Mnkn4q6VVgd6XHtf/YN42g+sNEJkha6df4A+DhCmWy8VwL3CZpEak3\nK0/ePfEr0nVY6vfEHZT1Nnd1rsDlwN2k+/xFM3ukbPtA4KUu4gohhBBCCA3SzvhX6n2+075mNrFq\n4QCApNnAGDPrqsHwsSPpHuBqM6vWeNwheK/WCuA8M1uTU8Zo6dGwQtg+tcDO+H9kCCGE2kjCzDqN\nqtpZG1gjgF8DG8v+FlYIOyxJh5GGYq4ALracN7+kne8fhRAqGHzgYNavW1+9YAghhJ1SXgOrJ4YI\nbnfM7D/N7O+icRV2Jv6Hho8ys3F5jatM2fjp5p/W1tZej2FH/Skqtzt74yrmXRQj8lqcyG0xIq/1\n2ykbWCGEEEIIIYRQhJ1yiGAIIZ8ki38XQgghhBC6FkMEQwghhBBCCKFg0cAKIYQeEGPYixO5LUbk\ntRiR1+JEbosRea1fNLBCCCGEEEIIoZvEHKwQQgcxByuEEEIIobq8OVi79EYwIYTtW/p7xD1v8ODh\nrF//cq/UHUIIIYTQHWKIYAihAuuVn9dff6VHzq43xBj24kRuixF5LUbktTiR22JEXusXDawQQggh\nhBBC6Cbd0sCSNFzSypxtrZJGdUc99ZJ0kKSlkh7OrFvbG7HkkXSKpKk1lFvrv3NzXVZ+gKRXJd2W\nPYakQXXEVjVXfn0P6mL7xZL+qdY6a4zr4tJ5SWqWNK5K+WMltfvPcknfqKGOqZJOrrJ9TJ1xnyTp\nWb8n/0bSTZJWSvqpn8f3quxfy7l+UdIzfp6LJZ2a2fZ9Sc/Xcv6h+zU1NfV2CDusyG0xIq/FiLwW\nJ3JbjMhr/bpzDtb2OCv+HOBRM5uYWbc9xllLTJaznOc64LEG6tmW8kUfp1ErgWPMbLOkIcCzkv63\nmX3Uw3FcBFxvZvcBSLoUGGhmJqm5m+p4E/iqma2X9D+AOcAnAMzsZklPADcBM7qpvhBCCCGEkNGd\nQwR3lTRN0ipJ90varbyApAskrfCfG3xdH+8NWOHful/l60dImitpmX8jf0gDMe0DvFG27s1MPOO8\nznZJv/F1UyXdKmmBpJdKvRSS9pA0L9M7cLavHy5pte+3RtJ0Saf7/mskfc7L9Zd0t6SFkpZIOsvD\n+AB4p4ZzebN8haS7Mj0zb0j6X77+GOAA4NHyXYArvf7lkg7LnNu/+jVYJul/5tVZwV+Aj/w4X/Jj\nL5M0t0K8+0n635Ke9p8TlKyVtFem3AuS9q9UvkL9G4FNXQVoZn81s83+cnfgnRoaVxtI1wZJN3jP\n0zJJN2bKnFLhPjlF0gOZc/knv88u+X/s3X28XeOd///XWyZpSkhECNLmRvodlY6kSaiaKkfRjpmh\nqqXUXfvwQItSN50avRGlqlW+37T90dGaNCWtikGjmhE0J+0DKXIrEtFqOqhJUKIyo5Tz/v2xrs06\n+6x9d5yVHSef5+NxHvZe67PW+lyfvU/s61zXtTZwJHCRpGsl/QwYAiySdERVnXaRNDeNQC2ovE7A\nC020dZnttenxQ8BgSQNzIWuBoQ3aHkoQc9jLE7UtR9S1HFHX8kRtyxF1bV1fjmDtCnzK9kJJ1wCn\nAldUdkraCbgUmEz24fWO1El5Ahhle2KKq3zQnkX21/45kgbRu87gAKArv8H2Xuk6E4Dzgb1tPydp\nWC5sR9vvk7QbMAe4CfgLcJjtDZK2AxamfQDjgY/aXinpAeCodPyh6RqHA18E7rJ9oqShwH2S7rR9\nL3BvymkqcIrtk6sbUsm7attJ6bjRwFxghiQB3yIbLTmooCZP2Z4q6TPAucDJwJeB9bnXYGitaxbk\n8LF0zAjgamAf249V1bNiOnCF7XskvR243fYESbcAHwFmSnoP8AfbT0uaVR0PTKi6/uWVx5JOyTb5\n6uoLp/P+OzAO+EQT7TorHTec7HV/Z3q+TS6s6H0CBSN2tq+RtA9wq+2b0rn+bHtKepwfwbqa7H3w\naMr7KuAA2/nfp5ptzcV8DFhs+6+5zV009Xs/Lfe4I/2EEEIIIWy+Ojs7m+pw9mUH6zHbC9Pj64DP\nkutgAXsC820/C5A+PO8LXAyMkzQd+AUwT9IQYGfbcwBsv9xqMqmjMSnlUuQDwGzbz6VrrM/tuyVt\nWyVph8opga8rW5fTBeyc27fG9sr0+CHgzvT4QWBsevxB4BBJn0/PBwGjgdWVi9peRNYDx74QAAAg\nAElEQVThaaWdg4HZwOm2n5B0GnCb7SezElB9v+2b038XkXVqAA4EXluXY7uZEbVq7wUW2H4snWN9\nQcyBwG7ptQEYImlL4AbgK8BM4Chen75WK76Q7X+rs+8+4O8k7QrcLmm+7T830a7ngRcl/QC4Dfh5\nbl/R++QNkbQV8PfA7Fy7B1bH1WtrOs+7gK/Ts5P9DLC9pGE1XqNkWvNJh6bEHPbyRG3LEXUtR9S1\nPFHbckRdX9fR0dGtHhdeeGFhXJlrsIrW3fT4ch3b6yVNAj4EfBo4AvhcUWy3E0mnAiel6/xjZVpU\n2rcF8HvgJbIPxa16qSDnY4ARwOS0lmcNMLggviv3PD9aILJRrt/2Ip96rgJutD0/Pd8b2CfVZ2uy\nqZsv2D6/KtdX6fvvQWv05UkC9qoaUQG4V9mU0BFk6+a+Wi9eb+A7mmyvlvQo8H/IOpmN4l9No0gH\nkL03T0+Pofh98grdR1t7TJVtYAvgucrIVm9IehvZaNpxtv+Q32f7RUnXA7+X9HHbPaZyhhBCCCGE\n3uvLNVhjJFWmlH0C+HXV/vuAfSUNlzQAOBpYkKbbDbB9M/AlYIrtDcDjkj4MIGmQpLfmT2b7StuT\nbU/Jd67Svi7bY4EHyI3MVPklcESaAoakbWvEVT44DyWbXtel7M5sYwpi6rkdOOO1A6R3N3FMXWm0\naojtyyrbbB9re6ztXcimAP4o17mq5Q7gtNx5e0zvU7b+bKc651gIvF/SmBRfVM95wJm5c07K7buZ\nbMRzZW5kpV580ySNTe85Un7vAH6bns9UWidX49itgGG2/xM4G5hYKzT997+ACZIGpjoeUCM+f8xr\nbL8ArEnT+yo51LpmUb5DyUbZvpAbUc7vH0b2OzEqOlcbV8xhL0/UthxR13JEXcsTtS1H1LV1fdnB\nehg4TdJKsptLfC9tN0DqBJ0HdAJLgPtt3wqMAjolLQGuTTEAx5PdkGEZcDcwshc5PQIU3pY8Ten7\nGlknbwlQWctTayRuFrBnyudYYFVBTNHxFReRjSYtV3ab9a9WB0iaKqnmmpoC5wC7K7vJxWJJjaYX\n1srtYmC4sluGL6FqwU2aqjYeeLbmie1nyKY33pzOcX1B2JnAHspusLECOCW37wayUcLrm4zvQdIp\nNWqwD7BM0uJ0nZNz0wMnAk/WOe3WwM/T6/4r4Ky0vfB9YvuJdI0VqS2Lq2PqPK84FjhR2U01VgCH\nVgfUaevpZK/VV3LvixG5/UOBdbbr3iwjhBBCCCH0jux230G7PGm903ZVt2kPLUrreT5l+9x259KX\nJG0N/MD2ZvO9UGm643TbRXdkrMS4fXfWF/3536QQQggh9B+SsN1jRlJ/72CNB34IbLB9cJvTCaGt\nJJ1DNkp4me2f1Ilr2z8KI0eOYe3aP7Tr8iGEEEIITavVwerLKYKbHNuP2n5/dK5CyG5pn9Ys1uxc\n5WLb8tOfO1cxh708UdtyRF3LEXUtT9S2HFHX1vXrDlYIIYQQQgghbEz9eopgCKF1khz/LoQQQggh\n1LdZThEMIYQQQgghhI0pOlghhLARxBz28kRtyxF1LUfUtTxR23JEXVsXHawQQgghhBBC6COxBiuE\n0E2swQohhBBCaCzWYIUQmiapz392fNuO7W5WCCGEEELpYgQrhNCNJDOthBNPy75fa3PV2dlJR0dH\nu9Pol6K25Yi6liPqWp6obTmirrXFCFYIIYQQQgghlKxPOliSxkh6sMa++ZKm9MV1WiVptKTFkubm\ntq1pRy61SNpP0owm4tak/9asdVX81pIel/Tt/DkkDW8ht4a1Sq/v6Dr7T5D0nWav2WReJ1TaJekC\nScc3iN9T0pL0s0zSx5u4xgxJ+zbYf3iLee8jaUV6T75F0mWSHpT0jdSOsxsc37CtKe5fJf1W0ipJ\nH8xtP0fSw820P/S9+OtfeaK25Yi6liPqWp6obTmirq3ryxGsTXHuz2HAPNsH57Ztink2k5NrPK7l\nImBBL67zRuLLPk9vPQhMtT0Z+BDw/0ka0IY8jgEusT3F9kvAScBE21/oqwtI2g04EtgNOBi4UpIA\nbF8OnACc1lfXCyGEEEII3fVlB2ugpOskrZR0g6TB1QGSjpa0PP1cmrZtkUYDlqfRhTPT9vGS7pC0\nVNIDksb1IqdhwFNV257O5XN8uuYSSTPTthmSpku6W9LvKqMUkraSdGfKZZmkQ9P2MWmkYIak1ZJm\nSTooHb9a0h4pbktJ10haKGmRpENSGi8DzzfRlqerN0j6fm5k5ilJX07bpwI7APOqDwHOSNdfJulv\nc2379/QaLJX0kVrXLPAn4NV0nn9I514q6Y6CfEdIulHSb9LP3sqskbRNLu4RSdsXxRdcfwPwYr0E\nbf/Fdld6+lbgeduvNmjXerLXBkmXppGnpZK+mYvZr+B9sp+kW3Nt+U56n51I1vG5SNK1kn4GDAEW\nSTqiqk67SJor6X5JCyqvE/BCo7YCHwaut/2K7T8AvwXek9u/Fhja4ByhBPE9IuWJ2pYj6lqOqGt5\norbliLq27m/68Fy7Ap+yvVDSNcCpwBWVnZJ2Ai4FJpN9eL0jdVKeAEbZnpjiKh+0Z5H9tX+OpEH0\nrjM4AOjKb7C9V7rOBOB8YG/bz0kalgvb0fb70mjAHOAm4C/AYbY3SNoOWJj2AYwHPmp7paQHgKPS\n8YemaxwOfBG4y/aJkoYC90m60/a9wL0pp6nAKbZPrm5IJe+qbSel40YDc4EZabTiW2SjJQcV1OQp\n21MlfQY4FzgZ+DKwPvcaDK11zYIcPpaOGQFcDexj+7GqelZMB66wfY+ktwO3254g6RbgI8BMSe8B\n/mD7aUmzquOBCVXXv7zyWNIp2SZfXX3hdN5/B8YBn2iiXWel44aTve7vTM+3yYUVvU+gYMTO9jWS\n9gFutX1TOtefbU9Jjy/IhV9N9j54NOV9FXCA7fzvU622jiK9n5I/pm0VXTTzez8/93gsWdVCCCGE\nEDZjnZ2dTXU4+7KD9ZjthenxdcBnyXWwgD2B+bafBUgfnvcFLgbGSZoO/AKYJ2kIsLPtOQC2X241\nmdTRmJRyKfIBYLbt59I11uf23ZK2rZK0Q+WUwNeVrcvpAnbO7Vtje2V6/BBwZ3r8INnHU4APAodI\n+nx6PggYDayuXNT2IrIOTyvtHAzMBk63/YSk04DbbD+ZlYDqO5vcnP67iKxTA3Ag8Nq6HNvNjKhV\ney+wwPZj6RzrC2IOBHZLrw3AEElbAjcAXwFmAkcBP20QX8j2v9XZdx/wd5J2BW6XNN/2n5to1/PA\ni5J+ANwG/Dy3r+h98oZI2gr4e2B2rt0Dq+PqtbWBZ4DtJQ2r8Rpl9u/l2UNNMYe9PFHbckRdyxF1\nLU/UthxR19d1dHR0q8eFF15YGNeXHazqv9oXrbvpcRtD2+slTSJbG/Np4Ajgc0Wx3U4knUq2hsXA\nP9pem9u3BfB74CWyD8Wteqkg52OAEcBk213KbgAxuCC+K/c8P1ogslGu3/Yin3quAm60XRlz2BvY\nJ9Vna7Kpmy/YPr8q11fp29cfGrxmaf9etv9atf1eZVNCR5Ctm/tqvfjX+x2ts71a0qPA/yHrZDaK\nfzWNIh1A9t48PT2G4vfJK3Qfbe0xVbaBLYDnKiNbvfBH4O25529L2wCw/aKk64HfS/q47R5TOUMI\nIYQQQu/15RqsMZIqU8o+Afy6av99wL6Shiu7wcDRwII03W6A7ZuBLwFTbG8AHpf0YQBJgyS9NX8y\n21fanpxuGLC2al+X7bHAA+RGZqr8EjgiTQFD0rY14iofnIeSTa/rkrQ/MKYgpp7bgTNeO0B6dxPH\n1JVGq4bYvqyyzfaxtsfa3oVsCuCPcp2rWu4gd+ODoul9ytaf7VTnHAuB90sak+KL6jkPODN3zkm5\nfTeTjXiuzI2s1ItvmqSx6T1Hyu8dZGuTkDRTaZ1cjWO3AobZ/k/gbGBirdD03/8CJkgamOp4QI34\n/DGvsf0CsEbSx3I51LpmkTnAUel3ZhxZW+/LnWsY2e/EqOhcbVwxh708UdtyRF3LEXUtT9S2HFHX\n1vVlB+th4DRJK8luLvG9tN0AqRN0HtAJLAHut30r2fqQTklLgGtTDMDxZDdkWAbcDYzsRU6PAIW3\nJU9T+r5G1slbAlTW8tQaiZsF7JnyORZYVRBTdHzFRWSjScuV3Wb9q9UBkqZK6rF+qI5zgN2V3eRi\nsaRG0wtr5XYxMFzZLcOXAB1VeYlsndmzNU9sP0M2vfHmdI7rC8LOBPZQdoONFcApuX03kI0SXt9k\nfA+STqlRg32AZZIWp+ucnJseOBF4ss5ptwZ+nl73XwFnpe2F7xPbT6RrrEhtWVwdU+d5xbHAicpu\nqrECOLQ6oFZb0/v6BmAl2ZTbU939232HAutsN7pZRgghhBBC6AV1/+zVv6T1TtvZPq9hcKhJ0rvI\nbmBybrtz6UuStgZ+YHuz+V6oNN1xuu2iOzJWYsy0Ei4+DfrzvzchhBBC2LxIwnaPGUn9vYM1Hvgh\nsKHqu7BC2OxIOodslPAy2z+pE1fKPwojR41k7RNrGweGEEIIIbwJ1Opg9eUUwU2O7Udtvz86VyFk\nt7RPaxZrdq5ysX3+s7l3rmIOe3mituWIupYj6lqeqG05oq6t69cdrBBCCCGEEELYmPr1FMEQQusk\nOf5dCCGEEEKob7OcIhhCCCGEEEIIG1N0sEIIYSOIOezlidqWI+pajqhreaK25Yi6ti46WCGEEEII\nIYTQR2INVgihm1iDFUIIIYTQWK01WH/TjmRCCJs2qce/FWEjGTlyDGvX/qHdaYQQQgihl2KKYAih\ngOOnz3/mNxW3bt1/NfMChZxYH1COqGs5oq7lidqWI+rauuhghRBCCCGEEEIf6ZMOlqQxkh6ssW++\npCl9cZ1WSRotabGkublta9qRSy2S9pM0o4m4Nem/NWtdFb+1pMclfTt/DknDW8itYa3S6zu6zv4T\nJH2n2Ws2mdcJlXZJukDS8Q3ih0v6paQX8vVocMwMSfs22H94i3nvI2lFek++RdJlkh6U9I3UjrMb\nHN9MWw+U9ICkZZLul7R/bt85kh6W9PFW8g59paPdCfRbHR0d7U6hX4q6liPqWp6obTmirq3ryxGs\nTXFV/GHAPNsH57Ztink2k5NrPK7lImBBL67zRuLLPk9v/QX4EnBOm/M4BrjE9hTbLwEnARNtf6EP\nr/E08M+2JwGfBK6t7LB9OXACcFofXi+EEEIIIeT0ZQdroKTrJK2UdIOkwdUBko6WtDz9XJq2bZFG\nA5anv7qfmbaPl3SHpKXpL/LjepHTMOCpqm1P5/I5Pl1ziaSZadsMSdMl3S3pd5VRCklbSbozNzpw\naNo+RtKqdNxqSbMkHZSOXy1pjxS3paRrJC2UtEjSISmNl4Hnm2jL09UbJH0/5b5E0lOSvpy2TwV2\nAOZVHwKcka6/TNLf5tr27+k1WCrpI7WuWeBPwKvpPP+Qzr1U0h0F+Y6QdKOk36SfvZVZI2mbXNwj\nkrYvii+4/gbgxXoJ2v5f2/cALzXRnor1ZK8Nki5NI09LJX0zF7NfwftkP0m35trynfQ+OxE4ErhI\n0rWSfgYMARZJOqKqTrtImptGoBZUXifghSbausz22vT4IWCwpIG5kLXA0BbqEPpMZ7sT6LdifUA5\noq7liLqWJ2pbjqhr6/ryLoK7Ap+yvVDSNcCpwBWVnZJ2Ai4FJpN9eL0jdVKeAEbZnpjiKh+0Z5H9\ntX+OpEH0rjM4AOjKb7C9V7rOBOB8YG/bz0kalgvb0fb7JO0GzAFuIhsFOcz2BknbAQvTPoDxwEdt\nr5T0AHBUOv7QdI3DgS8Cd9k+UdJQ4D5Jd9q+F7g35TQVOMX2ydUNqeRdte2kdNxoYC4wQ5KAb5GN\nlhxUUJOnbE+V9BngXOBk4MvA+txrMLTWNQty+Fg6ZgRwNbCP7ceq6lkxHbjC9j2S3g7cbnuCpFuA\njwAzJb0H+IPtpyXNqo4HJlRd//LKY0mnZJt8daO8m2jXWemcw8le93em59vkworeJ1AwYmf7Gkn7\nALfavimd68+2p6THF+TCryZ7Hzya6nEVcIDt/O9Tw7ZK+hiw2PZfc5u7aOr3flrucQcxvS2EEEII\nm7vOzs6mOpx92cF6zPbC9Pg64LPkOljAnsB8288CpA/P+wIXA+MkTQd+AcyTNATY2fYcANsvt5pM\n6mhMSrkU+QAw2/Zz6Rrrc/tuSdtWSdqhckrg68rW5XQBO+f2rbG9Mj1+CLgzPX4QGJsefxA4RNLn\n0/NBwGhgdeWitheRdXhaaedgYDZwuu0nJJ0G3Gb7yawEVN9v++b030VknRqAA4HX1uXYbmZErdp7\ngQW2H0vnWF8QcyCwW3ptAIZI2hK4AfgKMBM4Cvhpg/hCtv+tF3k38jzwoqQfALcBP8/tK3qfvCGS\ntgL+Hpida/fA6rhGbZX0LuDr9OxkPwNsL2lYjdcomdZ80qFJHe1OoN+K9QHliLqWI+panqhtOaKu\nr+vo6OhWjwsvvLAwri87WNV/tS9ad9Pjy3Vsr5c0CfgQ8GngCOBzRbHdTiSdSraGxcA/VqZFpX1b\nAL8nmxJ2WwttqMhPJavkcQwwAphsu0vZDSAGF8R35Z7nRwtENsr1217kU89VwI2256fnewP7pPps\nTTZ18wXb51fl+ip9/z1ojb48ScBeVSMqAPcqmxI6gmzd3FfrxWsjfkeT7VfTKNIBZO/N09NjKH6f\nvEL30dYeU2Ub2AJ4rjKy1RuS3kY2mnac7T/k99l+UdL1wO8lfdx2j6mcIYQQQgih9/pyDdYYSZUp\nZZ8Afl21/z5gX2V3dBsAHA0sSNPtBti+mexGBFNsbwAel/RhAEmDJL01fzLbV9qenG4YsLZqX5ft\nscAD5EZmqvwSOCJNAUPStjXiKh+ch5JNr+tSdme2MQUx9dwOnPHaAdK7mzimrjRaNcT2ZZVtto+1\nPdb2LmRTAH+U61zVcge5Gx8UTe9Ttv5spzrnWAi8X9KYFF9Uz3nAmblzTsrtu5lsxHNlbmSlXnxv\ndXutJM1UWidXGJyNKA2z/Z/A2cDEBuf9L2CCpIGpjgfUiO+RC4DtF4A1aXpfJYda1yzKdyjZKNsX\nciPK+f3DyH4nRkXnamPrbHcC/VasDyhH1LUcUdfyRG3LEXVtXV92sB4GTpO0kuzmEt9L2w2QOkHn\nkX3KWALcb/tWYBTQKWkJ2R3PzkvHHU92Q4ZlwN3AyF7k9AhQeFvyNKXva2SdvCVAZS1PrZG4WcCe\nKZ9jgVUFMUXHV1xENpq0XNlt1r9aHSBpqqRW1g+dA+yu7CYXiyU1ml5YK7eLgeHKbhm+hKq5TGmq\n2njg2Zontp8hm954czrH9QVhZwJ7KLvBxgrglNy+G8hGCa9vMr4HSafUqkEacbwcOEHSY5LemXZN\nBJ6sc9qtgZ+n1/1XwFlpe+H7xPYTqS0rUlsWV8fUeV5xLHCisptqrAAOLWhPrbaeTvZafSX3vhiR\n2z8UWGe77s0yQgghhBBC78hu9x20y5PWO21n+7yGwaGmtJ7nU7bPbXcufUnS1sAPbG823wuVpjtO\nt110R8ZKjNt/Z/3NmejP/y6HEEII/YUkbPeYkdTfO1jjgR8CG6q+CyuEzY6kc8hGCS+z/ZM6cdHB\naqvoYIUQQghvBrU6WH05RXCTY/tR2++PzlUI2S3t05rFmp2r1yl+2vQzcmR+eWdoRqwPKEfUtRxR\n1/JEbcsRdW1dX99FLoTQD8QISt/r7OyMW92GEEIIm4F+PUUwhNA6SY5/F0IIIYQQ6tsspwiGEEII\nIYQQwsYUHawQQtgIYg57eaK25Yi6liPqWp6obTmirq2LDlYIIYQQQggh9JFYgxVC6CbWYIUQQggh\nNBZrsEIIIYQQQgihZNHBCiH0ICl+evGz49t2rFnTmMNenqhtOaKu5Yi6lidqW46oa+vie7BCCD1N\na3cCb07rpq1rdwohhBBCaLNYgxVC6EaSo4PVS9PiS5pDCCGEzUWpa7AkjZH0YI198yVN6YvrtErS\naEmLJc3NbVvTjlxqkbSfpBlNxK1J/61Z66r4rSU9Lunb+XNIGt5Cbg1rlV7f0XX2nyDpO81es8m8\nTqi0S9IFko5vED9c0i8lvZCvR4NjZkjat8H+w1vMex9JK9J78i2SLpP0oKRvpHac3eD4hm1Ncf8q\n6beSVkn6YG77OZIelvTxVvIOIYQQQgjN68s1WJvin20PA+bZPji3bVPMs5mcXONxLRcBC3pxnTcS\nX/Z5eusvwJeAc9qcxzHAJban2H4JOAmYaPsLfXUBSbsBRwK7AQcDV0oSgO3LgROA0/rqeqF5MYe9\nPFHbckRdyxF1LU/UthxR19b1ZQdroKTrJK2UdIOkwdUBko6WtDz9XJq2bZFGA5ZLWibpzLR9vKQ7\nJC2V9ICkcb3IaRjwVNW2p3P5HJ+uuUTSzLRthqTpku6W9LvKKIWkrSTdmXJZJunQtH1MGimYIWm1\npFmSDkrHr5a0R4rbUtI1khZKWiTpkJTGy8DzTbTl6eoNkr6fcl8i6SlJX07bpwI7APOqDwHOSNdf\nJulvc2379/QaLJX0kVrXLPAn4NV0nn9I514q6Y6CfEdIulHSb9LP3sqskbRNLu4RSdsXxRdcfwPw\nYr0Ebf+v7XuAl5poT8V6stcGSZemkaelkr6Zi9mv4H2yn6Rbc235TnqfnUjW8blI0rWSfgYMARZJ\nOqKqTrtImivpfkkLKq8T8EKjtgIfBq63/YrtPwC/Bd6T278WGNpCHUIIIYQQQgv68iYXuwKfsr1Q\n0jXAqcAVlZ2SdgIuBSaTfXi9I3VSngBG2Z6Y4ioftGeR/bV/jqRB9K4zOADoym+wvVe6zgTgfGBv\n289JGpYL29H2+9JowBzgJrJRkMNsb5C0HbAw7QMYD3zU9kpJDwBHpeMPTdc4HPgicJftEyUNBe6T\ndKfte4F7U05TgVNsn1zdkEreVdtOSseNBuYCM9JoxbfIRksOKqjJU7anSvoMcC5wMvBlYH3uNRha\n65oFOXwsHTMCuBrYx/ZjVfWsmA5cYfseSW8Hbrc9QdItwEeAmZLeA/zB9tOSZlXHAxOqrn955bGk\nU7JNvrpR3k2066x0zuFkr/s70/NtcmFF7xMoGLGzfY2kfYBbbd+UzvVn21PS4wty4VeTvQ8eTfW4\nCjjAdv73qVZbR5HeT8kf07aKLpr5vZ+fezwW6M2fN0I3HR0d7U6h34raliPqWo6oa3mituWIur6u\ns7OzqRG9vuxgPWZ7YXp8HfBZch0sYE9gvu1nAdKH532Bi4FxkqYDvwDmSRoC7Gx7DoDtl1tNJnU0\nJqVcinwAmG37uXSN9bl9t6RtqyTtUDkl8HVl63K6gJ1z+9bYXpkePwTcmR4/SPbxFOCDwCGSPp+e\nDwJGA6srF7W9iKzD00o7BwOzgdNtPyHpNOA2209mJaB64d3N6b+LyDo1AAcCr63Lsd3MiFq19wIL\nbD+WzrG+IOZAYLf02gAMkbQlcAPwFWAmcBTw0wbxhWz/Wy/ybuR54EVJPwBuA36e21f0PnlDJG0F\n/D0wO9fugdVxb6CtzwDbSxpW4zXK7N/Ls4cQQggh9FMdHR3dOpwXXnhhYVyZa7CK1t30uMtG+pA3\nCegEPg18v1ZstxNJp6apcYsl7Vi1bwtgDdk6lNuayr67/FSySh7HACOAybYnk009HFwQ35V7nh8t\nENko1+T0M872at64q4AbbVfGHPYGTpf0e7KRrOMkXVLQtlfp+9v0133N0v69cjUYnabv3QuMT6Ng\nhwH/US++j3Ouy/arZFPsbgT+GfjP3O6i98krdP+96jFVtoEtgOfSOq1Ku/+uheP/CLw99/xtaRsA\ntl8Ergd+L6lohDOUJOawlydqW46oazmiruWJ2pYj6tq6vuxgjZFUmVL2CeDXVfvvA/ZVdke3AcDR\nwII03W6A7ZvJbkQwxfYG4HFJHwaQNEjSW/Mns31l+vA5xfbaqn1dtscCD5AbmanyS+CINAUMSdvW\niKt8cB5KNr2uS9L+wJiCmHpuB8547QDp3U0cU1carRpi+7LKNtvH2h5rexeyKYA/sn1+g1PdQe7G\nB0XT+5StP9upzjkWAu+XNCbFF9VzHnBm7pyTcvtuJhvxXJkbWakX31vdXitJM5XWyRUGZyNKw2z/\nJ3A2MLHBef8LmCBpYKrjAc3mAmD7BWCNpI/lcqh1zSJzgKPS78w44B1kv3uVcw0j+50YZbvHOrkQ\nQgghhPDG9GUH62HgNEkryW4u8b203QCpE3Qe2UjVEuB+27eSrQ/plLQEuDbFABxPdkOGZcDdwMhe\n5PQIUHhb8jSl72tknbwlQGUtT62RuFnAnimfY4FVBTFFx1dcRHYjkOXKbrP+1eoASVMltbJ+6Bxg\n99xIXqPphbVyuxgYruyW4UuAjqq8RLbO7NmaJ7afIZveeHM6x/UFYWcCeyi7wcYK4JTcvhvIRgmv\nbzK+B0mn1KqBslvOXw6cIOkxSe9MuyYCT9Y57dbAz9Pr/ivgrLS98H1i+4nUlhWpLYurY+o8rzgW\nOFHZTTVWAIcWtKewrel9fQOwkmzK7anu/sVMQ4F1aSQrbEQxh708UdtyRF3LEXUtT9S2HFHX1vXr\nLxpO6522s31ew+BQk6R3kd3A5Nx259KXJG0N/MD2ZvO9UOmmGdNtF92RsRITXzTcW9Pii4ZDCCGE\nzYVqfNFwf+9gjQd+CGyo+i6sEDY7ks4hGyW8zPZP6sT1338USjZy1EjWPrG2cF9nZ2f8FbAkUdty\nRF3LEXUtT9S2HFHX2mp1sPr6JgebFNuPAu9vdx4hbArSLe0vbxhIjMKEEEIIIfRWvx7BCiG0TpLj\n34UQQgghhPpqjWD15U0uQgghhBBCCGGzFh2sEELYCOJ7RMoTtS1H1LUcUdfyRG3LEXVtXXSwQggh\nhBBCCKGPxBqsEEI3sQYrhBBCCKGxWIMVQgghhBBCCCWLDlYIoQdJ8dPPfnbcccPzrOIAACAASURB\nVGy731alifUB5Yi6liPqWp6obTmirq3r19+DFULorZgi2Pc6gY62XX3duh4zGEIIIYRQgliDFULo\nRpKjg9UfKb5AOoQQQuhDm9QaLEljJD1YY998SVM2dk7p2qMlLZY0N7dtTTtyqUXSfpJmNBG3Jv23\nZq2r4reW9Likb+e2zZc0usFxMyTt2yDfWxtdvxX5c0o6QdIFTRzzDUkPSlou6cgm4i+QdHyD/We3\nmPeukpZIWiRpnKQzJK2UdG1qx3caHN+wrZImSbontXVpvq2Sjpb0sKSzWsk7hBBCCCE0r51rsDbF\nP6UeBsyzfXBu26aYZzM5ucbjWi4CFvQunZZyKeOcdc8v6R+BdwMTgfcC50oaUkJOjRwGzLY91fYa\n4DPAgbaPS/tbfV2L/A9wnO3dgYOB/ydpGwDbPwH2A6KD1Rad7U6g34r1AeWIupYj6lqeqG05oq6t\na2cHa6Ck69Jf8G+QNLg6IP3FfXn6uTRt2yKNmiyXtEzSmWn7eEl3pL/aPyBpXC9yGgY8VbXt6Vw+\nx6drLpE0M22bIWm6pLsl/U7S4Wn7VpLuTLksk3Ro2j5G0qp03GpJsyQdlI5fLWmPFLelpGskLUwj\nHoekNF4Gnm+iLU9Xb5D0/ZT7EklPSfpy2j4V2AGYV3XIn4BXG1xnfcoJSXumdixNeW9Vdf3CNkm6\nV9Juubj5kqbUqUHei8CGBjlOAH7lzP8Cy4F/aHDMC+ncpJGmh1K7fpyLeVfK9XeSPptiu40YSjon\njXYdDHwO+IykuyRdBewCzK28h3PHjJB0o6TfpJ+9m22r7d/ZfjQ9/m+y9/P2uf3rgKEN2h5CCCGE\nEHqpnTe52BX4lO2Fkq4BTgWuqOyUtBNwKTCZ7EP8HamT8gQwyvbEFLdNOmQWcIntOZIG0bvO4wCg\nK7/B9l7pOhOA84G9bT8naVgubEfb70udhDnATcBfgMNsb5C0HbAw7QMYD3zU9kpJDwBHpeMPTdc4\nHPgicJftEyUNBe6TdKfte4F7U05TgVNsn1zdkEreVdtOSseNBuYCMyQJ+BZwDHBQVfzHGhXM9lnp\nnAOB64EjbC9OI0QvVoUXtikd93FgmqQdUz0XS/pajfj89W+oPE4dsKm2p1VddxnwFUlXAFsB+wMP\nNWjXFbmnXwDG2v5r7v0G2Xu4g6zDslrSlZXDe57OcyV9D3ihcm5JHwI60vvphFz8dOAK2/dIejtw\nOzChybaSi3kPMLDS4cpp4ncjf9oO2nlzhv6jo90J9FsdHR3tTqFfirqWI+panqhtOaKur+vs7Gxq\nRK+dHazHbC9Mj68DPkuugwXsCcy3/SyApFnAvsDFwDhJ04FfAPPSh/mdbc8BsP1yq8mkjsaklEuR\nD5BN73ouXWN9bt8tadsqSTtUTgl8Xdn6pC5g59y+NbZXpscPAZVOw4PA2PT4g8Ahkj6fng8CRgOr\nKxe1vQjo0blq0M7BwGzgdNtPSDoNuM32k1kJ6O2txnYFnrS9OOW2IV0vH1OrTbPJRs+mAUcCNzaI\nL2T7VqDHei/bd0jaE7iHbETnHhqPzOUtA34s6RbSa53cZvsV4E+S1gEjWzgnZLUuqveBwG56vXhD\nJG2ZRt+A2m197cTZHyh+BBxXsPtZSeMLOl450xomH0IIIYSwOeno6OjW4bzwwgsL4zalNVhFa0t6\nfPhMHZtJZAsaPg18v1ZstxNJp6apcYvTKEl+3xbAGmA34Lamsu/upYKcjwFGAJNtTyb7YD+4IL4r\n97yL1zu9Ihvlmpx+xtlezRt3FXCj7fnp+d7A6ZJ+TzaSdZykS3p57kads8I22X4SeEbS7mQjWT/N\nHdMnNbB9STrHh8je94+0cPg/Ad8FpgD3p/cL9Hwd/wZ4hWwktKLH1NcmCNgr1+7R+c5Vw4OlrYGf\nA/9q+/6CkOnAUkmf7EVuodc6251AvxXrA8oRdS1H1LU8UdtyRF1b184O1hhJlWlsnwB+XbX/PmBf\nScMlDQCOBhak6XYDbN8MfAmYkkZLHpf0YQBJgyS9NX8y21emD6tTbK+t2tdleyzwANkH/CK/BI6Q\nNDxdY9sacZVOxlDgKdtdkvYHxhTE1HM7cMZrB0jvbuKYutJo1RDbl1W22T7W9ljbuwDnAj+yfX7B\nsTOV1ofVsBrYMU1bRNKQ9Lrl1WvTT4F/AbaxvaKJ+KYpW7dXed0mAruT1ptJuqTyvqlxrIDRthcA\n5wHbAPVukLEO2F7StpLeAvxzL1KeB7y2LkvSpGYPTFM1bwFmpt+RIucD77D9w17kFkIIIYQQ6mhn\nB+th4DRJK8luLvG9tN0AqRN0HtmffZcA96dpUaOATklLgGtTDMDxwBmSlgF30/p0LchGNYYX7UhT\n+r5G1slbAlyezzcfmv47C9gz5XMssKogpuj4iovIbgSyPN004avVAZKmSrq6TnuqnQPsnhvJa2V6\n4UTgyVo7bf+VrHP6XUlLyToJb6kKq9em/6Dn6NXFdeJ7kHSIpGkFuwYCv5a0gux9dqztylq73YG1\nBcdUDACuS6/jImC67T8XxFXet6+kPO8n6yCuKojtdkyBM4E9lN0cZQVwSnVAnbYeCewDfDL3Ok+s\nihmUbnYRNqqOdifQb8X6gHJEXcsRdS1P1LYcUdfWxRcN56S1PtvZPq9h8GYkTTn7ge1ao3tvWpLm\nVt2Wv19L6wCX2d6pTkx80XC/FF80HEIIIfQlbUpfNLwJuwl4n3JfNBzA9gv9sXMFsJl1ro4mG1n8\nZhPR8dPPfkaOzM9S7l9ifUA5oq7liLqWJ2pbjqhr69p5F8FNTrqr2vvbnUcIZUhfNPyTJmNLzmbz\n09nZGdMsQgghhM1ATBEMIXQjyfHvQgghhBBCfTFFMIQQQgghhBBKFh2sEELYCGIOe3mituWIupYj\n6lqeqG05oq6tiw5WCCGEEEIIIfSRWIMVQugm1mCFEEIIITQWa7BCCCGEEEIIoWTRwQoh9CApfuKn\n9J8d37Zjn7xfY31AOaKu5Yi6lidqW46oa+vie7BCCD1Na3cC/dAaYFy7k9i0rJu2rt0phBBCCH0u\n1mCFELqR5OhghY1iWnypdQghhDcvaRNagyVpjKQHa+ybL2nKxs4pXXu0pMWS5ua2rWlHLrVI2k/S\njCbi1qT/1qx1VfzWkh6X9O3ctvmSRjc4boakfRvke2uj67cif05JJ0i6oIljviHpQUnLJR3ZRPwF\nko5vsP/sFvPeVdISSYskjZN0hqSVkq5N7fhOg+ObbesJkh6RtDrfBklHS3pY0lmt5B1CCCGEEJrX\nzjVYm+KfLQ8D5tk+OLdtU8yzmZxc43EtFwELepdOS7mUcc6655f0j8C7gYnAe4FzJQ0pIadGDgNm\n255qew3wGeBA28el/a2+rj1I2hb4CrAnsBdwgaShALZ/AuwHRAerHTapP9X0L7E+oBxR13JEXcsT\ntS1H1LV17exgDZR0XfoL/g2SBlcHpL+4L08/l6ZtW6RRk+WSlkk6M20fL+kOSUslPSCpN6sdhgFP\nVW17OpfP8emaSyTNTNtmSJou6W5Jv5N0eNq+laQ7Uy7LJB2ato+RtCodt1rSLEkHpeNXS9ojxW0p\n6RpJC9OIxyEpjZeB55toy9PVGyR9P+W+RNJTkr6ctk8FdgDmVR3yJ+DVBtdZn3JC0p6pHUtT3ltV\nXb+wTZLulbRbLm6+pCl1apD3IrChQY4TgF8587/AcuAfGhzzQjo3aaTpodSuH+di3pVy/Z2kz6bY\nbiOGks5Jo10HA58DPiPpLklXAbsAcyvv4dwxIyTdKOk36WfvFtr6IbI/Ejxvez3Za/paW22vA4Y2\nOEcIIYQQQuildt7kYlfgU7YXSroGOBW4orJT0k7ApcBksg/xd6ROyhPAKNsTU9w26ZBZwCW250ga\nRO86jwOArvwG23ul60wAzgf2tv2cpGG5sB1tvy91EuYANwF/AQ6zvUHSdsDCtA9gPPBR2yslPQAc\nlY4/NF3jcOCLwF22T0wjEPdJutP2vcC9KaepwCm2T65uSCXvqm0npeNGA3OBGZIEfAs4BjioKv5j\njQpm+6x0zoHA9cARthenEaIXq8IL25SO+zgwTdKOqZ6LJX2tRnz++jdUHqcO2FTb06quuwz4iqQr\ngK2A/YGHGrTritzTLwBjbf81936D7D3cQdZhWS3pysrhPU/nuZK+B7xQObekDwEd6f10Qi5+OnCF\n7XskvR24HZjQZFtHAY/nnv8xbctr/LsxP/d4LHFzhr4QNSxNR0dHu1Pol6Ku5Yi6lidqW46o6+s6\nOzubGtFrZwfrMdsL0+PrgM+S62CRTXGab/tZAEmzgH2Bi4FxkqYDvwDmpQ/zO9ueA2D75VaTSR2N\nSSmXIh8gm971XLrG+ty+W9K2VZJ2qJwS+Lqy9UldwM65fWtsr0yPHwIqnYYHyT7OAnwQOETS59Pz\nQcBoYHXlorYXAT06Vw3aORiYDZxu+wlJpwG32X4yKwE9Fuo1aVfgSduLU24b0vXyMbXaNJtspGUa\ncCRwY4P4QrZvBXqs97J9h6Q9gXvIRijvofHIXN4y4MeSbiG91slttl8B/iRpHTCyhXNCVuuieh8I\n7KbXizdE0pZp9A2o3dYmPStpvO1Ha0bs38szhxBCCCH0Ux0dHd06nBdeeGFh3Ka0BqtobUmPD5+p\nYzMJ6AQ+DXy/Vmy3E0mnpqlxi9MoSX7fFmQrJHYDbmsq++5eKsj5GGAEMNn2ZLIP9oML4rtyz7t4\nvdMrslGuyelnnO3VvHFXATfaroxR7A2cLun3ZCNZx0m6pJfnbtQ5K2yT7SeBZyTtTjaS9dPcMX1S\nA9uXpHN8iOx9/0gLh/8T8F1gCnB/er9Az9fxb4BXyEZCK3pMfW2CgL1y7R6d71w18Ee6d0Lflrbl\nTQeWSvpkL3ILvRVrsEoT6wPKEXUtR9S1PFHbckRdW9fODtYYSZVpbJ8Afl21/z5gX0nDJQ0AjgYW\npOl2A2zfDHwJmJJGSx6X9GEASYMkvTV/MttXpg+rU2yvrdrXZXss8ADZB/wivwSOkDQ8XWPbGnGV\nTsZQ4CnbXZL2B8YUxNRzO3DGawdI727imLrSaNUQ25dVttk+1vZY27sA5wI/sn1+wbEzldaH1bAa\n2DFNW0TSkPS65dVr00+BfwG2sb2iifimKVu3V3ndJgK7k9abSbqk8r6pcayA0bYXAOcB2wD1bpCx\nDthe0raS3gL8cy9Snge8ti5L0qQWjr0dOEjS0PQePShtyzsfeIftH/YitxBCCCGEUEc7O1gPA6dJ\nWkl2c4nvpe0GSJ2g88hGqpYA96dpUaOATklLgGtTDMDxwBmSlgF30/p0LchGNYYX7UhT+r5G1slb\nAlyezzcfmv47C9gz5XMssKogpuj4iovIbgSyPN004avVAZKmSrq6TnuqnQPsnhvJa2V64UTgyVo7\nbf+VrHP6XUlLyToJb6kKq9em/6Dn6NXFdeJ7kHSIpGkFuwYCv5a0gux9dqztylq73YG1BcdUDACu\nS6/jImC67T8XxFXet6+kPO8n69isKojtdkyBM4E9lN0cZQVwSnVArbamKawXkf2x4DfAhVXTWQEG\npZtdhI0p1mCVJtYHlCPqWo6oa3mituWIurYuvmg4J6312c72eQ2DNyOStgZ+YLvW6N6blqS5Vbfl\n79fSOsBltneqExNfNBw2jmnxRcMhhBDevFTji4ajg5UjaTzwQ2DD5vShO2weJB1NdkfEmbb/b524\n+EchbBQjR41k7RP1BpCb09nZGX9hLUHUtRxR1/JEbcsRda2tVgernXcR3OSku6q9v915hFCG9EXD\nP2kytuRsNj/xP6gQQghh8xAjWCGEbiQ5/l0IIYQQQqiv1ghWO29yEUIIIYQQQgj9SnSwQghhI4jv\nESlP1LYcUddyRF3LE7UtR9S1ddHBCiGEEEIIIYQ+EmuwQgjdxBqsEEIIIYTGYg1WCCGEEEIIIZQs\nbtMeQuhB6vHHmBBCCG8CI0eOYe3aP7Q7jbaIr8MoR9S1ddHBCiEUiCmCfa8T6GhzDv1VJ1HbMnQS\ndS1DJ2XWdd26+ANZCO0Wa7BCCN1IcnSwQgjhzUrxZfEhbCSb1BosSWMkPVhj33xJUzZ2TunaoyUt\nljQ3t21NO3KpRdJ+kmY0Ebcm/bdmravit5b0uKRv57bNlzS6wXEzJO3bIN9bG12/FflzSjpB0gVN\nHPNqem2XSLqlifgLJB3fYP/ZLea9a7r+IknjJJ0haaWka1M7vtPg+IZtlTRJ0j2SHpS0VNKRuX1H\nS3pY0lmt5B1CCCGEEJrXzptcbIp/XjkMmGf74Ny2TTHPZnJyjce1XAQs6F06LeVSxjmbOf//2J5i\ne7Ltw0rIpxmHAbNtT7W9BvgMcKDt49L+Vl/XIv8DHGd7d+Bg4P9J2gbA9k+A/YDoYLVFZ7sT6Mc6\n251AP9XZ7gT6qc52J9Bvxfc1lSPq2rp2drAGSrou/QX/BkmDqwPSX9yXp59L07Yt0qjJcknLJJ2Z\nto+XdEf6q/0Dksb1IqdhwFNV257O5XN8uuYSSTPTthmSpku6W9LvJB2etm8l6c6UyzJJh6btYySt\nSsetljRL0kHp+NWS9khxW0q6RtLCNOJxSErjZeD5JtrydPUGSd9PuS+R9JSkL6ftU4EdgHlVh/wJ\neLXBddannJC0Z2rH0pT3VlXXL2yTpHsl7ZaLmy9pSp0a5L0IbGiQI0Crk9JfSOcmjTQ9lNr141zM\nu1Kuv5P02RTbbcRQ0jlptOtg4HPAZyTdJekqYBdgbuU9nDtmhKQbJf0m/ezdbFtt/872o+nxf5O9\nn7fP7V8HDG2xFiGEEEIIoUntvMnFrsCnbC+UdA1wKnBFZaeknYBLgclkH+LvSJ2UJ4BRtiemuG3S\nIbOAS2zPkTSI3nUeBwBd+Q2290rXmQCcD+xt+zlJw3JhO9p+X+okzAFuAv4CHGZ7g6TtgIVpH8B4\n4KO2V0p6ADgqHX9ousbhwBeBu2yfKGkocJ+kO23fC9ybcpoKnGL75OqGVPKu2nZSOm40MBeYIUnA\nt4BjgIOq4j/WqGC2z0rnHAhcDxxhe7GkIaQOSk5hm9JxHwemSdox1XOxpK/ViM9f/4bK49QBm2p7\nWkGqb0m1fhn4hu2fNWjXFbmnXwDG2v5r7v0G2Xu4g6zDslrSlZXDe57OcyV9D3ihcm5JHwI60vvp\nhFz8dOAK2/dIejtwOzChhbZWYt4DDKx0uHKa+N3In7aDWOjeFzranUA/1tHuBPqpjnYn0E91tDuB\nfivudFeOqOvrOjs7mxrRa2cH6zHbC9Pj64DPkutgAXsC820/CyBpFrAvcDEwTtJ04BfAvPRhfmfb\ncwBsv9xqMqmjMSnlUuQDZNO7nkvXWJ/bd0vatkrSDpVTAl9Xtj6pC9g5t2+N7ZXp8UNApdPwIDA2\nPf4gcIikz6fng4DRwOrKRW0vAnp0rhq0czAwGzjd9hOSTgNus/1kVoKWR3oqdgWetL045bYhXS8f\nU6tNs8lGz6YBRwI3NogvZPtWoNZ6rzG2/zuNbP5S0vI0Ta8Zy4AfK1u7lV+/dZvtV4A/SVoHjGzy\nfBWiuN4HArvp9eINkbSl7f+tBDRoa+UPFD8CjivY/ayk8QUdr5xpDZMPIYQQQticdHR0dOtwXnjh\nhYVxm9IarKK1JT0+fKaOzSSyScyfBr5fK7bbiaRT09S4xWmUJL9vC2ANsBtwW1PZd/dSQc7HACOA\nybYnk03VGlwQ35V73sXrnV6RjXJNTj/jbK/mjbsKuNH2/PR8b+B0Sb8nG8k6TtIlvTx3o85ZYZts\nPwk8I2l3spGsn+aO6ZMapOlypE5VJ9nIaLP+CfguMAW4P71foOfr+DfAK2QjoRU9pr42QcBeuXaP\nzneuGh4sbQ38HPhX2/cXhEwHlkr6ZC9yC73W2e4E+rHOdifQT3W2O4F+qrPdCfRbsVaoHFHX1rWz\ngzVGUmUa2yeAX1ftvw/YV9JwSQOAo4EFabrdANs3A18CpqTRksclfRhA0iBJb82fzPaV6cPqFNtr\nq/Z12R4LPED2Ab/IL4EjJA1P19i2RlylkzEUeMp2l6T9gTEFMfXcDpzx2gHSu5s4pq40WjXE9mWV\nbbaPtT3W9i7AucCPbJ9fcOxMpfVhNawGdkzTFpE0JL1uefXa9FPgX4BtbK9oIr5pkoalaaNIGgG8\nD1iZnl9Sed/UOFbAaNsLgPOAbYAhdS63Dthe0raS3gL8cy9Snge8ti5L0qRmD0xTNW8BZqbfkSLn\nA++w/cNe5BZCCCGEEOpoZwfrYeA0SSvJbi7xvbTdAKkTdB7Zn3qWAPenaVGjgE5JS4BrUwzA8cAZ\nkpYBd9P6dC2AR4DhRTvSlL6vkXXylgCX5/PNh6b/zgL2TPkcC6wqiCk6vuIishuBLE83TfhqdYCk\nqZKurtOeaucAu+dG8lqZXjgReLLWTtt/JeucflfSUrJOwluqwuq16T/oOXp1cZ34HiQdImlawa7d\ngAfS63YX2Vq9h9O+3YG1BcdUDACuS6/jImC67T8XxFXet6+kPO8n6yCuKojtdkyBM4E9lN0cZQVw\nSnVAnbYeCewDfDL3Ok+sihmUbnYRNqqOdifQj3W0O4F+qqPdCfRTHe1OoN+KtULliLq2Lr5oOCet\n9dnO9nkNgzcjacrZD2zXGt1705I0t+q2/P1aWge4zPZOdWLii4ZDCOFNK75oOISNRZvSFw1vwm4C\n3qfcFw0HsP1Cf+xcAWxmnaujyUYWv9nuXDZPne1OoB/rbHcC/VRnuxPopzrbnUC/FWuFyhF1bV07\n7yK4yUl3VXt/u/MIoQzpi4Z/0lx0b28mGUIIoZ1GjhzTOCiEUKqYIhhC6EaS49+FEEIIIYT6Yopg\nCCGEEEIIIZQsOlghhLARxBz28kRtyxF1LUfUtTxR23JEXVsXHawQQgghhBBC6COxBiuE0E2swQoh\nhBBCaCzWYIUQQgghhBBCyaKDFUIIG0HMYS9P1LYcUddyRF3LE7UtR9S1dfE9WCGEHqT4HqwQQghh\nYxo5aiRrn1jb7jRCH4g1WCGEbiSZae3OIoQQQtjMTIP4XP7mEmuwQgghhBBCCKFkbelgSRoj6cEa\n++ZLmrKxc0rXHi1psaS5uW1r2pFLLZL2kzSjibg16b81a10Vv7WkxyV9O7dtvqTRDY6bIWnfBvne\n2uj6rcifU9IJki5o4phX02u7RNItTcRfIOn4BvvPbjHvXdP1F0kaJ+kMSSslXZva8Z0Gxzfb1hMk\nPSJpdb4Nko6W9LCks1rJO/SRTepfkn4maluOqGs5oq7lidqWItZgta6da7A2xTHQw4B5ts/LbdsU\n82wmJ9d4XMtFwILepdNSLmWcs5nz/4/ttnTccw4DZtu+BEDSZ4ADbD8p6QRaf117kLQt8BVgCiBg\nkaSf2f8/e2cfblVV7f/PFxJRUURNULqgcXu8Wr6B/MyrF4/mS2q+XJOMMK3bY5amll7NtKuH1NRK\nf3kzNZMfcgVNLVSUSEQ5ZCKCcDioIGlhvl3UUgrN9zN+f8yxYZ199uvpLDYcxud59nPWmnPMOccc\na7FZY40x57a/mtmtkh4E5gP/9x+ZSBAEQRAEQVCaRqYIbiRpkr/Bv11S32IBf+O+2D+Xe1kvj5os\nltQm6UwvHybpfkmLJD0maccu6LQl8EpR2asZfU70MVslTfSyCZKulvSwpGckHevlm0ma6bq0STrK\ny4dKWurtlkmaLOlgb79M0l4ut6mk8ZLmesTjSFfjXeCvNczl1eICST933VslvSLpv7x8BLAtMKOo\nyV+AD6qMs9J1QtJIn8ci13uzovFLzknSI5J2zsjNkjS8gg2yvAW8UUVHSM5GPazyvvFI05M+r1sy\nMh93XZ+RdLrLdogYSjrbo12HAd8Evi7pAUnXAR8Fphfu4UybbST9UtKj/tmnjrkeSnpJ8FczW0m6\npp8uVJrZy0D/Om0RdAdd+UYKaiNsmw9h13wIu+ZH2DYXmpqaGq3CekcjI1g7AV82s7mSxgOnAlcV\nKiVtB1wO7El6iL/fnZQXgMFmtpvLbeFNJgPfN7OpkvrQNeexN9CeLTCzvX2cXYDzgX3M7HVJW2bE\nBpnZvu4kTAWmAG8Dx5jZG5K2BuZ6HcAw4LNmtkTSY8Dnvf1RPsaxwAXAA2b2FUn9gXmSZprZI8Aj\nrtMI4BQz+2rxRAp6F5Wd7O2GANOBCZIE/AgYCxxcJH9cNYOZ2be8z42AXwCjzWyhpH64g5Kh5Jy8\n3fFAs6RBbs+Fki4tI58d//bCsTtgI8ysuYSqG7ut3wWuMLO7q8zrqszpt4EdzOy9zP0G6R5uIjks\nyyRdW2jeuTubLul6YFWhb0mHAk1+P52Ukb8auMrM5kj6J+A+YJca5zoYeD5z/qKXZan+b2NW5ngH\n4j+tIAiCIAg2eFpaWmpKmWykg/Wcmc3140nA6WQcLGAkMMvMXgOQNBkYBVwC7CjpauDXwAx/mN/e\nzKYCmNm79SrjjsburkspDiSld73uY6zM1N3lZUslbVvoErhMaX1SO7B9pm65mS3x4yeBgtPwOOlx\nFuAQ4EhJ5/h5H2AIsKwwqJktADo5V1Xm2Re4A/iGmb0g6TRgmqepFfTuCjsBL5nZQtftDR8vK1Nu\nTneQIi3NwOeAX1aRL4mZ3QOUW+811Mz+1yObD0pabGa1Zmu3Abcord3Krt+aZmbvA3+R9DIwsMb+\nCojS9j4I2FlrjNdP0qZm9veCQJW5VuM1ScPM7A9lJQ7oYs9BeZYTjmpehG3zIeyaD2HX/Ajb5kJL\nS0tEsZympqYOthg3blxJuXVpDVaptSWdHj7NbKWk3UmpUF8DRpNSryo6BpJOBU72cQ43sxWZul7A\nH4F3gGl1zKHAOyV0HgtsA+xpZu1Km070LSHfnjlvZ801ESnK9XQX9KnEdcAvzawQo9gH2M/tszkp\ndXOVmZ3fhb6rOWdl5yTpz5J2JUWyTslUdZL3KFddmNn/+t/lklpIkdFaif3A3AAAIABJREFUHawj\nSM79UcAFkj7h5cXX8UPA+6RIaIFOqa81IGBvM3uvC21fJEXVCnyEjvEoSBGyRZJON7ObujBGEARB\nEARBUIZGrsEaKqmQxvYF4KGi+nnAKElbSeoNjAFme7pdbzO7E/guMNyjJc9LOhpAUh9Jm2Q7M7Nr\nzWxPMxueda68rt3MdgAeIz3gl+JBYLSkrXyMAWXkCk5Gf+AVd64OAIaWkKnEfcAZqxtIe9TQpiIe\nrepnZj8slJnZCWa2g5l9FPhP4H9KOVeSJsrXh5VhGTDI0xaR1M+vW5ZKc7oNOBfYwsyeqEG+ZiRt\n6WmjSNoG2BdY4uffL9w3ZdoKGGJms4HzgC2AfhWGexn4sKQBkjYGPtMFlWcAq9dl+QuFWrkPOFhS\nf79HD/ayLOcD/xzO1Vom3qrmR9g2H8Ku+RB2zY+wbS5E9Kp+GulgPQWcJmkJaXOJ673cANwJOg9o\nAVqB+Z4WNRhokdQK3OwyACcCZ0hqAx6m/nQtgN8DW5Wq8JS+S0lOXitwZVbfrKj/nQyMdH1OAJaW\nkCnVvsDFpGjSYt804XvFApJGSLqhwnyKORvYVWmTi4WS6kkv3A14qVylR1uOB66RtIjkJGxcJFZp\nTr/y9rdlyi6pIN8JSUdKai5RtTPwmF+3B0hr9Z7yul2BSj+b3huY5NdxAXC1mf2thFzhvn3f9ZxP\ncmyWlpDt0KYEZwJ7KW2O8gQdI3pA+bl6CuvFpJcFjwLjitJZAfr4ZhdBEARBEARBN6P4xeg1+Fqf\nrYu2ad/gkbQ5cKOZlYvurbdImm5mhzVaj7WFrwNsM7PtKsgYzWtPpw2GWBuQH2HbfAi75kPYNT/W\nd9s2w7r4XB5rsMojCTPrlJnWyDVY6yJTgJs2tIfuapjZKsqnTq7XbEjXWdIY0o6IP6gq3Jy3NkEQ\nBEEQZBk4uCvJV8G6SESwgiDogCSL74UgCIIgCILKlItgNXINVhAEQRAEQRAEQY8iHKwgCIK1QC0/\nTBh0jbBtPoRd8yHsmh9h23wIu9ZPOFhBEARBEARBEATdRKzBCoKgA7EGKwiCIAiCoDqxBisIgiAI\ngiAIgiBnwsEKgiBYC0QOe36EbfMh7JoPYdf8CNvmQ9i1fuJ3sIIg6ITUKdodBEEQ9FAGDhzKihXP\nNlqNIOgxxBqsIAg6IMkgvheCIAg2HEQ8DwZB/cQarCAIgiAIgiAIgpxpiIMlaaikx8vUzZI0fG3r\n5GMPkbRQ0vRM2fJG6FIOSftLmlCD3HL/W9bWRfKbS3pe0n9nymZJGlKl3QRJo6roe0+18esh26ek\nkyRdVEOb6ZJelzS1xjEuknRilfqzatcaJO0kqVXSAkk7SjpD0hJJN/s8flKlfdW5Stpd0hxJj0ta\nJOlzmboxkp6S9K169A66i5ZGK9CDaWm0Aj2UlkYr0ENpabQCPZZYK5QPYdf6aWQEa12MRR8DzDCz\nwzJl66KetehkZY7LcTEwu2vq1KVLHn3W0v8PgBNy0KMejgHuMLMRZrYc+DpwkJl90evrva6leBP4\nopntChwG/FjSFgBmdiuwPxAOVhAEQRAEQU400sHaSNIkf4N/u6S+xQL+xn2xfy73sl4eNVksqU3S\nmV4+TNL9/tb+MUk7dkGnLYFXispezehzoo/ZKmmil02QdLWkhyU9I+lYL99M0kzXpU3SUV4+VNJS\nb7dM0mRJB3v7ZZL2crlNJY2XNNcjHke6Gu8Cf61hLq8WF0j6ueveKukVSf/l5SOAbYEZRU3+AnxQ\nZZyVrhOSRvo8FrnemxWNX3JOkh6RtHNGbpak4RVskOUt4I0qOmJms2qRy7DK+8YjTU/6vG7JyHzc\ndX1G0uku2yFiKOlsj3YdBnwT+LqkByRdB3wUmF64hzNttpH0S0mP+mefWudqZs+Y2R/8+H9J9/OH\nM/UvA/3rsEPQbTQ1WoEeTFOjFeihNDVagR5KU6MV6LE0NTU1WoUeSdi1fhq5i+BOwJfNbK6k8cCp\nwFWFSknbAZcDe5Ie4u93J+UFYLCZ7eZyW3iTycD3zWyqpD50zXnsDbRnC8xsbx9nF+B8YB8ze13S\nlhmxQWa2rzsJU4EpwNvAMWb2hqStgbleBzAM+KyZLZH0GPB5b3+Uj3EscAHwgJl9RVJ/YJ6kmWb2\nCPCI6zQCOMXMvlo8kYLeRWUne7shwHRggiQBPwLGAgcXyR9XzWBm9i3vcyPgF8BoM1soqR/uoGQo\nOSdvdzzQLGmQ23OhpEvLyGfHv71w7A7YCDNrrqZ3DfO6KnP6bWAHM3svc79BuoebSA7LMknXFpp3\n7s6mS7oeWFXoW9KhQJPfTydl5K8GrjKzOZL+CbgP2KXeuUr6P8BGBYcrQw3/NrLdNhEPBEEQBEEQ\nbOi0tLTUlDLZSAfrOTOb68eTgNPJOFjASGCWmb0GIGkyMAq4BNhR0tXAr4EZ/jC/vZlNBTCzd+tV\nxh2N3V2XUhxISu963cdYmam7y8uWStq20CVwmdL6pHZg+0zdcjNb4sdPAgWn4XFgBz8+BDhS0jl+\n3gcYAiwrDGpmC4BOzlWVefYF7gC+YWYvSDoNmGZmLyUT0NX9uXcCXjKzha7bGz5eVqbcnO4gRc+a\ngc8Bv6wiXxIzuwfo1vVeThtwi6S78GvtTDOz94G/SHoZGFhnv6K0vQ8CdtYa4/WTtKmZ/b0gUG2u\n/oLif4Avlqh+TdKwEo5Xhuaqygf10kI4qnnRQtg2D1oIu+ZBC2HXfGhpaYloSw6EXdfQ1NTUwRbj\nxo0rKddIB6vTW/4SMp0ePs1spaTdgUOBrwGjSalXFR0DSacCJ/s4h5vZikxdL+CPwDvAtDrmUOCd\nEjqPBbYB9jSzdqVNJ/qWkG/PnLez5pqIFOV6ugv6VOI64JeeMgewD7Cf22dzUurmKjM7vwt9V3PO\nys5J0p8l7UqKZJ2Sqeok71GutckRJOf+KOACSZ/w8uLr+CHgfVIktECn1NcaELC3mb3XhbZI2hy4\nF/iOmc0vIXI1sEjS6WZ2U1fGCIIgCIIgCErTyDVYQyUV0ti+ADxUVD8PGCVpK0m9gTHAbE+3621m\ndwLfBYZ7tOR5SUcDSOojaZNsZ2Z2rZntaWbDs86V17Wb2Q7AY6QH/FI8CIyWtJWPMaCMXMHJ6A+8\n4s7VAcDQEjKVuA84Y3UDaY8a2lTEo1X9zOyHhTIzO8HMdjCzjwL/CfxPKedK0kT5+rAyLAMGedoi\nkvr5dctSaU63AecCW5jZEzXId4VOESNJ3y/cNyUbpCjSEDObDZwHbAH0qzDGy8CHJQ2QtDHwmS7o\nOQNYvS7LXyjUhKdq3gVM9H8jpTgf+OdwrtY2TY1WoAfT1GgFeihNjVagh9LUaAV6LBFlyYewa/00\n0sF6CjhN0hLS5hLXe7kBuBN0HimW3grM97SowUCLpFbgZpcBOBE4Q1Ib8DD1p2sB/B7YqlSFp/Rd\nSnLyWoErs/pmRf3vZGCk63MCsLSETKn2BS4mRZMW+6YJ3ysWkDRC0g0V5lPM2cCuSptcLJRUT3rh\nbsBL5So92nI8cI2kRSQnYeMisUpz+pW3vy1TdkkF+U5IOlJSc5m633rfB0p6TlJhvdmuwIpSbZze\nwCS/jguAq83sbyXkCvft+67nfJKDuLSEbIc2JTgT2Etpc5Qn6BjRK8yn3Fw/B+wHfClznXcrkunj\nm10EQRAEQRAE3Yzil7vX4Gt9tjaz86oKb0B4ytmNZlYuurfeIml60bb8PRpfB9hmZttVkLF189cJ\n1ndaiDfXedFC2DYPWgi75kEL655dRU94Hoy1QvkQdi2PJMysU2ZaI9dgrYtMAW7a0B66q2Fmqyif\nOrlesyFdZ0ljSDsi/qAG6bzVCYIgCNYRBg4cWl0oCIKaiQhWEAQdkGTxvRAEQRAEQVCZchGsRq7B\nCoIgCIIgCIIg6FGEgxUEQbAWqOWHCYOuEbbNh7BrPoRd8yNsmw9h1/oJBysIgiAIgiAIgqCbiDVY\nQRB0INZgBUEQBEEQVCfWYAVBEARBEARBEORMOFhBEARrgchhz4+wbT6EXfMh7JofYdt8CLvWT/wO\nVhAEnZDid7CCIAiCoLsZOHggK15Y0Wg1gpyJNVhBEHRAktHcaC2CIAiCoAfSDPHs3XOINVhBEARB\nEARBEAQ50xAHS9JQSY+XqZslafja1snHHiJpoaTpmbLljdClHJL2lzShBrnl/resrYvkN5f0vKT/\nzpTNkjSkSrsJkkZV0feeauPXQ7ZPSSdJuqiGNtMlvS5pao1jXCTpxCr1Z9WuNUjaSVKrpAWSdpR0\nhqQlkm72efykSvta53qSpN9LWpadg6Qxkp6S9K169A66iXXqm6SHEbbNh7BrPoRd8yNsmwuxBqt+\nGhnBWhfjo8cAM8zssEzZuqhnLTpZmeNyXAzM7po6demSR5+19P8D4IQc9KiHY4A7zGyEmS0Hvg4c\nZGZf9Pp6r2snJA0ALgRGAnsDF0nqD2BmtwL7A+FgBUEQBEEQ5EQjHayNJE3yN/i3S+pbLOBv3Bf7\n53Iv6+VRk8WS2iSd6eXDJN0vaZGkxyTt2AWdtgReKSp7NaPPiT5mq6SJXjZB0tWSHpb0jKRjvXwz\nSTNdlzZJR3n5UElLvd0ySZMlHeztl0nay+U2lTRe0lyPeBzparwL/LWGubxaXCDp5657q6RXJP2X\nl48AtgVmFDX5C/BBlXFWuk5IGunzWOR6b1Y0fsk5SXpE0s4ZuVmShlewQZa3gDeq6IiZzapFLsMq\n7xuPND3p87olI/Nx1/UZSae7bIeIoaSzPdp1GPBN4OuSHpB0HfBRYHrhHs602UbSLyU96p996pjr\noaSXBH81s5Wka/rpjB1eBvrXYYegu+jKN1JQG2HbfAi75kPYNT/CtrnQ1NTUaBXWOxq5i+BOwJfN\nbK6k8cCpwFWFSknbAZcDe5Ie4u93J+UFYLCZ7eZyW3iTycD3zWyqpD50zXnsDbRnC8xsbx9nF+B8\nYB8ze13SlhmxQWa2rzsJU4EpwNvAMWb2hqStgbleBzAM+KyZLZH0GPB5b3+Uj3EscAHwgJl9xSMQ\n8yTNNLNHgEdcpxHAKWb21eKJFPQuKjvZ2w0BpgMTJAn4ETAWOLhI/rhqBjOzb3mfGwG/AEab2UJJ\n/XAHJUPJOXm744FmSYPcngslXVpGPjv+7YVjd8BGmFlzNb1rmNdVmdNvAzuY2XuZ+w3SPdxEcliW\nSbq20LxzdzZd0vXAqkLfkg4Fmvx+OikjfzVwlZnNkfRPwH3ALjXOdTDwfOb8RS/LUv3fxqzM8Q7E\nf1pBEARBEGzwtLS01JQy2UgH6zkzm+vHk4DTyThYpBSnWWb2GoCkycAo4BJgR0lXA78GZvjD/PZm\nNhXAzN6tVxl3NHZ3XUpxICm963UfY2Wm7i4vWypp20KXwGVK65Page0zdcvNbIkfPwkUnIbHSY+z\nAIcAR0o6x8/7AEOAZYVBzWwB0Mm5qjLPvsAdwDfM7AVJpwHTzOylZAK6uj/3TsBLZrbQdXvDx8vK\nlJvTHaRISzPwOeCXVeRLYmb3AN263stpA26RdBd+rZ1pZvY+8BdJLwMD6+xXlLb3QcDOWmO8fpI2\nNbO/FwT+wbm+JmmYmf2hrMQBXew5KM9ywlHNi7BtPoRd8yHsmh9h21xoaWmJKJbT1NTUwRbjxo0r\nKddIB6vTW/4SMp0ePs1spaTdSalQXwNGk1KvKjoGkk4FTvZxDjezFZm6XsAfgXeAaXXMocA7JXQe\nC2wD7Glm7UqbTvQtId+eOW9nzTURKcr1dBf0qcR1wC89ZQ5gH2A/t8/mpNTNVWZ2fhf6ruaclZ2T\npD9L2pUUyTolU9VJ3qNca5MjSM79UcAFkj7h5cXX8UPA+6RIaIFOqa81IGBvM3uvC21fJEXVCnyE\njvEoSBGyRZJON7ObujBGEARBEARBUIZGrsEaKqmQxvYF4KGi+nnAKElbSeoNjAFme7pdbzO7E/gu\nMNyjJc9LOhpAUh9Jm2Q7M7NrzWxPMxueda68rt3MdgAeIz3gl+JBYLSkrXyMAWXkCk5Gf+AVd64O\nAIaWkKnEfcAZqxtIe9TQpiIerepnZj8slJnZCWa2g5l9FPhP4H9KOVeSJsrXh5VhGTDI0xaR1M+v\nW5ZKc7oNOBfYwsyeqEG+K3SKGEn6fuG+KdkgRZGGmNls4DxgC6BfhTFeBj4saYCkjYHPdEHPGcDq\ndVn+QqFW7gMOltTf79GDvSzL+cA/h3O1lom3qvkRts2HsGs+hF3zI2ybCxG9qp9GOlhPAadJWkLa\nXOJ6LzcAd4LOA1qAVmC+p0UNBloktQI3uwzAicAZktqAh6k/XQvg98BWpSo8pe9SkpPXClyZ1Tcr\n6n8nAyNdnxOApSVkSrUvcDEpmrTYN034XrGApBGSbqgwn2LOBnZV2uRioaR60gt3A14qV+nRluOB\nayQtIjkJGxeJVZrTr7z9bZmySyrId0LSkZKay9T91vs+UNJzkgrrzXYFKv2kem9gkl/HBcDVZva3\nEnKF+/Z913M+ybFZWkK2Q5sSnAnspbQ5yhN0jOgV5lNyrp7CejHpZcGjwLiidFaAPr7ZRRAEQRAE\nQdDNKH5Neg2+1mdrMzuvqvAGhKTNgRvNrFx0b71F0vSibfl7NL4OsM3MtqsgYzSvPZ02GGJtQH6E\nbfMh7JoPYdf8WB9s2wzr27N3rMEqjyTMrFNmWiPXYK2LTAFu2tAeuqthZqsonzq5XrMhXWdJY0g7\nIv6gqnBz3toEQRAEwYbHwMFdSbAK1jcighUEQQckWXwvBEEQBEEQVKZcBKuRa7CCIAiCIAiCIAh6\nFOFgBUEQrAVq+WHCoGuEbfMh7JoPYdf8CNvmQ9i1fsLBCoIgCIIgCIIg6CZiDVYQBB2INVhBEARB\nEATViTVYQRAEQRAEQRAEORMOVhAEwVogctjzI2ybD2HXfAi75kfYNh/CrvUTv4MVBEEnpE7R7qCb\nGDhwKCtWPNtoNYIgCIIgyIlYgxUEQQckGcT3Qn6I+N4NgiAIgvWfWIMVBEEQBEEQBEGQMzU5WJKG\nSnq8TN0sScO7V63akDRE0kJJ0zNlyxuhSzkk7S9pQg1yyzPy95STkbRVN+pVcpxMfUW9/b6YVUWm\n2++PbJ+1XG9Ju0maI6lN0t2S+tXQpmK/klbVrvHqNj+U9LikKyRtI2mupAWS9qvl2tY41x9IWipp\nkaRfSdoiU/dbSfMkbVuv7kF30NJoBXossT4gH8Ku+RB2zY+wbT6EXeunngjWupjTcgwww8wOy5St\ni3rWopOVOa63n3qo1l+9ejeCWsa/ETjXzHYH7gTO7YZ+uzLvk4HdzOzbwEHAYjMbYWa/q7G/WmRm\nAB83sz2Ap4HvrG5sNgpYABxRt+ZBEARBEARBTdTjYG0kaZKkJZJul9S3WEDSGEmL/XO5l/WSNMHL\n2iSd6eXDJN3vb9ofk7RjF/TfEnilqOzVjD4n+pitkiZ62QRJV0t6WNIzko718s0kzXRd2iQd5eVD\nPSIwQdIySZMlHeztl0nay+U2lTQ+E5U40tV4F/hrDXN5NXPcX9K9kp6SdG2mfHWOp6SzPBqyOGPT\nTb1dq5eP9vKRru8i12+z7MCSpnkksFXSSklfrFHvD4DXvI9emQjNIkmnFQu73ea4jW9zfQ+VdHtG\nZnVkTdIhxfJV7FaOj7kTAzAT+GwNbV51HQZJmu32WSxp3zWq6hKf6xxJH/bCCYV7ys9X+d+7gX7A\nAknnAlcAx3i/fel4bcdKetTrrpNW7zhRda5mNtPM2v10LvCRIpEVpH83wVqnqdEK9FiampoarUKP\nJOyaD2HX/Ajb5kPYtX7q2UVwJ+DLZjZX0njgVOCqQqWk7YDLgT2BlcD97qS8AAw2s91crpCyNBn4\nvplNldSHrq0H6w20ZwvMbG8fZxfgfGAfM3tdUvahcpCZ7StpZ2AqMAV4GzjGzN6QtDXp4XSqyw8D\nPmtmSyQ9Bnze2x/lYxwLXAA8YGZfkdQfmCdpppk9AjziOo0ATjGzrxZPpKC3MxLYGXgOuE/SsWY2\npVCplB53ksv1Bh6V1OJ6vmhmn3G5zSVtBPwCGG1mC5XS494qGvuITL//D7jLzFYV9C6Hmb0AHOen\nXwWGkiI0VmRv3KbfBT5lZm+5k3EWcBnwM0mbmNlbwPHALS5/QQn5S8rZTdI04CtmtqJI1SclHWVm\nU4HP0dnpKDW3Qr9fAH5jZpe5o1Nw8jYD5pjZdyVdQYpOfb9UV97f0ZL+ZmaF1MaXgRFmdoafF+bw\nL26DfzWzDyT9FBgLTKpxrln+g3Tts7ST7pkqNGeOmwjnIAiCIAiCDZ2WlpaaUibrcWqeM7O5fjwJ\n2K+ofiQwy8xe8zfok4FRwB+BHT1qdCiwyh/yt/cHXszsXTN7uw5d8Ifd3UkOXCkOBO4ws9d9jJWZ\nuru8bClQWI8i4DJJbaQox/Zas1ZluZkt8eMnvR7gcWAHPz4EOE9SK2mxRR9gSFYhM1tQyrkqwTwz\n+5OlrcZupbOt9wPuNLO3zexNkoP4b67PwZIuk7SfO0k7AS+Z2ULX4Y1MhGM1krYBbgbGeLt6OQj4\nmetcbG+ATwK7AA+7jU4EhpjZB8BvgCMl9Salr00tJ19JATM7oozD8R/AaZLmkxyjd+uY13zgy5Iu\nJDmPb3r5O2b2az9ewJr7oJha9zsvpP99ChgOzPd5Hwh8tJNw+bmmQaULgPfM7JaiqheB3aqr05z5\nNFUXD2qgpdEK9FhifUA+hF3zIeyaH2HbfAi7rqGpqYnm5ubVn3LUE8EqXv9Raj1Ip4dJM1spaXfg\nUOBrwGjgm6VkO3QknUqKChhwePZhUlIvkuP2DjCtjjkUeKeEzmOBbYA9zaxdaUOBviXk2zPn7ayx\noUhRrqe7oE8xtdi6cyOzpz0KdThwsaQHSM5kNVv3Ijlyze505oFI6+XGlqi7DfgG8Dow38zedAe6\nnHxdmNnvSfcfkj5GHWuQzOwhSaO8zU2SrjSzScB7GbEPWHMfvI+/uPA5bFSnugImmtkFdbZb04H0\nJdI9cGCJ6inAhZKWmNkuXR0jCIIgCIIgKE09EayhkrJpUw8V1c8DRknayiMRY4DZnurV28zuJKWI\nDTezN4DnJR0NIKmPpE2ynZnZtWa2p5kNL35Tb2btZrYD8BgpnaoUDwKj5TuzSRpQRq7gfPQHXnHn\n6gBSuluxTCXuA85Y3UDao4Y25dhbae1XL9L8im39EGn9Tl+l9VT/DjzkaZpvedTiR6RIyDJgkKcn\nIqmfX58sVwBtZnZHKWWU1nBNrKLz/cAphb5L2HsusK+kYV6/qTs7ALNd15NZk9JWSb4uMuujepHu\nwev9fHtJM6u0HUK6L8aTNsso7IhY7p54FtjLj4+mo4NV6T4q1D0AHJfReYDrUBOSPg2cAxxlZu+U\nEDkRmB7OVSNoarQCPZZYH5APYdd8CLvmR9g2H8Ku9VOPg/UUKc1qCWmR/PVeXkgJWwGcR8qDaSVF\nIu4BBgMtnu50s8tAetA7w1PyHgYGdkH/3wMlt7b2lL5LSU5eK3BlVt+sqP+dDIx0fU4AlpaQKdW+\nwMWkjUAWK21p/71iAUkjJN1QYT4F5gHXkNIR/2Bmd2XHNrNW4CZS+tojwA1m1gbsSlr71QpcCFxi\nZu+RnLRrJC0i7TK3cdF4ZwOHKG1ysVDSZ4rqhwB/r6LzjcDzwGIff0yRzn8GvgTc6jaeQ0pfxFMW\n7wU+7X8rylPmGiht1jGoRNUYScuAJaQ1ajd5+XZ0jESVoglok7SQtH7rx5V0AH4O7O82+CTwZqau\nUiSyYKelJCdwhs97BtBpThXm+hPSZhr3+7W8tqh+AGl3wSAIgiAIgiAH5Etm1ksknQNsbWbnVRUO\nuoxv4nCzmT3RaF26E6WdDv9kZvc2Wpe1hW+asdjMflZBxhq/+35PpIXkr4v1+Xt3XaSlpSXesOZA\n2DUfwq75EbbNh7BreSRhZp0ylOpZg7UuMoW0LmZ60W9hBd2I/25Tj8PMftpoHdYmkmaT1g2W2u0w\nCIIgCIIg6AbW6whWEATdT4pgBXkxcOBQVqx4ttFqBEEQBEHwD9JTI1hBEORAvHgJgiAIgiDoGl35\ncd8gCIKgTuJ3RPIjbJsPYdd8CLvmR9g2H8Ku9RMOVhAEQRAEQRAEQTcRa7CCIOiAJIvvhSAIgiAI\ngsqUW4MVEawgCIIgCIIgCIJuIhysIAiCtUDksOdH2DYfwq75EHbNj7BtPoRd6yccrCAIgiAIgiAI\ngm4i1mAFQdCB+B2s9ZOBgwey4oUVjVYjCIIgCDYYyq3BCgcrCIIOSDKaG61FUDfN8ftlQRAEQbA2\niU0ugiAIGsnyRivQc4n1AfkQds2HsGt+hG3zIexaPzU5WJKGSnq8TN0sScO7V63akDRE0kJJ0zNl\n69RjjKT9JU2oQW55Rv6ecjKStupGvUqOk6mvqLffF7OqyHT7/ZHts5brLWk3SXMktUm6W1K/GtpU\n7FfSqto1Xt3mh5Iel3SFpG0kzZW0QNJ+tVzbGuc6QNIMScsk3Sepf6but5LmSdq2Xt2DIAiCIAiC\n2qgngrUu5p4cA8wws8MyZeuinrXoZGWO6+2nHqr1V6/ejaCW8W8EzjWz3YE7gXO7od+uzPtkYDcz\n+zZwELDYzEaY2e9q7K8WmfOAmWa2E/Ag8J3Vjc1GAQuAI+rWPPjH2bHRCvRcmpqaGq1CjyTsmg9h\n1/wI2+ZD2LV+6nGwNpI0SdISSbdL6lssIGmMpMX+udzLekma4GVtks708mGS7pe0SNJjkrry+LEl\n8EpR2asZfU70MVslTfSyCZKulvSwpGckHevlm0ma6bq0STrKy4dKWurtlkmaLOlgb79M0l4ut6mk\n8ZmoxJGuxrvAX2uYy6uZ4/6S7pX0lKRrM+WrczwlneXRkMUZm27q7Vq9fLSXj3R9F7l+m2UHljTN\nI4GtklZK+mKNen8AvOZ99MpEaBZJOq1Y2O02x218m+t7qKTbMzIqbMp2AAAgAElEQVSrI2uSDimW\nr2K3cnzMnRiAmcBna2jzquswSNJst89iSfuuUVWX+FznSPqwF04o3FN+vsr/3g30AxZIOhe4AjjG\n++1Lx2s7VtKjXnedpEJdLXM9GpjoxxNJLyGyrCD9uwmCIAiCIAhyoB4HayfgGjPbBVgFnJqtlLQd\ncDnQBOwBjHQnZQ9gsJnt5hGEQtrZZOAnZrYH8K/A/3ZB/95Ae7bAzPZ2fXYBzgeazGxP4MyM2CAz\n2xc4kvSgC/A2cIyZ7QUcCFyZkR8G/NCjAjsBn/f25/gYABcAD5jZJ739jyRtYmaPmNm3XKcRkm4o\nNZGC3s5I4DRgZ+Cfsw/s3s9w4CSX2wc4WdLuwKeBF81sTzPbDfiNpI2AXwCnu60PAt4qGvsIMxsO\nfAV4Frgrq3c5zOwFMzvOT78KDCVFaPYgXd+szlsD3wU+5TZeAJxFcnj+j6RNXPR44BaXv6CEfFm7\nuaM4qISqTxYcZuBzwEcqzauo3y8Av3H77A4s8vLNgDk+14dI0amSXXl/RwN/N7PhZvYD4ELgF37+\ndmYO/+I2+Fcfsx0YW8dctzWzl11+BVCcDthO+ndTmVmZzzqVdLseE3bMjVgfkA9h13wIu+ZH2DYf\nwq5raGlpobm5efWnHB+qo8/nzGyuH08CTgeuytSPBGaZWSGiMRkYBVwC7CjpauDXwAylNTDbm9lU\nADN7tw498P5FeuCdVEbkQOAOM3vdx1iZqbvLy5ZqzXoUAZdJGkV6CN0+U7fczJb48ZMkpwDgcWAH\nPz4EOFLSOX7eBxgCLCsMamYLSI5INeaZ2Z98nrcC+wFTMvX7AXcWHswlTQH+DbiP5NhdBkwzs99J\n+gTwkpktdB3e8DYdBpS0DXAzcJyZ1b2+iOS4XWe+jVmRvQE+CewCPOzXbiOSg/KBpN+QbPcrUvra\nOSRHvZN8JQXMrFzq238AP5H0X8BUUnSuVuYD491RvdvM2rz8HTP7tR8vIM2/FJ12lilDIf3vU8Bw\nYL7Puy/wcifh8nMt12+BF0m2rcwBNfYeBEEQBEGwgdDU1NQhZXLcuHEl5epxsIof1EqtB+n0MGlm\nKz26cijwNWA08M1Ssh06kk4lRQUMONzfxhfqegF/BN4BptUxhwLvlNB5LLANsKeZtSttKNC3hHx7\n5rydNTYU8Fkze7oL+hRTi607NzJ72qNbhwMXS3qA5ExWs3Uv4Fag2cyWdkHfWhBpvdzYEnW3Ad8A\nXgfmm9mb7lyUk68LM/s96f5D0seoYw2SmT3kTvcRwE2SrjSzScB7GbEPWHMfvI9HhjOOYT0ImGhm\nF9TZrsDLkgaa2cse4SpOoZ0CXChpiUejg7VFrMHKjVgfkA9h13wIu+ZH2DYfwq71U0+K4FBJ2bSp\nh4rq5wGjJG0lqTcwBpjtqV69zexOUorYcI+iPC/paABJfTIpYgCY2bWe6jY861x5XbuZ7QA8Rkqn\nKsWDwGj5zmySBpSRKzgf/YFX3Lk6gJTuVixTifuAM1Y3kPaooU059lZa+9WLNL9iWz9EWr/T19dT\n/TvwkKdpvmVmtwA/IkVClgGDJI1wvfr59clyBdBmZneUUkZpDdfEUnUZ7gdOKfRdwt5zgX0lDfP6\nTd3ZAZjtup5MSmesJl8XmfVRvUj34PV+vr2kmVXaDiHdF+NJm2UUdkQsd088C+zlx0fT0cGqdB8V\n6h4AjsvoPMB1qJWpwJf8+CTg7qL6E4Hp4VwFQRAEQRDkQz0O1lPAaZKWkBbJX+/lhZSwFaQdzFqA\nVlIk4h5gMNAiqZWUgnaetzsROENSG/AwMLAL+v8eKLm1taf0XUpy8lpZs6aqXHRoMmndWBtwArC0\nhEyp9gUuJm0EslhpS/vvFQtUWoNVxDzgGlI64h/M7K7s2GbWCtxESl97BLjBU9d2Beb5fC8ELjGz\n90hO2jWSFgEzgI2LxjsbOERpk4uFkj5TVD8E+HsVnW8EngcW+/hjinT+M+nB/1a38RzSejbMrB24\nl7SG7N5q8pS5BhXWJY2RtAxYQlqjdpOXb0fHSFQpmoA2SQtJ67d+XEkH4OfA/m6DTwJvZuoqRSIL\ndlpKcgJn+LxnAJ3mVGGuVwAH+3w/RVoXmWUA0B1R1qBeYg1WbsT6gHwIu+ZD2DU/wrb5EHatH/mS\nmfUSX++0tZmdV1U46DKSrgBuNrMnGq1Ld6K00+GfzOzeRuuytpD0U9L28D+rIGM0rz2dNhiWk2+a\nYDOsz9/n/wgtLS2RwpIDYdd8CLvmR9g2H8Ku5ZGEmXXKUFrfHaxhpEjOG0W/hRUEQRGSZpPWDZ5g\nZi9WkFt/vxQ2YAYOHsiKF1ZUFwyCIAiCoFvokQ5WEATdjySL74UgCIIgCILKlHOw6lmDFQRBEHSR\nyGHPj7BtPoRd8yHsmh9h23wIu9ZPOFhBEARBEARBEATdRKQIBkHQgUgRDIIgCIIgqE6kCAZBEARB\nEARBEORMOFhBEARrgchhz4+wbT6EXfMh7JofYdt8CLvWTzhYQRAEQRAEQRAE3USswQqCoAPxO1hB\nEAQwcOBQVqx4ttFqBEGwDhO/gxUEQU0kByu+F4Ig2NAR8YwUBEElYpOLIAiChtLSaAV6MC2NVqCH\n0tJoBXoksZ4lP8K2+RB2rZ+aHCxJQyU9XqZulqTh3atWbUgaImmhpOmZsuWN0KUckvaXNKEGueUZ\n+XvKyUjaqhv1KjlOpr6i3n5fzKoi0+33R7bPWq63pIskveD3ykJJn66hTcV+Ja2qXePVbX4o6XFJ\nV0jaRtJcSQsk7VfLta1xrj+QtFTSIkm/krRFpu63kuZJ2rZe3YMgCIIgCILaqCeCtS7GyY8BZpjZ\nYZmydVHPWnSyMsf19lMP1fqrV+9GUOv4V5nZcP/8phv67cq8TwZ2M7NvAwcBi81shJn9rsb+apGZ\nAXzczPYAnga+s7qx2ShgAXBE3ZoH3UBToxXowTQ1WoEeSlOjFeiRNDU1NVqFHkvYNh/CrvVTj4O1\nkaRJkpZIul1S32IBSWMkLfbP5V7WS9IEL2uTdKaXD5N0v79pf0zSjl3Qf0vglaKyVzP6nOhjtkqa\n6GUTJF0t6WFJz0g61ss3kzTTdWmTdJSXD/WIwARJyyRNlnSwt18maS+X21TS+ExU4khX413grzXM\n5dXMcX9J90p6StK1mfLVOZ6SzvJoyOKMTTf1dq1ePtrLR7q+i1y/zbIDS5rmkZ1WSSslfbFGvT8A\nXvM+emUiNIsknVYs7Hab4za+zfU9VNLtGZnVkTVJhxTLV7FbJTrlx1bhVddhkKTZbp/FkvZdo6ou\n8bnOkfRhL5xQuKf8fJX/vRvoByyQdC5wBXCM99uXjtd2rKRHve46SYW6qnM1s5lm1u6nc4GPFIms\nIP27CYIgCIIgCPLAzKp+gKFAO/BJPx8PnOXHs4DhwHbAn4CtSI7bA8BRXjcj09cW/ncucJQf9wH6\n1qJLkV7jgG+WqdsFeAoY4Odb+t8JwG1+vDPwtB/3Bvr58daZ8qEkZ2MXP38MGO/HRwFT/PhS4At+\n3B9YBmxSpNMI4IYqc9of+LuPK1JE4livW+72HQ60AX2BzYAngN2BY4GfZfraHNgI+AMw3Mv6+fXZ\nH5haNPZwYBGweReuxdeA21mzcUrB3oX7Y2tgdsEmwLnAd93uz2bKrwXGlJPP9llCh2nAoBLlF7nt\nFgE3Av3rmNdZwHf8WMBmftwOHO7HVwDnZ+6vYzPt/1bm+CTgvzPnhWv7L8BUoLeX/xQ4oda5FslM\nLdyTmbL/Av6zSjuDizKfWQYWn3/4E3YM265vnw3drlgezJo1K5d+g7BtXoRd1zBr1iy76KKLVn/8\ne4Liz4eonefMbK4fTwJOB67K1I8EZplZIaIxGRgFXALsKOlq4NfADEn9gO3NbCpJs3fr0APvXySn\nYlIZkQOBO8zsdR9jZabuLi9bmlmPIuAySaNID8/bZ+qWm9kSP34SmOnHjwM7+PEhwJGSzvHzPsAQ\nkqOFj7cA+GoN05tnZn/yed4K7AdMydTvB9xpZm+7zBTg34D7gB9JugyYZma/k/QJ4CUzW+g6vOFt\nOgwoaRvgZuA4M6t7fREp5e06MzMfZ2VR/SdJTu/Dfu02AuaY2QeSfkOy3a9I6WvnkHJTOslXUsDM\nyqW+XQt8z8xM0iWk+/YrNc5rPjBe0kbA3WbW5uXvmNmv/XgBaf6lqDVyZv73UySHdL7Puy/wcifh\n8nNNg0oXAO+Z2S1FVS9SU95Pc3WRIAiCIAiCDYimpqYOKZPjxo0rKVePg2VVzqHEw6SZrZS0O3Ao\nKcoxGvhmKdkOHUmnktasGClSsCJT1wv4I/AO6U1+vbxTQuexwDbAnmbWrrShQN8S8u2Z83bW2FDA\nZ83s6S7oU0wttu7cyOxppc0fDgculvQAyZmsZutewK1As5kt7YK+tSBSJHNsibrbgG8ArwPzzexN\ndy7KydeFmWVT634OlN3co0Tbh9zpPgK4SdKVZjYJeC8j9gFr7oP38dTbjGNYDwImmtkFdbZb04H0\nJdI9cGCJ6inAhZKWmNkuXR0j6ApNjVagB9PUaAV6KE2NVqBHEutZ8iNsmw9h1/qpZw3WUEl7+/EX\ngIeK6ucBoyRtJak3Kc1rtqStSelOd5JSwoZ7FOV5SUcDSOojaZNsZ2Z2rZntaWlTghVFde1mtgMp\nXe/4Mvo+CIyW78wmaUAZuYLz0R94xZ2rA0gpesUylbgPOGN1A2mPGtqUY2+ltV+9SPMrtvVDpPU7\nfX091b8DD0naDnjLoxY/IkVClgGDJI1wvfr59clyBdBmZneUUsbXcE2sovP9wCmFvkvYey6wr6Rh\nXr+ppI953WzX9WTgFzXI14WkQZnTY0kplUjaXtLM0q1Wtx1Cui/Gk9ILCzsilrsnngX28uOj6ehg\nVbqPCnUPAMdl1nQNcB1qQmmHxHNI6bfvlBA5EZgezlUQBEEQBEE+1ONgPQWcJmkJaZH89V5eSAlb\nAZxH+uGMVlIk4h5gMNAiqZWUgnaetzsROENSG/AwMLAL+v+etG6lE57SdynJyWsFrszqmxX1v5OB\nka7PCcDSEjKl2he4mLQRyGKlLe2/VywgaYSkGyrMp8A84BpSOuIfzOyu7Nhm1grcREpfe4S0rqsN\n2BWY5/O9ELjEzN4jOWnXSFpEWtO1cdF4ZwOHKG1ysVDSZ4rqh5DWhVXiRuB5YLGPP6ZI5z8DXwJu\ndRvPAXbyunbgXuDT/reiPGWugdJmHYNKVP3Ar8si0tqzb3n5dnSMRJWiCWiTtBD4HPDjSjqQImT7\nuw0+CbyZqasUiSzYaSnpRcQMn/cMoNOcKsz1J6R1dvf7tby2qH4AaXfBYK3T0mgFejAtjVagh9LS\naAV6JPGbQvkRts2HsGv9FDYkWC/x9U5bm9l5VYWDLiPpCuBmM3ui0bp0J0o7Hf7JzO5ttC5rC0k/\nJW0P/7MKMlZjVmpQFy1EylVetBC2zYMWNmy7ijyekVpaWiLlKifCtvkQdi2PJMysU4bS+u5gDSNF\nct6wjr+FFQRBEZJmk9YNnmBmL1aQW3+/FIIgCLqJgQOHsmLFs41WIwiCdZge6WAFQdD9SLL4XgiC\nIAiCIKhMOQernjVYQRAEQReJHPb8CNvmQ9g1H8Ku+RG2zYewa/2EgxUEQRAEQRAEQdBNRIpgEAQd\niBTBIAiCIAiC6kSKYBAEQRAEQRAEQc6EgxUEQbAWiBz2/Ajb5kPYNR/CrvkRts2HsGv9hIMVBEEQ\nBEEQBEHQTcQarCAIOhC/gxUEQbDuMXDwQFa8sKLRagRBkCF+BysIgpqQZDQ3WosgCIKgA80Qz2xB\nsG4Rm1wEQRA0kuWNVqAHE7bNh7BrPoRdcyPWCuVD2LV+anKwJA2V9HiZulmShnevWrUhaYikhZKm\nZ8rWqa8uSftLmlCD3PKM/D3lZCRt1Y16lRwnU19Rb78vZlWR6fb7I9tnLddb0kWSXvB7ZaGkT9fQ\npmK/klbVrvHqNj+U9LikKyRtI2mupAWS9qvl2tY41wGSZkhaJuk+Sf0zdb+VNE/StvXqHgRBEARB\nENRGPRGsdTEufQwww8wOy5Sti3rWopOVOa63n3qo1l+9ejeCWse/ysyG++c33dBvV+Z9MrCbmX0b\nOAhYbGYjzOx3NfZXi8x5wEwz2wl4EPjO6sZmo4AFwBF1ax784+zYaAV6MGHbfAi75kPYNTeampoa\nrUKPJOxaP/U4WBtJmiRpiaTbJfUtFpA0RtJi/1zuZb0kTfCyNklnevkwSfdLWiTpMUld+crZEnil\nqOzVjD4n+pitkiZ62QRJV0t6WNIzko718s0kzXRd2iQd5eVDJS31dsskTZZ0sLdfJmkvl9tU0vhM\nVOJIV+Nd4K81zOXVzHF/SfdKekrStZny1Tmeks7yaMjijE039XatXj7ay0e6votcv82yA0ua5pGd\nVkkrJX2xRr0/AF7zPnplIjSLJJ1WLOx2m+M2vs31PVTS7RmZ1ZE1SYcUy1exWyU65cdW4VXXYZCk\n2W6fxZL2XaOqLvG5zpH0YS+cULin/HyV/70b6AcskHQucAVwjPfbl47XdqykR73uOkmFulrmejQw\n0Y8nkl5CZFlB+ncTBEEQBEEQ5MCH6pDdCfiymc2VNB44FbiqUClpO+ByYE9gJXC/OykvAIPNbDeX\n28KbTAa+b2ZTJfWha+vBegPt2QIz29vH2QU4H9jHzF6XlH2oHGRm+0raGZgKTAHeBo4xszckbQ3M\n9TqAYcBnzWyJpMeAz3v7o3yMY4ELgAfM7CueljVP0kwzewR4xHUaAZxiZl8tnkhBb2cksDPwHHCf\npGPNbEqhUik97iSX6w08KqnF9XzRzD7jcptL2gj4BTDazBZK6ge8VTT2EZl+/x9wl5mtKuhdDjN7\nATjOT78KDCVFaKzI3rhNvwt8yszecifjLOAy4GeSNjGzt4DjgVtc/oIS8peUs5ukacBXzKzUNkvf\ncMfxMeBsM6voPGb6/QLwGzO7zB2dgpO3GTDHzL4r6QpSdOr7pbry/o6W9DczK6Q2vgyMMLMz/Lww\nh39xG/yrmX0g6afAWGBSjXPd1sxe9jFXqHM6YDvpnqlMNvFzB+KNa3ewnLBjXoRt8yHsmg9h19xo\naWmJaEsOhF3X0NLSUtOatHocrOfMbK4fTwJOJ+NgkR72Z5lZIaIxGRhFeiDeUdLVwK+BGf6Qv72Z\nTQUws3fr0APvX8DurkspDgTuMLPXfYyVmbq7vGxp5gFUwGWSRpEeQrfP1C03syV+/CQw048fJz1+\nAhwCHCnpHD/vAwwBlhUGNbMFJEekGvPM7E8+z1uB/UhOYIH9gDvN7G2XmQL8G3Af8CNJlwHTzOx3\nkj4BvGRmC12HN7xNhwElbQPcDBznzlW9HARcZ77FUZG9AT4J7AI87NduI5KD8oGk35Bs9ytS+to5\nQFMp+UoKFBzFElwLfM8dv0tI9+1XapzXfGC8O6p3m1mbl79jZr/24wWk+Zei1shZIf3vU8BwYL7P\nuy/wcifh8nMt12+BF0m2rcwBNfYeBEEQBEGwgdDU1NTB2Rw3blxJuXocrOIHtVLrQTo9TJrZSkm7\nA4cCXwNGA98sJduhI+lUUlTAgMOzb+ol9QL+CLwDTKtjDgXeKaHzWGAbYE8za1faUKBvCfn2zHk7\na2woUpTr6S7oU0wttu7cyOxpj0IdDlws6QGSM1nN1r2AW4FmM1vaBX1rQaT1cmNL1N0GfAN4HZhv\nZm+6c1FOvi7MLJta93Og7OYeJdo+5E73EcBNkq40s0nAexmxD1hzH7yPR2MzjmE9CJhoZhfU2a7A\ny5IGmtnLkgbROYV2CnChpCVmtksXxwi6Qryxzo+wbT6EXfMh7JobEWXJh7Br/dSTljdUUjZt6qGi\n+nnAKElbSeoNjAFme6pXbzO7k5QiNtyjKM9LOhpAUh9Jm2Q7M7NrzWxP35RgRVFdu5ntQEr3Or6M\nvg8Co+U7s0kaUEau4Hz0B15x5+oAUrpbsUwl7gPOWN1A2qOGNuXYW2ntVy/S/Ipt/RBp/U5fpfVU\n/w485Gmab5nZLcCPSJGQZcAgT09EUj+/PlmuANrM7I5Syiit4ZpYqi7D/cAphb5L2HsusK+kYV6/\nqaSPed1s1/VkUjpjNfm6cEejwLHAE16+vaSZpVutbjuEdF+MB250PaH8PfEssJcfH01HB6vSfVSo\newA4TmvWdA1wHWplKvAlPz4JuLuo/kRgejhXQRAEQRAE+VCPg/UUcJqkJaRF8td7eSElbAVpB7MW\noJUUibgHGAy0SGolpaCd5+1OBM6Q1AY8DAzsgv6/B0pube0pfZeSnLxW4MqsvllR/zsZGOn6nAAs\nLSFTqn2Bi0kbgSxW2tL+e8UCkkZIuqHCfArMA64hpSP+wczuyo5tZq3ATaT0tUeAGzx1bVfS2q9W\n4ELgEjN7j+SkXSNpETAD2LhovLOBQ5Q2uVgo6TNF9UOAv1fR+UbgeWCxjz+mSOc/kx78b3UbzyGt\n68PM2oF7gU/734rylLkGSpt1DCpR9QO/LouA/YFvefl2dIxElaIJaJO0EPgc8ONKOpAiZPu7DT4J\nvJmpqxSJLNhpKelFxAyf9wyg05wqzPUK4GBJy0jphpcX1Q8AuiPKGtTLOvUDEj2MsG0+hF3zIeya\nG/F7TfkQdq0frc+/Cu7rnbY2s/OqCgddxjdxuNnMnmi0Lt2J0k6HfzKzexuty9rCN81YbGY/qyBj\nNK89nTYYYmF7foRt8yHsmg9dtWszrM/PbGuD2IwhH8Ku5ZGEmXXKUFrfHaxhpEjOG0W/hRUEQRGS\nZpPWDZ5gZi9WkFt/vxSCIAh6KAMHD2TFC6U2yQ2CoFH0SAcrCILuR5LF90IQBEEQBEFlyjlYXfnt\nqSAIgqBOIoc9P8K2+RB2zYewa36EbfMh7Fo/4WAFQRAEQRAEQRB0E5EiGARBByJFMAiCIAiCoDqR\nIhgE/5+9O4+zo6rzPv75JoBsQ4CoCSAJTEZ5RIUQQFEwacSdVQw7A8OAy0tHVFyGEZUEQUAFjSAq\nYyagiQjMRHYkLOkMBENCCAmQEEHC6hPgUeIERxHTv+ePc25SffuuTVe603zfr9d9dd1Tp6p+9atK\n554+59Q1MzMzMyuZG1hmZuuBx7CXx7kth/NaDue1PM5tOZzX9rmBZWZmZmZm1kc8B8vMuvH3YJmZ\nlW/EiNGsXPl4f4dhZq+AvwfLzFqSGlj+vWBmVi7hz2BmGzY/5MLMrF919ncAg1hnfwcwSHX2dwCD\nVGd/BzBoea5QOZzX9rXUwJI0WtIDddbNljSub8NqjaRRku6TdHOhbEV/xFKPpAmSprVQb0Wh/vX1\n6kjatg/jqnmcwvqGcef7YnaTOn1+fxT32cr1ljRR0oOS1rQaS7P9SlrdWrTdtvm2pAcknS/ptZLm\nSVooab9Wrm2L5/otScsk3S/pvyRtVVj335LmS3p9u7GbmZmZWWva6cEaiP3YhwGzIuJDhbKBGGcr\nMUWd5Xb3045m+2s37v7QyvEfAD4CzOnD/fbmvD8G7BYR/wq8F1gSEXtGxF0t7q+VOrOAt0TEWOAR\n4N/WbhwxHlgIHNh25NYHOvo7gEGso78DGKQ6+juAQaqjvwMYtDo6Ovo7hEHJeW1fOw2sjSVNl7RU\n0lWSNq2uIOkYSUvy67xcNkTStFy2WNJnc/kYSbfmv7TfK2nnXsS/NfBcVdnzhXhOyMdcJOnyXDZN\n0hRJcyU9KunwXL6FpNtyLIslHZLLR+cegWmSlkuaIel9efvlkvbK9TaXNLXQK3FwDuOvwB9bOJfn\nC8vDJN0g6WFJlxTK147xlHRa7g1ZUsjp5nm7Rbn8iFy+d473/hzfFsUDS7ox9wQukrRK0j+2GPca\n4A95H0MKPTT3S/p0deWct7tzjq/M8X5A0lWFOmt71iS9v7p+k7zVFBHLI+KRYv5a8HyOYaSkOTk/\nSyTtuy5UnZ3P9W5Jr8uF0yr3VH6/Ov+8FtgSWCjpy8D5wGF5v5vS/doeJ+mevO6HkirrWjnX2yKi\nK7+dB7yhqspK0r8bMzMzMyvBRm3U3QU4KSLmSZoKfAq4sLJS0nbAecAewCrg1txIeRrYISJ2y/Uq\nQ5ZmAN+MiOskbULv5oMNBbqKBRHxjnycXYGvAO+MiBckFT9UjoyIfSW9GbgOmAn8BTgsIl6UNJz0\n4fS6XH8M8NGIWCrpXuDovP0h+RiHA2cAt0fEyZKGAfMl3RYRvwZ+nWPaE/hERHy8+kQqcWd7A28G\nngRukXR4RMysrFQa5nZirjcUuEdSZ47zmYg4KNf7O0kbA78AjoiI+yRtCfy56tgHFvb7H8A1EbG6\nEnc9EfE0MDG//TgwmtRDE1X5Juf0q8ABEfHn3Mg4DTgX+LGkzSLiz8BRwM9z/TNq1D+7Xt4k3Qic\nHBErG8XdisJ+jwV+FRHn5oZOpZG3BXB3RHxV0vmk3qlv1tpV3t+hkv4nIipDG58F9oyIU/P7yjn8\nn5yDd0XEGkk/AI4DpvfiXP+ZdO2Lukj3TBOTCssd+C+ufaET57EsnTi3ZejEeS1DJ85rOTo7O93b\nUgLndZ3Ozs6W5qS108B6MiLm5eXpwGcoNLBIH/ZnR0SlR2MGMJ70gXhnSVOAm4BZ+UP+9hFxHUBE\n/LWNOMj7F7B7jqWW9wBXR8QL+RirCuuuyWXLtG4+ioBzJY0nfQjdvrBuRUQszcsPAbfl5QeAnfLy\n+4GDJX0pv98EGAUsrxw0IhaSGiLNzI+IJ/J5XgHsR2oEVuwH/DIi/pLrzATeDdwCfEfSucCNEXGX\npLcCv4uI+3IML+Ztuh1Q0muBnwETc+OqXe8Ffhj5kUhV+QbYB9gVmJuv3cakBsoaSb8i5e6/SMPX\nvkT636dH/UYBVBqKfWwBMDU3VK+NiMW5/KWIuCkvLySdfy2t9ppVhv8dAIwDFuTz3hR4tkflJucq\n6Qzg5Yj4edWqZ2jpf/ZJzauYmZmZvYp0dHR0a2xOnjy5ZuJYhU4AACAASURBVL12GljV8z9qzQfp\n8WEyIlZJ2h34APBJ4Ajgc7XqdtuR9ClSr0AAHy7+pV7SEOAx4CXgxjbOoeKlGjEfB7wW2CMiupQe\nKLBpjfpdhfddrMuhSL1cj/Qinmqt5LrnRhGP5F6oDwPfkHQ7qTHZLNdDgCuASRGxrBfxtkKk+XLH\n1Vh3JfAvwAvAgoj4U25c1Ku/3kTEnbnRfSBwmaQLImI68HKh2hrW3Qd/I/fGFhqG7RBweUSc0duY\nJf0T6R54T43VM4GvS1oaEbv29hjWGx39HcAg1tHfAQxSHf0dwCDV0d8BDFruZSmH89q+dobljZZU\nHDZ1Z9X6+cB4SdtKGgocA8zJQ72GRsQvSUPExuVelKckHQogaRNJmxV3FhGXRMQeETGuehhURHRF\nxE7AvaThVLXcARyh/GQ2SdvUqVdpfAwDnsuNq/1Jw92q6zRyC3Dq2g2ksS1sU887lOZ+DSGdX3Wu\n7yTN39lUaT7VR4A78zDNP+dei++QekKWAyPz8EQkbZmvT9H5wOKIuLpWMEpzuC5vEvOtwCcq+66R\n73nAvpLG5PWbS3pjXjcnx/ox1g1pa1T/lSjOddpe0m0NK0ujSPfFVOAnOc5u+6nyOLBXXj6U7g2s\nRvdRZd3twMTCnK5tcgwtkfRBUg/gIRHxUo0qJwA3u3FlZmZmVo52GlgPA5+WtJQ0Sf5HubwyJGwl\ncDppcPEiUk/E9cAOQKekRaQhaKfn7U4ATpW0GJgLjOhF/L8Baj7aOg/pO4fUyFsEXFCMt1g1/5wB\n7J3jOR5YVqNOre0rvkF6EMgSpUfan1VdQdKeki5tcD4V84GLScMRfxsR1xSPHRGLgMtIw9d+DVya\nh669jTT3axHwdeDsiHiZ1Ei7WNL9pKfMvabqeF8A3q/0kIv7JB1UtX4U8L9NYv4J8BSwJB//mKqY\n/x/wT8AVOcd3k+b1kR/KcAPwwfyzYX3qXAOlh3WMrFF+mKSnSMMUb9C6x/pvR/eeqFo6gMWS7gOO\nBL7XKAbg34EJOQf7AH8qrGvUE1nJ0zLSHyJm5fOeBdQ6p5rnClxEepjGrflaXlK1fhvS0wVtvevs\n7wAGsc7+DmCQ6uzvAAapzv4OYNDy9zWVw3ltnzbkbxHP852GR8TpTStbr+WHOPwsIh7s71j6ktKT\nDp+IiBv6O5b1JT80Y0lE/LhBnej/p+8PRp14aFBZOnFuy9CJ81qGTlJexYb8GWwg8sMYyuG81ieJ\niOgxQmlDb2CNIfXkvFj1XVhmVkXSHNK8weMj4pkG9dzAMjMrnRtYZhu6QdnAMrO+lxpYZmZWphEj\nRrNy5eP9HYaZvQL1Gli9+e4pMxvkIsKvPn7Nnj2732MYrC/n1nndkF6VvLpx1fc8V6gczmv73MAy\nMzMzMzPrIx4iaGbdSAr/XjAzMzNrzEMEzczMzMzMSuYGlpnZeuAx7OVxbsvhvJbDeS2Pc1sO57V9\nbmCZmZmZmZn1Ec/BMrNuPAfLzMzMrLl6c7A26o9gzGxgk3r8rjAzs0FixA4jWPn0yv4Ow2zQcg+W\nmXUjKZjU31EMQiuAnfs7iEHKuS2H81qOgZDXSen7Dgebzs5OOjo6+juMQcd5rc9PETQzMzMzMytZ\nSw0sSaMlPVBn3WxJ4/o2rNZIGiXpPkk3F8pW9Ecs9UiaIGlaC/VWFOpfX6+OpG37MK6axymsbxh3\nvi9mN6nT5/dHcZ+tXG9JEyU9KGlNq7E026+k1a1F222bb0t6QNL5kl4raZ6khZL2a+Xatniu20ia\nJWm5pFskDSus+29J8yW9vt3YrQ/091+sBzPnthzOazmc19K4l6Uczmv72unBGoh9yYcBsyLiQ4Wy\ngRhnKzFFneV299OOZvtrN+7+0MrxHwA+Aszpw/325rw/BuwWEf8KvBdYEhF7RsRdLe6vlTqnA7dF\nxC7AHcC/rd04YjywEDiw7cjNzMzMrCXtNLA2ljRd0lJJV0natLqCpGMkLcmv83LZEEnTctliSZ/N\n5WMk3Srpfkn3SurN33S2Bp6rKnu+EM8J+ZiLJF2ey6ZJmiJprqRHJR2ey7eQdFuOZbGkQ3L5aEnL\n8nbLJc2Q9L68/XJJe+V6m0uaWuiVODiH8Vfgjy2cy/OF5WGSbpD0sKRLCuVrx3hKOi33hiwp5HTz\nvN2iXH5ELt87x3t/jm+L4oEl3Zh7AhdJWiXpH1uMew3wh7yPIYUemvslfbq6cs7b3TnHV+Z4PyDp\nqkKdtT1rkt5fXb9J3mqKiOUR8Ugxfy14PscwUtKcnJ8lkvZdF6rOzud6t6TX5cJplXsqv1+df14L\nbAkslPRl4HzgsLzfTel+bY+TdE9e90Np7RMnmp4rcChweV6+nPRHiKKVpH83tr4NqL71Qca5LYfz\nWg7ntTT+vqZyOK/ta+cpgrsAJ0XEPElTgU8BF1ZWStoOOA/YA1gF3JobKU8DO0TEbrneVnmTGcA3\nI+I6SZvQu/lgQ4GuYkFEvCMfZ1fgK8A7I+IFScUPlSMjYl9JbwauA2YCfwEOi4gXJQ0H5uV1AGOA\nj0bEUkn3Akfn7Q/JxzgcOAO4PSJOzsOy5ku6LSJ+Dfw6x7Qn8ImI+Hj1iVTizvYG3gw8Cdwi6fCI\nmFlZqTTM7cRcbyhwj6TOHOczEXFQrvd3kjYGfgEcERH3SdoS+HPVsQ8s7Pc/gGsiYnUl7noi4mlg\nYn77cWA0qYcmqvJNzulXgQMi4s+5kXEacC7wY0mbRcSfgaOAn+f6Z9Sof3a9vEm6ETg5Il7xo5EK\n+z0W+FVEnJsbOpVG3hbA3RHxVUnnk3qnvllrV3l/h0r6n4ioDG18FtgzIk7N7yvn8H9yDt4VEWsk\n/QA4Dpje4rm+PiKezcdcqZ7DAbtI90xjxYGfO+EhLWZmZvaq19nZ2VKDs50G1pMRMS8vTwc+Q6GB\nRfqwPzsiKj0aM4DxpA/EO0uaAtwEzMof8rePiOsAIuKvbcRB3r+A3XMstbwHuDoiXsjHWFVYd00u\nW1b4ACrgXEnjSR9Cty+sWxERS/PyQ8BtefkB0sdPgPcDB0v6Un6/CTAKWF45aEQsJDVEmpkfEU/k\n87wC2I/UCKzYD/hlRPwl15kJvBu4BfiOpHOBGyPiLklvBX4XEfflGF7M23Q7oKTXAj8DJubGVbve\nC/yw8gVKVfkG2AfYFZibr93GpAbKGkm/IuXuv0jD174EdNSq3yiASkOxjy0ApuaG6rURsTiXvxQR\nN+XlhaTzr6XVXrPK8L8DgHHAgnzemwLP9qjc+rlWDyt8hpTbxvZvce/WOjdSy+PclsN5LYfzWhrP\nFSqH87pOR0dHt3xMnjy5Zr12GljVH9RqzQfp8WEyIlZJ2h34APBJ4Ajgc7XqdtuR9ClSr0AAHy7+\npV7SEOAx4CXgxjbOoeKlGjEfB7wW2CMiupQeKLBpjfpdhfddrMuhSL1cj/Qinmqt5LrnRhGP5F6o\nDwPfkHQ7qTHZLNdDgCuASRGxrBfxtkKk+XLH1Vh3JfAvwAvAgoj4U25c1Ku/3kTEnbnRfSBwmaQL\nImI68HKh2hrW3Qd/I/fGFhqG7RBweUSc0cuQn5U0IiKelTSSnkNoZwJfl7Q0Inbt5THMzMzMrI52\nhuWNllQcNnVn1fr5wHhJ20oaChwDzMlDvYZGxC9JQ8TG5V6UpyQdCiBpE0mbFXcWEZdExB4RMa56\nGFREdEXETsC9pOFUtdwBHKH8ZDZJ29SpV2l8DAOey42r/UnD3arrNHILcOraDaSxLWxTzzuU5n4N\nIZ1fda7vJM3f2VRpPtVHgDvzMM0/R8TPge+QekKWAyPz8EQkbZmvT9H5wOKIuLpWMEpzuC6vta7g\nVuATlX3XyPc8YF9JY/L6zSW9Ma+bk2P9GGk4Y7P6r0RxrtP2km5rWFkaRbovpgI/yXF220+Vx4G9\n8vKhdG9gNbqPKutuByYW5nRtk2No1XXAP+XlE4Frq9afANzsxlU/8LyL8ji35XBey+G8lsZzhcrh\nvLavnQbWw8CnJS0lTZL/US6vDAlbSXqCWSewiNQTcT2wA9ApaRFpCNrpebsTgFMlLQbmAiN6Ef9v\ngJqPts5D+s4hNfIWARcU4y1WzT9nAHvneI4HltWoU2v7im+QHgSyROmR9mdVV5C0p6RLG5xPxXzg\nYtJwxN9GxDXFY0fEIuAy0vC1XwOX5qFrbyPN/VoEfB04OyJeJjXSLpZ0PzALeE3V8b4AvF/pIRf3\nSTqoav0o4H+bxPwT4ClgST7+MVUx/z/SB/8rco7vJs3rIyK6gBuAD+afDetT5xooPaxjZI3ywyQ9\nRRqmeIPWPdZ/O7r3RNXSASyWdB9wJPC9RjEA/w5MyDnYB/hTYV2jnshKnpaR/hAxK5/3LKDWOdU8\nV1Jj+X2SlpOGG55XtX4boC96Wc3MzMysBm3I3+Sd5zsNj4jTm1a2XssPcfhZRDzY37H0JaUnHT4R\nETf0dyzrS35oxpKI+HGDOsGk9ReTmZmtZ5NgQ/78ZzZQSCIieoxQ2tAbWGNIPTkvVn0XlplVkTSH\nNG/w+Ih4pkG9DfeXgpmZNTVihxGsfPoVP3DX7FVvUDawzKzvSQr/Xuh7nZ2dfhJTSZzbcjiv5XBe\ny+PclsN5ra9eA6s33z1lZmZmZmZmNbgHy8y6cQ+WmZmZWXPuwTIzMzMzMyuZG1hmZuuBv0ekPM5t\nOZzXcjiv5XFuy+G8ts8NLDMzMzMzsz7iOVhm1o3nYJmZmZk1V28O1kb9EYyZDWxSj98V9gqNGDGa\nlSsf7+8wzMzMrGQeImhmNYRfffx69tkn2rsE1jLPDyiH81oO57U8zm05nNf2NWxgSRot6YE662ZL\nGldOWI1JGiXpPkk3F8pW9Ecs9UiaIGlaC/UGVNxFrcTWrI6kMyWd1ndRdd+npGmSxjepv7WkmZIW\nS5onadcWjjFb0qgm69u6/yVNlLRU0u35/RWS7pf02XwehzfZvpVzPTaf52JJd0narbDuAkkPSZrQ\nTtxmZmZm1rpWerAG4mSMw4BZEfGhQtlAjLOVmAZi3BUbevwVXwEWRcTuwInA9/spjpOBUyLiAEkj\ngb0iYmxETOnDYzwGjM/nejZwaWVFRHwBOAv45z48nlm/6+jo6O8QBiXntRzOa3mc23I4r+1rpYG1\nsaTp+S/vV0natLqCpGMkLcmv83LZkPwX9yX5r+mfzeVjJN2a/3J/r6SdexH31sBzVWXPF+I5IR9z\nkaTLc9k0SVMkzZX0aKW3QNIWkm7LsSyWdEguHy1pWd5uuaQZkt6Xt18uaa9cb3NJU3PPyEJJB+cw\n/gr8sYVzeT7vZ6SkOblnbomkfXP5akln53zdLel1ufygwjFnFcrPlPTTXHe5pFNy+YS8/xskPSzp\nEiUnSfpuIXenSLqgOqfN4q+X9yJJfy/pZkkLcixvkrSVpMcLdTaX9KSkobXq1zj+KlKuG9kVuAMg\nIpYDO1Xy1cDvgTX17uPsSEn35HxWrteJki4qnM/1ksZL+hqwHzBV0reAW4Ad8vXerypP4yR15vO+\nWdKIVs81IuZFROW+mwfsUFVlJenfj5mZmZmVISLqvoDRQBewT34/FTgtL88GxgHbAU8A25IabLcD\nh+R1swr72ir/nAcckpc3ATZtFEOduCYDn6uzblfgYWCb/H7r/HMacGVefjPwSF4eCmyZl4cXykeT\nPszumt/fC0zNy4cAM/PyOcCxeXkYsBzYrCqmPYFLm5zTacC/5WUBW+TlLuDDefl84CuVYxW2PRn4\ndl4+E1iUczsceBIYCUwA/jefl4BZwOHAFsCjwNC8/VzgLb24JvXyfmbhnrkNGJOX3w7cnpd/CUzI\ny0dWctWg/tp91rgvDqpRfg5wQWE/fwX2aPG86t3Hsws5/xBwa14+Efh+of71pB6lyjZ7FO6vJYV6\n0/L12Chfg+GFfExt9Vyr6nyx+r4D3g3c0GS7gPCrz1+ElWP27Nn9HcKg5LyWw3ktj3NbDue1vvx/\ne4/PUq08RfDJiJiXl6cDnwEuLKzfG5gdEX8AkDQDGE8anrSzpCnATcAsSVsC20fEdaSImvU89CBJ\nwO45llreA1wdES/kY6wqrLsmly2T9PrKLoFzlea2dAHbF9atiIilefkh0gd+gAeAnfLy+4GDJX0p\nv98EGEVqaJGPtxD4eJNTW0Dq3dgYuDYiFufylyLipry8EHhvXt5R0lWkBu7GwIrCvq7Nuf29pDtI\njYo/AvMj4glI83+A/SJiptKcoIMkPQxsFBEPNYm1lkZ5R9IWwLuAq/M1JMcNcBVwFDAHOBr4QZP6\nNUXEmXVWnQdMkXQf6dotAta0eF6PUXUfF9bNzD8XkhpMrWj2eL5dgLcCt+bzHgL8rrpSg3NNB5H2\nB04i9ZoVPQO8SdJrIuKl+nuYVFjuyC8zMzOzV6/Ozs6WHvrRSgMrmryHGh8aI2KVpN2BDwCfBI4A\nPlerbrcdSZ8CPpaP8+GIWFlYN4T0gfcl4MYWYq9W/EBZieM44LWknoUupYc2bFqjflfhfRfrcifg\noxHxSC/iWSsi7syNvAOByyRdEBHTgZcL1dYUjnsR8J2IuFHpoQXFD9zFayRqX7NivamkeUoPk3pS\nyjAEeCEiaj0Y4jrgHEnbkHqM7gC2bFC/LRGxmsK8o3yNH2tx21r38Sl5deV+KF6Xv9F96G2PIbVN\nCHgwIvZtc7t1O0gPtrgU+GClwVsREY9JWgY8IemA+o3pSb09vNl65/kB5XBey+G8lse5LYfzuk5H\nR0e3fEyePLlmvVbmYI2W9I68fCxwZ9X6+cB4SdtKGgocA8yRNJw07OyXwFeBcRHxIvCUpEMBJG0i\nabPiziLikojYIyLGFRtXeV1XROxEGq53VJ147wCOkLRtPsY2depVGljDgOdy42p/uvdEtPJlQLcA\np67dQBrbwjY9g0lPrHsuIqYCPyE1NBrFsBXrejZOrFp3aM7tcNLQwAW5fG+luWVDSPm7CyAi5gM7\nkq7dFXXiW9bkFBrmPTdyVkiaWNjnbnndn0jXdApp+Fo0qt8uScNyzyCSPgbMyfciSvPvtmuwbY/7\nuF7V/PNxYGye37Yjqfew7u5rlC0HXidpn3z8jdTCUw8L8Y4C/gv4x4j4bY31uwE7k3qSe9NTaWZm\nZmYNtNLAehj4tKSlpMnxP8rlabJGagSdDnSShl4tiIjrSZPrOyUtAn6W6wCcAJwqaTFprkllAn87\nfkOa89VDHtJ3DqmRtwioPLChXk/cDFLDYzFwPLCsRp1a21d8g/QgkCVKj7Q/q7qCpD0lXdpz0246\ngMV5GNuRwPeaHHcy8J+SFtDzYRRLSNfjbuCsQkP1XuBi0nDH3+ZGQ8VVwNxY94CEYvzDm8TeKO9F\nxwMnKz2w40HSXLaKK0m9ib8olB3XoH4PkiZLOqjGqjcDD+ZG4geAygNXBIwB/tBgt/Xu45r3U0TM\nJTWyHiJdw4XVdeq8r2z/MjAROF/S/aR/U+9s41y/Rvq3cYnSw0bmV63fBng8IrpqbGu2QfJ3tJTD\neS2H81oe57Yczmv7lOZnbVjyfKfhEXF608qvMpLOBFZHxIVV5ROAL0REzUaKpOuBCyNido11BwI7\nR8TFZcTcXyS9BTgpIr7Y37GsL5KOBD4SEcc0qBP12/XWe2JD/H27Iejs7PQQlhI4r+VwXsvj3JbD\nea1PEhHRY0TShtrAGgNcBrwY3b8L61Wv3QaWpGGkYZ6LIuLo9ReprW9Kj99/N+lplbc3qOcGVinc\nwDIzMxtMBlUDy8zKkxpY1tdGjBjNypWP93cYZmZm1kfqNbBamYNlZq8ytb7Twa9X9vrFLy7r78s6\naHl+QDmc13I4r+VxbsvhvLbPDSwzMzMzM7M+4iGCZtaNpPDvBTMzM7PGPETQzMzMzMysZG5gmZmt\nBx7DXh7nthzOazmc1/I4t+VwXtvnBpaZmZmZmVkf8RwsM+vGc7DMzMzMmqs3B2uj/gjGzAY2qcfv\nChugRuwwgpVPr+zvMMzMzCxzD5aZdSMpmNTfUQxCK4CdS9jvpPS9Za9mnZ2ddHR09HcYg47zWg7n\ntTzObTmc1/p69RRBSaMlPVBn3WxJ4/oqwHZIGiXpPkk3F8pW9Ecs9UiaIGlaC/UGVNxFrcTWrI6k\nMyWd1ndRdd+npGmSxjepv7WkmZIWS5onadcWjjFb0qgm69u6/yVNlLRU0u35/RWS7pf02XwehzfZ\nvum55nrfl/RI3vfYQvkFkh6SNKGduM3MzMysda085GIg/mn0MGBWRHyoUDYQ42wlpoEYd8WGHn/F\nV4BFEbE7cCLw/X6K42TglIg4QNJIYK+IGBsRU/rqAJI+BIyJiDcCnwB+VFkXEV8AzgL+ua+OZ20o\no/fKAPyX1ZI4r+VwXsvj3JbDeW1fKw2sjSVNz395v0rSptUVJB0jaUl+nZfLhuS/uC/JPQefzeVj\nJN2a/7p+r6TefOzYGniuquz5Qjwn5GMuknR5LpsmaYqkuZIerfQWSNpC0m05lsWSDsnloyUty9st\nlzRD0vvy9ssl7ZXrbS5pau4ZWSjp4BzGX4E/tnAuz+f9jJQ0J/fMLZG0by5fLensnK+7Jb0ulx9U\nOOasQvmZkn6a6y6XdEoun5D3f4OkhyVdouQkSd8t5O4USRdU57RZ/PXyXiTp7yXdLGlBjuVNkraS\n9HihzuaSnpQ0tFb9GsdfRcp1I7sCdwBExHJgp0q+Gvg9sKbefZwdKemenM/K9TpR0kWF87le0nhJ\nXwP2A6ZK+hZwC7BDvt77VeVpnKTOfN43SxrRxrkeCvw0n+s9wLDC9gArSf9+zMzMzKwErTSwdgEu\njohdgdXAp4orJW0HnAd0AGOBvXMjZSywQ0TslnsOKsPlZgAXRcRY4F3A/+1F3EOBrmJBRLwjx7Mr\nqceiIyL2AIofiEdGxL7AwcD5uewvwGERsRfwHuCCQv0xwLcjYpech6Pz9l/KxwA4A7g9IvbJ239H\n0mYR8euI+HyOaU9Jl9Y6kUrcwLHAryJiHLA7cH8u3wK4O+frTuBjufzOiNgnIvYErgS+XNjt20jX\n413A15V6SwD2Bj4NvBn4B+AjwFXAwZKG5jonAf9RFVtdLea94lLgXyJib1IOfxgR/wMs0rphawfl\nPKypVb/G8T8fEfNyDJMlHVTjuIuBSoP67cAo4A1NzmtiRDxD/fsYYGg+/89Dt1lLPXr1IuIbwL3A\nsRHxZeAQ4NGIGBcRd1XqSdoIuAj4aD7vacA32zjXHYCnCu+fyWUVXaR/P7a+DdjBwBs+f0dLOZzX\ncjiv5XFuy+G8tq+Vpwg+WflQB0wHPgNcWFi/NzA7Iv4AIGkGMB44G9hZ0hTgJmCWpC2B7SPiOoCI\naPbX+B4kidQAmV6nynuAqyPihXyMVYV11+SyZZJeX9klcK7S3JYuYPvCuhURsTQvPwTclpcfAHbK\ny+8nNVC+lN9vQvoAv7xy0IhYCHy8yaktIPVubAxcGxGLc/lLEXFTXl4IvDcv7yjpKmA7YGO6f3y7\nNuf295LuAN5O6k2bHxFPQJr/A+wXETOV5gQdJOlhYKOIeKhJrLU0yjuStiA1+K7O15AcN6RG3lHA\nHOBo4AdN6tcUEWfWWXUeMEXSfaRrtwhY0+J5PUbVfVxYNzP/XAiMbnF/zR7PtwvwVuDWfN5DgN9V\nV2pwrs08A7xJ0msi4qW6tWYXlnfCw9vMzMzsVa+zs7OlBmcrDazqv8bXmnPT40NjRKyStDvwAeCT\nwBHA52rV7bYj6VOkXpoAPhwRKwvrhpA+8L4E3NhC7NWKHygrcRwHvBbYIyK6lB7asGmN+l2F912s\ny51IvQ2P9CKetSLiztzIOxC4TNIFETEdeLlQbU3huBcB34mIG3PvT/EDd/EaifrzpCrlU0m9Tw/T\nvYemLw0BXsg9dNWuA86RtA0wjjScb8sG9dsSEaspzDvK1/ixFretdR+fkldX7ofidfkb3XuGewyp\nbULAg7mntDeeAXYsvH9DLgMgIh6TtAx4QtIBdRvT+/fy6FafG6ml8fyAcjiv5XBey+PclsN5Xaej\no6NbPiZPnlyzXitDBEdLKg5ju7Nq/XxgvKRt8zCzY4A5koaThlD9EvgqMC4iXgSeknQogKRNJG1W\n3FlEXBIRe+ShUyur1nVFxE6koVZH1Yn3DuAISdvmY2xTp16lgTUMeC43rvane09EK18GdAtw6toN\nCk9ta4fSE+uei4ipwE9IDY1GMWzFup6NE6vWHZpzOxyYQOodgzR8c3RuqB4F3AUQEfNJH8qPAa6o\nE9+yJqfQMO+5kbNC0sTCPnfL6/5EuqZTgBsiqVu/XZKG5Z5BJH0MmJPvRZTm323XYNse93G9qvnn\n48BYJTuSeg/r7r5G2XLgdZL2ycffSC089bDgOuCEvO0+wKqIeLZwPruRPupv38ueSjMzMzNroJUG\n1sPApyUtJU2OrzyVLAByI+h0oJM09GpBRFxPmvfRKWkR8LNcB9KHv1MlLQbmAsUJ+K36DbBtrRV5\nSN85pEbeItbNqarXEzeD1PBYDBwPLKtRp9b2Fd8gPQhkidIj7c+qrtBoDlZBB7A4D2M7Evhek+NO\nBv5T0gJ6PoxiCel63A2cVWio3gtcTBru+NvcaKi4CpgbET0ezJEbGQ01yHvR8cDJSg/seJA0D6ni\nSlJv4i8KZcc1qN9Dg3lJbwYezI3ED5Dnh+UheGOAPzTYbb37uOb9FBFzSY2sh0jXcGF1nTrvK9u/\nDEwEzpd0P+nf1DtbPdc8nHSFpEeBH1M1ZxLYBng8Irqqt7WSeQ5WaTw/oBzOazmc1/I4t+VwXtu3\nQX7RcJ7vNDwiTm9a+VVG0pnA6oi4sKp8AvCFiKjZSJF0PXBhRMyuse5AYOeIuLiMmPuLpLcAJ0XE\nF/s7lvVF0pHARyLimAZ1/EXDZfAXDZfGX4JZDue1HM5reZzbcjiv9anOFw1vqA2sMcBlwItV34X1\nqtduA0vSMNIwz0URcfT6i9TWN6XH778b+LeIuL1BvGGqlgAAIABJREFUPTewNiST3MAyMzPrD4Oq\ngWVm5ZHkXwobkBE7jGDl0yubVzQzM7M+Va+B1cocLDN7lYkIv/r4NXv27FL268aV5weUxXkth/Na\nHue2HM5r+9zAMjMzMzMz6yMeImhm3UgK/14wMzMza8xDBM3MzMzMzErmBpaZ2XrgMezlcW7L4byW\nw3ktj3NbDue1fW5gmZmZmZmZ9RHPwTKzbjwHy8zMzKy5enOwNuqPYMxsYJN6/K4wszpGjBjNypWP\n93cYZmY2QHiIoJnVEH71+Wv2AIhhsL76N7fPPvsEg5HnXZTDeS2Pc1sO57V9DRtYkkZLeqDOutmS\nxpUTVmOSRkm6T9LNhbIV/RFLPZImSJrWQr0BFXdRK7E1qyPpTEmn9V1U3fcpaZqk8S1s831Jj0i6\nX9LYFurPljSqyfq27n9JEyUtlXR7fn9Fjuez+TwOb7J903OVdKykxfl1l6TdCusukPSQpAntxG1m\nZmZmrWtliGCUHkX7DgNmRcTphbKBGGcrMQ3EuCs29PgBkPQhYExEvFHSO4AfAfv0QygnA6dExN2S\nRgJ7RcQbc4xNG+MtegwYHxF/lPRB4FLyuUbEFyTNB/4ZmNNHx7OWdfR3AINYR38HMCh1dHT0dwiD\nkvNaHue2HM5r+1oZIrixpOn5L+9XSdq0uoKkYyQtya/zctmQ/Bf3Jfmv6Z/N5WMk3Zr/cn+vpJ17\nEffWwHNVZc8X4jkhH3ORpMtz2TRJUyTNlfRopbdA0haSbsuxLJZ0SC4fLWlZ3m65pBmS3pe3Xy5p\nr1xvc0lTJc2TtFDSwTmMvwJ/bOFcns/7GSlpTu6ZWyJp31y+WtLZOV93S3pdLj+ocMxZhfIzJf00\n110u6ZRcPiHv/wZJD0u6RMlJkr5byN0pki6ozmmz+OvlvUjS30u6WdKCHMubJG0l6fFCnc0lPSlp\naK36NY6/ipTrRg4FfgoQEfcAwySNaLLN74E19e7j7EhJ9+R8Vq7XiZIuKpzP9ZLGS/oasB8wVdK3\ngFuAHfL13q8qT+MkdebzvrkQa9NzjYh5EVG57+YBO1RVWUn692NmZmZmZYiIui9gNNAF7JPfTwVO\ny8uzgXHAdsATwLakBtvtwCF53azCvrbKP+cBh+TlTYBNG8VQJ67JwOfqrNsVeBjYJr/fOv+cBlyZ\nl98MPJKXhwJb5uXhhfLRpA+zu+b39wJT8/IhwMy8fA5wbF4eBiwHNquKaU/g0ibndBrwb3lZwBZ5\nuQv4cF4+H/hK5ViFbU8Gvp2XzwQW5dwOB54ERgITgP/N5yVgFnA4sAXwKDA0bz8XeEsvrkm9vJ9Z\nuGduI/UkAbwduD0v/xKYkJePrOSqQf21+6xxXxxUo/x64F2F97cB41o8r3r38exCzj8E3JqXTwS+\nX3Xs8YVt9ijcX0sK9abl67FRvgbDC/mY2uq5VtX5YvV9B7wbuKHJdgHhV5+/Zg+AGAbrq79zSwxG\ns2fP7u8QBiXntTzObTmc1/ry73+qX60MEXwyIubl5enAZ4ALC+v3BmZHxB8AJM0AxgNnAztLmgLc\nBMyStCWwfURcR4qoWc9DD5IE7J5jqeU9wNUR8UI+xqrCumty2TJJr6/sEjhXaW5LF7B9Yd2KiFia\nlx8ifTAHeADYKS+/HzhY0pfy+02AUaSGFvl4C4GPNzm1BaTejY2BayNicS5/KSJuyssLgffm5R0l\nXUVq4G4MrCjs69qc299LuoPUOPkjMD8inoA0/wfYLyJmKs0JOkjSw8BGEfFQk1hraZR3JG0BvAu4\nOl9DctwAVwFHkYatHQ38oEn9miLizF7E3cxjVN3HhXUz88+FpAZTK5o9nm8X4K3Arfm8hwC/q67U\n7Fwl7Q+cROo1K3oGeJOk10TES/X3MKmw3IGHYJmZmdmrXWdnZ0sP/ejNHKzq91DjQ2NErJK0O/AB\n4JPAEcDnatXttiPpU8DH8nE+HBErC+uGkD7wvgTc2ELs1YofKCtxHAe8ltSz0KX00IZNa9TvKrzv\nYl3uBHw0Ih7pRTxrRcSduZF3IHCZpAsiYjrwcqHamsJxLwK+ExE3Kj20oPiBu3iNRO1rVqw3FfgK\nqQdq2is5jwaGAC9ERK0HQ1wHnCNpG1KP0R3Alg3qt+sZYMfC+zfksqbq3Men5NWV+6F4Xf5G96G3\nPYbUNiHgwYjYt83t1u0gPdjiUuCDlQZvRUQ8JmkZ8ISkA+o3pif19vBWV0d/BzCIdfR3AIOS512U\nw3ktj3NbDud1nY6Ojm75mDx5cs16rczBGq30YACAY4E7q9bPB8ZL2lbSUOAYYI6k4aRhZ78Evkoa\nkvUi8JSkQwEkbSJps+LOIuKSiNgjIsYVG1d5XVdE7EQarndUnXjvAI6QtG0+xjZ16lUaWMOA53Lj\nan+690S08mVAtwCnrt2ghSfU1QwmPbHuuYiYCvyE1NBoFMNWrOvZOLFq3aE5t8NJQwMX5PK9leaW\nDSHl7y6AiJhPaoAcA1xRJ75lTU6hYd4jYjWwQtLEwj53y+v+RLqmU0jD16JR/V64Djgh72MfYFVE\nPJvf3yZpu3ob1rqP61XNPx8Hxub5bTuSeg/r7r5G2XLgdTlOJG0kadcG+6iOdxTwX8A/RsRva6zf\nDdiZ1JPcm55KMzMzM2uglQbWw8CnJS0lTY7/US4PgNwIOh3oJM39WRAR15Mm13dKWgT8LNeB9EH3\nVEmLSXNNmj1soJbfkOZ89ZCH9J1DauQtAioPbKjXEzeD1PBYDBwPLKtRp9b2Fd8gPQhkidIj7c+q\nriBpT0mXNjgfSH+CXSzpPtK8m+81Oe5k4D8lLaDnwyiWkK7H3cBZhYbqvcDFpOGOv82NhoqrgLmx\n7gEJxfiHN4m9Ud6LjgdOVnpgx4OkuWwVV5J6E39RKDuuQf0eJE2WdFCN2G4iNdYeBX4MfCrXFzAG\n+EOD3da7j2veTxExl9TIeoh0DRdW16nzvrL9y8BE4HxJ95P+Tb2z1XMFvkb6t3GJ0sNG5let3wZ4\nPCK6amxrpers7wAGsc7+DmBQ8nfflMN5LY9zWw7ntX1K87M2LHm+0/Do/ph2Iz1FEFgdERdWlU8A\nvhARNRspkq4HLoyI2TXWHQjsHBEXlxFzf5H0FuCkiPhif8eyvkg6EvhIRBzToE7Ub9db73XioWxl\n6aR/cys2xP9Lm+ns7PTQoBI4r+VxbsvhvNYniYjoMSJpQ21gjQEuA16MiA/1czgDSrsNLEnDSMM8\nF0XE0esvUlvflB6//27S0ypvb1DPDSyztgzOBpaZmTU2qBpYZlYeN7DM2uUGlpnZq1G9BlYrc7DM\n7FVHfvnlV4uvESNa/ZaGDYvnXZTDeS2Pc1sO57V9rTym3cxeZfzX+L7nMezlcW7NzGwg8RBBM+tG\nUvj3gpmZmVljHiJoZmZmZmZWMjewzMzWA49hL49zWw7ntRzOa3mc23I4r+1zA8vMzMzMzKyPeA6W\nmXXjOVhmZmZmzXkOlpmZmZmZWcn8mHYz60Hq8ccYMzMzsw3SiB1GsPLplevteB4iaGbdSAom9XcU\ng9AKYOf+DmKQcm7L4byWw3ktj3NbjsGQ10nlfMdnr4YIShot6YE662ZLGtdXAbZD0ihJ90m6uVC2\noj9iqUfSBEnTWqg3oOIuaiW2ZnUknSnptL6Lqvs+JU2TNL6Fbb4v6RFJ90sa20L92ZJGNVnf1v0v\naaKkpZJuz++vyPF8Np/H4U22f0XnKukCSQ9JmtBO3NZHNvT/nAYy57Yczms5nNfyOLflcF7b1soc\nrIHYxXUYMCsiPlQoG4hxthLTQIy7YkOPHwBJHwLGRMQbgU8AP+qnUE4GTomIAySNBPaKiLERMaWv\nDtDoXCPiC8BZwD/31fHMzMzMrLtWGlgbS5qe//J+laRNqytIOkbSkvw6L5cNyX9xXyJpsaTP5vIx\nkm7Nf12/V1Jv2sVbA89VlT1fiOeEfMxFki7PZdMkTZE0V9Kjld4CSVtIui3HsljSIbl8tKRlebvl\nkmZIel/efrmkvXK9zSVNlTRP0kJJB+cw/gr8sYVzeT7vZ6SkOblnbomkfXP5akln53zdLel1ufyg\nwjFnFcrPlPTTXHe5pFNy+YS8/xskPSzpEiUnSfpuIXenSLqgOqfN4q+X9yJJfy/pZkkLcixvkrSV\npMcLdTaX9KSkobXq1zj+KlKuGzkU+ClARNwDDJM0osk2vwfW1LuPsyMl3ZPzWbleJ0q6qHA+10sa\nL+lrwH7AVEnfAm4BdsjXe7+qPI2T1JnP++ZCrH1xritJ/35sfRuwfdWDgHNbDue1HM5reZzbcjiv\nbWulgbULcHFE7AqsBj5VXClpO+A8oAMYC+ydGyljgR0iYreI2B2oDJebAVwUEWOBdwH/txdxDwW6\nigUR8Y4cz67AV4COiNgDKH4gHhkR+wIHA+fnsr8Ah0XEXsB7gAsK9ccA346IXXIejs7bfykfA+AM\n4PaI2Cdv/x1Jm0XEryPi8zmmPSVdWutEKnEDxwK/iohxwO7A/bl8C+DunK87gY/l8jsjYp+I2BO4\nEvhyYbdvI12PdwFfV+otAdgb+DTwZuAfgI8AVwEHSxqa65wE/EdVbHW1mPeKS4F/iYi9STn8YUT8\nD7BI64atHZTzsKZW/RrH/3xEzMsxTJZ0UI3j7gA8VXj/TC5rdF4TI+IZ6t/HAEPz+X8eus1a6tGr\nFxHfAO4Fjo2ILwOHAI9GxLiIuKtST9JGwEXAR/N5TwO+2Yfn2kX692NmZmZmJWjlKYJPVj7UAdOB\nzwAXFtbvDcyOiD8ASJoBjAfOBnaWNAW4CZglaUtg+4i4DiAimv01vgdJIjVAptep8h7g6oh4IR9j\nVWHdNblsmaTXV3YJnKs0t6UL2L6wbkVELM3LDwG35eUHgJ3y8vtJDZQv5febAKOA5ZWDRsRC4ONN\nTm0BqXdjY+DaiFicy1+KiJvy8kLgvXl5R0lXAdsBG9P97wvX5tz+XtIdwNtJvWnzI+IJSPN/gP0i\nYqbSnKCDJD0MbBQRDzWJtZZGeUfSFqQG39X5GpLjhtTIOwqYAxwN/KBJ/Zoi4sxexN3MY1Tdx4V1\nM/PPhcDoFvfX7PF8uwBvBW7N5z0E+F11pVdwrs8Ab5L0moh4qW6t2YXlnfD4677gHJbHuS2H81oO\n57U8zm05nNe1Ojs76ezsbFqvlQZW9V/ja8256fGhMSJWSdod+ADwSeAI4HO16nbbkfQpUi9NAB+O\niJWFdUNIH3hfAm5sIfZqxQ+UlTiOA14L7BERXUoPbdi0Rv2uwvsu1uVOpN6GR3oRz1oRcWdu5B0I\nXCbpgoiYDrxcqLamcNyLgO9ExI2596f4gbt4jUT9eVKV8qmk3qeH6d5D05eGAC/kHrpq1wHnSNoG\nGAfcAWzZoH67ngF2LLx/Qy5rqs59fEpeXbkfitflb3TvGe4xpLYJAQ/mntLeaHiuEfGYpGXAE5IO\nqNuY3r+XRzczMzMbpDo6Oujo6Fj7fvLkyTXrtTJEcLSk4jC2O6vWzwfGS9o2DzM7BpgjaThpCNUv\nga8C4yLiReApSYcCSNpE0mbFnUXEJRGxRx46tbJqXVdE7EQaanVUnXjvAI6QtG0+xjZ16lUaWMOA\n53Ljan+690S08mVAtwCnrt2ghSfU1QwmPbHuuYiYCvyE1NBoFMNWrOvZOLFq3aE5t8OBCaTeMUjD\nN0fnhupRwF0AETGf9KH8GOCKOvEta3IKDfMeEauBFZImFva5W173J9I1nQLcEEnd+r1wHXBC3sc+\nwKqIeDa/vy0Pc62p1n1cr2r++TgwVsmOpN7DuruvUbYceF2OE0kb5eGXrap7rrlsN9LforbvZU+l\n9ZbHsJfHuS2H81oO57U8zm05nNe2tdLAehj4tKSlpMnxlaeSBUBuBJ0OdAKLgAURcT1p3kenpEXA\nz3IdSB/+TpW0GJgLNHvYQC2/AbattSIP6TuH1MhbxLo5VfV64maQGh6LgeOBZTXq1Nq+4hukB4Es\nUXqk/VnVFRrNwSroABZLug84Evhek+NOBv5T0gJ6PoxiCel63A2cVWio3gtcTBru+NvcaKi4Cpgb\nET0ezJEbGQ01yHvR8cDJSg/seJA0D6niSlJv4i8KZcc1qN9DvXlJeYjlCkmPAj8mzyPMQ/DGAH9o\nsNt693HN+yki5pIaWQ+RruHC6jp13le2fxmYCJwv6X7Sv6l3vtJzLdgGeDwiuqq3NTMzM7NXboP8\nouE832l4RJzetPKrjKQzgdURcWFV+QTgCxFRs5Ei6XrgwoiYXWPdgcDOEXFxGTH3F0lvAU6KiC/2\ndyzri6QjgY9ExDEN6viLhs3MzGzwmDSAvmh4AJsJ7KvCFw1b70gaJmk58KdajSuAiLhxsDWuACLi\noVdZ4+oC4IukIahmZmZmVoINsgfLzMojyb8UzMzMbNAYscMIVj69snnFNtXrwWrlKYJm9irjP7z0\nvc7Ozm5PHrK+49yWw3kth/NaHue2HM5r+9yDZWbdSAr/XjAzMzNrbLDNwTIzMzMzMxtw3MAyM1sP\nWvnmd+sd57Yczms5nNfyOLflcF7b5waWmZmZmZlZH/EcLDPrxnOwzMzMzJrzHCwzMzMzM7OSuYFl\nZj1I6vYa+YaR/R3SBs9j2Mvj3JbDeS2H81oe57Yczmv7/D1YZtbTpO5vn530bL+EYWZmZrah8Rws\n63eSVkfE3/V3HACSxgGXA/Mj4uRctiIidu6HWHYHto+Im/P7E4GdImJyk+1uBvYB7oyIQwrlxwBn\nAj+OiO822D6qG1hM8pcPm5mZmRV5DpYNZAPpk/vxwA8qjausrfgk9dW/q7HAh6vKWonlW6Tz6L5h\nxBXABODzrzw0MzMzM6vFDSwbMCRNlrRI0n2SnpY0VdJoScskTZO0XNIMSe+TNDe/3ytvu7ekuyUt\nlHSXpDf2Moytgeeqyp7Px5ggaY6kGyQ9LOmSQuyrJX1H0iJgH0njJHVKWiDpZkkjcr1TJT0k6X5J\nP89lm+dznZfjP1jSxsBZwJE5H0cA/wu82OwEImJ2vXoR8SwwrO2s2CvmMezlcW7L4byWw3ktj3Nb\nDue1fZ6DZQNGRJwJnClpGPDfwEV51RjgoxGxVNK9wNERsa+kQ4AzgI8Ay4D9IqJL0gHAucDEXoQx\nFOiqiusdhbd7A28GngRukXR4RMwEtgB+HRFflLQRMAc4JCJ+L+lI4JvAycC/kob5vSxpq7zPM4Db\nI+LkfO7zgduArwN7RsSp1UFKOjivm9SLc/QfVszMzMxK4gaWDUTTgQsi4n5Jo4EVEbE0r3uI1PgA\neAAYnZe3Bn6ae66CXtzbuWH0FtY17GqZHxFP5PpXAPsBM4E1+SfALsBbgVslidSg+V1etxj4uaRr\ngGty2fuBgyV9Kb/fBBjVKNaIuB64vvWz6+YPksZExG/r1phdWN6pl0exbjo6Ovo7hEHLuS2H81oO\n57U8zm05nNd1Ojs7W+rRcwPLBhRJk4AnI+KnheKXCstdhfddrLuHvwHcERGH50ZZsYlQ2ffZwIFA\nRMS4qnVvIPUcPRoR9zYIsXoOVOX9nwvfzivgwYjYt8b2BwLjgUOAMyS9Ldf/aEQ8UhXTPg3ieCWm\nAPdL+kxEXFazxv4lHdnMzMxsA9XR0dGtwTl5cu3njnmokA0EgrXD3t4LfLbW+iaGAc/k5ZNqVYiI\nr0bEHtWNq7zuaWCHFIY6Ghzn7Xle2BDgKODOGjEuB15XaSBJ2kjSrnndqIiYA5wObEUaWngLsHYY\noKSxeXF1rtMbon7evgL8Q93GlZXCY9jL49yWw3kth/NaHue2HM5r+9zAsoGg0vPzeWB7YEF+sMOk\nqvXVy0XfAs6TtJBe3te5B+pRYNsG1e4FLiYNVfxtRFSG+a2NKyJeJs3/Ol/S/cAi4J15COJ0SYuB\nhcCUiPgfUu/bxpKWSHqA9HALSL1wuxYecrFWfhDGpFoBSvpv4ErgPZKelPS+qiqb5IddmJmZmVkf\n8/dgmRVI+gHwQET8qMa6CcAXit8ttaGR9HpgcURs16COvwfLzMzMrAl/D5ZZa34KnCRpan8H0tfy\nFw3PIvX2mZmZmVkJ3MAyK4iIeyLiHVVfNFxZN2dD7r2KiCsiYmxEfLdp5UndXyN2GFFmaK8KHsNe\nHue2HM5rOZzX8ji35XBe2+enCJpZDx4OaGZmZtY7noNlZt1ICv9eMDMzM2vMc7DMzMzMzMxK5gaW\nmdl64DHs5XFuy+G8lsN5LY9zWw7ntX1uYJmZmZmZmfURz8Eys248B8vMzMysOc/BMjMzMzMzK5kb\nWGbWg6Rur5FvGNnfIW3wPIa9PM5tOZzXcjiv5XFuy+G8ts/fg2VmPU3q/vbZSc/2SxhmZmZmGxrP\nwTLrJ5JGAzdExNtarP8t4GDgJeD/t3fnQZaV9RnHvw8gIgjExDiYGVmMIooiM+CgAWJjAi4ERIyC\nQRHUbEyEimK5JTBdRaKE0kgBEhcyIehIobggZRREhgQVWYZNFiWyCMYZF1DAKBH45Y97Gk/3dPfM\n7XvP9CzfT1VXn/Oec+5971M9XfPr933P+R5wdFXd38f7PQtYAiwA3lNVH5zivJpYYLHYhw9LkiS1\nuQZLWjf1U7VcBOxaVbsDtwHv7vO9fgq8FTilz+skSZK0hiywpNn1uCSfSHJzkvOSbJFkjyTXJlme\n5IYkjwBU1Ver6tHmuiuAef28UVX9pKquAR4e8mfQGnAOe3fMthvm2g1z7Y7ZdsNc+2eBJc2uZwGn\nV9VzgAeAY6rqmqqaX1ULgC8z+YjTm4D/WIv9lCRJ0hpwDZY0S5o1WJdV1Y7N/n7AW6vq0Gb/MOAt\nwAHtB1MleS+woKpePcP3PRF4YNo1WC9uNewInO0aLEmStHFbtmzZuBG90dHRSddgeRdBaXZNrFoK\nIMlzgROAfScUV0cBrwBeMtmLJTkJOBCoZgRsZvab8ZWSJEkbpJGREUZGRh7bHx0dnfQ8pwhKs2uH\nJHs1238GXJ5kW2ApcGRV3Tt2YpKXAe8ADq6qhyZ7sar6u9b0wums8tcWdcs57N0x226YazfMtTtm\n2w1z7Z8jWNLsuhVYlGQJ8G3gTOC1wPbAx5KE34xGnQZsDlzca+aKqjpmTd8oyRzgamBr4NEkxwHP\nqaoHh/mBJEmSNmauwZI0js/BkiRJWj2fgyVJkiRJHbPAkrSqxeO/5sydM4ud2TA4h707ZtsNc+2G\nuXbHbLthrv1zDZakVTgdUJIkaWZcgyVpnCTl7wVJkqTpuQZLkiRJkjpmgSVJa4Fz2Ltjtt0w126Y\na3fMthvm2j8LLEmSJEkaEtdgSRrHNViSJEmr5xosSZIkSeqYBZakVSQZ6Gu7edvN9kdY5ziHvTtm\n2w1z7Ya5dsdsu2Gu/fM5WJJWtXiwy1cuXjmUbkiSJK1vXIMlrWOS3AHsUVX3Jrm8qvZJ8mLg+Ko6\naIDXPQv4E2BlVe02zXk1aIHFYh9WLEmSNmyuwZLWH49VJlW1z2TtM7QEeOmAryFJkqRpWGBJsyTJ\nXya5NsnyJLcnuWTsUOucB1qXbJvkwiS3Jvlwv+9XVZcD9w3Ybc2Qc9i7Y7bdMNdumGt3zLYb5to/\nCyxpllTVR6pqPrAQuBv4wGSntbZfACwCng08I8mh3fdSkiRJ/XANljTLmtGolVU12uy312DdX1Xb\nNGuwRqtqpDnnaOB5VfW2Pt9rB+CLq12D9eJWw47ATn19JNdgSZKkDc6yZcvGjeiNjo5OugbLuwhK\nsyjJUcDTquqYNTh9YsUybj/JQuAjTfsJVXXhjDu234yvlCRJ2iCNjIwwMjLy2P7o6Oik5zlFUJol\nSfYA3g68frrTWtt7JdkhySbAYcDl7ROr6sqqml9VC6YprjLhNbWWOIe9O2bbDXPthrl2x2y7Ya79\ns8CSZs8i4EnApc2NLj7atLdHptrbVwKnAzcB36uqz/XzZkmWAt8Adk7y/WaaoSRJkobINViSxvE5\nWJIkSavnc7AkSZIkqWMWWJK0FjiHvTtm2w1z7Ya5dsdsu2Gu/fMugpJWtXiwy+fMnTOUbkiSJK1v\nXIMlaZwk5e8FSZKk6bkGS5IkSZI6ZoElSWuBc9i7Y7bdMNdumGt3zLYb5to/CyxJkiRJGhLXYEka\nxzVYkiRJq+caLEmSJEnqmAWWJK0FzmHvjtl2w1y7Ya7dMdtumGv/fA6WpFUkq4x2S5IkbTTmzJ3D\nintWzOha12BJGidJDfqgYUmSpPXaYlhdneQaLGkNJHk0ySmt/bcnOWGW+rJD059FrbbTkhw5G/2R\nJEnS6llgSeM9BBya5LdnuyONHwHHJXE67/rujtnuwAbMbLthrt0w1+6YbTfMtW8WWNJ4DwMfBd42\n8UAzonRJkuuSXJxkXtO+JMmpSb6e5L+THNq65vgkVzbXnDiD/vwYuAQ4apL+7J7km81rn59k26b9\n0iTvT/KtJLcm2btp3yTJPzXt1yX58xn0R5IkSdOwwJLGK+AM4IgkW084dhqwpKp2B5Y2+2O2q6q9\ngYOAkwGS7A88s6oWAvOBPZPsM4P+nAwcn1XvPHE28I6mP98G2gXcplW1F/C38NiKqjcDP2vaFwJ/\nkWSHPvujmdpptjuwATPbbphrN8y1O2bbDXPtm9OOpAmq6sEkZwPHAb9sHXoR8Kpm+xyaQqrx+eba\nW5I8pWk7ANg/yXIgwFbAM4HL++zPnUmuAI4Ya0uyDbBtVY291tnAea3LPtt8vwYYK6IOAJ6X5DXN\n/jZNf+5a5U0vbW3viL9cJUnSRm/ZsmVrdNt6CyxpcqcCy4ElrbbpbiXzUGs7re/vq6qPTXVRkkPo\njTwV8JaqWj7Fqe8DPgMsm+R9puvPI/zm33mAt1bVxdNc17Pfas9Qv+7AQrUrZtsNc+2GuXbHbLth\nro8ZGRlhZGTksf3R0dFJz3OKoDReAKrqPnojQm9uHfsG8Lpm+/XAf033GsBXgDcl2Qogye8l+d32\niVX1+aqaX1ULpiiuxvrzHeBm4OBm/37g3rF0qtlUAAAIw0lEQVT1VcAbgMvWoD/HjN0wI8kzkzxh\nimskSZI0A45gSeO1R6k+ACxqtR0LLElyPL2bTxw9yTWP7VfVxUl2Ab7ZLJ96gF5h9uMZ9ucf6I2q\njTkK+JemSLp9df0BPk5vwt/yZj3Xj4BD+uiLBuFf/7pjtt0w126Ya3fMthvm2jcfNCxpHB80LEmS\nNnqLfdCwJK3bfI5Id8y2G+baDXPtjtl2w1z75giWpHGS+EtBkiRt1ObMncOKe1ZMe44jWJLWWFX5\nNeSvE088cdb7sKF+ma25rk9f5mq269vXxprr6oqr6VhgSZIkSdKQWGBJ0lpw5513znYXNlhm2w1z\n7Ya5dsdsu2Gu/XMNlqRxXIMlSZK0ZmqSNVgWWJIkSZI0JE4RlCRJkqQhscCSJEmSpCGxwJIkSZKk\nIbHAkgRAkpcluTXJd5O8c7b7s65LclaSlUluaLU9KclFSb6T5CtJtm0de3eS25LckuSAVvuCJDc0\nuX9obX+OdVGSeUm+luSmJDcmObZpN98BJHl8km8lubbJ9h+bdnMdgiSbJFme5IJm31yHIMmdSa5v\nfm6vbNrMdkBJtk3y6Sanm5LsZa7DY4EliSSbAKcDLwV2BV6XZJfZ7dU6bwm9vNreBXy1qp4FfA14\nN0CS5wCvBZ4NvBz4cJKxuw6dCby5qnYGdk4y8TU3Rg8Db6uqXYEXAYuan0fzHUBVPQTsV1Xzgd2A\nlyTZG3MdluOAm1v75jocjwIjVTW/qhY2bWY7uFOBL1XVs4HnA7dirkNjgSUJYCFwW1XdVVW/Bs4F\nXjnLfVqnVdXlwH0Tml8JnN1snw0c0mwfDJxbVQ9X1Z3AbcDCJNsBW1fVVc15/966ZqNVVSuq6rpm\n+0HgFmAe5juwqvrfZvPx9P4PcB/mOrAk84BXAB9vNZvrcIRV/79qtgNIsg2wb1UtAWjy+jnmOjQW\nWJIA5gJ3t/bvadrUn6dU1UroFQnAU5r2ifn+oGmbSy/rMeY+QZIdgd2BK4A55juYZhrbtcAKYFlV\n3Yy5DsM/A+8A2s++MdfhKODiJFcleUvTZraD2Qn4SZIlzbTWjybZEnMdGgssSeqODxocQJInAp8B\njmtGsibmab59qqpHmymC84B9k4xgrgNJciCwshl1XeWBoy3mOjN7V9UCeiOEi5Lsiz+zg9oMWACc\n0WT7C3rTA811SCywJEHvr1Hbt/bnNW3qz8okcwCaqRM/atp/ADytdd5YvlO1b/SSbEavuDqnqr7Q\nNJvvkFTV/cCXgD0x10HtDRyc5HbgU/TWtp0DrDDXwVXVD5vvPwY+T29Kuz+zg7kHuLuqrm72z6dX\ncJnrkFhgSQK4CnhGkh2SbA4cDlwwy31aH4Txf7G+ADiq2X4j8IVW++FJNk+yE/AM4MpmCsbPkyxs\nFgwf2bpmY/evwM1VdWqrzXwHkOTJY3cFS/IEYH/gWsx1IFX1nqravqqeTu9359eq6g3AFzHXgSTZ\nshnJJslWwAHAjfgzO5BmGuDdSXZumv4IuAlzHZrNZrsDkmZfVT2S5G+Ai+j94eWsqrpllru1Tkuy\nFBgBfifJ94ETgfcDn07yJuAuenddoqpuTnIevTuM/Ro4pqrGpl4sAv4N2ILeHZ2+vDY/x7qoubPd\nEcCNzXqhAt4DnAycZ74z9lTg7OY/QpvQGx28pMnYXIfv/ZjroOYAn0tS9P7P+smquijJ1ZjtoI4F\nPpnkccDtwNHAppjrUOQ3+UiSJEmSBuEUQUmSJEkaEgssSZIkSRoSCyxJkiRJGhILLEmSJEkaEgss\nSZIkSRoSCyxJkiRJGhILLEmStE5JcmmSBVMcOzfJ05vtO5NcNuH4dUluaLbfmOS0ad7nzCQvmuLY\nwUn+fuafQtLGygJLkiStF5L8PrBVVd3eNBWwdZK5zfFdmra26R74uRdwxRTHvgi8OslmA3RZ0kbI\nAkuSJE0ryZZJLkxybZIbkrymab8jyclN2xWtkaUnJ/lMkm81X3/Qep2zmnOvSXJw075Fkk8luSnJ\nZ4EtpujK4fQKn7bzmnaA1wFLJxzfvhkR+06SE1qfaRfgu1VVSY5t3vu6JEsBqqqAbwAHzDA2SRsp\nCyxJkrQ6LwN+UFXzq2o34MutY/c1bWcApzZtpwIfrKq9gD8FPt60vxe4pKpeCLwEOCXJE4C/Bn5R\nVbsCJwJ7TtGPfYCrW/sFnA+8qtk/iFULsBc0x58PvKY19fDlrc/xTmD3qtod+KvWtVcBfzhFXyRp\nUhZYkiRpdW4E9k/yviT7VNUDrWPnNt8/Bbyw2f5j4PQk1wIXAE9MsiW90aB3Ne3LgM2B7ekVMZ8A\nqKobgeun6McOwA8ntP0UuC/JYcDNwC8nHL+4qn5WVb8CPkuvSAN4Kb8psK4HliY5Anikde3/ADtO\n0RdJmpTziiVJ0rSq6rZm5OcVwElJvlpVJ40dbp/afN8E2Kuqft1+nSQAr66q2yZpH9c0VVemOHYe\nvRG0I6e4Ztx+M2q2bVWtaNoOpFfkHQy8N8lzq+rR5r2mW8MlSatwBEuSJE0ryVOBX1bVUuAUoH2H\nv8Oa74cD32y2vwIc17r++a32Y1vtuzeb/wkc0bQ9F9htiq7cBWzX7lrz/XPAycBFk1yzf5Lfaoqq\nQ4CvA/sBlzbvF2D7qroMeBewDfDE5tqnNu8pSWvMESxJkrQ6z6O3XupR4P8Yv07pSUmuB35F7yYT\n0CuuzmjaN6VXQB0DnAR8qLmNeoA76I0anQksSXITcAvj11m1XU5vfdbyZr8AqupBeoXfZKNhV9Kb\nGjgXOKeqlje3bv90c3xT4BNJtmn6dGpV3d8cWwhcuNp0JKklvZvkSJIk9SfJHcAeVXXvWnq/pwOn\nVdWBA77O1fSmMD4yzTmhV8i9oKoeHuT9JG1cnCIoSZJmaq3+lbZ5/tX9Y7eDH+B19pyuuGocBJxv\ncSWpX45gSZIkSdKQOIIlSZIkSUNigSVJkiRJQ2KBJUmSJElDYoElSZIkSUNigSVJkiRJQ/L/uDxL\nkuJrs2cAAAAASUVORK5CYII=\n", - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "co_t, de_t = compression_decompression_times()\n", - "\n", - "fig = plt.figure(figsize=(12, len(compression_configs)*.3))\n", - "fig.suptitle('Compression speed', fontsize=14, y=1.01)\n", - "\n", - "\n", - "ax = fig.add_subplot(1, 1, 1)\n", - "\n", - "y = [i for i, (c, o) in enumerate(compression_configs) if c == 'blosc' and o['shuffle'] == 2]\n", - "x = (nbytes / 1000000) / np.array([co_t[i] for i in y])\n", - "ax.barh(bottom=np.array(y)+.2, width=x.max(axis=1), height=.6, label='bit shuffle', color='b')\n", - "\n", - "y = [i for i, (c, o) in enumerate(compression_configs) if c != 'blosc' or o['shuffle'] == 0]\n", - "x = (nbytes / 1000000) / np.array([co_t[i] for i in y])\n", - "ax.barh(bottom=np.array(y)+.2, width=x.max(axis=1), height=.6, label='no shuffle', color='g')\n", - "\n", - "ax.set_yticks(np.arange(len(labels))+.5)\n", - "ax.set_yticklabels(labels, rotation=0)\n", - "\n", - "xlim = (0, np.max((nbytes / 1000000) / np.array(co_t)) + 100)\n", - "ax.set_xlim(*xlim)\n", - "ax.set_ylim(0, len(co_t))\n", - "ax.set_xlabel('speed (Mb/s)')\n", - "ax.grid(axis='x')\n", - "ax.legend(loc='upper right')\n", - "\n", - "fig.tight_layout();" - ] - }, - { - "cell_type": "code", - "execution_count": 60, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "image/png": "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\nX77cRo8ebc2aNbOmTZva7rvvbr/97W/ta1/7mjVu3Nh23313u+CCC2zVqlXWqFEj27p1q5mZbd68\n2UaOHGkdO3a0Ll262A033GAVFRXVap/E9ir3UvU9gtUQTQL6KvFDw64yM3vSzH5d7Dhqm5ktNrOr\nix1HfZE0Hrga+H0Buf0VX+3bd8t/uhqAUltb4AJvt9Lk7VaavN1q7o9//CPTp09n+fLlLFu2jFtu\n2f6ToqlRo4cffpiuXbsydepUPv74Y66+uuot1vjx49lnn31Yv349H3zwAePGjauU/vjjj/PMM8+w\ncuVKFi5cyIMPPlilnvTPY8aM4brrrmP48OF8/PHHXHzxxUybNo1OnTrx8ccf88ADD1SJ4/zzz6dZ\ns2asWLGC+fPnM336dH7/+wJujwpU308RbHAsrFP5VrHjcK6uWfih4ULz1mUozjnnnCshP/nJT+jU\nqRMA119/PZdddhk33VRlJQuQ+x6iadOmvPfee6xcuZKePXvSt2/fSumjRo2iffuw4ue0005jwYLs\nD8Ku6b3K+++/z7Rp09i8eTO77bYbzZs35/LLL+f+++/noosuqlGZ6XwEyznndgK+tqA0ebuVJm+3\n0uTtVnNdunTZ9r5bt27bHhxRXT/96U/p2bMnJ510Et/4xje44447KqWnOlcALVq04NNPP61ZwDm8\n/fbb/Otf/6Jjx460a9eOtm3bcskll/DRRx/VWh27/AiWc84555xzLrt33nln2/vVq1dvG81Kl+9J\nfS1btuTOO+/kzjvvZMmSJRx33HEceeSRHHfccXn3+/zzz7d9XrduXY2fCrjPPvvQvHlz1q9fX2dP\nFvQRLOec2wn42oLS5O1WmrzdSpO3W83dc889rF27lg0bNjBu3DiGDx+eMV+HDh1YsWJF1nKefPJJ\nli8PvyKz++6706RJExo3bpy3/t69e7N48WIWLVrEli1bsv7Aby6pKYUdOnTgpJNO4oorruCTTz7B\nzFixYgXPPfdctcvMxjtYzjnnnHPONTDhIUvFf4iTJM4+++xt0/r2228/rr/++ox5r732Wm6++Wba\ntWvHXXfdVSX9zTff5IQTTmD33Xenb9++/PjHP6Z///7b6slmv/3242c/+xmDBg1i//3351vfqv7j\nE5LlP/zww3z55ZccdNBBtGvXjjPOOIN169bl2LuadflidudckiTzfxecc865+iPJHzDVgGVrn7i9\n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\nSZI0T/4f8YECY6U7o3gAAAAASUVORK5CYII=\n", - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "co_t, de_t = compression_decompression_times()\n", - "\n", - "fig = plt.figure(figsize=(12, len(compression_configs)*.3))\n", - "fig.suptitle('Decompression speed', fontsize=14, y=1.01)\n", - "\n", - "\n", - "ax = fig.add_subplot(1, 1, 1)\n", - "\n", - "y = [i for i, (c, o) in enumerate(compression_configs) if c == 'blosc' and o['shuffle'] == 2]\n", - "x = (nbytes / 1000000) / np.array([de_t[i] for i in y])\n", - "ax.barh(bottom=np.array(y)+.2, width=x.max(axis=1), height=.6, label='bit shuffle', color='b')\n", - "\n", - "y = [i for i, (c, o) in enumerate(compression_configs) if c != 'blosc' or o['shuffle'] == 0]\n", - "x = (nbytes / 1000000) / np.array([de_t[i] for i in y])\n", - "ax.barh(bottom=np.array(y)+.2, width=x.max(axis=1), height=.6, label='no shuffle', color='g')\n", - "\n", - "ax.set_yticks(np.arange(len(labels))+.5)\n", - "ax.set_yticklabels(labels, rotation=0)\n", - "\n", - "xlim = (0, np.max((nbytes / 1000000) / np.array(de_t)) + 100)\n", - "ax.set_xlim(*xlim)\n", - "ax.set_ylim(0, len(de_t))\n", - "ax.set_xlabel('speed (Mb/s)')\n", - "ax.grid(axis='x')\n", - "ax.legend(loc='upper right')\n", - "\n", - "fig.tight_layout();" - ] - }, - { - "cell_type": "code", - "execution_count": 61, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "import cpuinfo" - ] - }, - { - "cell_type": "code", - "execution_count": 63, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Vendor ID: GenuineIntel\n", - "Hardware Raw: \n", - "Brand: Intel(R) Xeon(R) CPU E3-1505M v5 @ 2.80GHz\n", - "Hz Advertised: 2.8000 GHz\n", - "Hz Actual: 1.1000 GHz\n", - "Hz Advertised Raw: (2800000000, 0)\n", - "Hz Actual Raw: (1100000000, 0)\n", - "Arch: X86_64\n", - "Bits: 64\n", - "Count: 8\n", - "Raw Arch String: x86_64\n", - "L2 Cache Size: 8192 KB\n", - "L2 Cache Line Size: 0\n", - "L2 Cache Associativity: 0\n", - "Stepping: 3\n", - "Model: 94\n", - "Family: 6\n", - "Processor Type: 0\n", - "Extended Model: 0\n", - "Extended Family: 0\n", - "Flags: 3dnowprefetch, abm, acpi, adx, aes, aperfmperf, apic, arat, arch_perfmon, avx, avx2, bmi1, bmi2, bts, clflush, clflushopt, cmov, constant_tsc, cx16, cx8, de, ds_cpl, dtes64, dtherm, dts, eagerfpu, epb, ept, erms, est, f16c, flexpriority, fma, fpu, fsgsbase, fxsr, hle, ht, hwp, hwp_act_window, hwp_epp, hwp_noitfy, ida, invpcid, lahf_lm, lm, mca, mce, mmx, monitor, movbe, mpx, msr, mtrr, nonstop_tsc, nopl, nx, pae, pat, pbe, pcid, pclmulqdq, pdcm, pdpe1gb, pebs, pge, pln, pni, popcnt, pse, pse36, pts, rdrand, rdseed, rdtscp, rep_good, rtm, sep, smap, smep, smx, ss, sse, sse2, sse4_1, sse4_2, ssse3, syscall, tm, tm2, tpr_shadow, tsc, tsc_adjust, tsc_deadline_timer, vme, vmx, vnmi, vpid, x2apic, xgetbv1, xsave, xsavec, xsaveopt, xtopology, xtpr\n" - ] - } - ], - "source": [ - "cpuinfo.main()" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.5.2" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} diff --git a/notebooks/object_arrays.ipynb b/notebooks/object_arrays.ipynb deleted file mode 100644 index 714d024907..0000000000 --- a/notebooks/object_arrays.ipynb +++ /dev/null @@ -1,350 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Object arrays\n", - "\n", - "See [#212](https://github.com/alimanfoo/zarr/pull/212) for more information." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'2.2.0a2.dev82+dirty'" - ] - }, - "execution_count": 2, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import zarr\n", - "zarr.__version__" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'0.5.0'" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import numcodecs\n", - "numcodecs.__version__" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## API changes in Zarr version 2.2" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Creation of an object array requires providing new ``object_codec`` argument:" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "z = zarr.empty(10, chunks=5, dtype=object, object_codec=numcodecs.MsgPack())\n", - "z" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To maintain backwards compatibility with previously-created data, the object codec is treated as a filter and inserted as the first filter in the chain:" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
Typezarr.core.Array
Data typeobject
Shape(10,)
Chunk shape(5,)
OrderC
Read-onlyFalse
Filter [0]MsgPack(encoding='utf-8')
CompressorBlosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store typebuiltins.dict
No. bytes80
No. bytes stored396
Storage ratio0.2
Chunks initialized0/2
" - ], - "text/plain": [ - "Type : zarr.core.Array\n", - "Data type : object\n", - "Shape : (10,)\n", - "Chunk shape : (5,)\n", - "Order : C\n", - "Read-only : False\n", - "Filter [0] : MsgPack(encoding='utf-8')\n", - "Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)\n", - "Store type : builtins.dict\n", - "No. bytes : 80\n", - "No. bytes stored : 396\n", - "Storage ratio : 0.2\n", - "Chunks initialized : 0/2" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "z.info" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array(['foo', 'bar', 1, list([2, 4, 6, 'baz']), {'a': 'b', 'c': 'd'}, None,\n", - " None, None, None, None], dtype=object)" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "z[0] = 'foo'\n", - "z[1] = b'bar' # msgpack doesn't support bytes objects correctly\n", - "z[2] = 1\n", - "z[3] = [2, 4, 6, 'baz']\n", - "z[4] = {'a': 'b', 'c': 'd'}\n", - "a = z[:]\n", - "a" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If no ``object_codec`` is provided, a ``ValueError`` is raised:" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [ - { - "ename": "ValueError", - "evalue": "missing object_codec for object array", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mz\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mzarr\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mempty\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m10\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchunks\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdtype\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mobject\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/creation.py\u001b[0m in \u001b[0;36mempty\u001b[0;34m(shape, **kwargs)\u001b[0m\n\u001b[1;32m 204\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 205\u001b[0m \"\"\"\n\u001b[0;32m--> 206\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mcreate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mshape\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mshape\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfill_value\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 207\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 208\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/creation.py\u001b[0m in \u001b[0;36mcreate\u001b[0;34m(shape, chunks, dtype, compressor, fill_value, order, store, synchronizer, overwrite, path, chunk_store, filters, cache_metadata, read_only, object_codec, **kwargs)\u001b[0m\n\u001b[1;32m 112\u001b[0m init_array(store, shape=shape, chunks=chunks, dtype=dtype, compressor=compressor,\n\u001b[1;32m 113\u001b[0m \u001b[0mfill_value\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfill_value\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0morder\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0morder\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0moverwrite\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0moverwrite\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpath\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mpath\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 114\u001b[0;31m chunk_store=chunk_store, filters=filters, object_codec=object_codec)\n\u001b[0m\u001b[1;32m 115\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 116\u001b[0m \u001b[0;31m# instantiate array\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/storage.py\u001b[0m in \u001b[0;36minit_array\u001b[0;34m(store, shape, chunks, dtype, compressor, fill_value, order, overwrite, path, chunk_store, filters, object_codec)\u001b[0m\n\u001b[1;32m 289\u001b[0m \u001b[0morder\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0morder\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0moverwrite\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0moverwrite\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpath\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mpath\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 290\u001b[0m \u001b[0mchunk_store\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mchunk_store\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfilters\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfilters\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 291\u001b[0;31m object_codec=object_codec)\n\u001b[0m\u001b[1;32m 292\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 293\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/storage.py\u001b[0m in \u001b[0;36m_init_array_metadata\u001b[0;34m(store, shape, chunks, dtype, compressor, fill_value, order, overwrite, path, chunk_store, filters, object_codec)\u001b[0m\n\u001b[1;32m 346\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mfilters\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 347\u001b[0m \u001b[0;31m# there are no filters so we can be sure there is no object codec\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 348\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'missing object_codec for object array'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 349\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 350\u001b[0m \u001b[0;31m# one of the filters may be an object codec, issue a warning rather\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mValueError\u001b[0m: missing object_codec for object array" - ] - } - ], - "source": [ - "z = zarr.empty(10, chunks=5, dtype=object)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For API backward-compatibility, if object codec is provided via filters, issue a warning but don't raise an error." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/home/aliman/src/github/alimanfoo/zarr/zarr/storage.py:353: FutureWarning: missing object_codec for object array; this will raise a ValueError in version 3.0\n", - " 'ValueError in version 3.0', FutureWarning)\n" - ] - } - ], - "source": [ - "z = zarr.empty(10, chunks=5, dtype=object, filters=[numcodecs.MsgPack()])" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If a user tries to subvert the system and create an object array with no object codec, a runtime check is added to ensure no object arrays are passed down to the compressor (which could lead to nasty errors and/or segfaults):" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "z = zarr.empty(10, chunks=5, dtype=object, object_codec=numcodecs.MsgPack())\n", - "z._filters = None # try to live dangerously, manually wipe filters" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [ - { - "ename": "RuntimeError", - "evalue": "cannot write object array without object codec", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mRuntimeError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mz\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'foo'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36m__setitem__\u001b[0;34m(self, selection, value)\u001b[0m\n\u001b[1;32m 1094\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1095\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mselection\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mpop_fields\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mselection\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1096\u001b[0;31m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mset_basic_selection\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mselection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvalue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfields\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1097\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1098\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mset_basic_selection\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mselection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvalue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36mset_basic_selection\u001b[0;34m(self, selection, value, fields)\u001b[0m\n\u001b[1;32m 1189\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_set_basic_selection_zd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mselection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvalue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfields\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1190\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1191\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_set_basic_selection_nd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mselection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvalue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfields\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1192\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1193\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mset_orthogonal_selection\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mselection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvalue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36m_set_basic_selection_nd\u001b[0;34m(self, selection, value, fields)\u001b[0m\n\u001b[1;32m 1480\u001b[0m \u001b[0mindexer\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mBasicIndexer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mselection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1481\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1482\u001b[0;31m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_set_selection\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mindexer\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvalue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfields\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1483\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1484\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m_set_selection\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mindexer\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvalue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36m_set_selection\u001b[0;34m(self, indexer, value, fields)\u001b[0m\n\u001b[1;32m 1528\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1529\u001b[0m \u001b[0;31m# put data\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1530\u001b[0;31m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_chunk_setitem\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mchunk_coords\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchunk_selection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchunk_value\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfields\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1531\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1532\u001b[0m def _chunk_getitem(self, chunk_coords, chunk_selection, out, out_selection,\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36m_chunk_setitem\u001b[0;34m(self, chunk_coords, chunk_selection, value, fields)\u001b[0m\n\u001b[1;32m 1633\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0mlock\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1634\u001b[0m self._chunk_setitem_nosync(chunk_coords, chunk_selection, value,\n\u001b[0;32m-> 1635\u001b[0;31m fields=fields)\n\u001b[0m\u001b[1;32m 1636\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1637\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m_chunk_setitem_nosync\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchunk_coords\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchunk_selection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvalue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36m_chunk_setitem_nosync\u001b[0;34m(self, chunk_coords, chunk_selection, value, fields)\u001b[0m\n\u001b[1;32m 1707\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1708\u001b[0m \u001b[0;31m# encode chunk\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1709\u001b[0;31m \u001b[0mcdata\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_encode_chunk\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mchunk\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1710\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1711\u001b[0m \u001b[0;31m# store\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36m_encode_chunk\u001b[0;34m(self, chunk)\u001b[0m\n\u001b[1;32m 1753\u001b[0m \u001b[0;31m# check object encoding\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1754\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0misinstance\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mchunk\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mndarray\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mand\u001b[0m \u001b[0mchunk\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdtype\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0mobject\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1755\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mRuntimeError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'cannot write object array without object codec'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1756\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1757\u001b[0m \u001b[0;31m# compress\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mRuntimeError\u001b[0m: cannot write object array without object codec" - ] - } - ], - "source": [ - "z[0] = 'foo'" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here is another way to subvert the system, wiping filters **after** storing some data. To cover this case a runtime check is added to ensure no object arrays are handled inappropriately during decoding (which could lead to nasty errors and/or segfaults)." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array(['Β‘Hola mundo!', 'Hej VΓ€rlden!', 'Servus Woid!', 'Hei maailma!',\n", - " 'Xin chΓ o thαΊΏ giα»›i', 'Njatjeta BotΓ«!', 'ΓΡια σου ΞΊΟŒΟƒΞΌΞ΅!', 'γ“γ‚“γ«γ‘γ―δΈ–η•Œ',\n", - " 'δΈ–η•ŒοΌŒδ½ ε₯½οΌ', 'HellΓ³, vilΓ‘g!', 'Zdravo svete!', 'ΰΉ€ΰΈΰΈ₯ΰΉ‚ΰΈ₯ΰΉ€ΰΈ§ΰΈ΄ΰΈ₯ΰΈ”ΰΉŒ'], dtype=object)" - ] - }, - "execution_count": 11, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from numcodecs.tests.common import greetings\n", - "z = zarr.array(greetings, chunks=5, dtype=object, object_codec=numcodecs.MsgPack())\n", - "z[:]" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [ - { - "ename": "RuntimeError", - "evalue": "cannot read object array without object codec", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mRuntimeError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mz\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_filters\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;31m# try to live dangerously, manually wipe filters\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mz\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36m__getitem__\u001b[0;34m(self, selection)\u001b[0m\n\u001b[1;32m 551\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 552\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mselection\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mpop_fields\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mselection\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 553\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_basic_selection\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mselection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfields\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 554\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 555\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mget_basic_selection\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mselection\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mEllipsis\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mout\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36mget_basic_selection\u001b[0;34m(self, selection, out, fields)\u001b[0m\n\u001b[1;32m 677\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 678\u001b[0m return self._get_basic_selection_nd(selection=selection, out=out,\n\u001b[0;32m--> 679\u001b[0;31m fields=fields)\n\u001b[0m\u001b[1;32m 680\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 681\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m_get_basic_selection_zd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mselection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mout\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36m_get_basic_selection_nd\u001b[0;34m(self, selection, out, fields)\u001b[0m\n\u001b[1;32m 719\u001b[0m \u001b[0mindexer\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mBasicIndexer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mselection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 720\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 721\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_get_selection\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mindexer\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mindexer\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mout\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mout\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfields\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 722\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 723\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mget_orthogonal_selection\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mselection\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mout\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfields\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36m_get_selection\u001b[0;34m(self, indexer, out, fields)\u001b[0m\n\u001b[1;32m 1007\u001b[0m \u001b[0;31m# load chunk selection into output array\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1008\u001b[0m self._chunk_getitem(chunk_coords, chunk_selection, out, out_selection,\n\u001b[0;32m-> 1009\u001b[0;31m drop_axes=indexer.drop_axes, fields=fields)\n\u001b[0m\u001b[1;32m 1010\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1011\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mout\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mshape\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36m_chunk_getitem\u001b[0;34m(self, chunk_coords, chunk_selection, out, out_selection, drop_axes, fields)\u001b[0m\n\u001b[1;32m 1597\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1598\u001b[0m \u001b[0;31m# decode chunk\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1599\u001b[0;31m \u001b[0mchunk\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_decode_chunk\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcdata\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1600\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1601\u001b[0m \u001b[0;31m# select data from chunk\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m~/src/github/alimanfoo/zarr/zarr/core.py\u001b[0m in \u001b[0;36m_decode_chunk\u001b[0;34m(self, cdata)\u001b[0m\n\u001b[1;32m 1733\u001b[0m \u001b[0mchunk\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mchunk\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mastype\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_dtype\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1734\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1735\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mRuntimeError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'cannot read object array without object codec'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1736\u001b[0m \u001b[0;32melif\u001b[0m \u001b[0misinstance\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mchunk\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mndarray\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1737\u001b[0m \u001b[0mchunk\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mchunk\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mview\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_dtype\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mRuntimeError\u001b[0m: cannot read object array without object codec" - ] - } - ], - "source": [ - "z._filters = [] # try to live dangerously, manually wipe filters\n", - "z[:]" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/notebooks/repr_info.ipynb b/notebooks/repr_info.ipynb deleted file mode 100644 index 487a4175ba..0000000000 --- a/notebooks/repr_info.ipynb +++ /dev/null @@ -1,365 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import zarr" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 2, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "root = zarr.group()\n", - "root" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
Name/
Typezarr.hierarchy.Group
Read-onlyFalse
Store typezarr.storage.DictStore
No. members0
No. arrays0
No. groups0
" - ], - "text/plain": [ - "Name : /\n", - "Type : zarr.hierarchy.Group\n", - "Read-only : False\n", - "Store type : zarr.storage.DictStore\n", - "No. members : 0\n", - "No. arrays : 0\n", - "No. groups : 0" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "root.info" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [], - "source": [ - "z = root.zeros('foo/bar/baz', shape=1000000)" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "z" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
Name/foo/bar/baz
Typezarr.core.Array
Data typefloat64
Shape(1000000,)
Chunk shape(15625,)
OrderC
Read-onlyFalse
CompressorBlosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store typezarr.storage.DictStore
No. bytes8000000 (7.6M)
No. bytes stored321
Storage ratio24922.1
Chunks initialized0/64
" - ], - "text/plain": [ - "Name : /foo/bar/baz\n", - "Type : zarr.core.Array\n", - "Data type : float64\n", - "Shape : (1000000,)\n", - "Chunk shape : (15625,)\n", - "Order : C\n", - "Read-only : False\n", - "Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)\n", - "Store type : zarr.storage.DictStore\n", - "No. bytes : 8000000 (7.6M)\n", - "No. bytes stored : 321\n", - "Storage ratio : 24922.1\n", - "Chunks initialized : 0/64" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "z.info" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "z[:] = 42" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
Name/foo/bar/baz
Typezarr.core.Array
Data typefloat64
Shape(1000000,)
Chunk shape(15625,)
OrderC
Read-onlyFalse
CompressorBlosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store typezarr.storage.DictStore
No. bytes8000000 (7.6M)
No. bytes stored39553 (38.6K)
Storage ratio202.3
Chunks initialized64/64
" - ], - "text/plain": [ - "Name : /foo/bar/baz\n", - "Type : zarr.core.Array\n", - "Data type : float64\n", - "Shape : (1000000,)\n", - "Chunk shape : (15625,)\n", - "Order : C\n", - "Read-only : False\n", - "Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)\n", - "Store type : zarr.storage.DictStore\n", - "No. bytes : 8000000 (7.6M)\n", - "No. bytes stored : 39553 (38.6K)\n", - "Storage ratio : 202.3\n", - "Chunks initialized : 64/64" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "z.info" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "for i in range(1000):\n", - " root.create_group(i)" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 10, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "root" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
Name/
Typezarr.hierarchy.Group
Read-onlyFalse
Store typezarr.storage.DictStore
No. members1001
No. arrays0
No. groups1001
Groups0, 1, 10, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 11, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 12, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 13, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 14, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 15, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 16, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 17, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 18, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 19, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 2, 20, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 21, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 22, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 23, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 24, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 25, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 26, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 27, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 28, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 29, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 3, 30, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 31, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 32, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 33, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 34, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 35, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 36, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 37, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 38, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 39, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 4, 40, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 41, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 42, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 43, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 44, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 45, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 46, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 47, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 48, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 49, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 5, 50, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 51, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 52, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 53, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 54, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 55, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 56, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 57, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 58, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 59, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 6, 60, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 61, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 62, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 63, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 64, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 65, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 66, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 67, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 68, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 69, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 7, 70, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 71, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 72, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 73, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 74, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 75, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 76, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 77, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 78, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 79, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 8, 80, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 81, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 82, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 83, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 84, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 85, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 86, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 87, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 88, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 89, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 9, 90, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 91, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 92, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 93, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 94, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 95, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 96, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 97, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 98, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 99, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, foo
" - ], - "text/plain": [ - "Name : /\n", - "Type : zarr.hierarchy.Group\n", - "Read-only : False\n", - "Store type : zarr.storage.DictStore\n", - "No. members : 1001\n", - "No. arrays : 0\n", - "No. groups : 1001\n", - "Groups : 0, 1, 10, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 11,\n", - " : 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 12, 120, 121,\n", - " : 122, 123, 124, 125, 126, 127, 128, 129, 13, 130, 131, 132, 133,\n", - " : 134, 135, 136, 137, 138, 139, 14, 140, 141, 142, 143, 144, 145,\n", - " : 146, 147, 148, 149, 15, 150, 151, 152, 153, 154, 155, 156, 157,\n", - " : 158, 159, 16, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169,\n", - " : 17, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 18, 180,\n", - " : 181, 182, 183, 184, 185, 186, 187, 188, 189, 19, 190, 191, 192,\n", - " : 193, 194, 195, 196, 197, 198, 199, 2, 20, 200, 201, 202, 203, 204,\n", - " : 205, 206, 207, 208, 209, 21, 210, 211, 212, 213, 214, 215, 216,\n", - " : 217, 218, 219, 22, 220, 221, 222, 223, 224, 225, 226, 227, 228,\n", - " : 229, 23, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 24,\n", - " : 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 25, 250, 251,\n", - " : 252, 253, 254, 255, 256, 257, 258, 259, 26, 260, 261, 262, 263,\n", - " : 264, 265, 266, 267, 268, 269, 27, 270, 271, 272, 273, 274, 275,\n", - " : 276, 277, 278, 279, 28, 280, 281, 282, 283, 284, 285, 286, 287,\n", - " : 288, 289, 29, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 3,\n", - " : 30, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 31, 310,\n", - " : 311, 312, 313, 314, 315, 316, 317, 318, 319, 32, 320, 321, 322,\n", - " : 323, 324, 325, 326, 327, 328, 329, 33, 330, 331, 332, 333, 334,\n", - " : 335, 336, 337, 338, 339, 34, 340, 341, 342, 343, 344, 345, 346,\n", - " : 347, 348, 349, 35, 350, 351, 352, 353, 354, 355, 356, 357, 358,\n", - " : 359, 36, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 37,\n", - " : 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 38, 380, 381,\n", - " : 382, 383, 384, 385, 386, 387, 388, 389, 39, 390, 391, 392, 393,\n", - " : 394, 395, 396, 397, 398, 399, 4, 40, 400, 401, 402, 403, 404, 405,\n", - " : 406, 407, 408, 409, 41, 410, 411, 412, 413, 414, 415, 416, 417,\n", - " : 418, 419, 42, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429,\n", - " : 43, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 44, 440,\n", - " : 441, 442, 443, 444, 445, 446, 447, 448, 449, 45, 450, 451, 452,\n", - " : 453, 454, 455, 456, 457, 458, 459, 46, 460, 461, 462, 463, 464,\n", - " : 465, 466, 467, 468, 469, 47, 470, 471, 472, 473, 474, 475, 476,\n", - " : 477, 478, 479, 48, 480, 481, 482, 483, 484, 485, 486, 487, 488,\n", - " : 489, 49, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 5, 50,\n", - " : 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 51, 510, 511,\n", - " : 512, 513, 514, 515, 516, 517, 518, 519, 52, 520, 521, 522, 523,\n", - " : 524, 525, 526, 527, 528, 529, 53, 530, 531, 532, 533, 534, 535,\n", - " : 536, 537, 538, 539, 54, 540, 541, 542, 543, 544, 545, 546, 547,\n", - " : 548, 549, 55, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559,\n", - " : 56, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 57, 570,\n", - " : 571, 572, 573, 574, 575, 576, 577, 578, 579, 58, 580, 581, 582,\n", - " : 583, 584, 585, 586, 587, 588, 589, 59, 590, 591, 592, 593, 594,\n", - " : 595, 596, 597, 598, 599, 6, 60, 600, 601, 602, 603, 604, 605, 606,\n", - " : 607, 608, 609, 61, 610, 611, 612, 613, 614, 615, 616, 617, 618,\n", - " : 619, 62, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 63,\n", - " : 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 64, 640, 641,\n", - " : 642, 643, 644, 645, 646, 647, 648, 649, 65, 650, 651, 652, 653,\n", - " : 654, 655, 656, 657, 658, 659, 66, 660, 661, 662, 663, 664, 665,\n", - " : 666, 667, 668, 669, 67, 670, 671, 672, 673, 674, 675, 676, 677,\n", - " : 678, 679, 68, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689,\n", - " : 69, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 7, 70, 700,\n", - " : 701, 702, 703, 704, 705, 706, 707, 708, 709, 71, 710, 711, 712,\n", - " : 713, 714, 715, 716, 717, 718, 719, 72, 720, 721, 722, 723, 724,\n", - " : 725, 726, 727, 728, 729, 73, 730, 731, 732, 733, 734, 735, 736,\n", - " : 737, 738, 739, 74, 740, 741, 742, 743, 744, 745, 746, 747, 748,\n", - " : 749, 75, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 76,\n", - " : 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 77, 770, 771,\n", - " : 772, 773, 774, 775, 776, 777, 778, 779, 78, 780, 781, 782, 783,\n", - " : 784, 785, 786, 787, 788, 789, 79, 790, 791, 792, 793, 794, 795,\n", - " : 796, 797, 798, 799, 8, 80, 800, 801, 802, 803, 804, 805, 806, 807,\n", - " : 808, 809, 81, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819,\n", - " : 82, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 83, 830,\n", - " : 831, 832, 833, 834, 835, 836, 837, 838, 839, 84, 840, 841, 842,\n", - " : 843, 844, 845, 846, 847, 848, 849, 85, 850, 851, 852, 853, 854,\n", - " : 855, 856, 857, 858, 859, 86, 860, 861, 862, 863, 864, 865, 866,\n", - " : 867, 868, 869, 87, 870, 871, 872, 873, 874, 875, 876, 877, 878,\n", - " : 879, 88, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 89,\n", - " : 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 9, 90, 900, 901,\n", - " : 902, 903, 904, 905, 906, 907, 908, 909, 91, 910, 911, 912, 913,\n", - " : 914, 915, 916, 917, 918, 919, 92, 920, 921, 922, 923, 924, 925,\n", - " : 926, 927, 928, 929, 93, 930, 931, 932, 933, 934, 935, 936, 937,\n", - " : 938, 939, 94, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949,\n", - " : 95, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 96, 960,\n", - " : 961, 962, 963, 964, 965, 966, 967, 968, 969, 97, 970, 971, 972,\n", - " : 973, 974, 975, 976, 977, 978, 979, 98, 980, 981, 982, 983, 984,\n", - " : 985, 986, 987, 988, 989, 99, 990, 991, 992, 993, 994, 995, 996,\n", - " : 997, 998, 999, foo" - ] - }, - "execution_count": 11, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "root.info" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
Name/foo/bar
Typezarr.hierarchy.Group
Read-onlyFalse
Store typezarr.storage.DictStore
No. members1
No. arrays1
No. groups0
Arraysbaz
" - ], - "text/plain": [ - "Name : /foo/bar\n", - "Type : zarr.hierarchy.Group\n", - "Read-only : False\n", - "Store type : zarr.storage.DictStore\n", - "No. members : 1\n", - "No. arrays : 1\n", - "No. groups : 0\n", - "Arrays : baz" - ] - }, - "execution_count": 15, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "root['foo/bar'].info" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/notebooks/repr_tree.ipynb b/notebooks/repr_tree.ipynb deleted file mode 100644 index dde8bbb9a0..0000000000 --- a/notebooks/repr_tree.ipynb +++ /dev/null @@ -1,1388 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'2.3.3.dev87'" - ] - }, - "execution_count": 1, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import zarr\n", - "zarr.__version__" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "g1 = zarr.group()\n", - "g2 = g1.create_group('foo')\n", - "g3 = g1.create_group('bar')\n", - "g3.create_group('baz')\n", - "g3.create_dataset('xxx', shape=100)\n", - "g3.create_dataset('yyy', shape=(100, 100), dtype='i4')\n", - "g5 = g3.create_group('quux')\n", - "g5.create_dataset('aaa', shape=100)\n", - "g5.create_dataset('bbb', shape=(100, 100), dtype='i4')\n", - "g7 = g3.create_group('zoo')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Generate text (unicode) tree:" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "/\n", - " β”œβ”€β”€ bar\n", - " β”‚ β”œβ”€β”€ baz\n", - " β”‚ β”œβ”€β”€ quux\n", - " β”‚ β”‚ β”œβ”€β”€ aaa (100,) float64\n", - " β”‚ β”‚ └── bbb (100, 100) int32\n", - " β”‚ β”œβ”€β”€ xxx (100,) float64\n", - " β”‚ β”œβ”€β”€ yyy (100, 100) int32\n", - " β”‚ └── zoo\n", - " └── foo\n" - ] - } - ], - "source": [ - "print(g1.tree())" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The ``level`` parameter controls how deep the tree is." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "/\n", - " β”œβ”€β”€ bar\n", - " └── foo\n" - ] - } - ], - "source": [ - "print(g1.tree(level=1))" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "/\n", - " β”œβ”€β”€ bar\n", - " β”‚ β”œβ”€β”€ baz\n", - " β”‚ β”œβ”€β”€ quux\n", - " β”‚ β”œβ”€β”€ xxx (100,) float64\n", - " β”‚ β”œβ”€β”€ yyy (100, 100) int32\n", - " β”‚ └── zoo\n", - " └── foo\n" - ] - } - ], - "source": [ - "print(g1.tree(level=2))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Alternative plain ASCII tree:" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "/\n", - " +-- bar\n", - " | +-- baz\n", - " | +-- quux\n", - " | | +-- aaa (100,) float64\n", - " | | +-- bbb (100, 100) int32\n", - " | +-- xxx (100,) float64\n", - " | +-- yyy (100, 100) int32\n", - " | +-- zoo\n", - " +-- foo\n" - ] - } - ], - "source": [ - "print(bytes(g1.tree()).decode())" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "HTML trees:" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [ - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "dc848c2195a54f1386f67cc631871449", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "Tree(nodes=(Node(disabled=True, name='/', nodes=(Node(disabled=True, name='bar', nodes=(Node(disabled=True, na…" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "g1.tree()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Use ``expand=True`` to have all groups automatically expanded." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [ - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "9459567637cf48cca67ba0145cc3a626", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "Tree(nodes=(Node(disabled=True, name='/', nodes=(Node(disabled=True, name='bar', nodes=(Node(disabled=True, na…" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "g1.tree(expand=True)" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [ - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "1c635a91c6a444fab7bcb33a33c73097", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "Tree(nodes=(Node(disabled=True, name='/', nodes=(Node(disabled=True, name='bar', nodes=(Node(disabled=True, na…" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "g1.tree(expand=True, level=2)" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [ - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "0a32522e7c3b4f95b2258027502167f7", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "Tree(nodes=(Node(disabled=True, name='/', nodes=(Node(disabled=True, name='bar'), Node(disabled=True, name='fo…" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "g1.tree(expand=True, level=1)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The ``expand`` parameter can also be an integer, giving the depth to expand to." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [ - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "2c9c017eebf94d2aa785439e94cfa533", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "Tree(nodes=(Node(disabled=True, name='/', nodes=(Node(disabled=True, name='bar', nodes=(Node(disabled=True, na…" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "g1.tree(expand=1)" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [ - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "edcb8650759d44a995538257d637a17e", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "Tree(nodes=(Node(disabled=True, name='/', nodes=(Node(disabled=True, name='bar', nodes=(Node(disabled=True, na…" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "g1.tree(expand=2)" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [ - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "ee03f431a4fa4395bb913c7107b8f82d", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "Tree(nodes=(Node(disabled=True, name='/', nodes=(Node(disabled=True, name='bar', nodes=(Node(disabled=True, na…" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "g1.tree(expand=3)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.7.2" - }, - "widgets": { - "application/vnd.jupyter.widget-state+json": { - "state": { - "00266d06794e4879b5f200a6da77a8b5": { - "model_module": "@jupyter-widgets/base", - "model_module_version": "1.2.0", - "model_name": "LayoutModel", - "state": {} - }, - "005396454d8a4ccdbd078066066abb25": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "4a5cee4c-65aa-4837-977c-ca04e7be6608", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "foo" - } - }, - "094a129d9ef04f56bbd9e2ef440cdf9f": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "ef9fee92-e6cb-4362-b095-715fa4bff3bc", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "aaa (100,) float64", - "opened": false - } - }, - "0a32522e7c3b4f95b2258027502167f7": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "TreeModel", - "state": { - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "layout": "IPY_MODEL_24a5ef087e4546aeb18b5bd4ea4106d9", - "nodes": [ - "IPY_MODEL_a91c0ac9a6644f18a6ec657cc3c2eb95" - ] - } - }, - "120c8e8cb7664fa0aa0a6ca27a1c5f3f": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "e6f11c15-cf73-4ac9-9737-0f539be27858", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "bar", - "nodes": [ - "IPY_MODEL_741dc4fd91c346f9882b87e9c927362d", - "IPY_MODEL_a6bd734a89044570af371e3f8d4c9fc7", - "IPY_MODEL_a443244f855e40e5bf02be971f470aad", - "IPY_MODEL_9d69e6ca94ae40de8103a7aa51a79a15", - "IPY_MODEL_71ae557f54c944b08874833dbc540339" - ] - } - }, - "14b81f73c9e6404bab187635805952ad": { - "model_module": "@jupyter-widgets/base", - "model_module_version": "1.2.0", - "model_name": "LayoutModel", - "state": {} - }, - "167b0ac3d49b4602900182c8580546eb": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "b7891bd2-6ef7-4d27-ad27-0f017548d302", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "xxx (100,) float64", - "opened": false - } - }, - "1b5ecaaed52a47d6b9846e8626dded36": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "a2ca1d10-8196-491a-898b-cb7ba4578157", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "zoo", - "opened": false - } - }, - "1c635a91c6a444fab7bcb33a33c73097": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "TreeModel", - "state": { - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "layout": "IPY_MODEL_231c730e6b154dd699e528a04e3bceac", - "nodes": [ - "IPY_MODEL_e4c46e3a01564d2986c3a0687e859251" - ] - } - }, - "2004cbc5c93142678c0443ab3260fc76": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "90ee3b0d-847e-4577-a7c3-9b21c666c292", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "/", - "nodes": [ - "IPY_MODEL_2fef457b9982499f87599dfc8404a768", - "IPY_MODEL_98eb0a6675c440ce9672156423051909" - ] - } - }, - "231c730e6b154dd699e528a04e3bceac": { - "model_module": "@jupyter-widgets/base", - "model_module_version": "1.2.0", - "model_name": "LayoutModel", - "state": {} - }, - "2376f63399664a9cb6fcb80112ebd316": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "0120995a-5972-45eb-94a2-4b4480395aa0", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "aaa (100,) float64", - "opened": false - } - }, - "23f8520500534a16903b1d760ee3c1b0": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "d6a76614-eafd-4059-83c0-7dc725969785", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "zoo" - } - }, - "24364dd05e21498a9ee6148d7069470c": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "775d02ae-3e15-4001-9680-89cdda964afe", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "foo" - } - }, - "24a5ef087e4546aeb18b5bd4ea4106d9": { - "model_module": "@jupyter-widgets/base", - "model_module_version": "1.2.0", - "model_name": "LayoutModel", - "state": {} - }, - "2bf13d8729f543c3b62c1dff0bc75f24": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "c994f1f5-1c0d-4a10-b056-54eb6e3654b0", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "quux", - "nodes": [ - "IPY_MODEL_859d15d7e1fb460fa9e1607835028d2f", - "IPY_MODEL_530d9c8872a34f68a5f203c490abea8c" - ] - } - }, - "2c9c017eebf94d2aa785439e94cfa533": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "TreeModel", - "state": { - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "layout": "IPY_MODEL_00266d06794e4879b5f200a6da77a8b5", - "nodes": [ - "IPY_MODEL_2004cbc5c93142678c0443ab3260fc76" - ] - } - }, - "2dd1565f8b5747f59bb0787235310fca": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "e5ac34b6-872f-41cf-84b2-0a2db45bf585", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "/", - "nodes": [ - "IPY_MODEL_c5c799513c214d878e6d9798e1418028", - "IPY_MODEL_7e51196f842148a59de5285587f7cdb3" - ] - } - }, - "2fef457b9982499f87599dfc8404a768": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "a1aad2fe-b5c5-4151-82a7-b681b524f55e", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "bar", - "nodes": [ - "IPY_MODEL_fda99f8dbbbe4636a0bab906c5267b81", - "IPY_MODEL_953f8443d806452aa6009c8d8cd6a00b", - "IPY_MODEL_167b0ac3d49b4602900182c8580546eb", - "IPY_MODEL_3aa51d78e7c14aa58818339ff8583364", - "IPY_MODEL_1b5ecaaed52a47d6b9846e8626dded36" - ], - "opened": false - } - }, - "3aa51d78e7c14aa58818339ff8583364": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "68f3fef0-f0a9-4549-80db-9c8f49e3c7c2", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "yyy (100, 100) int32", - "opened": false - } - }, - "3c31fa266b124cc7baa9572e10fff7d5": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "467cb368-3758-41ac-a037-d901001fedb8", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "foo", - "opened": false - } - }, - "3f686ef60c3742498467169845340486": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "46413eeb-ff88-4c8e-81f3-75175174511c", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "yyy (100, 100) int32", - "opened": false - } - }, - "41537120a09b49d7aef63cf97d3bcbdc": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "7bff3ed2-1676-4dc7-8865-8294df17bdf3", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "quux", - "nodes": [ - "IPY_MODEL_094a129d9ef04f56bbd9e2ef440cdf9f", - "IPY_MODEL_80da3a55f04d4ebfb5199c50553268a8" - ], - "opened": false - } - }, - "530d9c8872a34f68a5f203c490abea8c": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "ce5627ee-6b00-431f-8e0b-3e5f45e3228f", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "bbb (100, 100) int32" - } - }, - "57ce4623088643a18e8eec3ba6003fd7": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "9da1285e-bced-44b8-af47-95272401bcef", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "bar", - "nodes": [ - "IPY_MODEL_8bc5d72953c34131961f747b2cfac812", - "IPY_MODEL_a4b87dfad842423e88c5eeeba8817539", - "IPY_MODEL_81e1f7fa28b8482f9f6ec5694f99233f", - "IPY_MODEL_f394ec7d09a2410a8e19905a6b59751f", - "IPY_MODEL_9c89de1bc6f542bf8c16810dcfd5d703" - ] - } - }, - "585c788c4e60434295e208470bf2b9db": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "961d4b35-c7ad-4503-b212-18d2b5394cac", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "aaa (100,) float64", - "opened": false - } - }, - "5b06653afbb04bcd979f5390326b8115": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "9c26687d-6dab-4daa-95cc-bbbfab950e08", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "xxx (100,) float64", - "opened": false - } - }, - "60e395b510714a92b02b331dedac2c22": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "ec0906d5-3c8e-4c02-89fa-19f052ecb448", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "foo" - } - }, - "6390bb65bfd945aba4993fb82e052b13": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "23323321-dfbd-4fb1-b970-db209ff7dbdf", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "yyy (100, 100) int32" - } - }, - "6e160ea17f5c43248a8ef50ca08b3af4": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "185ee6a2-9064-4e40-a493-cd1fa2039510", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "bbb (100, 100) int32", - "opened": false - } - }, - "71ae557f54c944b08874833dbc540339": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "7442b769-5dd9-466e-bf71-d850dc4d864b", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "zoo" - } - }, - "741dc4fd91c346f9882b87e9c927362d": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "25667d21-0738-4b33-82a6-43cead9dcee3", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "baz" - } - }, - "7aed7c2c71fe4261bfee71d4e13b611a": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "b690530c-9414-47a6-ba1a-47b8582bb18e", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "baz" - } - }, - "7cc19caed25f418d8724b6d61cd40196": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "1ea2d350-3f19-4417-be0f-a8836eeb6015", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "bar", - "nodes": [ - "IPY_MODEL_d12eeab848e548869a02e76ee7deedcb", - "IPY_MODEL_41537120a09b49d7aef63cf97d3bcbdc", - "IPY_MODEL_5b06653afbb04bcd979f5390326b8115", - "IPY_MODEL_3f686ef60c3742498467169845340486", - "IPY_MODEL_d686caad9af343a6ad01cb98d7d46be9" - ], - "opened": false - } - }, - "7e51196f842148a59de5285587f7cdb3": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "66a2f671-756a-403b-b96a-78a4abca32c6", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "foo" - } - }, - "7f23d5608a9b4ae397e32c70bd7897bc": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "556be9fc-a7ff-45bb-b756-6494f58238a4", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "/", - "nodes": [ - "IPY_MODEL_7cc19caed25f418d8724b6d61cd40196", - "IPY_MODEL_3c31fa266b124cc7baa9572e10fff7d5" - ] - } - }, - "80da3a55f04d4ebfb5199c50553268a8": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "bdc7445a-2bdc-4191-bc18-d2e55227c338", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "bbb (100, 100) int32", - "opened": false - } - }, - "81e1f7fa28b8482f9f6ec5694f99233f": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "c4646b6f-fb0a-416e-817a-f52edb067149", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "xxx (100,) float64", - "opened": false - } - }, - "82f52a3353be4a368db1f71e15892a5c": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "92392f3d-ac69-48a2-be99-99d663baf567", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "bbb (100, 100) int32", - "opened": false - } - }, - "84f56fbf5c384e16b409ee918f6d7855": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "3ea55be4-a339-4798-af2e-e37ee07d0c3d", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "yyy (100, 100) int32" - } - }, - "8524ddcc608d42fcaa3ae6384ef98a25": { - "model_module": "@jupyter-widgets/base", - "model_module_version": "1.2.0", - "model_name": "LayoutModel", - "state": {} - }, - "859d15d7e1fb460fa9e1607835028d2f": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "74776201-7656-4b01-a9a4-723b0ec56602", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "aaa (100,) float64" - } - }, - "86f72ec1e4764ff1863e7daef9476476": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "2313648b-d4b1-47d1-a2ee-b07fbda43308", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "baz" - } - }, - "8818d09311f143f28672e8f75be2df01": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "bb7b5a89-cb39-4860-8d61-9419d59514e5", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "xxx (100,) float64" - } - }, - "896a87da7c2e4cd894c0e8bcc03e80fe": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "c73b4900-c1e4-4d60-814b-524de689373a", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "quux" - } - }, - "8bc5d72953c34131961f747b2cfac812": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "db5dcd99-6e88-40d0-b068-af436c365c8d", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "baz", - "opened": false - } - }, - "9459567637cf48cca67ba0145cc3a626": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "TreeModel", - "state": { - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "layout": "IPY_MODEL_14b81f73c9e6404bab187635805952ad", - "nodes": [ - "IPY_MODEL_2dd1565f8b5747f59bb0787235310fca" - ] - } - }, - "953f8443d806452aa6009c8d8cd6a00b": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "18140127-9a50-432d-98bf-297b8677e37e", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "quux", - "nodes": [ - "IPY_MODEL_2376f63399664a9cb6fcb80112ebd316", - "IPY_MODEL_deba2782b4c1464f81652d5f03920084" - ], - "opened": false - } - }, - "98eb0a6675c440ce9672156423051909": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "c89b7b7b-c3a3-4ac5-b2f6-9b938b2f7f98", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "foo", - "opened": false - } - }, - "9c89de1bc6f542bf8c16810dcfd5d703": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "b70bf77b-2424-478d-b009-67dd51fdfa5f", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "zoo", - "opened": false - } - }, - "9cb02d82f4964b9bb80202eb1e1965f0": { - "model_module": "@jupyter-widgets/base", - "model_module_version": "1.2.0", - "model_name": "LayoutModel", - "state": {} - }, - "9d69e6ca94ae40de8103a7aa51a79a15": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "530496d0-18ca-4d43-a6e4-b03d3816a567", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "yyy (100, 100) int32" - } - }, - "a443244f855e40e5bf02be971f470aad": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "cf32dfd6-d234-498c-821a-63424fe24b03", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "xxx (100,) float64" - } - }, - "a4b87dfad842423e88c5eeeba8817539": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "448a6ae8-e4b4-468d-8db1-a92092a5b255", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "quux", - "nodes": [ - "IPY_MODEL_585c788c4e60434295e208470bf2b9db", - "IPY_MODEL_82f52a3353be4a368db1f71e15892a5c" - ], - "opened": false - } - }, - "a6bd734a89044570af371e3f8d4c9fc7": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "36e727be-a1b7-4a0a-9941-aae4f617b6a7", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "quux", - "nodes": [ - "IPY_MODEL_eba07ec14a46420ab8f00565e998424f", - "IPY_MODEL_6e160ea17f5c43248a8ef50ca08b3af4" - ] - } - }, - "a91c0ac9a6644f18a6ec657cc3c2eb95": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "3b5d5c34-8fc1-4e50-be15-16cbae22778a", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "/", - "nodes": [ - "IPY_MODEL_ea998265f10549a1be0fea9579ab5ebd", - "IPY_MODEL_24364dd05e21498a9ee6148d7069470c" - ] - } - }, - "b612bbe40f3045cb9bce7662872d2194": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "5e418578-9312-4ce6-933a-c6d2606d0603", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "bar", - "nodes": [ - "IPY_MODEL_86f72ec1e4764ff1863e7daef9476476", - "IPY_MODEL_896a87da7c2e4cd894c0e8bcc03e80fe", - "IPY_MODEL_e7dd9b21300d4d84bf173916c6b05ccc", - "IPY_MODEL_6390bb65bfd945aba4993fb82e052b13", - "IPY_MODEL_df525d63b58649658b18437078be0b6c" - ] - } - }, - "c5c799513c214d878e6d9798e1418028": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "d8173610-bb78-45eb-9f56-a1e1f404d1e9", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "bar", - "nodes": [ - "IPY_MODEL_7aed7c2c71fe4261bfee71d4e13b611a", - "IPY_MODEL_2bf13d8729f543c3b62c1dff0bc75f24", - "IPY_MODEL_8818d09311f143f28672e8f75be2df01", - "IPY_MODEL_84f56fbf5c384e16b409ee918f6d7855", - "IPY_MODEL_23f8520500534a16903b1d760ee3c1b0" - ] - } - }, - "d00c74f3a7714efb9d89829e16ff4cd8": { - "model_module": "@jupyter-widgets/base", - "model_module_version": "1.2.0", - "model_name": "LayoutModel", - "state": {} - }, - "d12eeab848e548869a02e76ee7deedcb": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "f23a5051-caf9-4527-951d-61bb352a1c4f", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "baz", - "opened": false - } - }, - "d686caad9af343a6ad01cb98d7d46be9": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "ce8441db-4518-4d0d-b9e3-085f662b4c77", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "zoo", - "opened": false - } - }, - "db4c5c98a1bb49afa022d0009d5f4247": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "f6d98bfd-d8bb-4cd1-b714-e4ed7574f0a0", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "/", - "nodes": [ - "IPY_MODEL_57ce4623088643a18e8eec3ba6003fd7", - "IPY_MODEL_de6fc66267e449dd988127f5fecef78d" - ] - } - }, - "dc848c2195a54f1386f67cc631871449": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "TreeModel", - "state": { - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "layout": "IPY_MODEL_8524ddcc608d42fcaa3ae6384ef98a25", - "nodes": [ - "IPY_MODEL_7f23d5608a9b4ae397e32c70bd7897bc" - ] - } - }, - "de6fc66267e449dd988127f5fecef78d": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "1d94bc9b-a7d6-430c-a159-88c7848d2554", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "foo" - } - }, - "deba2782b4c1464f81652d5f03920084": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "c830b45a-298b-42df-a3db-7e5170e612a2", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "bbb (100, 100) int32", - "opened": false - } - }, - "df525d63b58649658b18437078be0b6c": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "2d8dbe4d-b683-452b-987b-84775b0b95db", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "zoo" - } - }, - "e4c46e3a01564d2986c3a0687e859251": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "8f477a24-5aa9-4d1f-8104-947cf2cca963", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "/", - "nodes": [ - "IPY_MODEL_b612bbe40f3045cb9bce7662872d2194", - "IPY_MODEL_005396454d8a4ccdbd078066066abb25" - ] - } - }, - "e7dd9b21300d4d84bf173916c6b05ccc": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "aec6a6ff-3944-4ff5-941d-51bcf07f7bcf", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "xxx (100,) float64" - } - }, - "ea998265f10549a1be0fea9579ab5ebd": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "0bc70d5d-6730-4265-a0f0-9c14c0ea868e", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "bar" - } - }, - "eba07ec14a46420ab8f00565e998424f": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "167e56c3-594e-4629-82b9-c71a12519d04", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "aaa (100,) float64", - "opened": false - } - }, - "edcb8650759d44a995538257d637a17e": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "TreeModel", - "state": { - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "layout": "IPY_MODEL_9cb02d82f4964b9bb80202eb1e1965f0", - "nodes": [ - "IPY_MODEL_db4c5c98a1bb49afa022d0009d5f4247" - ] - } - }, - "ee03f431a4fa4395bb913c7107b8f82d": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "TreeModel", - "state": { - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "layout": "IPY_MODEL_d00c74f3a7714efb9d89829e16ff4cd8", - "nodes": [ - "IPY_MODEL_fc9683e8600b461dbd4edaa9726179ad" - ] - } - }, - "f394ec7d09a2410a8e19905a6b59751f": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "900c0ef5-07f0-45be-9d4f-05a9e08d7709", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "icon": "table", - "name": "yyy (100, 100) int32", - "opened": false - } - }, - "fc9683e8600b461dbd4edaa9726179ad": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "26731003-f7ac-45fa-955d-181a02ba2b3d", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "/", - "nodes": [ - "IPY_MODEL_120c8e8cb7664fa0aa0a6ca27a1c5f3f", - "IPY_MODEL_60e395b510714a92b02b331dedac2c22" - ] - } - }, - "fda99f8dbbbe4636a0bab906c5267b81": { - "model_module": "ipytree", - "model_module_version": "0.1.3", - "model_name": "NodeModel", - "state": { - "_id": "093bd8d7-6f8d-4017-85eb-edf3260c4a30", - "_model_module_version": "0.1.3", - "_view_module_version": "0.1.3", - "disabled": true, - "name": "baz", - "opened": false - } - } - }, - "version_major": 2, - "version_minor": 0 - } - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} diff --git a/notebooks/store_benchmark.ipynb b/notebooks/store_benchmark.ipynb deleted file mode 100644 index 869e7df608..0000000000 --- a/notebooks/store_benchmark.ipynb +++ /dev/null @@ -1,1303 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "There are lies, damn lies and benchmarks..." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Setup" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'2.2.0a2.dev22+dirty'" - ] - }, - "execution_count": 1, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import zarr\n", - "zarr.__version__" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'6.2.5'" - ] - }, - "execution_count": 2, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import bsddb3\n", - "bsddb3.__version__" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'0.93'" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import lmdb\n", - "lmdb.__version__" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [], - "source": [ - "import dbm.gnu\n", - "import dbm.ndbm" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [], - "source": [ - "import os\n", - "import shutil\n", - "bench_dir = '../data/bench'\n", - "\n", - "\n", - "def clean():\n", - " if os.path.isdir(bench_dir):\n", - " shutil.rmtree(bench_dir)\n", - " os.makedirs(bench_dir)\n", - "\n", - " \n", - "def setup(a, name='foo/bar'):\n", - " global fdict_z, hdict_z, lmdb_z, gdbm_z, ndbm_z, bdbm_btree_z, bdbm_hash_z, zip_z, dir_z\n", - " \n", - " clean()\n", - " fdict_root = zarr.group(store=dict())\n", - " hdict_root = zarr.group(store=zarr.DictStore())\n", - " lmdb_root = zarr.group(store=zarr.LMDBStore(os.path.join(bench_dir, 'lmdb')))\n", - " gdbm_root = zarr.group(store=zarr.DBMStore(os.path.join(bench_dir, 'gdbm'), open=dbm.gnu.open))\n", - " ndbm_root = zarr.group(store=zarr.DBMStore(os.path.join(bench_dir, 'ndbm'), open=dbm.ndbm.open))\n", - " bdbm_btree_root = zarr.group(store=zarr.DBMStore(os.path.join(bench_dir, 'bdbm_btree'), open=bsddb3.btopen))\n", - " bdbm_hash_root = zarr.group(store=zarr.DBMStore(os.path.join(bench_dir, 'bdbm_hash'), open=bsddb3.hashopen))\n", - " zip_root = zarr.group(store=zarr.ZipStore(os.path.join(bench_dir, 'zip'), mode='w'))\n", - " dir_root = zarr.group(store=zarr.DirectoryStore(os.path.join(bench_dir, 'dir')))\n", - "\n", - " fdict_z = fdict_root.empty_like(name, a)\n", - " hdict_z = hdict_root.empty_like(name, a)\n", - " lmdb_z = lmdb_root.empty_like(name, a)\n", - " gdbm_z = gdbm_root.empty_like(name, a)\n", - " ndbm_z = ndbm_root.empty_like(name, a)\n", - " bdbm_btree_z = bdbm_btree_root.empty_like(name, a)\n", - " bdbm_hash_z = bdbm_hash_root.empty_like(name, a)\n", - " zip_z = zip_root.empty_like(name, a)\n", - " dir_z = dir_root.empty_like(name, a)\n", - "\n", - " # check compression ratio\n", - " fdict_z[:] = a\n", - " return fdict_z.info\n", - " \n", - " " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Main benchmarks" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "def save(a, z):\n", - " if isinstance(z.store, zarr.ZipStore):\n", - " # needed for zip benchmarks to avoid duplicate entries\n", - " z.store.clear()\n", - " z[:] = a\n", - " if hasattr(z.store, 'flush'):\n", - " z.store.flush()\n", - " \n", - " \n", - "def load(z, a):\n", - " z.get_basic_selection(out=a)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## arange" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
Name/foo/bar
Typezarr.core.Array
Data typeint64
Shape(500000000,)
Chunk shape(488282,)
OrderC
Read-onlyFalse
CompressorBlosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store typebuiltins.dict
No. bytes4000000000 (3.7G)
No. bytes stored59269657 (56.5M)
Storage ratio67.5
Chunks initialized1024/1024
" - ], - "text/plain": [ - "Name : /foo/bar\n", - "Type : zarr.core.Array\n", - "Data type : int64\n", - "Shape : (500000000,)\n", - "Chunk shape : (488282,)\n", - "Order : C\n", - "Read-only : False\n", - "Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)\n", - "Store type : builtins.dict\n", - "No. bytes : 4000000000 (3.7G)\n", - "No. bytes stored : 59269657 (56.5M)\n", - "Storage ratio : 67.5\n", - "Chunks initialized : 1024/1024" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = np.arange(500000000)\n", - "setup(a)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### save" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "324 ms Β± 60.9 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit save(a, fdict_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "302 ms Β± 11.6 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit save(a, hdict_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "316 ms Β± 12.6 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit save(a, lmdb_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "938 ms Β± 111 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit save(a, gdbm_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "406 ms Β± 8.93 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit save(a, ndbm_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1.43 s Β± 156 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit save(a, bdbm_btree_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1.24 s Β± 260 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit save(a, bdbm_hash_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": { - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "519 ms Β± 59.7 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit save(a, zip_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "609 ms Β± 48.9 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit save(a, dir_z)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### load" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "454 ms Β± 56.8 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit load(fdict_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "428 ms Β± 13.1 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit load(hdict_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "429 ms Β± 19.1 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit load(lmdb_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "459 ms Β± 10 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit load(gdbm_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "473 ms Β± 5.71 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit load(ndbm_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "504 ms Β± 8 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit load(bdbm_btree_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "519 ms Β± 9.59 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit load(bdbm_hash_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "575 ms Β± 12.5 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit load(zip_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "494 ms Β± 10.7 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit load(dir_z, a)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## randint" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
Name/foo/bar
Typezarr.core.Array
Data typeint64
Shape(500000000,)
Chunk shape(488282,)
OrderC
Read-onlyFalse
CompressorBlosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store typebuiltins.dict
No. bytes4000000000 (3.7G)
No. bytes stored2020785466 (1.9G)
Storage ratio2.0
Chunks initialized1024/1024
" - ], - "text/plain": [ - "Name : /foo/bar\n", - "Type : zarr.core.Array\n", - "Data type : int64\n", - "Shape : (500000000,)\n", - "Chunk shape : (488282,)\n", - "Order : C\n", - "Read-only : False\n", - "Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)\n", - "Store type : builtins.dict\n", - "No. bytes : 4000000000 (3.7G)\n", - "No. bytes stored : 2020785466 (1.9G)\n", - "Storage ratio : 2.0\n", - "Chunks initialized : 1024/1024" - ] - }, - "execution_count": 28, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "np.random.seed(42)\n", - "a = np.random.randint(0, 2**30, size=500000000)\n", - "setup(a)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### save" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "670 ms Β± 78.1 ms per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 save(a, fdict_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "611 ms Β± 6.11 ms per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 save(a, hdict_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "846 ms Β± 24 ms per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 save(a, lmdb_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "6.35 s Β± 785 ms per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 save(a, gdbm_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "4.62 s Β± 1.09 s per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 save(a, ndbm_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "7.84 s Β± 1.66 s per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 save(a, bdbm_btree_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "6.49 s Β± 808 ms per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 save(a, bdbm_hash_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "3.68 s Β± 441 ms per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 save(a, zip_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "3.55 s Β± 1.24 s per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 save(a, dir_z)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### load" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "566 ms Β± 72.8 ms per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 load(fdict_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 40, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "521 ms Β± 16.1 ms per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 load(hdict_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 41, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "532 ms Β± 16.1 ms per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 load(lmdb_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 42, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1.2 s Β± 10.9 ms per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 load(gdbm_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 43, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1.18 s Β± 13.2 ms per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 load(ndbm_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 44, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1.59 s Β± 16.7 ms per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 load(bdbm_btree_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 45, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1.61 s Β± 7.31 ms per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 load(bdbm_hash_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 46, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "2.33 s Β± 19.8 ms per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 load(zip_z, a)" - ] - }, - { - "cell_type": "code", - "execution_count": 47, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "790 ms Β± 56 ms per loop (mean Β± std. dev. of 3 runs, 1 loop each)\n" - ] - } - ], - "source": [ - "%timeit -r3 load(dir_z, a)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### dask" - ] - }, - { - "cell_type": "code", - "execution_count": 48, - "metadata": {}, - "outputs": [], - "source": [ - "import dask.array as da" - ] - }, - { - "cell_type": "code", - "execution_count": 50, - "metadata": {}, - "outputs": [], - "source": [ - "def dask_op(source, sink, chunks=None):\n", - " if isinstance(sink.store, zarr.ZipStore):\n", - " sink.store.clear()\n", - " if chunks is None:\n", - " try:\n", - " chunks = sink.chunks\n", - " except AttributeError:\n", - " chunks = source.chunks\n", - " d = da.from_array(source, chunks=chunks, asarray=False, fancy=False, lock=False)\n", - " result = (d // 2) * 2\n", - " da.store(result, sink, lock=False)\n", - " if hasattr(sink.store, 'flush'):\n", - " sink.store.flush()\n", - " " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Compare sources" - ] - }, - { - "cell_type": "code", - "execution_count": 76, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 15.6 s, sys: 1.8 s, total: 17.4 s\n", - "Wall time: 3.07 s\n" - ] - } - ], - "source": [ - "%time dask_op(fdict_z, fdict_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 77, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 16.5 s, sys: 104 ms, total: 16.6 s\n", - "Wall time: 2.59 s\n" - ] - } - ], - "source": [ - "%time dask_op(hdict_z, fdict_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 78, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 15.1 s, sys: 524 ms, total: 15.6 s\n", - "Wall time: 3.02 s\n" - ] - } - ], - "source": [ - "%time dask_op(lmdb_z, fdict_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 79, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 16.5 s, sys: 712 ms, total: 17.2 s\n", - "Wall time: 3.13 s\n" - ] - } - ], - "source": [ - "%time dask_op(gdbm_z, fdict_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 80, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 16.3 s, sys: 604 ms, total: 16.9 s\n", - "Wall time: 3.22 s\n" - ] - } - ], - "source": [ - "%time dask_op(ndbm_z, fdict_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 81, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 19.6 s, sys: 1.24 s, total: 20.9 s\n", - "Wall time: 3.27 s\n" - ] - } - ], - "source": [ - "%time dask_op(bdbm_btree_z, fdict_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 82, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 20.3 s, sys: 1.08 s, total: 21.4 s\n", - "Wall time: 3.53 s\n" - ] - } - ], - "source": [ - "%time dask_op(bdbm_hash_z, fdict_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 83, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 15.7 s, sys: 700 ms, total: 16.4 s\n", - "Wall time: 3.12 s\n" - ] - } - ], - "source": [ - "%time dask_op(zip_z, fdict_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 84, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 17.4 s, sys: 1.08 s, total: 18.5 s\n", - "Wall time: 2.91 s\n" - ] - } - ], - "source": [ - "%time dask_op(dir_z, fdict_z)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Compare sinks" - ] - }, - { - "cell_type": "code", - "execution_count": 51, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 15.8 s, sys: 1.4 s, total: 17.2 s\n", - "Wall time: 3.04 s\n" - ] - } - ], - "source": [ - "%time dask_op(fdict_z, hdict_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 52, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 16.2 s, sys: 1.6 s, total: 17.8 s\n", - "Wall time: 2.71 s\n" - ] - } - ], - "source": [ - "%time dask_op(fdict_z, lmdb_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 59, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 16.8 s, sys: 3.05 s, total: 19.8 s\n", - "Wall time: 8.01 s\n" - ] - } - ], - "source": [ - "%time dask_op(fdict_z, gdbm_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 54, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 17.9 s, sys: 3.01 s, total: 20.9 s\n", - "Wall time: 5.46 s\n" - ] - } - ], - "source": [ - "%time dask_op(fdict_z, ndbm_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 61, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 13.8 s, sys: 3.39 s, total: 17.2 s\n", - "Wall time: 7.87 s\n" - ] - } - ], - "source": [ - "%time dask_op(fdict_z, bdbm_btree_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 56, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 13.9 s, sys: 3.27 s, total: 17.2 s\n", - "Wall time: 6.73 s\n" - ] - } - ], - "source": [ - "%time dask_op(fdict_z, bdbm_hash_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 57, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 13.9 s, sys: 2.5 s, total: 16.4 s\n", - "Wall time: 3.8 s\n" - ] - } - ], - "source": [ - "%time dask_op(fdict_z, zip_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 58, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 15.7 s, sys: 3.72 s, total: 19.4 s\n", - "Wall time: 3.1 s\n" - ] - } - ], - "source": [ - "%time dask_op(fdict_z, dir_z)" - ] - }, - { - "cell_type": "code", - "execution_count": 62, - "metadata": {}, - "outputs": [], - "source": [ - "lmdb_z.store.close()\n", - "gdbm_z.store.close()\n", - "ndbm_z.store.close()\n", - "bdbm_btree_z.store.close()\n", - "bdbm_hash_z.store.close()\n", - "zip_z.store.close()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/notebooks/zip_benchmark.ipynb b/notebooks/zip_benchmark.ipynb deleted file mode 100644 index 6805552422..0000000000 --- a/notebooks/zip_benchmark.ipynb +++ /dev/null @@ -1,343 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "'2.0.2.dev0+dirty'" - ] - }, - "execution_count": 1, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import sys\n", - "sys.path.insert(0, '..')\n", - "import zarr\n", - "zarr.__version__" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "Array(/3L/calldata/genotype, (7449486, 773, 2), int8, chunks=(13107, 40, 2), order=C)\n", - " nbytes: 10.7G; nbytes_stored: 193.5M; ratio: 56.7; initialized: 11380/11380\n", - " compressor: Blosc(cname='zstd', clevel=1, shuffle=2)\n", - " store: ZipStore" - ] - }, - "execution_count": 2, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "store = zarr.ZipStore('/data/coluzzi/ag1000g/data/phase1/release/AR3.1/haplotypes/main/zarr2/zstd/ag1000g.phase1.ar3.1.haplotypes.zip',\n", - " mode='r')\n", - "grp = zarr.Group(store)\n", - "z = grp['3L/calldata/genotype']\n", - "z" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - " 1832 function calls in 0.024 seconds\n", - "\n", - " Ordered by: cumulative time\n", - "\n", - " ncalls tottime percall cumtime percall filename:lineno(function)\n", - " 1 0.000 0.000 0.024 0.024 {built-in method builtins.exec}\n", - " 1 0.000 0.000 0.024 0.024 :1()\n", - " 1 0.000 0.000 0.024 0.024 core.py:292(__getitem__)\n", - " 20 0.000 0.000 0.023 0.001 core.py:539(_chunk_getitem)\n", - " 20 0.000 0.000 0.020 0.001 core.py:679(_decode_chunk)\n", - " 20 0.000 0.000 0.020 0.001 codecs.py:355(decode)\n", - " 20 0.020 0.001 0.020 0.001 {zarr.blosc.decompress}\n", - " 20 0.000 0.000 0.002 0.000 storage.py:766(__getitem__)\n", - " 20 0.000 0.000 0.001 0.000 zipfile.py:1235(open)\n", - " 20 0.000 0.000 0.001 0.000 zipfile.py:821(read)\n", - " 20 0.000 0.000 0.001 0.000 zipfile.py:901(_read1)\n", - " 80 0.000 0.000 0.001 0.000 zipfile.py:660(read)\n", - " 20 0.000 0.000 0.000 0.000 zipfile.py:854(_update_crc)\n", - " 40 0.000 0.000 0.000 0.000 {built-in method zlib.crc32}\n", - " 80 0.000 0.000 0.000 0.000 {method 'read' of '_io.BufferedReader' objects}\n", - " 20 0.000 0.000 0.000 0.000 zipfile.py:937(_read2)\n", - " 80 0.000 0.000 0.000 0.000 core.py:390()\n", - " 20 0.000 0.000 0.000 0.000 zipfile.py:953(close)\n", - " 20 0.000 0.000 0.000 0.000 {method 'reshape' of 'numpy.ndarray' objects}\n", - " 20 0.000 0.000 0.000 0.000 util.py:106(is_total_slice)\n", - " 20 0.000 0.000 0.000 0.000 zipfile.py:708(__init__)\n", - " 20 0.000 0.000 0.000 0.000 {method 'decode' of 'bytes' objects}\n", - " 20 0.000 0.000 0.000 0.000 core.py:676(_chunk_key)\n", - " 80 0.000 0.000 0.000 0.000 {method 'seek' of '_io.BufferedReader' objects}\n", - " 20 0.000 0.000 0.000 0.000 {built-in method numpy.core.multiarray.frombuffer}\n", - " 80 0.000 0.000 0.000 0.000 core.py:398()\n", - " 20 0.000 0.000 0.000 0.000 {method 'join' of 'str' objects}\n", - " 20 0.000 0.000 0.000 0.000 core.py:386()\n", - " 20 0.000 0.000 0.000 0.000 {built-in method builtins.all}\n", - " 40 0.000 0.000 0.000 0.000 util.py:121()\n", - " 231 0.000 0.000 0.000 0.000 {built-in method builtins.isinstance}\n", - " 20 0.000 0.000 0.000 0.000 cp437.py:14(decode)\n", - " 80 0.000 0.000 0.000 0.000 {method 'tell' of '_io.BufferedReader' objects}\n", - " 20 0.000 0.000 0.000 0.000 zipfile.py:667(close)\n", - " 20 0.000 0.000 0.000 0.000 {built-in method _struct.unpack}\n", - " 140 0.000 0.000 0.000 0.000 {built-in method builtins.max}\n", - " 20 0.000 0.000 0.000 0.000 {function ZipExtFile.close at 0x7f8cd5ca2048}\n", - " 20 0.000 0.000 0.000 0.000 zipfile.py:1194(getinfo)\n", - " 140 0.000 0.000 0.000 0.000 {built-in method builtins.min}\n", - " 20 0.000 0.000 0.000 0.000 threading.py:1224(current_thread)\n", - " 20 0.000 0.000 0.000 0.000 zipfile.py:654(__init__)\n", - " 1 0.000 0.000 0.000 0.000 util.py:195(get_chunk_range)\n", - " 20 0.000 0.000 0.000 0.000 {built-in method _codecs.charmap_decode}\n", - " 1 0.000 0.000 0.000 0.000 util.py:166(normalize_array_selection)\n", - " 1 0.000 0.000 0.000 0.000 util.py:198()\n", - " 20 0.000 0.000 0.000 0.000 zipfile.py:1715(_fpclose)\n", - " 20 0.000 0.000 0.000 0.000 {method 'get' of 'dict' objects}\n", - " 63 0.000 0.000 0.000 0.000 {built-in method builtins.len}\n", - " 1 0.000 0.000 0.000 0.000 {built-in method numpy.core.multiarray.empty}\n", - " 2 0.000 0.000 0.000 0.000 util.py:182()\n", - " 20 0.000 0.000 0.000 0.000 {built-in method builtins.hasattr}\n", - " 20 0.000 0.000 0.000 0.000 {built-in method _thread.get_ident}\n", - " 1 0.000 0.000 0.000 0.000 util.py:130(normalize_axis_selection)\n", - " 20 0.000 0.000 0.000 0.000 zipfile.py:636(_get_decompressor)\n", - " 20 0.000 0.000 0.000 0.000 threading.py:1298(main_thread)\n", - " 4 0.000 0.000 0.000 0.000 core.py:373()\n", - " 3 0.000 0.000 0.000 0.000 util.py:187()\n", - " 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n", - "\n", - "\n" - ] - } - ], - "source": [ - "import cProfile\n", - "cProfile.run('z[:10]', sort='cumtime')" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "'0.11.0'" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import dask\n", - "import dask.array as da\n", - "dask.__version__" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "dask.array" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "d = da.from_array(z, chunks=z.chunks)\n", - "d" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 3min 35s, sys: 4.36 s, total: 3min 40s\n", - "Wall time: 29.5 s\n" - ] - }, - { - "data": { - "text/plain": [ - "array([[3, 0],\n", - " [1, 0],\n", - " [2, 0],\n", - " ..., \n", - " [2, 8],\n", - " [8, 8],\n", - " [0, 1]])" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "%time d.sum(axis=1).compute()" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "Array(/3L/calldata/genotype, (7449486, 773, 2), int8, chunks=(13107, 40, 2), order=C)\n", - " nbytes: 10.7G; nbytes_stored: 193.5M; ratio: 56.7; initialized: 11380/11380\n", - " compressor: Blosc(cname='zstd', clevel=1, shuffle=2)\n", - " store: DirectoryStore" - ] - }, - "execution_count": 9, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# compare with same data via directory store\n", - "store_dir = zarr.DirectoryStore('/data/coluzzi/ag1000g/data/phase1/release/AR3.1/haplotypes/main/zarr2/zstd/ag1000g.phase1.ar3.1.haplotypes')\n", - "grp_dir = zarr.Group(store_dir)\n", - "z_dir = grp_dir['3L/calldata/genotype']\n", - "z_dir" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "dask.array" - ] - }, - "execution_count": 10, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "d_dir = da.from_array(z_dir, chunks=z_dir.chunks)\n", - "d_dir" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 3min 39s, sys: 4.91 s, total: 3min 44s\n", - "Wall time: 31.1 s\n" - ] - }, - { - "data": { - "text/plain": [ - "array([[3, 0],\n", - " [1, 0],\n", - " [2, 0],\n", - " ..., \n", - " [2, 8],\n", - " [8, 8],\n", - " [0, 1]])" - ] - }, - "execution_count": 11, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "%time d_dir.sum(axis=1).compute()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.5.1" - } - }, - "nbformat": 4, - "nbformat_minor": 1 -} diff --git a/packages/zarr-http-server/.readthedocs.yaml b/packages/zarr-http-server/.readthedocs.yaml new file mode 100644 index 0000000000..efbda6852d --- /dev/null +++ b/packages/zarr-http-server/.readthedocs.yaml @@ -0,0 +1,43 @@ +# Read the Docs configuration for the zarr-http-server docs site, separate from +# the zarr-python site configured by the repo-root .readthedocs.yaml. The RTD +# project for zarr-http-server must set its configuration-file path to +# packages/zarr-http-server/.readthedocs.yaml. +version: 2 + +build: + os: ubuntu-22.04 + tools: + python: "3.12" + jobs: + post_checkout: + # Cancel pull request builds that do not touch this package. Exit code + # 183 cancels the build and reports success to the Git provider. Scoped + # to PR builds ("external" versions) because origin/main is only a + # meaningful diff base there. + - | + if [ "$READTHEDOCS_VERSION_TYPE" = "external" ] && git diff --quiet origin/main -- packages/zarr-http-server; + then + exit 183; + fi + install: + - pip install --upgrade pip + - pip install ./packages/zarr-http-server --group packages/zarr-http-server/pyproject.toml:docs + build: + html: + # Build from inside the package rather than pointing `-f` at its config + # from the repo root. mkdocs resolves some settings relative to the + # current working directory rather than to the config file, so building + # from elsewhere looks for them in the wrong place -- and silently, since + # the paths are valid, just wrong. zarr-indexing hit this: with + # `pymdownx.snippets` and a relative `base_path`, its snippets were + # searched for under the repo-root docs/ and the build failed with + # SnippetMissingError, while `just docs-check` passed because it runs + # from here. Building from the package directory makes this identical to + # the local and CI invocations, so a green build there means a green + # build here. + # + # $READTHEDOCS_OUTPUT is absolute, so the cd does not affect it. + - cd packages/zarr-http-server && mkdocs build --strict --site-dir $READTHEDOCS_OUTPUT/html + +mkdocs: + configuration: packages/zarr-http-server/mkdocs.yml diff --git a/packages/zarr-http-server/CHANGELOG.md b/packages/zarr-http-server/CHANGELOG.md new file mode 100644 index 0000000000..7c4bc92cad --- /dev/null +++ b/packages/zarr-http-server/CHANGELOG.md @@ -0,0 +1,3 @@ +# Release notes + + diff --git a/packages/zarr-http-server/LICENSE.txt b/packages/zarr-http-server/LICENSE.txt new file mode 100644 index 0000000000..1e8da4d242 --- /dev/null +++ b/packages/zarr-http-server/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-2025 Zarr Developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/zarr-http-server/README.md b/packages/zarr-http-server/README.md new file mode 100644 index 0000000000..53df0d2f50 --- /dev/null +++ b/packages/zarr-http-server/README.md @@ -0,0 +1,71 @@ +# zarr-http-server + +HTTP server for Zarr stores, arrays, and groups. + +Documentation: + +`zarr-http-server` exposes a Zarr `Store`, `Array`, or `Group` over HTTP via an +ASGI app, so any HTTP-capable client β€” including zarr-python itself, via +`FsspecStore` or `ObjectStore` β€” can read the data. The app is built on +[Starlette](https://www.starlette.io/) and can be run with any ASGI server; +the `serve` / `serve_background` helpers run it with +[Uvicorn](https://uvicorn.dev/). + +> [!WARNING] +> This package is experimental. Its API may change or be removed at any point. + +## Installation + +```bash +pip install zarr-http-server +``` + +## Quick start + +```python +import zarr +from zarr_http_server import node_app, serve_background + +store = zarr.storage.MemoryStore() +array = zarr.create_array(store, shape=(100,), chunks=(10,), dtype="float64") + +with serve_background(node_app(array)) as server: + print(server.url) # e.g. http://127.0.0.1:8000 +``` + +Building an app and running it are separate steps, and either app works with +either runner: + +- **Build** with `store_app` to serve every key in a store, or `node_app` to + serve only the keys belonging to one `Array` or `Group` β€” requests for keys + outside that node return 404 even when those keys exist in the underlying + store. +- **Run** with `serve`, which blocks, or `serve_background`, which returns a + handle you can shut down later. + +Reads are all that is enabled by default: `GET` and `HEAD` are served, and +`PUT`, `POST`, `DELETE` and `PATCH` are answered with 405. + +> [!CAUTION] +> `store_app` applies no per-key filtering. Only point it at a store whose full +> contents are safe to serve, and note that enabling `PUT` grants write access +> to everything the store contains. The +> [user guide](https://zarr-http-server.readthedocs.io/en/latest/guide/#read-only-serving) +> covers the read-only guarantees available. + +The [user guide](https://zarr-http-server.readthedocs.io/en/latest/guide/) +covers byte ranges, CORS, writes, serving several nodes, running from a +notebook, and Uvicorn configuration. + +## Examples + +[`examples/`](examples/) holds a runnable script and a notebook, both executed +by the test suite so neither can drift from the code: + +```bash +uv run examples/serve.py +``` + +## License + +MIT β€” see [LICENSE.txt](LICENSE.txt). diff --git a/packages/zarr-http-server/changes/3732.feature.md b/packages/zarr-http-server/changes/3732.feature.md new file mode 100644 index 0000000000..accd91ab81 --- /dev/null +++ b/packages/zarr-http-server/changes/3732.feature.md @@ -0,0 +1,3 @@ +Initial release of `zarr-http-server`: an HTTP server exposing Zarr stores, +arrays, and groups over an ASGI app, extracted from the +`zarr.experimental.serve` prototype in zarr-python. diff --git a/packages/zarr-http-server/changes/README.md b/packages/zarr-http-server/changes/README.md new file mode 100644 index 0000000000..80f0be782c --- /dev/null +++ b/packages/zarr-http-server/changes/README.md @@ -0,0 +1,25 @@ +Writing a changelog entry for `zarr-http-server` +--------------------------------------------- + +Fragments in **this** directory are released notes for the `zarr-http-server` +package only β€” kept separate from the parent zarr-python `changes/` +directory so a PR touching only `packages/zarr-http-server/` produces a +release note for this package only. + +Please put a new file in this directory named `xxxx..md`, where + +- `xxxx` is the pull request number associated with this entry +- `` is one of: + - feature + - bugfix + - doc + - removal + - misc + +Inside the file, please write a short description of what you have +changed, and how it impacts users of `zarr-http-server`. + +A `zarr-http-server` release runs `towncrier build` in `packages/zarr-http-server/`, +which consumes the fragments here and updates `CHANGELOG.md`. Fragments +that describe parent zarr-python changes (not the server package) +belong in the top-level `changes/` directory, not here. diff --git a/packages/zarr-http-server/docs/_static/favicon-96x96.png b/packages/zarr-http-server/docs/_static/favicon-96x96.png new file mode 100644 index 0000000000..e77977ccf4 Binary files /dev/null and b/packages/zarr-http-server/docs/_static/favicon-96x96.png differ diff --git a/packages/zarr-http-server/docs/_static/logo_bw.png b/packages/zarr-http-server/docs/_static/logo_bw.png new file mode 100644 index 0000000000..df1979d3cc Binary files /dev/null and b/packages/zarr-http-server/docs/_static/logo_bw.png differ diff --git a/packages/zarr-http-server/docs/api/index.md b/packages/zarr-http-server/docs/api/index.md new file mode 100644 index 0000000000..ce5d748b26 --- /dev/null +++ b/packages/zarr-http-server/docs/api/index.md @@ -0,0 +1,41 @@ +--- +title: API reference +--- + +# API reference + +Everything public is re-exported from the top-level `zarr_http_server` +namespace; the private `_serve` and `_keys` modules are implementation detail +and carry no compatibility guarantee. + +## Building an app + +::: zarr_http_server.store_app + +::: zarr_http_server.node_app + +## Running a server + +::: zarr_http_server.serve + +::: zarr_http_server.serve_background + +::: zarr_http_server.BackgroundServer + +## Configuration + +::: zarr_http_server.CorsOptions + +::: zarr_http_server.HTTPMethod + +::: zarr_http_server.ReadOnlyHTTPMethod + +::: zarr_http_server.READ_ONLY_HTTP_METHODS + +::: zarr_http_server.READ_WRITE_HTTP_METHODS + +::: zarr_http_server.AUTO_PORT + +::: zarr_http_server.DEFAULT_PORT + +::: zarr_http_server.DEFAULT_MAX_BODY_SIZE diff --git a/packages/zarr-http-server/docs/guide.md b/packages/zarr-http-server/docs/guide.md new file mode 100644 index 0000000000..d52d5b882d --- /dev/null +++ b/packages/zarr-http-server/docs/guide.md @@ -0,0 +1,393 @@ +--- +title: User guide +--- + +# User guide + +## Building an ASGI app + +[`store_app`][zarr_http_server.store_app] creates an ASGI app that exposes +every key in a store. Only point it at a store whose full contents are safe to +serve publicly β€” it grants read (and, if `PUT` is enabled, write) access to +everything the store contains, with no per-key filtering: + +```python +import zarr +from zarr_http_server import store_app + +store = zarr.storage.MemoryStore() +zarr.create_array(store, shape=(100, 100), chunks=(10, 10), dtype="float64") + +app = store_app(store) + +# Run with any ASGI server, e.g. Uvicorn: +# uvicorn my_module:app --host 0.0.0.0 --port 8000 +``` + +[`node_app`][zarr_http_server.node_app] creates an ASGI app that only serves +keys belonging to a specific `Array` or `Group`. Requests for keys outside the +node receive a 404, even if those keys exist in the underlying store: + +```python +import zarr +from zarr_http_server import node_app + +store = zarr.storage.MemoryStore() +root = zarr.open_group(store) +root.create_array("a", shape=(10,), dtype="int32") +root.create_array("b", shape=(20,), dtype="float64") + +# Only serve the array at "a" β€” requests for "b" will return 404. +app = node_app(root["a"]) +``` + +## Running the server + +Build an app, then run it. Either app works with either runner. + +[`serve`][zarr_http_server.serve] blocks until the server is stopped, which is +the shape for a script or a container entrypoint: + +```python +from zarr_http_server import serve, store_app + +serve(store_app(store), host="127.0.0.1", port=8000) +``` + +[`serve_background`][zarr_http_server.serve_background] instead starts the +server in a daemon thread and returns a +[`BackgroundServer`][zarr_http_server.BackgroundServer] as soon as the socket +is listening, so the caller can carry on. These are two functions rather than +one with a flag, because they differ in the only thing that matters at a call +site: whether control comes back. + +### Choosing a port + +Both default to `port="auto"`, which prefers port 8000 but falls back to any +free port if it is taken, reporting the result through `server.url` and +Uvicorn's startup line. An **explicit** port means the opposite β€” bind exactly +that or fail β€” because a caller who names one usually has a proxy or a +container port mapping expecting the server there, and silently moving would +break it while looking healthy. `port=0` keeps its usual meaning of "any free +port, no preference". + +### Reading back with a zarr client + +`BackgroundServer` is a context manager, so the server stops when the block +exits. The example below also *reads back* over HTTP, which is a client-side +concern: `zarr.open_array(server.url)` goes through `FsspecStore`, which needs +an HTTP-capable fsspec that `zarr-http-server` does not pull in +(`pip install "fsspec[http]"`). + +```python +import numpy as np +import zarr +from zarr.storage import MemoryStore + +from zarr_http_server import node_app, serve_background + +store = MemoryStore() +arr = zarr.create_array(store, shape=(100,), chunks=(10,), dtype="float64") +arr[:] = np.arange(100, dtype="float64") + +with serve_background(node_app(arr), host="127.0.0.1") as server: + remote = zarr.open_array(server.url, mode="r") + np.testing.assert_array_equal(remote[:], arr[:]) +# Server is shut down automatically when the block exits. +``` + +### Shutting down + +`BackgroundServer.shutdown()` β€” and leaving the `with` block β€” waits up to +`shutdown_timeout` seconds, 5 by default, for in-flight requests to finish +before forcing the server closed. It raises if the thread will not stop, so a +silent failure cannot leave you believing the port is free when it is not. + +```python +with serve_background(node_app(arr), shutdown_timeout=30) as server: + ... +``` + +## Serving several nodes + +Serving two arrays does not mean running two servers. Which approach fits +depends on where the arrays live. + +If they share a parent group, serve the parent β€” `node_app` recurses through +its members, so both are reachable under one port and node scoping still +applies to everything outside it: + +```python +server = serve_background(node_app(root)) +# -> /a/zarr.json, /a/c/0, /b/zarr.json, ... +``` + +If everything in the store is safe to expose, `store_app(store)` does the same +for the whole key space. + +Otherwise β€” arrays in *different* stores, or nodes that are not siblings β€” +`store_app` and `node_app` return plain Starlette apps, so mount them and run +the result: + +```python +from starlette.applications import Starlette +from starlette.routing import Mount + +from zarr_http_server import node_app, serve_background + +app = Starlette(routes=[ + Mount("/first", app=node_app(one)), + Mount("/second", app=node_app(other)), +]) +server = serve_background(app) +``` + +Each mount keeps its own validation, so a request under one cannot reach +another's data β€” `/first/../second/zarr.json` and its percent-encoded spellings +all return 404. + +Both runners take any ASGI app, so the split is clean: what an app *serves* +(`methods`, `cors_options`, `max_body_size`) is settled when the app is built, +while `serve` / `serve_background` only decide how it runs (`host`, `port`, +`shutdown_timeout`, `uvicorn_options`). + +## Serving from a notebook + +A notebook needs a server that outlives the cell that started it, so the `with` +form above is the wrong shape β€” it shuts the server down as soon as the block +ends. Start it, keep the handle, and stop it later: + +```python +# cell 1 β€” start +server = serve_background(node_app(array), host="127.0.0.1") +print(server.url) # e.g. http://127.0.0.1:54635 + +# cell 2..n β€” use it, across as many cells as you like +httpx.get(f"{server.url}/zarr.json") + +# last cell β€” stop +server.shutdown() +``` + +Two things make this comfortable in a kernel you re-run. `serve_background` +runs Uvicorn in a daemon thread with its own event loop, so it never touches +the kernel's loop and cannot block it. And its default `port="auto"` falls back +to a free port when 8000 is taken β€” re-running a start cell without stopping +the previous server is the classic notebook mistake, and a fixed port fails +there with *address already in use*. `server.url` reports the port actually +bound. + +If you forget to stop one, the thread is a daemon, so restarting the kernel +always clears it β€” and since each start takes a fresh port, a forgotten server +does not block the next one. + +[`examples/serve_notebook.ipynb`](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-http-server/examples/serve_notebook.ipynb) +is a runnable version of this. It is executed by the test suite, so it cannot +drift from the code. + +## Uvicorn configuration + +`serve` and `serve_background` name the options most callers need β€” `host`, +`port`, `shutdown_timeout` β€” and forward anything else to `uvicorn.Config` +through `uvicorn_options`, so nothing Uvicorn can do is out of reach: + +```python +server = serve_background( + store_app(store), + host="0.0.0.0", + port=8443, + uvicorn_options={ + "ssl_keyfile": "key.pem", + "ssl_certfile": "cert.pem", + "proxy_headers": True, + "forwarded_allow_ips": "10.0.0.0/8", + "log_level": "warning", + }, +) +``` + +Keys you pass are merged over the ones set for you, so they win. `server.url` +reflects the scheme actually in use (`https` when TLS is configured) and is +`None` when the server is not bound to a TCP host and port β€” a `uds` or `fd` +bind has no URL to report. + +## CORS + +Both app builders accept a [`CorsOptions`][zarr_http_server.CorsOptions] +parameter to enable +[CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) middleware for +browser-based clients: + +```python +from zarr_http_server import CorsOptions, store_app + +app = store_app( + store, + cors_options=CorsOptions( + allow_origins=["*"], + allow_methods=["GET"], + ), +) +``` + +`CorsOptions` carries every parameter Starlette's `CORSMiddleware` accepts β€” +`allow_headers`, `allow_credentials`, `allow_origin_regex`, +`allow_private_network`, `expose_headers` and `max_age` as well as the two +above β€” so configuring CORS never means reaching around this package. All keys +are optional. + +Two defaults differ from Starlette's, because the server knows things the +caller should not have to. It emits `Content-Range` on every ranged response, +which is *not* a CORS-safelisted response header, so `expose_headers` defaults +to `["Content-Range"]` β€” otherwise a browser client can read the bytes but not +learn which bytes it got. And it accepts a `Range` request header, so +`allow_headers` defaults to `["Range"]` β€” otherwise a preflight naming `Range` +is rejected. A key you supply replaces the default outright, so +`expose_headers=[]` means "expose nothing". + +`allow_methods` is checked against what the app actually serves: advertising a +method the route rejects raises `ValueError`, and `"*"` expands to what is +served rather than to every verb Starlette knows. + +## HTTP range requests + +The server supports the standard `Range` header for partial reads. The three +forms defined by [RFC 9110](https://httpwg.org/specs/rfc9110.html#field.range) +are supported: + +| Header | Meaning | +| ------------ | ------------------------ | +| `bytes=0-99` | First 100 bytes | +| `bytes=100-` | Everything from byte 100 | +| `bytes=-50` | Last 50 bytes | + +A successful range request returns HTTP 206 (Partial Content) with a +`Content-Range` header, including for suffix ranges β€” the server resolves +`bytes=-50` against the object's size so the response says which bytes it +carries. + +A range that is well-formed but names nothing readable β€” one lying wholly +beyond the end of the object, an inverted one such as `bytes=5-2`, or +`bytes=-0` β€” returns 416 (Range Not Satisfiable). A last-byte-position past the +end of the object is *not* in that category: per RFC 9110 Β§14.1.2 it is +clamped, so `bytes=0-999999` on a short object returns the whole thing. + +A `Range` header the server cannot use is **ignored** rather than refused, per +RFC 9110 Β§14.2: an unrecognized unit (`chars=0-7`), a multi-range request +(`bytes=0-7, 10-20`, which this server does not build multipart responses for), +or malformed syntax all return 200 with the full representation. + +## Read-only serving + +Read-only is the default. `store_app(store)` and `node_app(node)` accept `GET` +and `HEAD` and answer **405** to `PUT`, `POST`, `DELETE` and `PATCH` β€” no +argument is needed to get there. `HEAD` is served wherever `GET` is, as RFC +9110 Β§9.3.2 asks of every origin server, and is answered from the value's size +without transferring it. + +`POST` is not merely unrouted, it is unconfigurable: the accepted methods are +`GET`, `HEAD` and `PUT`, and asking for anything else raises `ValueError` when +the app is built. + +Two named sets let a call site state which it is, instead of leaving it to the +presence or absence of an argument: + +```python +from zarr_http_server import READ_ONLY_HTTP_METHODS, READ_WRITE_HTTP_METHODS, store_app + +app = store_app(store, methods=READ_ONLY_HTTP_METHODS) # GET, HEAD +app = store_app(store, methods=READ_WRITE_HTTP_METHODS) # GET, HEAD, PUT +``` + +The distinction also exists in the type domain. +[`ReadOnlyHTTPMethod`][zarr_http_server.ReadOnlyHTTPMethod] is a +`Literal["GET", "HEAD"]`, so a read-only set can be *declared* rather than +merely configured β€” a `frozenset[ReadOnlyHTTPMethod]` containing `"PUT"` is a +type error, not a runtime surprise: + +```python +from zarr_http_server import ReadOnlyHTTPMethod + +reads: frozenset[ReadOnlyHTTPMethod] = frozenset({"GET", "HEAD"}) # ok +reads = frozenset({"GET", "PUT"}) # type error +``` + +Both constants are derived from those Literals, so the runtime sets and the +static types cannot disagree about what the server serves. + +`READ_ONLY_HTTP_METHODS` is exactly the default, so passing it changes nothing +except that the intent is written down. The practical value is the other +direction: a writable app *must* name a method set, so `grep -r 'methods='` +finds every place that opts into writes. + +For a guarantee that does not depend on getting `methods` right, make the +*store* read-only. The store refuses writes itself, so no routing mistake β€” now +or in a later edit β€” can produce one: + +```python +app = store_app(store.with_read_only(True)) + +# For a node, open it read-only and node_app inherits that store: +app = node_app(zarr.open_array(store, mode="r")) +``` + +These two layers are independent, and the store is the stronger one: it holds +even if the HTTP layer is misconfigured. Asking for both at once β€” +`READ_WRITE_HTTP_METHODS` on a read-only store β€” is a contradiction that can +never succeed, so it raises `ValueError` at construction rather than turning +into a 403 for whichever client tries to write first. + +## Writes + +To enable writes, name a method set that includes `PUT`: + +```python +from zarr_http_server import READ_WRITE_HTTP_METHODS, store_app + +app = store_app(store, methods=READ_WRITE_HTTP_METHODS) +``` + +A `PUT` stores the request body at the given path and returns 204 (No Content). +Bodies are capped at +[`DEFAULT_MAX_BODY_SIZE`][zarr_http_server.DEFAULT_MAX_BODY_SIZE] (256 MiB) and +a larger one returns 413 (Content Too Large) β€” `Store.set` takes a whole +buffer, so an accepted body is held in memory in full. Raise or remove the cap +with `max_body_size`: + +```python +app = store_app(store, methods=READ_WRITE_HTTP_METHODS, max_body_size=None) +``` + +!!! danger "Writes through `store_app` are unvalidated" + + `store_app` exposes every key in the store, so `PUT` grants unrestricted + write access to all of it. It also does not *validate* keys, because it + proxies the raw key space and has no array semantics to check against: a + client that misspells a chunk key β€” `c/00/00` where zarr writes `c/0/0` β€” + gets a successful write to a key no reader will ever consult, so the data + is stored but invisible to anyone opening the array. + + `node_app` rejects such a key with 404, since it knows which node it is + serving and therefore which keys are real. If you are serving a zarr + hierarchy to clients you do not control and writes are enabled, prefer + `node_app`. + + Note also that a client that can write a node's metadata can change what + that node contains, and so what it will serve. + +## Examples + +Both live in +[`examples/`](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-http-server/examples) +and are executed by the test suite, so neither can drift from the code. + +`serve.py` creates an in-memory Zarr array, serves it, and fetches the +`zarr.json` metadata document and a raw chunk with `httpx`. It declares its own +dependencies inline, so uv installs them for you: + +```bash +uv run examples/serve.py +``` + +`serve_notebook.ipynb` is the notebook equivalent, showing how to start a +server in one cell and stop it in another. diff --git a/packages/zarr-http-server/docs/index.md b/packages/zarr-http-server/docs/index.md new file mode 100644 index 0000000000..271de6445e --- /dev/null +++ b/packages/zarr-http-server/docs/index.md @@ -0,0 +1,71 @@ +# zarr-http-server + +HTTP server for Zarr stores, arrays, and groups. + +`zarr-http-server` is developed in the +[zarr-python repository](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-http-server) +and released independently of `zarr` itself. Install it with: + +``` +pip install zarr-http-server +``` + +!!! warning "Experimental" + + This package is experimental. Its API may change or be removed at any + point. + +## What this is + +`zarr-http-server` exposes a Zarr `Store`, `Array`, or `Group` over HTTP via an +ASGI app, so any HTTP-capable client β€” including zarr-python itself, via +`FsspecStore` or `ObjectStore` β€” can read the data. The app is built on +[Starlette](https://www.starlette.io/) and can be run with any ASGI server; +the `serve` / `serve_background` helpers run it with +[Uvicorn](https://uvicorn.dev/). + +Building an app and running it are separate steps, and either app works with +either runner: + +- **Build** with [`store_app`][zarr_http_server.store_app] to serve every key + in a store, or [`node_app`][zarr_http_server.node_app] to serve only the keys + belonging to one `Array` or `Group` β€” requests for keys outside that node + return 404 even when those keys exist in the underlying store. +- **Run** with [`serve`][zarr_http_server.serve], which blocks, or + [`serve_background`][zarr_http_server.serve_background], which returns a + handle you can shut down later. + +Byte-range reads, configurable CORS headers, and a configurable set of allowed +HTTP methods are handled by the app. + +## Quick start + +```python +import zarr +from zarr_http_server import node_app, serve_background + +store = zarr.storage.MemoryStore() +array = zarr.create_array(store, shape=(100,), chunks=(10,), dtype="float64") + +with serve_background(node_app(array)) as server: + print(server.url) # e.g. http://127.0.0.1:8000 +``` + +Reads are all that is enabled by default: `GET` and `HEAD` are served, and +`PUT`, `POST`, `DELETE` and `PATCH` are answered with 405. + +!!! danger "Serving a whole store grants access to all of it" + + `store_app` applies no per-key filtering. Only point it at a store whose + full contents are safe to serve, and note that enabling `PUT` grants write + access to everything the store contains. See + [read-only serving](guide.md#read-only-serving) for the guarantees + available. + +## Next steps + +- [User guide](guide.md) β€” building apps, running them, byte ranges, CORS, + writes, notebooks, and Uvicorn configuration +- [API reference](api/index.md) +- [Changelog](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-http-server/CHANGELOG.md) +- [License (MIT)](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-http-server/LICENSE.txt) diff --git a/packages/zarr-http-server/examples/serve.py b/packages/zarr-http-server/examples/serve.py new file mode 100644 index 0000000000..45caa9ea67 --- /dev/null +++ b/packages/zarr-http-server/examples/serve.py @@ -0,0 +1,45 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "zarr-http-server @ git+https://github.com/zarr-developers/zarr-python.git@main#subdirectory=packages/zarr-http-server", +# "httpx", +# ] +# /// +""" +Serve a Zarr array over HTTP and fetch its metadata and chunks. + +This example creates an in-memory array, serves it in a background thread, +then uses ``httpx`` to request the ``zarr.json`` metadata document and a raw +chunk. +""" + +import json + +import httpx +import numpy as np +import zarr +from zarr.storage import MemoryStore + +from zarr_http_server import node_app, serve_background + +# -- create an array -------------------------------------------------------- +store = MemoryStore() +data = np.arange(1000, dtype="uint8").reshape(10, 10, 10) +# no compression +arr = zarr.create_array(store, data=data, chunks=(5, 5, 5), write_data=True, compressors=None) + +# -- serve it in the background --------------------------------------------- +# port=0 asks the OS for a free port, so running this twice -- or running it +# while something else holds 8000 -- works. `server.url` reports what it bound. +with serve_background(node_app(arr), host="127.0.0.1") as server: + # -- fetch metadata ------------------------------------------------------ + resp = httpx.get(f"{server.url}/zarr.json") + assert resp.status_code == 200 + meta = resp.json() + print("zarr.json:") + print(json.dumps(meta, indent=2)) + + # -- fetch a raw chunk --------------------------------------------------- + resp = httpx.get(f"{server.url}/c/0/0/0") + assert resp.status_code == 200 + print(f"\nchunk c/0/0/0: {len(resp.content)} bytes") diff --git a/packages/zarr-http-server/examples/serve_notebook.ipynb b/packages/zarr-http-server/examples/serve_notebook.ipynb new file mode 100644 index 0000000000..e751a526c1 --- /dev/null +++ b/packages/zarr-http-server/examples/serve_notebook.ipynb @@ -0,0 +1,213 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "6cb56289", + "metadata": {}, + "source": [ + "# Serving a Zarr array from a notebook\n", + "\n", + "A notebook needs a server that outlives the cell that started it, which is the\n", + "one thing the `with serve_background(...)` form in the README cannot give\n", + "that shuts the server down as soon as the block ends.\n", + "\n", + "The notebook pattern is instead:\n", + "\n", + "1. start with `serve_background` and keep the handle,\n", + "2. use the server across as many cells as you like,\n", + "3. `shutdown()` when you are done.\n", + "\n", + "Two details make this comfortable in a kernel you re-run:\n", + "\n", + "- **`serve_background`** runs uvicorn in a daemon thread with its own event\n", + " loop, so it never touches the kernel's loop and cannot block it.\n", + "- **`port=\"auto\"`**, its default, prefers port 8000 but takes a free one if\n", + " it is busy. Re-running a start cell without stopping the previous server is\n", + " the classic notebook mistake, and a fixed port fails there with *address\n", + " already in use*. `server.url` reports the port actually bound." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e2e217fa", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import zarr\n", + "from zarr.storage import MemoryStore\n", + "\n", + "from zarr_http_server import node_app, serve_background\n", + "\n", + "store = MemoryStore()\n", + "array = zarr.create_array(\n", + " store,\n", + " data=np.arange(1000, dtype=\"uint8\").reshape(10, 10, 10),\n", + " chunks=(5, 5, 5),\n", + " compressors=None,\n", + " write_data=True,\n", + ")\n", + "array.info" + ] + }, + { + "cell_type": "markdown", + "id": "35752272", + "metadata": {}, + "source": [ + "## Start\n", + "\n", + "`serve_background` returns a `BackgroundServer` as soon as the socket is\n", + "so the next cell can use it immediately." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b5010cdb", + "metadata": {}, + "outputs": [], + "source": [ + "server = serve_background(node_app(array), host=\"127.0.0.1\")\n", + "\n", + "print(f\"serving at {server.url}\")\n", + "assert server.url is not None" + ] + }, + { + "cell_type": "markdown", + "id": "d4e1f8d6", + "metadata": {}, + "source": [ + "## Use it\n", + "\n", + "The server is alive across cells now. Anything that speaks HTTP can read from\n", + "it -- here `httpx`, but a browser or another zarr client works the same way.\n", + "\n", + "(With `fsspec[http]` installed you can also do\n", + "`zarr.open_array(server.url, mode=\"r\")` to read the array back through zarr\n", + "itself.)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5ac501fa", + "metadata": {}, + "outputs": [], + "source": [ + "import httpx\n", + "\n", + "metadata = httpx.get(f\"{server.url}/zarr.json\", timeout=30)\n", + "print(metadata.status_code, metadata.headers[\"content-type\"])\n", + "assert metadata.status_code == 200\n", + "assert metadata.json()[\"shape\"] == [10, 10, 10]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c7a94eff", + "metadata": {}, + "outputs": [], + "source": [ + "chunk = httpx.get(f\"{server.url}/c/0/0/0\", timeout=30)\n", + "print(f\"chunk c/0/0/0: {len(chunk.content)} bytes\")\n", + "assert chunk.status_code == 200\n", + "\n", + "# Byte ranges work too, and say which bytes came back.\n", + "part = httpx.get(f\"{server.url}/c/0/0/0\", headers={\"Range\": \"bytes=0-9\"}, timeout=30)\n", + "print(part.status_code, part.headers[\"content-range\"], part.content)\n", + "assert part.status_code == 206\n", + "assert part.content == chunk.content[:10]" + ] + }, + { + "cell_type": "markdown", + "id": "c8fd3ea2", + "metadata": {}, + "source": [ + "## Writes are off unless you ask\n", + "\n", + "The default is read-only, so a stray `PUT` from a notebook cell -- or from\n", + "anyone else who can reach the port -- is refused." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2f6bee45", + "metadata": {}, + "outputs": [], + "source": [ + "refused = httpx.put(f\"{server.url}/c/0/0/0\", content=b\"nope\", timeout=30)\n", + "print(\"PUT ->\", refused.status_code)\n", + "assert refused.status_code == 405" + ] + }, + { + "cell_type": "markdown", + "id": "74f4bebc", + "metadata": {}, + "source": [ + "## Stop\n", + "\n", + "`shutdown()` waits for in-flight requests, then forces the server closed. It\n", + "raises if the thread will not stop, so a silent failure cannot leave you\n", + "believing the port is free when it is not." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "53a3e8d4", + "metadata": {}, + "outputs": [], + "source": [ + "server.shutdown()\n", + "\n", + "# The port really is closed now.\n", + "try:\n", + " httpx.get(f\"{server.url}/zarr.json\", timeout=5)\n", + "except httpx.HTTPError as exc:\n", + " print(f\"as expected, no longer serving: {type(exc).__name__}\")\n", + "else:\n", + " raise AssertionError(\"server still responding after shutdown\")" + ] + }, + { + "cell_type": "markdown", + "id": "8a7742e0", + "metadata": {}, + "source": [ + "## If you forget to stop one\n", + "\n", + "The server thread is a daemon, so it dies with the kernel -- restarting the\n", + "kernel always clears it. Because `port=0` picks a fresh port each time, a\n", + "forgotten server does not block the next one either; it just holds a port\n", + "until the kernel exits.\n", + "\n", + "If you want the shutdown tied to a block rather than a cell, the context\n", + "manager form still works inside a single cell:\n", + "\n", + "```python\n", + "with serve_background(node_app(array)) as server:\n", + " ... # everything must happen in this cell\n", + "```" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/packages/zarr-http-server/justfile b/packages/zarr-http-server/justfile new file mode 100644 index 0000000000..d65b1b53b7 --- /dev/null +++ b/packages/zarr-http-server/justfile @@ -0,0 +1,68 @@ +# Development verbs for the zarr-http-server package. Recipes run with this +# directory as the working directory regardless of where `just` is invoked. +# +# CI calls these recipes rather than repeating their commands, so a green run +# in .github/workflows/zarr-http-server.yml means the same thing as a green +# `just check` here. + +# Pinned to the ruff that .pre-commit-config.yaml uses, so this and the +# pre-commit gate enforce one standard. An unpinned `uvx ruff` floats to the +# newest release: when ruff 0.16 began selecting BLE001 under the root +# config's `B` prefix, this job failed on rules the pinned ruff never enforced, +# with no code change to blame. Bump alongside the pre-commit rev. +ruff_version := "0.16.0" + +# List available recipes +default: + @just --list + +# The `examples` group carries the deps the README examples need, so the test +# that reads a served array back with a zarr client runs here instead of +# silently skipping. +# Run the test suite; extra args are passed to pytest +test *args: + uv run --group test --group examples pytest tests {{ args }} + +# Lint the package sources and tests +lint: + uvx ruff@{{ ruff_version }} check . + +# This package type-checks with mypy (see [tool.mypy] in pyproject.toml) +# rather than the pyright used by the other packages under packages/. +# Type-check the package sources +typecheck: + uv run --group test --with mypy mypy src + +# Run everything CI runs for this package +check: lint typecheck test docs-check + +# Preview the changelog that the next release would generate +changelog-draft: + uvx towncrier build --draft --version Unreleased + +# Build this package's documentation site, warnings as errors +docs-check: + env DISABLE_MKDOCS_2_WARNING=true uv run --group docs mkdocs build --strict + +# With no argument, uses port 8000 if free, otherwise an ephemeral free port; +# an explicitly requested port is used as-is so a conflict fails loudly. +# Serve this package's documentation site +docs-serve port="": + #!/usr/bin/env bash + set -euo pipefail + port="{{ port }}" + if [ -z "$port" ]; then + port=$(uv run --group docs python -c ' + import socket + s = socket.socket() + try: + s.bind(("127.0.0.1", 8000)) + except OSError: + s.close() + s = socket.socket() + s.bind(("127.0.0.1", 0)) + print(s.getsockname()[1]) + s.close() + ') + fi + exec env DISABLE_MKDOCS_2_WARNING=true uv run --group docs mkdocs serve -a "localhost:$port" diff --git a/packages/zarr-http-server/mkdocs.yml b/packages/zarr-http-server/mkdocs.yml new file mode 100644 index 0000000000..7ebfe8c017 --- /dev/null +++ b/packages/zarr-http-server/mkdocs.yml @@ -0,0 +1,100 @@ +site_name: zarr-http-server +# The package lives in the zarr-python monorepo; point the header source +# widget at the package directory rather than the repository root. +repo_name: zarr-python/packages/zarr-http-server +repo_url: https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-http-server +# Absolute because mkdocs would otherwise append this to repo_url's subpath. +edit_uri: https://github.com/zarr-developers/zarr-python/edit/main/packages/zarr-http-server/docs/ +site_description: HTTP server for Zarr stores, arrays, and groups. +site_author: Davis Bennett +site_url: !ENV [READTHEDOCS_CANONICAL_URL, 'https://zarr-http-server.readthedocs.io/'] +docs_dir: docs +use_directory_urls: true + +nav: + - index.md + - guide.md + - API Reference: + - api/index.md + - Changelog: https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-http-server/CHANGELOG.md + +watch: + - src + +theme: + language: en + name: material + logo: _static/logo_bw.png + favicon: _static/favicon-96x96.png + + palette: + # Light mode + - media: "(prefers-color-scheme: light)" + scheme: default + toggle: + icon: material/brightness-7 + name: Switch to dark mode + + # Dark mode + - media: "(prefers-color-scheme: dark)" + scheme: slate + toggle: + icon: material/brightness-4 + name: Switch to light mode + + font: + text: Roboto + code: Roboto Mono + + features: + - content.code.annotate + - content.code.copy + - navigation.indexes + - navigation.instant + - navigation.tracking + - search.suggest + - search.share + +plugins: + - autorefs + - search + - mkdocstrings: + enable_inventory: true + handlers: + python: + paths: [src] + options: + allow_inspection: true + docstring_section_style: list + docstring_style: numpy + inherited_members: true + line_length: 60 + separate_signature: true + show_root_heading: true + show_signature_annotations: true + show_source: true + show_symbol_type_toc: true + signature_crossrefs: true + show_if_no_docstring: true + extensions: + - griffe_inherited_docstrings + + inventories: + - https://docs.python.org/3/objects.inv + - https://zarr.readthedocs.io/en/stable/objects.inv + +markdown_extensions: + - admonition + - attr_list + - def_list + - footnotes + - md_in_html + - pymdownx.details + - pymdownx.superfences + - toc: + permalink: true + - pymdownx.highlight: + anchor_linenums: true + line_spans: __span + pygments_lang_class: true + - pymdownx.inlinehilite diff --git a/packages/zarr-http-server/pyproject.toml b/packages/zarr-http-server/pyproject.toml new file mode 100644 index 0000000000..10db7ae496 --- /dev/null +++ b/packages/zarr-http-server/pyproject.toml @@ -0,0 +1,163 @@ +[build-system] +requires = ["hatchling>=1.29.0", "hatch-vcs"] +build-backend = "hatchling.build" + +[project] +name = "zarr-http-server" +dynamic = ["version"] +description = "HTTP server for Zarr stores, arrays, and groups." +readme = "README.md" +requires-python = ">=3.12" +license = "MIT" +license-files = ["LICENSE.txt"] +authors = [ + { name = "Davis Bennett", email = "davis.v.bennett@gmail.com" }, +] +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Intended Audience :: Information Technology", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Scientific/Engineering", + "Topic :: Internet :: WWW/HTTP :: HTTP Servers", + "Typing :: Typed", +] +keywords = ["zarr", "http", "server", "asgi"] +dependencies = [ + "zarr>=3.1", + "starlette>=1.0", + "uvicorn>=0.29", +] + +[project.urls] +Homepage = "https://github.com/zarr-developers/zarr-python" +Source = "https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-http-server" +Issues = "https://github.com/zarr-developers/zarr-python/issues" +Changelog = "https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-http-server/CHANGELOG.md" +Documentation = "https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-http-server/README.md" + +[dependency-groups] +test = [ + "pytest", + "httpx", + "httpx2", + "hypothesis", + # Executing examples/serve_notebook.ipynb in the suite: nbformat reads it, + # nbclient runs it, ipykernel is the kernel it runs in. + "nbformat", + "nbclient", + "ipykernel", +] +examples = [ + # Optional dependencies to run the README examples. Reading a served + # array back with `zarr.open_array(url)` goes through FsspecStore, which + # needs an HTTP-capable fsspec; `examples/serve.py` uses httpx. + "fsspec[http]", + "httpx", +] +docs = [ + # Pins match the zarr-python docs environment in the repo-root + # pyproject.toml so the two sites render with the same toolchain. + "mkdocs-material==9.7.7", + "mkdocs==1.6.1", + "mkdocstrings==1.0.6", + "mkdocstrings-python==2.0.5", + "griffe-inherited-docstrings==1.1.3", + # mkdocstrings uses ruff to format rendered signatures + "ruff==0.16.0", +] + +# Dev-only: resolve zarr from the repo root so package tests run against +# in-repo zarr. Affects uv resolution only, not published metadata. +[tool.uv.sources] +zarr = { path = "../..", editable = true } + +[tool.hatch.version] +source = "vcs" +tag-pattern = '^zarr_http_server-v(?P.+)$' +# `git_describe_command` ensures we get the zarr_http_server tags instead of latest. +# `local_scheme` strips the git commit info so the appending info is just a counter from latest tag. +# test-pypi doesn't accept git commit info in tags, and the count should be enough to distinguish unique runs. +raw-options = { root = "../..", git_describe_command = "git describe --dirty --tags --long --match zarr_http_server-v*", local_scheme = "no-local-version" } + +[tool.hatch.build.targets.wheel] +packages = ["src/zarr_http_server"] + +# An allowlist, so nothing that merely happens to sit in the package directory +# β€” a scratch script, a stray notebook β€” can ride along in a release. With no +# sdist section at all hatchling defaults to "everything not gitignored", which +# is a blocklist by another name. The list keeps an sdist self-testing: +# `tests/test_examples.py` runs `examples/serve.py` and executes every cell of +# `examples/serve_notebook.ipynb`, so those are part of the suite rather than +# decoration, and `/docs` plus `/mkdocs.yml` are a self-contained site. +# `changes/` and `.readthedocs.yaml` are deliberately absent: towncrier +# fragments are consumed into `CHANGELOG.md` at release time, and the RTD +# config only means anything in the repository. `pyproject.toml`, `README.md` +# and `LICENSE.txt` are added by hatchling itself. +[tool.hatch.build.targets.sdist] +include = [ + "/src", + "/tests", + "/docs", + "/examples", + "/mkdocs.yml", + "/justfile", + "/CHANGELOG.md", +] + +[tool.ruff] +extend = "../../pyproject.toml" +target-version = "py312" + +[tool.pytest.ini_options] +minversion = "7" +testpaths = ["tests"] +xfail_strict = true +addopts = ["-ra", "--strict-config", "--strict-markers"] +filterwarnings = [ + "error", +] + +[tool.mypy] +files = ["src"] +python_version = "3.12" +ignore_missing_imports = true +namespace_packages = false +pretty = true +show_error_code_links = true +show_error_context = true +strict = true +warn_unreachable = true +enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool", "truthy-iterable"] + +[tool.numpydoc_validation] +# Mirrors the root zarr-python config so moved docstrings (written for that +# config) don't trip stricter defaults just because this package has its own +# pyproject.toml. See https://numpydoc.readthedocs.io/en/latest/validation.html#built-in-validation-checks +checks = [ + "GL10", + "SS04", + "PR02", + "PR03", + "PR05", + "PR06", +] + +[tool.towncrier] +# Fragments for this package live alongside the package source, separate +# from the parent zarr-python `changes/` directory, so a PR touching only +# `packages/zarr-http-server/` produces a release note for this package only. +directory = "changes" +filename = "CHANGELOG.md" +package = "zarr_http_server" +underlines = ["", "", ""] +title_format = "## {version} ({project_date})" +issue_format = "[#{issue}](https://github.com/zarr-developers/zarr-python/issues/{issue})" +start_string = "\n" diff --git a/packages/zarr-http-server/src/zarr_http_server/__init__.py b/packages/zarr-http-server/src/zarr_http_server/__init__.py new file mode 100644 index 0000000000..4f4fbd22f8 --- /dev/null +++ b/packages/zarr-http-server/src/zarr_http_server/__init__.py @@ -0,0 +1,38 @@ +"""Zarr-http-server: HTTP server for Zarr stores, arrays, and groups.""" + +from importlib.metadata import version + +from zarr_http_server._serve import ( + AUTO_PORT, + DEFAULT_MAX_BODY_SIZE, + DEFAULT_PORT, + READ_ONLY_HTTP_METHODS, + READ_WRITE_HTTP_METHODS, + BackgroundServer, + CorsOptions, + HTTPMethod, + ReadOnlyHTTPMethod, + node_app, + serve, + serve_background, + store_app, +) + +__version__ = version("zarr-http-server") + +__all__ = [ + "AUTO_PORT", + "DEFAULT_MAX_BODY_SIZE", + "DEFAULT_PORT", + "READ_ONLY_HTTP_METHODS", + "READ_WRITE_HTTP_METHODS", + "BackgroundServer", + "CorsOptions", + "HTTPMethod", + "ReadOnlyHTTPMethod", + "__version__", + "node_app", + "serve", + "serve_background", + "store_app", +] diff --git a/packages/zarr-http-server/src/zarr_http_server/_keys.py b/packages/zarr-http-server/src/zarr_http_server/_keys.py new file mode 100644 index 0000000000..e468cd066d --- /dev/null +++ b/packages/zarr-http-server/src/zarr_http_server/_keys.py @@ -0,0 +1,218 @@ +"""Utilities for determining the set of valid store keys for zarr nodes. + +A zarr node (array or group) implicitly defines a subset of keys in the +underlying store. For an **array** the valid keys are: + +* metadata documents (``zarr.json`` for v3, ``.zarray`` / ``.zattrs`` for v2) +* chunk (or shard) keys whose decoded coordinates fall within the storage grid + +For a **group** the valid keys are: + +* its own metadata documents +* any path ``/`` where ```` is a direct member and + ```` is recursively valid for that child +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +ZARR_JSON = "zarr.json" +ZARRAY_JSON = ".zarray" +ZGROUP_JSON = ".zgroup" +ZATTRS_JSON = ".zattrs" +ZMETADATA_V2_JSON = ".zmetadata" + +if TYPE_CHECKING: + from zarr import Array, Group + +_ARRAY_METADATA_KEYS_V3 = frozenset({ZARR_JSON}) +_ARRAY_METADATA_KEYS_V2 = frozenset({ZARRAY_JSON, ZATTRS_JSON}) +_GROUP_METADATA_KEYS_V3 = frozenset({ZARR_JSON}) +_GROUP_METADATA_KEYS_V2 = frozenset({ZGROUP_JSON, ZATTRS_JSON, ZMETADATA_V2_JSON}) + + +def array_metadata_keys(zarr_format: int) -> frozenset[str]: + """Return the metadata key basenames an array owns, for a zarr format. + + Parameters + ---------- + zarr_format : int + The zarr format version (2 or 3). + + Returns + ------- + frozenset of str + """ + if zarr_format == 3: + return _ARRAY_METADATA_KEYS_V3 + return _ARRAY_METADATA_KEYS_V2 + + +def group_metadata_keys(zarr_format: int) -> frozenset[str]: + """Return the metadata key basenames a group owns, for a zarr format. + + Parameters + ---------- + zarr_format : int + The zarr format version (2 or 3). + + Returns + ------- + frozenset of str + """ + if zarr_format == 3: + return _GROUP_METADATA_KEYS_V3 + return _GROUP_METADATA_KEYS_V2 + + +def decode_chunk_key(array: Array[Any], key: str) -> tuple[int, ...] | None: + """Try to decode *key* into chunk coordinates for *array*. + + Parameters + ---------- + array : Array + The array whose chunk key encoding should be used. + key : str + The candidate chunk key string. + + Returns + ------- + tuple of int, or None + The decoded coordinates, or ``None`` if *key* is not a valid chunk key. + """ + try: + if array.metadata.zarr_format == 2: + coords = tuple(int(p) for p in key.split(array.metadata.dimension_separator)) + # A 0-d v2 array holds its single chunk under "0", which decodes + # to a 1-tuple that no 0-d grid could match. + if len(array.shape) == 0: + return () if coords == (0,) else None + return coords + + # Ask zarr rather than predicting it: the encoding owns its own + # grammar, so a new or third-party chunk key encoding decodes here + # without this package knowing anything about it. + return array.metadata.chunk_key_encoding.decode_chunk_key(key) + except (ValueError, TypeError, NotImplementedError): + return None + + +def _shard_grid_shape(array: Array[Any]) -> tuple[int, ...]: + """Shape of the shard grid, falling back to the chunk grid when unsharded.""" + shard_shape = array.shards if array.shards is not None else array.chunks + return tuple(-(-s // c) for s, c in zip(array.shape, shard_shape, strict=True)) + + +def is_valid_chunk_key(array: Array[Any], key: str) -> bool: + """Check whether *key* is a valid chunk key for *array*. + + Decodes the key, checks that the resulting coordinates fall within the + storage grid (shard grid if sharding is used, chunk grid otherwise), and + requires the key to be spelled exactly as zarr itself would spell it. + + That last check is what makes the accepted key set equal to the set of + keys zarr can actually read. Decoding alone is lenient -- `int` accepts + leading zeros, a leading `+`/`-`, surrounding whitespace, underscore + separators, and non-ASCII decimal digits -- so `c/00/00` and `c/0/0` + decode to the same coordinates while naming *different* store keys. A + write to the non-canonical spelling would be stored under a key no reader + ever looks up: the client sees success and the data is invisible. + + Parameters + ---------- + array : Array + The array to validate against. + key : str + The candidate chunk key string. + + Returns + ------- + bool + """ + coords = decode_chunk_key(array, key) + if coords is None: + return False + grid = _shard_grid_shape(array) + if len(coords) != len(grid): + return False + if not all(0 <= c < g for c, g in zip(coords, grid, strict=True)): + return False + return array.metadata.encode_chunk_key(coords) == key + + +def is_valid_array_key(array: Array[Any], key: str) -> bool: + """Check whether *key* is a valid store key for *array*. + + Valid keys are metadata documents and chunk keys. + + Parameters + ---------- + array : Array + The array to validate against. + key : str + The candidate key, relative to the array's root. + + Returns + ------- + bool + """ + if key in array_metadata_keys(array.metadata.zarr_format): + return True + return is_valid_chunk_key(array, key) + + +def is_valid_node_key(node: Array[Any] | Group, key: str) -> bool: + """Check whether *key* is a valid store key relative to *node*. + + For an ``Array``, valid keys are metadata documents and chunk keys. + + For a ``Group``, valid keys are the group's own metadata documents, or + a path of the form ``/`` where ```` is a direct + member and ```` is recursively valid for that child. + + Parameters + ---------- + node : Array or Group + The zarr node to validate against. + key : str + The candidate key, relative to the node's root. + + Returns + ------- + bool + """ + from zarr import Array + + if isinstance(node, Array): + return is_valid_array_key(node, key) + + # Group + if key in group_metadata_keys(node.metadata.zarr_format): + return True + + # Try to match the first path component against a child member. + if "/" in key: + child_name, remainder = key.split("/", 1) + else: + # A bare name with no slash can't be a valid group-level key β€” + # groups contain children (which have subkeys), not bare keys. + return False + + try: + child = node[child_name] + except KeyError: + # There is no such member, so no key beneath it can be valid. + # + # Only a missing name is caught here. Anything else -- an I/O error + # reading the child's metadata, unparsable JSON, a codec from a + # plugin this process lacks -- means the key could not be *judged*, + # which is not the same as judging it absent. Reporting those as 404 + # would be a lie with teeth: under the v3 spec an absent chunk is an + # uninitialized one, so a correct reader answers a 404 by silently + # substituting the array's fill value over data that exists. Letting + # them propagate surfaces a 500, which is the honest answer and the + # one a client cannot mistake for data. + return False + + return is_valid_node_key(child, remainder) diff --git a/packages/zarr-http-server/src/zarr_http_server/_serve.py b/packages/zarr-http-server/src/zarr_http_server/_serve.py new file mode 100644 index 0000000000..dce1df6b12 --- /dev/null +++ b/packages/zarr-http-server/src/zarr_http_server/_serve.py @@ -0,0 +1,1170 @@ +from __future__ import annotations + +import asyncio +import errno +import logging +import ntpath +import socket +import sys +import threading +import time +from enum import Enum, auto +from functools import partial +from typing import TYPE_CHECKING, Any, Literal, Self, TypedDict, cast, get_args + +from zarr.abc.store import OffsetByteRequest, RangeByteRequest, SuffixByteRequest +from zarr.buffer import cpu + +from zarr_http_server._keys import array_metadata_keys, group_metadata_keys, is_valid_node_key + +if TYPE_CHECKING: + from collections.abc import Mapping + from collections.abc import Set as AbstractSet + + import uvicorn + from starlette.applications import Starlette + from starlette.requests import Request + from starlette.responses import Response + from zarr import Array, Group + from zarr.abc.store import ByteRequest, Store + +__all__ = [ + "AUTO_PORT", + "DEFAULT_MAX_BODY_SIZE", + "DEFAULT_PORT", + "READ_ONLY_HTTP_METHODS", + "READ_WRITE_HTTP_METHODS", + "BackgroundServer", + "CorsOptions", + "HTTPMethod", + "ReadOnlyHTTPMethod", + "node_app", + "serve", + "serve_background", + "store_app", +] + + +class CorsOptions(TypedDict, total=False): + """Options forwarded to Starlette's `CORSMiddleware`. + + Every parameter the middleware accepts appears here, so configuring CORS + never requires reaching around this package. Keys left out fall back to + the defaults described below; a key that is present is used verbatim, + including an empty list. + + Two defaults differ from Starlette's own, because this server knows + something its caller should not have to. It emits `Content-Range` on + every ranged response, which is *not* a CORS-safelisted response header -- + with Starlette's empty `expose_headers` a browser client can read the + bytes but not learn which bytes it got. And it accepts a `Range` request + header, which Starlette's empty `allow_headers` would reject at preflight. + + * `expose_headers` defaults to `["Content-Range"]` + * `allow_headers` defaults to `["Range"]` + + Everything else defaults to the middleware's own value: no origins, `GET` + only, no credentials, no origin regex, no private-network access, and a + 600-second preflight cache. + """ + + allow_origins: list[str] + allow_methods: list[str] + allow_headers: list[str] + allow_credentials: bool + allow_origin_regex: str | None + allow_private_network: bool + expose_headers: list[str] + max_age: int + + +_CORS_DEFAULTS: CorsOptions = { + "expose_headers": ["Content-Range"], + "allow_headers": ["Range"], +} + + +ReadOnlyHTTPMethod = Literal["GET", "HEAD"] +"""An HTTP method that cannot modify the store. + +Distinguished from `HTTPMethod` in the type domain, not only at runtime, so a +read-only interface can be *declared* rather than merely configured: a +parameter annotated `AbstractSet[ReadOnlyHTTPMethod]` cannot be handed `"PUT"` +without a type error, whatever the value turns out to be at runtime. + +`HEAD` belongs here because Starlette routes it wherever `GET` goes, which is +what RFC 9110 Β§9.3.2 asks of an origin server. It is answered from the value's +size rather than by building and discarding a body. +""" + +_WriteHTTPMethod = Literal["PUT"] +"""An HTTP method that modifies the store. + +Private because nothing needs to name "the write methods" on its own -- it +exists so `HTTPMethod` can be defined as the union rather than as a third +hand-written list of the same strings. +""" + +HTTPMethod = ReadOnlyHTTPMethod | _WriteHTTPMethod +"""An HTTP method this server implements. + +`GET` and `HEAD` read a key; `PUT` writes one. Other verbs are not accepted: +the handler has no behavior for them, so serving them would silently answer +as if they were `GET`. +""" + +# Derived from the types above rather than restated, so the runtime sets and +# the static types cannot disagree about what this server serves. Adding a +# method to a Literal is then the only edit needed. +READ_ONLY_HTTP_METHODS: frozenset[ReadOnlyHTTPMethod] = frozenset(get_args(ReadOnlyHTTPMethod)) +"""Methods that only read. The default for every app in this package. + +Naming the set makes a read-only deployment say so at the call site, rather +than being the absence of an argument: + + store_app(store, methods=READ_ONLY_HTTP_METHODS) + +Typed as a set of `ReadOnlyHTTPMethod`, so a caller building on it keeps the +static guarantee: adding `"PUT"` to a `frozenset[ReadOnlyHTTPMethod]` is a +type error, not a runtime surprise. + +The stronger guarantee is a read-only store, which holds however `methods` is +configured -- see `store.with_read_only(True)`. +""" + +READ_WRITE_HTTP_METHODS: frozenset[HTTPMethod] = frozenset( + get_args(ReadOnlyHTTPMethod) + get_args(_WriteHTTPMethod) +) +"""Methods that read and write. Serving these grants clients write access. + +Every writable app must name a method set, so this constant is also what makes +writable deployments findable: grepping for `READ_WRITE_HTTP_METHODS` (or for +`methods=` generally) turns up every place that opts in. +""" + +_SUPPORTED_METHODS: frozenset[str] = READ_WRITE_HTTP_METHODS + +_LOGGER = logging.getLogger("uvicorn.error") +"""uvicorn's own logger, so a port fallback appears alongside its startup lines.""" + +DEFAULT_PORT = 8000 +"""Port tried first when `port="auto"`.""" + +AUTO_PORT: Literal["auto"] = "auto" +"""Sentinel for `port`: prefer `DEFAULT_PORT`, but settle for any free port. + +An explicit port is a requirement -- it binds that port or fails -- because a +caller who names one usually has something else expecting the server there. +`"auto"` says the opposite: no particular port is needed, so a collision +should not stop the server from starting. `port=0` keeps its usual meaning of +"any free port", with no preference. +""" + +_STARTUP_TIMEOUT = 5.0 +"""Seconds to wait for a background server to report that it is listening.""" + +_STARTUP_ABANDON_TIMEOUT = 5.0 +"""Seconds to wait for a server that failed to start to stop again.""" + +_SHUTDOWN_JOIN_MARGIN = 1.0 +"""Seconds to wait beyond uvicorn's graceful bound before forcing shutdown. + +uvicorn spends a fixed ~0.2s tearing down (a 0.1s loop tick plus a 0.1s +sleep) before its own `timeout_graceful_shutdown` wait begins, so a join that +merely equals that bound is guaranteed to expire first and escalate to +`force_exit` -- which makes uvicorn skip ASGI lifespan shutdown. +""" + +DEFAULT_MAX_BODY_SIZE = 256 * 1024 * 1024 +"""Default cap on a `PUT` body, in bytes. + +`Store.set` takes a whole `Buffer`, so an accepted body is held in memory in +full; the body is read incrementally and abandoned once it passes this cap, +so one request cannot size the server's memory use. Pass +`max_body_size=None` to lift the cap and read the body whole. +""" + + +class BackgroundServer: + """A running background HTTP server that can be used as a context manager. + + Wraps a ``uvicorn.Server`` running in a daemon thread. When used as a + context manager the server is shut down automatically on exit. + + Parameters + ---------- + server : uvicorn.Server + The running uvicorn server instance. + thread : threading.Thread + The daemon thread running the server. + host : str or None + The host the server was asked to bind, or ``None`` when it is not + listening on a TCP socket. + port : int or None + The port actually bound, or ``None`` when the server is not listening + on a TCP socket. + scheme : str, optional + URL scheme the server is reachable over. Defaults to ``"http"``. + shutdown_timeout : int, optional + Seconds to wait for in-flight requests to finish gracefully during + :meth:`shutdown` before forcing the server closed. Defaults to ``5``. + + Examples + -------- + >>> with serve_background(node_app(arr)) as server: # doctest: +SKIP + ... print(f"Listening on {server.host}:{server.port}") + ... # server is shut down when the block exits + """ + + def __init__( + self, + server: uvicorn.Server, + thread: threading.Thread, + *, + host: str | None, + port: int | None, + scheme: str = "http", + shutdown_timeout: int = 5, + ) -> None: + self._server = server + self._thread = thread + self.host = host + self.port = port + self.scheme = scheme + self._shutdown_timeout = shutdown_timeout + + @property + def url(self) -> str | None: + """The base URL of the running server. + + ``None`` when the server is not listening on a TCP socket -- a unix + socket or an inherited file descriptor has no host and port, and + inventing one would be a URL that connects to nothing. + """ + if self.host is None or self.port is None: + return None + return f"{self.scheme}://{self.host}:{self.port}" + + def shutdown(self) -> None: + """Signal the server to shut down and wait for it to stop. + + Waits for the server thread to exit on its own, then escalates to + ``force_exit`` if it has not, so a request wedged outside uvicorn's + loop cannot block here forever. + + Raises + ------ + RuntimeError + If the thread is still running after both waits. Returning + normally would report success for a server that is still bound to + its port and still serving, which the caller cannot detect any + other way. + """ + self._server.should_exit = True + # Outlast uvicorn's own graceful wait rather than matching it. uvicorn + # spends roughly 0.2s on teardown (a 0.1s loop tick plus a 0.1s sleep) + # *before* its `timeout_graceful_shutdown` wait even begins, so an + # equal bound here always expires first -- escalating to force_exit on + # the path that is supposed to be the orderly one, which makes uvicorn + # skip ASGI lifespan shutdown entirely. + self._thread.join(timeout=self._graceful_timeout + _SHUTDOWN_JOIN_MARGIN) + if self._thread.is_alive(): + self._server.force_exit = True + self._thread.join(timeout=self._shutdown_timeout) + + if self._thread.is_alive(): + raise RuntimeError( + "Server thread did not stop within " + f"{self._graceful_timeout + _SHUTDOWN_JOIN_MARGIN + self._shutdown_timeout:.1f}s, " + "even after force_exit. The server may still be serving and " + "holding its port; a request blocked in a store call cannot be " + "cancelled from here." + ) + + @property + def _graceful_timeout(self) -> float: + """uvicorn's own graceful-shutdown bound, whoever configured it.""" + configured = self._server.config.timeout_graceful_shutdown + return float(configured) if configured is not None else float(self._shutdown_timeout) + + def __enter__(self) -> Self: + return self + + def __exit__(self, *args: object) -> None: + self.shutdown() + + +class _RangeVerdict(Enum): + """The outcome of a Range header that does not name a readable range.""" + + IGNORE = auto() + """Serve the full representation with 200, as if no Range had been sent.""" + + UNSATISFIABLE = auto() + """Answer 416: the range is well-formed but names nothing readable.""" + + +_MAX_BYTE_POS = sys.maxsize +"""Largest byte position this server will pass to a store. + +Range bounds arrive as arbitrary-precision Python integers, but a store +ultimately turns them into an index-sized `seek`/`read`. Feeding an oversized +value through raises `OverflowError`/`ValueError` from deep inside the store +rather than producing a response, so bounds are clamped or rejected here. +""" + + +def _parse_int(text: str) -> int | None: + """Parse a byte position, accepting only the canonical spelling of one. + + `int` is lenient in ways an HTTP byte position is not -- it accepts + surrounding whitespace, a leading `+`/`-`, underscore separators, and + non-ASCII decimal digits -- so `bytes=+0-1` and `bytes=0_0-1` would parse. + RFC 9110 defines a byte position as 1*DIGIT. + """ + if not text.isascii() or not text.isdigit(): + return None + return int(text) + + +def _parse_range_header(range_header: str) -> ByteRequest | _RangeVerdict: + """Parse an HTTP Range header into a ByteRequest. + + A header this server cannot turn into a single read is *ignored* rather + than rejected. RFC 9110 Β§14.2 requires a server to ignore a Range whose + unit it does not recognize, and permits ignoring one it cannot parse; in + both cases the correct answer is the full representation, not 416. + Answering 416 would tell a client the object is unreadable when it is + merely the request that was unsupported -- and a client coalescing two + chunk reads into one multi-range request would take that at face value. + + 416 is reserved for a well-formed range that genuinely names nothing. + + Parameters + ---------- + range_header : str + The value of the Range header, e.g. ``"bytes=0-99"`` or ``"bytes=-100"``. + + Returns + ------- + ByteRequest or _RangeVerdict + A ``RangeByteRequest``, ``OffsetByteRequest``, or ``SuffixByteRequest`` + for a readable range, otherwise the verdict to apply. + """ + if not range_header.startswith("bytes="): + # An unrecognized range unit; RFC 9110 Β§14.2 says MUST ignore. + return _RangeVerdict.IGNORE + range_spec = range_header[len("bytes=") :] + if "," in range_spec: + # A multipart range. Legal to send, and legal to answer with the whole + # representation; this server does not build multipart/byteranges. + return _RangeVerdict.IGNORE + + if range_spec.startswith("-"): + # suffix request: bytes=-N + suffix = _parse_int(range_spec[1:]) + if suffix is None: + return _RangeVerdict.IGNORE + if suffix == 0: + # "the last zero bytes" names nothing. + return _RangeVerdict.UNSATISFIABLE + return SuffixByteRequest(suffix=min(suffix, _MAX_BYTE_POS)) + + parts = range_spec.split("-", 1) + if len(parts) != 2: + return _RangeVerdict.IGNORE + start_str, end_str = parts + start = _parse_int(start_str) + if start is None: + return _RangeVerdict.IGNORE + if start > _MAX_BYTE_POS: + # No object can be this long, so the range starts past every end. + return _RangeVerdict.UNSATISFIABLE + if end_str == "": + # offset request: bytes=N- + return OffsetByteRequest(offset=start) + end_pos = _parse_int(end_str) + if end_pos is None: + return _RangeVerdict.IGNORE + # HTTP end is inclusive, ByteRequest end is exclusive. A last-byte-pos at + # or past the end of the object is satisfiable -- RFC 9110 Β§14.1.2 says to + # clamp it -- so an oversized bound is capped rather than refused. + end = min(end_pos, _MAX_BYTE_POS - 1) + 1 + if start >= end: + # An inverted range like "bytes=5-2" is unsatisfiable, not a read + # of negative length. + return _RangeVerdict.UNSATISFIABLE + return RangeByteRequest(start=start, end=end) + + +def _is_drive_qualified(path: str) -> bool: + """Whether *path* carries a drive or UNC prefix that would discard a store root. + + A drive-qualified key such as `C:/Windows`, or the drive-relative `a:b`, + replaces the root it is joined to rather than extending it. This is + rejected on every platform, not just Windows: the check is a string-level + gate in front of an arbitrary `Store`, and this package cannot know how a + given implementation resolves keys. + + The cost is that a node whose *first* path segment looks like `:...` + is unreachable -- `ntpath` treats any single character before a colon as + a drive, so there is no safe subset to admit. Such names are legal but + rare, and later segments are unaffected (`sub/a:b` is served normally). + + Parameters + ---------- + path : str + The candidate key, with separators already folded to `/`. + + Returns + ------- + bool + """ + return ntpath.splitdrive(path)[0] != "" + + +def _names_nothing(exc: OSError) -> bool: + """Whether an `OSError` answers about the *name*, rather than reporting failure. + + `ENAMETOOLONG` is the store saying no such name is expressible here. That + is an answer about the key -- nothing can be stored under it, so a miss is + honest -- and it is unreachable for real data, because `encode_chunk_key` + never produces a segment near a filesystem's length limit. Answering 404 + therefore cannot make a reader substitute fill values over a chunk that + exists, and it keeps a client from turning a freely chosen key into a 5xx. + + Every other `errno` describes a failure to complete the operation and must + surface as one. `EINVAL` was accepted here and was the dangerous case: it + is POSIX's catch-all, reachable on a perfectly ordinary short key through + a bad seek or an unsupported filesystem feature. Under the v3 spec an + absent chunk is an uninitialized one, so reporting such a failure as 404 + has a correct reader write fill values over data that is merely + unreadable. When in doubt the store's own signal is the one to trust: + `None` means absent, a raised error means the request could not be + answered. + + Parameters + ---------- + exc : OSError + The error raised by the store. + + Returns + ------- + bool + """ + return exc.errno == errno.ENAMETOOLONG + + +def _content_range(byte_range: RangeByteRequest | OffsetByteRequest, length: int) -> str: + """Build a `Content-Range` value for a 206 response. + + Parameters + ---------- + byte_range : RangeByteRequest or OffsetByteRequest + The range that was served. A suffix request is resolved to an absolute + range before reaching here, because RFC 9110 Β§15.3.7 requires every + single-part 206 to carry a `Content-Range` and a suffix's first-byte + position is not knowable without the object's size. + length : int + The number of bytes actually returned. + + Returns + ------- + str + A `bytes -/*` value. + """ + start = byte_range.start if isinstance(byte_range, RangeByteRequest) else byte_range.offset + # The total length is unknown here; RFC 9110 permits "*" in its place. + return f"bytes {start}-{start + length - 1}/*" + + +async def _resolve_suffix( + store: Store, path: str, byte_range: SuffixByteRequest +) -> RangeByteRequest | _RangeVerdict: + """Turn a suffix request into an absolute range using the object's size. + + A suffix range names its bytes relative to an end this server does not + otherwise need to know. Resolving it here is what lets the 206 carry a + `Content-Range`, which RFC 9110 requires and which a caller reading a + shard index needs in order to locate what it was given. + """ + try: + size = await store.getsize(path) + except FileNotFoundError: + return _RangeVerdict.UNSATISFIABLE + if size == 0: + return _RangeVerdict.UNSATISFIABLE + # A suffix longer than the object is satisfiable and yields the whole + # object, per RFC 9110 Β§14.1.2. + return RangeByteRequest(start=max(0, size - byte_range.suffix), end=size) + + +_JSON_BASENAMES = ( + array_metadata_keys(2) + | array_metadata_keys(3) + | group_metadata_keys(2) + | group_metadata_keys(3) +) +"""Metadata documents that are JSON, for every zarr format. + +Derived from the same tables that decide which keys a node owns, so a v2 +array's `.zarray` is typed as JSON rather than as opaque bytes -- and adding a +document in one place cannot leave the media type behind in the other. +""" + + +def content_type_for(path: str) -> str: + """Media type for a store key, chosen by its basename.""" + if path.rsplit("/", 1)[-1] in _JSON_BASENAMES: + return "application/json" + return "application/octet-stream" + + +async def _head_response(store: Store, path: str, content_type: str) -> Response: + """Answer a HEAD without transferring the value. + + A HEAD body is discarded at the wire, so routing HEAD through the GET + handler reads the whole object -- megabytes of chunk or shard -- to report + a length. `Store.getsize` is a `stat` on a filesystem store and an + info/HEAD call on a remote one. + """ + from starlette.responses import Response + + try: + size = await store.getsize(path) + except FileNotFoundError: + return Response(status_code=404) + except OSError as exc: + if not _names_nothing(exc): + raise + return Response(status_code=404) + return Response(status_code=200, media_type=content_type, headers={"Content-Length": str(size)}) + + +async def _get_response( + store: Store, + path: str, + byte_range: RangeByteRequest | OffsetByteRequest | None = None, +) -> Response: + """Fetch a key from the store and return an HTTP response.""" + from starlette.responses import Response + + proto = cpu.buffer_prototype + content_type = content_type_for(path) + + try: + buf = await store.get(path, proto, byte_range=byte_range) + except (MemoryError, OverflowError): + # The client's last-byte-pos is wider than the store can materialize + # -- it sizes its read from the range, not from the object. RFC 9110 + # Β§14.1.2 makes a last-byte-pos at or past the end of the object + # satisfiable and clamps it to the end, so re-read from the same start + # to EOF, which is what the clamped range denotes. Refusing with 416 + # would deny a request that is merely over-wide, and a client asking + # for "from here to well past the end" is asking a normal question. + if not isinstance(byte_range, RangeByteRequest): + raise + byte_range = OffsetByteRequest(offset=byte_range.start) + buf = await store.get(path, proto, byte_range=byte_range) + except OSError as exc: + if not _names_nothing(exc): + # A real I/O failure, which must not be reported as a miss. Under + # the v3 spec an absent chunk is an uninitialized one, and a + # reader is right to substitute the array's fill value for it -- + # so 404 asserts something about the store's contents. An + # unreadable chunk is not an uninitialized chunk, and answering + # 404 would have a correct client silently materialize fill + # values over data that exists. + raise + return Response(status_code=404) + if buf is None: + return Response(status_code=404) + + if byte_range is None: + return Response(content=buf.to_bytes(), status_code=200, media_type=content_type) + + body = buf.to_bytes() + if len(body) == 0: + # The range lies wholly beyond the end of the object. + return Response(status_code=416) + + headers = {"Content-Range": _content_range(byte_range, len(body))} + return Response(content=body, status_code=206, media_type=content_type, headers=headers) + + +async def _handle_request(request: Request) -> Response: + """Handle a request, optionally filtering by node validity.""" + from starlette.responses import Response + + store: Store = request.app.state.store + node: Array[Any] | Group | None = request.app.state.node + prefix: str = request.app.state.prefix + path = request.path_params.get("path", "") + + # Reject non-canonical / traversal-prone keys before touching the store. + # Starlette percent-decodes path params, so "..%2f" arrives as a literal + # ".." segment and "%2f"-encoded leading slashes arrive as an empty leading + # segment (making the key absolute, which escapes a filesystem store root). + # Backslashes are separators on Windows and drive-qualified or + # root-relative keys discard a filesystem store's root entirely, so fold + # separators before checking segments -- mirroring zarr's normalize_path + # (src/zarr/storage/_utils.py) plus a drive check it doesn't need. Legitimate + # zarr keys never contain empty, ".", or ".." segments, or a drive letter. + segments = path.replace("\\", "/").split("/") + if any(segment in ("", ".", "..") for segment in segments) or _is_drive_qualified(path): + return Response(status_code=404) + + # A NUL can never appear in a store key, and reaches the filesystem layer + # as a raised error rather than a miss. Rejecting it here keeps that out + # of the store, so the store's own errors always mean real I/O trouble. + if "\x00" in path: + return Response(status_code=404) + + # If serving a node, validate the key before touching the store. Group + # validation opens children through zarr's synchronous API, which drives + # the store to completion and would otherwise block the event loop for + # the duration -- serializing every concurrent request behind it, and + # outlasting the shutdown timeout. + if node is not None and not await asyncio.to_thread(is_valid_node_key, node, path): + return Response(status_code=404) + + # Resolve the full store key by prepending the node's prefix. + store_key = f"{prefix}/{path}" if prefix else path + + if request.method == "PUT": + if store.read_only: + # The store will refuse this with a ValueError from deep inside + # `set`, which is a 500 -- a server fault. Refusing to write to a + # read-only store is not a fault, it is the answer. + return Response(status_code=403) + + max_body_size: int | None = request.app.state.max_body_size + if max_body_size is None: + body = await request.body() + else: + declared = request.headers.get("content-length") + if declared is not None and declared.isdigit() and int(declared) > max_body_size: + return Response(status_code=413) + + # Read incrementally and stop at the cap. `request.body()` would + # buffer the whole body first, which a chunked request can use to + # exceed the cap by any amount before it is ever checked. + chunks: list[bytes] = [] + received = 0 + async for chunk in request.stream(): + received += len(chunk) + if received > max_body_size: + return Response(status_code=413) + chunks.append(chunk) + body = b"".join(chunks) + + buf = cpu.buffer_prototype.buffer.from_bytes(body) + try: + await store.set(store_key, buf) + except OSError as exc: + if not _names_nothing(exc): + # A real write failure -- a full disk, a read-only mount, a + # permissions problem. Reporting it as 404 would tell the + # client the write is pointless rather than failed. + raise + return Response(status_code=404) + return Response(status_code=204) + + if request.method == "HEAD": + # A HEAD body is discarded at the wire, so reading the value to build + # one transfers the whole object to answer a question about its size. + # `getsize` is a stat on a filesystem store and a HEAD/info call on a + # remote one. + return await _head_response(store, store_key, content_type_for(path)) + + range_header = request.headers.get("range") + byte_range: RangeByteRequest | OffsetByteRequest | None = None + if range_header is not None: + parsed = _parse_range_header(range_header) + if parsed is _RangeVerdict.UNSATISFIABLE: + return Response(status_code=416) + if isinstance(parsed, SuffixByteRequest): + parsed = await _resolve_suffix(store, store_key, parsed) + if parsed is _RangeVerdict.UNSATISFIABLE: + return Response(status_code=416) + # _RangeVerdict.IGNORE falls through with byte_range still None, which + # serves the full representation with 200. + if not isinstance(parsed, _RangeVerdict): + byte_range = parsed + + return await _get_response(store, store_key, byte_range) + + +def _make_starlette_app( + *, + methods: AbstractSet[HTTPMethod] | None = None, + cors_options: CorsOptions | None = None, +) -> Starlette: + """Create a Starlette app with the request handler. + + Raises + ------ + ValueError + If `methods` contains anything outside `GET`, `PUT`, and `HEAD`. + """ + from starlette.applications import Starlette + from starlette.middleware.cors import CORSMiddleware + from starlette.routing import Route + + if methods is None: + methods = READ_ONLY_HTTP_METHODS + + # An empty set must not reach Starlette: `Route` treats a falsy `methods` + # as "match every method", so asking for no methods would serve them all. + if not methods: + raise ValueError( + "methods must name at least one HTTP method; " + f"accepted methods are {', '.join(sorted(_SUPPORTED_METHODS))}." + ) + + unsupported = sorted(set(methods) - _SUPPORTED_METHODS) + if unsupported: + raise ValueError( + f"Unsupported HTTP method(s): {', '.join(unsupported)}. " + f"Accepted methods are {', '.join(sorted(_SUPPORTED_METHODS))}." + ) + + app = Starlette( + routes=[Route("/{path:path}", _handle_request, methods=list(methods))], + ) + + if cors_options is not None: + # Typed loosely on purpose: unpacking a merged TypedDict loses the + # per-key types, so the looseness is contained to this block rather + # than spread across casts at each use. + merged: dict[str, Any] = {**_CORS_DEFAULTS, **cors_options} + if "allow_methods" in merged: + # Only when the caller said something. Absent, Starlette's own + # `GET`-only default stands: widening it to everything served + # would newly advertise `PUT` cross-origin on a write-enabled app + # that never asked for it. + merged["allow_methods"] = _reconcile_allow_methods( + merged["allow_methods"], served=_served_methods(methods) + ) + app.add_middleware( + CORSMiddleware, + # Our defaults first, so a key the caller supplied wins outright + # rather than being merged into -- an explicit `expose_headers: []` + # means "expose nothing", not "expose our default". + **merged, + ) + return app + + +def _reject_writes_to_a_read_only_store( + store: Store, methods: AbstractSet[HTTPMethod] | None +) -> None: + """Refuse a configuration whose writes can never succeed. + + A store's `read_only` is fixed when it is built, so asking to serve `PUT` + from one is a contradiction that would only reveal itself as a 403 on the + first write a client attempts -- possibly long after deployment, and to + the client rather than to whoever misconfigured it. Saying so at + construction matches how unsupported `methods` and contradictory + `cors_options` are already handled. + + Raises + ------ + ValueError + If `methods` asks for `PUT` on a read-only store. + """ + if methods is not None and "PUT" in methods and store.read_only: + raise ValueError( + "methods asks for PUT, but the store is read-only, so no write " + "could ever succeed. Drop PUT to serve reads, or pass a writable " + "store (`store.with_read_only(False)`)." + ) + + +def _served_methods(methods: AbstractSet[HTTPMethod]) -> frozenset[str]: + """The methods the route will actually answer. + + Starlette adds `HEAD` to any route that serves `GET`, which RFC 9110 + Β§9.3.2 asks of every origin server, so `HEAD` is served whenever `GET` is + whether or not it was named. + """ + served = set(methods) + if "GET" in served: + served.add("HEAD") + return frozenset(served) + + +def _reconcile_allow_methods(allow_methods: list[str], *, served: frozenset[str]) -> list[str]: + """Check `cors_options["allow_methods"]` against what the route serves. + + An advertised method the route rejects is a promise the server cannot + keep: a browser caches the preflight and every later cross-origin call + fails with 405 after a successful handshake. The reverse is worse -- the + same silence lets `allow_methods=["*"]` on a write-enabled app hand every + origin on the internet write access, which is exactly the footgun the + `methods` validation above exists to prevent. + + `"*"` expands to what is actually served rather than being rejected: it + is the idiomatic spelling of "everything this app does", and the app + cannot do more than it serves. + """ + if "*" in allow_methods: + return sorted(served) + + unserved = sorted(set(allow_methods) - served) + if unserved: + raise ValueError( + f"cors_options['allow_methods'] advertises {', '.join(unserved)}, " + f"which this app does not serve (it serves {', '.join(sorted(served))}). " + "A browser would cache that preflight and every such request would " + "then fail with 405." + ) + return list(allow_methods) + + +def _build_server( + app: Starlette, + *, + host: str, + port: int | Literal["auto"], + shutdown_timeout: int, + uvicorn_options: Mapping[str, object] | None, +) -> tuple[uvicorn.Server, dict[str, object], socket.socket | None]: + """Configure a `uvicorn.Server` for *app*, and report how it will bind. + + Returns the options actually used -- a key from `uvicorn_options` may have + replaced one passed here -- and, for `port="auto"`, the socket already + bound on the caller's behalf, which must be handed to `Server.run`. + """ + import uvicorn + + options: dict[str, object] = { + "host": host, + "port": port, + "timeout_graceful_shutdown": shutdown_timeout, + } + if uvicorn_options is not None: + options.update(uvicorn_options) + + sock: socket.socket | None = None + if options.get("port") == AUTO_PORT: + if _binds_without_a_port(options): + # A uds or fd bind ignores host and port; leave a valid int in + # place of the sentinel so `Config` still type-checks. + options["port"] = DEFAULT_PORT + else: + # Bind here rather than probing and handing uvicorn a port number: + # probing would release the port before uvicorn claimed it, which + # is the bind-then-close race that makes "find a free port" helpers + # flaky. Holding the socket means nothing can take it in between. + sock = _bind_preferred_or_free(str(options["host"]), DEFAULT_PORT) + # Keep Config agreeing with reality, so uvicorn's own "running on + # ..." line names the port it is really serving. + options["port"] = sock.getsockname()[1] + + # uvicorn.Config's parameters are individually typed and there are ~50 of + # them; `Mapping[str, object]` is the honest type for the public argument, + # so the cast is confined to the call itself. + return uvicorn.Server(uvicorn.Config(app, **cast("dict[str, Any]", options))), options, sock + + +def _binds_without_a_port(options: Mapping[str, object]) -> bool: + """Whether these options bind something other than a TCP host and port.""" + return options.get("uds") is not None or options.get("fd") is not None + + +def _bind_preferred_or_free(host: str, preferred: int) -> socket.socket: + """Bind *preferred* on *host* if it is free, otherwise any free port. + + The address family comes from `getaddrinfo` rather than being assumed: + hard-coding `AF_INET` would fail for an IPv6 host such as ``"::1"``. + """ + for candidate in (preferred, 0): + family, socktype, proto, _, sockaddr = socket.getaddrinfo( + host, candidate, type=socket.SOCK_STREAM + )[0] + sock = socket.socket(family, socktype, proto) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + sock.bind(sockaddr) + except OSError: + sock.close() + if candidate == 0: + # Nothing is free, which is a real failure rather than a + # reason to keep looking. + raise + _LOGGER.info( + "port %d is in use; binding a free port instead. Pass an " + "explicit port to require a particular one.", + preferred, + ) + continue + return sock + raise AssertionError("unreachable") # pragma: no cover + + +def serve( + app: Starlette, + *, + host: str = "127.0.0.1", + port: int | Literal["auto"] = AUTO_PORT, + shutdown_timeout: int = 5, + uvicorn_options: Mapping[str, object] | None = None, +) -> None: + """Run an ASGI app under Uvicorn, blocking until it is stopped. + + Returns only when the server stops, so this is the shape for a process + whose job is to serve -- a script, a container entrypoint. Use + :func:`serve_background` when the caller has more to do. + + Build the app first with :func:`store_app` or :func:`node_app`, or compose + several of them; what an app serves is settled when it is built, and this + only decides how it runs. + + .. code-block:: python + + serve(store_app(store), host="0.0.0.0", port=8000) + + Parameters + ---------- + app : Starlette + The ASGI app to run. + host : str, optional + The host to bind to. Defaults to ``"127.0.0.1"``. + port : int, optional + The port to bind to. Defaults to ``8000``. + shutdown_timeout : int, optional + Seconds to wait for in-flight requests to finish gracefully when the + server is shut down, via uvicorn's ``timeout_graceful_shutdown``. + Defaults to ``5``. + uvicorn_options : Mapping[str, object], optional + Extra options passed straight to `uvicorn.Config`, merged over the + ones set here (`host`, `port`, `timeout_graceful_shutdown`), so a + caller key wins. This is the escape hatch for anything uvicorn can do + that this signature does not name -- TLS via `ssl_keyfile` / + `ssl_certfile`, `proxy_headers` and `forwarded_allow_ips` behind a + reverse proxy, `root_path` when mounted under a prefix, `log_level`, + `limit_concurrency`, or a `uds` / `fd` bind. + """ + server, _, sock = _build_server( + app, + host=host, + port=port, + shutdown_timeout=shutdown_timeout, + uvicorn_options=uvicorn_options, + ) + server.run(sockets=[sock] if sock is not None else None) + + +def serve_background( + app: Starlette, + *, + host: str = "127.0.0.1", + port: int | Literal["auto"] = AUTO_PORT, + shutdown_timeout: int = 5, + uvicorn_options: Mapping[str, object] | None = None, +) -> BackgroundServer: + """Start an ASGI app under Uvicorn in a daemon thread and return at once. + + Returns once the socket is listening, so the next statement can use the + server. The returned handle is also a context manager: + + .. code-block:: python + + with serve_background(node_app(array)) as server: + httpx.get(f"{server.url}/zarr.json") + + In a notebook, where the server must outlive the cell that started it, + keep the handle instead and call :meth:`BackgroundServer.shutdown` later. + + Parameters + ---------- + app : Starlette + The ASGI app to run. + host : str, optional + The host to bind to. Defaults to ``"127.0.0.1"``. + port : int, optional + The port to bind to. Defaults to ``0``, which asks the OS for a free + one -- unlike :func:`serve`, whose caller usually needs a port others + already know. A background server is normally reached through + :attr:`BackgroundServer.url`, and a fixed default would make starting + a second one, or re-running a notebook cell, fail on a port collision. + shutdown_timeout : int, optional + Seconds to wait for in-flight requests to finish gracefully, both for + uvicorn's ``timeout_graceful_shutdown`` and for the wait + :meth:`BackgroundServer.shutdown` uses before forcing the thread + closed. Defaults to ``5``. + uvicorn_options : Mapping[str, object], optional + Extra options passed straight to `uvicorn.Config`, merged over the + ones set here so a caller key wins. See :func:`serve`. Binding + somewhere other than a TCP host and port leaves + :attr:`BackgroundServer.url` as ``None``. + + Returns + ------- + BackgroundServer + A handle for the running server. + + Raises + ------ + RuntimeError + If the server does not start -- most often because the port is + already in use. + """ + server, options, sock = _build_server( + app, + host=host, + port=port, + shutdown_timeout=shutdown_timeout, + uvicorn_options=uvicorn_options, + ) + + # uvicorn skips signal-handler installation off the main thread + # (Server.capture_signals), so no workaround is needed here. + thread = threading.Thread( + target=partial(server.run, sockets=[sock] if sock is not None else None), daemon=True + ) + thread.start() + + deadline = time.monotonic() + _STARTUP_TIMEOUT + while not server.started: + if not thread.is_alive(): + # uvicorn logs the underlying error and calls sys.exit, which in a + # thread ends it without surfacing anything to the caller. The + # overwhelmingly common cause is a port already in use. + raise RuntimeError( + f"Server thread exited before startup completed; {host}:{port} " + "may already be in use. See the server log for the cause." + ) + if time.monotonic() > deadline: + # The thread is still alive here, unlike the branch above, and it + # is about to finish starting. Raising without stopping it would + # leave a server bound to the port with no handle to shut it down + # -- a daemon thread serving for the rest of the process, and a + # retry on the same port failing with the other error above. + server.should_exit = True + server.force_exit = True + thread.join(timeout=_STARTUP_ABANDON_TIMEOUT) + raise RuntimeError( + f"Server failed to start within {_STARTUP_TIMEOUT:g} seconds; " + "it has been signalled to stop." + ) + time.sleep(0.01) + + # Report the port the socket actually bound rather than the one asked for, + # so `port=0` ("pick a free port") yields a usable `url`. A unix-socket or + # file-descriptor bind has no host and port at all, so both stay None and + # `url` reports None rather than naming an address nothing is listening on. + bound_port: int | None = None + for bound in server.servers: + for sock in bound.sockets: + sockname = sock.getsockname() + if isinstance(sockname, tuple) and len(sockname) >= 2: + bound_port = int(sockname[1]) + break + break + + # The host is taken from the request rather than the socket: a wildcard + # bind reports "0.0.0.0", which is not an address a client can connect to. + requested_host = options.get("host") + bound_host = ( + str(requested_host) if bound_port is not None and requested_host is not None else None + ) + + return BackgroundServer( + server, + thread, + host=bound_host, + port=bound_port, + scheme="https" if server.config.is_ssl else "http", + shutdown_timeout=shutdown_timeout, + ) + + +def store_app( + store: Store, + *, + methods: AbstractSet[HTTPMethod] | None = None, + cors_options: CorsOptions | None = None, + max_body_size: int | None = DEFAULT_MAX_BODY_SIZE, +) -> Starlette: + """Create a Starlette ASGI app that serves every key in a zarr ``Store``. + + Parameters + ---------- + store : Store + The zarr store to serve. + methods : set of HTTPMethod, optional + The HTTP methods to accept: any of `"GET"`, `"HEAD"`, and `"PUT"`. + Defaults to `{"GET"}`, which also serves `HEAD`. Passing any other + method raises `ValueError`. + cors_options : CorsOptions, optional + If provided, CORS middleware will be added with the given options. + max_body_size : int or None, optional + Largest `PUT` body to accept, in bytes; larger requests get a 413. + `Store.set` takes a whole `Buffer`, so bodies cannot be streamed and + are held in memory in full. Defaults to `DEFAULT_MAX_BODY_SIZE`; + pass `None` to lift the cap. + + Returns + ------- + Starlette + An ASGI application. + """ + _reject_writes_to_a_read_only_store(store, methods) + app = _make_starlette_app(methods=methods, cors_options=cors_options) + app.state.store = store + app.state.node = None + app.state.prefix = "" + app.state.max_body_size = max_body_size + return app + + +def node_app( + node: Array[Any] | Group, + *, + methods: AbstractSet[HTTPMethod] | None = None, + cors_options: CorsOptions | None = None, + max_body_size: int | None = DEFAULT_MAX_BODY_SIZE, +) -> Starlette: + """Create a Starlette ASGI app that serves only the keys belonging to a + zarr ``Array`` or ``Group``. + + For an ``Array``, the served keys are the metadata document(s) and all + chunk (or shard) keys whose coordinates fall within the array's grid. + + For a ``Group``, the served keys are the group's own metadata plus any + path that resolves through the group's members to a valid array metadata + document or chunk key. + + Requests for keys outside this set receive a 404 response, even if the + underlying store contains data at that path. + + Parameters + ---------- + node : Array or Group + The zarr array or group to serve. + methods : set of HTTPMethod, optional + The HTTP methods to accept: any of `"GET"`, `"HEAD"`, and `"PUT"`. + Defaults to `{"GET"}`, which also serves `HEAD`. Passing any other + method raises `ValueError`. + cors_options : CorsOptions, optional + If provided, CORS middleware will be added with the given options. + max_body_size : int or None, optional + Largest `PUT` body to accept, in bytes; larger requests get a 413. + `Store.set` takes a whole `Buffer`, so bodies cannot be streamed and + are held in memory in full. Defaults to `DEFAULT_MAX_BODY_SIZE`; + pass `None` to lift the cap. + + Returns + ------- + Starlette + An ASGI application. + """ + _reject_writes_to_a_read_only_store(node.store_path.store, methods) + app = _make_starlette_app(methods=methods, cors_options=cors_options) + app.state.store = node.store_path.store + app.state.node = node + app.state.prefix = node.store_path.path + app.state.max_body_size = max_body_size + return app diff --git a/src/zarr/codecs/registry.py b/packages/zarr-http-server/src/zarr_http_server/py.typed similarity index 100% rename from src/zarr/codecs/registry.py rename to packages/zarr-http-server/src/zarr_http_server/py.typed diff --git a/packages/zarr-http-server/tests/conftest.py b/packages/zarr-http-server/tests/conftest.py new file mode 100644 index 0000000000..84694b42ba --- /dev/null +++ b/packages/zarr-http-server/tests/conftest.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Literal + +import pytest +from zarr.storage import MemoryStore + +if TYPE_CHECKING: + from zarr.abc.store import Store + +ZarrFormat = Literal[2, 3] + + +@pytest.fixture +def store(request: pytest.FixtureRequest) -> Store: + """Store fixture resolved via indirect parametrization.""" + if request.param != "memory": + raise ValueError(f"unsupported store param: {request.param!r}") + return MemoryStore() + + +@pytest.fixture(params=(2, 3), ids=["zarr2", "zarr3"]) +def zarr_format(request: pytest.FixtureRequest) -> ZarrFormat: + """Zarr format version fixture, parametrized over v2 and v3.""" + if request.param == 2: + return 2 + elif request.param == 3: + return 3 + msg = f"Invalid zarr format requested. Got {request.param}, expected one of (2, 3)." + raise ValueError(msg) diff --git a/packages/zarr-http-server/tests/test_examples.py b/packages/zarr-http-server/tests/test_examples.py new file mode 100644 index 0000000000..20a5d5b1b0 --- /dev/null +++ b/packages/zarr-http-server/tests/test_examples.py @@ -0,0 +1,60 @@ +"""The shipped examples must keep working. + +An example that has quietly rotted is worse than no example: it is the first +thing a new user copies. These run the real files rather than a paraphrase of +them, so a signature change or a behavior change fails here rather than in +someone's notebook. +""" + +from __future__ import annotations + +import pathlib +import runpy + +import pytest + +EXAMPLES = pathlib.Path(__file__).resolve().parent.parent / "examples" +NOTEBOOK = EXAMPLES / "serve_notebook.ipynb" +SCRIPT = EXAMPLES / "serve.py" + + +@pytest.mark.parametrize("path", [NOTEBOOK, SCRIPT], ids=["notebook", "script"]) +def test_example_exists(path: pathlib.Path) -> None: + """Guards the paths above: a renamed or moved example would otherwise turn + its execution test into a skip, or a no-op, that nobody notices.""" + assert path.is_file(), f"missing example at {path}" + + +def test_serve_script_runs() -> None: + """Run examples/serve.py top to bottom. + + In-process rather than as a subprocess: the script's inline uv metadata + resolves `zarr-http-server` from git, so `uv run` on it would test whatever + is on main instead of the working tree. + """ + runpy.run_path(str(SCRIPT), run_name="__main__") + + +def test_serve_notebook_executes() -> None: + """Run every cell in a real kernel. + + The notebook asserts its own expectations -- status codes, byte ranges, + that a PUT is refused, that the port is closed after `shutdown()` -- so + this is not merely a check that nothing raised. `NotebookClient.execute` + defaults to ``allow_errors=False``, so any failed cell raises + `CellExecutionError` and fails this test with that cell's traceback. + """ + nbformat = pytest.importorskip("nbformat") + nbclient = pytest.importorskip("nbclient") + pytest.importorskip("ipykernel", reason="a kernel is needed to execute the notebook") + + notebook = nbformat.read(NOTEBOOK, as_version=4) + + # Run with the notebook's own directory as cwd, so any relative path it + # uses means the same thing as when a reader opens it. + nbclient.NotebookClient( + notebook, + timeout=300, + kernel_name="python3", + resources={"metadata": {"path": str(EXAMPLES)}}, + ).execute() diff --git a/packages/zarr-http-server/tests/test_properties.py b/packages/zarr-http-server/tests/test_properties.py new file mode 100644 index 0000000000..ff54392dfc --- /dev/null +++ b/packages/zarr-http-server/tests/test_properties.py @@ -0,0 +1,580 @@ +"""Property-based tests driven against a real HTTP endpoint. + +Every test here talks to an actual uvicorn server over a socket, not to an +in-process ASGI client, so the properties cover the parts of the stack that +only exist on the wire: header parsing, method dispatch, and status codes. + +Each property checks **two** things after a request -- the response, and the +state of the backing store. That pairing is the point. A server can answer +correctly and corrupt the store, or refuse a request and write anyway, and a +response-only assertion sees neither. The bug that motivated this module did +exactly that: a `PUT` to a non-canonically spelled chunk key ("c/00/00" +instead of "c/0/0") answered `204 No Content` and stored the body under a key +no reader ever looks up, so the client saw success and the data was invisible. + +The vocabulary below splits keys into two families: + +* **in-band** -- keys the served node genuinely owns: its metadata documents + and the canonical spelling of each chunk key in its grid. These must be + served, and writes to them must be visible to a zarr reader. +* **out-of-band** -- everything else: non-canonical spellings of a valid + chunk key, coordinates outside the grid, traversal attempts, and keys + belonging to a sibling node. These must be refused *and* must leave the + store byte-for-byte unchanged. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Literal +from urllib.parse import quote + +import httpx +import numpy as np +import pytest +import zarr +from hypothesis import assume, given, settings +from hypothesis import strategies as st +from zarr.buffer import cpu +from zarr.core.sync import sync + +from zarr_http_server import node_app, serve_background, store_app +from zarr_http_server._keys import _shard_grid_shape + +if TYPE_CHECKING: + from collections.abc import Iterator + + from zarr import Array + from zarr.abc.store import Store + +# Real HTTP round trips are slower and jumpier than hypothesis' default +# deadline allows, and a CI runner under load makes that worse. +_HTTP = settings(deadline=None, max_examples=50) + +# An uncompressed array so a chunk's bytes are exactly its raw values: a PUT +# body of the right length is a legitimate chunk, which lets these tests +# assert that a write is readable through a zarr client rather than merely +# present in the store. +_SHAPE = (6, 4) +_CHUNKS = (2, 2) +_DTYPE = "int32" + + +@dataclass(frozen=True) +class Served: + """A running server plus the handles needed to reason about its keys.""" + + url: str + store: Store + array: Array[Any] + kind: Literal["store", "node"] + + http_prefix: str + """Prepended to an array-relative key to form the request path.""" + + store_prefix: str + """Prepended to an array-relative key to form the backing store key.""" + + def path(self, array_relative_key: str) -> str: + return f"{self.http_prefix}{array_relative_key}" + + def store_key(self, array_relative_key: str) -> str: + return f"{self.store_prefix}{array_relative_key}" + + +def _snapshot(store: Store) -> dict[str, bytes]: + """Every key in *store* mapped to its bytes. + + Comparing two snapshots is how these tests assert that a rejected request + changed nothing -- not just that it added no key, but that it modified + none either. + """ + + async def _read() -> dict[str, bytes]: + out: dict[str, bytes] = {} + async for key in store.list(): + buf = await store.get(key, cpu.buffer_prototype) + if buf is not None: + out[key] = buf.to_bytes() + return out + + return sync(_read()) + + +@pytest.fixture( + scope="module", + params=[ + ("store", 2, "memory"), + ("store", 3, "memory"), + ("node", 2, "memory"), + ("node", 3, "memory"), + # LocalStore reads through the filesystem, which sizes its read from + # the range rather than from the object and so raises on an over-wide + # one. MemoryStore just slices a `bytes` and is happy with any bound, + # so a memory-only matrix cannot tell a clamped range from a refused + # one -- the store backend is part of what these properties test. + ("store", 3, "local"), + ("node", 3, "local"), + ], + ids=["store-v2", "store-v3", "node-v2", "node-v3", "store-v3-local", "node-v3-local"], +) +def served( + request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory +) -> Iterator[Served]: + """One real server per (app kind, zarr format, store backend). + + Module-scoped because hypothesis drives hundreds of requests per test and + a server per example would dominate the runtime. `port=0` lets the OS + choose the port and `server.url` reports what it actually bound, which + avoids the bind-then-close race of picking a port up front. + """ + kind, zarr_format, backend = request.param + + store: Store + if backend == "local": + root_dir = tmp_path_factory.mktemp(f"{kind}-v{zarr_format}") + store = zarr.storage.LocalStore(root_dir) + else: + store = zarr.storage.MemoryStore() + root = zarr.open_group(store, mode="w", zarr_format=zarr_format) + array = root.create_array( + "inside", shape=_SHAPE, chunks=_CHUNKS, dtype=_DTYPE, compressors=None + ) + array[:] = np.arange(int(np.prod(_SHAPE)), dtype=_DTYPE).reshape(_SHAPE) + # A sibling the node_app must never serve, and whose keys therefore make + # good out-of-band probes. + sibling = root.create_array( + "outside", shape=_CHUNKS, chunks=_CHUNKS, dtype=_DTYPE, compressors=None + ) + sibling[:] = 1 + + if kind == "node": + server = serve_background(node_app(array, methods={"GET", "PUT"}), host="127.0.0.1", port=0) + http_prefix = "" + else: + server = serve_background( + store_app(store, methods={"GET", "PUT"}), host="127.0.0.1", port=0 + ) + http_prefix = "inside/" + assert server is not None + + try: + yield Served( + url=server.url, + store=store, + array=array, + kind=kind, + http_prefix=http_prefix, + store_prefix="inside/", + ) + finally: + server.shutdown() + + +def _grid(array: Array[Any]) -> tuple[int, ...]: + return _shard_grid_shape(array) + + +@st.composite +def chunk_coords(draw: st.DrawFn, array: Array[Any]) -> tuple[int, ...]: + """Coordinates of a chunk that exists in *array*'s storage grid.""" + return tuple(draw(st.integers(min_value=0, max_value=g - 1)) for g in _grid(array)) + + +@st.composite +def out_of_grid_coords(draw: st.DrawFn, array: Array[Any]) -> tuple[int, ...]: + """Coordinates outside the grid, so the key is well-formed but names nothing.""" + grid = _grid(array) + axis = draw(st.integers(min_value=0, max_value=len(grid) - 1)) + coords = list(draw(chunk_coords(array))) + coords[axis] = draw(st.integers(min_value=grid[axis], max_value=grid[axis] + 50)) + return tuple(coords) + + +# The confusability with ASCII digits is the point: `int()` accepts these as +# decimal digits, so they name a different store key while decoding to the +# same coordinate. That is the defect these strategies probe for. +_ARABIC_INDIC = "Ω Ω‘Ω’Ω£Ω€Ω₯Ω¦Ω§Ω¨Ω©" +_FULLWIDTH = "οΌοΌ‘οΌ’οΌ“οΌ”οΌ•οΌ–οΌ—οΌ˜οΌ™" # noqa: RUF001 + + +def _respellings(digits: str) -> list[str]: + """Strings `int()` maps to the same value as *digits*, spelled differently. + + These are exactly the spellings that make decode-only validation unsafe: + each names a *different* store key while decoding to the same coordinate. + """ + value = int(digits) + return [ + f"0{digits}", + f"00{digits}", + f"+{digits}", + f" {digits}", + f"{digits} ", + f"\t{digits}", + "".join(_ARABIC_INDIC[int(d)] for d in digits), + "".join(_FULLWIDTH[int(d)] for d in digits), + *([f"-{digits}"] if value == 0 else []), + ] + + +@st.composite +def non_canonical_chunk_keys(draw: st.DrawFn, array: Array[Any]) -> str: + """A chunk key that decodes into the grid but is not zarr's own spelling. + + Built by taking the canonical key and re-spelling one of its digit runs, + which keeps this strategy independent of the chunk key encoding's grammar. + """ + coords = draw(chunk_coords(array)) + canonical = array.metadata.encode_chunk_key(coords) + runs = list(re.finditer(r"\d+", canonical)) + assume(runs) + run = draw(st.sampled_from(runs)) + replacement = draw(st.sampled_from(_respellings(run.group()))) + key = canonical[: run.start()] + replacement + canonical[run.end() :] + assume(key != canonical) + return key + + +TRAVERSAL_KEYS = [ + # Percent-encoded on purpose. An HTTP client resolves dot-segments before + # it sends -- httpx turns "../secret" into "/secret" and ".." into "/" per + # RFC 3986 Β§5.2.4 -- so a literal "../" probe never reaches the server as + # traversal and asserts nothing. Encoded, it survives the client intact + # and Starlette decodes it back into a real ".." segment on arrival, which + # is the form the server's own guard has to catch. + "..%2Fsecret", + "%2e%2e%2Fsecret", + "%2e%2e%2F%2e%2e%2Fetc%2Fpasswd", + "%2e%2e", + "%2e", + "%2e%2Fzarr.json", + "a%2F..%2F..%2Fb", + "%2Fabsolute", + "sub%2F%2Fempty", + "C%3A%2Fwindows", + "..%5Cwindows", + "a%5C..%5C..%5Cb", + "%00nul", +] + + +def _chunk_payload(array: Array[Any]) -> bytes: + """Bytes of a full, uncompressed chunk for *array*.""" + return np.zeros(_CHUNKS, dtype=array.dtype).tobytes() + + +def _url(served: Served, array_relative_key: str) -> str: + """Request URL for a key, percent-encoded so it survives the wire verbatim. + + Generated keys contain characters a URL cannot carry literally -- a tab + makes httpx raise `InvalidURL`, and a space or a non-ASCII digit would be + re-encoded on the way out anyway. Encoding here means Starlette decodes + the path param back to exactly the key the strategy produced, so the + property really is "for any key K, a request for K is refused" rather than + "for any key the URL parser happened to leave alone". + """ + return f"{served.url}/{quote(served.path(array_relative_key), safe='/')}" + + +def _require_node_scope(served: Served) -> None: + """Skip a property that only a node-scoped app can satisfy. + + `store_app` proxies the store's raw key space and has no array semantics + to validate against, so every syntactically acceptable key is in-band for + it by contract -- including a non-canonical chunk spelling. Only + `node_app` claims to serve exactly one node's keys, so only `node_app` can + be held to what that set contains. + """ + if served.kind != "node": + pytest.skip("store_app serves the raw key space; node scoping does not apply") + + +class TestInBandRequests: + """Keys the node owns are served, and writes to them are visible.""" + + @given(data=st.data()) + @_HTTP + def test_get_of_a_canonical_key_returns_the_stored_bytes( + self, served: Served, data: st.DataObject + ) -> None: + """A GET of an in-band key returns exactly what the store holds, and + reading never changes the store.""" + coords = data.draw(chunk_coords(served.array)) + relative = served.array.metadata.encode_chunk_key(coords) + + before = _snapshot(served.store) + response = httpx.get(_url(served, relative), timeout=30) + + expected = before.get(served.store_key(relative)) + if expected is None: + assert response.status_code == 404 + else: + assert response.status_code == 200 + assert response.content == expected + assert _snapshot(served.store) == before + + @given(data=st.data()) + @_HTTP + def test_put_of_a_canonical_key_is_stored_and_readable( + self, served: Served, data: st.DataObject + ) -> None: + """The headline property: a PUT that reports success must be visible. + + Success means three things at once -- a 2xx, the bytes landing under + the key the client named, and a zarr client subsequently reading back + the values that were written. The original defect satisfied the first + and failed the other two. + """ + coords = data.draw(chunk_coords(served.array)) + fill = data.draw(st.integers(min_value=-(2**31), max_value=2**31 - 1)) + relative = served.array.metadata.encode_chunk_key(coords) + payload = np.full(_CHUNKS, fill, dtype=served.array.dtype).tobytes() + + before = _snapshot(served.store) + response = httpx.put(_url(served, relative), content=payload, timeout=30) + assert response.status_code == 204 + + after = _snapshot(served.store) + key = served.store_key(relative) + assert after[key] == payload, "the body did not land under the key the client named" + assert set(after) - set(before) <= {key}, "the write touched a key the client did not name" + + # The write is not merely present, it is legible: reopen the array and + # read the chunk the coordinates address. + reread = zarr.open_array(served.store, path="inside") + block = tuple(slice(c * s, (c + 1) * s) for c, s in zip(coords, _CHUNKS, strict=True)) + assert np.array_equal(reread[block], np.full(_CHUNKS, fill, dtype=served.array.dtype)) + + @given(data=st.data()) + @_HTTP + def test_range_of_a_stored_key_returns_the_matching_slice( + self, served: Served, data: st.DataObject + ) -> None: + """A satisfiable range returns exactly the bytes it names, and says so + in Content-Range.""" + relative = served.array.metadata.encode_chunk_key(tuple(0 for _ in _grid(served.array))) + key = served.store_key(relative) + before = _snapshot(served.store) + assume(key in before) + body = before[key] + + start = data.draw(st.integers(min_value=0, max_value=len(body) - 1)) + end = data.draw(st.integers(min_value=start, max_value=len(body) - 1)) + + response = httpx.get( + _url(served, relative), headers={"Range": f"bytes={start}-{end}"}, timeout=30 + ) + + assert response.status_code == 206 + assert response.content == body[start : end + 1] + # RFC 9110 Β§15.3.7: a single-part 206 must carry Content-Range, and it + # must describe the bytes actually returned. + content_range = response.headers["content-range"] + assert content_range.startswith(f"bytes {start}-{start + len(response.content) - 1}/") + assert _snapshot(served.store) == before + + @given(suffix=st.integers(min_value=1, max_value=200)) + @_HTTP + def test_suffix_range_returns_the_tail_and_locates_it( + self, served: Served, suffix: int + ) -> None: + """A suffix range must report where in the object its bytes came from. + + Zarr's sharding codec reads a shard index this way, so a 206 without + Content-Range leaves the reader unable to tell a clamped whole-object + read from the tail it asked for. + """ + relative = served.array.metadata.encode_chunk_key(tuple(0 for _ in _grid(served.array))) + key = served.store_key(relative) + before = _snapshot(served.store) + assume(key in before) + body = before[key] + + response = httpx.get( + _url(served, relative), headers={"Range": f"bytes=-{suffix}"}, timeout=30 + ) + + assert response.status_code == 206 + expected = body[-suffix:] if suffix <= len(body) else body + assert response.content == expected + first = len(body) - len(expected) + assert response.headers["content-range"].startswith(f"bytes {first}-{len(body) - 1}/") + assert _snapshot(served.store) == before + + +class TestOutOfBandRequests: + """Keys the node does not own are refused, and change nothing.""" + + @given(data=st.data()) + @_HTTP + def test_non_canonical_chunk_key_is_refused_and_writes_nothing( + self, served: Served, data: st.DataObject + ) -> None: + """The regression that motivated this module. + + A key that decodes into the grid but is spelled differently from + zarr's own rendering names a store key no reader consults. Accepting a + write to it reports success and loses the data, so it must be refused + and the store must be untouched. + """ + _require_node_scope(served) + relative = data.draw(non_canonical_chunk_keys(served.array)) + payload = _chunk_payload(served.array) + + before = _snapshot(served.store) + put = httpx.put(_url(served, relative), content=payload, timeout=30) + assert put.status_code == 404 + assert _snapshot(served.store) == before, "a refused write still modified the store" + + get = httpx.get(_url(served, relative), timeout=30) + assert get.status_code == 404 + assert _snapshot(served.store) == before + + @given(data=st.data()) + @_HTTP + def test_out_of_grid_chunk_key_is_refused_and_writes_nothing( + self, served: Served, data: st.DataObject + ) -> None: + """Coordinates past the end of the grid address no chunk of this array.""" + _require_node_scope(served) + coords = data.draw(out_of_grid_coords(served.array)) + relative = served.array.metadata.encode_chunk_key(coords) + + before = _snapshot(served.store) + put = httpx.put(_url(served, relative), content=_chunk_payload(served.array), timeout=30) + get = httpx.get(_url(served, relative), timeout=30) + + assert put.status_code == 404 + assert get.status_code == 404 + assert _snapshot(served.store) == before + + @given(key=st.sampled_from(TRAVERSAL_KEYS)) + @_HTTP + def test_traversal_key_is_refused_and_writes_nothing(self, served: Served, key: str) -> None: + """Nothing that tries to leave the served scope may be served or written.""" + before = _snapshot(served.store) + put = httpx.put(f"{served.url}/{key}", content=b"payload", timeout=30) + get = httpx.get(f"{served.url}/{key}", timeout=30) + + assert put.status_code in (403, 404, 405), f"{key!r} was accepted for writing" + assert get.status_code in (403, 404, 405), f"{key!r} was served" + assert _snapshot(served.store) == before + + @given(data=st.data()) + @_HTTP + def test_node_app_never_serves_a_sibling(self, served: Served, data: st.DataObject) -> None: + """A node_app is scoped to one node, so a sibling's keys are invisible + even though they exist in the same store.""" + if served.kind != "node": + pytest.skip("store_app deliberately serves the whole store") + + coords = data.draw(chunk_coords(served.array)) + chunk = served.array.metadata.encode_chunk_key(coords) + relative = data.draw( + st.sampled_from( + [ + f"outside/{chunk}", + "outside/zarr.json", + "outside/.zarray", + f"../outside/{chunk}", + ] + ) + ) + + before = _snapshot(served.store) + get = httpx.get(f"{served.url}/{relative}", timeout=30) + put = httpx.put(f"{served.url}/{relative}", content=b"payload", timeout=30) + + assert get.status_code == 404 + assert put.status_code == 404 + assert _snapshot(served.store) == before + + +class TestMethodsAndRanges: + """Transport-level invariants that hold for every key.""" + + @given( + method=st.sampled_from(["DELETE", "POST", "PATCH", "OPTIONS"]), + data=st.data(), + ) + @_HTTP + def test_unconfigured_method_is_refused_and_writes_nothing( + self, served: Served, method: str, data: st.DataObject + ) -> None: + """Only the methods the app was configured with may reach the store.""" + coords = data.draw(chunk_coords(served.array)) + relative = served.array.metadata.encode_chunk_key(coords) + + before = _snapshot(served.store) + response = httpx.request(method, _url(served, relative), content=b"payload", timeout=30) + + assert response.status_code == 405 + assert _snapshot(served.store) == before + + @given( + header=st.sampled_from( + [ + "bytes=abc-def", + "bytes=0-1,4-5", + "chars=0-7", + "bytes=", + "nonsense", + "bytes=+0-1", + ] + ) + ) + @_HTTP + def test_unusable_range_serves_the_whole_object(self, served: Served, header: str) -> None: + """RFC 9110 Β§14.2: a Range the server cannot use is ignored, not refused.""" + relative = served.array.metadata.encode_chunk_key(tuple(0 for _ in _grid(served.array))) + before = _snapshot(served.store) + key = served.store_key(relative) + assume(key in before) + + response = httpx.get(_url(served, relative), headers={"Range": header}, timeout=30) + + assert response.status_code == 200 + assert response.content == before[key] + assert "content-range" not in response.headers + + @given( + header=st.sampled_from( + [ + "bytes=5-2", + "bytes=-0", + "bytes=99999999999999999999-", + "bytes=100000-100001", + ] + ) + ) + @_HTTP + def test_unsatisfiable_range_is_refused(self, served: Served, header: str) -> None: + """A well-formed range that names nothing readable is a 416.""" + relative = served.array.metadata.encode_chunk_key(tuple(0 for _ in _grid(served.array))) + before = _snapshot(served.store) + assume(served.store_key(relative) in before) + + response = httpx.get(_url(served, relative), headers={"Range": header}, timeout=30) + + assert response.status_code == 416 + assert _snapshot(served.store) == before + + @given(end=st.integers(min_value=10**19, max_value=10**30)) + @_HTTP + def test_absurdly_wide_range_is_clamped_not_refused(self, served: Served, end: int) -> None: + """RFC 9110 Β§14.1.2 clamps a last-byte-pos past the end of the object, + so an over-wide range reads to EOF rather than erroring.""" + relative = served.array.metadata.encode_chunk_key(tuple(0 for _ in _grid(served.array))) + key = served.store_key(relative) + before = _snapshot(served.store) + assume(key in before) + + response = httpx.get( + _url(served, relative), headers={"Range": f"bytes=0-{end}"}, timeout=30 + ) + + assert response.status_code == 206 + assert response.content == before[key] + assert _snapshot(served.store) == before diff --git a/packages/zarr-http-server/tests/test_serve.py b/packages/zarr-http-server/tests/test_serve.py new file mode 100644 index 0000000000..8db6752ba1 --- /dev/null +++ b/packages/zarr-http-server/tests/test_serve.py @@ -0,0 +1,1831 @@ +from __future__ import annotations + +import asyncio +import errno +import os +import socket +from typing import TYPE_CHECKING, Any, Literal, get_args + +import numpy as np +import pytest +import zarr +from starlette.applications import Starlette +from starlette.routing import Mount +from starlette.testclient import TestClient +from zarr.buffer import cpu +from zarr.storage import LocalStore, MemoryStore + +from zarr_http_server._serve import ( + _SHUTDOWN_JOIN_MARGIN, + READ_ONLY_HTTP_METHODS, + READ_WRITE_HTTP_METHODS, + CorsOptions, + ReadOnlyHTTPMethod, + _bind_preferred_or_free, + _parse_range_header, + _RangeVerdict, + node_app, + serve_background, + store_app, +) + +if TYPE_CHECKING: + import pathlib + from collections.abc import Coroutine, Iterator + + from zarr.abc.store import Store + +ZarrFormat = Literal[2, 3] + +SHUTDOWN_TIMEOUT = 1 +"""shutdown_timeout used by the bounded-shutdown test.""" + +SLOW_HANDLER_SECONDS = 5 +"""How long that test's handler sleeps -- far longer than the shutdown bound, +so an unbounded join would be obvious.""" + + +def sync[T](coro: Coroutine[Any, Any, T]) -> T: + """Run a store coroutine to completion (tests use MemoryStore only).""" + return asyncio.run(coro) + + +@pytest.fixture +def group_with_arrays(store: Store) -> zarr.Group: + """Create a group containing a regular array and a sharded array.""" + root = zarr.open_group(store, mode="w") + zarr.create_array(root.store_path / "regular", shape=(4, 4), chunks=(2, 2), dtype="f8") + zarr.create_array( + root.store_path / "sharded", + shape=(8, 8), + chunks=(2, 2), + shards=(4, 4), + dtype="i4", + ) + return root + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestNodeAppDoesNotExposeNonZarrKeys: + """node_app must never expose keys that are not part of the zarr hierarchy.""" + + def test_non_zarr_key_returns_404(self, store: Store, group_with_arrays: zarr.Group) -> None: + """A key that is not valid zarr metadata or a valid chunk key should return 404, + even if the underlying store contains data at that path.""" + non_zarr_buf = cpu.buffer_prototype.buffer.from_bytes(b"secret data") + sync(store.set("secret.txt", non_zarr_buf)) + + app = node_app(group_with_arrays) + client = TestClient(app) + + # The non-zarr key must not be accessible. + response = client.get("/secret.txt") + assert response.status_code == 404 + + def test_non_zarr_key_nested_returns_404( + self, store: Store, group_with_arrays: zarr.Group + ) -> None: + """A non-zarr key nested under a real array's path should return 404, + even though the path prefix matches a valid zarr node.""" + non_zarr_buf = cpu.buffer_prototype.buffer.from_bytes(b"not a chunk") + sync(store.set("regular/notes.txt", non_zarr_buf)) + + app = node_app(group_with_arrays) + client = TestClient(app) + + response = client.get("/regular/notes.txt") + assert response.status_code == 404 + + def test_valid_metadata_is_accessible(self, group_with_arrays: zarr.Group) -> None: + """Zarr metadata keys (zarr.json) for both the root group and child arrays + should be served with a 200 status.""" + app = node_app(group_with_arrays) + client = TestClient(app) + + # Root group metadata + response = client.get("/zarr.json") + assert response.status_code == 200 + + # Array metadata + response = client.get("/regular/zarr.json") + assert response.status_code == 200 + + def test_valid_chunk_is_accessible(self, group_with_arrays: zarr.Group) -> None: + """A valid, in-bounds chunk key for an array with written data should + be served with a 200 status.""" + arr = group_with_arrays["regular"] + assert isinstance(arr, zarr.Array) + arr[:] = np.ones((4, 4)) + + app = node_app(group_with_arrays) + client = TestClient(app) + + # c/0/0 is a valid chunk key for a (4,4) array with (2,2) chunks. + response = client.get("/regular/c/0/0") + assert response.status_code == 200 + + def test_out_of_bounds_chunk_key_returns_404( + self, store: Store, group_with_arrays: zarr.Group + ) -> None: + """A chunk key that is syntactically valid but references indices beyond + the array's chunk grid should return 404.""" + arr = group_with_arrays["regular"] + assert isinstance(arr, zarr.Array) + arr[:] = np.ones((4, 4)) + + # Put real data at the out-of-grid key, so that a 404 can only come + # from the bounds check -- not from the key merely being absent. + planted = cpu.buffer_prototype.buffer.from_bytes(b"out of grid") + sync(store.set("regular/c/99/99", planted)) + assert sync(store.get("regular/c/99/99", cpu.buffer_prototype)) is not None + + app = node_app(group_with_arrays) + client = TestClient(app) + + # (4,4) array with (2,2) chunks has grid shape (2,2), so c/99/99 is + # syntactically valid but out of bounds. + response = client.get("/regular/c/99/99") + assert response.status_code == 404 + + def test_empty_path_returns_404(self, group_with_arrays: zarr.Group) -> None: + """A request to the root path '/' should return 404 because an empty + string is not a valid zarr key.""" + app = node_app(group_with_arrays) + client = TestClient(app) + + response = client.get("/") + assert response.status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestShardedArrayByteRangeReads: + """Byte-range reads against a sharded array served via node_app.""" + + def test_range_read_returns_206(self, group_with_arrays: zarr.Group) -> None: + """A Range header requesting a specific byte range (e.g. bytes=0-7) should + return 206 Partial Content with exactly those bytes.""" + arr = group_with_arrays["sharded"] + assert isinstance(arr, zarr.Array) + arr[:] = np.arange(64, dtype="i4").reshape((8, 8)) + + app = node_app(group_with_arrays) + client = TestClient(app) + + # c/0/0 is the first shard key for an (8,8) array with (4,4) shards. + full_response = client.get("/sharded/c/0/0") + assert full_response.status_code == 200 + full_body = full_response.content + + # Request the first 8 bytes. + range_response = client.get("/sharded/c/0/0", headers={"Range": "bytes=0-7"}) + assert range_response.status_code == 206 + assert range_response.content == full_body[:8] + + def test_suffix_range_read(self, group_with_arrays: zarr.Group) -> None: + """A suffix byte range (e.g. bytes=-4) should return the last N bytes + of the resource with a 206 status.""" + arr = group_with_arrays["sharded"] + assert isinstance(arr, zarr.Array) + arr[:] = np.arange(64, dtype="i4").reshape((8, 8)) + + app = node_app(group_with_arrays) + client = TestClient(app) + + full_response = client.get("/sharded/c/0/0") + full_body = full_response.content + + # Request the last 4 bytes. + range_response = client.get("/sharded/c/0/0", headers={"Range": "bytes=-4"}) + assert range_response.status_code == 206 + assert range_response.content == full_body[-4:] + + def test_offset_range_read(self, group_with_arrays: zarr.Group) -> None: + """An offset byte range (e.g. bytes=4-) should return all bytes from + the given offset to the end, with a 206 status.""" + arr = group_with_arrays["sharded"] + assert isinstance(arr, zarr.Array) + arr[:] = np.arange(64, dtype="i4").reshape((8, 8)) + + app = node_app(group_with_arrays) + client = TestClient(app) + + full_response = client.get("/sharded/c/0/0") + full_body = full_response.content + + # Request everything from byte 4 onward. + range_response = client.get("/sharded/c/0/0", headers={"Range": "bytes=4-"}) + assert range_response.status_code == 206 + assert range_response.content == full_body[4:] + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestUnusableRangeHeadersAreIgnored: + """A Range this server cannot turn into a read is ignored, not refused. + + RFC 9110 Β§14.2 requires ignoring a Range whose unit is unrecognized and + permits ignoring one that will not parse; either way the answer is 200 + with the full representation. Refusing with 416 would tell a client the + object is unreadable when only the request shape was unsupported -- and + a multi-range request, which is legal to send and which proxies and + download accelerators do send, would take that at face value. + """ + + @pytest.mark.parametrize( + "header", + [ + "bytes=abc-def", + "bytes=-abc", + "bytes=abc-", + "bytes=0-7,10-20", + "chars=0-7", + "bytes=", + "bytes=+0-1", + ], + ) + def test_unusable_range_serves_full_representation(self, store: Store, header: str) -> None: + """Non-numeric bounds, multi-range, a non-'bytes' unit, an empty spec + and a non-canonical byte position all fall back to a plain 200.""" + body = b"some data here" + sync(store.set("key", cpu.buffer_prototype.buffer.from_bytes(body))) + + client = TestClient(store_app(store), raise_server_exceptions=False) + + response = client.get("/key", headers={"Range": header}) + assert response.status_code == 200 + assert response.content == body + assert "content-range" not in response.headers + + +class TestParseRangeHeader: + """Unit tests for _parse_range_header.""" + + def test_parser_rejects_an_inverted_range(self) -> None: + """Pin the parser itself: on a MemoryStore an unguarded inverted range + happens to return b"" and still yields 416, so the status code alone + cannot tell whether the guard is present.""" + assert _parse_range_header("bytes=5-2") is _RangeVerdict.UNSATISFIABLE + assert _parse_range_header("bytes=0-0") is not _RangeVerdict.UNSATISFIABLE + + def test_valid_range(self) -> None: + """'bytes=0-99' should parse into a RangeByteRequest with start=0 and + end=100 (end is exclusive, so the inclusive HTTP end is incremented).""" + from zarr.abc.store import RangeByteRequest + + result = _parse_range_header("bytes=0-99") + assert result == RangeByteRequest(start=0, end=100) + + def test_valid_suffix(self) -> None: + """'bytes=-50' should parse into a SuffixByteRequest requesting the + last 50 bytes of the resource.""" + from zarr.abc.store import SuffixByteRequest + + result = _parse_range_header("bytes=-50") + assert result == SuffixByteRequest(suffix=50) + + def test_valid_offset(self) -> None: + """'bytes=10-' should parse into an OffsetByteRequest starting at + byte 10 and reading to the end of the resource.""" + from zarr.abc.store import OffsetByteRequest + + result = _parse_range_header("bytes=10-") + assert result == OffsetByteRequest(offset=10) + + def test_non_bytes_unit(self) -> None: + """An unrecognized range unit must be ignored, per RFC 9110 Β§14.2.""" + assert _parse_range_header("chars=0-7") is _RangeVerdict.IGNORE + + def test_garbage_values(self) -> None: + """Non-numeric bounds are ignored rather than raising a ValueError.""" + assert _parse_range_header("bytes=abc-def") is _RangeVerdict.IGNORE + + def test_multi_range(self) -> None: + """Multi-range requests (e.g. bytes=0-7,10-20) are legal to send; this + server does not build multipart/byteranges, so it serves the whole + representation instead of refusing.""" + assert _parse_range_header("bytes=0-7,10-20") is _RangeVerdict.IGNORE + + def test_empty_spec(self) -> None: + """A Range header with no range specifier after 'bytes=' is ignored.""" + assert _parse_range_header("bytes=") is _RangeVerdict.IGNORE + + def test_non_canonical_byte_position(self) -> None: + """`int` would accept these; RFC 9110 defines a byte position as + 1*DIGIT, so they are not ranges and the header is ignored.""" + assert _parse_range_header("bytes=+0-1") is _RangeVerdict.IGNORE + assert _parse_range_header("bytes= 0-1") is _RangeVerdict.IGNORE + assert _parse_range_header("bytes=0_0-1") is _RangeVerdict.IGNORE + + def test_oversized_start_is_unsatisfiable(self) -> None: + """A first-byte-pos past any possible object names nothing.""" + assert _parse_range_header("bytes=99999999999999999999-") is _RangeVerdict.UNSATISFIABLE + + def test_zero_length_suffix_is_unsatisfiable(self) -> None: + """ "The last zero bytes" names nothing.""" + assert _parse_range_header("bytes=-0") is _RangeVerdict.UNSATISFIABLE + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestWriteViaPut: + """store_app and node_app can be configured to accept PUT writes.""" + + def test_put_writes_to_store(self, store: Store) -> None: + """A PUT request to store_app with PUT enabled should write the + request body into the store at the given key.""" + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + payload = b"hello zarr" + response = client.put("/some/key", content=payload) + assert response.status_code == 204 + + # Verify the data landed in the store. + buf = sync(store.get("some/key", cpu.buffer_prototype)) + assert buf is not None + assert buf.to_bytes() == payload + + def test_put_then_get_roundtrip(self, store: Store) -> None: + """Data written via PUT should be retrievable via a subsequent GET + at the same key.""" + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + payload = b"\x00\x01\x02\x03" + client.put("/data/blob", content=payload) + + response = client.get("/data/blob") + assert response.status_code == 200 + assert response.content == payload + + def test_put_rejected_when_not_configured(self, store: Store) -> None: + """PUT requests should return 405 Method Not Allowed when the server + is created with the default methods (GET only).""" + app = store_app(store) + client = TestClient(app) + + response = client.put("/some/key", content=b"data") + assert response.status_code == 405 + + def test_put_on_node_validates_key(self, store: Store, group_with_arrays: zarr.Group) -> None: + """PUT requests via node_app should be rejected with 404 when the + target key is not a valid zarr key (metadata or chunk).""" + app = node_app(group_with_arrays, methods={"GET", "PUT"}) + client = TestClient(app) + + response = client.put("/not_a_zarr_key.bin", content=b"data") + assert response.status_code == 404 + + def test_put_to_valid_chunk_key_succeeds(self, group_with_arrays: zarr.Group) -> None: + """PUT requests via node_app to a valid chunk key should succeed + with 204, and the written data should be retrievable via GET.""" + app = node_app(group_with_arrays, methods={"GET", "PUT"}) + client = TestClient(app) + + payload = b"\x00" * 32 + response = client.put("/regular/c/0/0", content=payload) + assert response.status_code == 204 + + # Confirm it round-trips. + get_response = client.get("/regular/c/0/0") + assert get_response.status_code == 200 + assert get_response.content == payload + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestMethodValidation: + """Only the methods the handler implements may be served.""" + + def test_supported_methods_are_served(self, store: Store) -> None: + """GET, PUT and HEAD each behave as their verb implies.""" + app = store_app(store, methods={"GET", "PUT", "HEAD"}) + client = TestClient(app) + + assert client.put("/zarr.json", content=b'{"a":1}').status_code == 204 + assert client.get("/zarr.json").content == b'{"a":1}' + + # HEAD reports the same status as GET but carries no body. + head = client.head("/zarr.json") + assert head.status_code == 200 + assert head.content == b"" + + def test_empty_method_set_raises(self, store: Store) -> None: + """Asking for no methods must be rejected rather than producing a + server that answers every verb, including writes: Starlette treats a + falsy `methods` on a Route as "match anything".""" + for build in ( + lambda: store_app(store, methods=set()), + lambda: node_app(zarr.open_group(store, mode="a"), methods=set()), + ): + with pytest.raises(ValueError, match="at least one"): + build() + + @pytest.mark.parametrize("method", ["DELETE", "POST", "PATCH", "OPTIONS", "TRACE"]) + def test_unsupported_method_raises(self, store: Store, method: str) -> None: + """A verb the handler cannot implement is rejected when the app is + built, rather than silently answering as if it were a GET.""" + for build in ( + lambda: store_app(store, methods={"GET", method}), # type: ignore[arg-type] + lambda: node_app(zarr.open_group(store, mode="a"), methods={"GET", method}), # type: ignore[arg-type] + ): + with pytest.raises(ValueError, match=method): + build() + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestStoreAppEdgeCases: + """Edge cases for store_app.""" + + def test_get_nonexistent_key_returns_404(self, store: Store) -> None: + """GET for a key that does not exist in the store should return 404.""" + app = store_app(store) + client = TestClient(app) + + response = client.get("/no/such/key") + assert response.status_code == 404 + + def test_empty_path_returns_404(self, store: Store) -> None: + """GET to the root path '/' (empty key) should return 404 because + an empty string is not a valid store key.""" + app = store_app(store) + client = TestClient(app) + + response = client.get("/") + assert response.status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestNodeAppDirectArray: + """Serve a single array directly (not through a group).""" + + def test_serve_nested_array_directly(self, store: Store) -> None: + """When node_app is given a nested array (not a group), requests + should use keys relative to that array's path. Metadata and in-bounds + chunks should return 200, and out-of-bounds chunks should return 404.""" + root = zarr.open_group(store, mode="w") + arr = zarr.create_array( + root.store_path / "sub/nested", + shape=(4,), + chunks=(2,), + dtype="f8", + ) + arr[:] = np.arange(4, dtype="f8") + + # Serve the array directly β€” its prefix is "sub/nested". + app = node_app(arr) + client = TestClient(app) + + # Metadata should be accessible at the array root. + response = client.get("/zarr.json") + assert response.status_code == 200 + + # Chunk keys are relative to the array. + response = client.get("/c/0") + assert response.status_code == 200 + + response = client.get("/c/1") + assert response.status_code == 200 + + # Out of bounds. + response = client.get("/c/99") + assert response.status_code == 404 + + def test_serve_root_array(self, store: Store) -> None: + """When node_app is given an array stored at the root of a store + (empty prefix), metadata and chunk keys should be accessible at + their natural paths.""" + arr = zarr.create_array( + store, + shape=(6,), + chunks=(3,), + dtype="i4", + ) + arr[:] = np.arange(6, dtype="i4") + + # Root-level array has prefix = "". + app = node_app(arr) + client = TestClient(app) + + response = client.get("/zarr.json") + assert response.status_code == 200 + + response = client.get("/c/0") + assert response.status_code == 200 + + response = client.get("/c/1") + assert response.status_code == 200 + + response = client.get("/c/2") + assert response.status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestContentType: + """Responses should have the correct Content-Type.""" + + def test_metadata_has_json_content_type(self, group_with_arrays: zarr.Group) -> None: + """Zarr metadata files (zarr.json) should be served with + Content-Type: application/json.""" + app = node_app(group_with_arrays) + client = TestClient(app) + + response = client.get("/zarr.json") + assert response.status_code == 200 + assert response.headers["content-type"] == "application/json" + + def test_chunk_has_octet_stream_content_type(self, group_with_arrays: zarr.Group) -> None: + """Chunk data should be served with Content-Type: application/octet-stream + since it is binary data.""" + arr = group_with_arrays["regular"] + assert isinstance(arr, zarr.Array) + arr[:] = np.ones((4, 4)) + + app = node_app(group_with_arrays) + client = TestClient(app) + + response = client.get("/regular/c/0/0") + assert response.status_code == 200 + assert response.headers["content-type"] == "application/octet-stream" + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestCorsMiddleware: + """CORS middleware should add the expected headers.""" + + def test_cors_headers_present(self, store: Store) -> None: + """When cors_options are provided, responses should include the + Access-Control-Allow-Origin header matching the request origin.""" + buf = cpu.buffer_prototype.buffer.from_bytes(b"data") + sync(store.set("key", buf)) + + cors = CorsOptions(allow_origins=["https://example.com"], allow_methods=["GET"]) + app = store_app(store, cors_options=cors) + client = TestClient(app) + + response = client.get("/key", headers={"Origin": "https://example.com"}) + assert response.status_code == 200 + assert response.headers["access-control-allow-origin"] == "https://example.com" + + def test_cors_preflight(self, store: Store) -> None: + """CORS preflight OPTIONS requests should return 200 with the + Access-Control-Allow-Origin header when CORS is configured.""" + cors = CorsOptions(allow_origins=["*"], allow_methods=["GET", "PUT"]) + app = store_app(store, methods={"GET", "PUT"}, cors_options=cors) + client = TestClient(app) + + response = client.options( + "/any/path", + headers={ + "Origin": "https://example.com", + "Access-Control-Request-Method": "PUT", + }, + ) + assert response.status_code == 200 + assert "access-control-allow-origin" in response.headers + + def test_no_cors_headers_without_option(self, store: Store) -> None: + """When no cors_options are provided, responses should not include + any CORS headers, even if the request includes an Origin header.""" + buf = cpu.buffer_prototype.buffer.from_bytes(b"data") + sync(store.set("key", buf)) + + app = store_app(store) + client = TestClient(app) + + response = client.get("/key", headers={"Origin": "https://example.com"}) + assert response.status_code == 200 + assert "access-control-allow-origin" not in response.headers + + +def _metadata_key(zarr_format: ZarrFormat) -> str: + """Return the metadata key for the given zarr format.""" + return "zarr.json" if zarr_format == 3 else ".zarray" + + +def _chunk_key(zarr_format: ZarrFormat, coords: str) -> str: + """Return a chunk key for the given format. + + *coords* is a dot-separated string like ``"0.0"``. For v3 this becomes + ``"c/0/0"``; for v2 it is returned unchanged. + """ + if zarr_format == 3: + return "c/" + coords.replace(".", "/") + return coords + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestNodeAppV2AndV3: + """Test node_app with both v2 and v3 arrays side by side.""" + + def test_metadata_accessible(self, store: Store, zarr_format: ZarrFormat) -> None: + """The format-appropriate metadata key should be served with 200.""" + arr = zarr.create_array(store, shape=(4,), chunks=(2,), dtype="f8", zarr_format=zarr_format) + app = node_app(arr) + client = TestClient(app) + + response = client.get(f"/{_metadata_key(zarr_format)}") + assert response.status_code == 200 + + def test_chunk_accessible(self, store: Store, zarr_format: ZarrFormat) -> None: + """An in-bounds chunk key should be served with 200 for both formats.""" + arr = zarr.create_array(store, shape=(4,), chunks=(2,), dtype="f8", zarr_format=zarr_format) + arr[:] = np.ones(4) + + app = node_app(arr) + client = TestClient(app) + + response = client.get(f"/{_chunk_key(zarr_format, '0')}") + assert response.status_code == 200 + + def test_out_of_bounds_chunk_returns_404(self, store: Store, zarr_format: ZarrFormat) -> None: + """An out-of-bounds chunk key should return 404 for both formats.""" + arr = zarr.create_array(store, shape=(4,), chunks=(2,), dtype="f8", zarr_format=zarr_format) + arr[:] = np.ones(4) + + # Plant data at the out-of-grid key so the 404 must come from the + # bounds check rather than from the key being absent. + key = _chunk_key(zarr_format, "99") + sync(store.set(key, cpu.buffer_prototype.buffer.from_bytes(b"out of grid"))) + assert sync(store.get(key, cpu.buffer_prototype)) is not None + + app = node_app(arr) + client = TestClient(app) + + response = client.get(f"/{key}") + assert response.status_code == 404 + + def test_non_zarr_key_returns_404(self, store: Store, zarr_format: ZarrFormat) -> None: + """A non-zarr key should return 404 regardless of format.""" + arr = zarr.create_array(store, shape=(4,), chunks=(2,), dtype="f8", zarr_format=zarr_format) + non_zarr_buf = cpu.buffer_prototype.buffer.from_bytes(b"secret") + sync(store.set("secret.txt", non_zarr_buf)) + + app = node_app(arr) + client = TestClient(app) + + response = client.get("/secret.txt") + assert response.status_code == 404 + + def test_data_roundtrip(self, store: Store, zarr_format: ZarrFormat) -> None: + """Data written to an array should be readable via store_app for + both formats.""" + arr = zarr.create_array(store, shape=(4,), chunks=(2,), dtype="f8", zarr_format=zarr_format) + arr[:] = np.arange(4, dtype="f8") + + app = store_app(store) + client = TestClient(app) + + # Metadata should be accessible. + response = client.get(f"/{_metadata_key(zarr_format)}") + assert response.status_code == 200 + + # First chunk should be accessible. + response = client.get(f"/{_chunk_key(zarr_format, '0')}") + assert response.status_code == 200 + assert len(response.content) > 0 + + +class TestPathTraversalProtection: + """store_app and node_app must reject path-traversal attempts before + touching the store, regardless of URL-encoding tricks.""" + + def test_get_traversal_outside_store_root_returns_404(self, tmp_path: Any) -> None: + """A GET for a percent-encoded '../secret.txt' must not escape the + store root and read a file outside it.""" + from zarr.storage import LocalStore + + root = tmp_path / "store_root" + root.mkdir() + secret = tmp_path / "secret.txt" + secret.write_text("top secret contents") + + store = LocalStore(root) + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + response = client.get("/..%2fsecret.txt") + assert response.status_code == 404 + assert b"top secret" not in response.content + + def test_put_traversal_outside_store_root_returns_404(self, tmp_path: Any) -> None: + """A PUT to a percent-encoded '../pwned.txt' must not escape the + store root and write a file outside it.""" + from zarr.storage import LocalStore + + root = tmp_path / "store_root" + root.mkdir() + pwned = tmp_path / "pwned.txt" + + store = LocalStore(root) + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + response = client.put("/..%2fpwned.txt", content=b"pwned") + assert response.status_code == 404 + assert not pwned.exists() + + @pytest.mark.parametrize( + ("encoded_path", "climb_depth"), + [ + ("/..%2fsecret.txt", 1), + ("/%2e%2e/secret.txt", 1), + ("/..%2f..%2fsecret.txt", 2), + ], + ) + def test_encoded_traversal_variants_return_404( + self, tmp_path: Any, encoded_path: str, climb_depth: int + ) -> None: + """Various percent-encoded traversal spellings must all be rejected. + + The store root is nested exactly ``climb_depth`` directories below + ``tmp_path`` and the secret lives at ``tmp_path/secret.txt`` -- the + exact location each traversal's ".." segments resolve to -- so a + case with a missing or deleted guard would actually reach the + secret instead of just returning 404 for an unrelated reason (e.g. + a two-level climb landing on a directory that happens to be empty). + """ + from zarr.storage import LocalStore + + parts = [f"level{i}" for i in range(climb_depth - 1)] + ["store_root"] + root = tmp_path.joinpath(*parts) + root.mkdir(parents=True) + secret = tmp_path / "secret.txt" + secret.write_text("top secret contents") + + store = LocalStore(root) + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + response = client.get(encoded_path) + assert response.status_code == 404 + assert b"top secret" not in response.content + + def test_get_absolute_key_bypass_returns_404(self, tmp_path: Any) -> None: + """A percent-encoded leading slash decodes to an ABSOLUTE path param + (e.g. request '/%2fetc%2fhostname' -> path param '/etc/hostname'). + '/etc/hostname'.split('/') -> ['', 'etc', 'hostname'] has no '.' or + '..' segment, so the two-element guard misses it, but LocalStore + resolves an absolute key by discarding its root entirely -- an + arbitrary-file read. The empty leading segment must be rejected.""" + from zarr.storage import LocalStore + + root = tmp_path / "store_root" + root.mkdir() + secret = tmp_path / "secret_abs.txt" + secret.write_text("top secret absolute contents") + + store = LocalStore(root) + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + # Mirror the exploit: percent-encode every "/" (including the + # leading one) in the absolute secret path as "%2f". + encoded_path = "/" + str(secret).replace("/", "%2f") + + response = client.get(encoded_path) + assert response.status_code == 404 + assert b"top secret absolute" not in response.content + assert secret.read_text() == "top secret absolute contents" + + def test_put_absolute_key_bypass_returns_404(self, tmp_path: Any) -> None: + """Same absolute-key vector as above, but for PUT: a percent-encoded + leading slash must not allow writing a file outside the store root.""" + from zarr.storage import LocalStore + + root = tmp_path / "store_root" + root.mkdir() + pwned = tmp_path / "pwned_abs.txt" + + store = LocalStore(root) + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + encoded_path = "/" + str(pwned).replace("/", "%2f") + + response = client.put(encoded_path, content=b"pwned") + assert response.status_code == 404 + assert not pwned.exists() + + @pytest.mark.parametrize( + "encoded_path", + [ + "/..%5C..%5Cwin.ini", + "/%5CWindows%5Cwin.ini", + "/C:/Windows/win.ini", + "/C:%5CWindows", + "/%5C%5Chost%5Cshare%5Cx", + ], + ) + def test_backslash_and_drive_traversal_variants_return_404(self, encoded_path: str) -> None: + """Backslash is a path separator on Windows, and a drive-qualified or + root-relative key discards a filesystem store's root entirely on + Windows, even though POSIX only ever treats '/' as a separator. The + guard must reject these purely from the string, before the store is + ever touched -- verified here by making the store raise if called.""" + from unittest.mock import AsyncMock + + from zarr.storage import MemoryStore + + store = MemoryStore() + store.get = AsyncMock(side_effect=AssertionError("store.get should not be called")) # type: ignore[method-assign] + store.set = AsyncMock(side_effect=AssertionError("store.set should not be called")) # type: ignore[method-assign] + + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + response = client.get(encoded_path) + assert response.status_code == 404 + + def test_put_backslash_traversal_returns_404(self) -> None: + """A PUT to a backslash-encoded '..\\..\\pwned.txt' must be rejected + before the store is touched, mirroring the GET case above.""" + from unittest.mock import AsyncMock + + from zarr.storage import MemoryStore + + store = MemoryStore() + store.set = AsyncMock(side_effect=AssertionError("store.set should not be called")) # type: ignore[method-assign] + + app = store_app(store, methods={"GET", "PUT"}) + client = TestClient(app) + + response = client.put("/..%5C..%5Cpwned.txt", content=b"pwned") + assert response.status_code == 404 + + +def _get_free_port() -> int: + """Return an unused TCP port on localhost.""" + import socket + + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + port: int = s.getsockname()[1] + return port + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestServeBackground: + """Test serve_background with store- and node-scoped apps.""" + + def test_background_server_over_a_store_app(self, store: Store) -> None: + """serve_background over a store app should return a BackgroundServer + that responds to HTTP requests and can be used as a context manager.""" + import httpx + + from zarr_http_server import serve_background + + buf = cpu.buffer_prototype.buffer.from_bytes(b"hello") + sync(store.set("key", buf)) + + port = _get_free_port() + with serve_background(store_app(store), host="127.0.0.1", port=port) as server: + assert server.host == "127.0.0.1" + assert server.port == port + assert server.url == f"http://127.0.0.1:{port}" + + response = httpx.get(f"{server.url}/key") + assert response.status_code == 200 + assert response.content == b"hello" + + def test_background_server_over_a_node_app(self, store: Store) -> None: + """serve_background over a node app should return a BackgroundServer + that responds to HTTP requests and can be used as a context manager.""" + import httpx + + from zarr_http_server import serve_background + + arr = zarr.create_array(store, shape=(4,), chunks=(2,), dtype="f8") + arr[:] = np.arange(4, dtype="f8") + + port = _get_free_port() + with serve_background(node_app(arr), host="127.0.0.1", port=port) as server: + response = httpx.get(f"{server.url}/zarr.json") + assert response.status_code == 200 + + +class TestStoreFailuresAreNotReportedAsMisses: + """Under the v3 spec an absent chunk is an uninitialized one, and a reader + is right to substitute the array's fill value for it. A 404 therefore + asserts something about the store's contents, and an I/O failure must not + borrow it -- that would have a correct client materialize fill values over + data that exists.""" + + @pytest.mark.skipif(os.geteuid() == 0, reason="root bypasses the permission bits under test") + def test_unreadable_key_is_a_server_error(self, tmp_path: pathlib.Path) -> None: + root = tmp_path / "root" + root.mkdir() + (root / "key").write_bytes(b"real data") + os.chmod(root / "key", 0o000) + + client = TestClient(store_app(LocalStore(str(root))), raise_server_exceptions=False) + try: + assert client.get("/key").status_code >= 500 + finally: + os.chmod(root / "key", 0o600) + + @pytest.mark.skipif(os.geteuid() == 0, reason="root bypasses the permission bits under test") + def test_unwritable_store_is_a_server_error(self, tmp_path: pathlib.Path) -> None: + root = tmp_path / "ro" + root.mkdir() + os.chmod(root, 0o500) + + client = TestClient( + store_app(LocalStore(str(root)), methods={"GET", "PUT"}), + raise_server_exceptions=False, + ) + try: + assert client.put("/key", content=b"data").status_code >= 500 + finally: + os.chmod(root, 0o700) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestShardGridBounds: + """A sharded array's storage grid is its shard grid, not its chunk grid.""" + + def test_out_of_shard_grid_key_returns_404(self, store: Store) -> None: + arr = zarr.create_array(store, shape=(8, 8), chunks=(2, 2), shards=(4, 4), dtype="i4") + arr[:] = np.arange(64, dtype="i4").reshape(8, 8) + + # (8,8) with (4,4) shards has a 2x2 shard grid, so c/3/3 is out of it. + # Plant data there so the 404 must come from the bounds check. + sync(store.set("c/3/3", cpu.buffer_prototype.buffer.from_bytes(b"PLANTED"))) + assert sync(store.get("c/3/3", cpu.buffer_prototype)) is not None + + client = TestClient(node_app(arr)) + assert client.get("/c/0/0").status_code == 200 + assert client.get("/c/3/3").status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestWrongArityChunkKeys: + """A chunk key with the wrong number of coordinates is invalid, and must + not reach the grid comparison -- zip(strict=True) would raise there.""" + + @pytest.mark.parametrize("key", ["c/0", "c/0/0/0", "c/0/0/0/0"]) + def test_wrong_arity_returns_404(self, store: Store, key: str) -> None: + arr = zarr.create_array(store, shape=(4, 4), chunks=(2, 2), dtype="f8") + arr[:] = np.ones((4, 4)) + + sync(store.set(key, cpu.buffer_prototype.buffer.from_bytes(b"PLANTED"))) + + client = TestClient(node_app(arr), raise_server_exceptions=False) + assert client.get(f"/{key}").status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestNodeNamesContainingAColon: + """A leading `:` is a drive reference to `ntpath`, so the guard rejects + it on every platform to keep it a pure string gate in front of any store. + The documented cost is that such a name is unreachable in the first + segment -- but only there.""" + + def test_colon_named_node_in_a_later_segment_is_served(self, store: Store) -> None: + root = zarr.open_group(store, mode="w") + sub = root.create_group("sub") + sub.create_array("a:b", shape=(2,), chunks=(2,), dtype="f8") + + client = TestClient(node_app(root)) + assert client.get("/sub/a:b/zarr.json").status_code == 200 + + def test_colon_named_node_in_the_first_segment_is_rejected(self, store: Store) -> None: + root = zarr.open_group(store, mode="w") + root.create_array("a:b", shape=(2,), chunks=(2,), dtype="f8") + + client = TestClient(node_app(root)) + assert client.get("/a:b/zarr.json").status_code == 404 + + +class TestChunkedBodyIsCapped: + """A chunked request carries no Content-Length, so the cap has to hold + while the body is being read rather than after it is buffered.""" + + def test_chunked_body_over_cap_is_rejected(self, tmp_path: pathlib.Path) -> None: + store = LocalStore(str(tmp_path / "root")) + client = TestClient( + store_app(store, methods={"GET", "PUT"}, max_body_size=64), + raise_server_exceptions=False, + ) + + def body() -> Iterator[bytes]: + for _ in range(20): + yield b"x" * 32 + + # httpx sends an iterator body with Transfer-Encoding: chunked. + assert client.put("/key", content=body()).status_code == 413 + assert not (tmp_path / "root" / "key").exists() + + +class TestHostileKeysAreNotServerErrors: + """A key the store cannot express is a miss, not a server fault: the + server must never answer 5xx for input a client can choose freely. + + This needs a filesystem-backed store -- a `MemoryStore` accepts any key + as a dict key, so only `LocalStore` surfaces the underlying errors (an + embedded NUL, a name longer than the filesystem allows). + """ + + @pytest.mark.parametrize( + "path", ["/x%00y", "/ok.txt%00", "/" + "a" * 3000, "/" + "b" * 3000 + "/zarr.json"] + ) + def test_unexpressable_key_returns_404_not_500(self, tmp_path: pathlib.Path, path: str) -> None: + store = LocalStore(str(tmp_path / "root")) + client = TestClient(store_app(store, methods={"GET", "PUT"})) + + assert client.get(path).status_code == 404 + assert client.put(path, content=b"x").status_code == 404 + + +class TestGenericStoreFailuresAreNotMisses: + """Only an error that answers about the *name* may become a 404. + + `ENAMETOOLONG` says no such name is expressible, which is an answer about + the key. `EINVAL` is POSIX's catch-all and is reachable on a perfectly + ordinary short key -- a bad seek, an unsupported filesystem feature -- so + reporting it as absence would have a v3 reader write fill values over a + chunk that exists but could not be read. + """ + + @staticmethod + def _store_failing_with(code: int) -> Store: + class Failing(MemoryStore): + async def get(self, key: str, prototype: Any, byte_range: Any = None) -> Any: + raise OSError(code, os.strerror(code)) + + async def set(self, key: str, value: Any) -> None: + raise OSError(code, os.strerror(code)) + + return Failing() + + def test_einval_is_not_reported_as_absent(self) -> None: + """The regression this class exists for.""" + client = TestClient( + store_app(self._store_failing_with(errno.EINVAL), methods={"GET", "PUT"}), + raise_server_exceptions=False, + ) + + assert client.get("/c/0/0").status_code >= 500 + assert client.put("/c/0/0", content=b"data").status_code >= 500 + + def test_enametoolong_is_still_a_miss(self) -> None: + """A name the store cannot express holds nothing, so 404 is honest.""" + client = TestClient( + store_app(self._store_failing_with(errno.ENAMETOOLONG), methods={"GET", "PUT"}), + raise_server_exceptions=False, + ) + + assert client.get("/c/0/0").status_code == 404 + assert client.put("/c/0/0", content=b"data").status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestPutBodyLimit: + """`Store.set` takes a whole buffer, so an unbounded body would let one + request size the server's memory use.""" + + def test_body_over_the_limit_is_rejected(self, store: Store) -> None: + client = TestClient(store_app(store, methods={"GET", "PUT"}, max_body_size=64)) + + assert client.put("/key", content=b"x" * 65).status_code == 413 + # Nothing was written. + assert sync(store.get("key", cpu.buffer_prototype)) is None + # A body within the limit still succeeds. + assert client.put("/key", content=b"x" * 64).status_code == 204 + + def test_limit_can_be_lifted(self, store: Store) -> None: + client = TestClient(store_app(store, methods={"GET", "PUT"}, max_body_size=None)) + assert client.put("/key", content=b"x" * 5000).status_code == 204 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestRangeResponseCorrectness: + """A 206 must describe which bytes it carries, and a range that cannot be + satisfied must say so rather than returning an empty 206.""" + + def test_206_carries_content_range(self, store: Store) -> None: + sync(store.set("key", cpu.buffer_prototype.buffer.from_bytes(b"0123456789"))) + client = TestClient(store_app(store)) + + response = client.get("/key", headers={"Range": "bytes=2-5"}) + assert response.status_code == 206 + assert response.content == b"2345" + assert response.headers["Content-Range"] == "bytes 2-5/*" + + def test_range_beyond_end_is_416(self, store: Store) -> None: + sync(store.set("key", cpu.buffer_prototype.buffer.from_bytes(b"0123456789"))) + client = TestClient(store_app(store)) + + assert client.get("/key", headers={"Range": "bytes=1000-2000"}).status_code == 416 + + def test_inverted_range_is_416(self, store: Store) -> None: + sync(store.set("key", cpu.buffer_prototype.buffer.from_bytes(b"0123456789"))) + client = TestClient(store_app(store)) + + assert client.get("/key", headers={"Range": "bytes=5-2"}).status_code == 416 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestZeroDimensionalArray: + """A 0-d array has exactly one chunk, spelled `0` in v2 and `c` in v3.""" + + @pytest.mark.parametrize("zarr_format", [2, 3]) + def test_sole_chunk_is_served(self, store: Store, zarr_format: ZarrFormat) -> None: + arr = zarr.create_array(store, shape=(), dtype="i4", zarr_format=zarr_format) + arr[...] = 7 + + client = TestClient(node_app(arr)) + chunk_key = "0" if zarr_format == 2 else "c" + + assert client.get(f"/{chunk_key}").status_code == 200 + # A 1-d coordinate is not valid for a 0-d grid. + assert client.get("/0/0").status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestGroupAndArrayMetadataKeysAreDistinct: + """A v2 group owns `.zgroup`; `.zarray` belongs to arrays, and vice versa.""" + + def test_node_does_not_claim_the_other_kind_of_metadata(self, store: Store) -> None: + root = zarr.open_group(store, mode="w", zarr_format=2) + arr = root.create_array("a", shape=(2,), chunks=(2,), dtype="f8") + + # Plant both documents so a 404 reflects the key set, not absence. + sync(store.set(".zarray", cpu.buffer_prototype.buffer.from_bytes(b"{}"))) + sync(store.set("a/.zgroup", cpu.buffer_prototype.buffer.from_bytes(b"{}"))) + + assert TestClient(node_app(root)).get("/.zarray").status_code == 404 + assert TestClient(node_app(arr)).get("/.zgroup").status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestBackgroundServerReportsBoundPort: + """`port=0` asks the OS for a free port, so the server must report the + port it actually bound rather than the zero it was asked for.""" + + def test_port_zero_reports_the_bound_port(self, store: Store) -> None: + import httpx + + from zarr_http_server import serve_background + + sync(store.set("key", cpu.buffer_prototype.buffer.from_bytes(b"hello"))) + + with serve_background(store_app(store), host="127.0.0.1", port=0) as server: + assert server.port != 0 + assert server.url == f"http://127.0.0.1:{server.port}" + # The reported URL is the one that actually serves the data. + assert httpx.get(f"{server.url}/key").content == b"hello" + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestUnopenableChildIsAnError: + """A child that cannot be *judged* must not be reported as absent. + + 404 is a claim about the store's contents, and under the v3 spec an + absent chunk is an uninitialized one -- so a correct reader answers 404 + by silently substituting the array's fill value. Returning it for a child + whose metadata could not be read would materialize zeros over data that + exists. Only a genuinely missing member is a 404; corrupt metadata, an + I/O error, or a codec this process lacks all surface as 5xx. + """ + + def test_child_with_unparseable_metadata_is_not_reported_as_missing(self, store: Store) -> None: + """A corrupt child metadata document must not yield 404.""" + root = zarr.open_group(store, mode="w") + root.create_array("good", shape=(2,), chunks=(2,), dtype="f8") + sync(store.set("junk/zarr.json", cpu.buffer_prototype.buffer.from_bytes(b"not json"))) + + client = TestClient(node_app(root), raise_server_exceptions=False) + + assert client.get("/good/zarr.json").status_code == 200 + assert client.get("/junk/zarr.json").status_code >= 500 + assert client.get("/junk/c/0").status_code >= 500 + + def test_absent_child_is_reported_as_missing(self, store: Store) -> None: + """A member that simply is not there is still a plain 404.""" + root = zarr.open_group(store, mode="w") + root.create_array("good", shape=(2,), chunks=(2,), dtype="f8") + + client = TestClient(node_app(root), raise_server_exceptions=False) + + assert client.get("/nope/zarr.json").status_code == 404 + assert client.get("/junk/c/0").status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestReadBackWithZarrClient: + """The round-trip the README leads with: serve an array, then open it + with a zarr client over HTTP. + + This needs an HTTP-capable fsspec, which is a client-side concern that + `zarr-http-server` deliberately does not depend on -- it lives in the `docs` + dependency group, alongside the other deps the README examples need. + """ + + def test_served_array_reads_back_identically(self, store: Store) -> None: + """`zarr.open_array(server.url)` should return the same data that was + served, so the README's headline example stays true.""" + pytest.importorskip("fsspec") + pytest.importorskip("aiohttp") + + from zarr_http_server import serve_background + + expected = np.arange(100, dtype="uint8").reshape(10, 10) + arr = zarr.create_array(store, data=expected, chunks=(5, 5), write_data=True) + + port = _get_free_port() + with serve_background(node_app(arr), host="127.0.0.1", port=port) as server: + remote = zarr.open_array(server.url, mode="r") + np.testing.assert_array_equal(remote[:], expected) + + +class TestBackgroundServerBoundedShutdown: + """BackgroundServer.shutdown() must not hang forever on a slow or stuck + in-flight request.""" + + def test_shutdown_returns_promptly_with_slow_inflight_request(self) -> None: + """A request that takes far longer than shutdown_timeout must not + prevent shutdown() from returning within roughly shutdown_timeout, + via uvicorn's force_exit rather than an unbounded thread join.""" + import asyncio + import threading + import time + + import httpx + from starlette.applications import Starlette + from starlette.responses import Response + from starlette.routing import Route + + async def slow(request: Any) -> Response: + # Sleeps far longer than shutdown_timeout below, so a correct + # implementation must force the connection closed rather than + # wait for this to finish. + await asyncio.sleep(SLOW_HANDLER_SECONDS) + return Response(status_code=204) + + app = Starlette(routes=[Route("/slow", slow, methods=["GET"])]) + port = _get_free_port() + server = serve_background( + app, host="127.0.0.1", port=port, shutdown_timeout=SHUTDOWN_TIMEOUT + ) + assert server is not None + + request_errors: list[BaseException] = [] + + def make_slow_request() -> None: + try: + httpx.get(f"http://127.0.0.1:{port}/slow", timeout=10) + except Exception as exc: # noqa: BLE001 -- connection drop when the server force-closes is expected + request_errors.append(exc) + + request_thread = threading.Thread(target=make_slow_request, daemon=True) + request_thread.start() + time.sleep(0.2) # give the request time to actually start + + start = time.monotonic() + server.shutdown() + elapsed = time.monotonic() - start + + # The property is that shutdown is *bounded*, not that it hits a + # particular wall-clock number. Derive the bound from the timeouts + # that produce it rather than hard-coding one: shutdown() waits + # `shutdown_timeout + _SHUTDOWN_JOIN_MARGIN` for a graceful stop, then + # `shutdown_timeout` more after force_exit. A literal here silently + # loses its headroom whenever one of those constants changes -- which + # is what happened when the margin was introduced. + bound = (SHUTDOWN_TIMEOUT + _SHUTDOWN_JOIN_MARGIN) + SHUTDOWN_TIMEOUT + 1.0 + assert elapsed < bound, f"shutdown() took {elapsed:.2f}s, expected under {bound:.1f}s" + # ...and the point of it all: far less than the handler's own sleep, + # which an unbounded join would have waited out in full. + assert elapsed < SLOW_HANDLER_SECONDS + + request_thread.join(timeout=10) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestCorsOptionsCoverTheMiddleware: + """`CorsOptions` exposes every `CORSMiddleware` parameter, with our own + defaults only for the two the server knows about.""" + + _ORIGIN = "https://viewer.example" + + def _client(self, store: Store, cors: CorsOptions) -> TestClient: + return TestClient(store_app(store, methods={"GET"}, cors_options=cors)) + + def test_ranged_response_is_readable_cross_origin(self, store: Store) -> None: + """`Content-Range` is not CORS-safelisted, so without `expose_headers` + a browser reads the bytes but cannot learn which bytes it got.""" + sync(store.set("k", cpu.buffer_prototype.buffer.from_bytes(b"0123456789"))) + client = self._client(store, {"allow_origins": [self._ORIGIN], "allow_methods": ["GET"]}) + + response = client.get("/k", headers={"Origin": self._ORIGIN, "Range": "bytes=0-3"}) + + assert response.status_code == 206 + assert response.headers["access-control-expose-headers"] == "Content-Range" + + def test_range_survives_a_preflight(self, store: Store) -> None: + """A preflight naming `Range` must be allowed, not answered 400.""" + client = self._client(store, {"allow_origins": [self._ORIGIN], "allow_methods": ["GET"]}) + + preflight = client.options( + "/k", + headers={ + "Origin": self._ORIGIN, + "Access-Control-Request-Method": "GET", + "Access-Control-Request-Headers": "range", + }, + ) + + assert preflight.status_code == 200 + assert "Range" in preflight.headers["access-control-allow-headers"] + + def test_caller_value_replaces_the_default(self, store: Store) -> None: + """Our defaults apply only to absent keys; a supplied key wins outright + so `expose_headers: []` means "expose nothing", not "expose ours".""" + sync(store.set("k", cpu.buffer_prototype.buffer.from_bytes(b"data"))) + base: CorsOptions = {"allow_origins": [self._ORIGIN], "allow_methods": ["GET"]} + + empty = self._client(store, {**base, "expose_headers": []}) + assert ( + "access-control-expose-headers" + not in empty.get("/k", headers={"Origin": self._ORIGIN}).headers + ) + + custom = self._client(store, {**base, "expose_headers": ["X-Custom"]}) + assert ( + custom.get("/k", headers={"Origin": self._ORIGIN}).headers[ + "access-control-expose-headers" + ] + == "X-Custom" + ) + + def test_parameters_beyond_the_original_two_are_reachable(self, store: Store) -> None: + """The regression this class exists for: `CorsOptions` used to carry + only `allow_origins` and `allow_methods`, sealing the rest away.""" + sync(store.set("k", cpu.buffer_prototype.buffer.from_bytes(b"data"))) + client = self._client( + store, + { + "allow_origin_regex": r"https://.*\.example", + "allow_credentials": True, + "max_age": 30, + }, + ) + origin = "https://sub.example" + + response = client.get("/k", headers={"Origin": origin}) + assert response.headers["access-control-allow-origin"] == origin + assert response.headers["access-control-allow-credentials"] == "true" + + preflight = client.options( + "/k", headers={"Origin": origin, "Access-Control-Request-Method": "GET"} + ) + assert preflight.headers["access-control-max-age"] == "30" + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestUvicornOptionsAreNotSealedOff: + """`uvicorn.Config` takes ~50 parameters; naming four of them and dropping + the rest would put TLS, proxy headers, `root_path` and log level out of + reach entirely.""" + + def test_options_reach_uvicorn_config(self, store: Store) -> None: + """A key this signature does not name still lands on the Config.""" + from zarr_http_server import serve_background + + server = serve_background( + store_app(store), + host="127.0.0.1", + port=0, + uvicorn_options={"root_path": "/api", "log_level": "warning"}, + ) + assert server is not None + try: + config = server._server.config + assert config.root_path == "/api" + assert config.log_level == "warning" + # Ours still apply where the caller did not override them. + assert config.timeout_graceful_shutdown == 5 + finally: + server.shutdown() + + def test_caller_options_win_over_ours(self, store: Store) -> None: + """The merge order is ours-then-theirs, so a caller can override even + an option this signature sets itself.""" + from zarr_http_server import serve_background + + server = serve_background( + store_app(store), + host="127.0.0.1", + port=0, + shutdown_timeout=5, + uvicorn_options={"timeout_graceful_shutdown": 11}, + ) + assert server is not None + try: + assert server._server.config.timeout_graceful_shutdown == 11 + finally: + server.shutdown() + + @pytest.mark.skipif(not hasattr(socket, "AF_UNIX"), reason="needs unix domain sockets") + def test_non_tcp_bind_reports_no_url(self, store: Store, tmp_path: pathlib.Path) -> None: + """A unix-socket bind has no host and port, so `url` must say so rather + than naming an address nothing is listening on.""" + import httpx + + from zarr_http_server import serve_background + + sock = str(tmp_path / "s.sock") + server = serve_background(store_app(store), uvicorn_options={"uds": sock}) + assert server is not None + try: + assert server.url is None + assert server.host is None + assert server.port is None + # ...and it really is serving, just not over TCP. + with httpx.Client(transport=httpx.HTTPTransport(uds=sock)) as client: + response = client.get("http://localhost/zarr.json", timeout=10) + assert response.status_code in (200, 404) + finally: + server.shutdown() + + +class TestHeadDoesNotTransferTheBody: + """A HEAD body is discarded at the wire, so building one is pure waste.""" + + def test_head_does_not_read_the_value(self, tmp_path: pathlib.Path) -> None: + """The regression this class exists for: HEAD used to fall through to + the GET handler and pull the whole object to report its length.""" + read = {"bytes": 0} + + class CountingLocal(LocalStore): + async def get(self, key: str, prototype: Any, byte_range: Any = None) -> Any: + buf = await super().get(key, prototype, byte_range) + if buf is not None: + read["bytes"] += len(buf) + return buf + + store = CountingLocal(str(tmp_path / "root")) + payload = b"x" * 100_000 + sync(store.set("big", cpu.buffer_prototype.buffer.from_bytes(payload))) + client = TestClient(store_app(store)) + + read["bytes"] = 0 + response = client.head("/big") + + assert response.status_code == 200 + assert response.headers["content-length"] == str(len(payload)) + assert read["bytes"] == 0, "HEAD read the value to report its length" + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + def test_head_of_a_missing_key_is_404(self, store: Store) -> None: + client = TestClient(store_app(store)) + assert client.head("/nope").status_code == 404 + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestMetadataContentType: + """Metadata documents are JSON in every zarr format, not just v3.""" + + @pytest.mark.parametrize( + ("zarr_format", "key"), [(3, "zarr.json"), (2, ".zarray"), (2, ".zattrs")] + ) + def test_metadata_is_served_as_json( + self, store: Store, zarr_format: ZarrFormat, key: str + ) -> None: + zarr.create_array( + store, name="a", shape=(4,), chunks=(2,), dtype="i4", zarr_format=zarr_format + ) + sync(store.set(f"a/{key}", cpu.buffer_prototype.buffer.from_bytes(b"{}"))) + + response = TestClient(store_app(store)).get(f"/a/{key}") + + assert response.status_code == 200 + assert response.headers["content-type"].startswith("application/json") + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestCorsAllowMethodsMatchTheRoute: + """Advertising a method the route rejects is a promise the server cannot + keep: the browser caches the preflight and every later call 405s.""" + + def test_wildcard_expands_to_what_is_served(self, store: Store) -> None: + """`"*"` is the idiomatic "everything this app does", so it expands to + exactly that rather than to every verb Starlette knows.""" + app = store_app( + store, methods={"GET"}, cors_options={"allow_origins": ["*"], "allow_methods": ["*"]} + ) + + preflight = TestClient(app).options( + "/k", headers={"Origin": "https://e.test", "Access-Control-Request-Method": "GET"} + ) + + advertised = preflight.headers["access-control-allow-methods"] + assert set(advertised.replace(" ", "").split(",")) == {"GET", "HEAD"} + + def test_advertising_an_unserved_method_is_rejected(self, store: Store) -> None: + with pytest.raises(ValueError, match="does not serve"): + store_app( + store, + methods={"GET"}, + cors_options={"allow_origins": ["*"], "allow_methods": ["GET", "DELETE"]}, + ) + + def test_head_counts_as_served_when_get_is(self, store: Store) -> None: + """Starlette routes HEAD wherever GET goes, so naming it is not an error.""" + store_app( + store, + methods={"GET"}, + cors_options={"allow_origins": ["*"], "allow_methods": ["GET", "HEAD"]}, + ) + + def test_absent_allow_methods_is_left_alone(self, store: Store) -> None: + """Starlette's GET-only default stands; widening it to everything + served would newly advertise PUT on a write-enabled app.""" + app = store_app(store, methods={"GET", "PUT"}, cors_options={"allow_origins": ["*"]}) + + preflight = TestClient(app).options( + "/k", headers={"Origin": "https://e.test", "Access-Control-Request-Method": "GET"} + ) + + assert "PUT" not in preflight.headers["access-control-allow-methods"] + + +class TestReadOnlyServing: + """The guarantees a read-only deployment rests on. + + Two independent layers: `methods` decides what the route answers, and the + store decides whether a write could succeed at all. The second is the one + that survives a misconfiguration of the first, so both are pinned here. + """ + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + @pytest.mark.parametrize("method", ["PUT", "POST", "DELETE", "PATCH"]) + def test_default_app_refuses_every_mutating_method(self, store: Store, method: str) -> None: + """The default is read-only: no argument is needed to get there, and + nothing a client sends can write.""" + sync(store.set("k", cpu.buffer_prototype.buffer.from_bytes(b"data"))) + before = sync(store.get("k", cpu.buffer_prototype)).to_bytes() + client = TestClient(store_app(store), raise_server_exceptions=False) + + response = client.request(method, "/k", content=b"overwritten") + + assert response.status_code == 405 + assert sync(store.get("k", cpu.buffer_prototype)).to_bytes() == before + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + def test_post_can_never_be_enabled(self, store: Store) -> None: + """POST is not merely unrouted, it is unconfigurable: there is no + handler behavior for it, so asking is an error rather than a no-op.""" + with pytest.raises(ValueError, match="Unsupported HTTP method"): + store_app(store, methods={"GET", "POST"}) # type: ignore[arg-type] + + def test_read_only_store_refuses_writes_independently_of_methods( + self, tmp_path: pathlib.Path + ) -> None: + """The layer that survives getting `methods` wrong. + + Constructed through the private builder because the public entry + points now reject this combination outright; the handler check stays + as the backstop for a store whose `read_only` is not fixed. + """ + from zarr_http_server._serve import _make_starlette_app + + writable = LocalStore(str(tmp_path / "root")) + sync(writable.set("k", cpu.buffer_prototype.buffer.from_bytes(b"data"))) + + app = _make_starlette_app(methods={"GET", "PUT"}) + app.state.store = writable.with_read_only(True) + app.state.node = None + app.state.prefix = "" + app.state.max_body_size = None + + response = TestClient(app, raise_server_exceptions=False).put("/k", content=b"x") + + assert response.status_code == 403 + assert sync(writable.get("k", cpu.buffer_prototype)).to_bytes() == b"data" + + def test_put_on_a_read_only_store_is_rejected_at_construction( + self, tmp_path: pathlib.Path + ) -> None: + """A write that could never succeed is a configuration error, not a + runtime 403 delivered to whoever happens to try first.""" + store = LocalStore(str(tmp_path / "root")).with_read_only(True) + + with pytest.raises(ValueError, match="store is read-only"): + store_app(store, methods={"GET", "PUT"}) + + def test_read_only_node_is_rejected_at_construction(self, tmp_path: pathlib.Path) -> None: + """The same check applies to a node, whose store it inherits.""" + store = LocalStore(str(tmp_path / "root")) + zarr.create_array(store, shape=(4,), chunks=(2,), dtype="i4", compressors=None) + read_only_array = zarr.open_array(store, mode="r") + + with pytest.raises(ValueError, match="store is read-only"): + node_app(read_only_array, methods={"GET", "PUT"}) + + +class TestMethodSetConstants: + """Named method sets let a call site state its intent, and make writable + deployments findable: every writable app must name one.""" + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + def test_read_only_constant_matches_the_default(self, store: Store) -> None: + """Passing it explicitly and omitting `methods` are the same server, so + saying so out loud costs nothing.""" + sync(store.set("k", cpu.buffer_prototype.buffer.from_bytes(b"data"))) + + default = TestClient(store_app(store), raise_server_exceptions=False) + named = TestClient( + store_app(store, methods=READ_ONLY_HTTP_METHODS), raise_server_exceptions=False + ) + + for method in ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"]: + assert default.request(method, "/k").status_code == ( + named.request(method, "/k").status_code + ) + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + @pytest.mark.parametrize("method", ["PUT", "POST", "DELETE", "PATCH"]) + def test_read_only_constant_refuses_writes(self, store: Store, method: str) -> None: + sync(store.set("k", cpu.buffer_prototype.buffer.from_bytes(b"data"))) + client = TestClient( + store_app(store, methods=READ_ONLY_HTTP_METHODS), raise_server_exceptions=False + ) + + assert client.request(method, "/k", content=b"x").status_code == 405 + assert sync(store.get("k", cpu.buffer_prototype)).to_bytes() == b"data" + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + def test_read_write_constant_permits_exactly_put(self, store: Store) -> None: + """It grants writes -- and still not POST, which has no handler.""" + client = TestClient( + store_app(store, methods=READ_WRITE_HTTP_METHODS), raise_server_exceptions=False + ) + + assert client.put("/k", content=b"data").status_code == 204 + assert client.post("/k", content=b"data").status_code == 405 + assert sync(store.get("k", cpu.buffer_prototype)).to_bytes() == b"data" + + def test_constants_cannot_be_mutated_by_a_caller(self) -> None: + """Frozen, so one caller cannot widen the default for every other.""" + assert isinstance(READ_ONLY_HTTP_METHODS, frozenset) + assert isinstance(READ_WRITE_HTTP_METHODS, frozenset) + assert "PUT" not in READ_ONLY_HTTP_METHODS + + def test_constants_match_the_types_they_model(self) -> None: + """The sets are derived from the Literals, so they cannot disagree + about what this server serves. Pinning the contents here makes + widening either type a deliberate, visible edit.""" + assert frozenset(get_args(ReadOnlyHTTPMethod)) == READ_ONLY_HTTP_METHODS + assert set(READ_ONLY_HTTP_METHODS) == {"GET", "HEAD"} + assert set(READ_WRITE_HTTP_METHODS) == {"GET", "HEAD", "PUT"} + # Read-only is a strict subset: the only difference is the write verb. + assert READ_ONLY_HTTP_METHODS < READ_WRITE_HTTP_METHODS + assert {"PUT"} == READ_WRITE_HTTP_METHODS - READ_ONLY_HTTP_METHODS + + +class TestServeAnyApp: + """`serve` runs whatever ASGI app it is handed, which is what makes + several nodes on one port possible.""" + + @staticmethod + def _two_mounted_arrays() -> tuple[Starlette, bytes, bytes]: + """Two arrays in *separate* stores, so no common parent exists and + mounting is the only way to serve both from one server.""" + first, second = MemoryStore(), MemoryStore() + one = zarr.create_array(first, shape=(4,), chunks=(2,), dtype="i4", compressors=None) + other = zarr.create_array(second, shape=(4,), chunks=(2,), dtype="i4", compressors=None) + one[:] = 7 + other[:] = 9 + + app = Starlette( + routes=[Mount("/first", app=node_app(one)), Mount("/second", app=node_app(other))] + ) + return app, np.full(2, 7, dtype="i4").tobytes(), np.full(2, 9, dtype="i4").tobytes() + + def test_mounted_apps_each_serve_their_own_node(self) -> None: + app, first_chunk, second_chunk = self._two_mounted_arrays() + client = TestClient(app, raise_server_exceptions=False) + + assert client.get("/first/zarr.json").status_code == 200 + assert client.get("/second/zarr.json").status_code == 200 + assert client.get("/first/c/0").content == first_chunk + assert client.get("/second/c/0").content == second_chunk + + @pytest.mark.parametrize( + "path", + [ + "/first/%2e%2e/second/zarr.json", + "/first/..%2f..%2fsecond/zarr.json", + "/first/%2e%2e%2fsecond/c/0", + "/first/%2fsecond/zarr.json", + ], + ) + def test_one_mount_cannot_reach_another(self, path: str) -> None: + """Per-node validation runs inside each mount, so composing apps does + not widen what any of them serves.""" + app, _, _ = self._two_mounted_arrays() + + assert TestClient(app, raise_server_exceptions=False).get(path).status_code == 404 + + def test_serve_runs_a_composed_app_in_the_background(self) -> None: + """The gap `serve` closes: a composed app previously had no way to use + the background-server ergonomics, only a blocking `uvicorn.run`.""" + import httpx + + app, first_chunk, second_chunk = self._two_mounted_arrays() + + server = serve_background(app, host="127.0.0.1", port=0) + try: + assert server.url is not None + assert httpx.get(f"{server.url}/first/c/0", timeout=30).content == first_chunk + assert httpx.get(f"{server.url}/second/c/0", timeout=30).content == second_chunk + finally: + server.shutdown() + + +class TestPortSelection: + """`port="auto"` prefers a predictable port but never fails over one. + + An explicit port means the opposite -- bind exactly that or fail -- because + a caller who names one usually has something else expecting the server + there, and silently moving would break it while looking healthy. + """ + + @staticmethod + def _free_port() -> int: + """A port that was free a moment ago. Only ever used as the *preferred* + port, never bound afterwards, so the usual bind-then-close race does + not apply: if something takes it, that is the case under test.""" + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return int(sock.getsockname()[1]) + + def test_preferred_port_is_used_when_free(self) -> None: + preferred = self._free_port() + + sock = _bind_preferred_or_free("127.0.0.1", preferred) + try: + assert sock.getsockname()[1] == preferred + finally: + sock.close() + + def test_falls_back_when_the_preferred_port_is_taken(self) -> None: + with socket.socket() as squatter: + squatter.bind(("127.0.0.1", 0)) + squatter.listen() + taken = int(squatter.getsockname()[1]) + + sock = _bind_preferred_or_free("127.0.0.1", taken) + try: + assert sock.getsockname()[1] != taken + finally: + sock.close() + + def test_address_family_follows_the_host(self) -> None: + """Hard-coding AF_INET would bind the wrong family for an IPv6 host.""" + try: + sock = _bind_preferred_or_free("::1", 0) + except OSError: # pragma: no cover - depends on the host's networking + pytest.skip("no IPv6 loopback available") + try: + assert sock.family == socket.AF_INET6 + finally: + sock.close() + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + def test_auto_produces_a_working_server(self, store: Store) -> None: + """Whichever port it lands on, `url` names it and the server answers.""" + import httpx + + server = serve_background(store_app(store)) + try: + assert server.url is not None + assert server.port is not None + assert httpx.get(f"{server.url}/nope", timeout=30).status_code == 404 + finally: + server.shutdown() + + # uvicorn answers a failed bind with `sys.exit` on its own thread, which + # pytest reports as an unhandled thread exception -- and this package turns + # warnings into errors. That exit is exactly what the RuntimeError below + # reports to the caller, so it is expected here rather than a defect. + @pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning") + @pytest.mark.parametrize("store", ["memory"], indirect=True) + def test_an_explicit_port_that_is_taken_fails(self, store: Store) -> None: + """The regression this class exists for: `auto` must not leak into the + explicit case, where a collision has to be loud.""" + with socket.socket() as squatter: + squatter.bind(("127.0.0.1", 0)) + squatter.listen() + taken = int(squatter.getsockname()[1]) + + with pytest.raises(RuntimeError, match="may already be in use"): + serve_background(store_app(store), port=taken) + + @pytest.mark.parametrize("store", ["memory"], indirect=True) + def test_port_zero_still_means_any_free_port(self, store: Store) -> None: + """`0` keeps its OS meaning rather than being folded into `auto`.""" + server = serve_background(store_app(store), port=0) + try: + assert server.port not in (0, None) + finally: + server.shutdown() diff --git a/packages/zarr-http-server/uv.lock b/packages/zarr-http-server/uv.lock new file mode 100644 index 0000000000..946da90503 --- /dev/null +++ b/packages/zarr-http-server/uv.lock @@ -0,0 +1,2212 @@ +version = 1 +revision = 3 +requires-python = ">=3.12" + +[[package]] +name = "aiohappyeyeballs" +version = "2.7.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/f4/eec0465c2f67b2664688d0240b3212d5196fd89e741df67ddb81f8d35658/aiohappyeyeballs-2.7.1.tar.gz", hash = "sha256:065665c041c42a5938ed220bdcd7230f22527fbec085e1853d2402c8a3615d9d", size = 24757, upload-time = "2026-07-01T17:11:55.501Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/43/1947f06babed6b3f1d7f38b0c767f52df66bfb2bc10b468c4a7de9eceff2/aiohappyeyeballs-2.7.1-py3-none-any.whl", hash = "sha256:9243213661e29250eb41368e5daa826fc017156c3b8a11440826b2e3ed376472", size = 15038, upload-time = "2026-07-01T17:11:54.055Z" }, +] + +[[package]] +name = "aiohttp" +version = "3.14.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiohappyeyeballs" }, + { name = "aiosignal" }, + { name = "attrs" }, + { name = "frozenlist" }, + { name = "multidict" }, + { name = "propcache" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "yarl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/58/d9/22ce5786ac0c1653ae8b6c23bded02c1686d11f0dbb45b31ce128e0df985/aiohttp-3.14.3.tar.gz", hash = "sha256:9491196535a88924a60afd5b5f434b5b203b6cc616250878dbdb223a8f7844bc", size = 7971213, upload-time = "2026-07-23T01:57:27.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/d4/eb96299230e20acf2efae207cb8d69051f1f68e357e5ea5e479bf6fb097a/aiohttp-3.14.3-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:39aded8c7f3b935b54aab1d8d73c70ec0ee2d3ec3b943e0e86611bc150ba47f5", size = 754690, upload-time = "2026-07-23T01:53:47.332Z" }, + { url = "https://files.pythonhosted.org/packages/88/11/e7a70a209eb9a067c0d3212b518a0134e3484f5178c7533878b6b514d469/aiohttp-3.14.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:5bcb6ff3fdab1258a192679ff1a05d44f59626430aa05cd1a9d2447423599228", size = 509484, upload-time = "2026-07-23T01:53:51.159Z" }, + { url = "https://files.pythonhosted.org/packages/30/07/4bbc222cc8dbe31d4c3e8a5baad2286e4d42026ac0c570027b89afce6344/aiohttp-3.14.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:617105e2c3018ee38d0c8ce5ee3c84f621a6d8b9f723202aacaff28449ca91ee", size = 511949, upload-time = "2026-07-23T01:53:55.083Z" }, + { url = "https://files.pythonhosted.org/packages/54/b9/42e74c46b7b7c794b995bbc1f573fb48950c38b19d8600c62a6804ee2d67/aiohttp-3.14.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f631fe87a6f30df5fbe6d79640b25e4cffb38c31c7fb6f10871517b84b0f8c1a", size = 1765282, upload-time = "2026-07-23T01:53:59.662Z" }, + { url = "https://files.pythonhosted.org/packages/6b/ed/62bc4d74363ad346d518e0720363a949f63e2e23439a79eb5813d4d29bb3/aiohttp-3.14.3-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:a94dbaae5ae27bd849c93570669bff91e0510f33a80805738e3de72a7be0447b", size = 1741511, upload-time = "2026-07-23T01:54:04.063Z" }, + { url = "https://files.pythonhosted.org/packages/d0/9f/181e8a8bc79e47d13c7fc4540bd7a3b729d9505609c61f392a8dd2fbfe55/aiohttp-3.14.3-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8f2f1c4c032c7cedd7d8da6f54c97b70266c6570c3108d3fdffee7188bb70529", size = 1810680, upload-time = "2026-07-23T01:54:09.882Z" }, + { url = "https://files.pythonhosted.org/packages/5c/9a/dec94d6ad694552fe3424e3f1928d7a606a5d9d9433a04e7ecdd9d38ae7f/aiohttp-3.14.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ea05e1f97ceea523942d9b2a7d7c0359d781d683d6b043f5943a602b14da4787", size = 1905646, upload-time = "2026-07-23T01:54:13.475Z" }, + { url = "https://files.pythonhosted.org/packages/52/b7/7cd31f29d6055bd711ae6e669367fba6f5ae9de463910a793e30556a8db7/aiohttp-3.14.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:543906c127fb1d929b95076db19b83fa2d46751006ff1e23b093aa5ac4d8db42", size = 1792122, upload-time = "2026-07-23T01:54:15.752Z" }, + { url = "https://files.pythonhosted.org/packages/66/73/10b1ef93afa61f4963c746257b70ced619cf31a4798671de5fdb2608501d/aiohttp-3.14.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0a5ff2dfbb9ce645fa5b8ef3e02c6c0b9cc3f6030ff863d0c51fffc50cb5541b", size = 1591127, upload-time = "2026-07-23T01:54:19.489Z" }, + { url = "https://files.pythonhosted.org/packages/49/ed/3b203fa6de1b338c14acdc06bf6ca9b043b7944f005966958c2ced932cde/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:041badb8f84396357c4d3ad26de6afd7a32b112f43d3c63045c0c8278cfd2043", size = 1725210, upload-time = "2026-07-23T01:54:24.129Z" }, + { url = "https://files.pythonhosted.org/packages/28/b7/1c2aab8c706436dcc28598452488ac9cd7c409da815237c28c27d58993e6/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:530125ee1163c4219af35dc3aa1206e541e7b31b6efc1a3f93b70a136f65d427", size = 1764848, upload-time = "2026-07-23T01:54:27.973Z" }, + { url = "https://files.pythonhosted.org/packages/54/50/94c28f08b131c4bf10984ea2c7a536c9920608bb2d6e7f95642c30cc87b7/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:c8653fd547c93a61aadc612007790f5555cdd18946fa48cf45e26d8ea4ea473d", size = 1777102, upload-time = "2026-07-23T01:54:31.775Z" }, + { url = "https://files.pythonhosted.org/packages/13/d4/e7d09ba7d345fb2d74440fd2fa033c5e079fac05552927705986f41a364f/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:89176250f686cb9853c0fb7ead90e639e915b84a6f43eedc2a4e7ec21f1037f0", size = 1580205, upload-time = "2026-07-23T01:54:34.518Z" }, + { url = "https://files.pythonhosted.org/packages/a3/84/072a91d68e1e1eb587985b54baab94221277f877e8ef274fc213a0ceae28/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:3a26434dafe408229ff3403458ca58de24fb51936504decac49ce6755f77e59d", size = 1797219, upload-time = "2026-07-23T01:54:36.995Z" }, + { url = "https://files.pythonhosted.org/packages/e0/eb/aad34e897e668424d6e995da5dff8a4a09af93363d3392488772957a63aa/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d1558173930a5a8d3069cee5c92fc91c87c4dbcb099debbb3622053717145a19", size = 1768629, upload-time = "2026-07-23T01:54:40.103Z" }, + { url = "https://files.pythonhosted.org/packages/b6/2b/6bb88ddba0fecd9122aa3ebcad25996cf6c083a4a7040dbb3a4f97972af6/aiohttp-3.14.3-cp312-cp312-win32.whl", hash = "sha256:16100ad3ab8d649fdfbee87602d9d2dcdca9df0b9eda8a1b5fdc0d41f96da559", size = 451481, upload-time = "2026-07-23T01:54:42.547Z" }, + { url = "https://files.pythonhosted.org/packages/76/9b/f2f8f108da17ecef2cc3efc424e8b7ad3782b1a8360f7b8eae8ced84f6ea/aiohttp-3.14.3-cp312-cp312-win_amd64.whl", hash = "sha256:33a2d7c28d33797a2e99923dffa63f83d908a19b6bf26cfe80fa790aa5e1a75a", size = 476845, upload-time = "2026-07-23T01:54:44.853Z" }, + { url = "https://files.pythonhosted.org/packages/3e/44/28dac80a8941b604f4da10ce21097614ca1bf905ce93dca28d8d7de9c1e7/aiohttp-3.14.3-cp312-cp312-win_arm64.whl", hash = "sha256:362a3fd481769cac1a824514bcd86fda51c65e8fe6e051099e008fddde6db17c", size = 448050, upload-time = "2026-07-23T01:54:47.087Z" }, + { url = "https://files.pythonhosted.org/packages/57/be/5afd201cc0ab139029aadb75392efe85a293403d9dd3a3226161c21ce00c/aiohttp-3.14.3-cp313-cp313-android_21_arm64_v8a.whl", hash = "sha256:2e9878ae68e4a5f1c0abe4dd497dbc3d51946f5837b56759e2a02e78fa90ef86", size = 506269, upload-time = "2026-07-23T01:54:49.075Z" }, + { url = "https://files.pythonhosted.org/packages/22/09/dec8189d62b45ade009f6792a2264b942a90cb88aeaf181239933cd72c3c/aiohttp-3.14.3-cp313-cp313-android_21_x86_64.whl", hash = "sha256:f3d2669fe7dec7fc359ecdb5984b29b50d85d5d00f8c1cb61de4f4a24ee42627", size = 515166, upload-time = "2026-07-23T01:54:51.894Z" }, + { url = "https://files.pythonhosted.org/packages/28/24/2854869d29ed8a8b19d74f9ec6629515f7e04d02dd329d9d179201e58e47/aiohttp-3.14.3-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:cc7cb243a68167172f48c1fd43cee91ec4b1d40cefd190edd43369d1a6bc9c82", size = 486263, upload-time = "2026-07-23T01:54:54.223Z" }, + { url = "https://files.pythonhosted.org/packages/d4/dd/57187c8be2a35aea65eaee3bd2c3dcbbcf0204f5106c89637e3610380cd1/aiohttp-3.14.3-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:78253b573e6ffab5028924fc98bc281aae05445969982a10864bc360dea2016c", size = 492299, upload-time = "2026-07-23T01:54:56.236Z" }, + { url = "https://files.pythonhosted.org/packages/b9/11/06ae6ed8f0d414edf4068861e233d8fe23ee699bfd4b3ceb8663db948a62/aiohttp-3.14.3-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:7041d52c3a7fa20c9e8c182b534704abb19502c8bdcbde7ab23bfda6f642394f", size = 502235, upload-time = "2026-07-23T01:54:58.377Z" }, + { url = "https://files.pythonhosted.org/packages/7e/a3/559639c34a345d2cf7c52dff6838119f2eaf29eb508227b5b83f573af813/aiohttp-3.14.3-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ac74facc01463f138b0da5580329cfcc82818dea5656e83ddcd11268fc12ff80", size = 750883, upload-time = "2026-07-23T01:55:00.65Z" }, + { url = "https://files.pythonhosted.org/packages/91/cd/41e131f13afd1e7b0172a9d9eda085ef90eb8439f41f0d279db81ed3ae60/aiohttp-3.14.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:d6218d92e450824e9b4881f44e8c09f1853b490f9a64130801024a4793b1b3b0", size = 508473, upload-time = "2026-07-23T01:55:02.945Z" }, + { url = "https://files.pythonhosted.org/packages/bc/6b/e7f13410d391c6e55b4c007a8de024355389d7d459e3d64c42b2d33617e5/aiohttp-3.14.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:11fb37ef075669eee52ab1928fbf6e1741fada40409fa309ebde9607a962aebf", size = 509190, upload-time = "2026-07-23T01:55:05.173Z" }, + { url = "https://files.pythonhosted.org/packages/97/21/6464573e53d69672cc1eada3e5c5cb2d2efa82701e8305a0f2047a576967/aiohttp-3.14.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:55bdcc472aafe2de4a253045cc128007a64f1e0264fb675791e132ea5edaa3bd", size = 1761478, upload-time = "2026-07-23T01:55:07.383Z" }, + { url = "https://files.pythonhosted.org/packages/1a/81/d217043a4c17fbce360905e3b2bdd20139ebc9a2de836d035d179c4da006/aiohttp-3.14.3-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c39846c3aad97a8530c89d7a3869a8f8e9e3762c6ac0504481e5c80948f7e807", size = 1735092, upload-time = "2026-07-23T01:55:09.803Z" }, + { url = "https://files.pythonhosted.org/packages/a1/66/e13a02d0eeb1a9a502402a977abb4e4abff9fe4051c26f80558c57a7c975/aiohttp-3.14.3-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5895ef58c4620afe02fa16044f023dc4dafec08158f9d08874a46a7dbc0341b8", size = 1800546, upload-time = "2026-07-23T01:55:12.012Z" }, + { url = "https://files.pythonhosted.org/packages/26/5e/57d42fca1d18cb5acc1cad945d017fabc5d6ae71d8a08ad66be8dc3ee544/aiohttp-3.14.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fa9467a8113aa69d3d7c55a70ef0b7c636010a40993f3df9d9d0d73b3eb7ef24", size = 1895250, upload-time = "2026-07-23T01:55:14.357Z" }, + { url = "https://files.pythonhosted.org/packages/ca/1c/7da8d08e74d56f00070822f9638ff3f1c563f8ad87d1efa996c87bfc8644/aiohttp-3.14.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d7d2deec16eeedf55f2c7cf75b521ea3856a5177e123844f8fd0f114ce252cb5", size = 1789289, upload-time = "2026-07-23T01:55:16.668Z" }, + { url = "https://files.pythonhosted.org/packages/cd/0f/cf16bcf56896981c1a0319f5d5db9337994b5165730c48a8fa07e9b34be6/aiohttp-3.14.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:dd54d0e8717de95939766febac482ac0474d8ac3b048115f9f2b1d23a16e7db4", size = 1586706, upload-time = "2026-07-23T01:55:18.913Z" }, + { url = "https://files.pythonhosted.org/packages/fe/6f/76eac12a7f2480e1e304f842efdb07db33256b0d9165b866b6ef0806c202/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:df82f3787c940c94986b34222d59c9e38843fba85139f36e85255a82ad5355a9", size = 1724652, upload-time = "2026-07-23T01:55:21.296Z" }, + { url = "https://files.pythonhosted.org/packages/39/b6/19c8c592baeeb94b75f966547d40c02ac7590902306ec5863d5c027cf506/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:42a67efc36300d052fb4508a53e8b6901b9284b599ae63945c377569c5fcc1e1", size = 1756239, upload-time = "2026-07-23T01:55:23.705Z" }, + { url = "https://files.pythonhosted.org/packages/dc/c9/4e9383150296f97f873b680c4de8fb2cd88608fb9f48c79edcb111611abc/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:7a75aa63cbf9b21cfaf60dc2657e19df2c2867d91707d653fee171ffeedd1371", size = 1769161, upload-time = "2026-07-23T01:55:26.082Z" }, + { url = "https://files.pythonhosted.org/packages/aa/1e/147bdc6cc5de5f3ab011be8bf5d6e786633249f22c20bae06f85e45f5387/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:e92eb8acc45eb6a9f4935071a77edf5b85cc6f8dfad5cd99e97653c26593cdde", size = 1578759, upload-time = "2026-07-23T01:55:28.846Z" }, + { url = "https://files.pythonhosted.org/packages/fd/31/78388a9d6040ece2e11df62ea229a822cf5e52d238374b220ae9975b2623/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:b014a6ed7cf912e787149fdc529166d3ceabac23f26efeea3158c9aba2354e7e", size = 1792025, upload-time = "2026-07-23T01:55:31.457Z" }, + { url = "https://files.pythonhosted.org/packages/03/51/a3d29fdf2c25d796746af8ad6fe56a45d6256c38b0a8a2ed752e1160b3a2/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:3d4f72af88ac2474bb5bca640030320e3d38a0163a1d7533500e87be458eef71", size = 1768477, upload-time = "2026-07-23T01:55:33.87Z" }, + { url = "https://files.pythonhosted.org/packages/29/a6/442e18b5afeade534d877a2dc3c3e392aff8d49787890b0cf84790410267/aiohttp-3.14.3-cp313-cp313-win32.whl", hash = "sha256:5f08ec777f35ee70720233b8b9811d3bb5d728137f30ac91b7457709c3261ac0", size = 451069, upload-time = "2026-07-23T01:55:36.121Z" }, + { url = "https://files.pythonhosted.org/packages/9d/69/3d876ac02659f271cf7f6769f14a8e3de5b6e888ed8b5a7e998086a4cec8/aiohttp-3.14.3-cp313-cp313-win_amd64.whl", hash = "sha256:dff9461ec275f22135650d5ba4b4931a11f3958df7dfbb8db630000d4dee0883", size = 476518, upload-time = "2026-07-23T01:55:38.303Z" }, + { url = "https://files.pythonhosted.org/packages/b2/0e/50d6e6471cd31edce8b282bdec59375a3a69124d8a989a0b1313355cae52/aiohttp-3.14.3-cp313-cp313-win_arm64.whl", hash = "sha256:ddcac3c6b382e81f1dd0499199d4136b877beb4cb5ef770bbbfba56c4b8f55d2", size = 447676, upload-time = "2026-07-23T01:55:40.451Z" }, + { url = "https://files.pythonhosted.org/packages/c8/20/887fdcf832326571b370ffc347b3e70abe101096f3720126aac161b1d872/aiohttp-3.14.3-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:49f7325beb0f85ef4aef5f48f490269575f83e6e2acad00a1d80b807eb027062", size = 509067, upload-time = "2026-07-23T01:55:42.618Z" }, + { url = "https://files.pythonhosted.org/packages/ad/a3/92cec936f78cc4bf0fa5554ebe593b73459d94e3c62303e1902a4cccb6f7/aiohttp-3.14.3-cp314-cp314-android_24_x86_64.whl", hash = "sha256:e3be98a7c30b8c25d573dafba7171d66dfb05ee6a9070fc46535464ff97700a6", size = 514774, upload-time = "2026-07-23T01:55:44.937Z" }, + { url = "https://files.pythonhosted.org/packages/29/ba/2a0c38df3fc557620b6a5acd98364af050053b6285b4dc7ee74100c63c18/aiohttp-3.14.3-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:614c61d478b83953e261d02bb2df750f17227cd33ef8002945bf5aebbde21919", size = 488134, upload-time = "2026-07-23T01:55:47.135Z" }, + { url = "https://files.pythonhosted.org/packages/48/d6/d51b7d4bf309af3693940d8ffd2b9ed0b682434ef85959b7c9c137f60cf8/aiohttp-3.14.3-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:1caa7b0d05f3e3a36f87788c59e970a7ee1cefcfcbb924a9f138c4a6551c9cb7", size = 494201, upload-time = "2026-07-23T01:55:49.451Z" }, + { url = "https://files.pythonhosted.org/packages/3f/5a/8f624384e5f1efabb5229b94157eb966b021e97bdb188c62860c2ae243c2/aiohttp-3.14.3-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:dfa68deb2a443bdaa3ea5297b0699c1464f08aef3812b486d1348eee61b07dc0", size = 502766, upload-time = "2026-07-23T01:55:51.656Z" }, + { url = "https://files.pythonhosted.org/packages/a6/26/4ff0164370deec18fb19254ee4ab10b7a73304ac0c860b13f5f84663759b/aiohttp-3.14.3-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:e72ee89e28d907a18f46959b4eb0bb06701cc7f8cf4366e00029e2ccfaaf5924", size = 756557, upload-time = "2026-07-23T01:55:53.964Z" }, + { url = "https://files.pythonhosted.org/packages/97/a3/7056b86dc0d9ec709ea9777eae3b0161428f943372f8b98c01c11593b682/aiohttp-3.14.3-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ad4c8b7488d745d2ca4838ebd8ae5ba9b56341d30b1da43640e4ce87f9f49646", size = 510168, upload-time = "2026-07-23T01:55:56.22Z" }, + { url = "https://files.pythonhosted.org/packages/85/ed/0357a015892fd68058bf2d39d3fd1958e459b997a7db30aaa6aaa434ae96/aiohttp-3.14.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:db332af25642007330fca8be5c4d194caf2bea7a7fc84415aff3497af5dfee6b", size = 512957, upload-time = "2026-07-23T01:55:58.437Z" }, + { url = "https://files.pythonhosted.org/packages/47/d1/8aba53f15ccb2238405f5e9d30e2a8ca44f93878c26e7165ade00d374b1c/aiohttp-3.14.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:25bd2708db6bdf6a6630dd37bdcdfcb47c4434d22ac69c64665b802910140b30", size = 1750149, upload-time = "2026-07-23T01:56:00.856Z" }, + { url = "https://files.pythonhosted.org/packages/49/bd/40c3fee327529284375c6701cbb0fa4600cc2e8432af1378f897e2ef7d3a/aiohttp-3.14.3-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:cef89a58e628c4efcac3275c2d68083f82426dcdc89c1492a6f654f9f7ea6ab9", size = 1707685, upload-time = "2026-07-23T01:56:03.371Z" }, + { url = "https://files.pythonhosted.org/packages/2a/a3/ca0cc6724cca8114b05694abd916060758c79894c3aa5b012cdadc1bc28e/aiohttp-3.14.3-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c23ec8ee9d5ab2f5421f9c7fffce208435607af27fd46d4a44e031954352838f", size = 1803911, upload-time = "2026-07-23T01:56:05.817Z" }, + { url = "https://files.pythonhosted.org/packages/95/b5/85b099c299c3ffd38ad9b3e43694c8a346934e4a30c88c4fd5a841234f77/aiohttp-3.14.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e2667f0bbe7eb6c74eae5e9691441ad186e5845ca3cff63230fc09c4e7514f5d", size = 1876929, upload-time = "2026-07-23T01:56:08.413Z" }, + { url = "https://files.pythonhosted.org/packages/d5/b7/1da684a04175473fa4cddbf9a2f572e79514c3fd27a74597f43057d4f3da/aiohttp-3.14.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:18cb43369747b2ae007bd2655fb8e63a099c2ff1d207962943636dac989b3147", size = 1761112, upload-time = "2026-07-23T01:56:10.918Z" }, + { url = "https://files.pythonhosted.org/packages/d1/16/bc4b55e3e5cb175fd69c53c90d60d2f47797cb343da5106e23863dc4dba4/aiohttp-3.14.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d77640cc618c1d99fc4f8589c0f24a730adfa54eb1e57ef7bf0c8dfb78da898c", size = 1583500, upload-time = "2026-07-23T01:56:13.613Z" }, + { url = "https://files.pythonhosted.org/packages/2a/e8/13a9d957a1ee40837f46aa30f0f4c657e673ad86a2e6362a9f9be20d26d9/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:53e5179d8abb5710f8e83ba207c41c8d1261fcffd4616500e15ca2b7a33be10a", size = 1713940, upload-time = "2026-07-23T01:56:15.969Z" }, + { url = "https://files.pythonhosted.org/packages/38/05/d33c680c1bcf1c7e130f9cbfc1fc02fe8bb0c4af2a94a53dd5fb56131e5c/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:cd817772b2fcf2b8c0905795318485f9ec16eae60b29feb7f4c77085311637f0", size = 1724413, upload-time = "2026-07-23T01:56:18.591Z" }, + { url = "https://files.pythonhosted.org/packages/85/1d/af798d306f7a74b6a632dbcabcf62a4c91391b7582d2a8c6d7712e2cc54e/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:4e3ac92d90e92773b2362d506068e9a948192bd553e743c5b2429e28527c8661", size = 1770748, upload-time = "2026-07-23T01:56:21.074Z" }, + { url = "https://files.pythonhosted.org/packages/a8/92/ad720d472556a995049206867765e9410969684f86ee09423ff9969044c1/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:3f42e9b78301f11c8f861746175d8b9c1ccef713fcad9eab396e2f6db8ed4a22", size = 1577564, upload-time = "2026-07-23T01:56:23.475Z" }, + { url = "https://files.pythonhosted.org/packages/60/ad/0ed7586cbef7a884e23a752fa2bb987a122e6a5dd50dab109258d0a95193/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:9d9edccfe496b476db5f398d97b865e9a6752bcf8aec4eef8390ce20fb64bb41", size = 1782080, upload-time = "2026-07-23T01:56:25.994Z" }, + { url = "https://files.pythonhosted.org/packages/97/ea/dbaed0d73e8a69aad653b045dab451c67c2454bb731a37b45a86593e9422/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:1c5ec8fb1bcc31a8466f74aaf26c345d5c386fa4bd08a3f0eb9c7a4a3fe8b5bf", size = 1745813, upload-time = "2026-07-23T01:56:28.604Z" }, + { url = "https://files.pythonhosted.org/packages/81/1b/6893d4bc57e434fc93a6c9217c637d967a0b651d989f6e3265179375754a/aiohttp-3.14.3-cp314-cp314-win32.whl", hash = "sha256:38901a84da3ce22249f6e860bf8f90d141bcab7da090cc398f8bb58c0e44b7da", size = 455872, upload-time = "2026-07-23T01:56:31.031Z" }, + { url = "https://files.pythonhosted.org/packages/f5/8b/c7baa1ba1eda4db6989baefe5de6d99834921b84ebd7918624febcb9f290/aiohttp-3.14.3-cp314-cp314-win_amd64.whl", hash = "sha256:8b3b60de05f3dcb6f6a00f818bb2ec781cee4de0645f59ccaf99b1d1823b6100", size = 481030, upload-time = "2026-07-23T01:56:33.365Z" }, + { url = "https://files.pythonhosted.org/packages/22/8c/c29d067df825a2df88ca432db848aa2fe8199598359cc06c12b09320cac9/aiohttp-3.14.3-cp314-cp314-win_arm64.whl", hash = "sha256:1576145bdceeb92382d899751e12743a3a5b8e460a841e3e50543859e54864dc", size = 453669, upload-time = "2026-07-23T01:56:35.731Z" }, + { url = "https://files.pythonhosted.org/packages/6a/a4/9c033beb355d39b6147980597ec9645e4729243f686ee4dc73945de72030/aiohttp-3.14.3-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:8800c996b01c2772a783e3e46f3e1abd5823029adca0df54231960de9bfefa5b", size = 791403, upload-time = "2026-07-23T01:56:37.972Z" }, + { url = "https://files.pythonhosted.org/packages/80/ca/87c32a0a7704583cfc49660bd817889bae5b830bf53b5dcb4e92145ac2da/aiohttp-3.14.3-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:ebe8e504f058fe91223351cecd2d9d6946c9d241bb0250d898ffbdf584cc72b0", size = 526413, upload-time = "2026-07-23T01:56:40.523Z" }, + { url = "https://files.pythonhosted.org/packages/9e/d8/8ec0e471248c500acdce2be3f46db8fb62b5eb60efef072529cc85ee1d26/aiohttp-3.14.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:30402d03a7c0ff52bce290b57e564e9079fd9d0cb545c8aba73f86a103162d2e", size = 532135, upload-time = "2026-07-23T01:56:42.876Z" }, + { url = "https://files.pythonhosted.org/packages/fe/45/f8919fd936e8b79fcd9bda7b6d8e62613462a713f4f17987fd7c34399142/aiohttp-3.14.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9fc7b5bfec6573f3ae844f457fdde5adeb713f8b8e4a81ad64fc207b49383716", size = 1922742, upload-time = "2026-07-23T01:56:45.528Z" }, + { url = "https://files.pythonhosted.org/packages/f6/ec/9ca76b28a27525b0cc53e20842e0228b022f301ce1f436b7d814b4aaf2df/aiohttp-3.14.3-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8a5fd34f7f7410d1730d5c2ba873cacb2eed3fede366feb268a70ba22581ed8f", size = 1787371, upload-time = "2026-07-23T01:56:48.045Z" }, + { url = "https://files.pythonhosted.org/packages/b1/04/6acdbf17315f7b55f1937e3387acb89a3cddeb4995689553d064af8e92ab/aiohttp-3.14.3-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:270d3dace9ca2f10f0da5d8ebe519b7a310fc6112ed916e32df5866df0888553", size = 1912623, upload-time = "2026-07-23T01:56:50.605Z" }, + { url = "https://files.pythonhosted.org/packages/86/e6/438b0c79ca6f45eb9fd9817dd4c01a91919a38c0de5ee9e05e2b4dc0ece7/aiohttp-3.14.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:3ae5b3a59436d089b5395d910121a390feed4d00578eb95a0fd1a329fe963100", size = 2005515, upload-time = "2026-07-23T01:56:53.153Z" }, + { url = "https://files.pythonhosted.org/packages/bb/6b/62cbd6577758699525f5c712d1ddef57d9875fbab0ae8d5f5a202fd598f8/aiohttp-3.14.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2498f0fe69ead802f9675beca44a7c21c62fdaa4ec5145ea1c3ad6edbee29f85", size = 1879906, upload-time = "2026-07-23T01:56:55.818Z" }, + { url = "https://files.pythonhosted.org/packages/00/95/18bcbf830a21dc3aae24d8f6b6feaf3db1d2090242d00a7868db2ffb0b67/aiohttp-3.14.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a0dc483c00da8b673abbb367eb6f8d8f4bcec30eb58529ea13cb42e7fd2dfa33", size = 1675849, upload-time = "2026-07-23T01:56:58.861Z" }, + { url = "https://files.pythonhosted.org/packages/a9/19/47f4968659c5e23606c3790c80fc624e691c153d036148449ee84d31b287/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c7d3a97c678d34fc5b59da671ee9cd630096ddc643e7b5a30d54a2a6f3574d3f", size = 1843496, upload-time = "2026-07-23T01:57:01.591Z" }, + { url = "https://files.pythonhosted.org/packages/64/af/38c33c4dd82fddcb4e56c4653b6f1072a8edbc6b7fa15809f14932c41e2d/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:f8fb78a83c9e5f741ca3a68cfb455c1f5bb83b4e7249a3848b3cd78d0a8563b0", size = 1827746, upload-time = "2026-07-23T01:57:05.131Z" }, + { url = "https://files.pythonhosted.org/packages/a1/9d/0537cda4885ac8f5b7053d164dd06312f4c483a4edcb8ee5b8aaf2a989bf/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:74ab5b6a9fb13e873e5a90946588baecaf488745e1db1a4a5c433f971f035098", size = 1853810, upload-time = "2026-07-23T01:57:08.043Z" }, + { url = "https://files.pythonhosted.org/packages/19/fe/26f9c5e6458385aa86497836b0dea6fb2f027827d63f37c7856cce9286ee/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:bd52f811e65f6fb634b1047159657c98f52b407f8efec907bcfc09da9a4c0a25", size = 1668895, upload-time = "2026-07-23T01:57:10.837Z" }, + { url = "https://files.pythonhosted.org/packages/ec/4c/618b1db9b9ba079b8875d2cdf78e7c4a3bf72903bd5850fee7dd9544600a/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:f0f177d1b195b9e06376cfd7d308d8a1b920909a609d03ac82a8c73bbb16d3b9", size = 1883833, upload-time = "2026-07-23T01:57:13.672Z" }, + { url = "https://files.pythonhosted.org/packages/94/c6/bd959bd1e4771f9fd944e9e436224c48c77b018b73b519b5aad346335bcc/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:498c6c623134f8e09a3c4e60bcd607a0b4590dd7dbf08dd40851b27cbb520ccb", size = 1844251, upload-time = "2026-07-23T01:57:16.593Z" }, + { url = "https://files.pythonhosted.org/packages/5e/19/08d41839658bdd44a0ed2480f3891705ecb487ce28c0dde62c9040c997e0/aiohttp-3.14.3-cp314-cp314t-win32.whl", hash = "sha256:b304db572b4368edd8dda8a2274f73156fe15558fca4a917cb8a09fc47af5963", size = 474180, upload-time = "2026-07-23T01:57:19.306Z" }, + { url = "https://files.pythonhosted.org/packages/99/5d/3cd6ef0a2b2851f7ab913b5b079334781bd50ff56a323e4454063377a080/aiohttp-3.14.3-cp314-cp314t-win_amd64.whl", hash = "sha256:b20032766aedf6261c7a566585a40867d092ac03a0d81592d5370ef9b054f99b", size = 500528, upload-time = "2026-07-23T01:57:21.762Z" }, + { url = "https://files.pythonhosted.org/packages/a4/37/cfd1ed540a4d318da025590d96b728e63713c09e9377950fc655dadeb856/aiohttp-3.14.3-cp314-cp314t-win_arm64.whl", hash = "sha256:2e1161602f45a54de2ce0905243a95f58cb42dcd378402f3697f5e0b21e9d2e7", size = 469280, upload-time = "2026-07-23T01:57:24.241Z" }, +] + +[[package]] +name = "aiosignal" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "frozenlist" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/62/06741b579156360248d1ec624842ad0edf697050bbaf7c3e46394e106ad1/aiosignal-1.4.0.tar.gz", hash = "sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7", size = 25007, upload-time = "2025-07-03T22:54:43.528Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" }, +] + +[[package]] +name = "anyio" +version = "4.14.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/cc/a381afa6efea9f496eff839d4a6a1aed3bfafc7b3ab4b0d1b243a12573dd/anyio-4.14.2.tar.gz", hash = "sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f", size = 260176, upload-time = "2026-07-12T20:29:07.082Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/da/35/f2287558c17e29fafc8ef3daf819bb9834061cfa43bff8014f7df7f63bdc/anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494", size = 125813, upload-time = "2026-07-12T20:29:05.763Z" }, +] + +[[package]] +name = "appnope" +version = "0.1.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/35/5d/752690df9ef5b76e169e68d6a129fa6d08a7100ca7f754c89495db3c6019/appnope-0.1.4.tar.gz", hash = "sha256:1de3860566df9caf38f01f86f65e0e13e379af54f9e4bee1e66b48f2efffd1ee", size = 4170, upload-time = "2024-02-06T09:43:11.258Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/81/29/5ecc3a15d5a33e31b26c11426c45c501e439cb865d0bff96315d86443b78/appnope-0.1.4-py2.py3-none-any.whl", hash = "sha256:502575ee11cd7a28c0205f379b525beefebab9d161b7c964670864014ed7213c", size = 4321, upload-time = "2024-02-06T09:43:09.663Z" }, +] + +[[package]] +name = "asttokens" +version = "3.0.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/25/1e/faf0f247f6f881b98fc4d6d07e14085cb89d13665084e6d6ac1dc2c03d0b/asttokens-3.0.2.tar.gz", hash = "sha256:3ecdbd8f2cc195f53ccada3a613538bb5f9ef6f6869129f13e03c30a677b8fe2", size = 63136, upload-time = "2026-07-12T03:31:49.084Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d4/2b/04b8a15f3a1c77bc79ddf5c73875327f34b4fa75982df2b76e45e402d364/asttokens-3.0.2-py3-none-any.whl", hash = "sha256:9da13157f5b28becde0bd374fc677dcd3c290614264eff096f167c469cd9f933", size = 28702, upload-time = "2026-07-12T03:31:47.542Z" }, +] + +[[package]] +name = "attrs" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, +] + +[[package]] +name = "babel" +version = "2.18.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/b2/51899539b6ceeeb420d40ed3cd4b7a40519404f9baf3d4ac99dc413a834b/babel-2.18.0.tar.gz", hash = "sha256:b80b99a14bd085fcacfa15c9165f651fbb3406e66cc603abf11c5750937c992d", size = 9959554, upload-time = "2026-02-01T12:30:56.078Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/77/f5/21d2de20e8b8b0408f0681956ca2c69f1320a3848ac50e6e7f39c6159675/babel-2.18.0-py3-none-any.whl", hash = "sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35", size = 10196845, upload-time = "2026-02-01T12:30:53.445Z" }, +] + +[[package]] +name = "backrefs" +version = "8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/56/4744bcd0c82184e80c52b0ac4076c261a8ffa1f1b343ff2f6e89ce0e1cef/backrefs-8.0.tar.gz", hash = "sha256:b556cd7d36c3a3a2f256b89590b176b8eddfb73bcfaee3a3ddd84ea66d21ce50", size = 7013081, upload-time = "2026-07-26T19:54:24.638Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e3/fd/9bf53b6a6f6f519ffaac765df2f2a25e5c2fc6d32cfd2b2747099e72c911/backrefs-8.0-py310-none-any.whl", hash = "sha256:4a627b817fd2dce43b79ab48da63613340509381cd8ce0897078a0bce79a2ab8", size = 380377, upload-time = "2026-07-26T19:54:17.457Z" }, + { url = "https://files.pythonhosted.org/packages/e1/29/4bd7ae72a2634da00379c2b3bcc5439e7c94620235c6afea8af15229a973/backrefs-8.0-py311-none-any.whl", hash = "sha256:f0c35cf0102ba6b6070c12a492be3c1c1d3f5839529784b9a9565d6d04569a01", size = 392169, upload-time = "2026-07-26T19:54:18.782Z" }, + { url = "https://files.pythonhosted.org/packages/29/13/232505664e8e2a0c7a2eb0c505cfade9d715538f89a5d62bc4c272968f62/backrefs-8.0-py312-none-any.whl", hash = "sha256:87f0fae8c5f207fe9f4b2887efc71d42f4900ac78faa1af08d675ef303692dc5", size = 398084, upload-time = "2026-07-26T19:54:19.954Z" }, + { url = "https://files.pythonhosted.org/packages/8a/69/47a3dc20abc4fa5486655fde681bd55e63211b46c886d8c02223d6468431/backrefs-8.0-py313-none-any.whl", hash = "sha256:601ce68ca12385dbda06ce264406b4c4210cf5b79fd0fd627592365c92f29a88", size = 400040, upload-time = "2026-07-26T19:54:21.194Z" }, + { url = "https://files.pythonhosted.org/packages/1c/cf/e5f9b68a5b0e939a2fb933a66c20180d0c9241bf8927f7a47fa48c1675e9/backrefs-8.0-py314-none-any.whl", hash = "sha256:9ec96efa080938be92323e8e730e57718c9c88eb15ad70bbef4e1766df591408", size = 411903, upload-time = "2026-07-26T19:54:23.221Z" }, +] + +[[package]] +name = "certifi" +version = "2026.7.22" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" }, +] + +[[package]] +name = "cffi" +version = "2.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pycparser" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/69/43965eccfdead3b9220015fd1320e117be8c6ed01a62ffab76eeb752f5d5/cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0", size = 184821, upload-time = "2026-08-03T21:19:44.887Z" }, + { url = "https://files.pythonhosted.org/packages/54/7d/16e5a096677b5e313ca80cd5e5170efa3ea44624a82bb111925522da64b1/cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf", size = 184719, upload-time = "2026-08-03T21:19:46.129Z" }, + { url = "https://files.pythonhosted.org/packages/56/e6/8941622732edec876dd17d0453dce07317ae96db34f2ec1436c9d3785986/cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a", size = 214799, upload-time = "2026-08-03T21:19:47.218Z" }, + { url = "https://files.pythonhosted.org/packages/44/de/f98430906df1545ffde0d543dd124a7a439bc2cd32b36b9c53f805df7333/cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890", size = 222389, upload-time = "2026-08-03T21:19:48.331Z" }, + { url = "https://files.pythonhosted.org/packages/6a/5b/717f1526b9957b34456313c31645c5b82b8fb5c3fe9e4752999be7128bfc/cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50", size = 210249, upload-time = "2026-08-03T21:19:49.543Z" }, + { url = "https://files.pythonhosted.org/packages/64/b3/f8aa4f3e34986c7e4ec45072d1b1b9dd295b6b18007b45518d79726dd725/cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e", size = 208775, upload-time = "2026-08-03T21:19:50.918Z" }, + { url = "https://files.pythonhosted.org/packages/b1/db/dceb9dd5b231e1da801793f8acc9f3c52a7e1afe40bb1aae37e02b0faad5/cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf", size = 221822, upload-time = "2026-08-03T21:19:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a0/d2/6cd24ae3be000a634109c247d1475d62e5616d0dc78c82770942ec384248/cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517", size = 225232, upload-time = "2026-08-03T21:19:53.109Z" }, + { url = "https://files.pythonhosted.org/packages/cb/52/3fa190537004dd7f0ab860a6dc7c0175b8667f68d1e618a46f5498d30250/cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735", size = 223597, upload-time = "2026-08-03T21:19:54.515Z" }, + { url = "https://files.pythonhosted.org/packages/80/fb/0bb75b7039588c074b37ae99f40d9bfddf990ecb2fbc346ebccd2e56b9be/cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e", size = 175292, upload-time = "2026-08-03T21:19:55.566Z" }, + { url = "https://files.pythonhosted.org/packages/d9/79/615cc094e2fb508cade7de88d3b4f6c4ec2bab695c97bce9153dc65aadf5/cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a", size = 185919, upload-time = "2026-08-03T21:19:56.89Z" }, + { url = "https://files.pythonhosted.org/packages/70/c6/d0ea84713fe46b243a436a18fcd47d639732747e21635c8a27191b06dc30/cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80", size = 180093, upload-time = "2026-08-03T21:19:58.155Z" }, + { url = "https://files.pythonhosted.org/packages/9d/f4/035513d4117049066b4779dc3b7c0c0fdad175fa13731c9f4003f1cd1478/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e", size = 194248, upload-time = "2026-08-03T21:19:59.399Z" }, + { url = "https://files.pythonhosted.org/packages/76/af/2aeb4dbb5fc41a04161ae9ff1518de7cec08e164f44a8ce6a4cf7fd2cd1d/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c", size = 196908, upload-time = "2026-08-03T21:20:00.746Z" }, + { url = "https://files.pythonhosted.org/packages/a7/46/2e5fdde8555706dd98139a910ca11be02809f3f605ce956f655d0214e100/cffi-2.1.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6", size = 184805, upload-time = "2026-08-03T21:20:02.02Z" }, + { url = "https://files.pythonhosted.org/packages/55/41/4c7042f317b9217502988f0873af87e16ad606dc20f84e546e3e6ce9764c/cffi-2.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971", size = 184764, upload-time = "2026-08-03T21:20:03.141Z" }, + { url = "https://files.pythonhosted.org/packages/43/1f/1c3d90d91811c8f86ced9ed637956c54bfe5b79ca98fe976d7f8c8979f6b/cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c", size = 214722, upload-time = "2026-08-03T21:20:04.377Z" }, + { url = "https://files.pythonhosted.org/packages/37/6f/3b5ce4c3b2192d250f04908f2bfd91ef34552ec8f7716a5d4abdb8d67bb2/cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125", size = 222369, upload-time = "2026-08-03T21:20:05.544Z" }, + { url = "https://files.pythonhosted.org/packages/02/10/4b3c75dde3d9663c9e02ba05c2668b954f671d4bbe346413ca8c696b295a/cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264", size = 210175, upload-time = "2026-08-03T21:20:06.75Z" }, + { url = "https://files.pythonhosted.org/packages/df/62/14f74b9543e605d17701dc797b815958b8bb70b7624ce1b832ddad48ed6c/cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3", size = 208670, upload-time = "2026-08-03T21:20:08.04Z" }, + { url = "https://files.pythonhosted.org/packages/95/95/86342356ff5953b3fb06f7ef7c5bee212d45e770abc7218d451b9148313c/cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2", size = 221824, upload-time = "2026-08-03T21:20:09.274Z" }, + { url = "https://files.pythonhosted.org/packages/eb/ff/7b3429ff53aafe931ed8a5fc69f481bbef7ba6de87ddcbb63d08f483f613/cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b", size = 225148, upload-time = "2026-08-03T21:20:10.7Z" }, + { url = "https://files.pythonhosted.org/packages/34/34/a95870b9221e09cf4f2ce3178b1a210abdfe63a1bd357da940418d7b8d15/cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7", size = 223564, upload-time = "2026-08-03T21:20:12.165Z" }, + { url = "https://files.pythonhosted.org/packages/70/ea/839b50531021a647fb5e929f72cf97bc1ff702b5472166164b5b6e76b851/cffi-2.1.1-cp313-cp313-win32.whl", hash = "sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac", size = 175263, upload-time = "2026-08-03T21:20:13.559Z" }, + { url = "https://files.pythonhosted.org/packages/60/a6/8b149b2c3f2e11aaa1618ef64500b45f50f22c57a977a4dff1aff1f91042/cffi-2.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d", size = 185688, upload-time = "2026-08-03T21:20:14.69Z" }, + { url = "https://files.pythonhosted.org/packages/01/9a/11f687cb39d6a3504060d5242f04f48c735afb4d3d533958a20594890cb2/cffi-2.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973", size = 180078, upload-time = "2026-08-03T21:20:15.917Z" }, + { url = "https://files.pythonhosted.org/packages/d3/7b/d6bbf82b8b96e7391438898c42f5bd96dd02030fd5b64937d248220003e2/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c", size = 194064, upload-time = "2026-08-03T21:20:17.148Z" }, + { url = "https://files.pythonhosted.org/packages/94/e6/bcc91b283be94735e268487a054004f0aa19947b6348fa367db53230abc8/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb", size = 196720, upload-time = "2026-08-03T21:20:18.268Z" }, + { url = "https://files.pythonhosted.org/packages/d9/99/c4b0c17cacdc9c3b8f280026286a9826d6a208c0f047591a3c3ce99b91fd/cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54", size = 184964, upload-time = "2026-08-03T21:20:19.708Z" }, + { url = "https://files.pythonhosted.org/packages/b3/a9/9db617d05d7367c1ad0ab00b3aa6e6f9281edd689b4ee9ea0e5a84e89c97/cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72", size = 184962, upload-time = "2026-08-03T21:20:20.833Z" }, + { url = "https://files.pythonhosted.org/packages/67/b8/b42132ca113dc567d37684437b46ca1dafc885902b02a110a02d5b511857/cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1", size = 222328, upload-time = "2026-08-03T21:20:22.118Z" }, + { url = "https://files.pythonhosted.org/packages/80/10/c5c0cbf0a657aecf59ef511409734230bf556f05a0d6c9eed7aa5c0a0166/cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062", size = 209985, upload-time = "2026-08-03T21:20:23.401Z" }, + { url = "https://files.pythonhosted.org/packages/d5/6c/bfa0b87b03b9238148beca990292843c9396ba069b54496596594173de7b/cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03", size = 208530, upload-time = "2026-08-03T21:20:24.628Z" }, + { url = "https://files.pythonhosted.org/packages/e9/02/4e7d553a7ac4b4238b38b3c1b80d486e9d4436f8d2acbf87a0997fe3f402/cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96", size = 221525, upload-time = "2026-08-03T21:20:25.758Z" }, + { url = "https://files.pythonhosted.org/packages/82/1d/a4aaf9babd75acb4d5f223bff71533bee748dd770a382619a798960ee9ba/cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527", size = 225053, upload-time = "2026-08-03T21:20:26.985Z" }, + { url = "https://files.pythonhosted.org/packages/81/10/5dc0e7bdd18e22107054288283380fc97a06ae3f1656a106908d666a3c88/cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13", size = 223213, upload-time = "2026-08-03T21:20:28.277Z" }, + { url = "https://files.pythonhosted.org/packages/0b/e9/d0061c364cde06ee43168a0d076ac1da512cbc380d44767b844ba34fe2b6/cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c", size = 177682, upload-time = "2026-08-03T21:20:44.288Z" }, + { url = "https://files.pythonhosted.org/packages/a7/06/1c3e01e3ba14c39f6d10bfbac52753b7e22259e38088e5cfe1d704918690/cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48", size = 187949, upload-time = "2026-08-03T21:20:45.623Z" }, + { url = "https://files.pythonhosted.org/packages/87/5b/da4e39efe18eeb89cf580ea9cfc66b6a7c3eadb808fc0cc1d3a295cb5a5d/cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836", size = 182947, upload-time = "2026-08-03T21:20:46.955Z" }, + { url = "https://files.pythonhosted.org/packages/23/59/40338bf421c5accea1d45158170c87006ef1cd371b05c077e76476949728/cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3", size = 188504, upload-time = "2026-08-03T21:20:29.495Z" }, + { url = "https://files.pythonhosted.org/packages/7d/47/5ecf1023850036e674c77ec4de86182d309ae344e39e7cba984b7df5d647/cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2", size = 188259, upload-time = "2026-08-03T21:20:31.291Z" }, + { url = "https://files.pythonhosted.org/packages/2a/9c/92934c3bea9f785b23eba304538c0b4d37a2a96d2431eb3a1bc87a11aa19/cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94", size = 223864, upload-time = "2026-08-03T21:20:32.571Z" }, + { url = "https://files.pythonhosted.org/packages/4d/45/ba4c93527bc38616a8bd36488acb69a2212d60486794f0c1f318949bbb76/cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc", size = 211538, upload-time = "2026-08-03T21:20:33.808Z" }, + { url = "https://files.pythonhosted.org/packages/80/e9/b6ef565e452acb932fb0cb5443f44a78efbd1233e566f02b5a83855e9115/cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29", size = 210688, upload-time = "2026-08-03T21:20:34.974Z" }, + { url = "https://files.pythonhosted.org/packages/9a/95/eff5f0cee78d2eabc7eebffec40d3fc1876b5f3c95582e018bb4b99601f2/cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676", size = 223803, upload-time = "2026-08-03T21:20:36.564Z" }, + { url = "https://files.pythonhosted.org/packages/fa/01/579d39fb8bef00a335a23d83757b44feb24cd6345a2c451b64cb67b9c362/cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e", size = 226763, upload-time = "2026-08-03T21:20:37.816Z" }, + { url = "https://files.pythonhosted.org/packages/8d/b0/0b44f47c60b01b57b6e2bbd92343f13a85a1d93bc46ccf6e47e244acd99c/cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f", size = 225688, upload-time = "2026-08-03T21:20:38.959Z" }, + { url = "https://files.pythonhosted.org/packages/eb/d2/3b7176cb570a1d3e27faf67b72f591af508036e0d8b2be2ef9af9e8c84bb/cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4", size = 182868, upload-time = "2026-08-03T21:20:40.388Z" }, + { url = "https://files.pythonhosted.org/packages/56/78/31f00c1bcd97c9bbf55f1bfdf5bc809a5de8887473e90bb9960dca825e80/cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e", size = 194104, upload-time = "2026-08-03T21:20:41.725Z" }, + { url = "https://files.pythonhosted.org/packages/7b/1b/58496f2ed0a35de575250c02a43ab3cc2c04d494a88fed31c1cabc0fd176/cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5", size = 186402, upload-time = "2026-08-03T21:20:43.042Z" }, + { url = "https://files.pythonhosted.org/packages/c1/8f/9ebe220eab48a093d1a5a5e339ab0dc7316eef3bb04d63c42f0251b61f50/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d", size = 194043, upload-time = "2026-08-03T21:20:48.179Z" }, + { url = "https://files.pythonhosted.org/packages/ff/69/844bad3ece306c4782c2ecb93597035b6690d48704b803914c199da1e8b3/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b", size = 196737, upload-time = "2026-08-03T21:20:49.457Z" }, + { url = "https://files.pythonhosted.org/packages/1b/8a/af668013284634733f02d683458a0728739c7d6ddb5e14cb0c20832266fe/cffi-2.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4", size = 184933, upload-time = "2026-08-03T21:20:50.639Z" }, + { url = "https://files.pythonhosted.org/packages/0c/75/2f5207ff6d1a613133b23a5203cc0c2a628313b5eb3974d7956ae3c57950/cffi-2.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8", size = 185002, upload-time = "2026-08-03T21:20:52.173Z" }, + { url = "https://files.pythonhosted.org/packages/e2/31/9e1313b0a6e30e91b3b3d3fff51ae99c857c07738e3afcce1f7334e1b7ab/cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6", size = 222271, upload-time = "2026-08-03T21:20:53.462Z" }, + { url = "https://files.pythonhosted.org/packages/50/e3/f6234a833e6e08c7007003074723c406559eecf9b48dfc97471e5a8eb7a0/cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80", size = 209919, upload-time = "2026-08-03T21:20:54.783Z" }, + { url = "https://files.pythonhosted.org/packages/0d/fc/5f74e293fced6edb51af3a46c4ccf6c23c9943774ecb375ddbd522c76add/cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779", size = 208529, upload-time = "2026-08-03T21:20:56.066Z" }, + { url = "https://files.pythonhosted.org/packages/44/16/29e6d01b388bef055ecd6ca8244b3f4d336bd09e92d5d892187b9601084e/cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399", size = 221630, upload-time = "2026-08-03T21:20:57.336Z" }, + { url = "https://files.pythonhosted.org/packages/a4/18/fa7f1f6857d5eb88a4ca99ffcbfb7c387a287ccc154c64a73e86314745d7/cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688", size = 225134, upload-time = "2026-08-03T21:20:58.675Z" }, + { url = "https://files.pythonhosted.org/packages/e0/9f/e8e3dfa04a1b4c241f8c91faacad872b4d4efd051d49764ad4e2fd4b9fea/cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7", size = 223197, upload-time = "2026-08-03T21:20:59.968Z" }, + { url = "https://files.pythonhosted.org/packages/f8/7e/8debeb04f1ab9fe2a6963964cd6f1aaf7192627b83926586a6a4e089c9fa/cffi-2.1.1-cp315-cp315-win32.whl", hash = "sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac", size = 177683, upload-time = "2026-08-03T21:21:14.901Z" }, + { url = "https://files.pythonhosted.org/packages/e0/31/5158704cc474ab65c1647932e88be78dc0873f47130e253be38bcaf13d01/cffi-2.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960", size = 187897, upload-time = "2026-08-03T21:21:16.108Z" }, + { url = "https://files.pythonhosted.org/packages/cc/4b/b3a2da8570c704ffc0f9762cdc3ec0f02c8573798e0b5cf7f11c82bbb70f/cffi-2.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1", size = 182935, upload-time = "2026-08-03T21:21:17.271Z" }, + { url = "https://files.pythonhosted.org/packages/d0/ef/5443574510a1207e6f6bc38ba6e1f1de36cb48fef07b2728bb896a21f430/cffi-2.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc", size = 188464, upload-time = "2026-08-03T21:21:01.163Z" }, + { url = "https://files.pythonhosted.org/packages/7e/ae/a56fa8c4686ad50e148fcbc8d3ae0d03915ff5c30d795058988c24118cef/cffi-2.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab", size = 188262, upload-time = "2026-08-03T21:21:02.382Z" }, + { url = "https://files.pythonhosted.org/packages/53/b2/6187f46f2912276a3ae284076109cc5c8680482f11f766ccf26db4a86427/cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e", size = 223779, upload-time = "2026-08-03T21:21:03.553Z" }, + { url = "https://files.pythonhosted.org/packages/8a/f6/c3ad28bd19f77047a03084424fbd4cbe997303267c14423737324be0385d/cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358", size = 211520, upload-time = "2026-08-03T21:21:04.863Z" }, + { url = "https://files.pythonhosted.org/packages/a0/cd/ccac9013a5bd9fd764de118674ab9c805b5ca10c19270d90ee273f8b2240/cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231", size = 210673, upload-time = "2026-08-03T21:21:06.223Z" }, + { url = "https://files.pythonhosted.org/packages/52/86/2976131c639aead931c5bee5aba67e4b09fbeb8018b6f282f70803f923a7/cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6", size = 223835, upload-time = "2026-08-03T21:21:07.539Z" }, + { url = "https://files.pythonhosted.org/packages/ac/0c/33a7aeab2f9c76918c52e084beb39c570db3588133412929e8ec06fab90b/cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94", size = 226705, upload-time = "2026-08-03T21:21:08.774Z" }, + { url = "https://files.pythonhosted.org/packages/e3/26/2cde30fdde421130bfc18f70395731a6e6b2053c6a1978a5258ff04e72fa/cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5", size = 225539, upload-time = "2026-08-03T21:21:09.911Z" }, + { url = "https://files.pythonhosted.org/packages/6d/cd/a361394c94b2129d604bb846f624a8e88255a3ee33129c434a00d715e64f/cffi-2.1.1-cp315-cp315t-win32.whl", hash = "sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66", size = 182707, upload-time = "2026-08-03T21:21:11.226Z" }, + { url = "https://files.pythonhosted.org/packages/9b/b5/ba2b299993c26577d529b6ae29841f9e15b9fcf004d65f423f4fcf94ade9/cffi-2.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3", size = 193772, upload-time = "2026-08-03T21:21:12.39Z" }, + { url = "https://files.pythonhosted.org/packages/aa/29/35e016098c814cd93de9cd320c66b5bfba14dc6ecedd3cb518fa7c408c69/cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692", size = 186360, upload-time = "2026-08-03T21:21:13.636Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.4.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bd/2a/23f34ec9d04624958e137efdc394888716353190e75f25dd22c7a2c7a8aa/charset_normalizer-3.4.9.tar.gz", hash = "sha256:673611bbd43f0810bec0b0f028ddeaaa501190339cac411f347ac76917c3ae7b", size = 152439, upload-time = "2026-07-07T14:34:58.454Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/70/4a/ecbd131485c07fcdfad54e28946d513e3da22ef3b4bd854dcafae54ec739/charset_normalizer-3.4.9-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:45b0cc4e3556cd875e09102988d1ab8356c998b596c9fced84547c8138b487a0", size = 319300, upload-time = "2026-07-07T14:33:15.666Z" }, + { url = "https://files.pythonhosted.org/packages/ec/96/5d9364e3342d69f3a045e1777bc47c85c383e6e9466d561b33fdb419d1f9/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9b2aff1c7b3884512b9512c3eaadd9bab39fb45042ffaaa1dd08ff2b9f8109d9", size = 215802, upload-time = "2026-07-07T14:33:17.031Z" }, + { url = "https://files.pythonhosted.org/packages/4b/4c/5361f9aa7f2cb58d94f2ab831b3d493f69efb1d239654b4744e3c09527cb/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9104ed0bd76a429d46f9ec0dbc9b08ad1d2dcdf2b00a5a0daa1c145329b35b44", size = 237171, upload-time = "2026-07-07T14:33:18.576Z" }, + { url = "https://files.pythonhosted.org/packages/50/78/ce342ca4ff30b2eb49fe6d9578df85974f90c67d294113e94efdd9664cbd/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7b86a2b16095d250c6f58b3d9b2eee6f4147754344f3dab0922f7c9bf7d226c9", size = 233075, upload-time = "2026-07-07T14:33:20.084Z" }, + { url = "https://files.pythonhosted.org/packages/01/c4/4fa4c8b3097a11f3c5f09a35b72ed6855fb1d332469504962ab7bafcc702/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5e226f6218febc71f6c1fc2fafb91c226f75bdc1d8fb12d66823716e891608fd", size = 224256, upload-time = "2026-07-07T14:33:21.747Z" }, + { url = "https://files.pythonhosted.org/packages/87/3a/ad914516df7e358a81aae018caa5e0470ba827fa6d763b1d2e87d920a5f6/charset_normalizer-3.4.9-cp312-cp312-manylinux_2_31_armv7l.whl", hash = "sha256:90c44bc373b7687f6948b693cceaea1348ae0975d7474746559494468e3c1d84", size = 208784, upload-time = "2026-07-07T14:33:23.313Z" }, + { url = "https://files.pythonhosted.org/packages/d7/74/3c12f9755717dfe5c5c87da63f35d765fa0c00382ec26bf23f7fae34f2ba/charset_normalizer-3.4.9-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9cdef90ae47919cae358d8ab15797a800ed41da7aba5d72419fb510729e2ed4b", size = 219928, upload-time = "2026-07-07T14:33:24.814Z" }, + { url = "https://files.pythonhosted.org/packages/33/9a/895095b83e7907abd6d3d99aad3a38ad0d9686cc186cb0c94c24320fe63e/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:60f44ade2cf573dad7a277e6f8ca9a51a21dda572b13bd7d8539bb3cd5dbedde", size = 218489, upload-time = "2026-07-07T14:33:26.42Z" }, + { url = "https://files.pythonhosted.org/packages/a1/34/ef5c05f412f42520d7709b7d3784d19640839eb7366ded1755511585429f/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:a1786910334ed46ab1dd73222f2cd1e05c2c3bb39f6dddb4f8b36fc382058a39", size = 210267, upload-time = "2026-07-07T14:33:27.952Z" }, + { url = "https://files.pythonhosted.org/packages/83/dc/9b29fa4412b318bf3bfea985c35d67eb55e04b59a7c3f2237168b0e0be6f/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:03d07803992c6c7bbc976327f34b18b6160327fc81cb82c9d504720ac0be3b62", size = 226030, upload-time = "2026-07-07T14:33:29.397Z" }, + { url = "https://files.pythonhosted.org/packages/0e/42/6dbc00b8cd16011691203e33570fa42ed5746599a2e878112d16eab403a3/charset_normalizer-3.4.9-cp312-cp312-win32.whl", hash = "sha256:78841cccf1af7b40f6f716338d50c0902dbe88d9f800b3c973b7a9a0a693a642", size = 151185, upload-time = "2026-07-07T14:33:30.781Z" }, + { url = "https://files.pythonhosted.org/packages/80/cc/f920afd1a23c58ccd53c1d36085a71893a4737ff5e66e0371efab6809850/charset_normalizer-3.4.9-cp312-cp312-win_amd64.whl", hash = "sha256:4b3dac63058cc36820b0dd072f89898604e2d39686fe05321729d00d8ac185a0", size = 162557, upload-time = "2026-07-07T14:33:32.176Z" }, + { url = "https://files.pythonhosted.org/packages/f0/e6/0386d43a261ff4e4b30c5857af7df877254b46bec7b9d1b74b6bf969a90b/charset_normalizer-3.4.9-cp312-cp312-win_arm64.whl", hash = "sha256:78fa18e436a1a0e58dbd7e02fc4473f3f32cceb12df9dfca542d075961c307d2", size = 152665, upload-time = "2026-07-07T14:33:33.711Z" }, + { url = "https://files.pythonhosted.org/packages/b2/06/97ec2aeae780b31d742b6352218b43841a6871e2564578ca522dce4a45c3/charset_normalizer-3.4.9-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:440eede837960000d74978f0eba527be106b5b9aee0daf779d395276ed0b0614", size = 317688, upload-time = "2026-07-07T14:33:35.408Z" }, + { url = "https://files.pythonhosted.org/packages/d0/39/8ff066c672434225f8d25f8b739f992af250944392173dcc88362681c9bf/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:21e764fd1e70b6a3e205a0e46f3051701f98a8cb3fad66eeb80e48bb502f8698", size = 214982, upload-time = "2026-07-07T14:33:36.996Z" }, + { url = "https://files.pythonhosted.org/packages/92/8f/3a47a3667c83c2df9483d91644c6c107de3bf8874aa1793da9d3012eb986/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e4fd89cc178bced6ad29cb3e6dd4aa63fa5017c3524dbd0b25998fb64a87cc8b", size = 236460, upload-time = "2026-07-07T14:33:38.536Z" }, + { url = "https://files.pythonhosted.org/packages/f1/60/b22cdbee7e4013dab8b0d7647fc6181120fbbbc8f7025c226d15bd5a47fc/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bd47ba7fc3ca94896759ea0109775132d3e7ab921fbf54038e1bab2e46c313c9", size = 232003, upload-time = "2026-07-07T14:33:40.059Z" }, + { url = "https://files.pythonhosted.org/packages/ea/f8/72eb13dcabe7257035cea8aefd922caad2f110d252bf9f67c4c2ca763aee/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:84fd18bcc17526fc2b3c1af7d2b9217d32c9c04448c16ec693b9b4f1985c3d33", size = 223149, upload-time = "2026-07-07T14:33:41.631Z" }, + { url = "https://files.pythonhosted.org/packages/b0/3e/faee8f9de92b14ee1198e9163252bb15efee7301b31256a3b6d9ebfdd0dd/charset_normalizer-3.4.9-cp313-cp313-manylinux_2_31_armv7l.whl", hash = "sha256:5b10cd92fc5c498b35a8635df6d5a100207f88b63a4dc1de7ef9a548e1e2cd63", size = 207901, upload-time = "2026-07-07T14:33:43.209Z" }, + { url = "https://files.pythonhosted.org/packages/3a/25/45f30093ae27dd7b92a793b61882a38685f993700113ca36e0c9c14965e1/charset_normalizer-3.4.9-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a4fbdde9dd4a9ce5fd52c2b3a347bb50cc89483ef783f1cb00d408c13f7a96c0", size = 219176, upload-time = "2026-07-07T14:33:44.725Z" }, + { url = "https://files.pythonhosted.org/packages/48/18/c8f397329c35e32f6a837e488986f4ae03bd2abebc453b48714991630c2f/charset_normalizer-3.4.9-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:416c229f77e5ea25b3dfd4b582f8d73d7e43c22320302b9ab128a2d3a0b38efe", size = 217356, upload-time = "2026-07-07T14:33:46.192Z" }, + { url = "https://files.pythonhosted.org/packages/86/7e/5ce0bba863470fd1902d5e5843968951bddf38abe4742fc97116ef4598b3/charset_normalizer-3.4.9-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:75286256590a6320cf106a0d28970d3560aad9ee09aa7b34fb40524792436d35", size = 209614, upload-time = "2026-07-07T14:33:47.705Z" }, + { url = "https://files.pythonhosted.org/packages/6c/ef/2473d3c4d869155be4af1191111d59c4d5c4e0173026f7e85b176e23bf65/charset_normalizer-3.4.9-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:69b157c5d3292bcd443faca052f3096f637f1e074b98212a933c074ae23dc3b8", size = 224991, upload-time = "2026-07-07T14:33:49.238Z" }, + { url = "https://files.pythonhosted.org/packages/d0/a3/53ddae3db108a088156aa8ddfafd411ebbc1340f48c5573f697b27f69a39/charset_normalizer-3.4.9-cp313-cp313-win32.whl", hash = "sha256:51307f5c71007673a2bf8232ad973483d281e74cb99c8c5a990af1eefa6277d9", size = 150622, upload-time = "2026-07-07T14:33:50.711Z" }, + { url = "https://files.pythonhosted.org/packages/e8/ef/6953a77c7cf2c2ff9998e6f575ab3e380119f100223381565a4f94c1f836/charset_normalizer-3.4.9-cp313-cp313-win_amd64.whl", hash = "sha256:fe2c7201c642b7c308f1675355ad7ff7b66acfe3541625efe5a3ad38f29d6115", size = 161947, upload-time = "2026-07-07T14:33:52.197Z" }, + { url = "https://files.pythonhosted.org/packages/6e/fb/d560d1d1555debbfe7849d9cac6145c1b537709d79576bf22557ed803b82/charset_normalizer-3.4.9-cp313-cp313-win_arm64.whl", hash = "sha256:611057cc5d5c0afc743ba8be6bd828c17e0aaa8643f9d0a9b9bb7dea80eb8012", size = 152594, upload-time = "2026-07-07T14:33:53.486Z" }, + { url = "https://files.pythonhosted.org/packages/7e/8d/496817fa0944239ecae662dd57ea765cfeaec6a735f9f025d4b7b72e7143/charset_normalizer-3.4.9-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:0327fcd59a935777d83410750c50600ee9571af2846f71ce40f25b13da1ef380", size = 317253, upload-time = "2026-07-07T14:33:54.994Z" }, + { url = "https://files.pythonhosted.org/packages/2b/f9/ef4a69ea338ad3c0deceea0f5f7d2380ae8b52132b06d652cb0d2cd86706/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8a79d9f4d8001473a30c163556b3c3bfebec837495a412dde78b51672f6134f9", size = 215898, upload-time = "2026-07-07T14:33:56.334Z" }, + { url = "https://files.pythonhosted.org/packages/8c/e7/5ddfd76fc061eb52de219658a4aa431cbacadf0a0219c8854f00da50d289/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:33bdcc2a32c0a0e861f60841a512c8acc658c87c2ac59d89e3a46dacf7d866e4", size = 236718, upload-time = "2026-07-07T14:33:57.9Z" }, + { url = "https://files.pythonhosted.org/packages/49/ba/768fa3f36048d81c477a0ce61f813bc1454d80917ccfe550abd9f44f5e24/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f840ed6d8ecba8255df8c42b87fadeda98ddfc6eeec05e2dc66e26d46dd6f58a", size = 232519, upload-time = "2026-07-07T14:33:59.811Z" }, + { url = "https://files.pythonhosted.org/packages/f4/c4/b3e049d2aa3766180c78507110543d9d50894cc97f57de543f1be521dcdc/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c25fe15c70c59eb7c5ce8c06a1f3fa1da0ecc5ea1e7a5922c40fd2fa9b0d5046", size = 223143, upload-time = "2026-07-07T14:34:01.517Z" }, + { url = "https://files.pythonhosted.org/packages/19/79/55c32d06d76ae4feafe053f061f3e3ab70bcf19f4007797ce8c3efda7830/charset_normalizer-3.4.9-cp314-cp314-manylinux_2_31_armv7l.whl", hash = "sha256:f7fb7d750cfa0a070d2c24e831fd3481019a60dd317ea2b39acbcebc08b6ed81", size = 206742, upload-time = "2026-07-07T14:34:03.04Z" }, + { url = "https://files.pythonhosted.org/packages/10/e0/47c079dd82d217c807479cd59ffd30af56307ea31c108b75758970459ad3/charset_normalizer-3.4.9-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4d1c96a7a18b9690a4d46df09e3e3382406ae3213727cd1019ebade1c4a81917", size = 219191, upload-time = "2026-07-07T14:34:04.657Z" }, + { url = "https://files.pythonhosted.org/packages/42/ab/b9bc2e77d6b44a7e46ef62ec5cac1c9a6ba7b9135a5d560f002696ec9995/charset_normalizer-3.4.9-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a4cfde78a9f2880208d16a93b795726a3017d5977e08d1e162a7a31322479c41", size = 218328, upload-time = "2026-07-07T14:34:06.115Z" }, + { url = "https://files.pythonhosted.org/packages/f1/78/c9c71d599f5aa2d42bcdd35cbbd46d7f535351a57e40ff7d8e5a7e219401/charset_normalizer-3.4.9-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:d4d6fcde76f94f5cb9e43e9e9a61f16dacefd228cbbf6f1a09bd9b219a92f1a1", size = 207406, upload-time = "2026-07-07T14:34:07.554Z" }, + { url = "https://files.pythonhosted.org/packages/f6/39/c914445c321a845097ce4f6ac7de9a18228a77b766272125a1ce00d851eb/charset_normalizer-3.4.9-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:898f0e9068ca27d37f8e83a5b962821df851532e6c4a7d615c1c033f9da6eedf", size = 225157, upload-time = "2026-07-07T14:34:09.061Z" }, + { url = "https://files.pythonhosted.org/packages/9b/f2/c0d4b8508565a36bc5c624e88ed297f5b0b1095011034d7f5b83a69908b5/charset_normalizer-3.4.9-cp314-cp314-win32.whl", hash = "sha256:c1c948747b03be832dceed96ca815cef7360de9aa19d37c730f8e3f6101aca48", size = 151095, upload-time = "2026-07-07T14:34:10.901Z" }, + { url = "https://files.pythonhosted.org/packages/49/fd/a1d26144398c67486422a72bf5812cda22cb4ccfcd95a290fb41ceb4b8e2/charset_normalizer-3.4.9-cp314-cp314-win_amd64.whl", hash = "sha256:16b65ea0f2465b6fb52aa22de5eca612aa964ddfec00a912e26f4656cbef890b", size = 162796, upload-time = "2026-07-07T14:34:12.47Z" }, + { url = "https://files.pythonhosted.org/packages/20/95/d75e82f8ce9fd323ebf059c16c9aadefb22a1ecde13b7840b35835e4886c/charset_normalizer-3.4.9-cp314-cp314-win_arm64.whl", hash = "sha256:40a126142a56b2dfc0aacbad1de8310cbf60da7656db0e6b16eebd48e3e93519", size = 153334, upload-time = "2026-07-07T14:34:14.044Z" }, + { url = "https://files.pythonhosted.org/packages/00/5e/17398df3a139985ba9d11ed072531986f408c8fca952835ef1ab1820c02b/charset_normalizer-3.4.9-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:609b3ba8fcc0fb5ab7af00719d0fb6ad0cb518e48e7712d12fd68f1327951198", size = 338848, upload-time = "2026-07-07T14:34:15.688Z" }, + { url = "https://files.pythonhosted.org/packages/cd/91/7253a32e86b7e1d1239b1b36ba6dd0f021a21107ab33054b53119cc083b9/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:51447e9aa2684679af07ca5021c3db526e0284347ebf4ffcec1154c3350cfe32", size = 223022, upload-time = "2026-07-07T14:34:17.248Z" }, + { url = "https://files.pythonhosted.org/packages/cb/32/2e64bd2be10e89c61e57ebe6a93fd98ae88eb7ebe414b5121f22c96c69eb/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cc1b0fff8ead343dae06305f954eb8468ba0ec1a97881f42489d198e4ce3c632", size = 241590, upload-time = "2026-07-07T14:34:18.813Z" }, + { url = "https://files.pythonhosted.org/packages/3d/ef/d96ec496cfea0c21db43b0ad03891308b02388d054cc902cf0e5a1ad6a88/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fa36ec09ef71d158186bc79e359ff5fdd6e7996fe8ab638f00d6b93139ba4fcf", size = 239584, upload-time = "2026-07-07T14:34:20.52Z" }, + { url = "https://files.pythonhosted.org/packages/d4/ce/9af95f7876194bd7a14e3dfe4a4de2e0bff02666a3910d72beafd06cc297/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:df115d4d83168fdf2cae48ef1ff6d1cb4c466364e30861b37121de0f3bf1b990", size = 230224, upload-time = "2026-07-07T14:34:22.189Z" }, + { url = "https://files.pythonhosted.org/packages/52/94/af74dde74a3996bd959c350709bfe50e297823d70a8c1cbd54b838880863/charset_normalizer-3.4.9-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:f86c6358749bd4fda175388691e3ba8c46e24c5347d0afd20f9b7edfc9faf07d", size = 212667, upload-time = "2026-07-07T14:34:23.857Z" }, + { url = "https://files.pythonhosted.org/packages/ee/f0/f1c4fe746c395922961b5916ed1d7d6e7d4c84851d19ed43cc89980ec953/charset_normalizer-3.4.9-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:32286a2c8d167e897177b673176c1e3e00d4057caf5d2b64eef9a3666b03018e", size = 227179, upload-time = "2026-07-07T14:34:25.586Z" }, + { url = "https://files.pythonhosted.org/packages/e4/56/6c745619ac397e8871e2bcd3cea1eec86b877488f33888b3aef5c3ed506e/charset_normalizer-3.4.9-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:83aed2c10721ddd90f68140685391b50811a880af20654c59af6b6c66c40513c", size = 225372, upload-time = "2026-07-07T14:34:27.212Z" }, + { url = "https://files.pythonhosted.org/packages/78/ad/98aae8630ac71f16711968e38a5acfecce41b778bf2f0312851020f565a8/charset_normalizer-3.4.9-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:cd6c3d4b783c556fa00bf540854e42f135e2f256abd29669fcd0da0f2dec79c2", size = 215222, upload-time = "2026-07-07T14:34:28.774Z" }, + { url = "https://files.pythonhosted.org/packages/f7/40/9593d54209765207a7f11073c06494c1721e4ca4a0a426c597679bf7f91e/charset_normalizer-3.4.9-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ee2f2a527e3c1a6e6411eb4209642e138b544a2d72fe5d0d76daf77b24063534", size = 231958, upload-time = "2026-07-07T14:34:30.345Z" }, + { url = "https://files.pythonhosted.org/packages/b1/27/693ee5e8a18191eb38647360c51cd505013e2bd3b366aa43fd5344c21e3c/charset_normalizer-3.4.9-cp314-cp314t-win32.whl", hash = "sha256:0d861473f743244d349b50f850d10eb87aeb22bbdcc8e64f79273c94af5a8226", size = 155580, upload-time = "2026-07-07T14:34:31.884Z" }, + { url = "https://files.pythonhosted.org/packages/80/3f/bd97d3d9c613013d07cb7733d299385b41df37f0471310f5a73dc359f0b8/charset_normalizer-3.4.9-cp314-cp314t-win_amd64.whl", hash = "sha256:9b8e0f3107e2200b76f6054de99016eac3ee6762713587b36baaa7e4bd2ae177", size = 167620, upload-time = "2026-07-07T14:34:33.438Z" }, + { url = "https://files.pythonhosted.org/packages/3d/c6/eee9dca4439b1061f76373f06ea855678cc4a64c1c3c90b50e479edbb8eb/charset_normalizer-3.4.9-cp314-cp314t-win_arm64.whl", hash = "sha256:19ac87f93086ce37b86e098888555c4b4bc48102279bae3350098c0ed664b501", size = 158037, upload-time = "2026-07-07T14:34:35.018Z" }, + { url = "https://files.pythonhosted.org/packages/98/2b/f97f1c193fb855c345d678f5077d6926034db0722df74c8f057020e05a25/charset_normalizer-3.4.9-py3-none-any.whl", hash = "sha256:68e5f26a1ad57ded6d1cfb85331d1c1a195314756471d97758c48498bb4dcdf5", size = 64538, upload-time = "2026-07-07T14:34:56.993Z" }, +] + +[[package]] +name = "click" +version = "8.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/76/d4/81420972a676e8ffea40450d8c8c92943e7218a78fe9b64359836cc9876b/click-8.4.2.tar.gz", hash = "sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6", size = 338000, upload-time = "2026-06-24T17:45:15.148Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/e2/79c688af8b210d232694e31e59da9f6ec747bae31c3f5946e4e9b98860d5/click-8.4.2-py3-none-any.whl", hash = "sha256:e6f9f66136c816745b9d65817da91d61d957fb16e02e4dcd0552553c5a197b76", size = 119243, upload-time = "2026-06-24T17:45:13.73Z" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "comm" +version = "0.2.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/4c/13/7d740c5849255756bc17888787313b61fd38a0a8304fc4f073dfc46122aa/comm-0.2.3.tar.gz", hash = "sha256:2dc8048c10962d55d7ad693be1e7045d891b7ce8d999c97963a5e3e99c055971", size = 6319, upload-time = "2025-07-25T14:02:04.452Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/60/97/891a0971e1e4a8c5d2b20bbe0e524dc04548d2307fee33cdeba148fd4fc7/comm-0.2.3-py3-none-any.whl", hash = "sha256:c615d91d75f7f04f095b30d1c1711babd43bdc6419c1be9886a85f2f4e489417", size = 7294, upload-time = "2025-07-25T14:02:02.896Z" }, +] + +[[package]] +name = "debugpy" +version = "1.8.21" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f2/aa/12037145b7a56eaa5b29b41872f7a21b538e807e13f32c4d3c46e59be084/debugpy-1.8.21.tar.gz", hash = "sha256:a3c53278e84c94e11bd87c53970ec391d1a67396c8b22609fcac576520e611a6", size = 1697577, upload-time = "2026-06-01T19:30:35.156Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a2/df/bf625547431a9cadc9f4cbfeda38866e2b17f6aed147b625377e87834449/debugpy-1.8.21-cp312-cp312-macosx_15_0_universal2.whl", hash = "sha256:9f96713896f39c3dff0ee841f47320c3f2983d33c341e009361bb0ebc79adc4e", size = 2483609, upload-time = "2026-06-01T19:30:50.794Z" }, + { url = "https://files.pythonhosted.org/packages/bf/09/59324b903599031ff9faaec1758292409f6561a0ec2492fe4b703327705a/debugpy-1.8.21-cp312-cp312-manylinux_2_34_x86_64.whl", hash = "sha256:c193d474f0a211191f2b4449d2d06157c689013035bd952f3b617e0ef422b176", size = 3968900, upload-time = "2026-06-01T19:30:52.341Z" }, + { url = "https://files.pythonhosted.org/packages/14/cd/27f65b805d7fe005c44e1a36b9183ecdfbcdbf9d3e721a5115d461ecc7ee/debugpy-1.8.21-cp312-cp312-win32.whl", hash = "sha256:4743373c1cac7f9e74a1b9915bf1dbe0e900eca657ffb170ae07ac8363205ae9", size = 5336340, upload-time = "2026-06-01T19:30:54.047Z" }, + { url = "https://files.pythonhosted.org/packages/77/1d/c84e30c0c674184948b66f076ab271c01d940618a2824c23cd035a27bc20/debugpy-1.8.21-cp312-cp312-win_amd64.whl", hash = "sha256:bd7ba9dd3daa7c2f942c6ca8d4695a16bf9ac16b63615261c7982bc74f7ed20c", size = 5374751, upload-time = "2026-06-01T19:30:55.891Z" }, + { url = "https://files.pythonhosted.org/packages/77/6b/d817e1f8cc77aa055d37fba092e0febfdff40fe652d8d53d4cd7a86ad98d/debugpy-1.8.21-cp313-cp313-macosx_15_0_universal2.whl", hash = "sha256:13678151fc401e2d68c9880b91e28714f797d40422994572b24560ef80910a88", size = 2477398, upload-time = "2026-06-01T19:30:57.644Z" }, + { url = "https://files.pythonhosted.org/packages/48/57/412421516afc3055fa577516f00beec3d663f9b0ab330639547ae6c57720/debugpy-1.8.21-cp313-cp313-manylinux_2_34_x86_64.whl", hash = "sha256:ecbd158386c31ffe71d46f72d44d56e66331ab9b16cad649156d514368f23ab2", size = 3962096, upload-time = "2026-06-01T19:30:59.235Z" }, + { url = "https://files.pythonhosted.org/packages/c1/62/2c616337cf6ba7b07ebbc97f02c6c945a8e2f76b365e33ee809c32ee36d1/debugpy-1.8.21-cp313-cp313-win32.whl", hash = "sha256:2c2ae706dec41d99a9ca1f7ebc987a83e65578363be6f6b3ac9067504917fae1", size = 5336288, upload-time = "2026-06-01T19:31:00.79Z" }, + { url = "https://files.pythonhosted.org/packages/f8/99/9175103392f84c4b1bf7622888cdc68da07f0ff7d9e581266428f6776033/debugpy-1.8.21-cp313-cp313-win_amd64.whl", hash = "sha256:aa648733047443eb1d07682c4ef287d36a54507b643ffdf38b09a3ef002c72a0", size = 5376567, upload-time = "2026-06-01T19:31:02.56Z" }, + { url = "https://files.pythonhosted.org/packages/ce/3d/f4bbb323a548bfab2af3d6b4ffd9bf22636e55956a1285d317a1de643aad/debugpy-1.8.21-cp314-cp314-macosx_15_0_universal2.whl", hash = "sha256:9bb2a685287a2ac9b181cde89edcec64845cb51de7faaa75badb9a698bc24782", size = 2477209, upload-time = "2026-06-01T19:31:04.157Z" }, + { url = "https://files.pythonhosted.org/packages/8c/2d/6e7ec524984a1702777868de49a4c53202bddac2a432a76a093469587750/debugpy-1.8.21-cp314-cp314-manylinux_2_34_x86_64.whl", hash = "sha256:3d6922439bf33fd38a3e2c447869ebc7b97da5cd3d329ff1ef9bc06c4903437e", size = 3927115, upload-time = "2026-06-01T19:31:05.863Z" }, + { url = "https://files.pythonhosted.org/packages/97/47/d1aa6d64005a98a9144647d99306b419396f9ad7bf1d73c119e17a81fb4d/debugpy-1.8.21-cp314-cp314-win32.whl", hash = "sha256:15d4963bd5ffa48f0da0947fd06757fa7621945048a14ad7705431566d3c0e7c", size = 5336724, upload-time = "2026-06-01T19:31:07.711Z" }, + { url = "https://files.pythonhosted.org/packages/5f/67/b905b90d163af11878c1af8abafa4a25206335e112e284e413454543a6da/debugpy-1.8.21-cp314-cp314-win_amd64.whl", hash = "sha256:fe0744a12353406de0ae8ccff0d0a4a666f00801a3db8fd04e7a5f761cd520e8", size = 5373803, upload-time = "2026-06-01T19:31:09.469Z" }, + { url = "https://files.pythonhosted.org/packages/95/51/67e7cf11a53e40694f720457d5b3a1cdaaa3d5a9a633e482f225456b93ff/debugpy-1.8.21-py2.py3-none-any.whl", hash = "sha256:b1e37d333663c8851516a47364ef473da127f9caebe4417e6df6f5825a7e9a92", size = 5352888, upload-time = "2026-06-01T19:31:25.186Z" }, +] + +[[package]] +name = "donfig" +version = "0.8.1.post1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/25/71/80cc718ff6d7abfbabacb1f57aaa42e9c1552bfdd01e64ddd704e4a03638/donfig-0.8.1.post1.tar.gz", hash = "sha256:3bef3413a4c1c601b585e8d297256d0c1470ea012afa6e8461dc28bfb7c23f52", size = 19506, upload-time = "2024-05-23T14:14:31.513Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/d5/c5db1ea3394c6e1732fb3286b3bd878b59507a8f77d32a2cebda7d7b7cd4/donfig-0.8.1.post1-py3-none-any.whl", hash = "sha256:2a3175ce74a06109ff9307d90a230f81215cbac9a751f4d1c6194644b8204f9d", size = 21592, upload-time = "2024-05-23T14:13:55.283Z" }, +] + +[[package]] +name = "executing" +version = "2.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cc/28/c14e053b6762b1044f34a13aab6859bbf40456d37d23aa286ac24cfd9a5d/executing-2.2.1.tar.gz", hash = "sha256:3632cc370565f6648cc328b32435bd120a1e4ebb20c77e3fdde9a13cd1e533c4", size = 1129488, upload-time = "2025-09-01T09:48:10.866Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl", hash = "sha256:760643d3452b4d777d295bb167ccc74c64a81df23fb5e08eff250c425a4b2017", size = 28317, upload-time = "2025-09-01T09:48:08.5Z" }, +] + +[[package]] +name = "fastjsonschema" +version = "2.22.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/98/474719c58eddaf77fa443b063693e76d49db32bbe851bcbaf58d2700119f/fastjsonschema-2.22.1.tar.gz", hash = "sha256:0b83d1ce8d7845b959dcb20e1a5c3c8883b6541d9c52ab02cce5166b75ec805f", size = 382291, upload-time = "2026-07-27T13:31:08.515Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/17/e1/62cc96341f01bdff2ba967441939178fcd1900d11ce7e6554d9954a5d7ec/fastjsonschema-2.22.1-py3-none-any.whl", hash = "sha256:cf377ff5c9a6f4f3125fb35f75a2c5767bd824ffbcf62c209a93cd48d1453999", size = 26239, upload-time = "2026-07-27T13:31:03.251Z" }, +] + +[[package]] +name = "frozenlist" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2d/f5/c831fac6cc817d26fd54c7eaccd04ef7e0288806943f7cc5bbf69f3ac1f0/frozenlist-1.8.0.tar.gz", hash = "sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad", size = 45875, upload-time = "2025-10-06T05:38:17.865Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/29/948b9aa87e75820a38650af445d2ef2b6b8a6fab1a23b6bb9e4ef0be2d59/frozenlist-1.8.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:78f7b9e5d6f2fdb88cdde9440dc147259b62b9d3b019924def9f6478be254ac1", size = 87782, upload-time = "2025-10-06T05:36:06.649Z" }, + { url = "https://files.pythonhosted.org/packages/64/80/4f6e318ee2a7c0750ed724fa33a4bdf1eacdc5a39a7a24e818a773cd91af/frozenlist-1.8.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:229bf37d2e4acdaf808fd3f06e854a4a7a3661e871b10dc1f8f1896a3b05f18b", size = 50594, upload-time = "2025-10-06T05:36:07.69Z" }, + { url = "https://files.pythonhosted.org/packages/2b/94/5c8a2b50a496b11dd519f4a24cb5496cf125681dd99e94c604ccdea9419a/frozenlist-1.8.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f833670942247a14eafbb675458b4e61c82e002a148f49e68257b79296e865c4", size = 50448, upload-time = "2025-10-06T05:36:08.78Z" }, + { url = "https://files.pythonhosted.org/packages/6a/bd/d91c5e39f490a49df14320f4e8c80161cfcce09f1e2cde1edd16a551abb3/frozenlist-1.8.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:494a5952b1c597ba44e0e78113a7266e656b9794eec897b19ead706bd7074383", size = 242411, upload-time = "2025-10-06T05:36:09.801Z" }, + { url = "https://files.pythonhosted.org/packages/8f/83/f61505a05109ef3293dfb1ff594d13d64a2324ac3482be2cedc2be818256/frozenlist-1.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96f423a119f4777a4a056b66ce11527366a8bb92f54e541ade21f2374433f6d4", size = 243014, upload-time = "2025-10-06T05:36:11.394Z" }, + { url = "https://files.pythonhosted.org/packages/d8/cb/cb6c7b0f7d4023ddda30cf56b8b17494eb3a79e3fda666bf735f63118b35/frozenlist-1.8.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3462dd9475af2025c31cc61be6652dfa25cbfb56cbbf52f4ccfe029f38decaf8", size = 234909, upload-time = "2025-10-06T05:36:12.598Z" }, + { url = "https://files.pythonhosted.org/packages/31/c5/cd7a1f3b8b34af009fb17d4123c5a778b44ae2804e3ad6b86204255f9ec5/frozenlist-1.8.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c4c800524c9cd9bac5166cd6f55285957fcfc907db323e193f2afcd4d9abd69b", size = 250049, upload-time = "2025-10-06T05:36:14.065Z" }, + { url = "https://files.pythonhosted.org/packages/c0/01/2f95d3b416c584a1e7f0e1d6d31998c4a795f7544069ee2e0962a4b60740/frozenlist-1.8.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d6a5df73acd3399d893dafc71663ad22534b5aa4f94e8a2fabfe856c3c1b6a52", size = 256485, upload-time = "2025-10-06T05:36:15.39Z" }, + { url = "https://files.pythonhosted.org/packages/ce/03/024bf7720b3abaebcff6d0793d73c154237b85bdf67b7ed55e5e9596dc9a/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:405e8fe955c2280ce66428b3ca55e12b3c4e9c336fb2103a4937e891c69a4a29", size = 237619, upload-time = "2025-10-06T05:36:16.558Z" }, + { url = "https://files.pythonhosted.org/packages/69/fa/f8abdfe7d76b731f5d8bd217827cf6764d4f1d9763407e42717b4bed50a0/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:908bd3f6439f2fef9e85031b59fd4f1297af54415fb60e4254a95f75b3cab3f3", size = 250320, upload-time = "2025-10-06T05:36:17.821Z" }, + { url = "https://files.pythonhosted.org/packages/f5/3c/b051329f718b463b22613e269ad72138cc256c540f78a6de89452803a47d/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:294e487f9ec720bd8ffcebc99d575f7eff3568a08a253d1ee1a0378754b74143", size = 246820, upload-time = "2025-10-06T05:36:19.046Z" }, + { url = "https://files.pythonhosted.org/packages/0f/ae/58282e8f98e444b3f4dd42448ff36fa38bef29e40d40f330b22e7108f565/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:74c51543498289c0c43656701be6b077f4b265868fa7f8a8859c197006efb608", size = 250518, upload-time = "2025-10-06T05:36:20.763Z" }, + { url = "https://files.pythonhosted.org/packages/8f/96/007e5944694d66123183845a106547a15944fbbb7154788cbf7272789536/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:776f352e8329135506a1d6bf16ac3f87bc25b28e765949282dcc627af36123aa", size = 239096, upload-time = "2025-10-06T05:36:22.129Z" }, + { url = "https://files.pythonhosted.org/packages/66/bb/852b9d6db2fa40be96f29c0d1205c306288f0684df8fd26ca1951d461a56/frozenlist-1.8.0-cp312-cp312-win32.whl", hash = "sha256:433403ae80709741ce34038da08511d4a77062aa924baf411ef73d1146e74faf", size = 39985, upload-time = "2025-10-06T05:36:23.661Z" }, + { url = "https://files.pythonhosted.org/packages/b8/af/38e51a553dd66eb064cdf193841f16f077585d4d28394c2fa6235cb41765/frozenlist-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:34187385b08f866104f0c0617404c8eb08165ab1272e884abc89c112e9c00746", size = 44591, upload-time = "2025-10-06T05:36:24.958Z" }, + { url = "https://files.pythonhosted.org/packages/a7/06/1dc65480ab147339fecc70797e9c2f69d9cea9cf38934ce08df070fdb9cb/frozenlist-1.8.0-cp312-cp312-win_arm64.whl", hash = "sha256:fe3c58d2f5db5fbd18c2987cba06d51b0529f52bc3a6cdc33d3f4eab725104bd", size = 40102, upload-time = "2025-10-06T05:36:26.333Z" }, + { url = "https://files.pythonhosted.org/packages/2d/40/0832c31a37d60f60ed79e9dfb5a92e1e2af4f40a16a29abcc7992af9edff/frozenlist-1.8.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8d92f1a84bb12d9e56f818b3a746f3efba93c1b63c8387a73dde655e1e42282a", size = 85717, upload-time = "2025-10-06T05:36:27.341Z" }, + { url = "https://files.pythonhosted.org/packages/30/ba/b0b3de23f40bc55a7057bd38434e25c34fa48e17f20ee273bbde5e0650f3/frozenlist-1.8.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:96153e77a591c8adc2ee805756c61f59fef4cf4073a9275ee86fe8cba41241f7", size = 49651, upload-time = "2025-10-06T05:36:28.855Z" }, + { url = "https://files.pythonhosted.org/packages/0c/ab/6e5080ee374f875296c4243c381bbdef97a9ac39c6e3ce1d5f7d42cb78d6/frozenlist-1.8.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f21f00a91358803399890ab167098c131ec2ddd5f8f5fd5fe9c9f2c6fcd91e40", size = 49417, upload-time = "2025-10-06T05:36:29.877Z" }, + { url = "https://files.pythonhosted.org/packages/d5/4e/e4691508f9477ce67da2015d8c00acd751e6287739123113a9fca6f1604e/frozenlist-1.8.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:fb30f9626572a76dfe4293c7194a09fb1fe93ba94c7d4f720dfae3b646b45027", size = 234391, upload-time = "2025-10-06T05:36:31.301Z" }, + { url = "https://files.pythonhosted.org/packages/40/76/c202df58e3acdf12969a7895fd6f3bc016c642e6726aa63bd3025e0fc71c/frozenlist-1.8.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eaa352d7047a31d87dafcacbabe89df0aa506abb5b1b85a2fb91bc3faa02d822", size = 233048, upload-time = "2025-10-06T05:36:32.531Z" }, + { url = "https://files.pythonhosted.org/packages/f9/c0/8746afb90f17b73ca5979c7a3958116e105ff796e718575175319b5bb4ce/frozenlist-1.8.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:03ae967b4e297f58f8c774c7eabcce57fe3c2434817d4385c50661845a058121", size = 226549, upload-time = "2025-10-06T05:36:33.706Z" }, + { url = "https://files.pythonhosted.org/packages/7e/eb/4c7eefc718ff72f9b6c4893291abaae5fbc0c82226a32dcd8ef4f7a5dbef/frozenlist-1.8.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f6292f1de555ffcc675941d65fffffb0a5bcd992905015f85d0592201793e0e5", size = 239833, upload-time = "2025-10-06T05:36:34.947Z" }, + { url = "https://files.pythonhosted.org/packages/c2/4e/e5c02187cf704224f8b21bee886f3d713ca379535f16893233b9d672ea71/frozenlist-1.8.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:29548f9b5b5e3460ce7378144c3010363d8035cea44bc0bf02d57f5a685e084e", size = 245363, upload-time = "2025-10-06T05:36:36.534Z" }, + { url = "https://files.pythonhosted.org/packages/1f/96/cb85ec608464472e82ad37a17f844889c36100eed57bea094518bf270692/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ec3cc8c5d4084591b4237c0a272cc4f50a5b03396a47d9caaf76f5d7b38a4f11", size = 229314, upload-time = "2025-10-06T05:36:38.582Z" }, + { url = "https://files.pythonhosted.org/packages/5d/6f/4ae69c550e4cee66b57887daeebe006fe985917c01d0fff9caab9883f6d0/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:517279f58009d0b1f2e7c1b130b377a349405da3f7621ed6bfae50b10adf20c1", size = 243365, upload-time = "2025-10-06T05:36:40.152Z" }, + { url = "https://files.pythonhosted.org/packages/7a/58/afd56de246cf11780a40a2c28dc7cbabbf06337cc8ddb1c780a2d97e88d8/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:db1e72ede2d0d7ccb213f218df6a078a9c09a7de257c2fe8fcef16d5925230b1", size = 237763, upload-time = "2025-10-06T05:36:41.355Z" }, + { url = "https://files.pythonhosted.org/packages/cb/36/cdfaf6ed42e2644740d4a10452d8e97fa1c062e2a8006e4b09f1b5fd7d63/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:b4dec9482a65c54a5044486847b8a66bf10c9cb4926d42927ec4e8fd5db7fed8", size = 240110, upload-time = "2025-10-06T05:36:42.716Z" }, + { url = "https://files.pythonhosted.org/packages/03/a8/9ea226fbefad669f11b52e864c55f0bd57d3c8d7eb07e9f2e9a0b39502e1/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:21900c48ae04d13d416f0e1e0c4d81f7931f73a9dfa0b7a8746fb2fe7dd970ed", size = 233717, upload-time = "2025-10-06T05:36:44.251Z" }, + { url = "https://files.pythonhosted.org/packages/1e/0b/1b5531611e83ba7d13ccc9988967ea1b51186af64c42b7a7af465dcc9568/frozenlist-1.8.0-cp313-cp313-win32.whl", hash = "sha256:8b7b94a067d1c504ee0b16def57ad5738701e4ba10cec90529f13fa03c833496", size = 39628, upload-time = "2025-10-06T05:36:45.423Z" }, + { url = "https://files.pythonhosted.org/packages/d8/cf/174c91dbc9cc49bc7b7aab74d8b734e974d1faa8f191c74af9b7e80848e6/frozenlist-1.8.0-cp313-cp313-win_amd64.whl", hash = "sha256:878be833caa6a3821caf85eb39c5ba92d28e85df26d57afb06b35b2efd937231", size = 43882, upload-time = "2025-10-06T05:36:46.796Z" }, + { url = "https://files.pythonhosted.org/packages/c1/17/502cd212cbfa96eb1388614fe39a3fc9ab87dbbe042b66f97acb57474834/frozenlist-1.8.0-cp313-cp313-win_arm64.whl", hash = "sha256:44389d135b3ff43ba8cc89ff7f51f5a0bb6b63d829c8300f79a2fe4fe61bcc62", size = 39676, upload-time = "2025-10-06T05:36:47.8Z" }, + { url = "https://files.pythonhosted.org/packages/d2/5c/3bbfaa920dfab09e76946a5d2833a7cbdf7b9b4a91c714666ac4855b88b4/frozenlist-1.8.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:e25ac20a2ef37e91c1b39938b591457666a0fa835c7783c3a8f33ea42870db94", size = 89235, upload-time = "2025-10-06T05:36:48.78Z" }, + { url = "https://files.pythonhosted.org/packages/d2/d6/f03961ef72166cec1687e84e8925838442b615bd0b8854b54923ce5b7b8a/frozenlist-1.8.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:07cdca25a91a4386d2e76ad992916a85038a9b97561bf7a3fd12d5d9ce31870c", size = 50742, upload-time = "2025-10-06T05:36:49.837Z" }, + { url = "https://files.pythonhosted.org/packages/1e/bb/a6d12b7ba4c3337667d0e421f7181c82dda448ce4e7ad7ecd249a16fa806/frozenlist-1.8.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:4e0c11f2cc6717e0a741f84a527c52616140741cd812a50422f83dc31749fb52", size = 51725, upload-time = "2025-10-06T05:36:50.851Z" }, + { url = "https://files.pythonhosted.org/packages/bc/71/d1fed0ffe2c2ccd70b43714c6cab0f4188f09f8a67a7914a6b46ee30f274/frozenlist-1.8.0-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b3210649ee28062ea6099cfda39e147fa1bc039583c8ee4481cb7811e2448c51", size = 284533, upload-time = "2025-10-06T05:36:51.898Z" }, + { url = "https://files.pythonhosted.org/packages/c9/1f/fb1685a7b009d89f9bf78a42d94461bc06581f6e718c39344754a5d9bada/frozenlist-1.8.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:581ef5194c48035a7de2aefc72ac6539823bb71508189e5de01d60c9dcd5fa65", size = 292506, upload-time = "2025-10-06T05:36:53.101Z" }, + { url = "https://files.pythonhosted.org/packages/e6/3b/b991fe1612703f7e0d05c0cf734c1b77aaf7c7d321df4572e8d36e7048c8/frozenlist-1.8.0-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3ef2d026f16a2b1866e1d86fc4e1291e1ed8a387b2c333809419a2f8b3a77b82", size = 274161, upload-time = "2025-10-06T05:36:54.309Z" }, + { url = "https://files.pythonhosted.org/packages/ca/ec/c5c618767bcdf66e88945ec0157d7f6c4a1322f1473392319b7a2501ded7/frozenlist-1.8.0-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5500ef82073f599ac84d888e3a8c1f77ac831183244bfd7f11eaa0289fb30714", size = 294676, upload-time = "2025-10-06T05:36:55.566Z" }, + { url = "https://files.pythonhosted.org/packages/7c/ce/3934758637d8f8a88d11f0585d6495ef54b2044ed6ec84492a91fa3b27aa/frozenlist-1.8.0-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:50066c3997d0091c411a66e710f4e11752251e6d2d73d70d8d5d4c76442a199d", size = 300638, upload-time = "2025-10-06T05:36:56.758Z" }, + { url = "https://files.pythonhosted.org/packages/fc/4f/a7e4d0d467298f42de4b41cbc7ddaf19d3cfeabaf9ff97c20c6c7ee409f9/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:5c1c8e78426e59b3f8005e9b19f6ff46e5845895adbde20ece9218319eca6506", size = 283067, upload-time = "2025-10-06T05:36:57.965Z" }, + { url = "https://files.pythonhosted.org/packages/dc/48/c7b163063d55a83772b268e6d1affb960771b0e203b632cfe09522d67ea5/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:eefdba20de0d938cec6a89bd4d70f346a03108a19b9df4248d3cf0d88f1b0f51", size = 292101, upload-time = "2025-10-06T05:36:59.237Z" }, + { url = "https://files.pythonhosted.org/packages/9f/d0/2366d3c4ecdc2fd391e0afa6e11500bfba0ea772764d631bbf82f0136c9d/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:cf253e0e1c3ceb4aaff6df637ce033ff6535fb8c70a764a8f46aafd3d6ab798e", size = 289901, upload-time = "2025-10-06T05:37:00.811Z" }, + { url = "https://files.pythonhosted.org/packages/b8/94/daff920e82c1b70e3618a2ac39fbc01ae3e2ff6124e80739ce5d71c9b920/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:032efa2674356903cd0261c4317a561a6850f3ac864a63fc1583147fb05a79b0", size = 289395, upload-time = "2025-10-06T05:37:02.115Z" }, + { url = "https://files.pythonhosted.org/packages/e3/20/bba307ab4235a09fdcd3cc5508dbabd17c4634a1af4b96e0f69bfe551ebd/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:6da155091429aeba16851ecb10a9104a108bcd32f6c1642867eadaee401c1c41", size = 283659, upload-time = "2025-10-06T05:37:03.711Z" }, + { url = "https://files.pythonhosted.org/packages/fd/00/04ca1c3a7a124b6de4f8a9a17cc2fcad138b4608e7a3fc5877804b8715d7/frozenlist-1.8.0-cp313-cp313t-win32.whl", hash = "sha256:0f96534f8bfebc1a394209427d0f8a63d343c9779cda6fc25e8e121b5fd8555b", size = 43492, upload-time = "2025-10-06T05:37:04.915Z" }, + { url = "https://files.pythonhosted.org/packages/59/5e/c69f733a86a94ab10f68e496dc6b7e8bc078ebb415281d5698313e3af3a1/frozenlist-1.8.0-cp313-cp313t-win_amd64.whl", hash = "sha256:5d63a068f978fc69421fb0e6eb91a9603187527c86b7cd3f534a5b77a592b888", size = 48034, upload-time = "2025-10-06T05:37:06.343Z" }, + { url = "https://files.pythonhosted.org/packages/16/6c/be9d79775d8abe79b05fa6d23da99ad6e7763a1d080fbae7290b286093fd/frozenlist-1.8.0-cp313-cp313t-win_arm64.whl", hash = "sha256:bf0a7e10b077bf5fb9380ad3ae8ce20ef919a6ad93b4552896419ac7e1d8e042", size = 41749, upload-time = "2025-10-06T05:37:07.431Z" }, + { url = "https://files.pythonhosted.org/packages/f1/c8/85da824b7e7b9b6e7f7705b2ecaf9591ba6f79c1177f324c2735e41d36a2/frozenlist-1.8.0-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:cee686f1f4cadeb2136007ddedd0aaf928ab95216e7691c63e50a8ec066336d0", size = 86127, upload-time = "2025-10-06T05:37:08.438Z" }, + { url = "https://files.pythonhosted.org/packages/8e/e8/a1185e236ec66c20afd72399522f142c3724c785789255202d27ae992818/frozenlist-1.8.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:119fb2a1bd47307e899c2fac7f28e85b9a543864df47aa7ec9d3c1b4545f096f", size = 49698, upload-time = "2025-10-06T05:37:09.48Z" }, + { url = "https://files.pythonhosted.org/packages/a1/93/72b1736d68f03fda5fdf0f2180fb6caaae3894f1b854d006ac61ecc727ee/frozenlist-1.8.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:4970ece02dbc8c3a92fcc5228e36a3e933a01a999f7094ff7c23fbd2beeaa67c", size = 49749, upload-time = "2025-10-06T05:37:10.569Z" }, + { url = "https://files.pythonhosted.org/packages/a7/b2/fabede9fafd976b991e9f1b9c8c873ed86f202889b864756f240ce6dd855/frozenlist-1.8.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:cba69cb73723c3f329622e34bdbf5ce1f80c21c290ff04256cff1cd3c2036ed2", size = 231298, upload-time = "2025-10-06T05:37:11.993Z" }, + { url = "https://files.pythonhosted.org/packages/3a/3b/d9b1e0b0eed36e70477ffb8360c49c85c8ca8ef9700a4e6711f39a6e8b45/frozenlist-1.8.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:778a11b15673f6f1df23d9586f83c4846c471a8af693a22e066508b77d201ec8", size = 232015, upload-time = "2025-10-06T05:37:13.194Z" }, + { url = "https://files.pythonhosted.org/packages/dc/94/be719d2766c1138148564a3960fc2c06eb688da592bdc25adcf856101be7/frozenlist-1.8.0-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0325024fe97f94c41c08872db482cf8ac4800d80e79222c6b0b7b162d5b13686", size = 225038, upload-time = "2025-10-06T05:37:14.577Z" }, + { url = "https://files.pythonhosted.org/packages/e4/09/6712b6c5465f083f52f50cf74167b92d4ea2f50e46a9eea0523d658454ae/frozenlist-1.8.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:97260ff46b207a82a7567b581ab4190bd4dfa09f4db8a8b49d1a958f6aa4940e", size = 240130, upload-time = "2025-10-06T05:37:15.781Z" }, + { url = "https://files.pythonhosted.org/packages/f8/d4/cd065cdcf21550b54f3ce6a22e143ac9e4836ca42a0de1022da8498eac89/frozenlist-1.8.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:54b2077180eb7f83dd52c40b2750d0a9f175e06a42e3213ce047219de902717a", size = 242845, upload-time = "2025-10-06T05:37:17.037Z" }, + { url = "https://files.pythonhosted.org/packages/62/c3/f57a5c8c70cd1ead3d5d5f776f89d33110b1addae0ab010ad774d9a44fb9/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:2f05983daecab868a31e1da44462873306d3cbfd76d1f0b5b69c473d21dbb128", size = 229131, upload-time = "2025-10-06T05:37:18.221Z" }, + { url = "https://files.pythonhosted.org/packages/6c/52/232476fe9cb64f0742f3fde2b7d26c1dac18b6d62071c74d4ded55e0ef94/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:33f48f51a446114bc5d251fb2954ab0164d5be02ad3382abcbfe07e2531d650f", size = 240542, upload-time = "2025-10-06T05:37:19.771Z" }, + { url = "https://files.pythonhosted.org/packages/5f/85/07bf3f5d0fb5414aee5f47d33c6f5c77bfe49aac680bfece33d4fdf6a246/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:154e55ec0655291b5dd1b8731c637ecdb50975a2ae70c606d100750a540082f7", size = 237308, upload-time = "2025-10-06T05:37:20.969Z" }, + { url = "https://files.pythonhosted.org/packages/11/99/ae3a33d5befd41ac0ca2cc7fd3aa707c9c324de2e89db0e0f45db9a64c26/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:4314debad13beb564b708b4a496020e5306c7333fa9a3ab90374169a20ffab30", size = 238210, upload-time = "2025-10-06T05:37:22.252Z" }, + { url = "https://files.pythonhosted.org/packages/b2/60/b1d2da22f4970e7a155f0adde9b1435712ece01b3cd45ba63702aea33938/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:073f8bf8becba60aa931eb3bc420b217bb7d5b8f4750e6f8b3be7f3da85d38b7", size = 231972, upload-time = "2025-10-06T05:37:23.5Z" }, + { url = "https://files.pythonhosted.org/packages/3f/ab/945b2f32de889993b9c9133216c068b7fcf257d8595a0ac420ac8677cab0/frozenlist-1.8.0-cp314-cp314-win32.whl", hash = "sha256:bac9c42ba2ac65ddc115d930c78d24ab8d4f465fd3fc473cdedfccadb9429806", size = 40536, upload-time = "2025-10-06T05:37:25.581Z" }, + { url = "https://files.pythonhosted.org/packages/59/ad/9caa9b9c836d9ad6f067157a531ac48b7d36499f5036d4141ce78c230b1b/frozenlist-1.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:3e0761f4d1a44f1d1a47996511752cf3dcec5bbdd9cc2b4fe595caf97754b7a0", size = 44330, upload-time = "2025-10-06T05:37:26.928Z" }, + { url = "https://files.pythonhosted.org/packages/82/13/e6950121764f2676f43534c555249f57030150260aee9dcf7d64efda11dd/frozenlist-1.8.0-cp314-cp314-win_arm64.whl", hash = "sha256:d1eaff1d00c7751b7c6662e9c5ba6eb2c17a2306ba5e2a37f24ddf3cc953402b", size = 40627, upload-time = "2025-10-06T05:37:28.075Z" }, + { url = "https://files.pythonhosted.org/packages/c0/c7/43200656ecc4e02d3f8bc248df68256cd9572b3f0017f0a0c4e93440ae23/frozenlist-1.8.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:d3bb933317c52d7ea5004a1c442eef86f426886fba134ef8cf4226ea6ee1821d", size = 89238, upload-time = "2025-10-06T05:37:29.373Z" }, + { url = "https://files.pythonhosted.org/packages/d1/29/55c5f0689b9c0fb765055629f472c0de484dcaf0acee2f7707266ae3583c/frozenlist-1.8.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:8009897cdef112072f93a0efdce29cd819e717fd2f649ee3016efd3cd885a7ed", size = 50738, upload-time = "2025-10-06T05:37:30.792Z" }, + { url = "https://files.pythonhosted.org/packages/ba/7d/b7282a445956506fa11da8c2db7d276adcbf2b17d8bb8407a47685263f90/frozenlist-1.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2c5dcbbc55383e5883246d11fd179782a9d07a986c40f49abe89ddf865913930", size = 51739, upload-time = "2025-10-06T05:37:32.127Z" }, + { url = "https://files.pythonhosted.org/packages/62/1c/3d8622e60d0b767a5510d1d3cf21065b9db874696a51ea6d7a43180a259c/frozenlist-1.8.0-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:39ecbc32f1390387d2aa4f5a995e465e9e2f79ba3adcac92d68e3e0afae6657c", size = 284186, upload-time = "2025-10-06T05:37:33.21Z" }, + { url = "https://files.pythonhosted.org/packages/2d/14/aa36d5f85a89679a85a1d44cd7a6657e0b1c75f61e7cad987b203d2daca8/frozenlist-1.8.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92db2bf818d5cc8d9c1f1fc56b897662e24ea5adb36ad1f1d82875bd64e03c24", size = 292196, upload-time = "2025-10-06T05:37:36.107Z" }, + { url = "https://files.pythonhosted.org/packages/05/23/6bde59eb55abd407d34f77d39a5126fb7b4f109a3f611d3929f14b700c66/frozenlist-1.8.0-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:2dc43a022e555de94c3b68a4ef0b11c4f747d12c024a520c7101709a2144fb37", size = 273830, upload-time = "2025-10-06T05:37:37.663Z" }, + { url = "https://files.pythonhosted.org/packages/d2/3f/22cff331bfad7a8afa616289000ba793347fcd7bc275f3b28ecea2a27909/frozenlist-1.8.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cb89a7f2de3602cfed448095bab3f178399646ab7c61454315089787df07733a", size = 294289, upload-time = "2025-10-06T05:37:39.261Z" }, + { url = "https://files.pythonhosted.org/packages/a4/89/5b057c799de4838b6c69aa82b79705f2027615e01be996d2486a69ca99c4/frozenlist-1.8.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:33139dc858c580ea50e7e60a1b0ea003efa1fd42e6ec7fdbad78fff65fad2fd2", size = 300318, upload-time = "2025-10-06T05:37:43.213Z" }, + { url = "https://files.pythonhosted.org/packages/30/de/2c22ab3eb2a8af6d69dc799e48455813bab3690c760de58e1bf43b36da3e/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:168c0969a329b416119507ba30b9ea13688fafffac1b7822802537569a1cb0ef", size = 282814, upload-time = "2025-10-06T05:37:45.337Z" }, + { url = "https://files.pythonhosted.org/packages/59/f7/970141a6a8dbd7f556d94977858cfb36fa9b66e0892c6dd780d2219d8cd8/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:28bd570e8e189d7f7b001966435f9dac6718324b5be2990ac496cf1ea9ddb7fe", size = 291762, upload-time = "2025-10-06T05:37:46.657Z" }, + { url = "https://files.pythonhosted.org/packages/c1/15/ca1adae83a719f82df9116d66f5bb28bb95557b3951903d39135620ef157/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:b2a095d45c5d46e5e79ba1e5b9cb787f541a8dee0433836cea4b96a2c439dcd8", size = 289470, upload-time = "2025-10-06T05:37:47.946Z" }, + { url = "https://files.pythonhosted.org/packages/ac/83/dca6dc53bf657d371fbc88ddeb21b79891e747189c5de990b9dfff2ccba1/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:eab8145831a0d56ec9c4139b6c3e594c7a83c2c8be25d5bcf2d86136a532287a", size = 289042, upload-time = "2025-10-06T05:37:49.499Z" }, + { url = "https://files.pythonhosted.org/packages/96/52/abddd34ca99be142f354398700536c5bd315880ed0a213812bc491cff5e4/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:974b28cf63cc99dfb2188d8d222bc6843656188164848c4f679e63dae4b0708e", size = 283148, upload-time = "2025-10-06T05:37:50.745Z" }, + { url = "https://files.pythonhosted.org/packages/af/d3/76bd4ed4317e7119c2b7f57c3f6934aba26d277acc6309f873341640e21f/frozenlist-1.8.0-cp314-cp314t-win32.whl", hash = "sha256:342c97bf697ac5480c0a7ec73cd700ecfa5a8a40ac923bd035484616efecc2df", size = 44676, upload-time = "2025-10-06T05:37:52.222Z" }, + { url = "https://files.pythonhosted.org/packages/89/76/c615883b7b521ead2944bb3480398cbb07e12b7b4e4d073d3752eb721558/frozenlist-1.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:06be8f67f39c8b1dc671f5d83aaefd3358ae5cdcf8314552c57e7ed3e6475bdd", size = 49451, upload-time = "2025-10-06T05:37:53.425Z" }, + { url = "https://files.pythonhosted.org/packages/e0/a3/5982da14e113d07b325230f95060e2169f5311b1017ea8af2a29b374c289/frozenlist-1.8.0-cp314-cp314t-win_arm64.whl", hash = "sha256:102e6314ca4da683dca92e3b1355490fed5f313b768500084fbe6371fddfdb79", size = 42507, upload-time = "2025-10-06T05:37:54.513Z" }, + { url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" }, +] + +[[package]] +name = "fsspec" +version = "2026.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/00/78/f34251dadb8f3921264a1d9b8946f5e542014ee2614b285261b4e40e6775/fsspec-2026.7.0.tar.gz", hash = "sha256:c803c40f4cf860b49dea58ee3e1c33cb9c790520e233537e1340049f89b82a88", size = 317040, upload-time = "2026-07-28T16:34:51.052Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fd/3c/6a2bf344106328fd04963664a60b9bb6496fc25df8e962fcdc1367285fb9/fsspec-2026.7.0-py3-none-any.whl", hash = "sha256:b57ddbafedfaef7018c1ecab32aa200a9d7ca26b77965f64e48b70061249d279", size = 206583, upload-time = "2026-07-28T16:34:49.538Z" }, +] + +[package.optional-dependencies] +http = [ + { name = "aiohttp" }, +] + +[[package]] +name = "ghp-import" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d9/29/d40217cbe2f6b1359e00c6c307bb3fc876ba74068cbab3dde77f03ca0dc4/ghp-import-2.1.0.tar.gz", hash = "sha256:9c535c4c61193c2df8871222567d7fd7e5014d835f97dc7b7439069e2413d343", size = 10943, upload-time = "2022-05-02T15:47:16.11Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f7/ec/67fbef5d497f86283db54c22eec6f6140243aae73265799baaaa19cd17fb/ghp_import-2.1.0-py3-none-any.whl", hash = "sha256:8337dd7b50877f163d4c0289bc1f1c7f127550241988d568c1db512c4324a619", size = 11034, upload-time = "2022-05-02T15:47:14.552Z" }, +] + +[[package]] +name = "google-crc32c" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/03/41/4b9c02f99e4c5fb477122cd5437403b552873f014616ac1d19ac8221a58d/google_crc32c-1.8.0.tar.gz", hash = "sha256:a428e25fb7691024de47fecfbff7ff957214da51eddded0da0ae0e0f03a2cf79", size = 14192, upload-time = "2025-12-16T00:35:25.142Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e9/5f/7307325b1198b59324c0fa9807cafb551afb65e831699f2ce211ad5c8240/google_crc32c-1.8.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:4b8286b659c1335172e39563ab0a768b8015e88e08329fa5321f774275fc3113", size = 31300, upload-time = "2025-12-16T00:21:56.723Z" }, + { url = "https://files.pythonhosted.org/packages/21/8e/58c0d5d86e2220e6a37befe7e6a94dd2f6006044b1a33edf1ff6d9f7e319/google_crc32c-1.8.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:2a3dc3318507de089c5384cc74d54318401410f82aa65b2d9cdde9d297aca7cb", size = 30867, upload-time = "2025-12-16T00:38:31.302Z" }, + { url = "https://files.pythonhosted.org/packages/ce/a9/a780cc66f86335a6019f557a8aaca8fbb970728f0efd2430d15ff1beae0e/google_crc32c-1.8.0-cp312-cp312-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:14f87e04d613dfa218d6135e81b78272c3b904e2a7053b841481b38a7d901411", size = 33364, upload-time = "2025-12-16T00:40:22.96Z" }, + { url = "https://files.pythonhosted.org/packages/21/3f/3457ea803db0198c9aaca2dd373750972ce28a26f00544b6b85088811939/google_crc32c-1.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb5c869c2923d56cb0c8e6bcdd73c009c36ae39b652dbe46a05eb4ef0ad01454", size = 33740, upload-time = "2025-12-16T00:40:23.96Z" }, + { url = "https://files.pythonhosted.org/packages/df/c0/87c2073e0c72515bb8733d4eef7b21548e8d189f094b5dad20b0ecaf64f6/google_crc32c-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:3cc0c8912038065eafa603b238abf252e204accab2a704c63b9e14837a854962", size = 34437, upload-time = "2025-12-16T00:35:21.395Z" }, + { url = "https://files.pythonhosted.org/packages/d1/db/000f15b41724589b0e7bc24bc7a8967898d8d3bc8caf64c513d91ef1f6c0/google_crc32c-1.8.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:3ebb04528e83b2634857f43f9bb8ef5b2bbe7f10f140daeb01b58f972d04736b", size = 31297, upload-time = "2025-12-16T00:23:20.709Z" }, + { url = "https://files.pythonhosted.org/packages/d7/0d/8ebed0c39c53a7e838e2a486da8abb0e52de135f1b376ae2f0b160eb4c1a/google_crc32c-1.8.0-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:450dc98429d3e33ed2926fc99ee81001928d63460f8538f21a5d6060912a8e27", size = 30867, upload-time = "2025-12-16T00:43:14.628Z" }, + { url = "https://files.pythonhosted.org/packages/ce/42/b468aec74a0354b34c8cbf748db20d6e350a68a2b0912e128cabee49806c/google_crc32c-1.8.0-cp313-cp313-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3b9776774b24ba76831609ffbabce8cdf6fa2bd5e9df37b594221c7e333a81fa", size = 33344, upload-time = "2025-12-16T00:40:24.742Z" }, + { url = "https://files.pythonhosted.org/packages/1c/e8/b33784d6fc77fb5062a8a7854e43e1e618b87d5ddf610a88025e4de6226e/google_crc32c-1.8.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:89c17d53d75562edfff86679244830599ee0a48efc216200691de8b02ab6b2b8", size = 33694, upload-time = "2025-12-16T00:40:25.505Z" }, + { url = "https://files.pythonhosted.org/packages/92/b1/d3cbd4d988afb3d8e4db94ca953df429ed6db7282ed0e700d25e6c7bfc8d/google_crc32c-1.8.0-cp313-cp313-win_amd64.whl", hash = "sha256:57a50a9035b75643996fbf224d6661e386c7162d1dfdab9bc4ca790947d1007f", size = 34435, upload-time = "2025-12-16T00:35:22.107Z" }, + { url = "https://files.pythonhosted.org/packages/21/88/8ecf3c2b864a490b9e7010c84fd203ec8cf3b280651106a3a74dd1b0ca72/google_crc32c-1.8.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:e6584b12cb06796d285d09e33f63309a09368b9d806a551d8036a4207ea43697", size = 31301, upload-time = "2025-12-16T00:24:48.527Z" }, + { url = "https://files.pythonhosted.org/packages/36/c6/f7ff6c11f5ca215d9f43d3629163727a272eabc356e5c9b2853df2bfe965/google_crc32c-1.8.0-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:f4b51844ef67d6cf2e9425983274da75f18b1597bb2c998e1c0a0e8d46f8f651", size = 30868, upload-time = "2025-12-16T00:48:12.163Z" }, + { url = "https://files.pythonhosted.org/packages/56/15/c25671c7aad70f8179d858c55a6ae8404902abe0cdcf32a29d581792b491/google_crc32c-1.8.0-cp314-cp314-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b0d1a7afc6e8e4635564ba8aa5c0548e3173e41b6384d7711a9123165f582de2", size = 33381, upload-time = "2025-12-16T00:40:26.268Z" }, + { url = "https://files.pythonhosted.org/packages/42/fa/f50f51260d7b0ef5d4898af122d8a7ec5a84e2984f676f746445f783705f/google_crc32c-1.8.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8b3f68782f3cbd1bce027e48768293072813469af6a61a86f6bb4977a4380f21", size = 33734, upload-time = "2025-12-16T00:40:27.028Z" }, + { url = "https://files.pythonhosted.org/packages/08/a5/7b059810934a09fb3ccb657e0843813c1fee1183d3bc2c8041800374aa2c/google_crc32c-1.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:d511b3153e7011a27ab6ee6bb3a5404a55b994dc1a7322c0b87b29606d9790e2", size = 34878, upload-time = "2025-12-16T00:35:23.142Z" }, +] + +[[package]] +name = "griffe-inherited-docstrings" +version = "1.1.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "griffelib" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cb/da/fd002dc5f215cd896bfccaebe8b4aa1cdeed8ea1d9d60633685bd61ff933/griffe_inherited_docstrings-1.1.3.tar.gz", hash = "sha256:cd1f937ec9336a790e5425e7f9b92f5a5ab17f292ba86917f1c681c0704cb64e", size = 26738, upload-time = "2026-02-21T09:38:44.312Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/16/20/4bc15f242181daad1c104e0a7d33be49e712461ea89e548152be0365b9ea/griffe_inherited_docstrings-1.1.3-py3-none-any.whl", hash = "sha256:aa7f6e624515c50d9325a5cfdf4b2acac547f1889aca89092d5da7278f739695", size = 6710, upload-time = "2026-02-20T11:06:38.75Z" }, +] + +[[package]] +name = "griffelib" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/e4/8d187ea29c2e30b3a09505c567513077d6117861bde1fbd997a167f262ec/griffelib-2.1.0.tar.gz", hash = "sha256:762a186d2c6fd6794d4ea20d428d597ffb857cb56b66421651cbba15bdd5e813", size = 216234, upload-time = "2026-06-19T12:05:42.278Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e4/d3/5268aeabf2ad82658c4e2ff3a060648d0f02f3926cb53247c0e4d0dab49e/griffelib-2.1.0-py3-none-any.whl", hash = "sha256:cc7b3d2d2865ad0b909fcc38086e3f554b5ea7acbaa7bbb7ecaa3f5dfb7d9f00", size = 142560, upload-time = "2026-06-19T12:05:38.742Z" }, +] + +[[package]] +name = "h11" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, +] + +[[package]] +name = "httpcore" +version = "1.0.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, +] + +[[package]] +name = "httpcore2" +version = "2.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "h11" }, + { name = "truststore" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/39/a8/20ed1ed79cbc2ecdf5301c0968ab7c85547212e2a7bd126ddd2d986e206e/httpcore2-2.9.1.tar.gz", hash = "sha256:4d8acbf8b306f48c9d6046591fd5ba4037d1b1b1000d140fc2c3eab1e9a0c0e2", size = 67089, upload-time = "2026-07-24T09:21:03.867Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9f/fb/46c52b781975c335a2bcf1072c7bbc007cbdc8d674217f5ee1daba2c848b/httpcore2-2.9.1-py3-none-any.whl", hash = "sha256:6182472379e855fe4221246a2bb7ecede403bc61c6798062ae1787d051ccde26", size = 82809, upload-time = "2026-07-24T09:21:01.178Z" }, +] + +[[package]] +name = "httpx" +version = "0.28.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "certifi" }, + { name = "httpcore" }, + { name = "idna" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, +] + +[[package]] +name = "httpx2" +version = "2.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "httpcore2" }, + { name = "idna" }, + { name = "truststore" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/21/14/38128fbafd7e0ed41d874df6c9a653d47c2d111cfe59e2b4ac95161b4abd/httpx2-2.9.1.tar.gz", hash = "sha256:1932a768737e3666291582833da748cc4e563c337cf96706fccc04fa6e58764a", size = 95458, upload-time = "2026-07-24T09:21:04.972Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/13/b8/cfd91c4ab9134d386d48f0b6ac662ff3d4be6efdee59ee1c67ebc3c0487c/httpx2-2.9.1-py3-none-any.whl", hash = "sha256:1820fe14a9ab1107bfeff39259987429450b070ec0ff38cc87eb0d8c97fdc71a", size = 91191, upload-time = "2026-07-24T09:21:02.6Z" }, +] + +[[package]] +name = "hypothesis" +version = "6.165.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sortedcontainers" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/18/7a/7a277ac07776191be594f74f6425649d529e4876f7d3ff1ee96d393ffdbc/hypothesis-6.165.3.tar.gz", hash = "sha256:687c5abb1a9c11478577c2cf18685c0eb82150d278477d3e14da290a1ef2a098", size = 502263, upload-time = "2026-08-11T01:23:09.1Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f9/c7/18152acad5f85f91554b2030000319b952a54151509953651ec40f37d50d/hypothesis-6.165.3-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:56af539c811b11ab5475704c300b8f0b46cc6dd0edc267e02a16487e803c77f8", size = 781671, upload-time = "2026-08-11T01:22:09.176Z" }, + { url = "https://files.pythonhosted.org/packages/d3/77/4293ea8a7fdb713956a8bf460b9070115df69f8216a900507633f9cdb225/hypothesis-6.165.3-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:f40c10cfdb1ea2cd75e5d4e6e0cfdcb6198ab8406e8922666480e6dc11eea341", size = 777291, upload-time = "2026-08-11T01:22:15.991Z" }, + { url = "https://files.pythonhosted.org/packages/02/fa/fa2071a6afaefc082dc7a033f41ae61436caf442d5973ba8ca9c29a69460/hypothesis-6.165.3-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7a0854b1de4577f7e1beb1d681360285b5d678b65a809787ff4eab5b8b25efca", size = 1106490, upload-time = "2026-08-11T01:22:07.858Z" }, + { url = "https://files.pythonhosted.org/packages/ba/86/de724b7f9cd10e3be4efa21770457172e549d7576b1d8e29d6177eef5e47/hypothesis-6.165.3-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:360991cda8e488924905af48949033b90d4877ac97b9ad5d826d4d0f5a4b8cfb", size = 1135054, upload-time = "2026-08-11T01:22:29.499Z" }, + { url = "https://files.pythonhosted.org/packages/12/6a/96721cf447bd3c64b5e6843dde4444b20f3ddd901ad366cc73d0e7314bf5/hypothesis-6.165.3-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bf502000f4a8ef4c9ab9493ca3b4fe17ae3033c18a8e2a31cdd69515dc7d97be", size = 1155997, upload-time = "2026-08-11T01:21:48.496Z" }, + { url = "https://files.pythonhosted.org/packages/0f/ae/a793cce6497f233b155f97684bf7d0e424c25613dd87b8af8a4e87820232/hypothesis-6.165.3-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:b9fcf47ad18f87f7c15bd36289bd45708bbfd250129d73bf554653e2f9afc931", size = 1111326, upload-time = "2026-08-11T01:22:21.9Z" }, + { url = "https://files.pythonhosted.org/packages/28/8d/dc3cdfd55843d038effa2458a9c9bd73002218a8c0fd58c2c0ab7fa328db/hypothesis-6.165.3-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2fb05529cbcab5a317d03d7bb0e90d382f79ef1643e3568577916d0e24bfe70b", size = 1148079, upload-time = "2026-08-11T01:21:51.071Z" }, + { url = "https://files.pythonhosted.org/packages/db/4b/2f62924ac41f3d3482b29ded4c213f27ff4a103e56e84eeb528d4900cac7/hypothesis-6.165.3-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:57eae10a64340cd621a78eae9cb0459bd68ea99fbaa933c4f00e34d5087b6376", size = 1281862, upload-time = "2026-08-11T01:21:39.274Z" }, + { url = "https://files.pythonhosted.org/packages/7e/d4/01c78b7b7348b6e8cef9b999109dfb93b14c7e1e38bc22170129f8b17181/hypothesis-6.165.3-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:19df0f2239052e9a870634a1d9bcdff95e2a2ab508573e5dd5c3d1ca545f5b3c", size = 1408437, upload-time = "2026-08-11T01:22:13.243Z" }, + { url = "https://files.pythonhosted.org/packages/35/76/e940b5a5aaf75bcd4784f1f3f9bf2b9a642a706bc0a9639077ca84f1325f/hypothesis-6.165.3-cp310-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:9781a8026adff4b4516404cf0e5f2cadcb471318c2882a264e1c57c4c092266f", size = 1281168, upload-time = "2026-08-11T01:21:58.964Z" }, + { url = "https://files.pythonhosted.org/packages/fc/84/b153e81a614f45e0902e3b9e8a8b079e64214c50abb6fbe9acc62ccf686d/hypothesis-6.165.3-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1dd7e05f88e3e108a5e4f5f71a3eaf205559e8951e3c1f1ffd04cea82ed3b731", size = 1323263, upload-time = "2026-08-11T01:21:52.374Z" }, + { url = "https://files.pythonhosted.org/packages/fb/5f/e5144d9e91ab7260650cb1ee032ca23208d49ebb1334845baf6407c1a9d9/hypothesis-6.165.3-cp310-abi3-win32.whl", hash = "sha256:d1389bda38cb222acc109aef5b31643ce799a39a76294a50ad8b84e32f92d76d", size = 667499, upload-time = "2026-08-11T01:21:47.36Z" }, + { url = "https://files.pythonhosted.org/packages/a9/18/f008b6f1f1c293d51c2776f8815d95bccb777dcf87df2a0ab56b273b47dc/hypothesis-6.165.3-cp310-abi3-win_amd64.whl", hash = "sha256:10cda6988ca4b1da389548b6fdd71af236b588a601fc1757e56eb8988e4240d8", size = 673643, upload-time = "2026-08-11T01:22:46.975Z" }, + { url = "https://files.pythonhosted.org/packages/e2/3d/e7eade134bd7f57d4071d82ae84691bc3017fe6945af0bb149578ba8b565/hypothesis-6.165.3-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:f88fe4915f8dd4f8999a197f9e22c3a7177042aa994d35c0c7c7b22541d2885b", size = 783298, upload-time = "2026-08-11T01:22:14.706Z" }, + { url = "https://files.pythonhosted.org/packages/d6/a5/668810f493feaf886a9240ad689792fb32450667c8e5770c3bcaa7fabeac/hypothesis-6.165.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c7d9f6c36b812f6069c7436492e12812cf541391954e21d5bd7fcafc9fb46700", size = 774856, upload-time = "2026-08-11T01:22:35.836Z" }, + { url = "https://files.pythonhosted.org/packages/e4/a0/0af93a70f5128763079ab714277ccad4a7de42d442d67dd43e3029178162/hypothesis-6.165.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:423ca8e30087bb41db7e6f47dbf98690a2155241b9f1057e366dc138d7dcc4fe", size = 1105274, upload-time = "2026-08-11T01:23:03.591Z" }, + { url = "https://files.pythonhosted.org/packages/7b/00/ddcdc99beee469573addf5cfcd817c9a20a71832b1ca88404b6d3f99c44c/hypothesis-6.165.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c58c66f3e1b8d4091bb52664d5af4b0c1715293c6822d5344b166494534cd498", size = 1155379, upload-time = "2026-08-11T01:22:23.371Z" }, + { url = "https://files.pythonhosted.org/packages/de/10/d574b21e63f16a1cad9c0cf4592aa170285940f034d04bb33a1e08025397/hypothesis-6.165.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3774882c4685e5474b7940697da55963e591b71c6dce593d90ac4128766371ad", size = 1279259, upload-time = "2026-08-11T01:21:53.63Z" }, + { url = "https://files.pythonhosted.org/packages/b9/3f/13f6b6c7d7d0b9bb570a18617eb659b015c312b1d8d1d3aaf9f2edea9628/hypothesis-6.165.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5cb3a397a5422c67387f4408989dbdfc2b1e0306f883f2aa79b9472c80958464", size = 1322605, upload-time = "2026-08-11T01:21:42.853Z" }, + { url = "https://files.pythonhosted.org/packages/6c/dd/243317f5fb8497601dc65d3ded984834eb5f36b8ec59e7853ef753ec0ee1/hypothesis-6.165.3-cp312-cp312-win_amd64.whl", hash = "sha256:dbb74811d54b6317ba0d2047aad269c09afefaa25d1849f8f33f80a638b0c3af", size = 670812, upload-time = "2026-08-11T01:22:50.245Z" }, + { url = "https://files.pythonhosted.org/packages/03/3e/95cba31dbe775b99a4548cdae192e1ad15cee7b64fbdfe6cd4c9d00031b4/hypothesis-6.165.3-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:447f139d6dd70a5d8b178ef507463fb0430ace9ce42e3b2351d2803a391fe774", size = 783183, upload-time = "2026-08-11T01:22:45.286Z" }, + { url = "https://files.pythonhosted.org/packages/56/0e/51bf125cdf7855b69097b8f59c73ef3cf5f4e3d68a16e808d2d1f08a1ff1/hypothesis-6.165.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:6152c718606f1705e673c6b30a6ebd3ff08d340da85291dd3c432c73b28a9b3a", size = 774820, upload-time = "2026-08-11T01:22:24.825Z" }, + { url = "https://files.pythonhosted.org/packages/0a/69/b954f742b97441a5c49f8f8704826ee0637a6cce3a7d06ce85fbefc54ac5/hypothesis-6.165.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:27fe7826ad83ccc2e8062f0fab43b137bab34cef1a149a926b34a7b8382ee22c", size = 1105186, upload-time = "2026-08-11T01:21:41.733Z" }, + { url = "https://files.pythonhosted.org/packages/6e/8a/33e41d9cc1be7661e0b4129c225a93c3f12544714300aadb95ae7eedf894/hypothesis-6.165.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a1ff92876a324f7b9cdb92cedf103e380b7a12aa7df55ebcb16dd0f495a879e8", size = 1155215, upload-time = "2026-08-11T01:22:06.604Z" }, + { url = "https://files.pythonhosted.org/packages/ee/53/ba09526c9100ace5752908ac7251d2dc3960ce7e0e97a31152aaa26c33ee/hypothesis-6.165.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:53f1564c97d27fc109f212404d49cd71d7789777dbe0685628ffe9838df56240", size = 1279245, upload-time = "2026-08-11T01:21:56.182Z" }, + { url = "https://files.pythonhosted.org/packages/c1/93/fc637d355791a65364a3409ff06ade7ba5d3fc6f1d07a729781dec315fa0/hypothesis-6.165.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:788a9b0a7aae719a2b71a1c2f07e51deb1d0fe990164a9090c686833ed4bfbad", size = 1322370, upload-time = "2026-08-11T01:22:48.492Z" }, + { url = "https://files.pythonhosted.org/packages/b6/8d/826053ba0263143fed2b0e8af009dc868d8a932e7246e191deb8ca7ce8ff/hypothesis-6.165.3-cp313-cp313-win_amd64.whl", hash = "sha256:37830f0795abfdf738d2a5b6f829a73f3ab498de45a2e61b0bf3bd38d8c9ddb9", size = 670804, upload-time = "2026-08-11T01:22:00.103Z" }, + { url = "https://files.pythonhosted.org/packages/e7/27/3230f8de3d853b2b547731916ae1d1026bd197cd3f2d35dafc0b445da46b/hypothesis-6.165.3-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:38826441dbf528cc156388d0a05526086a12da3e1348353d3fa14de03e57c4b2", size = 783286, upload-time = "2026-08-11T01:22:40.816Z" }, + { url = "https://files.pythonhosted.org/packages/6c/28/9f9ca830d376c50babe55c616f6d99eea886c6ebcd8b512dcd5d56f9e40c/hypothesis-6.165.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:87490115edd34a246a4ba8b1144cbdf571438c46c406ece05caf65908667c9a9", size = 774963, upload-time = "2026-08-11T01:23:05.409Z" }, + { url = "https://files.pythonhosted.org/packages/33/3c/3c81f08ec1edce160da509c5785d78c0e25a7913899c4b9ff724bfd01420/hypothesis-6.165.3-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f51f4346cfa26bca68c68f7bbbd2b1812208bc9f572187c95ecab080ed402153", size = 1105730, upload-time = "2026-08-11T01:22:42.311Z" }, + { url = "https://files.pythonhosted.org/packages/bf/b5/f6f81b9aec9999ec63920d168617cab67a038be05487eff3410ccd072bfe/hypothesis-6.165.3-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4da89eb4b36b3260ff714d2ecc3274b9bd599fd96687d2d9ed53d5e1a801a7a7", size = 1155383, upload-time = "2026-08-11T01:21:57.58Z" }, + { url = "https://files.pythonhosted.org/packages/dd/27/7f3a8c6101675bf95c80cd8c9173d65892ca0b7b640551156dc4537fab1f/hypothesis-6.165.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:eb6d31c14d7bdfe03e501d88ee296c149a74cc93e3d01c76ea335e64ee5f33ec", size = 1279606, upload-time = "2026-08-11T01:22:37.56Z" }, + { url = "https://files.pythonhosted.org/packages/d9/16/0c23e06a24e421e532f62a95021fae34f685f3a194c081c6991b4ab202b3/hypothesis-6.165.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0863e1a9258bc103abe616fa9471cfa66a1535ea404dd8a0bf360e0a29502397", size = 1322697, upload-time = "2026-08-11T01:22:27.857Z" }, + { url = "https://files.pythonhosted.org/packages/dc/56/8356dadf45e5c635b46aa2b57fa74f3210250a8e38b860b6b75f50ed0b42/hypothesis-6.165.3-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:53c56155f2cfbb45ec97fef9ea3b8453b4a34c48c3c5cacee16f97dd2a037994", size = 614859, upload-time = "2026-08-11T01:22:01.304Z" }, + { url = "https://files.pythonhosted.org/packages/e3/79/124d4faf235219acd685c359760a5cb3995609bc50ce465e54c3249841ee/hypothesis-6.165.3-cp314-cp314-win_amd64.whl", hash = "sha256:c48f41e950b5e602e2fdf8f92dcc8ac7bf715a003bf822afb7c9d5cbc41bc344", size = 670600, upload-time = "2026-08-11T01:22:10.356Z" }, + { url = "https://files.pythonhosted.org/packages/01/7a/41ac5e68d9ce079d1b76d4c54126354df61b948c3d519d1289aca877eedc/hypothesis-6.165.3-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:9563d3040178fb1f522665bcec6458cc0d21ab77d7c637058a8be4ea8c01d236", size = 781746, upload-time = "2026-08-11T01:22:34.472Z" }, + { url = "https://files.pythonhosted.org/packages/5d/fb/7ecc21aae63a83dbc8036f9a0544c6b3d798db566b97b5202bdf8e770f80/hypothesis-6.165.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1fe1783543b43ba9808c016950e5e84b3804dc3365ba77c37c427b5896a558a1", size = 773382, upload-time = "2026-08-11T01:22:55.279Z" }, + { url = "https://files.pythonhosted.org/packages/cb/f2/9cc2a4768f9a483b12e307ba585f5eb9c7f5500bd16ff82ddbf62a9a1b88/hypothesis-6.165.3-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9ea34806a4df4e8305a096dcf8e53cdd903c96c1e0d2dd5b001d2283f639c3f1", size = 1103911, upload-time = "2026-08-11T01:23:00.286Z" }, + { url = "https://files.pythonhosted.org/packages/54/9e/b551a494f84976ee5bb9374c197ccc126dea2ec6f22098d5f70705237473/hypothesis-6.165.3-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d188454b95ce46ba991e3c52161255d76af25170ad28591f6b30b045e501216e", size = 1154060, upload-time = "2026-08-11T01:22:20.413Z" }, + { url = "https://files.pythonhosted.org/packages/69/37/8e22a236f1f1e599525549a34672fb0523109f571486fe209b12a84a942e/hypothesis-6.165.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:a1c47b15ce97a9b1346bc7d7013c5f215380f78ae01c0f73a1638bd8b98bdd76", size = 1277631, upload-time = "2026-08-11T01:22:30.965Z" }, + { url = "https://files.pythonhosted.org/packages/13/0f/feb33bfc23853b4ba6360ff5e34235cd8bea0d7dd1eb21e17491f581c4e2/hypothesis-6.165.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:996077ef7a3bb332b6638f698ddf7555c82784b58dde80eeba3f07c0a322b40f", size = 1321326, upload-time = "2026-08-11T01:21:45.089Z" }, + { url = "https://files.pythonhosted.org/packages/9f/3b/ad56b56540a0719f493edec0dd442ebb21272147d2482ef505d19760a6d3/hypothesis-6.165.3-cp314-cp314t-win_amd64.whl", hash = "sha256:57a8273bdafe3f450afe66999fd130d4935d775eaf4ef63fcac0bee8015fc512", size = 670613, upload-time = "2026-08-11T01:22:05.294Z" }, +] + +[[package]] +name = "idna" +version = "3.18" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/63/9496c57188a2ee585e0f1db071d75089a11e98aa86eb99d9d7618fc1edce/idna-3.18.tar.gz", hash = "sha256:ffb385a7e039654cef1ab9ef32c6fafe283c0c0467bba1d9029738ce4a14a848", size = 196711, upload-time = "2026-06-02T14:34:07.794Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/5e/d4e9f1a599fb8e573b7b87160658329fbf28d19eac2718f51fc3def3aa5a/idna-3.18-py3-none-any.whl", hash = "sha256:7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2", size = 65455, upload-time = "2026-06-02T14:34:06.319Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, +] + +[[package]] +name = "ipykernel" +version = "7.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "appnope", marker = "sys_platform == 'darwin'" }, + { name = "comm" }, + { name = "debugpy" }, + { name = "ipython" }, + { name = "jupyter-client" }, + { name = "jupyter-core" }, + { name = "matplotlib-inline" }, + { name = "nest-asyncio2" }, + { name = "packaging" }, + { name = "psutil" }, + { name = "pyzmq" }, + { name = "tornado" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/3d/c4/e4a38f579de4225a561305666f7541cdabb30075def2aa1ac17bd73c1fb5/ipykernel-7.3.0.tar.gz", hash = "sha256:9acaaaf97d16355166e4085afe9d225bfbdf2b7ef520f9df3be8f2b248275e09", size = 184899, upload-time = "2026-06-10T08:41:25.481Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3d/02/77b271f5dc58bfbc0b577c877b2365d1ffea2afe66a80c13f2312820348c/ipykernel-7.3.0-py3-none-any.whl", hash = "sha256:897eb64da762549ef610698fca5e9675195ec6ac8ec7f19d81ce1ca20c876057", size = 120583, upload-time = "2026-06-10T08:41:23.648Z" }, +] + +[[package]] +name = "ipython" +version = "9.16.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "ipython-pygments-lexers" }, + { name = "jedi" }, + { name = "matplotlib-inline" }, + { name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "prompt-toolkit" }, + { name = "psutil", marker = "sys_platform != 'cygwin' and sys_platform != 'emscripten'" }, + { name = "pygments" }, + { name = "stack-data" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/96/b150fe7e25a5a29ae9ac1374e71488639605d39a1ea4abb74c9ce33af235/ipython-9.16.1.tar.gz", hash = "sha256:5a3d1f9a47ff216d6cf9cf863124f6a2c1a198d1354c546a4d24a370a283b64c", size = 4515302, upload-time = "2026-08-03T08:36:15.571Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bc/8e/1239df488393d61076653bfb29f759d0f60cab8e030abdf7c17c31539b51/ipython-9.16.1-py3-none-any.whl", hash = "sha256:4acae635506f6d352d94c4899a19d5f85f8bc4d230932342dca556fdab1c69b4", size = 625974, upload-time = "2026-08-03T08:36:13.654Z" }, +] + +[[package]] +name = "ipython-pygments-lexers" +version = "1.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ef/4c/5dd1d8af08107f88c7f741ead7a40854b8ac24ddf9ae850afbcf698aa552/ipython_pygments_lexers-1.1.1.tar.gz", hash = "sha256:09c0138009e56b6854f9535736f4171d855c8c08a563a0dcd8022f78355c7e81", size = 8393, upload-time = "2025-01-17T11:24:34.505Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d9/33/1f075bf72b0b747cb3288d011319aaf64083cf2efef8354174e3ed4540e2/ipython_pygments_lexers-1.1.1-py3-none-any.whl", hash = "sha256:a9462224a505ade19a605f71f8fa63c2048833ce50abc86768a0d81d876dc81c", size = 8074, upload-time = "2025-01-17T11:24:33.271Z" }, +] + +[[package]] +name = "jedi" +version = "0.20.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "parso" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/46/b7/a3635f6a2d7cf5b5dd98064fc1d5fbbafcb25477bcea204a3a92145d158b/jedi-0.20.0.tar.gz", hash = "sha256:c3f4ccbd276696f4b19c54618d4fb18f9fc24b0aef02acf704b23f487daa1011", size = 3119416, upload-time = "2026-05-01T23:38:47.814Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9a/93/242e2eab5fe682ffcb8b0084bde703a41d51e17ee0f3a31ff0d9d813620a/jedi-0.20.0-py2.py3-none-any.whl", hash = "sha256:7bdd9c2634f56713299976f4cbd59cb3fa92165cc5e05ea811fb253480728b67", size = 4884812, upload-time = "2026-05-01T23:38:43.919Z" }, +] + +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, +] + +[[package]] +name = "jsonschema" +version = "4.26.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "jsonschema-specifications" }, + { name = "referencing" }, + { name = "rpds-py" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b3/fc/e067678238fa451312d4c62bf6e6cf5ec56375422aee02f9cb5f909b3047/jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326", size = 366583, upload-time = "2026-01-07T13:41:07.246Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/90/f63fb5873511e014207a475e2bb4e8b2e570d655b00ac19a9a0ca0a385ee/jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce", size = 90630, upload-time = "2026-01-07T13:41:05.306Z" }, +] + +[[package]] +name = "jsonschema-specifications" +version = "2025.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "referencing" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/74/a633ee74eb36c44aa6d1095e7cc5569bebf04342ee146178e2d36600708b/jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d", size = 32855, upload-time = "2025-09-08T01:34:59.186Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" }, +] + +[[package]] +name = "jupyter-client" +version = "8.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jupyter-core" }, + { name = "python-dateutil" }, + { name = "pyzmq" }, + { name = "tornado" }, + { name = "traitlets" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7d/dc/5512503b088997c2250b8bf18258fba9d9ce5ead641183700960d3c9d342/jupyter_client-8.9.1.tar.gz", hash = "sha256:a58f730dd9e728ba16ba1d62ebccf7ffe1ebbdbce4e95cfae941b7321ae1f4fa", size = 359256, upload-time = "2026-06-09T13:15:01.033Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3f/6f/56d39bf385c5c27988aebaf0c18a2a17e960575740100973511018bd904e/jupyter_client-8.9.1-py3-none-any.whl", hash = "sha256:0b7a295bc46e8751e9adae84781f726c851c1d911bd793edc4a3bde942e3da81", size = 109828, upload-time = "2026-06-09T13:14:58.835Z" }, +] + +[[package]] +name = "jupyter-core" +version = "5.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "platformdirs" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/02/49/9d1284d0dc65e2c757b74c6687b6d319b02f822ad039e5c512df9194d9dd/jupyter_core-5.9.1.tar.gz", hash = "sha256:4d09aaff303b9566c3ce657f580bd089ff5c91f5f89cf7d8846c3cdf465b5508", size = 89814, upload-time = "2025-10-16T19:19:18.444Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/e7/80988e32bf6f73919a113473a604f5a8f09094de312b9d52b79c2df7612b/jupyter_core-5.9.1-py3-none-any.whl", hash = "sha256:ebf87fdc6073d142e114c72c9e29a9d7ca03fad818c5d300ce2adc1fb0743407", size = 29032, upload-time = "2025-10-16T19:19:16.783Z" }, +] + +[[package]] +name = "markdown" +version = "3.10.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/29/6f/da4c6aea59b3001f2e8c0ec7497475aadaf3b021c10cab5b2858f0f32b26/markdown-3.10.3.tar.gz", hash = "sha256:3589362618f743188b4d955b874402bc814f4f83f544dc207719f4baa7d9c45f", size = 372596, upload-time = "2026-07-30T19:05:29.005Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/69/4a5af2bc115a9a33fefe51709749de8262be3f9ba063d1753a837cdbc49c/markdown-3.10.3-py3-none-any.whl", hash = "sha256:fa6c92a00a4a3c98b22728c64a935ae1928250ae65058a6ded814d2cc29a4cea", size = 110757, upload-time = "2026-07-30T19:05:27.883Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5a/72/147da192e38635ada20e0a2e1a51cf8823d2119ce8883f7053879c2199b5/markupsafe-3.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e", size = 11615, upload-time = "2025-09-27T18:36:30.854Z" }, + { url = "https://files.pythonhosted.org/packages/9a/81/7e4e08678a1f98521201c3079f77db69fb552acd56067661f8c2f534a718/markupsafe-3.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce", size = 12020, upload-time = "2025-09-27T18:36:31.971Z" }, + { url = "https://files.pythonhosted.org/packages/1e/2c/799f4742efc39633a1b54a92eec4082e4f815314869865d876824c257c1e/markupsafe-3.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d", size = 24332, upload-time = "2025-09-27T18:36:32.813Z" }, + { url = "https://files.pythonhosted.org/packages/3c/2e/8d0c2ab90a8c1d9a24f0399058ab8519a3279d1bd4289511d74e909f060e/markupsafe-3.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d", size = 22947, upload-time = "2025-09-27T18:36:33.86Z" }, + { url = "https://files.pythonhosted.org/packages/2c/54/887f3092a85238093a0b2154bd629c89444f395618842e8b0c41783898ea/markupsafe-3.0.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a", size = 21962, upload-time = "2025-09-27T18:36:35.099Z" }, + { url = "https://files.pythonhosted.org/packages/c9/2f/336b8c7b6f4a4d95e91119dc8521402461b74a485558d8f238a68312f11c/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b", size = 23760, upload-time = "2025-09-27T18:36:36.001Z" }, + { url = "https://files.pythonhosted.org/packages/32/43/67935f2b7e4982ffb50a4d169b724d74b62a3964bc1a9a527f5ac4f1ee2b/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f", size = 21529, upload-time = "2025-09-27T18:36:36.906Z" }, + { url = "https://files.pythonhosted.org/packages/89/e0/4486f11e51bbba8b0c041098859e869e304d1c261e59244baa3d295d47b7/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b", size = 23015, upload-time = "2025-09-27T18:36:37.868Z" }, + { url = "https://files.pythonhosted.org/packages/2f/e1/78ee7a023dac597a5825441ebd17170785a9dab23de95d2c7508ade94e0e/markupsafe-3.0.3-cp312-cp312-win32.whl", hash = "sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d", size = 14540, upload-time = "2025-09-27T18:36:38.761Z" }, + { url = "https://files.pythonhosted.org/packages/aa/5b/bec5aa9bbbb2c946ca2733ef9c4ca91c91b6a24580193e891b5f7dbe8e1e/markupsafe-3.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c", size = 15105, upload-time = "2025-09-27T18:36:39.701Z" }, + { url = "https://files.pythonhosted.org/packages/e5/f1/216fc1bbfd74011693a4fd837e7026152e89c4bcf3e77b6692fba9923123/markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f", size = 13906, upload-time = "2025-09-27T18:36:40.689Z" }, + { url = "https://files.pythonhosted.org/packages/38/2f/907b9c7bbba283e68f20259574b13d005c121a0fa4c175f9bed27c4597ff/markupsafe-3.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e1cf1972137e83c5d4c136c43ced9ac51d0e124706ee1c8aa8532c1287fa8795", size = 11622, upload-time = "2025-09-27T18:36:41.777Z" }, + { url = "https://files.pythonhosted.org/packages/9c/d9/5f7756922cdd676869eca1c4e3c0cd0df60ed30199ffd775e319089cb3ed/markupsafe-3.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:116bb52f642a37c115f517494ea5feb03889e04df47eeff5b130b1808ce7c219", size = 12029, upload-time = "2025-09-27T18:36:43.257Z" }, + { url = "https://files.pythonhosted.org/packages/00/07/575a68c754943058c78f30db02ee03a64b3c638586fba6a6dd56830b30a3/markupsafe-3.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:133a43e73a802c5562be9bbcd03d090aa5a1fe899db609c29e8c8d815c5f6de6", size = 24374, upload-time = "2025-09-27T18:36:44.508Z" }, + { url = "https://files.pythonhosted.org/packages/a9/21/9b05698b46f218fc0e118e1f8168395c65c8a2c750ae2bab54fc4bd4e0e8/markupsafe-3.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccfcd093f13f0f0b7fdd0f198b90053bf7b2f02a3927a30e63f3ccc9df56b676", size = 22980, upload-time = "2025-09-27T18:36:45.385Z" }, + { url = "https://files.pythonhosted.org/packages/7f/71/544260864f893f18b6827315b988c146b559391e6e7e8f7252839b1b846a/markupsafe-3.0.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:509fa21c6deb7a7a273d629cf5ec029bc209d1a51178615ddf718f5918992ab9", size = 21990, upload-time = "2025-09-27T18:36:46.916Z" }, + { url = "https://files.pythonhosted.org/packages/c2/28/b50fc2f74d1ad761af2f5dcce7492648b983d00a65b8c0e0cb457c82ebbe/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a4afe79fb3de0b7097d81da19090f4df4f8d3a2b3adaa8764138aac2e44f3af1", size = 23784, upload-time = "2025-09-27T18:36:47.884Z" }, + { url = "https://files.pythonhosted.org/packages/ed/76/104b2aa106a208da8b17a2fb72e033a5a9d7073c68f7e508b94916ed47a9/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:795e7751525cae078558e679d646ae45574b47ed6e7771863fcc079a6171a0fc", size = 21588, upload-time = "2025-09-27T18:36:48.82Z" }, + { url = "https://files.pythonhosted.org/packages/b5/99/16a5eb2d140087ebd97180d95249b00a03aa87e29cc224056274f2e45fd6/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8485f406a96febb5140bfeca44a73e3ce5116b2501ac54fe953e488fb1d03b12", size = 23041, upload-time = "2025-09-27T18:36:49.797Z" }, + { url = "https://files.pythonhosted.org/packages/19/bc/e7140ed90c5d61d77cea142eed9f9c303f4c4806f60a1044c13e3f1471d0/markupsafe-3.0.3-cp313-cp313-win32.whl", hash = "sha256:bdd37121970bfd8be76c5fb069c7751683bdf373db1ed6c010162b2a130248ed", size = 14543, upload-time = "2025-09-27T18:36:51.584Z" }, + { url = "https://files.pythonhosted.org/packages/05/73/c4abe620b841b6b791f2edc248f556900667a5a1cf023a6646967ae98335/markupsafe-3.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5", size = 15113, upload-time = "2025-09-27T18:36:52.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/3a/fa34a0f7cfef23cf9500d68cb7c32dd64ffd58a12b09225fb03dd37d5b80/markupsafe-3.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:7e68f88e5b8799aa49c85cd116c932a1ac15caaa3f5db09087854d218359e485", size = 13911, upload-time = "2025-09-27T18:36:53.513Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d7/e05cd7efe43a88a17a37b3ae96e79a19e846f3f456fe79c57ca61356ef01/markupsafe-3.0.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:218551f6df4868a8d527e3062d0fb968682fe92054e89978594c28e642c43a73", size = 11658, upload-time = "2025-09-27T18:36:54.819Z" }, + { url = "https://files.pythonhosted.org/packages/99/9e/e412117548182ce2148bdeacdda3bb494260c0b0184360fe0d56389b523b/markupsafe-3.0.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:3524b778fe5cfb3452a09d31e7b5adefeea8c5be1d43c4f810ba09f2ceb29d37", size = 12066, upload-time = "2025-09-27T18:36:55.714Z" }, + { url = "https://files.pythonhosted.org/packages/bc/e6/fa0ffcda717ef64a5108eaa7b4f5ed28d56122c9a6d70ab8b72f9f715c80/markupsafe-3.0.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4e885a3d1efa2eadc93c894a21770e4bc67899e3543680313b09f139e149ab19", size = 25639, upload-time = "2025-09-27T18:36:56.908Z" }, + { url = "https://files.pythonhosted.org/packages/96/ec/2102e881fe9d25fc16cb4b25d5f5cde50970967ffa5dddafdb771237062d/markupsafe-3.0.3-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8709b08f4a89aa7586de0aadc8da56180242ee0ada3999749b183aa23df95025", size = 23569, upload-time = "2025-09-27T18:36:57.913Z" }, + { url = "https://files.pythonhosted.org/packages/4b/30/6f2fce1f1f205fc9323255b216ca8a235b15860c34b6798f810f05828e32/markupsafe-3.0.3-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b8512a91625c9b3da6f127803b166b629725e68af71f8184ae7e7d54686a56d6", size = 23284, upload-time = "2025-09-27T18:36:58.833Z" }, + { url = "https://files.pythonhosted.org/packages/58/47/4a0ccea4ab9f5dcb6f79c0236d954acb382202721e704223a8aafa38b5c8/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9b79b7a16f7fedff2495d684f2b59b0457c3b493778c9eed31111be64d58279f", size = 24801, upload-time = "2025-09-27T18:36:59.739Z" }, + { url = "https://files.pythonhosted.org/packages/6a/70/3780e9b72180b6fecb83a4814d84c3bf4b4ae4bf0b19c27196104149734c/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:12c63dfb4a98206f045aa9563db46507995f7ef6d83b2f68eda65c307c6829eb", size = 22769, upload-time = "2025-09-27T18:37:00.719Z" }, + { url = "https://files.pythonhosted.org/packages/98/c5/c03c7f4125180fc215220c035beac6b9cb684bc7a067c84fc69414d315f5/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8f71bc33915be5186016f675cd83a1e08523649b0e33efdb898db577ef5bb009", size = 23642, upload-time = "2025-09-27T18:37:01.673Z" }, + { url = "https://files.pythonhosted.org/packages/80/d6/2d1b89f6ca4bff1036499b1e29a1d02d282259f3681540e16563f27ebc23/markupsafe-3.0.3-cp313-cp313t-win32.whl", hash = "sha256:69c0b73548bc525c8cb9a251cddf1931d1db4d2258e9599c28c07ef3580ef354", size = 14612, upload-time = "2025-09-27T18:37:02.639Z" }, + { url = "https://files.pythonhosted.org/packages/2b/98/e48a4bfba0a0ffcf9925fe2d69240bfaa19c6f7507b8cd09c70684a53c1e/markupsafe-3.0.3-cp313-cp313t-win_amd64.whl", hash = "sha256:1b4b79e8ebf6b55351f0d91fe80f893b4743f104bff22e90697db1590e47a218", size = 15200, upload-time = "2025-09-27T18:37:03.582Z" }, + { url = "https://files.pythonhosted.org/packages/0e/72/e3cc540f351f316e9ed0f092757459afbc595824ca724cbc5a5d4263713f/markupsafe-3.0.3-cp313-cp313t-win_arm64.whl", hash = "sha256:ad2cf8aa28b8c020ab2fc8287b0f823d0a7d8630784c31e9ee5edea20f406287", size = 13973, upload-time = "2025-09-27T18:37:04.929Z" }, + { url = "https://files.pythonhosted.org/packages/33/8a/8e42d4838cd89b7dde187011e97fe6c3af66d8c044997d2183fbd6d31352/markupsafe-3.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe", size = 11619, upload-time = "2025-09-27T18:37:06.342Z" }, + { url = "https://files.pythonhosted.org/packages/b5/64/7660f8a4a8e53c924d0fa05dc3a55c9cee10bbd82b11c5afb27d44b096ce/markupsafe-3.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026", size = 12029, upload-time = "2025-09-27T18:37:07.213Z" }, + { url = "https://files.pythonhosted.org/packages/da/ef/e648bfd021127bef5fa12e1720ffed0c6cbb8310c8d9bea7266337ff06de/markupsafe-3.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737", size = 24408, upload-time = "2025-09-27T18:37:09.572Z" }, + { url = "https://files.pythonhosted.org/packages/41/3c/a36c2450754618e62008bf7435ccb0f88053e07592e6028a34776213d877/markupsafe-3.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97", size = 23005, upload-time = "2025-09-27T18:37:10.58Z" }, + { url = "https://files.pythonhosted.org/packages/bc/20/b7fdf89a8456b099837cd1dc21974632a02a999ec9bf7ca3e490aacd98e7/markupsafe-3.0.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d", size = 22048, upload-time = "2025-09-27T18:37:11.547Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a7/591f592afdc734f47db08a75793a55d7fbcc6902a723ae4cfbab61010cc5/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda", size = 23821, upload-time = "2025-09-27T18:37:12.48Z" }, + { url = "https://files.pythonhosted.org/packages/7d/33/45b24e4f44195b26521bc6f1a82197118f74df348556594bd2262bda1038/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf", size = 21606, upload-time = "2025-09-27T18:37:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/ff/0e/53dfaca23a69fbfbbf17a4b64072090e70717344c52eaaaa9c5ddff1e5f0/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe", size = 23043, upload-time = "2025-09-27T18:37:14.408Z" }, + { url = "https://files.pythonhosted.org/packages/46/11/f333a06fc16236d5238bfe74daccbca41459dcd8d1fa952e8fbd5dccfb70/markupsafe-3.0.3-cp314-cp314-win32.whl", hash = "sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9", size = 14747, upload-time = "2025-09-27T18:37:15.36Z" }, + { url = "https://files.pythonhosted.org/packages/28/52/182836104b33b444e400b14f797212f720cbc9ed6ba34c800639d154e821/markupsafe-3.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581", size = 15341, upload-time = "2025-09-27T18:37:16.496Z" }, + { url = "https://files.pythonhosted.org/packages/6f/18/acf23e91bd94fd7b3031558b1f013adfa21a8e407a3fdb32745538730382/markupsafe-3.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4", size = 14073, upload-time = "2025-09-27T18:37:17.476Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f0/57689aa4076e1b43b15fdfa646b04653969d50cf30c32a102762be2485da/markupsafe-3.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab", size = 11661, upload-time = "2025-09-27T18:37:18.453Z" }, + { url = "https://files.pythonhosted.org/packages/89/c3/2e67a7ca217c6912985ec766c6393b636fb0c2344443ff9d91404dc4c79f/markupsafe-3.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175", size = 12069, upload-time = "2025-09-27T18:37:19.332Z" }, + { url = "https://files.pythonhosted.org/packages/f0/00/be561dce4e6ca66b15276e184ce4b8aec61fe83662cce2f7d72bd3249d28/markupsafe-3.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634", size = 25670, upload-time = "2025-09-27T18:37:20.245Z" }, + { url = "https://files.pythonhosted.org/packages/50/09/c419f6f5a92e5fadde27efd190eca90f05e1261b10dbd8cbcb39cd8ea1dc/markupsafe-3.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50", size = 23598, upload-time = "2025-09-27T18:37:21.177Z" }, + { url = "https://files.pythonhosted.org/packages/22/44/a0681611106e0b2921b3033fc19bc53323e0b50bc70cffdd19f7d679bb66/markupsafe-3.0.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e", size = 23261, upload-time = "2025-09-27T18:37:22.167Z" }, + { url = "https://files.pythonhosted.org/packages/5f/57/1b0b3f100259dc9fffe780cfb60d4be71375510e435efec3d116b6436d43/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5", size = 24835, upload-time = "2025-09-27T18:37:23.296Z" }, + { url = "https://files.pythonhosted.org/packages/26/6a/4bf6d0c97c4920f1597cc14dd720705eca0bf7c787aebc6bb4d1bead5388/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523", size = 22733, upload-time = "2025-09-27T18:37:24.237Z" }, + { url = "https://files.pythonhosted.org/packages/14/c7/ca723101509b518797fedc2fdf79ba57f886b4aca8a7d31857ba3ee8281f/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc", size = 23672, upload-time = "2025-09-27T18:37:25.271Z" }, + { url = "https://files.pythonhosted.org/packages/fb/df/5bd7a48c256faecd1d36edc13133e51397e41b73bb77e1a69deab746ebac/markupsafe-3.0.3-cp314-cp314t-win32.whl", hash = "sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d", size = 14819, upload-time = "2025-09-27T18:37:26.285Z" }, + { url = "https://files.pythonhosted.org/packages/1a/8a/0402ba61a2f16038b48b39bccca271134be00c5c9f0f623208399333c448/markupsafe-3.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9", size = 15426, upload-time = "2025-09-27T18:37:27.316Z" }, + { url = "https://files.pythonhosted.org/packages/70/bc/6f1c2f612465f5fa89b95bead1f44dcb607670fd42891d8fdcd5d039f4f4/markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa", size = 14146, upload-time = "2025-09-27T18:37:28.327Z" }, +] + +[[package]] +name = "matplotlib-inline" +version = "0.2.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bd/c0/9f7c9a46090390368a4d7bcb76bb87a4a36c421e4c0792cdb53486ffac7a/matplotlib_inline-0.2.2.tar.gz", hash = "sha256:72f3fe8fce36b70d4a5b612f899090cd0401deddc4ea90e1572b9f4bfb058c79", size = 8150, upload-time = "2026-05-08T17:33:33.49Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/09/5b161152e2d90f7b87f781c2e1267494aef9c32498df793f73ad0a0a494a/matplotlib_inline-0.2.2-py3-none-any.whl", hash = "sha256:3c821cf1c209f59fb2d2d64abbf5b23b67bcb2210d663f9918dd851c6da1fcf6", size = 9534, upload-time = "2026-05-08T17:33:32.055Z" }, +] + +[[package]] +name = "mergedeep" +version = "1.3.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3a/41/580bb4006e3ed0361b8151a01d324fb03f420815446c7def45d02f74c270/mergedeep-1.3.4.tar.gz", hash = "sha256:0096d52e9dad9939c3d975a774666af186eda617e6ca84df4c94dec30004f2a8", size = 4661, upload-time = "2021-02-05T18:55:30.623Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/19/04f9b178c2d8a15b076c8b5140708fa6ffc5601fb6f1e975537072df5b2a/mergedeep-1.3.4-py3-none-any.whl", hash = "sha256:70775750742b25c0d8f36c55aed03d24c3384d17c951b3175d898bd778ef0307", size = 6354, upload-time = "2021-02-05T18:55:29.583Z" }, +] + +[[package]] +name = "mkdocs" +version = "1.6.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "ghp-import" }, + { name = "jinja2" }, + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mergedeep" }, + { name = "mkdocs-get-deps" }, + { name = "packaging" }, + { name = "pathspec" }, + { name = "pyyaml" }, + { name = "pyyaml-env-tag" }, + { name = "watchdog" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bc/c6/bbd4f061bd16b378247f12953ffcb04786a618ce5e904b8c5a01a0309061/mkdocs-1.6.1.tar.gz", hash = "sha256:7b432f01d928c084353ab39c57282f29f92136665bdd6abf7c1ec8d822ef86f2", size = 3889159, upload-time = "2024-08-30T12:24:06.899Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/5b/dbc6a8cddc9cfa9c4971d59fb12bb8d42e161b7e7f8cc89e49137c5b279c/mkdocs-1.6.1-py3-none-any.whl", hash = "sha256:db91759624d1647f3f34aa0c3f327dd2601beae39a366d6e064c03468d35c20e", size = 3864451, upload-time = "2024-08-30T12:24:05.054Z" }, +] + +[[package]] +name = "mkdocs-autorefs" +version = "1.4.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mkdocs" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/52/c0/f641843de3f612a6b48253f39244165acff36657a91cc903633d456ae1ac/mkdocs_autorefs-1.4.4.tar.gz", hash = "sha256:d54a284f27a7346b9c38f1f852177940c222da508e66edc816a0fa55fc6da197", size = 56588, upload-time = "2026-02-10T15:23:55.105Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/28/de/a3e710469772c6a89595fc52816da05c1e164b4c866a89e3cb82fb1b67c5/mkdocs_autorefs-1.4.4-py3-none-any.whl", hash = "sha256:834ef5408d827071ad1bc69e0f39704fa34c7fc05bc8e1c72b227dfdc5c76089", size = 25530, upload-time = "2026-02-10T15:23:53.817Z" }, +] + +[[package]] +name = "mkdocs-get-deps" +version = "0.2.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mergedeep" }, + { name = "platformdirs" }, + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ce/25/b3cccb187655b9393572bde9b09261d267c3bf2f2cdabe347673be5976a6/mkdocs_get_deps-0.2.2.tar.gz", hash = "sha256:8ee8d5f316cdbbb2834bc1df6e69c08fe769a83e040060de26d3c19fad3599a1", size = 11047, upload-time = "2026-03-10T02:46:33.632Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/29/744136411e785c4b0b744d5413e56555265939ab3a104c6a4b719dad33fd/mkdocs_get_deps-0.2.2-py3-none-any.whl", hash = "sha256:e7878cbeac04860b8b5e0ca31d3abad3df9411a75a32cde82f8e44b6c16ff650", size = 9555, upload-time = "2026-03-10T02:46:32.256Z" }, +] + +[[package]] +name = "mkdocs-material" +version = "9.7.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "babel" }, + { name = "backrefs" }, + { name = "colorama" }, + { name = "jinja2" }, + { name = "markdown" }, + { name = "mkdocs" }, + { name = "mkdocs-material-extensions" }, + { name = "paginate" }, + { name = "pygments" }, + { name = "pymdown-extensions" }, + { name = "requests" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f1/cd/c05d3a530ba7934f144fb45f7203cd236adc25c7bdcc34673d202f4b0278/mkdocs_material-9.7.7.tar.gz", hash = "sha256:c0649c065b1b0512d60aad8c10f947f8e455284475239b364b610f2deb4d0855", size = 4097923, upload-time = "2026-07-17T16:21:33.156Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ad/21/17c1bc9e6f47c972ad66fb2ac2568f99f90f1207eeb6fc3b34d094dba7b5/mkdocs_material-9.7.7-py3-none-any.whl", hash = "sha256:8ea9bb1737a5b524a5f9dcf2e1b4ebda8274ae3008aa7845720a97083bef708f", size = 9305438, upload-time = "2026-07-17T16:21:30.017Z" }, +] + +[[package]] +name = "mkdocs-material-extensions" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/79/9b/9b4c96d6593b2a541e1cb8b34899a6d021d208bb357042823d4d2cabdbe7/mkdocs_material_extensions-1.3.1.tar.gz", hash = "sha256:10c9511cea88f568257f960358a467d12b970e1f7b2c0e5fb2bb48cab1928443", size = 11847, upload-time = "2023-11-22T19:09:45.208Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5b/54/662a4743aa81d9582ee9339d4ffa3c8fd40a4965e033d77b9da9774d3960/mkdocs_material_extensions-1.3.1-py3-none-any.whl", hash = "sha256:adff8b62700b25cb77b53358dad940f3ef973dd6db797907c49e3c2ef3ab4e31", size = 8728, upload-time = "2023-11-22T19:09:43.465Z" }, +] + +[[package]] +name = "mkdocstrings" +version = "1.0.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jinja2" }, + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mkdocs" }, + { name = "mkdocs-autorefs" }, + { name = "pymdown-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/53/71/f85bdf13355073ae15a7375f09879375a830553552e58c1c4b7e0bbc5c8b/mkdocstrings-1.0.6.tar.gz", hash = "sha256:a0b8c2bdd29a6416c80d717aa369bbf7831946bd9f23c2a66db1b1dbe7693dbd", size = 100649, upload-time = "2026-07-11T19:38:05.732Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/5b/4c1902e8bdd5c4db63284e9d101dece4038d4025d6d88850ffe0a1578980/mkdocstrings-1.0.6-py3-none-any.whl", hash = "sha256:2703708697487d1b6d6d7b412e176fa436edf120c1bf81dc9e126b12d00893c7", size = 35787, upload-time = "2026-07-11T19:38:04.417Z" }, +] + +[[package]] +name = "mkdocstrings-python" +version = "2.0.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "griffelib" }, + { name = "mkdocs-autorefs" }, + { name = "mkdocstrings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/b6/e858701499d57eee8b3fd8e78168083956c6683ddbe727b46758b19e1119/mkdocstrings_python-2.0.5.tar.gz", hash = "sha256:3a4d92556ad39637e88af94a5374213af9a8e3040c3824ceaed04b486c017594", size = 199578, upload-time = "2026-06-19T10:41:08.868Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/fc/10ab7e80650a9c9e8f4f1105f8c8e73567f88ed0c06ada589ab81d38687c/mkdocstrings_python-2.0.5-py3-none-any.whl", hash = "sha256:30c837bbff016549f659fcba6539ac351303f0fd7e713c89a040611072236e9d", size = 104951, upload-time = "2026-06-19T10:41:07.378Z" }, +] + +[[package]] +name = "multidict" +version = "6.7.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1a/c2/c2d94cbe6ac1753f3fc980da97b3d930efe1da3af3c9f5125354436c073d/multidict-6.7.1.tar.gz", hash = "sha256:ec6652a1bee61c53a3e5776b6049172c53b6aaba34f18c9ad04f82712bac623d", size = 102010, upload-time = "2026-01-26T02:46:45.979Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8d/9c/f20e0e2cf80e4b2e4b1c365bf5fe104ee633c751a724246262db8f1a0b13/multidict-6.7.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:a90f75c956e32891a4eda3639ce6dd86e87105271f43d43442a3aedf3cddf172", size = 76893, upload-time = "2026-01-26T02:43:52.754Z" }, + { url = "https://files.pythonhosted.org/packages/fe/cf/18ef143a81610136d3da8193da9d80bfe1cb548a1e2d1c775f26b23d024a/multidict-6.7.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3fccb473e87eaa1382689053e4a4618e7ba7b9b9b8d6adf2027ee474597128cd", size = 45456, upload-time = "2026-01-26T02:43:53.893Z" }, + { url = "https://files.pythonhosted.org/packages/a9/65/1caac9d4cd32e8433908683446eebc953e82d22b03d10d41a5f0fefe991b/multidict-6.7.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b0fa96985700739c4c7853a43c0b3e169360d6855780021bfc6d0f1ce7c123e7", size = 43872, upload-time = "2026-01-26T02:43:55.041Z" }, + { url = "https://files.pythonhosted.org/packages/cf/3b/d6bd75dc4f3ff7c73766e04e705b00ed6dbbaccf670d9e05a12b006f5a21/multidict-6.7.1-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:cb2a55f408c3043e42b40cc8eecd575afa27b7e0b956dfb190de0f8499a57a53", size = 251018, upload-time = "2026-01-26T02:43:56.198Z" }, + { url = "https://files.pythonhosted.org/packages/fd/80/c959c5933adedb9ac15152e4067c702a808ea183a8b64cf8f31af8ad3155/multidict-6.7.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eb0ce7b2a32d09892b3dd6cc44877a0d02a33241fafca5f25c8b6b62374f8b75", size = 258883, upload-time = "2026-01-26T02:43:57.499Z" }, + { url = "https://files.pythonhosted.org/packages/86/85/7ed40adafea3d4f1c8b916e3b5cc3a8e07dfcdcb9cd72800f4ed3ca1b387/multidict-6.7.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c3a32d23520ee37bf327d1e1a656fec76a2edd5c038bf43eddfa0572ec49c60b", size = 242413, upload-time = "2026-01-26T02:43:58.755Z" }, + { url = "https://files.pythonhosted.org/packages/d2/57/b8565ff533e48595503c785f8361ff9a4fde4d67de25c207cd0ba3befd03/multidict-6.7.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9c90fed18bffc0189ba814749fdcc102b536e83a9f738a9003e569acd540a733", size = 268404, upload-time = "2026-01-26T02:44:00.216Z" }, + { url = "https://files.pythonhosted.org/packages/e0/50/9810c5c29350f7258180dfdcb2e52783a0632862eb334c4896ac717cebcb/multidict-6.7.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:da62917e6076f512daccfbbde27f46fed1c98fee202f0559adec8ee0de67f71a", size = 269456, upload-time = "2026-01-26T02:44:02.202Z" }, + { url = "https://files.pythonhosted.org/packages/f3/8d/5e5be3ced1d12966fefb5c4ea3b2a5b480afcea36406559442c6e31d4a48/multidict-6.7.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bfde23ef6ed9db7eaee6c37dcec08524cb43903c60b285b172b6c094711b3961", size = 256322, upload-time = "2026-01-26T02:44:03.56Z" }, + { url = "https://files.pythonhosted.org/packages/31/6e/d8a26d81ac166a5592782d208dd90dfdc0a7a218adaa52b45a672b46c122/multidict-6.7.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3758692429e4e32f1ba0df23219cd0b4fc0a52f476726fff9337d1a57676a582", size = 253955, upload-time = "2026-01-26T02:44:04.845Z" }, + { url = "https://files.pythonhosted.org/packages/59/4c/7c672c8aad41534ba619bcd4ade7a0dc87ed6b8b5c06149b85d3dd03f0cd/multidict-6.7.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:398c1478926eca669f2fd6a5856b6de9c0acf23a2cb59a14c0ba5844fa38077e", size = 251254, upload-time = "2026-01-26T02:44:06.133Z" }, + { url = "https://files.pythonhosted.org/packages/7b/bd/84c24de512cbafbdbc39439f74e967f19570ce7924e3007174a29c348916/multidict-6.7.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:c102791b1c4f3ab36ce4101154549105a53dc828f016356b3e3bcae2e3a039d3", size = 252059, upload-time = "2026-01-26T02:44:07.518Z" }, + { url = "https://files.pythonhosted.org/packages/fa/ba/f5449385510825b73d01c2d4087bf6d2fccc20a2d42ac34df93191d3dd03/multidict-6.7.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:a088b62bd733e2ad12c50dad01b7d0166c30287c166e137433d3b410add807a6", size = 263588, upload-time = "2026-01-26T02:44:09.382Z" }, + { url = "https://files.pythonhosted.org/packages/d7/11/afc7c677f68f75c84a69fe37184f0f82fce13ce4b92f49f3db280b7e92b3/multidict-6.7.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:3d51ff4785d58d3f6c91bdbffcb5e1f7ddfda557727043aa20d20ec4f65e324a", size = 259642, upload-time = "2026-01-26T02:44:10.73Z" }, + { url = "https://files.pythonhosted.org/packages/2b/17/ebb9644da78c4ab36403739e0e6e0e30ebb135b9caf3440825001a0bddcb/multidict-6.7.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fc5907494fccf3e7d3f94f95c91d6336b092b5fc83811720fae5e2765890dfba", size = 251377, upload-time = "2026-01-26T02:44:12.042Z" }, + { url = "https://files.pythonhosted.org/packages/ca/a4/840f5b97339e27846c46307f2530a2805d9d537d8b8bd416af031cad7fa0/multidict-6.7.1-cp312-cp312-win32.whl", hash = "sha256:28ca5ce2fd9716631133d0e9a9b9a745ad7f60bac2bccafb56aa380fc0b6c511", size = 41887, upload-time = "2026-01-26T02:44:14.245Z" }, + { url = "https://files.pythonhosted.org/packages/80/31/0b2517913687895f5904325c2069d6a3b78f66cc641a86a2baf75a05dcbb/multidict-6.7.1-cp312-cp312-win_amd64.whl", hash = "sha256:fcee94dfbd638784645b066074b338bc9cc155d4b4bffa4adce1615c5a426c19", size = 46053, upload-time = "2026-01-26T02:44:15.371Z" }, + { url = "https://files.pythonhosted.org/packages/0c/5b/aba28e4ee4006ae4c7df8d327d31025d760ffa992ea23812a601d226e682/multidict-6.7.1-cp312-cp312-win_arm64.whl", hash = "sha256:ba0a9fb644d0c1a2194cf7ffb043bd852cea63a57f66fbd33959f7dae18517bf", size = 43307, upload-time = "2026-01-26T02:44:16.852Z" }, + { url = "https://files.pythonhosted.org/packages/f2/22/929c141d6c0dba87d3e1d38fbdf1ba8baba86b7776469f2bc2d3227a1e67/multidict-6.7.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:2b41f5fed0ed563624f1c17630cb9941cf2309d4df00e494b551b5f3e3d67a23", size = 76174, upload-time = "2026-01-26T02:44:18.509Z" }, + { url = "https://files.pythonhosted.org/packages/c7/75/bc704ae15fee974f8fccd871305e254754167dce5f9e42d88a2def741a1d/multidict-6.7.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:84e61e3af5463c19b67ced91f6c634effb89ef8bfc5ca0267f954451ed4bb6a2", size = 45116, upload-time = "2026-01-26T02:44:19.745Z" }, + { url = "https://files.pythonhosted.org/packages/79/76/55cd7186f498ed080a18440c9013011eb548f77ae1b297206d030eb1180a/multidict-6.7.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:935434b9853c7c112eee7ac891bc4cb86455aa631269ae35442cb316790c1445", size = 43524, upload-time = "2026-01-26T02:44:21.571Z" }, + { url = "https://files.pythonhosted.org/packages/e9/3c/414842ef8d5a1628d68edee29ba0e5bcf235dbfb3ccd3ea303a7fe8c72ff/multidict-6.7.1-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:432feb25a1cb67fe82a9680b4d65fb542e4635cb3166cd9c01560651ad60f177", size = 249368, upload-time = "2026-01-26T02:44:22.803Z" }, + { url = "https://files.pythonhosted.org/packages/f6/32/befed7f74c458b4a525e60519fe8d87eef72bb1e99924fa2b0f9d97a221e/multidict-6.7.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e82d14e3c948952a1a85503817e038cba5905a3352de76b9a465075d072fba23", size = 256952, upload-time = "2026-01-26T02:44:24.306Z" }, + { url = "https://files.pythonhosted.org/packages/03/d6/c878a44ba877f366630c860fdf74bfb203c33778f12b6ac274936853c451/multidict-6.7.1-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:4cfb48c6ea66c83bcaaf7e4dfa7ec1b6bbcf751b7db85a328902796dfde4c060", size = 240317, upload-time = "2026-01-26T02:44:25.772Z" }, + { url = "https://files.pythonhosted.org/packages/68/49/57421b4d7ad2e9e60e25922b08ceb37e077b90444bde6ead629095327a6f/multidict-6.7.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1d540e51b7e8e170174555edecddbd5538105443754539193e3e1061864d444d", size = 267132, upload-time = "2026-01-26T02:44:27.648Z" }, + { url = "https://files.pythonhosted.org/packages/b7/fe/ec0edd52ddbcea2a2e89e174f0206444a61440b40f39704e64dc807a70bd/multidict-6.7.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:273d23f4b40f3dce4d6c8a821c741a86dec62cded82e1175ba3d99be128147ed", size = 268140, upload-time = "2026-01-26T02:44:29.588Z" }, + { url = "https://files.pythonhosted.org/packages/b0/73/6e1b01cbeb458807aa0831742232dbdd1fa92bfa33f52a3f176b4ff3dc11/multidict-6.7.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9d624335fd4fa1c08a53f8b4be7676ebde19cd092b3895c421045ca87895b429", size = 254277, upload-time = "2026-01-26T02:44:30.902Z" }, + { url = "https://files.pythonhosted.org/packages/6a/b2/5fb8c124d7561a4974c342bc8c778b471ebbeb3cc17df696f034a7e9afe7/multidict-6.7.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:12fad252f8b267cc75b66e8fc51b3079604e8d43a75428ffe193cd9e2195dfd6", size = 252291, upload-time = "2026-01-26T02:44:32.31Z" }, + { url = "https://files.pythonhosted.org/packages/5a/96/51d4e4e06bcce92577fcd488e22600bd38e4fd59c20cb49434d054903bd2/multidict-6.7.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:03ede2a6ffbe8ef936b92cb4529f27f42be7f56afcdab5ab739cd5f27fb1cbf9", size = 250156, upload-time = "2026-01-26T02:44:33.734Z" }, + { url = "https://files.pythonhosted.org/packages/db/6b/420e173eec5fba721a50e2a9f89eda89d9c98fded1124f8d5c675f7a0c0f/multidict-6.7.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:90efbcf47dbe33dcf643a1e400d67d59abeac5db07dc3f27d6bdeae497a2198c", size = 249742, upload-time = "2026-01-26T02:44:35.222Z" }, + { url = "https://files.pythonhosted.org/packages/44/a3/ec5b5bd98f306bc2aa297b8c6f11a46714a56b1e6ef5ebda50a4f5d7c5fb/multidict-6.7.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:5c4b9bfc148f5a91be9244d6264c53035c8a0dcd2f51f1c3c6e30e30ebaa1c84", size = 262221, upload-time = "2026-01-26T02:44:36.604Z" }, + { url = "https://files.pythonhosted.org/packages/cd/f7/e8c0d0da0cd1e28d10e624604e1a36bcc3353aaebdfdc3a43c72bc683a12/multidict-6.7.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:401c5a650f3add2472d1d288c26deebc540f99e2fb83e9525007a74cd2116f1d", size = 258664, upload-time = "2026-01-26T02:44:38.008Z" }, + { url = "https://files.pythonhosted.org/packages/52/da/151a44e8016dd33feed44f730bd856a66257c1ee7aed4f44b649fb7edeb3/multidict-6.7.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:97891f3b1b3ffbded884e2916cacf3c6fc87b66bb0dde46f7357404750559f33", size = 249490, upload-time = "2026-01-26T02:44:39.386Z" }, + { url = "https://files.pythonhosted.org/packages/87/af/a3b86bf9630b732897f6fc3f4c4714b90aa4361983ccbdcd6c0339b21b0c/multidict-6.7.1-cp313-cp313-win32.whl", hash = "sha256:e1c5988359516095535c4301af38d8a8838534158f649c05dd1050222321bcb3", size = 41695, upload-time = "2026-01-26T02:44:41.318Z" }, + { url = "https://files.pythonhosted.org/packages/b2/35/e994121b0e90e46134673422dd564623f93304614f5d11886b1b3e06f503/multidict-6.7.1-cp313-cp313-win_amd64.whl", hash = "sha256:960c83bf01a95b12b08fd54324a4eb1d5b52c88932b5cba5d6e712bb3ed12eb5", size = 45884, upload-time = "2026-01-26T02:44:42.488Z" }, + { url = "https://files.pythonhosted.org/packages/ca/61/42d3e5dbf661242a69c97ea363f2d7b46c567da8eadef8890022be6e2ab0/multidict-6.7.1-cp313-cp313-win_arm64.whl", hash = "sha256:563fe25c678aaba333d5399408f5ec3c383ca5b663e7f774dd179a520b8144df", size = 43122, upload-time = "2026-01-26T02:44:43.664Z" }, + { url = "https://files.pythonhosted.org/packages/6d/b3/e6b21c6c4f314bb956016b0b3ef2162590a529b84cb831c257519e7fde44/multidict-6.7.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:c76c4bec1538375dad9d452d246ca5368ad6e1c9039dadcf007ae59c70619ea1", size = 83175, upload-time = "2026-01-26T02:44:44.894Z" }, + { url = "https://files.pythonhosted.org/packages/fb/76/23ecd2abfe0957b234f6c960f4ade497f55f2c16aeb684d4ecdbf1c95791/multidict-6.7.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:57b46b24b5d5ebcc978da4ec23a819a9402b4228b8a90d9c656422b4bdd8a963", size = 48460, upload-time = "2026-01-26T02:44:46.106Z" }, + { url = "https://files.pythonhosted.org/packages/c4/57/a0ed92b23f3a042c36bc4227b72b97eca803f5f1801c1ab77c8a212d455e/multidict-6.7.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e954b24433c768ce78ab7929e84ccf3422e46deb45a4dc9f93438f8217fa2d34", size = 46930, upload-time = "2026-01-26T02:44:47.278Z" }, + { url = "https://files.pythonhosted.org/packages/b5/66/02ec7ace29162e447f6382c495dc95826bf931d3818799bbef11e8f7df1a/multidict-6.7.1-cp313-cp313t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:3bd231490fa7217cc832528e1cd8752a96f0125ddd2b5749390f7c3ec8721b65", size = 242582, upload-time = "2026-01-26T02:44:48.604Z" }, + { url = "https://files.pythonhosted.org/packages/58/18/64f5a795e7677670e872673aca234162514696274597b3708b2c0d276cce/multidict-6.7.1-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:253282d70d67885a15c8a7716f3a73edf2d635793ceda8173b9ecc21f2fb8292", size = 250031, upload-time = "2026-01-26T02:44:50.544Z" }, + { url = "https://files.pythonhosted.org/packages/c8/ed/e192291dbbe51a8290c5686f482084d31bcd9d09af24f63358c3d42fd284/multidict-6.7.1-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0b4c48648d7649c9335cf1927a8b87fa692de3dcb15faa676c6a6f1f1aabda43", size = 228596, upload-time = "2026-01-26T02:44:51.951Z" }, + { url = "https://files.pythonhosted.org/packages/1e/7e/3562a15a60cf747397e7f2180b0a11dc0c38d9175a650e75fa1b4d325e15/multidict-6.7.1-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:98bc624954ec4d2c7cb074b8eefc2b5d0ce7d482e410df446414355d158fe4ca", size = 257492, upload-time = "2026-01-26T02:44:53.902Z" }, + { url = "https://files.pythonhosted.org/packages/24/02/7d0f9eae92b5249bb50ac1595b295f10e263dd0078ebb55115c31e0eaccd/multidict-6.7.1-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1b99af4d9eec0b49927b4402bcbb58dea89d3e0db8806a4086117019939ad3dd", size = 255899, upload-time = "2026-01-26T02:44:55.316Z" }, + { url = "https://files.pythonhosted.org/packages/00/e3/9b60ed9e23e64c73a5cde95269ef1330678e9c6e34dd4eb6b431b85b5a10/multidict-6.7.1-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6aac4f16b472d5b7dc6f66a0d49dd57b0e0902090be16594dc9ebfd3d17c47e7", size = 247970, upload-time = "2026-01-26T02:44:56.783Z" }, + { url = "https://files.pythonhosted.org/packages/3e/06/538e58a63ed5cfb0bd4517e346b91da32fde409d839720f664e9a4ae4f9d/multidict-6.7.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:21f830fe223215dffd51f538e78c172ed7c7f60c9b96a2bf05c4848ad49921c3", size = 245060, upload-time = "2026-01-26T02:44:58.195Z" }, + { url = "https://files.pythonhosted.org/packages/b2/2f/d743a3045a97c895d401e9bd29aaa09b94f5cbdf1bd561609e5a6c431c70/multidict-6.7.1-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:f5dd81c45b05518b9aa4da4aa74e1c93d715efa234fd3e8a179df611cc85e5f4", size = 235888, upload-time = "2026-01-26T02:44:59.57Z" }, + { url = "https://files.pythonhosted.org/packages/38/83/5a325cac191ab28b63c52f14f1131f3b0a55ba3b9aa65a6d0bf2a9b921a0/multidict-6.7.1-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:eb304767bca2bb92fb9c5bd33cedc95baee5bb5f6c88e63706533a1c06ad08c8", size = 243554, upload-time = "2026-01-26T02:45:01.054Z" }, + { url = "https://files.pythonhosted.org/packages/20/1f/9d2327086bd15da2725ef6aae624208e2ef828ed99892b17f60c344e57ed/multidict-6.7.1-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:c9035dde0f916702850ef66460bc4239d89d08df4d02023a5926e7446724212c", size = 252341, upload-time = "2026-01-26T02:45:02.484Z" }, + { url = "https://files.pythonhosted.org/packages/e8/2c/2a1aa0280cf579d0f6eed8ee5211c4f1730bd7e06c636ba2ee6aafda302e/multidict-6.7.1-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:af959b9beeb66c822380f222f0e0a1889331597e81f1ded7f374f3ecb0fd6c52", size = 246391, upload-time = "2026-01-26T02:45:03.862Z" }, + { url = "https://files.pythonhosted.org/packages/e5/03/7ca022ffc36c5a3f6e03b179a5ceb829be9da5783e6fe395f347c0794680/multidict-6.7.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:41f2952231456154ee479651491e94118229844dd7226541788be783be2b5108", size = 243422, upload-time = "2026-01-26T02:45:05.296Z" }, + { url = "https://files.pythonhosted.org/packages/dc/1d/b31650eab6c5778aceed46ba735bd97f7c7d2f54b319fa916c0f96e7805b/multidict-6.7.1-cp313-cp313t-win32.whl", hash = "sha256:df9f19c28adcb40b6aae30bbaa1478c389efd50c28d541d76760199fc1037c32", size = 47770, upload-time = "2026-01-26T02:45:06.754Z" }, + { url = "https://files.pythonhosted.org/packages/ac/5b/2d2d1d522e51285bd61b1e20df8f47ae1a9d80839db0b24ea783b3832832/multidict-6.7.1-cp313-cp313t-win_amd64.whl", hash = "sha256:d54ecf9f301853f2c5e802da559604b3e95bb7a3b01a9c295c6ee591b9882de8", size = 53109, upload-time = "2026-01-26T02:45:08.044Z" }, + { url = "https://files.pythonhosted.org/packages/3d/a3/cc409ba012c83ca024a308516703cf339bdc4b696195644a7215a5164a24/multidict-6.7.1-cp313-cp313t-win_arm64.whl", hash = "sha256:5a37ca18e360377cfda1d62f5f382ff41f2b8c4ccb329ed974cc2e1643440118", size = 45573, upload-time = "2026-01-26T02:45:09.349Z" }, + { url = "https://files.pythonhosted.org/packages/91/cc/db74228a8be41884a567e88a62fd589a913708fcf180d029898c17a9a371/multidict-6.7.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:8f333ec9c5eb1b7105e3b84b53141e66ca05a19a605368c55450b6ba208cb9ee", size = 75190, upload-time = "2026-01-26T02:45:10.651Z" }, + { url = "https://files.pythonhosted.org/packages/d5/22/492f2246bb5b534abd44804292e81eeaf835388901f0c574bac4eeec73c5/multidict-6.7.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:a407f13c188f804c759fc6a9f88286a565c242a76b27626594c133b82883b5c2", size = 44486, upload-time = "2026-01-26T02:45:11.938Z" }, + { url = "https://files.pythonhosted.org/packages/f1/4f/733c48f270565d78b4544f2baddc2fb2a245e5a8640254b12c36ac7ac68e/multidict-6.7.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:0e161ddf326db5577c3a4cc2d8648f81456e8a20d40415541587a71620d7a7d1", size = 43219, upload-time = "2026-01-26T02:45:14.346Z" }, + { url = "https://files.pythonhosted.org/packages/24/bb/2c0c2287963f4259c85e8bcbba9182ced8d7fca65c780c38e99e61629d11/multidict-6.7.1-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:1e3a8bb24342a8201d178c3b4984c26ba81a577c80d4d525727427460a50c22d", size = 245132, upload-time = "2026-01-26T02:45:15.712Z" }, + { url = "https://files.pythonhosted.org/packages/a7/f9/44d4b3064c65079d2467888794dea218d1601898ac50222ab8a9a8094460/multidict-6.7.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:97231140a50f5d447d3164f994b86a0bed7cd016e2682f8650d6a9158e14fd31", size = 252420, upload-time = "2026-01-26T02:45:17.293Z" }, + { url = "https://files.pythonhosted.org/packages/8b/13/78f7275e73fa17b24c9a51b0bd9d73ba64bb32d0ed51b02a746eb876abe7/multidict-6.7.1-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6b10359683bd8806a200fd2909e7c8ca3a7b24ec1d8132e483d58e791d881048", size = 233510, upload-time = "2026-01-26T02:45:19.356Z" }, + { url = "https://files.pythonhosted.org/packages/4b/25/8167187f62ae3cbd52da7893f58cb036b47ea3fb67138787c76800158982/multidict-6.7.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:283ddac99f7ac25a4acadbf004cb5ae34480bbeb063520f70ce397b281859362", size = 264094, upload-time = "2026-01-26T02:45:20.834Z" }, + { url = "https://files.pythonhosted.org/packages/a1/e7/69a3a83b7b030cf283fb06ce074a05a02322359783424d7edf0f15fe5022/multidict-6.7.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:538cec1e18c067d0e6103aa9a74f9e832904c957adc260e61cd9d8cf0c3b3d37", size = 260786, upload-time = "2026-01-26T02:45:22.818Z" }, + { url = "https://files.pythonhosted.org/packages/fe/3b/8ec5074bcfc450fe84273713b4b0a0dd47c0249358f5d82eb8104ffe2520/multidict-6.7.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7eee46ccb30ff48a1e35bb818cc90846c6be2b68240e42a78599166722cea709", size = 248483, upload-time = "2026-01-26T02:45:24.368Z" }, + { url = "https://files.pythonhosted.org/packages/48/5a/d5a99e3acbca0e29c5d9cba8f92ceb15dce78bab963b308ae692981e3a5d/multidict-6.7.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fa263a02f4f2dd2d11a7b1bb4362aa7cb1049f84a9235d31adf63f30143469a0", size = 248403, upload-time = "2026-01-26T02:45:25.982Z" }, + { url = "https://files.pythonhosted.org/packages/35/48/e58cd31f6c7d5102f2a4bf89f96b9cf7e00b6c6f3d04ecc44417c00a5a3c/multidict-6.7.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:2e1425e2f99ec5bd36c15a01b690a1a2456209c5deed58f95469ffb46039ccbb", size = 240315, upload-time = "2026-01-26T02:45:27.487Z" }, + { url = "https://files.pythonhosted.org/packages/94/33/1cd210229559cb90b6786c30676bb0c58249ff42f942765f88793b41fdce/multidict-6.7.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:497394b3239fc6f0e13a78a3e1b61296e72bf1c5f94b4c4eb80b265c37a131cd", size = 245528, upload-time = "2026-01-26T02:45:28.991Z" }, + { url = "https://files.pythonhosted.org/packages/64/f2/6e1107d226278c876c783056b7db43d800bb64c6131cec9c8dfb6903698e/multidict-6.7.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:233b398c29d3f1b9676b4b6f75c518a06fcb2ea0b925119fb2c1bc35c05e1601", size = 258784, upload-time = "2026-01-26T02:45:30.503Z" }, + { url = "https://files.pythonhosted.org/packages/4d/c1/11f664f14d525e4a1b5327a82d4de61a1db604ab34c6603bb3c2cc63ad34/multidict-6.7.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:93b1818e4a6e0930454f0f2af7dfce69307ca03cdcfb3739bf4d91241967b6c1", size = 251980, upload-time = "2026-01-26T02:45:32.603Z" }, + { url = "https://files.pythonhosted.org/packages/e1/9f/75a9ac888121d0c5bbd4ecf4eead45668b1766f6baabfb3b7f66a410e231/multidict-6.7.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f33dc2a3abe9249ea5d8360f969ec7f4142e7ac45ee7014d8f8d5acddf178b7b", size = 243602, upload-time = "2026-01-26T02:45:34.043Z" }, + { url = "https://files.pythonhosted.org/packages/9a/e7/50bf7b004cc8525d80dbbbedfdc7aed3e4c323810890be4413e589074032/multidict-6.7.1-cp314-cp314-win32.whl", hash = "sha256:3ab8b9d8b75aef9df299595d5388b14530839f6422333357af1339443cff777d", size = 40930, upload-time = "2026-01-26T02:45:36.278Z" }, + { url = "https://files.pythonhosted.org/packages/e0/bf/52f25716bbe93745595800f36fb17b73711f14da59ed0bb2eba141bc9f0f/multidict-6.7.1-cp314-cp314-win_amd64.whl", hash = "sha256:5e01429a929600e7dab7b166062d9bb54a5eed752384c7384c968c2afab8f50f", size = 45074, upload-time = "2026-01-26T02:45:37.546Z" }, + { url = "https://files.pythonhosted.org/packages/97/ab/22803b03285fa3a525f48217963da3a65ae40f6a1b6f6cf2768879e208f9/multidict-6.7.1-cp314-cp314-win_arm64.whl", hash = "sha256:4885cb0e817aef5d00a2e8451d4665c1808378dc27c2705f1bf4ef8505c0d2e5", size = 42471, upload-time = "2026-01-26T02:45:38.889Z" }, + { url = "https://files.pythonhosted.org/packages/e0/6d/f9293baa6146ba9507e360ea0292b6422b016907c393e2f63fc40ab7b7b5/multidict-6.7.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:0458c978acd8e6ea53c81eefaddbbee9c6c5e591f41b3f5e8e194780fe026581", size = 82401, upload-time = "2026-01-26T02:45:40.254Z" }, + { url = "https://files.pythonhosted.org/packages/7a/68/53b5494738d83558d87c3c71a486504d8373421c3e0dbb6d0db48ad42ee0/multidict-6.7.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:c0abd12629b0af3cf590982c0b413b1e7395cd4ec026f30986818ab95bfaa94a", size = 48143, upload-time = "2026-01-26T02:45:41.635Z" }, + { url = "https://files.pythonhosted.org/packages/37/e8/5284c53310dcdc99ce5d66563f6e5773531a9b9fe9ec7a615e9bc306b05f/multidict-6.7.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:14525a5f61d7d0c94b368a42cff4c9a4e7ba2d52e2672a7b23d84dc86fb02b0c", size = 46507, upload-time = "2026-01-26T02:45:42.99Z" }, + { url = "https://files.pythonhosted.org/packages/e4/fc/6800d0e5b3875568b4083ecf5f310dcf91d86d52573160834fb4bfcf5e4f/multidict-6.7.1-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:17307b22c217b4cf05033dabefe68255a534d637c6c9b0cc8382718f87be4262", size = 239358, upload-time = "2026-01-26T02:45:44.376Z" }, + { url = "https://files.pythonhosted.org/packages/41/75/4ad0973179361cdf3a113905e6e088173198349131be2b390f9fa4da5fc6/multidict-6.7.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a7e590ff876a3eaf1c02a4dfe0724b6e69a9e9de6d8f556816f29c496046e59", size = 246884, upload-time = "2026-01-26T02:45:47.167Z" }, + { url = "https://files.pythonhosted.org/packages/c3/9c/095bb28b5da139bd41fb9a5d5caff412584f377914bd8787c2aa98717130/multidict-6.7.1-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:5fa6a95dfee63893d80a34758cd0e0c118a30b8dcb46372bf75106c591b77889", size = 225878, upload-time = "2026-01-26T02:45:48.698Z" }, + { url = "https://files.pythonhosted.org/packages/07/d0/c0a72000243756e8f5a277b6b514fa005f2c73d481b7d9e47cd4568aa2e4/multidict-6.7.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a0543217a6a017692aa6ae5cc39adb75e587af0f3a82288b1492eb73dd6cc2a4", size = 253542, upload-time = "2026-01-26T02:45:50.164Z" }, + { url = "https://files.pythonhosted.org/packages/c0/6b/f69da15289e384ecf2a68837ec8b5ad8c33e973aa18b266f50fe55f24b8c/multidict-6.7.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f99fe611c312b3c1c0ace793f92464d8cd263cc3b26b5721950d977b006b6c4d", size = 252403, upload-time = "2026-01-26T02:45:51.779Z" }, + { url = "https://files.pythonhosted.org/packages/a2/76/b9669547afa5a1a25cd93eaca91c0da1c095b06b6d2d8ec25b713588d3a1/multidict-6.7.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9004d8386d133b7e6135679424c91b0b854d2d164af6ea3f289f8f2761064609", size = 244889, upload-time = "2026-01-26T02:45:53.27Z" }, + { url = "https://files.pythonhosted.org/packages/7e/a9/a50d2669e506dad33cfc45b5d574a205587b7b8a5f426f2fbb2e90882588/multidict-6.7.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e628ef0e6859ffd8273c69412a2465c4be4a9517d07261b33334b5ec6f3c7489", size = 241982, upload-time = "2026-01-26T02:45:54.919Z" }, + { url = "https://files.pythonhosted.org/packages/c5/bb/1609558ad8b456b4827d3c5a5b775c93b87878fd3117ed3db3423dfbce1b/multidict-6.7.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:841189848ba629c3552035a6a7f5bf3b02eb304e9fea7492ca220a8eda6b0e5c", size = 232415, upload-time = "2026-01-26T02:45:56.981Z" }, + { url = "https://files.pythonhosted.org/packages/d8/59/6f61039d2aa9261871e03ab9dc058a550d240f25859b05b67fd70f80d4b3/multidict-6.7.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:ce1bbd7d780bb5a0da032e095c951f7014d6b0a205f8318308140f1a6aba159e", size = 240337, upload-time = "2026-01-26T02:45:58.698Z" }, + { url = "https://files.pythonhosted.org/packages/a1/29/fdc6a43c203890dc2ae9249971ecd0c41deaedfe00d25cb6564b2edd99eb/multidict-6.7.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:b26684587228afed0d50cf804cc71062cc9c1cdf55051c4c6345d372947b268c", size = 248788, upload-time = "2026-01-26T02:46:00.862Z" }, + { url = "https://files.pythonhosted.org/packages/a9/14/a153a06101323e4cf086ecee3faadba52ff71633d471f9685c42e3736163/multidict-6.7.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:9f9af11306994335398293f9958071019e3ab95e9a707dc1383a35613f6abcb9", size = 242842, upload-time = "2026-01-26T02:46:02.824Z" }, + { url = "https://files.pythonhosted.org/packages/41/5f/604ae839e64a4a6efc80db94465348d3b328ee955e37acb24badbcd24d83/multidict-6.7.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:b4938326284c4f1224178a560987b6cf8b4d38458b113d9b8c1db1a836e640a2", size = 240237, upload-time = "2026-01-26T02:46:05.898Z" }, + { url = "https://files.pythonhosted.org/packages/5f/60/c3a5187bf66f6fb546ff4ab8fb5a077cbdd832d7b1908d4365c7f74a1917/multidict-6.7.1-cp314-cp314t-win32.whl", hash = "sha256:98655c737850c064a65e006a3df7c997cd3b220be4ec8fe26215760b9697d4d7", size = 48008, upload-time = "2026-01-26T02:46:07.468Z" }, + { url = "https://files.pythonhosted.org/packages/0c/f7/addf1087b860ac60e6f382240f64fb99f8bfb532bb06f7c542b83c29ca61/multidict-6.7.1-cp314-cp314t-win_amd64.whl", hash = "sha256:497bde6223c212ba11d462853cfa4f0ae6ef97465033e7dc9940cdb3ab5b48e5", size = 53542, upload-time = "2026-01-26T02:46:08.809Z" }, + { url = "https://files.pythonhosted.org/packages/4c/81/4629d0aa32302ef7b2ec65c75a728cc5ff4fa410c50096174c1632e70b3e/multidict-6.7.1-cp314-cp314t-win_arm64.whl", hash = "sha256:2bbd113e0d4af5db41d5ebfe9ccaff89de2120578164f86a5d17d5a576d1e5b2", size = 44719, upload-time = "2026-01-26T02:46:11.146Z" }, + { url = "https://files.pythonhosted.org/packages/81/08/7036c080d7117f28a4af526d794aab6a84463126db031b007717c1a6676e/multidict-6.7.1-py3-none-any.whl", hash = "sha256:55d97cc6dae627efa6a6e548885712d4864b81110ac76fa4e534c03819fa4a56", size = 12319, upload-time = "2026-01-26T02:46:44.004Z" }, +] + +[[package]] +name = "nbclient" +version = "0.11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jupyter-client" }, + { name = "jupyter-core" }, + { name = "nbformat" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/28/a5/b3bae4b590c0cbcada2c63a34f7580024e834a8ba213e949a2f906705787/nbclient-0.11.0.tar.gz", hash = "sha256:04a134a5b087f2c5887f228aca155db50169b8cd9334dee6942c8e927e56081a", size = 62535, upload-time = "2026-06-05T07:52:41.746Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/36/c9/94d73e5a01c5b926c3fa2496e97d7a8dc28ed5a77c0b2ed712f1a62e6694/nbclient-0.11.0-py3-none-any.whl", hash = "sha256:ef7fa0d59d6e1d41103933d8a445a18d5de860ca6b613b87b8574accdb3c2895", size = 25288, upload-time = "2026-06-05T07:52:40.115Z" }, +] + +[[package]] +name = "nbformat" +version = "5.11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "fastjsonschema" }, + { name = "jsonschema" }, + { name = "jupyter-core" }, + { name = "traitlets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b2/fd/80f407a9525bc5bd9865e5c37db3b78867fa43217f8aac5eab22b5f028b3/nbformat-5.11.0.tar.gz", hash = "sha256:7dbaed4a69cae28c2b4d44ab7430a6af4544fb89455023f6f21550be757b60c8", size = 151822, upload-time = "2026-08-06T12:29:55.597Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/be/4a/0eece9dad5e73230ca972f7bc29456ce7d74772f123d401fcf67379008f7/nbformat-5.11.0-py3-none-any.whl", hash = "sha256:f70a17f591a9ccd1c601d5e61a4b20972703926df0ba42458ce14bf575766bb6", size = 79820, upload-time = "2026-08-06T12:29:54.178Z" }, +] + +[[package]] +name = "nest-asyncio2" +version = "1.7.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b4/73/731debf26e27e0a0323d7bda270dc2f634b398e38f040a09da1f4351d0aa/nest_asyncio2-1.7.2.tar.gz", hash = "sha256:1921d70b92cc4612c374928d081552efb59b83d91b2b789d935c665fa01729a8", size = 14743, upload-time = "2026-02-13T00:34:04.386Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c5/3c/3179b85b0e1c3659f0369940200cd6d0fa900e6cefcc7ea0bc6dd0e29ffb/nest_asyncio2-1.7.2-py3-none-any.whl", hash = "sha256:f5dfa702f3f81f6a03857e9a19e2ba578c0946a4ad417b4c50a24d7ba641fe01", size = 7843, upload-time = "2026-02-13T00:34:02.691Z" }, +] + +[[package]] +name = "numcodecs" +version = "0.16.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/44/bd/8a391e7c356366224734efd24da929cc4796fff468bfb179fe1af6548535/numcodecs-0.16.5.tar.gz", hash = "sha256:0d0fb60852f84c0bd9543cc4d2ab9eefd37fc8efcc410acd4777e62a1d300318", size = 6276387, upload-time = "2025-11-21T02:49:48.986Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/75/cc/55420f3641a67f78392dc0bc5d02cb9eb0a9dcebf2848d1ac77253ca61fa/numcodecs-0.16.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:24e675dc8d1550cd976a99479b87d872cb142632c75cc402fea04c08c4898523", size = 1656287, upload-time = "2025-11-21T02:49:25.755Z" }, + { url = "https://files.pythonhosted.org/packages/f5/6c/86644987505dcb90ba6d627d6989c27bafb0699f9fd00187e06d05ea8594/numcodecs-0.16.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:94ddfa4341d1a3ab99989d13b01b5134abb687d3dab2ead54b450aefe4ad5bd6", size = 1148899, upload-time = "2025-11-21T02:49:26.87Z" }, + { url = "https://files.pythonhosted.org/packages/97/1e/98aaddf272552d9fef1f0296a9939d1487914a239e98678f6b20f8b0a5c8/numcodecs-0.16.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b554ab9ecf69de7ca2b6b5e8bc696bd9747559cb4dd5127bd08d7a28bec59c3a", size = 8534814, upload-time = "2025-11-21T02:49:28.547Z" }, + { url = "https://files.pythonhosted.org/packages/fb/53/78c98ef5c8b2b784453487f3e4d6c017b20747c58b470393e230c78d18e8/numcodecs-0.16.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ad1a379a45bd3491deab8ae6548313946744f868c21d5340116977ea3be5b1d6", size = 9173471, upload-time = "2025-11-21T02:49:30.444Z" }, + { url = "https://files.pythonhosted.org/packages/1c/20/2fdec87fc7f8cec950d2b0bea603c12dc9f05b4966dc5924ba5a36a61bf6/numcodecs-0.16.5-cp312-cp312-win_amd64.whl", hash = "sha256:845a9857886ffe4a3172ba1c537ae5bcc01e65068c31cf1fce1a844bd1da050f", size = 801412, upload-time = "2025-11-21T02:49:32.123Z" }, + { url = "https://files.pythonhosted.org/packages/38/38/071ced5a5fd1c85ba0e14ba721b66b053823e5176298c2f707e50bed11d9/numcodecs-0.16.5-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:25be3a516ab677dad890760d357cfe081a371d9c0a2e9a204562318ac5969de3", size = 1654359, upload-time = "2025-11-21T02:49:33.673Z" }, + { url = "https://files.pythonhosted.org/packages/d1/c0/5f84ba7525577c1b9909fc2d06ef11314825fc4ad4378f61d0e4c9883b4a/numcodecs-0.16.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0107e839ef75b854e969cb577e140b1aadb9847893937636582d23a2a4c6ce50", size = 1144237, upload-time = "2025-11-21T02:49:35.294Z" }, + { url = "https://files.pythonhosted.org/packages/0b/00/787ea5f237b8ea7bc67140c99155f9c00b5baf11c49afc5f3bfefa298f95/numcodecs-0.16.5-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:015a7c859ecc2a06e2a548f64008c0ec3aaecabc26456c2c62f4278d8fc20597", size = 8483064, upload-time = "2025-11-21T02:49:36.454Z" }, + { url = "https://files.pythonhosted.org/packages/c4/e6/d359fdd37498e74d26a167f7a51e54542e642ea47181eb4e643a69a066c3/numcodecs-0.16.5-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:84230b4b9dad2392f2a84242bd6e3e659ac137b5a1ce3571d6965fca673e0903", size = 9126063, upload-time = "2025-11-21T02:49:38.018Z" }, + { url = "https://files.pythonhosted.org/packages/27/72/6663cc0382ddbb866136c255c837bcb96cc7ce5e83562efec55e1b995941/numcodecs-0.16.5-cp313-cp313-win_amd64.whl", hash = "sha256:5088145502ad1ebf677ec47d00eb6f0fd600658217db3e0c070c321c85d6cf3d", size = 799275, upload-time = "2025-11-21T02:49:39.558Z" }, + { url = "https://files.pythonhosted.org/packages/3c/9e/38e7ca8184c958b51f45d56a4aeceb1134ecde2d8bd157efadc98502cc42/numcodecs-0.16.5-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:b05647b8b769e6bc8016e9fd4843c823ce5c9f2337c089fb5c9c4da05e5275de", size = 1654721, upload-time = "2025-11-21T02:49:40.602Z" }, + { url = "https://files.pythonhosted.org/packages/a1/37/260fa42e7b2b08e6e00ad632f8dd620961a60a459426c26cea390f8c68d0/numcodecs-0.16.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:3832bd1b5af8bb3e413076b7d93318c8e7d7b68935006b9fa36ca057d1725a8f", size = 1146887, upload-time = "2025-11-21T02:49:41.721Z" }, + { url = "https://files.pythonhosted.org/packages/4e/15/e2e1151b5a8b14a15dfd4bb4abccce7fff7580f39bc34092780088835f3a/numcodecs-0.16.5-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:49f7b7d24f103187f53135bed28bb9f0ed6b2e14c604664726487bb6d7c882e1", size = 8476987, upload-time = "2025-11-21T02:49:43.363Z" }, + { url = "https://files.pythonhosted.org/packages/6d/30/16a57fc4d9fb0ba06c600408bd6634f2f1753c54a7a351c99c5e09b51ee2/numcodecs-0.16.5-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:aec9736d81b70f337d89c4070ee3ffeff113f386fd789492fa152d26a15043e4", size = 9102377, upload-time = "2025-11-21T02:49:45.508Z" }, + { url = "https://files.pythonhosted.org/packages/31/a5/a0425af36c20d55a3ea884db4b4efca25a43bea9214ba69ca7932dd997b4/numcodecs-0.16.5-cp314-cp314-win_amd64.whl", hash = "sha256:b16a14303800e9fb88abc39463ab4706c037647ac17e49e297faa5f7d7dbbf1d", size = 819022, upload-time = "2025-11-21T02:49:47.39Z" }, +] + +[[package]] +name = "numpy" +version = "2.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/22/fd/89965aa4ac08c74998539fcbf24fa3540f3e15237fbeb6bcf9c908f4aade/numpy-2.5.1.tar.gz", hash = "sha256:a48a113e6afea91f5608793bafa7ef2ad481fefbda87ec5069f483de61cb9fa3", size = 20755553, upload-time = "2026-07-04T17:08:00.933Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/7b/14687aa674250e5e546f616f486b0d56d3631cd5b2415739141ce40bdcea/numpy-2.5.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2c889b56fe48b1018f764b0eec8df59ab654e9148aa91faa12596043500de277", size = 16801574, upload-time = "2026-07-04T17:06:12.423Z" }, + { url = "https://files.pythonhosted.org/packages/e1/19/cc5bb2a3f2913d27d6dbb2c78d25921fabaedc6741d4a5a615a11f3c5bf3/numpy-2.5.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ab451b59c5643c570974c43aef780703ef1d3b4965d2be07afd530615a9358d1", size = 11772250, upload-time = "2026-07-04T17:06:15.726Z" }, + { url = "https://files.pythonhosted.org/packages/42/77/fdf34a71dd30f54979b18603bee915e0aaf825b07afe79acd60b04b691e2/numpy-2.5.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:78798bd5b9ad744056af8efa90e3b9ddaa53272a0848a483084a1cc0a13b2dc0", size = 5331516, upload-time = "2026-07-04T17:06:17.913Z" }, + { url = "https://files.pythonhosted.org/packages/ce/e2/eb7efa015b4cce41e2517bf182a7fce0d7d5b9d9ed76a29bfa0f4fe4505c/numpy-2.5.1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:2ae0ca40bcb22d6ba59c1dfd5446f49940b0f2d821fde133f10dda11f816b84e", size = 6664863, upload-time = "2026-07-04T17:06:20.02Z" }, + { url = "https://files.pythonhosted.org/packages/a9/4b/a2b32dd94ee9ffbeecb28152240042a3949db33b1c834d44090b80e1b3b8/numpy-2.5.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:61ac47e772e6b8ea489e1d2f441a34c5c3ac17327e7ce294cbdf535795ad4e75", size = 15167977, upload-time = "2026-07-04T17:06:21.621Z" }, + { url = "https://files.pythonhosted.org/packages/b8/a9/6e73d68500f80773f65f0654ea932019d6694329a0eb0ed0533de38df376/numpy-2.5.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:59fda5e192b570217ec2580c96f00e9a7e12ef6866a900eb089b62c1a32545ca", size = 16672469, upload-time = "2026-07-04T17:06:24.064Z" }, + { url = "https://files.pythonhosted.org/packages/24/7d/ad3e59015135f5261c95fd4cafeff159c955febd83a99a1d9250c4233815/numpy-2.5.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f7119ebff1a9829e9f431a4f9d28e703023bb6b9fe7c8f724467dbfc27c94ab3", size = 16527531, upload-time = "2026-07-04T17:06:26.69Z" }, + { url = "https://files.pythonhosted.org/packages/83/d0/a39b2fbcde9cb17a1dac678f254b33a6336298af9df338824c685425d5e8/numpy-2.5.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e824c2acf8862052246be5a44c15da1777940c60d010dd2aab897824d9c430f9", size = 18431940, upload-time = "2026-07-04T17:06:29.521Z" }, + { url = "https://files.pythonhosted.org/packages/04/12/cff070947791c1ed425ff76413189adbdc2fbe215eba7ce7fa454a03c7f8/numpy-2.5.1-cp312-cp312-win32.whl", hash = "sha256:08d60c810432eb83360958dea0999ac4cfb94531ea8efcbf0b7f277c2068aeb2", size = 6066764, upload-time = "2026-07-04T17:06:32.571Z" }, + { url = "https://files.pythonhosted.org/packages/65/66/53f31807a48a750f9d748da273bc3fcedd12b27ff1f3e373bfec55ef2dc0/numpy-2.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:f7d60026c0bdb1380e83bfa7a0419c4577ee4b9a08880afcb6dadeb74c649fa2", size = 12430966, upload-time = "2026-07-04T17:06:34.926Z" }, + { url = "https://files.pythonhosted.org/packages/2b/2a/d1a88066b1c14186f5d3c0d18c94f17b064511982bab0578d49ee9d43c29/numpy-2.5.1-cp312-cp312-win_arm64.whl", hash = "sha256:17a25e09640602e10bc8de0e6fa2b3fd68eedd84ba6d7842dc8f32f9ab87bd0b", size = 10350488, upload-time = "2026-07-04T17:06:37.785Z" }, + { url = "https://files.pythonhosted.org/packages/eb/07/ec2a3f0c91761581d4b7104a740791800025983f9a4dc4e73f91a99aeac4/numpy-2.5.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0bfebd8695f9863592fe744be833a258120b14a9f39da255e8aa8fade2c0ddd1", size = 16796419, upload-time = "2026-07-04T17:06:40.37Z" }, + { url = "https://files.pythonhosted.org/packages/ab/ab/ddb499fc4f8780354395face5b65c7fd107bcd6e1d667a5f07d046956f6f/numpy-2.5.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:30b44a6b53a7ae63c54c089a8726e5563ed302716c5b7ccc85afade40b0e7ff6", size = 11765832, upload-time = "2026-07-04T17:06:42.768Z" }, + { url = "https://files.pythonhosted.org/packages/88/b3/3c28c558a09fc72100c646dac6d2fce8e834c471b0edca01a29996706117/numpy-2.5.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:6165343f81b56ef8f514f396989e529b61d9dc709b99421b07e9f3e698e2287d", size = 5325143, upload-time = "2026-07-04T17:06:45.466Z" }, + { url = "https://files.pythonhosted.org/packages/5e/0e/ce19b985bb15c596f4f05954e76cccc77c845083b3b8f938a6c68e523128/numpy-2.5.1-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:4939237038ada79308dda3204ac6462df056b5672b2e25db1149cf873668b3e1", size = 6659749, upload-time = "2026-07-04T17:06:47.288Z" }, + { url = "https://files.pythonhosted.org/packages/2e/20/1ee6614d64332a1bba6411f38e68cb79eec1b2459e20a623777c5c5492a2/numpy-2.5.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1c6759f538fb912fc46de0a6b1758ccf7b57bc7c7ebebc23974fdac3de8db0cd", size = 15164716, upload-time = "2026-07-04T17:06:49.494Z" }, + { url = "https://files.pythonhosted.org/packages/ed/a7/2bcd3fdbb87804755c35b729bf8709d62025c5f4cfd7d5b2415997097515/numpy-2.5.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9726558e8db4a5bf7929a70ae50f63abda4daf0efe810e3bfbab95976f75fc1a", size = 16661440, upload-time = "2026-07-04T17:06:52.061Z" }, + { url = "https://files.pythonhosted.org/packages/fc/d7/a41e3310c886fe457d36e670bbf24fae411aca8a7b6ad92a32afd924077c/numpy-2.5.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3935f3b419b244a02732676fa5317a9193cc596a4c0646db07e5b421229ac9f7", size = 16526305, upload-time = "2026-07-04T17:06:54.605Z" }, + { url = "https://files.pythonhosted.org/packages/53/75/4333a9a707c1edd3a4e1a0c58eca52c0f31e55089fa80db02b5565b24df7/numpy-2.5.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:dc932a65ded7ce9013d120845a2514dcccb1a67bfc8deb8d37633762951904a6", size = 18423008, upload-time = "2026-07-04T17:06:57.54Z" }, + { url = "https://files.pythonhosted.org/packages/ee/90/e314a32b1c11a2ffe818ddad3a57b50b4b6e1b6c487192eb50cdef0415d0/numpy-2.5.1-cp313-cp313-win32.whl", hash = "sha256:4b4ff1608417eb7a59da7b967bbb798cacfe071d2caf526a24281cd562072ed9", size = 6063885, upload-time = "2026-07-04T17:07:00.14Z" }, + { url = "https://files.pythonhosted.org/packages/10/70/800b3fca480af32df9e8ea9f3d4a0c8feb4b32d7f195d174eabbda4829ad/numpy-2.5.1-cp313-cp313-win_amd64.whl", hash = "sha256:6c3fe51bc6a16453d452997053454f309e8e0ed7b42d6b361ce4ac8c32913d74", size = 12425674, upload-time = "2026-07-04T17:07:02.387Z" }, + { url = "https://files.pythonhosted.org/packages/8b/0b/196350c122f50f6ca56846f2d71efd5e0d24b7b2e07355e019b2e2c7a11e/numpy-2.5.1-cp313-cp313-win_arm64.whl", hash = "sha256:f7feb014281029e628ba2d5a007407443b06e418b6fe451d1e2adcbc8eba0107", size = 10350256, upload-time = "2026-07-04T17:07:04.878Z" }, + { url = "https://files.pythonhosted.org/packages/db/f4/731b6085a83faf6ca843394cbd5e217280c214399f7e8b21b9f552af0ae2/numpy-2.5.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:7c786fe9a5bbe360022e584c5a34cf6b54265c71bd7ec8ac3d8fec38968071f8", size = 16795063, upload-time = "2026-07-04T17:07:07.374Z" }, + { url = "https://files.pythonhosted.org/packages/bf/64/0e215f2048dd11a55bb989ed41b3585ef57452404e638d703a211a3e4157/numpy-2.5.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:32985c896d897419ef8da6917872d80b78ad0ea26d85b23245c7366ffde76d75", size = 11776652, upload-time = "2026-07-04T17:07:09.907Z" }, + { url = "https://files.pythonhosted.org/packages/b5/59/2b844c7a6e9deff69b404a66221e1542937734f65d5e6e39411876053862/numpy-2.5.1-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:efd736408cc97c79b9e6917338dfc8f06013b2274f992e96b1d9a81a71e2a2c2", size = 5335944, upload-time = "2026-07-04T17:07:12.227Z" }, + { url = "https://files.pythonhosted.org/packages/86/51/9bf7cb2cabcebc9e017e4ec7e6322b378317a542c08b4cb68479c1efc716/numpy-2.5.1-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:ab84dc6b074fa881cae55bea94cc4f68e285181ba7f32497bf7dee6b1496165b", size = 6656266, upload-time = "2026-07-04T17:07:14.368Z" }, + { url = "https://files.pythonhosted.org/packages/83/3e/fb7615b211b82a32f44d5180a6d421b61f84d4fadd578b48ba4ac34e189f/numpy-2.5.1-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:caf3e317d33d60c37986b452613f4ab51246d0691350c03d0cb4a898627f4a95", size = 15179720, upload-time = "2026-07-04T17:07:16.272Z" }, + { url = "https://files.pythonhosted.org/packages/41/5f/0f992cb24560673496c5d68de61913b57166ce530ffda07c1f280e0cc464/numpy-2.5.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:54ad769f17bc2d833b620851989f62054fb9ab93c969d9e1dc3c8e3d56beea21", size = 16664835, upload-time = "2026-07-04T17:07:19.021Z" }, + { url = "https://files.pythonhosted.org/packages/a2/2f/97d6475ee91afe2587797d09446f9d3e475ad4cb681662d824809327b75a/numpy-2.5.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c12afb53450fa976d4c681c50a7423729a4c51c0465ed9f32b8a9cabbc472373", size = 16539135, upload-time = "2026-07-04T17:07:22.015Z" }, + { url = "https://files.pythonhosted.org/packages/c4/5b/4db81e4ba0be7e2776b1de68c82aa862c7f8ec27e1b4927d4ae075e20678/numpy-2.5.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:e8c11c405efc5ff6816d5983c96cdfa215bab3428961243af3ff59b228490438", size = 18426684, upload-time = "2026-07-04T17:07:24.941Z" }, + { url = "https://files.pythonhosted.org/packages/1f/64/c0ba2d90724d450279a7df8f32057241070250a26a7e2b5337d77347f481/numpy-2.5.1-cp314-cp314-win32.whl", hash = "sha256:f2479a47f8d5932d1718168a681ad6e536a9df484c83cfcf9de365e164537ace", size = 6116103, upload-time = "2026-07-04T17:07:27.622Z" }, + { url = "https://files.pythonhosted.org/packages/c1/1a/837f9ed7405adcd7a40538792eb169eddd8fa5630c16a1ef49dae71a30f4/numpy-2.5.1-cp314-cp314-win_amd64.whl", hash = "sha256:24d0eb82c0541d3415a33425db64ae439dffccd7b4dbcb30e7c35120205c506a", size = 12562177, upload-time = "2026-07-04T17:07:29.887Z" }, + { url = "https://files.pythonhosted.org/packages/22/ed/49707938b6dd0a78a9178dd93227dc89e4c11af47f5c798d70366e8d0483/numpy-2.5.1-cp314-cp314-win_arm64.whl", hash = "sha256:5a4c988b38d261deeeaad9954e3deb091ad905c94e8bb6708654ef1d97f286b0", size = 10627739, upload-time = "2026-07-04T17:07:32.568Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c7/bb4b882cfe7f299cbc8b66e42e7dd78cf9d14e40f9469fc5e3db7e15b3bd/numpy-2.5.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a33276be12fa045805f477f22482088b66bb758ffbe89a9d21457de863a32e22", size = 11894709, upload-time = "2026-07-04T17:07:34.941Z" }, + { url = "https://files.pythonhosted.org/packages/40/3f/5af7f4a7f6224aef48017aa82bb6174c7a659d724be0c75017b7e64a55b4/numpy-2.5.1-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:f089d7b00756190aacf1f5d34bdf38c3c430ac82b4f868f8cede73380460fce7", size = 5453810, upload-time = "2026-07-04T17:07:37.495Z" }, + { url = "https://files.pythonhosted.org/packages/20/c9/3474309bc94d634d3f9c3eddf03250ecb8c22cd948ef16fef69a77cc5d7b/numpy-2.5.1-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:09e9bfd8d2cf479c7d174804fb3811c53a8e9f20a37444008606b57d6b7a826d", size = 6761189, upload-time = "2026-07-04T17:07:39.563Z" }, + { url = "https://files.pythonhosted.org/packages/90/8a/558ae39fdd55d7e7f7fef9a84a6e964ac6b23edbd2a07e52bb084500507d/numpy-2.5.1-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e68d8dd1e7eba712948f2053a29ec86917bc70ba1358df869d9f06649ef9cf09", size = 15225039, upload-time = "2026-07-04T17:07:41.682Z" }, + { url = "https://files.pythonhosted.org/packages/63/27/ca7392b2d030277bdf0273e7d23255b3ee57d57a7c170a6f4fb3981e1e5d/numpy-2.5.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:99d5095fa265a0c4152e7bb12759e14381ef5496152f1ce58f44bdf55c44beb4", size = 16701306, upload-time = "2026-07-04T17:07:44.611Z" }, + { url = "https://files.pythonhosted.org/packages/02/42/03d53ae7996c44d4374a8262e9dc41671fd56cbb98f7d47ef85cf5da4c6b/numpy-2.5.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ab87a91b3cc3382b8956095bd8f95e00cf679bb81554339be1a2ba404a1473c1", size = 16589955, upload-time = "2026-07-04T17:07:47.694Z" }, + { url = "https://files.pythonhosted.org/packages/7b/15/6c1784ae469640e65db111e9a34b3d0f14d91e8a38b9ce34810ced370dbb/numpy-2.5.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:224ca51130ef7da85bea2191625181cb4f337f9cb64b471f10c1a12aa8b60077", size = 18464252, upload-time = "2026-07-04T17:07:50.684Z" }, + { url = "https://files.pythonhosted.org/packages/94/a8/f98e50356cf167df656c526c2dfeec2d7dde182f2a3da4b458a5938e2776/numpy-2.5.1-cp314-cp314t-win32.whl", hash = "sha256:6eab239876581b2b3c5a242281b6007bbdbcd1c7085d7709bb57c5929b11e6bf", size = 6263298, upload-time = "2026-07-04T17:07:53.445Z" }, + { url = "https://files.pythonhosted.org/packages/72/ac/96ae880cdecad0b3275d9359fcec72667b49a4863c9f12942e43679dda02/numpy-2.5.1-cp314-cp314t-win_amd64.whl", hash = "sha256:83ce9c80d5b521b0d77ddcbe5447c218d247929b6cc056ca5351342accfff0af", size = 12748623, upload-time = "2026-07-04T17:07:55.384Z" }, + { url = "https://files.pythonhosted.org/packages/a1/5a/4d2b1601df3602dba7a14f3348ba9bfe94a18adb428e693df6154c293831/numpy-2.5.1-cp314-cp314t-win_arm64.whl", hash = "sha256:5a6db61f9aaa57e369905c67d852045d3c4f7126405b29d09b19dec118e9c9cb", size = 10697674, upload-time = "2026-07-04T17:07:58.506Z" }, +] + +[[package]] +name = "packaging" +version = "26.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d7/f1/e7a6dd94a8d4a5626c03e4e99c87f241ba9e350cd9e6d75123f992427270/packaging-26.2.tar.gz", hash = "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661", size = 228134, upload-time = "2026-04-24T20:15:23.917Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" }, +] + +[[package]] +name = "paginate" +version = "0.5.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/46/68dde5b6bc00c1296ec6466ab27dddede6aec9af1b99090e1107091b3b84/paginate-0.5.7.tar.gz", hash = "sha256:22bd083ab41e1a8b4f3690544afb2c60c25e5c9a63a30fa2f483f6c60c8e5945", size = 19252, upload-time = "2024-08-25T14:17:24.139Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/90/96/04b8e52da071d28f5e21a805b19cb9390aa17a47462ac87f5e2696b9566d/paginate-0.5.7-py2.py3-none-any.whl", hash = "sha256:b885e2af73abcf01d9559fd5216b57ef722f8c42affbb63942377668e35c7591", size = 13746, upload-time = "2024-08-25T14:17:22.55Z" }, +] + +[[package]] +name = "parso" +version = "0.8.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/30/4b/90c937815137d43ce71ba043cd3566221e9df6b9c805f24b5d138c9d40a7/parso-0.8.7.tar.gz", hash = "sha256:eaaac4c9fdd5e9e8852dc778d2d7405897ec510f2a298071453e5e3a07914bb1", size = 401824, upload-time = "2026-05-01T23:13:02.138Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/5d/8268b644392ee874ee82a635cd0df1773de230bde356c38de28e298392cc/parso-0.8.7-py2.py3-none-any.whl", hash = "sha256:a8926eb2a1b915486941fdbd31e86a4baf88fe8c210f25f2f35ecec5b574ca1c", size = 107025, upload-time = "2026-05-01T23:12:58.867Z" }, +] + +[[package]] +name = "pathspec" +version = "1.1.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5a/82/42f767fc1c1143d6fd36efb827202a2d997a375e160a71eb2888a925aac1/pathspec-1.1.1.tar.gz", hash = "sha256:17db5ecd524104a120e173814c90367a96a98d07c45b2e10c2f3919fff91bf5a", size = 135180, upload-time = "2026-04-27T01:46:08.907Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" }, +] + +[[package]] +name = "pexpect" +version = "4.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "ptyprocess" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772, upload-time = "2023-11-25T06:56:14.81Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.11.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e5/98/0bf930c4f97d0266b58a89e36c015f56232c52b5d2f207215d48cca9e8f7/platformdirs-4.11.2.tar.gz", hash = "sha256:3a2ae5fca3520a01ab1be8b45613537f52ddf5b5f6f53d88233892dfbf0cd82d", size = 32716, upload-time = "2026-08-10T15:48:06.092Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/e2/4e6eee633809c376c024821b91ade709cbfd040ec53939ffbcc292aa7eee/platformdirs-4.11.2-py3-none-any.whl", hash = "sha256:7f89089b6ea71bda7962953edcf784b2e2d9d285b40ad88be2bb75c6e9d82ab4", size = 23361, upload-time = "2026-08-10T15:48:04.855Z" }, +] + +[[package]] +name = "pluggy" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, +] + +[[package]] +name = "prompt-toolkit" +version = "3.0.53" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "wcwidth" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7d/ea/39b988c938f75cb75d7045b5c69f8bfed47ee2152c8837fb403de29d6fb8/prompt_toolkit-3.0.53.tar.gz", hash = "sha256:9ec8a0ad96d5c56148b3f914aa79c1564c3fde5d2e6b876e7bc327e353cf8fa6", size = 435492, upload-time = "2026-07-26T20:56:14.758Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/6f/84908cad2d6aa5144abcf7b42709fe4fdb459bc640ec7ac5786e7693dabc/prompt_toolkit-3.0.53-py3-none-any.whl", hash = "sha256:01c0891d7f9237d5e339f7d3e42cdae80b7534abb1c7c0e3352efba6231492f2", size = 392288, upload-time = "2026-07-26T20:56:12.512Z" }, +] + +[[package]] +name = "propcache" +version = "0.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/44/c87281c333769159c50594f22610f77398a47ccbfbbf23074e744e86f87c/propcache-0.5.2.tar.gz", hash = "sha256:01c4fc7480cd0598bb4b57022df55b9ca296da7fc5a8760bd8451a7e63a7d427", size = 50208, upload-time = "2026-05-08T21:02:12.199Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4a/cb/e27bc2b2737a0bb49962b275efa051e8f1c35a936df7d5139b6b658b7dc9/propcache-0.5.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:806719138ecd720339a12410fb9614ac9b2b2d3a5fdf8235d56981c36f4039ba", size = 95887, upload-time = "2026-05-08T21:00:11.277Z" }, + { url = "https://files.pythonhosted.org/packages/e6/13/b8ae04c59392f8d11c6cd9fb4011d1dc7c86b81225c770280300e259ffe1/propcache-0.5.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:db2b80ea58eab4f86b2beec3cc8b39e8ff9276ac20e96b7cce43c8ae84cd6b5a", size = 54654, upload-time = "2026-05-08T21:00:12.604Z" }, + { url = "https://files.pythonhosted.org/packages/2c/7d/49777a3e20b55863d4794384a38acd460c04157b0a00f8602b0d508b8431/propcache-0.5.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:e5cbfac9f61484f7e9f3597775500cd3ebe8274e9b050c38f9525c77c97520bf", size = 55190, upload-time = "2026-05-08T21:00:13.935Z" }, + { url = "https://files.pythonhosted.org/packages/44/c7/085d0cd63062e84044e3f05797749c3f8e3938ff3aeb0eb2f69d43fafc91/propcache-0.5.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5dbc581d2814337da56222fab8dc5f161cd798a434e49bac27930aaef798e144", size = 59995, upload-time = "2026-05-08T21:00:15.526Z" }, + { url = "https://files.pythonhosted.org/packages/9c/42/32cf8e3009e92b2645cf1e944f701e8ea4e924dffde1ee26db860bcbf7e4/propcache-0.5.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:857187f381f88c8e2fa2fe56ab94879d011b883d5a2ee5a1b60a8cd2a06846d9", size = 63422, upload-time = "2026-05-08T21:00:16.824Z" }, + { url = "https://files.pythonhosted.org/packages/9e/1b/f112433f99fc979431b87a39ef169e3f8df070d99a72792c56d6937ac48b/propcache-0.5.2-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:178b4a2cdaac1818e2bf1c5a99b94383fa73ea5382e032a48dec07dc5668dc42", size = 64342, upload-time = "2026-05-08T21:00:18.362Z" }, + { url = "https://files.pythonhosted.org/packages/14/15/5574111ae50dd6e879456888c0eadd4c5a869959775854e18e18a6b345f3/propcache-0.5.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f328175a2cde1f0ff2c4ed8ce968b9dcfb55f3a7153f39e2957ed994da13476", size = 61639, upload-time = "2026-05-08T21:00:19.692Z" }, + { url = "https://files.pythonhosted.org/packages/cc/da/4d775080b1490c0ae604acda868bd71aabe3a89ed16f2aa4339eb8a283e7/propcache-0.5.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5671d09a36b06d0fd4a3da0fccbcae360e9b1570924171a15e9e0997f0249fba", size = 61588, upload-time = "2026-05-08T21:00:21.155Z" }, + { url = "https://files.pythonhosted.org/packages/04/ac/f076982cbe2195ee9cf32de5a1e46951d9fb399fc207f390562dd0fd8fb2/propcache-0.5.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:80168e2ebe4d3ec6599d10ad8f520304ae1cad9b6c5a95372aef1b66b7bfb53a", size = 60029, upload-time = "2026-05-08T21:00:22.713Z" }, + { url = "https://files.pythonhosted.org/packages/70/60/189be62e0dd898dce3b331e1b8c7a543cd3a405ac0c81fe8ee8a9d5d77e1/propcache-0.5.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:45f11346f884bc47444f6e6647131055844134c3175b629f84952e2b5cd62b64", size = 56774, upload-time = "2026-05-08T21:00:24.001Z" }, + { url = "https://files.pythonhosted.org/packages/ea/9e/93377b9c7939c1ffae98f878dee955efadfd638078bc86dbc21f9d52f651/propcache-0.5.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:8e778ebd44ef4f66ed60a0416b06b489687db264a9c0b3620362f26489492913", size = 63532, upload-time = "2026-05-08T21:00:25.545Z" }, + { url = "https://files.pythonhosted.org/packages/14/f9/590ef6cfb9b8028d516d287812ece32bb0bc5f11fbb9c8bf6b2e6313fec8/propcache-0.5.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:c0cb9ed24c8964e172768d455a38254c2dd8a552905729ce006cad3d3dda59b1", size = 61592, upload-time = "2026-05-08T21:00:27.186Z" }, + { url = "https://files.pythonhosted.org/packages/b4/5e/70958b3034c297a630bba2f17ca7abc2d5f39a803ad7e370ab79d1ecd022/propcache-0.5.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:1d1ad32d9d4355e2be65574fd0bfd3677e7066b009cd5b9b2dee8aa6a6393b33", size = 64788, upload-time = "2026-05-08T21:00:28.8Z" }, + { url = "https://files.pythonhosted.org/packages/12/fd/77fe5936d8c3086ca9048f7f415f122ed82e53884a9ec193646b42deef06/propcache-0.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c80f4ba3e8f00189165999a742ee526ebeccedf6c3f7beb0c7df821e9772435a", size = 62514, upload-time = "2026-05-08T21:00:30.098Z" }, + { url = "https://files.pythonhosted.org/packages/cf/74/66bd798b5b3be70aa1b391f5cc9d6a0a5532d7fd3b19ec0b213e72e6ad9d/propcache-0.5.2-cp312-cp312-win32.whl", hash = "sha256:8c7972d8f193740d9175f0998ab38717e6cd322d5935c5b0fef8c0d323fd9031", size = 39018, upload-time = "2026-05-08T21:00:31.622Z" }, + { url = "https://files.pythonhosted.org/packages/61/7c/5c0d34aa3024694d6dcb9271cdbdd08c4e47c1c0ad95ec7e7bc74cdea145/propcache-0.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:d9ee8826a7d47863a08ac44e1a5f611a462eefc3a194b492da242128bec75b42", size = 42322, upload-time = "2026-05-08T21:00:32.918Z" }, + { url = "https://files.pythonhosted.org/packages/4d/91/875812f1a3feb20ceba818ef39fbe4d92f1081e04ac815c822496d0d038b/propcache-0.5.2-cp312-cp312-win_arm64.whl", hash = "sha256:2800a4a8ead6b28cccd1ec54b59346f0def7922ee1c7598e8499c733cfbb7c84", size = 38172, upload-time = "2026-05-08T21:00:35.124Z" }, + { url = "https://files.pythonhosted.org/packages/c5/09/f049e45385503fe67db75a6b6186a7b9f0c3930366dc960522c312a825b1/propcache-0.5.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:099aaf4b4d1a02265b92a977edf00b5c4f63b3b17ac6de39b0d637c9cac0188a", size = 94457, upload-time = "2026-05-08T21:00:36.355Z" }, + { url = "https://files.pythonhosted.org/packages/6b/65/83d1d05655baf63113731bd5a1008435e14f8d1e5a06cbe4ec5b23ad7a31/propcache-0.5.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:68ce1c44c7a813a7f71ea04315a8c7b330b63db99d059a797a4651bb6f69f117", size = 53835, upload-time = "2026-05-08T21:00:38.072Z" }, + { url = "https://files.pythonhosted.org/packages/a9/12/a6ba6482bb5ea3260c000c9b20881c95fa11c6b30173715668259f844ed7/propcache-0.5.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:fc299c129490f55f254cd90be0deca4764e36e9a7c08b4aa588479a3bbed3098", size = 54545, upload-time = "2026-05-08T21:00:39.319Z" }, + { url = "https://files.pythonhosted.org/packages/a9/19/7fa086f5764c59ec8a8e157cd93aa8497acc00aba9dcdec56bfffb32602d/propcache-0.5.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a6ae2198be502c10f09b2516e7b5d019816924bc3183a43ce792a7bd6625e6f4", size = 59886, upload-time = "2026-05-08T21:00:40.621Z" }, + { url = "https://files.pythonhosted.org/packages/a1/e4/5d7663dc8235956c8f5281698a3af1d351d8820341ddd890f59d9a9127f2/propcache-0.5.2-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6041d31504dc1779d700e1edcfb08eea334b357620b06681a4eabb57a74e574e", size = 63261, upload-time = "2026-05-08T21:00:41.775Z" }, + { url = "https://files.pythonhosted.org/packages/4a/4a/15a03adee24d6350da4292caeac44c34c033d2afe5e87eb370f38854560f/propcache-0.5.2-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f7eabc04151c78a9f4d5bbb5f1faf571e4defeb4b585e0fe95b60ff2dbe4d3d7", size = 64184, upload-time = "2026-05-08T21:00:43.018Z" }, + { url = "https://files.pythonhosted.org/packages/8b/c6/979176efdaa3d239e36d503d5af63a0a773b36662ed8f52e5b6a6d9fd40e/propcache-0.5.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4db0ba63d693afd40d249bd93f842b5f144f8fcbb83de05660373bcf30517b1d", size = 61534, upload-time = "2026-05-08T21:00:44.507Z" }, + { url = "https://files.pythonhosted.org/packages/c8/22/63e8cd1bae4c2d2be6493b6b7d10566ddafad88137cfbc99964a1119853c/propcache-0.5.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:1dbcf7675229b35d31abb6547d8ebc8c27a830ac3f9a794edff6254873ec7c0a", size = 61500, upload-time = "2026-05-08T21:00:45.796Z" }, + { url = "https://files.pythonhosted.org/packages/60/5a/28e5d9acbac1cc9ccb67045e8c1b943aa8d79fdf39c93bd73cacd68008ea/propcache-0.5.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d310c013aad2c72f1c3f2f8dd3279d460a858c551f97aeb8c63e4693cca7b4d2", size = 59994, upload-time = "2026-05-08T21:00:47.093Z" }, + { url = "https://files.pythonhosted.org/packages/f3/40/db650677f554a95b9c01a7c9d93d629e93a15562f5deb4573c9ee136fed2/propcache-0.5.2-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:06187263ddad280d05b4d8a8b3bb7d164cbebd469236544a42e6d9b28ac6a4fa", size = 56884, upload-time = "2026-05-08T21:00:48.376Z" }, + { url = "https://files.pythonhosted.org/packages/80/45/70b39b89516ff8b96bf732fa6fded8cef20f293cb1508690101c3c07ec51/propcache-0.5.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:3115559b8effafd63b142ea5ed53d63a16ea6469cbc63dce4ee194b42db5d853", size = 63464, upload-time = "2026-05-08T21:00:49.954Z" }, + { url = "https://files.pythonhosted.org/packages/f9/e2/fa59d3a89eac5534293124af4f1d0d0ada091ce4a0ab4610ce03fd2bdd8d/propcache-0.5.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:c60462af8e6dc30c35407c7237ea908d777b22862bbee27bc4699c0d8bcdc45a", size = 61588, upload-time = "2026-05-08T21:00:51.281Z" }, + { url = "https://files.pythonhosted.org/packages/0b/97/efb547a55c4bc7381cfb202d6a2239ac621045277bc1ea5dfd3a7f0516c0/propcache-0.5.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:40314bca9ac559716fe374094fc81c11dcc34b64fd6c585360f5775690505704", size = 64667, upload-time = "2026-05-08T21:00:52.602Z" }, + { url = "https://files.pythonhosted.org/packages/92/56/f5c7d9b4b7595d5127da38974d791b2153f3d1eae6c674af3583ace92ad3/propcache-0.5.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:cfa21e036ce1e1db2be04ba3b85d2df1bb1702fa01932d984c5464c665228ff4", size = 62463, upload-time = "2026-05-08T21:00:54.303Z" }, + { url = "https://files.pythonhosted.org/packages/bd/3b/484a3a65fc9f9f60c41dcd17b428bace5389544e2c680994534a20755066/propcache-0.5.2-cp313-cp313-win32.whl", hash = "sha256:f156a3529f38063b6dbaf356e15602a7f95f8055b1295a438433a6386f10463d", size = 38621, upload-time = "2026-05-08T21:00:55.808Z" }, + { url = "https://files.pythonhosted.org/packages/1c/fd/3f0f10dba4dabad3bf53102be007abf55481067952bde0fdddff439e7c61/propcache-0.5.2-cp313-cp313-win_amd64.whl", hash = "sha256:dfed59d0a5aeb01e242e66ff0300bc4a265a7c05f612d30016f0b60b1017d757", size = 41649, upload-time = "2026-05-08T21:00:57.061Z" }, + { url = "https://files.pythonhosted.org/packages/90/ec/6ce619cc32bb500a482f811f9cd509368b4e58e638d13f2c68f370d6b475/propcache-0.5.2-cp313-cp313-win_arm64.whl", hash = "sha256:ba338430e87ceb9c8f0cf754de38a9860560261e56c00376debd628698a7364f", size = 37636, upload-time = "2026-05-08T21:00:58.646Z" }, + { url = "https://files.pythonhosted.org/packages/1b/82/c1d268bbbf2ef981c5bf0fbbe746db617c66e3bcefe431a1aa8943fbe23a/propcache-0.5.2-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:a592f5f3da71c8691c788c13cb6734b6d17663d2e1cb8caddf0673d01ef8847d", size = 98872, upload-time = "2026-05-08T21:00:59.889Z" }, + { url = "https://files.pythonhosted.org/packages/f4/d4/52c871e73e864e6b34c0e2d58ac1ec5ccd149497ddc7ad2137ae98323a35/propcache-0.5.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:6a997d0489e9668a384fcfd5061b857aa5361de73191cac204d04b889cfbbafa", size = 56257, upload-time = "2026-05-08T21:01:01.195Z" }, + { url = "https://files.pythonhosted.org/packages/67/f0/9b90ca2a210b3d09bcfcd96ecd0f55545c091535abce2a45de2775cfd357/propcache-0.5.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:10734b5484ea113152ee25a91dccedf81631791805d2c9ccb054958e51842c94", size = 56696, upload-time = "2026-05-08T21:01:02.941Z" }, + { url = "https://files.pythonhosted.org/packages/9d/0e/6e9d4ba07c8e56e21ddec1e75f12148142b21ca83a51871babce095334f4/propcache-0.5.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cafca7e56c12bb02ae16d283742bef25a61122e9dab2b5b3f2ccbe589ce32164", size = 62378, upload-time = "2026-05-08T21:01:04.475Z" }, + { url = "https://files.pythonhosted.org/packages/65/19/c10badaa463dde8a27ce884f8ee2ec37e6035b7c9f5ff0c8f74f06f08dac/propcache-0.5.2-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f064f8d2b59177878b7615df1735cd8fe3462ed6be8c7b217d17a276489c2b7f", size = 65283, upload-time = "2026-05-08T21:01:05.959Z" }, + { url = "https://files.pythonhosted.org/packages/b0/b6/93bea99ca80e19cef6512a8580e5b7857bbe09422d9daa7fd4ef5723306c/propcache-0.5.2-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f78abfa8dfc32376fd1aacf597b2f2fbbe0ea751419aee718af5d4f82537ef8c", size = 66616, upload-time = "2026-05-08T21:01:07.228Z" }, + { url = "https://files.pythonhosted.org/packages/83/e4/5c7462e50625f051f37fb38b8224f7639f667184bbd34424ec83819bb1b7/propcache-0.5.2-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f7467da8a9822bf1a55336f877340c5bcbd3c482afc43a99771169f74a26dedc", size = 63773, upload-time = "2026-05-08T21:01:08.514Z" }, + { url = "https://files.pythonhosted.org/packages/ca/b6/99238894047b13c823be25027e736626cd414a52a5e30d2c3347c2733529/propcache-0.5.2-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a6ddc6ac9e25de626c1f129c1b467d7ecd33ce2237d3fd0c4e429feef0a7ee1f", size = 63664, upload-time = "2026-05-08T21:01:09.874Z" }, + { url = "https://files.pythonhosted.org/packages/85/1e/a3a1a63116a2b8edb415a8bb9a6f0c34bd03830b1e18e8ce2904e1dc1cf4/propcache-0.5.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:2f22cbbac9e26a8e864c0985ff1268d5d939d53d9d9411a9824279097e03a2cb", size = 62643, upload-time = "2026-05-08T21:01:11.132Z" }, + { url = "https://files.pythonhosted.org/packages/e4/03/893cf147de2fc6543c5eaa07ad833170e7e2a2385725bbebe8c0503723bb/propcache-0.5.2-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:fc76378c62a0f04d0cd82fbb1a2cd2d7e28fcb40d5873f28a6c44e388aaa2751", size = 59595, upload-time = "2026-05-08T21:01:12.387Z" }, + { url = "https://files.pythonhosted.org/packages/86/3b/04c1a2e12c57766568ba75ba72b3bf2042818d4c1425fab6fc07155c7cff/propcache-0.5.2-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:acd2c8edba48e31e58a363b8cf4e5c7db3b04b3f9e371f601df30d9b0d244836", size = 65711, upload-time = "2026-05-08T21:01:13.676Z" }, + { url = "https://files.pythonhosted.org/packages/1c/34/80f8d0099f8d6bacc4de1624c85672681c8cd1149ca2da0e38fd120b817f/propcache-0.5.2-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:452b5065457eb9991ec5eb38ff41d6cd4c991c9ac7c531c4d5849ae473a9a13f", size = 64247, upload-time = "2026-05-08T21:01:14.936Z" }, + { url = "https://files.pythonhosted.org/packages/f3/1a/8b08f3a5f1037e9e370c55883ceeeee0f6dd0416fb2d2d67b8bfc91f2a79/propcache-0.5.2-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:3430bb2bfe1331885c427745a751e774ee679fd4344f80b97bf879815fe8fa55", size = 67102, upload-time = "2026-05-08T21:01:16.281Z" }, + { url = "https://files.pythonhosted.org/packages/34/68/8bdb7bb7756d76e005490649d10e4a8369e610c74d619f71e1aedf889e9c/propcache-0.5.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:cef6cea3922890dd6c9654971001fa797b526c16ab5e1e46c05fd6f877be7568", size = 64964, upload-time = "2026-05-08T21:01:17.57Z" }, + { url = "https://files.pythonhosted.org/packages/0a/aa/50fb0b5d3968b61a510926ff8b8465f1d6e976b3ab74496d7a4b9fc42515/propcache-0.5.2-cp313-cp313t-win32.whl", hash = "sha256:72d61e16dd78228b58c5d47be830ff3da7e5f139abdf0aef9d86cde1c5cf2191", size = 42546, upload-time = "2026-05-08T21:01:18.946Z" }, + { url = "https://files.pythonhosted.org/packages/ae/4c/0ddbae64321bd4a95bcbfc19307238016b5b1fee645c84626c8d539e5b74/propcache-0.5.2-cp313-cp313t-win_amd64.whl", hash = "sha256:0958834041a0166d343b8d2cedcd8bcbaeb4fdbe0cf08320c5379f143c3be6e7", size = 46330, upload-time = "2026-05-08T21:01:20.162Z" }, + { url = "https://files.pythonhosted.org/packages/00/d9/9cddc8efb78d8af264c5ec9f6d10b62f57c515feda8d321595f56010fb23/propcache-0.5.2-cp313-cp313t-win_arm64.whl", hash = "sha256:6de8bd93ddde9b992cf2b2e0d796d501a19026b5b9fd87356d7d0779531a8d96", size = 40521, upload-time = "2026-05-08T21:01:21.399Z" }, + { url = "https://files.pythonhosted.org/packages/e2/ea/23ee535d90ce8bcc465a3028eb3cc0ce3bd1005f4bb27710b30587de798d/propcache-0.5.2-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:46088abff4cba581dea21ae0467a480526cb25aa5f3c269e909f800328bc3999", size = 94662, upload-time = "2026-05-08T21:01:22.683Z" }, + { url = "https://files.pythonhosted.org/packages/b5/06/c5a52f419b5d8972f8d46a7577476090d8e3263ff589ce40b5ca4968d5be/propcache-0.5.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:fc88b26f08d634f7bc819a7852e5214f5802641ab8d9fd5326892292eee1993e", size = 53928, upload-time = "2026-05-08T21:01:23.986Z" }, + { url = "https://files.pythonhosted.org/packages/63/b1/4260d67d6bd85e58a66b72d54ce15d5de789b6f3870cc6bedf8ff9667401/propcache-0.5.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:97797ebb098e670a2f92dd66f32897e30d7615b14e7f59711de23e30a9072539", size = 54650, upload-time = "2026-05-08T21:01:25.305Z" }, + { url = "https://files.pythonhosted.org/packages/70/06/2f46c318e3307cd7a6a7481def374ce838c0fe20084b39dd54b0879d0e99/propcache-0.5.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ba57fffe4ac99c5d30076161b5866336d97600769bad35cc68f7774b15298a4e", size = 59912, upload-time = "2026-05-08T21:01:26.545Z" }, + { url = "https://files.pythonhosted.org/packages/4c/29/fe1aebec2ce57ab985a9c382bded1124431f85078113aa222c5d278430d4/propcache-0.5.2-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:583c19759d9eec1e5b69e2fbef36a7d9c326041be9746cb822d335c8cedc2979", size = 63300, upload-time = "2026-05-08T21:01:27.937Z" }, + { url = "https://files.pythonhosted.org/packages/b4/18/2334b26768b6c82be8c69e83671b767d5ef426aa09b0cba6c2ea47816774/propcache-0.5.2-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d0326e2e5e1f3163fa306c834e48e8d490e5fae607a097a40c0648109b47ba80", size = 64208, upload-time = "2026-05-08T21:01:29.484Z" }, + { url = "https://files.pythonhosted.org/packages/2b/76/7f1bfd6afff4c5e38e36a3c6d68eb5f4b7311ea80baf693db78d95b603c4/propcache-0.5.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e00820e192c8dbebcafb383ebbf99030895f09905e7a0eb2e0340a0bcc2bc825", size = 61633, upload-time = "2026-05-08T21:01:31.068Z" }, + { url = "https://files.pythonhosted.org/packages/c4/46/b3ff8aba2b4953a3e50de2cf72f1b5748b8eca93b15f3dc2c84339084c09/propcache-0.5.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c66afea89b1e43725731d2004732a046fe6fe955d51f952c3e95a7314a284a39", size = 61724, upload-time = "2026-05-08T21:01:32.374Z" }, + { url = "https://files.pythonhosted.org/packages/c5/01/814cfcafbcff954f94c01cf30e097ddc88a076b5440fbcf4570753437d40/propcache-0.5.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:d4dc37dec6c6cdad0b57881a5658fd14fbf53e333b1a86cf86559f190e1d9ec4", size = 60069, upload-time = "2026-05-08T21:01:33.67Z" }, + { url = "https://files.pythonhosted.org/packages/da/68/5c6f7622d510cc666a300687e06fd060c1a43361c0c9b20d284f06d8096a/propcache-0.5.2-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:5570dbcc97571c15f68068e529c92715a12f8d54030e272d264b377e22bd17a5", size = 57099, upload-time = "2026-05-08T21:01:34.915Z" }, + { url = "https://files.pythonhosted.org/packages/55/27/9cb0b4c679124085327957d42521c99dba04c88c90c3e55a6f0b633ebccc/propcache-0.5.2-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:f814362777a9f841adddb200ecdf8f5cb1e5a3c4b7a86378edbd6ccb26edd702", size = 63391, upload-time = "2026-05-08T21:01:36.231Z" }, + { url = "https://files.pythonhosted.org/packages/f0/9d/7258aaa5bdf60fc6f27591eef6fe52768cb0beda7140be477c8b12c9794a/propcache-0.5.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:196913dea116aeb5a2ba95af4ddcb7ea85559ae07d8eee8751688310d09168c3", size = 61626, upload-time = "2026-05-08T21:01:37.545Z" }, + { url = "https://files.pythonhosted.org/packages/8e/0d/41c602003e8a9b16fe1e7eadf62c7bfba9d5474370b24200bf48b315f45f/propcache-0.5.2-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:6e7b8719005dd1175be4ab1cd25e9b98659a5e0347331506ec6760d2773a7fb5", size = 64781, upload-time = "2026-05-08T21:01:38.83Z" }, + { url = "https://files.pythonhosted.org/packages/8b/f3/38e66b1856e9bd079deea015bc4a55f7767c0e4db2f7dcf69e7e680ba4ce/propcache-0.5.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:51f96d685ab16e88cab128cd37a52c5da540809c8b879fa047731bfcb4ad35a4", size = 62570, upload-time = "2026-05-08T21:01:40.415Z" }, + { url = "https://files.pythonhosted.org/packages/95/ca/bbfe9b910ce57dde8bb4876b4520fc02a4e89497c10de26be936758a3aaa/propcache-0.5.2-cp314-cp314-win32.whl", hash = "sha256:cc6fc3cc62e8501d3ed62894425040d2728ecddb1ed072737a5c70bd537aa9f0", size = 39436, upload-time = "2026-05-08T21:01:41.654Z" }, + { url = "https://files.pythonhosted.org/packages/61/d2/45c9defbaa1ea297035d9d4cce9e8f80daafbf19319c6007f157c6256ea9/propcache-0.5.2-cp314-cp314-win_amd64.whl", hash = "sha256:81e3a30b0bb60caa22033dd0f8a3618d1d67356212514f62c57db75cb0ef410c", size = 42373, upload-time = "2026-05-08T21:01:43.041Z" }, + { url = "https://files.pythonhosted.org/packages/44/68/9ea5103f41d5217d7d6ec24db90018e23aebec070c3f9a6e54d12b841fd8/propcache-0.5.2-cp314-cp314-win_arm64.whl", hash = "sha256:0d2c9bf8528f135dbb805ce027567e09164f7efa51a2be07458a2c0420f292d0", size = 38554, upload-time = "2026-05-08T21:01:44.336Z" }, + { url = "https://files.pythonhosted.org/packages/8a/81/fadf555f42d3b762eea8a53950b0489fdc0aa9da5f8ed9e10ce0a4e01b48/propcache-0.5.2-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:4bc8ff1feffc6a61c7002ffe84634c41b822e104990ae009f44a0834430070bb", size = 99395, upload-time = "2026-05-08T21:01:45.883Z" }, + { url = "https://files.pythonhosted.org/packages/f5/c9/c61e134a686949cf7971af3a390148b1156f7be81c73bc0cd12c873e2d48/propcache-0.5.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:79aa3ff0a9b566633b642fa9caf7e21ed1c13d6feca718187873f199e1514078", size = 56653, upload-time = "2026-05-08T21:01:47.307Z" }, + { url = "https://files.pythonhosted.org/packages/cb/73/daf935ea7048ddd7ec8eec5345b4a40b619d2d178b3c0a0900796bc3c794/propcache-0.5.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1b31822f4474c4036bae62de9402710051d431a606d6a0f907fec79935a071aa", size = 56914, upload-time = "2026-05-08T21:01:48.573Z" }, + { url = "https://files.pythonhosted.org/packages/79/9f/aba959b435ea18617edd7cf0a7ad0b9c574b8fc7e3d2cd55fb59cb255d33/propcache-0.5.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:13fef48778b5a2a756523fdb781326b028ca75e32858b04f2cdd19f394564917", size = 62567, upload-time = "2026-05-08T21:01:49.903Z" }, + { url = "https://files.pythonhosted.org/packages/6c/a1/859942de9a791ff42f6141736f5b37749b8f53e65edfa49638c67dd67e6a/propcache-0.5.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8b73ab70f1a3351fbc71f663b3e645af6dd0329100c353081cf69c37433fc6fe", size = 65542, upload-time = "2026-05-08T21:01:51.204Z" }, + { url = "https://files.pythonhosted.org/packages/b5/61/315bc0fd6c0fc7f80a528b8afd209e5fc4a875ea79571b91b8f50f442907/propcache-0.5.2-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5538d2c13d93e4698af7e092b57bc7298fd35d1d58e656ae18f23ee0d0378e03", size = 66845, upload-time = "2026-05-08T21:01:52.539Z" }, + { url = "https://files.pythonhosted.org/packages/47/f7/9f8122e3132e8e354ac41975ef8f1099be7d5a16bc7ae562734e993665c0/propcache-0.5.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cd645f03898405cabe694fb8bc35241e3a9c332ec85627584fe3de201452b335", size = 63985, upload-time = "2026-05-08T21:01:53.847Z" }, + { url = "https://files.pythonhosted.org/packages/c8/54/c317819ec157cbf6f35df9df9657a6f82daf34d5faf15948b2f639c2192e/propcache-0.5.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a473b3440261e0c60706e732b2ed2f517857344fc21bf48fdfe211e2d98eb285", size = 63999, upload-time = "2026-05-08T21:01:55.179Z" }, + { url = "https://files.pythonhosted.org/packages/5a/56/387e3f7dfce0a9233df41fb888aa1c30222cb4bbbf09537c02dd9bd85fe2/propcache-0.5.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7afa37062e6650640e932e4cc9297d81f9f42d9944029cc386b8247dea4da837", size = 62779, upload-time = "2026-05-08T21:01:57.489Z" }, + { url = "https://files.pythonhosted.org/packages/a1/9c/596784cb5824ed61ee960d3f8655a3f0993e107c6e98ab6c818b7fb92ccb/propcache-0.5.2-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:8a90efd5777e996e42d568db9ac740b944d691e565cbfd31b2f7832f9184b2b8", size = 59796, upload-time = "2026-05-08T21:01:58.736Z" }, + { url = "https://files.pythonhosted.org/packages/c2/3d/1a6cfa1726a48542c1e8784a0761421476a5b68e09b7f36bf95eb954aaba/propcache-0.5.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:f19bb891234d72535764d703bfed1153cc34f4214d5bd7150aee1eec9e8f4366", size = 66023, upload-time = "2026-05-08T21:02:00.228Z" }, + { url = "https://files.pythonhosted.org/packages/e4/0e/05fd6990369477076e4e280bcb970de760fddf0161a46e988bc95f7940ec/propcache-0.5.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:32775082acd2d807ee3db715c7770d38767b817870acfa08c29e057f3c4d5b56", size = 64448, upload-time = "2026-05-08T21:02:01.888Z" }, + { url = "https://files.pythonhosted.org/packages/cd/86/5f8da315a4309c62c10c0b2516b17492d5d3bbe1bb862b96604db67e2a37/propcache-0.5.2-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:9282fb1a3bccd038da9f768b927b24a0c753e466c086b7c4f3c6982851eefb2d", size = 67329, upload-time = "2026-05-08T21:02:03.484Z" }, + { url = "https://files.pythonhosted.org/packages/da/d3/3368efe79ab21f0cdf86ef49895811c9cc933131d4cde1f28a624e22e712/propcache-0.5.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:cc49723e2f60d6b32a0f0b08a3fd6d13203c07f1cd9566cfce0f12a917c967a2", size = 65172, upload-time = "2026-05-08T21:02:04.745Z" }, + { url = "https://files.pythonhosted.org/packages/d5/07/127e8b0bacfb325396196f9d976a22453049b89b9b2b08477cc3145faa44/propcache-0.5.2-cp314-cp314t-win32.whl", hash = "sha256:2d7aa89ebca5acc98cba9d1472d976e394782f587bad6661003602a619fd1821", size = 43813, upload-time = "2026-05-08T21:02:06.025Z" }, + { url = "https://files.pythonhosted.org/packages/88/fb/46dad6c0ae49ed230ab1b16c890c2b6314e2403e6c412976f4a72d64a527/propcache-0.5.2-cp314-cp314t-win_amd64.whl", hash = "sha256:d447bb0b3054be5818458fbb171208b1d9ff11eba14e18ca18b90cbb45767370", size = 47764, upload-time = "2026-05-08T21:02:07.353Z" }, + { url = "https://files.pythonhosted.org/packages/e7/c4/a47d0a63aa309d10d59ede6e9d4cff03a344a79d1f0f4cd0cd74997b53e0/propcache-0.5.2-cp314-cp314t-win_arm64.whl", hash = "sha256:fe67a3d11cd9b4efabfa45c3d00ffba2b26811442a73a581a94b67c2b5faccf6", size = 41140, upload-time = "2026-05-08T21:02:09.065Z" }, + { url = "https://files.pythonhosted.org/packages/3a/ed/1cdcab6ba3d6ab7feca11fc14f0eeea80755bb53ef4e892079f31b10a25f/propcache-0.5.2-py3-none-any.whl", hash = "sha256:be1ddfcbb376e3de5d2e2db1d58d6d67463e6b4f9f040c000de8e300295465fe", size = 14036, upload-time = "2026-05-08T21:02:10.673Z" }, +] + +[[package]] +name = "psutil" +version = "7.2.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740, upload-time = "2026-01-28T18:14:54.428Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/08/510cbdb69c25a96f4ae523f733cdc963ae654904e8db864c07585ef99875/psutil-7.2.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:2edccc433cbfa046b980b0df0171cd25bcaeb3a68fe9022db0979e7aa74a826b", size = 130595, upload-time = "2026-01-28T18:14:57.293Z" }, + { url = "https://files.pythonhosted.org/packages/d6/f5/97baea3fe7a5a9af7436301f85490905379b1c6f2dd51fe3ecf24b4c5fbf/psutil-7.2.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e78c8603dcd9a04c7364f1a3e670cea95d51ee865e4efb3556a3a63adef958ea", size = 131082, upload-time = "2026-01-28T18:14:59.732Z" }, + { url = "https://files.pythonhosted.org/packages/37/d6/246513fbf9fa174af531f28412297dd05241d97a75911ac8febefa1a53c6/psutil-7.2.2-cp313-cp313t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1a571f2330c966c62aeda00dd24620425d4b0cc86881c89861fbc04549e5dc63", size = 181476, upload-time = "2026-01-28T18:15:01.884Z" }, + { url = "https://files.pythonhosted.org/packages/b8/b5/9182c9af3836cca61696dabe4fd1304e17bc56cb62f17439e1154f225dd3/psutil-7.2.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:917e891983ca3c1887b4ef36447b1e0873e70c933afc831c6b6da078ba474312", size = 184062, upload-time = "2026-01-28T18:15:04.436Z" }, + { url = "https://files.pythonhosted.org/packages/16/ba/0756dca669f5a9300d0cbcbfae9a4c30e446dfc7440ffe43ded5724bfd93/psutil-7.2.2-cp313-cp313t-win_amd64.whl", hash = "sha256:ab486563df44c17f5173621c7b198955bd6b613fb87c71c161f827d3fb149a9b", size = 139893, upload-time = "2026-01-28T18:15:06.378Z" }, + { url = "https://files.pythonhosted.org/packages/1c/61/8fa0e26f33623b49949346de05ec1ddaad02ed8ba64af45f40a147dbfa97/psutil-7.2.2-cp313-cp313t-win_arm64.whl", hash = "sha256:ae0aefdd8796a7737eccea863f80f81e468a1e4cf14d926bd9b6f5f2d5f90ca9", size = 135589, upload-time = "2026-01-28T18:15:08.03Z" }, + { url = "https://files.pythonhosted.org/packages/81/69/ef179ab5ca24f32acc1dac0c247fd6a13b501fd5534dbae0e05a1c48b66d/psutil-7.2.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:eed63d3b4d62449571547b60578c5b2c4bcccc5387148db46e0c2313dad0ee00", size = 130664, upload-time = "2026-01-28T18:15:09.469Z" }, + { url = "https://files.pythonhosted.org/packages/7b/64/665248b557a236d3fa9efc378d60d95ef56dd0a490c2cd37dafc7660d4a9/psutil-7.2.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7b6d09433a10592ce39b13d7be5a54fbac1d1228ed29abc880fb23df7cb694c9", size = 131087, upload-time = "2026-01-28T18:15:11.724Z" }, + { url = "https://files.pythonhosted.org/packages/d5/2e/e6782744700d6759ebce3043dcfa661fb61e2fb752b91cdeae9af12c2178/psutil-7.2.2-cp314-cp314t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1fa4ecf83bcdf6e6c8f4449aff98eefb5d0604bf88cb883d7da3d8d2d909546a", size = 182383, upload-time = "2026-01-28T18:15:13.445Z" }, + { url = "https://files.pythonhosted.org/packages/57/49/0a41cefd10cb7505cdc04dab3eacf24c0c2cb158a998b8c7b1d27ee2c1f5/psutil-7.2.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e452c464a02e7dc7822a05d25db4cde564444a67e58539a00f929c51eddda0cf", size = 185210, upload-time = "2026-01-28T18:15:16.002Z" }, + { url = "https://files.pythonhosted.org/packages/dd/2c/ff9bfb544f283ba5f83ba725a3c5fec6d6b10b8f27ac1dc641c473dc390d/psutil-7.2.2-cp314-cp314t-win_amd64.whl", hash = "sha256:c7663d4e37f13e884d13994247449e9f8f574bc4655d509c3b95e9ec9e2b9dc1", size = 141228, upload-time = "2026-01-28T18:15:18.385Z" }, + { url = "https://files.pythonhosted.org/packages/f2/fc/f8d9c31db14fcec13748d373e668bc3bed94d9077dbc17fb0eebc073233c/psutil-7.2.2-cp314-cp314t-win_arm64.whl", hash = "sha256:11fe5a4f613759764e79c65cf11ebdf26e33d6dd34336f8a337aa2996d71c841", size = 136284, upload-time = "2026-01-28T18:15:19.912Z" }, + { url = "https://files.pythonhosted.org/packages/e7/36/5ee6e05c9bd427237b11b3937ad82bb8ad2752d72c6969314590dd0c2f6e/psutil-7.2.2-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486", size = 129090, upload-time = "2026-01-28T18:15:22.168Z" }, + { url = "https://files.pythonhosted.org/packages/80/c4/f5af4c1ca8c1eeb2e92ccca14ce8effdeec651d5ab6053c589b074eda6e1/psutil-7.2.2-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979", size = 129859, upload-time = "2026-01-28T18:15:23.795Z" }, + { url = "https://files.pythonhosted.org/packages/b5/70/5d8df3b09e25bce090399cf48e452d25c935ab72dad19406c77f4e828045/psutil-7.2.2-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9", size = 155560, upload-time = "2026-01-28T18:15:25.976Z" }, + { url = "https://files.pythonhosted.org/packages/63/65/37648c0c158dc222aba51c089eb3bdfa238e621674dc42d48706e639204f/psutil-7.2.2-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e", size = 156997, upload-time = "2026-01-28T18:15:27.794Z" }, + { url = "https://files.pythonhosted.org/packages/8e/13/125093eadae863ce03c6ffdbae9929430d116a246ef69866dad94da3bfbc/psutil-7.2.2-cp36-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8", size = 148972, upload-time = "2026-01-28T18:15:29.342Z" }, + { url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" }, + { url = "https://files.pythonhosted.org/packages/b4/90/e2159492b5426be0c1fef7acba807a03511f97c5f86b3caeda6ad92351a7/psutil-7.2.2-cp37-abi3-win_amd64.whl", hash = "sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988", size = 137737, upload-time = "2026-01-28T18:15:33.849Z" }, + { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" }, +] + +[[package]] +name = "ptyprocess" +version = "0.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/20/e5/16ff212c1e452235a90aeb09066144d0c5a6a8c0834397e03f5224495c4e/ptyprocess-0.7.0.tar.gz", hash = "sha256:5c5d0a3b48ceee0b48485e0c26037c0acd7d29765ca3fbb5cb3831d347423220", size = 70762, upload-time = "2020-12-28T15:15:30.155Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/a6/858897256d0deac81a172289110f31629fc4cee19b6f01283303e18c8db3/ptyprocess-0.7.0-py2.py3-none-any.whl", hash = "sha256:4b41f3967fce3af57cc7e94b888626c18bf37a083e3651ca8feeb66d492fef35", size = 13993, upload-time = "2020-12-28T15:15:28.35Z" }, +] + +[[package]] +name = "pure-eval" +version = "0.2.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/05/0a34433a064256a578f1783a10da6df098ceaa4a57bbeaa96a6c0352786b/pure_eval-0.2.3.tar.gz", hash = "sha256:5f4e983f40564c576c7c8635ae88db5956bb2229d7e9237d03b3c0b0190eaf42", size = 19752, upload-time = "2024-07-21T12:58:21.801Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8e/37/efad0257dc6e593a18957422533ff0f87ede7c9c6ea010a2177d738fb82f/pure_eval-0.2.3-py3-none-any.whl", hash = "sha256:1db8e35b67b3d218d818ae653e27f06c3aa420901fa7b081ca98cbedc874e0d0", size = 11842, upload-time = "2024-07-21T12:58:20.04Z" }, +] + +[[package]] +name = "pycparser" +version = "3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" }, +] + +[[package]] +name = "pygments" +version = "2.20.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" }, +] + +[[package]] +name = "pymdown-extensions" +version = "11.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown" }, + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/21/a9/5f0c535ba3b08fe09270c16808e053a968868242ecbd5676d4e3a488bf28/pymdown_extensions-11.0.1.tar.gz", hash = "sha256:dd2905ae6fc5b75582fafb139a1266ffc754705efa902aa50067fa7ff4f94ec0", size = 857113, upload-time = "2026-07-02T17:59:22.955Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d6/54/da572c98c0b77626a91b5d3b89f0231d8bff5125c225420908632f8b342d/pymdown_extensions-11.0.1-py3-none-any.whl", hash = "sha256:db3943a62bab7e03af1364f0c4083e64b91fb097675a4b6cceccfbe9a77e5eb2", size = 269455, upload-time = "2026-07-02T17:59:21.271Z" }, +] + +[[package]] +name = "pytest" +version = "9.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, +] + +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/33/422b98d2195232ca1826284a76852ad5a86fe23e31b009c9886b2d0fb8b2/pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196", size = 182063, upload-time = "2025-09-25T21:32:11.445Z" }, + { url = "https://files.pythonhosted.org/packages/89/a0/6cf41a19a1f2f3feab0e9c0b74134aa2ce6849093d5517a0c550fe37a648/pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0", size = 173973, upload-time = "2025-09-25T21:32:12.492Z" }, + { url = "https://files.pythonhosted.org/packages/ed/23/7a778b6bd0b9a8039df8b1b1d80e2e2ad78aa04171592c8a5c43a56a6af4/pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", size = 775116, upload-time = "2025-09-25T21:32:13.652Z" }, + { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011, upload-time = "2025-09-25T21:32:15.21Z" }, + { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870, upload-time = "2025-09-25T21:32:16.431Z" }, + { url = "https://files.pythonhosted.org/packages/05/c0/b3be26a015601b822b97d9149ff8cb5ead58c66f981e04fedf4e762f4bd4/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", size = 761089, upload-time = "2025-09-25T21:32:17.56Z" }, + { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181, upload-time = "2025-09-25T21:32:18.834Z" }, + { url = "https://files.pythonhosted.org/packages/74/93/7baea19427dcfbe1e5a372d81473250b379f04b1bd3c4c5ff825e2327202/pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5", size = 137658, upload-time = "2025-09-25T21:32:20.209Z" }, + { url = "https://files.pythonhosted.org/packages/86/bf/899e81e4cce32febab4fb42bb97dcdf66bc135272882d1987881a4b519e9/pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b", size = 154003, upload-time = "2025-09-25T21:32:21.167Z" }, + { url = "https://files.pythonhosted.org/packages/1a/08/67bd04656199bbb51dbed1439b7f27601dfb576fb864099c7ef0c3e55531/pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", size = 140344, upload-time = "2025-09-25T21:32:22.617Z" }, + { url = "https://files.pythonhosted.org/packages/d1/11/0fd08f8192109f7169db964b5707a2f1e8b745d4e239b784a5a1dd80d1db/pyyaml-6.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8", size = 181669, upload-time = "2025-09-25T21:32:23.673Z" }, + { url = "https://files.pythonhosted.org/packages/b1/16/95309993f1d3748cd644e02e38b75d50cbc0d9561d21f390a76242ce073f/pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1", size = 173252, upload-time = "2025-09-25T21:32:25.149Z" }, + { url = "https://files.pythonhosted.org/packages/50/31/b20f376d3f810b9b2371e72ef5adb33879b25edb7a6d072cb7ca0c486398/pyyaml-6.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c", size = 767081, upload-time = "2025-09-25T21:32:26.575Z" }, + { url = "https://files.pythonhosted.org/packages/49/1e/a55ca81e949270d5d4432fbbd19dfea5321eda7c41a849d443dc92fd1ff7/pyyaml-6.0.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5", size = 841159, upload-time = "2025-09-25T21:32:27.727Z" }, + { url = "https://files.pythonhosted.org/packages/74/27/e5b8f34d02d9995b80abcef563ea1f8b56d20134d8f4e5e81733b1feceb2/pyyaml-6.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6", size = 801626, upload-time = "2025-09-25T21:32:28.878Z" }, + { url = "https://files.pythonhosted.org/packages/f9/11/ba845c23988798f40e52ba45f34849aa8a1f2d4af4b798588010792ebad6/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6", size = 753613, upload-time = "2025-09-25T21:32:30.178Z" }, + { url = "https://files.pythonhosted.org/packages/3d/e0/7966e1a7bfc0a45bf0a7fb6b98ea03fc9b8d84fa7f2229e9659680b69ee3/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be", size = 794115, upload-time = "2025-09-25T21:32:31.353Z" }, + { url = "https://files.pythonhosted.org/packages/de/94/980b50a6531b3019e45ddeada0626d45fa85cbe22300844a7983285bed3b/pyyaml-6.0.3-cp313-cp313-win32.whl", hash = "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26", size = 137427, upload-time = "2025-09-25T21:32:32.58Z" }, + { url = "https://files.pythonhosted.org/packages/97/c9/39d5b874e8b28845e4ec2202b5da735d0199dbe5b8fb85f91398814a9a46/pyyaml-6.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c", size = 154090, upload-time = "2025-09-25T21:32:33.659Z" }, + { url = "https://files.pythonhosted.org/packages/73/e8/2bdf3ca2090f68bb3d75b44da7bbc71843b19c9f2b9cb9b0f4ab7a5a4329/pyyaml-6.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb", size = 140246, upload-time = "2025-09-25T21:32:34.663Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8c/f4bd7f6465179953d3ac9bc44ac1a8a3e6122cf8ada906b4f96c60172d43/pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac", size = 181814, upload-time = "2025-09-25T21:32:35.712Z" }, + { url = "https://files.pythonhosted.org/packages/bd/9c/4d95bb87eb2063d20db7b60faa3840c1b18025517ae857371c4dd55a6b3a/pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310", size = 173809, upload-time = "2025-09-25T21:32:36.789Z" }, + { url = "https://files.pythonhosted.org/packages/92/b5/47e807c2623074914e29dabd16cbbdd4bf5e9b2db9f8090fa64411fc5382/pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7", size = 766454, upload-time = "2025-09-25T21:32:37.966Z" }, + { url = "https://files.pythonhosted.org/packages/02/9e/e5e9b168be58564121efb3de6859c452fccde0ab093d8438905899a3a483/pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788", size = 836355, upload-time = "2025-09-25T21:32:39.178Z" }, + { url = "https://files.pythonhosted.org/packages/88/f9/16491d7ed2a919954993e48aa941b200f38040928474c9e85ea9e64222c3/pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5", size = 794175, upload-time = "2025-09-25T21:32:40.865Z" }, + { url = "https://files.pythonhosted.org/packages/dd/3f/5989debef34dc6397317802b527dbbafb2b4760878a53d4166579111411e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764", size = 755228, upload-time = "2025-09-25T21:32:42.084Z" }, + { url = "https://files.pythonhosted.org/packages/d7/ce/af88a49043cd2e265be63d083fc75b27b6ed062f5f9fd6cdc223ad62f03e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35", size = 789194, upload-time = "2025-09-25T21:32:43.362Z" }, + { url = "https://files.pythonhosted.org/packages/23/20/bb6982b26a40bb43951265ba29d4c246ef0ff59c9fdcdf0ed04e0687de4d/pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac", size = 156429, upload-time = "2025-09-25T21:32:57.844Z" }, + { url = "https://files.pythonhosted.org/packages/f4/f4/a4541072bb9422c8a883ab55255f918fa378ecf083f5b85e87fc2b4eda1b/pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3", size = 143912, upload-time = "2025-09-25T21:32:59.247Z" }, + { url = "https://files.pythonhosted.org/packages/7c/f9/07dd09ae774e4616edf6cda684ee78f97777bdd15847253637a6f052a62f/pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3", size = 189108, upload-time = "2025-09-25T21:32:44.377Z" }, + { url = "https://files.pythonhosted.org/packages/4e/78/8d08c9fb7ce09ad8c38ad533c1191cf27f7ae1effe5bb9400a46d9437fcf/pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba", size = 183641, upload-time = "2025-09-25T21:32:45.407Z" }, + { url = "https://files.pythonhosted.org/packages/7b/5b/3babb19104a46945cf816d047db2788bcaf8c94527a805610b0289a01c6b/pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c", size = 831901, upload-time = "2025-09-25T21:32:48.83Z" }, + { url = "https://files.pythonhosted.org/packages/8b/cc/dff0684d8dc44da4d22a13f35f073d558c268780ce3c6ba1b87055bb0b87/pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702", size = 861132, upload-time = "2025-09-25T21:32:50.149Z" }, + { url = "https://files.pythonhosted.org/packages/b1/5e/f77dc6b9036943e285ba76b49e118d9ea929885becb0a29ba8a7c75e29fe/pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c", size = 839261, upload-time = "2025-09-25T21:32:51.808Z" }, + { url = "https://files.pythonhosted.org/packages/ce/88/a9db1376aa2a228197c58b37302f284b5617f56a5d959fd1763fb1675ce6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065", size = 805272, upload-time = "2025-09-25T21:32:52.941Z" }, + { url = "https://files.pythonhosted.org/packages/da/92/1446574745d74df0c92e6aa4a7b0b3130706a4142b2d1a5869f2eaa423c6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65", size = 829923, upload-time = "2025-09-25T21:32:54.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/7a/1c7270340330e575b92f397352af856a8c06f230aa3e76f86b39d01b416a/pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9", size = 174062, upload-time = "2025-09-25T21:32:55.767Z" }, + { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" }, +] + +[[package]] +name = "pyyaml-env-tag" +version = "1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/eb/2e/79c822141bfd05a853236b504869ebc6b70159afc570e1d5a20641782eaa/pyyaml_env_tag-1.1.tar.gz", hash = "sha256:2eb38b75a2d21ee0475d6d97ec19c63287a7e140231e4214969d0eac923cd7ff", size = 5737, upload-time = "2025-05-13T15:24:01.64Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/11/432f32f8097b03e3cd5fe57e88efb685d964e2e5178a48ed61e841f7fdce/pyyaml_env_tag-1.1-py3-none-any.whl", hash = "sha256:17109e1a528561e32f026364712fee1264bc2ea6715120891174ed1b980d2e04", size = 4722, upload-time = "2025-05-13T15:23:59.629Z" }, +] + +[[package]] +name = "pyzmq" +version = "27.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "implementation_name == 'pypy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/04/0b/3c9baedbdf613ecaa7aa07027780b8867f57b6293b6ee50de316c9f3222b/pyzmq-27.1.0.tar.gz", hash = "sha256:ac0765e3d44455adb6ddbf4417dcce460fc40a05978c08efdf2948072f6db540", size = 281750, upload-time = "2025-09-08T23:10:18.157Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/e7/038aab64a946d535901103da16b953c8c9cc9c961dadcbf3609ed6428d23/pyzmq-27.1.0-cp312-abi3-macosx_10_15_universal2.whl", hash = "sha256:452631b640340c928fa343801b0d07eb0c3789a5ffa843f6e1a9cee0ba4eb4fc", size = 1306279, upload-time = "2025-09-08T23:08:03.807Z" }, + { url = "https://files.pythonhosted.org/packages/e8/5e/c3c49fdd0f535ef45eefcc16934648e9e59dace4a37ee88fc53f6cd8e641/pyzmq-27.1.0-cp312-abi3-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:1c179799b118e554b66da67d88ed66cd37a169f1f23b5d9f0a231b4e8d44a113", size = 895645, upload-time = "2025-09-08T23:08:05.301Z" }, + { url = "https://files.pythonhosted.org/packages/f8/e5/b0b2504cb4e903a74dcf1ebae157f9e20ebb6ea76095f6cfffea28c42ecd/pyzmq-27.1.0-cp312-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3837439b7f99e60312f0c926a6ad437b067356dc2bc2ec96eb395fd0fe804233", size = 652574, upload-time = "2025-09-08T23:08:06.828Z" }, + { url = "https://files.pythonhosted.org/packages/f8/9b/c108cdb55560eaf253f0cbdb61b29971e9fb34d9c3499b0e96e4e60ed8a5/pyzmq-27.1.0-cp312-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:43ad9a73e3da1fab5b0e7e13402f0b2fb934ae1c876c51d0afff0e7c052eca31", size = 840995, upload-time = "2025-09-08T23:08:08.396Z" }, + { url = "https://files.pythonhosted.org/packages/c2/bb/b79798ca177b9eb0825b4c9998c6af8cd2a7f15a6a1a4272c1d1a21d382f/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:0de3028d69d4cdc475bfe47a6128eb38d8bc0e8f4d69646adfbcd840facbac28", size = 1642070, upload-time = "2025-09-08T23:08:09.989Z" }, + { url = "https://files.pythonhosted.org/packages/9c/80/2df2e7977c4ede24c79ae39dcef3899bfc5f34d1ca7a5b24f182c9b7a9ca/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_i686.whl", hash = "sha256:cf44a7763aea9298c0aa7dbf859f87ed7012de8bda0f3977b6fb1d96745df856", size = 2021121, upload-time = "2025-09-08T23:08:11.907Z" }, + { url = "https://files.pythonhosted.org/packages/46/bd/2d45ad24f5f5ae7e8d01525eb76786fa7557136555cac7d929880519e33a/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:f30f395a9e6fbca195400ce833c731e7b64c3919aa481af4d88c3759e0cb7496", size = 1878550, upload-time = "2025-09-08T23:08:13.513Z" }, + { url = "https://files.pythonhosted.org/packages/e6/2f/104c0a3c778d7c2ab8190e9db4f62f0b6957b53c9d87db77c284b69f33ea/pyzmq-27.1.0-cp312-abi3-win32.whl", hash = "sha256:250e5436a4ba13885494412b3da5d518cd0d3a278a1ae640e113c073a5f88edd", size = 559184, upload-time = "2025-09-08T23:08:15.163Z" }, + { url = "https://files.pythonhosted.org/packages/fc/7f/a21b20d577e4100c6a41795842028235998a643b1ad406a6d4163ea8f53e/pyzmq-27.1.0-cp312-abi3-win_amd64.whl", hash = "sha256:9ce490cf1d2ca2ad84733aa1d69ce6855372cb5ce9223802450c9b2a7cba0ccf", size = 619480, upload-time = "2025-09-08T23:08:17.192Z" }, + { url = "https://files.pythonhosted.org/packages/78/c2/c012beae5f76b72f007a9e91ee9401cb88c51d0f83c6257a03e785c81cc2/pyzmq-27.1.0-cp312-abi3-win_arm64.whl", hash = "sha256:75a2f36223f0d535a0c919e23615fc85a1e23b71f40c7eb43d7b1dedb4d8f15f", size = 552993, upload-time = "2025-09-08T23:08:18.926Z" }, + { url = "https://files.pythonhosted.org/packages/60/cb/84a13459c51da6cec1b7b1dc1a47e6db6da50b77ad7fd9c145842750a011/pyzmq-27.1.0-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:93ad4b0855a664229559e45c8d23797ceac03183c7b6f5b4428152a6b06684a5", size = 1122436, upload-time = "2025-09-08T23:08:20.801Z" }, + { url = "https://files.pythonhosted.org/packages/dc/b6/94414759a69a26c3dd674570a81813c46a078767d931a6c70ad29fc585cb/pyzmq-27.1.0-cp313-cp313-android_24_x86_64.whl", hash = "sha256:fbb4f2400bfda24f12f009cba62ad5734148569ff4949b1b6ec3b519444342e6", size = 1156301, upload-time = "2025-09-08T23:08:22.47Z" }, + { url = "https://files.pythonhosted.org/packages/a5/ad/15906493fd40c316377fd8a8f6b1f93104f97a752667763c9b9c1b71d42d/pyzmq-27.1.0-cp313-cp313t-macosx_10_15_universal2.whl", hash = "sha256:e343d067f7b151cfe4eb3bb796a7752c9d369eed007b91231e817071d2c2fec7", size = 1341197, upload-time = "2025-09-08T23:08:24.286Z" }, + { url = "https://files.pythonhosted.org/packages/14/1d/d343f3ce13db53a54cb8946594e567410b2125394dafcc0268d8dda027e0/pyzmq-27.1.0-cp313-cp313t-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:08363b2011dec81c354d694bdecaef4770e0ae96b9afea70b3f47b973655cc05", size = 897275, upload-time = "2025-09-08T23:08:26.063Z" }, + { url = "https://files.pythonhosted.org/packages/69/2d/d83dd6d7ca929a2fc67d2c3005415cdf322af7751d773524809f9e585129/pyzmq-27.1.0-cp313-cp313t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d54530c8c8b5b8ddb3318f481297441af102517602b569146185fa10b63f4fa9", size = 660469, upload-time = "2025-09-08T23:08:27.623Z" }, + { url = "https://files.pythonhosted.org/packages/3e/cd/9822a7af117f4bc0f1952dbe9ef8358eb50a24928efd5edf54210b850259/pyzmq-27.1.0-cp313-cp313t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f3afa12c392f0a44a2414056d730eebc33ec0926aae92b5ad5cf26ebb6cc128", size = 847961, upload-time = "2025-09-08T23:08:29.672Z" }, + { url = "https://files.pythonhosted.org/packages/9a/12/f003e824a19ed73be15542f172fd0ec4ad0b60cf37436652c93b9df7c585/pyzmq-27.1.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:c65047adafe573ff023b3187bb93faa583151627bc9c51fc4fb2c561ed689d39", size = 1650282, upload-time = "2025-09-08T23:08:31.349Z" }, + { url = "https://files.pythonhosted.org/packages/d5/4a/e82d788ed58e9a23995cee70dbc20c9aded3d13a92d30d57ec2291f1e8a3/pyzmq-27.1.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:90e6e9441c946a8b0a667356f7078d96411391a3b8f80980315455574177ec97", size = 2024468, upload-time = "2025-09-08T23:08:33.543Z" }, + { url = "https://files.pythonhosted.org/packages/d9/94/2da0a60841f757481e402b34bf4c8bf57fa54a5466b965de791b1e6f747d/pyzmq-27.1.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:add071b2d25f84e8189aaf0882d39a285b42fa3853016ebab234a5e78c7a43db", size = 1885394, upload-time = "2025-09-08T23:08:35.51Z" }, + { url = "https://files.pythonhosted.org/packages/4f/6f/55c10e2e49ad52d080dc24e37adb215e5b0d64990b57598abc2e3f01725b/pyzmq-27.1.0-cp313-cp313t-win32.whl", hash = "sha256:7ccc0700cfdf7bd487bea8d850ec38f204478681ea02a582a8da8171b7f90a1c", size = 574964, upload-time = "2025-09-08T23:08:37.178Z" }, + { url = "https://files.pythonhosted.org/packages/87/4d/2534970ba63dd7c522d8ca80fb92777f362c0f321900667c615e2067cb29/pyzmq-27.1.0-cp313-cp313t-win_amd64.whl", hash = "sha256:8085a9fba668216b9b4323be338ee5437a235fe275b9d1610e422ccc279733e2", size = 641029, upload-time = "2025-09-08T23:08:40.595Z" }, + { url = "https://files.pythonhosted.org/packages/f6/fa/f8aea7a28b0641f31d40dea42d7ef003fded31e184ef47db696bc74cd610/pyzmq-27.1.0-cp313-cp313t-win_arm64.whl", hash = "sha256:6bb54ca21bcfe361e445256c15eedf083f153811c37be87e0514934d6913061e", size = 561541, upload-time = "2025-09-08T23:08:42.668Z" }, + { url = "https://files.pythonhosted.org/packages/87/45/19efbb3000956e82d0331bafca5d9ac19ea2857722fa2caacefb6042f39d/pyzmq-27.1.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:ce980af330231615756acd5154f29813d553ea555485ae712c491cd483df6b7a", size = 1341197, upload-time = "2025-09-08T23:08:44.973Z" }, + { url = "https://files.pythonhosted.org/packages/48/43/d72ccdbf0d73d1343936296665826350cb1e825f92f2db9db3e61c2162a2/pyzmq-27.1.0-cp314-cp314t-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:1779be8c549e54a1c38f805e56d2a2e5c009d26de10921d7d51cfd1c8d4632ea", size = 897175, upload-time = "2025-09-08T23:08:46.601Z" }, + { url = "https://files.pythonhosted.org/packages/2f/2e/a483f73a10b65a9ef0161e817321d39a770b2acf8bcf3004a28d90d14a94/pyzmq-27.1.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7200bb0f03345515df50d99d3db206a0a6bee1955fbb8c453c76f5bf0e08fb96", size = 660427, upload-time = "2025-09-08T23:08:48.187Z" }, + { url = "https://files.pythonhosted.org/packages/f5/d2/5f36552c2d3e5685abe60dfa56f91169f7a2d99bbaf67c5271022ab40863/pyzmq-27.1.0-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:01c0e07d558b06a60773744ea6251f769cd79a41a97d11b8bf4ab8f034b0424d", size = 847929, upload-time = "2025-09-08T23:08:49.76Z" }, + { url = "https://files.pythonhosted.org/packages/c4/2a/404b331f2b7bf3198e9945f75c4c521f0c6a3a23b51f7a4a401b94a13833/pyzmq-27.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:80d834abee71f65253c91540445d37c4c561e293ba6e741b992f20a105d69146", size = 1650193, upload-time = "2025-09-08T23:08:51.7Z" }, + { url = "https://files.pythonhosted.org/packages/1c/0b/f4107e33f62a5acf60e3ded67ed33d79b4ce18de432625ce2fc5093d6388/pyzmq-27.1.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:544b4e3b7198dde4a62b8ff6685e9802a9a1ebf47e77478a5eb88eca2a82f2fd", size = 2024388, upload-time = "2025-09-08T23:08:53.393Z" }, + { url = "https://files.pythonhosted.org/packages/0d/01/add31fe76512642fd6e40e3a3bd21f4b47e242c8ba33efb6809e37076d9b/pyzmq-27.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:cedc4c68178e59a4046f97eca31b148ddcf51e88677de1ef4e78cf06c5376c9a", size = 1885316, upload-time = "2025-09-08T23:08:55.702Z" }, + { url = "https://files.pythonhosted.org/packages/c4/59/a5f38970f9bf07cee96128de79590bb354917914a9be11272cfc7ff26af0/pyzmq-27.1.0-cp314-cp314t-win32.whl", hash = "sha256:1f0b2a577fd770aa6f053211a55d1c47901f4d537389a034c690291485e5fe92", size = 587472, upload-time = "2025-09-08T23:08:58.18Z" }, + { url = "https://files.pythonhosted.org/packages/70/d8/78b1bad170f93fcf5e3536e70e8fadac55030002275c9a29e8f5719185de/pyzmq-27.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:19c9468ae0437f8074af379e986c5d3d7d7bfe033506af442e8c879732bedbe0", size = 661401, upload-time = "2025-09-08T23:08:59.802Z" }, + { url = "https://files.pythonhosted.org/packages/81/d6/4bfbb40c9a0b42fc53c7cf442f6385db70b40f74a783130c5d0a5aa62228/pyzmq-27.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:dc5dbf68a7857b59473f7df42650c621d7e8923fb03fa74a526890f4d33cc4d7", size = 575170, upload-time = "2025-09-08T23:09:01.418Z" }, +] + +[[package]] +name = "referencing" +version = "0.37.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "rpds-py" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/22/f5/df4e9027acead3ecc63e50fe1e36aca1523e1719559c499951bb4b53188f/referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8", size = 78036, upload-time = "2025-10-13T15:30:48.871Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231", size = 26766, upload-time = "2025-10-13T15:30:47.625Z" }, +] + +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + +[[package]] +name = "rpds-py" +version = "2026.6.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/aa/2a/9618a122aeb2a169a28b03889a2995fe297588964333d4a7d67bdf46e147/rpds_py-2026.6.3.tar.gz", hash = "sha256:1cebd1337c242e4ec2293e541f712b2da849b29f48f0c293684b71c0632625d4", size = 64051, upload-time = "2026-06-30T07:17:53.009Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5c/be/2e8974163072e7bab7df1a5acd54c4498e75e35d6d18b864d3a9d5dadc92/rpds_py-2026.6.3-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:a0811d33247c3d6128a3001d763f2aa056bb3425204335400ac54f89eec3a0d0", size = 343691, upload-time = "2026-06-30T07:15:14.96Z" }, + { url = "https://files.pythonhosted.org/packages/a4/73/319dfa745dd668efe89309141ded489126461fcecd2b8f3a3cda185129b6/rpds_py-2026.6.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:538949e262e46caa31ac01bdb3c1e8f642622922cacbabbae6a8445d9dc33eaf", size = 338542, upload-time = "2026-06-30T07:15:16.267Z" }, + { url = "https://files.pythonhosted.org/packages/21/63/4239893be1c4d09b709b1a8f6be4188f0870084ff547f46606b8a75f1b03/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:55927d532399c2c646100ff7feb48eaa940ad70f42cd68e1328f3ded9f81ca24", size = 368180, upload-time = "2026-06-30T07:15:17.62Z" }, + { url = "https://files.pythonhosted.org/packages/1c/ca/9c5de382225234ceb37b1844ebdb140db12b2a278bb9efe2fcd19f6c82ce/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f56f1695bc5c0871cbc33dc0130fcf503aab0c57dcc5a6700a4f49eba4f2652e", size = 375067, upload-time = "2026-06-30T07:15:18.952Z" }, + { url = "https://files.pythonhosted.org/packages/87/dc/863f69d1bf04ade34b7fe0d59b9fdf6f0135fe2d7cbca74f1d665589559d/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:270b293dae9058fc9fcedab50f13cebf46fb8ed1d1d54e0521a9da5d6b211975", size = 490509, upload-time = "2026-06-30T07:15:20.434Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ef/eac16a12048b45ec7c7fa94f2be3438a5f26bf9cc8580b18a1cfd609b7f6/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:127565fead0a10943b282957bd5447804ff3160ad79f2ad2635e6d249e380680", size = 382754, upload-time = "2026-06-30T07:15:21.831Z" }, + { url = "https://files.pythonhosted.org/packages/04/8f/d2f3f532616be4d06c316ef119683e832bd3d41e112bf3a88f4151c95b17/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ecabd69db66de867690f9797f2f8fa27ba501bbc24540cbdbdc649cd15888ba6", size = 366189, upload-time = "2026-06-30T07:15:23.371Z" }, + { url = "https://files.pythonhosted.org/packages/e3/29/41a7b0e98a4b44cd676ab7598419623373eb43b20be68c084935c1a8cf88/rpds_py-2026.6.3-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:58eadac9cd119677b60e1cf8ac4052f35949d71b8a9e5556efccbe82533cf22a", size = 377750, upload-time = "2026-06-30T07:15:24.659Z" }, + { url = "https://files.pythonhosted.org/packages/2e/05/ecda0bec46f9a1565090bcdc941d023f6a25aff85fda28f89f8d19878152/rpds_py-2026.6.3-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:7491ee23305ac3eb59e492b6945881f5cd77a6f731061a3f25b77fd40f9e99a4", size = 395576, upload-time = "2026-06-30T07:15:25.987Z" }, + { url = "https://files.pythonhosted.org/packages/68/a8/6ed52f03ee6cb854ce78785cc9a9a672eb880e83fd7224d471f667d151f1/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2c99f7e8ccb3dd6e3e4bfeac657a7b208c9bac8075f4b078c02d7404c34107fa", size = 543807, upload-time = "2026-06-30T07:15:27.356Z" }, + { url = "https://files.pythonhosted.org/packages/8f/d6/156c0d3eea27ba09b92562ba2364ba124c0a061b199e17eac637cd25a5e2/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:62698275682bf121181861295c9181e789030a2d516071f5b8f3c23c170cd0fc", size = 611187, upload-time = "2026-06-30T07:15:28.931Z" }, + { url = "https://files.pythonhosted.org/packages/f1/31/774212ed989c62f7f310220089f9b0a3fb8f40f5443d1727abd5d9f52bc9/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a214c993455f99a89aaeadc9b21241900037adc9d97203e374d75513c5911822", size = 573030, upload-time = "2026-06-30T07:15:30.553Z" }, + { url = "https://files.pythonhosted.org/packages/c9/50/22f73127a41f1ce4f87fe39aadfb9a126345801c274aa93ae88456249327/rpds_py-2026.6.3-cp312-cp312-win32.whl", hash = "sha256:501f9f04a588d6a09179368c57071301445191767c64e4b52a6aa9871f1ef5ed", size = 202185, upload-time = "2026-06-30T07:15:32.027Z" }, + { url = "https://files.pythonhosted.org/packages/04/3a/f0ee4d4dde9d3b69dedf1b5f74e7a40017046d55052d173e418c6a94f960/rpds_py-2026.6.3-cp312-cp312-win_amd64.whl", hash = "sha256:2c958bf94822e9290a40aaf2a822d4bc5c88099093e3948ad6c571eca9272e5f", size = 220394, upload-time = "2026-06-30T07:15:33.359Z" }, + { url = "https://files.pythonhosted.org/packages/f3/83/3382fe37f809b59f02aac04dbc4e765b480b46ee0227ed516e3bdc4d3dfc/rpds_py-2026.6.3-cp312-cp312-win_arm64.whl", hash = "sha256:22bffe6042b9bcb0822bcd1955ec00e245daf17b4344e4ed8e9551b976b63e96", size = 215753, upload-time = "2026-06-30T07:15:34.778Z" }, + { url = "https://files.pythonhosted.org/packages/a4/9e/b818ee580026ec578138e961027a68820c40afeb1ec8f6819b54fb99e196/rpds_py-2026.6.3-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:3cfe765c1da0072636ca06628261e0ea05688e160d5c8a03e0217c3854037223", size = 343012, upload-time = "2026-06-30T07:15:36.005Z" }, + { url = "https://files.pythonhosted.org/packages/f3/6b/686d9dc4359a8f163cfbbf89ee0b4e586431de22fe8248edb63a8cf50d49/rpds_py-2026.6.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f4d78253f6996be4901669ad25319f842f740eccf4d58e3c7f3dd39e6dde1d8f", size = 338203, upload-time = "2026-06-30T07:15:37.462Z" }, + { url = "https://files.pythonhosted.org/packages/9e/9b/069aa329940f8207615e091f5eedbbd40e1e15eac68a0790fd05ccdf796c/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:54f45a148e28767bf343d33a684693c70e451c6f4c0e9904709a723fafbdfc1f", size = 367984, upload-time = "2026-06-30T07:15:39.008Z" }, + { url = "https://files.pythonhosted.org/packages/14/db/34c203e4becff3703e4d3bc121842c00b8689197f398161203a880052f4e/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:842e7b070435622248c7a2c44ae53fa1440e073cc3023bc919fed570884097a7", size = 374815, upload-time = "2026-06-30T07:15:40.253Z" }, + { url = "https://files.pythonhosted.org/packages/ee/7d/8071067d2cc453d916ad836e828c943f575e8a44612537759002a1e07381/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8020133a74bd81b4572dd8e4be028a6b1ebcd70e6726edc3918008c08bee6ee6", size = 490545, upload-time = "2026-06-30T07:15:41.729Z" }, + { url = "https://files.pythonhosted.org/packages/a3/42/da06c5aa8f0484ff07f270787434204d9f4535e2f8c3b51ed402267e63c3/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cdc7e35386f3847df728fbcb5e887e2d79c19e2fa1eba9e51b6621d23e3243af", size = 382828, upload-time = "2026-06-30T07:15:43.327Z" }, + { url = "https://files.pythonhosted.org/packages/57/d7/fe978efc2ae50abe48eb7464668ea99f53c010c60aeebb7b35ad27f23661/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:acac386b453c2516111b50985d60ce46e7fadb5ea71ae7b25f4c946935bf27cf", size = 365678, upload-time = "2026-06-30T07:15:44.992Z" }, + { url = "https://files.pythonhosted.org/packages/69/9d/1d8922e1990b2a6eb532b6ff53d3e73d2b3bbffc84116c75826bee73dfc6/rpds_py-2026.6.3-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:425560c6fa0415f27261727bb20bd097568485e5eb0c121f1949417d1c516885", size = 377811, upload-time = "2026-06-30T07:15:46.523Z" }, + { url = "https://files.pythonhosted.org/packages/b1/3d/198dceafb4fb034a6a47347e1b0735d34e0bd4a50be4e898d408ee66cb14/rpds_py-2026.6.3-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a550fb4950a06dde3beb4721f5ad4b25bf4513784665b0a8522c792e2bd822a4", size = 395382, upload-time = "2026-06-30T07:15:47.955Z" }, + { url = "https://files.pythonhosted.org/packages/1f/f1/13968e49655d40b6b19d8b9140296bbc6f1d86b3f0f6c346cf9f1adddf4b/rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4f4bca01b63096f606e095734dd56e74e175f94cfbf24ff3d63281cec61f7bb7", size = 543832, upload-time = "2026-06-30T07:15:49.33Z" }, + { url = "https://files.pythonhosted.org/packages/ac/ab/289bcb1b90bd3e40a2900c561fa0e2087345ecbb094f0b870f2345142b7c/rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ccffae9a092a00deb7efd545fe5e2c33c33b88e7c054337e9a74c179347d0b7d", size = 611011, upload-time = "2026-06-30T07:15:50.847Z" }, + { url = "https://files.pythonhosted.org/packages/1e/16/5043105e679436ccfbc8e5e0dd2d663ed18a8b8113515fd06a5e5d77c83e/rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1cf01971c4f2c5553b772a542e4aaf191789cd331bc2cd4ff0e6e65ba49e1e97", size = 572431, upload-time = "2026-06-30T07:15:52.394Z" }, + { url = "https://files.pythonhosted.org/packages/85/ed/adab103321c0a6565d5ae1c2998349bc3ee175b82ccc5ae8fc04cc413075/rpds_py-2026.6.3-cp313-cp313-win32.whl", hash = "sha256:8c3d1e9c15b9d51ca0391e13da1a25a0a4df3c58a37c9dc368e0736cf7f69df0", size = 201710, upload-time = "2026-06-30T07:15:53.894Z" }, + { url = "https://files.pythonhosted.org/packages/7b/ed/a03b09668e74e5dabbf2e211f6468e1820c0552f7b0500082da31841bf7b/rpds_py-2026.6.3-cp313-cp313-win_amd64.whl", hash = "sha256:9250a9a0a6fd4648b3f868da8d91a4c52b5811a62df58e753d50ae4454a36f80", size = 219454, upload-time = "2026-06-30T07:15:55.25Z" }, + { url = "https://files.pythonhosted.org/packages/27/17/b8642c12930b71bc2b25831f6708ccf0f75abcd11883932ec9ce54ba3a78/rpds_py-2026.6.3-cp313-cp313-win_arm64.whl", hash = "sha256:900a67df3fd1660b035a4761c4ce73c382ea6b35f90f9863c36c6fd8bf8b09bb", size = 215063, upload-time = "2026-06-30T07:15:56.573Z" }, + { url = "https://files.pythonhosted.org/packages/b6/36/7fbe9dcdaf857fb3f63c2a2284b62492d95f5e8334e947e5fb6e7f68c9be/rpds_py-2026.6.3-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:931908d9fc855d8f74783377822be318edb6dcb19e47169dc038f9a1bf60b06e", size = 344510, upload-time = "2026-06-30T07:15:57.921Z" }, + { url = "https://files.pythonhosted.org/packages/ba/54/f785cc3d3f60839ca57a5af4927a9f347b07b2799c373fc20f7949f87c7e/rpds_py-2026.6.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d7469697dce35be237db177d42e2a2ee26e6dcc5fc052078a6fefabd288c6edd", size = 339495, upload-time = "2026-06-30T07:15:59.238Z" }, + { url = "https://files.pythonhosted.org/packages/63/ef/d4cdaf309e6b095b43597103cf8c0b951d6cca2acce68c474f75ec12e0c7/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bcfbcf66006befb9fd2aeaa9e01feaf881b4dc330a02ba07d2322b1c11be7b5d", size = 369454, upload-time = "2026-06-30T07:16:01.021Z" }, + { url = "https://files.pythonhosted.org/packages/96/4a/9559a68b7ee15db09d7981212e8c2e219d2a1d6d4faa0391d813c3496a36/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:847927daf4cffbd4e90e42bc890069897101edd015f956cb8721b3473372edda", size = 374583, upload-time = "2026-06-30T07:16:02.287Z" }, + { url = "https://files.pythonhosted.org/packages/ef/75/8964aa7d2c6e8ac43eba8eb6e6b0fdda1f46d39f2fc3e6aa9f2cb17f485d/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:aca6c1ef08a82bfe327cc156da694660f599923e2e6665b6d81c9c2d0ac9ffc8", size = 492919, upload-time = "2026-06-30T07:16:03.723Z" }, + { url = "https://files.pythonhosted.org/packages/8f/97/6908094ac804115e65aedfd90f1b5fee4eebebd3f6c4cfc5419939267565/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ae50181a047c871561212bb97f7932a2d45fb53e947bd9b57ebad85b529cbc53", size = 383725, upload-time = "2026-06-30T07:16:05.305Z" }, + { url = "https://files.pythonhosted.org/packages/d1/9c/0d1fdc2e7aba23e290d603bc494e97bd205bae262ce33c6b32a69768ed5e/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dc319e5a1de4b6913aac94bf6a2f9e847371e0a140a43dd4991db1a09bc2d504", size = 367255, upload-time = "2026-06-30T07:16:07.086Z" }, + { url = "https://files.pythonhosted.org/packages/c4/fe/f0209ca4a9ed074bc8acb44dfd0e81c3122e94c9689f5645b7973a866719/rpds_py-2026.6.3-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:e4316bf32babbed84e691e352faf967ce2f0f024174a8643c37c94a1080374fc", size = 379060, upload-time = "2026-06-30T07:16:08.525Z" }, + { url = "https://files.pythonhosted.org/packages/c6/8d/f1cc54c616b9d8897de8738aac148d20afca93f68187475fe194d09a71b9/rpds_py-2026.6.3-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8c6e5a2f750cc71c3e3b11d71661f21d6f9bc6cebc6564b1466417a1ec03ec77", size = 395960, upload-time = "2026-06-30T07:16:09.989Z" }, + { url = "https://files.pythonhosted.org/packages/fb/04/aafff00f73aeca2945f734f1d483c64ab8f472d0864ab02377fd8e89c3b2/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:4470ce197d4090875cf6affbf1f853338387428df97c4fb7b7106317b8214698", size = 545356, upload-time = "2026-06-30T07:16:11.816Z" }, + { url = "https://files.pythonhosted.org/packages/fd/cc/e229663b9e4ddac5a4acbe9085dd80a71af2a5d356b8b39d6bff233f24b0/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:ea964164cc9afa72d4d9b23cc28dafae93693c0a53e0b42acbff15b22c3f9ddd", size = 612319, upload-time = "2026-06-30T07:16:13.586Z" }, + { url = "https://files.pythonhosted.org/packages/e3/7a/8a0e6d3e6cd066af108b71b43122c3fe158dd9eb86acac626593a2582eb1/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:639c8929aa0afe81be836b04de888460d6bed38b9c54cfc18da8f6bfabf5af5d", size = 573508, upload-time = "2026-06-30T07:16:15.23Z" }, + { url = "https://files.pythonhosted.org/packages/87/03/2a69ab618a789cf6cf85c86bb844c62d090e700ab1a2aa676b3741b6c516/rpds_py-2026.6.3-cp314-cp314-win32.whl", hash = "sha256:882076c00c0a608b131187055ddc5ae29f2e7eaf870d6168980420d58528a5c8", size = 202504, upload-time = "2026-06-30T07:16:16.893Z" }, + { url = "https://files.pythonhosted.org/packages/85/62/a3892ba945f4e24c78f352e5de3c7620d8479f73f211406a97263d13c7d2/rpds_py-2026.6.3-cp314-cp314-win_amd64.whl", hash = "sha256:0be972be84cfcaf46c8c6edf690ca0f154ac17babf1f6a955a51579b34ad2dc5", size = 220380, upload-time = "2026-06-30T07:16:18.108Z" }, + { url = "https://files.pythonhosted.org/packages/3d/e7/c2bd44dc831931815ad11ebb5f430b5a0a4d3caa9de837107876c30c3432/rpds_py-2026.6.3-cp314-cp314-win_arm64.whl", hash = "sha256:2a9c6f195058cb45335e8cc3802745c603d716eb96bc9625950c1aac71c0c703", size = 215976, upload-time = "2026-06-30T07:16:19.654Z" }, + { url = "https://files.pythonhosted.org/packages/79/9c/fff7b74bce9a091ec9a012a03f9ff5f69364eaf9451060dfc4486da2ffdd/rpds_py-2026.6.3-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:f90938e92afda60266da758ee7d363447f7f0138c9559f9e1811629580582d90", size = 346840, upload-time = "2026-06-30T07:16:21.268Z" }, + { url = "https://files.pythonhosted.org/packages/e9/44/77bcb1168b33704908295533d27f10eb811e9e3e193e8993dc99572211d3/rpds_py-2026.6.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ec829541c45bca16e61c7ae50c20501f213605beb75d1aba91a6ee37fbbb56a4", size = 340282, upload-time = "2026-06-30T07:16:22.875Z" }, + { url = "https://files.pythonhosted.org/packages/87/3c/7a9081c7c9e645b39efe19e4ffbeccd80add246327cd9b888aecffd72317/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:afd70d95892096cdb26f15a00c45907b17817577aa8d1c76b2dcc2788391f9e9", size = 370403, upload-time = "2026-06-30T07:16:24.415Z" }, + { url = "https://files.pythonhosted.org/packages/f7/69/af47021eb7dad6ff3396cb001c08f0f3c4d06c20253f75be6421a59fe6b7/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:29dfa0533a5d4c94d4dfa1b694fcb56c9c63aad8330ffdd816fd225d0a7a162f", size = 376055, upload-time = "2026-06-30T07:16:26.111Z" }, + { url = "https://files.pythonhosted.org/packages/81/fc/a3bcf517084396a6dd258c592567a3c011ba4557f2fde23dceaf26e74f2e/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:af05d726809bff6b141be124d4c7ce998f9c9c7f30edb1f46c07aa103d540b41", size = 494419, upload-time = "2026-06-30T07:16:27.596Z" }, + { url = "https://files.pythonhosted.org/packages/c9/eb/13d529d1788135425c7bf207f8463458ca5d92e43f3f701365b83e9dffc1/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9826217f048f620d9a712672818bf231442c1b35d96b227a07eabd11b4bb6945", size = 384848, upload-time = "2026-06-30T07:16:29.183Z" }, + { url = "https://files.pythonhosted.org/packages/8e/f4/b7ac49f30013aba8f7b9566b1dd07e81de95e708c1374b7bacc5b9bc5c9c/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:536bceea4fa4acf7e1c61da2b5786304367c816c8895be71b8f537c480b0ea1f", size = 371369, upload-time = "2026-06-30T07:16:30.912Z" }, + { url = "https://files.pythonhosted.org/packages/31/86/6260bafa622f788b07ddec0e52d810305c8b9b0b8c27f58a2ab04bf62b4f/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:bc0011654b91cc4fb2ae701bec0a0ba1e552c0714247fa7af6c59e0ccfa3a4e1", size = 379673, upload-time = "2026-06-30T07:16:32.486Z" }, + { url = "https://files.pythonhosted.org/packages/19/c3/03f1ee79a047b48daeca157c89a18509cde22b6b951d642b9b0af1be660a/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:539d75de9e0d536c84ff18dfeb805398e58227001ce09231a26a08b9aed1ee0e", size = 397500, upload-time = "2026-06-30T07:16:34.471Z" }, + { url = "https://files.pythonhosted.org/packages/f0/95/8ed0cd8c377dca12aea498f119fe639fc474d1461545c39d2b5872eb1c0f/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:166cf54d9f44fc6ceb53c7860258dde44a81406646de79f8ed3234fca3b6e538", size = 545978, upload-time = "2026-06-30T07:16:36.45Z" }, + { url = "https://files.pythonhosted.org/packages/d3/f2/0eb57f0eaa83f8fc152a7e03de968ab77e1f00732bebc892b190c6eebde7/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:d34c20167764fbcf927194d532dd7e0c56772f0a5f943fa5ef9e9afbba8fb9db", size = 613350, upload-time = "2026-06-30T07:16:38.213Z" }, + { url = "https://files.pythonhosted.org/packages/5b/de/e0674bdbc3ef7634989b3f854c3f34bc1f587d36e5bfdc5c378d57034619/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ea7bb13b7c9a29791f87a0387ba7d3ad3a6d783d827e4d3f27b40a0ff44495e2", size = 576486, upload-time = "2026-06-30T07:16:39.797Z" }, + { url = "https://files.pythonhosted.org/packages/f2/f6/21101359743cd136ada781e8210a85769578422ba460672eea0e29739200/rpds_py-2026.6.3-cp314-cp314t-win32.whl", hash = "sha256:6de4744d05bd1aa1be4ed7ea1189e3979196808008113bbbf899a460966b925e", size = 201068, upload-time = "2026-06-30T07:16:41.316Z" }, + { url = "https://files.pythonhosted.org/packages/a6/b2/9574d4d44f7760c2aa32d92a0a4f41698e33f5b204a0bf5c9758f52c79d5/rpds_py-2026.6.3-cp314-cp314t-win_amd64.whl", hash = "sha256:c7b9a2f8f4d8e90af72571d3d495deebdd7e3c75451f5b41719aee166e940fc2", size = 220600, upload-time = "2026-06-30T07:16:43.091Z" }, + { url = "https://files.pythonhosted.org/packages/08/ae/f23a2697e6ee6340a578b0f136be6483657bef0c6f9497b752bb5c0964bb/rpds_py-2026.6.3-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:e059c5dde6452b44424bd1834557556c226b57781dee1227af23518459722b13", size = 344726, upload-time = "2026-06-30T07:16:44.5Z" }, + { url = "https://files.pythonhosted.org/packages/c3/63/e7b3a1a5358dd32c930a1062d8e15b67fd6e8922e81df9e91706d66ee5c8/rpds_py-2026.6.3-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2f7c26fbc5acd2522b95d4177fe4710ffd8e9b20529e703ffbf8db4d93903f05", size = 339587, upload-time = "2026-06-30T07:16:46.255Z" }, + { url = "https://files.pythonhosted.org/packages/ec/64/10a85681916ca55fffb91b0a211f84e34297c109243484dd6394660a8a7c/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a3086b538543802f84c843911242db20447de00d8752dd0efc936dbcf02218ba", size = 369585, upload-time = "2026-06-30T07:16:48.101Z" }, + { url = "https://files.pythonhosted.org/packages/76/c2/baf95c7c38823e12ba34407c5f5767a89e5cf2233895e56f608167ae9493/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8f2e5c5ee828d42cb11760761c0af6507927bec42d0ad5458f97c9203b054617", size = 375479, upload-time = "2026-06-30T07:16:49.93Z" }, + { url = "https://files.pythonhosted.org/packages/6a/94/0aad06c72d65101e11d33528d438cda99a39ce0da99466e156158f2541d3/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ed0c1e5d10cdc7135537988c74a0188da68e2f3c30813ba3744ab1e42e0480f9", size = 492418, upload-time = "2026-06-30T07:16:51.641Z" }, + { url = "https://files.pythonhosted.org/packages/b5/17/de3f5a479a1f056535d7489819639d8cd591ea6281d700390b43b1abd745/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8c2642a7603ec0b16ed77da4555db3b4b472341904873788327c0b0d7b95f1bb", size = 384123, upload-time = "2026-06-30T07:16:53.622Z" }, + { url = "https://files.pythonhosted.org/packages/46/7d/bf09bd1b145bb2671c03e1e6d1ab8651858d90d8c7dfeadd85a37a934fd8/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8e4320744c1ffdd95a603def63344bfab2d33edeab301c5007e7de9f9f5b3885", size = 367351, upload-time = "2026-06-30T07:16:55.241Z" }, + { url = "https://files.pythonhosted.org/packages/a3/ea/1bb734f314b8be319149ddee80b18bd41372bdcfbdf88d28131c0cd37719/rpds_py-2026.6.3-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:a9f4645593036b81bbdb36b9c8e0ea0d1c3fee968c4d59db0344c14087ef143a", size = 378827, upload-time = "2026-06-30T07:16:56.841Z" }, + { url = "https://files.pythonhosted.org/packages/4b/93/d9611e5b25e26df9a3649813ed66193ace9347a7c7fc4ab7cf70e94851c0/rpds_py-2026.6.3-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e55d236be29255554da47abe5c577637db7c24a02b8b46f0ca9524c855801868", size = 395966, upload-time = "2026-06-30T07:16:58.557Z" }, + { url = "https://files.pythonhosted.org/packages/c3/cb/99d77e16e5534ae1d90629bbe419ba6ee170833a6a85e3aa1cc41726fbbc/rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:24e9c5386e16669b674a69c156c8eeefcb578f3b3397b713b08e6d60f3c7b187", size = 545680, upload-time = "2026-06-30T07:17:00.164Z" }, + { url = "https://files.pythonhosted.org/packages/59/15/11a29755f790cef7a2f755e8e14f4f0c33f39489e1893a632a2eee59672b/rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:c60924535c75f1566b6eb75b5c31a48a43fef04fa2d0d201acbad8a9969c6107", size = 611853, upload-time = "2026-06-30T07:17:01.962Z" }, + { url = "https://files.pythonhosted.org/packages/68/86/0c27547e21644da938fb530f7e1a8148dd24d02db07e7a5f2567a17ce710/rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:38a2fea2787428f811719ceb9114cb78964a3138838320c29ac39526c79c16ba", size = 573715, upload-time = "2026-06-30T07:17:03.693Z" }, + { url = "https://files.pythonhosted.org/packages/29/71/4d8fcf700931815594bce892255bbd973b94efaf0fc1932b0590df18d886/rpds_py-2026.6.3-cp315-cp315-win32.whl", hash = "sha256:d483fe17f01ad64b7bf7cc38fcefff1ca9fb83f8c2b2542b68f97ffe0611b369", size = 202864, upload-time = "2026-06-30T07:17:05.746Z" }, + { url = "https://files.pythonhosted.org/packages/eb/62/b577562de0edbb55b2be85ce5fd09c33e386b9b13eee09833af4240fd5c4/rpds_py-2026.6.3-cp315-cp315-win_amd64.whl", hash = "sha256:67e3a721ffc5d8d2210d3671872298c4a84e4b8035cfe42ffd7cde35d772b146", size = 220430, upload-time = "2026-06-30T07:17:07.471Z" }, + { url = "https://files.pythonhosted.org/packages/c8/95/d6d0b2509825141eef60669a5739eec88dbc6a48053d6c92993a5704defe/rpds_py-2026.6.3-cp315-cp315-win_arm64.whl", hash = "sha256:6e84adbcf4bf841aed8116a8264b9f50b4cb3e7bd89b516122e616ac56ca269e", size = 215877, upload-time = "2026-06-30T07:17:09.008Z" }, + { url = "https://files.pythonhosted.org/packages/b7/bf/f3ea278f0afd615c1d0f19cb69043a41526e2bb600c2b536eb192218eb27/rpds_py-2026.6.3-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:ae6dd8f10bd17aad820876d24caec9efdafd80a318d16c0a48edb5e136902c6b", size = 346933, upload-time = "2026-06-30T07:17:10.762Z" }, + { url = "https://files.pythonhosted.org/packages/9d/29/9907bdf1c5346763cf10b7f6852aad86652168c259def904cbe0082c5864/rpds_py-2026.6.3-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:bdbd97738551fca3917c1bd7188bec1920bb520104f28e7e1007f9ceb17b7690", size = 340274, upload-time = "2026-06-30T07:17:12.266Z" }, + { url = "https://files.pythonhosted.org/packages/6f/2c/8e03767b5778ef25cebf74a7a91a2c3806f8eced4c92cb7406bbe060756d/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8b95977e7211527ab0ba576e286d023389fbeeb32a6b7b771665d333c60e5342", size = 370763, upload-time = "2026-06-30T07:17:14.107Z" }, + { url = "https://files.pythonhosted.org/packages/2e/e1/df2a7e1ba2efd796af26194250b8d42c821b46592311595162af9ef0528d/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d15fde0e6fb0d88a60d221204873743e5d9f0b7d29165e62cd86d0413ad74ba6", size = 376467, upload-time = "2026-06-30T07:17:15.76Z" }, + { url = "https://files.pythonhosted.org/packages/6b/de/8a0814d1946af29cb068fb259aa8622f856df1d0bab58429448726b537f5/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a136d453475ac0fcbda502ef1e6504bd28d6d904700915d278deeab0d00fe140", size = 496689, upload-time = "2026-06-30T07:17:17.308Z" }, + { url = "https://files.pythonhosted.org/packages/df/f3/f19e0c852ba13694f5a79f3b719331051573cb5693feacf8a88ffffc3a71/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f826877d462181e5eb1c26a0026b8d0cab05d99844ecb6d8bf3627a2ca0c0442", size = 385340, upload-time = "2026-06-30T07:17:18.928Z" }, + { url = "https://files.pythonhosted.org/packages/e2/ae/7ec3a9d2d4351f99e37bcb06b6b6f954512646bfdbf9742e1de727865daf/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:79486287de1730dbaff3dbd124d0ca4d2ef7f9d29bf2544f1f93c09b5bcbbd12", size = 372179, upload-time = "2026-06-30T07:17:20.539Z" }, + { url = "https://files.pythonhosted.org/packages/d3/ac/9cee911dff2aaa9a5a8354f6610bf2e6a616de9197c5fff4f54f82585f1e/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:808345f53cb952433ca2816f1604ff3515608a81784954f38d4452acfe8e61d5", size = 379993, upload-time = "2026-06-30T07:17:22.212Z" }, + { url = "https://files.pythonhosted.org/packages/83/6b/7c2a07ba88d1e9a936612f7a5d067467ed03d971d5a06f7d309dff044a7e/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1967debc37f64f2c4dc90a7f563aec558b471966e12adcac4e1c4240496b6ebf", size = 398909, upload-time = "2026-06-30T07:17:23.66Z" }, + { url = "https://files.pythonhosted.org/packages/97/0b/776ffcb66783637b0031f6d58d6fb55913c8b5abf00aeecd46bf933fb477/rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:f0840b5b17057f7fd918b76183a4b5a0635f43e14eb2ce60dce1d4ee4707ea00", size = 546584, upload-time = "2026-06-30T07:17:25.264Z" }, + { url = "https://files.pythonhosted.org/packages/55/33/ba3bc04d7092bd553c9b2b195624992d2cc4f3de1f380b7b93cbee67bd79/rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:faa679d19a6696fd54259ad321251ad77a13e70e03dd834daa762a44fb6196ef", size = 614357, upload-time = "2026-06-30T07:17:26.888Z" }, + { url = "https://files.pythonhosted.org/packages/8b/71/14edf065f04630b1a8472f7653cad03f6c478bcf95ea0e6aed55451e33ea/rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:23a439f31ccbeff1574e24889128821d1f7917470e830cf6544dced1c662262a", size = 576533, upload-time = "2026-06-30T07:17:28.546Z" }, + { url = "https://files.pythonhosted.org/packages/ba/76/65002b08596c389105720a8c0d22298b8dc25a4baf89b2ce431343c8b1de/rpds_py-2026.6.3-cp315-cp315t-win32.whl", hash = "sha256:913ca42ccad3f8cc6e292b587ae8ae49c8c823e5dce51a736252fc7c7cdfa577", size = 201204, upload-time = "2026-06-30T07:17:30.193Z" }, + { url = "https://files.pythonhosted.org/packages/8c/97/d855d6b3c322d1f27e26f5241c42016b56cf01377ea8ed348285f54652f0/rpds_py-2026.6.3-cp315-cp315t-win_amd64.whl", hash = "sha256:ae3d4fe8c0b9213624fdce7279d70e3b148b682ca20719ebd193a23ebfa47324", size = 220719, upload-time = "2026-06-30T07:17:31.788Z" }, +] + +[[package]] +name = "ruff" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/4d/94/1e5e4967626faf12fa56999cd6222dff6992ceb086ad7945756baf70c7a7/ruff-0.16.0.tar.gz", hash = "sha256:e460aafd5495ec89efaa6ced2e4a9a581116451e1c88b9d37ef497e0f8e93982", size = 4790557, upload-time = "2026-07-23T19:11:30.981Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4b/81/1c8818fee7ce1a04cd7d1b3172e0a8f8e4f1dc4feb7fc390e16daa8af323/ruff-0.16.0-py3-none-linux_armv6l.whl", hash = "sha256:e5115729eb08c585e5121978ba5d5b60caeae394ce21b9fb5e6cd33a1c6c9b1e", size = 10754633, upload-time = "2026-07-23T19:10:46.415Z" }, + { url = "https://files.pythonhosted.org/packages/23/df/beaf59c09d68db84304d555f188b276a77132a5d5b0b67a5c762aa143628/ruff-0.16.0-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:3c954b1d580bfa035b41654f7858cc7e71d5fc3ac5b723dd62bd9133830ed522", size = 10969164, upload-time = "2026-07-23T19:10:50.271Z" }, + { url = "https://files.pythonhosted.org/packages/42/ce/741cd197496a1abbf51352710fd15ed995d2a2be87189c1da26a450d6e83/ruff-0.16.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:e01c21d10eb1b29f47b7454e1f4056db9a3f0260c646aa88457c610291db9f81", size = 10488846, upload-time = "2026-07-23T19:10:52.639Z" }, + { url = "https://files.pythonhosted.org/packages/52/2a/a2db8e88cade358f5cdcb05674a917751074109315d014eb6352d9a893f7/ruff-0.16.0-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6e364e5ed22ed8dc05082fd78e35308618260907ac2d3c1d637b2e682415b6c9", size = 10889729, upload-time = "2026-07-23T19:10:54.89Z" }, + { url = "https://files.pythonhosted.org/packages/42/65/62a771694ebd63029dc953e27dbad40e1588bd4860ff9fe881018fddaa49/ruff-0.16.0-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d327b8fc113a1d4421a04f3839d3752057c8dd1ee320223a6f3f52d04ada462a", size = 10568275, upload-time = "2026-07-23T19:10:56.993Z" }, + { url = "https://files.pythonhosted.org/packages/3f/e2/ced249fe8af5f086c5c58cc21cc3356d50f32f7401c5df87050c999620a7/ruff-0.16.0-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a9b50c55e263103586b3dcf5f73d479eb8cb5fdb6098fec59a62891dab653717", size = 11385112, upload-time = "2026-07-23T19:10:59.615Z" }, + { url = "https://files.pythonhosted.org/packages/87/0b/05154977a8fd69eeb6c103271f55403bfd8711f5c0f8ed07489d95a504e7/ruff-0.16.0-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0ff4a79ce3ec0172f3241943835de1c4cb4e2dcd07f0f8c2d02603dbbbee4b17", size = 12207008, upload-time = "2026-07-23T19:11:02.154Z" }, + { url = "https://files.pythonhosted.org/packages/fb/29/98225831a3a1eab0e02f4acc6ca6559a98611dcc68b6965ff4b7234627c1/ruff-0.16.0-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e95c448fca1fb2a18372a9440926c5a6ee789639bb975c72e7ae6d0b04218ab4", size = 11650842, upload-time = "2026-07-23T19:11:04.557Z" }, + { url = "https://files.pythonhosted.org/packages/91/66/6bd3cf90500653d55dc0ffc8507aa8300bd49d0214b2e8cb4d3fef2943ba/ruff-0.16.0-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4f11a8d11010301d0a398a2fdef67691feca7294da6aef55e2150e8fa2cd520b", size = 11400718, upload-time = "2026-07-23T19:11:09.233Z" }, + { url = "https://files.pythonhosted.org/packages/8e/a2/a54eb4eae05d66364050a5d3b8a9c5ef88196531b3cbe7109d873f87f819/ruff-0.16.0-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:48044c678e9cb8698246c99b14aaccfa6601dea7379eb48a6f8f73f7a6d86cd0", size = 11426177, upload-time = "2026-07-23T19:11:11.994Z" }, + { url = "https://files.pythonhosted.org/packages/1a/be/16e3eea4b2a478a496919f5e36f17c4559e54620bd3bbac5d6affa068006/ruff-0.16.0-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:7aa0959bad8eb8bef50340154fc9b58678dae31fa4293afa38b44b6e552c0213", size = 10856126, upload-time = "2026-07-23T19:11:14.221Z" }, + { url = "https://files.pythonhosted.org/packages/a2/84/252eb8b868a16eec7257c14f504f77537e734b2d69c762e639e588e304a3/ruff-0.16.0-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:28ea2b7df8ebf7f9da6b7d47b230ab48f387c0a29be3b474c4d0740e197bb9af", size = 10571208, upload-time = "2026-07-23T19:11:16.378Z" }, + { url = "https://files.pythonhosted.org/packages/21/09/817a482f542f7570cbb4554b26e896610c7114f539b1d9e2d2145bf6bef6/ruff-0.16.0-py3-none-musllinux_1_2_i686.whl", hash = "sha256:33a3dfac8c35f81498dea9181bccc2f4c4bc8f1521a1dd9406e77643e0f0fb09", size = 11063329, upload-time = "2026-07-23T19:11:19.173Z" }, + { url = "https://files.pythonhosted.org/packages/2e/23/9403c180ca1cb9b1f7335f5c3e5305c09d49ea5b345196682a36028bde4a/ruff-0.16.0-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:a5237a0bda500d30d81b8e07a6973a5cbc772864cbf746ae2f4e8a2e01c9f4ed", size = 11489751, upload-time = "2026-07-23T19:11:21.74Z" }, + { url = "https://files.pythonhosted.org/packages/b2/1d/1b2ef7bcde851c78d7f17f1cca13fd6dc695fc4b3d6197941e72cae5b132/ruff-0.16.0-py3-none-win32.whl", hash = "sha256:7fab76fa065c873f41ff744347c6e77bcc3dfec4bcc754dc26b63d23c0f7f5fb", size = 10785885, upload-time = "2026-07-23T19:11:23.947Z" }, + { url = "https://files.pythonhosted.org/packages/b2/a3/d5e4ef7a56be3f928ffb90b94c25ba7d3cb9c7fe0736aeaaedf361770712/ruff-0.16.0-py3-none-win_amd64.whl", hash = "sha256:429c117f022bf481fabd9d551e7a3952b24c65e6ef44337ea09d90bebef14472", size = 11923141, upload-time = "2026-07-23T19:11:26.409Z" }, + { url = "https://files.pythonhosted.org/packages/cb/9a/8415f2657cbe200f41a4531ccededf135505a92d4a012229121f885b26f9/ruff-0.16.0-py3-none-win_arm64.whl", hash = "sha256:14296fedcd2705c77ab8235439278bbb38f285cf7da5528b00b3e330c3d4872d", size = 11273407, upload-time = "2026-07-23T19:11:28.705Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + +[[package]] +name = "sortedcontainers" +version = "2.4.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e8/c4/ba2f8066cceb6f23394729afe52f3bf7adec04bf9ed2c820b39e19299111/sortedcontainers-2.4.0.tar.gz", hash = "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88", size = 30594, upload-time = "2021-05-16T22:03:42.897Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl", hash = "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0", size = 29575, upload-time = "2021-05-16T22:03:41.177Z" }, +] + +[[package]] +name = "stack-data" +version = "0.6.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "asttokens" }, + { name = "executing" }, + { name = "pure-eval" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/28/e3/55dcc2cfbc3ca9c29519eb6884dd1415ecb53b0e934862d3559ddcb7e20b/stack_data-0.6.3.tar.gz", hash = "sha256:836a778de4fec4dcd1dcd89ed8abff8a221f58308462e1c4aa2a3cf30148f0b9", size = 44707, upload-time = "2023-09-30T13:58:05.479Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl", hash = "sha256:d5558e0c25a4cb0853cddad3d77da9891a08cb85dd9f9f91b9f8cd66e511e695", size = 24521, upload-time = "2023-09-30T13:58:03.53Z" }, +] + +[[package]] +name = "starlette" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/eb/e3/7c1dc7381d9f8ab7d854328ebfa884e62cb3f3d8549ddfd37c7814f42afa/starlette-1.3.1.tar.gz", hash = "sha256:05d0213193f2fbaae60e2ecb593b4add4262ad4e46536b54abe36f11a71724e0", size = 2703240, upload-time = "2026-06-12T09:23:11.602Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl", hash = "sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6", size = 73632, upload-time = "2026-06-12T09:23:10.017Z" }, +] + +[[package]] +name = "tornado" +version = "6.5.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/10/d3/343e5bb989d6515b1646cf3d40135d73f3d5e45339bded401b56cdac24dd/tornado-6.5.8.tar.gz", hash = "sha256:9452e1b208a8bd771e2cb1f2ff564985b9b214bdebbe622793e1799e0a6bd23f", size = 520493, upload-time = "2026-08-07T02:12:42.971Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f2/d5/007086fd8df5489338e204f65adce33fd4f21a4999dbb2b9cff2f897b5f4/tornado-6.5.8-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:cc6aa787d7cfab7c3d35189dc7a56fbd2399a569624c730c6b55b3d6531d0403", size = 449487, upload-time = "2026-08-07T02:12:28.682Z" }, + { url = "https://files.pythonhosted.org/packages/70/c8/5a24a99495903f594f6a199dd7beead1cbc0a13e2cb9102727bcaaf2a997/tornado-6.5.8-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:9715b5eb79735b2bcd454ce216a9275b7c0470e64ea1bf5742f78b2f72b26eeb", size = 447649, upload-time = "2026-08-07T02:12:30.306Z" }, + { url = "https://files.pythonhosted.org/packages/6e/de/f2e733f386b85962d1b1dc82cd63d169b5b4580062b35397eac9244a41fe/tornado-6.5.8-cp39-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:547d63f450d570c14fe0e8db2cfb14c9bbd1c2503b4a6612586267955aa47b58", size = 450707, upload-time = "2026-08-07T02:12:31.95Z" }, + { url = "https://files.pythonhosted.org/packages/0b/94/20efeee9a01c141e9ac47c397f81679dfda24b32768fc4fff24e76d36c2c/tornado-6.5.8-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7e2360a0ffbe145eca8af0b19cb7203d79b1a98dd4cccdd6b368f6f49c2e3808", size = 451677, upload-time = "2026-08-07T02:12:33.512Z" }, + { url = "https://files.pythonhosted.org/packages/42/ec/a96ccb8ccf0de2b7bc2c5fa1608a4803735018242e90c4882365a9fd418f/tornado-6.5.8-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:5d242290bdf7ab3151bc1065fdd75c0dcc21cbc7b49f22a4c56329c2d6566d22", size = 451510, upload-time = "2026-08-07T02:12:35.346Z" }, + { url = "https://files.pythonhosted.org/packages/29/b5/93185859245ad3f00e62175f29607346788b696369347f0146e0421286bb/tornado-6.5.8-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7b94ff0e128fe0542f3bd331fb44d06260fc4ac16881545159f34ef08aad4195", size = 450917, upload-time = "2026-08-07T02:12:36.963Z" }, + { url = "https://files.pythonhosted.org/packages/97/cf/fe33cf062834487d34d1559746a4a12521033c22645b6d74d4bca702e018/tornado-6.5.8-cp39-abi3-win32.whl", hash = "sha256:67832909c4779c64942380cb5f044a5c6163d00831472d80e25e115de9917836", size = 451952, upload-time = "2026-08-07T02:12:38.512Z" }, + { url = "https://files.pythonhosted.org/packages/cb/e1/468ad54333e92ccb62627e62cb88e5fc14a2171daa67ed47b1b8542d5b86/tornado-6.5.8-cp39-abi3-win_amd64.whl", hash = "sha256:11881db6b7c168494be2c2d12e65931451bdf7ee718535418ae1d8855dd5a0ee", size = 452391, upload-time = "2026-08-07T02:12:39.971Z" }, + { url = "https://files.pythonhosted.org/packages/ad/3e/cd5e4f06e34cde33b8ef66cf36aa2b5ad46354cc1af7d2136bbe365fee1d/tornado-6.5.8-cp39-abi3-win_arm64.whl", hash = "sha256:68a7468c7e289f8514d7d664101753903217eff1bb6822c6b5994a0b5f5bcb26", size = 451411, upload-time = "2026-08-07T02:12:41.469Z" }, +] + +[[package]] +name = "traitlets" +version = "5.16.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2c/2e/a7fbfe268c8a3b32546930c0297c101d65a4a14c304ad5790a9f478f0e4e/traitlets-5.16.1.tar.gz", hash = "sha256:ed900c2b631aa3a112811139fa97b8d2c3bad5e989656bba4b7e52c7852c18c1", size = 166137, upload-time = "2026-08-03T08:32:36.848Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ad/66/0d785f0bc5e4315a96c989bb476d0fc07ea4f85132550c7b156ca2035d52/traitlets-5.16.1-py3-none-any.whl", hash = "sha256:f775618166caa0396c8e337099240f2bd3e5e917d203b2e6fbe21a58d3cb1f6b", size = 86211, upload-time = "2026-08-03T08:32:34.48Z" }, +] + +[[package]] +name = "truststore" +version = "0.10.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/53/a3/1585216310e344e8102c22482f6060c7a6ea0322b63e026372e6dcefcfd6/truststore-0.10.4.tar.gz", hash = "sha256:9d91bd436463ad5e4ee4aba766628dd6cd7010cf3e2461756b3303710eebc301", size = 26169, upload-time = "2025-08-12T18:49:02.73Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/19/97/56608b2249fe206a67cd573bc93cd9896e1efb9e98bce9c163bcdc704b88/truststore-0.10.4-py3-none-any.whl", hash = "sha256:adaeaecf1cbb5f4de3b1959b42d41f6fab57b2b1666adb59e89cb0b53361d981", size = 18660, upload-time = "2025-08-12T18:49:01.46Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "urllib3" +version = "2.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, +] + +[[package]] +name = "uvicorn" +version = "0.51.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a2/65/b7c6c443ccc58678c91e1e973bbe2a878591538655d6e1d47f24ba1c51f3/uvicorn-0.51.0.tar.gz", hash = "sha256:f6f4b69b657c312f516dd2d268ab9ae6f254b11e4bac504f37b2ab58b24dd0b0", size = 94412, upload-time = "2026-07-08T10:59:05.962Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/45/ec/dbb7e5a6b91f86bfb9eb7d2988a2730907b6a729875b949c7f022e8b88fa/uvicorn-0.51.0-py3-none-any.whl", hash = "sha256:5d38af6cd620f2ae3849fb44fd4879e0890aa1febe8d47eb355fb45d93fe6a5b", size = 73219, upload-time = "2026-07-08T10:59:04.44Z" }, +] + +[[package]] +name = "watchdog" +version = "6.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/db/7d/7f3d619e951c88ed75c6037b246ddcf2d322812ee8ea189be89511721d54/watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282", size = 131220, upload-time = "2024-11-01T14:07:13.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/ea/3930d07dafc9e286ed356a679aa02d777c06e9bfd1164fa7c19c288a5483/watchdog-6.0.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:bdd4e6f14b8b18c334febb9c4425a878a2ac20efd1e0b231978e7b150f92a948", size = 96471, upload-time = "2024-11-01T14:06:37.745Z" }, + { url = "https://files.pythonhosted.org/packages/12/87/48361531f70b1f87928b045df868a9fd4e253d9ae087fa4cf3f7113be363/watchdog-6.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c7c15dda13c4eb00d6fb6fc508b3c0ed88b9d5d374056b239c4ad1611125c860", size = 88449, upload-time = "2024-11-01T14:06:39.748Z" }, + { url = "https://files.pythonhosted.org/packages/5b/7e/8f322f5e600812e6f9a31b75d242631068ca8f4ef0582dd3ae6e72daecc8/watchdog-6.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6f10cb2d5902447c7d0da897e2c6768bca89174d0c6e1e30abec5421af97a5b0", size = 89054, upload-time = "2024-11-01T14:06:41.009Z" }, + { url = "https://files.pythonhosted.org/packages/68/98/b0345cabdce2041a01293ba483333582891a3bd5769b08eceb0d406056ef/watchdog-6.0.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:490ab2ef84f11129844c23fb14ecf30ef3d8a6abafd3754a6f75ca1e6654136c", size = 96480, upload-time = "2024-11-01T14:06:42.952Z" }, + { url = "https://files.pythonhosted.org/packages/85/83/cdf13902c626b28eedef7ec4f10745c52aad8a8fe7eb04ed7b1f111ca20e/watchdog-6.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:76aae96b00ae814b181bb25b1b98076d5fc84e8a53cd8885a318b42b6d3a5134", size = 88451, upload-time = "2024-11-01T14:06:45.084Z" }, + { url = "https://files.pythonhosted.org/packages/fe/c4/225c87bae08c8b9ec99030cd48ae9c4eca050a59bf5c2255853e18c87b50/watchdog-6.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a175f755fc2279e0b7312c0035d52e27211a5bc39719dd529625b1930917345b", size = 89057, upload-time = "2024-11-01T14:06:47.324Z" }, + { url = "https://files.pythonhosted.org/packages/a9/c7/ca4bf3e518cb57a686b2feb4f55a1892fd9a3dd13f470fca14e00f80ea36/watchdog-6.0.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7607498efa04a3542ae3e05e64da8202e58159aa1fa4acddf7678d34a35d4f13", size = 79079, upload-time = "2024-11-01T14:06:59.472Z" }, + { url = "https://files.pythonhosted.org/packages/5c/51/d46dc9332f9a647593c947b4b88e2381c8dfc0942d15b8edc0310fa4abb1/watchdog-6.0.0-py3-none-manylinux2014_armv7l.whl", hash = "sha256:9041567ee8953024c83343288ccc458fd0a2d811d6a0fd68c4c22609e3490379", size = 79078, upload-time = "2024-11-01T14:07:01.431Z" }, + { url = "https://files.pythonhosted.org/packages/d4/57/04edbf5e169cd318d5f07b4766fee38e825d64b6913ca157ca32d1a42267/watchdog-6.0.0-py3-none-manylinux2014_i686.whl", hash = "sha256:82dc3e3143c7e38ec49d61af98d6558288c415eac98486a5c581726e0737c00e", size = 79076, upload-time = "2024-11-01T14:07:02.568Z" }, + { url = "https://files.pythonhosted.org/packages/ab/cc/da8422b300e13cb187d2203f20b9253e91058aaf7db65b74142013478e66/watchdog-6.0.0-py3-none-manylinux2014_ppc64.whl", hash = "sha256:212ac9b8bf1161dc91bd09c048048a95ca3a4c4f5e5d4a7d1b1a7d5752a7f96f", size = 79077, upload-time = "2024-11-01T14:07:03.893Z" }, + { url = "https://files.pythonhosted.org/packages/2c/3b/b8964e04ae1a025c44ba8e4291f86e97fac443bca31de8bd98d3263d2fcf/watchdog-6.0.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:e3df4cbb9a450c6d49318f6d14f4bbc80d763fa587ba46ec86f99f9e6876bb26", size = 79078, upload-time = "2024-11-01T14:07:05.189Z" }, + { url = "https://files.pythonhosted.org/packages/62/ae/a696eb424bedff7407801c257d4b1afda455fe40821a2be430e173660e81/watchdog-6.0.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:2cce7cfc2008eb51feb6aab51251fd79b85d9894e98ba847408f662b3395ca3c", size = 79077, upload-time = "2024-11-01T14:07:06.376Z" }, + { url = "https://files.pythonhosted.org/packages/b5/e8/dbf020b4d98251a9860752a094d09a65e1b436ad181faf929983f697048f/watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:20ffe5b202af80ab4266dcd3e91aae72bf2da48c0d33bdb15c66658e685e94e2", size = 79078, upload-time = "2024-11-01T14:07:07.547Z" }, + { url = "https://files.pythonhosted.org/packages/07/f6/d0e5b343768e8bcb4cda79f0f2f55051bf26177ecd5651f84c07567461cf/watchdog-6.0.0-py3-none-win32.whl", hash = "sha256:07df1fdd701c5d4c8e55ef6cf55b8f0120fe1aef7ef39a1c6fc6bc2e606d517a", size = 79065, upload-time = "2024-11-01T14:07:09.525Z" }, + { url = "https://files.pythonhosted.org/packages/db/d9/c495884c6e548fce18a8f40568ff120bc3a4b7b99813081c8ac0c936fa64/watchdog-6.0.0-py3-none-win_amd64.whl", hash = "sha256:cbafb470cf848d93b5d013e2ecb245d4aa1c8fd0504e863ccefa32445359d680", size = 79070, upload-time = "2024-11-01T14:07:10.686Z" }, + { url = "https://files.pythonhosted.org/packages/33/e8/e40370e6d74ddba47f002a32919d91310d6074130fe4e17dabcafc15cbf1/watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f", size = 79067, upload-time = "2024-11-01T14:07:11.845Z" }, +] + +[[package]] +name = "wcwidth" +version = "0.8.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/34/74/c6428f875774288bec1396f5bfcbc2d925700a4dad61727fd5f2b12f249d/wcwidth-0.8.2.tar.gz", hash = "sha256:91fbef97204b96a3d4d421609b80340b760cf33e26da123ff243d76b1fda8dda", size = 1466253, upload-time = "2026-06-29T18:11:11.601Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/96/42/3e5985a0a7e57de470b320c6d6a1a67c844f6737a587f3d44dd13d1819e7/wcwidth-0.8.2-py3-none-any.whl", hash = "sha256:d63947694a0539a1d51e01eda7caf800c291020e6cdd7e28ad7b14dd33ad4f85", size = 323166, upload-time = "2026-06-29T18:11:09.888Z" }, +] + +[[package]] +name = "yarl" +version = "1.24.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "multidict" }, + { name = "propcache" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/31/33/ebe9e3d1f86c7a0b51094c0a146392045ca1631d2664889539dec8088a33/yarl-1.24.5.tar.gz", hash = "sha256:e81b83143bee16329c23db3c1b2d82b29892fcbcb849186d2f6e98a5abe9a57f", size = 228679, upload-time = "2026-07-20T02:07:45.435Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1b/84/71d051c850b5af41d168c679d9eb67eb7c55283ac4ee131673edf134bc4e/yarl-1.24.5-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:d693396e5aea78db03decd60aec9ece16c9b40ba00a587f089615ff4e718a81d", size = 136035, upload-time = "2026-07-20T02:05:25.489Z" }, + { url = "https://files.pythonhosted.org/packages/03/4d/8ad27f9a1b7e69313cca5d695b925b48efe51208d3490e0844bae97cabc0/yarl-1.24.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3363fcc96e665878946ad7a106b9a13eac0541766a690ef287c0232ac768b6ec", size = 97642, upload-time = "2026-07-20T02:05:27.429Z" }, + { url = "https://files.pythonhosted.org/packages/ea/b4/05b4131c407006cd1e410e9c6539f16a0945724677e5364447313c15ea3e/yarl-1.24.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:9d399bdcfb4a0f659b9b3788bbc89babe63d9a6a65aacdf4d4e7065ff2e6316c", size = 97323, upload-time = "2026-07-20T02:05:29.441Z" }, + { url = "https://files.pythonhosted.org/packages/20/16/e618c875c73e0e39611f20a581b3d5e8d59b8857bf001bee3263044c6deb/yarl-1.24.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:90333fd89b43c0d08ac85f3f1447593fc2c66de18c3d6378d7125ea118dc7a54", size = 107741, upload-time = "2026-07-20T02:05:31.367Z" }, + { url = "https://files.pythonhosted.org/packages/d9/9a/c4defeaf3ed33fcb346aacf9c6e971a8d4e2bde04a0310e79abb208e7965/yarl-1.24.5-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:665b0a2c463cc9423dd647e0bfd9f4ccc9b50f768c55304d5e9f80b177c1de12", size = 103570, upload-time = "2026-07-20T02:05:33.303Z" }, + { url = "https://files.pythonhosted.org/packages/5f/e7/0e0e0de5865ebd5914537ef486f36c727a59865c3ac0cf5ff1b32aececbf/yarl-1.24.5-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e006d3a974c4ee19512e5f058abedb6eef36a5e553c14812bdeba1758d812e6d", size = 115815, upload-time = "2026-07-20T02:05:35.292Z" }, + { url = "https://files.pythonhosted.org/packages/2b/27/ca56b700cb170aba25a3893b75355b213935657dc5714d2383354a270e62/yarl-1.24.5-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e7d42c531243450ef0d4d9c172e7ed6ef052640f195629065041b5add4e058d1", size = 116025, upload-time = "2026-07-20T02:05:37.503Z" }, + { url = "https://files.pythonhosted.org/packages/d6/d0/d56c859b8222116f5d68459199f48359e0bf121b6f65a69bf329b3602ba0/yarl-1.24.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f08c7513ecef5aad65687bfdf6bc601ae9fccd04a42904501f8f7141abad9eb9", size = 109835, upload-time = "2026-07-20T02:05:39.506Z" }, + { url = "https://files.pythonhosted.org/packages/70/a2/3a35557e4d1a79425040eba202ccaf08bdc8717680fc77e2498a1ad2e0a5/yarl-1.24.5-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6c95b17fe34ed802f17e205112e6e10db92275c34fee290aa9bdc55a9c724027", size = 108884, upload-time = "2026-07-20T02:05:41.584Z" }, + { url = "https://files.pythonhosted.org/packages/e4/35/ef4c26356b7913c68983bac2d72a4212b3347af551cb8d250b99b5ed7b7f/yarl-1.24.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:56b149b22de33b23b0c6077ab9518c6dcb538ad462e1830e68d06591ccf6e38b", size = 107308, upload-time = "2026-07-20T02:05:43.697Z" }, + { url = "https://files.pythonhosted.org/packages/d5/91/ff0dc66c2ccf3e0153ab97ff61eabab4400e6a5264af427ab30cd69f1857/yarl-1.24.5-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:a8fe66b8f300da93798025a785a5b90b42f3810dc2b72283ff84a41aaaebc293", size = 103646, upload-time = "2026-07-20T02:05:45.895Z" }, + { url = "https://files.pythonhosted.org/packages/74/f0/33b9271c7f881766359d58266fa0811d2e5210ed860e28da7dc6d7786344/yarl-1.24.5-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:377fe3732edbaf78ee74efdf2c9f49f6e99f20e7f9d2649fda3eb4badd77d76e", size = 115305, upload-time = "2026-07-20T02:05:47.832Z" }, + { url = "https://files.pythonhosted.org/packages/ef/65/fd79fb1868c4a80db8661091de525bf430f63c3bea1b20e8b6a84fc7d359/yarl-1.24.5-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:e8ffa78582120024f476a611d7befc123cee59e47e8309d470cf667d806e613b", size = 108404, upload-time = "2026-07-20T02:05:49.604Z" }, + { url = "https://files.pythonhosted.org/packages/ff/ba/dbabe6b262f17a816c70cfc09558dbf03ece3ec76684d02f911a3d3a189c/yarl-1.24.5-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:daba5e594f06114e37db186efd2dd916609071e59daca901a0a2e71f02b142ce", size = 115940, upload-time = "2026-07-20T02:05:51.741Z" }, + { url = "https://files.pythonhosted.org/packages/a5/43/fab2d1dad9d340a268cdde63756a123d069723efff6a372d123fa74a9517/yarl-1.24.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:65be18ec59496c13908f02a2472751d9ef840b4f3fb5726f129306bf6a2a7bba", size = 110006, upload-time = "2026-07-20T02:05:53.554Z" }, + { url = "https://files.pythonhosted.org/packages/c4/27/41eb51bbd1b8d89546b83897cfb0164f1e109304fd408dbb151b639eec0f/yarl-1.24.5-cp312-cp312-win_amd64.whl", hash = "sha256:a929d878fec099030c292803b31e5d5540a7b6a31e6a3cc76cb4685fc2a2f51b", size = 97618, upload-time = "2026-07-20T02:05:55.57Z" }, + { url = "https://files.pythonhosted.org/packages/3c/25/b2553764b3d65db711d8f45416351ec4f420847558eb669edcbcaadf5780/yarl-1.24.5-cp312-cp312-win_arm64.whl", hash = "sha256:7ce27823052e2013b597e0c738b13e7e36b8ccb9400df8959417b052ab0fd92c", size = 93018, upload-time = "2026-07-20T02:05:57.554Z" }, + { url = "https://files.pythonhosted.org/packages/e1/63/64ef361967cc983573149dc1515d531db5da8a4c92d22bb833d59e01b313/yarl-1.24.5-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:79af890482fc94648e8cde4c68620378f7fef60932710fa17a66abc039244da2", size = 135075, upload-time = "2026-07-20T02:05:59.671Z" }, + { url = "https://files.pythonhosted.org/packages/bb/89/55920fd853ce43e608adbc3962456f0d649d6bb15250dc2988321da0fe1c/yarl-1.24.5-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:46c2f213e23a04b93a392942d782eb9e413e6ef6bf7c8c53884e599a5c174dcb", size = 97225, upload-time = "2026-07-20T02:06:01.769Z" }, + { url = "https://files.pythonhosted.org/packages/15/f0/7688d3f2cfff7590df2af38ec46d969f4281a4dddb08a9ad2eafbcdddf98/yarl-1.24.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:92ab3e11448f2ff7bf53c5a26eff0edc086898ec8b21fb154b85839ce1d88075", size = 96751, upload-time = "2026-07-20T02:06:03.676Z" }, + { url = "https://files.pythonhosted.org/packages/05/1a/a851a0f94aaaf379dd4f901bfc80f634280bec51eb260b47363e2a4cd62e/yarl-1.24.5-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ebb0ec7f17803063d5aeb982f3b1bd2b2f4e4fae6751226cbd6ba1fcfe9e63ff", size = 107960, upload-time = "2026-07-20T02:06:05.699Z" }, + { url = "https://files.pythonhosted.org/packages/6c/a8/faea066c12f9c77ca0de90641f1655f9dd7b412477bf28c76d692f3aecff/yarl-1.24.5-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:82632daed195dcc8ea664e8556dc9bdbd671960fb3776bd92806ce05792c2448", size = 103500, upload-time = "2026-07-20T02:06:07.556Z" }, + { url = "https://files.pythonhosted.org/packages/fb/9c/1e67084c2a6e2f2db0e3be798328cb3be42c0119b621d25461479a224d21/yarl-1.24.5-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:53e549287ef628fecba270045c9701b0c564563a9b0577d24a4ec75b8ab8040f", size = 115780, upload-time = "2026-07-20T02:06:09.599Z" }, + { url = "https://files.pythonhosted.org/packages/58/86/1f94664e147474337e3359f52012cf3d02f825f694317b178bfba1078c62/yarl-1.24.5-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fcd3b77e2f17bbe4ca56ec7bcb07992647d19d0b9c05d84886dcd6f9eb810afd", size = 115308, upload-time = "2026-07-20T02:06:11.352Z" }, + { url = "https://files.pythonhosted.org/packages/0a/43/8e55ae7538ba5f28ccb3c845c6dd4549cf7016d5992e5326512519107cdd/yarl-1.24.5-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d46b86567dd4e248c6c159fcbcdcce01e0a5c8a7cd2334a0fff759d0fa075b16", size = 110574, upload-time = "2026-07-20T02:06:13.129Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ba/a889ec8765cedcf2ac44dcb02d6a21e4861399b243b263c5f2dde27ee740/yarl-1.24.5-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7f72c74aa99359e27a2ee8d6613fefa28b5f76a983c083074dfc2aaa4ab46213", size = 109914, upload-time = "2026-07-20T02:06:15.243Z" }, + { url = "https://files.pythonhosted.org/packages/9c/c3/e45f821af67b791c2dbbe4a9f4137a1d33f8d386654a05a0c3f47bdfa25d/yarl-1.24.5-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3f45789ce415a7ec0820dc4f82925f9b5f7732070be1dec1f5f23ec381435a24", size = 107712, upload-time = "2026-07-20T02:06:17.443Z" }, + { url = "https://files.pythonhosted.org/packages/02/00/2ab0f42c9857fcb490bfaa6647b14540b53d241ab209f23220b958cc5832/yarl-1.24.5-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:6e73e7fe93f17a7b191f52ec9da9dd8c06a8fe735a1ecbd13b97d1c723bff385", size = 104251, upload-time = "2026-07-20T02:06:19.259Z" }, + { url = "https://files.pythonhosted.org/packages/7a/70/709d9a286e98af2c7fd8e4e6cada658b5c0e30d87dd7e2a63c2fb5767217/yarl-1.24.5-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:4a36f9becdd4c5c52a20c3e9484128b070b1dcfc8944c006f3a528295a359a9c", size = 115319, upload-time = "2026-07-20T02:06:21.207Z" }, + { url = "https://files.pythonhosted.org/packages/5c/6c/3eaa515142991fe84cfc483ff986492211f1978f90161ccefdbec919d09b/yarl-1.24.5-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:7bcbe0fcf850eae67b6b01749815a4f7161c560a844c769ad7b48fcd99f791c4", size = 109163, upload-time = "2026-07-20T02:06:23.006Z" }, + { url = "https://files.pythonhosted.org/packages/bb/64/711dafce66c323a3144d470547a71c5384c57623308ac8bb5e4b903ac148/yarl-1.24.5-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:24e861e9630e0daddcb9191fb187f60f034e17a4426f8101279f0c475cd74144", size = 115435, upload-time = "2026-07-20T02:06:24.923Z" }, + { url = "https://files.pythonhosted.org/packages/cf/f3/9b9d0e6d84bea851eb1ba99e4bdc755b86fd813e49ec86dfe42f26befdef/yarl-1.24.5-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:9335a099ad87287c37fe5d1a982ff392fa5efe5d14b40a730b1ec1d6a41382b4", size = 110691, upload-time = "2026-07-20T02:06:26.973Z" }, + { url = "https://files.pythonhosted.org/packages/86/e4/62a06b7e87c4246ac76b7c2da136f972eb4a3a1fc94abb07e7022d6fdb0a/yarl-1.24.5-cp313-cp313-win_amd64.whl", hash = "sha256:2dbe06fc16bc91502bca713704022182e5729861ae00277c3a23354b40929740", size = 97454, upload-time = "2026-07-20T02:06:29.163Z" }, + { url = "https://files.pythonhosted.org/packages/9e/c9/5fc8025b318ab10db413b61056bd0d95c557a70e8df4210c7511f866329c/yarl-1.24.5-cp313-cp313-win_arm64.whl", hash = "sha256:6b8536851f9f65e7f00c7a1d49ba7f2be0ffe2c11555367fc9f50d9f842410a1", size = 92813, upload-time = "2026-07-20T02:06:31.113Z" }, + { url = "https://files.pythonhosted.org/packages/a9/08/5f3085fef9564217074db9dd8573de1795bc82cde61a7ad10b6a7234a569/yarl-1.24.5-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:2729fcfc4f6a596fb0c50f32090400aa9367774ac296a00387e65098c0befa76", size = 135680, upload-time = "2026-07-20T02:06:33.273Z" }, + { url = "https://files.pythonhosted.org/packages/98/35/ba9436e579bd48a8801f2021d842d9ab4994c26e4c7dd3a4c1f1bcb57a9e/yarl-1.24.5-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ff330d3c30db4eb6b01d79e29d2d0b407a7ecad39cfd9ec993ece57396a2ec0d", size = 97395, upload-time = "2026-07-20T02:06:35.259Z" }, + { url = "https://files.pythonhosted.org/packages/18/a9/a07f76f3c44e02b25cc743af5ef93eef27f7013eadca770451b6a6ccb5db/yarl-1.24.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e42d75862735da90e7fc5a7b23db0c976f737113a54b3c9777a9b665e9cbff75", size = 97223, upload-time = "2026-07-20T02:06:37.216Z" }, + { url = "https://files.pythonhosted.org/packages/77/f7/a9a1d6fa7dd9e388f95b30f6ad3ec4e285f6c8f61f44ce16070c3fcfe414/yarl-1.24.5-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a3732e66413163e72508da9eff9ce9d2846fde51fae45d3605393d3e6cd303e9", size = 108777, upload-time = "2026-07-20T02:06:39.292Z" }, + { url = "https://files.pythonhosted.org/packages/2f/44/e0b86c302471fabd6f02808ecf2ac52b8412b624787849d4bf2cdb466f6f/yarl-1.24.5-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:5b8ee53be440a0cffc991a27be3057e0530122548dbe7c0892df08822fce5ede", size = 103119, upload-time = "2026-07-20T02:06:41.456Z" }, + { url = "https://files.pythonhosted.org/packages/d1/16/9c16d180bf8faaf223225eb50e1245870ff1ae0e302a27153988e65c51fd/yarl-1.24.5-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:af3aefa655adb5869491fa907e652290386800ae99cc50095cba71e2c6aefdca", size = 116471, upload-time = "2026-07-20T02:06:43.696Z" }, + { url = "https://files.pythonhosted.org/packages/d2/8d/b219b9df28a02ce95cfbdd41d2f7caa5669d0ff979c1c9975697145e33c5/yarl-1.24.5-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2120b96872df4a117cde97d270bac96aea7cc52205d305cf4611df694a487027", size = 115974, upload-time = "2026-07-20T02:06:45.874Z" }, + { url = "https://files.pythonhosted.org/packages/9b/e8/f20557aca240d88e69850ad1ee91756821d094bb1310565c04d25c6682a2/yarl-1.24.5-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:66410eb6345d467151934b49bfa70fb32f5b35a6140baa40ad97d6436abea2e9", size = 110830, upload-time = "2026-07-20T02:06:47.852Z" }, + { url = "https://files.pythonhosted.org/packages/db/18/199b85109a53eeca64ee19c9cca228287e8e4ab0cc1a09b28f530e65cce0/yarl-1.24.5-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4af7b7e1be0a69bee8210735fe6dcfc38879adfac6d62e789d53ba432d1ffa41", size = 110054, upload-time = "2026-07-20T02:06:49.84Z" }, + { url = "https://files.pythonhosted.org/packages/aa/2f/ed28147f8cd7f48c49367c90713b30a555284b6105a6a56f3a05568da795/yarl-1.24.5-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fa139875ff98ab97da323cfadfaff08900d1ad42f1b5087b0b812a55c5a06373", size = 108312, upload-time = "2026-07-20T02:06:51.835Z" }, + { url = "https://files.pythonhosted.org/packages/c5/c5/55e16ae0a5c227cea8df1c6871ba57d614a34243146c05729caf2a1bd9c5/yarl-1.24.5-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:0055afc45e864b92729ac7600e2d102c17bef060647e74bca75fa84d66b9ff36", size = 103662, upload-time = "2026-07-20T02:06:54.061Z" }, + { url = "https://files.pythonhosted.org/packages/8d/ea/dbd7c2caec459c9a426f18b02688ecbfb58620d0f6a3422d24769fbaf8ab/yarl-1.24.5-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:f0e466ed7511fe9d459a819edbc6c2585c0b6eabde9fa8a8947552468a7a6ef0", size = 116090, upload-time = "2026-07-20T02:06:56.015Z" }, + { url = "https://files.pythonhosted.org/packages/06/84/39ce4ce3059e07fece5fbdbee8c4053406af9aca911ce9fa5f8548aab6af/yarl-1.24.5-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:f141474e85b7e54998ec5180530a7cda99ab29e282fa50e0756d89981a9b43c5", size = 109523, upload-time = "2026-07-20T02:06:57.926Z" }, + { url = "https://files.pythonhosted.org/packages/a9/8b/71ff44137b405c64a7788075669c24010019f57a7464b78c3a6cbee539d9/yarl-1.24.5-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:e2935f8c39e3b03e83519292d78f075189978f3f4adc15a78144c7c8e2a1cba5", size = 116084, upload-time = "2026-07-20T02:06:59.868Z" }, + { url = "https://files.pythonhosted.org/packages/62/c0/423078fdd4042e1862c11f0ffd977a0ffa393783c12bee94685923bc189e/yarl-1.24.5-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9d1216a7f6f77836617dba35687c5b78a4170afc3c3f18fc788f785ba26565c4", size = 111006, upload-time = "2026-07-20T02:07:01.907Z" }, + { url = "https://files.pythonhosted.org/packages/cf/52/6daa2ee9d95e5c98b8128f8df91eb692eb423ab274b8cf08db52152fad26/yarl-1.24.5-cp314-cp314-win_amd64.whl", hash = "sha256:5ba4f78df2bcc19f764a4b26a8a4f5049c110090ad5825993aacb052bf8003ad", size = 99215, upload-time = "2026-07-20T02:07:03.852Z" }, + { url = "https://files.pythonhosted.org/packages/ec/0e/464a847d7359e0da75dd9fc5c1d1aa35d0159ea31e5f8e66a3c1c29ff3d0/yarl-1.24.5-cp314-cp314-win_arm64.whl", hash = "sha256:9e4e16c73d717c5cf27626c524d0a2e261ad20e46932b2670f64ad5dde23e26f", size = 94566, upload-time = "2026-07-20T02:07:06.074Z" }, + { url = "https://files.pythonhosted.org/packages/e2/55/e03acc4446772660bc335e86e41ef31e4d0d838fd641531a11a5ee33b493/yarl-1.24.5-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:e1ae548a9d901adca07899a4147a7c826bbcc06239d3ce9a59f57886a28a4c88", size = 142533, upload-time = "2026-07-20T02:07:08.284Z" }, + { url = "https://files.pythonhosted.org/packages/ae/71/4acd3a1fc7cf14345cdb302665ecd2097f62c365b4f14ca17d4f37775cf9/yarl-1.24.5-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:ff405d91509d88e8d44129cd87b18d70acd1f0c1aeabd7bc3c46792b1fe2acba", size = 100776, upload-time = "2026-07-20T02:07:10.197Z" }, + { url = "https://files.pythonhosted.org/packages/ff/0b/cfb76b7fe99686db264bff829779a539d923e7564ffd7ef18da6c54c3774/yarl-1.24.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:47e98aab9d8d82ff682e7b0b5dded33bf138a32b817fcf7fa3b27b2d7c412928", size = 100913, upload-time = "2026-07-20T02:07:12.357Z" }, + { url = "https://files.pythonhosted.org/packages/8b/3f/7116e782992abbd4fb6948488aec72078895e929a23078290739e8396fce/yarl-1.24.5-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f0a658a6d3fafee5c6f63c58f3e785c8c43c93fbc02bf9f2b6663f8185e0971f", size = 106507, upload-time = "2026-07-20T02:07:14.173Z" }, + { url = "https://files.pythonhosted.org/packages/33/90/d4d2d73ee78229cc889872eb8e085d8f5c6f51abdb178409fd9b23cf74fd/yarl-1.24.5-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:4377407001ca3c057773f44d8ddd6358fa5f691407c1ba92210bd3cf8d9e4c95", size = 99219, upload-time = "2026-07-20T02:07:16.019Z" }, + { url = "https://files.pythonhosted.org/packages/3e/fa/a6df1a9bccd644eec00abee0dff4277416222cec435330fd1f2858523ec1/yarl-1.24.5-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7c0494a31a1ac5461a226e7947a9c9b78c44e1dc7185164fa7e9651557a5d9bc", size = 111804, upload-time = "2026-07-20T02:07:18.141Z" }, + { url = "https://files.pythonhosted.org/packages/8a/9e/7b2a1f4bcc20e9447156dd2b1c4d01f70d9df0759025ee7d09a84ffae134/yarl-1.24.5-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a7cff474ab7cd149765bb784cf6d78b32e18e20473fb7bda860bce98ab58e9da", size = 110943, upload-time = "2026-07-20T02:07:20.06Z" }, + { url = "https://files.pythonhosted.org/packages/08/ff/22c92affb0f9b623ca753d27d968b5625b868f12c6378d049d55ae247643/yarl-1.24.5-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cbb833ccacdb5519eff9b8b71ee618cc2801c878e77e288775d77c3a2ced858a", size = 108251, upload-time = "2026-07-20T02:07:22.217Z" }, + { url = "https://files.pythonhosted.org/packages/45/44/5769b96298c1e195fb412997b6090af2a84105cf59c17613558a2d011d1f/yarl-1.24.5-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:82f75e05912e84b7a0fe57075d9c59de3cb352b928330f2eb69b2e1f54c3e1f0", size = 106025, upload-time = "2026-07-20T02:07:24.083Z" }, + { url = "https://files.pythonhosted.org/packages/4c/40/009e8e791fd9762c0e1567e69248acb4f49064597e1680874c16dd8bb798/yarl-1.24.5-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:16a2f5010280020e90f5330257e6944bc33e73593b136cc5a241e6c1dc292498", size = 106573, upload-time = "2026-07-20T02:07:26.248Z" }, + { url = "https://files.pythonhosted.org/packages/20/c6/b7480578f8a0a80946f36ad6df547ecec704f9ba69d2de60f8aa6f1c1cbf/yarl-1.24.5-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:ffcd54362564dc1a30fb74d8b8a6e5a6b11ebd5e27266adc3b7427a21a6c9104", size = 100751, upload-time = "2026-07-20T02:07:28.098Z" }, + { url = "https://files.pythonhosted.org/packages/d4/27/4476f3360b91a48c5cf125e91f59a3bd35299d84a431a258d57f5977bb11/yarl-1.24.5-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:0465ec8cedc2349b97a6b595ace64084a50c6e839eca40aa0626f38b8350e331", size = 111643, upload-time = "2026-07-20T02:07:30.88Z" }, + { url = "https://files.pythonhosted.org/packages/4c/4b/5cdd3e5ee944e8af31e52f6cd3d3af5fd7b937e036ccbbba2c9ffebede95/yarl-1.24.5-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:4db9aecb141cb7a5447171b57aa1ed3a8fee06af40b992ffc31206c0b0121550", size = 106312, upload-time = "2026-07-20T02:07:33.06Z" }, + { url = "https://files.pythonhosted.org/packages/18/86/f406b0c2a6f99575de2da671ef47aa06f89a5be83a27a46971c3b86cecdb/yarl-1.24.5-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:f540c013589084679a6c7fac07096b10159737918174f5dfc5e11bf5bca4dfe6", size = 110379, upload-time = "2026-07-20T02:07:35.155Z" }, + { url = "https://files.pythonhosted.org/packages/f0/6c/9f3adfbd3b30b4fa0f7ccb3a83eba2c1152d3fff554d535e640ba0f7ba2b/yarl-1.24.5-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:a61834fb15d81322d872eaafd333838ae7c9cea84067f232656f75965933d047", size = 108497, upload-time = "2026-07-20T02:07:37.35Z" }, + { url = "https://files.pythonhosted.org/packages/dd/37/91eb2e5ca883a529c1b390348a74cd9fc0512171727f547ce70bfe02be5c/yarl-1.24.5-cp314-cp314t-win_amd64.whl", hash = "sha256:5c88e5815a49d289e599f3513aa7fde0bc2092ff188f99c940f007f90f53d104", size = 102450, upload-time = "2026-07-20T02:07:39.578Z" }, + { url = "https://files.pythonhosted.org/packages/bf/f4/ed5c402ac8fde4403ed3366c2716bfddc8a6677ebd59f3d62772cc7fe468/yarl-1.24.5-cp314-cp314t-win_arm64.whl", hash = "sha256:cf139c02f5f23ef6532040a30ff662c00a318c952334f211046b8e60b7f17688", size = 97222, upload-time = "2026-07-20T02:07:41.55Z" }, + { url = "https://files.pythonhosted.org/packages/61/02/962c1cbfc401a30c1d034dc67ff395f64b52302c6d62de556c1fca99acc0/yarl-1.24.5-py3-none-any.whl", hash = "sha256:a33700d13d9b7d84fd10947b09ff69fb9a792e519c8cb9764a3ca70baa6c23a7", size = 58612, upload-time = "2026-07-20T02:07:43.461Z" }, +] + +[[package]] +name = "zarr" +source = { editable = "../../" } +dependencies = [ + { name = "donfig" }, + { name = "google-crc32c" }, + { name = "numcodecs" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "typing-extensions" }, +] + +[package.metadata] +requires-dist = [ + { name = "cast-value-rs", marker = "extra == 'cast-value-rs'" }, + { name = "cupy-cuda12x", marker = "sys_platform != 'darwin' and extra == 'gpu'" }, + { name = "donfig", specifier = ">=0.8" }, + { name = "fsspec", marker = "extra == 'remote'", specifier = ">=2023.10.0" }, + { name = "google-crc32c", specifier = ">=1.5" }, + { name = "numcodecs", specifier = ">=0.14" }, + { name = "numpy", specifier = ">=2" }, + { name = "obstore", marker = "extra == 'remote'", specifier = ">=0.5.1" }, + { name = "packaging", specifier = ">=22.0" }, + { name = "typer", marker = "extra == 'cli'" }, + { name = "typing-extensions", specifier = ">=4.14" }, + { name = "universal-pathlib", marker = "extra == 'optional'" }, +] +provides-extras = ["cast-value-rs", "cli", "gpu", "optional", "remote"] + +[package.metadata.requires-dev] +dev = [ + { name = "astroid", specifier = "==4.1.2" }, + { name = "botocore" }, + { name = "coverage", specifier = "==7.15.2" }, + { name = "fsspec", specifier = ">=2023.10.0" }, + { name = "griffe-inherited-docstrings", specifier = "==1.1.3" }, + { name = "hypothesis", specifier = "==6.164.0" }, + { name = "markdown-exec", extras = ["ansi"], specifier = "==1.12.3" }, + { name = "mike", specifier = "==2.2.0" }, + { name = "mkdocs", specifier = "==1.6.1" }, + { name = "mkdocs-material", extras = ["imaging"], specifier = "==9.7.7" }, + { name = "mkdocs-redirects", specifier = "==1.2.3" }, + { name = "mkdocstrings", specifier = "==1.0.6" }, + { name = "mkdocstrings-python", specifier = "==2.0.5" }, + { name = "moto", extras = ["s3", "server"], specifier = "==5.2.2" }, + { name = "mypy", specifier = "==2.3.0" }, + { name = "numcodecs", extras = ["msgpack"] }, + { name = "numpydoc", specifier = "==1.10.0" }, + { name = "obstore", specifier = ">=0.5.1" }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "pytest-accept", specifier = "==0.3.0" }, + { name = "pytest-asyncio", specifier = "==1.4.0" }, + { name = "pytest-benchmark", specifier = "==5.2.3" }, + { name = "pytest-codspeed", specifier = "==5.0.3" }, + { name = "pytest-cov", specifier = "==7.1.0" }, + { name = "pytest-xdist", specifier = "==3.8.0" }, + { name = "requests", specifier = "==2.34.2" }, + { name = "ruff", specifier = "==0.16.0" }, + { name = "s3fs", specifier = ">=2023.10.0" }, + { name = "tomlkit", specifier = "==0.15.1" }, + { name = "towncrier", specifier = "==25.8.0" }, + { name = "universal-pathlib" }, + { name = "uv", specifier = "==0.12.0" }, +] +docs = [ + { name = "astroid", specifier = "==4.1.2" }, + { name = "griffe-inherited-docstrings", specifier = "==1.1.3" }, + { name = "markdown-exec", extras = ["ansi"], specifier = "==1.12.3" }, + { name = "mike", specifier = "==2.2.0" }, + { name = "mkdocs", specifier = "==1.6.1" }, + { name = "mkdocs-material", extras = ["imaging"], specifier = "==9.7.7" }, + { name = "mkdocs-redirects", specifier = "==1.2.3" }, + { name = "mkdocstrings", specifier = "==1.0.6" }, + { name = "mkdocstrings-python", specifier = "==2.0.5" }, + { name = "numcodecs", extras = ["msgpack"] }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "ruff", specifier = "==0.16.0" }, + { name = "s3fs", specifier = ">=2023.10.0" }, + { name = "towncrier", specifier = "==25.8.0" }, +] +release = [{ name = "towncrier", specifier = "==25.8.0" }] +remote-tests = [ + { name = "botocore" }, + { name = "coverage", specifier = "==7.15.2" }, + { name = "fsspec", specifier = ">=2023.10.0" }, + { name = "hypothesis", specifier = "==6.164.0" }, + { name = "moto", extras = ["s3", "server"], specifier = "==5.2.2" }, + { name = "numpydoc", specifier = "==1.10.0" }, + { name = "obstore", specifier = ">=0.5.1" }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "pytest-accept", specifier = "==0.3.0" }, + { name = "pytest-asyncio", specifier = "==1.4.0" }, + { name = "pytest-benchmark", specifier = "==5.2.3" }, + { name = "pytest-codspeed", specifier = "==5.0.3" }, + { name = "pytest-cov", specifier = "==7.1.0" }, + { name = "pytest-xdist", specifier = "==3.8.0" }, + { name = "requests", specifier = "==2.34.2" }, + { name = "s3fs", specifier = ">=2023.10.0" }, + { name = "tomlkit", specifier = "==0.15.1" }, + { name = "uv", specifier = "==0.12.0" }, +] +test = [ + { name = "coverage", specifier = "==7.15.2" }, + { name = "hypothesis", specifier = "==6.164.0" }, + { name = "numpydoc", specifier = "==1.10.0" }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "pytest-accept", specifier = "==0.3.0" }, + { name = "pytest-asyncio", specifier = "==1.4.0" }, + { name = "pytest-benchmark", specifier = "==5.2.3" }, + { name = "pytest-codspeed", specifier = "==5.0.3" }, + { name = "pytest-cov", specifier = "==7.1.0" }, + { name = "pytest-xdist", specifier = "==3.8.0" }, + { name = "tomlkit", specifier = "==0.15.1" }, + { name = "uv", specifier = "==0.12.0" }, +] + +[[package]] +name = "zarr-http-server" +source = { editable = "." } +dependencies = [ + { name = "starlette" }, + { name = "uvicorn" }, + { name = "zarr" }, +] + +[package.dev-dependencies] +docs = [ + { name = "griffe-inherited-docstrings" }, + { name = "mkdocs" }, + { name = "mkdocs-material" }, + { name = "mkdocstrings" }, + { name = "mkdocstrings-python" }, + { name = "ruff" }, +] +examples = [ + { name = "fsspec", extra = ["http"] }, + { name = "httpx" }, +] +test = [ + { name = "httpx" }, + { name = "httpx2" }, + { name = "hypothesis" }, + { name = "ipykernel" }, + { name = "nbclient" }, + { name = "nbformat" }, + { name = "pytest" }, +] + +[package.metadata] +requires-dist = [ + { name = "starlette", specifier = ">=1.0" }, + { name = "uvicorn", specifier = ">=0.29" }, + { name = "zarr", editable = "../../" }, +] + +[package.metadata.requires-dev] +docs = [ + { name = "griffe-inherited-docstrings", specifier = "==1.1.3" }, + { name = "mkdocs", specifier = "==1.6.1" }, + { name = "mkdocs-material", specifier = "==9.7.7" }, + { name = "mkdocstrings", specifier = "==1.0.6" }, + { name = "mkdocstrings-python", specifier = "==2.0.5" }, + { name = "ruff", specifier = "==0.16.0" }, +] +examples = [ + { name = "fsspec", extras = ["http"] }, + { name = "httpx" }, +] +test = [ + { name = "httpx" }, + { name = "httpx2" }, + { name = "hypothesis" }, + { name = "ipykernel" }, + { name = "nbclient" }, + { name = "nbformat" }, + { name = "pytest" }, +] diff --git a/packages/zarr-indexing/.readthedocs.yaml b/packages/zarr-indexing/.readthedocs.yaml new file mode 100644 index 0000000000..c1925182f7 --- /dev/null +++ b/packages/zarr-indexing/.readthedocs.yaml @@ -0,0 +1,43 @@ +# Read the Docs configuration for the zarr-indexing docs site, separate from +# the zarr-python site configured by the repo-root .readthedocs.yaml. The RTD +# project for zarr-indexing must set its configuration-file path to +# packages/zarr-indexing/.readthedocs.yaml. +version: 2 + +build: + os: ubuntu-22.04 + tools: + python: "3.12" + jobs: + post_checkout: + # Cancel pull request builds that do not touch this package. Exit code + # 183 cancels the build and reports success to the Git provider. Scoped + # to PR builds ("external" versions) because origin/main is only a + # meaningful diff base there. + - | + if [ "$READTHEDOCS_VERSION_TYPE" = "external" ] && git diff --quiet origin/main -- packages/zarr-indexing; + then + exit 183; + fi + install: + - pip install --upgrade pip + - pip install ./packages/zarr-indexing --group packages/zarr-indexing/pyproject.toml:docs + build: + html: + # Build from inside the package rather than pointing `-f` at its config + # from the repo root. mkdocs resolves some settings relative to the + # current working directory rather than to the config file, so building + # from elsewhere looks for them in the wrong place -- and silently, since + # the paths are valid, just wrong. zarr-indexing hit this: with + # `pymdownx.snippets` and a relative `base_path`, its snippets were + # searched for under the repo-root docs/ and the build failed with + # SnippetMissingError, while `just docs-check` passed because it runs + # from here. Building from the package directory makes this identical to + # the local and CI invocations, so a green build there means a green + # build here. + # + # $READTHEDOCS_OUTPUT is absolute, so the cd does not affect it. + - cd packages/zarr-indexing && mkdocs build --strict --site-dir $READTHEDOCS_OUTPUT/html + +mkdocs: + configuration: packages/zarr-indexing/mkdocs.yml diff --git a/packages/zarr-indexing/CHANGELOG.md b/packages/zarr-indexing/CHANGELOG.md new file mode 100644 index 0000000000..7c4bc92cad --- /dev/null +++ b/packages/zarr-indexing/CHANGELOG.md @@ -0,0 +1,3 @@ +# Release notes + + diff --git a/packages/zarr-indexing/CONTRIBUTING.md b/packages/zarr-indexing/CONTRIBUTING.md new file mode 100644 index 0000000000..632e24929f --- /dev/null +++ b/packages/zarr-indexing/CONTRIBUTING.md @@ -0,0 +1,27 @@ +# Contributing to zarr-indexing + +Package-scoped development commands live in the [`justfile`](./justfile) +(requires [just](https://github.com/casey/just)): + +``` +just test # run the test suite (extra args go to pytest) +just lint # ruff, same invocation as CI +just typecheck # pyright, same invocation as CI +just docs-check # strict build of the docs site +just check # all of the above +just docs-serve # serve the docs site locally +``` + +Run them from this directory, or from anywhere in the repository as +`just packages/zarr-indexing/`. + +The test recipe runs against the workspace-root environment, because the +chunk-resolution tests exercise this package against `zarr`'s chunk grids and +`zarr` is deliberately not a dependency of this package. + +## License + +MIT + +The package lives at `packages/zarr-indexing` inside the +[zarr-python](https://github.com/zarr-developers/zarr-python) repository. diff --git a/packages/zarr-indexing/LICENSE.txt b/packages/zarr-indexing/LICENSE.txt new file mode 100644 index 0000000000..1e8da4d242 --- /dev/null +++ b/packages/zarr-indexing/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-2025 Zarr Developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/zarr-indexing/README.md b/packages/zarr-indexing/README.md new file mode 100644 index 0000000000..7e2cec10dd --- /dev/null +++ b/packages/zarr-indexing/README.md @@ -0,0 +1,52 @@ +# zarr-indexing + +Composable, lazy coordinate transforms for Zarr array indexing. + +Documentation: + +This package implements TensorStore-inspired index transforms. The core idea: +every indexing operation (slicing, fancy indexing, etc.) produces a coordinate +mapping from user space to storage space. These mappings compose lazily β€” no +I/O until you explicitly read or write. + +Key types: + +- `LazyArray` β€” wraps a system-memory/basic-indexing source and adds a `.lazy` + accessor: `LazyArray.from_numpy(numpy_array).lazy[10:50, ::2].lazy.oindex[[3, 1, 1], :]` + composes a transform and returns a new view without reading data, and + `result()` materializes it into owned system memory. `LazyArray(source)` uses + the conservative basic reader; `from_numpy` explicitly selects NumPy's + optimized reader. Device arrays require an explicit custom reader responsible + for transferring values into the supplied system-memory output buffer. +- `Reader` β€” the explicit backend execution boundary: transforms say which + values belong in the result, while readers say how a backend obtains them +- `IndexDomain` β€” a rectangular region of integer coordinates +- `IndexTransform` β€” maps input coordinates to storage coordinates +- `ChunkPlan` and `ChunkProjection` β€” lazily partition a selection over a + caller-selected grid and pair each chunk-local transform with its placement in + the request, without binding a storage backend or scheduler +- `ConstantMap`, `DimensionMap`, `ArrayMap` β€” the three ways a single output + dimension can depend on the input +- `compose` β€” chain two transforms into one + +The package depends only on NumPy and the standard library; it does not import +`zarr`. It is developed in the [zarr-python](https://github.com/zarr-developers/zarr-python) +repository and consumed by `zarr` to resolve array indexing operations. + +## Installation + +```bash +pip install zarr-indexing +``` + +## Examples + +- [Lazy indexing a NumPy array](examples/lazy_indexing_numpy/README.md) +- [Lazy indexing with Dask](examples/lazy_indexing_dask/README.md) + +## Contributing + +Development commands, the test suite and the docs build are described in +[CONTRIBUTING.md](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-indexing/CONTRIBUTING.md) +in the repository. Issues and pull requests go to +[zarr-developers/zarr-python](https://github.com/zarr-developers/zarr-python). diff --git a/packages/zarr-indexing/changes/3906.feature.md b/packages/zarr-indexing/changes/3906.feature.md new file mode 100644 index 0000000000..4a4b754bd8 --- /dev/null +++ b/packages/zarr-indexing/changes/3906.feature.md @@ -0,0 +1 @@ +Reworked the JSON layer to conform to the [ndsel](https://github.com/zarr-developers/ndsel) draft wire format, which adapts TensorStore's `IndexTransform`. A new `zarr_indexing.messages` module (`parse_ndsel`, `normalize_ndsel`, `NdselError`) is a pure JSON-to-JSON layer that accepts all five message kinds (`point`/`box`/`slice`/`points`/`transform`) and normalizes them to the canonical transform body, enforcing the full ndsel error taxonomy. The package is checked against the vendored, language-agnostic ndsel conformance corpus. Serialization produces and consumes the canonical body (`IndexTransform.to_json`/`from_json`, and the `IndexDomain` pair). On serialization, orthogonal (`oindex`) `index_array` maps no longer emit `input_dimension` alongside `index_array` (a combination both ndsel and TensorStore reject), and degenerate all-singleton index arrays collapse to constant maps; the in-memory `input_dimension` is reconstructed from the array's dependency axes on load. diff --git a/packages/zarr-indexing/changes/4222.bugfix.1.md b/packages/zarr-indexing/changes/4222.bugfix.1.md new file mode 100644 index 0000000000..8cff5be6e4 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.bugfix.1.md @@ -0,0 +1,39 @@ +Correctness fixes to indexing and resolution, all reachable from 0.1.0: + +- An integer index applied to an axis a previous `oindex`/`vindex` step had + already indexed left an all-singleton `ArrayMap` still naming the axis the + integer removed, which after renumbering aliased a different one. Such a map + now collapses to a `ConstantMap` at composition time. +- A `vindex` selection whose coordinate arrays are not on the leading axes + (`vindex[..., i, j]`, `vindex[..., mask]`) laid out its result incorrectly and + raised a shape mismatch on a partitioned read. Gathered dimensions now follow + NumPy's placement rule, and the per-part gather is realigned to the scatter. +- An `oindex`/`vindex` step whose entries are all slices, applied to a view with + a fancy-indexed axis, applied those slices positionally to every axis of the + existing index array β€” including broadcast singletons β€” truncating it to size + 0, so `result()` returned an unwritten buffer. Reindexing is now + dependency-aware. +- `parts()` raised on a view emptied by a slice over an axis of extent 1; an + empty domain now yields no parts, matching `result()`. +- Negative-stride chunk projection swapped the endpoints while keeping the step + negative, selecting nothing where the reversed axis was meant. Composition + evaluated an inner index array over `range(size)` rather than the outer + domain's own range, resolving every coordinate wrongly whenever that domain + did not start at 0 β€” which both step-1 and negative-step slices produce. +- A domain dimension no output map depends on, left behind when a later basic + index consumes the axis a `vindex` array varied over, was miscounted in three + places: the partition walk's out-selection rank, the lowering engine's axis + restoration, and the correlated gather's broadcast. +- The parts of a correlated view narrowed to a single point came back rank 1 + where the view was rank 0, so the documented + `out[part.out_selection] = part.view.result()` assembly raised `ValueError`. +- `result()` could return memory shared with the wrapped array: an unpartitioned + read of a basic selection lowered to plain slicing and handed back a view of + the source, and `numpy.array(view, copy=True)` inherited the alias. It now + always allocates, and verifies the parts covered the output before returning. +- `IndexTransform.from_json` rejects a non-integer `index_array` with an + `NdselError` carrying `invalid_json`, rather than truncating a float array, + coercing booleans, or leaking NumPy's conversion error for strings. +- `result(parts=...)` raises `ValueError` rather than `AssertionError` when the + supplied parts do not tile the view, and `with_parts` / `with_parts_per_axis` + raise the documented `ValueError` for non-iterable input. diff --git a/packages/zarr-indexing/changes/4222.bugfix.md b/packages/zarr-indexing/changes/4222.bugfix.md new file mode 100644 index 0000000000..0717e1e384 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.bugfix.md @@ -0,0 +1,9 @@ +An adversarial review of the whole package found, and this fixes, several +defects at its boundaries: `result()` and `__array__(copy=True)` could hand back +a live view of a source that merely stored its data in NumPy; the wire format +emitted a document nothing could load for a selection that selects nothing, and +its domain loader validated nothing; chunk-selection lowering described a +transposed block in two separate cases; a map derived from a vectorized +selection carried a stale `input_dimension`, which made one view's answer depend +on how it was partitioned; and `oindex` over a correlated view applied NumPy's +vectorized rule instead of the outer product. diff --git a/packages/zarr-indexing/changes/4222.feature.1.md b/packages/zarr-indexing/changes/4222.feature.1.md new file mode 100644 index 0000000000..bc62baf357 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.feature.1.md @@ -0,0 +1,7 @@ +Added `UnitStepReader` / `unit_step_reader`: a backend adapter for sources +whose basic indexing accepts only ascending step-1 slices (FFI bindings, HTTP +range endpoints). Every key it presents is `slice(start, stop, 1)` per axis; +strides, reversals, and gathers are applied to the in-memory block by the +residual lowering. The integrations guide documents the companion dense-box +re-partition idiom β€” resolving a unit-stride rectangular view as one backend +slab read while keeping partitioned reads for strided and fancy selections. diff --git a/packages/zarr-indexing/changes/4222.feature.2.md b/packages/zarr-indexing/changes/4222.feature.2.md new file mode 100644 index 0000000000..722f56db99 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.feature.2.md @@ -0,0 +1,24 @@ +Added `LazyArray`, which grafts the full NumPy indexing dialect onto any source +exposing `shape`, `dtype`, and basic integer/slice `__getitem__` β€” a chunked +store, an FFI binding, an HTTP endpoint. `view.lazy[...]`, `.lazy.oindex[...]` +and `.lazy.vindex[...]` each compose an `IndexTransform` and return a new view +without reading anything; `result()` materializes. Selections use positional +NumPy semantics (negatives wrap, scalars drop their axis, coordinate arrays keep +order and duplicates), which the new `zarr_indexing.boundary` module translates +into the algebra's literal coordinates. The wrapper describes reads only, and +behaves as a duck array: eager `__getitem__` and `__array__` make it a +`dask.array.from_array` source. + +A read is divided along a **partitioning** β€” discovered from the wrapped array, +or chosen with `with_parts` / `with_parts_per_axis` / `unpartitioned`. +`parts()` yields one `Partition` per box, pairing a resolvable sub-view with +where its cells belong in the result; `result()` is the assembly of that walk, +and re-partitioning never changes what it returns. `base_shape` says which shape a partitioning is expressed in. `is_box`, `bounding_box()` +and `strides()` report whether a selection is rectangular, so a consumer can +dispatch a slab read against a gather. + +See the [guide](https://zarr-indexing.readthedocs.io/en/latest/guide/) for the +model and the +[design notes](https://zarr-indexing.readthedocs.io/en/latest/design-notes/) +for the box/query distinction, the relationship to TensorStore, and current +scope limits. diff --git a/packages/zarr-indexing/changes/4222.feature.3.md b/packages/zarr-indexing/changes/4222.feature.3.md new file mode 100644 index 0000000000..ef0e1512c2 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.feature.3.md @@ -0,0 +1,9 @@ +Added source-independent chunk planning. `plan_chunks(transform, grids)` returns +a lazy, reusable `ChunkPlan` whose `ChunkProjection`s each pair a chunk-local +transform with a transform back to the request, over one shared cell domain, so +a consumer can read a chunk and place its values without re-deriving either. The +same representation covers basic, orthogonal and vectorized indexing, and +carries global chunk bounds plus conservative full/partial/unknown coverage. +I/O, buffering and scheduling stay with the consumer. `zarr_indexing.grid` gained +`EdgeDimensionGrid` and `dimension_grids_from_chunks` for building the per-axis +grids it takes. diff --git a/packages/zarr-indexing/changes/4222.feature.4.md b/packages/zarr-indexing/changes/4222.feature.4.md new file mode 100644 index 0000000000..623d381083 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.feature.4.md @@ -0,0 +1,8 @@ +`LazyArray` has an explicit reader boundary: an `IndexTransform` decides which +values belong in a result, and a `Reader` decides how one backend obtains them, +preserving the transform exactly. `LazyArray(source)` is conservative and assumes +only basic indexing; `LazyArray.from_numpy(array)` selects the optimized NumPy +reader; `with_reader` selects any other. Readers do not define indexing +semantics, partitioning, scheduling, or result ownership. Both built-in readers +lower through NumPy system memory, so a device array needs a custom reader that +transfers into the supplied output buffer. diff --git a/packages/zarr-indexing/changes/4222.feature.5.md b/packages/zarr-indexing/changes/4222.feature.5.md new file mode 100644 index 0000000000..859667775f --- /dev/null +++ b/packages/zarr-indexing/changes/4222.feature.5.md @@ -0,0 +1,8 @@ +Added the `zarr_indexing.testing` subpackage, behind a `testing` extra +(`pip install zarr-indexing[testing]`), carrying the Hypothesis machinery this +package tests itself with. `ChainedIndexingStateMachine` composes basic, +orthogonal and vectorized selections onto a `LazyArray` wrapping an array you +supply, then checks every view's shape, `result()`, and assembled `parts()` +against NumPy; `zarr_indexing.testing.strategies` exports the selection +strategies alone, for a project with its own harness. Nothing outside the +subpackage imports Hypothesis. diff --git a/packages/zarr-indexing/changes/4222.feature.6.md b/packages/zarr-indexing/changes/4222.feature.6.md new file mode 100644 index 0000000000..8c65f947e6 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.feature.6.md @@ -0,0 +1,9 @@ +Negative-step slices are supported, following merged ndsel 1.0-draft.2 and +TensorStore 0.1.84: `arr[::-1]`, `arr[5:1:-2]`, and reversal composed over an +already-strided or already-gathered view. One desugaring rule covers both signs β€” +omitted bounds resolve on the side the traversal starts and stops, and the origin +is `trunc(start / step)` β€” while a reversed interval is an error rather than a +silently empty selection. A reversing slice normally yields a negative domain +origin, since the result stays anchored to the source coordinate frame; +`LazyArray` re-bases every view to origin 0, so its positional dialect is +unaffected. diff --git a/packages/zarr-indexing/changes/4222.feature.md b/packages/zarr-indexing/changes/4222.feature.md new file mode 100644 index 0000000000..c02ab54edb --- /dev/null +++ b/packages/zarr-indexing/changes/4222.feature.md @@ -0,0 +1,11 @@ +Fancy selections compose without restriction, on both `LazyArray` and +`IndexTransform`: a second `oindex`/`vindex`/mask step may land on any axis of +an already-fancy view, including axes an existing index array merely broadcasts +along. Array-carrying transforms are chained through `compose`, and resolution +handles the resulting mixed, correlated and diagonal index-array structures on +one shared pointwise path, classified by `IndexTransform.index_array_structure`. +Only hand-built affine diagonals β€” an index array and a slice map bound to the +same axis β€” remain unsupported. + +`__dask_tokenize__` digests a view's canonical transform body rather than +embedding it, so tokens stay small for large fancy selections. diff --git a/packages/zarr-indexing/changes/4222.misc.md b/packages/zarr-indexing/changes/4222.misc.md new file mode 100644 index 0000000000..1bd73e1c80 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.misc.md @@ -0,0 +1,5 @@ +Restructured the documentation-contract tests: the snippet include graph is +now discovered by scanning the rendered markdown instead of hand-maintained +registries, prose and navigation assertions moved out of CI, and +`pymdownx.snippets` now sets `check_paths: true` so an unresolvable include +fails `mkdocs build --strict` instead of silently rendering nothing. diff --git a/packages/zarr-indexing/changes/4222.removal.1.md b/packages/zarr-indexing/changes/4222.removal.1.md new file mode 100644 index 0000000000..33ff9cb423 --- /dev/null +++ b/packages/zarr-indexing/changes/4222.removal.1.md @@ -0,0 +1,12 @@ +The canonical JSON converters are now methods on the types that own the +serialization: `IndexTransform.to_json()` / `IndexTransform.from_json()`, +`IndexDomain.to_json()` / `IndexDomain.from_json()`, and `to_json()` on each +output map kind. `output_index_map_from_json` remains a function, in +`zarr_indexing.output_map`, because the wire form is a tagged union and +loading it dispatches rather than belonging to any one kind. + +The free functions they replace β€” `transform_to_canonical`, +`transform_from_canonical`, `index_domain_to_json`, `index_domain_from_json`, +`output_index_map_to_json`, and the historical aliases +`index_transform_to_json` / `index_transform_from_json` β€” are removed. There +had been two spellings of each conversion; there is now one. diff --git a/packages/zarr-indexing/changes/4222.removal.2.md b/packages/zarr-indexing/changes/4222.removal.2.md new file mode 100644 index 0000000000..d3321ea81c --- /dev/null +++ b/packages/zarr-indexing/changes/4222.removal.2.md @@ -0,0 +1,15 @@ +Operations moved onto the types that own them, following the arrangement +TensorStore uses (public headers are the types; every transform operation +lives in `internal/` and surfaces as a method): + +- `compose(outer, inner)` is now `outer.compose(inner)`, and the algorithm + moved to the private `zarr_indexing._composition`. +- `selection_to_transform(selection, transform, mode)` is now + `transform.select(selection, mode)`. +- `index_array_structure(transform)` is now the `transform.index_array_structure` + property. +- `array_map_dependent_axis(m)` is now the `ArrayMap.dependent_axis` property, + alongside a new `ArrayMap.dependency_axes` giving every axis a map varies over. + +`zarr_indexing.affine` is now the private `zarr_indexing._affine`; it was +never exported or documented. diff --git a/packages/zarr-indexing/changes/4222.removal.3.md b/packages/zarr-indexing/changes/4222.removal.3.md new file mode 100644 index 0000000000..d5210f4c8d --- /dev/null +++ b/packages/zarr-indexing/changes/4222.removal.3.md @@ -0,0 +1,6 @@ +`with_parts` is now three named methods β€” `with_parts`, `with_parts_per_axis` +and `unpartitioned` β€” instead of one parameter whose meaning was decided by the +type of what it was given. `Partition.array` is `Partition.view`, no longer the +inverse of `LazyArray.array`. `ArrayMap`, `IndexTransform` and `Partition` can +be compared and hashed, which `frozen=True` had implied and neither could do. +`LazyArray.base_shape` says which shape a partitioning is expressed in. diff --git a/packages/zarr-indexing/changes/4222.removal.md b/packages/zarr-indexing/changes/4222.removal.md new file mode 100644 index 0000000000..5782c9ab4d --- /dev/null +++ b/packages/zarr-indexing/changes/4222.removal.md @@ -0,0 +1,11 @@ +`ArrayMap` no longer has an `input_dimension` field: what a map depends on is +read from its full-rank index array's shape (its non-singleton axes), the +single source of truth. A selection narrowed to a single coordinate is now +built as the `ConstantMap` it equals (`array_map_or_constant`), so a length-1 +fancy selection classifies as a box; hand-built all-singleton or shared-axis +`ArrayMap`s resolve through the pointwise path. The wire format is unaffected β€” +it never carried the field. + +The provisional tuple resolver and selector bridge are gone with it: +`iter_chunk_transforms` and `sub_transform_to_selections` are removed, their +role taken by `plan_chunks` and the paired projections it returns. diff --git a/packages/zarr-indexing/changes/README.md b/packages/zarr-indexing/changes/README.md new file mode 100644 index 0000000000..feb3f8674e --- /dev/null +++ b/packages/zarr-indexing/changes/README.md @@ -0,0 +1,25 @@ +Writing a changelog entry for `zarr-indexing` +----------------------------------------------- + +Fragments in **this** directory are release notes for the `zarr-indexing` +package only β€” kept separate from the parent zarr-python `changes/` +directory so a PR touching only `packages/zarr-indexing/` produces a +release note for this package only. + +Please put a new file in this directory named `xxxx..md`, where + +- `xxxx` is the pull request number associated with this entry +- `` is one of: + - feature + - bugfix + - doc + - removal + - misc + +Inside the file, please write a short description of what you have +changed, and how it impacts users of `zarr-indexing`. + +A `zarr-indexing` release runs `towncrier build` in `packages/zarr-indexing/`, +which consumes the fragments here and updates `CHANGELOG.md`. Fragments +that describe parent zarr-python changes (not the transforms package) +belong in the top-level `changes/` directory, not here. diff --git a/packages/zarr-indexing/docs/_static/favicon-96x96.png b/packages/zarr-indexing/docs/_static/favicon-96x96.png new file mode 100644 index 0000000000..e77977ccf4 Binary files /dev/null and b/packages/zarr-indexing/docs/_static/favicon-96x96.png differ diff --git a/packages/zarr-indexing/docs/_static/logo_bw.png b/packages/zarr-indexing/docs/_static/logo_bw.png new file mode 100644 index 0000000000..df1979d3cc Binary files /dev/null and b/packages/zarr-indexing/docs/_static/logo_bw.png differ diff --git a/packages/zarr-indexing/docs/api/boundary.md b/packages/zarr-indexing/docs/api/boundary.md new file mode 100644 index 0000000000..4f9fa99531 --- /dev/null +++ b/packages/zarr-indexing/docs/api/boundary.md @@ -0,0 +1,5 @@ +--- +title: boundary +--- + +::: zarr_indexing.boundary diff --git a/packages/zarr-indexing/docs/api/chunk_resolution.md b/packages/zarr-indexing/docs/api/chunk_resolution.md new file mode 100644 index 0000000000..0d81ec3829 --- /dev/null +++ b/packages/zarr-indexing/docs/api/chunk_resolution.md @@ -0,0 +1,5 @@ +--- +title: chunk_resolution +--- + +::: zarr_indexing.chunk_resolution diff --git a/packages/zarr-indexing/docs/api/domain.md b/packages/zarr-indexing/docs/api/domain.md new file mode 100644 index 0000000000..b039d3a7f4 --- /dev/null +++ b/packages/zarr-indexing/docs/api/domain.md @@ -0,0 +1,5 @@ +--- +title: domain +--- + +::: zarr_indexing.domain diff --git a/packages/zarr-indexing/docs/api/errors.md b/packages/zarr-indexing/docs/api/errors.md new file mode 100644 index 0000000000..994a74248a --- /dev/null +++ b/packages/zarr-indexing/docs/api/errors.md @@ -0,0 +1,5 @@ +--- +title: errors +--- + +::: zarr_indexing.errors diff --git a/packages/zarr-indexing/docs/api/grid.md b/packages/zarr-indexing/docs/api/grid.md new file mode 100644 index 0000000000..b7c376eb85 --- /dev/null +++ b/packages/zarr-indexing/docs/api/grid.md @@ -0,0 +1,22 @@ +--- +title: grid +--- + +`zarr_indexing.grid` owns compact chunk-grid metadata so indexing plans can be +constructed without importing Zarr. `FixedDimension(size, extent)` represents +regular chunks in constant memory, including a clipped final data region; +`VaryingDimension(edges, extent)` represents explicit rectilinear chunk edges. +`ChunkGrid(dimensions=...)` combines these dimensions and returns `ChunkSpec` +objects whose `shape` is the valid data size and whose `codec_shape` preserves +the full codec-buffer size at a regular-grid boundary. + +`dimension_grids_from_chunks` returns these compact dimensions: integer chunk +shapes become `FixedDimension` instances and explicit per-axis edge sequences +become `VaryingDimension` instances. `DimensionGridLike` remains the narrow +protocol used by the chunk planner, while `EdgeDimensionGrid` is kept for +explicit edge-based and coordinate-origin examples. + +Zarr's array implementation can later import these compact grid types from +`zarr_indexing`; this package intentionally has no import dependency on Zarr. + +::: zarr_indexing.grid diff --git a/packages/zarr-indexing/docs/api/index.md b/packages/zarr-indexing/docs/api/index.md new file mode 100644 index 0000000000..674c701a0f --- /dev/null +++ b/packages/zarr-indexing/docs/api/index.md @@ -0,0 +1,87 @@ +--- +title: API reference +--- + +# API reference + +Choose the guide stopping point that matches your job before following module +links: + +- **Use lazy indexing:** finish + [Lazy views compose](../guide/index.md#lazy-views-compose), + then open [`zarr_indexing.lazy_array`](lazy_array.md) for `LazyArray`. +- **Integrate a chunked source:** finish + [One cell domain, two projections](../guide/index.md#one-cell-domain-two-projections), + then open [`zarr_indexing.chunk_resolution`](chunk_resolution.md) for + `plan_chunks`. Start with + [Coordinates are addresses](../guide/index.md#coordinates-are-addresses) if + literal coordinates are unfamiliar. + +The modules are layered: the transform algebra at the bottom, chunk resolution +and the wire format built on top of it. + +**The transform algebra** + +- [`zarr_indexing.domain`](domain.md) β€” `IndexDomain`, a rectangular region of + integer coordinates with an explicit (possibly non-zero) origin +- [`zarr_indexing.output_map`](output_map.md) β€” `ConstantMap`, `DimensionMap`, + and `ArrayMap`: three representations of a set of integer coordinates, one + per storage dimension +- [`zarr_indexing.transform`](transform.md) β€” `IndexTransform`, which pairs a + domain with output maps, plus the indexing (`[...]`, `.oindex`, `.vindex`), + `intersect`, and `translate` operations, and `selection_to_transform` + transforms into one + +**Chunk resolution** + +- [`zarr_indexing.chunk_resolution`](chunk_resolution.md) β€” + `plan_chunks`, which lazily projects a request through a caller-selected grid, + plus the reusable `ChunkPlan` and paired-transform `ChunkProjection` values +- [`zarr_indexing.grid`](grid.md) β€” `DimensionGridLike`, the Protocol + describing the narrow chunk-grid surface chunk resolution consumes, so that + nothing here imports `zarr`, plus `EdgeDimensionGrid` and + `dimension_grids_from_chunks`, a concrete per-axis grid for callers with no + zarr grid to hand + +**Lazy arrays** + +- [`zarr_indexing.lazy_array`](lazy_array.md) β€” `LazyArray`, a wrapper for + system-memory/basic-indexing sources that adds a `.lazy` accessor for + TensorStore-style deferred indexing, plus `Partition` and `parts()` / + `with_parts()`, which determine the boxes a read is broken into. Device + sources require an explicit custom reader that transfers into the supplied + system-memory output +- [`zarr_indexing.reader`](reader.md) β€” `Reader`, the backend execution boundary + that obtains the values described by a complete transform; `basic_reader` + serves conservative duck arrays and `numpy_reader` is selected explicitly by + `LazyArray.from_numpy` +- [`zarr_indexing.boundary`](boundary.md) β€” the translation between NumPy's + positional dialect and the transform algebra's literal coordinates + +**The ndsel wire format** (see [the guide](../ndsel.md)) + +- [`zarr_indexing.messages`](messages.md) β€” `parse_ndsel` / `normalize_ndsel`, + the pure JSONβ†’JSON message layer, and `NdselError` +- [`zarr_indexing.json`](json.md) β€” lowering between canonical ndsel bodies and + in-memory transforms + +**Errors** + +- [`zarr_indexing.errors`](errors.md) β€” the index-error types this package + raises, also exported at the top level. `zarr.errors` defines classes of the + same names, which are different objects; both subclass `IndexError` + +**Test support** (needs the `testing` extra) + +- [`zarr_indexing.testing.stateful`](testing_stateful.md) β€” + `ChainedIndexingStateMachine`, a Hypothesis state machine that composes + indexing steps onto a `LazyArray` wrapping your array and checks every step + against NumPy, plus `apply_selection`, the NumPy model it checks against +- [`zarr_indexing.testing.strategies`](testing_strategies.md) β€” the selection + strategies the machine draws from, for a project that has its own harness + +Every name listed in `zarr_indexing.__all__` is re-exported at the top level, +so `from zarr_indexing import IndexTransform` and +`from zarr_indexing.transform import IndexTransform` are equivalent. +`zarr_indexing.testing` is deliberately not among them: it imports +`hypothesis`, which the rest of the package does not. diff --git a/packages/zarr-indexing/docs/api/json.md b/packages/zarr-indexing/docs/api/json.md new file mode 100644 index 0000000000..0183ab30e7 --- /dev/null +++ b/packages/zarr-indexing/docs/api/json.md @@ -0,0 +1,5 @@ +--- +title: json +--- + +::: zarr_indexing.json diff --git a/packages/zarr-indexing/docs/api/lazy_array.md b/packages/zarr-indexing/docs/api/lazy_array.md new file mode 100644 index 0000000000..f855511d46 --- /dev/null +++ b/packages/zarr-indexing/docs/api/lazy_array.md @@ -0,0 +1,27 @@ +--- +title: lazy_array +--- + +`LazyArray.lazy[...]` is metadata-only: every derived view keeps the same +reader and composes its transform without reading data. `result()` allocates +owned system memory, then calls that reader once for each projected part. +Rectangular parts write directly into their final slices; advanced placement +may first use an owned dense temporary. `LazyArray(source)` assumes only basic +indexing, while `LazyArray.from_numpy(array)` explicitly selects NumPy's +optimized reader. + +The built-in readers lower through NumPy system memory and support sources +whose basic reads can be converted there. They do not implicitly transfer +device arrays; a device source needs an explicit custom reader that transfers +into the supplied system-memory output. Derived views and parts share their +reader and part views may be materialized concurrently, so stateful readers +must synchronize their own mutable state. + +Every public `Partition.view.transform` directly maps that view's zero-origin +coordinates into its raw `Partition.view.array`, including for non-first +partitions. `Partition.projection.chunk_transform` intentionally stays local to +the selected chunk. During materialization the reader receives both frames in +one `ReadContext`: the public global transform in `context.transform` and the +same local plan in `context.projection`. + +::: zarr_indexing.lazy_array diff --git a/packages/zarr-indexing/docs/api/messages.md b/packages/zarr-indexing/docs/api/messages.md new file mode 100644 index 0000000000..6c2a434540 --- /dev/null +++ b/packages/zarr-indexing/docs/api/messages.md @@ -0,0 +1,5 @@ +--- +title: messages +--- + +::: zarr_indexing.messages diff --git a/packages/zarr-indexing/docs/api/output_map.md b/packages/zarr-indexing/docs/api/output_map.md new file mode 100644 index 0000000000..55114a6997 --- /dev/null +++ b/packages/zarr-indexing/docs/api/output_map.md @@ -0,0 +1,5 @@ +--- +title: output_map +--- + +::: zarr_indexing.output_map diff --git a/packages/zarr-indexing/docs/api/reader.md b/packages/zarr-indexing/docs/api/reader.md new file mode 100644 index 0000000000..39129c4d47 --- /dev/null +++ b/packages/zarr-indexing/docs/api/reader.md @@ -0,0 +1,51 @@ +--- +title: Readers +--- + +# Readers + +An `IndexTransform` defines which source value belongs at every result +position. A `Reader` defines how a particular backend obtains those values. +Readers do not define indexing semantics, partitioning, scheduling, or result +ownership. + +`Reader.read_into(source, context, out)` receives a `ReadContext` whose +`transform` maps zero-origin output-buffer coordinates to global coordinates in +`source`, with `context.transform.domain.shape == out.shape`. Its optional +`projection` is the existing plan for a partitioned read. The projection's +`chunk_transform` remains chunk-local, its `cell_transform` describes result +placement, and its `chunk_domain` describes the grid cell. The global read +transform and the projection's chunk transform deliberately use different +coordinate frames. + +An implementation must fill every cell of `out` in place, preserve the global +transform's exact values, order, and dtype, and return `None`. It must neither +replace nor retain `out`, which may be a strided writable view. Backend +exceptions propagate unchanged. Derived part views share their reader and may +be resolved concurrently, so a stateful reader owns its own synchronization. + +Reader wrappers compose by intercepting this one operation and forwarding the +same source, context, and output buffer to an inner reader: + +```python +class RecordingReader: + def __init__(self, inner): + self.inner = inner + self.calls = [] + + def read_into(self, source, context, out, /): + self.calls.append((source, context, out)) + self.inner.read_into(source, context, out) + + +inner = RecordingReader(numpy_reader) +outer = RecordingReader(inner) +view = LazyArray.from_numpy(array).with_reader(outer) +values = view.result() +``` + +Both wrappers observe the same three objects, in outer-to-inner order. This +delegation pattern supports policies such as logging and caching without +library-defined wrapper primitives. + +::: zarr_indexing.reader diff --git a/packages/zarr-indexing/docs/api/testing_stateful.md b/packages/zarr-indexing/docs/api/testing_stateful.md new file mode 100644 index 0000000000..0aeb57df29 --- /dev/null +++ b/packages/zarr-indexing/docs/api/testing_stateful.md @@ -0,0 +1,5 @@ +--- +title: testing.stateful +--- + +::: zarr_indexing.testing.stateful diff --git a/packages/zarr-indexing/docs/api/testing_strategies.md b/packages/zarr-indexing/docs/api/testing_strategies.md new file mode 100644 index 0000000000..1dd7d59457 --- /dev/null +++ b/packages/zarr-indexing/docs/api/testing_strategies.md @@ -0,0 +1,5 @@ +--- +title: testing.strategies +--- + +::: zarr_indexing.testing.strategies diff --git a/packages/zarr-indexing/docs/api/transform.md b/packages/zarr-indexing/docs/api/transform.md new file mode 100644 index 0000000000..8e67a162c1 --- /dev/null +++ b/packages/zarr-indexing/docs/api/transform.md @@ -0,0 +1,18 @@ +--- +title: transform +--- + +An `IndexTransform` is a function between coordinate spaces, and its field +names follow the function, not the data: + +| the API says | in array terms | +| --- | --- | +| input space (`domain`, `input_rank`) | request coordinates β€” the result being built | +| output space (`output`, one map per dimension) | source coordinates β€” where values are read | + +`output` is not data: it is the rule, per source dimension, for producing +coordinates. Values flow source β†’ request, against the arrow. The +[guide](../guide/index.md#a-transform-points-from-the-request-to-the-source) +demonstrates each output map form against its NumPy counterpart. + +::: zarr_indexing.transform diff --git a/packages/zarr-indexing/docs/design-notes.md b/packages/zarr-indexing/docs/design-notes.md new file mode 100644 index 0000000000..78b352d376 --- /dev/null +++ b/packages/zarr-indexing/docs/design-notes.md @@ -0,0 +1,296 @@ +--- +title: Design notes +--- + +# Design notes + +This page records advanced rationale that the API does not state directly: how +this library relates to TensorStore, why rectangular selections are a category +rather than a fast path, and what is deliberately not implemented yet. The +visual guide owns the mechanics of +[literal coordinates](guide/index.md#coordinates-are-addresses), +[view composition](guide/index.md#lazy-views-compose), +[chunk plans](guide/index.md#a-request-becomes-a-chunk-plan), and +[their paired projections](guide/index.md#one-cell-domain-two-projections). + +## Relationship to TensorStore + +The core is [TensorStore's](https://google.github.io/tensorstore/index_space.html) +index-transform model, reimplemented in Python against NumPy. The visual guide +introduces the shared model in +[Coordinates are addresses](guide/index.md#coordinates-are-addresses) and +[Lazy views compose](guide/index.md#lazy-views-compose); the comparison here is +about the deliberately matching semantics: + +- **The model.** Both use an `IndexTransform` made of an input domain and one + output index map per storage dimension, in constant, affine, and index-array + forms. +- **Slice semantics.** Slice bounds are literal domain coordinates: no + clamping, no negative wrapping, non-empty intervals must be contained in the + domain, and a strided slice's domain origin is `trunc(start/step)` rounded + toward zero. Every one of those rules was executed against tensorstore 0.1.84 + and is pinned in `tests/test_tensorstore_parity.py`. +- **The wire format.** A canonical [ndsel](ndsel.md) transform body is, + field-for-field, a TensorStore `IndexTransform` minus the `kind` + discriminator, and `tests/test_ndsel_tensorstore.py` loads our bodies into + `tensorstore.IndexTransform(json=...)` and round-trips them back through our + engine layer. + +The representations differ in one place: index arrays. Both models want an index +array at the transform's full input rank, with singleton axes for the dimensions +a map does not vary over. TensorStore enforces it β€” its JSON parser rejects a +rank-1 array over a rank-2 domain outright, with `Index array for output +dimension 0 has rank 1 but must have rank 2` (checked against tensorstore +0.1.84) β€” while our loader is the more permissive of the two and also accepts a +lower-rank array that broadcasts against the input domain. That is a +compatibility affordance, not a difference in the model: ndsel leaves index-array +rank to [the engine layer](ndsel.md#lowering-to-a-transform), and everything the +algebra builds itself is at full rank. + +The reason full rank matters here is that we *derive* meaning from those +singletons rather than merely tolerating them: an array full-sized on one axis +and singleton elsewhere is orthogonal, and one varying over several shared axes +is vectorized, so the distinction is readable off the shape β€” and the shape is +the *only* place it lives. An earlier `ArrayMap.input_dimension` field pinned +the orthogonal axis redundantly and was retired: the one shape it disambiguated +(a single-coordinate array, all axes singleton) is now normalized away at +construction, collapsed to the `ConstantMap` it equals, exactly as +[the serializer](api/json.md) has always collapsed it on the wire. + +Four deliberate differences: + +| | TensorStore | `zarr-indexing` | +| --- | --- | --- | +| Dialect | One strict dialect everywhere: literal coordinates, no negative wrapping | The algebra keeps that dialect; each public boundary picks its own. [`LazyArray`](api/lazy_array.md) speaks positional NumPy, `zarr.Array.lazy` speaks literal. [`zarr_indexing.boundary`](api/boundary.md) is the translation | +| Scheduling | An internal C++ scheduler owns concurrency and chunk ordering | [`parts()`](api/lazy_array.md) exposes the partition structure so the caller's own scheduler β€” dask, a thread pool, a task queue β€” drives it | +| Wire format | Implementation-defined JSON, specified by what the implementation accepts | [ndsel](ndsel.md) is spec-first, with a vendored language-agnostic conformance corpus every implementation runs | +| Backends | A driver ecosystem (zarr, N5, neuroglancer, GCS, …) built into the library | No drivers. The default reader needs `shape`, `dtype`, basic integer/slice indexing, and selected slabs convertible to NumPy system memory; other backends use explicit custom readers. A device reader owns transfer into the supplied system-memory output | + +The mechanics of a +[chunk plan](guide/index.md#a-request-becomes-a-chunk-plan) and its +[paired projections](guide/index.md#one-cell-domain-two-projections) belong to +the visual guide. +The relevant comparison is that both libraries use the paired-transform +boundary rather than a read key plus scatter indices, so slices, outer products, +and correlated gathers remain ordinary transforms that a consumer can lower to +its own execution vocabulary. + +The ownership boundary differs. `plan_chunks` retains only the logical request +and caller-supplied grid; it does not own reads, writes, buffers, locks, or +scheduling. Zarr can therefore plan reads against an inner codec-chunk grid and +writes against an atomic shard grid; napari or dask can turn the same +projections into tasks without putting a dask dependency in this package. +`coverage` is relative to that selected grid: `full` proves a blind replacement +safe, `partial` proves it is not, and `unknown` conservatively covers fancy +selections whose duplicates would require additional work to classify. + +The comparison also runs the other way. TensorStore is a mature, heavily +optimized C++ system whose performance this library cannot approach: resolution +here is Python-level bookkeeping over NumPy, and the per-part overhead is +significant. This library is small and depends on nothing beyond NumPy, so the +algebra can be adopted by a Python project that wants the model without the C++ +runtime. + +## Bounding-box selections vs query selections + +Every selection this library can express falls into exactly one of two +categories. The boundary between them is structural, not a heuristic: + +**A box** is a transform whose output maps are all `ConstantMap` or +`DimensionMap` β€” no `ArrayMap`. Such a map is affine and monotone: storage +coordinate `offset + stride * i` for `i` running over an interval. The whole +selection is therefore described by `O(ndim)` integers β€” an interval and a +stride per dimension β€” composition and intersection are interval arithmetic, +and the coordinates it touches form a regular lattice. Basic indexing produces +one, and composing basic indexing with basic indexing keeps one. + +**A query** is a transform with at least one `ArrayMap` β€” an explicit lookup +table of coordinates. It costs `O(n)` to store, it has no locality (the +coordinates may repeat, reverse, or scatter arbitrarily), and intersecting it +with a region means scanning it. `oindex`, `vindex`, and boolean masks all +produce one, and once an axis is a query, subsequent basic indexing cannot make +it a box again. A second query composes onto any axis of an existing one β€” +including the axes it merely broadcasts along β€” by evaluating the existing +lookup tables at the new coordinates. + +Those coordinate arrays are ordered sequences, never mathematical sets. Their +order and duplicate entries are part of the indexing semantics and must survive +planning and materialization. + +[ndsel](ndsel.md) encodes the same split in its message kinds: `point`, `box`, +and `slice` desugar to constant and affine output maps and are always boxes; +`points` desugars to `index_array` maps, and a `transform` body is a box +exactly when none of its output maps carries an `index_array`. A consumer can +therefore classify a selection off the wire without materializing anything: + +```python +from zarr_indexing import IndexTransform + +IndexTransform.from_shape((100, 80))[10:50, ::4].to_json()["output"] +# [{'offset': 0, 'stride': 1, 'input_dimension': 0}, +# {'offset': 0, 'stride': 4, 'input_dimension': 1}] + +import numpy as np +gather = IndexTransform.from_shape((100, 80)).oindex[np.array([90, 3, 3]), slice(None)] +gather.to_json()["output"][0] +# {'offset': 0, 'stride': 1, 'index_array': [[90], [3], [3]], +# 'index_array_bounds': ['-inf', '+inf']} +``` + +The distinction matters to consumers of a selection. A box can be tiled into +rectangular dask chunks or passed to a viewer or tile server that only accepts +rectangles; a query cannot, and has to be resolved into a gather. A box can also +be served as a single strided slab read, but the read has to be strided: reading +its bounding box and discarding the rest transfers proportionally more data as +soon as any stride exceeds 1. The two also behave differently under +partitioning: a box touches a regularly-spaced run of parts, in increasing +order, each at most once β€” a stride larger than a part's extent skips parts +outright, so the run is not contiguous β€” while a query can touch any subset of +them, in any order, more than once. + +[`LazyArray`](api/lazy_array.md) exposes the category directly: + +```python +import numpy as np +import zarr + +from zarr_indexing import LazyArray + +arr = zarr.create_array({}, shape=(100, 80), chunks=(30, 40), dtype="int32") +arr[:] = np.arange(8000).reshape(100, 80) +lazy = LazyArray(arr) + +slab = lazy.lazy[10:50, ::4] +slab.is_box # True +slab.bounding_box() # ((10, 50), (0, 77)) +slab.strides() # (1, 4) +slab.shape # (40, 20) + +gather = lazy.lazy.oindex[[90, 3, 3], :] +gather.is_box # False +gather.bounding_box() # ((3, 91), (0, 80)) +gather.strides() # None +gather.shape # (3, 80) +``` + +`bounding_box()` is defined for both: it is the hull, the smallest interval per +storage dimension containing every coordinate the selection reaches. +`strides()` is defined only for a box and gives the step per dimension. +Together the two describe a box selection completely. + +Both are needed, because a box is dense in its hull only when every stride is +1. The slab above spans a 40x77 hull over the 40x20 cells it selects, so a +consumer that issued one rectangular read of the hull and discarded the rest +would transfer 3.85x the data. A query's hull is looser still and carries no +stride at all: 88 rows of hull over three selected rows. An empty *box* touches +no coordinate to report an interval around, so `bounding_box()` is `None` while +`strides()` still answers β€” the step is a property of the selection's shape, not +of the region it reaches. Only a query returns `None` from both. + +There is deliberately no separate `BoxView` type today. A statically-typed +rectangular-only view is a plausible next step, but it should be introduced by +a consumer that needs the guarantee in its signatures rather than +speculatively; `is_box` is the runtime check until then. + +## Negative-origin domains and prependable grids + +Literal coordinates let a domain grow at its lower end without changing the +identity of anything already present. Prepending three cells extends `[0, 6)` +to `[-3, 6)`: the new cells receive addresses `-3`, `-2`, and `-1`, while the +old cells keep addresses `0` through `5`. Coordinate `0` does not become +coordinate `3`. + +The adjacent intervals `[-3, 0)`, `[0, 3)`, and `[3, 6)` follow the half-open +adjacency rule: each stopping boundary is included exactly once as the next +interval's starting boundary. + +```text +before [0, 6): + + | 0 1 2 | 3 4 5 | +chunk coordinate | 0 | 1 | + +after [-3, 6): + +| -3 -2 -1 | 0 1 2 | 3 4 5 | +| -1 | 0 | 1 | chunk coordinate +``` + +The same holds for chunk grids. `EdgeDimensionGrid` is the convenient +concrete grid for a zero-origin array: its chunk offsets are prefix sums +starting at zero. `DimensionGridLike` is the more general protocol consumed +by chunk planning, so it admits grids with negative chunk and cell +coordinates, including this prependable example: + +```python +--8<-- "snippets/coordinate_origins.py:prepend-grid" +``` + +Here the literal cell domain `[-3, 0)` belongs to chunk `-1`. Both public +projection transforms share the same synthetic input cell domain `[0, 3)`. +Evaluating its three points shows the two distinct outputs: +`chunk_transform` produces zero-origin chunk-local coordinates `0, 1, 2`, +while `cell_transform` produces the literal request coordinates `-3, -2, -1`. +The shared input domain is not itself the chunk-local coordinate frame. + +## Related work + +TensorStore is the prior art for the transform algebra, as described above. At +the execution boundary, this package instead gives each backend a `ReadContext` +through a `Reader`. Its global transform answers **which values?**; the reader +answers **how does this backend obtain them?** A partition view's transform +directly addresses the raw source in global coordinates. Its optional +projection retains the paired planning transforms, of which only +`chunk_transform` addresses zero-origin chunk-local coordinates. The reader +must preserve the global transform exactly, but it does not participate in +indexing semantics, partitioning, scheduling, or result ownership. + +Earlier versions used a capability taxonomy modeled on historical indexing +dialects. That model required deciding which fragment of a request a backend +could accept and finishing the rest elsewhere. A reader lowers the complete +transform and can compose through delegation instead. This resembles +[zarrita.js store extensions](https://zarrita.dev/packages/zarrita.html), where +storage-specific behavior is an explicit extension point rather than an +inferred array capability. The implementation remains independently authored: +no code is shared with TensorStore, xarray, or zarrita.js. + +## Current scope + +Negative steps are supported as of ndsel 1.0-draft.2: `a[::-1]` reverses, one +desugaring rule covers both signs, and a reversed interval is an error rather +than a silently empty selection. One consequence: a negative step normally +produces a negative domain origin. Reversing a length-20 zero-origin axis gives +the domain `[-19, 1)`, because the result stays anchored to the source +coordinate frame and a reversing map traverses that frame backwards. `LazyArray` +re-bases every view to origin 0, so the positional dialect never exposes it; a +caller working with `IndexTransform` directly will see it, and re-bases +explicitly with `translate_domain_to` for NumPy-shaped coordinates. + +Fancy selections compose without restriction: a second `oindex`/`vindex`/mask +step may land on any axis of an already-fancy view, including axes an existing +index array merely broadcasts along, so +`lazy.oindex[[2, 0], :].lazy.oindex[:, [1, 3]]` selects the outer product it +spells. An array-carrying transform is composed β€” the new selection is applied +to an identity transform over the current domain and chained on with `compose`, +which evaluates the existing lookup tables at the new coordinates β€” rather than +rewritten in place. Resolution classifies the result by structure +(`index_array_structure`): pure per-axis outer products keep the orthogonal +resolvers, and everything else β€” correlated maps, mixtures, index arrays +sharing an input axis (a diagonal gather, reachable only by hand-building a +transform) β€” takes the pointwise path that collapses the joint block. + +Three limits remain, all intentional and all expected to be lifted: + +- **Affine diagonals.** A hand-built transform in which an *index array* and a + *slice map* bind the same input dimension, or two slice maps share one, is + rejected at resolution with `NotImplementedError`. No selection dialect + produces one; supporting them means lowering the slice maps into the joint + block too. *Planned.* +- **Finite explicit bounds only.** `IndexDomain` has no implicit or unbounded + dimensions; the message layer will normalize a body with `"-inf"`/`"+inf"` + bounds, but the engine layer refuses to lower one into a transform. + TensorStore supports both. *Planned.* +- **Labels are carried, not propagated.** `IndexDomain` holds optional + dimension labels and the wire format round-trips them, but indexing + operations build new domains without them, so a label does not survive a + slice. *Planned.* diff --git a/packages/zarr-indexing/docs/examples/lazy_indexing_dask.md b/packages/zarr-indexing/docs/examples/lazy_indexing_dask.md new file mode 100644 index 0000000000..5c722fe355 --- /dev/null +++ b/packages/zarr-indexing/docs/examples/lazy_indexing_dask.md @@ -0,0 +1,7 @@ +--8<-- "lazy_indexing_dask/README.md" + +## Source Code + +```python +--8<-- "lazy_indexing_dask/lazy_indexing_dask.py" +``` diff --git a/packages/zarr-indexing/docs/examples/lazy_indexing_numpy.md b/packages/zarr-indexing/docs/examples/lazy_indexing_numpy.md new file mode 100644 index 0000000000..8a09ce4d01 --- /dev/null +++ b/packages/zarr-indexing/docs/examples/lazy_indexing_numpy.md @@ -0,0 +1,15 @@ +--8<-- "lazy_indexing_numpy/README.md" + +`LazyArray(source)` uses the conservative built-in reader: `source` must expose +`shape`, `dtype`, and basic integer/slice indexing, and every selected slab must +be convertible to NumPy system memory. Coordinate arrays passed through +`oindex` or `vindex` are ordered and duplicate-preserving; they are not sets. +When a view is partitioned, each `Partition.view.transform` addresses the raw +source globally while `Partition.projection.chunk_transform` stays +zero-origin and chunk-local. + +## Source Code + +```python +--8<-- "lazy_indexing_numpy/lazy_indexing_numpy.py" +``` diff --git a/packages/zarr-indexing/docs/examples/system_memory_chunk_cache.md b/packages/zarr-indexing/docs/examples/system_memory_chunk_cache.md new file mode 100644 index 0000000000..e4d92ba2b6 --- /dev/null +++ b/packages/zarr-indexing/docs/examples/system_memory_chunk_cache.md @@ -0,0 +1,11 @@ +--8<-- "system_memory_chunk_cache/README.md" + +`LazyArray` owns the indexing-derived result shape and assembly, while the +example's `SystemMemoryChunkReader` owns synchronous system-memory cache state +and chunk reads for each materialized part. + +## Source Code + +```python +--8<-- "system_memory_chunk_cache/system_memory_chunk_cache.py" +``` diff --git a/packages/zarr-indexing/docs/guide/index.md b/packages/zarr-indexing/docs/guide/index.md new file mode 100644 index 0000000000..780cfd7e56 --- /dev/null +++ b/packages/zarr-indexing/docs/guide/index.md @@ -0,0 +1,444 @@ +# Visual guide + +The whole model in one sentence: indexing through `LazyArray.lazy` builds a +view, chunk planning partitions its coordinates, and `result()` materializes +the view. This page follows one familiar NumPy selection, `source[2:5]`, +through those stages. + +The first four sections are for anyone indexing arrays: coordinates, +transforms, composition, and result axes. **If you are using lazy indexing +rather than building a storage backend, you can stop after section four.** +The last two sections are for integrators: they turn a request into a chunk +plan and pair each chunk read with its place in the result. + +Throughout, one division of labor holds: the transform answers **which +values?** and is independent of the backend; the reader answers **how do I +obtain them?** and must preserve the transform exactly. + +## An index selects coordinates {#an-index-selects-coordinates} + +Begin with an ordinary NumPy array. `source` contains the values 10 through 15. +The selection `source[2:5]` takes source coordinates 2, 3, and 4, containing +the values 12, 13, and 14. + +```text +source coordinate | 0 1 2 3 4 5 +source value | 10 11 12 13 14 15 +selection | [12 13 14] + source[2:5] + +result coordinate | 0 1 2 +source coordinate | 2 3 4 +result value | 12 13 14 +``` + +The result defines its own coordinates: `0`, `1`, and `2`. The aligned rows +make the correspondence explicit: those result coordinates receive values +`12`, `13`, and `14` from source coordinates `2`, `3`, and `4`. + +The wrapper below gives the same familiar selection a lazy spelling. Indexing +through `.lazy` creates `view`; the last line asks for its values and checks the +observable NumPy result. + +```python +--8<-- "snippets/canonical_slice.py:canonical-slice" +``` + +The important first step is simply that an index describes which source values +fill a result in a particular order. The next section gives the numbers on both +sides of that description a precise meaning. + +## Coordinates are addresses {#coordinates-are-addresses} + +### How to read a half-open interval + +`[0, 1)` is a **half-open interval**: start at 0, inclusive, and stop at 1, exclusive. +The `[` includes the lower boundary, while the `)` excludes the upper boundary. +For integer coordinates, `[0, 1)` therefore enumerates the ordered sequence +`[0]`. + +Half-openness lets adjacent slices and chunks meet without a gap or overlap. +Concatenation is ordered: the first interval is followed by the second. When +the first interval's exclusive stop matches the second interval's inclusive +start, the shared boundary coordinate appears exactly once. + +- `[0, 1) -> [0]` β€” Start at 0 and stop before 1, so the sequence contains only 0. +- `[1, 3) -> [1, 2]` β€” Start at 1 and stop before 3, so the sequence contains 1 and 2. +- `concat([0, 1), [1, 3)) = [0, 3)` β€” Append the second interval after the + first. Their matching exclusive/inclusive boundary produces one continuous + interval without a gap or duplicated coordinate. + +Explicit coordinates, including coordinate arrays, are always ordered +sequences rather than mathematical sets. Their order is semantic, and repeated +coordinates remain repeated in the result. + +In the transform algebra, **coordinates are just integers**. A negative +coordinate is a real address in a domain, with the same status as zero or a +positive coordinate; it is not automatically shorthand for counting backward +from an array's end. + +```text +domain [-2, 3) + +coordinate | -2 -1 0 1 2 +status | address address address address address +``` + +`IndexDomain` makes those bounds explicit. In the example below, narrowing the +domain at `-1` selects the literal address `-1`; the wrapper at the end treats +`-1` the way NumPy does β€” as the last position. + +```python +--8<-- "snippets/coordinate_origins.py:coordinate-origin" +``` + +Why carry literal coordinates at all? They let independently described +regions keep stable addresses β€” a domain can even grow at its lower end +without renumbering what is already there. The [design +notes](../design-notes.md#negative-origin-domains-and-prependable-grids) work +through that prepending example; nothing else in this guide depends on it. + +The literal model and NumPy's positional model are both useful, but they answer +different questions: + +| Surface | Meaning of an integer index | Meaning of `-1` | +| --- | --- | --- | +| `IndexDomain` and `IndexTransform` | A literal coordinate in the current domain | The actual address `-1`, if the domain contains it | +| `LazyArray.lazy` | A NumPy-style position in the current view | The last position, normalized before it reaches the transform algebra | + +`LazyArray` uses positions because it is an array-like wrapper: each derived +view starts at position zero and negative indices wrap exactly as they do in +NumPy. The lower-level domain and transform types keep literal coordinates. + +### A transform points from the request to the source + +An `IndexTransform` records how every coordinate in a request finds its source +coordinate. For the slice from the first section, request coordinate `i` maps +to source coordinate `i + 2`. This direction is deliberate: request to source, +not source to request. + +```text +request coordinate | 0 1 2 + | | | | + i + 2 | v v v +source coordinate | 2 3 4 +source value | 12 13 14 +``` + +A transform speaks function vocabulary while this guide speaks array +vocabulary. The two line up like this: + +| the API says | this guide says | +| --- | --- | +| input space (`domain`, `input_rank`) | request coordinates β€” the result being built | +| output space (`output`, one map per dimension) | source coordinates β€” where values are read | + +`output` names the output side of the coordinate *function*, not the data: +values flow source β†’ request, against the arrow. The neutral names exist +because transforms compose β€” in a chain, an interior transform's output space +is just the next transform's input space, neither a request nor a source. + +### The three map kinds, in NumPy terms + +Every output dimension is produced by one of three map forms. Each has a +NumPy counterpart, shown executably below. The examples share one helper β€” +and it doubles as the answer to how a bare transform meets data at all: a +reader materializes it into a buffer. + +```python +--8<-- "snippets/output_maps.py:resolve-helper" +``` + +`DimensionMap` is an arithmetic rule β€” the slice above is one, mapping +request `i` to source coordinate `i + 2`: + +```python +--8<-- "snippets/output_maps.py:dimension-map" +``` + +`ArrayMap` stores explicit source coordinates for irregular or fancy +indexing; order and repeats survive into the result: + +```python +--8<-- "snippets/output_maps.py:array-map" +``` + +`ConstantMap` fixes one source coordinate for every request cell. Whether an +axis appears in the result is decided by the **domain**, never by the map: +`image[2, :]` compiles to a `ConstantMap(2)` with no corresponding domain +axis (the axis is dropped), while pairing a constant map with a length-`n` +domain axis that no map consumes yields `n` cells all reading one +coordinate β€” a broadcast, the one arrangement with no NumPy index +counterpart: + +```python +--8<-- "snippets/output_maps.py:constant-map" +``` + +Together, the request domain and these per-source-dimension maps are the +complete reusable description of an index. + +## Lazy views compose {#lazy-views-compose} + +A lazy view can be indexed again. Each step changes the request-to-source +description, but it does not read an intermediate array. The chain is reduced +to one direct transform from the newest request to the original source. + +```text +source[2:5][::-1][1:] + +new request | intermediate view | original source +------------+-------------------+---------------- + 0 | 1 | 3 + 1 | 2 | 2 + +direct map: request i -> source (3 - i) +``` + +The executable example first selects `source[2:5]`, then reverses that view +and trims its first element: + +```python +--8<-- "snippets/lazy_composition.py:lazy-composition" +``` + +Immediately after `composed` is createdβ€”and before the final `result()` callβ€”its +metadata is ready to inspect: + +| Available without reading | Value in this example | +| --- | --- | +| `composed.shape` | `(2,)` | +| `composed.transform` | One transform mapping request `i` to source `3 - i` | + +Neither property needs source values. Composition works only on the coordinate +description; the assertion's call to `result()` is the first operation in the +example that materializes the selected data. + +!!! warning "Stop here: the materialization boundary" + Indexing through `.lazy[...]` never reads. These do: + + - `result()` + - eager indexing of the wrapper: `view[...]` + - `numpy.asarray(view)`, or passing the view to any NumPy function + (`numpy.add(view, 1)` converts, and therefore materializes, the view) + + Python arithmetic such as `view + 1` raises `TypeError` instead: this + wrapper defers indexing, not a general compute graph. + + Nor does it write. There is no `__setitem__`, so `view[...] = values` + raises `TypeError` too, and a wrapped source needs no `__setitem__` of + its own. A consumer that writes plans the selection with `plan_chunks` + and performs its own read-modify-write, keeping chunk atomicity and + concurrent-writer policy on the backend's side of the boundary. + +## An index defines a result array {#an-index-defines-a-result-array} + +An index chooses source points and also defines how those points are arranged in +the result. In the 3-by-4 image below, `image[1, :]` and `image[1:2, :]` choose +the same four source points: values `4`, `5`, `6`, and `7`. + +```text +same selected source cells + +source coordinate | (1, 0) (1, 1) (1, 2) (1, 3) +value | 4 5 6 7 + +image[1, :] + +result coordinate | 0 1 2 3 +value | 4 5 6 7 +shape | (4,); source axis 0 is omitted + +image[1:2, :] + +result coordinate | (0, 0) (0, 1) (0, 2) (0, 3) +value | 4 5 6 7 +shape | (1, 4); source axis 0 is retained with length 1 +``` + +The integer in `image[1, :]` fixes source axis 0. No result coordinate varies +along that axis, so it is omitted and the result shape is `(4,)`. The slice in +`image[1:2, :]` preserves source axis 0 as a length-one result axis, so the +result shape is `(1, 4)`. + +```python +--8<-- "snippets/axis_manipulation.py:axis-shape-comparison" +``` + +`None` inserts a new length-one axis without selecting different source points. +Here it produces the shape `(4, 1)`: + +```python +--8<-- "snippets/axis_manipulation.py:axis-insertion" +``` + +## A request becomes a chunk plan {#a-request-becomes-a-chunk-plan} + +Continue with the 3-by-4 image and `image[1, :]` introduced above. Giving the +image a 2-by-2 chunk shape does not change the four selected values or their +order. It changes only how the work is divided: columns 0 and 1 come from chunk +`(0, 0)`, while columns 2 and 3 come from chunk `(0, 1)`. + +```text + column + 0 1 | 2 3 + ----------+---------- +row 0 0 1 | 2 3 +row 1 [4] [5]| [6] [7] <- image[1, :] + ----------+---------- +row 2 8 9 | 10 11 + + left part right part +chunk_coords (0, 0) (0, 1) +global chunk_domain [0,2) x [0,2) [0,2) x [2,4) +selected global cells (1,0), (1,1) (1,2), (1,3) +chunk-local cells (1,0), (1,1) (1,0), (1,1) +request coordinates 0, 1 2, 3 +``` + +Every planned chunk keeps three coordinate frames distinct: + +- `chunk_coords` identifies a cell in the chunk grid. Chunk coordinates are + literal integers, so a grid that grows at its lower end can hold a chunk + whose coordinate really is `-1` β€” not an alias for the final chunk (see the + [design notes](../design-notes.md#negative-origin-domains-and-prependable-grids)). +- `chunk_domain` gives that chunk's bounds in **global source coordinates**. + Here the two domains are `[0, 2) Γ— [0, 2)` and `[0, 2) Γ— [2, 4)`. +- Chunk-local positions start from zero inside each chunk. Global column 2 is + therefore local column 0 in chunk `(0, 1)`. This zero-origin local frame is + separate from both the global `chunk_domain` and the possibly negative + chunk coordinate. + +`plan_chunks` needs only a transform and the chunk layout: one grid object +per source dimension. A per-dimension grid answers four questions β€” which +chunk contains a source index, where a chunk starts, how long it is, and +the vectorized form of the first (`index_to_chunk`, `chunk_offset`, +`chunk_size`, `indices_to_chunks`). The library builds these from chunk +sizes via `dimension_grids_from_chunks`; the executable example hand-rolls +one instead, to show that the whole contract is those four answers. It +plans the canonical request over 2-by-2 chunks, and iterates the same plan +again to show that planning is reusable. (The two transforms it inspects on +each projection are the next section's subject.) + +```python +--8<-- "snippets/chunk_projection.py:chunk-projection" +``` + +The plan describes work but does not perform it. It contains no array source, +storage backend, codec pipeline, buffer, or scheduler. A Zarr reader, a task +queue, or a viewport can consume the same logical plan and decide independently +how and when to fetch its two chunks. + +On the wrapper, this partitioning is called **parts**: `with_parts(shape)` +gives a `LazyArray` a grid of uniform boxes to divide its reads along +(re-partitioning is a pure setter β€” it changes how a read is divided, never +what `result()` returns), and a wrapped array advertising its own `chunks` +is partitioned that way automatically. + +A zero-length source axis has no chunks. `LazyArray` accepts a positive uniform +part shape for that axis, or explicit per-axis spellings `()`, `(0,)`, and +`(0, 0)`; each produces no parts and the same empty result. Zero-sized parts +remain invalid on a nonempty axis. + +## One cell domain, two projections {#one-cell-domain-two-projections} + +A chunk read has to answer two questions at once: which cells belong to this +chunk, and where does each of those cells belong in the requested result? + +Think of a projection as a small table with one row per selected cell. For +each row, `chunk_transform` gives the cell's zero-origin address inside the +chunk, and `cell_transform` gives the position in the requested result that +receives its value. The row numbers of that table are the shared **cell +domain** β€” a synthetic input space both transforms accept, which is why one +input point can be evaluated on both sides. + +```text +left chunk (0, 0) + +shared cell coordinate | 0 1 +cell_transform | v v +request coordinate | 0 1 + +shared cell coordinate | 0 1 +chunk_transform | v v +chunk-local coordinate | (1, 0) (1, 1) + +right chunk (0, 1) + +shared cell coordinate | 0 1 +request coordinate | 2 3 +chunk-local coordinate | (1, 0) (1, 1) +``` + +The directions are exact: **shared synthetic input cell domain β†’ request via +`cell_transform`**, and **shared cell domain β†’ chunk-local via +`chunk_transform`**. Neither arrow starts at the request or maps one output +space into the other. + +On the wrapper, `view.parts()` returns one `Partition` per planned chunk; +each bundles a sub-view of the request (`.view`), that chunk's projection +(`.projection`), and the NumPy selection placing its values in the result +(`.out_selection`). + +Within one `Partition`, the frames divide: `Partition.view.transform` is a +different, global transform β€” it maps the part view directly into the raw +wrapped source β€” while only `Partition.projection.chunk_transform` uses +zero-origin chunk-local coordinates. Readers receive both so the global +source address and the local planning frame cannot be confused. + +| Projection field | What its output coordinates mean | +| --- | --- | +| `cell_transform` | Literal coordinates in the original request; its output rank is the request rank | +| `chunk_transform` | Zero-origin coordinates in the selected chunk's local frame; its output rank is the source rank | + +The cell domain enumerates corresponding cells; it is not itself either +output coordinate space. The canonical row selection has a one-dimensional +request and a two-dimensional source, so its paired projections have request +rank one and source rank two. + +### Order and duplicates need the request-side projection + +Orthogonal indexing (`.lazy.oindex`) applies each axis's indexer +independently, like `numpy.ix_` β€” an outer product; the +[pattern reference](patterns.md) develops the dialects. It can visit source +cells in an order that does not match chunk order, and it can visit one +source cell more than once. In the request below, row 4 comes first and +row 1 appears twice. + +```text +request position | 0 1 2 +source row | 4 1 1 +result row | row 4 row 1 row 1 +``` + +A source bounding box cannot reconstruct this result. The box spanning rows 1 +through 4 also includes unrequested rows 2 and 3, and its increasing coordinate +order does not record that row 4 comes first. Narrowing the read to just rows 1 +and 4 still does not record the second use of row 1. For the same reason, a +chunk-local selector alone says which cells to read inside a chunk but cannot +say which request positions receive them, especially when the chunks are +processed in a different order. + +The executable example assembles the 3-by-4 request from a 6-by-8 source with +3-by-4 chunks. Each `Partition` resolves its own sub-view β€” the global +transform addressing the raw source β€” and `out_selection` places those +values at their request-side positions; the paired projection stays +available on `part.projection` for consumers that read chunks directly. +The assertion checks the reordered, duplicated result against direct NumPy +indexing. + +```python +--8<-- "snippets/chunk_projection.py:advanced-projection" +``` + +The paired representation preserves information that a bounding box or local +selector discards: exact request order, duplicate destinations, and the +correspondence between every request position and its chunk-local source cell. + +--- + + diff --git a/packages/zarr-indexing/docs/guide/integrations.md b/packages/zarr-indexing/docs/guide/integrations.md new file mode 100644 index 0000000000..03661ed43c --- /dev/null +++ b/packages/zarr-indexing/docs/guide/integrations.md @@ -0,0 +1,214 @@ +# Integration boundaries + +This package supplies indexing plans. It does **not** supply scheduling, +caching, codecs, or async orchestration. A consumer decides when projections +run, how decoded chunks are obtained, and where completed values are retained. +An `IndexTransform` says which source values belong in a result; a `Reader` +lowers that complete transform for one backend. The reader does not choose +indexing semantics or result ownership. + +## Zarr chunk dispatch + +A Zarr-oriented reader can consume each public `ChunkProjection` and use its +`chunk_coords` to obtain one decoded chunk from its own storage and codec +layers. This tiny source keeps four in-memory chunks keyed by their global +chunk coordinates and records the exact reads. For each projection, the +consumer enumerates the shared synthetic input cell domain, evaluates +`chunk_transform` to read zero-origin chunk-local coordinates, and evaluates +`cell_transform` to place each value at its literal request coordinate. + +```python +--8<-- "snippets/integrations.py:zarr-consumer" +``` + +The two reads are exactly `(0, 0)` and `(0, 1)`; untouched chunks `(1, 0)` and +`(1, 1)` are never read. The assembled request is `[4, 5, 6, 7]`. The +example intentionally begins with already decoded in-memory chunks: storage +keys, codecs, scheduling, caching, and asynchronous orchestration remain the +consumer's policy rather than responsibilities of the plan. + +## One slab read or many part reads + +A backend with its own native subset read β€” a Rust or C zarr implementation, +a database, an HTTP range endpoint β€” resolves a **dense box** (`is_box` with +every stride 1) best as a single read: hand it the whole selection and let it +dispatch to chunks, decode in parallel, and partial-decode shards on its own +side of the boundary. Splitting that read along this library's partitioning +only adds round-trips. Every **other** selection β€” a strided box, an `oindex` +or `vindex` gather β€” is where the partitioning earns its keep. The **cover** +of a read is the smallest step-1 slab enclosing every coordinate it needs; +partitioned, each part's cover is bounded by that part's box, so a sparse +selection can never force one read of its whole bounding hull (the smallest +rectangle containing every selected coordinate β€” a thousand rows for the two +of `oindex[[0, 999]]`). + +The composed view carries enough to make that call at materialization time, +and re-partitioning is a pure setter, so the policy is three lines: + +```python +--8<-- "snippets/integrations.py:dense-box-repartition" +``` + +The corner gather reads four single cells instead of the 10-by-10 hull, and +the dense box becomes exactly one backend call. Both regimes go through +`result()`; only the partitioning in force differs. + +### Sources that accept only unit-step slices + +The default `basic_reader` pushes strided and descending selections down as +positive-step slices, which reads the minimum but assumes the source accepts +any step. Many backends do not: FFI bindings and range requests often +support nothing but `slice(start, stop, 1)`. Select +[`unit_step_reader`][zarr_indexing.reader.UnitStepReader] for such a source +and every key it receives is an ascending unit-step slice per axis, with +strides, reversals, and gathers applied to the in-memory block instead: + +```python +view = LazyArray(source).with_reader(unit_step_reader) +``` + +A strided selection then over-reads its cover by the stride factor, which the +partitioning above bounds by one part. + +## napari-like consumer + +This is a **napari-like consumer**, not a napari integration. It models the +boundary a viewport could use without importing or claiming support for +napari. `RecordingArray` exposes a chunked, basic-indexing source β€” and its +`chunks` attribute is why the reads below split along `(2, 2)` boxes: +`LazyArray` discovers a partitioning from the wrapped array at construction +(`read_chunk_sizes`, then `chunks`), with `with_parts` as the explicit +override. Composing the +visible slice records no reads. Only `result()` materializes it, with the exact +source selectors `1:2, 0:2` and `1:2, 2:4`; neither selector crosses into an +untouched neighboring chunk. + +```python +--8<-- "snippets/integrations.py:viewport-consumer" +``` + +The viewport owns its interaction loop and any cancellation, caching, or +background execution. `LazyArray` contributes the composable selection and +the partition plan, then resolves only when the consumer asks for the result. + +### A system-memory chunk cache + +Napari accepts NumPy-like array objects and can defer materialization until an +image region is displayed. The indexing plan still deliberately owns no cache +or scheduler. A viewport adapter can place that policy around the plan, as the +executable reference below demonstrates. + +This remains a **napari-like consumer, not a napari integration**. It models +only decoded chunks resident in system memory, synchronously. + +For setup instructions and the complete executable, see the +[system-memory chunk cache example](../examples/system_memory_chunk_cache.md). + +```text + read succeeds +NEW -> QUEUED -> LOADING -------------> READY -> EVICTED + ^ | + | | read fails + | v + +--------- FAILED + retry + +EVICTED -> QUEUED + reload +``` + +The example keeps the lifecycle records and transitions explicit: + +```python +--8<-- "system_memory_chunk_cache/system_memory_chunk_cache.py:chunk-cache-types" +``` + +Its source represents already decoded chunks and records each read: + +```python +--8<-- "system_memory_chunk_cache/system_memory_chunk_cache.py:chunk-cache-source" +``` + +`LazyArray` converts a cache selection into transforms and partitions, then +allocates and assembles the result. The facade constructs exactly one tuple +from `view.parts()`: it derives the chunk coordinates to pin from that tuple, +then passes the same owned parts to `view.result(parts=parts)`. Planning is +therefore performed once for the request rather than repeated during +materialization. Neither pinning nor the result call rebuilds the plan; both +reuse those prepared `Partition` objects. + +`SystemMemoryChunkReader` receives one `ReadContext` for each materialized +part. Its global `context.transform` directly addresses the raw source, while +`context.projection.chunk_transform` addresses the already identified chunk +locally. The reader consumes that supplied projection directly; it never calls +the chunk planner. `LazyArray` retains responsibility for the projection's +result placement and final assembly. The reader owns only cache state and +source reads, while `SystemMemoryChunkCache` remains the thin NumPy-style facade +that prepares and pins the one plan: + +Its indexing dialects remain explicit: `cache[key]` accepts basic indexing +(integers, slices, ellipsis, and new axes), while `cache.oindex[key]` combines +per-axis index arrays as an outer product. Array keys are not silently treated +as orthogonal by plain square brackets; callers choose that behavior through +the named accessor. + +```python +--8<-- "system_memory_chunk_cache/system_memory_chunk_cache.py:chunk-cache-wrapper" +``` + +### Follow one viewport through the cache + +```python +--8<-- "system_memory_chunk_cache/system_memory_chunk_cache.py:chunk-cache-worked-example" +``` + +The worked example uses a 6-by-8 image, 3-by-4 chunks, and capacity for two +decoded chunks. Every read delta follows directly from the viewport request: + +| Step | Viewport | New reads | Resident afterward | Why | +| --- | --- | --- | --- | --- | +| 1 | `image[1:5, 2]` | `(0, 0)`, `(1, 0)` | `(0, 0)`, `(1, 0)` | Both projected chunks are loaded and assembled as `[10, 18, 26, 34]`. | +| 2 | `image[3:5, 2]` | None | `(0, 0)`, `(1, 0)` | The ready buffer for `(1, 0)` is reused and becomes most recently used. | +| 3 | `image[0:2, 5]` | `(0, 1)` | `(0, 1)`, `(1, 0)` | Placement returns `[5, 13]`, then LRU pressure evicts `(0, 0)`. | +| 4 | `image[1:5, 2]` | `(0, 0)` | `(0, 0)`, `(1, 0)` | The evicted chunk is reloaded while the required ready chunk is retained. | +| 5 | `image[3:5, 4:6]` | `(1, 1)` fails; no repeated read; `(1, 1)` succeeds after retry | `(0, 0)`, `(1, 1)` | Failure is retained until explicit retry; the repaired source then returns `[[28, 29], [36, 37]]`. | + +Chunks required by an active request are pinned through assembly, so a request +may temporarily span more chunks than the steady-state capacity. Capacity is +counted in decoded chunksβ€”not records or bytesβ€”and eviction occurs only after +all requested values have been placed. Because pinning and materialization use +the same prepared tuple, those lifecycle decisions cannot drift from the parts +that are actually read, and the cache never has to infer or reconstruct a +projection. + +The event log makes the failure boundary equally explicit: + +| Chunk | Transition | Reason | +| --- | --- | --- | +| `(1, 1)` | `NEW -> QUEUED` | requested | +| `(1, 1)` | `QUEUED -> LOADING` | queue drained | +| `(1, 1)` | `LOADING -> FAILED` | source read failed | +| `(1, 1)` | `FAILED -> QUEUED` | explicit retry | +| `(1, 1)` | `QUEUED -> LOADING` | queue drained | +| `(1, 1)` | `LOADING -> READY` | source read completed | + +A repeated request while the record is `FAILED` creates no event and performs +no source read. The retained failure forces the caller to choose when retry is +appropriate. A real viewport adapter could drain the queue in workers and +invalidate its canvas when chunks become ready without changing the selection +or projection semantics shown here. + +[Napari's image-layer documentation](https://napari.org/dev/howtos/layers/image.html) +describes its NumPy-like array boundary. Neuroglancer's +[`ChunkState`](https://github.com/google/neuroglancer/blob/master/src/chunk_manager/base.ts) +is conceptual prior art for making residency explicit. This example is a +smaller, independently authored, synchronous teaching model; it does not copy +that implementation or reproduce its full worker/GPU lifecycle. + +--- + + diff --git a/packages/zarr-indexing/docs/guide/patterns.md b/packages/zarr-indexing/docs/guide/patterns.md new file mode 100644 index 0000000000..9c3501da8a --- /dev/null +++ b/packages/zarr-indexing/docs/guide/patterns.md @@ -0,0 +1,327 @@ +# Indexing pattern reference + +Every NumPy indexing idiom is modeled by an `IndexTransform`: a domain (the +result's coordinates) and one output map per source dimension. This page +builds that model **by hand for each idiom**, so the anatomy is explicit β€” +which map kind an idiom needs, where the offset and stride go, and how an +index array's shape spells outer-product versus pointwise. Each model is +then proven equal to what the selection compiler derives, and its values +are checked against NumPy. + +## The idiom-to-model matrix + +Each idiom over a 6-by-8 `image`, shown two ways: the Python construction, +and the same transform in **wire form** β€” the [ndsel](../ndsel.md) +canonical body `to_json` produces. Both spell the whole +object: a domain whose extent is the result shape, then one output map per +source dimension. The index-array variables (`rows`, `columns`, +`mask_rows, mask_columns = np.nonzero(mask)`, and friends) are defined in +the executable matrix at the end of the page. + +**`image[1:5, ::2]`** β€” box. The offset picks where cell 0 reads; the +stride skips: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((4, 4)), + output=( + DimensionMap(input_dimension=0, offset=1), + DimensionMap(input_dimension=1, stride=2), + ), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [4, 4], + "input_labels": ["", ""], + "output": [ + {"offset": 1, "stride": 1, "input_dimension": 0}, + {"offset": 0, "stride": 2, "input_dimension": 1} + ] + } + ``` + +**`image[2, :]`** β€” box. A rank-1 domain with two output maps: the dropped +axis survives as the wire's constant form, a bare `{"offset": 2}`: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((8,)), + output=(ConstantMap(2), DimensionMap(input_dimension=0)), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [8], + "input_labels": [""], + "output": [ + {"offset": 2}, + {"offset": 0, "stride": 1, "input_dimension": 0} + ] + } + ``` + +**`image[::-2, :]`** β€” box. Reversal is nothing but a negative stride, and +the offset is where cell 0 reads (row 5): + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((3, 8)), + output=( + DimensionMap(input_dimension=0, offset=5, stride=-2), + DimensionMap(input_dimension=1), + ), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [3, 8], + "input_labels": ["", ""], + "output": [ + {"offset": 5, "stride": -2, "input_dimension": 0}, + {"offset": 0, "stride": 1, "input_dimension": 1} + ] + } + ``` + +**`image[2:2, :]`** β€” box. Emptiness lives in the domain +(`input_exclusive_max[0]` equals the minimum); the maps are ordinary: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((0, 8)), + output=( + DimensionMap(input_dimension=0, offset=2), + DimensionMap(input_dimension=1), + ), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [0, 8], + "input_labels": ["", ""], + "output": [ + {"offset": 2, "stride": 1, "input_dimension": 0}, + {"offset": 0, "stride": 1, "input_dimension": 1} + ] + } + ``` + +**`image[mask]`** β€” query. A mask is its nonzero coordinates: two +correlated index arrays over one flat axis, entry `i` of each pairing into +one cell: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(ArrayMap(mask_rows), ArrayMap(mask_columns)), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [10], + "input_labels": [""], + "output": [ + {"offset": 0, "stride": 1, "index_array": [0, 0, 1, 1, 2, 3, 3, 4, 5, 5], "index_array_bounds": ["-inf", "+inf"]}, + {"offset": 0, "stride": 1, "index_array": [0, 5, 2, 7, 4, 1, 6, 3, 0, 5], "index_array_bounds": ["-inf", "+inf"]} + ] + } + ``` + +**`image[np.ix_(rows, columns)]`** β€” query. The outer product is spelled by +nesting: `[[4], [1], [1]]` varies down the first axis, `[[2, 5]]` across +the second, each singleton along the other: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((3, 2)), + output=(ArrayMap(rows.reshape(3, 1)), ArrayMap(columns.reshape(1, 2))), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [3, 2], + "input_labels": ["", ""], + "output": [ + {"offset": 0, "stride": 1, "index_array": [[4], [1], [1]], "index_array_bounds": ["-inf", "+inf"]}, + {"offset": 0, "stride": 1, "index_array": [[2, 5]], "index_array_bounds": ["-inf", "+inf"]} + ] + } + ``` + +**`image[vector_rows, vector_columns]`** β€” query. Pointwise: two flat +arrays over one shared axis: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(vector_rows), ArrayMap(vector_columns)), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [3], + "input_labels": [""], + "output": [ + {"offset": 0, "stride": 1, "index_array": [4, 1, 1], "index_array_bounds": ["-inf", "+inf"]}, + {"offset": 0, "stride": 1, "index_array": [2, 5, 2], "index_array_bounds": ["-inf", "+inf"]} + ] + } + ``` + +**`image[broadcast_rows, broadcast_columns]`** β€” query. NumPy broadcasting, +materialized: each map carries the full `(2, 3)` block: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((2, 3)), + output=( + ArrayMap(np.broadcast_to(broadcast_rows, (2, 3))), + ArrayMap(np.broadcast_to(broadcast_columns, (2, 3))), + ), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [2, 3], + "input_labels": ["", ""], + "output": [ + {"offset": 0, "stride": 1, "index_array": [[0, 0, 0], [3, 3, 3]], "index_array_bounds": ["-inf", "+inf"]}, + {"offset": 0, "stride": 1, "index_array": [[1, 4, 6], [1, 4, 6]], "index_array_bounds": ["-inf", "+inf"]} + ] + } + ``` + +**`image[rows, 2:6]`** β€” query. One lookup table (order and repeats kept) +beside one ordinary affine map β€” one index array makes the whole selection +a query: + +=== "Python" + + ```python + IndexTransform( + domain=IndexDomain.from_shape((3, 4)), + output=( + ArrayMap(rows.reshape(3, 1)), + DimensionMap(input_dimension=1, offset=2), + ), + ) + ``` + +=== "JSON" + + ```json + { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [3, 4], + "input_labels": ["", ""], + "output": [ + {"offset": 0, "stride": 1, "index_array": [[4], [1], [1]], "index_array_bounds": ["-inf", "+inf"]}, + {"offset": 2, "stride": 1, "input_dimension": 1} + ] + } + ``` + +Two structural rules do all the work: + +- **Category**: `ConstantMap` and `DimensionMap` entries keep a selection a + box at any composition depth; one `ArrayMap` makes it a query permanently. + See the [design notes](../design-notes.md#bounding-box-selections-vs-query-selections) + for why consumers dispatch on this. +- **Fancy flavor is spelled by shape**: index arrays varying over distinct + axes (singleton elsewhere) form an outer product; arrays sharing their + non-singleton axes pair pointwise. + +## The executable matrix + +Each case hand-builds the model, checks shape, category, and NumPy values +(resolved through the public reader), then proves the selection compiler +derives the same transform. One wrinkle the last assert documents: compiled +*basic* selections keep literal domains (`t[1:5, ...]` starts at +coordinate 1 β€” see [Positions vs literal coordinates](#positions-vs-literal-coordinates)), +so they equal the zero-origin models after `translate_domain_to`: + +```python +--8<-- "snippets/indexing_patterns.py:indexing-patterns" +``` + +`LazyArray` adds nothing to these semantics: it is a regular array-like API +whose `.lazy`, `.lazy.oindex`, and `.lazy.vindex` accessors compile the same +dialects to the same transforms β€” the only difference is the return type, a +view instead of an array. The test suite holds the wrapper to this matrix. + +## Positions vs literal coordinates + +| Surface | Meaning of an integer index | Meaning of `-1` | +| --- | --- | --- | +| `IndexDomain` and `IndexTransform` | A literal coordinate in the current domain | The address `-1`, when the domain contains it | +| `LazyArray.lazy` | A NumPy-style position in the current view | The last position, normalized before transform composition | + +The wrapper's three indexing modes all use positions in the current view. Each +derived view begins at position zero, while the transform algebra underneath +retains literal coordinates. The +[Coordinates are addresses](index.md#coordinates-are-addresses) section develops +that distinction with non-zero and negative-origin domains. + +--- + + diff --git a/packages/zarr-indexing/docs/index.md b/packages/zarr-indexing/docs/index.md new file mode 100644 index 0000000000..1dd151d8ca --- /dev/null +++ b/packages/zarr-indexing/docs/index.md @@ -0,0 +1,53 @@ +# zarr-indexing + +This library is for modelling and transforming NumPy-style array indexing expressions. It separates +the *declaration* of an array indexing expression from the result of that expression. + +Developed for use in [`zarr`](https://zarr.readthedocs.io). + +Inspired by [TensorStore](https://google.github.io/tensorstore/), which pioneered +the approach used here. + + +## Install + +`zarr-indexing` is developed in the +[zarr-python repository](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-indexing) +and released independently of `zarr` itself: + +``` +pip install zarr-indexing +``` + +## Quickstart + +Wrap an array, compose a lazy view through `.lazy`, and call `result()` when +you want its values: + +```python +--8<-- "snippets/canonical_slice.py:landing-quickstart" +``` + +Nothing is read until the `result()` call, however many selections are +composed. [Lazy views compose](guide/index.md#lazy-views-compose) shows how +the chain stays one description, and where the materialization boundary is. + +## Learn more + +- [Visual guide](guide/index.md) β€” one selection followed from coordinates to + chunk plan. Using lazy indexing, start at + [An index selects coordinates](guide/index.md#an-index-selects-coordinates); + integrating a chunked backend, start at + [A request becomes a chunk plan](guide/index.md#a-request-becomes-a-chunk-plan). +- [Indexing pattern reference](guide/patterns.md) β€” every selection form with + its NumPy-verified result. +- [Integration boundaries](guide/integrations.md) β€” what a reader, writer, or + scheduler owns, and what the plan owns. +- [Lazy indexing a NumPy array](examples/lazy_indexing_numpy.md) and + [with Dask](examples/lazy_indexing_dask.md) β€” runnable examples. +- [The ndsel wire format](ndsel.md) β€” the JSON form of a selection. +- [Design notes](design-notes.md) β€” TensorStore lineage, box vs query, and + deliberate limits. +- [API reference](api/index.md) +- [Changelog](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-indexing/CHANGELOG.md) + Β· [License (MIT)](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-indexing/LICENSE.txt) diff --git a/packages/zarr-indexing/docs/ndsel.md b/packages/zarr-indexing/docs/ndsel.md new file mode 100644 index 0000000000..94971d49bf --- /dev/null +++ b/packages/zarr-indexing/docs/ndsel.md @@ -0,0 +1,159 @@ +--- +title: The ndsel wire format +--- + +# The ndsel wire format + +[ndsel](https://github.com/zarr-developers/ndsel) is a draft JSON +representation of NumPy-style n-dimensional selections, adapted from +TensorStore's `IndexTransform` model. This page documents the wire format, not +the coordinate model: [Coordinates are addresses](guide/index.md#coordinates-are-addresses) +introduces literal coordinates, and +[Lazy views compose](guide/index.md#lazy-views-compose) shows how views combine +before a transform is serialized. `zarr-indexing` implements ndsel in two layers: + +| Layer | Module | Depends on | Job | +| --- | --- | --- | --- | +| Message | [`zarr_indexing.messages`](api/messages.md) | stdlib only | JSON in, canonical JSON out. Validates and desugars. Never rounds, clamps, or drops information. | +| Engine | [`zarr_indexing.json`](api/json.md) | NumPy | Lowers a *canonical* body into an in-memory [`IndexTransform`](api/transform.md), and back. | + +Constraints that only make sense for a real array β€” finite bounds, index +arrays as `ndarray`s β€” live in the engine layer and nowhere else. As a result, +`messages` normalizes a message with `"-inf"` bounds that +`IndexTransform.from_json` refuses to lower. + +## Two entry points + +[`parse_ndsel`](api/messages.md#zarr_indexing.messages.parse_ndsel) +structurally validates a message of any kind and returns it unchanged. Use it +to confirm that a message is well formed while keeping it in its compact +shorthand form. + +[`normalize_ndsel`](api/messages.md#zarr_indexing.messages.normalize_ndsel) +desugars a message into the single deterministic **canonical transform body** +of the spec (section 4.3): a bare `IndexTransform` body without the `kind` +discriminator. + +```python +from zarr_indexing import normalize_ndsel + +normalize_ndsel({"kind": "box", "inclusive_min": [10, 5], "shape": [40, 1]}) +# {'input_rank': 2, +# 'input_inclusive_min': [10, 5], +# 'input_exclusive_max': [50, 6], +# 'input_labels': ['', ''], +# 'output': [{'offset': 0, 'stride': 1, 'input_dimension': 0}, +# {'offset': 0, 'stride': 1, 'input_dimension': 1}]} +``` + +Normalization is idempotent: re-tag the output with `kind: "transform"` and +normalizing it again returns the same body. Because the canonical body is +field-for-field a TensorStore `IndexTransform` minus `kind`, a normalized +message loads directly into `tensorstore.IndexTransform(json=...)`. + +Both entry points raise +[`NdselError`](api/messages.md#zarr_indexing.messages.NdselError), which +carries the spec `reason` code (`unknown_kind`, `rank_mismatch`, `step_zero`, +`output_map_conflict`, …) alongside a human-readable detail, so callers can +branch on the code rather than on message text. + +## The five message kinds + +Four are shorthands; the fifth is the canonical form itself. + +| `kind` | Fields | Selects | +| --- | --- | --- | +| `point` | `coords` | A single element. Normalizes to rank 0 with one `constant` output map per dimension. | +| `box` | `inclusive_min`, one of `exclusive_max` / `inclusive_max` / `shape`, `labels` | A rectangular region. Exactly one upper-bound spelling may appear. | +| `slice` | `start`, `stop`, `step`, `labels` | A strided region, one Python-style slice per dimension. | +| `points` | `coords` (a list of coordinate rows) | An explicit list of points β€” the `vindex` case. Normalizes to one `index_array` output map per dimension over a shared rank-1 input domain. | +| `transform` | `input_rank`, `input_inclusive_min`, one of the three `input_*` upper bounds, `input_labels`, `output` | The full canonical form. | + +Value rules the message layer enforces throughout: every integer is a 64-bit +signed value; JSON booleans are **not** integers (Python's +`isinstance(True, int)` is guarded against explicitly); the `"-inf"` / `"+inf"` +sentinels are legal only in bound positions; and an implicit bound is the +one-element `[n]`-bracket form, whose implicit/explicit flag survives +normalization intact. + +## Lowering to a transform + +The engine layer converts between canonical bodies and `IndexTransform`s: + +```python +from zarr_indexing import IndexTransform + +t = IndexTransform.from_json(canonical) +t.to_json() == canonical +``` + +`IndexDomain` carries the same pair for a bare domain body, and each output +map kind has a `to_json`; `output_index_map_from_json` dispatches the wire's +tagged union back to the right kind. + +Two engine constraints apply here and only here. A canonical body carrying a +`"-inf"` or `"+inf"` bound cannot be lowered β€” an `IndexDomain` addresses a +finite array β€” so `IndexTransform.from_json` raises. And implicit bounds lower +*by value*: the `[n]`-bracket flag is a message-layer concern, and the engine +keeps only the integer. + +### The `index_array` round trip + +ndsel and TensorStore both **reject** an output map that carries both +`input_dimension` and `index_array`. The in-memory +[`ArrayMap`](api/output_map.md#zarr_indexing.output_map.ArrayMap), though, +records an `input_dimension` to pin the axis an orthogonal (`oindex`) array +varies over. The serializer bridges that gap in both directions: + +- **On serialize**, a non-degenerate `index_array` map is emitted *without* + `input_dimension`. +- **On load**, the in-memory `input_dimension` is reconstructed from the + full-rank array's dependency axes β€” its non-singleton axes. An array that + solely owns a single non-singleton axis is orthogonal; arrays that share + non-singleton axes, or vary over several, are correlated (`vindex`), and get + `input_dimension = None`. A single 1-D array over a rank-1 domain is + inherently ambiguous between the two flavors and reconstructs as + orthogonal, which is behaviorally identical in that case. + +There is one deliberate exception, and it is the only place a round trip changes +representation rather than preserving it. An all-singleton `index_array` β€” size +1 β€” selects the same coordinate regardless of the input, so it is collapsed to +a `constant` map on serialize: + +```python +from zarr_indexing import IndexTransform + +IndexTransform.from_shape((100, 100)).oindex[[5], 0:2].to_json() +# {'input_rank': 2, +# 'input_inclusive_min': [0, 0], +# 'input_exclusive_max': [1, 2], +# 'input_labels': ['', ''], +# 'output': [{'offset': 5}, +# {'offset': 0, 'stride': 1, 'input_dimension': 1}]} +``` + +The size-1 input dimension stays in the domain, unconsumed by any output map. +The transform is still valid and the output shape is unchanged. A length-1 +`oindex` selection therefore round-trips behaviorally (an `ArrayMap` comes back +as a `ConstantMap`) rather than by object identity. + +## Conformance + +The package is checked against the language-agnostic ndsel conformance corpus, +vendored unmodified under +[`tests/conformance/`](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-indexing/tests/conformance) +β€” one JSON file per message kind plus `errors.json`, with the source commit +recorded in `PROVENANCE.md`. Each fixture is either a *success* case +(`input` + expected `normalized` body) or an *error* case (`input` + expected +reason code), and an implementation is conformant iff `normalize` reproduces +every one. `tests/test_conformance.py` runs the whole corpus as one +parametrized test per fixture, so a corpus update reports failures fixture by +fixture rather than as a single opaque assertion. + +Do not edit the vendored files; to pick up spec changes, re-vendor from a newer +ndsel commit and update the recorded SHA. + +A second, optional test (`tests/test_ndsel_tensorstore.py`, skipped unless +`tensorstore` is installed) checks against TensorStore itself by loading +canonical bodies into `tensorstore.IndexTransform` and re-loading TensorStore's +own `to_json()` output back through the engine layer. diff --git a/packages/zarr-indexing/docs/snippets/axis_manipulation.py b/packages/zarr-indexing/docs/snippets/axis_manipulation.py new file mode 100644 index 0000000000..1d1369fd87 --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/axis_manipulation.py @@ -0,0 +1,29 @@ +"""Indexing defines result axes as well as selected source points.""" + +import numpy as np + +from zarr_indexing import LazyArray + +# --8<-- [start:axis-shape-comparison] +image = np.arange(12).reshape(3, 4) +lazy = LazyArray.from_numpy(image) + +integer_view = lazy.lazy[1, :] +slice_view = lazy.lazy[1:2, :] + +INTEGER_RESULT = integer_view.result() +SLICE_RESULT = slice_view.result() + +assert INTEGER_RESULT.tolist() == [4, 5, 6, 7] +assert INTEGER_RESULT.shape == (4,) +assert SLICE_RESULT.tolist() == [[4, 5, 6, 7]] +assert SLICE_RESULT.shape == (1, 4) +# --8<-- [end:axis-shape-comparison] + +# --8<-- [start:axis-insertion] +inserted_view = lazy.lazy[1, :, None] +INSERTED_RESULT = inserted_view.result() + +assert INSERTED_RESULT.tolist() == [[4], [5], [6], [7]] +assert INSERTED_RESULT.shape == (4, 1) +# --8<-- [end:axis-insertion] diff --git a/packages/zarr-indexing/docs/snippets/canonical_slice.py b/packages/zarr-indexing/docs/snippets/canonical_slice.py new file mode 100644 index 0000000000..fc4417f641 --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/canonical_slice.py @@ -0,0 +1,30 @@ +"""The canonical basic-selection example used throughout the guide.""" + +import numpy as np + +from zarr_indexing import LazyArray + + +# --8<-- [start:landing-quickstart] +import numpy as np + +from zarr_indexing import LazyArray + +source = np.array([10, 11, 12, 13, 14, 15]) +view = LazyArray.from_numpy(source).lazy[2:5] + +view.result() +# array([12, 13, 14]) +# --8<-- [end:landing-quickstart] + +LANDING_QUICKSTART_RESULT = view.result() +assert LANDING_QUICKSTART_RESULT.tolist() == [12, 13, 14] + + +# --8<-- [start:canonical-slice] +source = np.array([10, 11, 12, 13, 14, 15]) +lazy = LazyArray.from_numpy(source) +view = lazy.lazy[2:5] + +assert view.result().tolist() == [12, 13, 14] +# --8<-- [end:canonical-slice] diff --git a/packages/zarr-indexing/docs/snippets/chunk_projection.py b/packages/zarr-indexing/docs/snippets/chunk_projection.py new file mode 100644 index 0000000000..5c56aafbbd --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/chunk_projection.py @@ -0,0 +1,57 @@ +"""Use public chunk projections without choosing a storage backend.""" + +import numpy as np +from numpy.typing import NDArray +from typing import cast + +from zarr_indexing import DimensionGridLike, IndexTransform, LazyArray, plan_chunks + + +# --8<-- [start:chunk-projection] +class RegularGrid: + """A small parameterized implementation of the public grid protocol.""" + + def __init__(self, size: int) -> None: + self.size = size + + def index_to_chunk(self, index: int) -> int: + return index // self.size + + def chunk_offset(self, chunk: int) -> int: + return chunk * self.size + + def chunk_size(self, chunk: int) -> int: + return self.size + + def indices_to_chunks(self, indices: NDArray[np.intp]) -> NDArray[np.intp]: + return np.floor_divide(indices, self.size).astype(np.intp) + + +transform = IndexTransform.from_shape((3, 4))[1, 0:4] +grids = cast( + tuple[DimensionGridLike, DimensionGridLike], + (RegularGrid(2), RegularGrid(2)), +) +plan = plan_chunks(transform, grids) +PROJECTIONS = tuple(plan) +assert tuple(projection.chunk_coords for projection in plan) == ((0, 0), (0, 1)) + +PAIRED_DOMAINS = tuple( + (projection.chunk_transform.domain, projection.cell_transform.domain) + for projection in PROJECTIONS +) +assert all(chunk_domain == cell_domain for chunk_domain, cell_domain in PAIRED_DOMAINS) +# --8<-- [end:chunk-projection] + + +# --8<-- [start:advanced-projection] +image = np.arange(48).reshape(6, 8) +advanced = LazyArray.from_numpy(image).with_parts((3, 4)).lazy.oindex[[4, 1, 1], 2:6] + +ADVANCED_EXPECTED = image[[4, 1, 1]][:, 2:6] +ADVANCED_RESULT = np.empty_like(ADVANCED_EXPECTED) +for part in advanced.parts(): + ADVANCED_RESULT[part.out_selection] = part.view.result() + +np.testing.assert_array_equal(ADVANCED_RESULT, ADVANCED_EXPECTED) +# --8<-- [end:advanced-projection] diff --git a/packages/zarr-indexing/docs/snippets/coordinate_origins.py b/packages/zarr-indexing/docs/snippets/coordinate_origins.py new file mode 100644 index 0000000000..724312e5e8 --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/coordinate_origins.py @@ -0,0 +1,65 @@ +"""Literal coordinate domains and a grid that supports prepending.""" + +import numpy as np +from numpy.typing import NDArray +from typing import cast + +from zarr_indexing import ( + DimensionGridLike, + IndexDomain, + IndexTransform, + LazyArray, + plan_chunks, +) + + +# --8<-- [start:coordinate-origin] +domain = IndexDomain(inclusive_min=(-2,), exclusive_max=(3,)) +assert domain.contains((-1,)) +assert domain.narrow(-1).inclusive_min == (-1,) + +values = np.array([10, 20, 30, 40, 50]) +assert LazyArray.from_numpy(values).lazy[-1:].result().tolist() == [50] +# --8<-- [end:coordinate-origin] + + +# --8<-- [start:prepend-grid] +class PrependableGrid: + """A regular grid whose coordinates may extend below zero.""" + + def index_to_chunk(self, index: int) -> int: + return index // 3 + + def chunk_offset(self, chunk: int) -> int: + return chunk * 3 + + def chunk_size(self, chunk: int) -> int: + return 3 + + def indices_to_chunks(self, indices: NDArray[np.intp]) -> NDArray[np.intp]: + return np.floor_divide(indices, 3).astype(np.intp) + + +projection, = plan_chunks( + IndexTransform.identity(IndexDomain((-3,), (0,))), + cast(tuple[DimensionGridLike], (PrependableGrid(),)), +) +assert projection.chunk_coords == (-1,) +assert projection.chunk_domain == IndexDomain((-3,), (0,)) +assert projection.chunk_transform.domain == IndexDomain((0,), (3,)) + + +assert projection.chunk_transform.domain == projection.cell_transform.domain +PREPEND_SHARED_CELL_COORDS = ((0,), (1,), (2,)) +prepend_shared_cell_points = np.asarray(PREPEND_SHARED_CELL_COORDS, dtype=np.intp) +PREPEND_CHUNK_LOCAL_COORDS = tuple( + tuple(point) + for point in projection.chunk_transform.apply_many(prepend_shared_cell_points).tolist() +) +PREPEND_REQUEST_COORDS = tuple( + tuple(point) + for point in projection.cell_transform.apply_many(prepend_shared_cell_points).tolist() +) +assert PREPEND_CHUNK_LOCAL_COORDS == ((0,), (1,), (2,)) +assert PREPEND_REQUEST_COORDS == ((-3,), (-2,), (-1,)) +# --8<-- [end:prepend-grid] diff --git a/packages/zarr-indexing/docs/snippets/indexing_patterns.py b/packages/zarr-indexing/docs/snippets/indexing_patterns.py new file mode 100644 index 0000000000..86ec75e4bc --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/indexing_patterns.py @@ -0,0 +1,210 @@ +"""Every indexing idiom hand-built as an IndexTransform, proven against the compiler.""" + +from typing import Any, Literal, TypedDict + +import numpy as np + +from zarr_indexing import ( + ArrayMap, + ConstantMap, + DimensionMap, + IndexDomain, + IndexTransform, + ReadContext, + numpy_reader, +) + + +# --8<-- [start:indexing-patterns] +class PatternCase(TypedDict): + """One indexing idiom: its hand-built transform model and its NumPy result.""" + + name: str + mode: Literal["basic", "oindex", "vindex"] + selection: Any + transform: IndexTransform + expected: Any + shape: tuple[int, ...] + category: Literal["box", "query"] + + +image = np.arange(48).reshape(6, 8) +rows = np.array([4, 1, 1], dtype=np.intp) +columns = np.array([2, 5], dtype=np.intp) +mask = image % 5 == 0 +mask_rows, mask_columns = np.nonzero(mask) +vector_rows = np.array([4, 1, 1], dtype=np.intp) +vector_columns = np.array([2, 5, 2], dtype=np.intp) +broadcast_rows = np.array([[0], [3]], dtype=np.intp) +broadcast_columns = np.array([[1, 4, 6]], dtype=np.intp) + +PATTERN_CASES: tuple[PatternCase, ...] = ( + { + # image[1:5, ::2] β€” an offset picks where cell 0 reads; a stride skips. + "name": "basic-slice", + "mode": "basic", + "selection": (slice(1, 5), slice(None, None, 2)), + "transform": IndexTransform( + domain=IndexDomain.from_shape((4, 4)), + output=( + DimensionMap(input_dimension=0, offset=1), + DimensionMap(input_dimension=1, stride=2), + ), + ), + "expected": image[1:5, ::2], + "shape": (4, 4), + "category": "box", + }, + { + # image[2, :] β€” the dropped axis survives as a ConstantMap: the result + # is rank 1, but there is still one output map per source dimension. + "name": "integer-axis-removal", + "mode": "basic", + "selection": (2, slice(None)), + "transform": IndexTransform( + domain=IndexDomain.from_shape((8,)), + output=(ConstantMap(2), DimensionMap(input_dimension=0)), + ), + "expected": image[2, :], + "shape": (8,), + "category": "box", + }, + { + # image[::-2, :] β€” reversal is only a negative stride; the offset is + # where result cell 0 reads (the last selected row, 5). + "name": "negative-stride", + "mode": "basic", + "selection": (slice(None, None, -2), slice(None)), + "transform": IndexTransform( + domain=IndexDomain.from_shape((3, 8)), + output=( + DimensionMap(input_dimension=0, offset=5, stride=-2), + DimensionMap(input_dimension=1), + ), + ), + "expected": image[::-2, :], + "shape": (3, 8), + "category": "box", + }, + { + # image[2:2, :] β€” emptiness lives in the domain; the maps are ordinary. + "name": "empty-selection", + "mode": "basic", + "selection": (slice(2, 2), slice(None)), + "transform": IndexTransform( + domain=IndexDomain.from_shape((0, 8)), + output=( + DimensionMap(input_dimension=0, offset=2), + DimensionMap(input_dimension=1), + ), + ), + "expected": image[2:2, :], + "shape": (0, 8), + "category": "box", + }, + { + # image[mask] β€” a mask is its nonzero coordinates: two correlated + # ArrayMaps over one flat result axis, row i paired with column i. + "name": "boolean-mask", + "mode": "vindex", + "selection": mask, + "transform": IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(ArrayMap(mask_rows), ArrayMap(mask_columns)), + ), + "expected": image[mask], + "shape": (10,), + "category": "query", + }, + { + # image[np.ix_(rows, columns)] β€” the outer product is spelled by shape: + # each array varies over its own distinct axis, singleton on the other. + "name": "orthogonal", + "mode": "oindex", + "selection": (rows, columns), + "transform": IndexTransform( + domain=IndexDomain.from_shape((3, 2)), + output=(ArrayMap(rows.reshape(3, 1)), ArrayMap(columns.reshape(1, 2))), + ), + "expected": image[np.ix_(rows, columns)], + "shape": (3, 2), + "category": "query", + }, + { + # image[vector_rows, vector_columns] β€” pointwise: both arrays share + # the same axis, so entry i of each pairs into one coordinate. + "name": "vectorized", + "mode": "vindex", + "selection": (vector_rows, vector_columns), + "transform": IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(vector_rows), ArrayMap(vector_columns)), + ), + "expected": image[vector_rows, vector_columns], + "shape": (3,), + "category": "query", + }, + { + # image[broadcast_rows, broadcast_columns] β€” NumPy broadcasting, + # materialized: each map carries the full (2, 3) broadcast block. + "name": "broadcasting", + "mode": "vindex", + "selection": (broadcast_rows, broadcast_columns), + "transform": IndexTransform( + domain=IndexDomain.from_shape((2, 3)), + output=( + ArrayMap(np.broadcast_to(broadcast_rows, (2, 3))), + ArrayMap(np.broadcast_to(broadcast_columns, (2, 3))), + ), + ), + "expected": image[broadcast_rows, broadcast_columns], + "shape": (2, 3), + "category": "query", + }, + { + # image[rows, 2:6] β€” one lookup-table axis (repeats and order kept) + # beside one ordinary affine axis: one ArrayMap makes the whole + # selection a query. + "name": "repeated-out-of-order", + "mode": "oindex", + "selection": (rows, slice(2, 6)), + "transform": IndexTransform( + domain=IndexDomain.from_shape((3, 4)), + output=( + ArrayMap(rows.reshape(3, 1)), + DimensionMap(input_dimension=1, offset=2), + ), + ), + "expected": image[rows, 2:6], + "shape": (3, 4), + "category": "query", + }, +) + +base = IndexTransform.from_shape(image.shape) + + +def resolve(transform: IndexTransform) -> np.ndarray[Any, Any]: + """Materialize a transform against `image` through the public reader.""" + out = np.empty(transform.domain.shape, dtype=image.dtype) + numpy_reader.read_into(image, ReadContext(transform), out) + return out + + +for case in PATTERN_CASES: + transform = case["transform"] + + # The model is the idiom: shape, values, and category all follow from it. + assert transform.domain.shape == case["shape"] + np.testing.assert_array_equal(resolve(transform), case["expected"]) + is_query = any(isinstance(m, ArrayMap) for m in transform.output) + assert ("query" if is_query else "box") == case["category"] + + # The selection compiler derives the same transform. Compiled basic + # selections keep literal domains (t[1:5, ...] starts at 1, not 0); + # re-zeroing exposes the equality with the NumPy-shaped model. + compiled = base[case["selection"]] if case["mode"] == "basic" else ( + getattr(base, case["mode"])[case["selection"]] + ) + assert compiled.translate_domain_to((0,) * compiled.input_rank) == transform +# --8<-- [end:indexing-patterns] diff --git a/packages/zarr-indexing/docs/snippets/integrations.py b/packages/zarr-indexing/docs/snippets/integrations.py new file mode 100644 index 0000000000..5699c0d319 --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/integrations.py @@ -0,0 +1,167 @@ +"""Boundaries for chunked-source and viewport consumers.""" + +from typing import Any + +import numpy as np + +from zarr_indexing import IndexDomain, LazyArray + + +# --8<-- [start:zarr-consumer] +class RecordingChunkSource: + """A decoded-chunk source keyed by public chunk coordinates.""" + + def __init__(self, chunks: dict[tuple[int, ...], np.ndarray[Any, Any]]) -> None: + self.chunks = chunks + self.reads: list[tuple[int, ...]] = [] + + def read(self, chunk_coords: tuple[int, ...]) -> np.ndarray[Any, Any]: + self.reads.append(chunk_coords) + return self.chunks[chunk_coords] + + +def _domain_points(domain: IndexDomain) -> np.ndarray[Any, np.dtype[np.intp]]: + """Enumerate a rectangular domain with a trailing coordinate axis.""" + if domain.ndim == 0: + return np.empty((1, 0), dtype=np.intp) + points = np.moveaxis(np.indices(domain.shape, dtype=np.intp), 0, -1).reshape( + -1, domain.ndim + ) + points += np.asarray(domain.inclusive_min, dtype=np.intp) + return points + + +def _gather_and_scatter( + destination: np.ndarray[Any, Any], + source: np.ndarray[Any, Any], + source_points: np.ndarray[Any, np.dtype[np.intp]], + destination_points: np.ndarray[Any, np.dtype[np.intp]], +) -> np.ndarray[Any, Any]: + """Gather and scatter a flattened point batch, including rank zero.""" + values = np.asarray(source[tuple(source_points.T)]).reshape(-1) + if destination_points.shape[-1] == 0: + destination[()] = values.reshape(destination.shape)[()] + else: + destination[tuple(destination_points.T)] = values + return values + + +zarr_image = np.arange(12).reshape(3, 4) +zarr_chunks = { + (chunk_row, chunk_column): zarr_image[ + chunk_row * 2 : (chunk_row + 1) * 2, + chunk_column * 2 : (chunk_column + 1) * 2, + ] + for chunk_row in range(2) + for chunk_column in range(2) +} +zarr_source = RecordingChunkSource(zarr_chunks) +zarr_view = LazyArray.from_numpy(zarr_image).with_parts((2, 2)).lazy[1, 0:4] +ZARR_RESULT = np.empty(zarr_view.shape, dtype=zarr_image.dtype) +shared_domains: list[tuple[IndexDomain, IndexDomain]] = [] +chunk_local_coords: list[tuple[tuple[int, ...], ...]] = [] +request_coords: list[tuple[tuple[int, ...], ...]] = [] +read_values: list[tuple[int, ...]] = [] + +for part in zarr_view.parts(): + projection = part.projection + assert projection.chunk_transform.domain == projection.cell_transform.domain + shared_domains.append( + (projection.chunk_transform.domain, projection.cell_transform.domain) + ) + domain = projection.chunk_transform.domain + cell_points = _domain_points(domain) + local_points_array = projection.chunk_transform.apply_many(cell_points) + result_points_array = projection.cell_transform.apply_many(cell_points) + chunk = zarr_source.read(projection.chunk_coords) + values_array = _gather_and_scatter( + ZARR_RESULT, chunk, local_points_array, result_points_array + ) + local_points = tuple(tuple(point) for point in local_points_array.tolist()) + result_points = tuple(tuple(point) for point in result_points_array.tolist()) + values = tuple(int(value) for value in values_array) + chunk_local_coords.append(local_points) + request_coords.append(result_points) + read_values.append(values) + +ZARR_SOURCE_KEYS = tuple(zarr_source.chunks) +ZARR_SOURCE_READS = tuple(zarr_source.reads) +ZARR_DISPATCHED_CHUNKS = ZARR_SOURCE_READS +ZARR_SHARED_DOMAINS = tuple(shared_domains) +ZARR_CHUNK_LOCAL_COORDS = tuple(chunk_local_coords) +ZARR_REQUEST_COORDS = tuple(request_coords) +ZARR_READ_VALUES = tuple(read_values) +assert ZARR_SOURCE_KEYS == ((0, 0), (0, 1), (1, 0), (1, 1)) +assert ZARR_SOURCE_READS == ((0, 0), (0, 1)) +assert ZARR_CHUNK_LOCAL_COORDS == (((1, 0), (1, 1)), ((1, 0), (1, 1))) +assert ZARR_REQUEST_COORDS == (((0,), (1,)), ((2,), (3,))) +assert ZARR_READ_VALUES == ((4, 5), (6, 7)) +assert ZARR_RESULT.tolist() == [4, 5, 6, 7] +# --8<-- [end:zarr-consumer] + + +# --8<-- [start:viewport-consumer] +class RecordingArray: + """An array-like source that records the basic reads it receives.""" + + def __init__(self, data: np.ndarray[Any, Any], chunks: tuple[int, ...]) -> None: + self._data = data + self.chunks = chunks + self.keys: list[tuple[slice, ...]] = [] + + @property + def shape(self) -> tuple[int, ...]: + return self._data.shape + + @property + def dtype(self) -> np.dtype[Any]: + return self._data.dtype + + def __getitem__(self, key: tuple[slice, ...]) -> np.ndarray[Any, Any]: + self.keys.append(key) + return self._data[key] + + +viewport_source = RecordingArray(np.arange(12).reshape(3, 4), chunks=(2, 2)) +viewport = LazyArray(viewport_source).lazy[1, 0:4] +VIEWPORT_READS_BEFORE_RESULT = tuple(viewport_source.keys) +assert VIEWPORT_READS_BEFORE_RESULT == () +assert viewport.result().tolist() == [4, 5, 6, 7] + +VIEWPORT_SOURCE_KEYS = tuple(viewport_source.keys) +VIEWPORT_SOURCE_CHUNKS = tuple( + (key[0].start // 2, key[1].start // 2) for key in VIEWPORT_SOURCE_KEYS +) +assert VIEWPORT_SOURCE_KEYS == ( + (slice(1, 2, 1), slice(0, 2, 1)), + (slice(1, 2, 1), slice(2, 4, 1)), +) +assert VIEWPORT_SOURCE_CHUNKS == ((0, 0), (0, 1)) +# --8<-- [end:viewport-consumer] + + +# --8<-- [start:dense-box-repartition] +def materialize(view: LazyArray) -> Any: + """Read a dense box as one slab; resolve everything else per part.""" + strides = view.strides() + if view.is_box and strides is not None and all(s == 1 for s in strides): + view = view.with_parts(view.base_shape) + return view.result() + + +slab_source = RecordingArray(np.arange(100).reshape(10, 10), chunks=(4, 4)) +slab = LazyArray(slab_source) + +dense = slab.lazy[2:9, 1:8] # a dense box: every stride 1 +assert materialize(dense).shape == (7, 7) +assert len(slab_source.keys) == 1 # one slab read; the source dispatches + +slab_source.keys.clear() +gather = slab.lazy.oindex[[0, 9], [0, 9]] # a query: keep the chunk parts +assert materialize(gather).tolist() == [[0, 9], [90, 99]] +assert len(slab_source.keys) == 4 # four covers, each inside one chunk +assert all( + (key[0].stop - key[0].start) * (key[1].stop - key[1].start) == 1 + for key in slab_source.keys +) +# --8<-- [end:dense-box-repartition] diff --git a/packages/zarr-indexing/docs/snippets/lazy_composition.py b/packages/zarr-indexing/docs/snippets/lazy_composition.py new file mode 100644 index 0000000000..a4d9884b2b --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/lazy_composition.py @@ -0,0 +1,14 @@ +"""Composing views keeps indexing lazy until the final result call.""" + +import numpy as np + +from zarr_indexing import LazyArray + + +# --8<-- [start:lazy-composition] +source = np.array([10, 11, 12, 13, 14, 15]) +view = LazyArray.from_numpy(source).lazy[2:5] +composed = view.lazy[::-1].lazy[1:] + +assert composed.result().tolist() == source[2:5][::-1][1:].tolist() +# --8<-- [end:lazy-composition] diff --git a/packages/zarr-indexing/docs/snippets/output_maps.py b/packages/zarr-indexing/docs/snippets/output_maps.py new file mode 100644 index 0000000000..a78fc73b50 --- /dev/null +++ b/packages/zarr-indexing/docs/snippets/output_maps.py @@ -0,0 +1,67 @@ +"""The three output map kinds, each demonstrated against its NumPy counterpart.""" + +from typing import Any + +import numpy as np + +from zarr_indexing import ( + ArrayMap, + ConstantMap, + DimensionMap, + IndexDomain, + IndexTransform, + ReadContext, + numpy_reader, +) + +# --8<-- [start:resolve-helper] +source = np.array([10, 11, 12, 13, 14, 15]) + + +def resolve(transform: IndexTransform, values: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]: + """Materialize `transform` against `values` through the public reader.""" + out = np.empty(transform.domain.shape, dtype=values.dtype) + numpy_reader.read_into(values, ReadContext(transform), out) + return out +# --8<-- [end:resolve-helper] + + +# --8<-- [start:dimension-map] +# DimensionMap is an affine rule: request i reads source offset + stride * i. +# Its NumPy counterpart is a basic slice. +sliced = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(DimensionMap(input_dimension=0, offset=2, stride=1),), +) +assert resolve(sliced, source).tolist() == source[2:5].tolist() + +# A negative stride walks the source backward, like a negative-step slice. +reversed_view = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(DimensionMap(input_dimension=0, offset=4, stride=-2),), +) +assert resolve(reversed_view, source).tolist() == source[4::-2].tolist() +# --8<-- [end:dimension-map] + +# --8<-- [start:array-map] +# ArrayMap is an explicit list of source coordinates; order and duplicates +# are semantic. Its NumPy counterpart is fancy indexing. +gather = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(index_array=np.array([4, 1, 1])),), +) +assert resolve(gather, source).tolist() == source[[4, 1, 1]].tolist() +# --8<-- [end:array-map] + +# --8<-- [start:constant-map] +# ConstantMap reads one source coordinate for every request cell. No NumPy +# selection spells this operation: source[0] drops the axis, and a repeated +# fancy index source[[0, 0, 0, 0]] matches the values but degrades the +# description to a coordinate list. The value-faithful counterpart is a +# broadcast. +repeat = IndexTransform( + domain=IndexDomain.from_shape((4,)), + output=(ConstantMap(offset=0),), +) +assert resolve(repeat, source).tolist() == np.broadcast_to(source[0:1], (4,)).tolist() +# --8<-- [end:constant-map] diff --git a/packages/zarr-indexing/examples/lazy_indexing_dask/README.md b/packages/zarr-indexing/examples/lazy_indexing_dask/README.md new file mode 100644 index 0000000000..c9edb903ef --- /dev/null +++ b/packages/zarr-indexing/examples/lazy_indexing_dask/README.md @@ -0,0 +1,55 @@ +# Lazy Indexing with Dask + +This example demonstrates how to use `zarr_indexing.LazyArray` with Dask, both as +an array Dask can wrap and as a source of independent tasks, and compares the two +ways of deferring an indexing operation. + +The example shows how to: + +- Pass a `LazyArray` β€” over a Zarr array or over a view of one β€” to + `dask.array.from_array` +- Build one Dask task per partition from `parts()`, compute them in parallel, and + place each result with the partition's `out_selection` +- Read `is_complete` to tell which partitions cover a stored chunk completely +- Rely on `__dask_tokenize__`, so that equal selections produce equal tokens and + Dask can cache and deduplicate the work +- Measure what a task graph costs for indexing-only work, against composing the + same selections into one transform + +A `LazyArray` exposes no `chunks` attribute, so `dask.array.from_array` chooses +its own block size unless one is given. The partitioning that `parts()` reports +is discovered from the wrapped array and is independent of Dask's blocks. + +## Choosing Between Them + +If Dask is doing arithmetic across chunks, reductions, rechunking, or distributed +execution, it is the right tool, and its task graph is what makes that work. + +If Dask is used *only* to defer indexing β€” take a view now, read it later, with +no computation in between β€” then the graph is overhead. Dask slices the chunk +grid on every indexing operation and records another layer, so composing +selections costs time proportional to both the depth of the chain and the number +of chunks in the array, and reading walks what was accumulated. `LazyArray` +composes each selection into the single transform it already holds, so composing +is independent of the depth of the chain, and reading enumerates only the +partitions the selection touches. The last test in this example prints both, and +the gap widens with the number of chunks and the number of selections. + +## Running the Example + +The script declares its dependencies inline +([PEP 723](https://peps.python.org/pep-0723/)), so the easiest way to run it is +with [uv](https://docs.astral.sh/uv/), which installs them automatically: + +```bash +cd packages/zarr-indexing +uv run --with-editable . examples/lazy_indexing_dask/lazy_indexing_dask.py +``` + +Alternatively, run it with plain Python, in which case you must first install +`zarr`, `zarr-indexing`, `dask[array]`, `numpy`, and `pytest` yourself: + +```bash +cd packages/zarr-indexing +python examples/lazy_indexing_dask/lazy_indexing_dask.py +``` diff --git a/packages/zarr-indexing/examples/lazy_indexing_dask/lazy_indexing_dask.py b/packages/zarr-indexing/examples/lazy_indexing_dask/lazy_indexing_dask.py new file mode 100644 index 0000000000..d6ed43f322 --- /dev/null +++ b/packages/zarr-indexing/examples/lazy_indexing_dask/lazy_indexing_dask.py @@ -0,0 +1,181 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "zarr @ git+https://github.com/zarr-developers/zarr-python.git@main", +# "zarr-indexing>=0.1", +# "dask[array]==2025.3.0", +# "numpy==2.4.3", +# "pytest==9.0.2" +# ] +# /// +# + +""" +Demonstrate using zarr_indexing.LazyArray with Dask +""" + +import sys +import time + +import dask +import dask.array as da +import numpy as np +import pytest +import zarr +from dask.base import tokenize + +from zarr_indexing import LazyArray + + +@pytest.fixture +def source() -> zarr.Array: + """A chunked Zarr array to wrap.""" + array = zarr.create_array(store={}, shape=(40, 30), chunks=(10, 10), dtype="i4") + array[:] = np.arange(40 * 30).reshape(40, 30) + return array + + +def test_from_array(source: zarr.Array) -> None: + """Hand a LazyArray to `dask.array.from_array`.""" + lazy = LazyArray(source) + + # `from_array` needs `shape`, `dtype`, and `__getitem__`, which the wrapper + # provides. Each Dask block reads its own region through the wrapper. + array = da.from_array(lazy, chunks=(10, 10)) + print(array) + assert np.array_equal(array.compute(scheduler="threads"), source[:]) + + # A view works the same way, and its shape is the shape of the selection. + view = LazyArray(source).lazy[5:35, 3:27] + array = da.from_array(view, chunks=(10, 10)) + assert array.shape == (30, 24) + assert np.array_equal(array.compute(scheduler="threads"), source[5:35, 3:27]) + + +def test_parts_as_tasks(source: zarr.Array) -> None: + """Build one task per partition and compute them in parallel.""" + view = LazyArray(source).lazy[5:35, 3:27] + + # The partitioning is discovered from the wrapped array's chunks, so each + # partition of the view lies within one stored chunk. + parts = list(view.parts()) + print(f"{len(parts)} parts for a {view.shape} view of a {source.shape} array") + + # A partition carries a sub-view to resolve and where its result belongs, so + # the reads are independent and the placement needs no coordination. + @dask.delayed + def read(part: object) -> np.ndarray: + return part.view.result() + + blocks = dask.compute(*[read(part) for part in parts], scheduler="threads") + + result = np.empty(view.shape, dtype=view.dtype) + for part, block in zip(parts, blocks, strict=True): + result[part.out_selection] = block + assert np.array_equal(result, source[5:35, 3:27]) + + # `is_complete` reports whether a partition covers its whole partition of + # the base array, which a writer uses to choose between overwriting a chunk + # and reading it first. + complete = [part.box for part in parts if part.is_complete] + print(f"{len(complete)} of {len(parts)} parts cover their chunk completely") + + +def test_tokenize(source: zarr.Array) -> None: + """Deterministic tokens let Dask cache and deduplicate work.""" + lazy = LazyArray(source) + + # Two wrappers over the same array and the same selection are the same task + # to Dask, whether or not they are the same Python object. + assert tokenize(lazy) == tokenize(LazyArray(source)) + assert tokenize(lazy.lazy[0:10]) == tokenize(LazyArray(source).lazy[0:10]) + + # Different selections are different tasks. + assert tokenize(lazy.lazy[0:10]) != tokenize(lazy.lazy[10:20]) + + # Selections that describe the same region are the same task, however they + # were composed. + assert tokenize(lazy.lazy[0:20].lazy[5:10]) == tokenize(lazy.lazy[5:10]) + + +def test_indexing_only_workload() -> None: + """Compare an accumulating task graph with a fused transform. + + Dask records each indexing operation as another graph layer, and slices the + chunk grid to build it, so composing selections costs time proportional to + the number of selections and the number of chunks. `LazyArray` composes each + selection into the single transform it already holds, so the cost of + composing does not grow with the depth of the chain, and reading resolves + that one transform rather than walking a graph. + + Timings are printed rather than asserted, since they depend on the machine. + """ + data = np.zeros((2000, 4), dtype="i4") # 2000 chunks, one row each + + def dask_chain(depth: int) -> da.Array: + array = da.from_array(data, chunks=(1, 4)) + for _ in range(depth): + array = array[1:] + return array + + def lazy_chain(depth: int) -> LazyArray: + view = LazyArray.from_numpy(data) + for _ in range(depth): + view = view.lazy[1:] + return view + + # Read once through each path first, so the timings below exclude the cost + # of importing and initializing the machinery. + dask_chain(1)[:2].compute(scheduler="synchronous") + lazy_chain(1).lazy[:2].result() + + header = ( + f"{'selections':>10} {'dask compose':>13} {'dask read':>10} {'layers':>7}" + f" {'LazyArray compose':>18} {'LazyArray read':>15}" + ) + print(header) + for depth in (1, 5, 20): + start = time.perf_counter() + chained = dask_chain(depth) + dask_compose = time.perf_counter() - start + + start = time.perf_counter() + from_dask = chained[:2].compute(scheduler="synchronous") + dask_read = time.perf_counter() - start + + start = time.perf_counter() + view = lazy_chain(depth) + lazy_compose = time.perf_counter() - start + + start = time.perf_counter() + from_lazy = view.lazy[:2].result() + lazy_read = time.perf_counter() - start + + # Both paths describe the same selection, so they read the same data. + assert np.array_equal(from_dask, from_lazy) + + layers = len(chained.__dask_graph__().layers) + print( + f"{depth:>10} {dask_compose * 1e3:>12.2f}ms {dask_read * 1e3:>9.2f}ms {layers:>7}" + f" {lazy_compose * 1e3:>17.3f}ms {lazy_read * 1e3:>14.3f}ms" + ) + + +if __name__ == "__main__": + # Run the example with printed output, and a dummy pytest configuration file specified. + # Without the dummy configuration file, at test time pytest will attempt to use the + # configuration file in the project root, which will error because Zarr is using some + # plugins that are not installed in this example. + sys.exit( + pytest.main( + [ + "-s", + __file__, + f"-c {__file__}", + # Suppress: "PytestAssertRewriteWarning: Module already imported so + # cannot be rewritten; zarr" + "-W", + "ignore::pytest.PytestAssertRewriteWarning", + ] + ) + ) diff --git a/packages/zarr-indexing/examples/lazy_indexing_numpy/README.md b/packages/zarr-indexing/examples/lazy_indexing_numpy/README.md new file mode 100644 index 0000000000..e76e065047 --- /dev/null +++ b/packages/zarr-indexing/examples/lazy_indexing_numpy/README.md @@ -0,0 +1,38 @@ +# Lazy Indexing a NumPy Array + +This example demonstrates how to wrap an array in `zarr_indexing.LazyArray` and +index it without reading data. + +The example shows how to: + +- Wrap a NumPy array and read the forwarded `shape`, `dtype`, and `ndim` +- Compose selections through `.lazy[...]`, `.lazy.oindex[...]`, and + `.lazy.vindex[...]`, and materialize the composed view once with `result()` +- Tell a box selection (slices and integers, described by an interval and a step + per dimension) from a query selection (points gathered through an index array) + using `is_box`, `bounding_box()`, and `strides()` +- Declare a partitioning with `with_parts()`, iterate it with `parts()`, and + assemble a result from the partitions + +`LazyArray` wraps any object exposing `shape`, `dtype`, and `__getitem__`, so the +same API applies to a Zarr array, and the partitioning is then discovered from +the array's chunks. The Dask example covers that case. + +## Running the Example + +The script declares its dependencies inline +([PEP 723](https://peps.python.org/pep-0723/)), so the easiest way to run it is +with [uv](https://docs.astral.sh/uv/), which installs them automatically: + +```bash +cd packages/zarr-indexing +uv run --with-editable . examples/lazy_indexing_numpy/lazy_indexing_numpy.py +``` + +Alternatively, run it with plain Python, in which case you must first install +`zarr-indexing`, `numpy`, and `pytest` yourself: + +```bash +cd packages/zarr-indexing +python examples/lazy_indexing_numpy/lazy_indexing_numpy.py +``` diff --git a/packages/zarr-indexing/examples/lazy_indexing_numpy/lazy_indexing_numpy.py b/packages/zarr-indexing/examples/lazy_indexing_numpy/lazy_indexing_numpy.py new file mode 100644 index 0000000000..ae29a7fc51 --- /dev/null +++ b/packages/zarr-indexing/examples/lazy_indexing_numpy/lazy_indexing_numpy.py @@ -0,0 +1,133 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "zarr-indexing>=0.1", +# "numpy==2.4.3", +# "pytest==9.0.2" +# ] +# /// +# + +""" +Demonstrate lazy indexing over a plain NumPy array with zarr_indexing.LazyArray +""" + +import sys + +import numpy as np +import pytest + +from zarr_indexing import LazyArray + + +def test_wrap_and_compose() -> None: + """Wrap an array, compose selections without reading, then materialize once.""" + data = np.arange(12 * 8).reshape(12, 8) + lazy = LazyArray.from_numpy(data) + + # The wrapper forwards the attributes an array consumer expects. + assert lazy.shape == (12, 8) + assert lazy.dtype == data.dtype + assert lazy.ndim == 2 + + # `.lazy[...]` returns another LazyArray. No element of `data` is read. + view = lazy.lazy[2:10, ::2] + print(view) + assert view.shape == (8, 4) + + # Selections compose. Each step narrows the view; still nothing is read. + smaller = view.lazy[1:5, 1:3] + + # `result()` performs the read. NumPy is the reference for the whole chain. + assert np.array_equal(smaller.result(), data[2:10, ::2][1:5, 1:3]) + + # Selections use positional NumPy semantics: indices count from zero within + # the current view, and negative indices count from the end. + assert np.array_equal(lazy.lazy[-1].result(), data[-1]) + assert np.array_equal(lazy.lazy[::-1].result(), data[::-1]) + + # Orthogonal and vectorized indexing are available under the same accessor. + rows = np.array([9, 1, 4]) + assert np.array_equal(lazy.lazy.oindex[rows, :].result(), data[rows, :]) + cols = np.array([0, 3, 7]) + assert np.array_equal(lazy.lazy.vindex[rows, cols].result(), data[rows, cols]) + + # A LazyArray is also an ordinary duck array: __getitem__ reads immediately, + # and np.asarray materializes the view. + assert np.array_equal(lazy[2:4, 0], data[2:4, 0]) + assert np.array_equal(np.asarray(view), data[2:10, ::2]) + + +def test_box_and_query_selections() -> None: + """Distinguish selections that describe a region from selections that gather points.""" + data = np.arange(12 * 8).reshape(12, 8) + lazy = LazyArray.from_numpy(data) + + # A box selection is built from slices and integers alone. It is described + # completely by an interval and a step per dimension, so a consumer can + # serve it as one strided read. + box = lazy.lazy[2:10, ::2] + print(f"box: is_box={box.is_box} bounding_box={box.bounding_box()} strides={box.strides()}") + assert box.is_box + assert box.bounding_box() == ((2, 10), (0, 7)) + assert box.strides() == (1, 2) + + # A query selection gathers points through an index array. Its coordinates + # are a lookup table, so `strides()` is undefined and `bounding_box()` is + # the hull of the points rather than an exact description. + query = lazy.lazy.oindex[np.array([9, 1, 4]), :] + print(f"query: is_box={query.is_box} bounding_box={query.bounding_box()}") + assert not query.is_box + assert query.strides() is None + assert query.bounding_box() == ((1, 10), (0, 8)) + + # Composing a box onto a query keeps it a query. + assert not query.lazy[0:2, 0:2].is_box + + +def test_parts() -> None: + """Iterate the partitions a view covers, and assemble the result from them.""" + data = np.arange(12 * 8).reshape(12, 8) + + # A plain NumPy array declares no partitioning, so `with_parts` states one. + # Partitioning changes the granularity of reads, never the result. + lazy = LazyArray.from_numpy(data).with_parts((4, 4)) + view = lazy.lazy[2:10, ::2] + + parts = list(view.parts()) + print(f"{len(parts)} parts") + for part in parts[:2]: + print(f" base_coords={part.base_coords} box={part.box} complete={part.is_complete}") + + # Each part carries a sub-view of its own, where that sub-view lands in the + # result, and whether it covers its partition completely. Resolving the + # parts and placing them is what `result()` does. + assembled = np.empty(view.shape, dtype=view.dtype) + for part in parts: + assembled[part.out_selection] = part.view.result() + assert np.array_equal(assembled, view.result()) + + # The partitioning is a read strategy, so a different one gives the same data. + assert np.array_equal( + LazyArray.from_numpy(data).with_parts((5, 3)).lazy[2:10, ::2].result(), assembled + ) + + +if __name__ == "__main__": + # Run the example with printed output, and a dummy pytest configuration file specified. + # Without the dummy configuration file, at test time pytest will attempt to use the + # configuration file in the project root, which will error because Zarr is using some + # plugins that are not installed in this example. + sys.exit( + pytest.main( + [ + "-s", + __file__, + f"-c {__file__}", + # Suppress: "PytestAssertRewriteWarning: Module already imported so + # cannot be rewritten; zarr" + "-W", + "ignore::pytest.PytestAssertRewriteWarning", + ] + ) + ) diff --git a/packages/zarr-indexing/examples/system_memory_chunk_cache/README.md b/packages/zarr-indexing/examples/system_memory_chunk_cache/README.md new file mode 100644 index 0000000000..d6271f9401 --- /dev/null +++ b/packages/zarr-indexing/examples/system_memory_chunk_cache/README.md @@ -0,0 +1,46 @@ +# System-memory chunk cache + +This executable reference architecture demonstrates a small, synchronous +system-memory chunk cache for a NumPy-like image consumer. It is inspired by +Neuroglancer's explicit chunk lifecycle: + +```text +NEW -> QUEUED -> LOADING -> READY + | + v + FAILED + +READY -> EVICTED +FAILED -> QUEUED (explicit retry) +``` + +`RecordingChunkSource` owns decoded source-chunk reads and records them for the +example. `LazyArray` converts NumPy-style indexing into transforms and +partitions, then assembles the final result. `SystemMemoryChunkReader` +intercepts each materialized part and owns the lifecycle records, queue +draining, resident ready buffers, LRU eviction, retained load failures, and +explicit retry. The reader owns cache state and source reads, but not result +shape or assembly. + +Each request calls `view.parts()` once and keeps the resulting tuple. The cache +pins the tuple's chunk coordinates, then materializes with +`view.result(parts=parts)`, so scheduling and assembly reuse one plan. Every +reader call consumes the exact projection attached to its `ReadContext`; the +reader does not invoke the chunk planner again. + +The requests demonstrate lazy selections, paired chunk projections, overlapping +viewport requests that reuse resident chunks, eviction under capacity pressure, +a retained failure that does not retry implicitly, and an explicit retry after +the source is repaired. The integration guide contains the detailed request +table. + +This is synchronous system-memory reference architecture, not a +production-ready cache, scheduler, renderer, or complete napari integration. +Its types are intentionally not exported by `zarr_indexing`. + +## Running the example + +```bash +cd packages/zarr-indexing +uv run --with-editable . examples/system_memory_chunk_cache/system_memory_chunk_cache.py +``` diff --git a/packages/zarr-indexing/examples/system_memory_chunk_cache/system_memory_chunk_cache.py b/packages/zarr-indexing/examples/system_memory_chunk_cache/system_memory_chunk_cache.py new file mode 100644 index 0000000000..1645d89b2c --- /dev/null +++ b/packages/zarr-indexing/examples/system_memory_chunk_cache/system_memory_chunk_cache.py @@ -0,0 +1,432 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "zarr-indexing>=0.1", +# "numpy==2.4.3", +# ] +# /// +# +from __future__ import annotations + +from contextlib import contextmanager +from dataclasses import dataclass +from enum import StrEnum +from typing import TYPE_CHECKING, Any + +import numpy as np + +from zarr_indexing import ( + IndexDomain, + LazyArray, + ReadContext, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + +type ChunkCoords = tuple[int, ...] + + +# --8<-- [start:chunk-cache-types] +class ChunkState(StrEnum): + NEW = "new" + QUEUED = "queued" + LOADING = "loading" + READY = "ready" + FAILED = "failed" + EVICTED = "evicted" + + +@dataclass(slots=True) +class ChunkRecord: + state: ChunkState = ChunkState.NEW + buffer: np.ndarray[Any, Any] | None = None + error: Exception | None = None + last_access: int = -1 + + +@dataclass(frozen=True, slots=True) +class ChunkEvent: + chunk_coords: ChunkCoords + previous: ChunkState + current: ChunkState + reason: str + + +class ChunkLoadError(RuntimeError): + pass + + +# --8<-- [end:chunk-cache-types] + + +# --8<-- [start:chunk-cache-source] +class RecordingChunkSource: + def __init__(self, data: np.ndarray[Any, Any], chunks: tuple[int, ...]) -> None: + self._data = data + self.chunks = chunks + self.reads: list[ChunkCoords] = [] + self.failures: set[ChunkCoords] = set() + + @property + def shape(self) -> tuple[int, ...]: + return self._data.shape + + @property + def dtype(self) -> np.dtype[Any]: + return self._data.dtype + + def __getitem__(self, key: Any) -> np.ndarray[Any, Any]: + raise AssertionError("the cache must read complete chunks through read_chunk") + + def read_chunk(self, chunk_coords: ChunkCoords) -> np.ndarray[Any, Any]: + self.reads.append(chunk_coords) + if chunk_coords in self.failures: + raise OSError(f"source read failed for chunk {chunk_coords}") + key = tuple( + slice(coord * size, min((coord + 1) * size, extent)) + for coord, size, extent in zip(chunk_coords, self.chunks, self.shape, strict=True) + ) + return self._data[key].copy() + + +def _domain_points(domain: IndexDomain) -> np.ndarray[Any, np.dtype[np.intp]]: + """Enumerate a rectangular domain with a trailing coordinate axis.""" + if domain.ndim == 0: + return np.empty((1, 0), dtype=np.intp) + points = np.moveaxis(np.indices(domain.shape, dtype=np.intp), 0, -1).reshape(-1, domain.ndim) + points += np.asarray(domain.inclusive_min, dtype=np.intp) + return points + + +def _gather_and_scatter( + destination: np.ndarray[Any, Any], + source: np.ndarray[Any, Any], + source_points: np.ndarray[Any, np.dtype[np.intp]], + destination_points: np.ndarray[Any, np.dtype[np.intp]], +) -> np.ndarray[Any, Any]: + """Gather and scatter a flattened point batch, including rank zero.""" + values = np.asarray(source[tuple(source_points.T)]).reshape(-1) + if destination_points.shape[-1] == 0: + destination[()] = values.reshape(destination.shape)[()] + else: + destination[tuple(destination_points.T)] = values + return values + + +# --8<-- [end:chunk-cache-source] + + +# --8<-- [start:chunk-cache-wrapper] +LEGAL_TRANSITIONS: dict[ChunkState, frozenset[ChunkState]] = { + ChunkState.NEW: frozenset({ChunkState.QUEUED}), + ChunkState.QUEUED: frozenset({ChunkState.LOADING}), + ChunkState.LOADING: frozenset({ChunkState.READY, ChunkState.FAILED}), + ChunkState.READY: frozenset({ChunkState.EVICTED}), + ChunkState.FAILED: frozenset({ChunkState.QUEUED}), + ChunkState.EVICTED: frozenset({ChunkState.QUEUED}), +} + + +class _OrthogonalIndexer: + """Expose outer-product indexing without changing ``cache[key]`` semantics.""" + + def __init__(self, getitem: Callable[[Any], np.ndarray[Any, Any]]) -> None: + self._getitem = getitem + + def __getitem__(self, key: Any) -> np.ndarray[Any, Any]: + return self._getitem(key) + + +class SystemMemoryChunkReader: + def __init__(self, *, capacity: int) -> None: + self.capacity = capacity + self._records: dict[ChunkCoords, ChunkRecord] = {} + self._queue: list[ChunkCoords] = [] + self._clock = 0 + self._requests = 0 + self.events: list[ChunkEvent] = [] + self.projection_uses: list[tuple[str, str]] = [] + + def state(self, chunk_coords: ChunkCoords) -> ChunkState: + return self._record(chunk_coords).state + + def resident(self) -> tuple[ChunkCoords, ...]: + return tuple( + sorted( + coords + for coords, record in self._records.items() + if record.state is ChunkState.READY + ) + ) + + def _record(self, chunk_coords: ChunkCoords) -> ChunkRecord: + return self._records.setdefault(chunk_coords, ChunkRecord()) + + def _transition(self, chunk_coords: ChunkCoords, current: ChunkState, reason: str) -> None: + record = self._record(chunk_coords) + if current not in LEGAL_TRANSITIONS[record.state]: + raise ValueError(f"illegal chunk transition {record.state} -> {current}") + previous = record.state + record.state = current + self.events.append(ChunkEvent(chunk_coords, previous, current, reason)) + + def retry(self, chunk_coords: ChunkCoords) -> None: + record = self._record(chunk_coords) + if record.state is not ChunkState.FAILED: + raise ValueError(f"retry requires failed chunk {chunk_coords}, got {record.state}") + record.error = None + self._transition(chunk_coords, ChunkState.QUEUED, "explicit retry") + self._queue.append(chunk_coords) + + @contextmanager + def request(self, required: tuple[ChunkCoords, ...]) -> Iterator[None]: + """Prepare every part and defer eviction until one request completes.""" + self._prepare(required) + self._requests += 1 + try: + yield + except Exception: + self._requests -= 1 + raise + else: + self._requests -= 1 + if self._requests == 0: + self._evict(pinned=frozenset()) + + def _touch(self, record: ChunkRecord) -> None: + self._clock += 1 + record.last_access = self._clock + + def _queue_once(self, chunk_coords: ChunkCoords) -> None: + record = self._record(chunk_coords) + if record.state in {ChunkState.QUEUED, ChunkState.LOADING, ChunkState.READY}: + return + if record.state is ChunkState.FAILED: + raise ValueError(f"failed chunk {chunk_coords} requires explicit retry") + self._transition(chunk_coords, ChunkState.QUEUED, "requested") + self._queue.append(chunk_coords) + + def _prepare(self, required: tuple[ChunkCoords, ...]) -> None: + for chunk_coords in required: + record = self._record(chunk_coords) + if record.state is ChunkState.FAILED: + assert record.error is not None + raise ChunkLoadError( + f"chunk {chunk_coords} is failed; call retry first" + ) from record.error + + for chunk_coords in required: + record = self._record(chunk_coords) + if record.state is ChunkState.READY: + self._touch(record) + else: + self._queue_once(chunk_coords) + + def _ensure_ready( + self, + source: RecordingChunkSource, + required: tuple[ChunkCoords, ...], + ) -> None: + if self._requests == 0: + self._prepare(required) + self._drain(source, frozenset(required)) + + def _drain(self, source: RecordingChunkSource, required: frozenset[ChunkCoords]) -> None: + pending = self._queue + self._queue = [] + for index, chunk_coords in enumerate(pending): + if chunk_coords not in required: + self._queue.append(chunk_coords) + continue + record = self._record(chunk_coords) + self._transition(chunk_coords, ChunkState.LOADING, "queue drained") + try: + record.buffer = source.read_chunk(chunk_coords) + except OSError as error: + record.buffer = None + record.error = error + self._transition(chunk_coords, ChunkState.FAILED, "source read failed") + self._queue.extend(pending[index + 1 :]) + raise ChunkLoadError(f"could not load chunk {chunk_coords}") from error + record.error = None + self._transition(chunk_coords, ChunkState.READY, "source read completed") + self._touch(record) + + def _evict(self, *, pinned: frozenset[ChunkCoords]) -> None: + while len(self.resident()) > self.capacity: + candidates = ( + (record.last_access, chunk_coords) + for chunk_coords, record in self._records.items() + if record.state is ChunkState.READY and chunk_coords not in pinned + ) + _, chunk_coords = min(candidates) + record = self._record(chunk_coords) + record.buffer = None + self._transition(chunk_coords, ChunkState.EVICTED, "LRU capacity") + + def read_into( + self, + source: RecordingChunkSource, + context: ReadContext, + out: np.ndarray[Any, Any], + /, + ) -> None: + projection = context.projection + if projection is None: + raise ValueError("SystemMemoryChunkReader requires context.projection") + required = (projection.chunk_coords,) + self._ensure_ready(source, required) + record = self._record(projection.chunk_coords) + assert record.buffer is not None + cell_points = _domain_points(projection.chunk_transform.domain) + chunk_points = projection.chunk_transform.apply_many(cell_points) + destination_points = _domain_points(context.transform.domain) + _gather_and_scatter(out, record.buffer, chunk_points, destination_points) + self.projection_uses.append(("chunk_transform", "context.transform")) + if self._requests == 0: + self._evict(pinned=frozenset()) + + +class SystemMemoryChunkCache: + def __init__(self, source: RecordingChunkSource, *, capacity: int) -> None: + self.source = source + self.reader = SystemMemoryChunkReader(capacity=capacity) + self._lazy = LazyArray(source).with_reader(self.reader) + + @property + def shape(self) -> tuple[int, ...]: + return self.source.shape + + @property + def dtype(self) -> np.dtype[Any]: + return self.source.dtype + + @property + def oindex(self) -> _OrthogonalIndexer: + return _OrthogonalIndexer(lambda key: self._read(key, orthogonal=True)) + + @property + def events(self) -> list[ChunkEvent]: + return self.reader.events + + @property + def projection_uses(self) -> tuple[tuple[str, str], ...]: + return tuple(self.reader.projection_uses) + + def state(self, chunk_coords: ChunkCoords) -> ChunkState: + return self.reader.state(chunk_coords) + + def resident(self) -> tuple[ChunkCoords, ...]: + return self.reader.resident() + + def retry(self, chunk_coords: ChunkCoords) -> None: + self.reader.retry(chunk_coords) + + def __getitem__(self, key: Any) -> np.ndarray[Any, Any]: + return self._read(key, orthogonal=False) + + def _read(self, key: Any, *, orthogonal: bool) -> np.ndarray[Any, Any]: + self.reader.projection_uses.clear() + lazy = self._lazy.lazy + view = lazy.oindex[key] if orthogonal else lazy[key] + # One prepared tuple is the request plan: pin from it, then hand the + # same owned parts back to LazyArray for assembly without replanning. + parts = tuple(view.parts()) + required = tuple(dict.fromkeys(part.base_coords for part in parts)) + with self.reader.request(required): + return np.asarray(view.result(parts=parts)) + + +# --8<-- [end:chunk-cache-wrapper] + + +# --8<-- [start:chunk-cache-worked-example] +image = np.arange(48).reshape(6, 8) +source = RecordingChunkSource(image, chunks=(3, 4)) +cache = SystemMemoryChunkCache(source, capacity=2) + +READS_BEFORE_SELECTION = tuple(source.reads) +INITIAL_RESULT = cache[1:5, 2] +INITIAL_READS = tuple(source.reads) + +before_overlap = len(source.reads) +OVERLAP_RESULT = cache[3:5, 2] +OVERLAP_NEW_READS = tuple(source.reads[before_overlap:]) + +before_eviction = len(source.reads) +EVICTION_RESULT = cache[0:2, 5] +EVICTION_NEW_READS = tuple(source.reads[before_eviction:]) +AFTER_EVICTION_RESIDENT = cache.resident() + +before_reload = len(source.reads) +RELOAD_RESULT = cache[1:5, 2] +RELOAD_NEW_READS = tuple(source.reads[before_reload:]) +AFTER_RELOAD_RESIDENT = cache.resident() + +source.failures.add((1, 1)) +failed_once = False +try: + cache[3:5, 4:6] +except ChunkLoadError: + failed_once = True +assert failed_once +FAILED_READ_COUNT = source.reads.count((1, 1)) +failed_twice = False +try: + cache[3:5, 4:6] +except ChunkLoadError: + failed_twice = True +assert failed_twice +FAILED_REPEAT_READ_COUNT = source.reads.count((1, 1)) +FAILURE_READ_COUNTS = (FAILED_READ_COUNT, FAILED_REPEAT_READ_COUNT) + +source.failures.remove((1, 1)) +cache.retry((1, 1)) +before_retry = len(source.reads) +RETRY_RESULT = cache[3:5, 4:6] +RETRY_NEW_READS = tuple(source.reads[before_retry:]) +RETRY_STATE = cache.state((1, 1)).value +WORKED_EVENTS = tuple(cache.events) +FAILED_TRANSITIONS = tuple( + event.current.value for event in WORKED_EVENTS if event.chunk_coords == (1, 1) +) +FAILED_EVENT_ROWS = tuple( + (event.previous.value, event.current.value, event.reason) + for event in WORKED_EVENTS + if event.chunk_coords == (1, 1) +) +# --8<-- [end:chunk-cache-worked-example] + +assert READS_BEFORE_SELECTION == () +assert INITIAL_RESULT.tolist() == [10, 18, 26, 34] +assert INITIAL_READS == ((0, 0), (1, 0)) +assert OVERLAP_RESULT.tolist() == [26, 34] +assert OVERLAP_NEW_READS == () +assert EVICTION_RESULT.tolist() == [5, 13] +assert EVICTION_NEW_READS == ((0, 1),) +assert AFTER_EVICTION_RESIDENT == ((0, 1), (1, 0)) +assert RELOAD_RESULT.tolist() == [10, 18, 26, 34] +assert RELOAD_NEW_READS == ((0, 0),) +assert AFTER_RELOAD_RESIDENT == ((0, 0), (1, 0)) +assert FAILURE_READ_COUNTS == (1, 1) +assert RETRY_RESULT.tolist() == [[28, 29], [36, 37]] +assert RETRY_NEW_READS == ((1, 1),) +assert RETRY_STATE == "ready" +assert FAILED_TRANSITIONS == ( + "queued", + "loading", + "failed", + "queued", + "loading", + "ready", +) +assert FAILED_EVENT_ROWS == ( + ("new", "queued", "requested"), + ("queued", "loading", "queue drained"), + ("loading", "failed", "source read failed"), + ("failed", "queued", "explicit retry"), + ("queued", "loading", "queue drained"), + ("loading", "ready", "source read completed"), +) diff --git a/packages/zarr-indexing/justfile b/packages/zarr-indexing/justfile new file mode 100644 index 0000000000..1b7164f647 --- /dev/null +++ b/packages/zarr-indexing/justfile @@ -0,0 +1,67 @@ +# Development verbs for the zarr-indexing package. Recipes run with this +# directory as the working directory regardless of where `just` is invoked. + +# List available recipes +default: + @just --list + +# The chunk-resolution tests exercise this package against zarr's ChunkGrid, so +# they need an environment that has both `zarr` and this package installed. +# `zarr` is deliberately not a dependency of this package, and the repo is not +# a uv workspace, so run against the repo-root environment (which provides +# `zarr`) with this package layered in as an editable overlay β€” the same +# invocation CI uses. +# Run the test suite; extra args are passed to pytest +test *args: + uv run --project ../.. --group test --with-editable . python -m pytest tests src/zarr_indexing {{ args }} + +# TensorStore is the oracle for the parity suites, which skip without it. It +# ships binary wheels only, so it rides in as a run-time overlay rather than +# joining a dependency group; if a future Python lacks a tensorstore wheel, +# gate the CI job that calls this on the matrix version. +# Run the tensorstore parity suites; extra args are passed to pytest +test-tensorstore *args: + uv run --project ../.. --group test --with-editable . --with 'tensorstore>=0.1.84' python -m pytest tests/test_ndsel_tensorstore.py tests/test_tensorstore_parity.py {{ args }} + +# Lint with the same invocation CI uses. Ruff is pinned to the repo-wide +# version (see pyproject.toml [dependency-groups] docs); bump together. +lint: + uvx ruff@0.16.0 check . + +# Type-check the package sources, documentation Python, and their contract tests +typecheck: + uv run --group test --with pyright pyright + +# Run everything CI runs for this package +check: lint typecheck test test-tensorstore docs-check + +# Preview the changelog that the next release would generate +changelog-draft: + uvx towncrier build --draft --version Unreleased + +# Build this package's documentation site, warnings as errors +docs-check: + env DISABLE_MKDOCS_2_WARNING=true uv run --group docs mkdocs build --strict + +# With no argument, uses port 8000 if free, otherwise an ephemeral free port; +# an explicitly requested port is used as-is so a conflict fails loudly. +# Serve this package's documentation site +docs-serve port="": + #!/usr/bin/env bash + set -euo pipefail + port="{{ port }}" + if [ -z "$port" ]; then + port=$(uv run --group docs python -c ' + import socket + s = socket.socket() + try: + s.bind(("127.0.0.1", 8000)) + except OSError: + s.close() + s = socket.socket() + s.bind(("127.0.0.1", 0)) + print(s.getsockname()[1]) + s.close() + ') + fi + exec env DISABLE_MKDOCS_2_WARNING=true uv run --group docs mkdocs serve -a "localhost:$port" diff --git a/packages/zarr-indexing/mkdocs.yml b/packages/zarr-indexing/mkdocs.yml new file mode 100644 index 0000000000..d97e63b150 --- /dev/null +++ b/packages/zarr-indexing/mkdocs.yml @@ -0,0 +1,155 @@ +site_name: zarr-indexing +# The package lives in the zarr-python monorepo; point the header source +# widget at the package directory rather than the repository root. +repo_name: zarr-python/packages/zarr-indexing +repo_url: https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-indexing +# Absolute because mkdocs would otherwise append this to repo_url's subpath. +edit_uri: https://github.com/zarr-developers/zarr-python/edit/main/packages/zarr-indexing/docs/ +site_description: Composable, lazy coordinate transforms for Zarr array indexing. +site_author: Davis Bennett +site_url: !ENV [READTHEDOCS_CANONICAL_URL, 'https://zarr-indexing.readthedocs.io/'] +docs_dir: docs +use_directory_urls: true +exclude_docs: | + snippets/*.py + +# --strict promotes warnings to errors, but broken link anchors and pages +# missing from nav are only INFO by default β€” a strict build passed with +# both breakages. Warn so strict actually fails on them. +validation: + links: + anchors: warn + nav: + omitted_files: warn + +# Top-level rank is consistent: collections (Guide, Examples, API Reference) +# and standalone artifacts (landing, ndsel spec, design notes, changelog). +# Guide mirrors the docs/guide/ directory β€” its three pages are one +# collection (learn / look up / integrate), pydantic's Concepts pattern at +# small scale; navigation.indexes makes the Guide entry itself land on the +# visual guide. No tabs: at eight content pages, hiding sections costs more +# than it organizes. +nav: + - index.md + - Guide: + - guide/index.md + - Indexing patterns: guide/patterns.md + - Integration boundaries: guide/integrations.md + - Examples: + - Lazy indexing a NumPy array: examples/lazy_indexing_numpy.md + - Lazy indexing with Dask: examples/lazy_indexing_dask.md + - System-memory chunk cache: examples/system_memory_chunk_cache.md + - The ndsel wire format: ndsel.md + - Design notes: design-notes.md + - API Reference: + - api/index.md + - ' zarr_indexing.transform': api/transform.md + - ' zarr_indexing.domain': api/domain.md + - ' zarr_indexing.output_map': api/output_map.md + - ' zarr_indexing.chunk_resolution': api/chunk_resolution.md + - ' zarr_indexing.grid': api/grid.md + - ' zarr_indexing.lazy_array': api/lazy_array.md + - ' zarr_indexing.reader': api/reader.md + - ' zarr_indexing.boundary': api/boundary.md + - ' zarr_indexing.json': api/json.md + - ' zarr_indexing.messages': api/messages.md + - ' zarr_indexing.errors': api/errors.md + - ' zarr_indexing.testing.stateful': api/testing_stateful.md + - ' zarr_indexing.testing.strategies': api/testing_strategies.md + - Changelog: https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-indexing/CHANGELOG.md + # This site is a Read the Docs subproject of zarr-python; give readers a way + # back to the parent docs, which list every companion package. + - 'zarr-python β†ͺ': https://zarr.readthedocs.io/ + +watch: + - src + +theme: + language: en + name: material + logo: _static/logo_bw.png + favicon: _static/favicon-96x96.png + + palette: + # Light mode + - media: "(prefers-color-scheme: light)" + scheme: default + toggle: + icon: material/brightness-7 + name: Switch to dark mode + + # Dark mode + - media: "(prefers-color-scheme: dark)" + scheme: slate + toggle: + icon: material/brightness-4 + name: Switch to light mode + + font: + text: Roboto + code: Roboto Mono + + features: + - content.code.annotate + - content.code.copy + - content.tabs.link + - navigation.indexes + - navigation.instant + - navigation.tracking + - search.suggest + - search.share + +plugins: + - autorefs + - search + - mkdocstrings: + enable_inventory: true + handlers: + python: + paths: [src] + options: + allow_inspection: true + docstring_section_style: list + docstring_style: numpy + inherited_members: true + line_length: 60 + separate_signature: true + show_root_heading: true + show_signature_annotations: true + show_source: true + show_symbol_type_toc: true + signature_crossrefs: true + show_if_no_docstring: true + extensions: + - griffe_inherited_docstrings + + inventories: + - https://docs.python.org/3/objects.inv + - https://numpy.org/doc/stable/objects.inv + - https://zarr.readthedocs.io/en/stable/objects.inv + +markdown_extensions: + - admonition + - attr_list + - def_list + - footnotes + - md_in_html + - pymdownx.details + - pymdownx.superfences + - toc: + permalink: true + - pymdownx.highlight: + anchor_linenums: true + line_spans: __span + pygments_lang_class: true + - pymdownx.inlinehilite + # Content tabs (Python/JSON pairs in the pattern matrix); content.tabs.link + # in the theme features keeps every pair switched together. + - pymdownx.tabbed: + alternate_style: true + - pymdownx.snippets: + base_path: [docs, examples] + # Fail the build on an unresolvable include or missing region instead + # of silently rendering nothing. tests/test_doc_examples.py mirrors + # base_path when it verifies the include graph. + check_paths: true diff --git a/packages/zarr-indexing/pyproject.toml b/packages/zarr-indexing/pyproject.toml new file mode 100644 index 0000000000..60f69a1dbb --- /dev/null +++ b/packages/zarr-indexing/pyproject.toml @@ -0,0 +1,171 @@ +[build-system] +requires = ["hatchling>=1.29.0", "hatch-vcs"] +build-backend = "hatchling.build" + +[project] +name = "zarr-indexing" +dynamic = ["version"] +description = "Composable, lazy coordinate transforms for Zarr array indexing." +readme = "README.md" +requires-python = ">=3.12" +license = "MIT" +license-files = ["LICENSE.txt"] +authors = [ + { name = "Davis Bennett", email = "davis.v.bennett@gmail.com" }, +] +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Intended Audience :: Information Technology", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Scientific/Engineering", + "Topic :: Software Development :: Libraries :: Python Modules", + "Typing :: Typed", +] +keywords = ["zarr"] +dependencies = [ + "numpy>=2", +] + +[project.optional-dependencies] +# `zarr_indexing.testing` β€” a Hypothesis state machine and selection strategies +# for projects checking their own array against this package. Nothing else in +# the package imports hypothesis. +testing = ["hypothesis>=6.160.0"] + +[project.urls] +Homepage = "https://github.com/zarr-developers/zarr-python" +Source = "https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-indexing" +Issues = "https://github.com/zarr-developers/zarr-python/issues" +Changelog = "https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-indexing/CHANGELOG.md" +Documentation = "https://zarr-indexing.readthedocs.io/" + +[dependency-groups] +# The transform tests exercise chunk resolution against zarr's ChunkGrid +# (tests/test_chunk_resolution.py) and are collected by the parent zarr-python +# test suite, which already has zarr installed. `zarr` is intentionally NOT +# listed here to avoid a workspace dependency cycle; run these tests from the +# repo root (`uv run pytest packages/zarr-indexing/tests`), not in isolation. +# `hypothesis` arrives via the `testing` extra, which is what +# `zarr_indexing.testing` needs; the repo-root `test` group pins the exact +# version CI runs against. Bump the two together. +test = ["pytest", "hypothesis>=6.160.0"] +docs = [ + # Pins match the zarr-python docs environment in the repo-root + # pyproject.toml so the two sites render with the same toolchain. + "mkdocs-material==9.7.7", + "mkdocs==1.6.1", + "mkdocstrings==1.0.6", + "mkdocstrings-python==2.0.5", + "griffe-inherited-docstrings==1.1.3", + # mkdocstrings uses ruff to format rendered signatures + "ruff==0.15.22", +] + +[tool.hatch.version] +source = "vcs" +tag-pattern = '^zarr_indexing-v(?P.+)$' +# `git_describe_command` ensures we get the zarr_indexing tags instead of latest. +# `local_scheme` strips the git commit info so the appending info is just a counter from latest tag. +# test-pypi doesn't accept git commit info in tags, and the count should be enough to distinguish unique runs. +raw-options = { root = "../..", git_describe_command = "git describe --dirty --tags --long --match zarr_indexing-v*", local_scheme = "no-local-version" } + +[tool.hatch.build.targets.wheel] +packages = ["src/zarr_indexing"] + +# An allowlist, so nothing that merely happens to sit in the package directory +# β€” a scratch script, a stray notebook β€” can ride along in a release. The list +# keeps an sdist self-testing: `tests/` carries the vendored ndsel conformance +# corpus, and `tests/test_doc_examples.py` executes `docs/snippets/*.py` and +# `examples/*/*.py`, so those are part of the suite rather than decoration. +# `pyproject.toml`, `README.md` and `LICENSE.txt` are added by hatchling itself. +[tool.hatch.build.targets.sdist] +include = [ + "/src", + "/tests", + "/docs", + "/examples", + "/mkdocs.yml", + "/justfile", + "/CHANGELOG.md", + "/CONTRIBUTING.md", +] + +[tool.ruff] +extend = "../../pyproject.toml" +target-version = "py312" + +[tool.ruff.lint.per-file-ignores] +# Chunk discovery and __dask_tokenize__ deliberately catch Exception: a +# foreign source's attributes may fail arbitrarily and discovery must degrade +# to "no information"; a token call must never raise. Configured here (not as +# noqa comments) because the pinned pre-commit ruff and the floating CI ruff +# disagree on whether these rules fire, and RUF100 strips the comments. +"src/zarr_indexing/lazy_array.py" = ["BLE001", "S110"] + +[tool.pytest.ini_options] +minversion = "7" +# src is collected for its doctests: every public object's Examples section +# executes under --doctest-modules, so the documented examples cannot rot. +testpaths = ["tests", "src/zarr_indexing"] +pythonpath = ["."] +xfail_strict = true +addopts = ["-ra", "--strict-config", "--strict-markers", "--doctest-modules"] +doctest_optionflags = [ + "NORMALIZE_WHITESPACE", + "ELLIPSIS", + "IGNORE_EXCEPTION_DETAIL", +] +filterwarnings = [ + "error", +] + +[tool.pyright] +include = [ + "src", + "docs/snippets", + "tests/test_doc_examples.py", +] +enableExperimentalFeatures = true +typeCheckingMode = "strict" +pythonVersion = "3.12" +# This strict config was written for zarr-metadata's JSON/dataclass-shaped +# code. zarr-indexing is numpy-heavy, and numpy's stubs return partially +# unknown types (e.g. `ndarray[Unknown, Unknown]`, `dtype[Unknown]`) even for +# fully-typed call sites, so the reportUnknown* family below cannot reasonably +# be satisfied here. Downgraded to warnings (not silenced) rather than +# disabled outright, and CI (which only fails the pyright job on errors, not +# warnings) still surfaces them for visibility. +reportUnknownVariableType = "warning" +reportUnknownArgumentType = "warning" +reportUnknownMemberType = "warning" +reportUnknownParameterType = "warning" + +[tool.numpydoc_validation] +checks = [ + "GL10", + "SS04", + "PR02", + "PR03", + "PR05", + "PR06", +] + +[tool.towncrier] +# Fragments for this package live alongside the package source, separate +# from the parent zarr-python `changes/` directory, so a PR touching only +# `packages/zarr-indexing/` produces a release note for this package only. +directory = "changes" +filename = "CHANGELOG.md" +package = "zarr_indexing" +underlines = ["", "", ""] +title_format = "## {version} ({project_date})" +issue_format = "[#{issue}](https://github.com/zarr-developers/zarr-python/issues/{issue})" +start_string = "\n" diff --git a/packages/zarr-indexing/src/zarr_indexing/__init__.py b/packages/zarr-indexing/src/zarr_indexing/__init__.py new file mode 100644 index 0000000000..9acfd28a21 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/__init__.py @@ -0,0 +1,116 @@ +"""Composable, lazy coordinate transforms for zarr array indexing. + +This package implements TensorStore-inspired index transforms. The core idea: +every indexing operation (slicing, fancy indexing, etc.) produces a coordinate +mapping from user space to storage space. These mappings compose lazily β€” no +I/O until you explicitly read or write. + +Key types: + +- `IndexDomain` β€” a rectangular region of integer coordinates +- `IndexTransform` β€” maps input coordinates to storage coordinates +- `ConstantMap`, `DimensionMap`, `ArrayMap` β€” the three ways a single + output dimension can depend on the input (see `output_map.py`) +- `IndexTransform.compose` β€” chain two transforms into one + +`LazyArray` wraps a system-memory/basic-indexing source and gives it deferred +indexing through `.lazy[...]`, yielding its reads as `Partition`s. Other +backends use an explicit `Reader` adapter. + +`plan_chunks` projects a transform through a caller-selected chunk grid without +coupling the result to a storage backend or scheduler. `selection_to_transform` +is also exported for consumers starting with a NumPy-style selection. The +`DimensionGridLike` Protocol describes the narrow grid surface chunk resolution +consumes without importing zarr. +""" + +from importlib.metadata import version + +from zarr_indexing.chunk_resolution import ( + ChunkCoverage, + ChunkPlan, + ChunkProjection, + plan_chunks, +) +from zarr_indexing.domain import IndexDomain +from zarr_indexing.errors import BoundsCheckError, VindexInvalidSelectionError +from zarr_indexing.grid import ( + ChunkGrid, + ChunkSpec, + DimensionGrid, + DimensionGridLike, + EdgeDimensionGrid, + FixedDimension, + VaryingDimension, + dimension_grids_from_chunks, +) +from zarr_indexing.json import ( + IndexDomainJSON, + IndexTransformJSON, + OutputIndexMapJSON, +) +from zarr_indexing.lazy_array import LazyArray, Partition +from zarr_indexing.messages import NdselError, normalize_ndsel, parse_ndsel +from zarr_indexing.output_map import ( + ArrayMap, + ConstantMap, + DimensionMap, + OutputIndexMap, + output_index_map_from_json, +) +from zarr_indexing.reader import ( + BasicReader, + NumPyReader, + ReadContext, + Reader, + UnitStepReader, + basic_reader, + numpy_reader, + unit_step_reader, +) +from zarr_indexing.transform import ( + IndexTransform, +) + +__version__ = version("zarr-indexing") + +__all__ = [ + "ArrayMap", + "BasicReader", + "BoundsCheckError", + "ChunkCoverage", + "ChunkGrid", + "ChunkPlan", + "ChunkProjection", + "ChunkSpec", + "ConstantMap", + "DimensionGrid", + "DimensionGridLike", + "DimensionMap", + "EdgeDimensionGrid", + "FixedDimension", + "IndexDomain", + "IndexDomainJSON", + "IndexTransform", + "IndexTransformJSON", + "LazyArray", + "NdselError", + "NumPyReader", + "OutputIndexMap", + "OutputIndexMapJSON", + "Partition", + "ReadContext", + "Reader", + "UnitStepReader", + "VaryingDimension", + "VindexInvalidSelectionError", + "__version__", + "basic_reader", + "dimension_grids_from_chunks", + "normalize_ndsel", + "numpy_reader", + "output_index_map_from_json", + "parse_ndsel", + "plan_chunks", + "unit_step_reader", +] diff --git a/packages/zarr-indexing/src/zarr_indexing/_affine.py b/packages/zarr-indexing/src/zarr_indexing/_affine.py new file mode 100644 index 0000000000..d1846ffe2d --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/_affine.py @@ -0,0 +1,77 @@ +"""Checked affine coordinate arithmetic.""" + +from __future__ import annotations + +from typing import Any, overload + +import numpy as np +import numpy.typing as npt + +_INTP_INFO = np.iinfo(np.intp) + + +def _fits_intp(value: int) -> bool: + return _INTP_INFO.min <= value <= _INTP_INFO.max + + +@overload +def checked_affine(offset: int, stride: int, coordinates: int) -> int: ... + + +@overload +def checked_affine( + offset: int, + stride: int, + coordinates: npt.NDArray[np.integer[Any]], +) -> npt.NDArray[np.intp]: ... + + +def checked_affine( + offset: int, + stride: int, + coordinates: int | npt.NDArray[np.integer[Any]], +) -> int | npt.NDArray[np.intp]: + """Evaluate ``offset + stride * coordinates`` without integer overflow. + + Bounds are established with Python integers before coordinates are cast or + NumPy performs fixed-width arithmetic. The common representable case then + uses an ``np.intp`` fast path whose multiplication and addition were proven + safe; cancellation cases use exact object arithmetic. + """ + offset = int(offset) + stride = int(stride) + if not isinstance(coordinates, np.ndarray): + mapped = offset + stride * int(coordinates) + if not _fits_intp(mapped): + raise OverflowError(f"output coordinate {mapped} is outside np.intp range") + return mapped + + if coordinates.size == 0: + return np.empty(coordinates.shape, dtype=np.intp) + + coordinate_min = int(np.min(coordinates)) + coordinate_max = int(np.max(coordinates)) + product_at_min = stride * coordinate_min + product_at_max = stride * coordinate_max + mapped_at_min = offset + product_at_min + mapped_at_max = offset + product_at_max + mapped_min = min(mapped_at_min, mapped_at_max) + mapped_max = max(mapped_at_min, mapped_at_max) + if not _fits_intp(mapped_min) or not _fits_intp(mapped_max): + invalid = mapped_min if not _fits_intp(mapped_min) else mapped_max + raise OverflowError(f"output coordinate {invalid} is outside np.intp range") + + safe_fixed_width = ( + _fits_intp(coordinate_min) + and _fits_intp(coordinate_max) + and _fits_intp(offset) + and _fits_intp(stride) + and _fits_intp(product_at_min) + and _fits_intp(product_at_max) + ) + if safe_fixed_width: + intp_coordinates = coordinates.astype(np.intp, copy=False) + return np.asarray(offset + stride * intp_coordinates, dtype=np.intp) + + exact = offset + stride * coordinates.astype(object) + return np.asarray(exact, dtype=np.intp) diff --git a/packages/zarr-indexing/src/zarr_indexing/_composition.py b/packages/zarr-indexing/src/zarr_indexing/_composition.py new file mode 100644 index 0000000000..f90ea26fa7 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/_composition.py @@ -0,0 +1,242 @@ +"""Composition β€” chaining two transforms into one. + +`compose(outer, inner)` is the operation that makes views stack. `outer` maps +user coordinates to intermediate coordinates, `inner` maps those intermediate +coordinates to output coordinates, and the result maps user coordinates +straight through β€” so a view of a view of an array is still a single +`IndexTransform`, and indexing never accumulates layers to walk at read time. + +Composition works one output map at a time, and each case reduces to +substituting the outer map into the inner one: + +- A `ConstantMap` inner map ignores its input, so it survives unchanged. +- A `DimensionMap` inner map is affine, so composing it with an outer + `ConstantMap` or `DimensionMap` folds into new `offset`/`stride` values; + composing it with an outer `ArrayMap` leaves the index array alone and + rescales around it. +- An `ArrayMap` inner map must be *evaluated* at the coordinates the outer + transform produces, which is the only case that touches array data. +""" + +from __future__ import annotations + +from typing import Any + +import numpy as np + +from zarr_indexing._affine import checked_affine +from zarr_indexing.errors import BoundsCheckError +from zarr_indexing.output_map import ( + ArrayMap, + ConstantMap, + DimensionMap, + OutputIndexMap, + array_map_or_constant, +) +from zarr_indexing.transform import IndexTransform + + +def compose(outer: IndexTransform, inner: IndexTransform) -> IndexTransform: + """Compose two IndexTransforms. + + `outer` maps user coords (rank m) to intermediate coords (rank n). + `inner` maps intermediate coords (rank n) to output coords (rank p). + The result maps user coords (rank m) to output coords (rank p). + + Precondition: `outer.output_rank == inner.domain.ndim`. + + Examples + -------- + Chained indexing β€” `source[2:5]`, then `[::-1]` on the result β€” collapses + to a single transform (a reversed axis keeps literal coordinates, so the + composed domain is `[-4, -1)`): + + >>> inner = IndexTransform.from_shape((10,))[2:5] + >>> outer = IndexTransform.identity(inner.domain)[::-1] + >>> chained = compose(outer, inner) + >>> chained == inner[::-1] + True + >>> [chained.apply((i,)) for i in (-4, -3, -2)] + [(4,), (3,), (2,)] + >>> np.arange(10)[2:5][::-1].tolist() + [4, 3, 2] + """ + if outer.output_rank != inner.domain.ndim: + raise ValueError( + f"outer output rank ({outer.output_rank}) must match inner input rank " + f"({inner.domain.ndim})" + ) + + _validate_outer_outputs(outer, inner) + + result_output = [ + _compose_single(outer, inner_map, inner.domain.inclusive_min) for inner_map in inner.output + ] + + return IndexTransform(domain=outer.domain, output=tuple(result_output)) + + +def _validate_outer_outputs(outer: IndexTransform, inner: IndexTransform) -> None: + """Prove that every intermediate coordinate is in the inner domain. + + An empty outer domain has no points, so containment is vacuously true. For + a nonempty domain, each map form has an exact, constant-space range proof: + constants are singletons, dimension maps are affine intervals, and array + maps need only their extrema. + """ + if any(extent == 0 for extent in outer.domain.shape): + return + + for axis, (outer_map, inner_lo, inner_hi) in enumerate( + zip( + outer.output, + inner.domain.inclusive_min, + inner.domain.exclusive_max, + strict=True, + ) + ): + output_lo, output_hi = _output_bounds(outer, outer_map) + if output_lo < inner_lo or output_hi >= inner_hi: + raise BoundsCheckError( + f"outer output dimension {axis} produces coordinates " + f"[{output_lo}, {output_hi}] outside the inner input domain " + f"[{inner_lo}, {inner_hi})" + ) + + +def _output_bounds(outer: IndexTransform, output_map: OutputIndexMap) -> tuple[int, int]: + """Return the exact inclusive bounds of one output map on a nonempty domain.""" + if isinstance(output_map, ConstantMap): + return output_map.offset, output_map.offset + + if isinstance(output_map, DimensionMap): + input_lo = outer.domain.inclusive_min[output_map.input_dimension] + input_hi = outer.domain.exclusive_max[output_map.input_dimension] + first = output_map.offset + output_map.stride * input_lo + last = output_map.offset + output_map.stride * (input_hi - 1) + return min(first, last), max(first, last) + + index_lo = int(output_map.index_array.min()) + index_hi = int(output_map.index_array.max()) + first = output_map.offset + output_map.stride * index_lo + last = output_map.offset + output_map.stride * index_hi + return min(first, last), max(first, last) + + +def _compose_single( + outer: IndexTransform, inner_map: OutputIndexMap, inner_origin: tuple[int, ...] +) -> OutputIndexMap: + """Compose a single inner output map with the full outer transform.""" + if isinstance(inner_map, ConstantMap): + return ConstantMap(offset=inner_map.offset) + + if isinstance(inner_map, DimensionMap): + return _compose_dimension(outer, inner_map) + + # inner_map: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap) + return _compose_array(outer, inner_map, inner_origin) + + +def _compose_dimension(outer: IndexTransform, inner_map: DimensionMap) -> OutputIndexMap: + """Compose when inner is a DimensionMap. + + storage = offset_i + stride_i * intermediate[dim_i] + where intermediate[dim_i] = outer.output[dim_i](user_input) + """ + dim_i = inner_map.input_dimension + offset_i = inner_map.offset + stride_i = inner_map.stride + outer_map = outer.output[dim_i] + + if isinstance(outer_map, ConstantMap): + return ConstantMap(offset=checked_affine(offset_i, stride_i, outer_map.offset)) + + if isinstance(outer_map, DimensionMap): + return DimensionMap( + input_dimension=outer_map.input_dimension, + offset=offset_i + stride_i * outer_map.offset, + stride=stride_i * outer_map.stride, + ) + + # outer_map: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap) + # Affine post-composition leaves the index array (and hence its full + # input rank and dependency axes) untouched. + return ArrayMap( + index_array=outer_map.index_array, + offset=offset_i + stride_i * outer_map.offset, + stride=stride_i * outer_map.stride, + ) + + +def _dimension_positions( + outer: IndexTransform, outer_map: DimensionMap, inner_origin: int +) -> np.ndarray[Any, np.dtype[np.intp]]: + """Build exact positional indices for an affine outer map.""" + dimension = outer_map.input_dimension + extent = outer.domain.shape[dimension] + start = checked_affine( + outer_map.offset - inner_origin, + outer_map.stride, + outer.domain.inclusive_min[dimension], + ) + shape = (1,) * dimension + (extent,) + (1,) * (outer.input_rank - dimension - 1) + if extent == 0: + return np.empty(shape, dtype=np.intp) + if extent == 1: + return np.full(shape, start, dtype=np.intp) + steps = np.arange(extent, dtype=np.intp) + return checked_affine(start, outer_map.stride, steps).reshape(shape) + + +def _array_positions(outer_map: ArrayMap, inner_origin: int) -> np.ndarray[Any, np.dtype[np.intp]]: + """Build exact positional indices without fixed-width affine overflow.""" + return checked_affine(outer_map.offset - inner_origin, outer_map.stride, outer_map.index_array) + + +def _positions_for_axis( + outer: IndexTransform, outer_map: OutputIndexMap, inner_origin: int +) -> int | np.ndarray[Any, np.dtype[np.intp]]: + """Convert one intermediate coordinate map to inner-array positions.""" + if isinstance(outer_map, ConstantMap): + return outer_map.offset - inner_origin + if isinstance(outer_map, DimensionMap): + return _dimension_positions(outer, outer_map, inner_origin) + return _array_positions(outer_map, inner_origin) + + +def _compose_array( + outer: IndexTransform, inner_map: ArrayMap, inner_origin: tuple[int, ...] +) -> OutputIndexMap: + """Compose when inner is an ArrayMap. + + storage = offset_i + stride_i * arr_i[intermediate] + We need to evaluate arr_i at the intermediate coordinates produced by outer. + + Both domains carry their own origin, and neither is necessarily 0 β€” a step-1 + slice keeps its literal bounds and a negative step produces a negative + origin, so non-zero origins are the ordinary case here rather than the exotic + one. The intermediate coordinates are read over the *outer* domain's own + range, and the inner array is addressed positionally from the *inner* + domain's origin. + """ + arr_i = inner_map.index_array + if any(extent == 0 for extent in outer.domain.shape): + # The empty map is singleton on every non-empty axis: it varies over no + # axis at all, and the emptiness lives in the domain emitted alongside. + empty_shape = tuple(0 if extent == 0 else 1 for extent in outer.domain.shape) + return ArrayMap( + index_array=np.empty(empty_shape, dtype=arr_i.dtype), + offset=inner_map.offset, + stride=inner_map.stride, + ) + + positions = tuple( + 0 if size == 1 else _positions_for_axis(outer, outer_map, origin) + for outer_map, origin, size in zip(outer.output, inner_origin, arr_i.shape, strict=True) + ) + # A gather narrowed to one coordinate β€” scalar or all-singleton β€” is the + # ConstantMap it equals; `array_map_or_constant` normalizes both. + gathered = np.asarray(arr_i[positions]) + if gathered.ndim == 0: + return ConstantMap(offset=checked_affine(inner_map.offset, inner_map.stride, int(gathered))) + return array_map_or_constant(gathered, offset=inner_map.offset, stride=inner_map.stride) diff --git a/packages/zarr-indexing/src/zarr_indexing/_selector.py b/packages/zarr-indexing/src/zarr_indexing/_selector.py new file mode 100644 index 0000000000..3a632ec886 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/_selector.py @@ -0,0 +1,41 @@ +"""Internal scalar-selector coercion shared by indexing dialects.""" + +from __future__ import annotations + +import operator +from typing import Any, SupportsIndex, cast + +import numpy as np + + +def is_bool_scalar(value: Any) -> bool: + """Return whether ``value`` is a Python or NumPy boolean scalar.""" + return isinstance(value, (bool, np.bool_)) + + +def as_scalar_index(value: Any) -> int | None: + """Return a non-boolean scalar selector as an exact Python integer. + + Selector coercion follows Python's ``__index__`` protocol, rather than + accepting only the concrete integer classes we happen to know about. In + particular, ``operator.index`` rejects lossy ``__int__``-only objects and + validates that ``__index__`` really returned an integer. + """ + if is_bool_scalar(value): + return None + # ndarray defines ``__index__`` for its scalar-integer case, but the + # attribute also makes non-scalar and non-integer arrays look like + # ``SupportsIndex`` at runtime. Those are array selectors, not malformed + # scalar selectors, and must continue through array dtype validation. + if isinstance(value, np.ndarray): + array = cast("np.ndarray[Any, np.dtype[Any]]", value) + if array.ndim != 0 or array.dtype.kind not in "iu": + return None + if not isinstance(value, SupportsIndex): + return None + return operator.index(cast(SupportsIndex, value)) + + +def require_index(value: Any) -> int: + """Coerce a required slice component through ``__index__``.""" + return operator.index(value) diff --git a/packages/zarr-indexing/src/zarr_indexing/_wire.py b/packages/zarr-indexing/src/zarr_indexing/_wire.py new file mode 100644 index 0000000000..c3e6fd82b6 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/_wire.py @@ -0,0 +1,119 @@ +"""Shared lowering rules between the canonical ndsel wire form and the engine. + +Package-private: the types that serialize themselves (`IndexDomain`, +`IndexTransform`, the output map kinds) all need these, so they cannot live in +any one of them, and they are not API. The three engine constraints named in +[`zarr_indexing.json`][zarr_indexing.json] β€” finite bounds, implicit bounds +lowering by value, integer `index_array` content β€” are enforced here. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import numpy as np + +from zarr_indexing.messages import NdselError + +if TYPE_CHECKING: + from zarr_indexing.domain import IndexDomain + from zarr_indexing.json import BoundJSON + + +def lower_bound(bound: BoundJSON, where: str) -> int: + """Lower a canonical bound to a finite integer, rejecting infinities. + + Reached only with a bound the message layer has already validated as an + `index-value`, so the one thing left to rule out is a sentinel: an + `IndexDomain` addresses a finite array. + """ + value = bound[0] if isinstance(bound, list) else bound + if value == "-inf" or value == "+inf": + raise NdselError( + "invalid_json", + f"{where} is infinite ({value!r}); an IndexDomain addresses a finite " + f"array and cannot lower an infinite bound", + ) + return int(value) + + +def lower_index_array(raw: Any, where: str) -> np.ndarray[Any, np.dtype[np.intp]]: + """Lower a canonical `index_array` to `intp`, rejecting non-integer content. + + The message layer carries `index_array` verbatim β€” the spec defers its shape + and type to the engine β€” so this is where the content is checked. An index + array names output coordinates, and nothing but an integer names one: converting + `[0.9, 1.9]` would silently read cells 0 and 1, and `[true, false]` cells 1 + and 0. Strings raise here rather than leaking NumPy's own conversion error. + """ + if not isinstance(raw, list): + # A bare integer would become a rank-0 array and then be widened into a + # length-1 map, so a document that names no cells would select one. + raise NdselError( + "invalid_json", + f"{where} must be an array of integers, got {raw!r}", + ) + try: + arr = np.asarray(raw) + except (TypeError, ValueError) as exc: + raise NdselError("invalid_json", f"{where} is not an array: {exc}") from exc + if arr.size == 0 and arr.dtype.kind == "f": + # An empty JSON list carries no element type and NumPy defaults it to + # float64. An empty selection is legal, so take it as an empty index array. + return np.zeros(arr.shape, dtype=np.intp) + if arr.dtype.kind not in "iu": + raise NdselError( + "invalid_json", + f"{where} must hold integers, got an array of {arr.dtype.name}; an " + f"index array names output coordinates, which floats, booleans and " + f"strings do not", + ) + return np.asarray(arr, dtype=np.intp) + + +def lower_labels(labels: list[str]) -> tuple[str, ...] | None: + """All-empty labels collapse to `None` so a label-free domain round-trips.""" + return None if all(label == "" for label in labels) else tuple(labels) + + +def emit_labels(labels: tuple[str, ...] | None, rank: int) -> list[str]: + """Emit canonical labels: `[""]*rank` when the domain is unlabeled.""" + return [""] * rank if labels is None else list(labels) + + +def full_rank_index_array( + arr: np.ndarray[Any, np.dtype[np.intp]], + domain: IndexDomain, + where: str, +) -> np.ndarray[Any, np.dtype[np.intp]]: + """Give an incoming `index_array` the input rank the engine requires. + + ndsel leaves index-array rank unvalidated, so a conformant producer may send + an array of lower rank that broadcasts against the domain. A non-empty one + is aligned to the *trailing* input dimensions, which is how NumPy broadcasts + and how a producer omitting leading singletons means it to be read. + + An empty array is a different matter: `[]` is the only spelling of every + empty shape once the leading axis is the zero-length one, so the axis it + varies over cannot be read off it. It is recovered from the domain, which + can only be empty on the axis in question β€” and rejected when the domain + leaves that ambiguous. This package never emits such a document (an empty + map is degenerate and collapses to a constant, as TensorStore's does), so + this path exists for external producers alone. + """ + if arr.size == 0 and arr.ndim != domain.ndim: + empty_axes = [k for k, extent in enumerate(domain.shape) if extent == 0] + if len(empty_axes) != 1: + raise NdselError( + "invalid_json", + f"{where}.index_array is empty, but the input domain has " + f"{len(empty_axes)} zero-length dimensions, so the axis it varies " + f"over cannot be recovered", + ) + shape = [1] * domain.ndim + shape[empty_axes[0]] = 0 + return arr.reshape(tuple(shape)) + + if arr.ndim < domain.ndim: + return arr.reshape((1,) * (domain.ndim - arr.ndim) + arr.shape) + return arr diff --git a/packages/zarr-indexing/src/zarr_indexing/boundary.py b/packages/zarr-indexing/src/zarr_indexing/boundary.py new file mode 100644 index 0000000000..e7f1b1c4bd --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/boundary.py @@ -0,0 +1,374 @@ +"""The positional (NumPy) selection dialect, lowered onto the transform algebra. + +The transform algebra uses **literal domain coordinates**: an index is a point +in the view's own coordinate system, which after `view = arr[10:50]` runs from +10 to 49, and a negative index is a negative coordinate rather than an offset +from the end (TensorStore's convention β€” see `zarr_indexing.transform`). + +NumPy uses **positions**: index 0 always means the first element of the object +being indexed, and `-1` means the last. This module translates between the two. +It validates a selection against the view's shape with NumPy semantics, then +shifts every coordinate by the domain's origin so the transform layer sees +literal coordinates. + +Note +---- +`zarr.Array` currently carries its own copy of this normalization, tuned to a +different boundary contract (`Array.lazy[...]` deliberately exposes the literal +dialect, so a view's coordinates keep their meaning across composition). This +module is the generic, zarr-free version used by `LazyArray`; consolidating +zarr's copy onto it is left to a follow-up. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +import numpy as np + +from zarr_indexing._selector import as_scalar_index, is_bool_scalar, require_index + +if TYPE_CHECKING: + from zarr_indexing.domain import IndexDomain + +SelectionMode = Literal["basic", "orthogonal", "vectorized"] + + +def _as_index_array(sel: Any) -> np.ndarray[Any, np.dtype[Any]] | None: + """Return `sel` as an ndarray if it is array-like, else None.""" + if isinstance(sel, np.ndarray): + return sel + if isinstance(sel, (list, tuple)): + arr = np.asarray(sel) + if arr.size == 0 and arr.dtype.kind == "f": + # An empty Python list carries no element type and NumPy defaults it + # to float64. Selecting nothing is legal β€” NumPy takes `a[np.ix_([])]` + # β€” so read it as the empty integer selection it spells, rather than + # rejecting it for a dtype it never had a chance to have. + return np.zeros(arr.shape, dtype=np.intp) + if arr.dtype.kind in "biu": + return arr + raise IndexError( + f"arrays used as indices must be of integer or boolean type; got dtype {arr.dtype}" + ) + return None + + +def _axes_consumed(sel: Any, mode: SelectionMode) -> int: + """How many axes of the view a single selection entry consumes.""" + if sel is None: + return 0 + arr = _as_index_array(sel) + # A multidimensional boolean mask consumes one axis per mask dimension. + # Orthogonal indexing is per-axis by construction, so a mask there is 1-D + # and consumes exactly one axis. + if mode == "vectorized" and arr is not None and arr.dtype == np.bool_: + return arr.ndim + return 1 + + +def _normalize_int(value: int, size: int, axis: int) -> int: + """Bounds-check a positional integer index, wrapping negatives NumPy-style.""" + idx = value + if idx < 0: + idx += size + if idx < 0 or idx >= size: + raise IndexError(f"index {value} is out of bounds for axis {axis} with size {size}") + return idx + + +def _normalize_slice(sel: slice, size: int, axis: int) -> tuple[int, int, int]: + """Resolve a positional slice to `(start, stop, step)`, either direction. + + `slice.indices` already applies NumPy's rules β€” negative bounds count from + the end, out-of-range bounds clamp, and a reversed slice runs downward with + `stop` one *below* the last selected position. The one thing it does not do + is canonicalize an empty result: it can hand back a stop on the far side of + the start (`5:2` going up, `2:5` going down), which the transform layer + reads as a direction error rather than an empty selection. Collapsing it to + `stop == start` keeps NumPy's "empty, not an error" answer. + """ + start_bound = None if sel.start is None else require_index(sel.start) + stop_bound = None if sel.stop is None else require_index(sel.stop) + step = 1 if sel.step is None else require_index(sel.step) + if step == 0: + raise ValueError(f"slice step cannot be zero (axis {axis})") # ValueError: NumPy parity + start, stop, step = slice(start_bound, stop_bound, step).indices(size) + stop = max(stop, start) if step > 0 else min(stop, start) + return start, stop, step + + +def _normalize_int_array( + arr: np.ndarray[Any, np.dtype[Any]], size: int, axis: int +) -> np.ndarray[Any, np.dtype[np.intp]]: + """Bounds-check a positional integer index array, wrapping negatives.""" + if arr.dtype.kind not in "iu": + raise IndexError( + f"arrays used as indices must be of integer or boolean type; got dtype {arr.dtype}" + ) + # Cast before wrapping: an unsigned array cannot represent the intermediate + # negative values, and `intp` covers every index NumPy can address. + out = arr.astype(np.intp, copy=True) + if out.size > 0: + negative = out < 0 + if bool(negative.any()): + out = np.where(negative, out + size, out) + lo, hi = int(out.min()), int(out.max()) + if lo < 0 or hi >= size: + bad = lo if lo < 0 else hi + raise IndexError(f"index {bad} is out of bounds for axis {axis} with size {size}") + return out + + +def _expanded_axis_walk(entries: tuple[Any, ...], ndim: int, mode: SelectionMode) -> list[int]: + """The starting axis each entry addresses, with an ellipsis expanded. + + The returned list has one entry per element of `entries`; the value for an + `Ellipsis` (or a `newaxis`) is the axis it starts at, which is also the axis + the following entry resumes from once the skipped axes are accounted for. + """ + for sel in entries: + if is_bool_scalar(sel): + raise IndexError( + "boolean scalars are not valid indices; use a boolean array " + "matching the shape of the axes it selects" + ) + if sum(1 for sel in entries if sel is Ellipsis) > 1: + raise IndexError("an index can only have a single ellipsis ('...')") + consumed = sum(_axes_consumed(sel, mode) for sel in entries if sel is not Ellipsis) + if consumed > ndim: + raise IndexError( + f"too many indices for array: array has {ndim} dimensions, but {consumed} were indexed" + ) + + axes: list[int] = [] + axis = 0 + for sel in entries: + axes.append(axis) + axis += (ndim - consumed) if sel is Ellipsis else _axes_consumed(sel, mode) + return axes + + +def validate_advanced_selection( + selection: Any, + domain: IndexDomain, + mode: Literal["orthogonal", "vectorized"], +) -> None: + """Validate advanced-index selector dtypes and boolean mask extents. + + This is the validation shared by positional callers such as `LazyArray` + and direct `IndexTransform.oindex` / `.vindex` callers. It deliberately + does not normalize coordinates: direct transforms use literal coordinates, + whereas positional callers shift and wrap them separately. + """ + entries: tuple[Any, ...] = selection if isinstance(selection, tuple) else (selection,) + axes = _expanded_axis_walk(entries, domain.ndim, mode) + + for sel, axis in zip(entries, axes, strict=True): + arr = _as_index_array(sel) + if arr is None: + continue + if arr.dtype == np.bool_: + n_axes = _axes_consumed(sel, mode) + expected = domain.shape[axis : axis + n_axes] + if arr.shape != tuple(expected): + extent = ( + f"dimension {expected[0]}" + if len(expected) == 1 + else f"dimensions {tuple(expected)}" + ) + raise IndexError( + f"boolean index has shape {arr.shape} but {extent} has shape {tuple(expected)}" + ) + elif arr.dtype.kind not in "iu": + raise IndexError( + f"arrays used as indices must be of integer or boolean type; got dtype {arr.dtype}" + ) + + +def split_scalar_axes( + selection: Any, + domain: IndexDomain, + mode: SelectionMode, +) -> tuple[tuple[Any, ...] | None, Any]: + """Peel scalar integer indices out of a fancy selection. + + A scalar integer drops its axis, and neither the orthogonal nor the + vectorized path of the transform algebra models that β€” both widen a scalar + into a length-1 index array, which keeps the axis β€” so the scalars are split + off here and applied as a separate basic step first. + + Applying them *first* is this package's rule, not NumPy's. NumPy groups a + scalar with the advanced indices for the purpose of placing the broadcast + result, so the two disagree when a scalar and an index array are separated: + `a[0, ..., [1, 2]]` has shape `(2, 3)` for a `(2, 3, 4)` array, where + `a[0][..., [1, 2]]` has shape `(3, 2)`. The earlier claim here that they + always agree rested on `a[0, [1, 2], :]`, where the indices are adjacent and + they happen to. Scalar-first is the documented dialect (see the `lazy_array` + module docstring) β€” the divergence is deliberate, and this note exists so + that the correct end is not "fixed" later. + + Parameters + ---------- + selection + A positional orthogonal or vectorized selection. + domain + The domain of the view being indexed. + mode + `"orthogonal"` or `"vectorized"`; controls how many axes each entry + covers, which decides where the scalars sit. + + Returns + ------- + tuple[tuple[Any, ...] | None, Any] + `(basic_selection, remaining_selection)`. `basic_selection` is a + full-rank basic selection in **literal** domain coordinates that drops + the scalar axes, or `None` when the selection has no scalar entries (in + which case `remaining_selection` is `selection` unchanged). + + Raises + ------ + IndexError + If a boolean scalar is used as an index, an index is out of bounds, or + too many indices are supplied. + """ + entries = selection if isinstance(selection, tuple) else (selection,) + axes = _expanded_axis_walk(entries, domain.ndim, mode) + + scalar_axes: dict[int, int] = {} + remaining: list[Any] = [] + for sel, axis in zip(entries, axes, strict=True): + scalar = as_scalar_index(sel) + if scalar is not None: + scalar_axes[axis] = _normalize_int(scalar, domain.shape[axis], axis) + else: + remaining.append(sel) + + if len(scalar_axes) == 0: + return None, selection + + basic: list[Any] = [] + for axis in range(domain.ndim): + lo = domain.inclusive_min[axis] + if axis in scalar_axes: + basic.append(lo + scalar_axes[axis]) + else: + basic.append(slice(lo, domain.exclusive_max[axis])) + return tuple(basic), tuple(remaining) + + +def normalize_positional_selection( + selection: Any, + domain: IndexDomain, + mode: SelectionMode, +) -> Any: + """Translate a positional (NumPy-dialect) selection into literal coordinates. + + Positions are zero-based offsets into the current view; negatives wrap + from the end. The returned selection addresses the same cells in the + literal coordinate system `domain` uses, ready for + `zarr_indexing.transform.selection_to_transform`. + + Parameters + ---------- + selection + A NumPy-style selection: integers, slices, `Ellipsis`, integer arrays or + lists, or boolean arrays. + domain + The domain of the view being indexed. Its shape defines the positional + bounds and its origin the coordinate shift. + mode + Which selection dialect the entries follow: `"basic"` (integers and + slices), `"orthogonal"` (per-axis arrays, outer product), or + `"vectorized"` (correlated coordinate arrays or a single mask). + + Returns + ------- + tuple[Any, ...] + The selection with every coordinate expressed in literal domain + coordinates. + + Raises + ------ + IndexError + If a boolean scalar is used as an index, a boolean mask does not match + the shape of the axes it covers, an index is out of bounds, or too many + indices are supplied. + """ + entries = selection if isinstance(selection, tuple) else (selection,) + shape = domain.shape + origin = domain.inclusive_min + ndim = domain.ndim + + if mode in ("orthogonal", "vectorized"): + validate_advanced_selection(selection, domain, mode) + else: + for sel in entries: + if is_bool_scalar(sel): + raise IndexError( + "boolean scalars are not valid indices; use a boolean array " + "matching the shape of the axes it selects" + ) + + n_ellipsis = sum(1 for sel in entries if sel is Ellipsis) + if n_ellipsis > 1: + raise IndexError("an index can only have a single ellipsis ('...')") + consumed = sum(_axes_consumed(sel, mode) for sel in entries if sel is not Ellipsis) + if consumed > ndim: + raise IndexError( + f"too many indices for array: array has {ndim} dimensions, but {consumed} were indexed" + ) + + result: list[Any] = [] + axis = 0 + for sel in entries: + if sel is Ellipsis: + # Passed through rather than expanded: every mode of + # `selection_to_transform` expands an ellipsis (and pads short + # selections) to whole-axis slices itself, and `vectorized` mode + # rejects an explicit slice, so expanding here would turn a legal + # partial coordinate selection into an error. + result.append(Ellipsis) + axis += ndim - consumed + continue + if sel is None: + # newaxis: no axis of the view is consumed, and there is no + # coordinate to shift. The transform layer decides whether the mode + # accepts it. + result.append(None) + continue + + arr = _as_index_array(sel) + if arr is not None and arr.dtype == np.bool_: + n_axes = _axes_consumed(sel, mode) + expected = shape[axis : axis + n_axes] + if arr.shape != tuple(expected): + raise IndexError( + f"boolean index has shape {arr.shape} but the axes it " + f"covers have shape {tuple(expected)}" + ) + for offset, positions in enumerate(np.nonzero(arr)): + result.append(positions.astype(np.intp) + origin[axis + offset]) + axis += n_axes + continue + + if axis >= ndim: + raise IndexError( + f"too many indices for array: array has {ndim} dimensions, " + f"but {consumed} were indexed" + ) + size = shape[axis] + if arr is not None: + result.append(_normalize_int_array(arr, size, axis) + origin[axis]) + elif isinstance(sel, slice): + start, stop, step = _normalize_slice(sel, size, axis) + result.append(slice(start + origin[axis], stop + origin[axis], step)) + elif (scalar := as_scalar_index(sel)) is not None: + result.append(_normalize_int(scalar, size, axis) + origin[axis]) + else: + raise IndexError(f"unsupported selection type: {type(sel)!r}") + axis += 1 + + # Axes the selection did not mention are left to `selection_to_transform`, + # which pads them with whole-axis slices in every mode. + return tuple(result) diff --git a/packages/zarr-indexing/src/zarr_indexing/chunk_resolution.py b/packages/zarr-indexing/src/zarr_indexing/chunk_resolution.py new file mode 100644 index 0000000000..af148685a0 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/chunk_resolution.py @@ -0,0 +1,595 @@ +"""Chunk resolution β€” mapping transforms to chunk-level I/O. + +Given an `IndexTransform` (which coordinates a user wants to access) and a +`ChunkGrid` (how storage is divided into chunks), chunk resolution answers: + + For each chunk, which storage coordinates does this transform touch, + and where do those values land in the output buffer? + +The algorithm is: + +1. **Enumerate candidate chunks** β€” determine which chunks could possibly + be touched by the transform's output coordinate ranges. + +2. **Intersect** β€” for each candidate chunk, call + `transform.intersect(chunk_domain)` to restrict the transform to + coordinates within that chunk. If the intersection is empty, skip it. + +3. **Translate** β€” shift the restricted transform to chunk-local coordinates + via `transform.translate(-chunk_origin)`. + +4. **Project** β€” pair the chunk-local storage transform with a transform back + to the request's cells. Both use the same compact, zero-origin domain. + +Sorted one-dimensional correlated array maps can be partitioned directly +because every touched chunk owns a contiguous slice of the index array. That +case bypasses candidate enumeration and repeated intersection. + +The public result is a lazy, reusable `ChunkPlan`. Each `ChunkProjection` is +source-independent: it identifies the chunk and expresses both sides of the +gather without assuming NumPy selectors, a codec pipeline, or an execution +scheduler. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Literal + +import numpy as np + +from zarr_indexing._affine import checked_affine +from zarr_indexing.domain import IndexDomain +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap +from zarr_indexing.transform import ( + IndexTransform, +) + +if TYPE_CHECKING: + from collections.abc import Iterator, Sequence + + from zarr_indexing.grid import DimensionGridLike + +_OutIndices = ( + dict[int, np.ndarray[Any, np.dtype[np.intp]]] | np.ndarray[Any, np.dtype[np.intp]] | None +) + +_ChunkTransformResult = tuple[ + tuple[int, ...], + IndexTransform, + _OutIndices, +] + +type ChunkCoverage = Literal["full", "partial", "unknown"] + + +def _data_size(dim_grid: DimensionGridLike, chunk_ix: int) -> int: + """Return a chunk's data extent, falling back for narrow-protocol grids.""" + data_size = getattr(dim_grid, "data_size", None) + if data_size is None: + return dim_grid.chunk_size(chunk_ix) + return int(data_size(chunk_ix)) + + +@dataclass(frozen=True, slots=True) +class ChunkProjection: + """One source-independent projection of a request through a chunk. + + Both transforms share a synthetic input domain. ``chunk_transform`` maps + that domain to chunk-local storage coordinates; ``cell_transform`` maps it + to the original request domain. + + Attributes + ---------- + chunk_coords + Coordinates of the selected cell in the caller's grid. + chunk_domain + Bounds of that grid cell in global storage coordinates. + chunk_transform + Mapping from the shared synthetic domain to chunk-local storage. + cell_transform + Mapping from the shared synthetic domain to request coordinates. + coverage + Whether the request is proven to cover the whole grid cell exactly + once. Fancy selections are conservatively ``"unknown"``. + + Examples + -------- + Row 1 of a `(3, 4)` array with `(2, 2)` chunks touches only part of the + first chunk, whose domain spans rows `[0, 2)` and columns `[0, 2)`: + + >>> from zarr_indexing import IndexTransform + >>> from zarr_indexing.grid import dimension_grids_from_chunks + >>> grids = dimension_grids_from_chunks((2, 2), shape=(3, 4)) + >>> plan = plan_chunks(IndexTransform.from_shape((3, 4))[1, :], grids) + >>> first = next(iter(plan)) + >>> first.chunk_coords + (0, 0) + >>> first.chunk_domain.shape + (2, 2) + >>> first.coverage + 'partial' + """ + + chunk_coords: tuple[int, ...] + chunk_domain: IndexDomain + chunk_transform: IndexTransform + cell_transform: IndexTransform + coverage: ChunkCoverage + + def __post_init__(self) -> None: + if self.chunk_transform.domain != self.cell_transform.domain: + raise ValueError( + "chunk_transform and cell_transform must share an input domain; " + f"got {self.chunk_transform.domain!r} and {self.cell_transform.domain!r}" + ) + + +@dataclass(frozen=True, slots=True) +class ChunkPlan: + """A reusable, lazy partition of an index transform over a chunk grid. + + Construct plans with `plan_chunks`; iterating either the plan or + `projections()` performs a fresh chunk walk. + + Examples + -------- + Row 1 of a `(3, 4)` array with `(2, 2)` chunks crosses two chunks, and + the plan can be walked again after it is exhausted: + + >>> from zarr_indexing import IndexTransform + >>> from zarr_indexing.grid import dimension_grids_from_chunks + >>> grids = dimension_grids_from_chunks((2, 2), shape=(3, 4)) + >>> plan = plan_chunks(IndexTransform.from_shape((3, 4))[1, :], grids) + >>> [p.chunk_coords for p in plan] + [(0, 0), (0, 1)] + >>> [p.chunk_coords for p in plan.projections()] + [(0, 0), (0, 1)] + """ + + transform: IndexTransform + """The composed request this plan partitions.""" + + dimension_grids: tuple[DimensionGridLike, ...] + """One grid per storage dimension, defining the chunk layout the plan walks.""" + + def projections(self) -> Iterator[ChunkProjection]: + """Return a fresh iterator over the chunks touched by this plan.""" + return _iter_chunk_projections(self.transform, self.dimension_grids) + + def __iter__(self) -> Iterator[ChunkProjection]: + """Equivalent to `projections()`: each iteration performs a fresh chunk walk.""" + return self.projections() + + +def plan_chunks( + transform: IndexTransform, + dimension_grids: Sequence[DimensionGridLike], +) -> ChunkPlan: + """Plan a transform against a caller-selected chunk grid. + + Parameters + ---------- + transform + Mapping from the request domain to storage coordinates. + dimension_grids + One storage grid per transform output dimension. + + Returns + ------- + ChunkPlan + A reusable plan whose projections are computed lazily. + + Examples + -------- + Row 1 of a `(3, 4)` array with `(2, 2)` chunks touches the two chunks in + the top grid row, each contributing a `(2, 2)` chunk domain: + + >>> from zarr_indexing import IndexTransform + >>> from zarr_indexing.grid import dimension_grids_from_chunks + >>> grids = dimension_grids_from_chunks((2, 2), shape=(3, 4)) + >>> plan = plan_chunks(IndexTransform.from_shape((3, 4))[1, :], grids) + >>> [p.chunk_coords for p in plan] + [(0, 0), (0, 1)] + >>> [p.chunk_domain.shape for p in plan] + [(2, 2), (2, 2)] + """ + grids = tuple(dimension_grids) + if len(grids) != transform.output_rank: + raise ValueError( + "dimension_grids must have one entry per transform output dimension; " + f"got {len(grids)} grids for output rank {transform.output_rank}" + ) + return ChunkPlan(transform=transform, dimension_grids=grids) + + +def _one_dimensional_array_map( + transform: IndexTransform, +) -> tuple[ArrayMap, np.ndarray[Any, np.dtype[np.intp]]] | None: + """Return a nonempty 1-D single-ArrayMap transform's map and storage coords. + + A one-dimensional array selection has no cross-dimensional correlation to + preserve β€” the orthogonal and vectorized flavors coincide there β€” so the + sorted fast path applies to either spelling. The computed storage + coordinates are also reused by general resolution when they are unsorted. + """ + if transform.input_rank != 1 or transform.output_rank != 1: + return None + + m = transform.output[0] + if not isinstance(m, ArrayMap) or m.index_array.ndim != 1 or m.index_array.size == 0: + return None + + return m, checked_affine(m.offset, m.stride, m.index_array) + + +def _iter_sorted_1d_array_map( + m: ArrayMap, + storage: np.ndarray[Any, np.dtype[np.intp]], + dim_grid: DimensionGridLike, +) -> Iterator[_ChunkTransformResult]: + """Resolve a sorted 1-D ArrayMap one touched chunk at a time.""" + start = 0 + while start < storage.size: + chunk = dim_grid.index_to_chunk(int(storage[start])) + chunk_start = dim_grid.chunk_offset(chunk) + chunk_stop = chunk_start + _data_size(dim_grid, chunk) + stop = int(np.searchsorted(storage, chunk_stop, side="left")) + + restricted = IndexTransform( + domain=IndexDomain(inclusive_min=(0,), exclusive_max=(stop - start,)), + output=( + ArrayMap( + index_array=m.index_array[start:stop], + offset=m.offset, + stride=m.stride, + ), + ), + ) + local = restricted.translate((-chunk_start,)) + surviving = np.arange(start, stop, dtype=np.intp) + + yield (chunk,), local, surviving + start = stop + + +def _iter_chunk_transform_results( + transform: IndexTransform, + dim_grids: Sequence[DimensionGridLike], +) -> Iterator[_ChunkTransformResult]: + """Resolve a transform into private intersection bookkeeping. + + The survivor arrays are an implementation detail immediately converted to + a public `cell_transform` by `_iter_chunk_projections`. + """ + + if any(size == 0 for size in transform.domain.shape): + # An empty view touches no chunk. Checked on the domain rather than on + # the index arrays: an axis of genuine extent 1 is stored as a broadcast + # singleton, so a slice that empties the domain does not shrink the + # array, and the emptiness shows only here. + return + + array_map_1d = _one_dimensional_array_map(transform) + if array_map_1d is not None: + sorted_map, storage = array_map_1d + if storage[0] <= storage[-1] and bool(np.all(storage[1:] >= storage[:-1])): + dim_grid = dim_grids[0] + first_chunk = dim_grid.index_to_chunk(int(storage[0])) + if dim_grid.chunk_size(first_chunk) > 0: + yield from _iter_sorted_1d_array_map(sorted_map, storage, dim_grid) + return + + # Enumerate candidate chunks via the cartesian product of per-slot candidate + # chunk ids, then for each candidate intersect the transform with the chunk + # domain (`transform.intersect` handles orthogonal and vectorized cases + # alike, filtering out combinations it does not actually touch). + # + # A slot covers one or more output dimensions and contributes exactly the + # chunk-coordinate tuples those dimensions can touch: + # + # - `ConstantMap`/`DimensionMap` dims each form their own slot with a + # contiguous range β€” a single chunk for a constant, and the span between + # the first and last chunk for a slice. These are already tight (or + # nearly so). + # - Orthogonal `ArrayMap` (fancy) dims each form their own slot with only + # the *distinct* chunk ids the index array actually lands in + # (`np.unique`), never the dense `range(min_chunk, max_chunk + 1)` + # between them. A sparse fancy selection (e.g. two far-apart coordinates) + # would otherwise enumerate every chunk in the bounding box, making + # resolution scale with grid size instead of with the number of selected + # coordinates. + # - Correlated (vindex) `ArrayMap` dims share one *joint* slot holding the + # distinct chunk-coordinate tuples the points actually land in. The + # cartesian product of their per-dimension distinct sets would include + # combinations no point touches β€” quadratic in the number of selected + # points for a diagonal selection β€” while the joint distinct set is + # bounded by the point count (see zarr-python gh-4174). + structure = transform.index_array_structure + correlated_dims: list[int] = [] + correlated_chunk_ids: list[np.ndarray[Any, np.dtype[np.intp]]] = [] + slot_dims: list[tuple[int, ...]] = [] + slot_candidates: list[Sequence[tuple[int, ...]]] = [] + for out_dim, m in enumerate(transform.output): + dg = dim_grids[out_dim] + if isinstance(m, ConstantMap): + # Single chunk + coordinate = checked_affine(m.offset, 0, 0) + c = dg.index_to_chunk(coordinate) + slot_dims.append((out_dim,)) + slot_candidates.append(((c,),)) + elif isinstance(m, DimensionMap): + d = m.input_dimension + dim_lo = transform.domain.inclusive_min[d] + dim_hi = transform.domain.exclusive_max[d] + if dim_lo >= dim_hi: + return # empty domain + first_storage = checked_affine(m.offset, m.stride, dim_lo) + if m.stride > 0: + s_min = first_storage + s_max = checked_affine(m.offset, m.stride, dim_hi - 1) + elif m.stride < 0: + s_min = checked_affine(m.offset, m.stride, dim_hi - 1) + s_max = first_storage + else: + s_min = s_max = first_storage + first = dg.index_to_chunk(s_min) + last = dg.index_to_chunk(s_max) + slot_dims.append((out_dim,)) + point_count = dim_hi - dim_lo + chunk_count = last - first + 1 + if point_count < chunk_count: + steps = np.arange(point_count, dtype=np.intp) + storage = checked_affine(first_storage, m.stride, steps) + chunk_ids = dg.indices_to_chunks(storage) + slot_candidates.append([(int(c),) for c in np.unique(chunk_ids)]) + else: + slot_candidates.append([(c,) for c in range(first, last + 1)]) + else: + # m: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap). + # Storage coordinates were already computed for a correlated 1-D map. + storage = ( + array_map_1d[1] + if array_map_1d is not None + else checked_affine(m.offset, m.stride, m.index_array) + ) + if storage.size == 0: + # Empty fancy selection: no coordinates, so no chunks are touched. + return + # Keep the index-array shape: correlated maps broadcast against each + # other below, and raveling first would lose the singleton axes. + chunk_ids = dg.indices_to_chunks(storage) + if structure == "orthogonal": + slot_dims.append((out_dim,)) + slot_candidates.append([(int(c),) for c in np.unique(chunk_ids)]) + else: + # Every index array of a general transform joins one joint + # slot: their chunk ids broadcast over the shared block, so the + # distinct tuples enumerate only combinations some point + # actually touches. + correlated_dims.append(out_dim) + correlated_chunk_ids.append(chunk_ids) + + if len(correlated_dims) == 1: + slot_dims.append((correlated_dims[0],)) + slot_candidates.append([(int(c),) for c in np.unique(correlated_chunk_ids[0])]) + elif len(correlated_dims) >= 2: + # Group the points jointly: distinct rows of the per-point chunk + # coordinates, O(points log points) regardless of grid size. + broadcast = np.broadcast_arrays(*correlated_chunk_ids) + stacked = np.stack([b.ravel() for b in broadcast], axis=1) + joint = np.unique(stacked, axis=0) + slot_dims.append(tuple(correlated_dims)) + slot_candidates.append([tuple(int(c) for c in row) for row in joint]) + + import itertools + + output_rank = len(transform.output) + for combo in itertools.product(*slot_candidates): + chunk_coords_list = [0] * output_rank + for dims, part in zip(slot_dims, combo, strict=True): + for d, c in zip(dims, part, strict=True): + chunk_coords_list[d] = c + chunk_coords = tuple(chunk_coords_list) + + # Build the chunk domain in storage space + chunk_min: list[int] = [] + chunk_max: list[int] = [] + chunk_shift: list[int] = [] + for out_dim, c in enumerate(chunk_coords): + dg = dim_grids[out_dim] + c_start = dg.chunk_offset(c) + c_size = _data_size(dg, c) + chunk_min.append(c_start) + chunk_max.append(c_start + c_size) + chunk_shift.append(-c_start) + + chunk_domain = IndexDomain( + inclusive_min=tuple(chunk_min), + exclusive_max=tuple(chunk_max), + ) + + # Intersect transform with chunk domain + result = transform.intersect(chunk_domain) + if result is None: + continue + + restricted, surviving = result + + # Translate to chunk-local coordinates + local = restricted.translate(tuple(chunk_shift)) + + yield (chunk_coords, local, surviving) + + +def _covers_whole_chunk(transform: IndexTransform, chunk_shape: tuple[int, ...]) -> bool: + """Whether an affine chunk-local transform bijects onto every chunk cell.""" + domain = transform.domain + used_nontrivial_inputs: set[int] = set() + for out_dim, m in enumerate(transform.output): + extent = chunk_shape[out_dim] + if isinstance(m, ConstantMap): + if extent != 1 or m.offset != 0: + return False + elif isinstance(m, DimensionMap): + if abs(m.stride) != 1: + return False + lo = domain.inclusive_min[m.input_dimension] + hi = domain.exclusive_max[m.input_dimension] + if hi <= lo: + if extent != 0: + return False + continue + first = m.offset + m.stride * lo + last = m.offset + m.stride * (hi - 1) + if min(first, last) != 0 or max(first, last) != extent - 1: + return False + if extent > 1: + if m.input_dimension in used_nontrivial_inputs: + return False + used_nontrivial_inputs.add(m.input_dimension) + else: + return False + nontrivial_inputs = {dimension for dimension, extent in enumerate(domain.shape) if extent > 1} + return used_nontrivial_inputs == nontrivial_inputs + + +def _orthogonal_cell_transform( + original: IndexTransform, + restricted: IndexTransform, + survivors: dict[int, np.ndarray[Any, np.dtype[np.intp]]] | np.ndarray[Any, np.dtype[np.intp]], +) -> IndexTransform: + """Map a compacted orthogonal intersection back to request coordinates.""" + by_input_dimension: dict[int, np.ndarray[Any, np.dtype[np.intp]]] = {} + if isinstance(survivors, dict): + survivor_items = survivors.items() + else: + array_output_dimensions = [ + output_dimension + for output_dimension, output_map in enumerate(original.output) + if isinstance(output_map, ArrayMap) + ] + if len(array_output_dimensions) != 1: + raise ValueError( + "one survivor array requires exactly one orthogonal ArrayMap; " + f"found output dimensions {array_output_dimensions}" + ) + survivor_items = ((array_output_dimensions[0], survivors),) + + for output_dimension, positions in survivor_items: + output_map = original.output[output_dimension] + if not isinstance(output_map, ArrayMap): + raise TypeError( + f"survivors for output dimension {output_dimension} do not describe an ArrayMap" + ) + input_dimension = output_map.dependent_axis + if input_dimension is None: + raise ValueError( + f"output dimension {output_dimension} has no orthogonal input dimension" + ) + by_input_dimension[input_dimension] = np.asarray(positions, dtype=np.intp) + + output: list[ConstantMap | DimensionMap | ArrayMap] = [] + rank = original.input_rank + for input_dimension in range(rank): + positions = by_input_dimension.get(input_dimension) + if positions is None: + output.append(DimensionMap(input_dimension=input_dimension)) + continue + shape = (1,) * input_dimension + (positions.size,) + (1,) * (rank - input_dimension - 1) + output.append( + ArrayMap( + index_array=positions.reshape(shape), + offset=original.domain.inclusive_min[input_dimension], + ) + ) + return IndexTransform(domain=restricted.domain, output=tuple(output)) + + +def _correlated_cell_transform( + original: IndexTransform, + restricted: IndexTransform, + survivors: np.ndarray[Any, np.dtype[np.intp]], +) -> IndexTransform: + """Map compacted correlated points back through the request's row-major domain.""" + positions = np.asarray(survivors, dtype=np.intp) + # Correlated broadcast axes already contribute positional survivor offsets; + # residual affine axes still contribute literal coordinates. Remove only + # the latter origins before unraveling the fully positional flat offsets. + literal_axes = { + output_map.input_dimension + for output_map in original.output + if isinstance(output_map, DimensionMap) + } + origin_offset = 0 + flat_stride = 1 + for input_dimension in range(original.input_rank - 1, -1, -1): + if input_dimension in literal_axes: + origin_offset += original.domain.inclusive_min[input_dimension] * flat_stride + extent = original.domain.shape[input_dimension] + flat_stride *= extent + coordinates = np.unravel_index( + checked_affine(-origin_offset, 1, positions), original.domain.shape + ) + output = tuple( + ArrayMap( + index_array=np.asarray(coordinate, dtype=np.intp), + offset=origin, + ) + for coordinate, origin in zip(coordinates, original.domain.inclusive_min, strict=True) + ) + return IndexTransform(domain=restricted.domain, output=output) + + +def _cell_transform( + original: IndexTransform, + restricted: IndexTransform, + survivors: _OutIndices, +) -> IndexTransform: + """Convert private survivor bookkeeping into a direction-neutral transform.""" + if survivors is None: + return IndexTransform.identity(restricted.domain) + if original.index_array_structure == "general": + if isinstance(survivors, dict): + raise ValueError("general intersections require one shared survivor array") + return _correlated_cell_transform(original, restricted, survivors) + return _orthogonal_cell_transform(original, restricted, survivors) + + +def _iter_chunk_projections( + transform: IndexTransform, + dim_grids: Sequence[DimensionGridLike], +) -> Iterator[ChunkProjection]: + """Convert private intersection results into public paired projections.""" + for chunk_coords, chunk_transform, survivors in _iter_chunk_transform_results( + transform, dim_grids + ): + chunk_min = tuple( + grid.chunk_offset(coord) for grid, coord in zip(dim_grids, chunk_coords, strict=True) + ) + chunk_shape = tuple( + _data_size(grid, coord) for grid, coord in zip(dim_grids, chunk_coords, strict=True) + ) + chunk_domain = IndexDomain( + inclusive_min=chunk_min, + exclusive_max=tuple( + origin + extent for origin, extent in zip(chunk_min, chunk_shape, strict=True) + ), + ) + cell_transform = _cell_transform(transform, chunk_transform, survivors) + synthetic_origin = (0,) * chunk_transform.input_rank + chunk_transform = chunk_transform.translate_domain_to(synthetic_origin) + cell_transform = cell_transform.translate_domain_to(synthetic_origin) + if survivors is not None or any(isinstance(m, ArrayMap) for m in chunk_transform.output): + coverage: ChunkCoverage = "unknown" + elif _covers_whole_chunk(chunk_transform, chunk_shape): + coverage = "full" + else: + coverage = "partial" + yield ChunkProjection( + chunk_coords=chunk_coords, + chunk_domain=chunk_domain, + chunk_transform=chunk_transform, + cell_transform=cell_transform, + coverage=coverage, + ) diff --git a/packages/zarr-indexing/src/zarr_indexing/domain.py b/packages/zarr-indexing/src/zarr_indexing/domain.py new file mode 100644 index 0000000000..a353b81254 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/domain.py @@ -0,0 +1,325 @@ +"""Index domains β€” rectangular regions in N-dimensional integer space. + +An `IndexDomain` represents the set of valid coordinates for an array or +array view. It is the cartesian product of per-dimension integer ranges:: + + IndexDomain(inclusive_min=(2, 5), exclusive_max=(10, 20)) + # represents {(i, j) : 2 <= i < 10, 5 <= j < 20} + +Unlike NumPy, domains can have **non-zero origins**. After slicing +`arr[5:10]`, the result has origin 5 and shape 5 β€” coordinates 5 through +9 are valid. This follows the TensorStore convention. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any + +from zarr_indexing.errors import BoundsCheckError + +if TYPE_CHECKING: + from zarr_indexing.json import IndexDomainJSON + + +@dataclass(frozen=True, slots=True) +class IndexDomain: + """A rectangular region in N-dimensional index space. + + The valid coordinates are the integers in + `[inclusive_min[d], exclusive_max[d])` for each dimension `d`. + + Examples + -------- + >>> domain = IndexDomain(inclusive_min=(2, 5), exclusive_max=(10, 20)) + >>> domain.shape + (8, 15) + + Unlike a NumPy shape, a domain keeps literal coordinates: narrowing to + `[5, 10)` gives a region whose valid coordinates are 5 through 9, not + re-zeroed: + + >>> view = IndexDomain.from_shape((10,)).narrow(slice(5, 10)) + >>> view.origin, view.shape + ((5,), (5,)) + >>> view.contains((5,)), view.contains((0,)) + (True, False) + """ + + inclusive_min: tuple[int, ...] + """The lower corner: each dimension's smallest literal coordinate. May be negative.""" + + exclusive_max: tuple[int, ...] + """Each dimension's upper bound, excluded: valid coordinates end at `exclusive_max - 1`.""" + + labels: tuple[str, ...] | None = None + """Optional per-dimension names; carried through the wire format, never consulted by indexing.""" + # Lazily-memoized shape. Excluded from init/repr/eq/hash: it is derived + # state, not part of the domain's identity. The domain is frozen, so the + # value is computed at most once (see `shape`). `None` is the unset + # sentinel; an empty shape caches as `()`. + _shape: tuple[int, ...] | None = field(default=None, init=False, repr=False, compare=False) + + def __post_init__(self) -> None: + if len(self.inclusive_min) != len(self.exclusive_max): + raise ValueError( + f"inclusive_min and exclusive_max must have the same length. " + f"Got {len(self.inclusive_min)} and {len(self.exclusive_max)}." + ) + for i, (lo, hi) in enumerate(zip(self.inclusive_min, self.exclusive_max, strict=True)): + if lo > hi: + raise ValueError( + f"inclusive_min must be <= exclusive_max for all dimensions. " + f"Dimension {i}: {lo} > {hi}" + ) + if self.labels is not None and len(self.labels) != len(self.inclusive_min): + raise ValueError( + f"labels must have the same length as dimensions. " + f"Got {len(self.labels)} labels for {len(self.inclusive_min)} dimensions." + ) + + @classmethod + def from_shape(cls, shape: tuple[int, ...]) -> IndexDomain: + """Create a domain with origin at zero.""" + return cls( + inclusive_min=(0,) * len(shape), + exclusive_max=shape, + ) + + @property + def ndim(self) -> int: + """Number of dimensions.""" + return len(self.inclusive_min) + + @property + def origin(self) -> tuple[int, ...]: + """The lower corner of the domain β€” an alias for `inclusive_min`, and may be negative.""" + return self.inclusive_min + + @property + def shape(self) -> tuple[int, ...]: + """Per-dimension extents: `exclusive_max - inclusive_min` for each dimension.""" + cached = self._shape + if cached is None: + cached = tuple( + hi - lo for lo, hi in zip(self.inclusive_min, self.exclusive_max, strict=True) + ) + object.__setattr__(self, "_shape", cached) + return cached + + def contains(self, index: tuple[int, ...]) -> bool: + """Whether the literal coordinate `index` lies inside this domain. + + Coordinates are literal, not NumPy-style offsets: a negative value is + the coordinate itself, valid only if the domain's bounds include it. + A tuple of the wrong length is simply not contained (returns `False`). + """ + if len(index) != self.ndim: + return False + return all( + lo <= idx < hi + for lo, hi, idx in zip(self.inclusive_min, self.exclusive_max, index, strict=True) + ) + + def contains_domain(self, other: IndexDomain) -> bool: + """Whether every coordinate of `other` lies inside this domain. + + An empty `other` within this domain's bounds is contained. A rank + mismatch returns `False` rather than raising. + """ + if other.ndim != self.ndim: + return False + return all( + self_lo <= other_lo and other_hi <= self_hi + for self_lo, self_hi, other_lo, other_hi in zip( + self.inclusive_min, + self.exclusive_max, + other.inclusive_min, + other.exclusive_max, + strict=True, + ) + ) + + def intersect(self, other: IndexDomain) -> IndexDomain | None: + """Return the overlap of this domain with `other`, or `None` if they are disjoint. + + Raises + ------ + ValueError + If the two domains have different ranks. + """ + if other.ndim != self.ndim: + raise ValueError( + f"Cannot intersect domains with different ranks: {self.ndim} vs {other.ndim}" + ) + new_min = tuple( + max(a, b) for a, b in zip(self.inclusive_min, other.inclusive_min, strict=True) + ) + new_max = tuple( + min(a, b) for a, b in zip(self.exclusive_max, other.exclusive_max, strict=True) + ) + if any(lo >= hi for lo, hi in zip(new_min, new_max, strict=True)): + return None + return IndexDomain(inclusive_min=new_min, exclusive_max=new_max) + + def translate(self, offset: tuple[int, ...]) -> IndexDomain: + """Return this domain shifted by `offset` per dimension; the shape is unchanged. + + Offsets may be negative, and the result may have a negative origin. + + Raises + ------ + ValueError + If `offset` does not have one entry per dimension. + """ + if len(offset) != self.ndim: + raise ValueError( + f"Offset must have same length as domain dimensions. " + f"Domain has {self.ndim} dimensions, offset has {len(offset)}." + ) + new_min = tuple(lo + off for lo, off in zip(self.inclusive_min, offset, strict=True)) + new_max = tuple(hi + off for hi, off in zip(self.exclusive_max, offset, strict=True)) + return IndexDomain(inclusive_min=new_min, exclusive_max=new_max) + + def narrow(self, selection: Any) -> IndexDomain: + """Apply a basic selection and return a narrowed domain. + + Indices are absolute coordinates, not NumPy-style offsets: `-3` names + the coordinate `-3`, and is out of bounds unless the domain contains it. + Integer indices produce a length-1 extent. Strided slices are not + supported β€” use `IndexTransform` for strides. + + Raises + ------ + BoundsCheckError + If a bound lies outside this domain. A slice bound used to be + clamped instead, so `narrow(slice(-3, None))` on `[0, 10)` quietly + returned the whole axis β€” reading as the NumPy spelling of "the last + three" and answering with something else β€” and `narrow(slice(20, + 30))` returned a domain its own parent did not contain. The rest of + the algebra states no clamping and no negative wrapping as an + invariant and enforces it; this is the one place that did not. + """ + normalized = _normalize_selection(selection, self.ndim) + new_inclusive_min: list[int] = [] + new_exclusive_max: list[int] = [] + for dim_idx, (sel, dim_lo, dim_hi) in enumerate( + zip(normalized, self.inclusive_min, self.exclusive_max, strict=True) + ): + if isinstance(sel, int): + if sel < dim_lo or sel >= dim_hi: + raise BoundsCheckError( + f"index {sel} is out of bounds for dimension {dim_idx} " + f"with domain [{dim_lo}, {dim_hi})" + ) + new_inclusive_min.append(sel) + new_exclusive_max.append(sel + 1) + else: + start, stop, step = sel.start, sel.stop, sel.step + if step is not None and step != 1: + raise ValueError( + "IndexDomain.narrow only supports step=1 slices. " + f"Got step={step}. Use IndexTransform for strided access." + ) + abs_start = dim_lo if start is None else start + abs_stop = dim_hi if stop is None else stop + for bound, name in ((abs_start, "start"), (abs_stop, "stop")): + if bound < dim_lo or bound > dim_hi: + raise BoundsCheckError( + f"slice {name} {bound} is out of bounds for dimension " + f"{dim_idx} with domain [{dim_lo}, {dim_hi}); indices " + f"here are absolute coordinates, so they are neither " + f"clamped to the domain nor counted from its end" + ) + # An empty interval is legal; a reversed one is the same request + # spelled backwards, and reads as empty rather than as an error. + new_inclusive_min.append(abs_start) + new_exclusive_max.append(max(abs_stop, abs_start)) + return IndexDomain( + inclusive_min=tuple(new_inclusive_min), + exclusive_max=tuple(new_exclusive_max), + ) + + # -- serialization ------------------------------------------------------ + + def to_json(self) -> IndexDomainJSON: + """Convert to the canonical ndsel JSON representation. + + Examples + -------- + >>> IndexDomain(inclusive_min=(0,), exclusive_max=(3,)).to_json() + {'input_inclusive_min': [0], 'input_exclusive_max': [3], 'input_labels': ['']} + """ + from zarr_indexing._wire import emit_labels + + return { + "input_inclusive_min": list(self.inclusive_min), + "input_exclusive_max": list(self.exclusive_max), + "input_labels": emit_labels(self.labels, self.ndim), + } + + @classmethod + def from_json(cls, data: IndexDomainJSON) -> IndexDomain: + """Construct from the canonical ndsel JSON representation. + + The document is validated by the message layer first, exactly as a + transform body is. Reading the keys directly would be a second, + undefended way into the same objects: `int(value)` alone accepts + `3.9`, `"3"` and `True`, and each of those builds a domain that is + not the document's. + + Examples + -------- + >>> domain = IndexDomain.from_json( + ... {"input_inclusive_min": [1], "input_exclusive_max": [4], "input_labels": [""]} + ... ) + >>> (domain.inclusive_min, domain.exclusive_max, domain.shape) + ((1,), (4,), (3,)) + >>> IndexDomain.from_json(domain.to_json()) == domain + True + """ + from zarr_indexing._wire import lower_bound, lower_labels + from zarr_indexing.messages import NdselError, normalize_ndsel + + # The annotation says what a well-formed caller passes; this is a parser + # of documents that arrive from elsewhere, so the shape is checked + # rather than assumed. + if not isinstance(data, dict): # pyright: ignore[reportUnnecessaryIsInstance] + raise NdselError("invalid_json", f"an index domain must be a JSON object, got {data!r}") + body = normalize_ndsel({**data, "kind": "transform"}) + return cls( + inclusive_min=tuple( + lower_bound(b, f"input_inclusive_min[{i}]") + for i, b in enumerate(body["input_inclusive_min"]) + ), + exclusive_max=tuple( + lower_bound(b, f"input_exclusive_max[{i}]") + for i, b in enumerate(body["input_exclusive_max"]) + ), + labels=lower_labels(body["input_labels"]), + ) + + +def _normalize_selection(selection: Any, ndim: int) -> tuple[int | slice, ...]: + """Normalize a basic selection to a tuple of ints/slices with length ndim.""" + if not isinstance(selection, tuple): + selection = (selection,) + result: list[int | slice] = [] + ellipsis_seen = False + for sel in selection: + if sel is Ellipsis: + if ellipsis_seen: + raise IndexError("an index can only have a single ellipsis ('...')") + ellipsis_seen = True + num_missing = ndim - (len(selection) - 1) + result.extend([slice(None)] * num_missing) + else: + result.append(sel) + while len(result) < ndim: + result.append(slice(None)) + if len(result) > ndim: + raise IndexError( + f"too many indices for array: array has {ndim} dimensions, " + f"but {len(result)} were indexed" + ) + return tuple(result) diff --git a/packages/zarr-indexing/src/zarr_indexing/errors.py b/packages/zarr-indexing/src/zarr_indexing/errors.py new file mode 100644 index 0000000000..efd3b1ecd6 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/errors.py @@ -0,0 +1,67 @@ +"""Canonical index-error types raised by the transform algebra. + +Both subclass the built-in `IndexError`, so an `except IndexError` catch site +keeps working unchanged whichever library raised. + +`zarr.errors` defines classes of the same names, and they are *not* these +objects: `zarr.errors.BoundsCheckError is BoundsCheckError` is false. Catching +zarr's around a call into this package therefore catches nothing but their +shared `IndexError` base. Import these from here. +""" + +from __future__ import annotations + +__all__ = [ + "BoundsCheckError", + "VindexInvalidSelectionError", +] + + +class VindexInvalidSelectionError(IndexError): + """A wrapper `vindex` selection contained a slice. + + Raised by `LazyArray`'s selection validation: the wrapper's vectorized + dialect accepts coordinate selections (integer arrays, with scalars and + an ellipsis) or a single boolean mask, and rejects slices with this + error. Other invalid entries raise plain `IndexError`, and the + engine-level `IndexTransform.vindex` is wider β€” it accepts residual + slice dimensions without raising. + + Examples + -------- + Raised by the wrapper, not the engine β€” a slice inside `vindex`: + + >>> import numpy as np + >>> from zarr_indexing import LazyArray + >>> view = LazyArray.from_numpy(np.arange(12).reshape(3, 4)) + >>> view.lazy.vindex[np.array([0, 2]), :] + Traceback (most recent call last): + ... + zarr_indexing.errors.VindexInvalidSelectionError: ... + """ + + +class BoundsCheckError(IndexError): + """A selection addressed coordinates outside the domain being indexed. + + Raised for out-of-domain integer indices, slice bounds, index-array + values, and points passed to `IndexTransform.apply`. Coordinates in this + algebra are literal: they are never clamped, and a negative value below + the domain's `inclusive_min` is out of bounds rather than counted from + the end. + + Examples + -------- + >>> from zarr_indexing import IndexTransform + >>> IndexTransform.from_shape((8,)).apply((9,)) + Traceback (most recent call last): + ... + zarr_indexing.errors.BoundsCheckError: ... + + A negative index is a literal coordinate, not "from the end": + + >>> IndexTransform.from_shape((8,))[-1] + Traceback (most recent call last): + ... + zarr_indexing.errors.BoundsCheckError: ... + """ diff --git a/packages/zarr-indexing/src/zarr_indexing/grid.py b/packages/zarr-indexing/src/zarr_indexing/grid.py new file mode 100644 index 0000000000..20ad3f95c2 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/grid.py @@ -0,0 +1,826 @@ +"""Compact chunk grids and the narrow planner protocol. + +``DimensionGridLike`` describes only the per-axis operations required by +``plan_chunks``. The concrete compact grids below also retain enough metadata +to describe chunk data regions and codec buffer regions without importing +Zarr's array implementation. +""" + +from __future__ import annotations + +import bisect +import itertools +import operator +from dataclasses import dataclass, field +from functools import reduce +from typing import TYPE_CHECKING, Any, Protocol, cast, runtime_checkable + +import numpy as np + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator, Sequence + + import numpy.typing as npt + + +class DimensionGridLike(Protocol): + """The per-dimension chunk-mapping surface consumed by chunk resolution. + + Examples + -------- + `EdgeDimensionGrid` provides this surface. Chunk sizes `(2, 3)` tile + source coordinates `[0, 5)`, so index 4 lands in the second chunk: + + >>> grid = EdgeDimensionGrid([2, 3]) + >>> grid.index_to_chunk(4) + 1 + >>> grid.chunk_offset(1), grid.chunk_size(1) + (2, 3) + """ + + def index_to_chunk(self, idx: int) -> int: + """Map a global source index to the index of the chunk that contains it. + + Implementers must raise `IndexError` when `idx` lies outside `[0, extent)`. + """ + ... + + def chunk_offset(self, chunk_ix: int) -> int: + """The global source coordinate at which chunk `chunk_ix` begins.""" + ... + + def chunk_size(self, chunk_ix: int) -> int: + """The declared length of chunk `chunk_ix`, i.e. its codec buffer size along this axis.""" + ... + + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: + """Vectorized `index_to_chunk`: map global source indices to chunk indices. + + Implementers must raise `IndexError` if any index lies outside `[0, extent)`. + """ + ... + + +def _bounded_indices(indices: npt.NDArray[np.intp], extent: int) -> npt.NDArray[np.intp]: + """Normalize a vector lookup and enforce the scalar grid bounds.""" + arr = np.asarray(indices, dtype=np.intp) + if arr.size > 0 and (int(arr.min()) < 0 or int(arr.max()) >= extent): + raise IndexError( + f"indices must lie in [0, {extent}); got [{int(arr.min())}, {int(arr.max())}]" + ) + return arr + + +@dataclass(frozen=True) +class FixedDimension: + """Uniform chunk size with a boundary chunk clipped to the axis extent. + + Examples + -------- + Chunks of size 3 on an axis of extent 10 give 4 chunks. The last chunk + still declares a codec buffer of 3 but holds only 1 valid element: + + >>> dim = FixedDimension(size=3, extent=10) + >>> dim.nchunks + 4 + >>> dim.index_to_chunk(7) + 2 + >>> dim.chunk_size(3), dim.data_size(3) + (3, 1) + """ + + size: int + """The declared chunk length along this axis; every chunk's codec buffer size.""" + + extent: int + """The axis length in global source coordinates.""" + + nchunks: int = field(init=False, repr=False) + """Derived: the number of chunks holding data within `extent`.""" + + ngridcells: int = field(init=False, repr=False) + """Derived: the number of declared grid cells; equals `nchunks` for a fixed dimension.""" + + def __post_init__(self) -> None: + if self.size < 0: + raise ValueError(f"FixedDimension size must be >= 0, got {self.size}") + if self.extent < 0: + raise ValueError(f"FixedDimension extent must be >= 0, got {self.extent}") + if self.size == 0 and self.extent > 0: + raise ValueError( + "FixedDimension size must be > 0 when extent is nonzero; " + f"got size {self.size} and extent {self.extent}" + ) + nchunks = 0 if self.size == 0 else (self.extent + self.size - 1) // self.size + object.__setattr__(self, "nchunks", nchunks) + object.__setattr__(self, "ngridcells", nchunks) + + def index_to_chunk(self, idx: int) -> int: + """Map a global source index to its chunk index (`idx // size`). + + Raises `IndexError` when `idx` lies outside `[0, extent)`. + """ + if idx < 0 or idx >= self.extent: + raise IndexError(f"index {idx} is out of bounds for extent {self.extent}") + return 0 if self.size == 0 else idx // self.size + + def chunk_offset(self, chunk_ix: int) -> int: + """The global source coordinate where chunk `chunk_ix` begins (`chunk_ix * size`). + + Not bounds-checked: chunk indices past the last chunk extrapolate linearly. + """ + return chunk_ix * self.size + + def chunk_size(self, chunk_ix: int) -> int: + """The declared chunk length, `size` for every chunk. + + The boundary chunk is not clipped here; use `data_size` for the valid data length. + """ + return self.size + + def data_size(self, chunk_ix: int) -> int: + """The number of valid data elements in chunk `chunk_ix`, clipped to `extent`. + + Interior chunks report `size`; the boundary chunk reports the remainder, and chunk + indices at or past `nchunks` report 0. + """ + if self.size == 0: + return 0 + return max(0, min(self.size, self.extent - chunk_ix * self.size)) + + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: + """Vectorized `index_to_chunk` over an array of global source indices. + + Raises `IndexError` if any index lies outside `[0, extent)`. + """ + arr = _bounded_indices(indices, self.extent) + if self.size == 0: + return np.zeros_like(arr) + return arr // self.size + + def with_extent(self, new_extent: int) -> FixedDimension: + """Return a copy with the same chunk size and the axis extent set to `new_extent`.""" + return FixedDimension(size=self.size, extent=new_extent) + + def resize(self, new_extent: int) -> FixedDimension: + """Return a copy resized to `new_extent`; the fixed chunk size covers any new extent.""" + return FixedDimension(size=self.size, extent=new_extent) + + @property + def size_repr(self) -> str: + """The chunk size rendered as a scalar for `ChunkGrid.__repr__`.""" + return str(self.size) + + +@dataclass(frozen=True, init=False) +class VaryingDimension: + """Explicit chunk edge lengths, with trailing data clipped to ``extent``. + + Examples + -------- + Edges `(2, 3, 5)` clipped to extent 9: the last chunk declares 5 but + holds only 4 valid elements, and index 4 lands in the second chunk: + + >>> dim = VaryingDimension(edges=(2, 3, 5), extent=9) + >>> dim.nchunks + 3 + >>> dim.index_to_chunk(4) + 1 + >>> dim.chunk_offset(2) + 5 + >>> dim.chunk_size(2), dim.data_size(2) + (5, 4) + """ + + edges: tuple[int, ...] + """The declared per-chunk edge lengths, in order; codec buffer sizes, unclipped.""" + + cumulative: tuple[int, ...] + """Prefix sums of `edges`; derived, and what index lookups binary-search.""" + + extent: int + """The axis length in global source coordinates; at most the sum of `edges`.""" + nchunks: int = field(init=False, repr=False) + """Derived: the number of chunks holding data within `extent`.""" + + ngridcells: int = field(init=False, repr=False) + """Derived: the number of declared edges; exceeds `nchunks` when trailing cells are empty.""" + + def __init__(self, edges: Sequence[int], extent: int) -> None: + edges_tuple = tuple(edges) + if not edges_tuple: + raise ValueError("VaryingDimension edges must not be empty") + if any(edge <= 0 for edge in edges_tuple): + raise ValueError(f"All edge lengths must be > 0, got {edges_tuple}") + cumulative = tuple(itertools.accumulate(edges_tuple)) + if extent < 0: + raise ValueError(f"VaryingDimension extent must be >= 0, got {extent}") + if extent > cumulative[-1]: + raise ValueError( + f"VaryingDimension extent {extent} exceeds sum of edges {cumulative[-1]}" + ) + object.__setattr__(self, "edges", edges_tuple) + object.__setattr__(self, "cumulative", cumulative) + object.__setattr__(self, "extent", extent) + nchunks = 0 if extent == 0 else bisect.bisect_left(cumulative, extent) + 1 + object.__setattr__(self, "nchunks", nchunks) + object.__setattr__(self, "ngridcells", len(edges_tuple)) + + def index_to_chunk(self, idx: int) -> int: + """Map a global source index to the chunk whose edge interval contains it. + + Raises `IndexError` when `idx` lies outside `[0, extent)`. + """ + if idx < 0 or idx >= self.extent: + raise IndexError(f"index {idx} is out of bounds for extent {self.extent}") + return bisect.bisect_right(self.cumulative, idx) + + def chunk_offset(self, chunk_ix: int) -> int: + """The global source coordinate where chunk `chunk_ix` begins (sum of prior edges).""" + return self.cumulative[chunk_ix - 1] if chunk_ix > 0 else 0 + + def chunk_size(self, chunk_ix: int) -> int: + """The declared edge length of chunk `chunk_ix`. + + Trailing chunks are not clipped to `extent` here; use `data_size` for that. + """ + return self.edges[chunk_ix] + + def data_size(self, chunk_ix: int) -> int: + """The number of valid data elements in chunk `chunk_ix`, clipped to `extent`. + + Grid cells that lie entirely at or past `extent` report 0. + """ + offset = self.chunk_offset(chunk_ix) + return max(0, min(self.edges[chunk_ix], self.extent - offset)) + + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: + """Vectorized `index_to_chunk` over an array of global source indices. + + Raises `IndexError` if any index lies outside `[0, extent)`. + """ + arr = _bounded_indices(indices, self.extent) + return np.searchsorted(self.cumulative, arr, side="right") + + def with_extent(self, new_extent: int) -> VaryingDimension: + """Return a copy with the same edges re-clipped to `new_extent`. + + The existing edges must already cover the new extent; raises `ValueError` when + `new_extent` exceeds the sum of edges. Use `resize` to grow past the edges. + """ + if self.cumulative[-1] < new_extent: + raise ValueError( + f"VaryingDimension edge sum {self.cumulative[-1]} is less than new extent " + f"{new_extent}" + ) + return VaryingDimension(self.edges, extent=new_extent) + + def resize(self, new_extent: int) -> VaryingDimension: + """Return a copy resized to `new_extent`. + + Shrinking (or growing within the existing edges) keeps the edges and re-clips them; + growing past the sum of edges appends one new trailing edge covering the remainder. + """ + if new_extent == self.extent: + return self + if new_extent > self.cumulative[-1]: + return VaryingDimension((*self.edges, new_extent - self.cumulative[-1]), new_extent) + return VaryingDimension(self.edges, extent=new_extent) + + @property + def size_repr(self) -> str: + """The edge lengths rendered as a tuple for `ChunkGrid.__repr__`.""" + return repr(self.edges) + + +@runtime_checkable +class DimensionGrid(Protocol): + """Structural interface shared by the compact dimension grids. + + Examples + -------- + `FixedDimension` satisfies the protocol structurally: + + >>> dim = FixedDimension(size=2, extent=5) + >>> isinstance(dim, DimensionGrid) + True + >>> dim.nchunks, dim.extent + (3, 5) + >>> dim.with_extent(4).nchunks + 2 + """ + + @property + def nchunks(self) -> int: + """The number of chunks holding data within `extent`.""" + ... + + @property + def ngridcells(self) -> int: + """The number of declared grid cells; may exceed `nchunks` when trailing cells are empty.""" + ... + + @property + def extent(self) -> int: + """The axis length in global source coordinates.""" + ... + + def index_to_chunk(self, idx: int) -> int: + """Map a global source index to the chunk index that contains it. + + Implementers must raise `IndexError` when `idx` lies outside `[0, extent)`. + """ + ... + + def chunk_offset(self, chunk_ix: int) -> int: + """The global source coordinate at which chunk `chunk_ix` begins.""" + ... + + def chunk_size(self, chunk_ix: int) -> int: + """The declared (codec buffer) length of chunk `chunk_ix`, never clipped to `extent`.""" + ... + + def data_size(self, chunk_ix: int) -> int: + """The valid data length of chunk `chunk_ix`, clipped to `extent` at the boundary.""" + ... + + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: + """Vectorized `index_to_chunk`; must raise `IndexError` for indices outside `[0, extent)`.""" + ... + + def with_extent(self, new_extent: int) -> DimensionGrid: + """Return a grid with the existing chunk layout re-clipped to `new_extent`. + + Implementers must not invent new grid cells: raise `ValueError` when the declared + layout cannot cover `new_extent`. + """ + ... + + def resize(self, new_extent: int) -> DimensionGrid: + """Return a grid covering `new_extent`, extending the chunk layout when it must grow.""" + ... + + @property + def size_repr(self) -> str: + """A compact rendering of the chunk sizes, used by `ChunkGrid.__repr__`.""" + ... + + +@dataclass(frozen=True) +class ChunkSpec: + """A chunk's valid data region and its full codec buffer shape. + + Examples + -------- + The last chunk of a size-10 axis chunked by 3 holds one valid element + (`slices`), while its codec buffer still spans 3: + + >>> spec = ChunkGrid.from_sizes((10,), (3,))[3] + >>> spec.slices + (slice(9, 10, 1),) + >>> spec.shape, spec.codec_shape + ((1,), (3,)) + >>> spec.is_boundary + True + """ + + slices: tuple[slice, ...] + """Per-dimension bounds of the valid data region, in global source coordinates.""" + + codec_shape: tuple[int, ...] + """The declared (codec buffer) chunk shape, unclipped by the array extent.""" + + @property + def shape(self) -> tuple[int, ...]: + """The shape of the valid data region described by `slices`. + + Smaller than `codec_shape` on boundary chunks, where the array extent clips the chunk. + """ + return tuple(chunk_slice.stop - chunk_slice.start for chunk_slice in self.slices) + + @property + def is_boundary(self) -> bool: + """Whether the valid data region is smaller than the full codec buffer on any axis.""" + return self.shape != self.codec_shape + + +@dataclass(frozen=True) +class ChunkGrid: + """A concrete regular or rectilinear arrangement of chunks for one array. + + Examples + -------- + A `(3, 4)` array with `(2, 2)` chunks has a `(2, 2)` grid whose bottom + row of chunks is clipped to one valid row of data: + + >>> grid = ChunkGrid.from_sizes((3, 4), (2, 2)) + >>> grid.grid_shape + (2, 2) + >>> grid.chunk_sizes + ((2, 1), (2, 2)) + >>> spec = grid[1, 0] + >>> spec.shape, spec.codec_shape, spec.is_boundary + ((1, 2), (2, 2), True) + """ + + dimensions: tuple[DimensionGrid, ...] + """One per-axis grid, each mapping that axis's source indices to chunks.""" + + _is_regular: bool = field(init=False, repr=False) + + def __post_init__(self) -> None: + object.__setattr__( + self, + "_is_regular", + all(isinstance(dimension, FixedDimension) for dimension in self.dimensions), + ) + + def __repr__(self) -> str: + sizes = ", ".join(dimension.size_repr for dimension in self.dimensions) + shape = tuple(dimension.extent for dimension in self.dimensions) + return f"ChunkGrid(chunk_sizes=({sizes}), array_shape={shape})" + + @classmethod + def from_sizes( + cls, array_shape: Sequence[int], chunk_sizes: Sequence[int | Sequence[int]] + ) -> ChunkGrid: + """Build a grid from an array shape and one chunk-size spec per dimension. + + An `int` entry gives a fixed chunk size along that axis; a sequence of ints gives + explicit per-chunk edge lengths. A uniform sequence consistent with the axis extent + collapses to a fixed dimension, so the result may report `is_regular`. + + Parameters + ---------- + array_shape : Sequence[int] + The array extent along each dimension, in global source coordinates. + chunk_sizes : Sequence[int | Sequence[int]] + Per-dimension chunk layout: a single size or explicit edge lengths. + """ + extents = _shape_tuple(array_shape) + if len(extents) != len(chunk_sizes): + raise ValueError( + f"array_shape has {len(extents)} dimensions but chunk_sizes has " + f"{len(chunk_sizes)} dimensions" + ) + dimensions: list[DimensionGrid] = [] + for dimension_spec, extent in zip(chunk_sizes, extents, strict=True): + if isinstance(dimension_spec, int): + dimensions.append(FixedDimension(size=dimension_spec, extent=extent)) + else: + edges = tuple(dimension_spec) + if not edges: + raise ValueError("Each dimension must have at least one chunk") + if ( + edges[0] > 0 + and all(edge == edges[0] for edge in edges) + and (extent == sum(edges) or len(edges) == (extent + edges[0] - 1) // edges[0]) + ): + dimensions.append(FixedDimension(size=edges[0], extent=extent)) + else: + dimensions.append(VaryingDimension(edges, extent=extent)) + return cls(dimensions=tuple(dimensions)) + + @property + def ndim(self) -> int: + """The number of dimensions.""" + return len(self.dimensions) + + @property + def is_regular(self) -> bool: + """Whether every dimension uses a single fixed chunk size. + + False when any axis carries explicit (rectilinear) per-chunk edge lengths. + """ + return self._is_regular + + @property + def grid_shape(self) -> tuple[int, ...]: + """The number of data-bearing chunks along each dimension.""" + return tuple(dimension.nchunks for dimension in self.dimensions) + + @property + def chunk_shape(self) -> tuple[int, ...]: + """The uniform declared chunk shape of a regular grid. + + Raises `ValueError` for rectilinear grids, which have no single chunk shape; + use `grid[coords]` for per-chunk sizes instead. + """ + if not self.is_regular: + raise ValueError( + "chunk_shape is only available for regular chunk grids. " + "Use grid[coords] for per-chunk sizes." + ) + return tuple( + dimension.size for dimension in self.dimensions if isinstance(dimension, FixedDimension) + ) + + @property + def chunk_sizes(self) -> tuple[tuple[int, ...], ...]: + """Per-dimension tuples of each chunk's valid data length. + + Boundary chunks report their clipped extent, not the declared codec size. + """ + return tuple( + tuple(dimension.data_size(index) for index in range(dimension.nchunks)) + for dimension in self.dimensions + ) + + def __getitem__(self, coords: int | tuple[int, ...]) -> ChunkSpec | None: + """Look up the `ChunkSpec` at the given chunk coordinates (grid cells, not indices). + + Returns `None` when any coordinate falls outside the grid; raises `ValueError` + when the number of coordinates does not match `ndim`. The spec's slices are in + global source coordinates. + """ + if isinstance(coords, int): + coords = (coords,) + if len(coords) != self.ndim: + raise ValueError( + f"Expected {self.ndim} coordinate(s) for a {self.ndim}-d chunk grid, " + f"got {len(coords)}." + ) + slices: list[slice] = [] + codec_shape: list[int] = [] + for dimension, index in zip(self.dimensions, coords, strict=True): + if index < 0 or index >= dimension.nchunks: + return None + offset = dimension.chunk_offset(index) + slices.append(slice(offset, offset + dimension.data_size(index), 1)) + codec_shape.append(dimension.chunk_size(index)) + return ChunkSpec(tuple(slices), tuple(codec_shape)) + + def __iter__(self) -> Iterator[ChunkSpec]: + """Yield a `ChunkSpec` for every data-bearing chunk in row-major (C) order.""" + for coords in itertools.product( + *(range(dimension.nchunks) for dimension in self.dimensions) + ): + spec = self[coords] + if spec is not None: + yield spec + + def all_chunk_coords( + self, + *, + origin: Sequence[int] | None = None, + selection_shape: Sequence[int] | None = None, + ) -> Iterator[tuple[int, ...]]: + """Iterate chunk coordinates over a rectangular grid region in row-major (C) order. + + `origin` defaults to the grid origin and `selection_shape` to the rest of the grid. + The region is not bounds-checked: an oversized region yields coordinates outside + the grid, which `__getitem__` resolves to `None`. + """ + origin_parsed = (0,) * self.ndim if origin is None else tuple(origin) + selection_shape_parsed = ( + tuple( + grid_size - coordinate + for coordinate, grid_size in zip(origin_parsed, self.grid_shape, strict=True) + ) + if selection_shape is None + else tuple(selection_shape) + ) + return itertools.product( + *( + range(coordinate, coordinate + size) + for coordinate, size in zip(origin_parsed, selection_shape_parsed, strict=True) + ) + ) + + def iter_chunk_regions( + self, + *, + origin: Sequence[int] | None = None, + selection_shape: Sequence[int] | None = None, + ) -> Iterator[tuple[slice, ...]]: + """Yield each chunk's valid-data slices, in global source coordinates. + + Covers the same region as `all_chunk_coords`, silently skipping coordinates + that fall outside the grid. + """ + for coords in self.all_chunk_coords(origin=origin, selection_shape=selection_shape): + spec = self[coords] + if spec is not None: + yield spec.slices + + def get_nchunks(self) -> int: + """The total number of data-bearing chunks: the product of `grid_shape` (1 if 0-d).""" + return reduce(operator.mul, (dimension.nchunks for dimension in self.dimensions), 1) + + def update_shape(self, new_shape: tuple[int, ...]) -> ChunkGrid: + """Return a grid resized to `new_shape` by resizing each dimension. + + Fixed axes keep their chunk size; rectilinear axes gain one trailing edge when + grown past their declared edges. Raises `ValueError` when `new_shape` does not + have `ndim` entries. + """ + if len(new_shape) != self.ndim: + raise ValueError( + f"new_shape has {len(new_shape)} dimensions but chunk grid has {self.ndim} dimensions" + ) + return ChunkGrid( + dimensions=tuple( + dimension.resize(new_extent) + for dimension, new_extent in zip(self.dimensions, new_shape, strict=True) + ) + ) + + +class EdgeDimensionGrid: + """An explicitly edge-based grid for coordinate-origin examples and planners. + + Examples + -------- + Chunk sizes `(2, 3)` tile source coordinates `[0, 5)`; lookups outside + that range raise: + + >>> grid = EdgeDimensionGrid([2, 3]) + >>> grid.num_chunks, grid.extent + (2, 5) + >>> grid.index_to_chunk(2) + 1 + >>> grid.index_to_chunk(5) + Traceback (most recent call last): + ... + IndexError: index 5 is out of bounds for an axis of extent 5 + """ + + __slots__ = ("_offsets", "sizes") + + sizes: tuple[int, ...] + """The length of each chunk along the axis, in order; every entry is positive.""" + + def __init__(self, sizes: Sequence[int]) -> None: + """Build a one-axis grid from explicit per-chunk sizes. + + Every size must be positive; raises `ValueError` otherwise. A zero-length axis + is spelled as an empty sequence (no chunks), not as a zero size. + + Parameters + ---------- + sizes : Sequence[int] + The length of each chunk along the axis, in order. + """ + normalized = tuple(int(size) for size in sizes) + for index, size in enumerate(normalized): + if size <= 0: + raise ValueError( + f"chunk sizes must be positive; got {size} at position {index} of {normalized}. " + "A zero-length axis is spelled as no chunks at all: EdgeDimensionGrid(())" + ) + self.sizes = normalized + offsets: np.ndarray[Any, np.dtype[np.intp]] = np.zeros(len(normalized) + 1, dtype=np.intp) + if normalized: + np.cumsum(np.asarray(normalized, dtype=np.intp), out=offsets[1:]) + self._offsets = offsets + + @property + def num_chunks(self) -> int: + """The number of chunks along the axis.""" + return len(self.sizes) + + @property + def extent(self) -> int: + """The axis length in global source coordinates: the sum of all chunk sizes.""" + return int(self._offsets[-1]) + + def __repr__(self) -> str: + return f"EdgeDimensionGrid(sizes={self.sizes})" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, EdgeDimensionGrid): + return NotImplemented + return self.sizes == other.sizes + + def __hash__(self) -> int: + return hash((type(self).__name__, self.sizes)) + + def index_to_chunk(self, idx: int) -> int: + """Map a global source index to the chunk whose interval contains it. + + Raises `IndexError` when `idx` lies outside `[0, extent)`. + """ + if idx < 0 or idx >= self.extent: + raise IndexError(f"index {idx} is out of bounds for an axis of extent {self.extent}") + return int(np.searchsorted(self._offsets, idx, side="right")) - 1 + + def chunk_offset(self, chunk_ix: int) -> int: + """The global source coordinate where chunk `chunk_ix` begins. + + Raises `IndexError` when `chunk_ix` lies outside `[0, num_chunks)`. + """ + if chunk_ix < 0 or chunk_ix >= len(self.sizes): + raise IndexError( + f"chunk index {chunk_ix} is out of bounds for {len(self.sizes)} chunks" + ) + return int(self._offsets[chunk_ix]) + + def chunk_size(self, chunk_ix: int) -> int: + """The length of chunk `chunk_ix`; every chunk holds data, so no boundary clipping applies. + + Raises `IndexError` when `chunk_ix` lies outside `[0, num_chunks)`. + """ + if chunk_ix < 0 or chunk_ix >= len(self.sizes): + raise IndexError( + f"chunk index {chunk_ix} is out of bounds for {len(self.sizes)} chunks" + ) + return self.sizes[chunk_ix] + + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: + """Vectorized `index_to_chunk` over an array of global source indices. + + Raises `IndexError` if any index lies outside `[0, extent)`. + """ + arr = _bounded_indices(indices, self.extent) + return (np.searchsorted(self._offsets, arr, side="right") - 1).astype(np.intp) + + +def _shape_tuple(shape: Sequence[int]) -> tuple[int, ...]: + result = tuple(int(size) for size in shape) + if any(size < 0 for size in result): + raise ValueError(f"shape entries must be non-negative; got {result}") + return result + + +def _entry_kind(entry: Any) -> str: + if isinstance(entry, (int, np.integer)) and not isinstance(entry, bool): + return "int" + if isinstance(entry, (str, bytes)): + return "neither" + try: + iter(cast("Iterable[Any]", entry)) + except TypeError: + return "neither" + return "sequence" + + +def dimension_grids_from_chunks( + chunks: Sequence[int] | Sequence[Sequence[int]], shape: Sequence[int] +) -> tuple[DimensionGrid, ...]: + """Build compact dimensions from regular sizes or explicit per-axis edges. + + Examples + -------- + One integer per dimension builds fixed grids, ready for `plan_chunks`: + + >>> from zarr_indexing import IndexTransform, plan_chunks + >>> grids = dimension_grids_from_chunks((2, 2), shape=(3, 4)) + >>> [type(grid).__name__ for grid in grids] + ['FixedDimension', 'FixedDimension'] + >>> plan = plan_chunks(IndexTransform.from_shape((3, 4))[1, :], grids) + >>> [p.chunk_coords for p in plan] + [(0, 0), (0, 1)] + """ + shape_t = _shape_tuple(shape) + entries: tuple[Any, ...] = tuple(chunks) + if len(entries) != len(shape_t): + raise ValueError( + f"chunks must have one entry per dimension; got {len(entries)} entries for shape {shape_t}" + ) + + conventions = ( + "chunks must be either a uniform chunk shape (one integer per dimension) " + "or per-axis chunk sizes (one sequence of integers per dimension)" + ) + kinds = [_entry_kind(entry) for entry in entries] + neither = [(axis, entries[axis]) for axis, kind in enumerate(kinds) if kind == "neither"] + if neither: + described = ", ".join(f"{entry!r} at dimension {axis}" for axis, entry in neither) + verb = "is" if len(neither) == 1 else "are" + raise ValueError(f"{conventions}; {described} {verb} neither") + + integer_count = sum(kind == "int" for kind in kinds) + if entries and integer_count == len(entries): + dimensions: list[DimensionGrid] = [] + for entry, extent in zip(entries, shape_t, strict=True): + size = int(entry) + if size <= 0: + raise ValueError(f"chunk shape entries must be positive; got {size}") + dimensions.append(FixedDimension(size=size, extent=extent)) + return tuple(dimensions) + if integer_count: + raise ValueError(f"{conventions}, not a mixture; got {entries!r}") + + dimensions = [] + for axis, (entry, extent) in enumerate(zip(entries, shape_t, strict=True)): + elements: tuple[Any, ...] = tuple(cast("Iterable[Any]", entry)) + if any( + not isinstance(element, (int, np.integer)) or isinstance(element, bool) + for element in elements + ): + raise ValueError( + f"per-axis chunk sizes must be integers; dimension {axis} has {entry!r}" + ) + edges = tuple(int(element) for element in elements) + total = sum(edges) + if total != extent: + raise ValueError( + f"per-axis chunk sizes for dimension {axis} sum to {total}, but the array extent is {extent}" + ) + if extent == 0 and all(edge == 0 for edge in edges): + dimensions.append(FixedDimension(size=0, extent=0)) + continue + if any(edge <= 0 for edge in edges): + raise ValueError(f"chunk sizes must be positive; got {edges}") + dimensions.append(VaryingDimension(edges=edges, extent=extent)) + return tuple(dimensions) diff --git a/packages/zarr-indexing/src/zarr_indexing/json.py b/packages/zarr-indexing/src/zarr_indexing/json.py new file mode 100644 index 0000000000..8bf42c74a5 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/json.py @@ -0,0 +1,166 @@ +"""The canonical ndsel wire vocabulary, and the rules for lowering it. + +This is the **engine layer**. Where `messages.py` is pure JSONβ†’JSON and imposes +no array constraints, this module holds the JSON shapes a canonical ndsel body +takes (spec section 4.3, as produced by `zarr_indexing.messages.normalize_ndsel`) +together with the lowering rules that turn one into the numpy-backed engine +representation. + +The conversions themselves are **methods on the types**, since each type owns +its one serialization: `IndexTransform.to_json` / `from_json`, +`IndexDomain.to_json` / `from_json`, and `to_json` on each output map kind, +with `output_index_map_from_json` in `zarr_indexing.output_map` dispatching the +wire's tagged union back to the right kind. This module is what they share. + +Three engine constraints live **here and only here**: + +- **Finite bounds.** An `IndexDomain` addresses a finite array, so a canonical + body carrying a `"-inf"`/`"+inf"` bound cannot be lowered; `from_json` raises. +- **Implicit bounds lower by value.** The `[n]`-bracket implicit/explicit flag + is a message-layer concern; the engine keeps only the integer value. +- **Integer `index_array` content.** The message layer carries `index_array` + verbatim (the spec defers its shape and type), so lowering is where a float, + boolean or string array is rejected β€” as an `NdselError`, rather than + truncating `[0.9, 1.9]` to cells 0 and 1 or leaking a raw NumPy error. + +## The `index_array` wire format (and the degenerate-collapse it documents) + +ndsel and TensorStore both **reject** an output map that carries *both* +`input_dimension` and `index_array`; `input_dimension` belongs to affine +(`single_input_dimension`) maps. The in-memory `ArrayMap` matches: what a map +depends on is read from its full-rank array's shape (its non-singleton axes), +so there is nothing to reconstruct on load. On serialize (`to_json`): + +1. An all-singleton `index_array` (size 1) selects a single coordinate + regardless of input, so it is **collapsed to a `constant` map** + `{offset: offset + stride*value}`. The size-1 input dimension stays in the + domain, unconsumed β€” a valid transform. The selection layer already builds + such maps as `ConstantMap` (`output_map.array_map_or_constant`); this covers + hand-built transforms. +2. An **empty** `index_array` (size 0) collapses the same way, to + `{offset: 0}`. It names no cell, and it can only be empty because an input + dimension is β€” the full-rank invariant makes every axis either 1 or the + domain's extent β€” so nothing is ever read through it and the emptiness is + carried by the domain, which is emitted separately. TensorStore does the + same: `t[ts.d[0][[]]]` is `out[0] = 0`, emitted as `{}`. Emitting the array + instead would produce a document neither implementation could load, because + `ndarray.tolist()` renders every empty array as `[]` once the leading axis + is the zero-length one, and nested lists cannot spell the shape back β€” + `[[]]` is `(1, 0)` and nothing spells `(0, 1)`. +3. Non-degenerate `index_array` maps are emitted with their array and bounds + only. + +""" + +from __future__ import annotations + +from typing import Any, Required, TypedDict + +# --------------------------------------------------------------------------- +# TypedDict definitions (canonical JSON shapes) +# --------------------------------------------------------------------------- + +# An `index_array` serializes via `ndarray.tolist()`, so it is a nested list of +# ints whose nesting depth equals the array rank. +NestedIntList = list[Any] + +# A canonical *lowered* body carries only finite integer bounds, but the JSON +# shape admits the full ndsel `bound` grammar: an explicit int / sentinel, or a +# one-element implicit `[value]` array. +IndexValueJSON = int | str +BoundJSON = int | str | list[IndexValueJSON] + + +class IndexDomainJSON(TypedDict, total=False): + """Canonical JSON representation of an IndexDomain. + + Examples + -------- + >>> doc: IndexDomainJSON = { + ... "input_inclusive_min": [0], + ... "input_exclusive_max": [4], + ... "input_labels": ["x"], + ... } + >>> from zarr_indexing import IndexDomain + >>> IndexDomain.from_json(doc).shape + (4,) + """ + + input_inclusive_min: Required[list[BoundJSON]] + """Per-dimension lower bounds; `"-inf"` is legal on the wire but cannot be lowered.""" + + input_exclusive_max: Required[list[BoundJSON]] + """Per-dimension exclusive upper bounds; `"+inf"` is legal on the wire but cannot be lowered.""" + + input_labels: Required[list[str]] + """Per-dimension names; the empty string marks an unlabeled dimension.""" + + +class OutputIndexMapJSON(TypedDict, total=False): + """Canonical JSON representation of a single output index map. + + Exactly one of three forms (distinguished by which fields are present): + + - `{"offset": 5}` β€” constant + - `{"offset": 0, "stride": 1, "input_dimension": 0}` β€” single_input_dimension + - `{"offset": 0, "stride": 1, "index_array": [...], + "index_array_bounds": ["-inf", "+inf"]}` β€” index_array + + Examples + -------- + >>> from zarr_indexing import output_index_map_from_json + >>> constant: OutputIndexMapJSON = {"offset": 5} + >>> output_index_map_from_json(constant) + ConstantMap(offset=5) + >>> affine: OutputIndexMapJSON = {"offset": 0, "stride": 2, "input_dimension": 1} + >>> output_index_map_from_json(affine) + DimensionMap(input_dimension=1, offset=0, stride=2) + """ + + offset: int + """Constant term; alone it is the whole constant form.""" + + stride: int + """Multiplier applied to the input coordinate or to each `index_array` value.""" + + input_dimension: int + """The input dimension the single_input_dimension form reads.""" + + index_array: NestedIntList + """Nested lists of output coordinates, one nesting level per input dimension.""" + + index_array_bounds: list[IndexValueJSON] + """Bounds the `index_array` values are promised to lie in; `["-inf", "+inf"]` if unconstrained.""" + + +class IndexTransformJSON(TypedDict, total=False): + """Canonical JSON representation of an IndexTransform (spec section 4.3). + + Examples + -------- + >>> doc: IndexTransformJSON = { + ... "input_rank": 1, + ... "input_inclusive_min": [0], + ... "input_exclusive_max": [2], + ... "input_labels": [""], + ... "output": [{"offset": 1, "stride": 2, "input_dimension": 0}], + ... } + >>> from zarr_indexing import IndexTransform + >>> IndexTransform.from_json(doc).domain.shape + (2,) + """ + + input_rank: Required[int] + """The number of input dimensions; the bounds and labels lists match it in length.""" + + input_inclusive_min: Required[list[BoundJSON]] + """Per-dimension lower bounds; `"-inf"` is legal on the wire but cannot be lowered.""" + + input_exclusive_max: Required[list[BoundJSON]] + """Per-dimension exclusive upper bounds; `"+inf"` is legal on the wire but cannot be lowered.""" + + input_labels: Required[list[str]] + """Per-dimension names; the empty string marks an unlabeled dimension.""" + + output: Required[list[OutputIndexMapJSON]] + """One output map per output dimension.""" diff --git a/packages/zarr-indexing/src/zarr_indexing/lazy_array.py b/packages/zarr-indexing/src/zarr_indexing/lazy_array.py new file mode 100644 index 0000000000..950a97b25e --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/lazy_array.py @@ -0,0 +1,1365 @@ +"""`LazyArray` β€” TensorStore-style lazy indexing over array-like sources. + +`LazyArray` wraps a source with `shape`, `dtype`, and basic integer/slice +`__getitem__`, whose reads can be lowered through NumPy system memory. It adds +a `.lazy` accessor whose indexing operations build up an +[`IndexTransform`](transform.md) instead of reading data: + +```python +view = LazyArray(source).lazy[10:50, ::2].lazy.oindex[[3, 1, 1], :] +view.shape # known without touching the data +values = view.result() +``` + +Nothing is read until `result()` (or `__array__`, or an eager `__getitem__`). +Every `.lazy` operation is metadata-only. Composition does not accumulate +layers: a view of a view is still a single transform and retains its reader. + +Parts +----- +A `LazyArray` carries a **partitioning** of the array it wraps: a grid of boxes +that a read is broken into. `parts()` walks those boxes as they fall through the +view, yielding a [`Partition`](#zarr_indexing.lazy_array.Partition) per box. Its +paired projection describes the chunk-local read and where its cells land in the +request; `view` carries that partition's transform. `result()` allocates one +fresh output buffer, then reads each partition once through the selected reader +into the final buffer or an owned temporary for fancy placement. + +The part view's transform directly addresses its raw wrapped array. The paired +projection deliberately retains the chunk-local frame; both travel together in +the `ReadContext` passed to the reader. + +The partitioning is discovered from the wrapped array at construction β€” first +`read_chunk_sizes` (zarr's clipped per-axis sizes, sharding-aware), then +`chunks`, read as per-axis sizes if its entries are sequences and as a uniform +box shape if they are integers. Those attribute names belong to the wrapped +array; this API refers only to parts. An array that advertises neither gets a +single whole-array part, and resolving it reads the whole view through its +selected reader in one pass. + +`with_parts` replaces the partitioning without touching the data or the view: + +```python +view.with_parts((64, 64)) # uniform boxes, tail clipped +view.with_parts_per_axis(((3, 3, 1),)) # explicit per-axis sizes +view.unpartitioned() # one whole-array part; resolve in one shot +``` + +Repartitioning changes how the read is divided, not what `result()` returns. +Parts that do not align with the source's own boxes are permitted and can be +useful (to bound peak memory, or to batch small reads); they cost extra I/O but +do not affect correctness. + +Readers +------- +Every wrapper carries a reader that owns the backend-specific request. The +transform answers **which values?** and is independent of the backend; the +reader answers **how does this backend obtain them?** and must preserve the +complete transform exactly. Readers do not define indexing semantics, +partitioning, scheduling, or result ownership. The conservative +`LazyArray(source)` uses `basic_reader`, which needs only basic slicing. +`LazyArray.from_numpy(array)` explicitly opts into `numpy_reader` for direct +NumPy indexing. `with_reader()` replaces the reader without reading or changing +the view metadata. The reader object is shared by all derived views and their +parts. Consumers may materialize part views concurrently; `LazyArray` does not +serialize calls, so a stateful reader must synchronize its own mutable state. + +Both built-in readers lower through NumPy system memory. They do not implicitly +transfer device arrays. A device source requires an explicit custom reader that +performs any needed transfer into the supplied system-memory output buffer. + +Boxes and queries +----------------- +A selection is either **rectangular** β€” an interval and a stride per dimension, +which is what basic indexing composes to at any depth β€” or a **query**, an +explicit list of coordinates, which is what `oindex`, `vindex`, and masks +produce and which subsequent basic indexing cannot undo. `is_box` reports the +category and `bounding_box()` reports the storage region touched: the exact +interval per dimension for a box, a hull for a query. A box is only *dense* in +that interval when every entry of `strides()` is 1. The distinction is +structural rather than an optimization; [the design +notes](../design-notes.md) describe why it matters to consumers of a selection. + +The positional dialect +---------------------- +Selections on `LazyArray` are **positional, NumPy-style**: index 0 is the first +element of the current view, `-1` is the last, boolean masks must match the +view's shape, and every index is bounds-checked against the view. + +This differs deliberately from `zarr.Array.lazy[...]`, which exposes the +**literal** TensorStore dialect: a zarr view keeps the coordinate system of the +array it came from, so after `v = arr.lazy[10:50]` the first element of `v` is +`v[10]` and a negative index is out of bounds rather than counted from the end. +That dialect suits zarr, where a view's coordinates stay comparable with the +parent array's. `LazyArray` is a duck array and has to behave like the array it +wraps to be usable as a NumPy drop-in or as a dask source, so it re-zeroes its +coordinates on every view and uses positions. `zarr_indexing.boundary` performs +the translation between the two. + +Two more NumPy rules the dialect keeps, in every mode: + +- A scalar integer drops its axis. Any non-boolean object implementing Python's + `SupportsIndex` protocol is accepted as one, including in slice bounds and + steps; an `__int__` method alone is deliberately not enough. A scalar is a + basic index wherever it appears, applied before any advanced index rather + than broadcast against one. So + `lazy.oindex[0]` has the shape of `x[0]`, `lazy.oindex[0, [1, 2], :]` means + `x[0][numpy.ix_([1, 2], ...)]`, and `lazy.oindex[0, 1, 2]` and + `lazy.vindex[0, 1, 2]` are both zero-rank. Use a length-1 list to keep an + axis. +- Advanced indices are placed as NumPy places them. For a `vindex` selection + that leaves some axes unindexed, the gathered dimensions sit where the + coordinate arrays sat when those arrays are adjacent, and lead when a slice + separates them β€” so `lazy.vindex[..., i, j]` has shape + `(x.shape[0], *broadcast)`, matching `x[..., i, j]`. + +Materializing on fallback +------------------------- +`LazyArray` implements `__array__` but deliberately implements neither +`__array_ufunc__` nor `__array_function__`. A NumPy *function* given a view +therefore materializes the whole thing through +`__array__` and works on the resulting array: `numpy.sum(view)`, +`numpy.add(view, 1)` and `numpy.stack([view, view])` all do, and so does +`numpy.ones(view.shape) + view`, where the ndarray on the left dispatches. + +Python's arithmetic *operators* do not: `view + 1` raises `TypeError`, because +the wrapper defines no arithmetic dunders and an `int` has nothing to dispatch +to. Both facts follow from the same intent β€” laziness here applies to indexing, +not to building a deferred compute graph β€” and a `LazyArray` is not a drop-in +for arithmetic on a large array either way. Use `.lazy[...]` to narrow the view +first, or pass the wrapper to `dask.array.from_array` so that dask owns the +compute graph. + +Ownership +--------- +`result()` always allocates fresh system memory before reading through the +selected reader. A `numpy.ma` source keeps its mask by receiving a masked +output buffer; other source-specific array types do not survive materializing. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import operator +import uuid +from collections.abc import Sequence +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Protocol, cast + +import numpy as np + +from zarr_indexing.boundary import ( + SelectionMode, + normalize_positional_selection, + split_scalar_axes, +) +from zarr_indexing.chunk_resolution import ( + ChunkProjection, + plan_chunks, +) +from zarr_indexing.grid import DimensionGrid, FixedDimension, dimension_grids_from_chunks +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap +from zarr_indexing.reader import ( + ReadContext, + Reader, + basic_reader, + numpy_reader, +) +from zarr_indexing.transform import ( + IndexTransform, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + SelectFn = Callable[[Any, SelectionMode], "LazyArray"] + +__all__ = ["LazyArray", "Partition"] + +# Above this many bytes, the no-dask token fallback describes an array +# structurally instead of digesting its contents. See `_wrapped_token`. +_TOKEN_DIGEST_LIMIT = 1 << 20 + + +def _invoke_reader( + reader: Reader, + source: Any, + context: ReadContext, + out: np.ndarray[Any, Any], +) -> None: + """Invoke a reader and enforce its in-place return contract.""" + returned = reader.read_into(source, context, out) + if returned is not None: + raise TypeError(f"reader.read_into must return None, got {type(returned).__name__}") + + +def _is_correlated(transform: IndexTransform) -> bool: + """True when the transform gathers a list of points rather than an outer product.""" + return transform.index_array_structure == "general" + + +class ArrayLike(Protocol): + """The surface `LazyArray` needs from the array it wraps.""" + + @property + def shape(self) -> tuple[int, ...]: ... + @property + def dtype(self) -> Any: ... + def __getitem__(self, key: Any) -> Any: ... + + +# NumPy's dtype-specialized ``__getitem__`` overloads do not structurally match +# the deliberately broad protocol above under strict type checking. Accept an +# ndarray explicitly so users do not have to erase its type with ``cast(Any, …)``. +_WrappedArray = ArrayLike | np.ndarray[Any, Any] + + +# --------------------------------------------------------------------------- # +# Partition discovery +# --------------------------------------------------------------------------- # + + +def _read_source_attribute(array: Any, name: str) -> Any: + """Read a partition-describing attribute, treating any failure as "absent". + + Discovery inspects an object we did not write. A missing attribute is the + common case, but zarr raises an `AttributeError` subclass from + `read_chunk_sizes` on a lazy view, and other backends compute the attribute + lazily and may fail for their own reasons. Any failure here means "this + array does not advertise a partitioning", never a hard error. + """ + try: + return getattr(array, name, None) + # Guarded properties (e.g. zarr's LazyViewError) and broken foreign + # attributes may raise anything; discovery must degrade to None. + except Exception: + return None + + +def _discover_parts(array: Any, shape: tuple[int, ...]) -> tuple[DimensionGrid, ...] | None: + """Resolve the partitioning advertised by `array`, or None for one whole part. + + Discovery parses external input: an attribute that does not describe a + partitioning of `shape` means "this object does not advertise one I + understand", and the array is treated as unpartitioned rather than rejected. + A partitioning is an I/O strategy, so reading the whole array is always a + correct fallback. `with_parts` is a public API and validates strictly. + """ + declared = _read_source_attribute(array, "read_chunk_sizes") + if declared is None: + declared = _read_source_attribute(array, "chunks") + if declared is None: + return None + try: + return dimension_grids_from_chunks(declared, shape) + except (ValueError, TypeError): + return None + + +def _whole_array_grids(shape: tuple[int, ...]) -> tuple[DimensionGrid, ...]: + """A partitioning with a single part covering the whole array.""" + return tuple(FixedDimension(size=extent, extent=extent) for extent in shape) + + +# --------------------------------------------------------------------------- # +# The lowering engine +# --------------------------------------------------------------------------- # + + +def _is_identity_transform(transform: IndexTransform, shape: tuple[int, ...]) -> bool: + """True when `transform` maps every coordinate of `shape` to itself. + + Structural rather than an `==` against `IndexTransform.from_shape`: an + `ArrayMap` holds an ndarray, so equality on two transforms that both carry + one would try to take the truth value of an array. + """ + domain = transform.domain + if domain.inclusive_min != (0,) * len(shape) or domain.exclusive_max != shape: + return False + if len(transform.output) != len(shape): + return False + return all( + isinstance(m, DimensionMap) and m.input_dimension == i and m.offset == 0 and m.stride == 1 + for i, m in enumerate(transform.output) + ) + + +# --------------------------------------------------------------------------- # +# Partitions +# --------------------------------------------------------------------------- # + + +@dataclass(frozen=True, slots=True, eq=False) +class _PartOwner: + """Opaque identity shared only by one view and the parts it prepared.""" + + +def _partition_out_selection( + cell_transform: IndexTransform, +) -> tuple[Any, ...]: + """Lower ``cell_transform`` to NumPy selectors on the request buffer.""" + domain = cell_transform.domain + if _is_correlated(cell_transform): + correlated_selectors: list[np.ndarray[Any, np.dtype[np.intp]]] = [] + for output_map in cell_transform.output: + if isinstance(output_map, ConstantMap): + coordinates = np.full(domain.shape, output_map.offset, dtype=np.intp) + elif isinstance(output_map, DimensionMap): + input_dimension = output_map.input_dimension + axis = np.arange( + domain.inclusive_min[input_dimension], + domain.exclusive_max[input_dimension], + dtype=np.intp, + ) + shape = ( + (1,) * input_dimension + + (axis.size,) + + ((1,) * (domain.ndim - input_dimension - 1)) + ) + coordinates = np.broadcast_to(axis.reshape(shape), domain.shape) + coordinates = output_map.offset + output_map.stride * coordinates + else: + coordinates = output_map.offset + output_map.stride * np.broadcast_to( + output_map.index_array, domain.shape + ) + correlated_selectors.append(np.asarray(coordinates, dtype=np.intp)) + return tuple(correlated_selectors) + + selectors: list[int | slice | np.ndarray[Any, np.dtype[np.intp]]] = [] + n_array_maps = sum(isinstance(output_map, ArrayMap) for output_map in cell_transform.output) + for output_map in cell_transform.output: + if isinstance(output_map, ConstantMap): + selectors.append(output_map.offset) + elif isinstance(output_map, DimensionMap): + input_dimension = output_map.input_dimension + lo = domain.inclusive_min[input_dimension] + hi = domain.exclusive_max[input_dimension] + selectors.append( + slice( + output_map.offset + output_map.stride * lo, + output_map.offset + output_map.stride * hi, + output_map.stride, + ) + ) + else: + selectors.append( + (output_map.offset + output_map.stride * output_map.index_array.ravel()).astype( + np.intp + ) + ) + if n_array_maps > 1: + axes = [ + np.asarray([selector], dtype=np.intp) + if isinstance(selector, int) + else ( + np.arange(selector.start, selector.stop, selector.step, dtype=np.intp) + if isinstance(selector, slice) + else selector + ) + for selector in selectors + ] + return np.ix_(*axes) + return tuple(selectors) + + +def _out_selection_cell_count(selection: tuple[Any, ...], out_shape: tuple[int, ...]) -> int: + """How many cells of an array of shape `out_shape` a `Partition.out_selection` writes. + + Counted from the selectors' own shapes, so nothing is read and no index + array is materialized. The selectors are slices and integer arrays: the + slices contribute their lengths, and the arrays broadcast against each other + exactly as NumPy's advanced indexing broadcasts them, whether they arrive as + an open mesh (`numpy.ix_`) or as parallel coordinates (`unravel_index`). + """ + total = 1 + array_shapes: list[tuple[int, ...]] = [] + if len(selection) != len(out_shape): + raise AssertionError( + f"a partition addressed {len(selection)} of the view's {len(out_shape)} " + "dimensions; this is a bug in zarr-indexing's partition walk" + ) + for selector, extent in zip(selection, out_shape, strict=True): + if isinstance(selector, slice): + start: Any = selector.start + stop: Any = selector.stop + step: Any = selector.step + if step is None and start is not None and stop is not None and 0 <= start <= stop: + # The shape a partition walk actually produces: a concrete, + # forward, in-bounds interval. Sized directly, so the common + # path allocates neither a tuple nor a range. + total *= int(stop) - int(start) + else: + total *= len(range(*selector.indices(extent))) + else: + array_shapes.append(tuple(int(s) for s in np.shape(selector))) + if len(array_shapes) > 0: + total *= math.prod(np.broadcast_shapes(*array_shapes)) + return total + + +@dataclass(frozen=True, kw_only=True) +class Partition: + """One box of a `LazyArray`'s partitioning, as it falls through the view. + + Yielded by [`LazyArray.parts`][zarr_indexing.lazy_array.LazyArray.parts]. + The parts of a view tile it exactly and disjointly: assembling every + `view.result()` at its `out_selection` reproduces the whole view's + `result()`, and each part can be resolved independently and concurrently. + Derived parts retain the same reader object; a shared stateful reader owns + synchronization for concurrent calls. + + A consumer that needs the plan before materialization can prepare it once + and reuse the same immutable parts for both scheduling and assembly: + + ```python + parts = tuple(view.parts()) + schedule(part.base_coords for part in parts) + values = view.result(parts=parts) + ``` + + Prepared parts are owned by the exact view that created them and must tile + it completely. Passing parts from another view, even an equivalent one, is + rejected without reading; omitting a part is likewise rejected rather than + returning a partly initialized result. + + Attributes + ---------- + projection + The source-independent description of this part. Its paired + `chunk_transform` and `cell_transform` share one compact synthetic + domain, mapping each selected cell to chunk-local storage and request + coordinates respectively. This is the authoritative placement model; + `base_coords` and `is_complete` are conveniences derived from it. + base_coords + Which box of the base partitioning this is, one coordinate per dimension + of the wrapped array. + box + The box itself, in the global storage coordinates of the wrapped + array: one `[inclusive_min, exclusive_max)` interval per dimension. It + describes the whole partition cell, while `view.bounding_box()` is the + global hull of only the selected values in that cell. For a nested or + repartitioned view this box may be narrower than + `projection.chunk_domain`. + view + A `LazyArray` covering exactly the cells of the view that live in this + box. Its transform directly addresses its raw wrapped `array`; only the + projection's `chunk_transform` is chunk-local. Resolving the view reads + the box once through its selected reader. Named `view` rather than + `array` because `LazyArray.array` is the opposite thing β€” the raw + wrapped source β€” and the two sat next to each other meaning inverses. + out_selection + Where `view.result()` belongs in an array of the whole view's shape β€” a + NumPy index tuple with one entry per dimension of the view, usable + directly as `out[part.out_selection] = ...`. + is_complete + Whether the view covers the whole box. Useful to a writer deciding + between a blind overwrite and a read-modify-write. Fancy projections + report `False` because their coverage is deliberately `unknown` until + duplicate-aware proof is added. + + Examples + -------- + Assembling every part's result at its `out_selection` reproduces the view: + + >>> import numpy as np + >>> source = np.arange(12).reshape(3, 4) + >>> view = LazyArray.from_numpy(source).with_parts((2, 2)) + >>> out = np.empty(view.shape, dtype=view.dtype) + >>> for part in view.parts(): + ... out[part.out_selection] = part.view.result() + >>> bool((out == source).all()) + True + """ + + projection: ChunkProjection + box: tuple[tuple[int, int], ...] + view: LazyArray + out_selection: tuple[Any, ...] + _owner: _PartOwner | None = field(default=None, repr=False, compare=False) + + @property + def base_coords(self) -> tuple[int, ...]: + """Coordinates of this partition in the selected base grid.""" + return self.projection.chunk_coords + + @property + def is_complete(self) -> bool: + """Whether the projection proves it covers the entire selected cell.""" + return self.projection.coverage == "full" + + +def _validate_prepared_parts(parts: Sequence[Partition], out_shape: tuple[int, ...]) -> None: + """Require `parts` to address every output cell exactly once. + + Prepared parts are caller-supplied input, so a plan that does not tile the + view is a `ValueError`, not an assertion about this library's own walk. + """ + coverage = np.zeros(out_shape, dtype=np.bool_) + addressed = 0 + try: + for part in parts: + # Name a rank mismatch explicitly instead of letting NumPy treat + # omitted selectors as implicit full slices. + addressed += _out_selection_cell_count(part.out_selection, out_shape) + if all(isinstance(selector, slice) for selector in part.out_selection): + # The common box part: plain assignment, no pointwise walk. + coverage[part.out_selection] = True + else: + # `logical_or.at` applies duplicate advanced coordinates one by + # one instead of buffering them as ordinary advanced indexing + # would. + np.logical_or.at(coverage, part.out_selection, True) + except (AssertionError, IndexError, TypeError, ValueError) as error: + raise ValueError("prepared parts do not tile the view exactly") from error + if addressed != math.prod(out_shape) or not np.all(coverage): + raise ValueError("prepared parts do not tile the view exactly") + + +# --------------------------------------------------------------------------- # +# Tokenization +# --------------------------------------------------------------------------- # + + +def _wrapped_token(array: Any) -> Any: + """A token for the wrapped array. + + In order of preference: the array's own `__dask_tokenize__`; + `dask.base.tokenize` when dask is importable (imported lazily β€” this package + never requires it); otherwise a local fallback that digests the contents of + a small array. + + The two environments do not agree, and neither is a translation of the + other: a token taken with dask installed is meaningless to a process without + it, and the reverse. A token is an identifier within one process, not a + portable name. + + Above `_TOKEN_DIGEST_LIMIT` the local fallback has nothing left to identify + the contents with β€” reading them is exactly what a token call must not do β€” + so it declines to claim equality at all and returns a value that matches + nothing, including itself. A cache keyed on it misses; the alternative, a + structural description, is a cache that hands one array's result to a + different array of the same shape and dtype. + """ + hook = getattr(array, "__dask_tokenize__", None) + if hook is not None: + try: + return hook() + # A token must never raise; fall through to the structural fallback. + except Exception: # pragma: no cover - a hook that refuses to run + pass + try: + # dask is an optional peer, never a dependency of this package, so it is + # imported here and its absence is ordinary. + from dask.base import tokenize # pyright: ignore[reportMissingImports] + except ImportError: + pass + else: + return tokenize(array) + + shape = tuple(int(s) for s in getattr(array, "shape", ())) + dtype = getattr(array, "dtype", None) + structural = (type(array).__qualname__, shape, str(dtype)) + # A token nothing can equal, for when the contents cannot be identified. It + # is the shape and dtype that would otherwise be mistaken for an identity, + # so they are kept alongside it for a reader looking at a graph. + unidentified = (*structural, "unidentified", uuid.uuid4().hex) + + # Decide whether to digest the contents from the *declared* size. Measuring + # it by converting first would read the whole array β€” a multi-gigabyte store + # pulled into memory by a token call, which is the opposite of the point. + itemsize = getattr(dtype, "itemsize", None) + if not isinstance(itemsize, int) or itemsize * math.prod(shape) > _TOKEN_DIGEST_LIMIT: + return unidentified + try: + contents = np.ascontiguousarray(array) + # A token must never raise; an unreadable source is simply unidentified. + except Exception: + return unidentified + return (*structural, hashlib.sha256(contents.tobytes()).hexdigest()) + + +# --------------------------------------------------------------------------- # +# The wrapper +# --------------------------------------------------------------------------- # + + +class LazyArray: + """A lazily-indexable view over a system-memory/basic-indexing source. + + Wrapping neither copies nor reads the wrapped array at construction time. + Indexing through `.lazy` composes an `IndexTransform` and returns another + `LazyArray`; `result()` materializes. + + Selections use the **positional NumPy dialect** and reads are broken up + along a **partitioning** discovered from the wrapped array. Every derived + view retains its reader; that reader receives the complete projected + transform once per part. See the module docstring, which also covers how the + dialect differs from `zarr.Array.lazy` and why every non-indexing NumPy + operation materializes the view. + + This wrapper describes **reads**. It defines no `__setitem__`, so + assigning into a view raises `TypeError`. Writing belongs to the + consumer: plan the selection with + [`plan_chunks`][zarr_indexing.chunk_resolution.plan_chunks] and own the + read-modify-write, since chunk atomicity and concurrent-writer policy are + the backend's to decide, not an indexing plan's. + + Parameters + ---------- + array + The array to wrap. It must expose `shape`, `dtype`, and `__getitem__` + with basic (integer/slice) indexing; `__setitem__` is not required, so + a read-only source wraps as well as a writable one. Its partitioning, + if it advertises one, is discovered here; use `with_parts` to choose + a different one. + This conservative constructor selects `basic_reader`; use `from_numpy` + for a NumPy array or `with_reader` to select another backend adapter. + + Examples + -------- + >>> import numpy as np + >>> source = np.arange(12).reshape(3, 4) + >>> view = LazyArray.from_numpy(source).with_parts((2, 2)).lazy[1:, ::2] + >>> view.shape + (2, 2) + >>> view.result() + array([[ 4, 6], + [ 8, 10]]) + """ + + __slots__ = ("_array", "_part_owner", "_parts", "_reader", "_transform", "_window") + + def __init__(self, array: _WrappedArray) -> None: + """Wrap `array` without reading it; parameters are documented on the class. + + The only validation here is the `numpy.matrix` rejection (`TypeError`). + """ + if isinstance(array, np.matrix): + # `np.matrix` keeps every result two-dimensional, so `m[1]` has shape + # `(1, n)` where every other array-like gives `(n,)`. A view's shape + # comes from the transform, which follows NumPy's rule, so the two + # disagree on every rank-reducing selection. Refused at the door + # rather than resolved into a shape the view did not promise. + raise TypeError( + "numpy.matrix cannot be wrapped: it never reduces rank, so a " + "view's shape and its result would disagree. Convert it first, " + "with numpy.asarray(m)." + ) + shape = tuple(int(s) for s in array.shape) + self._array = array + self._window: tuple[slice, ...] | None = None + self._transform = IndexTransform.from_shape(shape) + self._parts = _discover_parts(array, shape) + self._reader = basic_reader + self._part_owner = _PartOwner() + + @classmethod + def from_numpy(cls, array: np.ndarray[Any, Any]) -> LazyArray: + """Wrap a NumPy array with its explicitly selected optimized reader.""" + if not isinstance(cast(object, array), np.ndarray): + raise TypeError( + f"LazyArray.from_numpy requires a numpy.ndarray, got {type(array).__name__}" + ) + return cls(array).with_reader(numpy_reader) + + @classmethod + def _derive( + cls, + array: _WrappedArray, + transform: IndexTransform, + parts: tuple[DimensionGrid, ...] | None, + window: tuple[slice, ...] | None, + reader: Reader, + ) -> LazyArray: + """Build a wrapper sharing `array` but carrying a new transform or partitioning.""" + view = cls.__new__(cls) + view._array = array + # Views re-zero their coordinate system: the positional dialect means a + # view's first element is at position 0 whatever it was sliced from. + view._transform = transform.translate_domain_to((0,) * transform.input_rank) + view._parts = parts + view._window = window + view._reader = reader + view._part_owner = _PartOwner() + return view + + @property + def _base_shape(self) -> tuple[int, ...]: + """The shape of what this wrapper treats as its base array.""" + if self._window is None: + return tuple(int(s) for s in self._array.shape) + return tuple(s.stop - s.start for s in self._window) + + # -- array-like surface ------------------------------------------------- + + @property + def array(self) -> _WrappedArray: + """The wrapped array.""" + return self._array + + @property + def base_shape(self) -> tuple[int, ...]: + """The shape the partitioning is expressed in β€” not this view's shape. + + `with_parts` and `with_parts_per_axis` describe boxes of the array being + read, not of the view reading it, so a narrowed view still partitions + the extents named here. For a part's own `array`, this is the part's + box, which is why the same call means different sizes there. Without + somewhere to read it, the frame in force could only be inferred from an + error message. + """ + return self._base_shape + + @property + def transform(self) -> IndexTransform: + """The composed transform from this view's coordinates to storage.""" + return self._transform + + @property + def shape(self) -> tuple[int, ...]: + """The shape of this view β€” the transform's input domain, not the source's.""" + return self._transform.domain.shape + + @property + def ndim(self) -> int: + """Number of dimensions of this view β€” the transform's input rank.""" + return self._transform.input_rank + + @property + def size(self) -> int: + """Total number of elements in this view (the product of `shape`).""" + return math.prod(self.shape) + + @property + def dtype(self) -> Any: + """The wrapped array's dtype; views never change it.""" + return self._array.dtype + + @property + def reader(self) -> Reader: + """The backend adapter used when this view materializes.""" + return self._reader + + def with_reader(self, reader: Reader) -> LazyArray: + """Return the same metadata view resolved through `reader`.""" + if not callable(getattr(reader, "read_into", None)): + raise TypeError(f"reader.read_into must be callable, got {type(reader).__name__}") + return LazyArray._derive( + self._array, + self._transform, + self._parts, + self._window, + reader, + ) + + # -- shape of the selection --------------------------------------------- + + @property + def is_box(self) -> bool: + """Whether this view selects a rectangular region rather than a point list. + + True exactly when the composed transform's output maps are all + `ConstantMap` or `DimensionMap` β€” no `ArrayMap`. Such a selection is + affine and monotone along every axis, so it is described completely by + an interval and a stride per dimension: + [`bounding_box`][zarr_indexing.lazy_array.LazyArray.bounding_box] + together with + [`strides`][zarr_indexing.lazy_array.LazyArray.strides]. Basic indexing, + at any depth of composition, stays a box; one `oindex`, `vindex`, or + mask anywhere in the chain makes the selection a query permanently. + + A box is dense β€” every cell of its bounding box selected β€” only when + every stride is 1. A strided box covers its hull sparsely: + `lazy[10:50, ::4]` selects 40x20 cells out of a 40x77 hull, so a + consumer that reads the whole hull and discards the rest transfers 3.85x + the data it needs. Check `strides` before treating a box as a single + slab read. + + The distinction lets a consumer decide between a slab read and a + gather; see [the design notes](../design-notes.md) for why it is a + category rather than an optimization. + + Examples + -------- + >>> import numpy as np + >>> array = LazyArray.from_numpy(np.arange(12).reshape(3, 4)) + >>> (array.lazy[1:, ::2].is_box, array.lazy.oindex[[2, 0], :].is_box) + (True, False) + """ + return not any(isinstance(m, ArrayMap) for m in self._transform.output) + + def bounding_box(self) -> tuple[tuple[int, int], ...] | None: + """The storage region this view touches, one interval per storage dimension. + + Defined for any selection, box or not, as the hull: the smallest + `[inclusive_min, exclusive_max)` interval per dimension of the array + this view reads from that contains every coordinate the selection + reaches. + + The hull is dense β€” every cell in it selected β€” only for a box whose + every stride is 1. A strided box selects a sublattice of its hull (pair + this with [`strides`][zarr_indexing.lazy_array.LazyArray.strides] to + describe it fully), and a query's hull is a superset that can be + arbitrarily loose: `oindex[[0, 999]]` has a 1000-wide hull over two + rows. + + Returns + ------- + tuple of (int, int), or None + One interval per storage dimension, or `None` when the view is + empty (`size == 0`) and so touches no coordinate at all, leaving no + interval to report. + + Notes + ----- + The coordinates directly address the raw `array` this view exposes. + Consequently, partition views report source-global hulls; + [`Partition.box`][zarr_indexing.lazy_array.Partition] separately gives + the whole global partition cell rather than only the selected hull. + + Examples + -------- + >>> import numpy as np + >>> array = LazyArray.from_numpy(np.arange(12).reshape(3, 4)) + >>> array.lazy[1:, ::2].bounding_box() + ((1, 3), (0, 3)) + >>> array.lazy.oindex[[2, 0], :].bounding_box() + ((0, 3), (0, 4)) + >>> array.lazy[1:1].bounding_box() is None + True + """ + if self.size == 0: + return None + domain = self._transform.domain + bounds: list[tuple[int, int]] = [] + for m in self._transform.output: + if isinstance(m, ConstantMap): + bounds.append((m.offset, m.offset + 1)) + elif isinstance(m, DimensionMap): + d = m.input_dimension + first = m.offset + m.stride * domain.inclusive_min[d] + last = m.offset + m.stride * (domain.exclusive_max[d] - 1) + bounds.append((min(first, last), max(first, last) + 1)) + else: + coords = m.offset + m.stride * m.index_array + bounds.append((int(coords.min()), int(coords.max()) + 1)) + return tuple(bounds) + + def strides(self) -> tuple[int, ...] | None: + """The step between selected coordinates, one per storage dimension. + + Together with `bounding_box()`, this fully describes a box selection: + `bounding_box()` gives the interval per dimension, `strides()` gives the + step per dimension. A stride of 1 means every cell of the hull along + that dimension is selected; `k` means every `k`-th. Dimensions fixed by + an integer index report 1 β€” they span a single coordinate. + + Returns + ------- + tuple of int, or None + One positive stride per storage dimension, or `None` when + [`is_box`][zarr_indexing.lazy_array.LazyArray.is_box] is false: a + query's coordinates are a lookup table and have no step. An empty + box still reports its strides even though + [`bounding_box`][zarr_indexing.lazy_array.LazyArray.bounding_box] + returns `None`, because the step is a property of the selection's + shape, not of the (empty) region it touches. + + Notes + ----- + Magnitudes only. A reversing view (`lazy[::-1]`) selects the same set of + coordinates as the equivalent forward view, so it reports the same + bounding box and the same strides. The traversal direction is recorded + in the transform, not in this description of the region touched. A + consumer that needs the order reads the transform, or reverses the block + it gets back. + + Examples + -------- + >>> import numpy as np + >>> array = LazyArray.from_numpy(np.arange(24).reshape(4, 6)) + >>> (array.lazy[1:, ::2].bounding_box(), array.lazy[1:, ::2].strides()) + (((1, 4), (0, 5)), (1, 2)) + >>> array.lazy[2, ::3].strides() + (1, 3) + >>> array.lazy.oindex[[2, 0], :].strides() is None + True + """ + if not self.is_box: + return None + return tuple( + 1 if isinstance(m, ConstantMap) else abs(m.stride) for m in self._transform.output + ) + + # -- partitioning ------------------------------------------------------- + + def with_parts(self, parts: Sequence[int]) -> LazyArray: + """Return the same view, read in uniform boxes of shape `parts`. + + One integer per dimension of `base_shape`, with the trailing box in each + dimension clipped to the extent. The transform, the wrapped array, and + therefore `result()` are all unchanged; only the boxes the read is + broken into differ. Nothing is copied and nothing is read. + + For per-axis sizes see + [`with_parts_per_axis`][zarr_indexing.lazy_array.LazyArray.with_parts_per_axis], + and to read in one pass see + [`unpartitioned`][zarr_indexing.lazy_array.LazyArray.unpartitioned]. + The three were one parameter whose meaning was decided by inspecting the + type of what it was given, which left no way to ask for one of them and + be told when you had spelled it wrong. + + Parameters + ---------- + parts + The box shape, one integer per dimension of `base_shape`. + + Returns + ------- + LazyArray + The same view with a new partitioning. + + Raises + ------ + ValueError + If `parts` has the wrong length or contains a non-positive extent. + Uniform part sizes must remain positive even for a zero-length + axis; use `with_parts_per_axis` for the accepted explicit zero-axis + spellings. + + Examples + -------- + >>> import numpy as np + >>> view = LazyArray.from_numpy(np.arange(12).reshape(3, 4)) + >>> [part.base_coords for part in view.with_parts((2, 3)).parts()] + [(0, 0), (0, 1), (1, 0), (1, 1)] + """ + entries = self._part_entries(parts, "with_parts") + if any(isinstance(entry, Sequence) for entry in entries): + raise ValueError( + "with_parts takes one integer per dimension; for per-axis box " + "sizes use with_parts_per_axis" + ) + return self._with_grids(dimension_grids_from_chunks(entries, self._base_shape)) + + def with_parts_per_axis(self, sizes: Sequence[Sequence[int]]) -> LazyArray: + """Return the same view, read in boxes of explicitly listed sizes. + + The dask convention: one sequence of box extents per dimension of + `base_shape`, each summing to that dimension's extent. Use it when the + boxes are not uniform β€” a partitioning discovered from a store, or one + whose last box differs by more than clipping. + + Parameters + ---------- + sizes + One sequence of box extents per dimension of `base_shape`. + + Returns + ------- + LazyArray + The same view with a new partitioning. + + Raises + ------ + ValueError + If `sizes` has the wrong length, contains a negative extent, uses a + zero extent on a nonempty axis, or declares sizes that do not sum + to `base_shape`. On a zero-length axis, `()`, `(0,)`, and repeated + zeros all describe no chunks. + + Examples + -------- + >>> import numpy as np + >>> view = LazyArray.from_numpy(np.arange(12).reshape(3, 4)) + >>> [part.box for part in view.with_parts_per_axis(((1, 2), (4,))).parts()] + [((0, 1), (0, 4)), ((1, 3), (0, 4))] + """ + entries = self._part_entries(sizes, "with_parts_per_axis") + return self._with_grids(dimension_grids_from_chunks(entries, self._base_shape)) + + @staticmethod + def _part_entries(parts: Sequence[Any], method: str) -> tuple[Any, ...]: + """Materialize a partitioning argument, naming a non-iterable a ValueError. + + Both partitioning methods document ValueError for malformed input; a + bare integer would otherwise surface as a TypeError from iteration. + """ + try: + return tuple(parts) + except TypeError as error: + raise ValueError( + f"{method} takes one entry per dimension of base_shape; got {parts!r}" + ) from error + + def unpartitioned(self) -> LazyArray: + """Return the same view, read in one pass. + + `result()` still allocates its owned output buffer first, then calls the + reader once with the whole projected transform. `parts()` still yields a + single part covering everything. + + Returns + ------- + LazyArray + The same view with no partitioning. + """ + return self._with_grids(None) + + def _with_grids(self, grids: tuple[DimensionGrid, ...] | None) -> LazyArray: + return LazyArray._derive(self._array, self._transform, grids, self._window, self._reader) + + def parts(self) -> Iterator[Partition]: + """Iterate the base partitioning, projected through this view. + + Single-use: this is a generator, so it is consumed by the first walk and + a second `for` over the same object yields nothing. Call `parts()` again + for a fresh walk, or keep a `list` of it if you need to revisit. + + Yields one [`Partition`][zarr_indexing.lazy_array.Partition] per box the + view actually touches. The parts tile the view exactly and disjointly, + and each carries a `LazyArray` that can be resolved on its own: in + another thread, in another order, or not at all. Those views share this + view's reader, and `LazyArray` does not serialize calls, so a stateful + reader must synchronize its own mutable state. + + A wrapper with no partitioning (see `with_parts`) yields a single part + covering the whole array. + + Yields + ------ + Partition + One per touched box, in the resolver's own order. + + Examples + -------- + >>> import numpy as np + >>> view = LazyArray.from_numpy(np.arange(12).reshape(3, 4)).with_parts((2, 2)) + >>> part = next(view.lazy[:, 1:].parts()) + >>> (part.base_coords, part.view.shape, part.is_complete) + ((0, 0), (2, 1), False) + """ + base_shape = self._base_shape + grids = self._parts if self._parts is not None else _whole_array_grids(base_shape) + rank = len(base_shape) + + if self._window is None: + plan_transform = self._transform + else: + plan_transform = self._transform.translate(tuple(-item.start for item in self._window)) + + for projection in plan_chunks(plan_transform, grids): + base_coords = projection.chunk_coords + local = projection.chunk_transform + origin = tuple(grid.chunk_offset(c) for grid, c in zip(grids, base_coords, strict=True)) + extent = tuple(grid.data_size(c) for grid, c in zip(grids, base_coords, strict=True)) + if origin == (0,) * rank and extent == base_shape: + # The part is the whole base: lowering directly against the + # source beats materializing a block that is the source. + window = self._window + elif self._window is None: + window = tuple(slice(o, o + e) for o, e in zip(origin, extent, strict=True)) + else: + window = tuple( + slice(w.start + o, w.start + o + e) + for w, o, e in zip(self._window, origin, extent, strict=True) + ) + # The global box, computed from the origin directly rather than from + # `window`: a part covering the whole base carries no window (so + # nothing is pre-materialized) but still sits somewhere concrete. + if self._window is None: + global_origin = origin + else: + global_origin = tuple( + w.start + o for w, o in zip(self._window, origin, strict=True) + ) + yield Partition( + projection=projection, + box=tuple((o, o + e) for o, e in zip(global_origin, extent, strict=True)), + view=LazyArray._derive( + self._array, + local.translate(global_origin), + None, + window, + self._reader, + ), + out_selection=_partition_out_selection(projection.cell_transform), + _owner=self._part_owner, + ) + + # -- indexing ----------------------------------------------------------- + + @property + def lazy(self) -> _LazyIndexer: + """Lazy indexing: `lazy[...]`, `lazy.oindex[...]`, `lazy.vindex[...]`. + + Each returns a new `LazyArray` view; no data is read. + """ + return _LazyIndexer(self._select) + + def _select(self, selection: Any, mode: SelectionMode) -> LazyArray: + transform = self._transform + if mode != "basic": + # NumPy applies scalar integers as basic indices before the advanced + # ones, dropping their axes. Split them into their own step. + scalar_selection, selection = split_scalar_axes(selection, transform.domain, mode) + if scalar_selection is not None: + transform = transform.select(scalar_selection, "basic") + transform = transform.translate_domain_to((0,) * transform.input_rank) + literal = normalize_positional_selection(selection, transform.domain, mode) + if mode == "basic": + # IndexTransform's basic path includes NumPy's `None`/newaxis. + # `selection_to_transform` intentionally exposes a narrower basic + # selection contract and rejects it. + composed = transform[literal] + else: + composed = transform.select(literal, mode) + return LazyArray._derive(self._array, composed, self._parts, self._window, self._reader) + + def __getitem__(self, selection: Any) -> Any: + """Read a basic selection eagerly, like `numpy.ndarray.__getitem__`. + + Reads here are eager, not lazy, so that a `LazyArray` works as a duck + array for consumers (dask's `from_array`, `numpy.asarray`) that expect + indexing to produce data. Use `.lazy[...]` for the lazy form. + """ + return self._select(selection, "basic").result() + + def result(self, *, parts: Sequence[Partition] | None = None) -> Any: + """Materialize this view. + + Every result starts as a fresh system-memory buffer. Each touched + partition is read through the selected reader directly into its + rectangular destination, or into an owned dense temporary before fancy + placement. Empty views allocate without reading the source. + + Parameters + ---------- + parts + A reusable sequence previously returned by this exact view's + `parts()` method. Supplying it reuses that partition plan instead + of constructing another one. The parts must tile the view exactly. + + Returns + ------- + numpy.ndarray + An array of shape `self.shape`, identical whatever partitioning is + in force, always in fresh system memory. A view with a zero-rank + domain returns a zero-dimensional array, not a scalar. + + Raises + ------ + ValueError + If supplied parts were prepared by another view, or do not tile + this view exactly. The output buffer is uninitialized where nothing + was written, so a bad plan is reported rather than returned. + AssertionError + If this library's own partition walk fails to cover the view β€” a + bug in zarr-indexing, never a consequence of the caller's input. + """ + prepared_parts = None if parts is None else tuple(parts) + if prepared_parts is not None and any( + # Module-private provenance deliberately crosses the two public + # wrapper types without becoming part of either public surface. + part._owner is not self._part_owner # pyright: ignore[reportPrivateUsage] + for part in prepared_parts + ): + raise ValueError("prepared parts do not belong to this view") + + out_shape = self.shape + if prepared_parts is not None: + _validate_prepared_parts(prepared_parts, out_shape) + out = self._output_buffer(out_shape) + size = math.prod(out_shape) + if size == 0: + return out + + if prepared_parts is None and self._parts is None: + _invoke_reader(self._reader, self._array, ReadContext(self._transform), out) + return out + + written = 0 + selected_parts = self.parts() if prepared_parts is None else prepared_parts + for part in selected_parts: + # Counted before the scatter, so a part addressing the wrong + # number of axes is named rather than reported as a broadcast + # failure against the buffer. + written += _out_selection_cell_count(part.out_selection, out_shape) + direct = all(isinstance(selector, slice) for selector in part.out_selection) + if direct: + destination = out if len(part.out_selection) == 0 else out[part.out_selection] + else: + destination = part.view._output_buffer(part.view.shape) + _invoke_reader( + self._reader, + self._array, + ReadContext(part.view.transform, part.projection), + destination, + ) + if not direct: + out[part.out_selection] = destination + if written != size: + # The buffer is uninitialized where no part wrote, so a partition + # walk that does not tile the view exactly would otherwise hand + # back process memory dressed as data. The parts are disjoint by + # contract, so counting the cells each addresses is enough: + # a gap undercounts and an overlap overcounts. + if prepared_parts is not None: + raise ValueError( + "prepared parts do not tile the view exactly: " + f"they addressed {written} of the view's {size} cells" + ) + raise AssertionError( + f"the partition walk addressed {written} of the view's {size} " + "cells; this is a bug in zarr-indexing's partition walk" + ) + return out + + def _output_buffer(self, out_shape: tuple[int, ...]) -> Any: + """The buffer `result()` scatters parts into. + + Deliberately uninitialized: every cell is written by exactly one part, + and `result()` verifies that before returning. A masked source gets a + masked buffer so that reader writes preserve the mask; other source- + specific array types do not survive materializing. + """ + dtype = np.dtype(self.dtype) + if isinstance(self._array, np.ma.MaskedArray): + return np.ma.masked_all(out_shape, dtype=dtype) + return np.empty(out_shape, dtype=dtype) + + # -- protocols ---------------------------------------------------------- + + def __array__(self, dtype: Any = None, copy: bool | None = None) -> Any: + """Materialize the view as a NumPy array. + + The result never shares memory with the wrapped array, whatever `copy` + asks for: `result()` already allocates, so `copy=True` gets an array the + caller owns and `copy=None` gets the same one rather than a second + allocation. `copy=False` is refused, because materializing means reading + β€” the values do not exist as a NumPy array until this call makes them. + """ + if copy is False: + raise ValueError( + "a LazyArray cannot be converted to a NumPy array without a " + "copy: a view is a description of a read, and the values only " + "exist once the read is made" + ) + return np.asarray(self.result(), dtype=dtype) + + def __dask_tokenize__(self) -> Any: + """A deterministic token: the wrapped array and the view. + + Two wrappers produce equal tokens when they wrap the same data and + address the same cells. The view contributes a digest of its canonical + ndsel body, so transforms that differ only in representation produce + the same token, and a fancy selection with a large index array does not + embed that array's JSON in the token. See `_wrapped_token` for the + determinism scope of the wrapped array's contribution; dask is imported + lazily and is never a requirement of this package. + + The partitioning and reader are deliberately absent. Both decide how + the data is read β€” in which boxes, and through which request strategy β€” + and neither changes the values that come back, so two wrappers differing + only in those describe the same data. A token identifies data, so they + token alike and a consumer that caches on tokens reuses one result for + both. + """ + canonical = json.dumps(self._transform.to_json(), sort_keys=True) + return ( + type(self).__qualname__, + _wrapped_token(self._array), + hashlib.sha256(canonical.encode()).hexdigest(), + ) + + def __len__(self) -> int: + """The length of the first axis, as for a NumPy array; `TypeError` on a 0-d view.""" + if self.ndim == 0: + raise TypeError("len() of unsized object") + return self.shape[0] + + def __iter__(self) -> Iterator[Any]: + """Iterate eagerly over the first axis, like a NumPy array. + + The rank check happens in `__iter__` itself rather than in the + generator, so `iter(view)` on a zero-rank view raises immediately as + NumPy's does, instead of waiting for the first `next`. + """ + if self.ndim == 0: + raise TypeError("iteration over a 0-d array") + return (self[position] for position in range(self.shape[0])) + + # NumPy's own conversions decide what a size-1 (or wrong-sized) view means, + # including which exception it raises, so these delegate rather than + # reimplement. Each materializes the view first. + def __bool__(self) -> bool: + return bool(self.result()) + + def __int__(self) -> int: + return int(self.result()) + + def __float__(self) -> float: + return float(self.result()) + + def __index__(self) -> int: + return operator.index(self.result()) + + def __repr__(self) -> str: + wrapped = type(self._array).__name__ + described = [f"{wrapped} shape={self.shape} dtype={self.dtype}"] + if not _is_identity_transform(self._transform, self._base_shape): + described.append(f"view={self._transform.selection_repr}") + return f"" + + +class _LazyIndexer: + """The `.lazy` accessor: builds views instead of reading data. + + Holds the owning view's bound `_select` rather than the view itself, so the + accessor classes never reach into another object's internals. + """ + + __slots__ = ("_select",) + + def __init__(self, select: SelectFn) -> None: + self._select = select + + def __getitem__(self, selection: Any) -> LazyArray: + """Basic (integer / slice / ellipsis) indexing, lazily.""" + return self._select(selection, "basic") + + @property + def oindex(self) -> _LazyOIndex: + """Orthogonal (outer-product) indexing, lazily.""" + return _LazyOIndex(self._select) + + @property + def vindex(self) -> _LazyVIndex: + """Vectorized (coordinate / mask) indexing, lazily.""" + return _LazyVIndex(self._select) + + +class _LazyOIndex: + """`lazy.oindex[...]` β€” one selection per axis, combined as an outer product.""" + + __slots__ = ("_select",) + + def __init__(self, select: SelectFn) -> None: + self._select = select + + def __getitem__(self, selection: Any) -> LazyArray: + return self._select(selection, "orthogonal") + + +class _LazyVIndex: + """`lazy.vindex[...]` β€” correlated coordinate arrays, or a single mask.""" + + __slots__ = ("_select",) + + def __init__(self, select: SelectFn) -> None: + self._select = select + + def __getitem__(self, selection: Any) -> LazyArray: + return self._select(selection, "vectorized") diff --git a/packages/zarr-indexing/src/zarr_indexing/messages.py b/packages/zarr-indexing/src/zarr_indexing/messages.py new file mode 100644 index 0000000000..df0e0c87eb --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/messages.py @@ -0,0 +1,757 @@ +"""The ndsel message layer β€” pure JSON in, canonical JSON out. + +This module implements the [ndsel](https://github.com/zarr-developers/ndsel) draft wire +format: a JSON-serializable representation of NumPy-style n-dimensional +selections that adapts TensorStore's `IndexTransform` model. It is a **pure +JSONβ†’JSON** layer: it depends on nothing but the standard library, imposes no +engine (numpy/array) constraints, and never rounds, clamps, or drops +information. Engine constraints (finite bounds, in-memory `IndexTransform` +construction) live one layer up, in `json.py`. + +Two entry points: + +- `parse_ndsel(obj)` β€” structurally validate an ndsel message of any of the + five kinds (`point`/`box`/`slice`/`points`/`transform`), returning it + unchanged. Raises `NdselError` (carrying a spec reason code) on any defect. +- `normalize_ndsel(obj)` β€” desugar and canonicalize a message to the single + deterministic **canonical transform body** of the spec (section 4.3): a bare + `IndexTransform` JSON body, without the `kind` discriminator. `normalize` is + idempotent when its output is re-tagged with `kind: "transform"`. + +The canonical body is, field-for-field, a TensorStore `IndexTransform` (minus +`kind`), so a normalized `transform` loads directly into TensorStore once +`kind` is stripped. + +Value rules enforced here: every integer is a 64-bit signed value; JSON +booleans are **not** integers (Python's `isinstance(True, int)` is guarded +against explicitly); the `"-inf"`/`"+inf"` sentinels are legal only in bound +positions; an implicit bound is the one-element `[n]`-bracket form, and its +implicit/explicit flag is preserved through normalization. +""" + +from __future__ import annotations + +from typing import Any + +__all__ = [ + "NdselError", + "normalize_ndsel", + "parse_ndsel", +] + +# --------------------------------------------------------------------------- +# Error taxonomy +# --------------------------------------------------------------------------- + +#: The complete set of ndsel reason codes (spec section 6). +REASON_CODES = frozenset( + { + "invalid_json", + "unknown_kind", + "unknown_field", + "multiple_upper_bounds", + "bounds_out_of_order", + "output_map_conflict", + "rank_mismatch", + "step_zero", + # Retired in 1.0-draft.2, when negative `step` became specified. Kept in + # the set so a message carrying the code is still recognized, but no + # condition in this implementation emits it. + "negative_step_unsupported", + } +) + + +class NdselError(ValueError): + """An ndsel message failed validation. + + Carries the spec `reason` code (one of `REASON_CODES`) so callers and the + conformance harness can assert on it directly, plus a human-readable + `detail`. + + Examples + -------- + >>> try: + ... normalize_ndsel({"kind": "bogus"}) + ... except NdselError as error: + ... (error.reason, str(error)) + ('unknown_kind', "unknown_kind: unknown kind 'bogus'") + """ + + def __init__(self, reason: str, detail: str = "") -> None: + """Store `reason` and `detail` and compose the message as `"reason: detail"`. + + `reason` is a spec reason code (one of `REASON_CODES`); `detail` is + optional human-readable context, and when empty the message is the + bare `reason`. + """ + self.reason = reason + self.detail = detail + super().__init__(f"{reason}: {detail}" if detail else reason) + + +# --------------------------------------------------------------------------- +# 64-bit signed integer range (spec section 3.5) +# --------------------------------------------------------------------------- + +_I64_MIN = -(2**63) +_I64_MAX = 2**63 - 1 + +_KNOWN_KINDS = frozenset({"point", "box", "slice", "points", "transform"}) + +# The two upper-bound spellings, keyed by message prefix. Only one of the three +# per group may appear (spec section 4.1 / 5.2). +_BOX_UPPER = ("exclusive_max", "inclusive_max", "shape") +_TRANSFORM_UPPER = ("input_exclusive_max", "input_inclusive_max", "input_shape") + +_OUTPUT_MAP_FIELDS = frozenset( + { + "offset", + "stride", + "input_dimension", + "index_array", + "index_array_bounds", + } +) + +# An upper bound on `input_rank`, because normalization allocates proportionally +# to it β€” an identity `output`, a bound per dimension, a label per dimension β€” +# from a document that carries no data behind the number. Matches the rank +# TensorStore accepts, which is well above any real array. +_MAX_RANK = 32 + + +# --------------------------------------------------------------------------- +# Leaf value validators +# --------------------------------------------------------------------------- + + +def _is_int(value: Any) -> bool: + """True iff `value` is a JSON integer β€” an `int` that is not a `bool`. + + JSON has no boolean-as-integer: `True`/`False` are rejected even though + Python makes `bool` a subclass of `int` (spec section 3.6). + """ + return isinstance(value, int) and not isinstance(value, bool) + + +def _check_int(value: Any, where: str) -> int: + """Validate a plain-integer position: an in-range i64, never a sentinel.""" + if not _is_int(value): + raise NdselError("invalid_json", f"{where} must be an integer, got {value!r}") + if value < _I64_MIN or value > _I64_MAX: + raise NdselError("invalid_json", f"{where} is outside the 64-bit signed range: {value}") + return int(value) + + +def _is_sentinel(value: Any) -> bool: + return value in ("-inf", "+inf") + + +def _check_index_value(value: Any, where: str) -> int | str: + """Validate an `index-value`: an in-range i64 or a `"-inf"`/`"+inf"` sentinel.""" + if _is_sentinel(value): + return str(value) + return _check_int(value, where) + + +def _check_bound(value: Any, where: str) -> int | str | list[int | str]: + """Validate a `bound`: an explicit `index-value`, or a one-element implicit `[index-value]`.""" + if isinstance(value, list): + if len(value) != 1: + raise NdselError( + "invalid_json", + f"{where} implicit bound must be a one-element array, got {value!r}", + ) + return [_check_index_value(value[0], where)] + return _check_index_value(value, where) + + +def _check_int_list(value: Any, where: str) -> list[int]: + if not isinstance(value, list): + raise NdselError("invalid_json", f"{where} must be an array, got {value!r}") + return [_check_int(v, f"{where}[{i}]") for i, v in enumerate(value)] + + +def _check_bound_list(value: Any, where: str) -> list[Any]: + if not isinstance(value, list): + raise NdselError("invalid_json", f"{where} must be an array, got {value!r}") + return [_check_bound(v, f"{where}[{i}]") for i, v in enumerate(value)] + + +def _check_label_list(value: Any, where: str) -> list[str]: + if not isinstance(value, list): + raise NdselError("invalid_json", f"{where} must be an array, got {value!r}") + for i, v in enumerate(value): + if not isinstance(v, str): + raise NdselError("invalid_json", f"{where}[{i}] must be a string, got {v!r}") + return list(value) + + +# --------------------------------------------------------------------------- +# Extended-integer order for bounds (spec section 4.1) +# --------------------------------------------------------------------------- + + +def _bound_value(bound: int | str | list[int | str]) -> int | str: + """The underlying `index-value` of a bound, dropping the implicit bracket.""" + return bound[0] if isinstance(bound, list) else bound + + +def _bound_is_implicit(bound: int | str | list[int | str]) -> bool: + return isinstance(bound, list) + + +def _ext_key(value: int | str) -> tuple[int, int]: + """A sort key giving the extended-integer order `-inf < n < +inf` exactly. + + Uses an integer tier plus the value, so no float rounding of near-`2**63` + integers can misorder the `inclusive_min <= exclusive_max` check. + """ + if value == "-inf": + return (0, 0) + if value == "+inf": + return (2, 0) + assert isinstance(value, int) + return (1, value) + + +def _rewrap(value: int | str, *, implicit: bool) -> int | str | list[int | str]: + return [value] if implicit else value + + +# --------------------------------------------------------------------------- +# Message-level helpers +# --------------------------------------------------------------------------- + + +def _require_object(obj: Any) -> dict[str, Any]: + if not isinstance(obj, dict): + raise NdselError("invalid_json", f"message must be a JSON object, got {type(obj).__name__}") + return obj + + +def _message_kind(obj: dict[str, Any]) -> str: + kind = obj.get("kind") + if not isinstance(kind, str): + raise NdselError("invalid_json", "message must have a string 'kind' field") + if kind not in _KNOWN_KINDS: + raise NdselError("unknown_kind", f"unknown kind {kind!r}") + return kind + + +def _check_membership(obj: dict[str, Any], allowed: frozenset[str], what: str) -> None: + """Strict membership (spec section 3.7): reject any undefined member.""" + for key in obj: + if key not in allowed: + raise NdselError("unknown_field", f"{what} has undefined member {key!r}") + + +def _single_upper_bound(obj: dict[str, Any], fields: tuple[str, str, str]) -> str | None: + present = [f for f in fields if f in obj] + if len(present) > 1: + raise NdselError( + "multiple_upper_bounds", + f"at most one of {fields} may be present; got {present}", + ) + return present[0] if present else None + + +def _resolve_upper_bound( + upper_field: str | None, + upper_raw: list[Any] | None, + inclusive_min: list[Any], + rank: int, + *, + kind_of: str, +) -> list[int | str | list[int | str]]: + """Produce `exclusive_max` from whichever upper-bound spelling was supplied. + + - `exclusive_max`/`input_exclusive_max` β†’ used directly. + - `inclusive_max`/`input_inclusive_max` β†’ each element `+1`. + - `shape`/`input_shape` β†’ `inclusive_min + shape` per element. + - none β†’ an **implicit `+inf`** in every dimension. + + The implicit/explicit bracket travels with the extent-bearing field (the + upper bound, or `shape`), matching the spec's `[n]`-bracket convention. + """ + if upper_field is None: + return [["+inf"] for _ in range(rank)] + + assert upper_raw is not None + if kind_of == "exclusive": + return list(upper_raw) + + result: list[int | str | list[int | str]] = [] + for k in range(rank): + raw = upper_raw[k] + implicit = _bound_is_implicit(raw) + value = _bound_value(raw) + if kind_of == "inclusive": + new = _inclusive_to_exclusive(value, f"{upper_field}[{k}]") + else: # shape + new = _shape_to_exclusive(_bound_value(inclusive_min[k]), value, f"{upper_field}[{k}]") + result.append(_rewrap(new, implicit=implicit)) + return result + + +def _checked_i64(value: int, where: str) -> int: + """An arithmetic result that must still be a 64-bit signed integer. + + Normalization is idempotent (spec section 4.3): whatever it emits must pass + the same validation on the way back in. Desugaring adds β€” `inclusive_max + 1`, + `inclusive_min + shape` β€” so a bound at the top of the range would otherwise + be emitted one past it and rejected by the next call on our own output. + """ + if value < _I64_MIN or value > _I64_MAX: + raise NdselError( + "invalid_json", + f"{where} is {value}, which is outside the 64-bit signed range; the " + f"normalized form cannot represent it", + ) + return value + + +def _inclusive_to_exclusive(value: int | str, where: str) -> int | str: + if value == "+inf" or value == "-inf": + return value + assert isinstance(value, int) + return _checked_i64(value + 1, f"{where} converted to an exclusive bound") + + +def _shape_to_exclusive(min_value: int | str, shape_value: int | str, where: str) -> int | str: + if shape_value == "-inf": + raise NdselError( + "invalid_json", + f"{where} is '-inf'; a shape counts cells and cannot be negatively infinite", + ) + if shape_value == "+inf" or min_value == "+inf": + return "+inf" + if min_value == "-inf": + return "-inf" + assert isinstance(min_value, int) + assert isinstance(shape_value, int) + return _checked_i64(min_value + shape_value, f"{where} added to its inclusive_min") + + +def _validate_domain(inclusive_min: list[Any], exclusive_max: list[Any], *, prefix: str) -> None: + """Every dimension must satisfy `inclusive_min <= exclusive_max` (empty is valid).""" + for k, (lo, hi) in enumerate(zip(inclusive_min, exclusive_max, strict=True)): + if _ext_key(_bound_value(lo)) > _ext_key(_bound_value(hi)): + raise NdselError( + "bounds_out_of_order", + f"{prefix}[{k}]: inclusive_min {_bound_value(lo)!r} > " + f"exclusive_max {_bound_value(hi)!r}", + ) + + +def _identity_output(rank: int) -> list[dict[str, Any]]: + return [{"offset": 0, "stride": 1, "input_dimension": k} for k in range(rank)] + + +# --------------------------------------------------------------------------- +# Per-kind desugaring +# --------------------------------------------------------------------------- + + +def _normalize_point(obj: dict[str, Any]) -> dict[str, Any]: + _check_membership(obj, frozenset({"kind", "coords"}), "point") + if "coords" not in obj: + raise NdselError("invalid_json", "point requires 'coords'") + coords = _check_int_list(obj["coords"], "coords") + return { + "input_rank": 0, + "input_inclusive_min": [], + "input_exclusive_max": [], + "input_labels": [], + "output": [{"offset": c} for c in coords], + } + + +def _infer_rank( + obj: dict[str, Any], + named_lengths: list[tuple[str, int]], + *, + declared: int | None, +) -> int: + """Reconcile a declared rank (if any) with every present array's length.""" + rank = declared + for name, length in named_lengths: + if rank is None: + rank = length + elif rank != length: + raise NdselError( + "rank_mismatch", + f"{name} has length {length}, inconsistent with rank {rank}", + ) + return rank if rank is not None else 0 + + +def _normalize_box(obj: dict[str, Any]) -> dict[str, Any]: + allowed = frozenset( + {"kind", "inclusive_min", "exclusive_max", "inclusive_max", "shape", "labels"} + ) + _check_membership(obj, allowed, "box") + + inclusive_min_raw = ( + _check_bound_list(obj["inclusive_min"], "inclusive_min") if "inclusive_min" in obj else None + ) + upper_field = _single_upper_bound(obj, _BOX_UPPER) + upper_raw = _check_bound_list(obj[upper_field], upper_field) if upper_field else None + labels_raw = _check_label_list(obj["labels"], "labels") if "labels" in obj else None + + named_lengths: list[tuple[str, int]] = [] + if inclusive_min_raw is not None: + named_lengths.append(("inclusive_min", len(inclusive_min_raw))) + if upper_raw is not None: + named_lengths.append((upper_field or "", len(upper_raw))) + if labels_raw is not None: + named_lengths.append(("labels", len(labels_raw))) + rank = _infer_rank(obj, named_lengths, declared=None) + + inclusive_min = inclusive_min_raw if inclusive_min_raw is not None else [0] * rank + exclusive_max = _resolve_upper_bound( + upper_field, upper_raw, inclusive_min, rank, kind_of=_upper_kind(upper_field, _BOX_UPPER) + ) + labels = labels_raw if labels_raw is not None else [""] * rank + _validate_domain(inclusive_min, exclusive_max, prefix="box") + + return { + "input_rank": rank, + "input_inclusive_min": inclusive_min, + "input_exclusive_max": exclusive_max, + "input_labels": labels, + "output": _identity_output(rank), + } + + +def _upper_kind(upper_field: str | None, fields: tuple[str, str, str]) -> str: + if upper_field is None or upper_field == fields[0]: + return "exclusive" + if upper_field == fields[1]: + return "inclusive" + return "shape" + + +def _normalize_slice(obj: dict[str, Any]) -> dict[str, Any]: + allowed = frozenset({"kind", "start", "stop", "step", "labels"}) + _check_membership(obj, allowed, "slice") + if "start" not in obj: + raise NdselError("invalid_json", "slice requires 'start'") + if "stop" not in obj: + raise NdselError("invalid_json", "slice requires 'stop'") + start = _check_int_list(obj["start"], "start") + stop = _check_int_list(obj["stop"], "stop") + step = _check_int_list(obj["step"], "step") if "step" in obj else [1] * len(start) + labels_raw = _check_label_list(obj["labels"], "labels") if "labels" in obj else None + + n = len(start) + for name, arr in (("stop", stop), ("step", step)): + if len(arr) != n: + raise NdselError( + "rank_mismatch", f"{name} has length {len(arr)}, expected {n} (from start)" + ) + if labels_raw is not None and len(labels_raw) != n: + raise NdselError( + "rank_mismatch", f"labels has length {len(labels_raw)}, expected {n} (from start)" + ) + + for k, s in enumerate(step): + if s == 0: + raise NdselError("step_zero", f"step[{k}] is zero") + + inclusive_min: list[Any] = [] + exclusive_max: list[Any] = [] + output: list[dict[str, Any]] = [] + for k in range(n): + a, b, s = start[k], stop[k], step[k] + # One rule for both signs (spec 5.3): the traversal runs from `a` + # toward `b`, so the source interval's length is `b - a` going up and + # `a - b` going down. + length = (b - a) if s > 0 else (a - b) + if length < 0: + # A reversed interval is a mistake about the direction of travel, + # not an empty selection. `b == a` is the way to select nothing. + raise NdselError( + "bounds_out_of_order", + f"start[{k}]={a} and stop[{k}]={b} with step {s} run the wrong " + "way; an empty selection is spelled stop == start", + ) + m = -(-length // abs(s)) # ceil(length / |s|) + o = _trunc_div(a, s) # trunc(a / s), toward zero, both signs + offset = a - s * o # lattice phase, |offset| < |s| + inclusive_min.append(o) + exclusive_max.append(o + m) + output.append({"offset": offset, "stride": s, "input_dimension": k}) + + labels = labels_raw if labels_raw is not None else [""] * n + return { + "input_rank": n, + "input_inclusive_min": inclusive_min, + "input_exclusive_max": exclusive_max, + "input_labels": labels, + "output": output, + } + + +def _normalize_points(obj: dict[str, Any]) -> dict[str, Any]: + _check_membership(obj, frozenset({"kind", "coords"}), "points") + if "coords" not in obj: + raise NdselError("invalid_json", "points requires 'coords'") + coords = obj["coords"] + if not isinstance(coords, list): + raise NdselError("invalid_json", f"points coords must be an array, got {coords!r}") + + rows: list[list[int]] = [] + n: int | None = None + for i, row in enumerate(coords): + if not isinstance(row, list): + raise NdselError("invalid_json", f"points coords[{i}] must be an array, got {row!r}") + row_ints = [_check_int(v, f"coords[{i}][{j}]") for j, v in enumerate(row)] + if n is None: + n = len(row_ints) + elif len(row_ints) != n: + raise NdselError( + "rank_mismatch", + f"points coords[{i}] has length {len(row_ints)}, expected {n} (ragged)", + ) + rows.append(row_ints) + + m = len(rows) + n = n if n is not None else 0 + output = [ + { + "offset": 0, + "stride": 1, + "index_array": [rows[i][k] for i in range(m)], + "index_array_bounds": ["-inf", "+inf"], + } + for k in range(n) + ] + return { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [m], + "input_labels": [""], + "output": output, + } + + +def _normalize_output_map(raw: Any, where: str) -> dict[str, Any]: + if not isinstance(raw, dict): + raise NdselError("invalid_json", f"{where} must be a JSON object, got {raw!r}") + _check_membership(raw, _OUTPUT_MAP_FIELDS, where) + + has_index_array = "index_array" in raw + has_input_dim = "input_dimension" in raw + if has_index_array and has_input_dim: + raise NdselError( + "output_map_conflict", + f"{where} carries both 'input_dimension' and 'index_array'", + ) + + offset = _check_int(raw["offset"], f"{where}.offset") if "offset" in raw else 0 + + if has_index_array: + stride = _check_int(raw["stride"], f"{where}.stride") if "stride" in raw else 1 + bounds = ( + _check_index_array_bounds(raw["index_array_bounds"], where) + if "index_array_bounds" in raw + else ["-inf", "+inf"] + ) + # index_array is carried verbatim (spec section 7 defers shape validation). + normalized: dict[str, Any] = { + "offset": offset, + "stride": stride, + "index_array": raw["index_array"], + "index_array_bounds": bounds, + } + return normalized + + if has_input_dim: + input_dim = _check_int(raw["input_dimension"], f"{where}.input_dimension") + if input_dim < 0: + raise NdselError( + "invalid_json", f"{where}.input_dimension must be >= 0, got {input_dim}" + ) + stride = _check_int(raw["stride"], f"{where}.stride") if "stride" in raw else 1 + return {"offset": offset, "stride": stride, "input_dimension": input_dim} + + # Constant map: only offset survives. A stray `stride`/`index_array_bounds` + # is schema-valid (the output-map schema permits those members on any map), + # so it is silently dropped rather than rejected β€” a constant carries only + # `offset` in canonical form (spec section 4.3). + return {"offset": offset} + + +def _check_index_array_bounds(value: Any, where: str) -> list[int | str]: + if not isinstance(value, list) or len(value) != 2: + raise NdselError( + "invalid_json", + f"{where}.index_array_bounds must be a two-element array, got {value!r}", + ) + lo = _check_index_value(value[0], f"{where}.index_array_bounds[0]") + hi = _check_index_value(value[1], f"{where}.index_array_bounds[1]") + if _ext_key(lo) > _ext_key(hi): + raise NdselError( + "bounds_out_of_order", + f"{where}.index_array_bounds: lower bound {lo!r} > upper bound {hi!r}", + ) + return [lo, hi] + + +def _normalize_transform(obj: dict[str, Any]) -> dict[str, Any]: + allowed = frozenset( + { + "kind", + "input_rank", + "input_inclusive_min", + "input_exclusive_max", + "input_inclusive_max", + "input_shape", + "input_labels", + "output", + } + ) + _check_membership(obj, allowed, "transform") + + declared_rank: int | None = None + if "input_rank" in obj: + declared_rank = _check_int(obj["input_rank"], "input_rank") + if declared_rank < 0: + raise NdselError("invalid_json", f"input_rank must be >= 0, got {declared_rank}") + if declared_rank > _MAX_RANK: + # Normalization fills a bound, a label and an identity output map per + # dimension, so an unbacked rank is a request to allocate from a + # document that carries nothing. + raise NdselError( + "invalid_json", + f"input_rank must be <= {_MAX_RANK}, got {declared_rank}", + ) + + inclusive_min_raw = ( + _check_bound_list(obj["input_inclusive_min"], "input_inclusive_min") + if "input_inclusive_min" in obj + else None + ) + upper_field = _single_upper_bound(obj, _TRANSFORM_UPPER) + upper_raw = _check_bound_list(obj[upper_field], upper_field) if upper_field else None + labels_raw = ( + _check_label_list(obj["input_labels"], "input_labels") if "input_labels" in obj else None + ) + + named_lengths: list[tuple[str, int]] = [] + if inclusive_min_raw is not None: + named_lengths.append(("input_inclusive_min", len(inclusive_min_raw))) + if upper_raw is not None: + named_lengths.append((upper_field or "", len(upper_raw))) + if labels_raw is not None: + named_lengths.append(("input_labels", len(labels_raw))) + rank = _infer_rank(obj, named_lengths, declared=declared_rank) + + inclusive_min = inclusive_min_raw if inclusive_min_raw is not None else [0] * rank + exclusive_max = _resolve_upper_bound( + upper_field, + upper_raw, + inclusive_min, + rank, + kind_of=_upper_kind(upper_field, _TRANSFORM_UPPER), + ) + labels = labels_raw if labels_raw is not None else [""] * rank + _validate_domain(inclusive_min, exclusive_max, prefix="input") + + if "output" in obj: + if not isinstance(obj["output"], list): + raise NdselError("invalid_json", f"output must be an array, got {obj['output']!r}") + output = [_normalize_output_map(m, f"output[{i}]") for i, m in enumerate(obj["output"])] + for i, m in enumerate(output): + # An `input_dimension` names one of *this* transform's input + # dimensions, so the rank is what bounds it. Checked here rather than + # in `_normalize_output_map`, which sees one map and not the rank. + if "input_dimension" in m and m["input_dimension"] >= rank: + raise NdselError( + "rank_mismatch", + f"output[{i}].input_dimension is {m['input_dimension']}, " + f"outside the valid range [0, {rank}) for input_rank {rank}", + ) + else: + output = _identity_output(rank) + + return { + "input_rank": rank, + "input_inclusive_min": inclusive_min, + "input_exclusive_max": exclusive_max, + "input_labels": labels, + "output": output, + } + + +_NORMALIZERS = { + "point": _normalize_point, + "box": _normalize_box, + "slice": _normalize_slice, + "points": _normalize_points, + "transform": _normalize_transform, +} + + +# --------------------------------------------------------------------------- +# trunc division (spec section 5.3 correction, matches _trunc_div in transform.py) +# --------------------------------------------------------------------------- + + +def _trunc_div(a: int, b: int) -> int: + """Integer division rounded toward zero (C semantics).""" + q = a // b + if q < 0 and q * b != a: + q += 1 + return q + + +# --------------------------------------------------------------------------- +# Public entry points +# --------------------------------------------------------------------------- + + +def normalize_ndsel(obj: Any) -> dict[str, Any]: + """Desugar and canonicalize an ndsel message to its canonical transform body. + + Accepts any of the five message kinds and returns the bare canonical + `IndexTransform` body of spec section 4.3 β€” no `kind` field. Raises + `NdselError` (carrying a reason code) for any invalid input. + + Examples + -------- + >>> body = normalize_ndsel({"kind": "box", "shape": [2, 3]}) + >>> (body["input_rank"], body["input_inclusive_min"], body["input_exclusive_max"]) + (2, [0, 0], [2, 3]) + >>> body["output"][0] + {'offset': 0, 'stride': 1, 'input_dimension': 0} + """ + message = _require_object(obj) + kind = _message_kind(message) + return _NORMALIZERS[kind](message) + + +def parse_ndsel(obj: Any) -> dict[str, Any]: + """Structurally validate an ndsel message, returning it unchanged. + + A lighter gate than `normalize_ndsel`: it confirms the message is a + well-formed ndsel message of a recognized kind (correct field membership, + JSON types, upper-bound exclusivity, domain ordering, step signs) and + raises `NdselError` otherwise, but does not desugar it. Useful for + validating a message you intend to keep in its compact shorthand form. + + Examples + -------- + >>> message = {"kind": "point", "coords": [3, 4]} + >>> parse_ndsel(message) is message + True + >>> normalize_ndsel(message)["output"] + [{'offset': 3}, {'offset': 4}] + """ + message = _require_object(obj) + _message_kind(message) + # Validation and desugaring share one pass; run it and discard the body. + normalize_ndsel(message) + return message diff --git a/packages/zarr-indexing/src/zarr_indexing/output_map.py b/packages/zarr-indexing/src/zarr_indexing/output_map.py new file mode 100644 index 0000000000..3ee7250efa --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/output_map.py @@ -0,0 +1,403 @@ +"""Output index maps β€” three ordered mappings to integer coordinates. + +An output index map describes how input cells address one dimension of +the output space. Its coordinates form an **ordered, duplicate-preserving sequence** +aligned with the input domain, never a mathematical set. Three representations +cover the cases that arise in practice: + +- `ConstantMap(offset=5)` β€” every request cell maps to coordinate `5` +- `DimensionMap(input_dimension=0, offset=3, stride=2)` over input `[0, 5)` + β€” the ordered arithmetic progression `[3, 5, 7, 9, 11]` +- `ArrayMap(index_array=[5, 1, 1])` β€” the explicit sequence `[5, 1, 1]`, + preserving both order and the repeated coordinate + +Every output map participates in two operations defined on `IndexTransform`, +which provides the input-domain context these maps lack: + +- **intersect** β€” retain mapped cells whose coordinates lie within a range + (e.g., a chunk), without changing their order or multiplicity. + Restricting `[3, 5, 5, 9]` to `[4, 8)` produces `[5, 5]`. +- **translate** β€” shift every coordinate by a constant (e.g., make chunk-local). + Translating `[5, 5, 7]` by `-4` produces `[1, 1, 3]`. + +These two operations are the foundation of chunk resolution: for each chunk, +intersect the map with the chunk's range, then translate to chunk-local +coordinates. + +The three types exist because they trade off generality for efficiency: + +- `ConstantMap`: O(1) storage, O(1) intersection +- `DimensionMap`: O(1) storage, O(1) intersection (analytical) +- `ArrayMap`: O(n) storage, O(n) intersection (must scan the array) + +Collapsing everything to `ArrayMap` would be correct but wasteful β€” a +billion-element slice would materialize a billion coordinates just to group +them by chunk, when `DimensionMap` does it with three integers. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +import numpy as np + +from zarr_indexing._affine import checked_affine + +if TYPE_CHECKING: + import numpy.typing as npt + + from zarr_indexing.json import OutputIndexMapJSON + + +def _array_map_dependency_axes(index_array: np.ndarray[Any, Any]) -> tuple[int, ...]: + """Return the input axes on which a normalized index array varies. + + Normalized `ArrayMap` index arrays carry the full input rank of their + enclosing transform: an axis the array varies over has its full size, while + an axis the array is independent of is a singleton (size 1). The dependency + axes are therefore exactly the axes of size 2 or more. An orthogonal + (`oindex`) array depends on a single axis; a vectorized (`vindex`) array + depends on all of the (shared) broadcast axes. + + A size-**0** axis carries no dependency either: the array has no values to + vary, so an empty selection stays the flavor it was made as rather than + reading as correlated with every other axis. + """ + return tuple(axis for axis, size in enumerate(index_array.shape) if size > 1) + + +@dataclass(frozen=True, slots=True) +class ConstantMap: + """A constant output-coordinate mapping. + + Every input cell maps to `offset`. Arises from integer indexing (e.g., + `arr[5]` fixes one dimension to coordinate 5). + + Examples + -------- + Every input cell maps to the same output coordinate β€” the NumPy analogy + is a broadcast (`np.broadcast_to(5, (3,))`), not an index: + + >>> from zarr_indexing.domain import IndexDomain + >>> from zarr_indexing.transform import IndexTransform + >>> domain = IndexDomain.from_shape((3,)) + >>> t = IndexTransform(domain=domain, output=(ConstantMap(offset=5),)) + >>> t.apply((0,)), t.apply((1,)), t.apply((2,)) + ((5,), (5,), (5,)) + """ + + offset: int = 0 + """The fixed output coordinate every input cell maps to.""" + + def to_json(self) -> OutputIndexMapJSON: + """Convert to the canonical wire form: the bare `constant` map. + + Examples + -------- + >>> ConstantMap(5).to_json() + {'offset': 5} + """ + return {"offset": self.offset} + + +@dataclass(frozen=True, slots=True) +class DimensionMap: + """An ordered affine mapping to output coordinates. + + Maps each input coordinate `i` to `offset + stride * i`, where the input + range comes from the enclosing `IndexTransform`'s domain. Arises from slice + indexing (e.g., `arr[2:10:3]` gives offset=2, stride=3). + + Examples + -------- + The slice `arr[2:11:3]` reads coordinates `2, 5, 8` β€” the rule + `offset + stride * i` with `offset=2`, `stride=3`: + + >>> m = DimensionMap(input_dimension=0, offset=2, stride=3) + >>> [m.offset + m.stride * i for i in range(3)] + [2, 5, 8] + >>> np.arange(11)[2:11:3].tolist() + [2, 5, 8] + """ + + input_dimension: int + """The input (domain) dimension whose coordinate this map reads.""" + + offset: int = 0 + """The output coordinate that input coordinate `0` maps to.""" + + stride: int = 1 + """The output-coordinate step per unit input step; negative walks backward, zero repeats `offset`.""" + + def to_json(self) -> OutputIndexMapJSON: + """Convert to the canonical wire form: the `single_input_dimension` map. + + Examples + -------- + >>> DimensionMap(input_dimension=1, offset=0, stride=2).to_json() + {'offset': 0, 'stride': 2, 'input_dimension': 1} + """ + return { + "offset": self.offset, + "stride": self.stride, + "input_dimension": self.input_dimension, + } + + +@dataclass(frozen=True, slots=True) +class ArrayMap: + """An explicit ordered, duplicate-preserving coordinate mapping. + + Maps each input position `i` to `offset + stride * index_array[i]`. + Index-array order and repeated entries are semantic and remain present in + the result. Arises from fancy indexing (e.g., `arr[[5, 1, 1]]` or boolean + masks). + + Freshly constructed maps are normalized to the **full input rank** of their + enclosing transform: `index_array` has the enclosing domain's rank, sized + fully on the axes it varies over and singleton (size 1) elsewhere. The + shape is the single source of truth for what the map depends on β€” its + **dependency axes** are exactly its non-singleton axes (see + `_array_map_dependency_axes`) β€” and it distinguishes the two + flavors of multi-array fancy indexing: + + - **orthogonal** (`oindex`): each array varies along a single, *distinct* + axis (all others singleton); the result is their outer product. + - **vectorized** (`vindex`): the arrays are correlated and share the same + non-singleton (broadcast) axes; the result is a pointwise scatter. + + A map holding exactly one coordinate carries no shape to read a dependency + from, and none is needed: it is the `ConstantMap` it equals, and the + selection layer builds that instead (see `array_map_or_constant`). A + hand-built all-singleton `ArrayMap` is still a valid value; resolution + classifies it with the correlated maps and reads it pointwise. + + Examples + -------- + The fancy selection `arr[[5, 1, 1]]` reads coordinate 5, then 1, then 1 + β€” order and the duplicate preserved, exactly as NumPy fancy indexing: + + >>> m = ArrayMap(index_array=np.array([5, 1, 1])) + >>> [m.offset + m.stride * c for c in m.index_array.tolist()] + [5, 1, 1] + >>> np.arange(10)[[5, 1, 1]].tolist() + [5, 1, 1] + """ + + index_array: npt.NDArray[np.integer[Any]] + """Explicit coordinates at the enclosing transform's full input rank; order and + duplicates are semantic. Its non-singleton axes are the map's dependency axes.""" + + offset: int = 0 + """Constant term of the affine adjustment: the output coordinate is `offset + stride * index_array[i]`.""" + + stride: int = 1 + """Multiplier applied to each `index_array` value before `offset` is added.""" + + def __post_init__(self) -> None: + """Own the index array and expose it read-only. + + A map is frozen, but the array inside it was not: reaching through a + view's transform to `index_array[0] = 9` silently changed what the view + returned, in a package whose whole contract is that a view is a + description of a read and resolving it twice answers alike. Owning the + array also prevents the caller from changing the contents behind the + read-only view, which would invalidate this value object's hash. + """ + # Immutable bytes are the ultimate owner so callers cannot re-enable + # the WRITEABLE flag, as they can on a read-only array that owns its + # allocation. `asarray` also accepts the NumPy scalars that reach here + # after indexing an array down to one element. + array = np.asarray(self.index_array) + if not np.issubdtype(array.dtype, np.integer): + raise TypeError(f"index_array must have an integer dtype, got {array.dtype}") + normalized = checked_affine(0, 1, array) + frozen = np.frombuffer(normalized.tobytes(), dtype=np.intp).reshape(normalized.shape) + object.__setattr__(self, "index_array", frozen) + + def __reduce__(self) -> tuple[object, tuple[object, int, int]]: + """Reconstruct through `__init__`, preserving the ownership invariant.""" + return ( + type(self), + (self.index_array, self.offset, self.stride), + ) + + def __eq__(self, other: object) -> bool: + """Value equality, comparing index arrays element-wise. + + The generated `__eq__` compares them with `==`, whose result for two + arrays is an array β€” so asking whether two maps are equal raised + `ValueError: the truth value of an array ... is ambiguous`. `frozen=True` + reads as a promise that a value can be compared and hashed, and this is + what makes good on it. + """ + if not isinstance(other, ArrayMap): + return NotImplemented + return ( + self.offset == other.offset + and self.stride == other.stride + and self.index_array.shape == other.index_array.shape + and bool(np.array_equal(self.index_array, other.index_array)) + ) + + def __hash__(self) -> int: + """Hashed by the array's contents, so equal maps hash alike. + + The generated `__hash__` hashed the ndarray itself, which is unhashable; + a map could therefore not go in a set, or key a cache. + """ + return hash( + ( + self.offset, + self.stride, + self.index_array.shape, + self.index_array.tobytes(), + ) + ) + + @property + def dependency_axes(self) -> tuple[int, ...]: + """Every input axis this map varies over: its non-singleton axes. + + One axis means orthogonal, several mean correlated, and none means + the map is degenerate β€” the shape is the single source of truth for + all three. + + Examples + -------- + >>> ArrayMap(index_array=np.array([[4, 0, 2]])).dependency_axes + (1,) + >>> ArrayMap(index_array=np.array([[1, 2], [3, 4]])).dependency_axes + (0, 1) + """ + return _array_map_dependency_axes(self.index_array) + + @property + def dependent_axis(self) -> int | None: + """Return the single input axis an orthogonal `ArrayMap` varies over. + + This is the array's one non-singleton axis, read from the shape β€” the + single source of truth for what a map depends on. The selection layer + collapses a single-coordinate map to a `ConstantMap` + (`array_map_or_constant`), so a non-empty map built by this package always + has at least one dependency axis. + + Returns + ------- + int or None + The axis the map varies over, or `None` when it varies over no input + axis at all β€” an empty map, or a hand-built all-singleton one. `None` + is a valid result, not an error; such maps resolve through the + pointwise (general) path. + + Raises + ------ + ValueError + If the map varies over more than one axis, which makes it correlated + rather than orthogonal. + + Examples + -------- + An `oindex` selection on axis 1 of a rank-2 transform stores its + coordinates full-sized on axis 1 and singleton on axis 0, so the + dependency axis is read straight off the shape: + + >>> m = ArrayMap(index_array=np.array([[4, 0, 2]])) + >>> m.index_array.shape + (1, 3) + >>> m.dependent_axis + 1 + """ + dep = self.dependency_axes + if len(dep) == 1: + return dep[0] + if len(dep) == 0: + return None + raise ValueError( + f"orthogonal ArrayMap must vary over exactly one axis; got dependency axes {dep}" + ) + + def to_json(self) -> OutputIndexMapJSON: + """Convert to the canonical wire form, collapsing a degenerate map. + + A map holding exactly one coordinate, or none at all, is emitted as a + `constant` map β€” see the module note on the wire format in + [`zarr_indexing.json`][zarr_indexing.json]. Both are degenerate: the + first selects one coordinate whatever the input, and the second names + no cell and can only be empty because an input dimension is, so the + emptiness travels in the domain instead. + + Examples + -------- + >>> ArrayMap(np.array([[4], [1], [1]])).to_json()["index_array"] + [[4], [1], [1]] + >>> ArrayMap(np.array([7])).to_json() # degenerate: one coordinate + {'offset': 7} + """ + if self.index_array.size == 1: + value = int(self.index_array.reshape(-1)[0]) + return {"offset": self.offset + self.stride * value} + if self.index_array.size == 0: + return {"offset": 0} + return { + "offset": self.offset, + "stride": self.stride, + "index_array": self.index_array.tolist(), + "index_array_bounds": ["-inf", "+inf"], + } + + +def output_index_map_from_json(data: OutputIndexMapJSON) -> OutputIndexMap: + """Construct the output map a canonical wire form names. + + The wire form is a tagged union β€” `index_array`, then `input_dimension`, + else constant β€” so loading it dispatches to the right kind here rather + than on any one of them. + + Examples + -------- + >>> output_index_map_from_json({"offset": 5}) + ConstantMap(offset=5) + >>> output_index_map_from_json({"offset": 0, "stride": 2, "input_dimension": 1}) + DimensionMap(input_dimension=1, offset=0, stride=2) + """ + from zarr_indexing._wire import lower_index_array + + if "index_array" in data: + return ArrayMap( + index_array=lower_index_array(data["index_array"], "index_array"), + offset=data.get("offset", 0), + stride=data.get("stride", 1), + ) + if "input_dimension" in data: + return DimensionMap( + input_dimension=data["input_dimension"], + offset=data.get("offset", 0), + stride=data.get("stride", 1), + ) + return ConstantMap(offset=data.get("offset", 0)) + + +def array_map_or_constant( + index_array: npt.NDArray[np.integer[Any]], + offset: int = 0, + stride: int = 1, +) -> ArrayMap | ConstantMap: + """An `ArrayMap`, collapsed to the `ConstantMap` it equals when it can be. + + An index array holding exactly one coordinate maps every input cell to the + same place; representing it as a lookup table would leave a map whose shape + names no dependency axis, the one form the shape-derived classifier cannot + read. The selection and composition layers build their array maps through + this helper so that a non-empty `ArrayMap` always varies over at least one + axis. An empty array stays an `ArrayMap`: it maps no cell at all, and the + emptiness lives in the domain that accompanies it. + """ + arr = np.asarray(index_array) + if arr.size == 1: + return ConstantMap(offset=checked_affine(offset, stride, int(arr.reshape(-1)[0]))) + return ArrayMap(index_array=arr, offset=offset, stride=stride) + + +OutputIndexMap = ConstantMap | DimensionMap | ArrayMap diff --git a/src/zarr/v2/_storage/__init__.py b/packages/zarr-indexing/src/zarr_indexing/py.typed similarity index 100% rename from src/zarr/v2/_storage/__init__.py rename to packages/zarr-indexing/src/zarr_indexing/py.typed diff --git a/packages/zarr-indexing/src/zarr_indexing/reader.py b/packages/zarr-indexing/src/zarr_indexing/reader.py new file mode 100644 index 0000000000..8d47d51d21 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/reader.py @@ -0,0 +1,585 @@ +"""Backend reader protocol and built-in system-memory implementations.""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Final, Protocol + +if TYPE_CHECKING: + from collections.abc import Callable + +import numpy as np + +from zarr_indexing._affine import checked_affine +from zarr_indexing.chunk_resolution import ChunkProjection # noqa: TC001 (runtime annotation) +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap, OutputIndexMap +from zarr_indexing.transform import ( + IndexTransform, +) + +__all__ = [ + "BasicReader", + "NumPyReader", + "ReadContext", + "Reader", + "UnitStepReader", + "basic_reader", + "numpy_reader", + "unit_step_reader", +] + + +@dataclass(frozen=True, slots=True) +class ReadContext: + """A source-global transform and optional projection for a partitioned read. + + Examples + -------- + >>> transform = IndexTransform.from_shape((6,))[1:5:2] + >>> context = ReadContext(transform) + >>> context.transform.domain.shape + (2,) + >>> context.projection is None + True + """ + + transform: IndexTransform + """Maps zero-origin output-buffer coordinates to global coordinates in the source.""" + + projection: ChunkProjection | None = None + """The partition plan when this read is one part of a partitioned view, else `None`.""" + + +class Reader(Protocol): + """Backend adapter that fills supplied system-memory result buffers. + + A reader may be shared by every view and part derived from one + [`LazyArray`][zarr_indexing.lazy_array.LazyArray]. Part reads may run + concurrently, so a stateful implementation must synchronize its own + mutable state. `LazyArray` deliberately adds no serialization. + + Examples + -------- + The protocol is not `runtime_checkable`; an object satisfies it by + exposing a conforming `read_into`, as `basic_reader` does: + + >>> transform = IndexTransform.from_shape((6,))[1:5:2] + >>> source = np.arange(6) + >>> out = np.empty(transform.domain.shape, dtype=source.dtype) + >>> basic_reader.read_into(source, ReadContext(transform), out) + >>> out.tolist() + [1, 3] + """ + + def read_into( + self, + source: Any, + context: ReadContext, + out: np.ndarray[Any, Any], + /, + ) -> None: + """Fill `out` with the exact source values selected by `context`. + + `context.transform` maps zero-origin coordinates in the output buffer + to global coordinates in `source`, and its domain shape equals + `out.shape`. `context.projection`, when present, is the corresponding + partition plan: its `chunk_transform` is chunk-local, its + `cell_transform` describes result placement, and its `chunk_domain` + describes the grid cell. Fill every cell in place, preserving the + transform's exact values, order, and dtype, then return `None`. Do not + replace or retain `out`; it may be a strided writable view rather than + an owning array. + + Backend exceptions propagate unchanged. Because callers may resolve + parts concurrently through the same reader object, stateful readers + are responsible for synchronizing their own state. + """ + ... + + +class BasicReader: + """Reader for system-memory sources exposing basic integer/slice indexing. + + Each transform is decomposed into the smallest enclosing positive-slice + slab and a residual transform. The slab is read once with basic indexing, + so fancy or negative-step selections may over-read, and the residual is + then lowered through NumPy system-memory operations into the supplied + buffer. + + Slice results must permit conversion to NumPy system memory. Device arrays + that reject implicit conversion require a custom reader responsible for + transferring values into the supplied system-memory output buffer. + + Examples + -------- + >>> transform = IndexTransform.from_shape((6,))[1:5:2] + >>> source = np.arange(6) + >>> out = np.empty(transform.domain.shape, dtype=source.dtype) + >>> BasicReader().read_into(source, ReadContext(transform), out) + >>> out.tolist() == source[1:5:2].tolist() + True + """ + + __slots__ = () + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + """Read one transform through a positive-slice slab and residual lowering.""" + transform = context.transform + key, residual = _decompose_basic(transform) + block = np.asanyarray(source[key]) + out[...] = _lower(block, residual) + + +class NumPyReader: + """Reader optimized for NumPy system-memory arrays. + + This is the reader selected by + [`LazyArray.from_numpy`][zarr_indexing.lazy_array.LazyArray.from_numpy]. It + applies the complete transform with NumPy operations and is applicable to + `numpy.ndarray` sources, including `numpy.ma.MaskedArray`. + + Examples + -------- + >>> transform = IndexTransform.from_shape((3, 4))[::2, 1:3] + >>> source = np.arange(12).reshape(3, 4) + >>> out = np.empty(transform.domain.shape, dtype=source.dtype) + >>> NumPyReader().read_into(source, ReadContext(transform), out) + >>> out.tolist() + [[1, 2], [9, 10]] + """ + + __slots__ = () + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + """Read one transform through a narrowed slab into `out`.""" + transform = context.transform + key, residual = _decompose_basic(transform) + block = np.asanyarray(source[key]) + out[...] = _lower(block, residual) + + +class UnitStepReader: + """Reader for sources whose basic indexing accepts only step-1 slices. + + Each transform is decomposed into the smallest enclosing ascending + unit-step slab and a residual transform, so the source only ever receives + `slice(start, stop, 1)` on every axis β€” the one form an API without + general strided reads (an FFI binding, an HTTP range endpoint) supports. + `BasicReader` instead pushes strided and reversed slices down, which + reads less but asks more of the source. + + The residual lowering applies strides, reversals, and gathers to the + in-memory block, so a strided selection over-reads its cover by the + stride factor. Partitioning the wrapping + [`LazyArray`][zarr_indexing.lazy_array.LazyArray] (`with_parts`) bounds + each cover by a part. + + Slice results must permit conversion to NumPy system memory, exactly as + for `BasicReader`. + + Examples + -------- + The source below is only ever asked for step-1 slices β€” here the cover + `slice(1, 4, 1)` β€” and the stride is replayed against the block: + + >>> transform = IndexTransform.from_shape((6,))[1:5:2] + >>> source = np.arange(6) + >>> out = np.empty(transform.domain.shape, dtype=source.dtype) + >>> UnitStepReader().read_into(source, ReadContext(transform), out) + >>> out.tolist() + [1, 3] + """ + + __slots__ = () + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + """Read one transform through an ascending unit-step slab into `out`.""" + transform = context.transform + key, residual = _decompose_unit_step(transform) + block = np.asanyarray(source[key]) + out[...] = _lower(block, residual) + + +basic_reader: Final = BasicReader() +numpy_reader: Final = NumPyReader() +unit_step_reader: Final = UnitStepReader() + + +def _take(array: Any, indices: np.ndarray[Any, np.dtype[np.intp]], axis: int) -> Any: + return np.take(array, indices, axis=axis) + + +def _reshape(array: Any, shape: tuple[int, ...]) -> Any: + return np.reshape(array, shape) + + +def _transpose(array: Any, permutation: tuple[int, ...]) -> Any: + return np.transpose(array, permutation) + + +def _expand_dims(array: Any, axis: int) -> Any: + return np.expand_dims(array, axis) + + +def _dimension_map_coords( + m: DimensionMap, transform: IndexTransform +) -> np.ndarray[Any, np.dtype[np.intp]]: + """The storage coordinates a DimensionMap enumerates, in view order.""" + d = m.input_dimension + lo = transform.domain.inclusive_min[d] + hi = transform.domain.exclusive_max[d] + extent = hi - lo + if extent == 0: + return np.empty((0,), dtype=np.intp) + first = checked_affine(m.offset, m.stride, lo) + return checked_affine(first, m.stride, np.arange(extent, dtype=np.intp)) + + +def _array_map_coords(m: ArrayMap) -> np.ndarray[Any, np.dtype[np.intp]]: + """The storage coordinates an ArrayMap enumerates, flattened.""" + return checked_affine(m.offset, m.stride, m.index_array).reshape(-1) + + +def _correlated_map_coords( + m: ArrayMap, broadcast_axes: list[int], broadcast_shape: tuple[int, ...], input_rank: int +) -> np.ndarray[Any, np.dtype[np.intp]]: + """One storage coordinate per point of the correlated block, flattened. + + A correlated `ArrayMap`'s index array carries the transform's full input + rank, with a singleton on every axis it does not vary over β€” including + broadcast axes it shares with the *other* correlated maps but is itself + constant along. Flattening it directly would then yield fewer coordinates + than there are points, so it is reduced to the broadcast block and + broadcast up to it explicitly. + """ + coords = checked_affine(m.offset, m.stride, m.index_array) + if math.prod(broadcast_shape) == 0: + # A zero-extent broadcast axis makes the correlated block empty β€” for + # example an ArrayMap composed over an empty domain, which the package + # promises resolves like any other. The per-axis reshape below cannot + # express that block (a 0-size array does not reshape to the non-zero + # singleton axes), and there is no coordinate to produce anyway. + return np.empty(0, dtype=np.intp) + if coords.ndim == input_rank: + # Drop the axes bound by a slice, which the map is singleton along. + # Removing size-1 axes by reshape preserves element order wherever they + # sit, so no transpose is needed. + coords = coords.reshape(tuple(coords.shape[axis] for axis in broadcast_axes)) + return np.ascontiguousarray(np.broadcast_to(coords, broadcast_shape)).reshape(-1) + + +def _restore_domain_axis_order( + result: Any, axis_input_dims: list[int], domain_shape: tuple[int, ...] +) -> Any: + """Permute `result`'s axes into input-domain order, restoring dropped axes. + + `axis_input_dims[k]` is the input (domain) dimension that axis `k` of + `result` corresponds to. Axes are permuted so that they appear in increasing + domain-dimension order, and any domain dimension no output map depends on is + reinserted at **its own extent**. + + An unreferenced dimension is not always a singleton. A `vindex` coordinate + array with a broadcast axis it does not vary over leaves that axis in the + domain; a later basic index that consumes the axis the array *does* vary + over collapses the map to a `ConstantMap` and leaves the broadcast axis + behind, with whatever extent the basic index gave it β€” including 0. Every + position along such an axis holds the same values, so it is restored by + repeating the block, and an extent of 0 restores an empty result rather than + fabricating a row. + + This is also where NumPy's advanced-index placement rules are absorbed: + whatever order the gather produced, the lowered result always comes back in + the view's own axis order. + """ + if len(set(axis_input_dims)) != len(axis_input_dims): + raise NotImplementedError( + "resolving a transform whose output maps share an input dimension " + "(a diagonal view) is not supported" + ) + order = sorted(range(len(axis_input_dims)), key=lambda k: axis_input_dims[k]) + if order != list(range(len(order))): + result = _transpose(result, tuple(order)) + covered = set(axis_input_dims) + for dim, extent in enumerate(domain_shape): + if dim in covered: + continue + result = _expand_dims(result, dim) + if extent != 1: + result = _take(result, np.zeros(extent, dtype=np.intp), axis=dim) + return result + + +def _lower(array: Any, transform: IndexTransform) -> Any: + """Lower a transform to one pass of array operations over `array`. + + Every read, partitioned or not, goes through this function. The result is + always in the transform's own domain axis order and of exactly its domain + shape. + """ + if math.prod(transform.domain.shape) == 0: + # An empty domain selects nothing, and its maps may legitimately be + # empty along the vanished axes (an ArrayMap composed over an empty + # domain, which the package promises resolves like any other). The + # resolvers below cannot evaluate such maps β€” and have no reason to. + return np.empty(transform.domain.shape, dtype=np.asanyarray(array).dtype) + if transform.index_array_structure == "general": + result = _lower_general(array, transform) + else: + result = _lower_orthogonal(array, transform) + if isinstance(result, np.generic): + # Basic indexing every axis of a NumPy array yields a scalar; `result()` + # documents a zero-dimensional array. + return np.asarray(result) + return result + + +def _lower_orthogonal(array: Any, transform: IndexTransform) -> Any: + """Basic slicing plus one `take` per fancy-indexed axis (an outer product). + + Orthogonal `ArrayMap`s vary over distinct input axes, so gathering them one + axis at a time is exact β€” a `take` along one storage axis leaves every other + axis's coordinates untouched. + """ + outputs = transform.output + gathered: dict[int, np.ndarray[Any, np.dtype[np.intp]]] = {} + for out_dim, m in enumerate(outputs): + if isinstance(m, ArrayMap): + gathered[out_dim] = _array_map_coords(m) + elif isinstance(m, DimensionMap) and m.stride <= 0: + # Reversing and repeating maps have no positive-step slice; gather them. + gathered[out_dim] = _dimension_map_coords(m, transform) + + result = array + for out_dim, coords in gathered.items(): + result = _take(result, coords, axis=out_dim) + + selection: list[Any] = [] + axis_input_dims: list[int] = [] + for out_dim, m in enumerate(outputs): + if isinstance(m, ConstantMap): + selection.append(m.offset) + continue + if out_dim in gathered: + selection.append(slice(None)) + else: + assert isinstance(m, DimensionMap) + d = m.input_dimension + lo = transform.domain.inclusive_min[d] + hi = transform.domain.exclusive_max[d] + selection.append(slice(m.offset + m.stride * lo, m.offset + m.stride * hi, m.stride)) + if isinstance(m, ArrayMap): + axis = m.dependent_axis + if axis is None: + raise NotImplementedError( + "resolving an orthogonal ArrayMap that varies over no input " + "dimension is not supported; such a map should have been " + "collapsed to a ConstantMap" + ) + axis_input_dims.append(axis) + else: + axis_input_dims.append(m.input_dimension) + result = result[tuple(selection)] + return _restore_domain_axis_order(result, axis_input_dims, transform.domain.shape) + + +def _lower_general(array: Any, transform: IndexTransform) -> Any: + """Flatten the index-array axes, gather the points once, reshape back. + + The general path for every index-array structure the orthogonal resolver + cannot take: correlated (`vindex`) maps, maps sharing an input axis (a + diagonal gather), and mixtures of correlated and orthogonal maps. All + index arrays are treated as lookup tables over the joint block of + non-slice axes: the corresponding storage axes are moved to the front and + flattened, the per-point coordinates are converted to offsets into that + flat axis with row-major strides, and a single `take` collects them. + """ + outputs = transform.output + correlated_dims = [d for d, m in enumerate(outputs) if isinstance(m, ArrayMap)] + + slice_input_dims = {m.input_dimension for m in outputs if isinstance(m, DimensionMap)} + broadcast_axes = [d for d in range(transform.input_rank) if d not in slice_input_dims] + broadcast_shape = tuple(transform.domain.shape[d] for d in broadcast_axes) + + for d in correlated_dims: + arr_map = outputs[d] + assert isinstance(arr_map, ArrayMap) + # The axes the array varies over (its non-singleton axes; see + # transform._array_map_dependency_axes) must all live in the block. + dependency = (axis for axis, size in enumerate(arr_map.index_array.shape) if size > 1) + if any(a not in broadcast_axes for a in dependency): + # Reachable only by hand-building a transform: no selection binds + # the same input axis to both a slice map and an index array. + raise NotImplementedError( + "resolving a transform whose index array varies over an input " + "dimension also bound by a slice map is not supported" + ) + + # Gather any reversing or repeating slice axis first, then take the basic-slice + # cut. The correlated axes keep their full extent: their coordinates are absolute. + gathered: dict[int, np.ndarray[Any, np.dtype[np.intp]]] = { + d: _dimension_map_coords(m, transform) + for d, m in enumerate(outputs) + if isinstance(m, DimensionMap) and m.stride <= 0 + } + result = array + for out_dim, coords in gathered.items(): + result = _take(result, coords, axis=out_dim) + + selection: list[Any] = [] + residual_axis_dims: list[int] = [] + correlated_positions: list[int] = [] + residual_positions: list[int] = [] + axis = 0 + for out_dim, m in enumerate(outputs): + if isinstance(m, ConstantMap): + selection.append(m.offset) + continue + if out_dim in correlated_dims: + selection.append(slice(None)) + correlated_positions.append(axis) + elif out_dim in gathered: + selection.append(slice(None)) + residual_positions.append(axis) + assert isinstance(m, DimensionMap) + residual_axis_dims.append(m.input_dimension) + else: + assert isinstance(m, DimensionMap) + d = m.input_dimension + lo = transform.domain.inclusive_min[d] + hi = transform.domain.exclusive_max[d] + selection.append(slice(m.offset + m.stride * lo, m.offset + m.stride * hi, m.stride)) + residual_positions.append(axis) + residual_axis_dims.append(d) + axis += 1 + result = result[tuple(selection)] + + # Correlated axes to the front, in output order, so the flattening strides + # below match the order the coordinates are combined in. + perm = tuple(correlated_positions) + tuple(residual_positions) + if perm != tuple(range(len(perm))): + result = _transpose(result, perm) + + n_corr = len(correlated_dims) + corr_sizes = tuple(int(s) for s in result.shape[:n_corr]) + tail_shape = tuple(int(s) for s in result.shape[n_corr:]) + result = _reshape(result, (math.prod(corr_sizes), *tail_shape)) + + flat_index = np.zeros(math.prod(broadcast_shape), dtype=np.intp) + stride = 1 + for position in range(n_corr - 1, -1, -1): + m = outputs[correlated_dims[position]] + assert isinstance(m, ArrayMap) + flat_index = flat_index + ( + _correlated_map_coords(m, broadcast_axes, broadcast_shape, transform.input_rank) + * stride + ) + stride *= corr_sizes[position] + + result = _take(result, flat_index, axis=0) + result = _reshape(result, broadcast_shape + tail_shape) + return _restore_domain_axis_order( + result, list(broadcast_axes) + residual_axis_dims, transform.domain.shape + ) + + +def _push_slice_for_dimension_map( + m: DimensionMap, transform: IndexTransform +) -> tuple[slice, DimensionMap]: + """The positive-step slice covering a `DimensionMap`, and its block-local map. + + A negative step is read forwards and reversed by the residual: a source is + only ever asked for a slice that walks upwards, which is the one form every + array-like agrees on. + """ + d = m.input_dimension + lo = transform.domain.inclusive_min[d] + hi = max(transform.domain.exclusive_max[d], lo) + if hi == lo: + return slice(0, 0, 1), DimensionMap(input_dimension=d, offset=-lo, stride=1) + first = checked_affine(m.offset, m.stride, lo) + last = checked_affine(m.offset, m.stride, hi - 1) + if m.stride > 0: + return ( + slice(first, last + 1, m.stride), + DimensionMap(input_dimension=d, offset=-lo, stride=1), + ) + if m.stride == 0: + return ( + slice(first, first + 1, 1), + DimensionMap(input_dimension=d, offset=0, stride=0), + ) + # Descending: the block holds the same coordinates in ascending order, so + # the residual walks it backwards from the last block position. + return ( + slice(last, first + 1, -m.stride), + DimensionMap(input_dimension=d, offset=hi - 1, stride=-1), + ) + + +def _push_unit_slice_for_dimension_map( + m: DimensionMap, transform: IndexTransform +) -> tuple[slice, DimensionMap]: + """The unit-step slice covering a `DimensionMap`, and its block-local map. + + Strides and reversals stay in the residual: the source is only ever asked + for a contiguous ascending slice, and the original stride is replayed + against the in-memory block. The cover therefore over-reads a strided + selection by its stride factor, which is the price of a source that + accepts nothing but `slice(start, stop, 1)`. + """ + d = m.input_dimension + lo = transform.domain.inclusive_min[d] + hi = max(transform.domain.exclusive_max[d], lo) + if hi == lo: + return slice(0, 0, 1), DimensionMap(input_dimension=d, offset=-lo, stride=1) + first = checked_affine(m.offset, m.stride, lo) + if m.stride == 0: + return ( + slice(first, first + 1, 1), + DimensionMap(input_dimension=d, offset=0, stride=0), + ) + last = checked_affine(m.offset, m.stride, hi - 1) + origin = min(first, last) + return ( + slice(origin, max(first, last) + 1, 1), + DimensionMap(input_dimension=d, offset=m.offset - origin, stride=m.stride), + ) + + +def _decompose_basic(transform: IndexTransform) -> tuple[tuple[slice, ...], IndexTransform]: + return _decompose(transform, _push_slice_for_dimension_map) + + +def _decompose_unit_step(transform: IndexTransform) -> tuple[tuple[slice, ...], IndexTransform]: + return _decompose(transform, _push_unit_slice_for_dimension_map) + + +def _decompose( + transform: IndexTransform, + push_dimension_map: Callable[[DimensionMap, IndexTransform], tuple[slice, DimensionMap]], +) -> tuple[tuple[slice, ...], IndexTransform]: + key: list[slice] = [] + residual: list[OutputIndexMap] = [] + for output_map in transform.output: + if isinstance(output_map, ConstantMap): + coordinate = checked_affine(output_map.offset, 0, 0) + key.append(slice(coordinate, coordinate + 1, 1)) + residual.append(ConstantMap(offset=0)) + elif isinstance(output_map, DimensionMap): + pushed, local = push_dimension_map(output_map, transform) + key.append(pushed) + residual.append(local) + else: + coordinates = checked_affine( + output_map.offset, output_map.stride, output_map.index_array + ) + if coordinates.size == 0: + key.append(slice(0, 0, 1)) + local_index = coordinates + else: + origin = int(coordinates.min()) + key.append(slice(origin, int(coordinates.max()) + 1, 1)) + local_index = checked_affine(-origin, 1, coordinates) + residual.append(ArrayMap(index_array=local_index)) + return tuple(key), IndexTransform(domain=transform.domain, output=tuple(residual)) diff --git a/packages/zarr-indexing/src/zarr_indexing/testing/__init__.py b/packages/zarr-indexing/src/zarr_indexing/testing/__init__.py new file mode 100644 index 0000000000..e98d051900 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/testing/__init__.py @@ -0,0 +1,57 @@ +"""Test support for projects whose arrays are read through `LazyArray`. + +A Hypothesis state machine that composes indexing steps onto a `LazyArray` +wrapping your array and checks every step against NumPy +([`stateful`][zarr_indexing.testing.stateful]), and the selection strategies it +draws from, exported on their own for a project that has its own harness +([`strategies`][zarr_indexing.testing.strategies]). + +```python +from zarr_indexing.testing import ChainedIndexingStateMachine, state_machine_test + +class MyArrayIndexing(ChainedIndexingStateMachine): + def make_source(self, data): + array = my_format.create(shape=data.shape, dtype=data.dtype) + array[:] = data + return array + +TestMyArrayIndexing = state_machine_test(MyArrayIndexing) +``` + +This subpackage needs `hypothesis`, which the rest of `zarr_indexing` does not: +install it with the `testing` extra (`pip install zarr-indexing[testing]`). +""" + +from zarr_indexing.testing.stateful import ( + DEFAULT_DATA, + DEFAULT_PARTITIONINGS, + DEFAULT_SETTINGS, + ChainedIndexingStateMachine, + apply_selection, + outer_selection, + repartition, + state_machine_test, +) +from zarr_indexing.testing.strategies import ( + basic_selections, + masks, + orthogonal_selections, + slice_selections, + vectorized_selections, +) + +__all__ = [ + "DEFAULT_DATA", + "DEFAULT_PARTITIONINGS", + "DEFAULT_SETTINGS", + "ChainedIndexingStateMachine", + "apply_selection", + "basic_selections", + "masks", + "orthogonal_selections", + "outer_selection", + "repartition", + "slice_selections", + "state_machine_test", + "vectorized_selections", +] diff --git a/packages/zarr-indexing/src/zarr_indexing/testing/stateful.py b/packages/zarr-indexing/src/zarr_indexing/testing/stateful.py new file mode 100644 index 0000000000..4458d7922a --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/testing/stateful.py @@ -0,0 +1,380 @@ +"""A stateful property test for indexing an array through `LazyArray`. + +`ChainedIndexingStateMachine` composes indexing steps onto a `LazyArray` +wrapping *your* array β€” `lazy[...]`, `lazy.oindex[...]`, `lazy.vindex[...]`, +each step applied to the view the last one produced β€” while applying the same +steps to a NumPy array holding the same values. After every step the view must +still agree with that model three ways: its shape, its `result()`, and the +assembly of its `parts()`. + +Point it at an array by subclassing and overriding `make_source`: + +```python +from zarr_indexing.testing import ChainedIndexingStateMachine, state_machine_test + +class MyArrayIndexing(ChainedIndexingStateMachine): + def make_source(self, data): + array = my_format.create(shape=data.shape, dtype=data.dtype) + array[:] = data + return array + +TestMyArrayIndexing = state_machine_test(MyArrayIndexing) +``` + +`data`, `partitionings`, and `readers` are class attributes; override any of +them to widen or narrow what is drawn. The base class needs no `make_source` at +all β€” left alone it wraps the NumPy array itself, which is a useful smoke test +of this package but says nothing about yours. + +What it is checking +------------------- +The parts invariant is the one with teeth. +[`Partition`][zarr_indexing.lazy_array.Partition] documents +`out[part.out_selection] = part.view.result()` as the assembly procedure, so +this checks that literally: a part's values must arrive at exactly the shape its +`out_selection` addresses β€” not merely a shape that broadcasts into it β€” land +there, and cover the view once. Checking through `result()` alone would prove +only that `result()` is self-consistent. + +The `choose_reader` rule draws a reader and applies it to the view, so the +execution strategy becomes part of the chain. Every reader listed by a subclass +must preserve the NumPy model for its source. The universal `basic_reader` is +always exercised, even when a subclass lists only specialized readers; with no +declared readers it is the sole strategy drawn. + +Requires the `testing` extra (`pip install zarr-indexing[testing]`). +""" + +from __future__ import annotations + +import math +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any, ClassVar + +import numpy as np +from hypothesis import HealthCheck, settings +from hypothesis import strategies as st +from hypothesis.stateful import RuleBasedStateMachine, initialize, invariant, precondition, rule + +from zarr_indexing.lazy_array import LazyArray +from zarr_indexing.reader import Reader, basic_reader +from zarr_indexing.testing.strategies import ( + basic_selections, + orthogonal_selections, + slice_selections, + vectorized_selections, +) + +if TYPE_CHECKING: + from zarr_indexing.boundary import SelectionMode + +__all__ = [ + "DEFAULT_DATA", + "DEFAULT_PARTITIONINGS", + "DEFAULT_SETTINGS", + "ChainedIndexingStateMachine", + "apply_selection", + "outer_selection", + "repartition", + "state_machine_test", +] + +DEFAULT_DATA = np.arange(7 * 5 * 4, dtype=np.int64).reshape(7, 5, 4) +"""The values the source holds by default: distinct, so a misplaced cell shows.""" + +DEFAULT_PARTITIONINGS: tuple[Any, ...] = ( + None, + (2, 2, 2), + (7, 5, 4), + (3, 2, 3), + ((3, 3, 1), (2, 2, 1), (3, 1)), + (4, 3, 3), +) +"""Partitionings to read under: a single whole-array part, uniform boxes of +several shapes (some of which do not divide the extent), and explicit per-axis +sizes. Boxes that straddle whatever the source declares are deliberate β€” they +cost extra I/O but must not change an answer.""" + +DEFAULT_SETTINGS = settings( + max_examples=250, + stateful_step_count=10, + deadline=None, + suppress_health_check=[ + HealthCheck.data_too_large, + HealthCheck.filter_too_much, + HealthCheck.too_slow, + ], +) +"""Enough examples to find a defect reachable only through a narrow chain, at a +few seconds per run when there is nothing to find. Every step is followed by +checks that each materialize the whole view, so the budget buys examples rather +than long chains β€” a chain runs out of axes to index within a few steps anyway. + +`filter_too_much` is suppressed because a chain that reaches a rank-0 view +leaves only `repartition` enabled, so a run that opens there is discarded.""" + + +# --------------------------------------------------------------------------- # +# The NumPy model +# --------------------------------------------------------------------------- # + + +def outer_selection(array: Any, selection: Sequence[Any]) -> Any: + """Apply an orthogonal selection to a NumPy array: the outer product of its axes. + + NumPy has no operator for this, so the model is built from `numpy.ix_`. + Scalar integers are basic indices β€” NumPy applies them first and drops the + axis β€” so they are peeled off before the outer product is formed. + """ + + def is_scalar(sel: Any) -> bool: + return isinstance(sel, (int, np.integer)) and not isinstance(sel, bool) + + scalars = tuple(sel if is_scalar(sel) else slice(None) for sel in selection) + reduced = array[scalars] + axes = [ + np.arange(size)[sel] + for size, sel in zip(reduced.shape, [s for s in selection if not is_scalar(s)], strict=True) + ] + if len(axes) == 0: + return reduced + return reduced[np.ix_(*axes)] + + +def apply_selection(array: Any, selection: tuple[Any, ...], mode: SelectionMode) -> Any: + """Apply a selection to a NumPy array in the given mode β€” the model a view is checked against. + + NumPy's own semantics *are* basic and vectorized indexing, so only the + orthogonal mode needs building (see `outer_selection`). + """ + if mode == "orthogonal": + return outer_selection(array, selection) + return array[selection] + + +def state_machine_test( + machine: type[RuleBasedStateMachine], *, config: settings = DEFAULT_SETTINGS +) -> Any: + """The pytest-collectable `TestCase` for a machine, with settings applied. + + Hypothesis builds a fresh `TestCase` per state-machine class, so settings + set on a base class do not reach a subclass's; this applies them where they + land. Assign the result to a module-level name beginning with `Test`. + """ + case = machine.TestCase + case.settings = config + return case + + +def repartition(view: LazyArray, parts: Any) -> LazyArray: + """Apply one of `partitionings` to a view. + + The three partitioning spellings are three named methods, so a list holding + a mix of them needs a dispatch somewhere. Choosing among them is what a test + harness drawing from that list is doing, so it lives here rather than being + pushed back into the public API as a type-inspecting parameter. + """ + if parts is None: + return view.unpartitioned() + if any(isinstance(entry, Sequence) for entry in parts): + return view.with_parts_per_axis(parts) + return view.with_parts(parts) + + +# --------------------------------------------------------------------------- # +# The machine +# --------------------------------------------------------------------------- # + +_SOURCE = "_zarr_indexing_cached_source" + + +class ChainedIndexingStateMachine(RuleBasedStateMachine): + """Indexing steps composed onto one `LazyArray`, against NumPy as the model. + + Subclass and override `make_source` to point it at your own array. See the + module docstring for the shape of that subclass and for what the invariants + check. + + Attributes + ---------- + data + The values the source holds, and the model every step is checked + against. Any shape and dtype NumPy supports; every axis must be + non-empty. + partitionings + Drawn once per run, before any indexing: `with_parts` is a pure setter + that carries through composition untouched and is read only when a view + resolves, so choosing it up front reaches the same states choosing it + mid-chain does, and spends the whole step budget on indexing. + readers + Execution strategies `choose_reader` may draw. Every listed reader must + preserve the model for the source. `basic_reader` is always included; + `None` means the reader already carried by the constructed view. + """ + + data: ClassVar[Any] = DEFAULT_DATA + partitionings: ClassVar[Sequence[Any]] = DEFAULT_PARTITIONINGS + readers: ClassVar[Sequence[Reader] | None] = None + + def make_source(self, data: Any) -> Any: + """Build the array under test, holding `data`. + + Called once per machine class and cached, not once per example: an + example is cheap and a source may not be. The machine only ever reads, + so the same object serves every run β€” but it must therefore not be + mutated by anything else while the test runs. + + The default returns `data` itself, so an unsubclassed machine exercises + this package against NumPy. + """ + return data + + def __init__(self) -> None: + super().__init__() + cls = type(self) + self.model: Any = np.asarray(cls.data) + source = cls.__dict__.get(_SOURCE) + if source is None: + source = self.make_source(self.model) + setattr(cls, _SOURCE, source) + self.view = LazyArray(source) + self.reader_choices = _reader_set(self.view, cls.readers) + self.chain: list[tuple[str, Any]] = [] + + def _indexable(self) -> bool: + """Whether there is anything left to index. + + A rank-0 or empty view takes no further step β€” NumPy would reject one + too β€” so the chain ends there, and the invariants keep checking. + """ + return self.model.ndim > 0 and self.model.size > 0 + + def _step(self, mode: SelectionMode, selection: tuple[Any, ...]) -> None: + self.chain.append((mode, selection)) + self.model = apply_selection(self.model, selection, mode) + if mode == "basic": + self.view = self.view.lazy[selection] + elif mode == "orthogonal": + self.view = self.view.lazy.oindex[selection] + else: + self.view = self.view.lazy.vindex[selection] + + # -- rules -------------------------------------------------------------- + + @initialize(data=st.data()) + def choose_partitioning(self, data: st.DataObject) -> None: + """Fix how the read is broken up, before any indexing.""" + parts = data.draw(st.sampled_from(list(type(self).partitionings))) + self.view = repartition(self.view, parts) + self.chain.append(("parts", parts)) + + @precondition(lambda self: self._indexable()) + @rule(data=st.data()) + def basic(self, data: st.DataObject) -> None: + self._step("basic", data.draw(basic_selections(self.model.shape))) + + @precondition(lambda self: self._indexable()) + @rule(data=st.data()) + def orthogonal(self, data: st.DataObject) -> None: + self._step("orthogonal", data.draw(orthogonal_selections(self.model.shape))) + + @precondition(lambda self: self._indexable()) + @rule(data=st.data()) + def vectorized(self, data: st.DataObject) -> None: + self._step("vectorized", data.draw(vectorized_selections(self.model.shape))) + + @precondition(lambda self: self._indexable()) + @rule(data=st.data()) + def slices_only(self, data: st.DataObject) -> None: + """An `oindex` step carrying only slices is not a fancy selection. + + It narrows the view's own axes and composes like basic indexing. Drawn + as its own rule so that narrowing an existing index array by slices β€” + a distinct code path from narrowing it with coordinates β€” stays + exercised at full weight. + """ + self._step("orthogonal", data.draw(slice_selections(self.model.shape))) + + @rule(data=st.data()) + def choose_reader(self, data: st.DataObject) -> None: + """Read the rest of the chain through another conforming strategy.""" + reader = data.draw(st.sampled_from(list(self.reader_choices))) + self.view = self.view.with_reader(reader) + self.chain.append(("reader", type(reader).__qualname__)) + + @precondition(lambda self: not self._indexable()) + @rule(data=st.data()) + def repartition(self, data: st.DataObject) -> None: + """Re-box a chain that has run out of axes to index. + + Something must stay enabled once the view is rank-0 or empty, or + Hypothesis has no move to make and abandons the run. Re-boxing is the + useful thing to do there: it changes nothing the invariants may see, and + a rank-0 view read through every partitioning is exactly the state a + collapsed correlated selection reaches. + """ + parts = data.draw(st.sampled_from(list(type(self).partitionings))) + self.view = repartition(self.view, parts) + self.chain.append(("parts", parts)) + + # -- invariants --------------------------------------------------------- + + @invariant() + def the_view_has_the_models_shape(self) -> None: + assert self.view.shape == self.model.shape, self.chain + + @invariant() + def result_matches_the_model(self) -> None: + np.testing.assert_array_equal( + np.asarray(self.view.result()), self.model, err_msg=str(self.chain) + ) + + @invariant() + def parts_tile_the_view(self) -> None: + """The documented assembly, run literally. + + Every part's values arrive at exactly the shape its `out_selection` + addresses β€” not merely a shape that broadcasts into it β€” and together + the parts cover the view once. + """ + assembled = np.zeros(self.view.shape, dtype=self.view.dtype) + hits = np.zeros(self.view.shape, dtype=np.int64) + for part in self.view.parts(): + value = np.asarray(part.view.result()) + assert value.shape == assembled[part.out_selection].shape, ( + f"part {part.base_coords} carries {value.shape} for an out_selection " + f"addressing {assembled[part.out_selection].shape}: {self.chain}" + ) + # `is_complete` is what a consumer reads to decide it may take a + # whole-box read and skip assembling anything, so a wrongly-`True` + # one is the silent-corruption case. Asserted one way only: the flag + # is documented as conservative, free to say `False` about a part it + # does cover (a strided walk over a one-cell box, a fancy axis that + # happens to enumerate everything), and only the claim to cover + # everything has to be earned. Both quantities are already in hand + # here, and nothing else in the suite compares them. + if part.is_complete: + box_cells = math.prod(stop - start for start, stop in part.box) + assert value.size == box_cells, ( + f"part {part.base_coords} reports is_complete but carries " + f"{value.size} of its box's {box_cells} cells: {self.chain}" + ) + assembled[part.out_selection] = value + np.add.at(hits, part.out_selection, 1) + + np.testing.assert_array_equal(assembled, self.model, err_msg=str(self.chain)) + np.testing.assert_array_equal( + hits, np.ones(self.view.shape, dtype=np.int64), err_msg=str(self.chain) + ) + + +def _reader_set(view: LazyArray, declared: Sequence[Reader] | None) -> tuple[Reader, ...]: + """The readers `choose_reader` draws from, `basic_reader` always among them.""" + readers = list(declared) if declared is not None else [view.reader] + if all(reader is not basic_reader for reader in readers): + readers.insert(0, basic_reader) + unique: list[Reader] = [] + for reader in readers: + if all(reader is not existing for existing in unique): + unique.append(reader) + return tuple(unique) diff --git a/packages/zarr-indexing/src/zarr_indexing/testing/strategies.py b/packages/zarr-indexing/src/zarr_indexing/testing/strategies.py new file mode 100644 index 0000000000..63a3d351a9 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/testing/strategies.py @@ -0,0 +1,207 @@ +"""Hypothesis strategies for the selections `LazyArray` accepts. + +Each strategy takes the shape of the array being indexed and generates one +selection for it β€” an index tuple with one entry per axis, in the spelling its +mode expects. They are the generators behind +[`ChainedIndexingStateMachine`][zarr_indexing.testing.stateful.ChainedIndexingStateMachine] +and are exported on their own for a project that has its own test harness and +wants only the hard part. + +```python +from hypothesis import given, strategies as st +from zarr_indexing.testing.strategies import basic_selections + +@given(selection=basic_selections((7, 5, 4))) +def test_my_array_slices_like_numpy(selection): + assert_array_equal(my_array[selection], reference[selection]) +``` + +Every axis of `shape` must be non-empty: a selection over an axis of extent 0 +has no coordinates to draw. Filter or narrow the shape before calling. + +Requires the `testing` extra (`pip install zarr-indexing[testing]`). +""" + +from __future__ import annotations + +import operator +from typing import TYPE_CHECKING, Any + +import numpy as np +from hypothesis import strategies as st + +if TYPE_CHECKING: + from collections.abc import Callable + +__all__ = [ + "basic_selections", + "empty_masks", + "masks", + "orthogonal_selections", + "slice_selections", + "vectorized_selections", +] + + +def _entries(shape: tuple[int, ...], entry: Callable[[int], st.SearchStrategy[Any]]) -> Any: + """One `entry` strategy per axis, as an index tuple.""" + return st.tuples(*[entry(size) for size in shape]) + + +def _basic_entry(size: int) -> st.SearchStrategy[Any]: + steps = st.integers(1, 3) + return st.one_of( + # A scalar integer drops its axis, in every mode, exactly as NumPy does. + st.integers(-size, size - 1), + st.builds(slice, st.integers(0, size), st.integers(0, size), steps), + # Downward. The start is drawn from below `-size` as well, where the walk + # begins off the front and selects nothing β€” a case that reads as an + # ordinary negative index but is empty β€” and a stop that falls off the + # front is spelled `None`. + st.builds( + slice, + st.integers(-2 * size - 1, size - 1), + st.none() | st.integers(0, size), + steps.map(operator.neg), + ), + st.just(slice(None)), + ) + + +def _orthogonal_entry(size: int) -> st.SearchStrategy[Any]: + """One axis of an `oindex` selection. + + The slices carry a step and are free to stop early. Drawing them as + `slice(start, size)` alone meant no strided or reversed slice ever reached + `oindex`, and no orthogonal selection ever stopped short of the axis end. + + An empty coordinate list is drawn too. It selects nothing, which is legal + and is exactly the shape that lost its axis on the way through JSON β€” but + with `min_size=1` no fancy selection was ever empty. + """ + coordinate = st.integers(-size, size - 1) + return st.one_of( + coordinate, + st.lists(coordinate, min_size=1, max_size=4), + st.just([]), + masks((size,)), + empty_masks((size,)), + st.builds( + slice, + st.integers(0, size - 1), + st.integers(0, size) | st.none(), + st.integers(1, 3) | st.integers(-3, -1), + ), + ) + + +def _slice_entry(size: int) -> st.SearchStrategy[slice]: + return st.one_of( + st.builds(slice, st.integers(0, size - 1), st.just(size), st.integers(1, 2)), + st.just(slice(None, None, -1)), + st.just(slice(None)), + ) + + +@st.composite +def masks(draw: st.DrawFn, shape: tuple[int, ...]) -> np.ndarray[Any, np.dtype[np.bool_]]: + """Boolean masks over `shape`, each selecting at least one cell. + + An all-False mask is legal but is a separate concern β€” it empties the view, + and a chain of selections is more interesting when every step leaves + something to index β€” so one cell is always forced True. + """ + size = int(np.prod(shape)) + flags = np.array(draw(st.lists(st.booleans(), min_size=size, max_size=size))) + flags[draw(st.integers(0, size - 1))] = True + return flags.reshape(shape) + + +def empty_masks(shape: tuple[int, ...]) -> st.SearchStrategy[np.ndarray[Any, np.dtype[np.bool_]]]: + """The all-False mask over `shape` β€” a fancy selection that empties the view. + + Split out from `masks`, which forces a cell True so a chain has something + left to index at the next step. Drawn on its own because an empty fancy + selection is a shape the code paths treat separately, and nothing generated + one. + """ + return st.just(np.zeros(shape, dtype=np.bool_)) + + +def basic_selections(shape: tuple[int, ...]) -> st.SearchStrategy[tuple[Any, ...]]: + """Basic selections: one scalar integer or slice per axis. + + Slices run in both directions, including the two empty spellings β€” a + forward slice whose stop precedes its start, and a backward one whose start + is off the front of the axis. + """ + return _entries(shape, _basic_entry) + + +def orthogonal_selections(shape: tuple[int, ...]) -> st.SearchStrategy[tuple[Any, ...]]: + """Orthogonal (`oindex`) selections: an outer product of per-axis choices. + + Each axis draws a scalar, a coordinate list (unsorted, with duplicates), a + boolean mask, or a slice. + """ + return _entries(shape, _orthogonal_entry) + + +def slice_selections(shape: tuple[int, ...]) -> st.SearchStrategy[tuple[Any, ...]]: + """Selections of slices alone, for the `oindex` spelling that carries no coordinates. + + Such a step is not a fancy selection β€” it narrows the view's own axes and + composes like basic indexing β€” so it is legal after a fancy step, where + genuine coordinates are not. The starts reach past the origin, which is what + distinguishes a step that walks an existing index array's dependency axes + from one that walks its broadcast singletons. + """ + return _entries(shape, _slice_entry) + + +@st.composite +def vectorized_selections(draw: st.DrawFn, shape: tuple[int, ...]) -> tuple[Any, ...]: + """Vectorized (`vindex`) selections over a leading or trailing block of axes. + + `vindex` is coordinate-only β€” it rejects a slice outright β€” so a partial + selection names its axes by position: a leading block, or a trailing one + reached through an ellipsis. Either a single boolean mask spanning the whole + covered block, or one entry per axis, each a coordinate array or a scalar + (a scalar being a basic index NumPy applies before the coordinates). + """ + ndim = len(shape) + trailing = draw(st.booleans()) + count = draw(st.integers(1, ndim)) + axes = range(ndim - count, ndim) if trailing else range(count) + sizes = [shape[axis] for axis in axes] + + entries: list[Any] + if draw(st.booleans()): + entries = [draw(masks(tuple(sizes)))] + else: + # The coordinate arrays share one shape, which is what makes the + # selection correlated. That shape is not always one-dimensional: a + # vectorized read of a (2, 3) block of points is an ordinary thing to + # ask for and produces a result of that rank. Drawing only 1-D arrays + # meant no rank-raising vindex was ever generated β€” and a length of 0 + # covers the empty case the same way `_orthogonal_entry` does. + coordinate_shape = draw( + st.one_of( + st.integers(0, 4).map(lambda length: (length,)), + st.tuples(st.integers(1, 2), st.integers(1, 3)), + ) + ) + entries = [ + draw( + st.one_of( + st.integers(-size, size - 1), + st.lists( + st.integers(-size, size - 1), + min_size=int(np.prod(coordinate_shape)), + max_size=int(np.prod(coordinate_shape)), + ).map(lambda values: np.array(values, dtype=np.intp).reshape(coordinate_shape)), + ) + ) + for size in sizes + ] + return (Ellipsis, *entries) if trailing else tuple(entries) diff --git a/packages/zarr-indexing/src/zarr_indexing/transform.py b/packages/zarr-indexing/src/zarr_indexing/transform.py new file mode 100644 index 0000000000..a8a5963a26 --- /dev/null +++ b/packages/zarr-indexing/src/zarr_indexing/transform.py @@ -0,0 +1,1941 @@ +"""Index transforms β€” composable, lazy coordinate mappings. + +An `IndexTransform` pairs an **input domain** (the coordinates a user sees) +with a tuple of **output maps** (the output coordinates those inputs map to). +One output map per output dimension. See `output_map.py` for the three +output map types. + +Key operations: + +- **Indexing** (`transform[2:8]`, `.oindex[idx]`, `.vindex[idx]`) β€” + produces a new transform with a narrower input domain and adjusted output + maps. No I/O occurs. This is how lazy slicing works. + +- **intersect(output_domain)** β€” restrict to output coordinates within a + region. This is chunk resolution: "which of my coordinates fall in this + chunk?" + +- **translate(shift)** β€” shift all output coordinates. This makes coordinates + chunk-local: "express my coordinates relative to the chunk origin." + +- **`transform.compose(inner)`** β€” chain two transforms into one. + +The transform is the atomic unit that connects user-facing indexing to +chunk-level I/O. A wrapper holds one β€” `LazyArray` starts from the identity β€” +and `.lazy[...]` composes a new transform lazily rather than reading. Reading +resolves the transform against the chunk grid via intersect + translate. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Literal, cast + +import numpy as np + +from zarr_indexing._affine import checked_affine +from zarr_indexing._selector import as_scalar_index, require_index +from zarr_indexing.boundary import validate_advanced_selection +from zarr_indexing.domain import IndexDomain +from zarr_indexing.errors import BoundsCheckError, VindexInvalidSelectionError +from zarr_indexing.output_map import ( + ArrayMap, + ConstantMap, + DimensionMap, + OutputIndexMap, + array_map_or_constant, +) + +if TYPE_CHECKING: + from collections.abc import Sequence + + import numpy.typing as npt + + from zarr_indexing.json import IndexTransformJSON + + +@dataclass(frozen=True, slots=True) +class _PointOutOfBounds(Exception): + """Internal signal from the shared point kernel: one coordinate left the domain. + + Never escapes this module. `apply` and `apply_many` format it as the + public `BoundsCheckError`, each in its own vocabulary β€” the kernel knows + batches, but a single-point caller must never hear about them. + """ + + dimension: int + value: int + lower: int + upper: int + batch_position: tuple[int, ...] + + +@dataclass(frozen=True, slots=True) +class IndexTransform: + """A composable mapping from input coordinates to output coordinates. + + An `IndexTransform` has: + + - `domain`: an `IndexDomain` describing the valid input coordinates + (the result's coordinate range, possibly with non-zero origin). + - `output`: a tuple of output maps (one per output dimension), each + describing which output coordinates the inputs touch. + + In array-indexing terms: `domain` describes the coordinates of the result + array an indexing operation produces, and `output` is the rule relating + each result coordinate to a coordinate in the source. Note the direction β€” + the transform's input side is the result, its output side addresses the + source; the coordinate mapping runs opposite to the data flow. + + Indexing an existing transform composes a new one without I/O. + + Examples + -------- + The operation "every other element of a 100-element array, starting at + index 0" β€” `array[::2]` β€” is a 50-cell domain whose cell `i` reads + output coordinate `2 * i`: + + >>> domain = IndexDomain.from_shape((50,)) + >>> output = (DimensionMap(input_dimension=0, offset=0, stride=2),) + >>> transform = IndexTransform(domain=domain, output=output) + >>> transform.apply((0,)), transform.apply((1,)), transform.apply((49,)) + ((0,), (2,), (98,)) + + The selection compiler derives the identical transform from the source's + shape and the slice: + + >>> transform == IndexTransform.from_shape((100,))[::2] + True + """ + + domain: IndexDomain + """The input domain: the request coordinates this transform accepts.""" + + output: tuple[OutputIndexMap, ...] + """One output map per output dimension, each producing that dimension's coordinate.""" + + def __post_init__(self) -> None: + for i, m in enumerate(self.output): + if isinstance(m, DimensionMap): + if m.input_dimension < 0 or m.input_dimension >= self.domain.ndim: + raise ValueError( + f"output[{i}].input_dimension = {m.input_dimension} " + f"is out of range for input rank {self.domain.ndim}" + ) + elif isinstance(m, ArrayMap): + # An index array carries the transform's full input rank: the axis + # a map varies over is full-sized, every other axis a singleton. + # The rank is what makes the dependency axes readable from the + # shape, so a mismatch is a bug rather than a spelling. External + # JSON may use a lower-rank array that broadcasts against the + # domain; `from_json` widens those on the way in, + # so the invariant holds for every transform that exists. + if m.index_array.ndim != self.domain.ndim: + raise ValueError( + f"output[{i}].index_array has {m.index_array.ndim} dims " + f"but input domain has {self.domain.ndim} dims" + ) + # Every axis is either the domain's extent or a singleton it + # broadcasts over. Any other size addresses input coordinates the + # array has no entry for, which reads as a smaller selection + # rather than as the error it is. + bad = [ + (axis, size, extent) + for axis, (size, extent) in enumerate( + zip(m.index_array.shape, self.domain.shape, strict=True) + ) + if size not in (1, extent) + ] + if len(bad) > 0: + axis, size, extent = bad[0] + raise ValueError( + f"output[{i}].index_array has {size} entries on axis {axis}, " + f"which is neither 1 nor the domain's extent of {extent} " + f"(index_array shape {m.index_array.shape}, " + f"domain shape {self.domain.shape})" + ) + + def __eq__(self, other: object) -> bool: + """Value equality. `ArrayMap` compares its index array element-wise, so + a transform holding one can be compared at all β€” the generated `__eq__` + raised `ValueError: the truth value of an array ... is ambiguous`.""" + if not isinstance(other, IndexTransform): + return NotImplemented + return self.domain == other.domain and self.output == other.output + + def __hash__(self) -> int: + """Hashed by value, so a transform can key a cache or enter a set.""" + return hash((self.domain, self.output)) + + @property + def input_rank(self) -> int: + """Number of input dimensions β€” the rank of `domain`.""" + return self.domain.ndim + + @property + def output_rank(self) -> int: + """Number of output dimensions β€” one per output map.""" + return len(self.output) + + @classmethod + def identity(cls, domain: IndexDomain) -> IndexTransform: + """The identity transform over `domain`: every result cell reads the source at its own address.""" + output = tuple(DimensionMap(input_dimension=i) for i in range(domain.ndim)) + return cls(domain=domain, output=output) + + @classmethod + def from_shape(cls, shape: tuple[int, ...]) -> IndexTransform: + """The identity transform over a zero-origin domain of the given `shape`.""" + return cls.identity(IndexDomain.from_shape(shape)) + + def apply(self, point: Sequence[int]) -> tuple[int, ...]: + """Map one coordinate of `domain` to the source coordinate that fills it. + + In array-indexing terms: `point` names a cell of the result array, and + the returned tuple β€” each `output` map evaluated at `point` β€” names the + source-array cell its value is read from: the coordinate arrow, + running result to source. + + Parameters + ---------- + point : Sequence[int] + One literal coordinate for each input dimension. + + Returns + ------- + tuple[int, ...] + One coordinate for each output map. + + Raises + ------ + ValueError + If ``point`` does not have exactly one coordinate per input + dimension. + TypeError + If the coordinates do not have an integer dtype. + BoundsCheckError + If a coordinate lies outside the input domain. + OverflowError + If a mapped output coordinate cannot be represented by + ``np.intp``. + + Examples + -------- + The `[::2]` transform reads result cell `i` from source coordinate + `2 * i`, so cell 3 of the result holds `source[6]`: + + >>> transform = IndexTransform.from_shape((100,))[::2] + >>> transform.apply((3,)) + (6,) + """ + coordinates = np.asarray(point) + expected_shape = (self.input_rank,) + if coordinates.shape != expected_shape: + raise ValueError(f"point must have shape {expected_shape}, got {coordinates.shape}") + # An empty Python sequence has no elements from which NumPy can infer + # an integer dtype, but it is the unique point in a rank-zero domain. + if self.input_rank == 0 and isinstance(point, (list, tuple)): + coordinates = coordinates.astype(np.intp) + try: + result = self._apply_points(coordinates) + except _PointOutOfBounds as error: + raise BoundsCheckError( + f"coordinate {error.value} on input dimension {error.dimension} " + f"is outside the domain [{error.lower}, {error.upper})" + ) from None + return tuple(int(value) for value in result) + + def apply_many(self, points: npt.ArrayLike) -> npt.NDArray[np.intp]: + """Map a batch of `domain` coordinates to the source coordinates that fill them. + + The vectorized form of `apply`: each row of `points` names a result + cell, and the corresponding output row names the source-array cell + its value is read from. + + Parameters + ---------- + points : numpy.typing.ArrayLike + Integer coordinates with shape ``batch_shape + (input_rank,)``. + + Returns + ------- + numpy.typing.NDArray[numpy.intp] + An owned array with shape ``batch_shape + (output_rank,)``. + + Raises + ------ + ValueError + If ``points`` has no trailing coordinate axis or that axis does + not contain exactly one coordinate per input dimension. + TypeError + If the coordinates do not have an integer dtype. + BoundsCheckError + If a coordinate lies outside the input domain. + OverflowError + If a mapped output coordinate cannot be represented by + ``np.intp``. + + Examples + -------- + Three result cells of the `[::2]` transform, located in one call: + + >>> transform = IndexTransform.from_shape((100,))[::2] + >>> transform.apply_many(np.array([[0], [1], [49]])).tolist() + [[0], [2], [98]] + """ + coordinates = np.asarray(points) + if coordinates.ndim == 0 or coordinates.shape[-1] != self.input_rank: + raise ValueError( + "points must have a trailing coordinate axis of size " + f"{self.input_rank}, got shape {coordinates.shape}" + ) + try: + return self._apply_points(coordinates) + except _PointOutOfBounds as error: + raise BoundsCheckError( + f"point at batch position {error.batch_position} has input dimension " + f"{error.dimension} coordinate {error.value} outside " + f"[{error.lower}, {error.upper})" + ) from None + + def _apply_points(self, points: np.ndarray[Any, Any]) -> npt.NDArray[np.intp]: + """Vectorized implementation shared by ``apply`` and ``apply_many``. + + Out-of-domain coordinates raise the internal `_PointOutOfBounds` + signal; each public entry point formats it in its own vocabulary β€” + `apply` never mentions a batch, `apply_many` names the batch position.""" + if not np.issubdtype(points.dtype, np.integer): + raise TypeError(f"points must have an integer dtype, got {points.dtype}") + + invalid = np.zeros(points.shape, dtype=np.bool_) + for dimension, (lower, upper) in enumerate( + zip(self.domain.inclusive_min, self.domain.exclusive_max, strict=True) + ): + invalid[..., dimension] = (points[..., dimension] < lower) | ( + points[..., dimension] >= upper + ) + invalid_positions = np.argwhere(invalid) + if invalid_positions.size > 0: + first = invalid_positions[0] + dimension = int(first[-1]) + batch_position = tuple(int(position) for position in first[:-1]) + point_index = tuple(int(position) for position in first) + value = int(points[point_index]) + lower = self.domain.inclusive_min[dimension] + upper = self.domain.exclusive_max[dimension] + raise _PointOutOfBounds(dimension, value, lower, upper, batch_position) + + batch_shape = points.shape[:-1] + result = np.empty(batch_shape + (self.output_rank,), dtype=np.intp) + for output_dimension, output_map in enumerate(self.output): + if isinstance(output_map, ConstantMap): + if result[..., output_dimension].size == 0: + continue + result[..., output_dimension] = checked_affine(output_map.offset, 0, 0) + elif isinstance(output_map, DimensionMap): + result[..., output_dimension] = checked_affine( + output_map.offset, + output_map.stride, + points[..., output_map.input_dimension], + ) + else: + index = tuple( + np.zeros(batch_shape, dtype=np.intp) + if output_map.index_array.shape[axis] == 1 + else _positions_from_origin(points[..., axis], self.domain.inclusive_min[axis]) + for axis in range(self.input_rank) + ) + result[..., output_dimension] = checked_affine( + output_map.offset, + output_map.stride, + np.asarray(output_map.index_array[index]), + ) + return result + + def inverted(self) -> IndexTransform: + """Return the restricted, exactly representable inverse transform. + + Inversion is defined for square transforms containing only constants + and unique unit-stride dimension maps. Any input dimension not named by + a dimension map must have singleton extent, so its coordinate can be + recovered as a constant. + + Returns + ------- + IndexTransform + A new transform mapping output coordinates back to input + coordinates. + + Raises + ------ + ValueError + If this transform does not have a representable inverse, including + when input labels cannot be transferred to unlabeled output + dimensions. + """ + if self.domain.labels is not None: + raise ValueError( + "cannot invert transform: input labels cannot be represented " + "because output dimensions do not carry labels" + ) + if self.input_rank != self.output_rank: + raise ValueError( + "cannot invert transform: input rank must equal output rank, got " + f"{self.input_rank} and {self.output_rank}" + ) + + referenced: set[int] = set() + for output_dimension, output_map in enumerate(self.output): + if isinstance(output_map, ArrayMap): + raise ValueError( # noqa: TRY004 - valid map, invalid inverse + f"cannot invert transform: output[{output_dimension}] is an ArrayMap" + ) + if isinstance(output_map, DimensionMap): + if output_map.stride not in (-1, 1): + raise ValueError( + "cannot invert transform: DimensionMap stride must be +1 or -1, " + f"got {output_map.stride} for output[{output_dimension}]" + ) + if output_map.input_dimension in referenced: + raise ValueError( + "cannot invert transform: input dimension " + f"{output_map.input_dimension} is referenced more than once" + ) + referenced.add(output_map.input_dimension) + + for input_dimension, extent in enumerate(self.domain.shape): + if input_dimension not in referenced and extent != 1: + raise ValueError( + "cannot invert transform: unreferenced input dimension " + f"{input_dimension} has extent {extent}, not 1" + ) + + inverse_min: list[int] = [] + inverse_max: list[int] = [] + inverse_output: dict[int, OutputIndexMap] = {} + for output_dimension, output_map in enumerate(self.output): + if isinstance(output_map, ConstantMap): + inverse_min.append(output_map.offset) + inverse_max.append(output_map.offset + 1) + continue + + assert isinstance(output_map, DimensionMap) + input_dimension = output_map.input_dimension + lower = self.domain.inclusive_min[input_dimension] + upper = self.domain.exclusive_max[input_dimension] + if output_map.stride == 1: + inverse_min.append(output_map.offset + lower) + inverse_max.append(output_map.offset + upper) + inverse_output[input_dimension] = DimensionMap( + output_dimension, + offset=-output_map.offset, + ) + else: + inverse_min.append(output_map.offset - upper + 1) + inverse_max.append(output_map.offset - lower + 1) + inverse_output[input_dimension] = DimensionMap( + output_dimension, + offset=output_map.offset, + stride=-1, + ) + + for input_dimension, lower in enumerate(self.domain.inclusive_min): + if input_dimension not in referenced: + inverse_output[input_dimension] = ConstantMap(lower) + + return IndexTransform( + domain=IndexDomain(tuple(inverse_min), tuple(inverse_max)), + output=tuple(inverse_output[dimension] for dimension in range(self.input_rank)), + ) + + @property + def selection_repr(self) -> str: + """Compact domain string, e.g. `'{ [2, 8), [0, 10) }'`. + + Follows TensorStore's IndexDomain notation: each dimension shown + as `[inclusive_min, exclusive_max)` with stride annotation if not 1. + Constant (integer-indexed) dimensions show as a single value. + Array-indexed dimensions show the set of selected coordinates. + """ + parts: list[str] = [] + for m in self.output: + if isinstance(m, ConstantMap): + parts.append(str(m.offset)) + elif isinstance(m, DimensionMap): + d = m.input_dimension + lo = self.domain.inclusive_min[d] + hi = self.domain.exclusive_max[d] + start = m.offset + m.stride * lo + stop = m.offset + m.stride * hi + if m.stride == 1: + parts.append(f"[{start}, {stop})") + else: + parts.append(f"[{start}, {stop}) step {m.stride}") + else: + # m: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap) + storage = m.offset + m.stride * m.index_array + n = int(storage.size) # .size, not len(): index_array may be 0-d + if n <= 5: + vals = ", ".join(str(int(v)) for v in storage.ravel()) + parts.append("{" + vals + "}") + else: + parts.append("{" + f"array({n})" + "}") + return "{ " + ", ".join(parts) + " }" + + def __repr__(self) -> str: + maps: list[str] = [] + for i, m in enumerate(self.output): + if isinstance(m, ConstantMap): + maps.append(f"out[{i}] = {m.offset}") + elif isinstance(m, DimensionMap): + maps.append(f"out[{i}] = {m.offset} + {m.stride} * in[{m.input_dimension}]") + else: + # m: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap) + maps.append(f"out[{i}] = {m.offset} + {m.stride} * arr{m.index_array.shape}[in]") + maps_str = ", ".join(maps) + return f"IndexTransform(domain={self.domain}, {maps_str})" + + def intersect( + self, output_domain: IndexDomain + ) -> ( + tuple[ + IndexTransform, + dict[int, np.ndarray[Any, np.dtype[np.intp]]] + | np.ndarray[Any, np.dtype[np.intp]] + | None, + ] + | None + ): + """Keep only the cells whose source coordinates fall inside `output_domain`. + + Chunk resolution is the canonical caller: intersecting a request with + one chunk's box keeps the cells that chunk can serve. + + Returns `(restricted_transform, out_indices)` or None if empty. + + `out_indices` carries the surviving output positions: `None` when all + positions survive (ConstantMap/DimensionMap only), a single integer array + for one ArrayMap (or correlated/vectorized ArrayMaps), or a dict keyed by + output dimension for >= 2 orthogonal ArrayMaps (an outer product). + """ + return _intersect(self, output_domain) + + def translate(self, shift: tuple[int, ...]) -> IndexTransform: + """Shift the source coordinates every cell reads by `shift`, per dimension. + + The domain is untouched: the result keeps its cells, and each one + reads from a shifted source address β€” for example, making a chunk's + global addresses chunk-local by translating by the chunk's negated + origin. + """ + if len(shift) != self.output_rank: + raise ValueError(f"shift must have length {self.output_rank}, got {len(shift)}") + new_output: list[OutputIndexMap] = [] + for m, s in zip(self.output, shift, strict=True): + if isinstance(m, ConstantMap): + new_output.append(ConstantMap(offset=m.offset + s)) + elif isinstance(m, DimensionMap): + new_output.append( + DimensionMap( + input_dimension=m.input_dimension, + offset=m.offset + s, + stride=m.stride, + ) + ) + else: + # m: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap) + new_output.append( + ArrayMap( + index_array=m.index_array, + offset=m.offset + s, + stride=m.stride, + ) + ) + return IndexTransform(domain=self.domain, output=tuple(new_output)) + + def __getitem__(self, selection: Any) -> IndexTransform: + """Compose a basic selection (int, slice, ellipsis, newaxis) into a new transform. + + No I/O occurs. Integers and slice bounds are literal domain coordinates + (TensorStore convention): negative values are not counted from the end, + and out-of-domain values raise `BoundsCheckError`. Integer indices drop + their input dimension; `None` inserts a size-1 dimension. + """ + return _apply_basic_indexing(self, selection) + + def translate_domain_by(self, shift: tuple[int, ...]) -> IndexTransform: + """Shift the *input* domain by `shift`, preserving which cells are addressed. + + TensorStore's `translate_by`: the domain moves, and every output map is + re-offset so that new coordinate `c` addresses the cell that `c - shift` + addressed before. ArrayMaps are indexed positionally over the domain, so + their index arrays are unchanged. + """ + if len(shift) != self.input_rank: + raise ValueError(f"shift must have length {self.input_rank}, got {len(shift)}") + new_domain = self.domain.translate(shift) + new_output: list[OutputIndexMap] = [] + for m in self.output: + if isinstance(m, DimensionMap): + s = shift[m.input_dimension] + new_output.append( + DimensionMap( + input_dimension=m.input_dimension, + offset=m.offset - m.stride * s, + stride=m.stride, + ) + ) + else: + # ConstantMap: no input dependence. ArrayMap: positional over + # the domain, invariant under domain translation. + new_output.append(m) + return IndexTransform(domain=new_domain, output=tuple(new_output)) + + def translate_domain_to(self, origins: tuple[int, ...]) -> IndexTransform: + """Move the input domain so its per-dimension origins equal `origins`. + + TensorStore's `translate_to`; `translate_domain_to((0,) * rank)` + re-zeros a view's coordinate system without changing which cells it + addresses. + """ + if len(origins) != self.input_rank: + raise ValueError(f"origins must have length {self.input_rank}, got {len(origins)}") + shift = tuple(o - m for o, m in zip(origins, self.domain.inclusive_min, strict=True)) + return self.translate_domain_by(shift) + + @property + def oindex(self) -> _OIndexHelper: + """Accessor for the orthogonal (outer-product) indexing dialect. + + `transform.oindex[sel]` applies each index array independently per + dimension and returns a new transform. + """ + return _OIndexHelper(self) + + @property + def vindex(self) -> _VIndexHelper: + """Accessor for the vectorized (coordinate/mask) indexing dialect. + + `transform.vindex[sel]` broadcasts all index arrays together, NumPy + fancy-indexing style, and returns a new transform. + """ + return _VIndexHelper(self) + + @property + def index_array_structure(self) -> Literal["none", "orthogonal", "general"]: + """Classify how a transform's index arrays relate to its input axes. + + Returns + ------- + `"none"` when no output map is an `ArrayMap`; `"orthogonal"` when every + `ArrayMap` varies over exactly one input axis, each its own (an outer + product, one independent gather per axis); `"general"` otherwise β€” + correlated (`vindex`) maps sharing their non-singleton axes, maps produced + by composing fancy steps, maps sharing an input axis (a diagonal gather), + and empty or hand-built all-singleton maps whose shape names no axis. The + orthogonal resolvers narrow one axis at a time and are only sound for + `"orthogonal"`; everything else takes the pointwise path that collapses + the joint block. Everything is read off the index arrays' shapes. + + Examples + -------- + >>> t = IndexTransform.from_shape((4, 5)) + >>> t.index_array_structure + 'none' + + `oindex` arrays each vary over their own axis (an outer product): + + >>> t.oindex[[0, 2], [1, 3]].index_array_structure + 'orthogonal' + + `vindex` arrays are correlated β€” they share the broadcast axis: + + >>> t.vindex[np.array([0, 2]), np.array([1, 3])].index_array_structure + 'general' + """ + seen: set[int] = set() + has_array = False + for m in self.output: + if not isinstance(m, ArrayMap): + continue + has_array = True + dep = m.dependency_axes + if len(dep) != 1 or dep[0] in seen: + return "general" + seen.add(dep[0]) + return "orthogonal" if has_array else "none" + + def select( + self, + selection: Any, + mode: Literal["basic", "orthogonal", "vectorized"] = "basic", + ) -> IndexTransform: + """Convert a user selection into a composed IndexTransform. + + Negative indices are treated as literal coordinates (TensorStore convention). + The caller (Array layer) is responsible for converting numpy-style negative + indices before calling this function. + + Examples + -------- + The `mode` picks the dialect; the result is the composed self the + corresponding accessor builds: + + >>> t = IndexTransform.from_shape((10,)) + >>> t.select(slice(2, 8)) == t[2:8] + True + >>> s = t.select(([9, 0, 0],), mode="orthogonal") + >>> s.apply((0,)), s.apply((1,)), s.apply((2,)) + ((9,), (0,), (0,)) + """ + if mode == "basic": + _validate_basic_selection(selection) + return self[selection] + elif mode == "orthogonal": + _validate_array_selection(selection, self.domain.shape, mode) + return self.oindex[selection] + elif mode == "vectorized": + _validate_array_selection(selection, self.domain.shape, mode) + return self.vindex[selection] + else: + raise ValueError(f"Unknown mode: {mode!r}") + + def compose(self, inner: IndexTransform) -> IndexTransform: + """Chain `inner` onto this transform, yielding one direct transform. + + This transform maps its own input coordinates to `inner`'s input + coordinates, and `inner` maps those onward; the result maps this + transform's input coordinates straight to `inner`'s output + coordinates. Composition is what keeps a view of a view a single + description rather than a stack of layers, and it is exact: index + arrays are evaluated at the new coordinates rather than accumulated. + + The precondition is that this transform's output rank equals `inner`'s + input rank; a mismatch, or coordinates leaving `inner`'s domain, raises. + + Examples + -------- + Chained indexing β€” `source[2:5]`, then `[::-1]` on the result β€” + collapses to one transform (a reversed axis keeps literal coordinates, + so the composed domain is `[-4, -1)`): + + >>> inner = IndexTransform.from_shape((10,))[2:5] + >>> outer = IndexTransform.identity(inner.domain)[::-1] + >>> chained = outer.compose(inner) + >>> chained == inner[::-1] + True + >>> [chained.apply((i,)) for i in (-4, -3, -2)] + [(4,), (3,), (2,)] + """ + from zarr_indexing._composition import compose + + return compose(self, inner) + + # -- serialization ------------------------------------------------------ + + def to_json(self) -> IndexTransformJSON: + """Convert to the canonical ndsel transform body (spec section 4.3). + + The result is fully explicit: `input_rank`, fully written bounds and + labels, and an `output` carrying `offset`/`stride` on every affine and + array map. It is field-for-field a TensorStore `IndexTransform` minus + the `kind` discriminator, so it loads directly into + `tensorstore.IndexTransform(json=...)`. + + Examples + -------- + >>> body = IndexTransform.from_shape((6,))[1:5:2].to_json() + >>> (body["input_inclusive_min"], body["input_exclusive_max"]) + ([0], [2]) + >>> body["output"] + [{'offset': 1, 'stride': 2, 'input_dimension': 0}] + """ + from zarr_indexing._wire import emit_labels + + return { + "input_rank": self.domain.ndim, + "input_inclusive_min": list(self.domain.inclusive_min), + "input_exclusive_max": list(self.domain.exclusive_max), + "input_labels": emit_labels(self.domain.labels, self.domain.ndim), + "output": [m.to_json() for m in self.output], + } + + @classmethod + def from_json(cls, data: IndexTransformJSON) -> IndexTransform: + """Construct from a canonical (or canonicalizable) ndsel transform body. + + The body is first run through the message layer (`normalize_ndsel`) so + that omitted fields β€” identity `output`, default bounds and labels β€” + are filled and validated, then lowered to the engine representation. + Lower-rank `index_array`s are widened to the full input rank on the way + in. + + Examples + -------- + >>> body = IndexTransform.from_shape((6,))[1:5:2].to_json() + >>> transform = IndexTransform.from_json(body) + >>> transform.domain.shape + (2,) + >>> transform.to_json() == body # the round trip is exact + True + """ + from zarr_indexing._wire import ( + full_rank_index_array, + lower_bound, + lower_index_array, + lower_labels, + ) + from zarr_indexing.messages import NdselError, normalize_ndsel + + if not isinstance(data, dict): # pyright: ignore[reportUnnecessaryIsInstance] + raise NdselError( + "invalid_json", f"a transform body must be a JSON object, got {data!r}" + ) + kind = data.get("kind", "transform") + if kind != "transform": + # Spelled before normalization so a body carrying its own `kind` + # cannot reinterpret the document as some other message and return + # a selection this constructor never promised. + raise NdselError("invalid_json", f"a transform body cannot carry kind {kind!r}") + body = normalize_ndsel({**data, "kind": "transform"}) + + domain = IndexDomain( + inclusive_min=tuple( + lower_bound(b, f"input_inclusive_min[{i}]") + for i, b in enumerate(body["input_inclusive_min"]) + ), + exclusive_max=tuple( + lower_bound(b, f"input_exclusive_max[{i}]") + for i, b in enumerate(body["input_exclusive_max"]) + ), + labels=lower_labels(body["input_labels"]), + ) + + output: list[OutputIndexMap] = [] + for i, om in enumerate(body["output"]): + if "index_array" in om: + where = f"output[{i}]" + arr = lower_index_array(om["index_array"], f"{where}.index_array") + # ndsel leaves index-array rank unvalidated, so an external + # producer may send an array of lower rank that broadcasts + # against the domain. Widen it here, on the way in, so every + # transform that exists holds the full-rank invariant the + # engine reads dependency axes from. + output.append( + ArrayMap( + index_array=full_rank_index_array(arr, domain, where), + offset=om.get("offset", 0), + stride=om.get("stride", 1), + ) + ) + elif "input_dimension" in om: + output.append( + DimensionMap( + input_dimension=om["input_dimension"], + offset=om.get("offset", 0), + stride=om.get("stride", 1), + ) + ) + else: + output.append(ConstantMap(offset=om.get("offset", 0))) + + try: + return cls(domain=domain, output=tuple(output)) + except ValueError as exc: + # The engine's invariants are the last gate a document passes, and + # they speak in the engine's vocabulary. A document that fails them + # is invalid input, so it leaves here as one β€” with the engine's + # account of what was wrong kept, since it names the offending + # output map and axis. + raise NdselError("rank_mismatch", str(exc)) from exc + + +def _positions_from_origin(coordinates: np.ndarray[Any, Any], origin: int) -> npt.NDArray[np.intp]: + """Convert literal coordinates to positional indices without wrapping.""" + return checked_affine(-int(origin), 1, coordinates) + + +def _intersect( + transform: IndexTransform, output_domain: IndexDomain +) -> ( + tuple[ + IndexTransform, + dict[int, np.ndarray[Any, np.dtype[np.intp]]] | np.ndarray[Any, np.dtype[np.intp]] | None, + ] + | None +): + """Intersect a transform with an output domain (e.g., a chunk's bounds). + + For each output dimension, restrict to output coordinates within + `[output_domain.inclusive_min[d], output_domain.exclusive_max[d])`. + + Two flavors of fancy indexing require different treatment, distinguished by + the ArrayMaps' dependency axes (see `ArrayMap.dependency_axes`): + + - **orthogonal** (`oindex`): each ArrayMap varies over a single, distinct + input axis, forming an outer product. Every output dimension is intersected + independently and the input domain narrowed per axis. + - **correlated** (`vindex`): the ArrayMaps share their (broadcast) dependency + axes and scatter through a single flat index. A point survives only if ALL + its output coordinates fall within the output domain; residual slice + dimensions are intersected independently, as in the orthogonal case. + + The routing is `index_array_structure`: only a pure per-axis outer product + takes the orthogonal path. + + Returns `None` if the intersection is empty. + """ + if output_domain.ndim != transform.output_rank: + raise ValueError( + f"output_domain rank ({output_domain.ndim}) != " + f"transform output rank ({transform.output_rank})" + ) + + if any(size == 0 for size in transform.domain.shape): + # An empty input domain addresses no coordinates at all, so it meets no + # output domain. Deciding it here keeps the per-flavor intersections from + # having to reconcile an empty domain with an index array that is *not* + # empty: a genuine extent-1 axis is stored as a broadcast singleton, so + # emptying its domain leaves the array at size 1. + return None + + if transform.index_array_structure == "general": + return _intersect_general(transform, output_domain) + return _intersect_orthogonal(transform, output_domain) + + +def _intersect_dimension_map( + m: DimensionMap, input_lo: int, input_hi: int, lo: int, hi: int +) -> tuple[int, int] | None: + """Narrow a DimensionMap's input range to output coordinates in `[lo, hi)`. + + `input_lo`/`input_hi` are the current (possibly already narrowed) input + range for the map's axis. Returns the new `(input_lo, input_hi)` or `None` + if no input produces an in-bounds output coordinate. + """ + if input_lo >= input_hi: + return None + if m.stride > 0: + new_input_lo = max(input_lo, _ceil_div(lo - m.offset, m.stride)) + new_input_hi = min(input_hi, _ceil_div(hi - m.offset, m.stride)) + elif m.stride < 0: + new_input_lo = max(input_lo, _ceil_div(hi - 1 - m.offset, m.stride)) + new_input_hi = min(input_hi, _ceil_div(lo - 1 - m.offset, m.stride)) + else: + if lo <= m.offset < hi: + new_input_lo, new_input_hi = input_lo, input_hi + else: + return None + if new_input_lo >= new_input_hi: + return None + return new_input_lo, new_input_hi + + +def _ceil_div(numerator: int, denominator: int) -> int: + """Return ``ceil(numerator / denominator)`` using exact integer arithmetic.""" + return -((-numerator) // denominator) + + +def _intersect_orthogonal( + transform: IndexTransform, output_domain: IndexDomain +) -> ( + tuple[ + IndexTransform, + dict[int, np.ndarray[Any, np.dtype[np.intp]]] | np.ndarray[Any, np.dtype[np.intp]] | None, + ] + | None +): + """Intersect a transform with no correlated ArrayMaps. + + Every output dimension is intersected independently. Multiple ArrayMaps bound + to distinct input dimensions form an outer product, so each array's surviving + *output* positions are tracked separately. + """ + new_min = list(transform.domain.inclusive_min) + new_max = list(transform.domain.exclusive_max) + new_output: list[OutputIndexMap] = [] + out_positions: dict[int, np.ndarray[Any, np.dtype[np.intp]]] = {} + + for out_dim, m in enumerate(transform.output): + lo = output_domain.inclusive_min[out_dim] + hi = output_domain.exclusive_max[out_dim] + + if isinstance(m, ConstantMap): + if lo <= m.offset < hi: + new_output.append(m) + else: + return None + + elif isinstance(m, DimensionMap): + d = m.input_dimension + narrowed = _intersect_dimension_map(m, new_min[d], new_max[d], lo, hi) + if narrowed is None: + return None + new_min[d], new_max[d] = narrowed + new_output.append(m) + + else: + # m: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap) + # Orthogonal: the array varies over a single axis. Filter along that + # axis and keep the array at full input rank so the singleton axes + # it broadcasts over are preserved. + axis = m.dependent_axis + if axis is None: + raise ValueError( + f"output[{out_dim}] is an ArrayMap that varies over no input " + "dimension; a map with no dependency axis should have been " + "collapsed to a ConstantMap" + ) + d = axis + storage = checked_affine(m.offset, m.stride, m.index_array) + mask = (storage >= lo) & (storage < hi) + # The array is singleton on every axis but `d`, so its mask reduces + # to a 1-D vector along `d`. + survivors = np.nonzero(mask.reshape(-1))[0].astype(np.intp) + if survivors.size == 0: + return None + filtered = np.take(m.index_array, survivors, axis=d) + new_output.append( + ArrayMap( + index_array=np.asarray(filtered, dtype=np.intp), + offset=m.offset, + stride=m.stride, + ) + ) + new_max[d] = new_min[d] + int(survivors.size) + out_positions[out_dim] = survivors + + new_domain = IndexDomain( + inclusive_min=tuple(new_min), + exclusive_max=tuple(new_max), + ) + result = IndexTransform(domain=new_domain, output=tuple(new_output)) + + # Hand back the surviving output positions in the shape the bridge expects: + # None (no arrays), a single vector (one array), or a per-output-dim dict + # (>= 2 orthogonal arrays β†’ outer product). + out_indices: ( + dict[int, np.ndarray[Any, np.dtype[np.intp]]] | np.ndarray[Any, np.dtype[np.intp]] | None + ) + if len(out_positions) == 0: + out_indices = None + elif len(out_positions) == 1: + out_indices = next(iter(out_positions.values())) + else: + out_indices = out_positions + return (result, out_indices) + + +def _intersect_general( + transform: IndexTransform, + output_domain: IndexDomain, +) -> tuple[IndexTransform, np.ndarray[Any, np.dtype[np.intp]]] | None: + """Intersect a transform with any index-array structure, pointwise. + + Every `ArrayMap` β€” correlated, orthogonal, or several sharing an axis β€” is + treated as a lookup table over the joint block of non-slice axes: a block + point survives only if ALL its output coordinates fall within the output + domain. Residual DimensionMap dimensions are intersected independently (as in + the orthogonal case) and preserved, so a partial vindex β€” e.g. two coordinate + arrays over a 3-D array, leaving one slice dimension β€” resolves correctly. + Treating an orthogonal map this way forfeits its per-axis independence (the + block enumerates the outer product), which is why the pure-orthogonal case + keeps its own resolver. + + The surviving broadcast axes collapse to a single axis; the returned + `out_indices` is the flat scatter index into the (row-major flattened) + output buffer, of shape `(surviving_points,) + (residual slice sizes)`. + + A rank-0 broadcast block β€” every coordinate array a scalar, as after + `vindex[...]` narrowed to a single point β€” has no axis to collapse and stays + rank 0: the block either survives whole or the intersection is empty. The + result keeps only the residual slice axes and `out_indices` loses its leading + points axis, so the sub-transform's rank still matches the view's. + """ + correlated_dims = [i for i, m in enumerate(transform.output) if isinstance(m, ArrayMap)] + + # The broadcast axes are exactly the input axes no `DimensionMap` binds: a + # correlated transform's input domain is its residual slice axes plus the + # collapsed broadcast block. Deriving them by complement rather than from the + # index array's non-singleton axes keeps this correct when a broadcast axis + # is itself size 1, and when NumPy's placement rule puts the broadcast block + # somewhere other than the front (see `_broadcast_insertion_point`). + bound_axes = {m.input_dimension for m in transform.output if isinstance(m, DimensionMap)} + broadcast_axes = tuple(a for a in range(transform.input_rank) if a not in bound_axes) + broadcast_shape = tuple(transform.domain.shape[a] for a in broadcast_axes) + + for out_dim in correlated_dims: + arr_map = cast("ArrayMap", transform.output[out_dim]) + if any(a not in broadcast_axes for a in arr_map.dependency_axes): + # Reachable only by hand-building a transform: no selection binds + # the same input axis to both a slice map and an index array. + raise NotImplementedError( + "intersecting a transform whose index array varies over an " + "input dimension also bound by a slice map is not supported" + ) + + # Joint bounds mask over the broadcast block. + combined: np.ndarray[Any, np.dtype[np.bool_]] | None = None + for out_dim in correlated_dims: + cm = cast("ArrayMap", transform.output[out_dim]) + storage = checked_affine(cm.offset, cm.stride, cm.index_array) + lo = output_domain.inclusive_min[out_dim] + hi = output_domain.exclusive_max[out_dim] + mask = (storage >= lo) & (storage < hi) + combined = mask if combined is None else (combined & mask) + assert combined is not None + # Index arrays are singleton on every non-broadcast axis, so the mask + # collapses (C-order) to the broadcast block. A map may also be singleton + # along a block axis it does not vary over (an orthogonal member, or a + # leftover broadcast axis), so the collapsed mask is broadcast up to the + # full block rather than reshaped. + combined_block = combined.reshape(tuple(combined.shape[a] for a in broadcast_axes)) + combined_bcast = np.broadcast_to(combined_block, broadcast_shape) + surviving = np.nonzero(combined_bcast.reshape(-1))[0].astype(np.intp) + if surviving.size == 0: + return None + + # Intersect residual (slice / constant) dimensions independently. Slice dims + # are ordered by input dimension so their flat-buffer strides are row-major. + slice_dims: list[tuple[int, int, int, int, DimensionMap]] = [] # (in_dim, lo, hi, full, m) + for out_dim, m in enumerate(transform.output): + if out_dim in correlated_dims: + continue + lo = output_domain.inclusive_min[out_dim] + hi = output_domain.exclusive_max[out_dim] + if isinstance(m, ConstantMap): + if not (lo <= m.offset < hi): + return None + elif isinstance(m, DimensionMap): + d = m.input_dimension + input_lo = transform.domain.inclusive_min[d] + input_hi = transform.domain.exclusive_max[d] + narrowed = _intersect_dimension_map(m, input_lo, input_hi, lo, hi) + if narrowed is None: + return None + slice_dims.append((d, narrowed[0], narrowed[1], input_hi - input_lo, m)) + slice_dims.sort(key=lambda item: item[0]) + + n_points = int(surviving.size) + n_slice = len(slice_dims) + corr_values: dict[int, np.ndarray[Any, np.dtype[np.intp]]] = {} + for out_dim in correlated_dims: + arr = cast("ArrayMap", transform.output[out_dim]).index_array + block = arr.reshape(tuple(arr.shape[a] for a in broadcast_axes)) + corr_values[out_dim] = np.asarray( + np.ascontiguousarray(np.broadcast_to(block, broadcast_shape)).reshape(-1)[surviving], + dtype=np.intp, + ) + + # A rank-0 broadcast block contributes no axis: the leading `(n_points,)` of + # the domain, of every index array, and of `out_indices` is present only when + # there was a block to collapse. + points_shape = (n_points,) if len(broadcast_shape) > 0 else () + + # New domain: the collapsed broadcast axis if there is one, then one axis per + # residual slice. + new_min = [0] * len(points_shape) + new_max = list(points_shape) + new_input_dim_of = {} + for new_axis, (d, nlo, nhi, _full, _m) in enumerate(slice_dims, start=len(points_shape)): + new_min.append(nlo) + new_max.append(nhi) + new_input_dim_of[d] = new_axis + new_domain = IndexDomain(inclusive_min=tuple(new_min), exclusive_max=tuple(new_max)) + + corr_shape = points_shape + (1,) * n_slice + new_output: list[OutputIndexMap] = [] + for out_dim, m in enumerate(transform.output): + if out_dim in correlated_dims: + corr = cast("ArrayMap", m) + new_output.append( + ArrayMap( + index_array=corr_values[out_dim].reshape(corr_shape).astype(np.intp), + offset=corr.offset, + stride=corr.stride, + ) + ) + elif isinstance(m, ConstantMap): + new_output.append(m) + else: + assert isinstance(m, DimensionMap) + new_output.append( + DimensionMap( + input_dimension=new_input_dim_of[m.input_dimension], + offset=m.offset, + stride=m.stride, + ) + ) + result = IndexTransform(domain=new_domain, output=tuple(new_output)) + + # Flat scatter index into the caller's row-major output buffer, whose shape + # is the *input* domain's shape. The buffer is addressed positionally, so + # this assumes a zero-origin domain β€” the resolvers normalize with + # `translate_domain_to` before resolving. + # + # Each surviving point is a flat index into the broadcast block; unravel it + # to per-axis coordinates so the buffer stride of each broadcast axis is + # applied at its real position, wherever NumPy's placement rule put it. + domain_shape = transform.domain.shape + buffer_strides = [1] * len(domain_shape) + for axis in range(len(domain_shape) - 2, -1, -1): + buffer_strides[axis] = buffer_strides[axis + 1] * domain_shape[axis + 1] + + point_offsets = np.zeros(n_points, dtype=np.intp) + if len(broadcast_shape) > 0: + for axis, coords_along_axis in zip( + broadcast_axes, np.unravel_index(surviving, broadcast_shape), strict=True + ): + point_offsets = point_offsets + coords_along_axis.astype(np.intp) * buffer_strides[axis] + + n_lead = len(points_shape) + out_indices: np.ndarray[Any, np.dtype[np.intp]] = point_offsets.reshape( + points_shape + (1,) * n_slice + ) + for j in range(n_slice): + d, nlo, nhi, _full, _m = slice_dims[j] + coords = np.arange(nlo, nhi, dtype=np.intp) * buffer_strides[d] + shape = [1] * (n_lead + n_slice) + shape[n_lead + j] = coords.size + out_indices = out_indices + coords.reshape(shape) + return (result, out_indices.astype(np.intp)) + + +def _normalize_basic_selection(selection: Any, ndim: int) -> tuple[int | slice | None, ...]: + """Normalize a selection to a tuple of int, slice, or None (newaxis), + expanding ellipsis and padding with slice(None) as needed. + """ + if not isinstance(selection, tuple): + selection = (selection,) + + # Count non-newaxis, non-ellipsis entries to determine how many real dims are addressed + n_newaxis = sum(1 for s in selection if s is None) + has_ellipsis = any(s is Ellipsis for s in selection) + n_real = len(selection) - n_newaxis - (1 if has_ellipsis else 0) + + if n_real > ndim: + raise IndexError( + f"too many indices for array: array has {ndim} dimensions, but {n_real} were indexed" + ) + + result: list[int | slice | None] = [] + ellipsis_seen = False + for sel in selection: + if sel is Ellipsis: + if ellipsis_seen: + raise IndexError("an index can only have a single ellipsis ('...')") + ellipsis_seen = True + num_missing = ndim - n_real + result.extend([slice(None)] * num_missing) + elif (scalar := as_scalar_index(sel)) is not None: + result.append(scalar) + elif isinstance(sel, slice) or sel is None: + result.append(sel) + else: + raise IndexError(f"unsupported selection type for basic indexing: {type(sel)!r}") + + # Pad remaining dimensions with slice(None) + while sum(1 for s in result if s is not None) < ndim: + result.append(slice(None)) + + return tuple(result) + + +def _positional_slice(pos: int, size: int, step: int) -> slice: + """A NumPy slice selecting `size` elements from `pos`, walking by `step`. + + The stop is `pos + size*step`, except in two cases. An empty selection is + written out explicitly, because the arithmetic form can be a negative stop + that NumPy would read as counting from the end. And a downward walk + reaching the start of the array must stop at `None`, for the same reason: + `slice(6, -1, -1)` selects nothing where `slice(6, None, -1)` selects the + first seven elements in reverse. + """ + if size <= 0: + return slice(0, 0, 1) + stop = pos + size * step + if step < 0 and stop < 0: + return slice(pos, None, step) + return slice(pos, stop, step) + + +def _reindex_array( + m: ArrayMap, + normalized: tuple[int | slice | None, ...], + domain: IndexDomain, +) -> np.ndarray[Any, np.dtype[np.intp]]: + """Apply basic indexing operations to an ArrayMap's index_array. + + The array's axes correspond to the transform's input dimensions (0-indexed + over the domain shape). Each axis is either a **dependency axis** β€” the array + varies with that input dimension β€” or a **singleton** axis it + broadcasts over. Integer indexing, slicing, or newaxis is applied to the + array only along its dependency axes; a selection on a singleton axis does not + touch the array's values (it just narrows or drops that broadcast axis). + """ + dependent = set(m.dependency_axes) + arr = m.index_array + + # Build a numpy indexing tuple: one entry per old input dimension + idx: list[Any] = [] + old_dim = 0 + newaxis_positions: list[int] = [] + result_axis = 0 + + for sel in normalized: + if sel is None: + newaxis_positions.append(result_axis) + result_axis += 1 + elif isinstance(sel, int): + if old_dim < arr.ndim: + if old_dim in dependent: + # Convert absolute domain coordinate to 0-based array index + idx.append(sel - domain.inclusive_min[old_dim]) + else: + # Broadcast axis: keep the single element and drop the axis. + idx.append(0) + old_dim += 1 + else: + # sel: slice (normalized: tuple[int | slice | None, ...]) + if old_dim < arr.ndim: + if old_dim in dependent: + lo = domain.inclusive_min[old_dim] + hi = domain.exclusive_max[old_dim] + # Bounds are literal domain coordinates; the stored array is + # indexed positionally, so shift by the domain origin. + start, step, _origin, size = _resolve_slice_ts(sel, old_dim, lo, hi) + pos = start - lo + idx.append(_positional_slice(pos, size, step)) + else: + # Broadcast axis: preserve the singleton (it still broadcasts + # over the narrowed domain), regardless of the slice bounds. + idx.append(slice(None)) + old_dim += 1 + result_axis += 1 + + result = arr[tuple(idx)] if idx else arr + + for pos in newaxis_positions: + result = np.expand_dims(result, axis=pos) + + return np.asarray(result, dtype=np.intp) + + +def _compose_selection( + transform: IndexTransform, + selection: Any, + mode: Literal["orthogonal", "vectorized"], +) -> IndexTransform: + """Apply an advanced selection to an array-carrying transform by composition. + + The selection is applied to an identity transform over the current domain β€” + the same code path a fresh transform takes, so the dialect (placement, + bounds, domains) is identical by construction β€” and the result is chained + onto `transform` with `compose`, which evaluates the existing index arrays + at the new coordinates. This is how a second fancy step lands on *any* axis + of an already-fancy view: axes an existing array varies over, axes it merely + broadcasts along, or a mixture. + """ + # Deferred import: `composition` imports this module at import time. + + identity = IndexTransform.identity(transform.domain) + if mode == "orthogonal": + outer = _apply_oindex(identity, selection) + else: + outer = _apply_vindex(identity, selection) + return outer.compose(transform) + + +def _apply_basic_indexing(transform: IndexTransform, selection: Any) -> IndexTransform: + """Apply basic indexing (int, slice, ellipsis, newaxis) to an IndexTransform.""" + normalized = _normalize_basic_selection(selection, transform.domain.ndim) + + new_inclusive_min: list[int] = [] + new_exclusive_max: list[int] = [] + old_dim = 0 + new_dim_idx = 0 + old_to_new_dim: dict[int, int] = {} + dropped_dims: set[int] = set() + + # Per old-dim: the slice parameters (for computing new output maps) + dim_slice_params: dict[int, tuple[int, int, int]] = {} # old_dim -> (start, stop, step) + dim_int_val: dict[int, int] = {} # old_dim -> integer index value + + for sel in normalized: + if sel is None: + # newaxis: add a size-1 dimension + new_inclusive_min.append(0) + new_exclusive_max.append(1) + new_dim_idx += 1 + elif isinstance(sel, int): + # Integer index: drop this input dimension. + # Negative indices are literal coordinates (TensorStore convention), + # NOT "from the end" like NumPy. The Array layer handles conversion. + lo = transform.domain.inclusive_min[old_dim] + hi = transform.domain.exclusive_max[old_dim] + idx = sel + if idx < lo or idx >= hi: + hint = _LITERAL_HINT if sel < 0 else "" + raise BoundsCheckError( + f"index {sel} is out of bounds for dimension {old_dim} " + f"(valid indices [{lo}, {hi})){hint}" + ) + dropped_dims.add(old_dim) + dim_int_val[old_dim] = idx + old_dim += 1 + else: + # sel: slice (normalized: tuple[int | slice | None, ...]) + lo = transform.domain.inclusive_min[old_dim] + hi = transform.domain.exclusive_max[old_dim] + + # TensorStore semantics: bounds are literal coordinates; a step-1 + # slice keeps them as the new domain, a strided slice's domain is + # [trunc(start/step), trunc(start/step) + size). + start, step, origin, size = _resolve_slice_ts(sel, old_dim, lo, hi) + new_inclusive_min.append(origin) + new_exclusive_max.append(origin + size) + dim_slice_params[old_dim] = (start, step, origin) + old_to_new_dim[old_dim] = new_dim_idx + new_dim_idx += 1 + old_dim += 1 + + new_domain = IndexDomain( + inclusive_min=tuple(new_inclusive_min), + exclusive_max=tuple(new_exclusive_max), + ) + + # Now update output maps + new_output: list[OutputIndexMap] = [] + for m in transform.output: + if isinstance(m, ConstantMap): + new_output.append(m) + elif isinstance(m, DimensionMap): + d = m.input_dimension + if d in dropped_dims: + # Integer index: this output becomes constant + new_offset = m.offset + m.stride * dim_int_val[d] + new_output.append(ConstantMap(offset=new_offset)) + elif d in old_to_new_dim: + # Slice: new coordinate `origin + k` maps to old coordinate + # `start + k*step`, i.e. old = start - step*origin + step*new. + start, step, origin = dim_slice_params[d] + new_offset = m.offset + m.stride * (start - step * origin) + new_stride = m.stride * step + new_input_dim = old_to_new_dim[d] + new_output.append( + DimensionMap( + input_dimension=new_input_dim, offset=new_offset, stride=new_stride + ) + ) + else: + raise RuntimeError(f"unexpected: dimension {d} not handled") + else: + # m: ArrayMap (OutputIndexMap = ConstantMap | DimensionMap | ArrayMap). + # A result narrowed to a single coordinate collapses to the + # ConstantMap it equals β€” whether an integer consumed the dependency + # axis or a slice narrowed it to one entry β€” so a non-empty ArrayMap + # always varies over at least one axis. Nothing here renumbers: the + # array's axes are the new domain's axes by construction. + new_arr = _reindex_array(m, normalized, transform.domain) + new_output.append(array_map_or_constant(new_arr, offset=m.offset, stride=m.stride)) + + return IndexTransform(domain=new_domain, output=tuple(new_output)) + + +def _reshape_to_axis( + values: np.ndarray[Any, np.dtype[np.intp]], axis: int, ndim: int +) -> np.ndarray[Any, np.dtype[np.intp]]: + """Reshape a 1-D selection to full rank `ndim` varying only along `axis`. + + The result has `values` laid out along `axis` and singleton (size-1) axes + everywhere else, so its dependency axis is derivable from its shape. + """ + flat = np.asarray(values, dtype=np.intp).ravel() + shape = [1] * ndim + shape[axis] = flat.shape[0] + return flat.reshape(shape) + + +class _OIndexHelper: + """Helper that provides orthogonal (outer) indexing via `transform.oindex[...]`.""" + + def __init__(self, transform: IndexTransform) -> None: + self._transform = transform + + def __getitem__(self, selection: Any) -> IndexTransform: + return _apply_oindex(self._transform, selection) + + +def _normalize_oindex_selection( + selection: Any, ndim: int +) -> tuple[np.ndarray[Any, np.dtype[np.intp]] | slice, ...]: + """Normalize an oindex selection: arrays, slices, booleans, integers.""" + if not isinstance(selection, tuple): + selection = (selection,) + + # Expand ellipsis + has_ellipsis = any(s is Ellipsis for s in selection) + n_ellipsis = 1 if has_ellipsis else 0 + n_real = len(selection) - n_ellipsis + + result: list[np.ndarray[Any, np.dtype[np.intp]] | slice] = [] + for sel in selection: + if sel is Ellipsis: + num_missing = ndim - n_real + result.extend([slice(None)] * num_missing) + elif isinstance(sel, np.ndarray) and sel.dtype == np.bool_: + # Boolean array -> integer indices + (indices,) = np.nonzero(sel) + result.append(indices.astype(np.intp)) + elif isinstance(sel, np.ndarray): + result.append(sel.astype(np.intp)) + elif isinstance(sel, slice): + result.append(sel) + elif (scalar := as_scalar_index(sel)) is not None: + # Convert integer scalars to 1-element arrays for orthogonal indexing + result.append(np.array([scalar], dtype=np.intp)) + elif isinstance(sel, (list, tuple)): + array = np.asarray(sel) + if array.dtype == np.bool_: + (indices,) = np.nonzero(array) + result.append(indices.astype(np.intp)) + else: + result.append(np.asarray(sel, dtype=np.intp)) + else: + result.append(sel) + + # Pad with slice(None) + while len(result) < ndim: + result.append(slice(None)) + + return tuple(result) + + +def _apply_oindex(transform: IndexTransform, selection: Any) -> IndexTransform: + """Apply orthogonal indexing to an IndexTransform. + + Each index array is applied independently per dimension (outer product). + + A transform that already carries index arrays takes the composition path + (`_compose_selection`) instead of being rewritten in place, so the new + selection may land on any axis β€” including axes an existing array merely + broadcasts along. + """ + validate_advanced_selection(selection, transform.domain, "orthogonal") + if any(isinstance(m, ArrayMap) for m in transform.output): + return _compose_selection(transform, selection, "orthogonal") + normalized = _normalize_oindex_selection(selection, transform.domain.ndim) + + new_inclusive_min: list[int] = [] + new_exclusive_max: list[int] = [] + new_dim_idx = 0 + old_to_new_dim: dict[int, int] = {} + + # Info per old dim + dim_array: dict[int, np.ndarray[Any, np.dtype[np.intp]]] = {} + dim_slice_params: dict[int, tuple[int, int, int]] = {} + + for old_dim, sel in enumerate(normalized): + if isinstance(sel, np.ndarray): + lo = transform.domain.inclusive_min[old_dim] + hi = transform.domain.exclusive_max[old_dim] + # Index-array values are literal domain coordinates; the fancy dim + # they create gets a fresh zero-origin [0, n) domain (TensorStore). + _check_array_in_bounds(sel, lo, hi) + dim_array[old_dim] = sel + new_inclusive_min.append(0) + new_exclusive_max.append(len(sel)) + old_to_new_dim[old_dim] = new_dim_idx + new_dim_idx += 1 + else: + # sel: slice (_normalize_oindex_selection returns + # tuple[np.ndarray | slice, ...]) + lo = transform.domain.inclusive_min[old_dim] + hi = transform.domain.exclusive_max[old_dim] + start, step, origin, size = _resolve_slice_ts(sel, old_dim, lo, hi) + new_inclusive_min.append(origin) + new_exclusive_max.append(origin + size) + dim_slice_params[old_dim] = (start, step, origin) + old_to_new_dim[old_dim] = new_dim_idx + new_dim_idx += 1 + + new_domain = IndexDomain( + inclusive_min=tuple(new_inclusive_min), + exclusive_max=tuple(new_exclusive_max), + ) + + new_output: list[OutputIndexMap] = [] + for m in transform.output: + if isinstance(m, ConstantMap): + new_output.append(m) + elif isinstance(m, DimensionMap): + d = m.input_dimension + if d in dim_array: + new_axis = old_to_new_dim[d] + # Normalize to full input rank: the selection varies along its + # own new axis and is singleton on every other axis, so the + # dependency axis is readable from the shape. A single-entry + # selection holds one coordinate and collapses to the + # ConstantMap it equals; its length-1 axis stays in the domain. + full_arr = _reshape_to_axis(dim_array[d], new_axis, new_dim_idx) + new_output.append(array_map_or_constant(full_arr, offset=m.offset, stride=m.stride)) + elif d in dim_slice_params: + start, step, origin = dim_slice_params[d] + new_offset = m.offset + m.stride * (start - step * origin) + new_stride = m.stride * step + new_input_dim = old_to_new_dim[d] + new_output.append( + DimensionMap( + input_dimension=new_input_dim, offset=new_offset, stride=new_stride + ) + ) + else: + raise RuntimeError(f"unexpected: dimension {d} not handled") + else: + # m: ArrayMap β€” unreachable: array-carrying transforms took the + # composition path at the top of this function. + raise AssertionError( # noqa: TRY004 - unreachable, not a dispatch + "unreachable: ArrayMap transforms are composed" + ) + + return IndexTransform(domain=new_domain, output=tuple(new_output)) + + +class _VIndexHelper: + """Helper that provides vectorized (fancy) indexing via `transform.vindex[...]`.""" + + def __init__(self, transform: IndexTransform) -> None: + self._transform = transform + + def __getitem__(self, selection: Any) -> IndexTransform: + return _apply_vindex(self._transform, selection) + + +def _broadcast_insertion_point(array_dims: Sequence[int], slice_dims: Sequence[int]) -> int: + """Where the broadcast dimensions land, as a count of leading slice dimensions. + + NumPy's advanced-indexing placement rule: when the advanced indices are all + next to each other in the index tuple, the broadcast dimensions are inserted + at the spot they occupied; when a slice separates them, they lead. So + `a[:, i, j]` has shape `(len(a), *broadcast)` while `a[i, :, j]` has shape + `(*broadcast, a.shape[1])`. + + Returns the number of slice dimensions that precede the broadcast block; `0` + means the broadcast dimensions lead. + """ + if len(array_dims) == 0: + return 0 + first, last = array_dims[0], array_dims[-1] + separated = any(first < d < last for d in slice_dims) + if separated: + return 0 + return sum(1 for d in slice_dims if d < first) + + +def _as_boolean_index_array(selection: Any) -> np.ndarray[Any, np.dtype[np.bool_]] | None: + """Return an array-like boolean index as an ndarray, else None.""" + if not isinstance(selection, (np.ndarray, list, tuple)): + return None + array = np.asarray(selection) + if array.dtype != np.bool_: + return None + return array + + +def _selection_axis_count(selection: Any) -> int: + """Return how many input axes one vectorized selection entry consumes.""" + boolean_array = _as_boolean_index_array(selection) + return boolean_array.ndim if boolean_array is not None else 1 + + +def _apply_vindex(transform: IndexTransform, selection: Any) -> IndexTransform: + """Apply vectorized indexing to an IndexTransform. + + All array indices are broadcast together. Broadcast dimensions are prepended, + followed by non-array (slice) dimensions. + + A transform that already carries index arrays takes the composition path + (`_compose_selection`) instead of being rewritten in place; see + `_apply_oindex`. + """ + validate_advanced_selection(selection, transform.domain, "vectorized") + if any(isinstance(m, ArrayMap) for m in transform.output): + return _compose_selection(transform, selection, "vectorized") + if not isinstance(selection, tuple): + selection = (selection,) + + # Expand ellipsis and count consumed dimensions. Boolean masks consume one + # input axis per mask dimension, whether spelled as an ndarray or a list. + n_consumed = sum(_selection_axis_count(s) for s in selection if s is not Ellipsis) + ndim = transform.domain.ndim + + expanded: list[Any] = [] + for sel in selection: + if sel is Ellipsis: + num_missing = ndim - n_consumed + expanded.extend([slice(None)] * num_missing) + else: + expanded.append(sel) + # Count dimensions already consumed by expanded entries + n_expanded_dims = sum(_selection_axis_count(sel) for sel in expanded) + while n_expanded_dims < ndim: + expanded.append(slice(None)) + n_expanded_dims += 1 + + # Convert booleans, lists, ints to integer arrays + processed: list[np.ndarray[Any, np.dtype[np.intp]] | slice] = [] + for sel in expanded: + boolean_array = _as_boolean_index_array(sel) + if boolean_array is not None: + indices_tuple = np.nonzero(boolean_array) + processed.extend(indices.astype(np.intp) for indices in indices_tuple) + elif isinstance(sel, np.ndarray): + processed.append(sel.astype(np.intp)) + elif isinstance(sel, (list, tuple)): + processed.append(np.asarray(sel, dtype=np.intp)) + elif (scalar := as_scalar_index(sel)) is not None: + processed.append(np.array([scalar], dtype=np.intp)) + else: + processed.append(sel) + + # Separate array dims and slice dims + array_dims: list[int] = [] + slice_dims: list[int] = [] + arrays: list[np.ndarray[Any, np.dtype[np.intp]]] = [] + + for i, sel in enumerate(processed): + if isinstance(sel, np.ndarray): + lo = transform.domain.inclusive_min[i] + hi = transform.domain.exclusive_max[i] + _check_array_in_bounds(sel, lo, hi) + array_dims.append(i) + arrays.append(sel) + else: + slice_dims.append(i) + + # Broadcast all arrays together + broadcast_arrays: list[np.ndarray[Any, np.dtype[np.intp]]] + if len(arrays) > 0: + broadcast_arrays = list(np.broadcast_arrays(*arrays)) + broadcast_shape = broadcast_arrays[0].shape + else: + broadcast_arrays = [] + broadcast_shape = () + + # Slice dimensions (preserved-domain literal semantics, like basic indexing) + slice_dim_params: dict[int, tuple[int, int, int]] = {} + slice_bounds: list[tuple[int, int]] = [] + for old_dim in slice_dims: + sel = processed[old_dim] + assert isinstance(sel, slice) + lo = transform.domain.inclusive_min[old_dim] + hi = transform.domain.exclusive_max[old_dim] + start, step, origin, size = _resolve_slice_ts(sel, old_dim, lo, hi) + slice_bounds.append((origin, origin + size)) + slice_dim_params[old_dim] = (start, step, origin) + + n_before = _broadcast_insertion_point(array_dims, slice_dims) + + # Build the new domain with NumPy's placement rule: the broadcast + # (correlated) dimensions sit where the advanced indices sat when those are + # adjacent, and lead when a slice separates them. + new_inclusive_min = [lo for lo, _ in slice_bounds[:n_before]] + new_exclusive_max = [hi for _, hi in slice_bounds[:n_before]] + new_inclusive_min.extend([0] * len(broadcast_shape)) + new_exclusive_max.extend(broadcast_shape) + new_inclusive_min.extend(lo for lo, _ in slice_bounds[n_before:]) + new_exclusive_max.extend(hi for _, hi in slice_bounds[n_before:]) + + new_domain = IndexDomain( + inclusive_min=tuple(new_inclusive_min), + exclusive_max=tuple(new_exclusive_max), + ) + + # Build output maps + array_dim_to_broadcast: dict[int, np.ndarray[Any, np.dtype[np.intp]]] = {} + for i, d in enumerate(array_dims): + array_dim_to_broadcast[d] = broadcast_arrays[i] + + # New dim index for slice dims starts after broadcast dims + n_broadcast_dims = len(broadcast_shape) + + new_output: list[OutputIndexMap] = [] + for m in transform.output: + if isinstance(m, ConstantMap): + new_output.append(m) + elif isinstance(m, DimensionMap): + d = m.input_dimension + if d in array_dim_to_broadcast: + # Normalize to full input rank: the broadcast (correlated) axes + # come first, followed by a singleton axis per slice dimension. + # Every vectorized array shares the same broadcast axes, so the + # dependency axes derived from the shape coincide β€” the signature + # of a pointwise scatter rather than an outer product. + broadcast_arr = array_dim_to_broadcast[d] + full_arr = broadcast_arr.reshape( + (1,) * n_before + broadcast_shape + (1,) * (len(slice_dims) - n_before) + ) + new_output.append(array_map_or_constant(full_arr, offset=m.offset, stride=m.stride)) + else: + # Slice dim: new coord `origin + k` maps to old `start + k*step` + start, step, origin = slice_dim_params[d] + new_offset = m.offset + m.stride * (start - step * origin) + new_stride = m.stride * step + position = slice_dims.index(d) + new_input_dim = position if position < n_before else position + n_broadcast_dims + new_output.append( + DimensionMap( + input_dimension=new_input_dim, offset=new_offset, stride=new_stride + ) + ) + else: + # m: ArrayMap β€” unreachable: array-carrying transforms took the + # composition path at the top of this function. + raise AssertionError( # noqa: TRY004 - unreachable, not a dispatch + "unreachable: ArrayMap transforms are composed" + ) + + return IndexTransform(domain=new_domain, output=tuple(new_output)) + + +_LITERAL_HINT = ( + "; within this transform layer, indices are literal domain coordinates (the " + "public Array boundary wraps NumPy-style negatives before they reach here)" +) + + +def _trunc_div(a: int, b: int) -> int: + """Integer division rounded toward zero (C semantics), as TensorStore uses + for strided-slice domain origins β€” distinct from Python's floor division + for negative operands (`trunc(-9/2) == -4` where `-9 // 2 == -5`).""" + q = a // b + if q < 0 and q * b != a: + q += 1 + return q + + +def _resolve_slice_ts(sel: slice, dim: int, lo: int, hi: int) -> tuple[int, int, int, int]: + """Resolve a slice against domain `[lo, hi)` with TensorStore semantics. + + Slice bounds are **literal domain coordinates** β€” never from-the-end, never + clamped. One rule covers both signs of the step (each part verified against + tensorstore 0.1.84, and matching ndsel 1.0-draft.2 section 5.3): + + - defaults follow the direction of travel: `start = lo`, `stop = hi` going + up; `start = hi - 1`, `stop = lo - 1` going down; + - the traversal runs from `start` toward `stop`, which is excluded, so the + source interval is `[start, stop)` going up and `[stop + 1, start + 1)` + going down; + - a non-empty interval must be contained in the domain (no clamping β€” a + NumPy-style out-of-range or negative bound is an error, not a shorter or + wrapped result); + - an empty interval is valid anywhere, for either sign; + - an interval running the wrong way (`stop` on the far side of `start` from + the direction of travel) is an error, not an empty result; + - the result's domain origin is `trunc(start/step)` β€” toward zero, for both + signs β€” and coordinate `origin + k` maps to input `start + k*step`. + + A negative step normally produces a negative origin: reversing a + zero-origin axis of length 20 gives the domain `[-19, 1)`. The coordinate + frame stays anchored to the source; a caller that needs non-negative + coordinates re-bases explicitly with `translate_domain_to`. + + Returns `(start, step, origin, size)` in domain coordinates. + """ + start_bound = None if sel.start is None else require_index(sel.start) + stop_bound = None if sel.stop is None else require_index(sel.stop) + step = 1 if sel.step is None else require_index(sel.step) + if step == 0: + raise IndexError("slice step must not be zero") + if step > 0: + start = lo if start_bound is None else start_bound + stop = hi if stop_bound is None else stop_bound + interval_lo, interval_hi = start, stop + else: + start = hi - 1 if start_bound is None else start_bound + stop = lo - 1 if stop_bound is None else stop_bound + interval_lo, interval_hi = stop + 1, start + 1 + length = interval_hi - interval_lo + if length < 0: + raise IndexError( + f"slice from {start} to {stop} with step {step} does not specify a " + f"valid interval for dimension {dim}: the derived interval " + f"[{interval_lo}, {interval_hi}) runs the wrong way. An empty " + "selection is spelled stop == start." + ) + if length > 0 and (interval_lo < lo or interval_hi > hi): + hint = _LITERAL_HINT if (start < 0 or stop < 0) and lo >= 0 else "" + raise BoundsCheckError( + f"slice interval [{interval_lo}, {interval_hi}) is not contained " + f"within domain [{lo}, {hi}) for dimension {dim}{hint}" + ) + size = -(-length // abs(step)) # ceil(length / |step|) + origin = _trunc_div(start, step) + return start, step, origin, size + + +def _check_array_in_bounds(arr: np.ndarray[Any, np.dtype[np.intp]], lo: int, hi: int) -> None: + """Reject index-array values outside the domain `[lo, hi)`. + + Index-array values are literal domain coordinates (TensorStore semantics): + a value below `inclusive_min` is out of bounds rather than counting from + the end. Out-of-range values raise instead of silently wrapping. + """ + if arr.size == 0: + return + lo_val, hi_val = int(arr.min()), int(arr.max()) + if lo_val < lo: + hint = _LITERAL_HINT if lo_val < 0 and lo >= 0 else "" + raise BoundsCheckError( + f"index {lo_val} is out of bounds (valid indices [{lo}, {hi})){hint}" + ) + if hi_val >= hi: + raise BoundsCheckError(f"index {hi_val} is out of bounds (valid indices [{lo}, {hi}))") + + +def _validate_array_selection(selection: Any, shape: tuple[int, ...], mode: str) -> None: + """Validate array-based selections (orthogonal, vectorized). + + Rejects types that are not valid for coordinate/vectorized indexing. + Does not check bounds β€” the transform operations handle that. + """ + items = selection if isinstance(selection, tuple) else (selection,) + for sel in items: + if isinstance(sel, slice): + # vindex is coordinate-only (matches eager zarr): every axis needs an + # integer/boolean array, never a slice. Orthogonal (oindex) allows slices. + if mode == "vectorized": + raise VindexInvalidSelectionError( + "unsupported selection type for vectorized indexing; only " + "coordinate selection (tuple of integer arrays) and mask selection " + f"(single Boolean array) are supported; got {selection!r}" + ) + continue + if sel is Ellipsis or as_scalar_index(sel) is not None: + continue + if isinstance(sel, (list, np.ndarray)): + if mode == "orthogonal": + array = np.asarray(sel) + # An orthogonal selection is per-axis, so an integer array names + # coordinates along one axis and can only be one-dimensional. + # Left to the engine, this surfaced much later as a rank + # complaint about an `index_array` the caller never wrote. + if array.dtype.kind in "iu" and array.ndim > 1: + raise IndexError( + f"integer arrays in an orthogonal selection must be " + f"1-dimensional only; got one with {array.ndim} dimensions" + ) + continue + raise IndexError(f"unsupported selection type for {mode} indexing: {type(sel)!r}") + + +def _validate_basic_selection(selection: Any) -> None: + """Validate that a selection only contains basic indexing types (int, slice, Ellipsis). + + Rejects None (newaxis), arrays, lists, floats, strings, etc. + """ + items = selection if isinstance(selection, tuple) else (selection,) + for s in items: + if s is Ellipsis or isinstance(s, slice) or as_scalar_index(s) is not None: + continue + raise IndexError(f"unsupported selection type for basic indexing: {type(s)!r}") diff --git a/packages/zarr-indexing/tests/conformance/PROVENANCE.md b/packages/zarr-indexing/tests/conformance/PROVENANCE.md new file mode 100644 index 0000000000..749a2810e7 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/PROVENANCE.md @@ -0,0 +1,39 @@ +# Provenance of the ndsel conformance corpus + +The JSON fixtures in this directory (`point.json`, `box.json`, `slice.json`, +`points.json`, `transform.json`, `errors.json`) and `README.md` are **vendored, +unmodified**, from the ndsel reference repository. + +- **Source:** +- **Branch:** `main` (merge of d-v-b/ndsel#3, empty `index_array` serialization) +- **Commit:** `49b9e1db1ca93c55f320b025a666367de87a9014` (previously vendored: + `92d6a32df0cd1ac47d548f14f42909a95997cf19`, before that `c59bc556c`, itself + byte-identical to `c132b4c1caa3205830ce35a42502363171f650a7`) +- **Path in source:** `conformance/` + +**Do not edit these files.** They are vendored as-is so that +`zarr_indexing`' ndsel message layer can be checked against the same +language-agnostic corpus every other ndsel implementation runs. To update the +corpus, re-vendor from a newer ndsel commit and update the commit SHA above. + +ndsel PR #1 (merged) corrected the `slice` desugaring origin from +`floor(a/s)` to `trunc(a/s)` (rounding toward zero), which matches +`zarr_indexing`' existing `_trunc_div` semantics. + +ndsel PR #2 (merged) specified negative `step`, which changed two fixtures: + +- `slice.json` gained the negative-step cases (full reverse, `|s| > 1` + non-divisible, negative-coordinate intervals, empty-at-any-coordinate). +- `errors.json` retired `error/negative-step` β€” the reason code + `negative_step_unsupported` is retired with it β€” and replaced it with three + `bounds_out_of_order` fixtures pinning that a reversed interval is an error + for either sign of the step, rather than being clamped to empty. + +Re-vendoring those two files and teaching `zarr_indexing.messages` the new +desugaring are one change: the corpus is the definition of correct here, so it +lands in the same commit as the code that satisfies it. + +ndsel PR #3 (merged) specified empty `index_array` serialization, adding two +fixtures to `transform.json`: `normalize` carries an empty `index_array` +verbatim (it is not rewritten to a constant map), while a producer SHOULD +collapse it to a constant output map β€” which `zarr_indexing.json` already does. diff --git a/packages/zarr-indexing/tests/conformance/README.md b/packages/zarr-indexing/tests/conformance/README.md new file mode 100644 index 0000000000..ecb0c57ca2 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/README.md @@ -0,0 +1,16 @@ +# ndsel conformance corpus + +Language-agnostic fixtures. Each file is a JSON array of cases. + +A **success** case: + { "name": "...", "input": , "normalized": } + +An **error** case: + { "name": "...", "input": , "error": "" } + +An implementation is conformant iff, for every success case, +`normalize(input)` equals `normalized` by structural JSON equality, and for +every error case, `normalize(input)` is rejected with the given reason code. + +The `normalized` value is a canonical `transform` body (the `kind` field is +omitted; implementations compare the transform structure). diff --git a/packages/zarr-indexing/tests/conformance/box.json b/packages/zarr-indexing/tests/conformance/box.json new file mode 100644 index 0000000000..e847872f86 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/box.json @@ -0,0 +1,50 @@ +[ + { + "name": "box/2d-min-max", + "input": { "kind": "box", "inclusive_min": [0, 0], "exclusive_max": [3, 4] }, + "normalized": { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [3, 4], + "input_labels": ["", ""], + "output": [ + { "offset": 0, "stride": 1, "input_dimension": 0 }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + } + }, + { + "name": "box/shape-only-origin-zero", + "input": { "kind": "box", "shape": [5] }, + "normalized": { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [5], + "input_labels": [""], + "output": [ { "offset": 0, "stride": 1, "input_dimension": 0 } ] + } + }, + { + "name": "box/inclusive-max", + "input": { "kind": "box", "inclusive_min": [2], "inclusive_max": [9] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [2], "input_exclusive_max": [10], + "input_labels": [""], + "output": [ { "offset": 0, "stride": 1, "input_dimension": 0 } ] + } + }, + { + "name": "box/implicit-and-infinite-bounds", + "input": { "kind": "box", "inclusive_min": [["-inf"], 0], "exclusive_max": [["+inf"], 4], "labels": ["t", ""] }, + "normalized": { + "input_rank": 2, + "input_inclusive_min": [["-inf"], 0], + "input_exclusive_max": [["+inf"], 4], + "input_labels": ["t", ""], + "output": [ + { "offset": 0, "stride": 1, "input_dimension": 0 }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + } + } +] diff --git a/packages/zarr-indexing/tests/conformance/errors.json b/packages/zarr-indexing/tests/conformance/errors.json new file mode 100644 index 0000000000..072acd0af5 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/errors.json @@ -0,0 +1,25 @@ +[ + { "name": "error/step-zero", "input": { "kind": "slice", "start": [0], "stop": [4], "step": [0] }, "error": "step_zero" }, + { "name": "error/slice-reversed-interval-unit-step", "input": { "kind": "slice", "start": [9], "stop": [0] }, "error": "bounds_out_of_order" }, + { "name": "error/slice-reversed-interval-positive-step", "input": { "kind": "slice", "start": [9], "stop": [0], "step": [2] }, "error": "bounds_out_of_order" }, + { "name": "error/slice-reversed-interval-negative-step", "input": { "kind": "slice", "start": [5], "stop": [6], "step": [-1] }, "error": "bounds_out_of_order" }, + { "name": "error/multiple-upper-bounds", "input": { "kind": "box", "shape": [3], "exclusive_max": [3] }, "error": "multiple_upper_bounds" }, + { "name": "error/rank-mismatch", "input": { "kind": "slice", "start": [0, 0], "stop": [4] }, "error": "rank_mismatch" }, + { "name": "error/unknown-kind", "input": { "kind": "bogus" }, "error": "unknown_kind" }, + { "name": "error/transform-multiple-upper-bounds", "input": { "kind": "transform", "input_shape": [3], "input_exclusive_max": [3] }, "error": "multiple_upper_bounds" }, + { "name": "error/transform-rank-mismatch", "input": { "kind": "transform", "input_rank": 2, "input_inclusive_min": [0] }, "error": "rank_mismatch" }, + { "name": "error/missing-kind", "input": { "coords": [1, 2] }, "error": "invalid_json" }, + { "name": "error/point-missing-coords", "input": { "kind": "point" }, "error": "invalid_json" }, + { "name": "error/point-bool-coord", "input": { "kind": "point", "coords": [true] }, "error": "invalid_json" }, + { "name": "error/slice-missing-stop", "input": { "kind": "slice", "start": [0] }, "error": "invalid_json" }, + { "name": "error/box-non-list-bound", "input": { "kind": "box", "inclusive_min": 5 }, "error": "invalid_json" }, + { "name": "error/points-bool-coord", "input": { "kind": "points", "coords": [[true]] }, "error": "invalid_json" }, + { "name": "error/integer-out-of-i64-range", "input": { "kind": "point", "coords": [99999999999999999999] }, "error": "invalid_json" }, + { "name": "error/box-inverted-bounds", "input": { "kind": "box", "inclusive_min": [5], "exclusive_max": [3] }, "error": "bounds_out_of_order" }, + { "name": "error/box-negative-shape", "input": { "kind": "box", "shape": [-3] }, "error": "bounds_out_of_order" }, + { "name": "error/transform-inverted-bounds", "input": { "kind": "transform", "input_inclusive_min": [0], "input_exclusive_max": [-1] }, "error": "bounds_out_of_order" }, + { "name": "error/output-map-conflict", "input": { "kind": "transform", "output": [{ "input_dimension": 0, "index_array": [1, 2] }] }, "error": "output_map_conflict" }, + { "name": "error/box-unknown-field", "input": { "kind": "box", "shapee": [3] }, "error": "unknown_field" }, + { "name": "error/point-unknown-field", "input": { "kind": "point", "coords": [1], "extra": true }, "error": "unknown_field" }, + { "name": "error/output-map-unknown-field", "input": { "kind": "transform", "output": [{ "offset": 0, "bogus": 1 }] }, "error": "unknown_field" } +] diff --git a/packages/zarr-indexing/tests/conformance/point.json b/packages/zarr-indexing/tests/conformance/point.json new file mode 100644 index 0000000000..99a5ea16d8 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/point.json @@ -0,0 +1,30 @@ +[ + { + "name": "point/2d", + "input": { "kind": "point", "coords": [4, 7] }, + "normalized": { + "input_rank": 0, + "input_inclusive_min": [], + "input_exclusive_max": [], + "input_labels": [], + "output": [ { "offset": 4 }, { "offset": 7 } ] + } + }, + { + "name": "point/scalar-0d", + "input": { "kind": "point", "coords": [] }, + "normalized": { + "input_rank": 0, "input_inclusive_min": [], "input_exclusive_max": [], + "input_labels": [], "output": [] + } + }, + { + "name": "point/large-i64", + "input": { "kind": "point", "coords": [1152921504606846976] }, + "normalized": { + "input_rank": 0, "input_inclusive_min": [], "input_exclusive_max": [], + "input_labels": [], + "output": [ { "offset": 1152921504606846976 } ] + } + } +] diff --git a/packages/zarr-indexing/tests/conformance/points.json b/packages/zarr-indexing/tests/conformance/points.json new file mode 100644 index 0000000000..1ad92e12b1 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/points.json @@ -0,0 +1,34 @@ +[ + { + "name": "points/three-2d", + "input": { "kind": "points", "coords": [[1, 10], [2, 20], [3, 30]] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [0], "input_exclusive_max": [3], + "input_labels": [""], + "output": [ + { "offset": 0, "stride": 1, "index_array": [1, 2, 3], "index_array_bounds": ["-inf", "+inf"] }, + { "offset": 0, "stride": 1, "index_array": [10, 20, 30], "index_array_bounds": ["-inf", "+inf"] } + ] + } + }, + { + "name": "points/1d", + "input": { "kind": "points", "coords": [[5], [9], [2]] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [0], "input_exclusive_max": [3], + "input_labels": [""], + "output": [ + { "offset": 0, "stride": 1, "index_array": [5, 9, 2], "index_array_bounds": ["-inf", "+inf"] } + ] + } + }, + { + "name": "points/empty", + "input": { "kind": "points", "coords": [] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [0], "input_exclusive_max": [0], + "input_labels": [""], + "output": [] + } + } +] diff --git a/packages/zarr-indexing/tests/conformance/slice.json b/packages/zarr-indexing/tests/conformance/slice.json new file mode 100644 index 0000000000..959ebc6247 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/slice.json @@ -0,0 +1,156 @@ +[ + { + "name": "slice/unit-step-preserves-frame", + "input": { "kind": "slice", "start": [5], "stop": [10] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [5], "input_exclusive_max": [10], + "input_labels": [""], + "output": [ { "offset": 0, "stride": 1, "input_dimension": 0 } ] + } + }, + { + "name": "slice/divisible-stride", + "input": { "kind": "slice", "start": [4], "stop": [10], "step": [2] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [2], "input_exclusive_max": [5], + "input_labels": [""], + "output": [ { "offset": 0, "stride": 2, "input_dimension": 0 } ] + } + }, + { + "name": "slice/nondivisible-stride-phase-offset", + "input": { "kind": "slice", "start": [5], "stop": [10], "step": [2] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [2], "input_exclusive_max": [5], + "input_labels": [""], + "output": [ { "offset": 1, "stride": 2, "input_dimension": 0 } ] + } + }, + { + "name": "slice/2d-mixed-step", + "input": { "kind": "slice", "start": [0, 5], "stop": [10, 10], "step": [2, 1] }, + "normalized": { + "input_rank": 2, + "input_inclusive_min": [0, 5], + "input_exclusive_max": [5, 10], + "input_labels": ["", ""], + "output": [ + { "offset": 0, "stride": 2, "input_dimension": 0 }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + } + }, + { + "name": "slice/negative-start-trunc-origin", + "input": { "kind": "slice", "start": [-9], "stop": [5], "step": [2] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-4], "input_exclusive_max": [3], + "input_labels": [""], + "output": [ { "offset": -1, "stride": 2, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-start-trunc-origin-step3", + "input": { "kind": "slice", "start": [-8], "stop": [6], "step": [3] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-2], "input_exclusive_max": [3], + "input_labels": [""], + "output": [ { "offset": -2, "stride": 3, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-full-reverse", + "input": { "kind": "slice", "start": [19], "stop": [-1], "step": [-1] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-19], "input_exclusive_max": [1], + "input_labels": [""], + "output": [ { "offset": 0, "stride": -1, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-divisible-span", + "input": { "kind": "slice", "start": [15], "stop": [5], "step": [-2] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-7], "input_exclusive_max": [-2], + "input_labels": [""], + "output": [ { "offset": 1, "stride": -2, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-nondivisible-span", + "input": { "kind": "slice", "start": [15], "stop": [5], "step": [-4] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-3], "input_exclusive_max": [0], + "input_labels": [""], + "output": [ { "offset": 3, "stride": -4, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-down-to-zero", + "input": { "kind": "slice", "start": [9], "stop": [0], "step": [-2] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-4], "input_exclusive_max": [1], + "input_labels": [""], + "output": [ { "offset": 1, "stride": -2, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-negative-interval", + "input": { "kind": "slice", "start": [-1], "stop": [-6], "step": [-2] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [0], "input_exclusive_max": [3], + "input_labels": [""], + "output": [ { "offset": -1, "stride": -2, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-negative-interval-step3", + "input": { "kind": "slice", "start": [-2], "stop": [-9], "step": [-3] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [0], "input_exclusive_max": [3], + "input_labels": [""], + "output": [ { "offset": -2, "stride": -3, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-single-point", + "input": { "kind": "slice", "start": [5], "stop": [4], "step": [-3] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-1], "input_exclusive_max": [0], + "input_labels": [""], + "output": [ { "offset": 2, "stride": -3, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-empty", + "input": { "kind": "slice", "start": [5], "stop": [5], "step": [-1] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-5], "input_exclusive_max": [-5], + "input_labels": [""], + "output": [ { "offset": 0, "stride": -1, "input_dimension": 0 } ] + } + }, + { + "name": "slice/negative-step-keeps-labels", + "input": { "kind": "slice", "start": [19], "stop": [-1], "step": [-1], "labels": ["x"] }, + "normalized": { + "input_rank": 1, "input_inclusive_min": [-19], "input_exclusive_max": [1], + "input_labels": ["x"], + "output": [ { "offset": 0, "stride": -1, "input_dimension": 0 } ] + } + }, + { + "name": "slice/2d-mixed-sign-step", + "input": { "kind": "slice", "start": [19, 0], "stop": [-1, 10], "step": [-1, 2] }, + "normalized": { + "input_rank": 2, + "input_inclusive_min": [-19, 0], + "input_exclusive_max": [1, 5], + "input_labels": ["", ""], + "output": [ + { "offset": 0, "stride": -1, "input_dimension": 0 }, + { "offset": 0, "stride": 2, "input_dimension": 1 } + ] + } + } +] diff --git a/packages/zarr-indexing/tests/conformance/transform.json b/packages/zarr-indexing/tests/conformance/transform.json new file mode 100644 index 0000000000..3d12fe3352 --- /dev/null +++ b/packages/zarr-indexing/tests/conformance/transform.json @@ -0,0 +1,94 @@ +[ + { + "name": "transform/omitted-output-identity", + "input": { "kind": "transform", "input_inclusive_min": [0, 0], "input_exclusive_max": [3, 4] }, + "normalized": { + "input_rank": 2, "input_inclusive_min": [0, 0], "input_exclusive_max": [3, 4], + "input_labels": ["", ""], + "output": [ + { "offset": 0, "stride": 1, "input_dimension": 0 }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + } + }, + { + "name": "transform/implicit-bounds-and-labels", + "input": { + "kind": "transform", + "input_inclusive_min": [["-inf"], 7], + "input_exclusive_max": [["+inf"], 11], + "input_labels": ["x", "y"] + }, + "normalized": { + "input_rank": 2, + "input_inclusive_min": [["-inf"], 7], + "input_exclusive_max": [["+inf"], 11], + "input_labels": ["x", "y"], + "output": [ + { "offset": 0, "stride": 1, "input_dimension": 0 }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + } + }, + { + "name": "transform/explicit-output-all-three-map-kinds", + "input": { + "kind": "transform", + "input_inclusive_min": [0], + "input_exclusive_max": [3], + "output": [ + { "offset": 7 }, + { "input_dimension": 0, "stride": 2 }, + { "index_array": [1, 2, 3] } + ] + }, + "normalized": { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [3], + "input_labels": [""], + "output": [ + { "offset": 7 }, + { "offset": 0, "stride": 2, "input_dimension": 0 }, + { "offset": 0, "stride": 1, "index_array": [1, 2, 3], "index_array_bounds": ["-inf", "+inf"] } + ] + } + }, + { + "name": "transform/empty-index-array-carried-verbatim", + "input": { + "kind": "transform", + "input_inclusive_min": [0, 0], + "input_exclusive_max": [0, 3], + "output": [{ "index_array": [] }, { "input_dimension": 1 }] + }, + "normalized": { + "input_rank": 2, "input_inclusive_min": [0, 0], "input_exclusive_max": [0, 3], + "input_labels": ["", ""], + "output": [ + { "offset": 0, "stride": 1, "index_array": [], "index_array_bounds": ["-inf", "+inf"] }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + } + }, + { + "name": "transform/empty-index-array-is-idempotent", + "input": { + "input_rank": 2, "input_inclusive_min": [0, 0], "input_exclusive_max": [0, 3], + "input_labels": ["", ""], + "kind": "transform", + "output": [ + { "offset": 0, "stride": 1, "index_array": [], "index_array_bounds": ["-inf", "+inf"] }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + }, + "normalized": { + "input_rank": 2, "input_inclusive_min": [0, 0], "input_exclusive_max": [0, 3], + "input_labels": ["", ""], + "output": [ + { "offset": 0, "stride": 1, "index_array": [], "index_array_bounds": ["-inf", "+inf"] }, + { "offset": 0, "stride": 1, "input_dimension": 1 } + ] + } + } +] diff --git a/packages/zarr-indexing/tests/test_chunk_resolution.py b/packages/zarr-indexing/tests/test_chunk_resolution.py new file mode 100644 index 0000000000..fbd779f463 --- /dev/null +++ b/packages/zarr-indexing/tests/test_chunk_resolution.py @@ -0,0 +1,598 @@ +from __future__ import annotations + +from typing import Any + +import numpy as np +import pytest +from hypothesis import assume, given +from hypothesis import strategies as st + +import zarr_indexing +from zarr_indexing import ( + ChunkGrid, + ChunkPlan, + ChunkProjection, + FixedDimension, + VaryingDimension, + chunk_resolution, + plan_chunks, +) +from zarr_indexing.domain import IndexDomain +from zarr_indexing.grid import dimension_grids_from_chunks +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap +from zarr_indexing.transform import IndexTransform + + +def _storage_of(transform: IndexTransform, point: tuple[int, ...]) -> tuple[int, ...]: + """Evaluate the three map forms at one point, independently of planning.""" + result: list[int] = [] + for output_map in transform.output: + if isinstance(output_map, ConstantMap): + result.append(output_map.offset) + elif isinstance(output_map, DimensionMap): + result.append(output_map.offset + output_map.stride * point[output_map.input_dimension]) + else: + index = tuple( + 0 + if output_map.index_array.shape[axis] == 1 + else point[axis] - transform.domain.inclusive_min[axis] + for axis in range(output_map.index_array.ndim) + ) + result.append( + output_map.offset + output_map.stride * int(output_map.index_array[index]) + ) + return tuple(result) + + +def _points(domain: IndexDomain) -> list[tuple[int, ...]]: + """Enumerate a small finite domain in its own coordinates.""" + return [ + tuple( + coordinate + origin + for coordinate, origin in zip(position, domain.inclusive_min, strict=True) + ) + for position in np.ndindex(*domain.shape) + ] + + +def _count_intersect_calls(monkeypatch: pytest.MonkeyPatch) -> dict[str, int]: + """Count real intersections to protect touched-only candidate enumeration.""" + calls = {"n": 0} + original = IndexTransform.intersect + + def counting(self: IndexTransform, output_domain: IndexDomain) -> object: + calls["n"] += 1 + return original(self, output_domain) + + monkeypatch.setattr(IndexTransform, "intersect", counting) + return calls + + +def test_basic_plan_is_reiterable_and_projects_both_spaces() -> None: + """A plan can be revisited without losing either side of each projection.""" + transform = IndexTransform.from_shape((6,))[1:6] + grids = dimension_grids_from_chunks((3,), (6,)) + + plan = plan_chunks(transform, grids) + first = list(plan) + second = list(plan.projections()) + + assert isinstance(plan, ChunkPlan) + assert all(isinstance(projection, ChunkProjection) for projection in first) + assert [projection.chunk_coords for projection in first] == [(0,), (1,)] + assert [projection.chunk_domain for projection in first] == [ + IndexDomain((0,), (3,)), + IndexDomain((3,), (6,)), + ] + assert [projection.coverage for projection in first] == ["partial", "full"] + assert first == second + assert all( + projection.chunk_transform.domain == projection.cell_transform.domain + for projection in first + ) + assert all(projection.chunk_transform.domain.origin == (0,) for projection in first) + + +def test_projection_requires_one_shared_synthetic_domain() -> None: + """Paired transforms with different cell domains are rejected as incoherent.""" + with pytest.raises(ValueError, match="must share an input domain"): + ChunkProjection( + chunk_coords=(0,), + chunk_domain=IndexDomain.from_shape((3,)), + chunk_transform=IndexTransform.identity(IndexDomain.from_shape((2,))), + cell_transform=IndexTransform.identity(IndexDomain.from_shape((1,))), + coverage="partial", + ) + + +def test_projection_plan_is_the_only_public_chunk_resolution_surface() -> None: + """The greenfield API does not retain tuple or NumPy-selector bridges.""" + assert {"ChunkCoverage", "ChunkPlan", "ChunkProjection", "plan_chunks"} <= set( + zarr_indexing.__all__ + ) + assert "iter_chunk_transforms" not in zarr_indexing.__all__ + assert "sub_transform_to_selections" not in zarr_indexing.__all__ + + +def test_plan_rejects_grid_rank_different_from_transform_output_rank() -> None: + """A missing storage grid dimension is rejected before iteration.""" + transform = IndexTransform.from_shape((2, 3)) + + with pytest.raises(ValueError, match="1 grids for output rank 2"): + plan_chunks(transform, dimension_grids_from_chunks((2,), (2,))) + + +@pytest.mark.parametrize( + ("transform", "expected"), + [ + (IndexTransform.from_shape((5,)), ["full", "full"]), + (IndexTransform.from_shape((5,))[::-1], ["full", "full"]), + (IndexTransform.from_shape((5,))[::2], ["partial", "partial"]), + (IndexTransform.from_shape((5,))[2], ["partial"]), + ( + IndexTransform.from_shape((5,)).oindex[np.array([0, 1, 2, 3, 4])], + ["unknown", "unknown"], + ), + ], + ids=["clipped-edge", "reverse", "strided", "scalar", "fancy-is-conservative"], +) +def test_coverage_classification(transform: IndexTransform, expected: list[str]) -> None: + """Coverage is exact for affine requests and conservative for gathers.""" + grids = dimension_grids_from_chunks((3,), (5,)) + + assert [projection.coverage for projection in plan_chunks(transform, grids)] == expected + + +def test_repeated_input_dependency_is_not_full_coverage() -> None: + transform = IndexTransform( + domain=IndexDomain.from_shape((2,)), + output=(DimensionMap(input_dimension=0), DimensionMap(input_dimension=0)), + ) + grids = dimension_grids_from_chunks((2, 2), (2, 2)) + + assert [projection.coverage for projection in plan_chunks(transform, grids)] == ["partial"] + + +def test_unused_input_axis_is_not_full_coverage() -> None: + transform = IndexTransform( + domain=IndexDomain.from_shape((2, 2)), + output=(DimensionMap(input_dimension=0),), + ) + grids = dimension_grids_from_chunks((2,), (2,)) + + assert [projection.coverage for projection in plan_chunks(transform, grids)] == ["partial"] + + +@pytest.mark.parametrize( + ("transform", "grids"), + [ + ( + IndexTransform.from_shape((2, 3)), + dimension_grids_from_chunks((2, 3), (2, 3)), + ), + ( + IndexTransform( + domain=IndexDomain.from_shape((2, 3)), + output=(DimensionMap(input_dimension=1), DimensionMap(input_dimension=0)), + ), + dimension_grids_from_chunks((3, 2), (3, 2)), + ), + ( + IndexTransform.from_shape((2, 3))[::-1, ::-1], + dimension_grids_from_chunks((2, 3), (2, 3)), + ), + ( + IndexTransform( + domain=IndexDomain((4, 7), (6, 10)), + output=( + DimensionMap(input_dimension=0, offset=-4), + DimensionMap(input_dimension=1, offset=-7), + ), + ), + dimension_grids_from_chunks((2, 3), (2, 3)), + ), + ], + ids=["identity", "axis-permutation", "reversal", "translated-unit-affine"], +) +def test_bijective_unit_affine_transforms_retain_full_coverage( + transform: IndexTransform, grids: tuple[Any, ...] +) -> None: + assert [projection.coverage for projection in plan_chunks(transform, grids)] == ["full"] + + +def test_rank_zero_transform_has_full_coverage() -> None: + transform = IndexTransform.identity(IndexDomain((), ())) + + assert [projection.coverage for projection in plan_chunks(transform, ())] == ["full"] + + +@pytest.mark.parametrize( + ("transform", "grids", "expected_coords"), + [ + ( + IndexTransform.from_shape((30,)), + dimension_grids_from_chunks((10,), (30,)), + [(0,), (1,), (2,)], + ), + ( + IndexTransform.from_shape((20, 30)), + dimension_grids_from_chunks((10, 10), (20, 30)), + [(i, j) for i in range(2) for j in range(3)], + ), + ( + IndexTransform.from_shape((100, 100))[25, :], + dimension_grids_from_chunks((10, 10), (100, 100)), + [(2, j) for j in range(10)], + ), + ( + IndexTransform.from_shape((100,))[8:15], + dimension_grids_from_chunks((10,), (100,)), + [(0,), (1,)], + ), + ], + ids=["one-dimensional", "two-dimensional", "constant-map", "slice"], +) +def test_affine_plans_touch_the_expected_chunks( + transform: IndexTransform, + grids: tuple[Any, ...], + expected_coords: list[tuple[int, ...]], +) -> None: + """Identity, constant, and sliced transforms enumerate literal grid cells.""" + assert [projection.chunk_coords for projection in plan_chunks(transform, grids)] == ( + expected_coords + ) + + +@pytest.mark.parametrize( + ("transform", "grids"), + [ + ( + IndexTransform.from_shape((6,)).oindex[np.array([4, 0, 4, 2])], + dimension_grids_from_chunks((3,), (6,)), + ), + ( + IndexTransform.from_shape((4, 5)).oindex[np.array([3, 0]), np.array([4, 1, 1])], + dimension_grids_from_chunks(((1, 3), (2, 3)), (4, 5)), + ), + ( + IndexTransform.from_shape((2, 4, 5)).vindex[ + ..., np.array([3, 0, 3]), np.array([4, 1, 1]) + ], + dimension_grids_from_chunks((1, 2, 3), (2, 4, 5)), + ), + ], + ids=["repeated-oindex", "irregular-oindex", "vindex-with-residual"], +) +def test_projection_invariants_for_fancy_selections( + transform: IndexTransform, grids: tuple[Any, ...] +) -> None: + """Both transforms agree pointwise and cell ranges tile request space once.""" + plan = plan_chunks(transform, grids) + request_points: list[tuple[int, ...]] = [] + + for projection in plan: + assert projection.coverage == "unknown" + assert projection.chunk_transform.domain == projection.cell_transform.domain + for cell_point in _points(projection.cell_transform.domain): + request_point = _storage_of(projection.cell_transform, cell_point) + chunk_point = _storage_of(projection.chunk_transform, cell_point) + storage_point = _storage_of(plan.transform, request_point) + chunk_origin = projection.chunk_domain.inclusive_min + assert chunk_point == tuple( + value - origin for value, origin in zip(storage_point, chunk_origin, strict=True) + ) + assert all( + 0 <= value < extent + for value, extent in zip(chunk_point, projection.chunk_domain.shape, strict=True) + ) + request_points.append(request_point) + + assert sorted(request_points) == sorted(_points(transform.domain)) + + +@pytest.mark.parametrize( + "grid", + [ + pytest.param(FixedDimension(size=2, extent=4), id="fixed"), + pytest.param(VaryingDimension(edges=(1, 3), extent=4), id="varying"), + ], +) +def test_orthogonal_array_map_plan_rejects_coordinate_below_grid(grid: Any) -> None: + transform = IndexTransform( + domain=IndexDomain.from_shape((2,)), + output=(ArrayMap(np.array([-1, 1], dtype=np.intp)),), + ) + + # The sorted 1-D fast path reports the first offending coordinate. + with pytest.raises(IndexError, match=r"index -1 is out of bounds"): + list(plan_chunks(transform, (grid,))) + + +@pytest.mark.parametrize( + "grid", + [ + pytest.param(FixedDimension(size=2, extent=4), id="fixed"), + pytest.param(VaryingDimension(edges=(1, 3), extent=4), id="varying"), + ], +) +def test_orthogonal_array_map_plan_rejects_coordinate_above_grid(grid: Any) -> None: + transform = IndexTransform( + domain=IndexDomain.from_shape((2,)), + output=(ArrayMap(np.array([1, 4], dtype=np.intp)),), + ) + + # The sorted 1-D fast path reports the first offending coordinate. + with pytest.raises(IndexError, match=r"index 4 is out of bounds"): + list(plan_chunks(transform, (grid,))) + + +def test_nonempty_identity_plan_rejects_zero_size_fixed_dimension() -> None: + transform = IndexTransform.from_shape((4,)) + + with pytest.raises(ValueError, match="size must be > 0 when extent is nonzero"): + list(plan_chunks(transform, (FixedDimension(size=0, extent=4),))) + + +@given( + origin=st.integers(min_value=-4, max_value=4), + extent=st.integers(min_value=0, max_value=8), + stride=st.integers(min_value=-3, max_value=3), +) +def test_affine_projection_pairs_reconstruct_independent_source_coordinates( + origin: int, extent: int, stride: int +) -> None: + """Bounded literal-domain examples preserve every request/storage pair.""" + anchor = extent - 1 if stride < 0 else 0 + offset = anchor - stride * origin + expected_pairs = [ + ((coordinate,), (source_coordinate,)) + for coordinate in range(origin, origin + extent) + if 0 <= (source_coordinate := offset + stride * coordinate) < extent + ] + assume(expected_pairs) + + unrestricted = IndexTransform( + domain=IndexDomain((origin,), (origin + extent,)), + output=(DimensionMap(input_dimension=0, offset=offset, stride=stride),), + ) + intersection = unrestricted.intersect(IndexDomain.from_shape((extent,))) + assume(intersection is not None) + transform, _ = intersection + grids = dimension_grids_from_chunks((min(3, extent),), (extent,)) + + reconstructed_pairs = [ + ( + _storage_of(projection.cell_transform, cell_coordinate), + tuple( + local_coordinate + chunk_origin + for local_coordinate, chunk_origin in zip( + _storage_of(projection.chunk_transform, cell_coordinate), + projection.chunk_domain.inclusive_min, + strict=True, + ) + ), + ) + for projection in plan_chunks(transform, grids) + for cell_coordinate in _points(projection.cell_transform.domain) + ] + + assert sorted(reconstructed_pairs) == sorted(expected_pairs) + + +def test_correlated_projection_preserves_nonzero_request_coordinates() -> None: + base = IndexTransform.identity(IndexDomain((2, 5), (4, 8))) + transform = base.vindex[np.array([2, 3], dtype=np.intp), :] + grids = dimension_grids_from_chunks((2, 4), (4, 8)) + + points = [ + transform.apply(projection.cell_transform.apply(cell)) + for projection in plan_chunks(transform, grids) + for cell in _points(projection.cell_transform.domain) + ] + + assert sorted(points) == [(2, 5), (2, 6), (2, 7), (3, 5), (3, 6), (3, 7)] + + +def test_correlated_projection_preserves_translated_advanced_axis_coordinates() -> None: + transform = ( + IndexTransform.from_shape((4,)) + .vindex[np.array([0, 3], dtype=np.intp)] + .translate_domain_by((5,)) + ) + grids = dimension_grids_from_chunks((2,), (4,)) + + request_points = [ + projection.cell_transform.apply(cell) + for projection in plan_chunks(transform, grids) + for cell in _points(projection.cell_transform.domain) + ] + + assert sorted(request_points) == [(5,), (6,)] + + +def test_empty_request_has_no_projections() -> None: + """An empty fancy selection does not fabricate a touched chunk.""" + transform = IndexTransform.from_shape((10,)).oindex[np.array([], dtype=np.intp)] + grids = dimension_grids_from_chunks((3,), (10,)) + + assert list(plan_chunks(transform, grids)) == [] + + +class TestSortedOneDimensionalPlan: + def test_matches_general_resolution_for_randomized_selections( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """The direct sorted path has the same paired transforms as intersection.""" + rng = np.random.default_rng(0) + grids = ( + ChunkGrid(dimensions=(FixedDimension(size=7, extent=30),)), + ChunkGrid(dimensions=(VaryingDimension(edges=(3, 4, 8, 5, 10), extent=30),)), + ) + for grid in grids: + for _ in range(50): + indices = np.sort(rng.integers(0, 30, size=int(rng.integers(1, 80)))).astype( + np.intp + ) + transform = IndexTransform.from_shape((30,)).vindex[indices] + direct = list(plan_chunks(transform, grid.dimensions)) + with monkeypatch.context() as context: + context.setattr( + chunk_resolution, + "_one_dimensional_array_map", + lambda _transform: None, + ) + general = list(plan_chunks(transform, grid.dimensions)) + assert direct == general + + def test_sorted_coordinates_bypass_intersection(self, monkeypatch: pytest.MonkeyPatch) -> None: + """Sorted coordinates partition directly at touched chunk boundaries.""" + transform = IndexTransform.from_shape((12,)).vindex[ + np.array([0, 3, 4, 4, 9, 11], dtype=np.intp) + ] + grid = ChunkGrid(dimensions=(FixedDimension(size=4, extent=12),)) + calls = _count_intersect_calls(monkeypatch) + + projections = list(plan_chunks(transform, grid.dimensions)) + + assert [projection.chunk_coords for projection in projections] == [(0,), (1,), (2,)] + assert calls["n"] == 0 + assert [ + [ + _storage_of(projection.cell_transform, point)[0] + for point in _points(projection.cell_transform.domain) + ] + for projection in projections + ] == [[0, 1], [2, 3], [4, 5]] + + def test_unsorted_coordinates_use_intersection(self, monkeypatch: pytest.MonkeyPatch) -> None: + """Unsorted coordinates retain the general intersection path.""" + transform = IndexTransform.from_shape((12,)).vindex[np.array([9, 0, 4], dtype=np.intp)] + grid = ChunkGrid(dimensions=(FixedDimension(size=4, extent=12),)) + calls = _count_intersect_calls(monkeypatch) + + projections = list(plan_chunks(transform, grid.dimensions)) + + assert [projection.chunk_coords for projection in projections] == [(0,), (1,), (2,)] + assert calls["n"] == 3 + + +class CountingUnitGrid: + """A real unit grid that counts every planner-grid operation.""" + + def __init__(self, extent: int) -> None: + self._grid = FixedDimension(size=1, extent=extent) + self.calls = 0 + + def index_to_chunk(self, idx: int) -> int: + self.calls += 1 + return self._grid.index_to_chunk(idx) + + def chunk_offset(self, chunk_ix: int) -> int: + self.calls += 1 + return self._grid.chunk_offset(chunk_ix) + + def chunk_size(self, chunk_ix: int) -> int: + self.calls += 1 + return self._grid.chunk_size(chunk_ix) + + def indices_to_chunks( + self, indices: np.ndarray[Any, np.dtype[np.intp]] + ) -> np.ndarray[Any, np.dtype[np.intp]]: + self.calls += 1 + return self._grid.indices_to_chunks(indices) + + +def test_sparse_affine_plan_does_not_visit_intervening_chunks() -> None: + grid = CountingUnitGrid(extent=100_001) + transform = IndexTransform.from_shape((100_001,))[::100_000] + + assert [projection.chunk_coords for projection in plan_chunks(transform, (grid,))] == [ + (0,), + (100_000,), + ] + assert grid.calls <= 12 + + +def test_sparse_affine_plan_handles_large_origin_cancellation() -> None: + origin = int(np.iinfo(np.intp).max) + transform = IndexTransform( + domain=IndexDomain((origin,), (origin + 2,)), + output=(DimensionMap(input_dimension=0, offset=-2 * origin, stride=2),), + ) + grids = dimension_grids_from_chunks((1,), (3,)) + + assert [projection.chunk_coords for projection in plan_chunks(transform, grids)] == [ + (0,), + (2,), + ] + + +class TestTouchedOnlyCandidateEnumeration: + def test_sparse_one_dimensional_selection_skips_the_dense_span( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Two sorted points on a 1000-cell grid require no intersections.""" + transform = IndexTransform.from_shape((4000,)).vindex[np.array([1, 3997], dtype=np.intp)] + grid = ChunkGrid(dimensions=(FixedDimension(size=4, extent=4000),)) + calls = _count_intersect_calls(monkeypatch) + + projections = list(plan_chunks(transform, grid.dimensions)) + + assert [projection.chunk_coords for projection in projections] == [(0,), (999,)] + assert calls["n"] == 0 + + @pytest.mark.parametrize( + ("mode", "expected_coords", "expected_calls"), + [ + ("orthogonal", [(0, 0), (0, 999), (999, 0), (999, 999)], 4), + ("correlated", [(0, 0), (999, 999)], 2), + ], + ) + def test_sparse_two_dimensional_selection_uses_only_touched_combinations( + self, + monkeypatch: pytest.MonkeyPatch, + mode: str, + expected_coords: list[tuple[int, int]], + expected_calls: int, + ) -> None: + """Orthogonal points use their outer product; correlated points remain paired.""" + base = IndexTransform.from_shape((4000, 4000)) + first = np.array([1, 3997], dtype=np.intp) + second = np.array([2, 3998], dtype=np.intp) + transform = ( + base.oindex[first, second] if mode == "orthogonal" else base.vindex[first, second] + ) + grid = ChunkGrid( + dimensions=( + FixedDimension(size=4, extent=4000), + FixedDimension(size=4, extent=4000), + ) + ) + calls = _count_intersect_calls(monkeypatch) + + projections = list(plan_chunks(transform, grid.dimensions)) + + assert sorted(projection.chunk_coords for projection in projections) == expected_coords + assert calls["n"] == expected_calls + + def test_correlated_diagonal_scales_with_points_not_their_product( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Fifty diagonal points require fifty, rather than 2500, intersections.""" + n_points = 50 + coordinates = np.arange(n_points, dtype=np.intp) * 8 + transform = IndexTransform.from_shape((4000, 4000)).vindex[coordinates, coordinates] + grid = ChunkGrid( + dimensions=( + FixedDimension(size=4, extent=4000), + FixedDimension(size=4, extent=4000), + ) + ) + calls = _count_intersect_calls(monkeypatch) + + projections = list(plan_chunks(transform, grid.dimensions)) + + assert sorted(projection.chunk_coords for projection in projections) == [ + (2 * index, 2 * index) for index in range(n_points) + ] + assert calls["n"] == n_points diff --git a/packages/zarr-indexing/tests/test_composition.py b/packages/zarr-indexing/tests/test_composition.py new file mode 100644 index 0000000000..0cb6155344 --- /dev/null +++ b/packages/zarr-indexing/tests/test_composition.py @@ -0,0 +1,474 @@ +from __future__ import annotations + +import numpy as np +import pytest + +from zarr_indexing.domain import IndexDomain +from zarr_indexing.errors import BoundsCheckError +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap +from zarr_indexing.transform import IndexTransform + + +class TestComposeConstantInner: + """Inner = constant. Result is always constant.""" + + def test_constant_inner_any_outer(self) -> None: + outer = IndexTransform.from_shape((5,)) + inner = IndexTransform( + domain=IndexDomain.from_shape((5,)), + output=(ConstantMap(offset=42),), + ) + result = outer.compose(inner) + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == 42 + + +class TestComposeDimensionInner: + """Inner = DimensionMap.""" + + def test_dimension_inner_constant_outer(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(ConstantMap(offset=5),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(DimensionMap(input_dimension=0, offset=10, stride=3),), + ) + result = outer.compose(inner) + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == 25 + + def test_dimension_inner_constant_outer_rejects_affine_overflow(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ConstantMap(offset=2**62),), + ) + inner = IndexTransform( + domain=IndexDomain((2**62,), (2**62 + 1,)), + output=(DimensionMap(input_dimension=0, stride=4),), + ) + + with pytest.raises(OverflowError, match="outside np.intp"): + outer.compose(inner) + + def test_dimension_inner_dimension_outer(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(DimensionMap(input_dimension=0, offset=5, stride=2),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(DimensionMap(input_dimension=0, offset=10, stride=3),), + ) + result = outer.compose(inner) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == 25 + assert result.output[0].stride == 6 + assert result.output[0].input_dimension == 0 + + def test_dimension_inner_array_outer(self) -> None: + arr = np.array([0, 1, 2], dtype=np.intp) + outer = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(index_array=arr, offset=5, stride=2),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(DimensionMap(input_dimension=0, offset=10, stride=3),), + ) + result = outer.compose(inner) + assert isinstance(result.output[0], ArrayMap) + assert result.output[0].offset == 25 + assert result.output[0].stride == 6 + np.testing.assert_array_equal(result.output[0].index_array, arr) + + +class TestComposeArrayInner: + """Inner = ArrayMap.""" + + def test_array_inner_constant_outer(self) -> None: + inner_arr = np.array([10, 20, 30], dtype=np.intp) + outer = IndexTransform( + domain=IndexDomain.from_shape((5,)), + output=(ConstantMap(offset=1),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(index_array=inner_arr, offset=0, stride=1),), + ) + result = outer.compose(inner) + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == 20 + + def test_array_inner_constant_outer_rejects_affine_overflow(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ConstantMap(offset=0),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ArrayMap(np.array([2**62], dtype=np.intp), stride=4),), + ) + + with pytest.raises(OverflowError, match="outside np.intp"): + outer.compose(inner) + + def test_array_inner_array_outer(self) -> None: + outer_arr = np.array([0, 2, 1], dtype=np.intp) + inner_arr = np.array([10, 20, 30], dtype=np.intp) + outer = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(index_array=outer_arr, offset=0, stride=1),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(index_array=inner_arr, offset=0, stride=1),), + ) + result = outer.compose(inner) + assert isinstance(result.output[0], ArrayMap) + expected = np.array([10, 30, 20], dtype=np.intp) + np.testing.assert_array_equal(result.output[0].index_array, expected) + + +def _storage_of(transform: IndexTransform, point: tuple[int, ...]) -> tuple[int, ...]: + """The storage coordinates a transform assigns to one input point. + + The point is given in the transform's own domain coordinates; an index array + carries the full input rank, singleton on the axes it does not vary over, and + is addressed positionally from the domain origin. + """ + coords: list[int] = [] + for m in transform.output: + if isinstance(m, ConstantMap): + coords.append(m.offset) + elif isinstance(m, DimensionMap): + coords.append(m.offset + m.stride * point[m.input_dimension]) + else: + origin = transform.domain.inclusive_min + idx = tuple( + 0 if m.index_array.shape[axis] == 1 else point[axis] - origin[axis] + for axis in range(m.index_array.ndim) + ) + coords.append(m.offset + m.stride * int(m.index_array[idx])) + return tuple(coords) + + +def _assert_composes_pointwise(outer: IndexTransform, inner: IndexTransform) -> None: + """`outer.compose(inner)` must agree with running the two in sequence.""" + composed = outer.compose(inner) + assert composed.domain == outer.domain + lo = outer.domain.inclusive_min + hi = outer.domain.exclusive_max + for coord in np.ndindex(*outer.domain.shape): + point = tuple(int(c) + int(o) for c, o in zip(coord, lo, strict=True)) + assert all(point[d] < hi[d] for d in range(len(hi))) + intermediate = _storage_of(outer, point) + assert _storage_of(composed, point) == _storage_of(inner, intermediate) + + +class TestComposeOverANonZeroOriginDomain: + """The outer domain need not start at 0 β€” a step-1 slice preserves its + literal bounds and a negative step produces a negative origin β€” so the inner + map has to be evaluated over the outer domain's real range.""" + + def test_array_inner_sliced_outer(self) -> None: + inner = IndexTransform.from_shape((10,)).oindex[np.array([3, 1, 4, 1, 5])] + outer = IndexTransform.identity(IndexDomain.from_shape((5,)))[1:4] + assert outer.domain.inclusive_min == (1,) + result = outer.compose(inner) + assert isinstance(result.output[0], ArrayMap) + np.testing.assert_array_equal( + result.output[0].index_array, np.array([1, 4, 1], dtype=np.intp) + ) + _assert_composes_pointwise(outer, inner) + + def test_array_inner_reversed_outer(self) -> None: + inner = IndexTransform.from_shape((10,)).oindex[np.array([3, 1, 4, 1, 5])] + outer = IndexTransform.identity(IndexDomain.from_shape((5,)))[::-1] + assert outer.domain.inclusive_min == (-4,) + result = outer.compose(inner) + assert isinstance(result.output[0], ArrayMap) + np.testing.assert_array_equal( + result.output[0].index_array, np.array([5, 1, 4, 1, 3], dtype=np.intp) + ) + _assert_composes_pointwise(outer, inner) + + def test_array_inner_strided_outer(self) -> None: + inner = IndexTransform.from_shape((10,)).oindex[np.array([3, 1, 4, 1, 5, 9])] + outer = IndexTransform.identity(IndexDomain.from_shape((6,)))[1::2] + _assert_composes_pointwise(outer, inner) + + def test_array_inner_translated_outer(self) -> None: + inner = IndexTransform.from_shape((10,)).oindex[np.array([3, 1, 4, 1, 5])] + outer = IndexTransform.identity(IndexDomain.from_shape((5,))).translate_domain_to((-2,)) + _assert_composes_pointwise(outer, inner) + + def test_array_inner_array_outer_over_a_shifted_domain(self) -> None: + inner = IndexTransform.from_shape((10,)).oindex[np.array([3, 1, 4, 1, 5])] + outer = IndexTransform.from_shape((5,)).oindex[np.array([4, 0, 2])] + _assert_composes_pointwise(outer, inner) + + def test_array_inner_constant_outer_over_a_shifted_domain(self) -> None: + inner = IndexTransform.from_shape((10,)).oindex[np.array([3, 1, 4, 1, 5])] + outer = IndexTransform( + domain=IndexDomain.from_shape((4,)), + output=(ConstantMap(offset=3),), + ) + _assert_composes_pointwise(outer, inner) + + +class TestComposeMultiDim: + def test_2d_identity_compose(self) -> None: + a = IndexTransform.from_shape((10, 20)) + b = IndexTransform.from_shape((10, 20)) + result = a.compose(b) + assert result.domain.shape == (10, 20) + for i in range(2): + m = result.output[i] + assert isinstance(m, DimensionMap) + assert m.input_dimension == i + assert m.offset == 0 + assert m.stride == 1 + + def test_mixed_map_types(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=( + ConstantMap(offset=5), + DimensionMap(input_dimension=0, offset=0, stride=1), + ), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((10, 10)), + output=( + DimensionMap(input_dimension=0, offset=2, stride=3), + DimensionMap(input_dimension=1, offset=0, stride=1), + ), + ) + result = outer.compose(inner) + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == 17 + assert isinstance(result.output[1], DimensionMap) + assert result.output[1].input_dimension == 0 + assert result.output[1].offset == 0 + assert result.output[1].stride == 1 + + def test_rank_mismatch_raises(self) -> None: + outer = IndexTransform.from_shape((10,)) + inner = IndexTransform.from_shape((10, 20)) + with pytest.raises(ValueError, match="rank"): + outer.compose(inner) + + +class TestComposeInnerDomainValidation: + @pytest.mark.parametrize( + ("outer_map", "inner_lower"), + [ + (ConstantMap(offset=10), 10), + (ConstantMap(offset=14), 10), + (DimensionMap(input_dimension=0, offset=10, stride=1), 10), + (DimensionMap(input_dimension=0, offset=14, stride=-1), 10), + (DimensionMap(input_dimension=0, offset=10**100, stride=1), 10**100), + ], + ids=["lower-bound", "upper-bound", "forward", "reverse", "arbitrary-integer"], + ) + def test_valid_constant_and_affine_boundaries( + self, outer_map: ConstantMap | DimensionMap, inner_lower: int + ) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((5,)), + output=(outer_map,), + ) + inner = IndexTransform( + domain=IndexDomain((inner_lower,), (inner_lower + 5,)), + output=(DimensionMap(input_dimension=0),), + ) + + result = outer.compose(inner) + + assert result.domain == outer.domain + _assert_composes_pointwise(outer, inner) + + def test_rejects_constant_outer_coordinate_outside_inner_domain(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ConstantMap(offset=2),), + ) + inner = IndexTransform.identity(IndexDomain((0,), (2,))) + + with pytest.raises(BoundsCheckError, match="outside.*inner.*domain"): + outer.compose(inner) + + def test_rejects_affine_outer_range_crossing_inner_domain(self) -> None: + outer = IndexTransform( + domain=IndexDomain((10**100,), (10**100 + 3,)), + output=(DimensionMap(input_dimension=0),), + ) + inner = IndexTransform.identity(IndexDomain((10**100,), (10**100 + 2,))) + + with pytest.raises(BoundsCheckError, match="outside.*inner.*domain"): + outer.compose(inner) + + def test_empty_outer_domain_does_not_evaluate_nonexistent_points(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((0,)), + output=(ConstantMap(offset=99),), + ) + inner = IndexTransform.identity(IndexDomain((0,), (2,))) + + result = outer.compose(inner) + + assert result.domain.shape == (0,) + assert result.output == (ConstantMap(offset=99),) + + +class TestComposeMultidimensionalArrayInner: + def test_identity_gathers_a_two_dimensional_array_map(self) -> None: + inner = IndexTransform( + domain=IndexDomain.from_shape((2, 3)), + output=( + ArrayMap( + index_array=np.array([[11, 13, 17], [19, 23, 29]], dtype=np.intp), + offset=5, + stride=2, + ), + ), + ) + outer = IndexTransform.identity(inner.domain) + + result = outer.compose(inner) + + assert result == inner + _assert_composes_pointwise(outer, inner) + + def test_mixed_affine_and_constant_outputs_gather_with_metadata(self) -> None: + inner = IndexTransform( + domain=IndexDomain((4, 8), (7, 10)), + output=( + ArrayMap( + index_array=np.array([[2, 3], [5, 7], [11, 13]], dtype=np.intp), + offset=-3, + stride=4, + ), + ), + ) + outer = IndexTransform( + domain=IndexDomain((-2,), (0,)), + output=( + DimensionMap(input_dimension=0, offset=7, stride=1), + ConstantMap(offset=9), + ), + ) + + result = outer.compose(inner) + + assert result.domain == outer.domain + assert len(result.output) == 1 + array_map = result.output[0] + assert isinstance(array_map, ArrayMap) + assert array_map.index_array.shape == (2,) + assert array_map.offset == -3 + assert array_map.stride == 4 + np.testing.assert_array_equal(array_map.index_array, np.array([7, 13], dtype=np.intp)) + _assert_composes_pointwise(outer, inner) + + def test_out_of_bounds_affine_output_is_rejected_before_gather(self) -> None: + outer = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=( + DimensionMap(input_dimension=0, offset=1, stride=1), + ConstantMap(offset=0), + ), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((3, 2)), + output=(ArrayMap(np.arange(6, dtype=np.intp).reshape(3, 2)),), + ) + + with pytest.raises(BoundsCheckError, match="outside.*inner.*domain"): + outer.compose(inner) + + def test_rank_zero_array_map_composition(self) -> None: + domain = IndexDomain((), ()) + outer = IndexTransform.identity(domain) + inner = IndexTransform( + domain=domain, + output=(ArrayMap(np.array(7, dtype=np.intp), offset=2, stride=3),), + ) + + result = outer.compose(inner) + + assert result.domain == domain + assert result.output == (ConstantMap(offset=23),) + + +class TestComposeChain: + def test_three_transforms(self) -> None: + a = IndexTransform.from_shape((100,)) + b = IndexTransform( + domain=IndexDomain.from_shape((100,)), + output=(DimensionMap(input_dimension=0, offset=10, stride=1),), + ) + c = IndexTransform( + domain=IndexDomain.from_shape((110,)), + output=(DimensionMap(input_dimension=0, offset=5, stride=2),), + ) + bc = b.compose(c) + abc = a.compose(bc) + assert isinstance(abc.output[0], DimensionMap) + assert abc.output[0].offset == 25 + assert abc.output[0].stride == 2 + + +def test_composing_an_inner_array_with_a_broadcast_axis_wider_than_one_cell() -> None: + """A non-dependency axis is a singleton that broadcasts, so its coordinate is 0. + + Indexing it by the raw intermediate coordinate walked off the end of an axis + the array only has one entry for. + """ + outer = IndexTransform( + domain=IndexDomain(inclusive_min=(-2,), exclusive_max=(0,)), + output=(ConstantMap(offset=1), ConstantMap(offset=0)), + ) + inner = IndexTransform( + domain=IndexDomain(inclusive_min=(0, 0), exclusive_max=(2, 1)), + output=(ArrayMap(index_array=np.array([[13]], dtype=np.intp), offset=-2, stride=2),), + ) + composed = outer.compose(inner) + assert composed.output[0] == ConstantMap(offset=24) + + +def test_composing_a_one_dimensional_inner_array_under_a_higher_rank_outer() -> None: + """The shortcut gated on the output rank but sized by the input rank. + + A rank-2 outer therefore built a rank-1 array for a rank-2 domain, which the + engine's own invariant then rejected. + """ + outer = IndexTransform( + domain=IndexDomain.from_shape((2, 3)), + output=(DimensionMap(input_dimension=0, offset=1, stride=1),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((4,)), + output=(ArrayMap(index_array=np.array([7, 3, 5, 1], dtype=np.intp)),), + ) + composed = outer.compose(inner) + array_map = composed.output[0] + assert isinstance(array_map, ArrayMap) + assert array_map.index_array.shape == (2, 1) + np.testing.assert_array_equal(array_map.index_array, np.array([[3], [5]])) + + +def test_composing_out_of_the_inner_domain_is_refused() -> None: + """An intermediate outside the inner domain wrapped NumPy-style and read a cell.""" + outer = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ConstantMap(offset=-3),), + ) + inner = IndexTransform( + domain=IndexDomain.from_shape((2,)), + output=(ArrayMap(index_array=np.array([7, 3], dtype=np.intp)),), + ) + with pytest.raises(BoundsCheckError, match="outside.*inner.*domain"): + outer.compose(inner) diff --git a/packages/zarr-indexing/tests/test_conformance.py b/packages/zarr-indexing/tests/test_conformance.py new file mode 100644 index 0000000000..207a9d8236 --- /dev/null +++ b/packages/zarr-indexing/tests/test_conformance.py @@ -0,0 +1,55 @@ +"""ndsel conformance corpus harness. + +Runs the vendored, language-agnostic ndsel fixtures (see +`tests/conformance/PROVENANCE.md`) against this package's message layer +(`zarr_indexing.messages`). An implementation is conformant iff: + +- for every *success* fixture, `normalize_ndsel(input)` equals the fixture's + `normalized` value by structural JSON equality; +- for every *error* fixture, `normalize_ndsel(input)` is rejected with an + `NdselError` carrying the fixture's `error` reason code. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from zarr_indexing.messages import NdselError, normalize_ndsel + +_CONFORMANCE_DIR = Path(__file__).parent / "conformance" + + +def _load_cases() -> list[tuple[str, dict[str, Any]]]: + cases: list[tuple[str, dict[str, Any]]] = [] + for path in sorted(_CONFORMANCE_DIR.glob("*.json")): + data = json.loads(path.read_text()) + cases.extend((f"{path.stem}::{case['name']}", case) for case in data) + return cases + + +_CASES = _load_cases() +_SUCCESS = [(name, c) for name, c in _CASES if "normalized" in c] +_ERROR = [(name, c) for name, c in _CASES if "error" in c] + + +def test_corpus_is_present() -> None: + # Guard against an empty/missing vendored corpus silently passing. + assert len(_SUCCESS) > 0 + assert len(_ERROR) > 0 + + +@pytest.mark.parametrize(("name", "case"), _SUCCESS, ids=[name for name, _ in _SUCCESS]) +def test_success_fixture(name: str, case: dict[str, Any]) -> None: + result = normalize_ndsel(case["input"]) + assert result == case["normalized"] + + +@pytest.mark.parametrize(("name", "case"), _ERROR, ids=[name for name, _ in _ERROR]) +def test_error_fixture(name: str, case: dict[str, Any]) -> None: + with pytest.raises(NdselError) as excinfo: + normalize_ndsel(case["input"]) + assert excinfo.value.reason == case["error"] diff --git a/packages/zarr-indexing/tests/test_doc_examples.py b/packages/zarr-indexing/tests/test_doc_examples.py new file mode 100644 index 0000000000..240bd48531 --- /dev/null +++ b/packages/zarr-indexing/tests/test_doc_examples.py @@ -0,0 +1,488 @@ +"""Executable documentation contracts. + +Two kinds of test live here, and nothing else: + +1. **Structural.** Every snippet include in the rendered docs resolves to a + real file and a balanced, non-empty region β€” discovered by scanning the + markdown, never hand-registered β€” and every example file executes. The + examples carry their own inline assertions, so executing one *is* the + value check; expected values are stated once, in the example, beside the + prose that narrates them. +2. **Behavioral.** Documented classes are exercised where the example cannot + assert the behavior itself: error paths, cache lifecycle invariants, and + contracts stated in prose about types the docs define. + +Editorial choices β€” section order, exact wording, teaching progression β€” are +deliberately not pinned here; they belong to review. Structural breakage +belongs to `mkdocs build --strict`, whose configuration makes it actually +fail on the relevant classes: `check_paths: true` for unresolvable includes, +and `validation` set to warn (strict turns warnings into errors) for broken +link anchors and nav-omitted pages. +""" + +from __future__ import annotations + +import re +import runpy +import subprocess +import sys +from pathlib import Path +from typing import Any + +import numpy as np +import pytest + +import zarr_indexing +import zarr_indexing.lazy_array as lazy_array_module +from zarr_indexing import IndexTransform, LazyArray, ReadContext + +DOCS = Path(__file__).parents[1] / "docs" +PACKAGE_ROOT = DOCS.parent +STANDALONE_EXAMPLES = PACKAGE_ROOT / "examples" +DOC_SNIPPETS_DIR = DOCS / "snippets" +CACHE_EXAMPLE = STANDALONE_EXAMPLES / "system_memory_chunk_cache" / "system_memory_chunk_cache.py" + +# Mirrors `pymdownx.snippets: base_path` in mkdocs.yml. If that list changes, +# change this one in the same commit. +SNIPPET_BASE_PATHS = (DOCS, STANDALONE_EXAMPLES) + +_INCLUDE = re.compile(r'--8<--\s+"(?P[^":\n]+?)(?::(?P[^"\n]+))?"') + + +def _markdown_includes() -> tuple[tuple[str, str, str | None], ...]: + """Every snippet include in the rendered docs: (page, target, region).""" + return tuple( + (str(page.relative_to(DOCS)), match["target"], match["region"]) + for page in sorted(DOCS.rglob("*.md")) + for match in _INCLUDE.finditer(page.read_text()) + ) + + +INCLUDES = _markdown_includes() +# In-process executables: every snippet, plus the one standalone example that +# is importable as a module. The lazy_indexing_* examples are CLI scripts +# (they parse argv and call sys.exit), so they run as subprocesses below β€” +# no other test in the repository executes them. +EXECUTABLES = (*sorted(DOC_SNIPPETS_DIR.glob("*.py")), CACHE_EXAMPLE) +CLI_EXAMPLES = tuple( + script for script in sorted(STANDALONE_EXAMPLES.glob("*/*.py")) if script not in EXECUTABLES +) + +PATTERN_NAMESPACE: dict[str, Any] = runpy.run_path(str(DOC_SNIPPETS_DIR / "indexing_patterns.py")) +PATTERN_CASES: tuple[dict[str, Any], ...] = PATTERN_NAMESPACE["PATTERN_CASES"] +CACHE_NAMESPACE: dict[str, Any] = runpy.run_path(str(CACHE_EXAMPLE)) + +# The documented pattern matrix must keep covering every selection family. +REQUIRED_PATTERNS = { + "basic-slice", + "integer-axis-removal", + "negative-stride", + "empty-selection", + "boolean-mask", + "orthogonal", + "vectorized", + "broadcasting", + "repeated-out-of-order", +} + + +# --------------------------------------------------------------------------- # +# Structural: the include graph and the executable examples +# --------------------------------------------------------------------------- # + + +def test_docs_reference_snippets_at_all() -> None: + """An empty scan means the include regex rotted, not that the docs did.""" + assert len(INCLUDES) >= 10 + assert any(region for _, _, region in INCLUDES) + + +@pytest.mark.parametrize( + ("page", "target", "region"), + INCLUDES, + ids=[ + f"{page}->{target}" + (f":{region}" if region else "") for page, target, region in INCLUDES + ], +) +def test_markdown_include_resolves(page: str, target: str, region: str | None) -> None: + """Each include names exactly one real file; each region is balanced and non-empty.""" + resolved = [base / target for base in SNIPPET_BASE_PATHS if (base / target).is_file()] + assert len(resolved) == 1, f"{page} includes {target!r}: resolved to {resolved or 'nothing'}" + if region is None: + return + source = resolved[0].read_text() + starts = re.findall(rf"^\s*# --8<-- \[start:{re.escape(region)}\]$", source, re.MULTILINE) + ends = re.findall(rf"^\s*# --8<-- \[end:{re.escape(region)}\]$", source, re.MULTILINE) + assert len(starts) == 1, f"{target}:{region} needs exactly one start marker, has {len(starts)}" + assert len(ends) == 1, f"{target}:{region} needs exactly one end marker, has {len(ends)}" + body = source.split(starts[0], maxsplit=1)[1].split(ends[0], maxsplit=1)[0] + assert body.strip(), f"{target}:{region} is empty" + + +def test_snippet_directories_hold_only_their_kind() -> None: + """Rendered pages are markdown; executable snippets are Python.""" + assert all(p.suffix == ".md" for p in (DOCS / "examples").iterdir() if p.is_file()) + assert all(p.suffix == ".py" for p in DOC_SNIPPETS_DIR.iterdir() if p.is_file()) + + +@pytest.mark.parametrize("example", EXECUTABLES, ids=lambda path: path.stem) +def test_documentation_example_executes(example: Path) -> None: + """Examples are executable contracts; their inline asserts are the values check.""" + runpy.run_path(str(example), run_name="__main__") + + +@pytest.mark.parametrize("script", CLI_EXAMPLES, ids=lambda path: path.stem) +def test_cli_example_runs_as_a_subprocess(script: Path) -> None: + """The CLI examples exit 0 when run the way their READMEs instruct.""" + if "dask" in script.stem: + pytest.importorskip("dask.array") + completed = subprocess.run( + [sys.executable, str(script)], + capture_output=True, + text=True, + cwd=script.parent, + check=False, + ) + assert completed.returncode == 0, completed.stderr[-2000:] + + +@pytest.mark.parametrize( + "example_dir", + sorted(p for p in STANDALONE_EXAMPLES.iterdir() if p.is_dir()), + ids=lambda path: path.name, +) +def test_standalone_example_is_a_documented_script(example_dir: Path) -> None: + """Each standalone example ships a README and a same-named runnable script.""" + script = example_dir / f"{example_dir.name}.py" + assert script.is_file() + assert (example_dir / "README.md").is_file() + assert (DOCS / "examples" / f"{example_dir.name}.md").is_file() + assert script.read_text().startswith("# /// script\n"), "examples stay PEP 723 runnable" + + +# --------------------------------------------------------------------------- # +# Behavioral: the documented pattern matrix +# --------------------------------------------------------------------------- # + + +def test_indexing_pattern_matrix_is_complete() -> None: + assert {case["name"] for case in PATTERN_CASES} == REQUIRED_PATTERNS + + +def test_pattern_page_tabs_are_the_models() -> None: + """Both tabs of every matrix entry are the executable model, in order. + + The JSON tab must be the model's canonical wire form; the Python tab + must evaluate (in the executable matrix's namespace) to the model + itself. Either tab drifting from the snippet fails here. + """ + import json + import textwrap + + page = (DOCS / "guide" / "patterns.md").read_text() + + json_blocks = re.findall(r"```json\n(.*?)```", page, re.DOTALL) + assert len(json_blocks) == len(PATTERN_CASES) + for block, case in zip(json_blocks, PATTERN_CASES, strict=True): + assert json.loads(block) == case["transform"].to_json(), case["name"] + + python_blocks = [ + textwrap.dedent(block) + for block in re.findall(r"```python\n(.*?)```", page, re.DOTALL) + if "--8<--" not in block + ] + assert len(python_blocks) == len(PATTERN_CASES) + for block, case in zip(python_blocks, PATTERN_CASES, strict=True): + constructed = eval(block, dict(PATTERN_NAMESPACE)) + assert constructed == case["transform"], case["name"] + + +@pytest.mark.parametrize("case", PATTERN_CASES, ids=lambda case: case["name"]) +def test_indexing_pattern_matrix_matches_numpy(case: dict[str, Any]) -> None: + """The wrapper agrees with the matrix the snippet proves at the transform level.""" + image = PATTERN_NAMESPACE["image"] + lazy = LazyArray.from_numpy(image) + accessor = { + "basic": lazy.lazy, + "oindex": lazy.lazy.oindex, + "vindex": lazy.lazy.vindex, + }[case["mode"]] + view = accessor[case["selection"]] + result = view.result() + + np.testing.assert_array_equal(result, case["expected"]) + assert result.shape == case["shape"] + assert ("box" if view.is_box else "query") == case["category"] + + +# --------------------------------------------------------------------------- # +# Behavioral: contracts the guide states about wrapped sources and parts +# --------------------------------------------------------------------------- # + + +def test_default_source_contract_converts_basic_selected_slabs_to_system_memory() -> None: + """A source may return Python slabs as long as NumPy can convert each selected slab.""" + + class ListSlabSource: + def __init__(self) -> None: + self.data = np.arange(20).reshape(4, 5) + self.keys: list[tuple[Any, ...]] = [] + + @property + def shape(self) -> tuple[int, ...]: + return self.data.shape + + @property + def dtype(self) -> np.dtype[Any]: + return self.data.dtype + + def __getitem__(self, key: tuple[Any, ...]) -> object: + assert all(isinstance(item, (int, slice)) for item in key) + self.keys.append(key) + return self.data[key].tolist() + + source = ListSlabSource() + result = LazyArray(source).with_parts((2, 3)).lazy.oindex[[3, 1, 1], 1:5:2].result() + + np.testing.assert_array_equal(result, np.array([[16, 18], [6, 8], [6, 8]])) + assert len(source.keys) > 0 + assert all(all(isinstance(item, (int, slice)) for item in key) for key in source.keys) + + +def test_coordinate_array_example_preserves_order_and_duplicates() -> None: + """Coordinate arrays are ordered sequences, not mathematical sets.""" + view = LazyArray.from_numpy(np.arange(6)).with_parts((2,)).lazy.oindex[[4, 1, 1, 3]] + + np.testing.assert_array_equal(view.result(), np.array([4, 1, 1, 3])) + assembled = np.empty(view.shape, dtype=view.dtype) + for part in view.parts(): + assembled[part.out_selection] = part.view.result() + np.testing.assert_array_equal(assembled, np.array([4, 1, 1, 3])) + + +def test_documented_partition_transform_is_global_and_projection_is_chunk_local() -> None: + source = np.arange(8) + part = tuple(LazyArray.from_numpy(source).with_parts((4,)).parts())[1] + + assert part.view.transform.apply((0,)) == (4,) + assert part.view.array[part.view.transform.apply((0,))] == 4 + assert part.projection.chunk_transform.apply((0,)) == (0,) + + +@pytest.mark.parametrize( + ("mode", "parts"), + [ + ("per-axis", ((0,), (3,))), + ("per-axis", ((), (3,))), + ("uniform", (1, 1)), + ("per-axis", ((0, 0), (3,))), + ], + ids=["single-zero", "empty-sequence", "positive-uniform", "repeated-zero"], +) +def test_documented_zero_length_axis_partition_spellings_execute(mode: str, parts: Any) -> None: + data = np.zeros((0, 3)) + base = LazyArray.from_numpy(data) + view = base.with_parts(parts) if mode == "uniform" else base.with_parts_per_axis(parts) + + assert view.result().shape == (0, 3) + assert tuple(view.parts()) == () + + +def test_projection_example_exposes_paired_directions() -> None: + """Both transforms of every projection keep their documented output ranks.""" + namespace = runpy.run_path(str(DOC_SNIPPETS_DIR / "chunk_projection.py")) + np.testing.assert_array_equal(namespace["ADVANCED_RESULT"], namespace["ADVANCED_EXPECTED"]) + assert all(p.chunk_transform.output_rank == 2 for p in namespace["PROJECTIONS"]) + assert all(p.cell_transform.output_rank == 1 for p in namespace["PROJECTIONS"]) + + +@pytest.mark.parametrize( + "example", + [DOC_SNIPPETS_DIR / "integrations.py", CACHE_EXAMPLE], + ids=lambda path: path.stem, +) +def test_projection_examples_assemble_rank_zero_domains(example: Path) -> None: + """The examples' shared assembly helpers handle a zero-rank cell domain.""" + namespace = runpy.run_path(str(example)) + domain = zarr_indexing.IndexDomain((), ()) + cell_points = namespace["_domain_points"](domain) + destination = np.empty((), dtype=np.intp) + + values = namespace["_gather_and_scatter"]( + destination, + np.array(7, dtype=np.intp), + cell_points, + cell_points, + ) + + assert cell_points.shape == (1, 0) + assert values.shape == (1,) + assert destination[()] == 7 + + +# --------------------------------------------------------------------------- # +# Behavioral: the documented chunk cache (error paths the example cannot show) +# --------------------------------------------------------------------------- # + + +def make_documented_cache() -> tuple[Any, Any]: + source_type = CACHE_NAMESPACE["RecordingChunkSource"] + cache_type = CACHE_NAMESPACE["SystemMemoryChunkCache"] + source = source_type(np.arange(48).reshape(6, 8), chunks=(3, 4)) + return source, cache_type(source, capacity=2) + + +def test_system_memory_cache_assembles_and_deduplicates_public_projections() -> None: + source, cache = make_documented_cache() + + np.testing.assert_array_equal(cache.oindex[[1, 1], 2], np.array([10, 10])) + assert tuple(source.reads) == ((0, 0),) + assert cache.projection_uses == (("chunk_transform", "context.transform"),) + + +def test_chunk_cache_queues_all_parts_before_loading( + monkeypatch: pytest.MonkeyPatch, +) -> None: + source, cache = make_documented_cache() + planning_count = 0 + original_plan_chunks = lazy_array_module.plan_chunks + + def counted_plan_chunks(*args: Any, **kwargs: Any) -> Any: + nonlocal planning_count + planning_count += 1 + return original_plan_chunks(*args, **kwargs) + + with monkeypatch.context() as request_patch: + request_patch.setattr(lazy_array_module, "plan_chunks", counted_plan_chunks) + result = cache[1:5, 2] + + np.testing.assert_array_equal(result, np.array([10, 18, 26, 34])) + assert planning_count == 1 + assert source.reads == [(0, 0), (1, 0)] + + assert [ + (event.chunk_coords, event.previous.value, event.current.value) for event in cache.events + ] == [ + ((0, 0), "new", "queued"), + ((1, 0), "new", "queued"), + ((0, 0), "queued", "loading"), + ((0, 0), "loading", "ready"), + ((1, 0), "queued", "loading"), + ((1, 0), "loading", "ready"), + ] + + +def test_chunk_cache_reader_resolves_a_transform_from_cached_chunks() -> None: + """The reader boundary consumes the prepared projections of real parts.""" + source_type = CACHE_NAMESPACE["RecordingChunkSource"] + reader_type = CACHE_NAMESPACE["SystemMemoryChunkReader"] + source = source_type(np.arange(48).reshape(6, 8), chunks=(3, 4)) + reader = reader_type(capacity=2) + view = LazyArray(source).with_reader(reader).lazy[1:5, 2] + parts = tuple(view.parts()) + out = np.empty(view.shape, dtype=source.dtype) + for part in parts: + destination = out[part.out_selection] + assert ( + reader.read_into( + source, + ReadContext(part.view.transform, part.projection), + destination, + ) + is None + ) + + np.testing.assert_array_equal(out, np.array([10, 18, 26, 34])) + assert source.reads == [(0, 0), (1, 0)] + assert reader.projection_uses == [ + ("chunk_transform", "context.transform"), + ("chunk_transform", "context.transform"), + ] + + +def test_chunk_cache_reader_requires_a_prepared_projection() -> None: + source_type = CACHE_NAMESPACE["RecordingChunkSource"] + reader_type = CACHE_NAMESPACE["SystemMemoryChunkReader"] + source = source_type(np.arange(48).reshape(6, 8), chunks=(3, 4)) + transform = IndexTransform.from_shape(source.shape)[1:3, 2].translate_domain_to((0,)) + out = np.empty(transform.domain.shape, dtype=source.dtype) + + with pytest.raises(ValueError, match="requires context.projection"): + reader_type(capacity=2).read_into(source, ReadContext(transform), out) + + +def test_system_memory_cache_separates_basic_and_orthogonal_indexing() -> None: + source_type = CACHE_NAMESPACE["RecordingChunkSource"] + cache_type = CACHE_NAMESPACE["SystemMemoryChunkCache"] + data = np.arange(48).reshape(6, 8) + cache = cache_type(source_type(data, chunks=(3, 4)), capacity=4) + row = np.array([0, 2]) + column = np.array([1, 3]) + + np.testing.assert_array_equal(cache[0:3, 1:4], data[0:3, 1:4]) + np.testing.assert_array_equal( + cache.oindex[row, column], + data[np.ix_(row, column)], + ) + + +def test_system_memory_cache_does_not_treat_array_keys_as_orthogonal() -> None: + source, cache = make_documented_cache() + row = np.array([0, 2]) + column = np.array([1, 3]) + + with pytest.raises(IndexError, match="unsupported selection type for basic indexing"): + cache[row, column] + + assert tuple(source.reads) == () + + +def test_system_memory_cache_assembles_a_scalar_selection() -> None: + source, cache = make_documented_cache() + + result = cache[1, 2] + + assert result.shape == () + assert result[()] == 10 + assert tuple(source.reads) == ((0, 0),) + assert cache.projection_uses == (("chunk_transform", "context.transform"),) + + +def test_system_memory_cache_is_documentation_only() -> None: + assert not hasattr(zarr_indexing, "SystemMemoryChunkCache") + assert not hasattr(zarr_indexing, "ChunkState") + + +def test_chunk_source_failure_is_retained_as_failed_with_its_cause() -> None: + source, cache = make_documented_cache() + source.failures.add((1, 1)) + + with pytest.raises(CACHE_NAMESPACE["ChunkLoadError"]) as error: + cache[3:5, 4:6] + + assert isinstance(error.value.__cause__, OSError) + assert cache.state((1, 1)).value == "failed" + assert tuple(source.reads) == ((1, 1),) + + +def test_failed_chunk_is_not_retried_implicitly() -> None: + source, cache = make_documented_cache() + source.failures.add((1, 1)) + with pytest.raises(CACHE_NAMESPACE["ChunkLoadError"]): + cache[3:5, 4:6] + with pytest.raises(CACHE_NAMESPACE["ChunkLoadError"]): + cache[3:5, 4:6] + + assert tuple(source.reads) == ((1, 1),) + + +def test_retry_requires_a_failed_chunk() -> None: + _, cache = make_documented_cache() + with pytest.raises(ValueError, match="retry requires failed chunk .*new"): + cache.retry((0, 0)) + + +def test_illegal_chunk_transition_is_rejected() -> None: + _, cache = make_documented_cache() + with pytest.raises(ValueError, match="illegal chunk transition new -> ready"): + cache.reader._transition((0, 0), CACHE_NAMESPACE["ChunkState"].READY, "test") diff --git a/packages/zarr-indexing/tests/test_domain.py b/packages/zarr-indexing/tests/test_domain.py new file mode 100644 index 0000000000..0278ecd714 --- /dev/null +++ b/packages/zarr-indexing/tests/test_domain.py @@ -0,0 +1,218 @@ +from __future__ import annotations + +import pytest + +from zarr_indexing.domain import IndexDomain +from zarr_indexing.errors import BoundsCheckError + + +class TestIndexDomainConstruction: + def test_from_shape(self) -> None: + d = IndexDomain.from_shape((10, 20)) + assert d.inclusive_min == (0, 0) + assert d.exclusive_max == (10, 20) + assert d.ndim == 2 + assert d.origin == (0, 0) + assert d.shape == (10, 20) + + def test_from_shape_0d(self) -> None: + d = IndexDomain.from_shape(()) + assert d.ndim == 0 + assert d.shape == () + + def test_non_zero_origin(self) -> None: + d = IndexDomain(inclusive_min=(5, 10), exclusive_max=(15, 30)) + assert d.origin == (5, 10) + assert d.shape == (10, 20) + assert d.ndim == 2 + + def test_validation_mismatched_lengths(self) -> None: + with pytest.raises(ValueError, match="same length"): + IndexDomain(inclusive_min=(0,), exclusive_max=(10, 20)) + + def test_validation_min_greater_than_max(self) -> None: + with pytest.raises(ValueError, match="inclusive_min must be <="): + IndexDomain(inclusive_min=(10,), exclusive_max=(5,)) + + def test_empty_domain(self) -> None: + d = IndexDomain(inclusive_min=(5,), exclusive_max=(5,)) + assert d.shape == (0,) + + def test_labels(self) -> None: + d = IndexDomain(inclusive_min=(0, 0), exclusive_max=(10, 20), labels=("x", "y")) + assert d.labels == ("x", "y") + + def test_labels_none(self) -> None: + d = IndexDomain.from_shape((10,)) + assert d.labels is None + + +class TestIndexDomainContains: + def test_contains_inside(self) -> None: + d = IndexDomain.from_shape((10, 20)) + assert d.contains((0, 0)) is True + assert d.contains((9, 19)) is True + assert d.contains((5, 10)) is True + + def test_contains_outside(self) -> None: + d = IndexDomain.from_shape((10, 20)) + assert d.contains((10, 0)) is False + assert d.contains((-1, 0)) is False + assert d.contains((0, 20)) is False + + def test_contains_non_zero_origin(self) -> None: + d = IndexDomain(inclusive_min=(5,), exclusive_max=(10,)) + assert d.contains((5,)) is True + assert d.contains((9,)) is True + assert d.contains((4,)) is False + assert d.contains((10,)) is False + + def test_contains_wrong_ndim(self) -> None: + d = IndexDomain.from_shape((10, 20)) + assert d.contains((5,)) is False + + def test_contains_domain_inside(self) -> None: + outer = IndexDomain.from_shape((10, 20)) + inner = IndexDomain(inclusive_min=(2, 3), exclusive_max=(8, 15)) + assert outer.contains_domain(inner) is True + + def test_contains_domain_outside(self) -> None: + outer = IndexDomain.from_shape((10, 20)) + inner = IndexDomain(inclusive_min=(2, 3), exclusive_max=(11, 15)) + assert outer.contains_domain(inner) is False + + def test_contains_domain_wrong_ndim(self) -> None: + outer = IndexDomain.from_shape((10, 20)) + inner = IndexDomain.from_shape((5,)) + assert outer.contains_domain(inner) is False + + +class TestIndexDomainIntersect: + def test_overlapping(self) -> None: + a = IndexDomain(inclusive_min=(0, 0), exclusive_max=(10, 10)) + b = IndexDomain(inclusive_min=(5, 5), exclusive_max=(15, 15)) + result = a.intersect(b) + assert result is not None + assert result.inclusive_min == (5, 5) + assert result.exclusive_max == (10, 10) + + def test_disjoint(self) -> None: + a = IndexDomain(inclusive_min=(0,), exclusive_max=(5,)) + b = IndexDomain(inclusive_min=(10,), exclusive_max=(15,)) + assert a.intersect(b) is None + + def test_touching_boundary(self) -> None: + a = IndexDomain(inclusive_min=(0,), exclusive_max=(5,)) + b = IndexDomain(inclusive_min=(5,), exclusive_max=(10,)) + assert a.intersect(b) is None + + def test_contained(self) -> None: + a = IndexDomain.from_shape((20,)) + b = IndexDomain(inclusive_min=(5,), exclusive_max=(10,)) + result = a.intersect(b) + assert result is not None + assert result.inclusive_min == (5,) + assert result.exclusive_max == (10,) + + def test_wrong_ndim(self) -> None: + a = IndexDomain.from_shape((10,)) + b = IndexDomain.from_shape((10, 20)) + with pytest.raises(ValueError, match="different ranks"): + a.intersect(b) + + +class TestIndexDomainTranslate: + def test_translate_positive(self) -> None: + d = IndexDomain.from_shape((10, 20)) + result = d.translate((5, 10)) + assert result.inclusive_min == (5, 10) + assert result.exclusive_max == (15, 30) + + def test_translate_negative(self) -> None: + d = IndexDomain(inclusive_min=(10, 20), exclusive_max=(30, 40)) + result = d.translate((-10, -20)) + assert result.inclusive_min == (0, 0) + assert result.exclusive_max == (20, 20) + + def test_translate_wrong_length(self) -> None: + d = IndexDomain.from_shape((10,)) + with pytest.raises(ValueError, match="same length"): + d.translate((1, 2)) + + +class TestIndexDomainNarrow: + def test_narrow_slice(self) -> None: + d = IndexDomain.from_shape((10, 20)) + result = d.narrow((slice(2, 8), slice(5, 15))) + assert result.inclusive_min == (2, 5) + assert result.exclusive_max == (8, 15) + + def test_narrow_int(self) -> None: + d = IndexDomain.from_shape((10, 20)) + result = d.narrow((3, slice(None))) + assert result.inclusive_min == (3, 0) + assert result.exclusive_max == (4, 20) + + def test_narrow_ellipsis(self) -> None: + d = IndexDomain.from_shape((10, 20, 30)) + result = d.narrow((slice(1, 5), ...)) + assert result.inclusive_min == (1, 0, 0) + assert result.exclusive_max == (5, 20, 30) + + def test_narrow_slice_none(self) -> None: + d = IndexDomain.from_shape((10,)) + result = d.narrow((slice(None),)) + assert result == d + + def test_narrow_non_zero_origin(self) -> None: + d = IndexDomain(inclusive_min=(10,), exclusive_max=(20,)) + result = d.narrow((slice(12, 18),)) + assert result.inclusive_min == (12,) + assert result.exclusive_max == (18,) + + def test_narrow_int_out_of_bounds(self) -> None: + d = IndexDomain.from_shape((10,)) + with pytest.raises(BoundsCheckError, match="out of bounds"): + d.narrow((10,)) + + def test_narrow_int_below_origin(self) -> None: + d = IndexDomain(inclusive_min=(5,), exclusive_max=(10,)) + with pytest.raises(BoundsCheckError, match="out of bounds"): + d.narrow((4,)) + + def test_narrow_refuses_a_bound_outside_the_domain(self) -> None: + """Clamping made two different requests answer alike, and neither well. + + Indices here are absolute coordinates, so `-5` is a coordinate this + domain does not contain rather than NumPy's "five from the end" β€” and + clamping returned the whole axis for it, which is what a caller writing + the NumPy spelling would least expect. A stop past the end produced a + domain the parent did not contain. + """ + d = IndexDomain.from_shape((10,)) + with pytest.raises(BoundsCheckError, match="absolute coordinates"): + d.narrow((slice(-5, 100),)) + with pytest.raises(BoundsCheckError, match="out of bounds"): + d.narrow((slice(20, 30),)) + + def test_narrow_accepts_the_bounds_of_the_domain_itself(self) -> None: + d = IndexDomain.from_shape((10,)) + assert d.narrow((slice(0, 10),)) == d + + def test_narrow_bare_slice(self) -> None: + d = IndexDomain.from_shape((10,)) + result = d.narrow(slice(2, 8)) + assert result.inclusive_min == (2,) + assert result.exclusive_max == (8,) + + def test_narrow_too_many_indices(self) -> None: + d = IndexDomain.from_shape((10,)) + with pytest.raises(IndexError, match="too many indices"): + d.narrow((1, 2)) + + def test_narrow_step_not_one(self) -> None: + """A stride is not a bounds failure β€” the rest of the algebra raises + `ValueError` for a request it does not implement, and so does this.""" + d = IndexDomain.from_shape((10,)) + with pytest.raises(ValueError, match="step=1"): + d.narrow((slice(0, 10, 2),)) diff --git a/packages/zarr-indexing/tests/test_json.py b/packages/zarr-indexing/tests/test_json.py new file mode 100644 index 0000000000..9848c6801f --- /dev/null +++ b/packages/zarr-indexing/tests/test_json.py @@ -0,0 +1,586 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +from zarr_indexing.domain import IndexDomain +from zarr_indexing.messages import NdselError +from zarr_indexing.output_map import ( + ArrayMap, + ConstantMap, + DimensionMap, + output_index_map_from_json, +) +from zarr_indexing.transform import IndexTransform + +if TYPE_CHECKING: + from zarr_indexing.json import IndexTransformJSON + + +def _maps_equal(a: object, b: object) -> bool: + if type(a) is not type(b): + return False + if isinstance(a, ConstantMap): + assert isinstance(b, ConstantMap) + return a.offset == b.offset + if isinstance(a, DimensionMap): + assert isinstance(b, DimensionMap) + return (a.input_dimension, a.offset, a.stride) == (b.input_dimension, b.offset, b.stride) + assert isinstance(a, ArrayMap) + assert isinstance(b, ArrayMap) + return ( + a.offset == b.offset + and a.stride == b.stride + and np.array_equal(a.index_array, b.index_array) + ) + + +def _transforms_equal(a: IndexTransform, b: IndexTransform) -> bool: + """Structural equality that compares `ArrayMap` index arrays element-wise + (`IndexTransform`'s dataclass `__eq__` cannot, as numpy `==` is ambiguous).""" + return ( + a.domain == b.domain + and len(a.output) == len(b.output) + and all(_maps_equal(x, y) for x, y in zip(a.output, b.output, strict=True)) + ) + + +class TestIndexDomainJSON: + def test_roundtrip(self) -> None: + domain = IndexDomain(inclusive_min=(2, 5), exclusive_max=(10, 20)) + json = domain.to_json() + assert json == { + "input_inclusive_min": [2, 5], + "input_exclusive_max": [10, 20], + "input_labels": ["", ""], + } + restored = IndexDomain.from_json(json) + assert restored == domain + + def test_with_labels(self) -> None: + domain = IndexDomain(inclusive_min=(0, 0), exclusive_max=(10, 20), labels=("x", "y")) + json = domain.to_json() + assert json["input_labels"] == ["x", "y"] + restored = IndexDomain.from_json(json) + assert restored.labels == ("x", "y") + + def test_without_labels_emits_empty_and_round_trips_to_none(self) -> None: + domain = IndexDomain.from_shape((5,)) + json = domain.to_json() + # Canonical form always writes labels; an unlabeled domain gets [""]*rank. + assert json["input_labels"] == [""] + restored = IndexDomain.from_json(json) + assert restored.labels is None + + def test_zero_origin(self) -> None: + domain = IndexDomain.from_shape((10, 20, 30)) + json = domain.to_json() + assert json == { + "input_inclusive_min": [0, 0, 0], + "input_exclusive_max": [10, 20, 30], + "input_labels": ["", "", ""], + } + assert IndexDomain.from_json(json) == domain + + +class TestOutputIndexMapJSON: + def test_constant(self) -> None: + m = ConstantMap(offset=42) + json = m.to_json() + assert json == {"offset": 42} + restored = output_index_map_from_json(json) + assert isinstance(restored, ConstantMap) + assert restored.offset == 42 + + def test_constant_zero(self) -> None: + m = ConstantMap(offset=0) + json = m.to_json() + assert json == {"offset": 0} + restored = output_index_map_from_json(json) + assert isinstance(restored, ConstantMap) + assert restored.offset == 0 + + def test_dimension(self) -> None: + m = DimensionMap(input_dimension=1, offset=10, stride=3) + json = m.to_json() + assert json == {"offset": 10, "stride": 3, "input_dimension": 1} + restored = output_index_map_from_json(json) + assert isinstance(restored, DimensionMap) + assert restored.input_dimension == 1 + assert restored.offset == 10 + assert restored.stride == 3 + + def test_dimension_stride_1_written(self) -> None: + """Canonical form writes stride even at its default of 1.""" + m = DimensionMap(input_dimension=0) + json = m.to_json() + assert json == {"offset": 0, "stride": 1, "input_dimension": 0} + restored = output_index_map_from_json(json) + assert isinstance(restored, DimensionMap) + assert restored.stride == 1 + + def test_array(self) -> None: + arr = np.array([1, 5, 9], dtype=np.intp) + m = ArrayMap(index_array=arr, offset=2, stride=3) + json = m.to_json() + # Canonical: stride/offset present, index_array_bounds present, and + # no input_dimension (ndsel/TensorStore reject it beside index_array). + assert json == { + "offset": 2, + "stride": 3, + "index_array": [1, 5, 9], + "index_array_bounds": ["-inf", "+inf"], + } + restored = output_index_map_from_json(json) + assert isinstance(restored, ArrayMap) + np.testing.assert_array_equal(restored.index_array, arr) + assert restored.offset == 2 + assert restored.stride == 3 + + def test_array_stride_1_written(self) -> None: + arr = np.array([0, 1, 2], dtype=np.intp) + m = ArrayMap(index_array=arr) + json = m.to_json() + assert json["stride"] == 1 + restored = output_index_map_from_json(json) + assert isinstance(restored, ArrayMap) + assert restored.stride == 1 + + def test_array_2d(self) -> None: + arr = np.array([[1, 2], [3, 4]], dtype=np.intp) + m = ArrayMap(index_array=arr) + json = m.to_json() + assert json["index_array"] == [[1, 2], [3, 4]] + restored = output_index_map_from_json(json) + assert isinstance(restored, ArrayMap) + np.testing.assert_array_equal(restored.index_array, arr) + + def test_degenerate_singleton_array_collapses_to_constant(self) -> None: + """An all-singleton index_array selects one coordinate -> constant map.""" + m = ArrayMap(index_array=np.array([[4]], dtype=np.intp), offset=1, stride=2) + json = m.to_json() + assert json == {"offset": 1 + 2 * 4} + restored = output_index_map_from_json(json) + assert isinstance(restored, ConstantMap) + assert restored.offset == 9 + + +class TestIndexTransformJSON: + def test_identity(self) -> None: + t = IndexTransform.from_shape((10, 20)) + json = t.to_json() + assert json == { + "input_rank": 2, + "input_inclusive_min": [0, 0], + "input_exclusive_max": [10, 20], + "input_labels": ["", ""], + "output": [ + {"offset": 0, "stride": 1, "input_dimension": 0}, + {"offset": 0, "stride": 1, "input_dimension": 1}, + ], + } + restored = IndexTransform.from_json(json) + assert restored.domain == t.domain + assert len(restored.output) == 2 + for orig, rest in zip(t.output, restored.output, strict=True): + assert type(orig) is type(rest) + + def test_sliced(self) -> None: + t = IndexTransform.from_shape((100,))[10:50:2] + json = t.to_json() + restored = IndexTransform.from_json(json) + assert restored.domain.shape == t.domain.shape + assert isinstance(restored.output[0], DimensionMap) + orig = t.output[0] + assert isinstance(orig, DimensionMap) + assert restored.output[0].offset == orig.offset + assert restored.output[0].stride == orig.stride + + def test_with_constant(self) -> None: + t = IndexTransform.from_shape((10, 20))[3] + json = t.to_json() + restored = IndexTransform.from_json(json) + assert isinstance(restored.output[0], ConstantMap) + assert restored.output[0].offset == 3 + assert isinstance(restored.output[1], DimensionMap) + + def test_with_array(self) -> None: + idx = np.array([1, 5, 9], dtype=np.intp) + t = IndexTransform.from_shape((10, 20)).oindex[idx, :] + json = t.to_json() + # The oindex array must not carry input_dimension on the wire. + assert "input_dimension" not in json["output"][0] + restored = IndexTransform.from_json(json) + assert isinstance(restored.output[0], ArrayMap) + # Orthogonal arrays are normalized to full input rank with a singleton + # axis on the dimension they do not vary over. + assert restored.output[0].index_array.shape == (3, 1) + np.testing.assert_array_equal(restored.output[0].index_array, idx.reshape(3, 1)) + assert isinstance(restored.output[1], DimensionMap) + + def test_roundtrip_preserves_singleton_axes(self) -> None: + """Full-rank orthogonal arrays keep their singleton axes across JSON.""" + t = IndexTransform.from_shape((10, 20)).oindex[np.array([1, 3]), np.array([2, 4, 6])] + restored = IndexTransform.from_json(t.to_json()) + orig0, orig1 = t.output[0], t.output[1] + rest0, rest1 = restored.output[0], restored.output[1] + assert isinstance(orig0, ArrayMap) + assert isinstance(orig1, ArrayMap) + assert isinstance(rest0, ArrayMap) + assert isinstance(rest1, ArrayMap) + assert rest0.index_array.shape == (2, 1) + assert rest1.index_array.shape == (1, 3) + np.testing.assert_array_equal(rest0.index_array, orig0.index_array) + np.testing.assert_array_equal(rest1.index_array, orig1.index_array) + + def test_with_labels(self) -> None: + domain = IndexDomain(inclusive_min=(0, 0), exclusive_max=(10, 20), labels=("x", "y")) + t = IndexTransform.identity(domain) + json = t.to_json() + assert json["input_labels"] == ["x", "y"] + restored = IndexTransform.from_json(json) + assert restored.domain.labels == ("x", "y") + + def test_tensorstore_compatible_format(self) -> None: + """A canonical body loads and round-trips through the engine layer.""" + json: IndexTransformJSON = { + "input_rank": 3, + "input_inclusive_min": [0, 0, 0], + "input_exclusive_max": [100, 200, 3], + "input_labels": ["x", "y", "channel"], + "output": [ + {"offset": 5}, + {"offset": 10, "stride": 2, "input_dimension": 1}, + # Full input rank, which is what TensorStore itself requires: + # it rejects a rank-1 array over a rank-3 domain outright. + {"offset": 0, "stride": 1, "index_array": [[[1, 2, 0]]]}, + ], + } + t = IndexTransform.from_json(json) + assert t.domain.shape == (100, 200, 3) + assert t.domain.labels == ("x", "y", "channel") + assert isinstance(t.output[0], ConstantMap) + assert t.output[0].offset == 5 + assert isinstance(t.output[1], DimensionMap) + assert t.output[1].offset == 10 + assert t.output[1].stride == 2 + assert t.output[1].input_dimension == 1 + assert isinstance(t.output[2], ArrayMap) + np.testing.assert_array_equal(t.output[2].index_array, [[[1, 2, 0]]]) + + # Roundtrip + json_rt = t.to_json() + t_rt = IndexTransform.from_json(json_rt) + assert t_rt.domain == t.domain + + +class TestCanonicalRoundTrips: + """Round-trip `transform == from(to(transform))`, up to the documented + degenerate-collapse (all-singleton ArrayMap -> ConstantMap).""" + + def test_oindex_multi_axis(self) -> None: + t = IndexTransform.from_shape((10, 20, 30)).oindex[np.array([1, 3]), :, np.array([2, 4, 6])] + rt = IndexTransform.from_json(t.to_json()) + assert _transforms_equal(rt, t) + + def test_oindex_with_slice(self) -> None: + t = IndexTransform.from_shape((10, 20))[2:8].oindex[np.array([3, 5, 7]), :] + rt = IndexTransform.from_json(t.to_json()) + assert _transforms_equal(rt, t) + + def test_vindex(self) -> None: + t = IndexTransform.from_shape((10, 20)).vindex[np.array([1, 3, 5]), np.array([2, 4, 6])] + rt = IndexTransform.from_json(t.to_json()) + assert _transforms_equal(rt, t) + + def test_vindex_with_residual_slice(self) -> None: + t = IndexTransform.from_shape((10, 20, 30)).vindex[np.array([1, 3]), np.array([2, 4]), :] + rt = IndexTransform.from_json(t.to_json()) + assert _transforms_equal(rt, t) + + def test_length1_degenerate_oindex_collapses(self) -> None: + """A length-1 oindex selection is the ConstantMap it equals. + + The selection layer collapses it at construction; a hand-built + all-singleton ArrayMap still collapses on serialize, so the canonical + wire form is a `constant` map either way. + """ + t = IndexTransform.from_shape((10, 20)).oindex[np.array([7]), :] + m = t.output[0] + assert isinstance(m, ConstantMap) + assert m.offset == 7 + + hand_built = IndexTransform( + domain=t.domain, + output=(ArrayMap(index_array=np.array([[7]], dtype=np.intp)), t.output[1]), + ) + rt = IndexTransform.from_json(hand_built.to_json()) + rm = rt.output[0] + assert isinstance(rm, ConstantMap) + assert rm.offset == 7 + # The size-1 input dimension survives, unconsumed, in the domain. + assert rt.domain == t.domain + + def test_slices_and_constants(self) -> None: + t = IndexTransform.from_shape((10, 20, 30))[2:8:2, 5, :] + rt = IndexTransform.from_json(t.to_json()) + assert _transforms_equal(rt, t) + + +def _index_array_body(index_array: Any, rank: int = 1, extent: int = 2) -> IndexTransformJSON: + return { + "input_rank": rank, + "input_inclusive_min": [0] * rank, + "input_exclusive_max": [extent] * rank, + "input_labels": [""] * rank, + "output": [{"offset": 0, "stride": 1, "index_array": index_array}], + } + + +@pytest.mark.parametrize( + ("index_array", "detail"), + [ + ([0.9, 1.9], "float64"), + ([0, 1.5], "float64"), + ([True, False], "bool"), + (["a", "b"], "str"), + # Not lists at all, so they are turned away before their content is + # looked at: a bare string would be iterated into characters, and a bare + # integer would become a rank-0 array and then a length-1 map, so a + # document naming no cells would select one. + ("abc", "must be an array of integers"), + (5, "must be an array of integers"), + ([None, None], "object"), + ], + ids=["floats", "mixed", "bools", "strings", "string", "scalar", "nulls"], +) +def test_a_non_integer_index_array_is_rejected(index_array: Any, detail: str) -> None: + """An `index_array` addresses output coordinates, so it must be integral. + + Lowering a float array silently truncated it (`[0.9, 1.9]` selected cells 0 + and 1), a bool array coerced to 0/1, and a string array leaked a raw NumPy + `ValueError` from the middle of the conversion. + """ + with pytest.raises(NdselError) as excinfo: + IndexTransform.from_json(_index_array_body(index_array)) + assert excinfo.value.reason == "invalid_json" + assert "index_array" in str(excinfo.value) + assert detail in str(excinfo.value) + + +def test_a_ragged_index_array_is_rejected() -> None: + """A nested list that is not rectangular is not an array at all.""" + with pytest.raises(NdselError) as excinfo: + IndexTransform.from_json(_index_array_body([[0, 1], [2]])) + assert excinfo.value.reason == "invalid_json" + + +@pytest.mark.parametrize( + ("index_array", "rank", "extent"), + [([0, 1], 1, 2), ([[0], [1]], 2, 2), ([], 1, 0)], + ids=["1d", "2d", "empty"], +) +def test_an_integer_index_array_is_accepted(index_array: Any, rank: int, extent: int) -> None: + """Integers of any nesting still lower, including an empty selection. + + An empty array selects nothing, so the domain it is read over is empty too; + a domain with room for coordinates the array does not supply is rejected + (see `test_an_index_array_that_does_not_span_its_domain_is_rejected`). + """ + t = IndexTransform.from_json(_index_array_body(index_array, rank, extent)) + m = t.output[0] + assert isinstance(m, ArrayMap) + assert m.index_array.dtype == np.intp + + +def test_a_non_integer_index_array_is_rejected_by_the_map_loader() -> None: + """The single-map loader enforces the same constraint as the transform one.""" + with pytest.raises(NdselError) as excinfo: + output_index_map_from_json({"index_array": [0.5, 1.5]}) + assert excinfo.value.reason == "invalid_json" + + +def test_infinite_bound_rejected_on_lowering() -> None: + body: IndexTransformJSON = { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [["+inf"]], + "input_labels": [""], + "output": [{"offset": 0, "stride": 1, "input_dimension": 0}], + } + with pytest.raises(ValueError, match="infinite"): + IndexTransform.from_json(body) + + +def test_a_lower_rank_index_array_is_widened_on_the_way_in() -> None: + """External JSON may broadcast a lower-rank array; the engine never holds one. + + ndsel leaves index-array rank unvalidated, so a conformant producer may send + an array of lower rank. It is widened at the boundary, which keeps the + full-rank invariant true of every transform the engine builds. + """ + # A rank-1 array widens into the trailing axis, so it spans that axis's + # extent of four. + body: IndexTransformJSON = { + "input_inclusive_min": [0, 0], + "input_exclusive_max": [3, 4], + "output": [{"index_array": [1, 2, 0, 2]}, {"input_dimension": 1}], + } + transform = IndexTransform.from_json(body) + array_map = transform.output[0] + assert isinstance(array_map, ArrayMap) + assert array_map.index_array.shape == (1, 4) + assert array_map.index_array.ndim == transform.domain.ndim + + +def test_an_index_array_of_the_wrong_rank_is_rejected() -> None: + """Inside the engine, a rank that does not match the domain is a bug.""" + with pytest.raises(ValueError, match="index_array has 1 dims"): + IndexTransform( + domain=IndexDomain.from_shape((3, 4)), + output=(ArrayMap(index_array=np.array([1, 2, 0], dtype=np.intp)),), + ) + + +def test_an_index_array_that_does_not_span_its_domain_is_rejected() -> None: + """An array with entries for only part of an axis is not a smaller selection. + + Reading it that way is how a truncated index array turned into a partially + written result rather than an error. + """ + with pytest.raises(ValueError, match="neither 1 nor the domain's extent"): + IndexTransform( + domain=IndexDomain.from_shape((3, 2)), + output=( + ArrayMap(index_array=np.zeros((3, 0), dtype=np.intp)), + DimensionMap(input_dimension=1), + ), + ) + + +def test_an_empty_index_array_collapses_to_a_constant() -> None: + """Selecting nothing must survive a trip through JSON. + + An empty index array names no cell, and can only be empty because an input + dimension is, so nothing is ever read through it. It is degenerate in + exactly the way a size-1 array is, and collapses the same way β€” which is + also what TensorStore emits for `t[ts.d[0][[]]]`. + + Emitting the array instead produced a document nothing could load: + `tolist()` renders every empty array as `[]` once the leading axis is the + zero-length one, so the rank went with it, and the loader put the dependency + back on a different axis by prepending singletons. + """ + for shape, selection in ( + ((5, 3), (np.array([], dtype=np.intp), slice(None))), + ((5, 5), (np.array([], dtype=np.intp), np.array([], dtype=np.intp))), + ): + transform = IndexTransform.from_shape(shape).oindex[selection] + body = transform.to_json() + + assert all("index_array" not in m for m in body["output"]) + reloaded = IndexTransform.from_json(body) + assert reloaded.domain == transform.domain + assert reloaded.to_json() == body + + +def test_an_empty_index_array_from_elsewhere_is_recovered_from_the_domain() -> None: + """A producer that does emit one is still readable when the domain settles it. + + This package never writes such a document, but ndsel does not forbid it, and + the domain names the axis unambiguously when exactly one dimension is empty. + """ + body: IndexTransformJSON = { + "input_inclusive_min": [0, 0], + "input_exclusive_max": [0, 4], + "output": [{"index_array": []}, {"input_dimension": 1}], + } + array_map = IndexTransform.from_json(body).output[0] + assert isinstance(array_map, ArrayMap) + assert array_map.index_array.shape == (0, 1) + + +def test_an_ambiguous_empty_index_array_is_rejected() -> None: + """Two zero-length dimensions leave nothing to recover the axis from.""" + body: IndexTransformJSON = { + "input_inclusive_min": [0, 0], + "input_exclusive_max": [0, 0], + "output": [{"index_array": []}, {"input_dimension": 1}], + } + with pytest.raises(NdselError) as excinfo: + IndexTransform.from_json(body) + assert excinfo.value.reason == "invalid_json" + assert "zero-length" in str(excinfo.value) + + +@pytest.mark.parametrize( + ("document", "reason", "detail"), + [ + ( + {"input_inclusive_min": [0.0], "input_exclusive_max": [3], "input_labels": [""]}, + "invalid_json", + "must be an integer", + ), + ( + {"input_inclusive_min": [0], "input_exclusive_max": ["3"], "input_labels": [""]}, + "invalid_json", + "must be an integer", + ), + ( + {"input_inclusive_min": [False], "input_exclusive_max": [True], "input_labels": [""]}, + "invalid_json", + "must be an integer", + ), + ( + {"input_inclusive_min": [0], "input_exclusive_max": [3], "input_labels": [5]}, + "invalid_json", + "must be a string", + ), + ( + {"input_inclusive_min": [0], "input_exclusive_max": [2**200], "input_labels": [""]}, + "invalid_json", + "64-bit signed range", + ), + ], + ids=["float", "string", "bool", "non-string-label", "out-of-range"], +) +def test_a_malformed_domain_document_is_rejected(document: Any, reason: str, detail: str) -> None: + """The domain loader validates what the message layer validates. + + Reading the keys directly was a second, undefended way into the same + objects: a bare `int()` truncated `3.9` to 3, coerced `"3"` and `True`, and + let a non-string label into a `tuple[str, ...]` β€” each building a domain + that was not the document's, and re-dumping as a different document. + """ + with pytest.raises(NdselError) as excinfo: + IndexDomain.from_json(document) + assert excinfo.value.reason == reason + assert detail in str(excinfo.value) + + +def test_a_transform_body_cannot_reinterpret_itself_as_another_message() -> None: + """A `kind` inside the body must not change which message is being read.""" + with pytest.raises(NdselError) as excinfo: + IndexTransform.from_json({"kind": "points", "coords": [[1, 2], [3, 4]]}) + assert excinfo.value.reason == "invalid_json" + assert "kind" in str(excinfo.value) + + +def test_an_engine_invariant_failure_leaves_the_loader_as_a_typed_error() -> None: + """A document is invalid input however deep the check that catches it lives. + + The engine's rank and span invariants are the last gate a document passes, + and they raised a bare `ValueError` written in the engine's vocabulary. + """ + body: IndexTransformJSON = { + "input_rank": 1, + "input_inclusive_min": [0], + "input_exclusive_max": [5], + "input_labels": [""], + "output": [{"index_array": [[1, 2], [3, 4]]}], + } + with pytest.raises(NdselError) as excinfo: + IndexTransform.from_json(body) + assert excinfo.value.reason == "rank_mismatch" diff --git a/packages/zarr-indexing/tests/test_lazy_array.py b/packages/zarr-indexing/tests/test_lazy_array.py new file mode 100644 index 0000000000..ab94be1ae5 --- /dev/null +++ b/packages/zarr-indexing/tests/test_lazy_array.py @@ -0,0 +1,2618 @@ +"""Tests for `zarr_indexing.grid` grids and the `LazyArray` wrapper. + +The happy-path suite is a single oracle test: every selection case is applied +both to a `LazyArray` and to the NumPy array it wraps, and the results must +match. The case list is crossed with four source flavors β€” an unchunked NumPy +array, NumPy with each of the two declared chunk conventions, and a zarr array +whose chunking is auto-discovered β€” so the chunked and unchunked resolution +strategies are held to the same answers. +""" + +from __future__ import annotations + +import operator +import pickle +from concurrent.futures import ThreadPoolExecutor +from dataclasses import replace +from typing import TYPE_CHECKING, Any, cast + +import numpy as np +import pytest + +import zarr_indexing.lazy_array as lazy_array_module +from zarr_indexing import ( + ArrayMap, + ChunkGrid, + ChunkProjection, + ConstantMap, + DimensionMap, + EdgeDimensionGrid, + FixedDimension, + IndexTransform, + LazyArray, + ReadContext, + VaryingDimension, + dimension_grids_from_chunks, +) +from zarr_indexing.lazy_array import _out_selection_cell_count, _validate_prepared_parts +from zarr_indexing.reader import Reader, basic_reader, numpy_reader +from zarr_indexing.testing import repartition + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + +SHAPE = (7, 5, 4) +PART_SHAPE = (3, 2, 3) +EXPLICIT_PARTS = ((3, 3, 1), (2, 2, 1), (3, 1)) + + +class IndexLike: + """A scalar integer selector implemented only through `__index__`.""" + + def __init__(self, value: int) -> None: + self.value = value + + def __index__(self) -> int: + return self.value + + +class IntOnly: + def __int__(self) -> int: + return 2 + + +class BadIndex: + """An `__index__` that lies: the protocol requires an integer.""" + + def __index__(self) -> int: + return cast("int", 2.5) + + +def reference() -> np.ndarray[Any, np.dtype[np.int64]]: + """The array every source flavor holds, and the oracle for every case.""" + return np.arange(int(np.prod(SHAPE)), dtype=np.int64).reshape(SHAPE) + + +class DelegatingReader: + def __init__(self, inner: Reader) -> None: + self.inner = inner + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + self.inner.read_into(source, context, out) + + +def outer(ref: np.ndarray[Any, Any], selections: Sequence[Any]) -> np.ndarray[Any, Any]: + """NumPy oracle for orthogonal indexing: the outer product of per-axis selections. + + Scalar integers are basic indices β€” NumPy applies them first and drops the + axis β€” so they are peeled off before the outer product is formed. + """ + scalars = tuple( + sel if isinstance(sel, (int, np.integer)) and not isinstance(sel, bool) else slice(None) + for sel in selections + ) + reduced = ref[scalars] + axes = [ + np.arange(size)[sel] + for size, sel in zip( + reduced.shape, + [ + s + for s in selections + if not (isinstance(s, (int, np.integer)) and not isinstance(s, bool)) + ], + strict=True, + ) + ] + if len(axes) == 0: + return reduced + return reduced[np.ix_(*axes)] + + +# --------------------------------------------------------------------------- +# EdgeDimensionGrid +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("sizes", "expected_index_to_chunk", "expected_offsets", "expected_sizes"), + [ + # A clipped edge chunk. + ((3, 3, 1), [0, 0, 0, 1, 1, 1, 2], [0, 3, 6], [3, 3, 1]), + # A single chunk covering the whole axis. + ((4,), [0, 0, 0, 0], [0], [4]), + # A size-1 axis. + ((1,), [0], [0], [1]), + # Irregular sizes: the grid does not have to be regular. + ((1, 2, 1), [0, 1, 1, 2], [0, 1, 3], [1, 2, 1]), + ], +) +def test_edge_dimension_grid( + sizes: tuple[int, ...], + expected_index_to_chunk: list[int], + expected_offsets: list[int], + expected_sizes: list[int], +) -> None: + """All four `DimensionGridLike` methods agree with hand-computed values.""" + grid = EdgeDimensionGrid(sizes) + extent = sum(sizes) + + assert grid.num_chunks == len(sizes) + assert grid.extent == extent + assert [grid.index_to_chunk(i) for i in range(extent)] == expected_index_to_chunk + assert [grid.chunk_offset(c) for c in range(len(sizes))] == expected_offsets + assert [grid.chunk_size(c) for c in range(len(sizes))] == expected_sizes + np.testing.assert_array_equal( + grid.indices_to_chunks(np.arange(extent, dtype=np.intp)), + np.asarray(expected_index_to_chunk, dtype=np.intp), + ) + + +def test_edge_dimension_grid_rejects_nonpositive_size() -> None: + with pytest.raises(ValueError, match="chunk sizes must be positive"): + EdgeDimensionGrid((3, 0, 2)) + + +def test_edge_dimension_grid_rejects_out_of_bounds_index() -> None: + with pytest.raises(IndexError, match="out of bounds for an axis of extent 4"): + EdgeDimensionGrid((3, 1)).index_to_chunk(4) + + +def test_edge_dimension_grid_rejects_out_of_bounds_chunk() -> None: + with pytest.raises(IndexError, match="chunk index 2 is out of bounds"): + EdgeDimensionGrid((3, 1)).chunk_offset(2) + + +@pytest.mark.parametrize( + "grid", + [ + pytest.param(FixedDimension(size=2, extent=4), id="fixed"), + pytest.param(VaryingDimension(edges=(1, 3), extent=4), id="varying"), + ], +) +def test_compact_dimension_grid_rejects_vector_below_extent(grid: Any) -> None: + with pytest.raises(IndexError, match=r"indices must lie in \[0, 4\); got \[-1, 1\]"): + grid.indices_to_chunks(np.array([-1, 1], dtype=np.intp)) + + +@pytest.mark.parametrize( + "grid", + [ + pytest.param(FixedDimension(size=2, extent=4), id="fixed"), + pytest.param(VaryingDimension(edges=(1, 3), extent=4), id="varying"), + ], +) +def test_compact_dimension_grid_rejects_vector_above_extent(grid: Any) -> None: + with pytest.raises(IndexError, match=r"indices must lie in \[0, 4\); got \[1, 4\]"): + grid.indices_to_chunks(np.array([1, 4], dtype=np.intp)) + + +def test_fixed_dimension_rejects_zero_size_for_nonempty_extent() -> None: + with pytest.raises(ValueError, match="size must be > 0 when extent is nonzero"): + FixedDimension(size=0, extent=4) + + +def test_fixed_dimension_retains_zero_size_for_zero_extent() -> None: + grid = FixedDimension(size=0, extent=0) + + assert grid.nchunks == 0 + assert grid.ngridcells == 0 + + +@pytest.mark.parametrize( + ("chunks", "shape", "expected"), + [ + # Uniform chunk shape, tail clipped. + ((3, 4), (7, 4), (FixedDimension(size=3, extent=7), FixedDimension(size=4, extent=4))), + # Dask-convention per-axis sizes, passed through. + ( + ((3, 3, 1), (2, 2)), + (7, 4), + (VaryingDimension(edges=(3, 3, 1), extent=7), VaryingDimension(edges=(2, 2), extent=4)), + ), + # A chunk longer than the axis collapses to one clipped chunk. + ((10,), (4,), (FixedDimension(size=10, extent=4),)), + # A zero-length axis has no chunks at all. + ((3,), (0,), (FixedDimension(size=3, extent=0),)), + ], +) +def test_dimension_grids_from_chunks( + chunks: Any, shape: tuple[int, ...], expected: tuple[Any, ...] +) -> None: + grids = dimension_grids_from_chunks(chunks, shape) + assert grids == expected + + +def test_regular_dimension_metadata_is_constant_in_chunk_count() -> None: + dimensions = dimension_grids_from_chunks((1,), (1_000_000,)) + + assert dimensions == (FixedDimension(size=1, extent=1_000_000),) + assert dimensions[0].nchunks == 1_000_000 + assert dimensions[0].index_to_chunk(999_999) == 999_999 + + +def test_chunk_grid_distinguishes_codec_and_data_shape_at_the_edge() -> None: + grid = ChunkGrid(dimensions=(FixedDimension(size=3, extent=7),)) + + edge = grid[(2,)] + + assert edge is not None + assert edge.slices == (slice(6, 7, 1),) + assert edge.shape == (1,) + assert edge.codec_shape == (3,) + + +def test_dimension_grids_reject_negative_shape() -> None: + with pytest.raises(ValueError, match="shape entries must be non-negative"): + dimension_grids_from_chunks((3,), (-1,)) + + +def test_dimension_grids_from_chunks_rejects_wrong_length() -> None: + with pytest.raises(ValueError, match="one entry per dimension"): + dimension_grids_from_chunks((3,), (7, 4)) + + +def test_dimension_grids_from_chunks_rejects_mixed_conventions() -> None: + with pytest.raises(ValueError, match="not a mixture"): + dimension_grids_from_chunks((3, (2, 2)), (7, 4)) + + +def test_dimension_grids_from_chunks_rejects_wrong_total() -> None: + with pytest.raises(ValueError, match="sum to 5, but the array extent is 7"): + dimension_grids_from_chunks(((3, 2), (4,)), (7, 4)) + + +def test_dimension_grids_from_chunks_rejects_non_sequence_entry() -> None: + """A float entry is neither convention, and says so instead of raising TypeError.""" + with pytest.raises(ValueError, match=r"3\.5 at dimension 0 is neither"): + dimension_grids_from_chunks((3.5, (4,)), (7, 4)) + + +def test_array_map_dependent_axis_reports_no_axis() -> None: + """A map varying over nothing answers None rather than a stale binding.""" + correlated = ArrayMap(index_array=np.array([[1], [2]], dtype=np.intp)) + assert correlated.dependent_axis == 0 + assert ArrayMap(index_array=np.array([[3]], dtype=np.intp)).dependent_axis is None + + +def test_scalar_on_a_fancy_axis_collapses_to_a_constant() -> None: + """The degenerate-collapse rule: an all-singleton ArrayMap becomes a ConstantMap. + + Without it the map keeps an `input_dimension` naming an axis the integer + index just removed, which after renumbering aliases a different axis. + """ + view = IndexTransform.from_shape((7, 5)).oindex[np.array([3, 1]), slice(None)][0] + assert view.output[0] == ConstantMap(offset=3) + assert isinstance(view.output[1], DimensionMap) + assert view.domain.shape == (5,) + + +# --------------------------------------------------------------------------- +# Sources +# --------------------------------------------------------------------------- + + +def make_zarr_source() -> Any: + """A zarr array holding `reference()`, whose parts are auto-discovered.""" + zarr = pytest.importorskip("zarr") + array = zarr.create_array({}, shape=SHAPE, chunks=PART_SHAPE, dtype="int64") + array[:] = reference() + return array + + +def make_source(flavor: str) -> LazyArray: + """Build a `LazyArray` over `reference()` with the requested partitioning.""" + data = reference() + if flavor == "numpy-whole": + return LazyArray(data) + if flavor == "numpy-explicit-parts": + return LazyArray(data).with_parts_per_axis(EXPLICIT_PARTS) + if flavor == "numpy-uniform-parts": + return LazyArray(data).with_parts(PART_SHAPE) + if flavor == "zarr": + return LazyArray(make_zarr_source()) + if flavor == "zarr-misaligned": + # Parts that deliberately straddle the zarr array's own chunks. + return LazyArray(make_zarr_source()).with_parts((4, 3, 3)) + raise TypeError(f"unknown source flavor {flavor!r}") + + +FLAVORS = [ + "numpy-whole", + "numpy-explicit-parts", + "numpy-uniform-parts", + "zarr", + "zarr-misaligned", +] + + +@pytest.fixture(params=FLAVORS) +def source(request: pytest.FixtureRequest) -> LazyArray: + return make_source(request.param) + + +# --------------------------------------------------------------------------- +# The oracle +# --------------------------------------------------------------------------- + +MASK = (reference() % 11) == 0 +# A mask over the two trailing axes, for the `vindex[..., mask]` idiom. +TRAILING_MASK = (reference()[0] % 3) == 0 + +# (id, lazy view builder, NumPy oracle). Integer scalars are deliberately absent +# from the orthogonal cases: the transform algebra keeps an int-selected axis as +# a length-1 axis under `oindex`, which `np.ix_` cannot express. +CASES: list[tuple[str, Callable[[LazyArray], LazyArray], Callable[[Any], Any]]] = [ + ( + "basic-strided-and-int-drop", + lambda a: a.lazy[1:6:2, :, -1], + lambda r: r[1:6:2, :, -1], + ), + ("basic-ellipsis", lambda a: a.lazy[..., -2], lambda r: r[..., -2]), + ("basic-negative-scalar", lambda a: a.lazy[-3], lambda r: r[-3]), + ("basic-newaxis", lambda a: a.lazy[None, :, :, None], lambda r: r[None, :, :, None]), + ("basic-empty", lambda a: a.lazy[:, 2:2, :], lambda r: r[:, 2:2, :]), + ("basic-all-scalars", lambda a: a.lazy[-1, 0, 2], lambda r: r[-1, 0, 2]), + ( + "oindex-unsorted-duplicates-multi-axis", + lambda a: a.lazy.oindex[[4, 0, 0, 2], :, [3, 1]], + lambda r: outer(r, ([4, 0, 0, 2], slice(None), [3, 1])), + ), + ( + "oindex-negative-and-slice", + lambda a: a.lazy.oindex[:, [-1, 0], 1:4], + lambda r: outer(r, (slice(None), [-1, 0], slice(1, 4))), + ), + ( + "oindex-boolean-axis", + lambda a: a.lazy.oindex[np.array([True, False, True, False, False, False, True]), :, :], + lambda r: outer( + r, + (np.array([True, False, True, False, False, False, True]), slice(None), slice(None)), + ), + ), + ( + "vindex-coordinates", + lambda a: a.lazy.vindex[np.array([0, 6, 3]), np.array([1, 4, 0]), np.array([2, 0, 1])], + lambda r: r[np.array([0, 6, 3]), np.array([1, 4, 0]), np.array([2, 0, 1])], + ), + ( + "vindex-broadcast-pair", + lambda a: a.lazy.vindex[np.array([[0], [6]]), np.array([1, 4]), np.array([2, 0])], + lambda r: r[np.array([[0], [6]]), np.array([1, 4]), np.array([2, 0])], + ), + ( + "vindex-negative-coordinates", + lambda a: a.lazy.vindex[np.array([-1, -7]), np.array([-2, 0]), np.array([0, -1])], + lambda r: r[np.array([-1, -7]), np.array([-2, 0]), np.array([0, -1])], + ), + ("vindex-mask", lambda a: a.lazy.vindex[MASK], lambda r: r[MASK]), + ( + "compose-basic-then-oindex", + lambda a: a.lazy[1:6].lazy.oindex[[3, 0, 0], [4, 1], :], + lambda r: outer(r[1:6], ([3, 0, 0], [4, 1], slice(None))), + ), + ( + "compose-oindex-then-basic-other-axis", + lambda a: a.lazy.oindex[[4, 0, 2], :, :].lazy[:, 1:4, ::2], + lambda r: outer(r, ([4, 0, 2], slice(None), slice(None)))[:, 1:4, ::2], + ), + ( + "compose-basic-then-basic", + lambda a: a.lazy[2:, 1:].lazy[::2, -1], + lambda r: r[2:, 1:][::2, -1], + ), + ( + "compose-basic-then-vindex", + lambda a: a.lazy[1:6, :, 1:].lazy.vindex[ + np.array([0, 4]), np.array([2, 0]), np.array([1, 2]) + ], + lambda r: r[1:6, :, 1:][np.array([0, 4]), np.array([2, 0]), np.array([1, 2])], + ), + # Scalar integers are basic indices in the positional dialect: they drop the + # axis, in every mode, exactly as NumPy does. + ("oindex-scalar-drops-axis", lambda a: a.lazy.oindex[0], lambda r: r[0]), + ( + "oindex-scalar-with-arrays", + lambda a: a.lazy.oindex[0, [1, 2], :], + lambda r: outer(r, (0, [1, 2], slice(None))), + ), + ( + "oindex-scalar-middle-axis", + lambda a: a.lazy.oindex[[3, 1], -1, :], + lambda r: outer(r, ([3, 1], -1, slice(None))), + ), + ("oindex-all-scalars", lambda a: a.lazy.oindex[0, 1, 2], lambda r: r[0, 1, 2]), + ("vindex-all-scalars", lambda a: a.lazy.vindex[0, 1, 2], lambda r: r[0, 1, 2]), + ( + "vindex-scalar-with-arrays", + lambda a: a.lazy.vindex[0, [1, 2], [3, 0]], + lambda r: r[0, [1, 2], [3, 0]], + ), + ( + "vindex-scalar-on-middle-axis", + lambda a: a.lazy.vindex[[1, 2], 0, [3, 0]], + lambda r: r[[1, 2], 0, [3, 0]], + ), + # Scalar applied to a previously fancy-indexed axis, both orders. + ( + "compose-oindex-then-scalar", + lambda a: a.lazy.oindex[[3, 1], :, :].lazy[0], + lambda r: outer(r, ([3, 1], slice(None), slice(None)))[0], + ), + ( + "compose-oindex-then-scalar-negative", + lambda a: a.lazy.oindex[[3, 1, 1], :, :].lazy[-1, 2], + lambda r: outer(r, ([3, 1, 1], slice(None), slice(None)))[-1, 2], + ), + ( + "compose-scalar-then-oindex", + lambda a: a.lazy[0].lazy.oindex[[3, 1], :], + lambda r: outer(r[0], ([3, 1], slice(None))), + ), + ( + "compose-vindex-then-scalar", + lambda a: a.lazy.vindex[np.array([0, 6, 3]), np.array([1, 4, 0]), np.array([2, 0, 1])].lazy[ + 1 + ], + lambda r: r[np.array([0, 6, 3]), np.array([1, 4, 0]), np.array([2, 0, 1])][1], + ), + # Partial vindex whose coordinate arrays are NOT on the leading axes: NumPy + # inserts the gathered axis where the (adjacent) advanced indices sat. + ( + "vindex-trailing-arrays", + lambda a: a.lazy.vindex[..., np.array([1, 4, 0]), np.array([2, 0, 1])], + lambda r: r[..., np.array([1, 4, 0]), np.array([2, 0, 1])], + ), + ( + "vindex-single-trailing-array", + lambda a: a.lazy.vindex[..., np.array([3, 0, 1])], + lambda r: r[..., np.array([3, 0, 1])], + ), + ( + "vindex-trailing-mask", + lambda a: a.lazy.vindex[..., TRAILING_MASK], + lambda r: r[..., TRAILING_MASK], + ), + ( + "vindex-leading-partial", + lambda a: a.lazy.vindex[np.array([1, 2, 2])], + lambda r: r[np.array([1, 2, 2])], + ), + ( + "compose-basic-then-vindex-trailing", + lambda a: a.lazy[2:, 1:].lazy.vindex[..., np.array([1, 3, 0])], + lambda r: r[2:, 1:][..., np.array([1, 3, 0])], + ), + # A ConstantMap sitting between a slice and the coordinate arrays: NumPy + # counts the integer as an advanced index, so the gathered axis moves to the + # front of the chunk block even though the arrays are trailing. + ( + "compose-vindex-trailing-then-scalar", + lambda a: a.lazy.vindex[..., np.array([3, 0])].lazy[2], + lambda r: r[..., np.array([3, 0])][2], + ), + # Two fancy axes, then a scalar on the first: the surviving ArrayMap ends up + # behind a ConstantMap and a slice, which is where NumPy's integer-counts-as- + # advanced rule bites. + ( + "compose-oindex-two-axes-then-scalar", + lambda a: a.lazy.oindex[[3, 1, 0], 3:5, [2, 0, 2]].lazy[0], + lambda r: outer(r, ([3, 1, 0], slice(3, 5), [2, 0, 2]))[0], + ), + # Negative steps: the positional dialect is NumPy's, including the empty + # cases NumPy allows where the transform algebra alone would object. + ("reverse", lambda a: a.lazy[::-1], lambda r: r[::-1]), + ("reverse-every-axis", lambda a: a.lazy[::-1, ::-1, ::-1], lambda r: r[::-1, ::-1, ::-1]), + ("reverse-strided", lambda a: a.lazy[::-2], lambda r: r[::-2]), + ("reverse-nondivisible", lambda a: a.lazy[::-3], lambda r: r[::-3]), + ("reverse-bounded", lambda a: a.lazy[5:1:-1], lambda r: r[5:1:-1]), + ("reverse-negative-start", lambda a: a.lazy[-1:None:-1], lambda r: r[-1:None:-1]), + ("reverse-past-the-start", lambda a: a.lazy[:-8:-1], lambda r: r[:-8:-1]), + ("reverse-empty", lambda a: a.lazy[2:2:-1], lambda r: r[2:2:-1]), + # NumPy reads a reversed *positional* interval as empty; only the literal + # layer calls it a direction error. + ("reverse-inverted-is-empty", lambda a: a.lazy[2:5:-1], lambda r: r[2:5:-1]), + ("reverse-with-int-drop", lambda a: a.lazy[::-2, 2, ::-1], lambda r: r[::-2, 2, ::-1]), + ("reverse-trailing-axis", lambda a: a.lazy[..., ::-1], lambda r: r[..., ::-1]), + ( + "compose-reverse-then-reverse", + lambda a: a.lazy[::-1].lazy[::-1], + lambda r: r[::-1][::-1], + ), + ( + "compose-strided-then-reverse", + lambda a: a.lazy[::2].lazy[::-1], + lambda r: r[::2][::-1], + ), + ( + "compose-reverse-then-strided", + lambda a: a.lazy[::-1].lazy[::2], + lambda r: r[::-1][::2], + ), + ( + "compose-reverse-then-oindex", + lambda a: a.lazy[::-1].lazy.oindex[[3, 0, 0], :, :], + lambda r: outer(r[::-1], ([3, 0, 0], slice(None), slice(None))), + ), + ( + "compose-oindex-then-reverse", + lambda a: a.lazy.oindex[[3, 1, 2], :, :].lazy[::-1], + lambda r: outer(r, ([3, 1, 2], slice(None), slice(None)))[::-1], + ), + ( + "compose-reverse-then-vindex", + lambda a: a.lazy[::-1].lazy.vindex[..., np.array([1, 3, 0])], + lambda r: r[::-1][..., np.array([1, 3, 0])], + ), + ( + "compose-vindex-trailing-then-scalar-and-slice", + lambda a: a.lazy.vindex[..., np.array([3, 0, 1])].lazy[-1, 1:4], + lambda r: r[..., np.array([3, 0, 1])][-1, 1:4], + ), + # A downward walk that begins off the front of the axis selects nothing. + # Written against an oindex axis and a vindex axis, where the selection is + # carried by an index array rather than by the domain. + ( + "compose-oindex-then-empty-downward-walk", + lambda a: a.lazy.oindex[np.array([3, 1, 4]), :, :].lazy[-8::-1], + lambda r: r[np.array([3, 1, 4])][-8::-1], + ), + ( + "compose-vindex-then-empty-downward-walk", + lambda a: a.lazy.vindex[np.array([3, 1]), np.array([2, 0])].lazy[-9::-2], + lambda r: r[np.array([3, 1]), np.array([2, 0])][-9::-2], + ), + ( + "empty-downward-walk-on-a-plain-axis", + lambda a: a.lazy[-11::-1], + lambda r: r[-11::-1], + ), + # A fancy *spelling* whose entries are all slices is not a fancy selection: + # it narrows the view's own axes and must compose exactly like basic + # indexing. The slices start past 0, so a step that applied them to the + # broadcast (singleton) axes of the existing index array would truncate it. + ( + "compose-oindex-then-oindex-slices-only", + lambda a: a.lazy.oindex[[4, 0, 0], :, :].lazy.oindex[:, 2:5, 1:], + lambda r: outer(r, ([4, 0, 0], slice(None), slice(None)))[:, 2:5, 1:], + ), + ( + "compose-oindex-then-oindex-slices-only-strided", + lambda a: a.lazy.oindex[:, [3, 1, 1], :].lazy.oindex[1::2, :, ::-1], + lambda r: outer(r, (slice(None), [3, 1, 1], slice(None)))[1::2, :, ::-1], + ), + ( + "compose-vindex-then-oindex-slices-only", + lambda a: a.lazy.vindex[np.array([4, 0, 2]), np.array([1, 3, 0])].lazy.oindex[1:, 2:], + lambda r: r[np.array([4, 0, 2]), np.array([1, 3, 0])][1:, 2:], + ), + ( + "compose-oindex-then-oindex-array-on-its-own-axis", + lambda a: a.lazy.oindex[[4, 0, 0], :, :].lazy.oindex[[2, 0], 3:, :], + lambda r: outer( + outer(r, ([4, 0, 0], slice(None), slice(None))), + ([2, 0], slice(3, None), slice(None)), + ), + ), +] + + +@pytest.mark.parametrize(("build", "oracle"), [c[1:] for c in CASES], ids=[c[0] for c in CASES]) +def test_selection_matches_numpy( + source: LazyArray, + build: Callable[[LazyArray], LazyArray], + oracle: Callable[[Any], Any], +) -> None: + """Every selection resolves to what NumPy computes positionally on the same data.""" + view = build(source) + expected = np.asarray(oracle(reference())) + + assert view.shape == expected.shape + assert view.ndim == expected.ndim + np.testing.assert_array_equal(np.asarray(view.result()), expected) + # `__getitem__` is eager, and `__array__` routes through `result()`. + np.testing.assert_array_equal(np.asarray(view), expected) + + +# --------------------------------------------------------------------------- +# Randomized chain sweep +# --------------------------------------------------------------------------- + + +def _random_basic(rng: np.random.Generator, shape: tuple[int, ...]) -> tuple[Any, ...]: + selection: list[Any] = [] + for size in shape: + roll = rng.random() + if roll < 0.3: + selection.append(int(rng.integers(-size, size))) + elif roll < 0.55: + start = int(rng.integers(0, size)) + stop = int(rng.integers(start, size + 1)) + selection.append(slice(start, stop, int(rng.integers(1, 4)))) + elif roll < 0.8: + # Downward: `start >= stop` and the stop may fall off the front, + # which is spelled `None`. The start is drawn from below `-size` as + # well, where the walk begins off the front and selects nothing β€” + # a case that reads as an ordinary negative index but is empty. + start = int(rng.integers(-2 * size - 1, size)) if size else 0 + stop_choice = int(rng.integers(-1, max(start, 0) + 1)) + stop = None if stop_choice < 0 else stop_choice + selection.append(slice(start, stop, -int(rng.integers(1, 4)))) + else: + selection.append(slice(None)) + return tuple(selection) + + +def _random_oindex(rng: np.random.Generator, shape: tuple[int, ...]) -> tuple[Any, ...]: + selection: list[Any] = [] + for size in shape: + roll = rng.random() + if roll < 0.25: + selection.append(int(rng.integers(-size, size))) + elif roll < 0.65: + count = int(rng.integers(1, 5)) + selection.append(rng.integers(-size, size, size=count).tolist()) + elif roll < 0.8: + mask = rng.random(size) < 0.5 + mask[int(rng.integers(0, size))] = True + selection.append(mask) + else: + start = int(rng.integers(0, size)) + selection.append(slice(start, size)) + return tuple(selection) + + +def _broadcast_singleton_axes( + rng: np.random.Generator, entries: list[Any], length: int +) -> list[Any]: + """Reshape 1-D coordinate arrays so the selection carries singleton axes. + + A coordinate array of shape `(1, n)` or `(n, 1)` contributes a broadcast axis + it does not vary over. That axis stays in the view's domain, and a later + basic index that consumes its partner leaves it referenced by no output map + at all β€” the shape that makes a broadcast axis and a genuine extent-1 axis + indistinguishable from the index array alone. + """ + rank = int(rng.integers(2, 4)) + reshaped: list[Any] = [] + for entry in entries: + if not isinstance(entry, np.ndarray): + reshaped.append(entry) + continue + varying = int(rng.integers(0, rank)) + reshaped.append( + entry.reshape(tuple(length if axis == varying else 1 for axis in range(rank))) + ) + return reshaped + + +def _random_vindex(rng: np.random.Generator, shape: tuple[int, ...]) -> tuple[Any, ...]: + ndim = len(shape) + count = int(rng.integers(1, ndim + 1)) + trailing = bool(rng.random() < 0.5) + axes = range(ndim - count, ndim) if trailing else range(count) + sizes = [shape[axis] for axis in axes] + + entries: list[Any] + if rng.random() < 0.2: + # A single boolean mask spanning the whole covered block. + mask = rng.random(tuple(sizes)) < 0.5 + mask.flat[int(rng.integers(0, mask.size))] = True + entries = [mask] + else: + length = int(rng.integers(1, 5)) + entries = [ + int(rng.integers(-size, size)) + if rng.random() < 0.25 + else rng.integers(-size, size, size=length) + for size in sizes + ] + if rng.random() < 0.35: + entries = _broadcast_singleton_axes(rng, entries, length) + return (Ellipsis, *entries) if trailing else tuple(entries) + + +def _apply_oracle( + ref: np.ndarray[Any, Any], mode: str, selection: tuple[Any, ...] +) -> np.ndarray[Any, Any]: + if mode == "orthogonal": + return outer(ref, selection) + # NumPy's own semantics *are* basic and vectorized indexing. + return ref[selection] + + +def _apply_view(view: LazyArray, mode: str, selection: tuple[Any, ...]) -> LazyArray: + if mode == "basic": + return view.lazy[selection] + if mode == "orthogonal": + return view.lazy.oindex[selection] + return view.lazy.vindex[selection] + + +def _random_slices_only(rng: np.random.Generator, shape: tuple[int, ...]) -> tuple[Any, ...]: + """A selection of slices alone, spelled through `oindex`. + + `oindex` entries that are all slices are not a fancy selection β€” they narrow + the view's own axes and must compose like basic indexing. A start past 0 is + what distinguishes a step that walks the index array's dependency axes from + one that walks its broadcast singletons, so slices are drawn to reach past + the origin. (`vindex` is coordinate-only and rejects a slice outright, so + this spelling has no vectorized counterpart.) + """ + selection: list[Any] = [] + for size in shape: + roll = rng.random() + if roll < 0.4: + start = int(rng.integers(0, size)) if size else 0 + selection.append(slice(start, size)) + elif roll < 0.7: + start = int(rng.integers(0, size)) if size else 0 + selection.append(slice(start, size, int(rng.integers(1, 3)))) + elif roll < 0.85: + selection.append(slice(None, None, -1)) + else: + selection.append(slice(None)) + return tuple(selection) + + +def _random_chain(rng: np.random.Generator) -> list[tuple[str, tuple[Any, ...]]]: + """A chain of 2-4 steps, any of which may be fancy. + + A step spelled through `oindex` but carrying only slices is drawn separately + (`slices-only`): it narrows an existing index array by a *slice* rather than + by coordinates, a distinct code path kept at full weight. + """ + n_steps = int(rng.integers(2, 5)) + fancy_steps = {int(rng.integers(0, n_steps)) for _ in range(2)} + slices_only_at = int(rng.integers(0, n_steps)) if rng.random() < 0.4 else -1 + + chain: list[tuple[str, tuple[Any, ...]]] = [] + running = reference() + for step in range(n_steps): + if running.ndim == 0 or running.size == 0: + break + if step in fancy_steps: + mode = "orthogonal" if rng.random() < 0.5 else "vectorized" + else: + mode = "basic" + if step == slices_only_at and step not in fancy_steps: + mode = "orthogonal" + selection = _random_slices_only(rng, running.shape) + elif mode == "basic": + selection = _random_basic(rng, running.shape) + elif mode == "orthogonal": + selection = _random_oindex(rng, running.shape) + else: + selection = _random_vindex(rng, running.shape) + chain.append((mode, selection)) + running = _apply_oracle(running, mode, selection) + return chain + + +@pytest.mark.parametrize("flavor", FLAVORS) +def test_random_chains_match_numpy(flavor: str) -> None: + """A seeded sweep of composed chains, under every partitioning. + + The partitioning invariant as a property: `result()` is identical whatever + boxes the read is broken into, including boxes deliberately misaligned with + the source's own. + """ + rng = np.random.default_rng(20260730) + source = make_source(flavor) + partitionings: list[Any] = [None, (2, 2, 2), (7, 5, 4), ((4, 3), (1, 3, 1), (3, 1))] + # Reads against a real store cost more per chain; the NumPy flavors carry + # the bulk of the sweep and exercise the identical code path. + n_chains = 120 if flavor.startswith("zarr") else 400 + + for _ in range(n_chains): + chain = _random_chain(rng) + expected = reference() + for mode, selection in chain: + expected = _apply_oracle(expected, mode, selection) + + view = source + for mode, selection in chain: + view = _apply_view(view, mode, selection) + + assert view.shape == expected.shape, f"{flavor}: {chain}" + np.testing.assert_array_equal( + np.asarray(view.result()), np.asarray(expected), err_msg=f"{flavor}: {chain}" + ) + for parts in partitionings: + np.testing.assert_array_equal( + np.asarray(repartition(view, parts).result()), + np.asarray(expected), + err_msg=f"{flavor} parts={parts}: {chain}", + ) + + +# `result()` can absorb a defect that `parts()` cannot β€” an empty view assembles +# correctly from no parts at all, and a rank-0 one can be reshaped into place β€” +# so the iteration contract needs its own sweep, asserting the documented +# assembly literally rather than through `result()`. That sweep is the +# `ChainedIndexing` state machine in `test_lazy_array_stateful.py`, which drives +# the same operations and shrinks a failure to the chain that caused it. + + +PARTITIONINGS_1D: list[Any] = [None, (1,), (2,), (5,)] + + +def test_a_slice_only_fancy_step_after_a_fancy_step_reads_real_data() -> None: + """`oindex[:, 2:8]` after an `oindex` narrows the view, it does not re-index it. + + The second step carries no coordinates, so it is not fancy-after-fancy: it + must compose like basic indexing. Applying its slices to the *broadcast* + axes of the first step's index array instead truncates that array to size 0, + which leaves the resolver with no parts to read and `result()` handing back + an unwritten buffer. + """ + base = np.arange(24).reshape(3, 8) + expected = base[np.ix_([0, 2], range(8))][:, 2:8] + + for parts in (None, (2, 4), (1, 8), (3, 3)): + view = ( + repartition(LazyArray(base), parts).lazy.oindex[np.array([0, 2]), :].lazy.oindex[:, 2:8] + ) + assert view.shape == expected.shape, f"parts={parts}" + np.testing.assert_array_equal(np.asarray(view.result()), expected, err_msg=f"{parts}") + + +def test_a_fancy_step_composes_onto_any_axis_of_a_fancy_view() -> None: + """A second fancy step may land on axes the first one merely broadcasts along. + + Composition evaluates the existing index arrays at the new coordinates, so + `oindex` after `oindex`, `vindex` after `oindex`, and both orders around a + correlated gather all resolve β€” under every partitioning. + """ + base = np.arange(24).reshape(3, 8) + rows, cols = np.array([0, 2]), np.array([1, 3, 3]) + + for parts in (None, (2, 4), (1, 8), (3, 3)): + view = repartition(LazyArray(base), parts).lazy.oindex[rows, :] + + composed = view.lazy.oindex[:, cols] + expected = base[np.ix_(rows, cols)] + assert composed.shape == expected.shape, f"parts={parts}" + np.testing.assert_array_equal(np.asarray(composed.result()), expected, err_msg=f"{parts}") + + gathered = view.lazy.vindex[np.array([0, 1]), np.array([7, 0])] + np.testing.assert_array_equal( + np.asarray(gathered.result()), + base[np.ix_(rows, range(8))][[0, 1], [7, 0]], + err_msg=f"{parts}", + ) + + pointwise = repartition(LazyArray(base), parts).lazy.vindex[[0, 1, 2], [0, 2, 3]] + np.testing.assert_array_equal( + np.asarray(pointwise.lazy.oindex[[2, 0]].result()), + base[[0, 1, 2], [0, 2, 3]][[2, 0]], + err_msg=f"{parts}", + ) + np.testing.assert_array_equal( + np.asarray(pointwise.lazy.vindex[[1, 1, 0]].result()), + base[[0, 1, 2], [0, 2, 3]][[1, 1, 0]], + err_msg=f"{parts}", + ) + + +def test_a_partial_vindex_after_an_oindex_resolves_the_mixed_transform() -> None: + """A composed transform can mix correlated and orthogonal index arrays. + + `oindex` on the last axis then `vindex` on the first two leaves the + orthogonal gather in place while the new coordinate arrays are correlated; + resolution takes the pointwise path. + """ + base = np.arange(60).reshape(3, 4, 5) + expected = base[:, :, [4, 0]][[0, 2], [1, 3]] + + for parts in (None, (2, 2, 2), (3, 4, 5), (1, 1, 1)): + view = repartition(LazyArray(base), parts).lazy.oindex[:, :, [4, 0]] + composed = view.lazy.vindex[np.array([0, 2]), np.array([1, 3])] + assert composed.shape == expected.shape, f"parts={parts}" + np.testing.assert_array_equal(np.asarray(composed.result()), expected, err_msg=f"{parts}") + + +def test_a_boolean_mask_composes_onto_a_fancy_view() -> None: + base = np.arange(60).reshape(3, 4, 5) + mask = np.array([True, False, True]) + expected = base[[0, 1, 2]][mask] + + for parts in (None, (2, 2, 2), (1, 4, 5)): + view = repartition(LazyArray(base), parts).lazy.oindex[[0, 1, 2], :, :] + np.testing.assert_array_equal( + np.asarray(view.lazy.oindex[mask].result()), expected, err_msg=f"{parts}" + ) + + +def test_an_ellipsis_only_vindex_step_preserves_a_correlated_gather() -> None: + """Regression: a slice-only vindex step misread correlated maps as orthogonal. + + `vindex[...]` (and `vindex[..., scalar]`, whose remainder after the scalar + is split off is ellipsis-only) used to stamp each correlated map with its + block axis as an orthogonal binding. Two "orthogonal" maps then shared one + input axis, and the partition walk rejected its own transform mid-read. + """ + base = np.arange(16).reshape(4, 4) + + for parts in (None, (2, 2), (4, 4), (1, 3)): + pointwise = repartition(LazyArray(base), parts).lazy.vindex[[0, 1, 2], [0, 2, 3]] + np.testing.assert_array_equal( + np.asarray(pointwise.lazy.vindex[...].result()), + base[[0, 1, 2], [0, 2, 3]], + err_msg=f"{parts}", + ) + + planar = repartition(LazyArray(base), parts).lazy.vindex[ + np.array([[0], [1]]), np.array([[1], [3]]) + ] + np.testing.assert_array_equal( + np.asarray(planar.lazy.vindex[..., np.array(0)].result()), + base[[0, 1], [1, 3]], + err_msg=f"{parts}", + ) + + +# --------------------------------------------------------------------------- +# Domain dimensions no output map depends on +# --------------------------------------------------------------------------- +# +# A `vindex` coordinate array with a *singleton* broadcast axis leaves that axis +# in the view's domain while the map varies only over its partner. A later basic +# index that consumes the partner collapses the map to a `ConstantMap`, and the +# singleton axis survives with nothing referencing it. Every stage of resolution +# has to keep counting it: the lowered block needs the axis back at its true +# extent, and a part has to say where its values belong along it. + +UNREFERENCED_AXIS_PARTITIONINGS: list[Any] = [None, (1, 1, 1), (2, 2, 2), (3, 4, 5), (3, 1, 2)] + +# (id, view builder, NumPy oracle) over `np.arange(60).reshape(3, 4, 5)`. +UNREFERENCED_AXIS_CASES: list[ + tuple[str, Callable[[LazyArray], LazyArray], Callable[[Any], Any]] +] = [ + ( + "leading-singleton-row", + lambda a: a.lazy.vindex[np.array([[2, 0]])].lazy[:, 0], + lambda r: r[np.array([[2, 0]])][:, 0], + ), + ( + "trailing-singleton-column", + lambda a: a.lazy.vindex[np.array([[2], [0]])].lazy[0], + lambda r: r[np.array([[2], [0]])][0], + ), + ( + "repeated-coordinates-over-a-singleton", + lambda a: a.lazy.vindex[np.array([[1, 1]]), np.array([[3, 3]])].lazy[:, 0], + lambda r: r[np.array([[1, 1]]), np.array([[3, 3]])][:, 0], + ), + ( + "unreferenced-axis-emptied", + lambda a: a.lazy.vindex[np.array([[2, 0]])].lazy[0:0, 0], + lambda r: r[np.array([[2, 0]])][0:0, 0], + ), + ( + "partial-vindex-with-a-residual-slice", + lambda a: a.lazy.vindex[np.array([[2, 0]]), np.array([[1, 3]])].lazy[:, 0, 1:4], + lambda r: r[np.array([[2, 0]]), np.array([[1, 3]])][:, 0, 1:4], + ), +] + + +def unreferenced_axis_reference() -> np.ndarray[Any, np.dtype[np.int64]]: + return np.arange(60, dtype=np.int64).reshape(3, 4, 5) + + +@pytest.mark.parametrize( + ("build", "oracle"), + [case[1:] for case in UNREFERENCED_AXIS_CASES], + ids=[case[0] for case in UNREFERENCED_AXIS_CASES], +) +@pytest.mark.parametrize("parts", UNREFERENCED_AXIS_PARTITIONINGS) +def test_a_domain_axis_no_output_map_depends_on_still_resolves( + build: Callable[[LazyArray], LazyArray], + oracle: Callable[[Any], Any], + parts: Any, +) -> None: + """The value, the shape and the tiling all hold when an axis is unreferenced.""" + data = unreferenced_axis_reference() + expected = np.asarray(oracle(data)) + view = build(repartition(LazyArray(data), parts)) + + assert view.shape == expected.shape + np.testing.assert_array_equal(np.asarray(view.result()), expected) + + hits = np.zeros(view.shape, dtype=np.int64) + assembled = np.zeros(view.shape, dtype=view.dtype) + for part in view.parts(): + assembled[part.out_selection] = np.asarray(part.view.result()) + np.add.at(hits, part.out_selection, 1) + np.testing.assert_array_equal(assembled, expected) + np.testing.assert_array_equal(hits, np.ones(view.shape, dtype=np.int64)) + + +def test_an_unreferenced_domain_axis_of_extent_zero_stays_empty() -> None: + """An emptied broadcast axis must not be restored as a fabricated row. + + The lowered block has no axis for a dimension nothing depends on, so the + resolver puts one back. Putting it back at extent 1 invents a row of data + for a selection whose own `shape` says it is empty. + """ + data = np.arange(140, dtype=np.int64).reshape(7, 5, 4) + coords = np.array([[6], [3], [0]]) + for parts in (None, (1, 1, 1), (3, 2, 3), (7, 5, 4)): + view = repartition(LazyArray(data), parts).lazy.vindex[coords, -4].lazy[0, 0:0] + expected = data[coords, -4][0, 0:0] + assert view.shape == expected.shape == (0, 4), f"parts={parts}" + np.testing.assert_array_equal(np.asarray(view.result()), expected, err_msg=f"{parts}") + assert list(view.parts()) == [] + + +def test_a_zero_length_axis_resolves_the_same_way_under_every_partitioning() -> None: + """A size-0 axis carries no dependency, so it cannot make a map correlated.""" + base = np.zeros((3, 0)) + expected = base[np.ix_([1, 0, 0], np.arange(0, dtype=int))] + + for parts in (None, ((1, 1, 1), ()), ((3,), ())): + view = ( + repartition(LazyArray(base), parts) + .lazy.oindex[np.array([1, -3, -3]), :] + .lazy.oindex[:, :] + ) + assert view.shape == expected.shape, f"parts={parts}" + np.testing.assert_array_equal(np.asarray(view.result()), expected, err_msg=f"{parts}") + assert list(view.parts()) == [] + + +def test_an_empty_slice_of_a_length_one_correlated_axis_has_no_parts() -> None: + """`parts()` agrees with `result()` that an emptied view selects nothing. + + A correlated selection of exactly one point normalizes to an all-singleton + index array, indistinguishable by shape from an axis the map broadcasts + over β€” so a later slice that empties the domain leaves the array at size 1. + """ + base = np.arange(5) + mask = np.array([False, True, False, False, False]) + + for parts in PARTITIONINGS_1D: + view = repartition(LazyArray(base), parts).lazy.vindex[mask].lazy[1:-2] + assert view.shape == (0,), f"parts={parts}" + assert list(view.parts()) == [], f"parts={parts}" + np.testing.assert_array_equal(np.asarray(view.result()), base[mask][1:-2]) + + +def test_an_empty_slice_of_a_length_one_vindex_pair_has_no_parts() -> None: + """The same emptied view, spelled with explicit coordinates over two axes.""" + base = np.arange(35).reshape(7, 5) + + for parts in (None, (2, 2), (7, 5)): + view = ( + repartition(LazyArray(base), parts).lazy.vindex[np.array([6]), np.array([0])].lazy[0:0] + ) + assert view.shape == (0,), f"parts={parts}" + assert list(view.parts()) == [], f"parts={parts}" + np.testing.assert_array_equal( + np.asarray(view.result()), base[np.array([6]), np.array([0])][0:0] + ) + + +def test_a_correlated_view_narrowed_to_one_point_has_parts_of_the_views_rank() -> None: + """A rank-0 broadcast block survives intersection without gaining an axis. + + `Partition` documents `out[part.out_selection] = part.view.result()` as the + assembly, so a part's values must arrive at the rank the view has β€” including + the rank 0 a correlated selection reaches once every coordinate is a scalar. + """ + base = np.arange(140).reshape(7, 5, 4) + cases = [ + # No residual slice: the whole view is the one gathered point. + ((np.array([-1]), np.array([-1]), np.array([2])), 0), + # One residual slice dimension survives alongside the collapsed block. + ((np.array([6, 1]), np.array([4, 0])), 1), + ] + + for parts in (None, (2, 2, 2), (3, 3, 3), (7, 5, 4)): + for selection, tail in cases: + expected = base[selection][tail] + view = repartition(LazyArray(base), parts).lazy.vindex[selection].lazy[tail] + assert view.shape == expected.shape, f"parts={parts}, {selection}" + + assembled = np.zeros(view.shape, dtype=view.dtype) + hits = np.zeros(view.shape, dtype=np.int64) + for part in view.parts(): + assembled[part.out_selection] = np.asarray(part.view.result()) + np.add.at(hits, part.out_selection, 1) + + err = f"parts={parts}, {selection}" + np.testing.assert_array_equal(assembled, expected, err_msg=err) + np.testing.assert_array_equal(hits, np.ones(view.shape, dtype=np.int64), err_msg=err) + np.testing.assert_array_equal(np.asarray(view.result()), expected, err_msg=err) + + +def test_eager_getitem_returns_data(source: LazyArray) -> None: + """`arr[...]` reads immediately, like `numpy.ndarray.__getitem__`.""" + np.testing.assert_array_equal(np.asarray(source[1:3, ::2, -1]), reference()[1:3, ::2, -1]) + + +# --------------------------------------------------------------------------- +# Attribute forwarding +# --------------------------------------------------------------------------- + + +def test_forwards_array_attributes(source: LazyArray) -> None: + assert source.shape == SHAPE + assert source.ndim == len(SHAPE) + assert source.size == int(np.prod(SHAPE)) + assert source.dtype == np.dtype("int64") + assert len(source) == SHAPE[0] + assert "LazyArray" in repr(source) + + +def test_view_shape_comes_from_the_transform(source: LazyArray) -> None: + """A view reports its own shape, not the wrapped array's.""" + view = source.lazy[1:6:2, :, -1] + assert view.shape == (3, 5) + assert view.ndim == 2 + assert view.size == 15 + assert view.dtype == source.dtype + assert "view=" in repr(view) + + +def test_the_wrapper_has_no_chunks_vocabulary() -> None: + """`chunks` is the *source's* word, never the wrapper's.""" + assert not hasattr(make_source("numpy-whole"), "chunks") + assert not hasattr(make_source("zarr"), "chunks") + with pytest.raises(TypeError): + LazyArray(reference(), chunks=PART_SHAPE) # type: ignore[call-arg] + + +def test_scalar_is_basic_even_when_a_slice_separates_it_from_the_arrays() -> None: + """A documented, deliberate departure from one NumPy corner. + + NumPy counts an integer as an *advanced* index for its placement rule, so + `x[0, :, i]` has shape `(len(i), x.shape[1])` β€” the arrays lead because the + slice separates the integer from them. The positional dialect instead treats + every scalar as a basic index applied first, which is the rule the rest of + the surface follows and the only one `oindex` can express, so the same + selection reads as `x[0][:, i]`. + """ + data = reference() + view = make_source("numpy-uniform-parts").lazy.vindex[0, ..., np.array([3, 0])] + np.testing.assert_array_equal(np.asarray(view.result()), data[0][..., np.array([3, 0])]) + assert view.shape == data[0][..., np.array([3, 0])].shape + assert view.shape != data[0, ..., np.array([3, 0])].shape + + +def test_zero_dimensional_result_is_an_array(source: LazyArray) -> None: + """Both resolvers agree on the kind of a zero-rank result.""" + result = source.lazy[0, 1, 2].result() + assert isinstance(result, np.ndarray) + assert result.ndim == 0 + assert result[()] == reference()[0, 1, 2] + + +def test_construction_selects_readers_explicitly() -> None: + data = reference() + assert LazyArray(data).reader is basic_reader + assert LazyArray.from_numpy(data).reader is numpy_reader + + +def test_reader_wrappers_forward_the_read_contract_unchanged() -> None: + events: list[tuple[str, Any, ReadContext, Any]] = [] + + class RecordingDelegatingReader: + def __init__(self, name: str, inner: Reader) -> None: + self.name = name + self.inner = inner + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + events.append((self.name, source, context, out)) + self.inner.read_into(source, context, out) + + data = reference() + inner = RecordingDelegatingReader("inner", numpy_reader) + outer = RecordingDelegatingReader("outer", inner) + view = LazyArray(data).with_reader(outer).lazy[1:6:2, ::-1, 1].unpartitioned() + + result = view.result() + + assert [name for name, _, _, _ in events] == ["outer", "inner"] + outer_call, inner_call = events + assert outer_call[1] is inner_call[1] is data + assert outer_call[2] is inner_call[2] + assert outer_call[3] is inner_call[3] is result + np.testing.assert_array_equal(result, data[1:6:2, ::-1, 1]) + + +@pytest.mark.parametrize("value", [object(), [1, 2, 3], "array"]) +def test_from_numpy_rejects_non_ndarrays(value: Any) -> None: + with pytest.raises(TypeError, match="from_numpy requires a numpy.ndarray"): + LazyArray.from_numpy(value) + + +class RecordingReader: + def __init__(self) -> None: + self.calls: list[tuple[Any, ReadContext, Any]] = [] + self.contexts: list[ReadContext] = [] + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + self.calls.append((source, context, out)) + self.contexts.append(context) + basic_reader.read_into(source, context, out) + + +def test_view_operations_preserve_the_reader_without_reading() -> None: + data = reference() + reader = RecordingReader() + base = LazyArray(data).with_reader(reader) + views = ( + base.lazy[1:5], + base.with_parts((2, 2, 2)), + base.with_parts_per_axis(((3, 3, 1), (2, 3), (1, 3))), + base.unpartitioned(), + ) + assert reader.calls == [] + assert all(view.reader is reader for view in views) + assert all(part.view.reader is reader for part in views[1].parts()) + + +@pytest.mark.parametrize("value", [object(), None, lambda: None]) +def test_with_reader_requires_callable_read_into(value: Any) -> None: + with pytest.raises(TypeError, match="reader.read_into must be callable"): + LazyArray(reference()).with_reader(value) + + +class ReturningReader: + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> Any: + return np.empty(context.transform.domain.shape, dtype=source.dtype) + + +def test_result_rejects_a_reader_that_returns_a_value() -> None: + view = LazyArray(reference()).with_reader(ReturningReader()) + with pytest.raises(TypeError, match="must return None"): + view.result() + + +class BufferRecordingReader(RecordingReader): + def __init__(self) -> None: + super().__init__() + self.owns_data: list[bool] = [] + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + self.owns_data.append(bool(out.flags.owndata)) + super().read_into(source, context, out) + + +def test_reader_is_called_once_per_touched_part() -> None: + data = np.arange(48).reshape(6, 8) + reader = RecordingReader() + view = LazyArray(data).with_reader(reader).with_parts((3, 4)).lazy[1:5, 2] + np.testing.assert_array_equal(view.result(), data[1:5, 2]) + assert len(reader.calls) == len(tuple(view.parts())) == 2 + assert all( + call[1].transform.domain.inclusive_min == (0,) * call[1].transform.input_rank + for call in reader.calls + ) + + +def test_partition_reader_receives_global_transform_and_existing_projection() -> None: + reader = RecordingReader() + view = LazyArray(np.arange(8)).with_reader(reader).with_parts((4,)) + expected = [part.projection for part in view.parts()] + + np.testing.assert_array_equal(view.result(), np.arange(8)) + + assert [context.projection for context in reader.contexts] == expected + assert [context.transform.apply((0,)) for context in reader.contexts] == [(0,), (4,)] + + +def test_an_empty_result_does_not_call_the_reader() -> None: + reader = RecordingReader() + result = LazyArray(reference()).with_reader(reader).lazy[:, 0:0, :].result() + assert result.shape == (7, 0, 4) + assert reader.calls == [] + + +def test_rectangular_parts_write_into_result_views() -> None: + reader = BufferRecordingReader() + view = LazyArray(reference()).with_reader(reader).with_parts((2, 2, 2)).lazy[1:6, 1:4] + view.result() + assert reader.owns_data + assert not any(reader.owns_data) + + +def test_fancy_part_placement_uses_owned_dense_temporaries() -> None: + reader = BufferRecordingReader() + view = ( + LazyArray(reference()) + .with_reader(reader) + .with_parts((2, 2, 2)) + .lazy.oindex[[6, 1, 1], :, :] + ) + np.testing.assert_array_equal(view.result(), reference()[np.ix_([6, 1, 1], range(5), range(4))]) + assert any(reader.owns_data) + + +def test_reader_exception_propagates_unchanged() -> None: + error = RuntimeError("backend failed") + + class FailingReader: + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + raise error + + with pytest.raises(RuntimeError) as caught: + LazyArray(reference()).with_reader(FailingReader()).result() + assert caught.value is error + + +class ForeignArray: + """A minimal array-like whose advertised `chunks` we do not control.""" + + def __init__(self, data: np.ndarray[Any, Any], chunks: Any) -> None: + self._data = data + self.chunks = chunks + + @property + def shape(self) -> tuple[int, ...]: + return self._data.shape + + @property + def dtype(self) -> Any: + return self._data.dtype + + def __getitem__(self, key: Any) -> Any: + return self._data[key] + + +def test_malformed_discovered_parts_are_ignored() -> None: + """A foreign object's unusable `chunks` falls back to one whole-array part. + + Discovery parses external input, so an attribute that does not describe a + partitioning of the shape means "none I understand", not an error. + """ + data = reference() + for bogus in (((3, 3), (5,), (4,)), (3, 2), "nope", (3.5, 2, 2)): + wrapped = LazyArray(ForeignArray(data, bogus)) + assert len(list(wrapped.parts())) == 1 + np.testing.assert_array_equal(np.asarray(wrapped.lazy[1:3].result()), data[1:3]) + + +def test_discovered_parts_come_from_the_source_vocabulary() -> None: + """`read_chunk_sizes` wins over `chunks`, and both are read as parts.""" + data = reference() + wrapped = LazyArray(ForeignArray(data, PART_SHAPE)) + assert [part.base_coords for part in wrapped.parts()][:3] == [(0, 0, 0), (0, 0, 1), (0, 1, 0)] + assert len(list(wrapped.parts())) == 3 * 3 * 2 + + +# --------------------------------------------------------------------------- +# Boxes +# --------------------------------------------------------------------------- + +# (id, build, expected is_box, expected bounding_box). The bounds are storage +# intervals of the wrapped (7, 5, 4) array, computed by hand. +BOX_CASES: list[tuple[str, Callable[[LazyArray], LazyArray], bool, Any]] = [ + ("identity", lambda a: a, True, ((0, 7), (0, 5), (0, 4))), + ("basic-slice", lambda a: a.lazy[1:6, :, 1:3], True, ((1, 6), (0, 5), (1, 3))), + # Stride 2 over axis 1 touches 0, 2, 4; the hull is the closed span. + ("strided", lambda a: a.lazy[::3, ::2, :], True, ((0, 7), (0, 5), (0, 4))), + ("int-drop", lambda a: a.lazy[2, :, -1], True, ((2, 3), (0, 5), (3, 4))), + ("all-scalars", lambda a: a.lazy[0, 1, 2], True, ((0, 1), (1, 2), (2, 3))), + ("negative-and-open", lambda a: a.lazy[-2:], True, ((5, 7), (0, 5), (0, 4))), + ( + "oindex", + lambda a: a.lazy.oindex[[4, 0, 0], :, [3, 1]], + False, + ((0, 5), (0, 5), (1, 4)), + ), + ( + "vindex", + lambda a: a.lazy.vindex[np.array([0, 6, 3]), np.array([1, 4, 0]), np.array([2, 0, 1])], + False, + ((0, 7), (0, 5), (0, 3)), + ), + ("mask", lambda a: a.lazy.vindex[MASK], False, ((0, 7), (0, 5), (0, 4))), + # Composition preserves the category in both directions. + ("box-of-box", lambda a: a.lazy[1:6].lazy[:, 1:3], True, ((1, 6), (1, 3), (0, 4))), + ( + "box-after-fancy", + lambda a: a.lazy.oindex[[4, 0, 2], :, :].lazy[0:2], + False, + ((0, 5), (0, 5), (0, 4)), + ), + ("empty", lambda a: a.lazy[2:2], True, None), + ( + "empty-fancy", + lambda a: a.lazy.oindex[np.array([], dtype=np.intp), :, :], + False, + None, + ), +] + + +@pytest.mark.parametrize( + ("build", "expected_is_box", "expected_bounds"), + [case[1:] for case in BOX_CASES], + ids=[case[0] for case in BOX_CASES], +) +def test_is_box_and_bounding_box( + source: LazyArray, + build: Callable[[LazyArray], LazyArray], + expected_is_box: bool, + expected_bounds: Any, +) -> None: + """The box/query taxonomy, and the hull every selection has either way.""" + view = build(source) + assert view.is_box is expected_is_box + assert view.bounding_box() == expected_bounds + + +def test_a_unit_stride_box_is_dense_in_its_bounding_box() -> None: + """Stride 1 everywhere: the hull is exactly what the view selects.""" + data = reference() + view = make_source("numpy-uniform-parts").lazy[1:6, :, 1:3] + assert view.is_box + assert view.strides() == (1, 1, 1) + bounds = view.bounding_box() + assert bounds is not None + np.testing.assert_array_equal( + np.asarray(view.result()), + data[tuple(slice(lo, hi) for lo, hi in bounds)], + ) + + +def test_a_strided_box_is_sparse_in_its_bounding_box() -> None: + """Stride > 1: the hull is a superset, and `strides()` is what says by how much.""" + data = reference() + view = make_source("numpy-uniform-parts").lazy[1:6, ::2, :] + assert view.is_box + assert view.strides() == (1, 2, 1) + bounds = view.bounding_box() + assert bounds is not None + assert bounds == ((1, 6), (0, 5), (0, 4)) + + hull = data[tuple(slice(lo, hi) for lo, hi in bounds)] + assert hull.size == 5 * 5 * 4 + assert view.size == 5 * 3 * 4 + # A consumer that slabbed the hull and threw the rest away would over-read. + assert hull.size > view.size + # Applying the strides to the hull recovers the selection exactly. + np.testing.assert_array_equal( + np.asarray(view.result()), + hull[tuple(slice(None, None, step) for step in view.strides() or ())], + ) + + +def test_strides_are_none_for_a_query() -> None: + view = make_source("numpy-uniform-parts").lazy.oindex[[5, 1], :, :] + assert not view.is_box + assert view.strides() is None + + +def test_an_integer_indexed_dimension_has_stride_one() -> None: + view = make_source("numpy-uniform-parts").lazy[2, ::3, :] + assert view.strides() == (1, 3, 1) + assert view.bounding_box() == ((2, 3), (0, 4), (0, 4)) + + +def test_a_query_bounding_box_is_only_a_hull() -> None: + """For a fancy selection the box is a superset, and `is_box` says so.""" + view = make_source("numpy-uniform-parts").lazy.oindex[[5, 1], :, :] + assert not view.is_box + assert view.bounding_box() == ((1, 6), (0, 5), (0, 4)) + # The hull spans 5 rows; the selection touches 2 of them. + assert view.shape[0] == 2 + + +# --------------------------------------------------------------------------- +# Parts +# --------------------------------------------------------------------------- + + +class _ReadMustNotRun: + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + raise AssertionError("prepared-plan validation must happen before any read") + + +def test_prepared_part_validation_allocates_boolean_coverage_bitmap( + monkeypatch: pytest.MonkeyPatch, +) -> None: + view = LazyArray.from_numpy(reference()).with_parts(PART_SHAPE).lazy[1:6, ::2, 1:] + parts = tuple(view.parts()) + allocations: list[tuple[tuple[int, ...], np.dtype[Any]]] = [] + real_zeros = np.zeros + + def recording_zeros(shape: Any, *args: Any, **kwargs: Any) -> np.ndarray[Any, Any]: + result = real_zeros(shape, *args, **kwargs) + allocations.append((tuple(shape), result.dtype)) + return result + + monkeypatch.setattr(lazy_array_module.np, "zeros", recording_zeros) + + _validate_prepared_parts(parts, view.shape) + + assert allocations == [(view.shape, np.dtype(np.bool_))] + + +@pytest.mark.parametrize( + ("data", "part_shape", "build", "expected"), + [ + pytest.param( + np.arange(8), + (3,), + lambda array: array.lazy[1:7:2], + np.array([1, 3, 5]), + id="basic-reordered-parts", + ), + pytest.param( + np.arange(8), + (3,), + lambda array: array.lazy[3], + np.array(3), + id="scalar", + ), + pytest.param( + np.arange(20).reshape(4, 5), + (2, 3), + lambda array: array.lazy.oindex[[3, 1, 1], [4, 0]], + np.array([[19, 15], [9, 5], [9, 5]]), + id="orthogonal-fancy", + ), + pytest.param( + np.arange(20).reshape(4, 5), + (2, 3), + lambda array: array.lazy.vindex[[3, 1, 1], [4, 0, 4]], + np.array([19, 5, 9]), + id="correlated-fancy", + ), + pytest.param( + np.arange(8), + (3,), + lambda array: array.lazy[2:2], + np.array([], dtype=np.int64), + id="empty", + ), + ], +) +def test_result_accepts_prepared_parts_from_the_same_view( + monkeypatch: pytest.MonkeyPatch, + data: np.ndarray[Any, Any], + part_shape: tuple[int, ...], + build: Callable[[LazyArray], LazyArray], + expected: np.ndarray[Any, Any], +) -> None: + view = build(LazyArray.from_numpy(data).with_parts(part_shape)) + parts = tuple(reversed(tuple(view.parts()))) + + def unexpected_replan(self: LazyArray) -> Any: + raise AssertionError("result(parts=...) must not construct another partition plan") + + monkeypatch.setattr(LazyArray, "parts", unexpected_replan) + + np.testing.assert_array_equal(view.result(parts=parts), expected) + + +def test_result_rejects_prepared_parts_owned_by_another_view() -> None: + data = reference() + base = LazyArray.from_numpy(data).with_reader(_ReadMustNotRun()).with_parts(PART_SHAPE) + view = base.lazy[1:6, ::2, 1:] + owned_parts = tuple(view.parts()) + foreign_parts = tuple(base.lazy[1:6, ::2, 1:].parts()) + mixed_parts = (owned_parts[0], *foreign_parts[1:]) + + with pytest.raises(ValueError, match="prepared parts do not belong to this view"): + view.result(parts=mixed_parts) + + +def test_result_rejects_prepared_parts_that_do_not_tile_the_view() -> None: + data = reference() + view = ( + LazyArray.from_numpy(data) + .with_reader(_ReadMustNotRun()) + .with_parts(PART_SHAPE) + .lazy[1:6, ::2, 1:] + ) + parts = tuple(view.parts()) + + with pytest.raises(ValueError, match="prepared parts do not tile the view exactly"): + view.result(parts=parts[:-1]) + + +def test_result_rejects_prepared_parts_with_a_duplicate_and_omission() -> None: + view = LazyArray.from_numpy(np.arange(8)).with_reader(_ReadMustNotRun()).with_parts((4,)) + first, _second = tuple(view.parts()) + + with pytest.raises(ValueError, match="prepared parts do not tile the view exactly"): + view.result(parts=(first, first)) + + +def test_result_rejects_complete_prepared_parts_plus_a_duplicate() -> None: + view = LazyArray.from_numpy(np.arange(8)).with_reader(_ReadMustNotRun()).with_parts((4,)) + first, second = tuple(view.parts()) + + with pytest.raises(ValueError, match="prepared parts do not tile the view exactly"): + view.result(parts=(first, second, first)) + + +def test_result_rejects_overlapping_prepared_parts() -> None: + view = LazyArray.from_numpy(np.arange(8)).with_reader(_ReadMustNotRun()).with_parts((4,)) + first, second = tuple(view.parts()) + overlapping = replace(second, out_selection=(slice(2, 6),)) + + with pytest.raises(ValueError, match="prepared parts do not tile the view exactly"): + view.result(parts=(first, overlapping)) + + +def test_result_rejects_wrong_rank_prepared_parts() -> None: + view = LazyArray.from_numpy(np.arange(8)).with_reader(_ReadMustNotRun()).with_parts((4,)) + first, second = tuple(view.parts()) + wrong_rank = replace(first, out_selection=()) + + with pytest.raises(ValueError, match="prepared parts do not tile the view exactly"): + view.result(parts=(wrong_rank, second)) + + +def test_result_rejects_empty_prepared_parts_for_a_nonempty_view() -> None: + view = LazyArray.from_numpy(np.arange(8)).with_reader(_ReadMustNotRun()).with_parts((4,)) + + with pytest.raises(ValueError, match="prepared parts do not tile the view exactly"): + view.result(parts=()) + + +def test_result_accepts_empty_prepared_parts_for_an_empty_view() -> None: + view = ( + LazyArray.from_numpy(np.arange(8)).with_reader(_ReadMustNotRun()).with_parts((4,)).lazy[0:0] + ) + + np.testing.assert_array_equal(view.result(parts=()), np.array([], dtype=np.int64)) + + +@pytest.mark.parametrize("flavor", FLAVORS) +@pytest.mark.parametrize( + "build", + [ + lambda a: a, + lambda a: a.lazy[1:6, :, 1:], + lambda a: a.lazy.oindex[[4, 0, 0], :, [3, 1]], + lambda a: a.lazy.vindex[..., np.array([1, 4, 0]), np.array([2, 0, 1])], + # A reversing view drives the negative-stride branches of + # `_intersect_dimension_map` and chunk projection, which were + # written defensively long before anything could reach them. + lambda a: a.lazy[::-1, ::-2, :], + lambda a: a.lazy[5:1:-1, :, ::-1], + ], + ids=["identity", "basic", "oindex", "vindex", "reversed", "reversed-bounded"], +) +def test_parts_tile_the_view_exactly_and_disjointly( + flavor: str, build: Callable[[LazyArray], LazyArray] +) -> None: + """Assembling the parts reproduces `result()`; the placements cover with no overlap.""" + view = build(make_source(flavor)) + expected = np.asarray(view.result()) + + assembled = np.zeros(view.shape, dtype=view.dtype) + hits = np.zeros(view.shape, dtype=np.int64) + for part in view.parts(): + assembled[part.out_selection] = np.asarray(part.view.result()) + # `np.add.at` accumulates per element; `+= 1` on a fancy index would + # count a repeated position once and hide a real overlap. + np.add.at(hits, part.out_selection, 1) + + np.testing.assert_array_equal(assembled, expected) + np.testing.assert_array_equal(hits, np.ones(view.shape, dtype=np.int64)) + + +def _transform_point(transform: IndexTransform, point: tuple[int, ...]) -> tuple[int, ...]: + """Evaluate a transform pointwise for projection placement assertions.""" + result: list[int] = [] + for output_map in transform.output: + if isinstance(output_map, ConstantMap): + result.append(output_map.offset) + elif isinstance(output_map, DimensionMap): + result.append(output_map.offset + output_map.stride * point[output_map.input_dimension]) + else: + index = tuple( + 0 + if output_map.index_array.shape[axis] == 1 + else point[axis] - transform.domain.inclusive_min[axis] + for axis in range(output_map.index_array.ndim) + ) + result.append( + output_map.offset + output_map.stride * int(output_map.index_array[index]) + ) + return tuple(result) + + +@pytest.mark.parametrize( + "build", + [ + lambda array: array.lazy.oindex[[6, 0, 2], :, [3, 1]], + lambda array: array.lazy.vindex[..., np.array([4, 0, 4]), np.array([3, 1, 1])], + ], + ids=["orthogonal", "vectorized"], +) +def test_partition_exposes_projection_as_its_placement_authority( + build: Callable[[LazyArray], LazyArray], +) -> None: + """A part's NumPy placement addresses exactly its cell-transform range.""" + view = build(LazyArray(reference()).with_parts(PART_SHAPE)) + assembled = np.zeros(view.shape, dtype=view.dtype) + + for part in view.parts(): + projection = part.projection + assert isinstance(projection, ChunkProjection) + assert part.view.transform == projection.chunk_transform.translate( + tuple(lo for lo, _ in part.box) + ) + assert part.base_coords == projection.chunk_coords + assert part.box == tuple( + zip( + projection.chunk_domain.inclusive_min, + projection.chunk_domain.exclusive_max, + strict=True, + ) + ) + + expected_hits = np.zeros(view.shape, dtype=np.int8) + cell_domain = projection.cell_transform.domain + for positional_point in np.ndindex(*cell_domain.shape): + cell_point = tuple( + coordinate + origin + for coordinate, origin in zip( + positional_point, cell_domain.inclusive_min, strict=True + ) + ) + expected_hits[_transform_point(projection.cell_transform, cell_point)] = 1 + actual_hits = np.zeros(view.shape, dtype=np.int8) + actual_hits[part.out_selection] = 1 + np.testing.assert_array_equal(actual_hits, expected_hits) + + assembled[part.out_selection] = np.asarray(part.view.result()) + + np.testing.assert_array_equal(assembled, np.asarray(view.result())) + + +def test_nonfirst_partition_transform_directly_addresses_its_array() -> None: + source = np.arange(8) + part = list(LazyArray.from_numpy(source).with_parts((4,)).parts())[1] + + assert part.box == ((4, 8),) + assert part.view.transform.apply((0,)) == (4,) + assert part.view.array[part.view.transform.apply((0,))] == 4 + assert part.view.result()[0] == 4 + assert part.projection.chunk_transform.apply((0,)) == (0,) + + +def test_partition_token_encodes_its_public_global_transform() -> None: + source = np.arange(8) + base = LazyArray.from_numpy(source) + partition_view = list(base.with_parts((4,)).parts())[1].view + direct_view = base.lazy[4:8] + + assert partition_view.__dask_tokenize__() == direct_view.__dask_tokenize__() + + +def test_parts_resolve_independently_and_concurrently() -> None: + """Each part's `array` is a standalone `LazyArray` with no shared mutable state.""" + view = make_source("zarr").lazy[1:7, :, 1:].with_parts((2, 2, 2)) + parts = list(view.parts()) + assert len(parts) > 1 + + with ThreadPoolExecutor(max_workers=4) as pool: + values = list(pool.map(lambda part: np.asarray(part.view.result()), parts)) + + assembled = np.zeros(view.shape, dtype=view.dtype) + for part, value in zip(parts, values, strict=True): + assembled[part.out_selection] = value + np.testing.assert_array_equal(assembled, np.asarray(view.result())) + + +def test_parts_report_completeness() -> None: + """`is_complete` distinguishes a fully-covered box from a partial one.""" + array = make_source("numpy-uniform-parts") + assert all(part.is_complete for part in array.parts()) + # Boxes along axis 2 are [0, 3) and [3, 4); dropping column 0 leaves the + # first partially covered and the second whole. + trimmed = {part.base_coords[2]: part.is_complete for part in array.lazy[:, :, 1:].parts()} + assert trimmed == {0: False, 1: True} + # A fancy axis is always reported incomplete. + assert not any(part.is_complete for part in array.lazy.oindex[[4, 0, 0], :, :].parts()) + + +def test_partition_boxes_are_global_and_tile_the_base() -> None: + """Both the selected hull and the whole partition box use global coordinates.""" + view = make_source("numpy-uniform-parts").lazy[1:6, :, 1:] + parts = {part.base_coords: part for part in view.parts()} + + # The reviewer's repro: two parts of the same view now expose distinct + # source-global selected hulls as well as distinct whole partition boxes. + first, second = parts[0, 0, 0], parts[0, 1, 0] + assert first.view.bounding_box() == ((1, 3), (0, 2), (1, 3)) + assert second.view.bounding_box() == ((1, 3), (2, 4), (1, 3)) + assert first.box != second.box + assert first.box == ((0, 3), (0, 2), (0, 3)) + assert second.box == ((0, 3), (2, 4), (0, 3)) + + # Every box is the base partitioning's own box for those coordinates, and + # the touched boxes tile the region the view reads without overlapping. + grids = dimension_grids_from_chunks(PART_SHAPE, SHAPE) + for coords, part in parts.items(): + expected = tuple( + (grid.chunk_offset(c), grid.chunk_offset(c) + grid.data_size(c)) + for grid, c in zip(grids, coords, strict=True) + ) + assert part.box == expected + covered = np.zeros(SHAPE, dtype=np.int64) + for part in parts.values(): + covered[tuple(slice(lo, hi) for lo, hi in part.box)] += 1 + assert covered.max() == 1 + # The view reads rows 1..5 and columns 1.., so every box it touches + # intersects that region and no box outside it is visited. + assert covered[1:6, :, 1:].sum() > 0 + assert covered[6:, :, :].sum() == 0 + + +def test_partition_box_of_a_whole_array_part() -> None: + part = next(iter(make_source("numpy-whole").parts())) + assert part.box == tuple((0, extent) for extent in SHAPE) + + +def test_an_unpartitioned_wrapper_has_a_single_whole_array_part() -> None: + view = make_source("numpy-whole") + parts = list(view.parts()) + assert len(parts) == 1 + assert parts[0].base_coords == (0, 0, 0) + assert parts[0].view.shape == SHAPE + assert parts[0].is_complete + np.testing.assert_array_equal(np.asarray(parts[0].view.result()), reference()) + + +def test_with_parts_keeps_the_view_and_the_base() -> None: + view = make_source("zarr").lazy[1:6, ::2] + repartitioned = view.with_parts((2, 1, 4)) + assert repartitioned.shape == view.shape + assert repartitioned.array is view.array + assert repartitioned.transform == view.transform + # A different partitioning really is a different set of boxes. + assert [part.base_coords for part in repartitioned.parts()] != [ + part.base_coords for part in view.parts() + ] + np.testing.assert_array_equal(np.asarray(repartitioned.result()), np.asarray(view.result())) + + +def test_with_parts_none_forces_one_shot_resolution() -> None: + view = make_source("zarr").lazy.oindex[[4, 0, 0], :, :] + whole = view.unpartitioned() + assert len(list(whole.parts())) == 1 + np.testing.assert_array_equal(np.asarray(whole.result()), np.asarray(view.result())) + + +@pytest.mark.parametrize( + ("parts", "match"), + [ + ((3,), "one entry per dimension"), + ((3, (2, 2), 4), "not a mixture"), + (((3, 3), (2, 2, 1), (3, 1)), "sum to 6, but the array extent is 7"), + ((3, 0, 3), "chunk shape entries must be positive"), + # A float or a None belongs to neither convention; saying "not a + # mixture" would send the reader looking for the wrong mistake. + ((3.5, 2, 2), r"3\.5 at dimension 0 is neither"), + ((None, 5, 4), "None at dimension 0 is neither"), + ((3.5, 2.5, 2.5), r"3\.5 at dimension 0, 2\.5 at dimension 1, .* are neither"), + (((1.5, 5.5), (5,), (4,)), "per-axis chunk sizes must be integers; dimension 0"), + ], +) +def test_with_parts_validates_strictly(parts: Any, match: str) -> None: + """`with_parts` is our own API, so a malformed partitioning raises.""" + with pytest.raises(ValueError, match=match): + repartition(make_source("numpy-whole"), parts) + + +# --------------------------------------------------------------------------- +# Protocols +# --------------------------------------------------------------------------- + + +def test_dask_token_is_deterministic_and_discriminating() -> None: + """Same data and same view token alike; a different selection differs.""" + data = reference() + base = LazyArray(data) + assert base.__dask_tokenize__() == LazyArray(reference()).__dask_tokenize__() + + tokens = { + "base": base.__dask_tokenize__(), + "view": base.lazy[1:3].__dask_tokenize__(), + "other view": base.lazy[2:4].__dask_tokenize__(), + "other data": LazyArray(data + 1).__dask_tokenize__(), + } + assert len({repr(token) for token in tokens.values()}) == len(tokens) + # Equivalent transforms reached different ways still token alike. + assert base.lazy[1:5].lazy[0:2].__dask_tokenize__() == base.lazy[1:3].__dask_tokenize__() + + +def test_reader_and_partitioning_do_not_change_dask_identity() -> None: + base = LazyArray(reference()) + token = base.__dask_tokenize__() + assert base.with_reader(numpy_reader).__dask_tokenize__() == token + assert base.with_reader(basic_reader).__dask_tokenize__() == token + assert base.with_parts((2, 2, 2)).__dask_tokenize__() == token + + +@pytest.mark.parametrize("reader", [basic_reader, numpy_reader, DelegatingReader(numpy_reader)]) +def test_reader_survives_pickle(reader: Reader) -> None: + view = LazyArray(reference()).with_reader(reader).lazy[1:5, ::2] + restored = pickle.loads(pickle.dumps(view)) + assert type(restored.reader) is type(reader) + np.testing.assert_array_equal(restored.result(), view.result()) + + +def test_iteration_yields_eager_slices(source: LazyArray) -> None: + rows = list(source.lazy[2:5]) + assert len(rows) == 3 + for row, expected in zip(rows, reference()[2:5], strict=True): + np.testing.assert_array_equal(np.asarray(row), expected) + + +def test_iteration_over_a_zero_dimensional_view_is_rejected() -> None: + with pytest.raises(TypeError, match="iteration over a 0-d array"): + iter(make_source("numpy-uniform-parts").lazy[0, 0, 0]) + + +def test_len_of_a_zero_dimensional_view_is_rejected() -> None: + with pytest.raises(TypeError, match="len\\(\\) of unsized object"): + len(make_source("numpy-uniform-parts").lazy[0, 0, 0]) + + +@pytest.mark.parametrize( + ("convert", "selection"), + [ + (bool, (1, 1, 1)), + (int, (1, 1, 1)), + (float, (1, 1, 1)), + (operator.index, (1, 1, 1)), + (bool, (1, 1, slice(0, 1))), + ], + ids=["bool-0d", "int-0d", "float-0d", "index-0d", "bool-size-1"], +) +def test_scalar_conversions_match_numpy(convert: Any, selection: Any) -> None: + """Size-1 conversions delegate to NumPy, values and all.""" + data = reference() + view = make_source("numpy-uniform-parts").lazy[selection] + assert convert(view) == convert(data[selection]) + + +@pytest.mark.parametrize( + ("convert", "selection", "error"), + [ + (bool, (slice(0, 2), 0, 0), ValueError), + (bool, (slice(0, 0), 0, 0), ValueError), + (int, (slice(0, 1), 0, 0), TypeError), + (float, (slice(0, 2), 0, 0), TypeError), + (operator.index, (slice(0, 1), 0, 0), TypeError), + ], + ids=["bool-many", "bool-empty", "int-1d", "float-many", "index-1d"], +) +def test_scalar_conversions_raise_what_numpy_raises( + convert: Any, selection: Any, error: type[Exception] +) -> None: + data = reference() + view = make_source("numpy-uniform-parts").lazy[selection] + with pytest.raises(error): + convert(view) + with pytest.raises(error): + convert(data[selection]) + + +def test_pickle_round_trip() -> None: + """A wrapper over a picklable base survives a round trip, view and parts intact.""" + view = LazyArray(reference()).with_parts((2, 2, 2)).lazy[1:6, ::2].lazy.oindex[[3, 0, 0], :, :] + restored = pickle.loads(pickle.dumps(view)) + assert restored.shape == view.shape + assert restored.__dask_tokenize__() == view.__dask_tokenize__() + np.testing.assert_array_equal(np.asarray(restored.result()), np.asarray(view.result())) + + +# --------------------------------------------------------------------------- +# dask interop +# --------------------------------------------------------------------------- + + +def test_dask_from_array_roundtrip() -> None: + """A `LazyArray` is a drop-in dask source β€” no translation ceremony.""" + da = pytest.importorskip("dask.array") + source = make_source("zarr") + + lazy = da.from_array(source) + np.testing.assert_array_equal(lazy.compute(), reference()) + + # dask chooses its own blocks; the wrapper reads each of them through its + # own parts, so the two partitionings need not agree. + blocked = da.from_array(source, chunks=(4, 3, 3)) + assert blocked.chunks == ((4, 3), (3, 2), (3, 1)) + np.testing.assert_array_equal(blocked[2:, ::2].compute(), reference()[2:, ::2]) + + +# --------------------------------------------------------------------------- +# Errors +# --------------------------------------------------------------------------- + + +def test_boolean_scalar_is_rejected() -> None: + with pytest.raises(IndexError, match="boolean scalars are not valid indices"): + make_source("numpy-uniform-parts").lazy[True] + + +@pytest.mark.parametrize( + ("mode", "selection", "expected"), + [ + pytest.param("basic", IndexLike(2), np.array(2), id="basic-scalar"), + pytest.param( + "basic", + slice(IndexLike(1), IndexLike(7), IndexLike(2)), + np.array([1, 3, 5]), + id="basic-slice-components", + ), + pytest.param("orthogonal", IndexLike(2), np.array(2), id="orthogonal-scalar"), + pytest.param("vectorized", IndexLike(2), np.array(2), id="vectorized-scalar"), + ], +) +def test_positional_selectors_support_the_index_protocol( + mode: str, selection: Any, expected: np.ndarray[Any, Any] +) -> None: + source = LazyArray.from_numpy(np.arange(8)) + if mode == "basic": + view = source.lazy[selection] + else: + view = getattr(source.lazy, "oindex" if mode == "orthogonal" else "vindex")[selection] + + result = np.asarray(view.result()) + assert result.shape == expected.shape + np.testing.assert_array_equal(result, expected) + + +def test_positional_selector_rejects_int_only_objects() -> None: + with pytest.raises(IndexError, match="unsupported selection type"): + LazyArray.from_numpy(np.arange(8)).lazy[IntOnly()] + + +def test_positional_selector_propagates_malformed_index_protocol() -> None: + with pytest.raises(TypeError, match="__index__ returned non-int"): + LazyArray.from_numpy(np.arange(8)).lazy[BadIndex()] + + +def test_positional_slice_propagates_malformed_index_protocol() -> None: + with pytest.raises(TypeError, match="__index__ returned non-int"): + LazyArray.from_numpy(np.arange(8)).lazy[:: BadIndex()] + + +def test_protocol_objects_inside_an_index_array_remain_invalid() -> None: + selection = np.array([IndexLike(2)], dtype=object) + with pytest.raises(IndexError, match="integer or boolean"): + LazyArray.from_numpy(np.arange(8)).lazy.oindex[selection] + + +def test_mask_shape_must_match_the_view() -> None: + array = make_source("numpy-uniform-parts") + with pytest.raises(IndexError, match="boolean index has shape"): + array.lazy.vindex[np.ones((2, 2, 2), dtype=bool)] + + +def test_scalar_index_out_of_bounds() -> None: + with pytest.raises(IndexError, match="index 7 is out of bounds for axis 0 with size 7"): + make_source("numpy-uniform-parts").lazy[7] + + +def test_scalar_index_out_of_bounds_in_a_view() -> None: + """Bounds are the *view's*, not the wrapped array's.""" + array = make_source("numpy-uniform-parts").lazy[1:4] + with pytest.raises(IndexError, match="index 3 is out of bounds for axis 0 with size 3"): + array.lazy[3] + + +def test_index_array_out_of_bounds() -> None: + array = make_source("numpy-uniform-parts") + with pytest.raises(IndexError, match="index 99 is out of bounds for axis 0 with size 7"): + array.lazy.oindex[[0, 99], :, :] + + +def test_too_many_indices() -> None: + with pytest.raises(IndexError, match="too many indices"): + make_source("numpy-uniform-parts").lazy[0, 0, 0, 0] + + +def test_copy_false_conversion_is_rejected() -> None: + array = make_source("numpy-uniform-parts") + with pytest.raises(ValueError, match="cannot be converted to a NumPy array without a copy"): + np.array(array, copy=False) + + +# --------------------------------------------------------------------------- +# Negative steps +# --------------------------------------------------------------------------- + + +def test_reversed_box_reports_a_positive_stride(source: LazyArray) -> None: + """A reversal is still a box; `strides()` is magnitudes, so it matches the forward twin.""" + reversed_view = source.lazy[::-2] + forward = source.lazy[::2] + assert reversed_view.is_box + assert reversed_view.strides() == forward.strides() == (2, 1, 1) + assert reversed_view.bounding_box() == ((0, 7), (0, 5), (0, 4)) + + +def test_a_reversed_view_is_re_based_to_origin_zero() -> None: + """The literal domain of a reversal is negative; the positional dialect hides it.""" + view = make_source("numpy-whole").lazy[::-1] + # The algebra's own answer keeps the source frame. + assert IndexTransform.from_shape(SHAPE)[::-1].domain.inclusive_min[0] == -6 + # The wrapper re-bases, so positions start at 0 as NumPy expects. + assert view.transform.domain.inclusive_min == (0, 0, 0) + assert view.shape == SHAPE + np.testing.assert_array_equal(np.asarray(view.result()), reference()[::-1]) + + +def test_zero_step_is_rejected() -> None: + with pytest.raises(ValueError, match="step cannot be zero"): + make_source("numpy-whole").lazy[::0] + + +def test_reversed_positional_interval_is_empty_not_an_error() -> None: + """NumPy's rule at the boundary; the literal layer keeps TensorStore's.""" + view = make_source("numpy-uniform-parts").lazy[2:5:-1] + assert view.shape == (0, 5, 4) + np.testing.assert_array_equal(np.asarray(view.result()), reference()[2:5:-1]) + # Literal coordinates, on the other hand, call it a direction error. + with pytest.raises(IndexError, match="valid interval"): + IndexTransform.from_shape(SHAPE)[2:5:-1] + + +def test_negative_step_over_a_fancy_axis_reverses_the_coordinates(source: LazyArray) -> None: + """Reversing a gathered axis materializes, rather than attaching a stride.""" + view = source.lazy.oindex[[3, 1, 2], :, :].lazy[::-1] + expected = outer(reference(), ([3, 1, 2], slice(None), slice(None)))[::-1] + np.testing.assert_array_equal(np.asarray(view.result()), expected) + m = view.transform.output[0] + assert isinstance(m, ArrayMap) + np.testing.assert_array_equal(m.index_array.reshape(-1), np.array([2, 1, 3])) + + +# --------------------------------------------------------------------------- +# Minimal sources +# --------------------------------------------------------------------------- + + +class MinimalSource: + """The floor of the wrapped-array protocol: `shape`, `dtype`, `__getitem__`.""" + + def __init__(self, data: np.ndarray[Any, Any]) -> None: + self._data = data + + @property + def shape(self) -> tuple[int, ...]: + return self._data.shape + + @property + def dtype(self) -> Any: + return self._data.dtype + + def __getitem__(self, key: Any) -> Any: + return self._data[key] + + +class RecordingSource(MinimalSource): + """A minimal source that records every attempted data read.""" + + def __init__(self, data: np.ndarray[Any, Any]) -> None: + super().__init__(data) + self.reads: list[Any] = [] + + def __getitem__(self, key: Any) -> Any: + self.reads.append(key) + return super().__getitem__(key) + + +@pytest.mark.parametrize( + "build", + [ + lambda a: a.lazy[:, 2:2, :], + lambda a: a.lazy.vindex[np.array([[6], [3], [0]]), -4].lazy[0, 0:0], + ], + ids=["ordinary", "unreferenced-axis"], +) +def test_an_empty_view_does_not_read_its_source( + build: Callable[[LazyArray], LazyArray], +) -> None: + source = RecordingSource(reference()) + result = build(LazyArray(source)).result() + + assert result.size == 0 + assert source.reads == [] + + +# --------------------------------------------------------------------------- +# Materializing +# --------------------------------------------------------------------------- + + +class NumpyBackedSource: + """A duck array that stores its data in NumPy and returns views from reads. + + Not an `np.ndarray`, so nothing about the source can be compared against the + result's memory β€” but its blocks are NumPy views of storage the caller must + not be handed. The `BASIC` source this package invites people to wrap. + """ + + def __init__(self, data: np.ndarray[Any, Any]) -> None: + self.data = data + + @property + def shape(self) -> tuple[int, ...]: + return self.data.shape + + @property + def dtype(self) -> Any: + return self.data.dtype + + def __getitem__(self, selection: Any) -> Any: + return self.data[selection] + + +@pytest.mark.parametrize("parts", [None, (2, 2, 2), SHAPE]) +@pytest.mark.parametrize("wrap", [lambda d: d, NumpyBackedSource], ids=["ndarray", "duck"]) +@pytest.mark.parametrize( + ("build", "description"), + [ + (lambda a: a.lazy[1:3, :, :], "a basic slice"), + (lambda a: a.lazy[:, :, :], "the whole array"), + (lambda a: a.lazy[::-1, :, :], "a reversal"), + (lambda a: a.lazy.oindex[[2, 0], :, :], "a gather"), + ], +) +def test_materializing_never_hands_back_the_wrapped_array( + parts: Any, + wrap: Callable[[np.ndarray[Any, Any]], Any], + build: Callable[[LazyArray], LazyArray], + description: str, +) -> None: + """Writing to a materialized result must never reach the source. + + An unpartitioned read of a basic selection can be answered with a *view* of + the wrapped array, and NumPy 2 hands whatever `__array__` returns straight to + the caller. Every route out of the wrapper detaches, so the answer does not + depend on how the read happened to be divided. + + Run over both a raw `ndarray` and a duck array that merely stores its data in + NumPy: the second is the case where the source cannot be compared against the + result, so detaching has to decide from the result's own buffer instead. + """ + data = reference() + view = build(repartition(LazyArray(wrap(data)), parts)) + + for materialize in ( + lambda v: v.result(), + lambda v: np.array(v, copy=True), + lambda v: np.asarray(v), + lambda v: np.array(v), + ): + before = data.copy() + materialized = np.asarray(materialize(view)) + assert not np.shares_memory(materialized, data), description + materialized[...] = -1 + np.testing.assert_array_equal(data, before, err_msg=description) + + +def test_an_eager_getitem_never_hands_back_the_wrapped_array() -> None: + data = reference() + block = LazyArray(data)[1:3] + block[...] = -1 + np.testing.assert_array_equal(data, reference()) + + +def test_result_refuses_to_return_a_partly_written_buffer( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A partition walk that leaves a gap must raise, not return process memory. + + `result()` scatters into an uninitialized buffer, which is only safe because + the parts tile the view. This is the guard that turns any future break of + that contract into a failure instead of into plausible-looking numbers. + """ + view = LazyArray(reference()).with_parts(PART_SHAPE).lazy[:, 1:, :] + complete = LazyArray.parts + + def drop_one(self: LazyArray) -> Any: + return list(complete(self))[:-1] + + monkeypatch.setattr(LazyArray, "parts", drop_one) + with pytest.raises(AssertionError, match="partition walk addressed"): + view.result() + + +def test_result_refuses_a_partition_of_the_wrong_rank(monkeypatch: pytest.MonkeyPatch) -> None: + """A part addressing fewer axes than the view has is caught by name.""" + view = LazyArray(reference()).with_parts(PART_SHAPE).lazy[:, 1:, :] + complete = LazyArray.parts + + def truncate(self: LazyArray) -> Any: + return [replace(part, out_selection=part.out_selection[:-1]) for part in complete(self)] + + monkeypatch.setattr(LazyArray, "parts", truncate) + with pytest.raises(AssertionError, match="of the view's 3 dimensions"): + view.result() + + +class DuckBlock: + """An array-like meeting exactly the documented `BASIC` floor and no more. + + `shape`, `dtype`, and a `__getitem__` that understands integers and slices. + Anything else β€” an integer array, `take`, `reshape` β€” raises, and indexing it + yields another one of itself, so a block that comes back from it is as + limited as the source was. + """ + + def __init__(self, data: np.ndarray[Any, Any]) -> None: + self._data = data + + @property + def shape(self) -> tuple[int, ...]: + return self._data.shape + + @property + def dtype(self) -> Any: + return self._data.dtype + + def __array__(self, dtype: Any = None, copy: bool | None = None) -> Any: + return np.array(self._data, dtype=dtype, copy=True if copy is None else copy) + + def __getitem__(self, key: Any) -> DuckBlock: + selectors = key if isinstance(key, tuple) else (key,) + for selector in selectors: + if not isinstance(selector, (int, np.integer, slice)): + raise TypeError(f"basic indexing only, got {selector!r}") + return DuckBlock(self._data[key]) + + +@pytest.mark.parametrize( + ("build", "oracle"), + [ + (lambda a: a.lazy[1:5, ::2, :], lambda r: r[1:5, ::2, :]), + ( + lambda a: a.lazy.oindex[[4, 0, 0], :, :], + lambda r: r[np.ix_([4, 0, 0], range(5), range(4))], + ), + (lambda a: a.lazy.vindex[[4, 0], [1, 1]], lambda r: r[[4, 0], [1, 1]]), + (lambda a: a.lazy[::-1, :, :], lambda r: r[::-1, :, :]), + ], + ids=["basic", "oindex", "vindex", "reversal"], +) +@pytest.mark.parametrize("parts", [None, PART_SHAPE]) +def test_a_source_meeting_only_the_basic_floor_resolves_any_selection( + build: Callable[[LazyArray], LazyArray], oracle: Callable[[Any], Any], parts: Any +) -> None: + """The floor is a promise about the source; its blocks are coerced, not trusted.""" + expected = np.asarray(oracle(reference())) + view = build(repartition(LazyArray(DuckBlock(reference())), parts)) + assert view.shape == expected.shape + np.testing.assert_array_equal(np.asarray(view.result()), expected) + + +def test_the_duck_block_double_refuses_a_fancy_key() -> None: + """A negative control: the floor test only means something if the double bites.""" + with pytest.raises(TypeError, match="basic indexing only"): + DuckBlock(reference())[np.array([1, 0])] + + +# --------------------------------------------------------------------------- +# Sources with their own opinions +# --------------------------------------------------------------------------- + + +@pytest.mark.filterwarnings("ignore::PendingDeprecationWarning") +def test_numpy_matrix_is_refused() -> None: + """`np.matrix` never reduces rank, so a view's shape could not be honored.""" + with pytest.raises(TypeError, match="numpy.matrix cannot be wrapped"): + LazyArray(np.matrix(np.arange(12).reshape(3, 4))) + + +@pytest.mark.parametrize("parts", [None, (2, 2), (1, 4), (3, 4)]) +def test_a_masked_source_keeps_its_mask_under_every_partitioning(parts: Any) -> None: + data = np.ma.masked_greater(np.arange(12).reshape(3, 4), 7) + got = repartition(LazyArray(data), parts).lazy[:, 1:].result() + expected = data[:, 1:] + assert isinstance(got, np.ma.MaskedArray), parts + np.testing.assert_array_equal(np.ma.getmaskarray(got), np.ma.getmaskarray(expected)) + np.testing.assert_array_equal(np.ma.filled(got, 0), np.ma.filled(expected, 0)) + + +@pytest.mark.parametrize("parts", [None, (2, 2), (3, 4)]) +def test_a_masked_source_keeps_its_mask_when_the_view_is_empty(parts: Any) -> None: + """An empty result is still a result, and its type must not depend on the parts. + + An empty view is answered without reading the source at all, and that + shortcut reached for the array namespace's own `empty` β€” which knows nothing + about masks β€” so an unpartitioned empty view came back a plain array while + the same view partitioned came back masked. No cells either way, so nothing + about the values changed; the caller just got a different type depending on + how the read had been divided. + """ + data = np.ma.masked_greater(np.arange(12).reshape(3, 4), 7) + got = repartition(LazyArray(data), parts).lazy[:, 2:2].result() + assert isinstance(got, np.ma.MaskedArray), parts + assert np.asarray(got).shape == (3, 0), parts + + +def test_a_large_array_without_dask_refuses_to_claim_equality( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Above the digest limit the fallback must miss a cache rather than lie. + + Two arrays differing in one element used to token identically, because the + fallback described the shape and dtype and gave up on the contents. + """ + import sys + + monkeypatch.setitem(sys.modules, "dask.base", None) + big = np.zeros(1 << 19, dtype=np.int64) + other = big.copy() + other[0] = 1 + + assert LazyArray(big).__dask_tokenize__() != LazyArray(other).__dask_tokenize__() + assert LazyArray(big).__dask_tokenize__() != LazyArray(big).__dask_tokenize__() + + # Below the limit the contents are digested, so equal data still tokens alike. + small = np.zeros(8, dtype=np.int64) + assert LazyArray(small).__dask_tokenize__() == LazyArray(small.copy()).__dask_tokenize__() + + +# --------------------------------------------------------------------------- +# Completeness and partition spellings +# --------------------------------------------------------------------------- + + +def test_a_reversing_view_covers_its_parts() -> None: + """A reversal reads every cell of every box, back to front.""" + data = np.arange(48).reshape(8, 6) + forward = LazyArray(data).with_parts((2, 2)).lazy[:, :] + reversed_view = LazyArray(data).with_parts((2, 2)).lazy[::-1, ::-1] + assert [part.is_complete for part in reversed_view.parts()] == [ + part.is_complete for part in forward.parts() + ] + assert all(part.is_complete for part in reversed_view.parts()) + + +def test_a_strided_reversal_is_still_incomplete() -> None: + data = np.arange(48).reshape(8, 6) + view = LazyArray(data).with_parts((2, 2)).lazy[::-2, :] + assert not any(part.is_complete for part in view.parts()) + + +@pytest.mark.parametrize("parts", [((0,), (3,)), ((), (3,)), (1, 1), ((0, 0), (3,))]) +def test_a_zero_length_axis_accepts_every_spelling_of_no_chunks(parts: Any) -> None: + """`(0,)`, `(0, 0)`, `()` and a uniform shape all describe an axis with no cells.""" + data = np.zeros((0, 3)) + view = repartition(LazyArray(data), parts) + assert view.result().shape == (0, 3) + assert list(view.parts()) == [] + + +def test_a_zero_chunk_on_a_nonempty_axis_is_still_rejected() -> None: + with pytest.raises(ValueError, match="chunk sizes must be positive"): + LazyArray(np.zeros((4, 3))).with_parts_per_axis(((0, 4), (3,))) + + +@pytest.mark.parametrize( + "selection", + [ + (slice(None, None, -1), slice(None), slice(None)), + (slice(3, 1, -1), slice(None), slice(None)), + (slice(None, None, -2), slice(None, None, -1), slice(None)), + ], + ids=["reversed", "reversed-partial", "reversed-strided"], +) +def test_the_coverage_count_agrees_with_numpy_for_reversed_selections( + selection: tuple[Any, ...], +) -> None: + """The safety net behind `result()`'s coverage assertion, checked on its own. + + `_out_selection_cell_count` sizes a partition's `out_selection` without + materializing it, and `result()` trusts that count to decide whether the + walk covered the view. Nothing pinned it for a reversed slice, so dropping + its `start <= stop` guard β€” or wrapping the subtraction in `abs()` β€” left + the suite green. A net nobody tests only matters once something else breaks, + which is exactly when it needs to be right. + """ + data = reference() + view = LazyArray(data).with_parts((2, 2, 2)).lazy[selection] + out_shape = view.shape + for part in view.parts(): + counted = _out_selection_cell_count(part.out_selection, out_shape) + assert counted == np.empty(out_shape)[part.out_selection].size + + +@pytest.mark.parametrize( + ("selection", "out_shape", "expected"), + [ + (((slice(2, 5)),), (10,), 3), + # A backwards interval selects nothing. The fast path subtracts, which + # would make this negative and let an incomplete walk sum to the view's + # own size β€” so the count falls back to `range` whenever the interval is + # not a forward, in-bounds one. + (((slice(5, 2)),), (10,), 0), + # Counts from the end, to index 8 β€” past the stop, so nothing. + (((slice(-2, 5)),), (10,), 0), + ((slice(5, 2), slice(0, 3)), (10, 10), 0), + ], + ids=["forward", "backwards", "negative-start", "backwards-in-a-pair"], +) +def test_the_coverage_count_matches_numpy_for_intervals_the_fast_path_declines( + selection: tuple[Any, ...], out_shape: tuple[int, ...], expected: int +) -> None: + """The guard on `result()`'s safety net, exercised where the walk cannot reach it. + + A partition walk only ever produces concrete forward in-bounds intervals, so + the guard that keeps everything else off the subtraction fast path is not + reachable through `parts()` at all β€” which is why removing it left the whole + suite green. It is the net's own contract, so it is checked directly. + """ + counted = _out_selection_cell_count(selection, out_shape) + assert counted == np.empty(out_shape)[selection].size + assert counted == expected + + +def test_a_zero_dimensional_index_array_drops_its_axis_like_a_scalar() -> None: + """`a[np.array(2), :]` is `a[2, :]` in NumPy, and now here too. + + Only Python and NumPy integers counted as scalars, so a 0-d array fell + through to the fancy path and was widened into a length-1 index array β€” + keeping an axis NumPy drops. That was a third answer, agreeing with neither + NumPy nor eager zarr, which rejects it. + """ + data = np.arange(20).reshape(4, 5) + for mode, expected in ( + ("oindex", data[np.array(2), :]), + ("vindex", data[np.array(2), np.array(3)]), + ): + view = ( + LazyArray(data).lazy.oindex[np.array(2), slice(None)] + if mode == "oindex" + else LazyArray(data).lazy.vindex[np.array(2), np.array(3)] + ) + assert view.shape == expected.shape, mode + np.testing.assert_array_equal(np.asarray(view.result()), expected, err_msg=mode) + + +def test_a_multidimensional_array_in_an_orthogonal_selection_is_refused() -> None: + """The rule belongs to the selection, so the message speaks its vocabulary. + + Left to the engine, this surfaced as a rank complaint about an `index_array` + the caller never wrote β€” the transform layer's words for a mistake made two + layers above it. + """ + with pytest.raises(IndexError, match="must be 1-dimensional"): + LazyArray(np.arange(20).reshape(4, 5)).lazy.oindex[[[0, 1], [2, 3]], slice(None)] + + +def test_with_parts_rejects_a_bare_integer() -> None: + """Both partitioning methods document ValueError for malformed input.""" + view = LazyArray.from_numpy(np.arange(12).reshape(3, 4)) + with pytest.raises(ValueError, match="one entry per dimension"): + view.with_parts(3) # type: ignore[arg-type] + with pytest.raises(ValueError, match="one entry per dimension"): + view.with_parts_per_axis(3) # type: ignore[arg-type] + + +def test_fancy_composition_over_an_empty_axis() -> None: + """Regression: composing fancy steps over an empty axis stays unpinned. + + The empty-domain branch of `compose` produces index arrays that are + singleton on every non-empty axis; pinning one to an axis it merely + broadcasts along made a later basic step index a size-1 axis positionally + and raise, deep inside a legal chain. + """ + base = np.empty((3, 0, 6), dtype=np.int64) + view = LazyArray(base).lazy.oindex[[2, 1], :, [5, 0, 3]] + assert view.shape == (2, 0, 3) + composed = view.lazy.oindex[[1, 0], :, [2, 2]] + assert composed.shape == (2, 0, 2) + scalar = composed.lazy.vindex[..., np.array(1)] + assert scalar.shape == (2, 0) + assert np.asarray(scalar.result()).shape == (2, 0) diff --git a/packages/zarr-indexing/tests/test_lazy_array_stateful.py b/packages/zarr-indexing/tests/test_lazy_array_stateful.py new file mode 100644 index 0000000000..4f5dadc1e4 --- /dev/null +++ b/packages/zarr-indexing/tests/test_lazy_array_stateful.py @@ -0,0 +1,114 @@ +"""This package's own use of the state machine it exports. + +`ChainedIndexingStateMachine` composes indexing steps onto a `LazyArray` and +checks each step against NumPy β€” see +`zarr_indexing.testing.stateful` for what the invariants assert and why. + +Two sources: a NumPy array, which exercises both built-in readers, and a real +zarr array, whose partitioning is discovered from the store rather than +declared. The zarr case runs a smaller budget: it reads through a store, and it +exercises the same code paths. + +This replaces a seeded `_random_chain` sweep in `test_lazy_array` that read +chained selections through `parts()`. That sweep did reach the states it was +meant to, but a rank-0 correlated view was absorbed by a reshape in `result()` +and mirrored into the sweep rather than read as a failure; asserting the +documented assembly literally makes that impossible to paper over. +`test_lazy_array` keeps its `result()`-based sweep, which is the deterministic +cross-flavor coverage this does not attempt. +""" + +from __future__ import annotations + +from typing import Any, ClassVar + +import numpy as np +import pytest +from hypothesis import settings + +from zarr_indexing import LazyArray, ReadContext +from zarr_indexing.reader import basic_reader, numpy_reader +from zarr_indexing.testing import ( + DEFAULT_SETTINGS, + ChainedIndexingStateMachine, + state_machine_test, + stateful, +) + + +class NumpyIndexing(ChainedIndexingStateMachine): + readers = (numpy_reader,) + + +TestNumpyIndexing = state_machine_test(NumpyIndexing) + + +class UnhashableReader: + __hash__ = None + + def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: + basic_reader.read_into(source, context, out) + + def __eq__(self, other: object) -> bool: + return isinstance(other, UnhashableReader) + + +def test_reader_set_deduplicates_by_identity_without_hashing() -> None: + first = UnhashableReader() + second = UnhashableReader() + + readers = stateful._reader_set(LazyArray(np.arange(3)), (first, first, second)) + + assert readers[0] is basic_reader + assert readers[1] is first + assert readers[2] is second + assert len(readers) == 3 + + +class OneDimensionalIndexing(ChainedIndexingStateMachine): + """The same chains over a rank-1 source. + + The sorted one-dimensional fancy path in `chunk_resolution` is entered only + when both the input and output ranks are 1, and the output rank is the + *source's* β€” so the rank-3 default walls that path off from the machine + entirely, and from every downstream project told to subclass it. That path + is where reordering and duplicate coordinates are partitioned, which is the + corruption class this whole harness exists to catch. + """ + + data = np.arange(30, dtype=np.int64) + partitionings: ClassVar[tuple[Any, ...]] = (None, (4,), (30,), ((7, 8, 15),)) + + +TestOneDimensionalIndexing = state_machine_test(OneDimensionalIndexing) + + +class SingletonAxisIndexing(ChainedIndexingStateMachine): + """A source with an extent-1 axis, which the code must not read as a broadcast one. + + An index array's axis is a singleton either because the map broadcasts over + it or because the domain is genuinely one cell wide there, and the two are + told apart by the domain rather than the array. Nothing generated the second + kind. + """ + + data = np.arange(2 * 1 * 3, dtype=np.int64).reshape(2, 1, 3) + partitionings: ClassVar[tuple[Any, ...]] = (None, (1, 1, 1), (2, 1, 2)) + + +TestSingletonAxisIndexing = state_machine_test(SingletonAxisIndexing) + + +class ZarrIndexing(ChainedIndexingStateMachine): + """The same chains against a zarr array through the universal basic reader.""" + + def make_source(self, data: Any) -> Any: + zarr = pytest.importorskip("zarr") + array = zarr.create_array({}, shape=data.shape, chunks=(3, 2, 3), dtype=data.dtype) + array[:] = data + return array + + +TestZarrIndexing = state_machine_test( + ZarrIndexing, config=settings(DEFAULT_SETTINGS, max_examples=50) +) diff --git a/packages/zarr-indexing/tests/test_messages.py b/packages/zarr-indexing/tests/test_messages.py new file mode 100644 index 0000000000..2ebd41a263 --- /dev/null +++ b/packages/zarr-indexing/tests/test_messages.py @@ -0,0 +1,133 @@ +"""Message-layer tests beyond the vendored conformance corpus. + +The corpus (see `test_conformance.py`) covers the desugaring matrix and error +codes. These tests pin behaviors the corpus does not: `normalize` idempotence, +`parse_ndsel`, 64-bit boundary handling, and schema-valid-but-redundant maps. +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from zarr_indexing.messages import NdselError, normalize_ndsel, parse_ndsel + +_MESSAGES = [ + {"kind": "point", "coords": [4, 7]}, + {"kind": "box", "inclusive_min": [0, 0], "exclusive_max": [3, 4]}, + {"kind": "box", "inclusive_min": [["-inf"], 0], "exclusive_max": [["+inf"], 4]}, + {"kind": "slice", "start": [5], "stop": [10], "step": [2]}, + {"kind": "points", "coords": [[1, 10], [2, 20]]}, + { + "kind": "transform", + "input_inclusive_min": [0], + "input_exclusive_max": [3], + "output": [{"offset": 7}, {"input_dimension": 0, "stride": 2}, {"index_array": [1, 2, 3]}], + }, +] + + +@pytest.mark.parametrize("message", _MESSAGES) +def test_normalize_is_idempotent(message: dict[str, Any]) -> None: + once = normalize_ndsel(message) + twice = normalize_ndsel({"kind": "transform", **once}) + assert twice == once + + +@pytest.mark.parametrize("message", _MESSAGES) +def test_parse_returns_message_unchanged(message: dict[str, Any]) -> None: + assert parse_ndsel(message) == message + + +def test_parse_rejects_invalid() -> None: + with pytest.raises(NdselError) as excinfo: + parse_ndsel({"kind": "slice", "start": [0]}) + assert excinfo.value.reason == "invalid_json" + + +def test_constant_map_drops_redundant_stride() -> None: + # A constant map (no input_dimension, no index_array) is schema-valid even + # with a stray stride; it canonicalizes to offset-only. + result = normalize_ndsel( + {"kind": "transform", "input_rank": 0, "output": [{"offset": 5, "stride": 9}]} + ) + assert result["output"] == [{"offset": 5}] + + +def test_i64_min_and_max_round_trip() -> None: + i64_min, i64_max = -(2**63), 2**63 - 1 + result = normalize_ndsel({"kind": "point", "coords": [i64_min, i64_max]}) + assert result["output"] == [{"offset": i64_min}, {"offset": i64_max}] + + +def test_i64_overflow_rejected() -> None: + with pytest.raises(NdselError) as excinfo: + normalize_ndsel({"kind": "point", "coords": [2**63]}) + assert excinfo.value.reason == "invalid_json" + + +def test_bool_in_output_offset_rejected() -> None: + with pytest.raises(NdselError) as excinfo: + normalize_ndsel({"kind": "transform", "input_rank": 0, "output": [{"offset": True}]}) + assert excinfo.value.reason == "invalid_json" + + +def test_sentinel_not_allowed_in_plain_integer_position() -> None: + with pytest.raises(NdselError) as excinfo: + normalize_ndsel({"kind": "point", "coords": ["+inf"]}) + assert excinfo.value.reason == "invalid_json" + + +def test_not_an_object_rejected() -> None: + with pytest.raises(NdselError) as excinfo: + normalize_ndsel([1, 2, 3]) + assert excinfo.value.reason == "invalid_json" + + +def test_empty_string_kind_is_unknown_kind() -> None: + with pytest.raises(NdselError) as excinfo: + normalize_ndsel({"kind": ""}) + assert excinfo.value.reason == "unknown_kind" + + +class TestNegativeStep: + """ndsel 1.0-draft.2 section 5.3: one desugaring rule, both signs.""" + + def test_full_reverse(self) -> None: + """The spec's own worked example: reversing a length-20 axis.""" + body = normalize_ndsel({"kind": "slice", "start": [19], "stop": [-1], "step": [-1]}) + assert body["input_inclusive_min"] == [-19] + assert body["input_exclusive_max"] == [1] + assert body["output"] == [{"offset": 0, "stride": -1, "input_dimension": 0}] + + def test_trunc_origin_for_a_negative_step(self) -> None: + """`trunc(15 / -2) == -7`; `floor` would give -8.""" + body = normalize_ndsel({"kind": "slice", "start": [15], "stop": [5], "step": [-2]}) + assert body["input_inclusive_min"] == [-7] + assert body["input_exclusive_max"] == [-2] + assert body["output"] == [{"offset": 1, "stride": -2, "input_dimension": 0}] + + def test_empty_is_legal_at_any_coordinate(self) -> None: + body = normalize_ndsel({"kind": "slice", "start": [5], "stop": [5], "step": [-1]}) + assert body["input_inclusive_min"] == body["input_exclusive_max"] == [-5] + + @pytest.mark.parametrize( + "message", + [ + {"kind": "slice", "start": [9], "stop": [0]}, + {"kind": "slice", "start": [9], "stop": [0], "step": [2]}, + {"kind": "slice", "start": [5], "stop": [6], "step": [-1]}, + ], + ids=["unit-step", "positive-step", "negative-step"], + ) + def test_a_reversed_interval_is_an_error(self, message: dict[str, object]) -> None: + """Not clamped to empty: travelling the wrong way is a mistake, either sign.""" + with pytest.raises(NdselError) as excinfo: + normalize_ndsel(message) + assert excinfo.value.reason == "bounds_out_of_order" + + def test_zero_step_still_errors(self) -> None: + with pytest.raises(NdselError) as excinfo: + normalize_ndsel({"kind": "slice", "start": [0], "stop": [4], "step": [0]}) + assert excinfo.value.reason == "step_zero" diff --git a/packages/zarr-indexing/tests/test_ndsel_tensorstore.py b/packages/zarr-indexing/tests/test_ndsel_tensorstore.py new file mode 100644 index 0000000000..ab9465c8d1 --- /dev/null +++ b/packages/zarr-indexing/tests/test_ndsel_tensorstore.py @@ -0,0 +1,51 @@ +"""Cross-check canonical ndsel bodies against a real TensorStore. + +A normalized ndsel `transform` body is, field-for-field, a TensorStore +`IndexTransform` (minus the `kind` discriminator, which the canonical body never +carries). This test loads a handful of finite-bound canonical bodies into +`tensorstore.IndexTransform(json=...)` and confirms that TensorStore's own +`to_json()` re-loads, through our engine layer, into an equivalent transform. + +Skipped when tensorstore is not installed. Run it explicitly with: + + uv run --with tensorstore pytest \ + packages/zarr-indexing/tests/test_ndsel_tensorstore.py -q +""" + +from __future__ import annotations + +import numpy as np +import pytest + +from zarr_indexing.transform import IndexTransform + +ts = pytest.importorskip("tensorstore") + + +def _canonical_transforms() -> list[IndexTransform]: + base = IndexTransform.from_shape((10, 20)) + return [ + base, # identity + base[2:8:2, :], # strided DimensionMap + identity + base[3, :], # integer index -> ConstantMap + DimensionMap + base.oindex[np.array([1, 5, 9]), :], # orthogonal index_array + IndexTransform.from_shape((10, 20, 30)).vindex[ + np.array([1, 3]), np.array([2, 4]), : + ], # correlated index_arrays + residual slice + ] + + +@pytest.mark.parametrize("transform", _canonical_transforms()) +def test_body_loads_in_tensorstore_and_round_trips(transform: IndexTransform) -> None: + body = transform.to_json() + + # (1) The canonical body loads directly as a TensorStore IndexTransform. + ts_transform = ts.IndexTransform(json=body) + + # (2) TensorStore's own JSON re-loads, through our engine, to an equivalent + # transform. Comparing via our canonical form normalizes away + # representational choices (index_array_bounds, default omissions) that + # both sides make differently but that denote the same selection. + ts_json = ts_transform.to_json() + reloaded = IndexTransform.from_json(ts_json) + assert reloaded.to_json() == transform.to_json() diff --git a/packages/zarr-indexing/tests/test_output_map.py b/packages/zarr-indexing/tests/test_output_map.py new file mode 100644 index 0000000000..d1e21efaa7 --- /dev/null +++ b/packages/zarr-indexing/tests/test_output_map.py @@ -0,0 +1,99 @@ +from __future__ import annotations + +import pickle + +import numpy as np +import pytest + +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap + + +class TestConstantMap: + def test_construction(self) -> None: + m = ConstantMap(offset=42) + assert m.offset == 42 + + def test_default_offset(self) -> None: + m = ConstantMap() + assert m.offset == 0 + + def test_frozen(self) -> None: + m = ConstantMap(offset=5) + assert isinstance(m, ConstantMap) + + +class TestDimensionMap: + def test_construction(self) -> None: + m = DimensionMap(input_dimension=3, offset=5, stride=2) + assert m.input_dimension == 3 + assert m.offset == 5 + assert m.stride == 2 + + def test_defaults(self) -> None: + m = DimensionMap(input_dimension=0) + assert m.offset == 0 + assert m.stride == 1 + + def test_frozen(self) -> None: + m = DimensionMap(input_dimension=0) + assert isinstance(m, DimensionMap) + + +class TestArrayMap: + def test_construction(self) -> None: + arr = np.array([1, 3, 5], dtype=np.intp) + m = ArrayMap(index_array=arr, offset=10, stride=2) + assert m.offset == 10 + assert m.stride == 2 + np.testing.assert_array_equal(m.index_array, arr) + + def test_defaults(self) -> None: + arr = np.array([0, 1], dtype=np.intp) + m = ArrayMap(index_array=arr) + assert m.offset == 0 + assert m.stride == 1 + + def test_frozen(self) -> None: + arr = np.array([0], dtype=np.intp) + m = ArrayMap(index_array=arr) + assert isinstance(m, ArrayMap) + + def test_owns_index_array_and_keeps_hash_stable(self) -> None: + arr = np.array([1, 3, 5], dtype=np.intp) + m = ArrayMap(index_array=arr) + lookup = {m: "value"} + + arr[:] = 9 + + np.testing.assert_array_equal(m.index_array, [1, 3, 5]) + assert lookup[m] == "value" + + def test_pickle_round_trip_keeps_index_array_read_only(self) -> None: + restored = pickle.loads(pickle.dumps(ArrayMap(index_array=np.array([1, 3, 5])))) + + assert not restored.index_array.flags.writeable + with pytest.raises(ValueError, match="read-only"): + restored.index_array[0] = 9 + + def test_index_array_cannot_be_made_writeable(self) -> None: + m = ArrayMap(index_array=np.array([1, 3, 5])) + + with pytest.raises(ValueError): + m.index_array.flags.writeable = True + + def test_equal_array_maps_have_equal_hashes_across_integer_dtypes(self) -> None: + left = ArrayMap(np.array([1, 2], dtype=np.int32)) + right = ArrayMap(np.array([1, 2], dtype=np.int64)) + assert left == right + assert hash(left) == hash(right) + assert left.index_array.dtype == np.dtype(np.intp) + + def test_rejects_non_integer_index_array(self) -> None: + with pytest.raises(TypeError, match="index_array must have an integer dtype"): + ArrayMap(np.array([1.5, 2.0], dtype=np.float64)) + + def test_rejects_unsigned_index_array_value_outside_intp(self) -> None: + outside_intp = np.array([np.iinfo(np.uint64).max], dtype=np.uint64) + + with pytest.raises(OverflowError, match="outside np.intp range"): + ArrayMap(outside_intp) diff --git a/packages/zarr-indexing/tests/test_reader.py b/packages/zarr-indexing/tests/test_reader.py new file mode 100644 index 0000000000..11241a316c --- /dev/null +++ b/packages/zarr-indexing/tests/test_reader.py @@ -0,0 +1,514 @@ +from __future__ import annotations + +import math +from typing import TYPE_CHECKING, Any, get_type_hints + +import numpy as np +import numpy.typing as npt +import pytest + +import zarr_indexing.reader as reader_module +from zarr_indexing import ( + ArrayMap, + ChunkProjection, + ConstantMap, + DimensionMap, + IndexDomain, + IndexTransform, + LazyArray, + ReadContext, + plan_chunks, +) +from zarr_indexing.grid import dimension_grids_from_chunks +from zarr_indexing.reader import basic_reader, numpy_reader, unit_step_reader + +if TYPE_CHECKING: + from collections.abc import Callable + + +class BasicOnlySource: + def __init__(self, data: np.ndarray[Any, Any]) -> None: + self.data = data + self.keys: list[tuple[Any, ...]] = [] + + @property + def shape(self) -> tuple[int, ...]: + return self.data.shape + + @property + def dtype(self) -> np.dtype[Any]: + return self.data.dtype + + def __getitem__(self, key: tuple[Any, ...]) -> np.ndarray[Any, Any]: + assert all(isinstance(item, slice) and (item.step or 1) > 0 for item in key) + self.keys.append(key) + return self.data[key] + + +class UnitStepOnlySource(BasicOnlySource): + """A source that rejects everything but ascending unit-step slices.""" + + def __getitem__(self, key: tuple[Any, ...]) -> np.ndarray[Any, Any]: + assert all( + isinstance(item, slice) and item.step == 1 and 0 <= item.start <= item.stop <= size + for item, size in zip(key, self.data.shape, strict=True) + ) + self.keys.append(key) + return self.data[key] + + +SOURCE = np.arange(6 * 7 * 8).reshape(6, 7, 8) +BASE = IndexTransform.from_shape(SOURCE.shape) + + +SUCCESSFUL_CONTRACT_CASES = ( + pytest.param( + np.arange(8), + IndexTransform.from_shape((8,))[3], + (3,), + np.zeros((1, 0), dtype=np.intp), + np.array([[3]], dtype=np.intp), + np.array(3), + lambda array: array.lazy[3], + id="constant", + ), + pytest.param( + np.arange(8), + IndexTransform.from_shape((8,))[1:8:2], + (3,), + np.array([[0], [1], [2], [3]], dtype=np.intp), + np.array([[1], [3], [5], [7]], dtype=np.intp), + np.array([1, 3, 5, 7]), + lambda array: array.lazy[1:8:2], + id="positive-affine", + ), + pytest.param( + np.arange(8), + IndexTransform.from_shape((8,))[::-2], + (3,), + np.array([[-3], [-2], [-1], [0]], dtype=np.intp), + np.array([[7], [5], [3], [1]], dtype=np.intp), + np.array([7, 5, 3, 1]), + lambda array: array.lazy[::-2], + id="negative-affine", + ), + pytest.param( + np.arange(8), + IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(DimensionMap(input_dimension=0, offset=2, stride=0),), + ), + (3,), + np.array([[0], [1], [2]], dtype=np.intp), + np.array([[2], [2], [2]], dtype=np.intp), + np.array([2, 2, 2]), + lambda array: array.lazy.oindex[[2, 2, 2]], + id="zero-affine", + ), + pytest.param( + np.arange(20).reshape(4, 5), + IndexTransform.from_shape((4, 5)).oindex[[3, 1, 1], [4, 0]], + (2, 3), + np.array([[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1]], dtype=np.intp), + np.array([[3, 4], [3, 0], [1, 4], [1, 0], [1, 4], [1, 0]], dtype=np.intp), + np.array([[19, 15], [9, 5], [9, 5]]), + lambda array: array.lazy.oindex[[3, 1, 1], [4, 0]], + id="orthogonal-array", + ), + pytest.param( + np.arange(20).reshape(4, 5), + IndexTransform.from_shape((4, 5)).vindex[[3, 1, 1], [4, 0, 4]], + (2, 3), + np.array([[0], [1], [2]], dtype=np.intp), + np.array([[3, 4], [1, 0], [1, 4]], dtype=np.intp), + np.array([19, 5, 9]), + lambda array: array.lazy.vindex[[3, 1, 1], [4, 0, 4]], + id="correlated-array", + ), + pytest.param( + np.arange(8), + IndexTransform( + domain=IndexDomain((4,), (7,)), + output=(DimensionMap(input_dimension=0, offset=-3, stride=1),), + ), + (3,), + np.array([[4], [5], [6]], dtype=np.intp), + np.array([[1], [2], [3]], dtype=np.intp), + np.array([1, 2, 3]), + None, + id="non-zero-origin", + ), + pytest.param( + np.arange(8), + IndexTransform.from_shape((8,))[2:2], + (3,), + np.empty((0, 1), dtype=np.intp), + np.empty((0, 1), dtype=np.intp), + np.array([], dtype=np.intp), + lambda array: array.lazy[2:2], + id="empty", + ), +) + + +@pytest.mark.parametrize( + ( + "source_data", + "transform", + "chunk_shape", + "request_coordinates", + "storage_coordinates", + "expected_values", + "lazy_selection", + ), + SUCCESSFUL_CONTRACT_CASES, +) +def test_successful_transform_contract_across_planning_readers_and_lazy_array( + source_data: np.ndarray[Any, Any], + transform: IndexTransform, + chunk_shape: tuple[int, ...], + request_coordinates: npt.NDArray[np.intp], + storage_coordinates: npt.NDArray[np.intp], + expected_values: np.ndarray[Any, Any], + lazy_selection: Callable[[LazyArray], LazyArray] | None, +) -> None: + """One literal matrix keeps transform, planning, readers, and wrappers aligned.""" + np.testing.assert_array_equal(transform.apply_many(request_coordinates), storage_coordinates) + + grids = dimension_grids_from_chunks(chunk_shape, source_data.shape) + reconstructed_pairs = [ + ( + tuple(projection.cell_transform.apply(cell_coordinate)), + tuple( + local_coordinate + chunk_origin + for local_coordinate, chunk_origin in zip( + projection.chunk_transform.apply(cell_coordinate), + projection.chunk_domain.inclusive_min, + strict=True, + ) + ), + ) + for projection in plan_chunks(transform, grids) + for cell_coordinate in _domain_coordinates(projection.cell_transform.domain) + ] + expected_pairs = list( + zip( + map(tuple, request_coordinates.tolist()), + map(tuple, storage_coordinates.tolist()), + strict=True, + ) + ) + assert sorted(reconstructed_pairs) == sorted(expected_pairs) + + for reader, source in ( + (basic_reader, BasicOnlySource(source_data)), + (numpy_reader, source_data), + (unit_step_reader, UnitStepOnlySource(source_data)), + ): + out = np.empty(transform.domain.shape, dtype=source_data.dtype) + assert reader.read_into(source, ReadContext(transform), out) is None + np.testing.assert_array_equal(out, expected_values) + + if lazy_selection is not None: + view = lazy_selection(LazyArray.from_numpy(source_data).with_parts(chunk_shape)) + np.testing.assert_array_equal(view.result(), expected_values) + + +def _domain_coordinates(domain: IndexDomain) -> list[tuple[int, ...]]: + return [ + tuple( + position + origin for position, origin in zip(index, domain.inclusive_min, strict=True) + ) + for index in np.ndindex(*domain.shape) + ] + + +def test_read_context_public_annotations_resolve() -> None: + assert get_type_hints(ReadContext)["projection"] == ChunkProjection | None + + +READER_CASES = ( + pytest.param( + SOURCE, + BASE[1:6:2, 2, ::-2], + np.array( + [ + [79, 77, 75, 73], + [191, 189, 187, 185], + [303, 301, 299, 297], + ] + ), + id="strided-reversed-nonzero-origin", + ), + pytest.param( + SOURCE, + BASE.oindex[[5, 1, 1], slice(1, 6), [7, 2]], + np.array( + [ + [[295, 290], [303, 298], [311, 306], [319, 314], [327, 322]], + [[71, 66], [79, 74], [87, 82], [95, 90], [103, 98]], + [[71, 66], [79, 74], [87, 82], [95, 90], [103, 98]], + ] + ), + id="orthogonal-nonzero-origin", + ), + pytest.param( + SOURCE, + BASE.vindex[np.array([[5], [1]]), np.array([[2, 4, 0]])], + np.array( + [ + [ + [296, 297, 298, 299, 300, 301, 302, 303], + [312, 313, 314, 315, 316, 317, 318, 319], + [280, 281, 282, 283, 284, 285, 286, 287], + ], + [ + [72, 73, 74, 75, 76, 77, 78, 79], + [88, 89, 90, 91, 92, 93, 94, 95], + [56, 57, 58, 59, 60, 61, 62, 63], + ], + ] + ), + id="correlated-broadcast", + ), + pytest.param( + SOURCE, + BASE.vindex[[5, 1], [2, 2]], + np.array( + [ + [296, 297, 298, 299, 300, 301, 302, 303], + [72, 73, 74, 75, 76, 77, 78, 79], + ] + ), + id="correlated-vector", + ), + pytest.param( + SOURCE, + BASE[:, 0:0, :], + np.empty((6, 0, 8), dtype=SOURCE.dtype), + id="empty", + ), + pytest.param(SOURCE, BASE[2, 3, 4], np.array(140), id="scalar"), + pytest.param( + np.arange(8), + IndexTransform( + domain=IndexDomain((4,), (7,)), + output=(DimensionMap(input_dimension=0, offset=2, stride=0),), + ), + np.array([2, 2, 2]), + id="zero-stride-nonzero-origin", + ), +) + + +@pytest.mark.parametrize(("source_data", "transform", "expected"), READER_CASES) +@pytest.mark.parametrize("reader_name", ["basic", "numpy", "unit-step"]) +def test_builtin_readers_match_the_transform( + source_data: np.ndarray[Any, Any], + transform: IndexTransform, + expected: np.ndarray[Any, Any], + reader_name: str, +) -> None: + out = np.empty(transform.domain.shape, dtype=source_data.dtype) + if reader_name == "basic": + source = BasicOnlySource(source_data) + result = basic_reader.read_into(source, ReadContext(transform), out) + assert len(source.keys) == 1 + elif reader_name == "unit-step": + source = UnitStepOnlySource(source_data) + result = unit_step_reader.read_into(source, ReadContext(transform), out) + assert len(source.keys) == 1 + else: + result = numpy_reader.read_into(source_data, ReadContext(transform), out) + assert result is None + np.testing.assert_array_equal(out, expected) + + +@pytest.mark.parametrize("reader_name", ["basic", "numpy", "unit-step"]) +def test_builtin_readers_share_transform_affine_overflow(reader_name: str) -> None: + transform = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ArrayMap(np.array([2**62], dtype=np.intp), stride=4),), + ) + + with pytest.raises(OverflowError, match="outside np.intp"): + transform.apply_many(np.array([[0]], dtype=np.intp)) + + out = np.empty(transform.domain.shape, dtype=np.intp) + if reader_name == "basic": + with pytest.raises(OverflowError, match="outside np.intp"): + basic_reader.read_into(BasicOnlySource(np.arange(1)), ReadContext(transform), out) + elif reader_name == "unit-step": + with pytest.raises(OverflowError, match="outside np.intp"): + unit_step_reader.read_into( + UnitStepOnlySource(np.arange(1)), ReadContext(transform), out + ) + else: + with pytest.raises(OverflowError, match="outside np.intp"): + numpy_reader.read_into(np.arange(1), ReadContext(transform), out) + + +def test_empty_domain_composed_fancy_transform_reads_as_empty() -> None: + """An ArrayMap composed over an empty domain resolves like any other map. + + The composed map is legitimately empty along the vanished axis; the + resolvers used to fail reshaping it instead of noticing that an empty + domain selects nothing. + """ + source_data = np.arange(6).reshape(2, 3) + view = LazyArray.from_numpy(source_data).lazy.oindex[slice(0, 0), np.array([2, 1, 2, 0])] + transform = view.lazy.oindex[slice(None), np.array([1, 3, 1])].transform + assert transform.domain.shape == (0, 3) + + for reader, source in ( + (basic_reader, BasicOnlySource(source_data)), + (numpy_reader, source_data), + (unit_step_reader, UnitStepOnlySource(source_data)), + ): + out = np.empty(transform.domain.shape, dtype=source_data.dtype) + assert reader.read_into(source, ReadContext(transform), out) is None + + +def test_unit_step_reader_reads_through_lazy_array() -> None: + """The full dialect resolves through a source that only accepts unit-step slices. + + `UnitStepOnlySource` asserts the shape of every key it receives, so each + selection here also proves no strided, descending, or non-slice key + reached the source β€” partitioned and unpartitioned alike. + """ + selections: tuple[Callable[[LazyArray], LazyArray], ...] = ( + lambda v: v.lazy[1:5, ::2, ::-1], + lambda v: v.lazy[5:1:-2, None, 3, ::3], + lambda v: v.lazy.oindex[[3, 0, 3], ::-2, [7, 7]], + lambda v: v.lazy.vindex[np.array([[0, 5]]), np.array([[6], [0]]), 2], + lambda v: v.lazy[2:2, :, ::-1], + lambda v: v.lazy[::5, 6, 1:8:4], + ) + for select in selections: + for parts in (None, (2, 3, 8), (6, 7, 1)): + source = UnitStepOnlySource(SOURCE) + view = LazyArray(source).with_reader(unit_step_reader) + if parts is not None: + view = view.with_parts(parts) + expected = select(LazyArray.from_numpy(SOURCE)).result() + np.testing.assert_array_equal(select(view).result(), expected) + # An empty view allocates without reading; every other one must read. + assert (len(source.keys) > 0) == (expected.size > 0) + + +def test_constant_outside_intp_has_transform_planner_reader_error_parity() -> None: + outside_intp = int(np.iinfo(np.intp).max) + 1 + transform = IndexTransform( + domain=IndexDomain((), ()), + output=(ConstantMap(offset=outside_intp),), + ) + + with pytest.raises(OverflowError, match="outside np.intp range"): + transform.apply_many(np.zeros((1, 0), dtype=np.intp)) + + grids = dimension_grids_from_chunks((1,), (1,)) + with pytest.raises(OverflowError, match="outside np.intp range"): + list(plan_chunks(transform, grids)) + + for reader, source in ( + (basic_reader, BasicOnlySource(np.arange(1))), + (numpy_reader, np.arange(1)), + ): + with pytest.raises(OverflowError, match="outside np.intp range"): + reader.read_into(source, ReadContext(transform), np.empty((), dtype=np.intp)) + + +def test_numpy_reader_narrows_basic_slab_before_gather( + monkeypatch: pytest.MonkeyPatch, +) -> None: + source = np.arange(1_000_000).reshape(1000, 1000) + transform = IndexTransform.from_shape(source.shape).oindex[:10, [0, 999]] + seen: list[tuple[int, ...]] = [] + real_take = reader_module._take # pyright: ignore[reportPrivateUsage] + + def recording_take(array: Any, indices: npt.NDArray[np.intp], axis: int) -> Any: + seen.append(tuple(int(value) for value in array.shape)) + return real_take(array, indices, axis) + + monkeypatch.setattr(reader_module, "_take", recording_take) + out = np.empty(transform.domain.shape, dtype=source.dtype) + assert numpy_reader.read_into(source, ReadContext(transform), out) is None + assert out.shape == (10, 2) + np.testing.assert_array_equal( + out, + np.array( + [ + [0, 999], + [1000, 1999], + [2000, 2999], + [3000, 3999], + [4000, 4999], + [5000, 5999], + [6000, 6999], + [7000, 7999], + [8000, 8999], + [9000, 9999], + ] + ), + ) + assert seen + assert all(math.prod(shape) <= 20_000 for shape in seen), seen + + +def test_numpy_reader_preserves_a_mask_in_the_supplied_buffer() -> None: + source = np.ma.masked_greater(np.arange(12).reshape(3, 4), 7) + transform = IndexTransform.from_shape(source.shape)[:, 1:] + out = np.ma.masked_all(transform.domain.shape, dtype=source.dtype) + assert numpy_reader.read_into(source, ReadContext(transform), out) is None + np.testing.assert_array_equal(np.ma.getmaskarray(out), np.ma.getmaskarray(source[:, 1:])) + np.testing.assert_array_equal(np.ma.filled(out, 0), np.ma.filled(source[:, 1:], 0)) + + +# --------------------------------------------------------------------------- +# Diagonal gathers β€” output maps sharing an input axis +# --------------------------------------------------------------------------- + + +def test_reading_a_diagonal_gather_transform() -> None: + """Two index arrays bound to the same input axis resolve pointwise. + + No selection dialect produces this transform β€” it is the hand-built + diagonal-extraction form β€” but the reader resolves it through the same + pointwise path as a correlated gather. + """ + data = np.arange(30).reshape(5, 6) + rows = np.array([4, 0, 2]) + cols = np.array([1, 5, 2]) + transform = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=( + ArrayMap(index_array=rows), + ArrayMap(index_array=cols), + ), + ) + + out = np.empty((3,), dtype=data.dtype) + basic_reader.read_into(data, ReadContext(transform), out) + np.testing.assert_array_equal(out, data[rows, cols]) + + out = np.empty((3,), dtype=data.dtype) + numpy_reader.read_into(data, ReadContext(transform), out) + np.testing.assert_array_equal(out, data[rows, cols]) + + +def test_reading_a_diagonal_gather_with_a_residual_slice_axis() -> None: + data = np.arange(60).reshape(5, 6, 2) + rows = np.array([[4], [0], [2]]) + cols = np.array([[1], [5], [2]]) + transform = IndexTransform( + domain=IndexDomain.from_shape((3, 2)), + output=( + ArrayMap(index_array=rows), + ArrayMap(index_array=cols), + DimensionMap(input_dimension=1), + ), + ) + + out = np.empty((3, 2), dtype=data.dtype) + basic_reader.read_into(data, ReadContext(transform), out) + np.testing.assert_array_equal(out, data[rows[:, 0], cols[:, 0], :]) diff --git a/packages/zarr-indexing/tests/test_tensorstore_parity.py b/packages/zarr-indexing/tests/test_tensorstore_parity.py new file mode 100644 index 0000000000..9f4123fc02 --- /dev/null +++ b/packages/zarr-indexing/tests/test_tensorstore_parity.py @@ -0,0 +1,435 @@ +"""TensorStore-parity oracle tests for IndexTransform semantics. + +Every case in this module was executed against tensorstore 0.1.84 (see the +lazy-indexing design notes): the expected domains, values, and error conditions +are TensorStore's observed behavior, which zarr's lazy indexing matches by +design. Core rules pinned here: + +- **Domain preservation**: a step-1 slice keeps the literal coordinates of the + selected interval (`a[2:10]` has domain `[2, 10)`); nothing re-zeros + implicitly. Re-zeroing is explicit via `translate_to`. +- **Strided-domain rule**: for step ``k``, ``origin = trunc(start/k)`` (rounded + toward zero), ``shape = ceil((stop - start)/k)``, and coordinate + ``origin + i`` maps to base cell ``start + i*k``. +- **Strict containment**: non-empty slice intervals must lie within the domain + β€” no clamping, no negative-wrapping; empty intervals are valid anywhere; + reversed non-empty bounds are an error, not an empty result. +- **Fancy-dim rule**: index-array dims get fresh explicit ``[0, n)`` domains; + index-array values are absolute domain coordinates. +- **Translate rules**: ``translate_by``/``translate_to`` shift the input domain + while preserving which cells are addressed. +""" + +from __future__ import annotations + +from typing import ClassVar + +import numpy as np +import pytest + +from zarr_indexing.domain import IndexDomain +from zarr_indexing.errors import BoundsCheckError +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap +from zarr_indexing.transform import IndexTransform + + +def _identity(lo: int, hi: int) -> IndexTransform: + """Identity transform over the 1-D domain [lo, hi).""" + return IndexTransform.identity(IndexDomain(inclusive_min=(lo,), exclusive_max=(hi,))) + + +def _a() -> IndexTransform: + """The oracle's base fixture: identity over [0, 12).""" + return _identity(0, 12) + + +def _w() -> IndexTransform: + """The oracle's translated fixture: identity over [-10, 2), cell c -> base c + 10.""" + return _a().translate_domain_by((-10,)) + + +def _dim(t: IndexTransform) -> DimensionMap: + m = t.output[0] + assert isinstance(m, DimensionMap) + return m + + +def _base_cells(t: IndexTransform) -> list[int]: + """The base cells a 1-D single-DimensionMap transform addresses, in order.""" + m = _dim(t) + lo, hi = t.domain.inclusive_min[0], t.domain.exclusive_max[0] + return [m.offset + m.stride * c for c in range(lo, hi)] + + +class TestDomainPreservation: + """Oracle section 1-2: step-1 slices keep literal coordinates.""" + + def test_slice_preserves_domain(self) -> None: + t = _a()[2:10] + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((2,), (10,)) + assert _base_cells(t) == list(range(2, 10)) + + def test_integer_on_preserved_domain_is_a_coordinate(self) -> None: + v = _a()[2:10] + assert isinstance(v[3].output[0], ConstantMap) + assert v[3].output[0].offset == 3 # coordinate 3 = base cell 3 + assert v[2].output[0].offset == 2 + assert v[9].output[0].offset == 9 + + @pytest.mark.parametrize("bad", [0, -1, 10]) + def test_out_of_domain_integer_raises(self, bad: int) -> None: + with pytest.raises(BoundsCheckError, match=r"valid indices \[2, 10\)"): + _a()[2:10][bad] + + def test_slice_of_slice_is_literal(self) -> None: + v = _a()[2:10] + t = v[3:7] + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((3,), (7,)) + assert _base_cells(t) == [3, 4, 5, 6] + + def test_ellipsis_preserves_domain(self) -> None: + v = _a()[2:10] + t = v[...] + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((2,), (10,)) + + +class TestNegativeOriginDomain: + """Oracle section 3: on domain [-10, 2), -1 is just another index.""" + + def test_translated_domain(self) -> None: + w = _w() + assert (w.domain.inclusive_min, w.domain.exclusive_max) == ((-10,), (2,)) + assert _base_cells(w) == list(range(12)) + + @pytest.mark.parametrize(("coord", "base"), [(-5, 5), (-10, 0), (-1, 9), (1, 11)]) + def test_negative_coordinates_address_cells(self, coord: int, base: int) -> None: + t = _w()[coord] + assert isinstance(t.output[0], ConstantMap) + assert t.output[0].offset == base + + @pytest.mark.parametrize("bad", [-11, 2]) + def test_out_of_domain_raises(self, bad: int) -> None: + with pytest.raises(BoundsCheckError, match=r"valid indices \[-10, 2\)"): + _w()[bad] + + def test_negative_slice_bounds_are_coordinates(self) -> None: + t = _w()[-5:] + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((-5,), (2,)) + assert _base_cells(t) == [5, 6, 7, 8, 9, 10, 11] + t2 = _w()[-5:-2] + assert (t2.domain.inclusive_min, t2.domain.exclusive_max) == ((-5,), (-2,)) + assert _base_cells(t2) == [5, 6, 7] + + +class TestStridedDomains: + """Oracle section 5: origin = trunc(start/step), coord origin+i -> start + i*step.""" + + # (slice, expected (lo, hi), expected base cells) β€” verbatim oracle rows. + CASES: ClassVar[list[tuple[slice, tuple[int, int], list[int]]]] = [ + (slice(1, 10, 3), (0, 3), [1, 4, 7]), + (slice(None, None, 2), (0, 6), [0, 2, 4, 6, 8, 10]), + (slice(2, 11, 3), (0, 3), [2, 5, 8]), + (slice(0, 12, 4), (0, 3), [0, 4, 8]), + (slice(5, 12, 2), (2, 6), [5, 7, 9, 11]), + (slice(6, 12, 2), (3, 6), [6, 8, 10]), + (slice(7, 12, 3), (2, 4), [7, 10]), + ] + + @pytest.mark.parametrize(("sel", "dom", "cells"), CASES) + def test_strided_domain_and_cells( + self, sel: slice, dom: tuple[int, int], cells: list[int] + ) -> None: + t = _a()[sel] + assert (t.domain.inclusive_min[0], t.domain.exclusive_max[0]) == dom + assert _base_cells(t) == cells + + def test_strided_on_negative_origin(self) -> None: + # w[-9:2:2] -> domain [-4, 2), base cells 1,3,5,7,9,11 + t = _w()[-9:2:2] + assert (t.domain.inclusive_min[0], t.domain.exclusive_max[0]) == (-4, 2) + assert _base_cells(t) == [1, 3, 5, 7, 9, 11] + # w[::2] -> domain [-5, 1), base cells 0,2,4,6,8,10 + t2 = _w()[::2] + assert (t2.domain.inclusive_min[0], t2.domain.exclusive_max[0]) == (-5, 1) + assert _base_cells(t2) == [0, 2, 4, 6, 8, 10] + + def test_strided_composition(self) -> None: + s = _a()[1:10:3] # domain [0, 3), cells 1,4,7 + assert [s[k].output[0].offset for k in range(3)] == [1, 4, 7] + t = s[1:3] + assert (t.domain.inclusive_min[0], t.domain.exclusive_max[0]) == (1, 3) + assert _base_cells(t) == [4, 7] + t2 = _a()[::2][1:4] + assert (t2.domain.inclusive_min[0], t2.domain.exclusive_max[0]) == (1, 4) + assert _base_cells(t2) == [2, 4, 6] + t3 = _a()[::2][::2] + assert (t3.domain.inclusive_min[0], t3.domain.exclusive_max[0]) == (0, 3) + assert _base_cells(t3) == [0, 4, 8] + + @pytest.mark.parametrize("bad", [-2, -1, 3, 4]) + def test_strided_bounds(self, bad: int) -> None: + with pytest.raises(BoundsCheckError, match=r"valid indices \[0, 3\)"): + _a()[1:10:3][bad] + + +class TestStrictContainment: + """Oracle section 11: no clamping, no wrapping; empty intervals valid anywhere.""" + + @pytest.mark.parametrize( + "sel", + [ + slice(5, 100), + slice(-3, None), + slice(-3, -1), + slice(0, 13), + slice(12, 14), + slice(100, 200), + ], + ) + def test_uncontained_interval_raises(self, sel: slice) -> None: + with pytest.raises(BoundsCheckError, match="not contained"): + _a()[sel] + + def test_uncontained_on_negative_origin(self) -> None: + with pytest.raises(BoundsCheckError, match="not contained"): + _w()[-20:] + + @pytest.mark.parametrize( + ("sel", "pos"), [(slice(5, 5), 5), (slice(0, 0), 0), (slice(13, 13), 13)] + ) + def test_empty_interval_valid_anywhere(self, sel: slice, pos: int) -> None: + t = _a()[sel] + assert t.domain.shape == (0,) + assert t.domain.inclusive_min[0] == pos + + @pytest.mark.parametrize("sel", [slice(5, 2), slice(100, 50)]) + def test_reversed_bounds_raise(self, sel: slice) -> None: + with pytest.raises(IndexError, match="valid.*interval|interval"): + _a()[sel] + + +class TestNegativeStep: + """Section 1 of the negative-step study: one desugaring rule, both signs. + + Every expectation below is TensorStore 0.1.84's recorded output (study + sections 1.3-1.5), which an exhaustive 32,980-case sweep found zero + disagreements with. + """ + + # (domain, slice, expected domain, expected offset, expected stride, cells) + RECORDED: ClassVar[list[tuple[tuple[int, int], slice, tuple[int, int], int, int]]] = [ + ((0, 20), slice(15, 5, -1), (-15, -5), 0, -1), + ((0, 20), slice(15, 5, -2), (-7, -2), 1, -2), + ((0, 20), slice(15, 4, -2), (-7, -1), 1, -2), + ((0, 20), slice(None, None, -1), (-19, 1), 0, -1), + ((0, 20), slice(None, None, -2), (-9, 1), 1, -2), + ((0, 20), slice(5, None, -1), (-5, 1), 0, -1), + ((0, 20), slice(None, 5, -1), (-19, -5), 0, -1), + ((0, 20), slice(5, 5, -1), (-5, -5), 0, -1), + ((0, 20), slice(5, 4, -1), (-5, -4), 0, -1), + ((0, 20), slice(5, 4, -3), (-1, 0), 2, -3), + ((0, 20), slice(15, 5, -4), (-3, 0), 3, -4), + ((0, 20), slice(15, 5, -7), (-2, 0), 1, -7), + ((5, 25), slice(None, None, -2), (-12, -2), 0, -2), + ((-10, 10), slice(-1, -6, -2), (0, 3), -1, -2), + ((-10, 10), slice(-2, -9, -3), (0, 3), -2, -3), + ] + + @pytest.mark.parametrize( + ("domain", "sel", "expected_domain", "offset", "stride"), + RECORDED, + ids=[f"{d}{s}" for d, s, _, _, _ in RECORDED], + ) + def test_recorded_desugaring( + self, + domain: tuple[int, int], + sel: slice, + expected_domain: tuple[int, int], + offset: int, + stride: int, + ) -> None: + t = _identity(*domain)[sel] + assert (t.domain.inclusive_min[0], t.domain.exclusive_max[0]) == expected_domain + m = _dim(t) + assert (m.offset, m.stride) == (offset, stride) + + @pytest.mark.parametrize( + ("domain", "sel", "cells"), + [ + ((0, 20), slice(15, 5, -1), list(range(15, 5, -1))), + ((0, 20), slice(15, 5, -2), [15, 13, 11, 9, 7]), + ((0, 20), slice(None, None, -1), list(range(19, -1, -1))), + ((0, 20), slice(15, 5, -7), [15, 8]), + ((5, 25), slice(None, None, -2), list(range(24, 4, -2))), + ((-10, 10), slice(-1, -6, -2), [-1, -3, -5]), + ((-10, 10), slice(-2, -9, -3), [-2, -5, -8]), + ], + ) + def test_recorded_cells(self, domain: tuple[int, int], sel: slice, cells: list[int]) -> None: + assert _base_cells(_identity(*domain)[sel]) == cells + + def test_trunc_not_floor_or_ceil(self) -> None: + """The three rows of study section 1.2 that discriminate the rounding.""" + # floor would give -8 here, trunc gives -7. + assert _identity(0, 20)[15:5:-2].domain.inclusive_min[0] == -7 + # ceil would give 1 for both of these; trunc gives 0. + assert _identity(-10, 10)[-1:-6:-2].domain.inclusive_min[0] == 0 + assert _identity(-10, 10)[-2:-9:-3].domain.inclusive_min[0] == 0 + + @pytest.mark.parametrize("sel", [slice(5, 15, -1), slice(5, 6, -1)]) + def test_inverted_interval_raises(self, sel: slice) -> None: + with pytest.raises(IndexError, match="valid.*interval"): + _identity(0, 20)[sel] + + @pytest.mark.parametrize("sel", [slice(20, 0, -1), slice(20, 19, -1), slice(15, -5, -1)]) + def test_uncontained_interval_raises(self, sel: slice) -> None: + with pytest.raises(BoundsCheckError, match="not contained"): + _identity(0, 20)[sel] + + def test_zero_step_raises(self) -> None: + with pytest.raises(IndexError, match="step must not be zero"): + _identity(0, 20)[15:5:0] + + def test_empty_interval_legal_outside_the_domain(self) -> None: + t = _identity(0, 20)[25:25:-1] + assert t.domain.shape == (0,) + assert t.domain.inclusive_min[0] == -25 + + @pytest.mark.parametrize( + ("domain", "first", "second", "expected_domain", "offset", "stride", "cells"), + [ + # Study section 1.5, recorded verbatim. Each row applies `second` + # to the view `first` produced β€” strides multiply, and a double + # reverse recovers the identity. + ( + (0, 20), + slice(0, 20, 2), + slice(None, None, -1), + (-9, 1), + 0, + -2, + list(range(18, -2, -2)), + ), + ((0, 20), slice(0, 20, 2), slice(None, None, -2), (-4, 1), 2, -4, [18, 14, 10, 6, 2]), + ( + (0, 20), + slice(None, None, -1), + slice(None, None, -1), + (0, 20), + 0, + 1, + list(range(20)), + ), + ( + (0, 20), + slice(None, None, -1), + slice(None, None, 2), + (-9, 1), + 1, + -2, + list(range(19, -1, -2)), + ), + ( + (-10, 10), + slice(None, None, -1), + slice(None, None, -3), + (-3, 4), + -1, + 3, + [-10, -7, -4, -1, 2, 5, 8], + ), + ], + ids=[ + "strided-then-reverse", + "strided-then-reverse-by-two", + "double-reverse-is-identity", + "reverse-then-strided", + "reverse-then-strided-on-negative-origin", + ], + ) + def test_recorded_composition( + self, + domain: tuple[int, int], + first: slice, + second: slice, + expected_domain: tuple[int, int], + offset: int, + stride: int, + cells: list[int], + ) -> None: + t = _identity(*domain)[first][second] + assert (t.domain.inclusive_min[0], t.domain.exclusive_max[0]) == expected_domain + m = _dim(t) + assert (m.offset, m.stride) == (offset, stride) + assert _base_cells(t) == cells + + def test_negative_step_over_an_index_array_reverses_it(self) -> None: + """Study section 1.5: a reversing step materializes, it does not stride. + + Recorded: `oindex[[3, 1, 2]]` then `[2:-1:-1]` gives index array + `[[2], [1], [3]]` over domain `[-2, 1)`. + """ + base = IndexTransform.identity(IndexDomain(inclusive_min=(0, 0), exclusive_max=(4, 5))) + gathered = base.oindex[np.array([3, 1, 2]), slice(None)] + reversed_view = gathered[2:-1:-1, :] + + assert reversed_view.domain.inclusive_min[0] == -2 + assert reversed_view.domain.exclusive_max[0] == 1 + m = reversed_view.output[0] + assert isinstance(m, ArrayMap) + np.testing.assert_array_equal(m.index_array.reshape(-1), np.array([2, 1, 3])) + + +class TestTranslate: + """Oracle sections 4 and 12: translate_by / translate_to preserve the cell mapping.""" + + def test_translate_to_zero(self) -> None: + t = _a()[2:10].translate_domain_to((0,)) + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((0,), (8,)) + assert _base_cells(t) == list(range(2, 10)) + + def test_translate_to_offset(self) -> None: + t = _a().translate_domain_to((5,)) + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((5,), (17,)) + assert _base_cells(t) == list(range(12)) + + def test_translate_by_composes_with_stride(self) -> None: + # a[::2].translate_by[5] -> domain [5, 11), base = 2*(coord-5) + t = _a()[::2].translate_domain_by((5,)) + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((5,), (11,)) + assert _base_cells(t) == [0, 2, 4, 6, 8, 10] + assert t[5].output[0].offset == 0 + assert t[10].output[0].offset == 10 + with pytest.raises(BoundsCheckError, match=r"valid indices \[5, 11\)"): + t[0] + + def test_translate_strided_to(self) -> None: + t = _a()[1:10:3].translate_domain_to((100,)) + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((100,), (103,)) + assert _base_cells(t) == [1, 4, 7] + + +class TestFancyDims: + """Oracle section 7: fancy dims get fresh [0, n); values are absolute coordinates.""" + + def test_index_array_values_are_coordinates(self) -> None: + v = _a()[2:10] + t = v.oindex[(np.array([3, 5], dtype=np.intp),)] + assert (t.domain.inclusive_min, t.domain.exclusive_max) == ((0,), (2,)) + m = t.output[0] + assert isinstance(m, ArrayMap) + storage = m.offset + m.stride * m.index_array + np.testing.assert_array_equal(np.asarray(storage).ravel(), [3, 5]) + + def test_index_array_on_negative_origin(self) -> None: + t = _w().oindex[(np.array([-10, -1], dtype=np.intp),)] + m = t.output[0] + assert isinstance(m, ArrayMap) + storage = m.offset + m.stride * m.index_array + np.testing.assert_array_equal(np.asarray(storage).ravel(), [0, 9]) + + def test_index_array_out_of_domain_raises(self) -> None: + v = _a()[2:10] + for bad in ([0, 3], [-1, 3], [3, 10]): + with pytest.raises(BoundsCheckError): + v.oindex[(np.array(bad, dtype=np.intp),)] diff --git a/packages/zarr-indexing/tests/test_transform.py b/packages/zarr-indexing/tests/test_transform.py new file mode 100644 index 0000000000..a13eaf6e28 --- /dev/null +++ b/packages/zarr-indexing/tests/test_transform.py @@ -0,0 +1,1250 @@ +from __future__ import annotations + +from typing import cast + +import numpy as np +import pytest + +from zarr_indexing.domain import IndexDomain +from zarr_indexing.errors import BoundsCheckError +from zarr_indexing.lazy_array import LazyArray +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap +from zarr_indexing.transform import ( + IndexTransform, +) + + +class IndexLike: + """A scalar integer selector implemented only through `__index__`.""" + + def __init__(self, value: int) -> None: + self.value = value + + def __index__(self) -> int: + return self.value + + +class IntOnly: + def __int__(self) -> int: + return 2 + + +class BadIndex: + """An `__index__` that lies: the protocol requires an integer.""" + + def __index__(self) -> int: + return cast("int", 2.5) + + +class TestIndexTransformConstruction: + def test_from_shape(self) -> None: + t = IndexTransform.from_shape((10, 20)) + assert t.input_rank == 2 + assert t.output_rank == 2 + assert t.domain.shape == (10, 20) + assert t.domain.origin == (0, 0) + for i, m in enumerate(t.output): + assert isinstance(m, DimensionMap) + assert m.input_dimension == i + assert m.offset == 0 + assert m.stride == 1 + + def test_identity(self) -> None: + domain = IndexDomain(inclusive_min=(5,), exclusive_max=(15,)) + t = IndexTransform.identity(domain) + assert t.input_rank == 1 + assert t.output_rank == 1 + assert t.domain == domain + assert isinstance(t.output[0], DimensionMap) + assert t.output[0].input_dimension == 0 + + def test_from_shape_0d(self) -> None: + t = IndexTransform.from_shape(()) + assert t.input_rank == 0 + assert t.output_rank == 0 + assert t.domain.shape == () + + def test_custom_output_maps(self) -> None: + domain = IndexDomain.from_shape((10,)) + maps = (ConstantMap(offset=42), DimensionMap(input_dimension=0, offset=5, stride=2)) + t = IndexTransform(domain=domain, output=maps) + assert t.input_rank == 1 + assert t.output_rank == 2 + + def test_validation_input_dimension_out_of_range(self) -> None: + domain = IndexDomain.from_shape((10,)) + maps = (DimensionMap(input_dimension=5),) + with pytest.raises(ValueError, match="input_dimension"): + IndexTransform(domain=domain, output=maps) + + +class TestIndexTransformApply: + @pytest.mark.parametrize( + ("transform", "points", "expected"), + [ + pytest.param( + IndexTransform.identity(IndexDomain((-2, 5), (1, 8))), + np.array([-2, 7], dtype=np.int64), + np.array([-2, 7], dtype=np.intp), + id="identity-negative-and-nonzero-origins", + ), + pytest.param( + IndexTransform( + domain=IndexDomain((3,), (6,)), + output=( + ConstantMap(41), + DimensionMap(0, offset=10, stride=-2), + ), + ), + np.array([[3], [5]], dtype=np.int16), + np.array([[41, 4], [41, 0]], dtype=np.intp), + id="constant-and-negative-stride", + ), + pytest.param( + IndexTransform( + domain=IndexDomain((-2, 5), (1, 8)), + output=( + ArrayMap( + np.array([[7], [11], [13]], dtype=np.intp), + offset=-1, + stride=2, + ), + ), + ), + np.array( + [ + [[-2, 5], [-1, 7]], + [[0, 6], [-2, 6]], + ], + dtype=np.intp, + ), + np.array([[[13], [21]], [[25], [13]]], dtype=np.intp), + id="array-map-singleton-broadcast-multidimensional-batch", + ), + pytest.param( + IndexTransform(IndexDomain((), ()), (ConstantMap(42),)), + np.empty((2, 0), dtype=np.intp), + np.array([[42], [42]], dtype=np.intp), + id="rank-zero-input", + ), + pytest.param( + IndexTransform(IndexDomain((-1,), (2,)), ()), + np.array([[-1], [1]], dtype=np.intp), + np.empty((2, 0), dtype=np.intp), + id="rank-zero-output", + ), + pytest.param( + IndexTransform.identity(IndexDomain.from_shape((2,))), + np.empty((0, 1), dtype=np.intp), + np.empty((0, 1), dtype=np.intp), + id="empty-batch", + ), + ], + ) + def test_apply_many_maps_integer_point_batches( + self, + transform: IndexTransform, + points: np.ndarray, + expected: np.ndarray, + ) -> None: + result = transform.apply_many(points) + + np.testing.assert_array_equal(result, expected) + assert result.dtype == np.dtype(np.intp) + assert result.flags.owndata + + def test_apply_maps_one_point(self) -> None: + transform = IndexTransform( + IndexDomain((-2, 4), (1, 7)), + ( + DimensionMap(1, offset=3, stride=-1), + DimensionMap(0, offset=2, stride=2), + ), + ) + + assert transform.apply((-1, 6)) == (-3, 0) + + def test_apply_rejects_a_point_with_the_wrong_rank(self) -> None: + with pytest.raises(ValueError, match=r"point must have shape \(2,\), got \(1,\)"): + IndexTransform.from_shape((2, 3)).apply((1,)) + + def test_apply_rejects_an_explicitly_floating_rank_zero_point(self) -> None: + transform = IndexTransform(IndexDomain((), ()), ()) + with pytest.raises(TypeError, match="integer dtype"): + transform.apply(np.array([], dtype=np.float64)) + + @pytest.mark.parametrize( + "points", + [ + pytest.param(np.array(1, dtype=np.intp), id="no-coordinate-axis"), + pytest.param(np.zeros((4, 3), dtype=np.intp), id="wrong-trailing-size"), + ], + ) + def test_apply_many_rejects_an_invalid_coordinate_axis(self, points: np.ndarray) -> None: + with pytest.raises(ValueError, match="trailing coordinate axis"): + IndexTransform.from_shape((2, 3)).apply_many(points) + + @pytest.mark.parametrize( + "points", + [ + pytest.param(np.array([[True]], dtype=np.bool_), id="bool"), + pytest.param(np.array([[1.0]], dtype=np.float64), id="float"), + pytest.param(np.array([["1"]], dtype=np.str_), id="string"), + pytest.param(np.array([[1]], dtype=object), id="object"), + ], + ) + def test_apply_many_rejects_non_integer_coordinates(self, points: np.ndarray) -> None: + with pytest.raises(TypeError, match="integer dtype"): + IndexTransform.from_shape((2,)).apply_many(points) + + def test_apply_many_reports_the_first_out_of_bounds_coordinate(self) -> None: + transform = IndexTransform.identity(IndexDomain((-2, 10), (2, 13))) + points = np.array( + [ + [[-2, 10], [-1, 20]], + [[9, 11], [0, 12]], + ], + dtype=np.intp, + ) + + with pytest.raises(BoundsCheckError) as error: + transform.apply_many(points) + + assert str(error.value) == ( + "point at batch position (0, 1) has input dimension 1 coordinate 20 outside [10, 13)" + ) + + def test_apply_reports_a_single_point_error_without_batch_vocabulary(self) -> None: + transform = IndexTransform.identity(IndexDomain((-10,), (10,))) + + with pytest.raises(BoundsCheckError) as error: + transform.apply((11,)) + + assert str(error.value) == ( + "coordinate 11 on input dimension 0 is outside the domain [-10, 10)" + ) + assert error.value.__cause__ is None + assert error.value.__suppress_context__ + + @pytest.mark.parametrize( + "beyond_intp", + [ + pytest.param(int(np.iinfo(np.intp).max) + 1, id="first-uint64-coordinate"), + pytest.param(int(np.iinfo(np.uint64).max), id="maximum-uint64-coordinate"), + ], + ) + def test_apply_many_maps_large_literal_coordinates_exactly(self, beyond_intp: int) -> None: + transform = IndexTransform( + IndexDomain((beyond_intp,), (beyond_intp + 1,)), + (DimensionMap(0, offset=-beyond_intp),), + ) + + result = transform.apply_many(np.array([[beyond_intp]], dtype=np.uint64)) + + np.testing.assert_array_equal(result, np.array([[0]], dtype=np.intp)) + assert result.dtype == np.dtype(np.intp) + assert result.flags.owndata + + @pytest.mark.parametrize( + ("transform", "points"), + [ + pytest.param( + IndexTransform( + IndexDomain.from_shape((1,)), + (ConstantMap(np.iinfo(np.intp).max + 1),), + ), + [[0]], + id="constant", + ), + pytest.param( + IndexTransform( + IndexDomain.from_shape((2,)), + (DimensionMap(0, offset=np.iinfo(np.intp).max),), + ), + [[1]], + id="dimension", + ), + pytest.param( + IndexTransform( + IndexDomain.from_shape((1,)), + ( + ArrayMap( + np.array([1], dtype=np.intp), + offset=np.iinfo(np.intp).max, + ), + ), + ), + [[0]], + id="array", + ), + pytest.param( + IndexTransform.identity( + IndexDomain( + (int(np.iinfo(np.intp).max) + 1,), + (int(np.iinfo(np.intp).max) + 2,), + ) + ), + np.array([[int(np.iinfo(np.intp).max) + 1]], dtype=np.uint64), + id="large-input-identity", + ), + ], + ) + def test_apply_many_rejects_mapped_coordinates_outside_intp( + self, transform: IndexTransform, points: list[list[int]] | np.ndarray + ) -> None: + with pytest.raises(OverflowError, match="output coordinate.*np.intp"): + transform.apply_many(points) + + def test_apply_many_rejects_affine_coordinate_overflow(self) -> None: + transform = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ArrayMap(np.array([2**62], dtype=np.intp), stride=4),), + ) + with pytest.raises(OverflowError, match="outside np.intp"): + transform.apply_many(np.array([[0]], dtype=np.intp)) + + def test_apply_rejects_affine_coordinate_overflow(self) -> None: + transform = IndexTransform( + domain=IndexDomain.from_shape((1,)), + output=(ArrayMap(np.array([2**62], dtype=np.intp), stride=4),), + ) + with pytest.raises(OverflowError, match="outside np.intp"): + transform.apply((0,)) + + +class TestIndexTransformInverted: + @pytest.mark.parametrize( + ("transform", "points"), + [ + pytest.param( + IndexTransform( + IndexDomain((-3, 4), (1, 7)), + ( + DimensionMap(1, offset=10), + DimensionMap(0, offset=2, stride=-1), + ), + ), + np.array([[-3, 4], [0, 6]], dtype=np.intp), + id="permutation-translation-reversal-nonzero-origin", + ), + pytest.param( + IndexTransform( + IndexDomain((5, -2), (8, -1)), + (DimensionMap(0, offset=3), ConstantMap(99)), + ), + np.array([[5, -2], [7, -2]], dtype=np.intp), + id="constant-and-unreferenced-singleton", + ), + pytest.param( + IndexTransform(IndexDomain((), ()), ()), + np.empty((1, 0), dtype=np.intp), + id="rank-zero", + ), + ], + ) + def test_inverted_round_trips_points( + self, transform: IndexTransform, points: np.ndarray + ) -> None: + inverse = transform.inverted() + mapped = transform.apply_many(points) + + np.testing.assert_array_equal(inverse.apply_many(mapped), points) + assert inverse.apply(transform.apply(tuple(points[0]))) == tuple(points[0]) + assert inverse.inverted() == transform + + def test_inverted_rejects_unequal_ranks(self) -> None: + transform = IndexTransform(IndexDomain.from_shape((2,)), (ConstantMap(1), ConstantMap(2))) + with pytest.raises(ValueError, match="input rank must equal output rank"): + transform.inverted() + + def test_inverted_rejects_an_array_map(self) -> None: + transform = IndexTransform( + IndexDomain.from_shape((2,)), + (ArrayMap(np.array([1, 0], dtype=np.intp)),), + ) + with pytest.raises(ValueError, match="ArrayMap"): + transform.inverted() + + def test_inverted_rejects_a_non_unit_stride(self) -> None: + transform = IndexTransform( + IndexDomain.from_shape((2,)), + (DimensionMap(0, stride=2),), + ) + with pytest.raises(ValueError, match=r"stride must be \+1 or -1"): + transform.inverted() + + def test_inverted_rejects_a_repeated_input_dimension(self) -> None: + transform = IndexTransform( + IndexDomain.from_shape((2, 1)), + (DimensionMap(0), DimensionMap(0, offset=5)), + ) + with pytest.raises(ValueError, match="referenced more than once"): + transform.inverted() + + def test_inverted_rejects_an_unreferenced_non_singleton_dimension(self) -> None: + transform = IndexTransform( + IndexDomain.from_shape((2, 2)), + (DimensionMap(0), ConstantMap(7)), + ) + with pytest.raises(ValueError, match="unreferenced input dimension 1.*extent 2"): + transform.inverted() + + def test_inverted_rejects_input_labels_that_cannot_be_preserved(self) -> None: + transform = IndexTransform.identity(IndexDomain((0,), (2,), labels=("row",))) + with pytest.raises(ValueError, match="input labels cannot be represented"): + transform.inverted() + + +class TestIndexTransformBasicIndexing: + def test_slice_identity(self) -> None: + """slice(None) on identity transform is a no-op.""" + t = IndexTransform.from_shape((10, 20)) + result = t[slice(None), slice(None)] + assert result.domain.shape == (10, 20) + assert result.input_rank == 2 + assert result.output_rank == 2 + + def test_slice_narrows(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t[2:8, 5:15] + # Domains are preserved (TensorStore): the slice keeps its literal + # coordinates, so the map stays the identity (out = in). + assert result.domain.shape == (6, 10) + assert result.domain.origin == (2, 5) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == 0 + assert result.output[0].stride == 1 + assert result.output[0].input_dimension == 0 + assert isinstance(result.output[1], DimensionMap) + assert result.output[1].offset == 0 + assert result.output[1].input_dimension == 1 + + def test_strided_slice(self) -> None: + t = IndexTransform.from_shape((10,)) + result = t[::2] + assert result.domain.shape == (5,) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == 0 + assert result.output[0].stride == 2 + + def test_strided_slice_with_start(self) -> None: + t = IndexTransform.from_shape((10,)) + result = t[1:9:3] + # indices: 1, 4, 7 -> 3 elements + assert result.domain.shape == (3,) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == 1 + assert result.output[0].stride == 3 + + def test_int_drops_dimension(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t[3] + assert result.input_rank == 1 + assert result.output_rank == 2 + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == 3 + assert isinstance(result.output[1], DimensionMap) + assert result.output[1].input_dimension == 0 + + def test_int_middle_dimension(self) -> None: + t = IndexTransform.from_shape((10, 20, 30)) + result = t[:, 5, :] + assert result.input_rank == 2 + assert result.output_rank == 3 + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].input_dimension == 0 + assert isinstance(result.output[1], ConstantMap) + assert result.output[1].offset == 5 + assert isinstance(result.output[2], DimensionMap) + assert result.output[2].input_dimension == 1 + + def test_ellipsis(self) -> None: + t = IndexTransform.from_shape((10, 20, 30)) + result = t[2:8, ...] + assert result.input_rank == 3 + assert result.domain.shape == (6, 20, 30) + + def test_newaxis(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t[np.newaxis, :, :] + assert result.input_rank == 3 + assert result.domain.shape == (1, 10, 20) + assert result.output_rank == 2 + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].input_dimension == 1 + assert isinstance(result.output[1], DimensionMap) + assert result.output[1].input_dimension == 2 + + def test_int_out_of_bounds(self) -> None: + t = IndexTransform.from_shape((10,)) + with pytest.raises(IndexError): + t[10] + + def test_negative_int_is_literal(self) -> None: + """Negative indices are literal coordinates (TensorStore convention), + not 'from the end' like NumPy.""" + t = IndexTransform.from_shape((10,)) + with pytest.raises(IndexError): + t[-1] # -1 is out of bounds for domain [0, 10) + + def test_negative_int_valid_with_negative_origin(self) -> None: + """Negative index is valid if the domain includes negative coordinates.""" + domain = IndexDomain(inclusive_min=(-5,), exclusive_max=(5,)) + t = IndexTransform.identity(domain) + result = t[-3] + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == -3 + + def test_composition_of_slices(self) -> None: + """Slicing a sliced transform re-selects in literal domain coordinates.""" + t = IndexTransform.from_shape((100,)) + result = t[10:50][15:30] + assert result.domain.shape == (15,) + assert result.domain.origin == (15,) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == 0 + assert result.output[0].stride == 1 + + def test_composition_of_strides(self) -> None: + t = IndexTransform.from_shape((100,)) + result = t[::2][::3] + # t[::2] -> shape (50,), offset=0, stride=2 + # [::3] -> shape ceil(50/3)=17, offset=0, stride=2*3=6 + assert result.domain.shape == (17,) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].stride == 6 + + def test_bare_int(self) -> None: + """Non-tuple selection.""" + t = IndexTransform.from_shape((10, 20)) + result = t[3] + assert result.input_rank == 1 + + def test_bare_slice(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t[2:8] + assert result.domain.shape == (6, 20) + + @pytest.mark.parametrize( + ("mode", "selection", "expected_selection"), + [ + pytest.param("basic", IndexLike(2), 2, id="basic-scalar"), + pytest.param( + "basic", + slice(IndexLike(1), IndexLike(7), IndexLike(2)), + slice(1, 7, 2), + id="basic-slice-components", + ), + pytest.param("oindex", IndexLike(2), 2, id="orthogonal-scalar"), + pytest.param("vindex", IndexLike(2), 2, id="vectorized-scalar"), + ], + ) + def test_literal_selectors_support_the_index_protocol( + self, mode: str, selection: object, expected_selection: object + ) -> None: + transform = IndexTransform.from_shape((8,)) + if mode == "basic": + result = transform[selection] + expected = transform[expected_selection] + else: + result = getattr(transform, mode)[selection] + expected = getattr(transform, mode)[expected_selection] + + assert result == expected + + def test_literal_selector_rejects_int_only_objects(self) -> None: + with pytest.raises(IndexError, match="unsupported selection type"): + IndexTransform.from_shape((8,))[IntOnly()] + + def test_literal_selector_propagates_malformed_index_protocol(self) -> None: + with pytest.raises(TypeError, match="__index__ returned non-int"): + IndexTransform.from_shape((8,))[BadIndex()] + + def test_literal_slice_propagates_malformed_index_protocol(self) -> None: + with pytest.raises(TypeError, match="__index__ returned non-int"): + IndexTransform.from_shape((8,))[:: BadIndex()] + + +class TestBasicIndexingOnArrayMaps: + """When a transform already has ArrayMap outputs, basic indexing must + apply the corresponding operation to the index_array's axes.""" + + def test_int_on_array_map_drops_axis(self) -> None: + """Integer index on a dimension referenced by an ArrayMap should + index into the array on that axis.""" + arr = np.array([[10, 20], [30, 40], [50, 60]], dtype=np.intp) + # 2D input domain (3, 2), one ArrayMap output + t = IndexTransform( + domain=IndexDomain.from_shape((3, 2)), + output=(ArrayMap(index_array=arr),), + ) + # Index with int on dim 0 -> pick row 1 -> arr[1, :] = [30, 40] + result = t[1] + assert result.input_rank == 1 + assert result.domain.shape == (2,) + assert isinstance(result.output[0], ArrayMap) + np.testing.assert_array_equal(result.output[0].index_array, np.array([30, 40])) + + def test_slice_on_array_map(self) -> None: + """Slice on a dimension referenced by an ArrayMap should slice the array.""" + arr = np.array([10, 20, 30, 40, 50], dtype=np.intp) + t = IndexTransform( + domain=IndexDomain.from_shape((5,)), + output=(ArrayMap(index_array=arr),), + ) + result = t[1:4] + assert result.domain.shape == (3,) + assert isinstance(result.output[0], ArrayMap) + np.testing.assert_array_equal(result.output[0].index_array, np.array([20, 30, 40])) + + def test_strided_slice_on_array_map(self) -> None: + """Strided slice on ArrayMap should stride the array.""" + arr = np.array([10, 20, 30, 40, 50], dtype=np.intp) + t = IndexTransform( + domain=IndexDomain.from_shape((5,)), + output=(ArrayMap(index_array=arr),), + ) + result = t[::2] + assert result.domain.shape == (3,) + assert isinstance(result.output[0], ArrayMap) + np.testing.assert_array_equal(result.output[0].index_array, np.array([10, 30, 50])) + + def test_newaxis_on_array_map(self) -> None: + """Newaxis should insert an axis in the index_array.""" + arr = np.array([10, 20, 30], dtype=np.intp) + t = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(index_array=arr),), + ) + result = t[np.newaxis, :] + assert result.input_rank == 2 + assert result.domain.shape == (1, 3) + assert isinstance(result.output[0], ArrayMap) + assert result.output[0].index_array.shape == (1, 3) + np.testing.assert_array_equal(result.output[0].index_array, np.array([[10, 20, 30]])) + + def test_int_drops_one_of_two_array_dims(self) -> None: + """2D array map, int on dim 0, slice on dim 1.""" + arr = np.array([[10, 20, 30], [40, 50, 60]], dtype=np.intp) + t = IndexTransform( + domain=IndexDomain.from_shape((2, 3)), + output=(ArrayMap(index_array=arr),), + ) + result = t[0, 1:3] + assert result.input_rank == 1 + assert result.domain.shape == (2,) + assert isinstance(result.output[0], ArrayMap) + # arr[0, 1:3] = [20, 30] + np.testing.assert_array_equal(result.output[0].index_array, np.array([20, 30])) + + +class TestIndexTransformOindex: + def test_oindex_int_array(self) -> None: + t = IndexTransform.from_shape((10, 20)) + idx = np.array([1, 3, 5], dtype=np.intp) + result = t.oindex[idx, :] + assert result.input_rank == 2 + assert result.domain.shape == (3, 20) + assert isinstance(result.output[0], ArrayMap) + # Full input rank: the array varies along its own axis (0), singleton on 1. + assert result.output[0].index_array.shape == (3, 1) + np.testing.assert_array_equal(result.output[0].index_array, idx.reshape(3, 1)) + assert result.output[0].offset == 0 + assert result.output[0].stride == 1 + assert isinstance(result.output[1], DimensionMap) + assert result.output[1].input_dimension == 1 + + def test_oindex_bool_array(self) -> None: + t = IndexTransform.from_shape((5,)) + mask = np.array([True, False, True, False, True]) + result = t.oindex[mask] + assert result.domain.shape == (3,) + assert isinstance(result.output[0], ArrayMap) + np.testing.assert_array_equal( + result.output[0].index_array, np.array([0, 2, 4], dtype=np.intp) + ) + + def test_oindex_mixed(self) -> None: + t = IndexTransform.from_shape((10, 20)) + idx = np.array([2, 4], dtype=np.intp) + result = t.oindex[idx, 5:15] + assert result.input_rank == 2 + assert result.domain.shape == (2, 10) + # fancy dim: fresh zero-origin; slice dim: preserved literal coords + assert result.domain.origin == (0, 5) + assert isinstance(result.output[0], ArrayMap) + assert isinstance(result.output[1], DimensionMap) + assert result.output[1].offset == 0 + + def test_oindex_multiple_arrays(self) -> None: + t = IndexTransform.from_shape((10, 20, 30)) + idx0 = np.array([1, 3], dtype=np.intp) + idx1 = np.array([5, 10, 15], dtype=np.intp) + result = t.oindex[idx0, :, idx1] + assert result.input_rank == 3 + assert result.domain.shape == (2, 20, 3) + assert isinstance(result.output[0], ArrayMap) + assert isinstance(result.output[1], DimensionMap) + assert isinstance(result.output[2], ArrayMap) + + def test_oindex_multiple_arrays_preserves_independent_axes(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t.oindex[np.array([1, 3]), np.array([2, 4, 6])] + assert result.domain.shape == (2, 3) + assert isinstance(result.output[0], ArrayMap) + assert isinstance(result.output[1], ArrayMap) + assert result.output[0].index_array.shape == (2, 1) + assert result.output[1].index_array.shape == (1, 3) + + +class TestIndexTransformVindex: + def test_vindex_single_array(self) -> None: + t = IndexTransform.from_shape((10,)) + idx = np.array([1, 3, 5], dtype=np.intp) + result = t.vindex[idx] + assert result.input_rank == 1 + assert result.domain.shape == (3,) + assert isinstance(result.output[0], ArrayMap) + np.testing.assert_array_equal(result.output[0].index_array, idx) + + def test_vindex_broadcast(self) -> None: + t = IndexTransform.from_shape((10, 20)) + idx0 = np.array([[1, 2], [3, 4]], dtype=np.intp) + idx1 = np.array([[10, 11], [12, 13]], dtype=np.intp) + result = t.vindex[idx0, idx1] + assert result.input_rank == 2 + assert result.domain.shape == (2, 2) + assert isinstance(result.output[0], ArrayMap) + assert isinstance(result.output[1], ArrayMap) + np.testing.assert_array_equal(result.output[0].index_array, idx0) + np.testing.assert_array_equal(result.output[1].index_array, idx1) + + def test_vindex_with_slice(self) -> None: + t = IndexTransform.from_shape((10, 20, 30)) + idx = np.array([1, 3, 5], dtype=np.intp) + result = t.vindex[idx, :, :] + assert result.input_rank == 3 + assert result.domain.shape == (3, 20, 30) + assert isinstance(result.output[0], ArrayMap) + + def test_vindex_bool_mask(self) -> None: + t = IndexTransform.from_shape((5,)) + mask = np.array([True, False, True, False, True]) + result = t.vindex[mask] + assert result.domain.shape == (3,) + assert isinstance(result.output[0], ArrayMap) + + def test_vindex_multidimensional_boolean_list_mask(self) -> None: + result = IndexTransform.from_shape((2, 3)).vindex[ + [[True, False, True], [False, True, False]] + ] + + assert result.domain.shape == (3,) + np.testing.assert_array_equal( + result.apply_many(np.array([[0], [1], [2]], dtype=np.intp)), + np.array([[0, 0], [0, 2], [1, 1]], dtype=np.intp), + ) + + def test_vindex_broadcast_different_shapes(self) -> None: + t = IndexTransform.from_shape((10, 20)) + idx0 = np.array([1, 2, 3], dtype=np.intp) + idx1 = np.array([[10], [11]], dtype=np.intp) + result = t.vindex[idx0, idx1] + assert result.input_rank == 2 + assert result.domain.shape == (2, 3) + + def test_vindex_multiple_arrays_preserves_shared_axes(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t.vindex[np.array([1, 3]), np.array([2, 4])] + assert result.domain.shape == (2,) + assert isinstance(result.output[0], ArrayMap) + assert isinstance(result.output[1], ArrayMap) + assert result.output[0].index_array.shape == (2,) + assert result.output[1].index_array.shape == (2,) + + +@pytest.mark.parametrize("mode", ["oindex", "vindex"]) +def test_direct_advanced_index_rejects_float_arrays(mode: str) -> None: + helper = getattr(IndexTransform.from_shape((5,)), mode) + with pytest.raises(IndexError, match="integer or boolean"): + helper[np.array([1.9, 3.2])] + + +@pytest.mark.parametrize("mode", ["oindex", "vindex"]) +def test_direct_advanced_index_rejects_wrong_length_boolean_mask(mode: str) -> None: + helper = getattr(IndexTransform.from_shape((5,)), mode) + with pytest.raises(IndexError, match="boolean index.*dimension 5"): + helper[np.array([True, False])] + + +class TestSelectionToTransform: + def test_basic_slice(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t.select((slice(2, 8), slice(5, 15)), "basic") + assert result.domain.shape == (6, 10) + assert result.domain.origin == (2, 5) # preserved literal coordinates + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == 0 + + def test_basic_int(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t.select((3, slice(None)), "basic") + assert result.input_rank == 1 + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == 3 + + def test_basic_ellipsis(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t.select(Ellipsis, "basic") + assert result.domain.shape == (10, 20) + + def test_orthogonal(self) -> None: + t = IndexTransform.from_shape((10, 20)) + idx = np.array([1, 3, 5], dtype=np.intp) + result = t.select((idx, slice(None)), "orthogonal") + assert result.domain.shape == (3, 20) + assert isinstance(result.output[0], ArrayMap) + + def test_vectorized(self) -> None: + t = IndexTransform.from_shape((10, 20)) + idx0 = np.array([1, 3], dtype=np.intp) + idx1 = np.array([5, 7], dtype=np.intp) + result = t.select((idx0, idx1), "vectorized") + assert result.domain.shape == (2,) + assert isinstance(result.output[0], ArrayMap) + assert isinstance(result.output[1], ArrayMap) + + def test_composition_with_non_identity(self) -> None: + """Indexing a sliced transform uses literal domain coordinates. + + The slice [10:50] preserves its domain, so a follow-up [15:30] + re-selects coordinates 15..29 of the base (TensorStore semantics), and + the composed map stays the identity (out = in). + """ + t = IndexTransform.from_shape((100,))[10:50] + result = t.select(slice(15, 30), "basic") + assert (result.domain.inclusive_min, result.domain.exclusive_max) == ((15,), (30,)) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == 0 + assert result.output[0].stride == 1 + + +class TestIndexTransformIntersect: + def test_constant_inside(self) -> None: + t = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(ConstantMap(offset=5),), + ) + result = t.intersect(IndexDomain(inclusive_min=(0,), exclusive_max=(10,))) + assert result is not None + restricted, surviving = result + assert isinstance(restricted.output[0], ConstantMap) + assert restricted.output[0].offset == 5 + assert surviving is None + + def test_constant_outside(self) -> None: + t = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(ConstantMap(offset=5),), + ) + result = t.intersect(IndexDomain(inclusive_min=(10,), exclusive_max=(20,))) + assert result is None + + def test_dimension_partial(self) -> None: + """DimensionMap over [0,10) intersected with [5,15) narrows input to [5,10).""" + t = IndexTransform.from_shape((10,)) + result = t.intersect(IndexDomain(inclusive_min=(5,), exclusive_max=(15,))) + assert result is not None + restricted, surviving = result + assert restricted.domain.inclusive_min == (5,) + assert restricted.domain.exclusive_max == (10,) + assert surviving is None + + def test_dimension_no_overlap(self) -> None: + t = IndexTransform.from_shape((10,)) + result = t.intersect(IndexDomain(inclusive_min=(20,), exclusive_max=(30,))) + assert result is None + + def test_dimension_strided(self) -> None: + """stride=2, offset=1 over [0,5): storage 1,3,5,7,9. Chunk [4,8).""" + t = IndexTransform( + domain=IndexDomain.from_shape((5,)), + output=(DimensionMap(input_dimension=0, offset=1, stride=2),), + ) + result = t.intersect(IndexDomain(inclusive_min=(4,), exclusive_max=(8,))) + assert result is not None + restricted, _surviving = result + # input 2->5, input 3->7. Both in [4,8). + assert restricted.domain.inclusive_min == (2,) + assert restricted.domain.exclusive_max == (4,) + + @pytest.mark.parametrize( + ("input_domain", "output_domain", "output_map", "expected"), + [ + ( + (2**53, 2**53 + 3), + (2**53 + 1, 2**53 + 2), + DimensionMap(input_dimension=0), + (2**53 + 1, 2**53 + 2), + ), + ( + (-(2**53) - 2, -(2**53) + 1), + (-(2**53) - 1, -(2**53)), + DimensionMap(input_dimension=0), + (-(2**53) - 1, -(2**53)), + ), + ( + (-(2**53) - 2, -(2**53) + 1), + (2**53 + 1, 2**53 + 2), + DimensionMap(input_dimension=0, stride=-1), + (-(2**53) - 1, -(2**53)), + ), + ( + (2**53, 2**53 + 3), + (-(2**53) - 2, -(2**53) - 1), + DimensionMap(input_dimension=0, stride=-1), + (2**53 + 2, 2**53 + 3), + ), + ], + ids=[ + "positive-coordinates-positive-stride", + "negative-coordinates-positive-stride", + "positive-coordinates-negative-stride", + "negative-coordinates-negative-stride", + ], + ) + def test_dimension_intersection_is_exact_above_float_precision( + self, + input_domain: tuple[int, int], + output_domain: tuple[int, int], + output_map: DimensionMap, + expected: tuple[int, int], + ) -> None: + transform = IndexTransform( + domain=IndexDomain((input_domain[0],), (input_domain[1],)), + output=(output_map,), + ) + + result = transform.intersect(IndexDomain((output_domain[0],), (output_domain[1],))) + + assert result is not None + restricted, _surviving = result + assert restricted.domain == IndexDomain((expected[0],), (expected[1],)) + + def test_dimension_intersection_accepts_unbounded_python_integer_precision(self) -> None: + huge = 10**400 + transform = IndexTransform( + domain=IndexDomain((huge,), (huge + 2,)), + output=(DimensionMap(input_dimension=0),), + ) + + result = transform.intersect(IndexDomain((huge + 1,), (huge + 2,))) + + assert result is not None + restricted, _surviving = result + assert restricted.domain == IndexDomain((huge + 1,), (huge + 2,)) + + def test_array_partial(self) -> None: + arr = np.array([3, 8, 15, 22], dtype=np.intp) + t = IndexTransform( + domain=IndexDomain.from_shape((4,)), + output=(ArrayMap(index_array=arr),), + ) + result = t.intersect(IndexDomain(inclusive_min=(5,), exclusive_max=(20,))) + assert result is not None + restricted, surviving = result + assert isinstance(restricted.output[0], ArrayMap) + np.testing.assert_array_equal(restricted.output[0].index_array, np.array([8, 15])) + assert surviving is not None + np.testing.assert_array_equal(surviving, np.array([1, 2])) + + def test_array_none_inside(self) -> None: + arr = np.array([1, 2, 3], dtype=np.intp) + t = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=(ArrayMap(index_array=arr),), + ) + assert t.intersect(IndexDomain(inclusive_min=(10,), exclusive_max=(20,))) is None + + def test_2d_mixed(self) -> None: + """2D: ConstantMap on dim 0, DimensionMap on dim 1.""" + t = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=( + ConstantMap(offset=5), + DimensionMap(input_dimension=0, offset=0, stride=1), + ), + ) + chunk = IndexDomain(inclusive_min=(0, 5), exclusive_max=(10, 15)) + result = t.intersect(chunk) + assert result is not None + restricted, _ = result + assert isinstance(restricted.output[0], ConstantMap) + assert restricted.output[0].offset == 5 + assert isinstance(restricted.output[1], DimensionMap) + assert restricted.domain.inclusive_min == (5,) + assert restricted.domain.exclusive_max == (10,) + + +class TestIndexTransformTranslate: + def test_translate_constant(self) -> None: + t = IndexTransform( + domain=IndexDomain.from_shape((10,)), + output=(ConstantMap(offset=5),), + ) + result = t.translate((-5,)) + assert isinstance(result.output[0], ConstantMap) + assert result.output[0].offset == 0 + + def test_translate_dimension(self) -> None: + t = IndexTransform.from_shape((10,)) + result = t.translate((-3,)) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == -3 + assert result.output[0].stride == 1 + + def test_translate_array(self) -> None: + arr = np.array([5, 10], dtype=np.intp) + t = IndexTransform( + domain=IndexDomain.from_shape((2,)), + output=(ArrayMap(index_array=arr, offset=3),), + ) + result = t.translate((-3,)) + assert isinstance(result.output[0], ArrayMap) + assert result.output[0].offset == 0 + np.testing.assert_array_equal(result.output[0].index_array, arr) + + def test_translate_2d(self) -> None: + t = IndexTransform.from_shape((10, 20)) + result = t.translate((-5, -10)) + assert isinstance(result.output[0], DimensionMap) + assert result.output[0].offset == -5 + assert isinstance(result.output[1], DimensionMap) + assert result.output[1].offset == -10 + + +class TestArrayMapDependencyAxes: + """`ArrayMap.dependency_axes` derives the input axes an array varies on + from its (full-rank) shape: non-singleton axes vary, singleton axes do not.""" + + def test_orthogonal_single_axis(self) -> None: + t = IndexTransform.from_shape((10, 20)).oindex[np.array([1, 3]), np.array([2, 4, 6])] + m0, m1 = t.output[0], t.output[1] + assert isinstance(m0, ArrayMap) + assert isinstance(m1, ArrayMap) + assert m0.dependency_axes == (0,) + assert m1.dependency_axes == (1,) + + def test_vectorized_shares_axes(self) -> None: + t = IndexTransform.from_shape((10, 20)).vindex[np.array([1, 3]), np.array([2, 4])] + m0, m1 = t.output[0], t.output[1] + assert isinstance(m0, ArrayMap) + assert isinstance(m1, ArrayMap) + assert m0.dependency_axes == (0,) + assert m1.dependency_axes == (0,) + + def test_scalar_array_has_no_dependency(self) -> None: + assert ArrayMap(np.ones((1, 1), dtype=np.intp)).dependency_axes == () + + def test_zero_length_axis_has_no_dependency(self) -> None: + """An axis of size 0 carries no dependency either: it selects nothing, so + the array does not vary along it any more than along a singleton.""" + assert ArrayMap(np.zeros((0, 4), dtype=np.intp)).dependency_axes == (1,) + assert ArrayMap(np.zeros((3, 0), dtype=np.intp)).dependency_axes == (0,) + assert ArrayMap(np.zeros((0, 1), dtype=np.intp)).dependency_axes == () + + def test_zero_length_axis_does_not_make_a_map_correlated(self) -> None: + """An empty orthogonal selection is legal, so it must classify as one.""" + m = ArrayMap(index_array=np.zeros((0, 4), dtype=np.intp)) + assert m.dependent_axis == 1 + + +class TestIntersectArrayMapClassification: + """`_intersect` must distinguish orthogonal (outer-product) ArrayMaps from + correlated (vectorized) ones by their dependency axes, keep surviving arrays + at full input rank, and preserve residual (slice) dimensions.""" + + def test_orthogonal_outer_product_keeps_full_rank(self) -> None: + """Two arrays on distinct axes narrow independently and stay full rank; + out_indices is a per-output-dim dict of surviving positions.""" + t = IndexTransform.from_shape((10, 10)).oindex[np.array([1, 3, 8]), np.array([2, 6, 9])] + # Chunk covering storage [0,5) x [0,5): rows 1,3 survive (out pos 0,1), + # cols 2 survives (out pos 0). + chunk = IndexDomain(inclusive_min=(0, 0), exclusive_max=(5, 5)) + result = t.intersect(chunk) + assert result is not None + restricted, out_indices = result + assert isinstance(restricted.output[0], ArrayMap) + assert isinstance(restricted.output[1], ArrayMap) + # Full input rank preserved (not raveled to 1-D). + assert restricted.output[0].index_array.ndim == 2 + assert restricted.output[1].index_array.ndim == 2 + assert restricted.domain.ndim == 2 + assert isinstance(out_indices, dict) + np.testing.assert_array_equal(out_indices[0], np.array([0, 1])) + np.testing.assert_array_equal(out_indices[1], np.array([0])) + + def test_correlated_with_residual_slice_preserves_slice_dim(self) -> None: + """A vindex transform with two correlated arrays plus a residual slice + dim intersects without a rank error and keeps the DimensionMap.""" + t = IndexTransform.from_shape((4, 3, 5)).vindex[np.array([1, 3]), np.array([2, 0])] + # Chunk covering storage [0,2) x [2,3) x [0,5): only point (1,2,*) is in + # bounds on both array dims -> one surviving broadcast point. + chunk = IndexDomain(inclusive_min=(0, 2, 0), exclusive_max=(2, 3, 5)) + result = t.intersect(chunk) + assert result is not None + restricted, out_indices = result + # A DimensionMap for the residual slice dim survives (no post-init error). + assert any(isinstance(m, DimensionMap) for m in restricted.output) + assert out_indices is not None + + def test_length1_orthogonal_collapses_to_a_constant(self) -> None: + """A length-1 orthogonal array holds one coordinate: it is a ConstantMap. + + The length-1 axis stays in the domain, and the remaining genuine array + intersects orthogonally β€” a single survivor vector, not a joint gather. + """ + t = IndexTransform.from_shape((6, 6)).oindex[np.array([2]), np.array([1, 3, 5])] + assert isinstance(t.output[0], ConstantMap) + assert t.domain.shape == (1, 3) + chunk = IndexDomain(inclusive_min=(0, 0), exclusive_max=(6, 6)) + result = t.intersect(chunk) + assert result is not None + _restricted, out_indices = result + assert isinstance(out_indices, np.ndarray) + np.testing.assert_array_equal(out_indices, [0, 1, 2]) + + +class TestDerivedMapDependency: + """A map's `input_dimension` must describe the array it is built with. + + Three separate failures came from one stale value: a vectorized index applied + to an orthogonal map makes it correlated, but the old dependency was carried + onto the new array anyway. Readers fall back to that field when the shape + alone cannot say, so the wrong axis was believed much later β€” by a scatter + that filed positions under it, which is why the answer depended on how the + read was partitioned. + """ + + def test_a_vindex_over_a_fancy_view_is_marked_correlated(self) -> None: + base = np.arange(6) + view = ( + LazyArray(base) + .lazy.oindex[np.array([0, 1])] + .lazy.vindex[np.array([[0, 1, 0], [1, 0, 1]])] + ) + np.testing.assert_array_equal( + np.asarray(view.result()), base[[0, 1]][[[0, 1, 0], [1, 0, 1]]] + ) + + def test_the_same_view_resolves_alike_however_it_is_partitioned(self) -> None: + base = np.arange(36).reshape(6, 6) + + def build(array: LazyArray) -> LazyArray: + return array.lazy.oindex[np.array([-3, -6, -4]), -4].lazy.vindex[np.array([[-2, -3]])] + + unpartitioned = np.asarray(build(LazyArray(base)).result()) + partitioned = np.asarray(build(LazyArray(base).with_parts((3, 3))).result()) + np.testing.assert_array_equal(partitioned, unpartitioned) + np.testing.assert_array_equal(unpartitioned, np.array([[2, 20]])) + + def test_dependency_axes_are_read_from_the_shape(self) -> None: + """What a map varies over is its non-singleton axes β€” nothing else. + + The retired `input_dimension` field could contradict the array it rode + on; the shape cannot. + """ + t = IndexTransform( + domain=IndexDomain.from_shape((2, 3)), + output=( + ArrayMap(index_array=np.array([[0, 1, 2]], dtype=np.intp)), + ArrayMap(index_array=np.array([[0], [1]], dtype=np.intp)), + ), + ) + assert t.index_array_structure == "orthogonal" + + +def test_an_orthogonal_step_over_a_correlated_view_is_an_outer_product() -> None: + """`oindex` after `vindex` means the outer product, not a joint gather. + + The reindexing applied its index tuple positionally, which is NumPy's + *vectorized* rule, so two arrays collapsed into one axis and the result came + back a rank short of what was asked for. + """ + base = np.arange(14).reshape(7, 2) + view = LazyArray(base).lazy.vindex[ + np.array([[5, 5], [1, 2], [0, 4]]), np.array([[1, 1], [1, 0], [1, 0]]) + ] + result = np.asarray(view.lazy.oindex[np.array([1, 1, 0]), np.array([1, 1, 0, 1])].result()) + assert result.shape == (3, 4) + np.testing.assert_array_equal(result, np.array([[4, 4, 3, 4], [4, 4, 3, 4], [11, 11, 11, 11]])) + + +@pytest.mark.parametrize( + ("value", "description"), + [(1, "one below the lower bound"), (10, "the exclusive upper bound itself")], +) +def test_an_index_array_value_just_outside_the_domain_is_refused( + value: int, description: str +) -> None: + """The bound checks are probed at the boundary, not comfortably past it. + + Both were only ever exercised from well outside the domain, so relaxing + either by one β€” `lo - 1` instead of `lo` β€” went unnoticed while letting a + view read a cell it does not address. + """ + transform = IndexTransform.from_shape((12,))[2:10] + with pytest.raises(BoundsCheckError, match="out of bounds"): + transform.oindex[np.array([value, 3])] + + +def test_an_index_array_value_at_each_end_of_the_domain_is_accepted() -> None: + """The other side of the same boundary: the extremes themselves are in range.""" + transform = IndexTransform.from_shape((12,))[2:10] + array_map = transform.oindex[np.array([2, 9])].output[0] + assert isinstance(array_map, ArrayMap) + np.testing.assert_array_equal(array_map.index_array, np.array([2, 9])) + + +# --------------------------------------------------------------------------- +# Intersecting diagonal gathers +# --------------------------------------------------------------------------- + + +def test_intersecting_a_diagonal_gather_keeps_points_inside_the_domain() -> None: + """Index arrays sharing an input axis intersect pointwise, like vindex.""" + rows = np.array([4, 0, 2]) + cols = np.array([1, 5, 2]) + transform = IndexTransform( + domain=IndexDomain.from_shape((3,)), + output=( + ArrayMap(index_array=rows), + ArrayMap(index_array=cols), + ), + ) + + result = transform.intersect(IndexDomain(inclusive_min=(0, 0), exclusive_max=(3, 3))) + assert result is not None + restricted, survivors = result + # Only the point (2, 2) has both coordinates inside [0, 3) x [0, 3). + assert restricted.domain.shape == (1,) + assert isinstance(survivors, np.ndarray) + np.testing.assert_array_equal(survivors, [2]) + np.testing.assert_array_equal(restricted.apply((0,)), (2, 2)) + + assert transform.intersect(IndexDomain(inclusive_min=(0, 0), exclusive_max=(1, 1))) is None + + +def test_index_array_structure_classifies_the_three_shapes() -> None: + base = IndexTransform.from_shape((4, 6)) + assert (base[1:, ::2]).index_array_structure == "none" + assert (base.oindex[np.array([0, 2]), slice(None)]).index_array_structure == "orthogonal" + assert (base.vindex[np.array([0, 2]), np.array([1, 3])]).index_array_structure == "general" + diagonal = IndexTransform( + domain=IndexDomain.from_shape((2,)), + output=( + ArrayMap(index_array=np.array([0, 1])), + ArrayMap(index_array=np.array([2, 3])), + ), + ) + assert diagonal.index_array_structure == "general" diff --git a/packages/zarr-indexing/uv.lock b/packages/zarr-indexing/uv.lock new file mode 100644 index 0000000000..2687ba71d8 --- /dev/null +++ b/packages/zarr-indexing/uv.lock @@ -0,0 +1,769 @@ +version = 1 +revision = 3 +requires-python = ">=3.12" + +[[package]] +name = "babel" +version = "2.18.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/b2/51899539b6ceeeb420d40ed3cd4b7a40519404f9baf3d4ac99dc413a834b/babel-2.18.0.tar.gz", hash = "sha256:b80b99a14bd085fcacfa15c9165f651fbb3406e66cc603abf11c5750937c992d", size = 9959554, upload-time = "2026-02-01T12:30:56.078Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/77/f5/21d2de20e8b8b0408f0681956ca2c69f1320a3848ac50e6e7f39c6159675/babel-2.18.0-py3-none-any.whl", hash = "sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35", size = 10196845, upload-time = "2026-02-01T12:30:53.445Z" }, +] + +[[package]] +name = "backrefs" +version = "8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/56/4744bcd0c82184e80c52b0ac4076c261a8ffa1f1b343ff2f6e89ce0e1cef/backrefs-8.0.tar.gz", hash = "sha256:b556cd7d36c3a3a2f256b89590b176b8eddfb73bcfaee3a3ddd84ea66d21ce50", size = 7013081, upload-time = "2026-07-26T19:54:24.638Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e3/fd/9bf53b6a6f6f519ffaac765df2f2a25e5c2fc6d32cfd2b2747099e72c911/backrefs-8.0-py310-none-any.whl", hash = "sha256:4a627b817fd2dce43b79ab48da63613340509381cd8ce0897078a0bce79a2ab8", size = 380377, upload-time = "2026-07-26T19:54:17.457Z" }, + { url = "https://files.pythonhosted.org/packages/e1/29/4bd7ae72a2634da00379c2b3bcc5439e7c94620235c6afea8af15229a973/backrefs-8.0-py311-none-any.whl", hash = "sha256:f0c35cf0102ba6b6070c12a492be3c1c1d3f5839529784b9a9565d6d04569a01", size = 392169, upload-time = "2026-07-26T19:54:18.782Z" }, + { url = "https://files.pythonhosted.org/packages/29/13/232505664e8e2a0c7a2eb0c505cfade9d715538f89a5d62bc4c272968f62/backrefs-8.0-py312-none-any.whl", hash = "sha256:87f0fae8c5f207fe9f4b2887efc71d42f4900ac78faa1af08d675ef303692dc5", size = 398084, upload-time = "2026-07-26T19:54:19.954Z" }, + { url = "https://files.pythonhosted.org/packages/8a/69/47a3dc20abc4fa5486655fde681bd55e63211b46c886d8c02223d6468431/backrefs-8.0-py313-none-any.whl", hash = "sha256:601ce68ca12385dbda06ce264406b4c4210cf5b79fd0fd627592365c92f29a88", size = 400040, upload-time = "2026-07-26T19:54:21.194Z" }, + { url = "https://files.pythonhosted.org/packages/1c/cf/e5f9b68a5b0e939a2fb933a66c20180d0c9241bf8927f7a47fa48c1675e9/backrefs-8.0-py314-none-any.whl", hash = "sha256:9ec96efa080938be92323e8e730e57718c9c88eb15ad70bbef4e1766df591408", size = 411903, upload-time = "2026-07-26T19:54:23.221Z" }, +] + +[[package]] +name = "certifi" +version = "2026.7.22" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.4.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bd/2a/23f34ec9d04624958e137efdc394888716353190e75f25dd22c7a2c7a8aa/charset_normalizer-3.4.9.tar.gz", hash = "sha256:673611bbd43f0810bec0b0f028ddeaaa501190339cac411f347ac76917c3ae7b", size = 152439, upload-time = "2026-07-07T14:34:58.454Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/70/4a/ecbd131485c07fcdfad54e28946d513e3da22ef3b4bd854dcafae54ec739/charset_normalizer-3.4.9-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:45b0cc4e3556cd875e09102988d1ab8356c998b596c9fced84547c8138b487a0", size = 319300, upload-time = "2026-07-07T14:33:15.666Z" }, + { url = "https://files.pythonhosted.org/packages/ec/96/5d9364e3342d69f3a045e1777bc47c85c383e6e9466d561b33fdb419d1f9/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9b2aff1c7b3884512b9512c3eaadd9bab39fb45042ffaaa1dd08ff2b9f8109d9", size = 215802, upload-time = "2026-07-07T14:33:17.031Z" }, + { url = "https://files.pythonhosted.org/packages/4b/4c/5361f9aa7f2cb58d94f2ab831b3d493f69efb1d239654b4744e3c09527cb/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9104ed0bd76a429d46f9ec0dbc9b08ad1d2dcdf2b00a5a0daa1c145329b35b44", size = 237171, upload-time = "2026-07-07T14:33:18.576Z" }, + { url = "https://files.pythonhosted.org/packages/50/78/ce342ca4ff30b2eb49fe6d9578df85974f90c67d294113e94efdd9664cbd/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7b86a2b16095d250c6f58b3d9b2eee6f4147754344f3dab0922f7c9bf7d226c9", size = 233075, upload-time = "2026-07-07T14:33:20.084Z" }, + { url = "https://files.pythonhosted.org/packages/01/c4/4fa4c8b3097a11f3c5f09a35b72ed6855fb1d332469504962ab7bafcc702/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5e226f6218febc71f6c1fc2fafb91c226f75bdc1d8fb12d66823716e891608fd", size = 224256, upload-time = "2026-07-07T14:33:21.747Z" }, + { url = "https://files.pythonhosted.org/packages/87/3a/ad914516df7e358a81aae018caa5e0470ba827fa6d763b1d2e87d920a5f6/charset_normalizer-3.4.9-cp312-cp312-manylinux_2_31_armv7l.whl", hash = "sha256:90c44bc373b7687f6948b693cceaea1348ae0975d7474746559494468e3c1d84", size = 208784, upload-time = "2026-07-07T14:33:23.313Z" }, + { url = "https://files.pythonhosted.org/packages/d7/74/3c12f9755717dfe5c5c87da63f35d765fa0c00382ec26bf23f7fae34f2ba/charset_normalizer-3.4.9-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9cdef90ae47919cae358d8ab15797a800ed41da7aba5d72419fb510729e2ed4b", size = 219928, upload-time = "2026-07-07T14:33:24.814Z" }, + { url = "https://files.pythonhosted.org/packages/33/9a/895095b83e7907abd6d3d99aad3a38ad0d9686cc186cb0c94c24320fe63e/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:60f44ade2cf573dad7a277e6f8ca9a51a21dda572b13bd7d8539bb3cd5dbedde", size = 218489, upload-time = "2026-07-07T14:33:26.42Z" }, + { url = "https://files.pythonhosted.org/packages/a1/34/ef5c05f412f42520d7709b7d3784d19640839eb7366ded1755511585429f/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:a1786910334ed46ab1dd73222f2cd1e05c2c3bb39f6dddb4f8b36fc382058a39", size = 210267, upload-time = "2026-07-07T14:33:27.952Z" }, + { url = "https://files.pythonhosted.org/packages/83/dc/9b29fa4412b318bf3bfea985c35d67eb55e04b59a7c3f2237168b0e0be6f/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:03d07803992c6c7bbc976327f34b18b6160327fc81cb82c9d504720ac0be3b62", size = 226030, upload-time = "2026-07-07T14:33:29.397Z" }, + { url = "https://files.pythonhosted.org/packages/0e/42/6dbc00b8cd16011691203e33570fa42ed5746599a2e878112d16eab403a3/charset_normalizer-3.4.9-cp312-cp312-win32.whl", hash = "sha256:78841cccf1af7b40f6f716338d50c0902dbe88d9f800b3c973b7a9a0a693a642", size = 151185, upload-time = "2026-07-07T14:33:30.781Z" }, + { url = "https://files.pythonhosted.org/packages/80/cc/f920afd1a23c58ccd53c1d36085a71893a4737ff5e66e0371efab6809850/charset_normalizer-3.4.9-cp312-cp312-win_amd64.whl", hash = "sha256:4b3dac63058cc36820b0dd072f89898604e2d39686fe05321729d00d8ac185a0", size = 162557, upload-time = "2026-07-07T14:33:32.176Z" }, + { url = "https://files.pythonhosted.org/packages/f0/e6/0386d43a261ff4e4b30c5857af7df877254b46bec7b9d1b74b6bf969a90b/charset_normalizer-3.4.9-cp312-cp312-win_arm64.whl", hash = "sha256:78fa18e436a1a0e58dbd7e02fc4473f3f32cceb12df9dfca542d075961c307d2", size = 152665, upload-time = "2026-07-07T14:33:33.711Z" }, + { url = "https://files.pythonhosted.org/packages/b2/06/97ec2aeae780b31d742b6352218b43841a6871e2564578ca522dce4a45c3/charset_normalizer-3.4.9-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:440eede837960000d74978f0eba527be106b5b9aee0daf779d395276ed0b0614", size = 317688, upload-time = "2026-07-07T14:33:35.408Z" }, + { url = "https://files.pythonhosted.org/packages/d0/39/8ff066c672434225f8d25f8b739f992af250944392173dcc88362681c9bf/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:21e764fd1e70b6a3e205a0e46f3051701f98a8cb3fad66eeb80e48bb502f8698", size = 214982, upload-time = "2026-07-07T14:33:36.996Z" }, + { url = "https://files.pythonhosted.org/packages/92/8f/3a47a3667c83c2df9483d91644c6c107de3bf8874aa1793da9d3012eb986/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e4fd89cc178bced6ad29cb3e6dd4aa63fa5017c3524dbd0b25998fb64a87cc8b", size = 236460, upload-time = "2026-07-07T14:33:38.536Z" }, + { url = "https://files.pythonhosted.org/packages/f1/60/b22cdbee7e4013dab8b0d7647fc6181120fbbbc8f7025c226d15bd5a47fc/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bd47ba7fc3ca94896759ea0109775132d3e7ab921fbf54038e1bab2e46c313c9", size = 232003, upload-time = "2026-07-07T14:33:40.059Z" }, + { url = "https://files.pythonhosted.org/packages/ea/f8/72eb13dcabe7257035cea8aefd922caad2f110d252bf9f67c4c2ca763aee/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:84fd18bcc17526fc2b3c1af7d2b9217d32c9c04448c16ec693b9b4f1985c3d33", size = 223149, upload-time = "2026-07-07T14:33:41.631Z" }, + { url = "https://files.pythonhosted.org/packages/b0/3e/faee8f9de92b14ee1198e9163252bb15efee7301b31256a3b6d9ebfdd0dd/charset_normalizer-3.4.9-cp313-cp313-manylinux_2_31_armv7l.whl", hash = "sha256:5b10cd92fc5c498b35a8635df6d5a100207f88b63a4dc1de7ef9a548e1e2cd63", size = 207901, upload-time = "2026-07-07T14:33:43.209Z" }, + { url = "https://files.pythonhosted.org/packages/3a/25/45f30093ae27dd7b92a793b61882a38685f993700113ca36e0c9c14965e1/charset_normalizer-3.4.9-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a4fbdde9dd4a9ce5fd52c2b3a347bb50cc89483ef783f1cb00d408c13f7a96c0", size = 219176, upload-time = "2026-07-07T14:33:44.725Z" }, + { url = "https://files.pythonhosted.org/packages/48/18/c8f397329c35e32f6a837e488986f4ae03bd2abebc453b48714991630c2f/charset_normalizer-3.4.9-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:416c229f77e5ea25b3dfd4b582f8d73d7e43c22320302b9ab128a2d3a0b38efe", size = 217356, upload-time = "2026-07-07T14:33:46.192Z" }, + { url = "https://files.pythonhosted.org/packages/86/7e/5ce0bba863470fd1902d5e5843968951bddf38abe4742fc97116ef4598b3/charset_normalizer-3.4.9-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:75286256590a6320cf106a0d28970d3560aad9ee09aa7b34fb40524792436d35", size = 209614, upload-time = "2026-07-07T14:33:47.705Z" }, + { url = "https://files.pythonhosted.org/packages/6c/ef/2473d3c4d869155be4af1191111d59c4d5c4e0173026f7e85b176e23bf65/charset_normalizer-3.4.9-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:69b157c5d3292bcd443faca052f3096f637f1e074b98212a933c074ae23dc3b8", size = 224991, upload-time = "2026-07-07T14:33:49.238Z" }, + { url = "https://files.pythonhosted.org/packages/d0/a3/53ddae3db108a088156aa8ddfafd411ebbc1340f48c5573f697b27f69a39/charset_normalizer-3.4.9-cp313-cp313-win32.whl", hash = "sha256:51307f5c71007673a2bf8232ad973483d281e74cb99c8c5a990af1eefa6277d9", size = 150622, upload-time = "2026-07-07T14:33:50.711Z" }, + { url = "https://files.pythonhosted.org/packages/e8/ef/6953a77c7cf2c2ff9998e6f575ab3e380119f100223381565a4f94c1f836/charset_normalizer-3.4.9-cp313-cp313-win_amd64.whl", hash = "sha256:fe2c7201c642b7c308f1675355ad7ff7b66acfe3541625efe5a3ad38f29d6115", size = 161947, upload-time = "2026-07-07T14:33:52.197Z" }, + { url = "https://files.pythonhosted.org/packages/6e/fb/d560d1d1555debbfe7849d9cac6145c1b537709d79576bf22557ed803b82/charset_normalizer-3.4.9-cp313-cp313-win_arm64.whl", hash = "sha256:611057cc5d5c0afc743ba8be6bd828c17e0aaa8643f9d0a9b9bb7dea80eb8012", size = 152594, upload-time = "2026-07-07T14:33:53.486Z" }, + { url = "https://files.pythonhosted.org/packages/7e/8d/496817fa0944239ecae662dd57ea765cfeaec6a735f9f025d4b7b72e7143/charset_normalizer-3.4.9-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:0327fcd59a935777d83410750c50600ee9571af2846f71ce40f25b13da1ef380", size = 317253, upload-time = "2026-07-07T14:33:54.994Z" }, + { url = "https://files.pythonhosted.org/packages/2b/f9/ef4a69ea338ad3c0deceea0f5f7d2380ae8b52132b06d652cb0d2cd86706/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8a79d9f4d8001473a30c163556b3c3bfebec837495a412dde78b51672f6134f9", size = 215898, upload-time = "2026-07-07T14:33:56.334Z" }, + { url = "https://files.pythonhosted.org/packages/8c/e7/5ddfd76fc061eb52de219658a4aa431cbacadf0a0219c8854f00da50d289/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:33bdcc2a32c0a0e861f60841a512c8acc658c87c2ac59d89e3a46dacf7d866e4", size = 236718, upload-time = "2026-07-07T14:33:57.9Z" }, + { url = "https://files.pythonhosted.org/packages/49/ba/768fa3f36048d81c477a0ce61f813bc1454d80917ccfe550abd9f44f5e24/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f840ed6d8ecba8255df8c42b87fadeda98ddfc6eeec05e2dc66e26d46dd6f58a", size = 232519, upload-time = "2026-07-07T14:33:59.811Z" }, + { url = "https://files.pythonhosted.org/packages/f4/c4/b3e049d2aa3766180c78507110543d9d50894cc97f57de543f1be521dcdc/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c25fe15c70c59eb7c5ce8c06a1f3fa1da0ecc5ea1e7a5922c40fd2fa9b0d5046", size = 223143, upload-time = "2026-07-07T14:34:01.517Z" }, + { url = "https://files.pythonhosted.org/packages/19/79/55c32d06d76ae4feafe053f061f3e3ab70bcf19f4007797ce8c3efda7830/charset_normalizer-3.4.9-cp314-cp314-manylinux_2_31_armv7l.whl", hash = "sha256:f7fb7d750cfa0a070d2c24e831fd3481019a60dd317ea2b39acbcebc08b6ed81", size = 206742, upload-time = "2026-07-07T14:34:03.04Z" }, + { url = "https://files.pythonhosted.org/packages/10/e0/47c079dd82d217c807479cd59ffd30af56307ea31c108b75758970459ad3/charset_normalizer-3.4.9-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4d1c96a7a18b9690a4d46df09e3e3382406ae3213727cd1019ebade1c4a81917", size = 219191, upload-time = "2026-07-07T14:34:04.657Z" }, + { url = "https://files.pythonhosted.org/packages/42/ab/b9bc2e77d6b44a7e46ef62ec5cac1c9a6ba7b9135a5d560f002696ec9995/charset_normalizer-3.4.9-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a4cfde78a9f2880208d16a93b795726a3017d5977e08d1e162a7a31322479c41", size = 218328, upload-time = "2026-07-07T14:34:06.115Z" }, + { url = "https://files.pythonhosted.org/packages/f1/78/c9c71d599f5aa2d42bcdd35cbbd46d7f535351a57e40ff7d8e5a7e219401/charset_normalizer-3.4.9-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:d4d6fcde76f94f5cb9e43e9e9a61f16dacefd228cbbf6f1a09bd9b219a92f1a1", size = 207406, upload-time = "2026-07-07T14:34:07.554Z" }, + { url = "https://files.pythonhosted.org/packages/f6/39/c914445c321a845097ce4f6ac7de9a18228a77b766272125a1ce00d851eb/charset_normalizer-3.4.9-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:898f0e9068ca27d37f8e83a5b962821df851532e6c4a7d615c1c033f9da6eedf", size = 225157, upload-time = "2026-07-07T14:34:09.061Z" }, + { url = "https://files.pythonhosted.org/packages/9b/f2/c0d4b8508565a36bc5c624e88ed297f5b0b1095011034d7f5b83a69908b5/charset_normalizer-3.4.9-cp314-cp314-win32.whl", hash = "sha256:c1c948747b03be832dceed96ca815cef7360de9aa19d37c730f8e3f6101aca48", size = 151095, upload-time = "2026-07-07T14:34:10.901Z" }, + { url = "https://files.pythonhosted.org/packages/49/fd/a1d26144398c67486422a72bf5812cda22cb4ccfcd95a290fb41ceb4b8e2/charset_normalizer-3.4.9-cp314-cp314-win_amd64.whl", hash = "sha256:16b65ea0f2465b6fb52aa22de5eca612aa964ddfec00a912e26f4656cbef890b", size = 162796, upload-time = "2026-07-07T14:34:12.47Z" }, + { url = "https://files.pythonhosted.org/packages/20/95/d75e82f8ce9fd323ebf059c16c9aadefb22a1ecde13b7840b35835e4886c/charset_normalizer-3.4.9-cp314-cp314-win_arm64.whl", hash = "sha256:40a126142a56b2dfc0aacbad1de8310cbf60da7656db0e6b16eebd48e3e93519", size = 153334, upload-time = "2026-07-07T14:34:14.044Z" }, + { url = "https://files.pythonhosted.org/packages/00/5e/17398df3a139985ba9d11ed072531986f408c8fca952835ef1ab1820c02b/charset_normalizer-3.4.9-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:609b3ba8fcc0fb5ab7af00719d0fb6ad0cb518e48e7712d12fd68f1327951198", size = 338848, upload-time = "2026-07-07T14:34:15.688Z" }, + { url = "https://files.pythonhosted.org/packages/cd/91/7253a32e86b7e1d1239b1b36ba6dd0f021a21107ab33054b53119cc083b9/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:51447e9aa2684679af07ca5021c3db526e0284347ebf4ffcec1154c3350cfe32", size = 223022, upload-time = "2026-07-07T14:34:17.248Z" }, + { url = "https://files.pythonhosted.org/packages/cb/32/2e64bd2be10e89c61e57ebe6a93fd98ae88eb7ebe414b5121f22c96c69eb/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cc1b0fff8ead343dae06305f954eb8468ba0ec1a97881f42489d198e4ce3c632", size = 241590, upload-time = "2026-07-07T14:34:18.813Z" }, + { url = "https://files.pythonhosted.org/packages/3d/ef/d96ec496cfea0c21db43b0ad03891308b02388d054cc902cf0e5a1ad6a88/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fa36ec09ef71d158186bc79e359ff5fdd6e7996fe8ab638f00d6b93139ba4fcf", size = 239584, upload-time = "2026-07-07T14:34:20.52Z" }, + { url = "https://files.pythonhosted.org/packages/d4/ce/9af95f7876194bd7a14e3dfe4a4de2e0bff02666a3910d72beafd06cc297/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:df115d4d83168fdf2cae48ef1ff6d1cb4c466364e30861b37121de0f3bf1b990", size = 230224, upload-time = "2026-07-07T14:34:22.189Z" }, + { url = "https://files.pythonhosted.org/packages/52/94/af74dde74a3996bd959c350709bfe50e297823d70a8c1cbd54b838880863/charset_normalizer-3.4.9-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:f86c6358749bd4fda175388691e3ba8c46e24c5347d0afd20f9b7edfc9faf07d", size = 212667, upload-time = "2026-07-07T14:34:23.857Z" }, + { url = "https://files.pythonhosted.org/packages/ee/f0/f1c4fe746c395922961b5916ed1d7d6e7d4c84851d19ed43cc89980ec953/charset_normalizer-3.4.9-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:32286a2c8d167e897177b673176c1e3e00d4057caf5d2b64eef9a3666b03018e", size = 227179, upload-time = "2026-07-07T14:34:25.586Z" }, + { url = "https://files.pythonhosted.org/packages/e4/56/6c745619ac397e8871e2bcd3cea1eec86b877488f33888b3aef5c3ed506e/charset_normalizer-3.4.9-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:83aed2c10721ddd90f68140685391b50811a880af20654c59af6b6c66c40513c", size = 225372, upload-time = "2026-07-07T14:34:27.212Z" }, + { url = "https://files.pythonhosted.org/packages/78/ad/98aae8630ac71f16711968e38a5acfecce41b778bf2f0312851020f565a8/charset_normalizer-3.4.9-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:cd6c3d4b783c556fa00bf540854e42f135e2f256abd29669fcd0da0f2dec79c2", size = 215222, upload-time = "2026-07-07T14:34:28.774Z" }, + { url = "https://files.pythonhosted.org/packages/f7/40/9593d54209765207a7f11073c06494c1721e4ca4a0a426c597679bf7f91e/charset_normalizer-3.4.9-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ee2f2a527e3c1a6e6411eb4209642e138b544a2d72fe5d0d76daf77b24063534", size = 231958, upload-time = "2026-07-07T14:34:30.345Z" }, + { url = "https://files.pythonhosted.org/packages/b1/27/693ee5e8a18191eb38647360c51cd505013e2bd3b366aa43fd5344c21e3c/charset_normalizer-3.4.9-cp314-cp314t-win32.whl", hash = "sha256:0d861473f743244d349b50f850d10eb87aeb22bbdcc8e64f79273c94af5a8226", size = 155580, upload-time = "2026-07-07T14:34:31.884Z" }, + { url = "https://files.pythonhosted.org/packages/80/3f/bd97d3d9c613013d07cb7733d299385b41df37f0471310f5a73dc359f0b8/charset_normalizer-3.4.9-cp314-cp314t-win_amd64.whl", hash = "sha256:9b8e0f3107e2200b76f6054de99016eac3ee6762713587b36baaa7e4bd2ae177", size = 167620, upload-time = "2026-07-07T14:34:33.438Z" }, + { url = "https://files.pythonhosted.org/packages/3d/c6/eee9dca4439b1061f76373f06ea855678cc4a64c1c3c90b50e479edbb8eb/charset_normalizer-3.4.9-cp314-cp314t-win_arm64.whl", hash = "sha256:19ac87f93086ce37b86e098888555c4b4bc48102279bae3350098c0ed664b501", size = 158037, upload-time = "2026-07-07T14:34:35.018Z" }, + { url = "https://files.pythonhosted.org/packages/98/2b/f97f1c193fb855c345d678f5077d6926034db0722df74c8f057020e05a25/charset_normalizer-3.4.9-py3-none-any.whl", hash = "sha256:68e5f26a1ad57ded6d1cfb85331d1c1a195314756471d97758c48498bb4dcdf5", size = 64538, upload-time = "2026-07-07T14:34:56.993Z" }, +] + +[[package]] +name = "click" +version = "8.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/76/d4/81420972a676e8ffea40450d8c8c92943e7218a78fe9b64359836cc9876b/click-8.4.2.tar.gz", hash = "sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6", size = 338000, upload-time = "2026-06-24T17:45:15.148Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/e2/79c688af8b210d232694e31e59da9f6ec747bae31c3f5946e4e9b98860d5/click-8.4.2-py3-none-any.whl", hash = "sha256:e6f9f66136c816745b9d65817da91d61d957fb16e02e4dcd0552553c5a197b76", size = 119243, upload-time = "2026-06-24T17:45:13.73Z" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "ghp-import" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d9/29/d40217cbe2f6b1359e00c6c307bb3fc876ba74068cbab3dde77f03ca0dc4/ghp-import-2.1.0.tar.gz", hash = "sha256:9c535c4c61193c2df8871222567d7fd7e5014d835f97dc7b7439069e2413d343", size = 10943, upload-time = "2022-05-02T15:47:16.11Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f7/ec/67fbef5d497f86283db54c22eec6f6140243aae73265799baaaa19cd17fb/ghp_import-2.1.0-py3-none-any.whl", hash = "sha256:8337dd7b50877f163d4c0289bc1f1c7f127550241988d568c1db512c4324a619", size = 11034, upload-time = "2022-05-02T15:47:14.552Z" }, +] + +[[package]] +name = "griffe-inherited-docstrings" +version = "1.1.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "griffelib" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cb/da/fd002dc5f215cd896bfccaebe8b4aa1cdeed8ea1d9d60633685bd61ff933/griffe_inherited_docstrings-1.1.3.tar.gz", hash = "sha256:cd1f937ec9336a790e5425e7f9b92f5a5ab17f292ba86917f1c681c0704cb64e", size = 26738, upload-time = "2026-02-21T09:38:44.312Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/16/20/4bc15f242181daad1c104e0a7d33be49e712461ea89e548152be0365b9ea/griffe_inherited_docstrings-1.1.3-py3-none-any.whl", hash = "sha256:aa7f6e624515c50d9325a5cfdf4b2acac547f1889aca89092d5da7278f739695", size = 6710, upload-time = "2026-02-20T11:06:38.75Z" }, +] + +[[package]] +name = "griffelib" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/e4/8d187ea29c2e30b3a09505c567513077d6117861bde1fbd997a167f262ec/griffelib-2.1.0.tar.gz", hash = "sha256:762a186d2c6fd6794d4ea20d428d597ffb857cb56b66421651cbba15bdd5e813", size = 216234, upload-time = "2026-06-19T12:05:42.278Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e4/d3/5268aeabf2ad82658c4e2ff3a060648d0f02f3926cb53247c0e4d0dab49e/griffelib-2.1.0-py3-none-any.whl", hash = "sha256:cc7b3d2d2865ad0b909fcc38086e3f554b5ea7acbaa7bbb7ecaa3f5dfb7d9f00", size = 142560, upload-time = "2026-06-19T12:05:38.742Z" }, +] + +[[package]] +name = "hypothesis" +version = "6.164.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sortedcontainers" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7a/ac/7b76103bd74d8457e4de0c6a6c3a26ac6327016438bde125e0a3de83a5b8/hypothesis-6.164.0.tar.gz", hash = "sha256:5d63d263d8c71b571638c18d9591f6e34b836c60a12469e9d9105c1c785f00f1", size = 492022, upload-time = "2026-07-30T12:39:49.085Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7c/fe/d5b75a55892b33e72945f82efc71f645d29c0bfdb9f00727f7535a52edcc/hypothesis-6.164.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:14b861ac3353f8643b82a3ba76b8a0a54d2a06160c32b9a1f64a8ab41b179089", size = 771561, upload-time = "2026-07-30T12:39:00.404Z" }, + { url = "https://files.pythonhosted.org/packages/1c/b0/2f01e9efc7267446bad0e2a68f7472daa174a72553d213b16aefe44b2bda/hypothesis-6.164.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:3d8c8bb00a4b86ae90b9ad41f3e1c99d016ec3e64c0ff9d676a4bb7be4f56948", size = 767079, upload-time = "2026-07-30T12:39:23.123Z" }, + { url = "https://files.pythonhosted.org/packages/c3/26/d7bcd26b58e1df2bd39116b924b2a72676215d9650e68cbff9a629c3ce30/hypothesis-6.164.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e80e3ba8eaf37664eaa0f2625cef120b330b128a7df570210cf8be4f5ae65aaa", size = 1096364, upload-time = "2026-07-30T12:38:49.972Z" }, + { url = "https://files.pythonhosted.org/packages/9d/17/99fe7ea866935da83444c3ef7885a14fc7349d96ff61c6faebd37ef4edf2/hypothesis-6.164.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8cdf70f821e2d2f3a0bccaab29830aea8aefb63a77806e7e91246fb65a10c8d3", size = 1124963, upload-time = "2026-07-30T12:39:13.1Z" }, + { url = "https://files.pythonhosted.org/packages/38/e8/df08be6296cbc1271d44e81f8ff9dcd6267a07552fb768e0fdc166e93d40/hypothesis-6.164.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bcc3743e22b3cffa7267b4bc74d03628606e4a115495728e986a7be220987315", size = 1145886, upload-time = "2026-07-30T12:39:45.612Z" }, + { url = "https://files.pythonhosted.org/packages/4e/72/d5cf6fbfac40891d4281f630e16a6eb217ff56f97e350a06e0fd9322aa6a/hypothesis-6.164.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:730f09d4afcd8a918b3d589bfb6421e3b41c057aa57652a773ef4f512cc60836", size = 1101181, upload-time = "2026-07-30T12:39:05.194Z" }, + { url = "https://files.pythonhosted.org/packages/fb/ff/7ceb002329febffb678b65835ca6e9479a916325d088aadb0210d07f8252/hypothesis-6.164.0-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:9651cb48cb5a995295b442138d15d381547b935dcb0066fca7148a7955347400", size = 1137970, upload-time = "2026-07-30T12:39:16.076Z" }, + { url = "https://files.pythonhosted.org/packages/7c/8f/c12c697b73ca9ca24d8a913879e3e0a9db86479754c7221554247c701565/hypothesis-6.164.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:51d161d2655dd86143b370c577267b5b7b4c2e8fcb8a3f22c1a787572aad707c", size = 1270184, upload-time = "2026-07-30T12:38:54.436Z" }, + { url = "https://files.pythonhosted.org/packages/0e/2f/93f1c850c794fc9c80f5e61b3b20652126b865e6f57b348ae530446aadc7/hypothesis-6.164.0-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:e8a250552390128b57e3afe55035ce2c2cb1f6f0919817657854244f071bc5be", size = 1397987, upload-time = "2026-07-30T12:38:21.113Z" }, + { url = "https://files.pythonhosted.org/packages/c5/b8/bab2546325e15e87c8518dfbca263c81dbc35d566c516d66c9da98a38b77/hypothesis-6.164.0-cp310-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:570cd51944e1cc3443847d8afa3d17fcf8aac475a1f744c9e7318a5ad7ef5c9f", size = 1270755, upload-time = "2026-07-30T12:38:51.571Z" }, + { url = "https://files.pythonhosted.org/packages/6a/4e/ea97dd39678a42dc5a24e3e2a64d3b950fad9fb1dcce8d7be5afb52a0335/hypothesis-6.164.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:3a423e543055b3de5af7a7624c4285422541658367211fa293a3a57dd0ad01ba", size = 1312888, upload-time = "2026-07-30T12:38:30.847Z" }, + { url = "https://files.pythonhosted.org/packages/44/84/a6f2d5b12b23d65f16eb398750e430065f9d1f40f4418569e3b87ef58d23/hypothesis-6.164.0-cp310-abi3-win32.whl", hash = "sha256:f5e51490b2ce64c66138f24477d83c71b6224ab0ef65700da10187c464b54e94", size = 657401, upload-time = "2026-07-30T12:39:11.581Z" }, + { url = "https://files.pythonhosted.org/packages/f5/d3/c5ee410daa594cac2d3fe1fbe5473f2390e35f4369e168a817e43341ce2f/hypothesis-6.164.0-cp310-abi3-win_amd64.whl", hash = "sha256:c9059dfbb039342b6590bbce207f90e0f9a80fdf45a404c68c2d3e598be78ab3", size = 663566, upload-time = "2026-07-30T12:39:30.27Z" }, + { url = "https://files.pythonhosted.org/packages/90/91/4942fe3f2f08b920368ed5a2937346259e843e382205513b4a0e70d2de9d/hypothesis-6.164.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:6bc3373fe550cf4d7cadb94ceaeb91e431e1418a96b7baa330487366eaa67d3c", size = 773152, upload-time = "2026-07-30T12:38:33.328Z" }, + { url = "https://files.pythonhosted.org/packages/eb/df/e66d052386a2b6c3e2f3eab32a02d7de3c9c59cd21d5dd58c08ecfa715f0/hypothesis-6.164.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2780297ca68929b153eff7effb2ebe67e9487d2fd9f49fa961007f8f2d236c9e", size = 764713, upload-time = "2026-07-30T12:38:48.59Z" }, + { url = "https://files.pythonhosted.org/packages/f5/d5/5a50d14b8f04809e973c4dea884b367fef3663ff253c1205fa9e96229ef9/hypothesis-6.164.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6b400bb4eb5a4a1e19cd5af3cc63817909e6b54b4603e04022bdba46860913d7", size = 1095160, upload-time = "2026-07-30T12:38:58.925Z" }, + { url = "https://files.pythonhosted.org/packages/58/01/781b19ce4382ec239c4dc6ec3bd9f195e69e5570f2814bbf04b5781ecb18/hypothesis-6.164.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7fca6632933fc506dd96926d9383483e4c0066c7ff62c748d059a3276da761e7", size = 1145199, upload-time = "2026-07-30T12:39:09.904Z" }, + { url = "https://files.pythonhosted.org/packages/e9/64/30e016863515ca01c1c738b05dd50491353d3ccae6432362e56e0c15d0da/hypothesis-6.164.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b9e1f6e89e5ec34735b727f3ce41d12e7f3b8efc162c91c8a225e10b54b504b4", size = 1267980, upload-time = "2026-07-30T12:38:18.733Z" }, + { url = "https://files.pythonhosted.org/packages/84/23/17eb8d67d59ecd3a820c905fbdf514e371dd7d01631e62a304cdd5793abe/hypothesis-6.164.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:51b0f967f608707b24ed37a298174ae6eec7899bfe3f271d1c3062c39ad66c06", size = 1312181, upload-time = "2026-07-30T12:38:36.056Z" }, + { url = "https://files.pythonhosted.org/packages/42/69/cff9f3cd9524252adda7c8e0e129dfc176e72f64fdf0bf1552d1ea43d78d/hypothesis-6.164.0-cp312-cp312-win_amd64.whl", hash = "sha256:5770df7d518bf867a9379e9081abd9e44db1d15473430e26a0946438c08c5926", size = 660690, upload-time = "2026-07-30T12:38:28.107Z" }, + { url = "https://files.pythonhosted.org/packages/ba/b4/729697380a22dc2ce8feae3c64b08bf3bd3c27e99c3706cb9bdac40c6fc8/hypothesis-6.164.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:29e7cb48974cb9fd87602e20625c890385793c6b56c18a957085a9c291f56ef8", size = 773046, upload-time = "2026-07-30T12:39:40.473Z" }, + { url = "https://files.pythonhosted.org/packages/38/35/72374f02d90dfda198afd8aac6b1e7d1184506f97e62ebcf3d2c1e5bf761/hypothesis-6.164.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:1ff8c3819345be8dd15ee6588ee9383869a54c9a3d2232cce5e26b456424135d", size = 764659, upload-time = "2026-07-30T12:38:55.896Z" }, + { url = "https://files.pythonhosted.org/packages/6e/75/fb26388915d71e5949b98ccd0c9d95edcbe6b45d0370f177d43633d81ae2/hypothesis-6.164.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:33e88be13fac3ff7cb789a0b4cc43d99fb297db085f529fbb363188141c7d5bf", size = 1095078, upload-time = "2026-07-30T12:38:34.677Z" }, + { url = "https://files.pythonhosted.org/packages/be/63/f6da6e39667d39a1e44c5df82fbe6cff070c29aaffa9beb62a5322e7d8ae/hypothesis-6.164.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d2e296d03a77355ce2e1c32e85a636b555edf0ddaaef277f98f1b84fe38a4595", size = 1145015, upload-time = "2026-07-30T12:39:26.487Z" }, + { url = "https://files.pythonhosted.org/packages/88/c7/55ba09727da3d9a60628c50e31e6083a36f403cb230f5e1a7bd1749a5c39/hypothesis-6.164.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:53698a1b246714539dd0ecc2d556cde613d74e9f7385ec4109e0651ab2d382d6", size = 1268027, upload-time = "2026-07-30T12:38:25.676Z" }, + { url = "https://files.pythonhosted.org/packages/ff/35/4789cade332f799b0e8f2f7ea0fe2aae6157a85e60f74497e316dd17a7e3/hypothesis-6.164.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:004c92c4b869f8e258f0641101b7743cae8420436f4465383f681c086ef95c9d", size = 1311895, upload-time = "2026-07-30T12:39:14.621Z" }, + { url = "https://files.pythonhosted.org/packages/12/8a/18d85e624f8631aec42daa8a2f07c6edcedb7385b2c0f375ba8a30cbd065/hypothesis-6.164.0-cp313-cp313-win_amd64.whl", hash = "sha256:4878f81fa92a580d3e16b53e64e01a9d9fe1dca5973783558493a003138dbd36", size = 660656, upload-time = "2026-07-30T12:38:37.696Z" }, + { url = "https://files.pythonhosted.org/packages/c7/06/3c144d427799c7c72befb0bb3b199d419a89b96e1002fd8f0cc94c84ffb7/hypothesis-6.164.0-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:9110010bdf6deb3ba9134f8ce8b683e8bb0fba108a351045c96d60c410eb6963", size = 773254, upload-time = "2026-07-30T12:38:38.919Z" }, + { url = "https://files.pythonhosted.org/packages/74/2d/b61a10d9e70df04aa7e8f34efef8e4afe364e8995c59f894e1c35b428214/hypothesis-6.164.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:4df103e5d32b47d574c6e857d45361e2cba5a198d6dae4e4ee1bd248b3a2cbfa", size = 764786, upload-time = "2026-07-30T12:38:24.464Z" }, + { url = "https://files.pythonhosted.org/packages/99/68/7f80ac7bdffe78686135311c919534be411d4565c2a5ba38fd389880c553/hypothesis-6.164.0-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4abec95020960c0ed08e5be318d2bcdde79f2c6fc7785e368a9389d31d3e802a", size = 1095578, upload-time = "2026-07-30T12:38:57.422Z" }, + { url = "https://files.pythonhosted.org/packages/45/f9/97dcbac776bcf33cb4241b52111527821f707b60a84d03d0ea670b09a134/hypothesis-6.164.0-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9b106756cc9abd50ab1632541ea7b7223792d877a084726aa0304237d758181e", size = 1145207, upload-time = "2026-07-30T12:38:23.387Z" }, + { url = "https://files.pythonhosted.org/packages/a4/df/68184b6f71540435c895cf35ad1d67a3634a887c597ab38d3372c0d20186/hypothesis-6.164.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:11c4aab2ae6757fc4bc3bbf009487e24fd3490365817bbf40b9ec85a7e02fabb", size = 1268357, upload-time = "2026-07-30T12:38:52.946Z" }, + { url = "https://files.pythonhosted.org/packages/a0/76/6a6851dc8af89a5c0418937d38456417b2a1fc9db15c992b9cb43d53a7a3/hypothesis-6.164.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:4713edecbc0969557ca135769a36d1e524c8e3b7a2b271de48d98fa29f681bf6", size = 1312183, upload-time = "2026-07-30T12:39:28.604Z" }, + { url = "https://files.pythonhosted.org/packages/2f/19/83adeb1f8f045bd8a1ab9822d0c3db28b337d37fff01d809fcd6e3ea70f8/hypothesis-6.164.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:e6882d316c390d33c55ec8f1675f35ab238d7c0473ccf8d235c69eaef6c621b9", size = 604771, upload-time = "2026-07-30T12:39:33.579Z" }, + { url = "https://files.pythonhosted.org/packages/0b/62/fcb48ebfbccdc5b695de175b9d1d344b3688782150f0603124bb70c0891b/hypothesis-6.164.0-cp314-cp314-win_amd64.whl", hash = "sha256:7c3357633b38bca8c927fd90d02b39a0a3f35f24cdbcfb2fb1dcf69a3f63bd85", size = 660570, upload-time = "2026-07-30T12:39:43.898Z" }, + { url = "https://files.pythonhosted.org/packages/42/61/5857da7db0435fa69df658a9eafba62eb8a1319454005ce2a0d97f6f9e4d/hypothesis-6.164.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:53152cb549f52d661c47768d0d12a192ef26a7a9758a7f13b8ec41e8e63d6325", size = 771839, upload-time = "2026-07-30T12:38:26.842Z" }, + { url = "https://files.pythonhosted.org/packages/6c/9c/22292a9dab1c544362d1759244132c7d71a9d9d5eda5d454ec735fba6bd3/hypothesis-6.164.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:cee7898ad84b63da6506ae48483bb36f319a25ea4c2b1d2df47d021cc4080c24", size = 763363, upload-time = "2026-07-30T12:38:20.042Z" }, + { url = "https://files.pythonhosted.org/packages/e8/29/cc0c6e9a065a32f93fe52dde746232f007d2cabf619d4e7b1b37bd34c424/hypothesis-6.164.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0def33f0d236e54144a5218997e4492925144d4615f25fdbb4ac8e47b7b709e6", size = 1094171, upload-time = "2026-07-30T12:39:35.158Z" }, + { url = "https://files.pythonhosted.org/packages/a7/59/37040d0776a29d4bc6d0ca9a50ca2755200007e4a8ddc27b010115b69c85/hypothesis-6.164.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:471fd80d70f2df606b1320276168bc2c6007a586124a1d81628264ccb9266f68", size = 1144089, upload-time = "2026-07-30T12:38:43.024Z" }, + { url = "https://files.pythonhosted.org/packages/fa/10/5235ed3c090a2f12fa15cc1d08e5a36cfa31bc0607c45199b0806e930ab4/hypothesis-6.164.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:2eb285756aee62890fd08d6e97cf77651dfe7c093ceac094df52120a7a8dbe68", size = 1266595, upload-time = "2026-07-30T12:39:36.979Z" }, + { url = "https://files.pythonhosted.org/packages/7f/97/ffc4cee4dfdffe658e839d5f4df72ae3fa7bfea9401550b475d9700e0ee2/hypothesis-6.164.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:7c5215b5568968c35c6e124e5a4a8068f80419d6171414ddf735b49e1df1ab59", size = 1310998, upload-time = "2026-07-30T12:38:45.788Z" }, + { url = "https://files.pythonhosted.org/packages/dd/08/681d4a272cd2812151581c3328e41a80a34e420d676e419a25b4b9dc2291/hypothesis-6.164.0-cp314-cp314t-win_amd64.whl", hash = "sha256:a845e59fae87bb47a6fb84e0d5adb5679b3b55042fc3f8791da91486103cfbf0", size = 660724, upload-time = "2026-07-30T12:38:40.341Z" }, +] + +[[package]] +name = "idna" +version = "3.18" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/63/9496c57188a2ee585e0f1db071d75089a11e98aa86eb99d9d7618fc1edce/idna-3.18.tar.gz", hash = "sha256:ffb385a7e039654cef1ab9ef32c6fafe283c0c0467bba1d9029738ce4a14a848", size = 196711, upload-time = "2026-06-02T14:34:07.794Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/5e/d4e9f1a599fb8e573b7b87160658329fbf28d19eac2718f51fc3def3aa5a/idna-3.18-py3-none-any.whl", hash = "sha256:7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2", size = 65455, upload-time = "2026-06-02T14:34:06.319Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, +] + +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, +] + +[[package]] +name = "markdown" +version = "3.10.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/29/6f/da4c6aea59b3001f2e8c0ec7497475aadaf3b021c10cab5b2858f0f32b26/markdown-3.10.3.tar.gz", hash = "sha256:3589362618f743188b4d955b874402bc814f4f83f544dc207719f4baa7d9c45f", size = 372596, upload-time = "2026-07-30T19:05:29.005Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/69/4a5af2bc115a9a33fefe51709749de8262be3f9ba063d1753a837cdbc49c/markdown-3.10.3-py3-none-any.whl", hash = "sha256:fa6c92a00a4a3c98b22728c64a935ae1928250ae65058a6ded814d2cc29a4cea", size = 110757, upload-time = "2026-07-30T19:05:27.883Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5a/72/147da192e38635ada20e0a2e1a51cf8823d2119ce8883f7053879c2199b5/markupsafe-3.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e", size = 11615, upload-time = "2025-09-27T18:36:30.854Z" }, + { url = "https://files.pythonhosted.org/packages/9a/81/7e4e08678a1f98521201c3079f77db69fb552acd56067661f8c2f534a718/markupsafe-3.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce", size = 12020, upload-time = "2025-09-27T18:36:31.971Z" }, + { url = "https://files.pythonhosted.org/packages/1e/2c/799f4742efc39633a1b54a92eec4082e4f815314869865d876824c257c1e/markupsafe-3.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d", size = 24332, upload-time = "2025-09-27T18:36:32.813Z" }, + { url = "https://files.pythonhosted.org/packages/3c/2e/8d0c2ab90a8c1d9a24f0399058ab8519a3279d1bd4289511d74e909f060e/markupsafe-3.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d", size = 22947, upload-time = "2025-09-27T18:36:33.86Z" }, + { url = "https://files.pythonhosted.org/packages/2c/54/887f3092a85238093a0b2154bd629c89444f395618842e8b0c41783898ea/markupsafe-3.0.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a", size = 21962, upload-time = "2025-09-27T18:36:35.099Z" }, + { url = "https://files.pythonhosted.org/packages/c9/2f/336b8c7b6f4a4d95e91119dc8521402461b74a485558d8f238a68312f11c/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b", size = 23760, upload-time = "2025-09-27T18:36:36.001Z" }, + { url = "https://files.pythonhosted.org/packages/32/43/67935f2b7e4982ffb50a4d169b724d74b62a3964bc1a9a527f5ac4f1ee2b/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f", size = 21529, upload-time = "2025-09-27T18:36:36.906Z" }, + { url = "https://files.pythonhosted.org/packages/89/e0/4486f11e51bbba8b0c041098859e869e304d1c261e59244baa3d295d47b7/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b", size = 23015, upload-time = "2025-09-27T18:36:37.868Z" }, + { url = "https://files.pythonhosted.org/packages/2f/e1/78ee7a023dac597a5825441ebd17170785a9dab23de95d2c7508ade94e0e/markupsafe-3.0.3-cp312-cp312-win32.whl", hash = "sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d", size = 14540, upload-time = "2025-09-27T18:36:38.761Z" }, + { url = "https://files.pythonhosted.org/packages/aa/5b/bec5aa9bbbb2c946ca2733ef9c4ca91c91b6a24580193e891b5f7dbe8e1e/markupsafe-3.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c", size = 15105, upload-time = "2025-09-27T18:36:39.701Z" }, + { url = "https://files.pythonhosted.org/packages/e5/f1/216fc1bbfd74011693a4fd837e7026152e89c4bcf3e77b6692fba9923123/markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f", size = 13906, upload-time = "2025-09-27T18:36:40.689Z" }, + { url = "https://files.pythonhosted.org/packages/38/2f/907b9c7bbba283e68f20259574b13d005c121a0fa4c175f9bed27c4597ff/markupsafe-3.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e1cf1972137e83c5d4c136c43ced9ac51d0e124706ee1c8aa8532c1287fa8795", size = 11622, upload-time = "2025-09-27T18:36:41.777Z" }, + { url = "https://files.pythonhosted.org/packages/9c/d9/5f7756922cdd676869eca1c4e3c0cd0df60ed30199ffd775e319089cb3ed/markupsafe-3.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:116bb52f642a37c115f517494ea5feb03889e04df47eeff5b130b1808ce7c219", size = 12029, upload-time = "2025-09-27T18:36:43.257Z" }, + { url = "https://files.pythonhosted.org/packages/00/07/575a68c754943058c78f30db02ee03a64b3c638586fba6a6dd56830b30a3/markupsafe-3.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:133a43e73a802c5562be9bbcd03d090aa5a1fe899db609c29e8c8d815c5f6de6", size = 24374, upload-time = "2025-09-27T18:36:44.508Z" }, + { url = "https://files.pythonhosted.org/packages/a9/21/9b05698b46f218fc0e118e1f8168395c65c8a2c750ae2bab54fc4bd4e0e8/markupsafe-3.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccfcd093f13f0f0b7fdd0f198b90053bf7b2f02a3927a30e63f3ccc9df56b676", size = 22980, upload-time = "2025-09-27T18:36:45.385Z" }, + { url = "https://files.pythonhosted.org/packages/7f/71/544260864f893f18b6827315b988c146b559391e6e7e8f7252839b1b846a/markupsafe-3.0.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:509fa21c6deb7a7a273d629cf5ec029bc209d1a51178615ddf718f5918992ab9", size = 21990, upload-time = "2025-09-27T18:36:46.916Z" }, + { url = "https://files.pythonhosted.org/packages/c2/28/b50fc2f74d1ad761af2f5dcce7492648b983d00a65b8c0e0cb457c82ebbe/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a4afe79fb3de0b7097d81da19090f4df4f8d3a2b3adaa8764138aac2e44f3af1", size = 23784, upload-time = "2025-09-27T18:36:47.884Z" }, + { url = "https://files.pythonhosted.org/packages/ed/76/104b2aa106a208da8b17a2fb72e033a5a9d7073c68f7e508b94916ed47a9/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:795e7751525cae078558e679d646ae45574b47ed6e7771863fcc079a6171a0fc", size = 21588, upload-time = "2025-09-27T18:36:48.82Z" }, + { url = "https://files.pythonhosted.org/packages/b5/99/16a5eb2d140087ebd97180d95249b00a03aa87e29cc224056274f2e45fd6/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8485f406a96febb5140bfeca44a73e3ce5116b2501ac54fe953e488fb1d03b12", size = 23041, upload-time = "2025-09-27T18:36:49.797Z" }, + { url = "https://files.pythonhosted.org/packages/19/bc/e7140ed90c5d61d77cea142eed9f9c303f4c4806f60a1044c13e3f1471d0/markupsafe-3.0.3-cp313-cp313-win32.whl", hash = "sha256:bdd37121970bfd8be76c5fb069c7751683bdf373db1ed6c010162b2a130248ed", size = 14543, upload-time = "2025-09-27T18:36:51.584Z" }, + { url = "https://files.pythonhosted.org/packages/05/73/c4abe620b841b6b791f2edc248f556900667a5a1cf023a6646967ae98335/markupsafe-3.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5", size = 15113, upload-time = "2025-09-27T18:36:52.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/3a/fa34a0f7cfef23cf9500d68cb7c32dd64ffd58a12b09225fb03dd37d5b80/markupsafe-3.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:7e68f88e5b8799aa49c85cd116c932a1ac15caaa3f5db09087854d218359e485", size = 13911, upload-time = "2025-09-27T18:36:53.513Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d7/e05cd7efe43a88a17a37b3ae96e79a19e846f3f456fe79c57ca61356ef01/markupsafe-3.0.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:218551f6df4868a8d527e3062d0fb968682fe92054e89978594c28e642c43a73", size = 11658, upload-time = "2025-09-27T18:36:54.819Z" }, + { url = "https://files.pythonhosted.org/packages/99/9e/e412117548182ce2148bdeacdda3bb494260c0b0184360fe0d56389b523b/markupsafe-3.0.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:3524b778fe5cfb3452a09d31e7b5adefeea8c5be1d43c4f810ba09f2ceb29d37", size = 12066, upload-time = "2025-09-27T18:36:55.714Z" }, + { url = "https://files.pythonhosted.org/packages/bc/e6/fa0ffcda717ef64a5108eaa7b4f5ed28d56122c9a6d70ab8b72f9f715c80/markupsafe-3.0.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4e885a3d1efa2eadc93c894a21770e4bc67899e3543680313b09f139e149ab19", size = 25639, upload-time = "2025-09-27T18:36:56.908Z" }, + { url = "https://files.pythonhosted.org/packages/96/ec/2102e881fe9d25fc16cb4b25d5f5cde50970967ffa5dddafdb771237062d/markupsafe-3.0.3-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8709b08f4a89aa7586de0aadc8da56180242ee0ada3999749b183aa23df95025", size = 23569, upload-time = "2025-09-27T18:36:57.913Z" }, + { url = "https://files.pythonhosted.org/packages/4b/30/6f2fce1f1f205fc9323255b216ca8a235b15860c34b6798f810f05828e32/markupsafe-3.0.3-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b8512a91625c9b3da6f127803b166b629725e68af71f8184ae7e7d54686a56d6", size = 23284, upload-time = "2025-09-27T18:36:58.833Z" }, + { url = "https://files.pythonhosted.org/packages/58/47/4a0ccea4ab9f5dcb6f79c0236d954acb382202721e704223a8aafa38b5c8/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9b79b7a16f7fedff2495d684f2b59b0457c3b493778c9eed31111be64d58279f", size = 24801, upload-time = "2025-09-27T18:36:59.739Z" }, + { url = "https://files.pythonhosted.org/packages/6a/70/3780e9b72180b6fecb83a4814d84c3bf4b4ae4bf0b19c27196104149734c/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:12c63dfb4a98206f045aa9563db46507995f7ef6d83b2f68eda65c307c6829eb", size = 22769, upload-time = "2025-09-27T18:37:00.719Z" }, + { url = "https://files.pythonhosted.org/packages/98/c5/c03c7f4125180fc215220c035beac6b9cb684bc7a067c84fc69414d315f5/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8f71bc33915be5186016f675cd83a1e08523649b0e33efdb898db577ef5bb009", size = 23642, upload-time = "2025-09-27T18:37:01.673Z" }, + { url = "https://files.pythonhosted.org/packages/80/d6/2d1b89f6ca4bff1036499b1e29a1d02d282259f3681540e16563f27ebc23/markupsafe-3.0.3-cp313-cp313t-win32.whl", hash = "sha256:69c0b73548bc525c8cb9a251cddf1931d1db4d2258e9599c28c07ef3580ef354", size = 14612, upload-time = "2025-09-27T18:37:02.639Z" }, + { url = "https://files.pythonhosted.org/packages/2b/98/e48a4bfba0a0ffcf9925fe2d69240bfaa19c6f7507b8cd09c70684a53c1e/markupsafe-3.0.3-cp313-cp313t-win_amd64.whl", hash = "sha256:1b4b79e8ebf6b55351f0d91fe80f893b4743f104bff22e90697db1590e47a218", size = 15200, upload-time = "2025-09-27T18:37:03.582Z" }, + { url = "https://files.pythonhosted.org/packages/0e/72/e3cc540f351f316e9ed0f092757459afbc595824ca724cbc5a5d4263713f/markupsafe-3.0.3-cp313-cp313t-win_arm64.whl", hash = "sha256:ad2cf8aa28b8c020ab2fc8287b0f823d0a7d8630784c31e9ee5edea20f406287", size = 13973, upload-time = "2025-09-27T18:37:04.929Z" }, + { url = "https://files.pythonhosted.org/packages/33/8a/8e42d4838cd89b7dde187011e97fe6c3af66d8c044997d2183fbd6d31352/markupsafe-3.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe", size = 11619, upload-time = "2025-09-27T18:37:06.342Z" }, + { url = "https://files.pythonhosted.org/packages/b5/64/7660f8a4a8e53c924d0fa05dc3a55c9cee10bbd82b11c5afb27d44b096ce/markupsafe-3.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026", size = 12029, upload-time = "2025-09-27T18:37:07.213Z" }, + { url = "https://files.pythonhosted.org/packages/da/ef/e648bfd021127bef5fa12e1720ffed0c6cbb8310c8d9bea7266337ff06de/markupsafe-3.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737", size = 24408, upload-time = "2025-09-27T18:37:09.572Z" }, + { url = "https://files.pythonhosted.org/packages/41/3c/a36c2450754618e62008bf7435ccb0f88053e07592e6028a34776213d877/markupsafe-3.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97", size = 23005, upload-time = "2025-09-27T18:37:10.58Z" }, + { url = "https://files.pythonhosted.org/packages/bc/20/b7fdf89a8456b099837cd1dc21974632a02a999ec9bf7ca3e490aacd98e7/markupsafe-3.0.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d", size = 22048, upload-time = "2025-09-27T18:37:11.547Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a7/591f592afdc734f47db08a75793a55d7fbcc6902a723ae4cfbab61010cc5/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda", size = 23821, upload-time = "2025-09-27T18:37:12.48Z" }, + { url = "https://files.pythonhosted.org/packages/7d/33/45b24e4f44195b26521bc6f1a82197118f74df348556594bd2262bda1038/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf", size = 21606, upload-time = "2025-09-27T18:37:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/ff/0e/53dfaca23a69fbfbbf17a4b64072090e70717344c52eaaaa9c5ddff1e5f0/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe", size = 23043, upload-time = "2025-09-27T18:37:14.408Z" }, + { url = "https://files.pythonhosted.org/packages/46/11/f333a06fc16236d5238bfe74daccbca41459dcd8d1fa952e8fbd5dccfb70/markupsafe-3.0.3-cp314-cp314-win32.whl", hash = "sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9", size = 14747, upload-time = "2025-09-27T18:37:15.36Z" }, + { url = "https://files.pythonhosted.org/packages/28/52/182836104b33b444e400b14f797212f720cbc9ed6ba34c800639d154e821/markupsafe-3.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581", size = 15341, upload-time = "2025-09-27T18:37:16.496Z" }, + { url = "https://files.pythonhosted.org/packages/6f/18/acf23e91bd94fd7b3031558b1f013adfa21a8e407a3fdb32745538730382/markupsafe-3.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4", size = 14073, upload-time = "2025-09-27T18:37:17.476Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f0/57689aa4076e1b43b15fdfa646b04653969d50cf30c32a102762be2485da/markupsafe-3.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab", size = 11661, upload-time = "2025-09-27T18:37:18.453Z" }, + { url = "https://files.pythonhosted.org/packages/89/c3/2e67a7ca217c6912985ec766c6393b636fb0c2344443ff9d91404dc4c79f/markupsafe-3.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175", size = 12069, upload-time = "2025-09-27T18:37:19.332Z" }, + { url = "https://files.pythonhosted.org/packages/f0/00/be561dce4e6ca66b15276e184ce4b8aec61fe83662cce2f7d72bd3249d28/markupsafe-3.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634", size = 25670, upload-time = "2025-09-27T18:37:20.245Z" }, + { url = "https://files.pythonhosted.org/packages/50/09/c419f6f5a92e5fadde27efd190eca90f05e1261b10dbd8cbcb39cd8ea1dc/markupsafe-3.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50", size = 23598, upload-time = "2025-09-27T18:37:21.177Z" }, + { url = "https://files.pythonhosted.org/packages/22/44/a0681611106e0b2921b3033fc19bc53323e0b50bc70cffdd19f7d679bb66/markupsafe-3.0.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e", size = 23261, upload-time = "2025-09-27T18:37:22.167Z" }, + { url = "https://files.pythonhosted.org/packages/5f/57/1b0b3f100259dc9fffe780cfb60d4be71375510e435efec3d116b6436d43/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5", size = 24835, upload-time = "2025-09-27T18:37:23.296Z" }, + { url = "https://files.pythonhosted.org/packages/26/6a/4bf6d0c97c4920f1597cc14dd720705eca0bf7c787aebc6bb4d1bead5388/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523", size = 22733, upload-time = "2025-09-27T18:37:24.237Z" }, + { url = "https://files.pythonhosted.org/packages/14/c7/ca723101509b518797fedc2fdf79ba57f886b4aca8a7d31857ba3ee8281f/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc", size = 23672, upload-time = "2025-09-27T18:37:25.271Z" }, + { url = "https://files.pythonhosted.org/packages/fb/df/5bd7a48c256faecd1d36edc13133e51397e41b73bb77e1a69deab746ebac/markupsafe-3.0.3-cp314-cp314t-win32.whl", hash = "sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d", size = 14819, upload-time = "2025-09-27T18:37:26.285Z" }, + { url = "https://files.pythonhosted.org/packages/1a/8a/0402ba61a2f16038b48b39bccca271134be00c5c9f0f623208399333c448/markupsafe-3.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9", size = 15426, upload-time = "2025-09-27T18:37:27.316Z" }, + { url = "https://files.pythonhosted.org/packages/70/bc/6f1c2f612465f5fa89b95bead1f44dcb607670fd42891d8fdcd5d039f4f4/markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa", size = 14146, upload-time = "2025-09-27T18:37:28.327Z" }, +] + +[[package]] +name = "mergedeep" +version = "1.3.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3a/41/580bb4006e3ed0361b8151a01d324fb03f420815446c7def45d02f74c270/mergedeep-1.3.4.tar.gz", hash = "sha256:0096d52e9dad9939c3d975a774666af186eda617e6ca84df4c94dec30004f2a8", size = 4661, upload-time = "2021-02-05T18:55:30.623Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/19/04f9b178c2d8a15b076c8b5140708fa6ffc5601fb6f1e975537072df5b2a/mergedeep-1.3.4-py3-none-any.whl", hash = "sha256:70775750742b25c0d8f36c55aed03d24c3384d17c951b3175d898bd778ef0307", size = 6354, upload-time = "2021-02-05T18:55:29.583Z" }, +] + +[[package]] +name = "mkdocs" +version = "1.6.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "ghp-import" }, + { name = "jinja2" }, + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mergedeep" }, + { name = "mkdocs-get-deps" }, + { name = "packaging" }, + { name = "pathspec" }, + { name = "pyyaml" }, + { name = "pyyaml-env-tag" }, + { name = "watchdog" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bc/c6/bbd4f061bd16b378247f12953ffcb04786a618ce5e904b8c5a01a0309061/mkdocs-1.6.1.tar.gz", hash = "sha256:7b432f01d928c084353ab39c57282f29f92136665bdd6abf7c1ec8d822ef86f2", size = 3889159, upload-time = "2024-08-30T12:24:06.899Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/5b/dbc6a8cddc9cfa9c4971d59fb12bb8d42e161b7e7f8cc89e49137c5b279c/mkdocs-1.6.1-py3-none-any.whl", hash = "sha256:db91759624d1647f3f34aa0c3f327dd2601beae39a366d6e064c03468d35c20e", size = 3864451, upload-time = "2024-08-30T12:24:05.054Z" }, +] + +[[package]] +name = "mkdocs-autorefs" +version = "1.4.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mkdocs" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/52/c0/f641843de3f612a6b48253f39244165acff36657a91cc903633d456ae1ac/mkdocs_autorefs-1.4.4.tar.gz", hash = "sha256:d54a284f27a7346b9c38f1f852177940c222da508e66edc816a0fa55fc6da197", size = 56588, upload-time = "2026-02-10T15:23:55.105Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/28/de/a3e710469772c6a89595fc52816da05c1e164b4c866a89e3cb82fb1b67c5/mkdocs_autorefs-1.4.4-py3-none-any.whl", hash = "sha256:834ef5408d827071ad1bc69e0f39704fa34c7fc05bc8e1c72b227dfdc5c76089", size = 25530, upload-time = "2026-02-10T15:23:53.817Z" }, +] + +[[package]] +name = "mkdocs-get-deps" +version = "0.2.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mergedeep" }, + { name = "platformdirs" }, + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ce/25/b3cccb187655b9393572bde9b09261d267c3bf2f2cdabe347673be5976a6/mkdocs_get_deps-0.2.2.tar.gz", hash = "sha256:8ee8d5f316cdbbb2834bc1df6e69c08fe769a83e040060de26d3c19fad3599a1", size = 11047, upload-time = "2026-03-10T02:46:33.632Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/29/744136411e785c4b0b744d5413e56555265939ab3a104c6a4b719dad33fd/mkdocs_get_deps-0.2.2-py3-none-any.whl", hash = "sha256:e7878cbeac04860b8b5e0ca31d3abad3df9411a75a32cde82f8e44b6c16ff650", size = 9555, upload-time = "2026-03-10T02:46:32.256Z" }, +] + +[[package]] +name = "mkdocs-material" +version = "9.7.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "babel" }, + { name = "backrefs" }, + { name = "colorama" }, + { name = "jinja2" }, + { name = "markdown" }, + { name = "mkdocs" }, + { name = "mkdocs-material-extensions" }, + { name = "paginate" }, + { name = "pygments" }, + { name = "pymdown-extensions" }, + { name = "requests" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f1/cd/c05d3a530ba7934f144fb45f7203cd236adc25c7bdcc34673d202f4b0278/mkdocs_material-9.7.7.tar.gz", hash = "sha256:c0649c065b1b0512d60aad8c10f947f8e455284475239b364b610f2deb4d0855", size = 4097923, upload-time = "2026-07-17T16:21:33.156Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ad/21/17c1bc9e6f47c972ad66fb2ac2568f99f90f1207eeb6fc3b34d094dba7b5/mkdocs_material-9.7.7-py3-none-any.whl", hash = "sha256:8ea9bb1737a5b524a5f9dcf2e1b4ebda8274ae3008aa7845720a97083bef708f", size = 9305438, upload-time = "2026-07-17T16:21:30.017Z" }, +] + +[[package]] +name = "mkdocs-material-extensions" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/79/9b/9b4c96d6593b2a541e1cb8b34899a6d021d208bb357042823d4d2cabdbe7/mkdocs_material_extensions-1.3.1.tar.gz", hash = "sha256:10c9511cea88f568257f960358a467d12b970e1f7b2c0e5fb2bb48cab1928443", size = 11847, upload-time = "2023-11-22T19:09:45.208Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5b/54/662a4743aa81d9582ee9339d4ffa3c8fd40a4965e033d77b9da9774d3960/mkdocs_material_extensions-1.3.1-py3-none-any.whl", hash = "sha256:adff8b62700b25cb77b53358dad940f3ef973dd6db797907c49e3c2ef3ab4e31", size = 8728, upload-time = "2023-11-22T19:09:43.465Z" }, +] + +[[package]] +name = "mkdocstrings" +version = "1.0.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jinja2" }, + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mkdocs" }, + { name = "mkdocs-autorefs" }, + { name = "pymdown-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/53/71/f85bdf13355073ae15a7375f09879375a830553552e58c1c4b7e0bbc5c8b/mkdocstrings-1.0.6.tar.gz", hash = "sha256:a0b8c2bdd29a6416c80d717aa369bbf7831946bd9f23c2a66db1b1dbe7693dbd", size = 100649, upload-time = "2026-07-11T19:38:05.732Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/5b/4c1902e8bdd5c4db63284e9d101dece4038d4025d6d88850ffe0a1578980/mkdocstrings-1.0.6-py3-none-any.whl", hash = "sha256:2703708697487d1b6d6d7b412e176fa436edf120c1bf81dc9e126b12d00893c7", size = 35787, upload-time = "2026-07-11T19:38:04.417Z" }, +] + +[[package]] +name = "mkdocstrings-python" +version = "2.0.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "griffelib" }, + { name = "mkdocs-autorefs" }, + { name = "mkdocstrings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/b6/e858701499d57eee8b3fd8e78168083956c6683ddbe727b46758b19e1119/mkdocstrings_python-2.0.5.tar.gz", hash = "sha256:3a4d92556ad39637e88af94a5374213af9a8e3040c3824ceaed04b486c017594", size = 199578, upload-time = "2026-06-19T10:41:08.868Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/fc/10ab7e80650a9c9e8f4f1105f8c8e73567f88ed0c06ada589ab81d38687c/mkdocstrings_python-2.0.5-py3-none-any.whl", hash = "sha256:30c837bbff016549f659fcba6539ac351303f0fd7e713c89a040611072236e9d", size = 104951, upload-time = "2026-06-19T10:41:07.378Z" }, +] + +[[package]] +name = "numpy" +version = "2.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/22/fd/89965aa4ac08c74998539fcbf24fa3540f3e15237fbeb6bcf9c908f4aade/numpy-2.5.1.tar.gz", hash = "sha256:a48a113e6afea91f5608793bafa7ef2ad481fefbda87ec5069f483de61cb9fa3", size = 20755553, upload-time = "2026-07-04T17:08:00.933Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/7b/14687aa674250e5e546f616f486b0d56d3631cd5b2415739141ce40bdcea/numpy-2.5.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2c889b56fe48b1018f764b0eec8df59ab654e9148aa91faa12596043500de277", size = 16801574, upload-time = "2026-07-04T17:06:12.423Z" }, + { url = "https://files.pythonhosted.org/packages/e1/19/cc5bb2a3f2913d27d6dbb2c78d25921fabaedc6741d4a5a615a11f3c5bf3/numpy-2.5.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ab451b59c5643c570974c43aef780703ef1d3b4965d2be07afd530615a9358d1", size = 11772250, upload-time = "2026-07-04T17:06:15.726Z" }, + { url = "https://files.pythonhosted.org/packages/42/77/fdf34a71dd30f54979b18603bee915e0aaf825b07afe79acd60b04b691e2/numpy-2.5.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:78798bd5b9ad744056af8efa90e3b9ddaa53272a0848a483084a1cc0a13b2dc0", size = 5331516, upload-time = "2026-07-04T17:06:17.913Z" }, + { url = "https://files.pythonhosted.org/packages/ce/e2/eb7efa015b4cce41e2517bf182a7fce0d7d5b9d9ed76a29bfa0f4fe4505c/numpy-2.5.1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:2ae0ca40bcb22d6ba59c1dfd5446f49940b0f2d821fde133f10dda11f816b84e", size = 6664863, upload-time = "2026-07-04T17:06:20.02Z" }, + { url = "https://files.pythonhosted.org/packages/a9/4b/a2b32dd94ee9ffbeecb28152240042a3949db33b1c834d44090b80e1b3b8/numpy-2.5.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:61ac47e772e6b8ea489e1d2f441a34c5c3ac17327e7ce294cbdf535795ad4e75", size = 15167977, upload-time = "2026-07-04T17:06:21.621Z" }, + { url = "https://files.pythonhosted.org/packages/b8/a9/6e73d68500f80773f65f0654ea932019d6694329a0eb0ed0533de38df376/numpy-2.5.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:59fda5e192b570217ec2580c96f00e9a7e12ef6866a900eb089b62c1a32545ca", size = 16672469, upload-time = "2026-07-04T17:06:24.064Z" }, + { url = "https://files.pythonhosted.org/packages/24/7d/ad3e59015135f5261c95fd4cafeff159c955febd83a99a1d9250c4233815/numpy-2.5.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f7119ebff1a9829e9f431a4f9d28e703023bb6b9fe7c8f724467dbfc27c94ab3", size = 16527531, upload-time = "2026-07-04T17:06:26.69Z" }, + { url = "https://files.pythonhosted.org/packages/83/d0/a39b2fbcde9cb17a1dac678f254b33a6336298af9df338824c685425d5e8/numpy-2.5.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e824c2acf8862052246be5a44c15da1777940c60d010dd2aab897824d9c430f9", size = 18431940, upload-time = "2026-07-04T17:06:29.521Z" }, + { url = "https://files.pythonhosted.org/packages/04/12/cff070947791c1ed425ff76413189adbdc2fbe215eba7ce7fa454a03c7f8/numpy-2.5.1-cp312-cp312-win32.whl", hash = "sha256:08d60c810432eb83360958dea0999ac4cfb94531ea8efcbf0b7f277c2068aeb2", size = 6066764, upload-time = "2026-07-04T17:06:32.571Z" }, + { url = "https://files.pythonhosted.org/packages/65/66/53f31807a48a750f9d748da273bc3fcedd12b27ff1f3e373bfec55ef2dc0/numpy-2.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:f7d60026c0bdb1380e83bfa7a0419c4577ee4b9a08880afcb6dadeb74c649fa2", size = 12430966, upload-time = "2026-07-04T17:06:34.926Z" }, + { url = "https://files.pythonhosted.org/packages/2b/2a/d1a88066b1c14186f5d3c0d18c94f17b064511982bab0578d49ee9d43c29/numpy-2.5.1-cp312-cp312-win_arm64.whl", hash = "sha256:17a25e09640602e10bc8de0e6fa2b3fd68eedd84ba6d7842dc8f32f9ab87bd0b", size = 10350488, upload-time = "2026-07-04T17:06:37.785Z" }, + { url = "https://files.pythonhosted.org/packages/eb/07/ec2a3f0c91761581d4b7104a740791800025983f9a4dc4e73f91a99aeac4/numpy-2.5.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0bfebd8695f9863592fe744be833a258120b14a9f39da255e8aa8fade2c0ddd1", size = 16796419, upload-time = "2026-07-04T17:06:40.37Z" }, + { url = "https://files.pythonhosted.org/packages/ab/ab/ddb499fc4f8780354395face5b65c7fd107bcd6e1d667a5f07d046956f6f/numpy-2.5.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:30b44a6b53a7ae63c54c089a8726e5563ed302716c5b7ccc85afade40b0e7ff6", size = 11765832, upload-time = "2026-07-04T17:06:42.768Z" }, + { url = "https://files.pythonhosted.org/packages/88/b3/3c28c558a09fc72100c646dac6d2fce8e834c471b0edca01a29996706117/numpy-2.5.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:6165343f81b56ef8f514f396989e529b61d9dc709b99421b07e9f3e698e2287d", size = 5325143, upload-time = "2026-07-04T17:06:45.466Z" }, + { url = "https://files.pythonhosted.org/packages/5e/0e/ce19b985bb15c596f4f05954e76cccc77c845083b3b8f938a6c68e523128/numpy-2.5.1-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:4939237038ada79308dda3204ac6462df056b5672b2e25db1149cf873668b3e1", size = 6659749, upload-time = "2026-07-04T17:06:47.288Z" }, + { url = "https://files.pythonhosted.org/packages/2e/20/1ee6614d64332a1bba6411f38e68cb79eec1b2459e20a623777c5c5492a2/numpy-2.5.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1c6759f538fb912fc46de0a6b1758ccf7b57bc7c7ebebc23974fdac3de8db0cd", size = 15164716, upload-time = "2026-07-04T17:06:49.494Z" }, + { url = "https://files.pythonhosted.org/packages/ed/a7/2bcd3fdbb87804755c35b729bf8709d62025c5f4cfd7d5b2415997097515/numpy-2.5.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9726558e8db4a5bf7929a70ae50f63abda4daf0efe810e3bfbab95976f75fc1a", size = 16661440, upload-time = "2026-07-04T17:06:52.061Z" }, + { url = "https://files.pythonhosted.org/packages/fc/d7/a41e3310c886fe457d36e670bbf24fae411aca8a7b6ad92a32afd924077c/numpy-2.5.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3935f3b419b244a02732676fa5317a9193cc596a4c0646db07e5b421229ac9f7", size = 16526305, upload-time = "2026-07-04T17:06:54.605Z" }, + { url = "https://files.pythonhosted.org/packages/53/75/4333a9a707c1edd3a4e1a0c58eca52c0f31e55089fa80db02b5565b24df7/numpy-2.5.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:dc932a65ded7ce9013d120845a2514dcccb1a67bfc8deb8d37633762951904a6", size = 18423008, upload-time = "2026-07-04T17:06:57.54Z" }, + { url = "https://files.pythonhosted.org/packages/ee/90/e314a32b1c11a2ffe818ddad3a57b50b4b6e1b6c487192eb50cdef0415d0/numpy-2.5.1-cp313-cp313-win32.whl", hash = "sha256:4b4ff1608417eb7a59da7b967bbb798cacfe071d2caf526a24281cd562072ed9", size = 6063885, upload-time = "2026-07-04T17:07:00.14Z" }, + { url = "https://files.pythonhosted.org/packages/10/70/800b3fca480af32df9e8ea9f3d4a0c8feb4b32d7f195d174eabbda4829ad/numpy-2.5.1-cp313-cp313-win_amd64.whl", hash = "sha256:6c3fe51bc6a16453d452997053454f309e8e0ed7b42d6b361ce4ac8c32913d74", size = 12425674, upload-time = "2026-07-04T17:07:02.387Z" }, + { url = "https://files.pythonhosted.org/packages/8b/0b/196350c122f50f6ca56846f2d71efd5e0d24b7b2e07355e019b2e2c7a11e/numpy-2.5.1-cp313-cp313-win_arm64.whl", hash = "sha256:f7feb014281029e628ba2d5a007407443b06e418b6fe451d1e2adcbc8eba0107", size = 10350256, upload-time = "2026-07-04T17:07:04.878Z" }, + { url = "https://files.pythonhosted.org/packages/db/f4/731b6085a83faf6ca843394cbd5e217280c214399f7e8b21b9f552af0ae2/numpy-2.5.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:7c786fe9a5bbe360022e584c5a34cf6b54265c71bd7ec8ac3d8fec38968071f8", size = 16795063, upload-time = "2026-07-04T17:07:07.374Z" }, + { url = "https://files.pythonhosted.org/packages/bf/64/0e215f2048dd11a55bb989ed41b3585ef57452404e638d703a211a3e4157/numpy-2.5.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:32985c896d897419ef8da6917872d80b78ad0ea26d85b23245c7366ffde76d75", size = 11776652, upload-time = "2026-07-04T17:07:09.907Z" }, + { url = "https://files.pythonhosted.org/packages/b5/59/2b844c7a6e9deff69b404a66221e1542937734f65d5e6e39411876053862/numpy-2.5.1-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:efd736408cc97c79b9e6917338dfc8f06013b2274f992e96b1d9a81a71e2a2c2", size = 5335944, upload-time = "2026-07-04T17:07:12.227Z" }, + { url = "https://files.pythonhosted.org/packages/86/51/9bf7cb2cabcebc9e017e4ec7e6322b378317a542c08b4cb68479c1efc716/numpy-2.5.1-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:ab84dc6b074fa881cae55bea94cc4f68e285181ba7f32497bf7dee6b1496165b", size = 6656266, upload-time = "2026-07-04T17:07:14.368Z" }, + { url = "https://files.pythonhosted.org/packages/83/3e/fb7615b211b82a32f44d5180a6d421b61f84d4fadd578b48ba4ac34e189f/numpy-2.5.1-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:caf3e317d33d60c37986b452613f4ab51246d0691350c03d0cb4a898627f4a95", size = 15179720, upload-time = "2026-07-04T17:07:16.272Z" }, + { url = "https://files.pythonhosted.org/packages/41/5f/0f992cb24560673496c5d68de61913b57166ce530ffda07c1f280e0cc464/numpy-2.5.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:54ad769f17bc2d833b620851989f62054fb9ab93c969d9e1dc3c8e3d56beea21", size = 16664835, upload-time = "2026-07-04T17:07:19.021Z" }, + { url = "https://files.pythonhosted.org/packages/a2/2f/97d6475ee91afe2587797d09446f9d3e475ad4cb681662d824809327b75a/numpy-2.5.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c12afb53450fa976d4c681c50a7423729a4c51c0465ed9f32b8a9cabbc472373", size = 16539135, upload-time = "2026-07-04T17:07:22.015Z" }, + { url = "https://files.pythonhosted.org/packages/c4/5b/4db81e4ba0be7e2776b1de68c82aa862c7f8ec27e1b4927d4ae075e20678/numpy-2.5.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:e8c11c405efc5ff6816d5983c96cdfa215bab3428961243af3ff59b228490438", size = 18426684, upload-time = "2026-07-04T17:07:24.941Z" }, + { url = "https://files.pythonhosted.org/packages/1f/64/c0ba2d90724d450279a7df8f32057241070250a26a7e2b5337d77347f481/numpy-2.5.1-cp314-cp314-win32.whl", hash = "sha256:f2479a47f8d5932d1718168a681ad6e536a9df484c83cfcf9de365e164537ace", size = 6116103, upload-time = "2026-07-04T17:07:27.622Z" }, + { url = "https://files.pythonhosted.org/packages/c1/1a/837f9ed7405adcd7a40538792eb169eddd8fa5630c16a1ef49dae71a30f4/numpy-2.5.1-cp314-cp314-win_amd64.whl", hash = "sha256:24d0eb82c0541d3415a33425db64ae439dffccd7b4dbcb30e7c35120205c506a", size = 12562177, upload-time = "2026-07-04T17:07:29.887Z" }, + { url = "https://files.pythonhosted.org/packages/22/ed/49707938b6dd0a78a9178dd93227dc89e4c11af47f5c798d70366e8d0483/numpy-2.5.1-cp314-cp314-win_arm64.whl", hash = "sha256:5a4c988b38d261deeeaad9954e3deb091ad905c94e8bb6708654ef1d97f286b0", size = 10627739, upload-time = "2026-07-04T17:07:32.568Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c7/bb4b882cfe7f299cbc8b66e42e7dd78cf9d14e40f9469fc5e3db7e15b3bd/numpy-2.5.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a33276be12fa045805f477f22482088b66bb758ffbe89a9d21457de863a32e22", size = 11894709, upload-time = "2026-07-04T17:07:34.941Z" }, + { url = "https://files.pythonhosted.org/packages/40/3f/5af7f4a7f6224aef48017aa82bb6174c7a659d724be0c75017b7e64a55b4/numpy-2.5.1-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:f089d7b00756190aacf1f5d34bdf38c3c430ac82b4f868f8cede73380460fce7", size = 5453810, upload-time = "2026-07-04T17:07:37.495Z" }, + { url = "https://files.pythonhosted.org/packages/20/c9/3474309bc94d634d3f9c3eddf03250ecb8c22cd948ef16fef69a77cc5d7b/numpy-2.5.1-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:09e9bfd8d2cf479c7d174804fb3811c53a8e9f20a37444008606b57d6b7a826d", size = 6761189, upload-time = "2026-07-04T17:07:39.563Z" }, + { url = "https://files.pythonhosted.org/packages/90/8a/558ae39fdd55d7e7f7fef9a84a6e964ac6b23edbd2a07e52bb084500507d/numpy-2.5.1-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e68d8dd1e7eba712948f2053a29ec86917bc70ba1358df869d9f06649ef9cf09", size = 15225039, upload-time = "2026-07-04T17:07:41.682Z" }, + { url = "https://files.pythonhosted.org/packages/63/27/ca7392b2d030277bdf0273e7d23255b3ee57d57a7c170a6f4fb3981e1e5d/numpy-2.5.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:99d5095fa265a0c4152e7bb12759e14381ef5496152f1ce58f44bdf55c44beb4", size = 16701306, upload-time = "2026-07-04T17:07:44.611Z" }, + { url = "https://files.pythonhosted.org/packages/02/42/03d53ae7996c44d4374a8262e9dc41671fd56cbb98f7d47ef85cf5da4c6b/numpy-2.5.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ab87a91b3cc3382b8956095bd8f95e00cf679bb81554339be1a2ba404a1473c1", size = 16589955, upload-time = "2026-07-04T17:07:47.694Z" }, + { url = "https://files.pythonhosted.org/packages/7b/15/6c1784ae469640e65db111e9a34b3d0f14d91e8a38b9ce34810ced370dbb/numpy-2.5.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:224ca51130ef7da85bea2191625181cb4f337f9cb64b471f10c1a12aa8b60077", size = 18464252, upload-time = "2026-07-04T17:07:50.684Z" }, + { url = "https://files.pythonhosted.org/packages/94/a8/f98e50356cf167df656c526c2dfeec2d7dde182f2a3da4b458a5938e2776/numpy-2.5.1-cp314-cp314t-win32.whl", hash = "sha256:6eab239876581b2b3c5a242281b6007bbdbcd1c7085d7709bb57c5929b11e6bf", size = 6263298, upload-time = "2026-07-04T17:07:53.445Z" }, + { url = "https://files.pythonhosted.org/packages/72/ac/96ae880cdecad0b3275d9359fcec72667b49a4863c9f12942e43679dda02/numpy-2.5.1-cp314-cp314t-win_amd64.whl", hash = "sha256:83ce9c80d5b521b0d77ddcbe5447c218d247929b6cc056ca5351342accfff0af", size = 12748623, upload-time = "2026-07-04T17:07:55.384Z" }, + { url = "https://files.pythonhosted.org/packages/a1/5a/4d2b1601df3602dba7a14f3348ba9bfe94a18adb428e693df6154c293831/numpy-2.5.1-cp314-cp314t-win_arm64.whl", hash = "sha256:5a6db61f9aaa57e369905c67d852045d3c4f7126405b29d09b19dec118e9c9cb", size = 10697674, upload-time = "2026-07-04T17:07:58.506Z" }, +] + +[[package]] +name = "packaging" +version = "26.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d7/f1/e7a6dd94a8d4a5626c03e4e99c87f241ba9e350cd9e6d75123f992427270/packaging-26.2.tar.gz", hash = "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661", size = 228134, upload-time = "2026-04-24T20:15:23.917Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" }, +] + +[[package]] +name = "paginate" +version = "0.5.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/46/68dde5b6bc00c1296ec6466ab27dddede6aec9af1b99090e1107091b3b84/paginate-0.5.7.tar.gz", hash = "sha256:22bd083ab41e1a8b4f3690544afb2c60c25e5c9a63a30fa2f483f6c60c8e5945", size = 19252, upload-time = "2024-08-25T14:17:24.139Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/90/96/04b8e52da071d28f5e21a805b19cb9390aa17a47462ac87f5e2696b9566d/paginate-0.5.7-py2.py3-none-any.whl", hash = "sha256:b885e2af73abcf01d9559fd5216b57ef722f8c42affbb63942377668e35c7591", size = 13746, upload-time = "2024-08-25T14:17:22.55Z" }, +] + +[[package]] +name = "pathspec" +version = "1.1.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5a/82/42f767fc1c1143d6fd36efb827202a2d997a375e160a71eb2888a925aac1/pathspec-1.1.1.tar.gz", hash = "sha256:17db5ecd524104a120e173814c90367a96a98d07c45b2e10c2f3919fff91bf5a", size = 135180, upload-time = "2026-04-27T01:46:08.907Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.11.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/78/9b/560e4be8e26f6fd133a03630a8df0c663b9e8d61b4ade152b72005aec83b/platformdirs-4.11.0.tar.gz", hash = "sha256:0555d18370482847566ffabcaa53ad7c6c1c29f195989ae1ed634a05f76ea1e0", size = 31953, upload-time = "2026-07-21T13:09:36.565Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7d/68/d8d58938dfb1370b266a1a729e6d77a985be23689a0496498ee17b2cbf90/platformdirs-4.11.0-py3-none-any.whl", hash = "sha256:360ccded2b7fce0af0ff80cc8f5942a1c5d99b0e856033acb030bfc634709e74", size = 23247, upload-time = "2026-07-21T13:09:35.422Z" }, +] + +[[package]] +name = "pluggy" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, +] + +[[package]] +name = "pygments" +version = "2.20.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" }, +] + +[[package]] +name = "pymdown-extensions" +version = "11.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown" }, + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/21/a9/5f0c535ba3b08fe09270c16808e053a968868242ecbd5676d4e3a488bf28/pymdown_extensions-11.0.1.tar.gz", hash = "sha256:dd2905ae6fc5b75582fafb139a1266ffc754705efa902aa50067fa7ff4f94ec0", size = 857113, upload-time = "2026-07-02T17:59:22.955Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d6/54/da572c98c0b77626a91b5d3b89f0231d8bff5125c225420908632f8b342d/pymdown_extensions-11.0.1-py3-none-any.whl", hash = "sha256:db3943a62bab7e03af1364f0c4083e64b91fb097675a4b6cceccfbe9a77e5eb2", size = 269455, upload-time = "2026-07-02T17:59:21.271Z" }, +] + +[[package]] +name = "pytest" +version = "9.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, +] + +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/33/422b98d2195232ca1826284a76852ad5a86fe23e31b009c9886b2d0fb8b2/pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196", size = 182063, upload-time = "2025-09-25T21:32:11.445Z" }, + { url = "https://files.pythonhosted.org/packages/89/a0/6cf41a19a1f2f3feab0e9c0b74134aa2ce6849093d5517a0c550fe37a648/pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0", size = 173973, upload-time = "2025-09-25T21:32:12.492Z" }, + { url = "https://files.pythonhosted.org/packages/ed/23/7a778b6bd0b9a8039df8b1b1d80e2e2ad78aa04171592c8a5c43a56a6af4/pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", size = 775116, upload-time = "2025-09-25T21:32:13.652Z" }, + { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011, upload-time = "2025-09-25T21:32:15.21Z" }, + { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870, upload-time = "2025-09-25T21:32:16.431Z" }, + { url = "https://files.pythonhosted.org/packages/05/c0/b3be26a015601b822b97d9149ff8cb5ead58c66f981e04fedf4e762f4bd4/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", size = 761089, upload-time = "2025-09-25T21:32:17.56Z" }, + { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181, upload-time = "2025-09-25T21:32:18.834Z" }, + { url = "https://files.pythonhosted.org/packages/74/93/7baea19427dcfbe1e5a372d81473250b379f04b1bd3c4c5ff825e2327202/pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5", size = 137658, upload-time = "2025-09-25T21:32:20.209Z" }, + { url = "https://files.pythonhosted.org/packages/86/bf/899e81e4cce32febab4fb42bb97dcdf66bc135272882d1987881a4b519e9/pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b", size = 154003, upload-time = "2025-09-25T21:32:21.167Z" }, + { url = "https://files.pythonhosted.org/packages/1a/08/67bd04656199bbb51dbed1439b7f27601dfb576fb864099c7ef0c3e55531/pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", size = 140344, upload-time = "2025-09-25T21:32:22.617Z" }, + { url = "https://files.pythonhosted.org/packages/d1/11/0fd08f8192109f7169db964b5707a2f1e8b745d4e239b784a5a1dd80d1db/pyyaml-6.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8", size = 181669, upload-time = "2025-09-25T21:32:23.673Z" }, + { url = "https://files.pythonhosted.org/packages/b1/16/95309993f1d3748cd644e02e38b75d50cbc0d9561d21f390a76242ce073f/pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1", size = 173252, upload-time = "2025-09-25T21:32:25.149Z" }, + { url = "https://files.pythonhosted.org/packages/50/31/b20f376d3f810b9b2371e72ef5adb33879b25edb7a6d072cb7ca0c486398/pyyaml-6.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c", size = 767081, upload-time = "2025-09-25T21:32:26.575Z" }, + { url = "https://files.pythonhosted.org/packages/49/1e/a55ca81e949270d5d4432fbbd19dfea5321eda7c41a849d443dc92fd1ff7/pyyaml-6.0.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5", size = 841159, upload-time = "2025-09-25T21:32:27.727Z" }, + { url = "https://files.pythonhosted.org/packages/74/27/e5b8f34d02d9995b80abcef563ea1f8b56d20134d8f4e5e81733b1feceb2/pyyaml-6.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6", size = 801626, upload-time = "2025-09-25T21:32:28.878Z" }, + { url = "https://files.pythonhosted.org/packages/f9/11/ba845c23988798f40e52ba45f34849aa8a1f2d4af4b798588010792ebad6/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6", size = 753613, upload-time = "2025-09-25T21:32:30.178Z" }, + { url = "https://files.pythonhosted.org/packages/3d/e0/7966e1a7bfc0a45bf0a7fb6b98ea03fc9b8d84fa7f2229e9659680b69ee3/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be", size = 794115, upload-time = "2025-09-25T21:32:31.353Z" }, + { url = "https://files.pythonhosted.org/packages/de/94/980b50a6531b3019e45ddeada0626d45fa85cbe22300844a7983285bed3b/pyyaml-6.0.3-cp313-cp313-win32.whl", hash = "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26", size = 137427, upload-time = "2025-09-25T21:32:32.58Z" }, + { url = "https://files.pythonhosted.org/packages/97/c9/39d5b874e8b28845e4ec2202b5da735d0199dbe5b8fb85f91398814a9a46/pyyaml-6.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c", size = 154090, upload-time = "2025-09-25T21:32:33.659Z" }, + { url = "https://files.pythonhosted.org/packages/73/e8/2bdf3ca2090f68bb3d75b44da7bbc71843b19c9f2b9cb9b0f4ab7a5a4329/pyyaml-6.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb", size = 140246, upload-time = "2025-09-25T21:32:34.663Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8c/f4bd7f6465179953d3ac9bc44ac1a8a3e6122cf8ada906b4f96c60172d43/pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac", size = 181814, upload-time = "2025-09-25T21:32:35.712Z" }, + { url = "https://files.pythonhosted.org/packages/bd/9c/4d95bb87eb2063d20db7b60faa3840c1b18025517ae857371c4dd55a6b3a/pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310", size = 173809, upload-time = "2025-09-25T21:32:36.789Z" }, + { url = "https://files.pythonhosted.org/packages/92/b5/47e807c2623074914e29dabd16cbbdd4bf5e9b2db9f8090fa64411fc5382/pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7", size = 766454, upload-time = "2025-09-25T21:32:37.966Z" }, + { url = "https://files.pythonhosted.org/packages/02/9e/e5e9b168be58564121efb3de6859c452fccde0ab093d8438905899a3a483/pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788", size = 836355, upload-time = "2025-09-25T21:32:39.178Z" }, + { url = "https://files.pythonhosted.org/packages/88/f9/16491d7ed2a919954993e48aa941b200f38040928474c9e85ea9e64222c3/pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5", size = 794175, upload-time = "2025-09-25T21:32:40.865Z" }, + { url = "https://files.pythonhosted.org/packages/dd/3f/5989debef34dc6397317802b527dbbafb2b4760878a53d4166579111411e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764", size = 755228, upload-time = "2025-09-25T21:32:42.084Z" }, + { url = "https://files.pythonhosted.org/packages/d7/ce/af88a49043cd2e265be63d083fc75b27b6ed062f5f9fd6cdc223ad62f03e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35", size = 789194, upload-time = "2025-09-25T21:32:43.362Z" }, + { url = "https://files.pythonhosted.org/packages/23/20/bb6982b26a40bb43951265ba29d4c246ef0ff59c9fdcdf0ed04e0687de4d/pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac", size = 156429, upload-time = "2025-09-25T21:32:57.844Z" }, + { url = "https://files.pythonhosted.org/packages/f4/f4/a4541072bb9422c8a883ab55255f918fa378ecf083f5b85e87fc2b4eda1b/pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3", size = 143912, upload-time = "2025-09-25T21:32:59.247Z" }, + { url = "https://files.pythonhosted.org/packages/7c/f9/07dd09ae774e4616edf6cda684ee78f97777bdd15847253637a6f052a62f/pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3", size = 189108, upload-time = "2025-09-25T21:32:44.377Z" }, + { url = "https://files.pythonhosted.org/packages/4e/78/8d08c9fb7ce09ad8c38ad533c1191cf27f7ae1effe5bb9400a46d9437fcf/pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba", size = 183641, upload-time = "2025-09-25T21:32:45.407Z" }, + { url = "https://files.pythonhosted.org/packages/7b/5b/3babb19104a46945cf816d047db2788bcaf8c94527a805610b0289a01c6b/pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c", size = 831901, upload-time = "2025-09-25T21:32:48.83Z" }, + { url = "https://files.pythonhosted.org/packages/8b/cc/dff0684d8dc44da4d22a13f35f073d558c268780ce3c6ba1b87055bb0b87/pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702", size = 861132, upload-time = "2025-09-25T21:32:50.149Z" }, + { url = "https://files.pythonhosted.org/packages/b1/5e/f77dc6b9036943e285ba76b49e118d9ea929885becb0a29ba8a7c75e29fe/pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c", size = 839261, upload-time = "2025-09-25T21:32:51.808Z" }, + { url = "https://files.pythonhosted.org/packages/ce/88/a9db1376aa2a228197c58b37302f284b5617f56a5d959fd1763fb1675ce6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065", size = 805272, upload-time = "2025-09-25T21:32:52.941Z" }, + { url = "https://files.pythonhosted.org/packages/da/92/1446574745d74df0c92e6aa4a7b0b3130706a4142b2d1a5869f2eaa423c6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65", size = 829923, upload-time = "2025-09-25T21:32:54.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/7a/1c7270340330e575b92f397352af856a8c06f230aa3e76f86b39d01b416a/pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9", size = 174062, upload-time = "2025-09-25T21:32:55.767Z" }, + { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" }, +] + +[[package]] +name = "pyyaml-env-tag" +version = "1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/eb/2e/79c822141bfd05a853236b504869ebc6b70159afc570e1d5a20641782eaa/pyyaml_env_tag-1.1.tar.gz", hash = "sha256:2eb38b75a2d21ee0475d6d97ec19c63287a7e140231e4214969d0eac923cd7ff", size = 5737, upload-time = "2025-05-13T15:24:01.64Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/11/432f32f8097b03e3cd5fe57e88efb685d964e2e5178a48ed61e841f7fdce/pyyaml_env_tag-1.1-py3-none-any.whl", hash = "sha256:17109e1a528561e32f026364712fee1264bc2ea6715120891174ed1b980d2e04", size = 4722, upload-time = "2025-05-13T15:23:59.629Z" }, +] + +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + +[[package]] +name = "ruff" +version = "0.15.22" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3a/06/ae069393fc66e8ff33036d4b368003833bf6e88ccf182e17e7a2f1c754fd/ruff-0.15.22.tar.gz", hash = "sha256:3f15175b1fb580126f58285a5dae6b2ea89000136d980c64499211f116b54809", size = 4785063, upload-time = "2026-07-16T15:14:13.244Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/23/18/ee54b7ae1e121be7a28ea6da4b67564ebb0530e183a54415ab7e3bcd2c4e/ruff-0.15.22-py3-none-linux_armv6l.whl", hash = "sha256:44423e73493737f5e7c5b41d475483898ff37afcdae38bc3da5085e29af1c2d8", size = 10781258, upload-time = "2026-07-16T15:13:19.452Z" }, + { url = "https://files.pythonhosted.org/packages/2f/d2/2520cb14761ddbeaf57642a76942fc36adcbdbe53b4532241995f6fc485c/ruff-0.15.22-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:b82c6482946e9eda7ff2e091d25b8bad3f718684e1916d41bd56873cee05b697", size = 10999477, upload-time = "2026-07-16T15:13:23.318Z" }, + { url = "https://files.pythonhosted.org/packages/c9/10/74e53572aa758dfaa678c2a2646b5c5515d884b7ca56be4d2ce03ca4b560/ruff-0.15.22-py3-none-macosx_11_0_arm64.whl", hash = "sha256:11c1c715af53a09f714e011106bffc419751ec8232fcb5da42173284ea3fec6f", size = 10466716, upload-time = "2026-07-16T15:13:26.162Z" }, + { url = "https://files.pythonhosted.org/packages/1e/cc/44eaaf0844e028182f2d0a8f2190d0f359159aed0a9e5ab861d892f1ae2a/ruff-0.15.22-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:742a29cf29bddb7c8327895d6a10e0e6c5b38a96dd407af9b5d0857f809c0576", size = 10892644, upload-time = "2026-07-16T15:13:29.229Z" }, + { url = "https://files.pythonhosted.org/packages/9f/21/8edf559014d2b0f82beea19cfb713993ad802ccda16868769979c6090a84/ruff-0.15.22-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:72af58b951b0ae395935ae79763dc349bc0eb706319d28f7a33ad2cfb3cfc178", size = 10576719, upload-time = "2026-07-16T15:13:32.35Z" }, + { url = "https://files.pythonhosted.org/packages/bf/1e/3a13abd392a3b50b62e5938a831f9ab6e588358cacad5c18545b716d2182/ruff-0.15.22-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:62d425005c1835eb24e2ee4161cb90e8db263415f4a71c8c72c33abaa6c0c224", size = 11376494, upload-time = "2026-07-16T15:13:35.958Z" }, + { url = "https://files.pythonhosted.org/packages/bf/3e/422d3d95bcf04dd78e1aeac22184d4f9a8fb2c01865d39d44618484a0317/ruff-0.15.22-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e8b9b3f8779a4f08c969defc3c8c35abffaa757e601ed5ae66d6d1db6519969a", size = 12208370, upload-time = "2026-07-16T15:13:39.185Z" }, + { url = "https://files.pythonhosted.org/packages/1e/91/5d065a0e0a02bf4813f5119ad278462eed081d2b832eb7c021ade0ec9e65/ruff-0.15.22-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1e0dd1b2e4d3d585f897a0d137cbf4eaf6223bef4e8ce34d6bb12556c5f9249e", size = 11581098, upload-time = "2026-07-16T15:13:42.132Z" }, + { url = "https://files.pythonhosted.org/packages/f6/f9/a0d4871d12fae702eb1f41b686caf05f1f8b124dc6db6f784f53d74918fa/ruff-0.15.22-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:365523eb91d9224e1bcb03b022fbf0facb8f9e23792a2c53d9d4b3924bdbdebb", size = 11399422, upload-time = "2026-07-16T15:13:45.2Z" }, + { url = "https://files.pythonhosted.org/packages/18/80/c843a5176cddbceb0b7e8dd41cf9993490796c1c469348d384f5a5c13c56/ruff-0.15.22-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:fabfd168afdf29fee5be98b831efa9683c94d7c5a3b58b9ce5a2e38444589a74", size = 11381683, upload-time = "2026-07-16T15:13:48.46Z" }, + { url = "https://files.pythonhosted.org/packages/d4/00/8485de0ae92239438a36cfc51350db9b9e85c9ebdfaea91b18e422706662/ruff-0.15.22-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:225dbf095a87f1d9f90f5fd7924d2613ee452a75a4308c63a8f50f761787aa7c", size = 10850295, upload-time = "2026-07-16T15:13:51.655Z" }, + { url = "https://files.pythonhosted.org/packages/fa/91/24977ec2ec72eaf15e4394ace2959fdff2dd1e14f03e005e838023407169/ruff-0.15.22-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:1877d63b9d24ed278744f1523fd11b85540566d54641f97c566d7d9dc5ca5296", size = 10579640, upload-time = "2026-07-16T15:13:54.79Z" }, + { url = "https://files.pythonhosted.org/packages/9c/47/9b51216951974df1f263ac19da550d34252e0ed7218c25f10c5ef9ed7517/ruff-0.15.22-py3-none-musllinux_1_2_i686.whl", hash = "sha256:a1606c510bd7215680d32efab38965f7cdec3ef69f5170a3f4791404ffdd5262", size = 11105077, upload-time = "2026-07-16T15:13:57.915Z" }, + { url = "https://files.pythonhosted.org/packages/c2/47/20e9d4a3b8016778acea5fc32bb50d35d207500a17ddb529ffa6996feef8/ruff-0.15.22-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:630479b18625f5ffc373f77603a22a9f8ac0acd7ff0501178b5db28ec71e9c64", size = 11490980, upload-time = "2026-07-16T15:14:01.032Z" }, + { url = "https://files.pythonhosted.org/packages/4d/76/3f72d8fc38c1cb77b38c56a70da9d0c17700cc1cc50f9649c9d3c8f5ba71/ruff-0.15.22-py3-none-win32.whl", hash = "sha256:e5ba0e4a13fd14abbed2a77b517a3911290c6c6c59ef67784328d1668fab76cf", size = 10789165, upload-time = "2026-07-16T15:14:04.16Z" }, + { url = "https://files.pythonhosted.org/packages/cb/46/4965251734c2b6fcdca1b1b187d20bcac3af0ee5b083b89c910bb961ce3a/ruff-0.15.22-py3-none-win_amd64.whl", hash = "sha256:9be63ba1eb936acd2d1342fb8337c356353706fce233b2a15a09a97037e6acde", size = 11938297, upload-time = "2026-07-16T15:14:07.316Z" }, + { url = "https://files.pythonhosted.org/packages/57/c9/e69b1ff4c8b69093ef08b8919ab767af0569666865b39c30a8795d88d3c6/ruff-0.15.22-py3-none-win_arm64.whl", hash = "sha256:e1168075b72158510839f250027659cdd78476f40507dd517892304c41318661", size = 11298172, upload-time = "2026-07-16T15:14:10.51Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + +[[package]] +name = "sortedcontainers" +version = "2.4.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e8/c4/ba2f8066cceb6f23394729afe52f3bf7adec04bf9ed2c820b39e19299111/sortedcontainers-2.4.0.tar.gz", hash = "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88", size = 30594, upload-time = "2021-05-16T22:03:42.897Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl", hash = "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0", size = 29575, upload-time = "2021-05-16T22:03:41.177Z" }, +] + +[[package]] +name = "urllib3" +version = "2.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, +] + +[[package]] +name = "watchdog" +version = "6.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/db/7d/7f3d619e951c88ed75c6037b246ddcf2d322812ee8ea189be89511721d54/watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282", size = 131220, upload-time = "2024-11-01T14:07:13.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/ea/3930d07dafc9e286ed356a679aa02d777c06e9bfd1164fa7c19c288a5483/watchdog-6.0.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:bdd4e6f14b8b18c334febb9c4425a878a2ac20efd1e0b231978e7b150f92a948", size = 96471, upload-time = "2024-11-01T14:06:37.745Z" }, + { url = "https://files.pythonhosted.org/packages/12/87/48361531f70b1f87928b045df868a9fd4e253d9ae087fa4cf3f7113be363/watchdog-6.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c7c15dda13c4eb00d6fb6fc508b3c0ed88b9d5d374056b239c4ad1611125c860", size = 88449, upload-time = "2024-11-01T14:06:39.748Z" }, + { url = "https://files.pythonhosted.org/packages/5b/7e/8f322f5e600812e6f9a31b75d242631068ca8f4ef0582dd3ae6e72daecc8/watchdog-6.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6f10cb2d5902447c7d0da897e2c6768bca89174d0c6e1e30abec5421af97a5b0", size = 89054, upload-time = "2024-11-01T14:06:41.009Z" }, + { url = "https://files.pythonhosted.org/packages/68/98/b0345cabdce2041a01293ba483333582891a3bd5769b08eceb0d406056ef/watchdog-6.0.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:490ab2ef84f11129844c23fb14ecf30ef3d8a6abafd3754a6f75ca1e6654136c", size = 96480, upload-time = "2024-11-01T14:06:42.952Z" }, + { url = "https://files.pythonhosted.org/packages/85/83/cdf13902c626b28eedef7ec4f10745c52aad8a8fe7eb04ed7b1f111ca20e/watchdog-6.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:76aae96b00ae814b181bb25b1b98076d5fc84e8a53cd8885a318b42b6d3a5134", size = 88451, upload-time = "2024-11-01T14:06:45.084Z" }, + { url = "https://files.pythonhosted.org/packages/fe/c4/225c87bae08c8b9ec99030cd48ae9c4eca050a59bf5c2255853e18c87b50/watchdog-6.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a175f755fc2279e0b7312c0035d52e27211a5bc39719dd529625b1930917345b", size = 89057, upload-time = "2024-11-01T14:06:47.324Z" }, + { url = "https://files.pythonhosted.org/packages/a9/c7/ca4bf3e518cb57a686b2feb4f55a1892fd9a3dd13f470fca14e00f80ea36/watchdog-6.0.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7607498efa04a3542ae3e05e64da8202e58159aa1fa4acddf7678d34a35d4f13", size = 79079, upload-time = "2024-11-01T14:06:59.472Z" }, + { url = "https://files.pythonhosted.org/packages/5c/51/d46dc9332f9a647593c947b4b88e2381c8dfc0942d15b8edc0310fa4abb1/watchdog-6.0.0-py3-none-manylinux2014_armv7l.whl", hash = "sha256:9041567ee8953024c83343288ccc458fd0a2d811d6a0fd68c4c22609e3490379", size = 79078, upload-time = "2024-11-01T14:07:01.431Z" }, + { url = "https://files.pythonhosted.org/packages/d4/57/04edbf5e169cd318d5f07b4766fee38e825d64b6913ca157ca32d1a42267/watchdog-6.0.0-py3-none-manylinux2014_i686.whl", hash = "sha256:82dc3e3143c7e38ec49d61af98d6558288c415eac98486a5c581726e0737c00e", size = 79076, upload-time = "2024-11-01T14:07:02.568Z" }, + { url = "https://files.pythonhosted.org/packages/ab/cc/da8422b300e13cb187d2203f20b9253e91058aaf7db65b74142013478e66/watchdog-6.0.0-py3-none-manylinux2014_ppc64.whl", hash = "sha256:212ac9b8bf1161dc91bd09c048048a95ca3a4c4f5e5d4a7d1b1a7d5752a7f96f", size = 79077, upload-time = "2024-11-01T14:07:03.893Z" }, + { url = "https://files.pythonhosted.org/packages/2c/3b/b8964e04ae1a025c44ba8e4291f86e97fac443bca31de8bd98d3263d2fcf/watchdog-6.0.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:e3df4cbb9a450c6d49318f6d14f4bbc80d763fa587ba46ec86f99f9e6876bb26", size = 79078, upload-time = "2024-11-01T14:07:05.189Z" }, + { url = "https://files.pythonhosted.org/packages/62/ae/a696eb424bedff7407801c257d4b1afda455fe40821a2be430e173660e81/watchdog-6.0.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:2cce7cfc2008eb51feb6aab51251fd79b85d9894e98ba847408f662b3395ca3c", size = 79077, upload-time = "2024-11-01T14:07:06.376Z" }, + { url = "https://files.pythonhosted.org/packages/b5/e8/dbf020b4d98251a9860752a094d09a65e1b436ad181faf929983f697048f/watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:20ffe5b202af80ab4266dcd3e91aae72bf2da48c0d33bdb15c66658e685e94e2", size = 79078, upload-time = "2024-11-01T14:07:07.547Z" }, + { url = "https://files.pythonhosted.org/packages/07/f6/d0e5b343768e8bcb4cda79f0f2f55051bf26177ecd5651f84c07567461cf/watchdog-6.0.0-py3-none-win32.whl", hash = "sha256:07df1fdd701c5d4c8e55ef6cf55b8f0120fe1aef7ef39a1c6fc6bc2e606d517a", size = 79065, upload-time = "2024-11-01T14:07:09.525Z" }, + { url = "https://files.pythonhosted.org/packages/db/d9/c495884c6e548fce18a8f40568ff120bc3a4b7b99813081c8ac0c936fa64/watchdog-6.0.0-py3-none-win_amd64.whl", hash = "sha256:cbafb470cf848d93b5d013e2ecb245d4aa1c8fd0504e863ccefa32445359d680", size = 79070, upload-time = "2024-11-01T14:07:10.686Z" }, + { url = "https://files.pythonhosted.org/packages/33/e8/e40370e6d74ddba47f002a32919d91310d6074130fe4e17dabcafc15cbf1/watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f", size = 79067, upload-time = "2024-11-01T14:07:11.845Z" }, +] + +[[package]] +name = "zarr-indexing" +source = { editable = "." } +dependencies = [ + { name = "numpy" }, +] + +[package.optional-dependencies] +testing = [ + { name = "hypothesis" }, +] + +[package.dev-dependencies] +docs = [ + { name = "griffe-inherited-docstrings" }, + { name = "mkdocs" }, + { name = "mkdocs-material" }, + { name = "mkdocstrings" }, + { name = "mkdocstrings-python" }, + { name = "ruff" }, +] +test = [ + { name = "hypothesis" }, + { name = "pytest" }, +] + +[package.metadata] +requires-dist = [ + { name = "hypothesis", marker = "extra == 'testing'", specifier = ">=6.160.0" }, + { name = "numpy", specifier = ">=2" }, +] +provides-extras = ["testing"] + +[package.metadata.requires-dev] +docs = [ + { name = "griffe-inherited-docstrings", specifier = "==1.1.3" }, + { name = "mkdocs", specifier = "==1.6.1" }, + { name = "mkdocs-material", specifier = "==9.7.7" }, + { name = "mkdocstrings", specifier = "==1.0.6" }, + { name = "mkdocstrings-python", specifier = "==2.0.5" }, + { name = "ruff", specifier = "==0.15.22" }, +] +test = [ + { name = "hypothesis", specifier = ">=6.160.0" }, + { name = "pytest" }, +] diff --git a/packages/zarr-metadata/.readthedocs.yaml b/packages/zarr-metadata/.readthedocs.yaml new file mode 100644 index 0000000000..828773818c --- /dev/null +++ b/packages/zarr-metadata/.readthedocs.yaml @@ -0,0 +1,43 @@ +# Read the Docs configuration for the zarr-metadata docs site, separate from +# the zarr-python site configured by the repo-root .readthedocs.yaml. The RTD +# project for zarr-metadata must set its configuration-file path to +# packages/zarr-metadata/.readthedocs.yaml. +version: 2 + +build: + os: ubuntu-22.04 + tools: + python: "3.12" + jobs: + post_checkout: + # Cancel pull request builds that do not touch this package. Exit code + # 183 cancels the build and reports success to the Git provider. Scoped + # to PR builds ("external" versions) because origin/main is only a + # meaningful diff base there. + - | + if [ "$READTHEDOCS_VERSION_TYPE" = "external" ] && git diff --quiet origin/main -- packages/zarr-metadata; + then + exit 183; + fi + install: + - pip install --upgrade pip + - pip install ./packages/zarr-metadata --group packages/zarr-metadata/pyproject.toml:docs + build: + html: + # Build from inside the package rather than pointing `-f` at its config + # from the repo root. mkdocs resolves some settings relative to the + # current working directory rather than to the config file, so building + # from elsewhere looks for them in the wrong place -- and silently, since + # the paths are valid, just wrong. zarr-indexing hit this: with + # `pymdownx.snippets` and a relative `base_path`, its snippets were + # searched for under the repo-root docs/ and the build failed with + # SnippetMissingError, while `just docs-check` passed because it runs + # from here. Building from the package directory makes this identical to + # the local and CI invocations, so a green build there means a green + # build here. + # + # $READTHEDOCS_OUTPUT is absolute, so the cd does not affect it. + - cd packages/zarr-metadata && mkdocs build --strict --site-dir $READTHEDOCS_OUTPUT/html + +mkdocs: + configuration: packages/zarr-metadata/mkdocs.yml diff --git a/packages/zarr-metadata/CHANGELOG.md b/packages/zarr-metadata/CHANGELOG.md new file mode 100644 index 0000000000..c1e9f81a61 --- /dev/null +++ b/packages/zarr-metadata/CHANGELOG.md @@ -0,0 +1,346 @@ +# Release notes + + + +## 0.5.0 (2026-08-14) + +### Bugfixes + +- `JSONValue`'s array arm is now the covariant `Sequence["JSONValue"]` rather + than the invariant `list["JSONValue"] | tuple["JSONValue", ...]`. Values typed + with a narrower element type β€” a `list[str]` field on a TypedDict, a + `Sequence[float]` β€” now count as JSON values, and TypedDicts whose fields + carry precise types are now assignable to `Mapping[str, JSONValue]`. + Type-level cost, accepted deliberately: `Sequence` says nothing about the + concrete container and admits `str`/`bytes`, so runtime code narrowing a JSON + array must exclude `str`/`bytes`/`bytearray` β€” as it already had to, since + `str` was always a union arm. ([#4264](https://github.com/zarr-developers/zarr-python/pull/4264)) + +### Deprecations and Removals + +- Unified the naming grammar for SCREAMING_SNAKE constants with the one used for + type names. A constant's name is now a purely syntactic transformation of the + name of the `Literal` type it manifests, so the format version is spelled + `ZARR_V2`/`ZARR_V3` and comes first, matching the `ZarrV2`/`ZarrV3` prefix on + the corresponding type: + + - `ARRAY_METADATA_STORE_KEY_V2` β†’ `ZARR_V2_ARRAY_METADATA_STORE_KEY` + - `ARRAY_METADATA_STORE_KEY_V3` β†’ `ZARR_V3_ARRAY_METADATA_STORE_KEY` + - `ATTRIBUTES_STORE_KEY_V2` β†’ `ZARR_V2_ATTRIBUTES_STORE_KEY` + - `GROUP_METADATA_STORE_KEY_V2` β†’ `ZARR_V2_GROUP_METADATA_STORE_KEY` + - `GROUP_METADATA_STORE_KEY_V3` β†’ `ZARR_V3_GROUP_METADATA_STORE_KEY` + - `CONSOLIDATED_METADATA_STORE_KEY_V2` β†’ `ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY` + - `ARRAY_ORDER_V2` β†’ `ZARR_V2_ARRAY_ORDER` + - `ARRAY_DIMENSION_SEPARATOR_V2` β†’ `ZARR_V2_ARRAY_DIMENSION_SEPARATOR` + - `CONSOLIDATED_METADATA_KEY_V3` β†’ `ZARR_V3_CONSOLIDATED_METADATA_KEY` + + The old names are removed, not aliased. This supersedes the 0.4.0 convention + under which type names put the format version first while constants put it + last: every constant that manifests a `Literal` type now follows the same rule + as that type. + + The last of those is the one rename the syntactic rule does not force: + `ZARR_V3_CONSOLIDATED_METADATA_KEY` manifests no `Literal` type, so it is + outside the rule and was renamed for consistency with its siblings. + + Digit runs stay glued to the token they follow, so spec vocabulary is + preserved: `Uint8DataTypeName` pairs with `UINT8_DATA_TYPE_NAME` (not + `UINT_8_...`) and `Crc32cCodecName` with `CRC32C_CODEC_NAME`. No dtype, codec, + chunk-grid, or chunk-key-encoding constant changed name. + + Constants that do not manifest a `Literal` type are outside the rule and are + unchanged: the `*_METADATA_*_KEYS_V2`/`_V3` key sets, the + `CANONICAL_*_HEX_FLOAT*` bit patterns, and `UNSET`. The key sets keep the + version-last spelling, so `zarr_metadata.model` exports both + `ARRAY_METADATA_REQUIRED_KEYS_V2` and `ZARR_V2_ARRAY_METADATA_STORE_KEY`. They + name validation policy rather than a spec document, have no paired type to + derive from, and renaming them would be a second breaking change buying only + cosmetic consistency β€” so it is deliberately deferred. + + `tests/test_public_api.py::test_constant_names_derive_from_their_type_names` + derives every constant name from the type it manifests and asserts they match, + so the two grammars cannot diverge again. + + Store keys also moved to the modules that describe the documents they name, + matching the package's layering (the `v2`/`v3` modules describe the specs; the + `model` layer is built on top of them). `ZARR_V2_ATTRIBUTES_STORE_KEY` now + lives in `zarr_metadata.v2.attributes` beside the `.zattrs` type it names, + rather than in the array model; the other five moved likewise, and + `ZarrV2AttributesStoreKey` is no longer an array-specific concept. + `zarr_metadata.model` re-exports all six, so + `from zarr_metadata.model import ZARR_V2_ARRAY_METADATA_STORE_KEY` is + unaffected. + + `CONSOLIDATED_METADATA_KEY_V3` moved to `zarr_metadata.v3.consolidated` and was + renamed to `ZARR_V3_CONSOLIDATED_METADATA_KEY` for consistency. It is not a + store key: unlike v2's `.zmetadata` file, v3 consolidated metadata is embedded + as an extension field inside the group's own `zarr.json`. + + All seven keys and the six store-key `Literal` aliases are now also exported + from the top-level `zarr_metadata` namespace, alongside the document types and + the rest of the spec vocabulary, so `from zarr_metadata import + ZARR_V2_ARRAY_METADATA_STORE_KEY` works. The model layer's validators, parsers, + type guards, and metadata key sets remain `zarr_metadata.model` imports. + + ([#4232](https://github.com/zarr-developers/zarr-python/pull/4232)) + +### Misc + +- The source distribution now ships an explicit allowlist (`/src`, `/tests`, + `/docs`, `/mkdocs.yml`, `/justfile`, `/CHANGELOG.md`) rather than whatever + happens to sit in the package directory, so an sdist both tests and documents + itself and cannot pick up scratch files from the tree it was built in. ([#4248](https://github.com/zarr-developers/zarr-python/pull/4248)) + + +## 0.4.0 (2026-07-29) + +### Features + +- Added `zarr_metadata.model`: frozen-dataclass models (`ZarrV2ArrayMetadata`, + `ZarrV3ArrayMetadata`, `ZarrV2GroupMetadata`, `ZarrV3GroupMetadata`, + `ZarrV2ConsolidatedMetadata`, `ZarrV3ConsolidatedMetadata`, `ZarrV3NamedConfig`) + that are canonical, semantically lossless representations of Zarr metadata + documents, plus structural validators (`validate_*` / `is_*` / `parse_*`). + Every v3 extension point (data type, chunk grid, chunk key encoding, codecs, + storage transformers) is held as `ZarrV3NamedConfig`: a name, configuration, + and `must_understand` obligation; nothing is interpreted. On the wire, an + empty configuration with the default obligation uses the spec's plain-string + shorthand. Model fields are annotated with the role alias + `ZarrV3MetadataField` (today exactly `ZarrV3NamedConfig`), so annotations + convey the logical meaning and stay put if the spec adds another field form. + + Validation is strict about what the types declare: v2 `dtype` / `order` / + `compressor` / `filters` / `dimension_separator` shapes and the fixed + `zarr_format` / `node_type` literals are all enforced. Every + `ValidationProblem` carries a machine-readable `kind` + (`missing_key` / `invalid_type` / `invalid_value` / `invalid_json`) so + consumers can dispatch on the failure mode without matching message strings, + and every ingestion failure β€” including missing store keys and undecodable + bytes in `from_key_value` β€” surfaces as `MetadataValidationError`. An + adversarial review added further structural checks: JSON booleans are not + accepted as dimension lengths, dimensions are non-negative, + `dimension_names` must have one entry per dimension of `shape`, `attributes` + and `configuration` values are JSON-checked recursively (like `fill_value`), + non-finite floats and non-standard JSON constants are rejected, abstract + mappings and sequences normalize to encoder-safe canonical containers, + v2 `shape` and `chunks` must have the same rank, non-null v2 filter pipelines + contain at least one filter, document `TypeIs` guards only narrow values that + already use the declared canonical containers, + and the inline consolidated-metadata envelope and entries are deep-validated + so the group validator's verdict always agrees with the model constructor. + + The v3 models expose `must_understand_fields`: the subset of `extra_fields` + not explicitly waived with `must_understand: false` (fields are implicitly + must-understand per the spec). Readers discharge the spec's fail-to-open + duty by subtracting the extension names they recognize; the model only + partitions by obligation, since recognition is reader-specific. + + Optional pydantic integration ships as `zarr_metadata.pydantic` (importing it + requires pydantic 2.13 or newer; the core package does not depend on it): one + `Annotated` + field type per model, validating raw documents through `from_json`, passing + core-model instances through unchanged, serializing via `to_json`, and + publishing JSON Schemas derived from private constrained document types that + mirror the independently expressible runtime rules. Cross-field cardinality + relations still require runtime validation. The instances are the core model + classes, so values interoperate freely with non-pydantic code. + + `create_default` keeps its output self-consistent: overriding `shape` without + a chunk grid derives one regular chunk covering the array (v3 + `chunk_shape == shape`; v2 `chunks == shape`) instead of silently keeping the + scalar default's 0-d grid. + + A v2 `.zarray` that omits `dimension_separator` is interpreted with the v2 + convention's default `"."` (the model previously normalized absence to `"/"`, + which would misaddress the chunks of real-world default-separator arrays). + The value is never null: absent, `"."`, or `"/"` are the only spellings. + + Optional document keys use `UNSET` β€” a PEP 661 sentinel + (`typing_extensions.Sentinel`), usable directly in type expressions β€” never + `None`: in a model, `None` always corresponds to a JSON `null` in the + document (a v2 `compressor`, an unnamed dimension inside `dimension_names`), + and `UNSET` always means the key is absent. Checker note: ty types the + sentinel exactly; pyright needs `<= 1.1.404` until microsoft/pyright#11115 + is fixed (this package's CI pins it); mypy users need a `cast` or + `type: ignore` at narrowing sites until python/mypy#21647 merges. This keeps semantically distinct spellings + distinct β€” an absent `dimension_names` ("there are no dimension names") and + an explicit `[null, null]` ("every dimension has a name, which is null") are + different documents and round-trip as such. The `consolidated_metadata: null` + written by a historical zarr-python bug is the one deliberate exception to + faithful round-tripping: those stores remain readable, but the bug spelling + is repaired to absence on read and never written back. + + The v2 models treat the `.zattrs` file's presence as part of the store: + `attributes` is `UNSET` when no `.zattrs` file exists (and `to_key_value` + emits none), while an explicit empty `.zattrs` is `{}` and round-trips as a + file. Previously `to_key_value` always emitted `.zattrs`, silently adding a + file to stores that never had one. + + The store-key `Literal` aliases (`ZarrV2ArrayMetadataStoreKey`, + `ZarrV2AttributesStoreKey`, ...) are exported from `zarr_metadata.model` + alongside their constants, and each `to_key_value` return type is keyed by + them, so the set of store keys a model can emit is visible in its signature. + `from_key_value` deliberately keeps `Mapping[str, bytes]` input: it accepts + any string-keyed store mapping and ignores unrelated keys. + + `to_json` returns a document that shares no mutable state with the model: + every value that can hold a mutable container (attributes, configurations, + extra fields, v2 codec configurations, fill values, consolidated entries) is + deep-copied on the way out, so editing a serialized document can never + silently mutate the frozen model that produced it. ([#4119](https://github.com/zarr-developers/zarr-python/issues/4119)) + +### Improved Documentation + +- `zarr-metadata` now has a standalone documentation site at + , with a comprehensive API reference + covering every public module, versioned by this package's release tags. The + package also gained a `justfile` collecting its development commands + (`test`, `lint`, `typecheck`, `docs-check`, `docs-serve`, `changelog-draft`), + which the package CI workflow now delegates to. ([#4208](https://github.com/zarr-developers/zarr-python/issues/4208)) + +### Deprecations and Removals + +- The document (TypedDict) types are renamed to put the format version at the + front of the name and to mark the JSON-document form with a `JSON` suffix, + so a format version can never be misread as a class revision and the bare + entity names are reserved for the `zarr_metadata.model` dataclasses: + + - `ArrayMetadataV2` β†’ `ZarrV2ArrayMetadataJSON` (and `...Partial` accordingly) + - `ArrayMetadataV3` β†’ `ZarrV3ArrayMetadataJSON` (and `...Partial` accordingly) + - `GroupMetadataV2` β†’ `ZarrV2GroupMetadataJSON` (and `...Partial` accordingly) + - `GroupMetadataV3` β†’ `ZarrV3GroupMetadataJSON` (and `...Partial` accordingly) + - `ConsolidatedMetadataV2` β†’ `ZarrV2ConsolidatedMetadataJSON` + - `ConsolidatedMetadataV3` β†’ `ZarrV3ConsolidatedMetadataJSON` + - `NamedConfigV3` β†’ `ZarrV3NamedConfigJSON` + - `MetadataV3` β†’ `ZarrV3MetadataFieldJSON` (the union of the bare-name and + named-configuration spellings of one metadata field) + - `ExtensionFieldV3` β†’ `ZarrV3ExtensionField` + - `CodecMetadataV2` β†’ `ZarrV2CodecMetadata` + - `DataTypeMetadataV2` β†’ `ZarrV2DataTypeMetadata` + - `ArrayOrderV2` β†’ `ZarrV2ArrayOrder` + - `ArrayDimensionSeparatorV2` β†’ `ZarrV2ArrayDimensionSeparator` + - `ZArrayMetadata` β†’ `ZarrV2ZArrayJSON` (the strict on-disk `.zarray` document) + - `ZGroupMetadata` β†’ `ZarrV2ZGroupJSON` (the strict on-disk `.zgroup` document) + - `ZAttrsMetadata` β†’ `ZarrV2ZAttrsJSON` (the `.zattrs` document) + + The old names are removed, not aliased. The `zarr_metadata.pydantic` field + types take the bare entity names (`ZarrV3ArrayMetadata`, ...), matching the + model classes they validate into. + + The conventions, stated once for future additions: CamelCase type names put + the format version first (`ZarrV2ArrayMetadataJSON`, + `ZarrV3ArrayMetadataStoreKey`), while SCREAMING_SNAKE constants and + snake_case functions put it last (`ARRAY_METADATA_STORE_KEY_V2`, + `validate_array_metadata_v3`). The `JSON` suffix marks a raw-document type + whose bare name is taken by (or reserved for) a `zarr_metadata.model` + dataclass; raw field-level types the models hold verbatim + (`ZarrV2CodecMetadata`, `ZarrV3ExtensionField`) keep their bare names. + Extension-entity types put the registered entity name first and end in + exactly one role suffix (`BloscCodecMetadata`, `Uint8DataTypeName`) β€” the + `V2` in `V2ChunkKeyEncodingMetadata` is that encoding's entity name, not a + format version, which is always spelled `ZarrV2`/`ZarrV3`. Every public + type name is checked against this grammar by + `tests/test_public_api.py::test_public_type_names_comply_with_naming_grammar`. + + ([#4119](https://github.com/zarr-developers/zarr-python/issues/4119)) + + +## 0.3.0 (2026-06-19) + +### Deprecations and Removals + +- Introduces a new `JSONValue` type that models python objects that serialize directly to JSON. This type is used to annotate the contents of `attributes` and `fill_value` fields, replacing the use of the overly wide `object` type. This is technically a breaking change. ([#4037](https://github.com/zarr-developers/zarr-python/pull/4037)) +- Promoted a curated "front door" of names to the top-level `zarr_metadata` + namespace, so consumers can write e.g. `from zarr_metadata import + ArrayMetadataV3, ShardingIndexLocation, BLOSC_CNAME` instead of importing from + deep submodule paths. The front door covers every metadata-document TypedDict, + each codec/chunk-grid/chunk-key-encoding canonical type, the full data-type + trio for every dtype, and every constant + `Literal` pair. Deep submodule paths + continue to work unchanged. + + Several promoted names were given clearer, less ambiguous spellings than their + deep-module names, since they now appear bare at the top level: + `Endian`/`ENDIAN` β†’ `Endianness`/`ENDIANNESS`, + `IndexLocation`/`INDEX_LOCATION` β†’ `ShardingIndexLocation`/`SHARDING_INDEX_LOCATION`, + `RoundingMode`/`ROUNDING_MODE` β†’ `CastRoundingMode`/`CAST_ROUNDING_MODE`, + `OutOfRangeMode`/`OUT_OF_RANGE_MODE` β†’ `CastOutOfRangeMode`/`CAST_OUT_OF_RANGE_MODE`, + `DateTimeUnit` β†’ `NumpyTimeUnit`, + `NamedConfig` β†’ `NamedConfigV3`, and + `MetadataFieldV3` β†’ `MetadataV3` (matching the name `zarrs` uses for this + `name`-or-`{name, configuration}` shape). + + Also added the `NUMPY_TIME_UNIT` runtime constant (a `Final` tuple paired with + the `NumpyTimeUnit` Literal) in `zarr_metadata.v3.data_type.numpy_timedelta64`. ([#4083](https://github.com/zarr-developers/zarr-python/pull/4083)) + + +## 0.2.0 (2026-05-19) + +### Bugfixes + +- `GzipCodecConfiguration.level` is now required, and `GzipCodecMetadata` + no longer accepts the bare-string `"gzip"` form. The codec's compressed + output depends on `level`, so metadata that omits it cannot reproducibly + identify the chunk bytes produced by a writer. **Breaking** for consumers + that previously typed gzip codec metadata as the bare string or + constructed a `GzipCodecConfiguration` without `level`. + ([#3978](https://github.com/zarr-developers/zarr-python/pull/3978)) +- `BytesCodecObject.configuration` is now `NotRequired`. The configuration + has no required keys (`endian` is conditionally required at runtime + based on data type), so the object form may omit it entirely β€” matching + the bare-string short-hand. **Soft-breaking** for consumers that + previously relied on `configuration` always being present. + ([#3978](https://github.com/zarr-developers/zarr-python/pull/3978)) +- Better modelling of Zarr v2 stored metadata. Zarr v2 splits a node's + metadata across two JSON documents (`.zarray`/`.zgroup` and `.zattrs`), + but `GroupMetadataV2` had no `attributes` field while `ArrayMetadataV2` + did β€” an inconsistency. `GroupMetadataV2` now also has an optional + `attributes` field, and `ArrayMetadataV2.attributes` is now + `NotRequired` for symmetry. **Soft-breaking** for consumers that + relied on `ArrayMetadataV2.attributes` always being present. + ([#3962](https://github.com/zarr-developers/zarr-python/pull/3962)) + +### Features + +- Added `ArrayMetadataV3Partial`, `GroupMetadataV3Partial`, + `ArrayMetadataV2Partial`, and `GroupMetadataV2Partial` β€” sibling + TypedDicts to the existing full metadata types, declared with + `total=False` so every field is `NotRequired`. Use these when typing + dicts that intentionally hold a subset of a complete metadata document + (test fixtures, fragment templates, in-progress builders). An + equivalence test pins each `Partial` to the keys and value types of + its full sibling so the two cannot drift. + ([#3982](https://github.com/zarr-developers/zarr-python/pull/3982)) +- Added three new top-level types modelling the **strict on-disk** shape + of Zarr v2 metadata documents: `ZArrayMetadata` (the `.zarray` file), + `ZGroupMetadata` (the `.zgroup` file), and `ZAttrsMetadata` (the + `.zattrs` file). Use these when you want a type that faithfully matches + what's stored on disk; use the merged `ArrayMetadataV2`/`GroupMetadataV2` + when you want the in-memory representation a Python program typically + works with. + ([#3962](https://github.com/zarr-developers/zarr-python/pull/3962)) +- Added typed constants exposing the spec-permitted values of constrained + Literal fields, importable at the per-codec module level. For example, + `from zarr_metadata.v3.codec.bytes import ENDIAN` provides + `("little", "big")` as a tuple, enabling runtime iteration or validator + generation without re-stating the Literal values by hand. + ([#3978](https://github.com/zarr-developers/zarr-python/pull/3978)) + +## 0.1.1 (2026-05-06) + +### Misc + +- First usable release on PyPI. Version 0.1.0 was uploaded then deleted to + reserve the project name; this version is the first one PyPI will install. + No source changes from 0.1.0. + ([#3949](https://github.com/zarr-developers/zarr-python/pull/3949)) + +## 0.1.0 (2026-05-01) + +### Features + +- Initial release. Provides `TypedDict` definitions and `Literal` aliases + for the JSON shapes specified by Zarr v2 and v3 metadata, plus a subset + of `zarr-extensions` types and the un-specified-but-widely-used + consolidated metadata documents. Pair with a runtime validator like + `pydantic` to check JSON loaded from disk. + ([#3919](https://github.com/zarr-developers/zarr-python/pull/3919)) diff --git a/packages/zarr-metadata/LICENSE.txt b/packages/zarr-metadata/LICENSE.txt new file mode 100644 index 0000000000..1e8da4d242 --- /dev/null +++ b/packages/zarr-metadata/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-2025 Zarr Developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/zarr-metadata/README.md b/packages/zarr-metadata/README.md new file mode 100644 index 0000000000..6b6b172aec --- /dev/null +++ b/packages/zarr-metadata/README.md @@ -0,0 +1,134 @@ +# zarr-metadata + +Python types, models, and validators for Zarr v2 and v3 metadata. + +Documentation: + +## What this is + +Two layers and an optional integration: + +- **Typed JSON shapes**: `TypedDict` definitions and `Literal` aliases for the + JSON documents specified by the [Zarr v2](https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html) + and [Zarr v3](https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html) + specifications, plus types for [`zarr-extensions`](https://github.com/zarr-developers/zarr-extensions/) + and a few widely-used-but-unspecified entities (e.g. consolidated metadata). +- **Document models** (`zarr_metadata.model`): canonical frozen-dataclass + models of whole metadata documents, with structural validators, loc-aware + parsers, and store-key (de)serialization. A document produced by `to_json` + shares no mutable state with the model that produced it. +- **Optional Pydantic integration** (`zarr_metadata.pydantic`, requires + Pydantic 2.13 or newer): each model as a Pydantic field type that validates + raw documents through the same strict parser. + +## What this is for + +The public `TypedDict` definitions describe the static JSON shape of Zarr +metadata. For strict, loc-aware validation of JSON loaded from disk, use the +model parser: + +```python +import json +from zarr_metadata.model import ZarrV3ArrayMetadata + +with open("zarr.json", "rb") as f: + raw = json.load(f) + +metadata = ZarrV3ArrayMetadata.from_json(raw) +``` + +The optional Pydantic integration delegates raw input to the same strict +parser and returns the same normalized model class: + +```python +from pydantic import TypeAdapter +import zarr_metadata.pydantic as zmp + +metadata = TypeAdapter(zmp.ZarrV3ArrayMetadata).validate_python(raw) +encoded = metadata.to_key_value()["zarr.json"] +``` + +A bare `TypeAdapter` over a public document `TypedDict` is a coercive shape +adapter, not a Zarr conformance validator; it may coerce values or discard +members that the strict model parser rejects. + +## Validation boundary + +The model validators enforce the declared document structure and a small set +of context-free consistency rules, including fixed format literals, finite +JSON numbers, non-negative dimensions, non-empty v3 codec pipelines, and one +`dimension_names` entry per array dimension. They do not interpret extension +names or configurations, resolve codec pipelines, or decide whether a data +type, chunk grid, codec, or storage transformer is supported. Those decisions +belong to consumer implementations. + +The Pydantic integration's generated JSON Schemas express independently +checkable document structure and field constraints, but they are not a +replacement for runtime model validation. Standard JSON Schema treats a +mathematically integral number such as `1.0` as an integer, while the runtime +boundary requires Python `int` values, and it cannot express arbitrary +same-length relations such as `dimension_names` versus `shape` or v2 `chunks` +versus `shape`. Consumers should run the model parser after schema validation. + +## Scope + +At minimum, this library supports what Zarr-Python needs: the complete +Zarr v2 and v3 specs, consolidated metadata, and a subset of the metadata +defined in `zarr-extensions`. We are generally open to contributions that +add types, models, or structural validation for Zarr metadata with a +published spec. + +Runtime array behavior is out of scope: nothing here encodes or decodes +chunks, resolves codec or data type names to implementations, or performs +store I/O. The models begin and end at the metadata documents themselves β€” +`from_key_value` / `to_key_value` map documents to store keys and bytes, +and everything past that belongs to consumer libraries. + +## Developing + +Package-scoped development commands live in the [`justfile`](./justfile) +(requires [just](https://github.com/casey/just)): + +``` +just test # run the test suite (extra args go to pytest) +just lint # ruff, same invocation as CI +just typecheck # pyright, pinned to the version CI uses +just docs-check # strict build of the docs site +just check # all of the above +just docs-serve # serve the docs site locally +``` + +Run them from this directory, or from anywhere in the repository as +`just packages/zarr-metadata/`. + +## Releasing + +The package version is derived from git tags by `hatch-vcs`. Tags must +match the pattern `zarr_metadata-v` (e.g. `zarr_metadata-v0.2.0`) +so they do not collide with the main `zarr-python` release tags. + +To cut a release: + +1. Create and push a tag of the form `zarr_metadata-v` on the + commit you want to publish, e.g.: + ``` + git tag zarr_metadata-v0.2.0 + git push origin zarr_metadata-v0.2.0 + ``` +2. Pushing the tag fires the `zarr-metadata release` workflow, which + builds the wheel/sdist (version resolved from the tag), runs an + install smoke test, and publishes to PyPI via OIDC trusted publishing. + +We intentionally do *not* create a GitHub Release for `zarr-metadata` +versions β€” GitHub Releases live at the repo level, and a zarr-metadata +release would surface in the zarr-python repo's Releases UI as if it +were a zarr-python release. + +To dry-run a build against TestPyPI, dispatch the workflow manually +(`Actions` β†’ `zarr-metadata release` β†’ `Run workflow`). Manual dispatches +build from the current commit; with no recent tag the version will look +like `0.1.devN`, which is fine for TestPyPI. + +## License + +[MIT](./LICENSE.txt) diff --git a/packages/zarr-metadata/changes/README.md b/packages/zarr-metadata/changes/README.md new file mode 100644 index 0000000000..bf0fc85425 --- /dev/null +++ b/packages/zarr-metadata/changes/README.md @@ -0,0 +1,25 @@ +Writing a changelog entry for `zarr-metadata` +--------------------------------------------- + +Fragments in **this** directory are released notes for the `zarr-metadata` +package only β€” kept separate from the parent zarr-python `changes/` +directory so a PR touching only `packages/zarr-metadata/` produces a +release note for this package only. + +Please put a new file in this directory named `xxxx..md`, where + +- `xxxx` is the pull request number associated with this entry +- `` is one of: + - feature + - bugfix + - doc + - removal + - misc + +Inside the file, please write a short description of what you have +changed, and how it impacts users of `zarr-metadata`. + +A `zarr-metadata` release runs `towncrier build` in `packages/zarr-metadata/`, +which consumes the fragments here and updates `CHANGELOG.md`. Fragments +that describe parent zarr-python changes (not the metadata package) +belong in the top-level `changes/` directory, not here. diff --git a/packages/zarr-metadata/docs/_static/favicon-96x96.png b/packages/zarr-metadata/docs/_static/favicon-96x96.png new file mode 100644 index 0000000000..e77977ccf4 Binary files /dev/null and b/packages/zarr-metadata/docs/_static/favicon-96x96.png differ diff --git a/packages/zarr-metadata/docs/_static/logo_bw.png b/packages/zarr-metadata/docs/_static/logo_bw.png new file mode 100644 index 0000000000..df1979d3cc Binary files /dev/null and b/packages/zarr-metadata/docs/_static/logo_bw.png differ diff --git a/packages/zarr-metadata/docs/api/index.md b/packages/zarr-metadata/docs/api/index.md new file mode 100644 index 0000000000..5e230c7aa2 --- /dev/null +++ b/packages/zarr-metadata/docs/api/index.md @@ -0,0 +1,34 @@ +--- +title: API reference +--- + +# API reference + +The package is organized to mirror the structure of the Zarr specifications: + +- [`zarr_metadata.model`](model.md) β€” frozen-dataclass document models, + structural validators, loc-aware parsers, and the `UNSET` sentinel +- [`zarr_metadata.pydantic`](pydantic.md) β€” optional Pydantic field types + over the models +- [`zarr_metadata.v2`](v2.md) β€” `TypedDict` shapes for Zarr v2 documents + (`.zarray`, `.zgroup`, `.zattrs`, `.zmetadata`) +- [`zarr_metadata.v3`](v3/index.md) β€” `TypedDict` shapes for Zarr v3 + documents, with subpackages for [chunk grids](v3/chunk_grid.md), + [chunk key encodings](v3/chunk_key_encoding.md), [codecs](v3/codec.md), + and [data types](v3/data_type.md) + +The document types, models, and spec vocabulary β€” including the store keys β€” +are re-exported at the top level, so +`from zarr_metadata import ZarrV3ArrayMetadataJSON` and +`from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON` are equivalent. +The model layer's validators, parsers, type guards, and metadata key sets are +imported from [`zarr_metadata.model`](model.md) directly. + +## Common types + +A few cross-cutting aliases are exported only from the top-level +`zarr_metadata` namespace: + +::: zarr_metadata.JSONValue + +::: zarr_metadata.ZarrV3NamedConfigJSON diff --git a/packages/zarr-metadata/docs/api/model.md b/packages/zarr-metadata/docs/api/model.md new file mode 100644 index 0000000000..c82ba98f2d --- /dev/null +++ b/packages/zarr-metadata/docs/api/model.md @@ -0,0 +1,5 @@ +--- +title: model +--- + +::: zarr_metadata.model diff --git a/packages/zarr-metadata/docs/api/pydantic.md b/packages/zarr-metadata/docs/api/pydantic.md new file mode 100644 index 0000000000..edecb416a7 --- /dev/null +++ b/packages/zarr-metadata/docs/api/pydantic.md @@ -0,0 +1,5 @@ +--- +title: pydantic +--- + +::: zarr_metadata.pydantic diff --git a/packages/zarr-metadata/docs/api/v2.md b/packages/zarr-metadata/docs/api/v2.md new file mode 100644 index 0000000000..2fe5b6ec56 --- /dev/null +++ b/packages/zarr-metadata/docs/api/v2.md @@ -0,0 +1,17 @@ +--- +title: v2 +--- + +::: zarr_metadata.v2 + options: + members: false + +::: zarr_metadata.v2.array + +::: zarr_metadata.v2.group + +::: zarr_metadata.v2.attributes + +::: zarr_metadata.v2.codec + +::: zarr_metadata.v2.consolidated diff --git a/packages/zarr-metadata/docs/api/v3/chunk_grid.md b/packages/zarr-metadata/docs/api/v3/chunk_grid.md new file mode 100644 index 0000000000..724b1c9d8d --- /dev/null +++ b/packages/zarr-metadata/docs/api/v3/chunk_grid.md @@ -0,0 +1,11 @@ +--- +title: chunk_grid +--- + +::: zarr_metadata.v3.chunk_grid + options: + members: false + +::: zarr_metadata.v3.chunk_grid.regular + +::: zarr_metadata.v3.chunk_grid.rectilinear diff --git a/packages/zarr-metadata/docs/api/v3/chunk_key_encoding.md b/packages/zarr-metadata/docs/api/v3/chunk_key_encoding.md new file mode 100644 index 0000000000..bb063deb25 --- /dev/null +++ b/packages/zarr-metadata/docs/api/v3/chunk_key_encoding.md @@ -0,0 +1,11 @@ +--- +title: chunk_key_encoding +--- + +::: zarr_metadata.v3.chunk_key_encoding + options: + members: false + +::: zarr_metadata.v3.chunk_key_encoding.default + +::: zarr_metadata.v3.chunk_key_encoding.v2 diff --git a/packages/zarr-metadata/docs/api/v3/codec.md b/packages/zarr-metadata/docs/api/v3/codec.md new file mode 100644 index 0000000000..cb96d2c7d5 --- /dev/null +++ b/packages/zarr-metadata/docs/api/v3/codec.md @@ -0,0 +1,25 @@ +--- +title: codec +--- + +::: zarr_metadata.v3.codec + options: + members: false + +::: zarr_metadata.v3.codec.blosc + +::: zarr_metadata.v3.codec.bytes + +::: zarr_metadata.v3.codec.cast_value + +::: zarr_metadata.v3.codec.crc32c + +::: zarr_metadata.v3.codec.gzip + +::: zarr_metadata.v3.codec.scale_offset + +::: zarr_metadata.v3.codec.sharding_indexed + +::: zarr_metadata.v3.codec.transpose + +::: zarr_metadata.v3.codec.zstd diff --git a/packages/zarr-metadata/docs/api/v3/data_type.md b/packages/zarr-metadata/docs/api/v3/data_type.md new file mode 100644 index 0000000000..f482c33201 --- /dev/null +++ b/packages/zarr-metadata/docs/api/v3/data_type.md @@ -0,0 +1,45 @@ +--- +title: data_type +--- + +::: zarr_metadata.v3.data_type + options: + members: false + +::: zarr_metadata.v3.data_type.bool + +::: zarr_metadata.v3.data_type.int8 + +::: zarr_metadata.v3.data_type.int16 + +::: zarr_metadata.v3.data_type.int32 + +::: zarr_metadata.v3.data_type.int64 + +::: zarr_metadata.v3.data_type.uint8 + +::: zarr_metadata.v3.data_type.uint16 + +::: zarr_metadata.v3.data_type.uint32 + +::: zarr_metadata.v3.data_type.uint64 + +::: zarr_metadata.v3.data_type.float16 + +::: zarr_metadata.v3.data_type.float32 + +::: zarr_metadata.v3.data_type.float64 + +::: zarr_metadata.v3.data_type.complex64 + +::: zarr_metadata.v3.data_type.complex128 + +::: zarr_metadata.v3.data_type.raw + +::: zarr_metadata.v3.data_type.bytes + +::: zarr_metadata.v3.data_type.string + +::: zarr_metadata.v3.data_type.numpy_datetime64 + +::: zarr_metadata.v3.data_type.numpy_timedelta64 diff --git a/packages/zarr-metadata/docs/api/v3/index.md b/packages/zarr-metadata/docs/api/v3/index.md new file mode 100644 index 0000000000..f20267d372 --- /dev/null +++ b/packages/zarr-metadata/docs/api/v3/index.md @@ -0,0 +1,15 @@ +--- +title: v3 +--- + +::: zarr_metadata.v3 + options: + members: false + +::: zarr_metadata.v3.ZarrV3MetadataFieldJSON + +::: zarr_metadata.v3.array + +::: zarr_metadata.v3.group + +::: zarr_metadata.v3.consolidated diff --git a/packages/zarr-metadata/docs/index.md b/packages/zarr-metadata/docs/index.md new file mode 100644 index 0000000000..58e4f290c6 --- /dev/null +++ b/packages/zarr-metadata/docs/index.md @@ -0,0 +1,98 @@ +# zarr-metadata + +Basic tools for modelling Zarr metadata, with minimal dependencies. + +`zarr-metadata` is developed in the +[zarr-python repository](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-metadata) +and released independently of `zarr` itself. Install it with: + +``` +pip install zarr-metadata +``` + +## Who needs this + +This library might be useful to you if your software interacts with Zarr metadata documents. + +## What this is + +This library is *not* a full Zarr implementation. Instead, it's a collection of data structures and routines that +closely model the content of the Zarr specifications, such as: + +- **Typed JSON shapes** ([`zarr_metadata.v2`](api/v2.md) and + [`zarr_metadata.v3`](api/v3/index.md)): `TypedDict` definitions and + `Literal` aliases for the JSON documents specified by the + [Zarr v2](https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html) and + [Zarr v3](https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html) + specifications, plus types for + [zarr-extensions](https://github.com/zarr-developers/zarr-extensions/) and a + few widely-used-but-unspecified entities (e.g. consolidated metadata). +- **Document models** ([`zarr_metadata.model`](api/model.md)): canonical + frozen-dataclass models of whole metadata documents, with structural + validators, loc-aware parsers, and store-key (de)serialization. A document + produced by `to_json` shares no mutable state with the model that produced + it. +- **Optional Pydantic integration** ([`zarr_metadata.pydantic`](api/pydantic.md), + requires Pydantic 2.13 or newer): each model as a Pydantic field type that + validates raw documents through the same strict parser. + +## What this is for + +The public `TypedDict` definitions describe the static JSON shape of Zarr +metadata. For strict, loc-aware validation of JSON loaded from disk, use the +model parser: + +```python +import json +from zarr_metadata.model import ZarrV3ArrayMetadata + +with open("zarr.json", "rb") as f: + raw = json.load(f) + +metadata = ZarrV3ArrayMetadata.from_json(raw) +``` + +The optional Pydantic integration delegates raw input to the same strict +parser and returns the same normalized model class: + +```python +from pydantic import TypeAdapter +import zarr_metadata.pydantic as zmp + +metadata = TypeAdapter(zmp.ZarrV3ArrayMetadata).validate_python(raw) +encoded = metadata.to_key_value()["zarr.json"] +``` + +A bare `TypeAdapter` over a public document `TypedDict` is a coercive shape +adapter, not a Zarr conformance validator; it may coerce values or discard +members that the strict model parser rejects. + +## Validation boundary + +The model validators enforce the declared document structure and a small set +of context-free consistency rules, including fixed format literals, finite +JSON numbers, non-negative dimensions, non-empty v3 codec pipelines, and one +`dimension_names` entry per array dimension. They do not interpret extension +names or configurations, resolve codec pipelines, or decide whether a data +type, chunk grid, codec, or storage transformer is supported. Those decisions +belong to consumer implementations. + +## Scope + +At minimum, this library supports what Zarr-Python needs: the complete +Zarr v2 and v3 specs, consolidated metadata, and a subset of the metadata +defined in `zarr-extensions`. We are generally open to contributions that +add types, models, or structural validation for Zarr metadata with a +published spec. + +Runtime array behavior is out of scope: nothing here encodes or decodes +chunks, resolves codec or data type names to implementations, or performs +store I/O. The models begin and end at the metadata documents themselves β€” +`from_key_value` / `to_key_value` map documents to store keys and bytes, +and everything past that belongs to consumer libraries. + +## Reference + +- [API reference](api/index.md) +- [Changelog](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-metadata/CHANGELOG.md) +- [License (MIT)](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-metadata/LICENSE.txt) diff --git a/packages/zarr-metadata/justfile b/packages/zarr-metadata/justfile new file mode 100644 index 0000000000..0f1861ed7d --- /dev/null +++ b/packages/zarr-metadata/justfile @@ -0,0 +1,58 @@ +# Development verbs for the zarr-metadata package. Recipes run with this +# directory as the working directory regardless of where `just` is invoked. + +# List available recipes +default: + @just --list + +# Run the test suite; extra args are passed to pytest +test *args: + uv run --group test pytest tests {{ args }} + +# Lint with the same invocation CI uses +lint: + uvx ruff check . + +# Pinned to the last pyright that types PEP 661 sentinels in class attributes +# correctly; 1.1.405+ regressed (microsoft/pyright#11115). Unpin when fixed. +pyright_version := "1.1.404" + +# CI runs pyright on python 3.11; the pinned pyright predates 3.14, whose +# stdlib it cannot parse, so pin the interpreter to match CI. +# Type-check the package sources +typecheck: + uv run --python 3.11 --group test --with 'pyright=={{ pyright_version }}' pyright src + +# Run everything CI runs for this package +check: lint typecheck test docs-check + +# Preview the changelog that the next release would generate +changelog-draft: + uvx towncrier build --draft --version Unreleased + +# Build this package's documentation site, warnings as errors +docs-check: + env DISABLE_MKDOCS_2_WARNING=true uv run --group docs mkdocs build --strict + +# With no argument, uses port 8000 if free, otherwise an ephemeral free port; +# an explicitly requested port is used as-is so a conflict fails loudly. +# Serve this package's documentation site +docs-serve port="": + #!/usr/bin/env bash + set -euo pipefail + port="{{ port }}" + if [ -z "$port" ]; then + port=$(uv run --group docs python -c ' + import socket + s = socket.socket() + try: + s.bind(("127.0.0.1", 8000)) + except OSError: + s.close() + s = socket.socket() + s.bind(("127.0.0.1", 0)) + print(s.getsockname()[1]) + s.close() + ') + fi + exec env DISABLE_MKDOCS_2_WARNING=true uv run --group docs mkdocs serve -a "localhost:$port" diff --git a/packages/zarr-metadata/mkdocs.yml b/packages/zarr-metadata/mkdocs.yml new file mode 100644 index 0000000000..18e1fc8c35 --- /dev/null +++ b/packages/zarr-metadata/mkdocs.yml @@ -0,0 +1,111 @@ +site_name: zarr-metadata +# The package lives in the zarr-python monorepo; point the header source +# widget at the package directory rather than the repository root. +repo_name: zarr-python/packages/zarr-metadata +repo_url: https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-metadata +# Absolute because mkdocs would otherwise append this to repo_url's subpath. +edit_uri: https://github.com/zarr-developers/zarr-python/edit/main/packages/zarr-metadata/docs/ +site_description: Spec-defined metadata types, models, and validators for Zarr v2 and v3. +site_author: Davis Bennett +site_url: !ENV [READTHEDOCS_CANONICAL_URL, 'https://zarr-metadata.readthedocs.io/'] +docs_dir: docs +use_directory_urls: true + +nav: + - index.md + - API Reference: + - api/index.md + - ' zarr_metadata.model': api/model.md + - ' zarr_metadata.pydantic': api/pydantic.md + - ' zarr_metadata.v2': api/v2.md + - ' zarr_metadata.v3': + - api/v3/index.md + - ' zarr_metadata.v3.chunk_grid': api/v3/chunk_grid.md + - ' zarr_metadata.v3.chunk_key_encoding': api/v3/chunk_key_encoding.md + - ' zarr_metadata.v3.codec': api/v3/codec.md + - ' zarr_metadata.v3.data_type': api/v3/data_type.md + - Changelog: https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-metadata/CHANGELOG.md + # This site is a Read the Docs subproject of zarr-python; give readers a way + # back to the parent docs, which list every companion package. + - 'zarr-python β†ͺ': https://zarr.readthedocs.io/ + +watch: + - src + +theme: + language: en + name: material + logo: _static/logo_bw.png + favicon: _static/favicon-96x96.png + + palette: + # Light mode + - media: "(prefers-color-scheme: light)" + scheme: default + toggle: + icon: material/brightness-7 + name: Switch to dark mode + + # Dark mode + - media: "(prefers-color-scheme: dark)" + scheme: slate + toggle: + icon: material/brightness-4 + name: Switch to light mode + + font: + text: Roboto + code: Roboto Mono + + features: + - content.code.annotate + - content.code.copy + - navigation.indexes + - navigation.instant + - navigation.tracking + - search.suggest + - search.share + +plugins: + - autorefs + - search + - mkdocstrings: + enable_inventory: true + handlers: + python: + paths: [src] + options: + allow_inspection: true + docstring_section_style: list + docstring_style: numpy + inherited_members: true + line_length: 60 + separate_signature: true + show_root_heading: true + show_signature_annotations: true + show_source: true + show_symbol_type_toc: true + signature_crossrefs: true + show_if_no_docstring: true + extensions: + - griffe_inherited_docstrings + + inventories: + - https://docs.python.org/3/objects.inv + - https://zarr.readthedocs.io/en/stable/objects.inv + +markdown_extensions: + - admonition + - attr_list + - def_list + - footnotes + - md_in_html + - pymdownx.details + - pymdownx.superfences + - toc: + permalink: true + - pymdownx.highlight: + anchor_linenums: true + line_spans: __span + pygments_lang_class: true + - pymdownx.inlinehilite diff --git a/packages/zarr-metadata/pyproject.toml b/packages/zarr-metadata/pyproject.toml new file mode 100644 index 0000000000..a58d3579a1 --- /dev/null +++ b/packages/zarr-metadata/pyproject.toml @@ -0,0 +1,169 @@ +[build-system] +requires = ["hatchling>=1.29.0", "hatch-vcs"] +build-backend = "hatchling.build" + +[project] +name = "zarr-metadata" +dynamic = ["version"] +description = "Spec-defined metadata types, models, and validators for Zarr v2 and v3." +readme = "README.md" +requires-python = ">=3.11" +license = "MIT" +license-files = ["LICENSE.txt"] +authors = [ + { name = "Davis Bennett", email = "davis.v.bennett@gmail.com" }, +] +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Intended Audience :: Information Technology", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Scientific/Engineering", + "Topic :: Software Development :: Libraries :: Python Modules", + "Typing :: Typed", +] +keywords = ["zarr"] +dependencies = [ + # >=4.16: first release where `Sentinel` pickles by reference + # (`__reduce__` returns the sentinel's name), so `UNSET` β€” and any model + # holding it β€” can cross process boundaries and be deep-copied with its + # singleton identity intact. 4.15 and earlier refuse to pickle sentinels. + "typing_extensions>=4.16", +] + +[project.urls] +Homepage = "https://github.com/zarr-developers/zarr-python" +Source = "https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-metadata" +Issues = "https://github.com/zarr-developers/zarr-python/issues" +Changelog = "https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-metadata/CHANGELOG.md" +Documentation = "https://zarr-metadata.readthedocs.io/" + +[dependency-groups] +test = ["pytest", "pydantic>=2.13", "jsonschema"] +docs = [ + # Pins match the zarr-python docs environment in the repo-root + # pyproject.toml so the two sites render with the same toolchain. + "mkdocs-material==9.7.6", + "mkdocs==1.6.1", + "mkdocstrings==1.0.4", + "mkdocstrings-python==2.0.5", + "griffe-inherited-docstrings==1.1.3", + # mkdocstrings uses ruff to format rendered signatures + "ruff==0.15.20", +] + +[tool.hatch.version] +source = "vcs" +tag-pattern = '^zarr_metadata-v(?P.+)$' +# `git_describe_command` ensures we get the zarr_metadata tags instead of latest. +# `local_scheme` strips the git commit info so the appending info is just a counter from latest tag. +# test-pypi doesn't accept git commit info in tags, and the count should be enough to distinguish unique runs. +raw-options = { root = "../..", git_describe_command = "git describe --dirty --tags --long --match zarr_metadata-v*", local_scheme = "no-local-version" } + +[tool.hatch.build.targets.wheel] +packages = ["src/zarr_metadata"] + +# An allowlist, so nothing that merely happens to sit in the package directory +# β€” a scratch script, a stray notebook β€” can ride along in a release. The list +# keeps an sdist self-testing and self-documenting: every fixture this suite +# reads is a JSON file sitting next to the test module that loads it, so +# `/tests` is the whole test dependency, and `/docs` plus `/mkdocs.yml` are a +# self-contained site (mkdocstrings reads `src`, nothing reaches outside the +# package) so `just docs-check` runs from an unpacked sdist too. `changes/` +# and `.readthedocs.yaml` are deliberately absent: towncrier fragments are +# repo bookkeeping, and the RTD config addresses paths from the repo root. +# `pyproject.toml`, `README.md` and `LICENSE.txt` are added by hatchling itself. +[tool.hatch.build.targets.sdist] +include = [ + "/src", + "/tests", + "/docs", + "/mkdocs.yml", + "/justfile", + "/CHANGELOG.md", +] + +[tool.ruff] +extend = "../../pyproject.toml" +target-version = "py311" + +[tool.pytest.ini_options] +minversion = "7" +testpaths = ["tests"] +xfail_strict = true +addopts = ["-ra", "--strict-config", "--strict-markers"] +filterwarnings = [ + "error", + # Pydantic validates these public immutable-shape TypedDicts correctly but + # cannot enforce the type checker's ReadOnly mutation restriction. + "ignore:Items? .* using the `ReadOnly` qualifier.*:UserWarning:pydantic._internal._generate_schema", +] + +[tool.numpydoc_validation] +checks = [ + "GL10", + "SS04", + "PR02", + "PR03", + "PR05", + "PR06", +] + +# CI pins pyright==1.1.404: later versions regress PEP 661 sentinel typing in +# class attributes (microsoft/pyright#11115), which zarr_metadata.model._sentinel +# relies on. Use the same pin locally; unpin when the fix lands. +[tool.pyright] +include = ["src"] +enableExperimentalFeatures = true +typeCheckingMode = "strict" +pythonVersion = "3.11" + +[tool.towncrier] +# Fragments for this package live alongside the package source, separate +# from the parent zarr-python `changes/` directory, so a PR touching only +# `packages/zarr-metadata/` produces a release note for this package only. +directory = "changes" +filename = "CHANGELOG.md" +package = "zarr_metadata" +underlines = ["", "", ""] +title_format = "## {version} ({project_date})" +issue_format = "[#{issue}](https://github.com/zarr-developers/zarr-python/pull/{issue})" +start_string = "\n" + +# Declaring any type replaces towncrier's built-in set, so all five the +# `changes/README.md` menu offers are restated here. They are the defaults +# verbatim except for `misc`, whose `showcontent` towncrier defaults to false: +# a `misc` entry would render as a bare PR link, which tells a reader nothing. +# A change worth a release note is worth a sentence, whatever its category. +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Misc" +showcontent = true diff --git a/packages/zarr-metadata/src/zarr_metadata/__init__.py b/packages/zarr-metadata/src/zarr_metadata/__init__.py new file mode 100644 index 0000000000..1a6b39f04d --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/__init__.py @@ -0,0 +1,402 @@ +from importlib.metadata import version + +from zarr_metadata._common import JSONValue, ZarrV3NamedConfigJSON +from zarr_metadata.model import ( + UNSET, + ZARR_V2_ARRAY_METADATA_STORE_KEY, + ZARR_V2_ATTRIBUTES_STORE_KEY, + ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY, + ZARR_V2_GROUP_METADATA_STORE_KEY, + ZARR_V3_ARRAY_METADATA_STORE_KEY, + ZARR_V3_CONSOLIDATED_METADATA_KEY, + ZARR_V3_GROUP_METADATA_STORE_KEY, + MetadataValidationError, + ProblemKind, + ValidationProblem, + ZarrV2ArrayMetadata, + ZarrV2ArrayMetadataPartial, + ZarrV2ArrayMetadataStoreKey, + ZarrV2AttributesStoreKey, + ZarrV2ConsolidatedMetadata, + ZarrV2ConsolidatedMetadataStoreKey, + ZarrV2GroupMetadata, + ZarrV2GroupMetadataPartial, + ZarrV2GroupMetadataStoreKey, + ZarrV3ArrayMetadata, + ZarrV3ArrayMetadataPartial, + ZarrV3ArrayMetadataStoreKey, + ZarrV3ConsolidatedMetadata, + ZarrV3GroupMetadata, + ZarrV3GroupMetadataPartial, + ZarrV3GroupMetadataStoreKey, + ZarrV3MetadataField, + ZarrV3NamedConfig, +) +from zarr_metadata.v2.array import ( + ZARR_V2_ARRAY_DIMENSION_SEPARATOR, + ZARR_V2_ARRAY_ORDER, + ZarrV2ArrayDimensionSeparator, + ZarrV2ArrayMetadataJSON, + ZarrV2ArrayMetadataJSONPartial, + ZarrV2ArrayOrder, + ZarrV2DataTypeMetadata, + ZarrV2ZArrayJSON, +) +from zarr_metadata.v2.attributes import ZarrV2ZAttrsJSON +from zarr_metadata.v2.codec import ZarrV2CodecMetadata +from zarr_metadata.v2.consolidated import ZarrV2ConsolidatedMetadataJSON +from zarr_metadata.v2.group import ( + ZarrV2GroupMetadataJSON, + ZarrV2GroupMetadataJSONPartial, + ZarrV2ZGroupJSON, +) +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON +from zarr_metadata.v3.array import ( + ZarrV3ArrayMetadataJSON, + ZarrV3ArrayMetadataJSONPartial, + ZarrV3ExtensionField, +) +from zarr_metadata.v3.chunk_grid.rectilinear import ( + RECTILINEAR_CHUNK_GRID_NAME, + RectilinearChunkGridMetadata, + RectilinearChunkGridName, +) +from zarr_metadata.v3.chunk_grid.regular import ( + REGULAR_CHUNK_GRID_NAME, + RegularChunkGridMetadata, + RegularChunkGridName, +) +from zarr_metadata.v3.chunk_key_encoding.default import ( + DEFAULT_CHUNK_KEY_ENCODING_NAME, + DEFAULT_CHUNK_KEY_ENCODING_SEPARATOR, + DefaultChunkKeyEncodingMetadata, + DefaultChunkKeyEncodingName, + DefaultChunkKeyEncodingSeparator, +) +from zarr_metadata.v3.chunk_key_encoding.v2 import ( + V2_CHUNK_KEY_ENCODING_NAME, + V2_CHUNK_KEY_ENCODING_SEPARATOR, + V2ChunkKeyEncodingMetadata, + V2ChunkKeyEncodingName, + V2ChunkKeyEncodingSeparator, +) +from zarr_metadata.v3.codec.blosc import ( + BLOSC_CNAME, + BLOSC_CODEC_NAME, + BLOSC_SHUFFLE, + BloscCName, + BloscCodecMetadata, + BloscCodecName, + BloscShuffle, +) +from zarr_metadata.v3.codec.bytes import ( + BYTES_CODEC_NAME, + ENDIANNESS, + BytesCodecMetadata, + BytesCodecName, + Endianness, +) +from zarr_metadata.v3.codec.cast_value import ( + CAST_OUT_OF_RANGE_MODE, + CAST_ROUNDING_MODE, + CAST_VALUE_CODEC_NAME, + CastOutOfRangeMode, + CastRoundingMode, + CastValueCodecMetadata, + CastValueCodecName, +) +from zarr_metadata.v3.codec.crc32c import CRC32C_CODEC_NAME, Crc32cCodecMetadata, Crc32cCodecName +from zarr_metadata.v3.codec.gzip import GZIP_CODEC_NAME, GzipCodecMetadata, GzipCodecName +from zarr_metadata.v3.codec.scale_offset import ( + SCALE_OFFSET_CODEC_NAME, + ScaleOffsetCodecMetadata, + ScaleOffsetCodecName, +) +from zarr_metadata.v3.codec.sharding_indexed import ( + SHARDING_INDEX_LOCATION, + SHARDING_INDEXED_CODEC_NAME, + ShardingIndexedCodecMetadata, + ShardingIndexedCodecName, + ShardingIndexLocation, +) +from zarr_metadata.v3.codec.transpose import ( + TRANSPOSE_CODEC_NAME, + TransposeCodecMetadata, + TransposeCodecName, +) +from zarr_metadata.v3.codec.zstd import ZSTD_CODEC_NAME, ZstdCodecMetadata, ZstdCodecName +from zarr_metadata.v3.consolidated import ZarrV3ConsolidatedMetadataJSON +from zarr_metadata.v3.data_type.bool import ( + BOOL_DATA_TYPE_NAME, + BoolDataTypeName, + BoolFillValue, +) +from zarr_metadata.v3.data_type.bytes import ( + BYTES_DATA_TYPE_NAME, + BytesDataTypeName, + BytesFillValue, +) +from zarr_metadata.v3.data_type.complex64 import ( + COMPLEX64_DATA_TYPE_NAME, + Complex64DataTypeName, + Complex64FillValue, +) +from zarr_metadata.v3.data_type.complex128 import ( + COMPLEX128_DATA_TYPE_NAME, + Complex128DataTypeName, + Complex128FillValue, +) +from zarr_metadata.v3.data_type.float16 import ( + FLOAT16_DATA_TYPE_NAME, + Float16DataTypeName, + Float16FillValue, +) +from zarr_metadata.v3.data_type.float32 import ( + FLOAT32_DATA_TYPE_NAME, + Float32DataTypeName, + Float32FillValue, +) +from zarr_metadata.v3.data_type.float64 import ( + FLOAT64_DATA_TYPE_NAME, + Float64DataTypeName, + Float64FillValue, +) +from zarr_metadata.v3.data_type.int8 import ( + INT8_DATA_TYPE_NAME, + Int8DataTypeName, + Int8FillValue, +) +from zarr_metadata.v3.data_type.int16 import ( + INT16_DATA_TYPE_NAME, + Int16DataTypeName, + Int16FillValue, +) +from zarr_metadata.v3.data_type.int32 import ( + INT32_DATA_TYPE_NAME, + Int32DataTypeName, + Int32FillValue, +) +from zarr_metadata.v3.data_type.int64 import ( + INT64_DATA_TYPE_NAME, + Int64DataTypeName, + Int64FillValue, +) +from zarr_metadata.v3.data_type.numpy_datetime64 import ( + NUMPY_DATETIME64_DATA_TYPE_NAME, + NumpyDatetime64DataTypeName, + NumpyDatetime64FillValue, +) +from zarr_metadata.v3.data_type.numpy_timedelta64 import ( + NUMPY_TIME_UNIT, + NUMPY_TIMEDELTA64_DATA_TYPE_NAME, + NumpyTimedelta64DataTypeName, + NumpyTimedelta64FillValue, + NumpyTimeUnit, +) +from zarr_metadata.v3.data_type.raw import RawBytesDataTypeName, RawBytesFillValue +from zarr_metadata.v3.data_type.string import ( + STRING_DATA_TYPE_NAME, + StringDataTypeName, + StringFillValue, +) +from zarr_metadata.v3.data_type.struct import ( + STRUCT_DATA_TYPE_NAME, + StructDataTypeName, + StructFillValue, +) +from zarr_metadata.v3.data_type.uint8 import ( + UINT8_DATA_TYPE_NAME, + Uint8DataTypeName, + Uint8FillValue, +) +from zarr_metadata.v3.data_type.uint16 import ( + UINT16_DATA_TYPE_NAME, + Uint16DataTypeName, + Uint16FillValue, +) +from zarr_metadata.v3.data_type.uint32 import ( + UINT32_DATA_TYPE_NAME, + Uint32DataTypeName, + Uint32FillValue, +) +from zarr_metadata.v3.data_type.uint64 import ( + UINT64_DATA_TYPE_NAME, + Uint64DataTypeName, + Uint64FillValue, +) +from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON, ZarrV3GroupMetadataJSONPartial + +__version__ = version("zarr-metadata") + + +__all__ = [ + "BLOSC_CNAME", + "BLOSC_CODEC_NAME", + "BLOSC_SHUFFLE", + "BOOL_DATA_TYPE_NAME", + "BYTES_CODEC_NAME", + "BYTES_DATA_TYPE_NAME", + "CAST_OUT_OF_RANGE_MODE", + "CAST_ROUNDING_MODE", + "CAST_VALUE_CODEC_NAME", + "COMPLEX64_DATA_TYPE_NAME", + "COMPLEX128_DATA_TYPE_NAME", + "CRC32C_CODEC_NAME", + "DEFAULT_CHUNK_KEY_ENCODING_NAME", + "DEFAULT_CHUNK_KEY_ENCODING_SEPARATOR", + "ENDIANNESS", + "FLOAT16_DATA_TYPE_NAME", + "FLOAT32_DATA_TYPE_NAME", + "FLOAT64_DATA_TYPE_NAME", + "GZIP_CODEC_NAME", + "INT8_DATA_TYPE_NAME", + "INT16_DATA_TYPE_NAME", + "INT32_DATA_TYPE_NAME", + "INT64_DATA_TYPE_NAME", + "NUMPY_DATETIME64_DATA_TYPE_NAME", + "NUMPY_TIMEDELTA64_DATA_TYPE_NAME", + "NUMPY_TIME_UNIT", + "RECTILINEAR_CHUNK_GRID_NAME", + "REGULAR_CHUNK_GRID_NAME", + "SCALE_OFFSET_CODEC_NAME", + "SHARDING_INDEXED_CODEC_NAME", + "SHARDING_INDEX_LOCATION", + "STRING_DATA_TYPE_NAME", + "STRUCT_DATA_TYPE_NAME", + "TRANSPOSE_CODEC_NAME", + "UINT8_DATA_TYPE_NAME", + "UINT16_DATA_TYPE_NAME", + "UINT32_DATA_TYPE_NAME", + "UINT64_DATA_TYPE_NAME", + "UNSET", + "V2_CHUNK_KEY_ENCODING_NAME", + "V2_CHUNK_KEY_ENCODING_SEPARATOR", + "ZARR_V2_ARRAY_DIMENSION_SEPARATOR", + "ZARR_V2_ARRAY_METADATA_STORE_KEY", + "ZARR_V2_ARRAY_ORDER", + "ZARR_V2_ATTRIBUTES_STORE_KEY", + "ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY", + "ZARR_V2_GROUP_METADATA_STORE_KEY", + "ZARR_V3_ARRAY_METADATA_STORE_KEY", + "ZARR_V3_CONSOLIDATED_METADATA_KEY", + "ZARR_V3_GROUP_METADATA_STORE_KEY", + "ZSTD_CODEC_NAME", + "BloscCName", + "BloscCodecMetadata", + "BloscCodecName", + "BloscShuffle", + "BoolDataTypeName", + "BoolFillValue", + "BytesCodecMetadata", + "BytesCodecName", + "BytesDataTypeName", + "BytesFillValue", + "CastOutOfRangeMode", + "CastRoundingMode", + "CastValueCodecMetadata", + "CastValueCodecName", + "Complex64DataTypeName", + "Complex64FillValue", + "Complex128DataTypeName", + "Complex128FillValue", + "Crc32cCodecMetadata", + "Crc32cCodecName", + "DefaultChunkKeyEncodingMetadata", + "DefaultChunkKeyEncodingName", + "DefaultChunkKeyEncodingSeparator", + "Endianness", + "Float16DataTypeName", + "Float16FillValue", + "Float32DataTypeName", + "Float32FillValue", + "Float64DataTypeName", + "Float64FillValue", + "GzipCodecMetadata", + "GzipCodecName", + "Int8DataTypeName", + "Int8FillValue", + "Int16DataTypeName", + "Int16FillValue", + "Int32DataTypeName", + "Int32FillValue", + "Int64DataTypeName", + "Int64FillValue", + "JSONValue", + "MetadataValidationError", + "NumpyDatetime64DataTypeName", + "NumpyDatetime64FillValue", + "NumpyTimeUnit", + "NumpyTimedelta64DataTypeName", + "NumpyTimedelta64FillValue", + "ProblemKind", + "RawBytesDataTypeName", + "RawBytesFillValue", + "RectilinearChunkGridMetadata", + "RectilinearChunkGridName", + "RegularChunkGridMetadata", + "RegularChunkGridName", + "ScaleOffsetCodecMetadata", + "ScaleOffsetCodecName", + "ShardingIndexLocation", + "ShardingIndexedCodecMetadata", + "ShardingIndexedCodecName", + "StringDataTypeName", + "StringFillValue", + "StructDataTypeName", + "StructFillValue", + "TransposeCodecMetadata", + "TransposeCodecName", + "Uint8DataTypeName", + "Uint8FillValue", + "Uint16DataTypeName", + "Uint16FillValue", + "Uint32DataTypeName", + "Uint32FillValue", + "Uint64DataTypeName", + "Uint64FillValue", + "V2ChunkKeyEncodingMetadata", + "V2ChunkKeyEncodingName", + "V2ChunkKeyEncodingSeparator", + "ValidationProblem", + "ZarrV2ArrayDimensionSeparator", + "ZarrV2ArrayMetadata", + "ZarrV2ArrayMetadataJSON", + "ZarrV2ArrayMetadataJSONPartial", + "ZarrV2ArrayMetadataPartial", + "ZarrV2ArrayMetadataStoreKey", + "ZarrV2ArrayOrder", + "ZarrV2AttributesStoreKey", + "ZarrV2CodecMetadata", + "ZarrV2ConsolidatedMetadata", + "ZarrV2ConsolidatedMetadataJSON", + "ZarrV2ConsolidatedMetadataStoreKey", + "ZarrV2DataTypeMetadata", + "ZarrV2GroupMetadata", + "ZarrV2GroupMetadataJSON", + "ZarrV2GroupMetadataJSONPartial", + "ZarrV2GroupMetadataPartial", + "ZarrV2GroupMetadataStoreKey", + "ZarrV2ZArrayJSON", + "ZarrV2ZAttrsJSON", + "ZarrV2ZGroupJSON", + "ZarrV3ArrayMetadata", + "ZarrV3ArrayMetadataJSON", + "ZarrV3ArrayMetadataJSONPartial", + "ZarrV3ArrayMetadataPartial", + "ZarrV3ArrayMetadataStoreKey", + "ZarrV3ConsolidatedMetadata", + "ZarrV3ConsolidatedMetadataJSON", + "ZarrV3ExtensionField", + "ZarrV3GroupMetadata", + "ZarrV3GroupMetadataJSON", + "ZarrV3GroupMetadataJSONPartial", + "ZarrV3GroupMetadataPartial", + "ZarrV3GroupMetadataStoreKey", + "ZarrV3MetadataField", + "ZarrV3MetadataFieldJSON", + "ZarrV3NamedConfig", + "ZarrV3NamedConfigJSON", + "ZstdCodecMetadata", + "ZstdCodecName", + "__version__", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/_common.py b/packages/zarr-metadata/src/zarr_metadata/_common.py new file mode 100644 index 0000000000..08c143107f --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/_common.py @@ -0,0 +1,50 @@ +""" +Top-level cross-version primitives for Zarr metadata. + +Version-specific types live under `zarr_metadata.v2` and `zarr_metadata.v3`. +Codec and dtype spec types live under `zarr_metadata.v3.codec` and +`zarr_metadata.v3.data_type`. +""" + +from collections.abc import Mapping, Sequence +from typing import NotRequired + +from typing_extensions import TypeAliasType, TypedDict + +JSONValue = TypeAliasType( + "JSONValue", + int | float | bool | str | Sequence["JSONValue"] | Mapping[str, "JSONValue"] | None, +) +"""A recursive type alias for JSON-encodable values. + +Defined via `TypeAliasType` (rather than a plain `TypeAlias`) so the +self-reference is a named recursion point that pydantic can resolve when +building a `TypeAdapter`; a bare recursive `TypeAlias` raises +`PydanticUserError`/`RecursionError` at validation time. + +The array arm is the covariant `Sequence` rather than the invariant +`list["JSONValue"] | tuple["JSONValue", ...]`, so values typed with a +*narrower* element type still count as JSON values: a `list[str]` field on a +TypedDict is assignable to `JSONValue` under `Sequence` but not under +`list[JSONValue]` (`list` is invariant in its element type, and pyright's +diagnostic for that failure suggests exactly this change). This is what lets +downstream TypedDicts give their fields precise types (`Sequence[str]`, +`list[int]`, ...) while remaining assignable to `Mapping[str, JSONValue]`. +The type-level cost, accepted deliberately: `Sequence` says nothing about the +concrete container, and it admits `str`/`bytes` (`str` was already a union +arm); runtime code narrowing a JSON array must exclude `str`/`bytes`/ +`bytearray` regardless of how this alias is spelled. +""" + + +class ZarrV3NamedConfigJSON(TypedDict): + """ + Externally-tagged union member for a metadata field. + + The optional `configuration` mapping holds arbitrary JSON-encodable + values. `must_understand` is implicitly true when absent. + """ + + name: str + configuration: NotRequired[Mapping[str, JSONValue]] + must_understand: NotRequired[bool] diff --git a/packages/zarr-metadata/src/zarr_metadata/_pydantic_schema.py b/packages/zarr-metadata/src/zarr_metadata/_pydantic_schema.py new file mode 100644 index 0000000000..e9792d6931 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/_pydantic_schema.py @@ -0,0 +1,114 @@ +"""Private input types used only to generate accurate Pydantic JSON schemas.""" + +from __future__ import annotations + +from collections.abc import Mapping # noqa: TC003 # resolved by Pydantic at runtime +from typing import Annotated, Literal, NotRequired + +from pydantic import Field +from typing_extensions import TypedDict + +from zarr_metadata._common import JSONValue +from zarr_metadata.v2.array import ( # noqa: TC001 # resolved by Pydantic at runtime + ZarrV2DataTypeMetadata, +) +from zarr_metadata.v2.codec import ( # resolved by Pydantic at runtime + ZarrV2CodecMetadata, +) + +NonNegativeInt = Annotated[int, Field(ge=0)] + + +class ZarrV3NamedConfigJSON(TypedDict, closed=True): + """Closed v3 named configuration accepted at optional extension points.""" + + name: str + configuration: NotRequired[Mapping[str, JSONValue]] + must_understand: NotRequired[bool] + + +class ZarrV3MandatoryNamedConfigJSON(TypedDict, closed=True): + """Closed named configuration accepted where understanding is mandatory.""" + + name: str + configuration: NotRequired[Mapping[str, JSONValue]] + must_understand: NotRequired[Literal[True]] + + +ZarrV3MetadataFieldJSON = str | ZarrV3NamedConfigJSON +ZarrV3MandatoryMetadataFieldJSON = str | ZarrV3MandatoryNamedConfigJSON +ZarrV3CodecPipelineJSON = Annotated[tuple[ZarrV3MetadataFieldJSON, ...], Field(min_length=1)] +ZarrV2FilterPipelineJSON = Annotated[tuple[ZarrV2CodecMetadata, ...], Field(min_length=1)] + + +class ZarrV3ArrayMetadataJSON(TypedDict, extra_items=JSONValue): + """Schema input for a v3 array document, including arbitrary extensions.""" + + zarr_format: Literal[3] + node_type: Literal["array"] + data_type: ZarrV3MandatoryMetadataFieldJSON + shape: tuple[NonNegativeInt, ...] + chunk_grid: ZarrV3MandatoryMetadataFieldJSON + chunk_key_encoding: ZarrV3MandatoryMetadataFieldJSON + fill_value: JSONValue + codecs: ZarrV3CodecPipelineJSON + attributes: NotRequired[Mapping[str, JSONValue]] + storage_transformers: NotRequired[tuple[ZarrV3MetadataFieldJSON, ...]] + dimension_names: NotRequired[tuple[str | None, ...]] + + +class ZarrV3ConsolidatedMetadataJSON(TypedDict, closed=True): + """Schema input for the closed inline consolidated-metadata envelope.""" + + kind: Literal["inline"] + must_understand: Literal[False] + metadata: Mapping[str, ZarrV3ArrayMetadataJSON | ZarrV3GroupMetadataJSON] + + +class ZarrV3GroupMetadataJSON(TypedDict, extra_items=JSONValue): + """Schema input for a v3 group document, including arbitrary extensions.""" + + zarr_format: Literal[3] + node_type: Literal["group"] + attributes: NotRequired[Mapping[str, JSONValue]] + consolidated_metadata: NotRequired[ZarrV3ConsolidatedMetadataJSON | None] + + +class ZarrV2ArrayMetadataJSON(TypedDict, closed=True): + """Schema input for the closed, merged v2 array representation.""" + + zarr_format: Literal[2] + shape: tuple[NonNegativeInt, ...] + chunks: tuple[NonNegativeInt, ...] + dtype: ZarrV2DataTypeMetadata + compressor: ZarrV2CodecMetadata | None + fill_value: JSONValue + order: Literal["C", "F"] + filters: ZarrV2FilterPipelineJSON | None + dimension_separator: NotRequired[Literal[".", "/"]] + attributes: NotRequired[Mapping[str, JSONValue]] + + +class ZarrV2GroupMetadataJSON(TypedDict, closed=True): + """Schema input for the closed, merged v2 group representation.""" + + zarr_format: Literal[2] + attributes: NotRequired[Mapping[str, JSONValue]] + + +class ZarrV2ConsolidatedMetadataJSON(TypedDict, closed=True): + """Schema input matching the v2 consolidated model's structural parser.""" + + zarr_consolidated_format: Literal[1] + metadata: Mapping[str, JSONValue] + + +__all__ = [ + "ZarrV2ArrayMetadataJSON", + "ZarrV2ConsolidatedMetadataJSON", + "ZarrV2GroupMetadataJSON", + "ZarrV3ArrayMetadataJSON", + "ZarrV3ConsolidatedMetadataJSON", + "ZarrV3GroupMetadataJSON", + "ZarrV3MetadataFieldJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/model/__init__.py b/packages/zarr-metadata/src/zarr_metadata/model/__init__.py new file mode 100644 index 0000000000..edf3561d1d --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/model/__init__.py @@ -0,0 +1,148 @@ +"""In-memory models for Zarr metadata documents. + +Models are frozen dataclasses that hold a canonical, semantically lossless +representation of the JSON documents; they never interpret extension points +(codecs, chunk grids, data types). Validators check JSON structure, not domain validity. +Each document concept gets a `validate_*` function returning every problem +found (a `list[ValidationProblem]`, each with a machine-readable `kind`), an +`is_*` type guard, and a `parse_*` function that narrows or raises +`MetadataValidationError`. Model `from_json` / `from_key_value` constructors +raise `MetadataValidationError` for every ingestion failure, including +missing store keys and undecodable bytes. +""" + +from zarr_metadata.model._array import ( + ZarrV2ArrayMetadata, + ZarrV2ArrayMetadataPartial, + ZarrV3ArrayMetadata, + ZarrV3ArrayMetadataPartial, + ZarrV3MetadataField, + ZarrV3NamedConfig, +) +from zarr_metadata.model._group import ( + ZarrV2ConsolidatedMetadata, + ZarrV2GroupMetadata, + ZarrV2GroupMetadataPartial, + ZarrV3ConsolidatedMetadata, + ZarrV3GroupMetadata, + ZarrV3GroupMetadataPartial, +) +from zarr_metadata.model._sentinel import UNSET +from zarr_metadata.model._validation import ( + ARRAY_METADATA_OPTIONAL_KEYS_V3, + ARRAY_METADATA_REQUIRED_KEYS_V2, + ARRAY_METADATA_REQUIRED_KEYS_V3, + ARRAY_METADATA_STANDARD_KEYS_V3, + GROUP_METADATA_OPTIONAL_KEYS_V3, + GROUP_METADATA_REQUIRED_KEYS_V2, + GROUP_METADATA_REQUIRED_KEYS_V3, + GROUP_METADATA_STANDARD_KEYS_V3, + MetadataValidationError, + ProblemKind, + ValidationProblem, + is_array_metadata_v2, + is_array_metadata_v3, + is_group_metadata_v2, + is_group_metadata_v3, + is_json, + is_metadata_field_v3, + parse_array_metadata_v2, + parse_array_metadata_v3, + parse_group_metadata_v2, + parse_group_metadata_v3, + parse_json, + parse_metadata_field_v3, + validate_array_metadata_v2, + validate_array_metadata_v3, + validate_group_metadata_v2, + validate_group_metadata_v3, + validate_json, + validate_metadata_field_v3, +) + +# Store keys are facts about the on-disk specs, so they are defined in the +# `v2`/`v3` modules that describe those documents. They are re-exported here +# because the model layer is where consumers reach for them. +from zarr_metadata.v2.array import ( + ZARR_V2_ARRAY_METADATA_STORE_KEY, + ZarrV2ArrayMetadataStoreKey, +) +from zarr_metadata.v2.attributes import ( + ZARR_V2_ATTRIBUTES_STORE_KEY, + ZarrV2AttributesStoreKey, +) +from zarr_metadata.v2.consolidated import ( + ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY, + ZarrV2ConsolidatedMetadataStoreKey, +) +from zarr_metadata.v2.group import ( + ZARR_V2_GROUP_METADATA_STORE_KEY, + ZarrV2GroupMetadataStoreKey, +) +from zarr_metadata.v3.array import ( + ZARR_V3_ARRAY_METADATA_STORE_KEY, + ZarrV3ArrayMetadataStoreKey, +) +from zarr_metadata.v3.consolidated import ZARR_V3_CONSOLIDATED_METADATA_KEY +from zarr_metadata.v3.group import ( + ZARR_V3_GROUP_METADATA_STORE_KEY, + ZarrV3GroupMetadataStoreKey, +) + +__all__ = [ + "ARRAY_METADATA_OPTIONAL_KEYS_V3", + "ARRAY_METADATA_REQUIRED_KEYS_V2", + "ARRAY_METADATA_REQUIRED_KEYS_V3", + "ARRAY_METADATA_STANDARD_KEYS_V3", + "GROUP_METADATA_OPTIONAL_KEYS_V3", + "GROUP_METADATA_REQUIRED_KEYS_V2", + "GROUP_METADATA_REQUIRED_KEYS_V3", + "GROUP_METADATA_STANDARD_KEYS_V3", + "UNSET", + "ZARR_V2_ARRAY_METADATA_STORE_KEY", + "ZARR_V2_ATTRIBUTES_STORE_KEY", + "ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY", + "ZARR_V2_GROUP_METADATA_STORE_KEY", + "ZARR_V3_ARRAY_METADATA_STORE_KEY", + "ZARR_V3_CONSOLIDATED_METADATA_KEY", + "ZARR_V3_GROUP_METADATA_STORE_KEY", + "MetadataValidationError", + "ProblemKind", + "ValidationProblem", + "ZarrV2ArrayMetadata", + "ZarrV2ArrayMetadataPartial", + "ZarrV2ArrayMetadataStoreKey", + "ZarrV2AttributesStoreKey", + "ZarrV2ConsolidatedMetadata", + "ZarrV2ConsolidatedMetadataStoreKey", + "ZarrV2GroupMetadata", + "ZarrV2GroupMetadataPartial", + "ZarrV2GroupMetadataStoreKey", + "ZarrV3ArrayMetadata", + "ZarrV3ArrayMetadataPartial", + "ZarrV3ArrayMetadataStoreKey", + "ZarrV3ConsolidatedMetadata", + "ZarrV3GroupMetadata", + "ZarrV3GroupMetadataPartial", + "ZarrV3GroupMetadataStoreKey", + "ZarrV3MetadataField", + "ZarrV3NamedConfig", + "is_array_metadata_v2", + "is_array_metadata_v3", + "is_group_metadata_v2", + "is_group_metadata_v3", + "is_json", + "is_metadata_field_v3", + "parse_array_metadata_v2", + "parse_array_metadata_v3", + "parse_group_metadata_v2", + "parse_group_metadata_v3", + "parse_json", + "parse_metadata_field_v3", + "validate_array_metadata_v2", + "validate_array_metadata_v3", + "validate_group_metadata_v2", + "validate_group_metadata_v3", + "validate_json", + "validate_metadata_field_v3", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_array.py b/packages/zarr-metadata/src/zarr_metadata/model/_array.py new file mode 100644 index 0000000000..0b562bc188 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/model/_array.py @@ -0,0 +1,498 @@ +"""In-memory models for Zarr array metadata documents.""" + +from __future__ import annotations + +import copy +import dataclasses +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Literal, TypeAlias, cast + +from typing_extensions import TypedDict, Unpack + +from zarr_metadata.model._sentinel import UNSET +from zarr_metadata.model._validation import ( + ARRAY_METADATA_STANDARD_KEYS_V3, + MetadataValidationError, + ValidationProblem, + arrays_to_tuples, + dump_store_json, + load_store_json, + parse_array_metadata_v2, + parse_array_metadata_v3, + parse_metadata_field_v3, +) +from zarr_metadata.v2.array import ZARR_V2_ARRAY_METADATA_STORE_KEY +from zarr_metadata.v2.attributes import ZARR_V2_ATTRIBUTES_STORE_KEY +from zarr_metadata.v3.array import ZARR_V3_ARRAY_METADATA_STORE_KEY + +if TYPE_CHECKING: + from zarr_metadata._common import JSONValue, ZarrV3NamedConfigJSON + from zarr_metadata.v2.array import ( + ZarrV2ArrayDimensionSeparator, + ZarrV2ArrayMetadataJSON, + ZarrV2ArrayMetadataStoreKey, + ZarrV2ArrayOrder, + ZarrV2DataTypeMetadata, + ) + from zarr_metadata.v2.attributes import ZarrV2AttributesStoreKey + from zarr_metadata.v2.codec import ZarrV2CodecMetadata + from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON + from zarr_metadata.v3.array import ( + ZarrV3ArrayMetadataJSON, + ZarrV3ArrayMetadataStoreKey, + ZarrV3ExtensionField, + ) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ZarrV3NamedConfig: + """A normalized v3 metadata field with its reader obligation. + + Bare names and missing configurations normalize to an empty configuration. + Bare names and missing `must_understand` members normalize to the spec's + implicit `True` value. + """ + + name: str + configuration: dict[str, JSONValue] + must_understand: bool = True + + def to_json(self) -> ZarrV3MetadataFieldJSON: + if not self.configuration and self.must_understand: + return self.name + out: ZarrV3NamedConfigJSON = {"name": self.name} + if self.configuration: + # to_json output shares no mutable state with the model. + out["configuration"] = copy.deepcopy(self.configuration) + if not self.must_understand: + out["must_understand"] = False + return out + + @classmethod + def from_json(cls, data: object) -> ZarrV3NamedConfig: + field = parse_metadata_field_v3(data) + if isinstance(field, str): + return cls(name=field, configuration={}, must_understand=True) + # Sound cast: parse_metadata_field_v3 checked the configuration is a + # string-keyed mapping of JSON values; arrays_to_tuples only converts + # lists to tuples within that shape. + configuration = cast( + "dict[str, JSONValue]", arrays_to_tuples(dict(field.get("configuration", {}))) + ) + return cls( + name=field["name"], + configuration=configuration, + must_understand=field.get("must_understand", True), + ) + + +ZarrV3MetadataField: TypeAlias = ZarrV3NamedConfig +"""The in-memory model of one field of a v3 metadata document. + +This is the role-named alias for annotation positions: model fields and +consumer signatures should say `ZarrV3MetadataField` (the logical meaning) +rather than `ZarrV3NamedConfig` (the serialized form the field currently +takes). Today every metadata field normalizes to a named configuration plus +its reader obligation, so the alias is exactly `ZarrV3NamedConfig`; if a future +spec revision adds a field form that cannot be normalized to those values, +this alias widens to a union and annotation sites do not change. Mirrors the +raw-layer split between `ZarrV3NamedConfigJSON` (shape) and +`ZarrV3MetadataFieldJSON` (field union). +""" + + +def must_understand_subset( + extra_fields: Mapping[str, ZarrV3ExtensionField], +) -> dict[str, ZarrV3ExtensionField]: + """The subset of `extra_fields` the reader is obligated to understand. + + Per the v3 spec, an extension field is implicitly `must_understand: True` + unless it explicitly says otherwise, and an implementation MUST fail to + open a group or array carrying fields it does not recognize that are not + explicitly `must_understand: false`. A non-mapping field value cannot + carry the explicit waiver, so it always requires understanding (the + runtime isinstance check defends against values looser than the declared + `ZarrV3ExtensionField`). + """ + fields = cast("Mapping[str, object]", extra_fields) + return cast( + "dict[str, ZarrV3ExtensionField]", + { + name: value + for name, value in fields.items() + if not ( + isinstance(value, Mapping) + and cast("Mapping[str, object]", value).get("must_understand") is False + ) + }, + ) + + +class ZarrV3ArrayMetadataPartial(TypedDict, total=False): + """ + Partial form of the constructor-settable fields of `ZarrV3ArrayMetadata`. + + Every key is optional and typed with the model's own (not serialized) + value types, so it describes valid keyword arguments to + `ZarrV3ArrayMetadata.update`. The `init=False` fields `zarr_format` and + `node_type` are intentionally excluded, since they cannot be passed to + `dataclasses.replace`. + + Drift between this type and the model's settable fields is prevented by + `tests/model/test_array.py::test_partial_keys_match_settable_model_fields`. + """ + + shape: tuple[int, ...] + fill_value: JSONValue + data_type: ZarrV3MetadataField + chunk_grid: ZarrV3MetadataField + codecs: tuple[ZarrV3MetadataField, ...] + chunk_key_encoding: ZarrV3MetadataField + dimension_names: tuple[str | None, ...] | UNSET + attributes: dict[str, JSONValue] + storage_transformers: tuple[ZarrV3MetadataField, ...] + extra_fields: dict[str, ZarrV3ExtensionField] + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ZarrV3ArrayMetadata: + """In-memory model of a v3 array metadata document. + + A canonical, semantically lossless representation of the `zarr.json` + content for an array. Extension points (`data_type`, `chunk_grid`, + `chunk_key_encoding`, `codecs`, `storage_transformers`) are held as + `ZarrV3MetadataField` values (currently `ZarrV3NamedConfig` name, + configuration, and obligation records) and are never interpreted; + `fill_value` is held verbatim in its JSON form. Equivalent extension + spellings normalize to shorthand strings when configuration is empty and + understanding is required. + """ + + zarr_format: Literal[3] = field(default=3, init=False) + node_type: Literal["array"] = field(default="array", init=False) + shape: tuple[int, ...] + fill_value: JSONValue + data_type: ZarrV3MetadataField + chunk_grid: ZarrV3MetadataField + codecs: tuple[ZarrV3MetadataField, ...] + chunk_key_encoding: ZarrV3MetadataField + dimension_names: tuple[str | None, ...] | UNSET + attributes: dict[str, JSONValue] + storage_transformers: tuple[ZarrV3MetadataField, ...] + extra_fields: dict[str, ZarrV3ExtensionField] + + @classmethod + def create_default(cls, **overrides: Unpack[ZarrV3ArrayMetadataPartial]) -> ZarrV3ArrayMetadata: + """ + Create a default (empty) v3 array metadata model, with optional overrides. + + The default is a structurally-valid scalar `uint8` array β€” the array + analog of `list()` returning `[]`. Any field can be overridden by keyword + (the same fields accepted by `update`). Overriding `shape` without + `chunk_grid` derives a consistent default grid: one regular chunk + covering the array (`chunk_shape` equal to `shape`). + + The derivation is deliberately one-way. A user-supplied `chunk_grid` + is an extension point and is taken verbatim β€” deriving `shape` from + it would require interpreting the grid's configuration, which this + layer never does (and cannot do for unrecognized grid names). So + overriding `chunk_grid` without `shape` keeps the scalar default + `shape=()`, and consistency between the two is the caller's + responsibility. + """ + if "shape" in overrides and "chunk_grid" not in overrides: + overrides["chunk_grid"] = ZarrV3NamedConfig( + name="regular", configuration={"chunk_shape": tuple(overrides["shape"])} + ) + default = cls( + shape=(), + fill_value=0, + data_type=ZarrV3NamedConfig(name="uint8", configuration={}), + chunk_grid=ZarrV3NamedConfig(name="regular", configuration={"chunk_shape": ()}), + codecs=(ZarrV3NamedConfig(name="bytes", configuration={}),), + chunk_key_encoding=ZarrV3NamedConfig(name="default", configuration={}), + dimension_names=UNSET, + attributes={}, + storage_transformers=(), + extra_fields={}, + ) + return default.update(**overrides) + + def update(self, **kwargs: Unpack[ZarrV3ArrayMetadataPartial]) -> ZarrV3ArrayMetadata: + """ + Return a new `ZarrV3ArrayMetadata` with the given fields updated. + + Only the constructor-settable fields listed in + `ZarrV3ArrayMetadataPartial` can be updated; any attempt to update + other fields (including the fixed `zarr_format` / `node_type`) is + rejected at the type level. Each given field fully replaces its + previous value, including `extra_fields`. + + This is useful for test fixtures that want to override a few fields of a + base template without having to re-specify the entire document. + + No re-validation is performed (`update` is `dataclasses.replace`), so + a repair or edit can produce an invalid document; validity is checked + on `from_json`, not on field replacement. + """ + return dataclasses.replace(self, **kwargs) + + def __post_init__(self) -> None: + overlap = set(self.extra_fields.keys()).intersection(ARRAY_METADATA_STANDARD_KEYS_V3) + if overlap: + raise MetadataValidationError( + [ + ValidationProblem( + ("extra_fields",), + "Extra fields cannot overlap with standard Zarr V3 array metadata fields", + "invalid_value", + ) + ] + ) + + def to_json(self) -> ZarrV3ArrayMetadataJSON: + # to_json output shares no mutable state with the model: every value + # that can hold a mutable container is deep-copied. + out: ZarrV3ArrayMetadataJSON = { + "zarr_format": self.zarr_format, + "node_type": self.node_type, + "shape": self.shape, + "fill_value": copy.deepcopy(self.fill_value), + "data_type": self.data_type.to_json(), + "chunk_grid": self.chunk_grid.to_json(), + "codecs": tuple(codec.to_json() for codec in self.codecs), + "chunk_key_encoding": self.chunk_key_encoding.to_json(), + } + if self.dimension_names is not UNSET: + out["dimension_names"] = self.dimension_names + if len(self.attributes) > 0: + out["attributes"] = copy.deepcopy(self.attributes) + if len(self.storage_transformers) > 0: + out["storage_transformers"] = tuple( + transformer.to_json() for transformer in self.storage_transformers + ) + # Extra fields are the TypedDict's `extra_items` (PEP 728). Assign them + # by key rather than `out.update(**...)`: type checkers understand the + # indexed-write path against `extra_items`, but not the `update(**...)` + # overload. + for key, value in self.extra_fields.items(): + out[key] = copy.deepcopy(value) + return out + + @classmethod + def from_json(cls, data: object) -> ZarrV3ArrayMetadata: + parsed = parse_array_metadata_v3(arrays_to_tuples(data)) + # Sound cast: the TypedDict types all non-standard keys as its + # `extra_items` (`ZarrV3ExtensionField`); the comprehension's inferred value + # type is the union over ALL keys because the key filter cannot narrow it. + extra_fields = cast( + "dict[str, ZarrV3ExtensionField]", + {k: v for k, v in parsed.items() if k not in ARRAY_METADATA_STANDARD_KEYS_V3}, + ) + return cls( + shape=parsed["shape"], + fill_value=parsed["fill_value"], + data_type=ZarrV3NamedConfig.from_json(parsed["data_type"]), + chunk_grid=ZarrV3NamedConfig.from_json(parsed["chunk_grid"]), + codecs=tuple(ZarrV3NamedConfig.from_json(c) for c in parsed["codecs"]), + chunk_key_encoding=ZarrV3NamedConfig.from_json(parsed["chunk_key_encoding"]), + dimension_names=parsed.get("dimension_names", UNSET), + attributes=dict(parsed.get("attributes", {})), + storage_transformers=tuple( + ZarrV3NamedConfig.from_json(t) for t in parsed.get("storage_transformers", ()) + ), + extra_fields=extra_fields, + ) + + @property + def must_understand_fields(self) -> dict[str, ZarrV3ExtensionField]: + """Extra fields the reader is obligated to understand. + + Everything in `extra_fields` not explicitly waived with + `must_understand: false` (the spec's implicit-true rule). A compliant + reader MUST fail to open the array if this contains any field it does + not recognize; the model layer only partitions by obligation, since + recognition is reader-specific. + """ + return must_understand_subset(self.extra_fields) + + @classmethod + def from_key_value(cls, mapping: Mapping[str, bytes]) -> ZarrV3ArrayMetadata: + return cls.from_json(load_store_json(mapping, ZARR_V3_ARRAY_METADATA_STORE_KEY)) + + def to_key_value( + self, *, indent: int | str | None = None + ) -> Mapping[ZarrV3ArrayMetadataStoreKey, bytes]: + return {ZARR_V3_ARRAY_METADATA_STORE_KEY: dump_store_json(self.to_json(), indent=indent)} + + +class ZarrV2ArrayMetadataPartial(TypedDict, total=False): + """ + Partial form of the constructor-settable fields of `ZarrV2ArrayMetadata`. + + Every key is optional and typed with the model's own value types, so it + describes valid keyword arguments to `ZarrV2ArrayMetadata.update` and + `create_default`. The `init=False` field `zarr_format` is intentionally + excluded, since it cannot be passed to `dataclasses.replace`. + + Drift between this type and the model's settable fields is prevented by + `tests/model/test_array.py::test_v2_partial_keys_match_settable_model_fields`. + """ + + shape: tuple[int, ...] + dtype: ZarrV2DataTypeMetadata + chunks: tuple[int, ...] + fill_value: JSONValue + order: ZarrV2ArrayOrder + compressor: ZarrV2CodecMetadata | None + filters: tuple[ZarrV2CodecMetadata, ...] | None + dimension_separator: ZarrV2ArrayDimensionSeparator + attributes: dict[str, JSONValue] | UNSET + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ZarrV2ArrayMetadata: + """In-memory model of a v2 array metadata document. + + A canonical, lossless representation of the `.zarray` content plus the + sibling `.zattrs` attributes. `dtype`, `compressor`, and `filters` are + held in their raw JSON forms and are never interpreted; `fill_value` is + held verbatim in its JSON form. `attributes` is `UNSET` when no + `.zattrs` file (or merged `attributes` key) exists β€” distinct from an + explicit empty `.zattrs`, which is `{}` and round-trips as a file. One + spelling normalization: a `.zarray` that omits `dimension_separator` + means `"."` by the v2 convention, and the model holds and re-emits that + value explicitly. + """ + + zarr_format: Literal[2] = field(default=2, init=False) + shape: tuple[int, ...] + dtype: ZarrV2DataTypeMetadata + chunks: tuple[int, ...] + fill_value: JSONValue + order: ZarrV2ArrayOrder + compressor: ZarrV2CodecMetadata | None + filters: tuple[ZarrV2CodecMetadata, ...] | None + # "." is the v2 convention's default for an ABSENT dimension_separator key; + # from_json normalizes absence to it (a semantics-preserving spelling + # normalization, like the v3 bare-string metadata-field form). The value + # is never None: the document grammar has no null spelling for this field. + dimension_separator: ZarrV2ArrayDimensionSeparator = field(default=".") + attributes: dict[str, JSONValue] | UNSET + + def update(self, **kwargs: Unpack[ZarrV2ArrayMetadataPartial]) -> ZarrV2ArrayMetadata: + """ + Return a new `ZarrV2ArrayMetadata` with the given fields updated. + + Only the constructor-settable fields listed in + `ZarrV2ArrayMetadataPartial` can be updated; the fixed `zarr_format` is + rejected at the type level. Each given field fully replaces its previous + value. + """ + return dataclasses.replace(self, **kwargs) + + @classmethod + def create_default(cls, **overrides: Unpack[ZarrV2ArrayMetadataPartial]) -> ZarrV2ArrayMetadata: + """ + Create a default (empty) v2 array metadata model, with optional overrides. + + The default is a structurally-valid scalar `uint8` (`"|u1"`) array β€” the + array analog of `list()` returning `[]`. Any field can be overridden by + keyword (the same fields accepted by `update`). Overriding `shape` + without `chunks` derives `chunks` equal to `shape` (one chunk covering + the array). + + The derivation is deliberately one-way, matching the v3 model: + overriding `chunks` without `shape` keeps the scalar default + `shape=()`, and consistency between the two is the caller's + responsibility. + """ + if "shape" in overrides and "chunks" not in overrides: + overrides["chunks"] = tuple(overrides["shape"]) + default = cls( + shape=(), + dtype="|u1", + chunks=(), + fill_value=0, + order="C", + compressor=None, + filters=None, + attributes=UNSET, + ) + return default.update(**overrides) + + def to_json(self) -> ZarrV2ArrayMetadataJSON: + """Return the merged in-memory document form. + + `attributes` is included when set (even empty). This is not the + on-disk `.zarray` content: a conforming `.zarray` must exclude + `attributes` (they live in the sibling `.zattrs` file). Use + `to_key_value` to produce the spec-conforming split for storage. + """ + # to_json output shares no mutable state with the model: every value + # that can hold a mutable container is deep-copied. + out: ZarrV2ArrayMetadataJSON = { + "zarr_format": self.zarr_format, + "shape": self.shape, + "dtype": self.dtype, + "order": self.order, + "chunks": self.chunks, + "fill_value": copy.deepcopy(self.fill_value), + "dimension_separator": self.dimension_separator, + "compressor": copy.deepcopy(self.compressor), + "filters": copy.deepcopy(self.filters), + } + if self.attributes is not UNSET: + out["attributes"] = copy.deepcopy(self.attributes) + return out + + @classmethod + def from_json(cls, data: object) -> ZarrV2ArrayMetadata: + parsed = parse_array_metadata_v2(arrays_to_tuples(data)) + return cls( + shape=parsed["shape"], + dtype=parsed["dtype"], + chunks=parsed["chunks"], + fill_value=parsed["fill_value"], + order=parsed["order"], + compressor=parsed["compressor"], + filters=parsed["filters"], + dimension_separator=parsed.get("dimension_separator", "."), + attributes=(dict(parsed["attributes"]) if "attributes" in parsed else UNSET), + ) + + @classmethod + def from_key_value(cls, mapping: Mapping[str, bytes]) -> ZarrV2ArrayMetadata: + zarray_raw = cast("object", load_store_json(mapping, ZARR_V2_ARRAY_METADATA_STORE_KEY)) + if not isinstance(zarray_raw, Mapping): + return cls.from_json(zarray_raw) + zarray = cast("Mapping[str, object]", zarray_raw) + if "attributes" in zarray: + raise MetadataValidationError( + [ + ValidationProblem( + ("attributes",), + "unexpected document member", + "invalid_value", + ) + ] + ) + if ZARR_V2_ATTRIBUTES_STORE_KEY in mapping: + zattrs = cast("object", load_store_json(mapping, ZARR_V2_ATTRIBUTES_STORE_KEY)) + return cls.from_json({**zarray, "attributes": zattrs}) + return cls.from_json(zarray) + + def to_key_value( + self, *, indent: int | str | None = None + ) -> Mapping[ZarrV2ArrayMetadataStoreKey | ZarrV2AttributesStoreKey, bytes]: + # Attributes live only in the sibling `.zattrs` file; the `.zarray` + # document must exclude them. The `.zattrs` key is present exactly + # when attributes are set (even empty) β€” UNSET emits no file. + zarray = {k: v for k, v in self.to_json().items() if k != "attributes"} + out: dict[ZarrV2ArrayMetadataStoreKey | ZarrV2AttributesStoreKey, bytes] = { + ZARR_V2_ARRAY_METADATA_STORE_KEY: dump_store_json(zarray, indent=indent) + } + if self.attributes is not UNSET: + out[ZARR_V2_ATTRIBUTES_STORE_KEY] = dump_store_json(self.attributes, indent=indent) + return out diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_group.py b/packages/zarr-metadata/src/zarr_metadata/model/_group.py new file mode 100644 index 0000000000..63dfe5611f --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/model/_group.py @@ -0,0 +1,436 @@ +"""In-memory models for Zarr group and consolidated metadata documents.""" + +from __future__ import annotations + +import copy +import dataclasses +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Literal, cast + +from typing_extensions import TypedDict, Unpack + +from zarr_metadata.model._array import ( + ZarrV3ArrayMetadata, + must_understand_subset, +) +from zarr_metadata.model._sentinel import UNSET +from zarr_metadata.model._validation import ( + GROUP_METADATA_STANDARD_KEYS_V3, + MetadataValidationError, + ValidationProblem, + arrays_to_tuples, + dump_store_json, + load_store_json, + parse_group_metadata_v2, + parse_group_metadata_v3, + validate_consolidated_metadata_v3, + validate_json, +) +from zarr_metadata.v2.attributes import ZARR_V2_ATTRIBUTES_STORE_KEY +from zarr_metadata.v2.consolidated import ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY +from zarr_metadata.v2.group import ZARR_V2_GROUP_METADATA_STORE_KEY +from zarr_metadata.v3.consolidated import ZARR_V3_CONSOLIDATED_METADATA_KEY +from zarr_metadata.v3.group import ZARR_V3_GROUP_METADATA_STORE_KEY + +if TYPE_CHECKING: + from zarr_metadata._common import JSONValue + from zarr_metadata.v2.attributes import ZarrV2AttributesStoreKey + from zarr_metadata.v2.consolidated import ZarrV2ConsolidatedMetadataStoreKey + from zarr_metadata.v2.group import ZarrV2GroupMetadataJSON, ZarrV2GroupMetadataStoreKey + from zarr_metadata.v3.array import ZarrV3ExtensionField + from zarr_metadata.v3.consolidated import ZarrV3ConsolidatedMetadataJSON + from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON, ZarrV3GroupMetadataStoreKey + + +class ZarrV3GroupMetadataPartial(TypedDict, total=False): + """ + Partial form of the constructor-settable fields of `ZarrV3GroupMetadata`. + + Every key is optional and typed with the model's own value types, so it + describes valid keyword arguments to `ZarrV3GroupMetadata.update` and + `create_default`. The `init=False` fields `zarr_format` and `node_type` + are intentionally excluded, since they cannot be passed to + `dataclasses.replace`. + + Drift between this type and the model's settable fields is prevented by + `tests/model/test_group.py::test_group_partial_keys_match_settable_model_fields`. + """ + + attributes: dict[str, JSONValue] + consolidated_metadata: ZarrV3ConsolidatedMetadata | UNSET + extra_fields: dict[str, ZarrV3ExtensionField] + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ZarrV3GroupMetadata: + """In-memory model of a v3 group metadata document. + + A canonical, semantically lossless representation of the `zarr.json` + content for a group. The `consolidated_metadata` reference-implementation + convention is modeled as a typed field holding thin child models; every + other unknown top-level key lands in `extra_fields` verbatim. + """ + + zarr_format: Literal[3] = field(default=3, init=False) + node_type: Literal["group"] = field(default="group", init=False) + attributes: dict[str, JSONValue] + consolidated_metadata: ZarrV3ConsolidatedMetadata | UNSET + extra_fields: dict[str, ZarrV3ExtensionField] + + def __post_init__(self) -> None: + reserved = GROUP_METADATA_STANDARD_KEYS_V3 | {ZARR_V3_CONSOLIDATED_METADATA_KEY} + if set(self.extra_fields.keys()).intersection(reserved): + raise MetadataValidationError( + [ + ValidationProblem( + ("extra_fields",), + "Extra fields cannot overlap with standard Zarr V3 group metadata fields", + "invalid_value", + ) + ] + ) + + @classmethod + def create_default(cls, **overrides: Unpack[ZarrV3GroupMetadataPartial]) -> ZarrV3GroupMetadata: + """ + Create a default (empty) v3 group metadata model, with optional overrides. + + The default is a structurally-valid group with no attributes β€” the group + analog of `list()` returning `[]`. Any field can be overridden by keyword + (the same fields accepted by `update`). + """ + default = cls(attributes={}, consolidated_metadata=UNSET, extra_fields={}) + return default.update(**overrides) + + def update(self, **kwargs: Unpack[ZarrV3GroupMetadataPartial]) -> ZarrV3GroupMetadata: + """ + Return a new `ZarrV3GroupMetadata` with the given fields updated. + + Only the constructor-settable fields listed in + `ZarrV3GroupMetadataPartial` can be updated; the fixed `zarr_format` / + `node_type` are rejected at the type level. Each given field fully + replaces its previous value, including `extra_fields`. + """ + return dataclasses.replace(self, **kwargs) + + def to_json(self) -> ZarrV3GroupMetadataJSON: + # to_json output shares no mutable state with the model: every value + # that can hold a mutable container is deep-copied. + out: ZarrV3GroupMetadataJSON = { + "zarr_format": self.zarr_format, + "node_type": self.node_type, + } + if len(self.attributes) > 0: + out["attributes"] = copy.deepcopy(self.attributes) + if self.consolidated_metadata is not UNSET: + # Consolidated metadata is a known non-core top-level JSON field. + out[ZARR_V3_CONSOLIDATED_METADATA_KEY] = cast( + "ZarrV3ExtensionField", self.consolidated_metadata.to_json() + ) + for key, value in self.extra_fields.items(): + out[key] = copy.deepcopy(value) + return out + + @classmethod + def from_json(cls, data: object) -> ZarrV3GroupMetadata: + parsed = parse_group_metadata_v3(arrays_to_tuples(data)) + # Cast for narrowing across standard and arbitrary extra TypedDict items. + consolidated_raw = cast("object", parsed.get(ZARR_V3_CONSOLIDATED_METADATA_KEY, UNSET)) + consolidated: ZarrV3ConsolidatedMetadata | UNSET + if consolidated_raw is UNSET or consolidated_raw is None: + # consolidated_metadata: null was written by a historical + # zarr-python bug; it gets no model representation. It is read as + # absence and never written back β€” repaired, not preserved. + consolidated = UNSET + else: + consolidated = ZarrV3ConsolidatedMetadata.from_json(consolidated_raw) + # Sound cast: the TypedDict types all non-standard keys as its + # `extra_items` (`ZarrV3ExtensionField`); the comprehension's inferred value + # type is the union over ALL keys because the key filter cannot narrow it. + extra_fields = cast( + "dict[str, ZarrV3ExtensionField]", + { + k: v + for k, v in parsed.items() + if k not in GROUP_METADATA_STANDARD_KEYS_V3 + and k != ZARR_V3_CONSOLIDATED_METADATA_KEY + }, + ) + return cls( + attributes=dict(parsed.get("attributes", {})), + consolidated_metadata=consolidated, + extra_fields=extra_fields, + ) + + @property + def must_understand_fields(self) -> dict[str, ZarrV3ExtensionField]: + """Extra fields the reader is obligated to understand. + + Everything in `extra_fields` not explicitly waived with + `must_understand: false` (the spec's implicit-true rule). A compliant + reader MUST fail to open the group if this contains any field it does + not recognize; the model layer only partitions by obligation, since + recognition is reader-specific. + """ + return must_understand_subset(self.extra_fields) + + @classmethod + def from_key_value(cls, mapping: Mapping[str, bytes]) -> ZarrV3GroupMetadata: + return cls.from_json(load_store_json(mapping, ZARR_V3_GROUP_METADATA_STORE_KEY)) + + def to_key_value( + self, *, indent: int | str | None = None + ) -> Mapping[ZarrV3GroupMetadataStoreKey, bytes]: + return {ZARR_V3_GROUP_METADATA_STORE_KEY: dump_store_json(self.to_json(), indent=indent)} + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ZarrV3ConsolidatedMetadata: + """In-memory model of v3 inline consolidated metadata. + + Models the reference-implementation convention where consolidated metadata + is embedded as an extension field on a group's `zarr.json`. Each entry in + `metadata` is a complete child document, held as a thin array or group + model. `must_understand` is typed permissively as `bool` to mirror the + document shape, but only `False` is valid; this is enforced at runtime. + """ + + kind: Literal["inline"] = field(default="inline", init=False) + must_understand: bool = False + metadata: dict[str, ZarrV3ArrayMetadata | ZarrV3GroupMetadata] + + def __post_init__(self) -> None: + if self.must_understand is not False: + raise MetadataValidationError( + [ + ValidationProblem( + ("must_understand",), + f"Invalid value for 'must_understand'. Expected False. " + f"Got {self.must_understand!r}.", + "invalid_value", + ) + ] + ) + + def to_json(self) -> ZarrV3ConsolidatedMetadataJSON: + # `must_understand` is emitted as the literal False: the field is typed + # permissively as `bool`, but `__post_init__` guarantees the value. + return { + "kind": self.kind, + "must_understand": False, + "metadata": {key: node.to_json() for key, node in self.metadata.items()}, + } + + @classmethod + def from_json(cls, data: object) -> ZarrV3ConsolidatedMetadata: + normalized = arrays_to_tuples(data) + problems = validate_consolidated_metadata_v3(normalized) + if problems: + raise MetadataValidationError(problems) + env = cast("Mapping[str, object]", normalized) + entries: dict[str, ZarrV3ArrayMetadata | ZarrV3GroupMetadata] = {} + for key, entry in cast("Mapping[str, object]", env["metadata"]).items(): + node_type = cast("Mapping[str, object]", entry).get("node_type") + if node_type == "array": + entries[key] = ZarrV3ArrayMetadata.from_json(entry) + else: + entries[key] = ZarrV3GroupMetadata.from_json(entry) + return cls(metadata=entries) + + +class ZarrV2GroupMetadataPartial(TypedDict, total=False): + """ + Partial form of the constructor-settable fields of `ZarrV2GroupMetadata`. + + Every key is optional and typed with the model's own value types, so it + describes valid keyword arguments to `ZarrV2GroupMetadata.update` and + `create_default`. The `init=False` field `zarr_format` is intentionally + excluded, since it cannot be passed to `dataclasses.replace`. + + Drift between this type and the model's settable fields is prevented by + `tests/model/test_group.py::test_group_partial_keys_match_settable_model_fields`. + """ + + attributes: dict[str, JSONValue] | UNSET + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ZarrV2GroupMetadata: + """In-memory model of a v2 group metadata document. + + A canonical, lossless representation of the `.zgroup` content plus the + sibling `.zattrs` attributes, folded into a single in-memory value + (mirroring the merged `ZarrV2GroupMetadataJSON` document form). `attributes` is + `UNSET` when no `.zattrs` file (or merged `attributes` key) exists β€” + distinct from an explicit empty `.zattrs`, which is `{}` and round-trips + as a file. + """ + + zarr_format: Literal[2] = field(default=2, init=False) + attributes: dict[str, JSONValue] | UNSET + + @classmethod + def create_default(cls, **overrides: Unpack[ZarrV2GroupMetadataPartial]) -> ZarrV2GroupMetadata: + """ + Create a default (empty) v2 group metadata model, with optional overrides. + + The default is a structurally-valid group with no attributes β€” the group + analog of `list()` returning `[]`. Any field can be overridden by keyword + (the same fields accepted by `update`). + """ + default = cls(attributes=UNSET) + return default.update(**overrides) + + def update(self, **kwargs: Unpack[ZarrV2GroupMetadataPartial]) -> ZarrV2GroupMetadata: + """ + Return a new `ZarrV2GroupMetadata` with the given fields updated. + + Only the constructor-settable fields listed in + `ZarrV2GroupMetadataPartial` can be updated; the fixed `zarr_format` + is rejected at the type level. Each given field fully replaces its + previous value. + """ + return dataclasses.replace(self, **kwargs) + + def to_json(self) -> ZarrV2GroupMetadataJSON: + """Return the merged in-memory document form. + + `attributes` is included when set (even empty). This is not the + on-disk `.zgroup` content: a conforming `.zgroup` must exclude + `attributes` (they live in the sibling `.zattrs` file). Use + `to_key_value` to produce the spec-conforming split for storage. + """ + # to_json output shares no mutable state with the model. + out: ZarrV2GroupMetadataJSON = {"zarr_format": self.zarr_format} + if self.attributes is not UNSET: + out["attributes"] = copy.deepcopy(self.attributes) + return out + + @classmethod + def from_json(cls, data: object) -> ZarrV2GroupMetadata: + parsed = parse_group_metadata_v2(arrays_to_tuples(data)) + return cls(attributes=(dict(parsed["attributes"]) if "attributes" in parsed else UNSET)) + + @classmethod + def from_key_value(cls, mapping: Mapping[str, bytes]) -> ZarrV2GroupMetadata: + zgroup_raw = cast("object", load_store_json(mapping, ZARR_V2_GROUP_METADATA_STORE_KEY)) + if not isinstance(zgroup_raw, Mapping): + return cls.from_json(zgroup_raw) + zgroup = cast("Mapping[str, object]", zgroup_raw) + if "attributes" in zgroup: + raise MetadataValidationError( + [ + ValidationProblem( + ("attributes",), + "unexpected document member", + "invalid_value", + ) + ] + ) + if ZARR_V2_ATTRIBUTES_STORE_KEY in mapping: + zattrs = cast("object", load_store_json(mapping, ZARR_V2_ATTRIBUTES_STORE_KEY)) + return cls.from_json({**zgroup, "attributes": zattrs}) + return cls.from_json(zgroup) + + def to_key_value( + self, *, indent: int | str | None = None + ) -> Mapping[ZarrV2GroupMetadataStoreKey | ZarrV2AttributesStoreKey, bytes]: + # Attributes live only in the sibling `.zattrs` file; the `.zgroup` + # document must exclude them. The `.zattrs` key is present exactly + # when attributes are set (even empty) β€” UNSET emits no file. + zgroup = {k: v for k, v in self.to_json().items() if k != "attributes"} + out: dict[ZarrV2GroupMetadataStoreKey | ZarrV2AttributesStoreKey, bytes] = { + ZARR_V2_GROUP_METADATA_STORE_KEY: dump_store_json(zgroup, indent=indent) + } + if self.attributes is not UNSET: + out[ZARR_V2_ATTRIBUTES_STORE_KEY] = dump_store_json(self.attributes, indent=indent) + return out + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ZarrV2ConsolidatedMetadata: + """In-memory model of a v2 `.zmetadata` document. + + The `metadata` map holds the flat file-keyed entries (`"path/.zarray"`, + `"path/.zattrs"`, ...) verbatim, preserving the normalized JSON tree. + Entries are deliberately NOT merged into per-node models: which nodes had + a `.zattrs` file at all is information the canonical representation must + keep. Interpreting entries into node models is consumer work. + """ + + zarr_consolidated_format: Literal[1] = field(default=1, init=False) + metadata: dict[str, JSONValue] + + def to_json(self) -> dict[str, JSONValue]: + # to_json output shares no mutable state with the model. + return { + "zarr_consolidated_format": self.zarr_consolidated_format, + "metadata": copy.deepcopy(self.metadata), + } + + @classmethod + def from_json(cls, data: object) -> ZarrV2ConsolidatedMetadata: + normalized = arrays_to_tuples(data) + if not isinstance(normalized, Mapping): + raise MetadataValidationError( + [ValidationProblem((), "expected a mapping", "invalid_type")] + ) + doc = cast("Mapping[str, object]", normalized) + problems: list[ValidationProblem] = [ + ValidationProblem((key,), "missing required key", "missing_key") + for key in ("zarr_consolidated_format", "metadata") + if key not in doc + ] + problems.extend( + ValidationProblem((key,), "unexpected document member", "invalid_value") + for key in doc.keys() - {"zarr_consolidated_format", "metadata"} + ) + if "zarr_consolidated_format" in doc and ( + not isinstance(doc["zarr_consolidated_format"], int) + or isinstance(doc["zarr_consolidated_format"], bool) + or doc["zarr_consolidated_format"] != 1 + ): + problems.append( + ValidationProblem( + ("zarr_consolidated_format",), + f"expected 1, got {doc['zarr_consolidated_format']!r}", + "invalid_value", + ) + ) + if "metadata" in doc: + entries = doc["metadata"] + if not isinstance(entries, Mapping) or not all( + isinstance(k, str) for k in cast("Mapping[object, object]", entries) + ): + problems.append( + ValidationProblem( + ("metadata",), "expected a mapping with string keys", "invalid_type" + ) + ) + else: + for key, value in cast("Mapping[str, object]", entries).items(): + problems.extend( + ValidationProblem( + ("metadata", key, *problem.loc), problem.message, problem.kind + ) + for problem in validate_json(value) + ) + if problems: + raise MetadataValidationError(problems) + entries_tupled = cast( + "dict[str, JSONValue]", + arrays_to_tuples(dict(cast("Mapping[str, object]", doc["metadata"]))), + ) + return cls(metadata=entries_tupled) + + @classmethod + def from_key_value(cls, mapping: Mapping[str, bytes]) -> ZarrV2ConsolidatedMetadata: + return cls.from_json(load_store_json(mapping, ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY)) + + def to_key_value( + self, *, indent: int | str | None = None + ) -> Mapping[ZarrV2ConsolidatedMetadataStoreKey, bytes]: + return { + ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY: dump_store_json(self.to_json(), indent=indent) + } diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_sentinel.py b/packages/zarr-metadata/src/zarr_metadata/model/_sentinel.py new file mode 100644 index 0000000000..ad71e216fa --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/model/_sentinel.py @@ -0,0 +1,37 @@ +"""The absence sentinel for optional metadata-document keys. + +The models observe one invariant: `None` in a model always corresponds to a +JSON `null` in the document (a v2 `compressor`/`filters` value, an unnamed +dimension inside `dimension_names`), and `UNSET` always means the document +key is absent. The two are never interchangeable, so a model value can never +leak into a document as a spelling the writer did not intend. + +Check with identity: `if model.dimension_names is UNSET: ...`. + +Because the contract is identity, the sentinel must never be reconstructed +from state: pickling and copying work by *reference* (typing_extensions >= +4.16 implements `Sentinel.__reduce__` as a lookup of the sentinel's name on +its defining module), so `pickle.loads(pickle.dumps(UNSET)) is UNSET` holds +across process boundaries, and models holding `UNSET` pickle and deep-copy +freely. Earlier typing_extensions releases refused to pickle sentinels +outright β€” hence the `>=4.16` floor in this package's dependencies. + +Checker support (PEP 661 is Final; stdlib `sentinel` arrives in Python +3.15): ty types this spelling exactly, including `is`/`is not` narrowing. +Pyright supports it but a regression (1.1.405+, tracked as +https://github.com/microsoft/pyright/issues/11115) degrades class-attribute +reads to `Unknown`, so this package pins pyright to the last good version +until the fix lands. Mypy support is in review +(https://github.com/python/mypy/pull/21647); until it merges, mypy-checked +consumers of these fields need a `cast` or `type: ignore` at narrowing +sites. This is a deliberate short-term cost: the sentinel is the standard, +and the checkers are converging on it. +""" + +from __future__ import annotations + +from typing_extensions import Sentinel + +UNSET = Sentinel("UNSET") +"""Marks a metadata-document key as absent (PEP 661 sentinel; usable directly +in type expressions, e.g. `tuple[str, ...] | UNSET`). Test with `is UNSET`.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_validation.py b/packages/zarr-metadata/src/zarr_metadata/model/_validation.py new file mode 100644 index 0000000000..a12e1911b1 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/model/_validation.py @@ -0,0 +1,875 @@ +"""Structural validation for Zarr metadata documents. + +Validators check JSON structure (key presence, value shapes, and fixed +literals like `zarr_format`), not domain validity. Each concept gets a +`validate_*` function returning every problem found, an `is_*` type guard, +and a `parse_*` function that narrows or raises `MetadataValidationError`. + +Every `ValidationProblem` carries a machine-readable `kind` alongside its +human-readable `message`, so consumers can dispatch on the failure mode +(`missing_key`, `invalid_type`, `invalid_value`, `invalid_json`) without +string-matching messages. +""" + +from __future__ import annotations + +import json +import math +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any, Final, Literal, NoReturn, cast + +from typing_extensions import TypeIs + +from zarr_metadata._common import JSONValue +from zarr_metadata.v2.array import ZarrV2ArrayMetadataJSON +from zarr_metadata.v2.group import ZarrV2GroupMetadataJSON +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON +from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON +from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON + +ProblemKind = Literal["missing_key", "invalid_type", "invalid_value", "invalid_json"] +"""Machine-readable classification of a `ValidationProblem`. + +- `missing_key`: a required key (document key or store key) is absent. +- `invalid_type`: a value has the wrong structural type (e.g. a string where + a mapping is required, a non-JSON-serializable object). +- `invalid_value`: a value has an acceptable type but an invalid content + (e.g. `zarr_format: 2` in a v3 document, `order: "Q"`). +- `invalid_json`: bytes that do not decode as JSON. +""" + + +@dataclass(frozen=True, slots=True) +class ValidationProblem: + """A single structural problem found while validating a metadata document. + + `loc` is the path from the document root to the offending value, e.g. + `("codecs", 0, "name")`. An empty `loc` refers to the document as a whole. + `kind` classifies the failure mode for programmatic dispatch; `message` + is the human-readable description. + """ + + loc: tuple[str | int, ...] + message: str + kind: ProblemKind + + def __str__(self) -> str: + location = ".".join(str(part) for part in self.loc) if self.loc else "" + return f"{location}: {self.message}" + + +class MetadataValidationError(ValueError): + """Raised when a value fails structural metadata validation. + + Carries every problem found (not just the first) in `.problems`. + """ + + def __init__(self, problems: list[ValidationProblem]) -> None: + self.problems = problems + super().__init__("\n".join(str(problem) for problem in problems)) + + +def _prefix(loc_head: str | int, problems: list[ValidationProblem]) -> list[ValidationProblem]: + """Prepend `loc_head` to the `loc` of every problem (for nested validators).""" + return [ValidationProblem((loc_head, *p.loc), p.message, p.kind) for p in problems] + + +def validate_json(value: object) -> list[ValidationProblem]: + """Return every reason `value` is not JSON-serializable (recursively).""" + if isinstance(value, float): + if math.isfinite(value): + return [] + return [ValidationProblem((), f"non-finite float {value!r} is not JSON", "invalid_value")] + if isinstance(value, (str, int, bool)) or value is None: + return [] + problems: list[ValidationProblem] = [] + if isinstance(value, Mapping): + for key, item in cast("Mapping[object, object]", value).items(): + if not isinstance(key, str): + problems.append( + ValidationProblem((), f"non-string key {key!r} in JSON object", "invalid_type") + ) + continue + problems.extend(_prefix(key, validate_json(item))) + return problems + if isinstance(value, Sequence) and not isinstance(value, (bytes, bytearray)): + for index, item in enumerate(cast("Sequence[object]", value)): + problems.extend(_prefix(index, validate_json(item))) + return problems + return [ValidationProblem((), f"not a JSON-serializable value: {value!r}", "invalid_type")] + + +def _is_canonical_json(value: object) -> TypeIs[JSONValue]: + """Whether `value` already uses the concrete containers in `JSONValue`.""" + if isinstance(value, float): + return math.isfinite(value) + if isinstance(value, (str, int, bool)) or value is None: + return True + if isinstance(value, (list, tuple)): + sequence = cast("list[object] | tuple[object, ...]", value) + return all(_is_canonical_json(item) for item in sequence) + if isinstance(value, dict): + mapping = cast("dict[object, object]", value) + return all( + isinstance(key, str) and _is_canonical_json(item) for key, item in mapping.items() + ) + return False + + +def is_json(value: object) -> TypeIs[JSONValue]: + """Whether `value` is a canonical JSON structure (recursively).""" + return _is_canonical_json(value) + + +def parse_json(value: object) -> JSONValue: + """Return a canonical `JSONValue`, or raise `MetadataValidationError`.""" + normalized = arrays_to_tuples(value) + problems = validate_json(normalized) + if problems: + raise MetadataValidationError(problems) + return cast(JSONValue, normalized) + + +# The standard top-level keys of a v3 array metadata document. Anything outside +# this set is an extension field. Built from the TypedDict's required/optional +# key sets (which resolve inherited keys, unlike `__annotations__`). +ARRAY_METADATA_REQUIRED_KEYS_V3: Final[frozenset[str]] = frozenset( + ZarrV3ArrayMetadataJSON.__required_keys__ +) +ARRAY_METADATA_OPTIONAL_KEYS_V3: Final[frozenset[str]] = frozenset( + ZarrV3ArrayMetadataJSON.__optional_keys__ +) +ARRAY_METADATA_STANDARD_KEYS_V3: Final[frozenset[str]] = ( + ARRAY_METADATA_REQUIRED_KEYS_V3 | ARRAY_METADATA_OPTIONAL_KEYS_V3 +) + +ARRAY_METADATA_REQUIRED_KEYS_V2: Final[frozenset[str]] = frozenset( + ZarrV2ArrayMetadataJSON.__required_keys__ +) +ARRAY_METADATA_OPTIONAL_KEYS_V2: Final[frozenset[str]] = frozenset( + ZarrV2ArrayMetadataJSON.__optional_keys__ +) +ARRAY_METADATA_STANDARD_KEYS_V2: Final[frozenset[str]] = ( + ARRAY_METADATA_REQUIRED_KEYS_V2 | ARRAY_METADATA_OPTIONAL_KEYS_V2 +) + +# The standard top-level keys of a v3 group metadata document. Anything outside +# this set is an extension field. +GROUP_METADATA_REQUIRED_KEYS_V3: Final[frozenset[str]] = frozenset( + ZarrV3GroupMetadataJSON.__required_keys__ +) +GROUP_METADATA_OPTIONAL_KEYS_V3: Final[frozenset[str]] = frozenset( + ZarrV3GroupMetadataJSON.__optional_keys__ +) +GROUP_METADATA_STANDARD_KEYS_V3: Final[frozenset[str]] = ( + GROUP_METADATA_REQUIRED_KEYS_V3 | GROUP_METADATA_OPTIONAL_KEYS_V3 +) + +GROUP_METADATA_REQUIRED_KEYS_V2: Final[frozenset[str]] = frozenset( + ZarrV2GroupMetadataJSON.__required_keys__ +) +GROUP_METADATA_OPTIONAL_KEYS_V2: Final[frozenset[str]] = frozenset( + ZarrV2GroupMetadataJSON.__optional_keys__ +) +GROUP_METADATA_STANDARD_KEYS_V2: Final[frozenset[str]] = ( + GROUP_METADATA_REQUIRED_KEYS_V2 | GROUP_METADATA_OPTIONAL_KEYS_V2 +) + + +def _missing_keys(required: frozenset[str], doc: Mapping[str, object]) -> list[ValidationProblem]: + """One `missing_key` problem per required key absent from `doc`.""" + return [ + ValidationProblem((key,), "missing required key", "missing_key") + for key in sorted(required - doc.keys()) + ] + + +def _unexpected_keys( + allowed: frozenset[str], doc: Mapping[object, object] +) -> list[ValidationProblem]: + """One problem per member outside a closed document's declared shape.""" + problems: list[ValidationProblem] = [] + for key in doc: + if not isinstance(key, str): + problems.append( + ValidationProblem((), f"non-string document key {key!r}", "invalid_type") + ) + elif key not in allowed: + problems.append( + ValidationProblem((key,), "unexpected document member", "invalid_value") + ) + return problems + + +def _check_literal( + doc: Mapping[str, object], key: str, expected: object +) -> list[ValidationProblem]: + """One `invalid_value` problem if `doc[key]` is present but not `expected`.""" + if key in doc and (type(doc[key]) is not type(expected) or doc[key] != expected): + return [ + ValidationProblem((key,), f"expected {expected!r}, got {doc[key]!r}", "invalid_value") + ] + return [] + + +def _validate_extension_fields_v3( + doc: Mapping[object, object], + standard_keys: frozenset[str], + *, + additional_reserved_keys: frozenset[str] = frozenset(), +) -> list[ValidationProblem]: + """Validate v3 top-level key types and unknown-field JSON payloads.""" + problems: list[ValidationProblem] = [] + reserved_keys = standard_keys | additional_reserved_keys + for key, value in doc.items(): + if not isinstance(key, str): + problems.append( + ValidationProblem((), f"non-string top-level key {key!r}", "invalid_type") + ) + continue + if key in reserved_keys: + continue + problems.extend(_prefix(key, validate_json(value))) + return problems + + +def validate_metadata_field_v3( + value: object, *, allow_must_understand_false: bool = True +) -> list[ValidationProblem]: + """Return every reason `value` is not a v3 metadata field. + + A metadata field is a bare name string or a mapping containing `name` and + optional `configuration` and `must_understand` members. + """ + if isinstance(value, str): + return [] + if not isinstance(value, Mapping): + return [ + ValidationProblem( + (), + "expected a metadata field (string or extension object)", + "invalid_type", + ) + ] + field = cast("Mapping[object, object]", value) + problems: list[ValidationProblem] = [] + allowed_keys = frozenset({"name", "configuration", "must_understand"}) + for key in field: + if not isinstance(key, str): + problems.append( + ValidationProblem((), f"non-string metadata field key {key!r}", "invalid_type") + ) + elif key not in allowed_keys: + problems.append( + ValidationProblem((key,), "unexpected metadata field member", "invalid_value") + ) + if not isinstance(field.get("name"), str): + problems.append(ValidationProblem(("name",), "expected a string name", "invalid_type")) + if "configuration" in field: + configuration = field["configuration"] + if not isinstance(configuration, Mapping): + problems.append( + ValidationProblem(("configuration",), "expected a mapping", "invalid_type") + ) + elif not all(isinstance(k, str) for k in cast("Mapping[object, object]", configuration)): + problems.append( + ValidationProblem(("configuration",), "expected string keys", "invalid_type") + ) + else: + for key, item in cast("Mapping[str, object]", configuration).items(): + problems.extend(_prefix("configuration", _prefix(key, validate_json(item)))) + if "must_understand" in field: + must_understand = field["must_understand"] + if not isinstance(must_understand, bool): + problems.append( + ValidationProblem(("must_understand",), "expected a boolean", "invalid_type") + ) + elif not allow_must_understand_false and not must_understand: + problems.append( + ValidationProblem( + ("must_understand",), + "false is not supported at this extension point", + "invalid_value", + ) + ) + return problems + + +def is_metadata_field_v3(value: object) -> TypeIs[ZarrV3MetadataFieldJSON]: + """Whether `value` is a v3 metadata field: a bare name or a named config.""" + if isinstance(value, str): + return True + if not isinstance(value, dict): + return False + field = cast("dict[object, object]", value) + return _is_canonical_json(field) and not validate_metadata_field_v3(field) + + +def parse_metadata_field_v3(value: object) -> ZarrV3MetadataFieldJSON: + """Return `value` narrowed to `ZarrV3MetadataFieldJSON`, or raise `MetadataValidationError`.""" + normalized = arrays_to_tuples(value) + problems = validate_metadata_field_v3(normalized) + if problems: + raise MetadataValidationError(problems) + return cast(ZarrV3MetadataFieldJSON, normalized) + + +def _is_int_sequence(value: object) -> bool: + """Whether `value` is a non-string sequence of integers. + + JSON booleans decode to `bool`, which is an `int` subclass in Python but + is not an integer in a metadata document, so booleans are excluded. + """ + return ( + not isinstance(value, (str, bytes, bytearray)) + and isinstance(value, Sequence) + and all( + isinstance(item, int) and not isinstance(item, bool) + for item in cast("Sequence[object]", value) + ) + ) + + +def _validate_dim_sequence(doc: Mapping[str, object], key: str) -> list[ValidationProblem]: + """Validate a dimension sequence (`shape` / `chunks`) if present in `doc`. + + Dimension lengths are non-negative integers. + """ + if key not in doc: + return [] + value = doc[key] + if not _is_int_sequence(value): + return [ValidationProblem((key,), "expected a sequence of int", "invalid_type")] + if any(item < 0 for item in cast("Sequence[int]", value)): + return [ValidationProblem((key,), "expected non-negative integers", "invalid_value")] + return [] + + +def _is_dtype_v2(value: object) -> bool: + """Whether `value` is shaped like a v2 dtype: a string or field records. + + A field record is a `(name, dtype)` or `(name, dtype, shape)` sequence, + where `dtype` is itself a string or nested field records and `shape` is a + sequence of int. The string content is NOT interpreted β€” whether the + string names a real dtype is domain validity, not structure. + """ + if isinstance(value, str): + return True + if not isinstance(value, Sequence): + return False + for record in cast("Sequence[object]", value): + if isinstance(record, str) or not isinstance(record, Sequence): + return False + fields = cast("Sequence[object]", record) + if len(fields) not in (2, 3): + return False + if not isinstance(fields[0], str): + return False + if not _is_dtype_v2(fields[1]): + return False + if len(fields) == 3 and not _is_int_sequence(fields[2]): + return False + return True + + +def _is_canonical_dtype_v2(value: object) -> bool: + """Whether a validated v2 dtype uses the tuple-backed public representation.""" + if isinstance(value, str): + return True + if not isinstance(value, tuple): + return False + for record in cast("tuple[object, ...]", value): + if not isinstance(record, tuple): + return False + fields = cast("tuple[object, ...]", record) + if not _is_canonical_dtype_v2(fields[1]): + return False + if len(fields) == 3 and not isinstance(fields[2], tuple): + return False + return True + + +def _is_canonical_metadata_field_v3(value: object) -> bool: + """Whether a validated v3 metadata field has its declared runtime container type.""" + return isinstance(value, (str, dict)) + + +def _is_canonical_array_metadata_v3(value: object) -> bool: + """Whether a validated v3 array document matches `ZarrV3ArrayMetadataJSON` at runtime.""" + if not isinstance(value, dict): + return False + doc = cast("dict[str, object]", value) + if not isinstance(doc["shape"], tuple) or not isinstance(doc["codecs"], tuple): + return False + if "storage_transformers" in doc and not isinstance(doc["storage_transformers"], tuple): + return False + if "dimension_names" in doc and not isinstance(doc["dimension_names"], tuple): + return False + if not all( + _is_canonical_metadata_field_v3(doc[key]) + for key in ("data_type", "chunk_grid", "chunk_key_encoding") + ): + return False + if not all( + _is_canonical_metadata_field_v3(item) for item in cast("tuple[object, ...]", doc["codecs"]) + ): + return False + return "storage_transformers" not in doc or all( + _is_canonical_metadata_field_v3(item) + for item in cast("tuple[object, ...]", doc["storage_transformers"]) + ) + + +def _is_canonical_array_metadata_v2(value: object) -> bool: + """Whether a validated v2 array document matches `ZarrV2ArrayMetadataJSON` at runtime.""" + if not isinstance(value, dict): + return False + doc = cast("dict[str, object]", value) + if not isinstance(doc["shape"], tuple) or not isinstance(doc["chunks"], tuple): + return False + if not _is_canonical_dtype_v2(doc["dtype"]): + return False + compressor = doc["compressor"] + if compressor is not None and not isinstance(compressor, dict): + return False + filters = doc["filters"] + return filters is None or ( + isinstance(filters, tuple) + and all(isinstance(item, dict) for item in cast("tuple[object, ...]", filters)) + ) + + +def _is_codec_v2(value: object) -> bool: + """Whether `value` is shaped like a v2 codec config: a mapping with a string `id`.""" + return isinstance(value, Mapping) and isinstance( + cast("Mapping[object, object]", value).get("id"), str + ) + + +def _validate_codec_v2(value: object) -> list[ValidationProblem]: + """Validate a v2 codec's required shape and JSON-valued configuration.""" + if not _is_codec_v2(value): + return [ + ValidationProblem( + (), "expected a codec configuration with a string 'id'", "invalid_type" + ) + ] + return validate_json(value) + + +def _validate_attributes(value: object) -> list[ValidationProblem]: + """Validate an `attributes` value: a mapping with string keys. + + Returns a problem at `("attributes",)` if it is not, else `[]`. Shared by the + v2 and v3 validators. Unlike the other `validate_*` functions (which + return value-relative locs for the caller to `_prefix`), this emits the + already-parent-relative `("attributes",)` loc, since it is only ever called + with a document's `attributes` value. + """ + if not isinstance(value, Mapping) or not all( + isinstance(k, str) for k in cast("Mapping[object, object]", value) + ): + return [ + ValidationProblem( + ("attributes",), "expected a mapping with string keys", "invalid_type" + ) + ] + problems: list[ValidationProblem] = [] + for key, item in cast("Mapping[str, object]", value).items(): + problems.extend(_prefix("attributes", _prefix(key, validate_json(item)))) + return problems + + +def validate_array_metadata_v3(value: object) -> list[ValidationProblem]: + """Return every reason `value` is not a structurally-valid v3 array doc. + + Checks structure, not domain validity. Unknown top-level keys are allowed + (they map to `extra_fields`). + """ + if not isinstance(value, Mapping): + return [ValidationProblem((), "expected a mapping", "invalid_type")] + doc = cast("Mapping[str, object]", value) + problems: list[ValidationProblem] = _missing_keys(ARRAY_METADATA_REQUIRED_KEYS_V3, doc) + problems.extend( + _validate_extension_fields_v3( + cast("Mapping[object, object]", value), ARRAY_METADATA_STANDARD_KEYS_V3 + ) + ) + problems.extend(_check_literal(doc, "zarr_format", 3)) + problems.extend(_check_literal(doc, "node_type", "array")) + problems.extend(_validate_dim_sequence(doc, "shape")) + if "fill_value" in doc: + problems.extend(_prefix("fill_value", validate_json(doc["fill_value"]))) + for key in ("data_type", "chunk_grid", "chunk_key_encoding"): + if key in doc: + problems.extend( + _prefix( + key, + validate_metadata_field_v3(doc[key], allow_must_understand_false=False), + ) + ) + for key in ("codecs", "storage_transformers"): + if key in doc: + entries = doc[key] + if isinstance(entries, str) or not isinstance(entries, Sequence): + problems.append(ValidationProblem((key,), "expected a sequence", "invalid_type")) + else: + if key == "codecs" and len(cast("Sequence[object]", entries)) == 0: + problems.append( + ValidationProblem( + ("codecs",), "expected at least one codec", "invalid_value" + ) + ) + for index, entry in enumerate(cast("Sequence[object]", entries)): + problems.extend(_prefix(key, _prefix(index, validate_metadata_field_v3(entry)))) + if "attributes" in doc: + problems.extend(_validate_attributes(doc["attributes"])) + if "dimension_names" in doc: + # Simple typed sequences (dimension_names, shape, chunks) report a single + # field-level loc, not per-bad-item locs; per-index locs are reserved for + # the metadata-field lists (codecs, storage_transformers). + names = doc["dimension_names"] + if isinstance(names, str) or not isinstance(names, Sequence): + problems.append( + ValidationProblem(("dimension_names",), "expected a sequence", "invalid_type") + ) + elif not all( + item is None or isinstance(item, str) for item in cast("Sequence[object]", names) + ): + problems.append( + ValidationProblem( + ("dimension_names",), "expected items of str or None", "invalid_type" + ) + ) + elif _is_int_sequence(doc.get("shape")) and len(cast("Sequence[object]", names)) != len( + cast("Sequence[int]", doc["shape"]) + ): + problems.append( + ValidationProblem( + ("dimension_names",), + "expected one name per dimension of shape", + "invalid_value", + ) + ) + return problems + + +def is_array_metadata_v3(value: object) -> TypeIs[ZarrV3ArrayMetadataJSON]: + """Whether `value` is a structurally-valid v3 array metadata document.""" + return ( + _is_canonical_json(value) + and not validate_array_metadata_v3(value) + and _is_canonical_array_metadata_v3(value) + ) + + +def parse_array_metadata_v3(value: object) -> ZarrV3ArrayMetadataJSON: + """Return `value` as `ZarrV3ArrayMetadataJSON`, or raise `MetadataValidationError`.""" + normalized = arrays_to_tuples(value) + problems = validate_array_metadata_v3(normalized) + if problems: + raise MetadataValidationError(problems) + return cast("ZarrV3ArrayMetadataJSON", normalized) + + +def validate_array_metadata_v2(value: object) -> list[ValidationProblem]: + """Return every reason `value` is not a structurally-valid v2 array doc. + + Checks structure, not domain validity: `dtype` must be a string or field + records, but the string content is not interpreted; `compressor` and + `filters` are required keys that may be `None`, and otherwise must be + codec configurations (mappings with a string `id`). + """ + if not isinstance(value, Mapping): + return [ValidationProblem((), "expected a mapping", "invalid_type")] + doc = cast("Mapping[str, object]", value) + problems: list[ValidationProblem] = _missing_keys(ARRAY_METADATA_REQUIRED_KEYS_V2, doc) + problems.extend( + _unexpected_keys(ARRAY_METADATA_STANDARD_KEYS_V2, cast("Mapping[object, object]", value)) + ) + problems.extend(_check_literal(doc, "zarr_format", 2)) + shape_problems = _validate_dim_sequence(doc, "shape") + chunks_problems = _validate_dim_sequence(doc, "chunks") + problems.extend(shape_problems) + problems.extend(chunks_problems) + if ( + not shape_problems + and not chunks_problems + and _is_int_sequence(doc.get("shape")) + and _is_int_sequence(doc.get("chunks")) + ): + shape = cast("Sequence[int]", doc["shape"]) + chunks = cast("Sequence[int]", doc["chunks"]) + if len(shape) != len(chunks): + problems.append( + ValidationProblem( + ("chunks",), + "expected the same number of dimensions as shape", + "invalid_value", + ) + ) + if "dtype" in doc and not _is_dtype_v2(doc["dtype"]): + problems.append( + ValidationProblem( + ("dtype",), + "expected a v2 dtype string or a sequence of field records", + "invalid_type", + ) + ) + if "order" in doc and doc["order"] not in ("C", "F"): + problems.append( + ValidationProblem( + ("order",), f"expected 'C' or 'F', got {doc['order']!r}", "invalid_value" + ) + ) + if "compressor" in doc: + compressor = doc["compressor"] + if compressor is not None: + problems.extend(_prefix("compressor", _validate_codec_v2(compressor))) + if "filters" in doc: + filters = doc["filters"] + if filters is not None and ( + isinstance(filters, str) + or not isinstance(filters, Sequence) + or not all(_is_codec_v2(item) for item in cast("Sequence[object]", filters)) + ): + problems.append( + ValidationProblem( + ("filters",), + "expected null or a sequence of codec configurations with string 'id's", + "invalid_type", + ) + ) + elif filters is not None: + if len(cast("Sequence[object]", filters)) == 0: + problems.append( + ValidationProblem(("filters",), "expected at least one filter", "invalid_value") + ) + for index, item in enumerate(cast("Sequence[object]", filters)): + problems.extend(_prefix("filters", _prefix(index, validate_json(item)))) + if "dimension_separator" in doc and doc["dimension_separator"] not in (".", "/"): + problems.append( + ValidationProblem( + ("dimension_separator",), + f"expected '.' or '/', got {doc['dimension_separator']!r}", + "invalid_value", + ) + ) + if "fill_value" in doc: + problems.extend(_prefix("fill_value", validate_json(doc["fill_value"]))) + if "attributes" in doc: + problems.extend(_validate_attributes(doc["attributes"])) + return problems + + +def is_array_metadata_v2(value: object) -> TypeIs[ZarrV2ArrayMetadataJSON]: + """Whether `value` is a structurally-valid v2 array metadata document.""" + return ( + _is_canonical_json(value) + and not validate_array_metadata_v2(value) + and _is_canonical_array_metadata_v2(value) + ) + + +def parse_array_metadata_v2(value: object) -> ZarrV2ArrayMetadataJSON: + """Return `value` as `ZarrV2ArrayMetadataJSON`, or raise `MetadataValidationError`.""" + normalized = arrays_to_tuples(value) + problems = validate_array_metadata_v2(normalized) + if problems: + raise MetadataValidationError(problems) + return cast("ZarrV2ArrayMetadataJSON", normalized) + + +def validate_consolidated_metadata_v3(value: object) -> list[ValidationProblem]: + """Return every reason `value` is not a valid inline consolidated envelope. + + Locs are value-relative (the caller prefixes with `consolidated_metadata` + where appropriate). Entries recurse into the array and group document + validators, so a validator verdict always agrees with what + `ZarrV3ConsolidatedMetadata.from_json` accepts. + """ + if not isinstance(value, Mapping): + return [ValidationProblem((), "expected a mapping", "invalid_type")] + env = cast("Mapping[str, object]", value) + problems: list[ValidationProblem] = [ + ValidationProblem((key,), "missing required key", "missing_key") + for key in ("kind", "must_understand", "metadata") + if key not in env + ] + problems.extend( + _unexpected_keys( + frozenset({"kind", "must_understand", "metadata"}), + cast("Mapping[object, object]", value), + ) + ) + problems.extend(_check_literal(env, "kind", "inline")) + if "must_understand" in env and env["must_understand"] is not False: + problems.append(ValidationProblem(("must_understand",), "expected False", "invalid_value")) + if "metadata" in env: + entries = env["metadata"] + if not isinstance(entries, Mapping): + problems.append(ValidationProblem(("metadata",), "expected a mapping", "invalid_type")) + else: + for key, entry in cast("Mapping[object, object]", entries).items(): + if not isinstance(key, str): + problems.append( + ValidationProblem(("metadata",), f"non-string key {key!r}", "invalid_type") + ) + continue + entry_obj: object = entry + node_type: object = None + if isinstance(entry, Mapping): + node_type = cast("Mapping[str, object]", entry).get("node_type") + if node_type == "array": + problems.extend( + _prefix("metadata", _prefix(key, validate_array_metadata_v3(entry_obj))) + ) + elif node_type == "group": + problems.extend( + _prefix("metadata", _prefix(key, validate_group_metadata_v3(entry_obj))) + ) + else: + problems.append( + ValidationProblem( + ("metadata", key, "node_type"), + "expected 'array' or 'group'", + "invalid_value", + ) + ) + return problems + + +def validate_group_metadata_v3(value: object) -> list[ValidationProblem]: + """Return every reason `value` is not a structurally-valid v3 group doc. + + Checks structure, not domain validity. Unknown top-level keys are allowed + (they map to `extra_fields`); a `consolidated_metadata` key, if present, + is deep-validated (envelope and entries) via + `validate_consolidated_metadata_v3`. + """ + if not isinstance(value, Mapping): + return [ValidationProblem((), "expected a mapping", "invalid_type")] + doc = cast("Mapping[str, object]", value) + problems: list[ValidationProblem] = _missing_keys(GROUP_METADATA_REQUIRED_KEYS_V3, doc) + problems.extend( + _validate_extension_fields_v3( + cast("Mapping[object, object]", value), + GROUP_METADATA_STANDARD_KEYS_V3, + additional_reserved_keys=frozenset({"consolidated_metadata"}), + ) + ) + problems.extend(_check_literal(doc, "zarr_format", 3)) + problems.extend(_check_literal(doc, "node_type", "group")) + if "attributes" in doc: + problems.extend(_validate_attributes(doc["attributes"])) + if "consolidated_metadata" in doc and doc["consolidated_metadata"] is not None: + # consolidated_metadata: null (a historical zarr-python bug) is + # structurally accepted so those stores remain readable, but the model + # repairs it to absence on read and never writes it back. + problems.extend( + _prefix( + "consolidated_metadata", + validate_consolidated_metadata_v3(doc["consolidated_metadata"]), + ) + ) + return problems + + +def is_group_metadata_v3(value: object) -> TypeIs[ZarrV3GroupMetadataJSON]: + """Whether `value` is a structurally-valid v3 group metadata document.""" + return _is_canonical_json(value) and not validate_group_metadata_v3(value) + + +def parse_group_metadata_v3(value: object) -> ZarrV3GroupMetadataJSON: + """Return `value` narrowed to `ZarrV3GroupMetadataJSON`, or raise `MetadataValidationError`.""" + normalized = arrays_to_tuples(value) + problems = validate_group_metadata_v3(normalized) + if problems: + raise MetadataValidationError(problems) + return cast(ZarrV3GroupMetadataJSON, normalized) + + +def validate_group_metadata_v2(value: object) -> list[ValidationProblem]: + """Return every reason `value` is not a structurally-valid v2 group doc. + + Validates the in-memory merged form: the `.zgroup` fields plus an + optional `attributes` mapping folded in from `.zattrs`. + """ + if not isinstance(value, Mapping): + return [ValidationProblem((), "expected a mapping", "invalid_type")] + doc = cast("Mapping[str, object]", value) + problems: list[ValidationProblem] = _missing_keys(GROUP_METADATA_REQUIRED_KEYS_V2, doc) + problems.extend( + _unexpected_keys(GROUP_METADATA_STANDARD_KEYS_V2, cast("Mapping[object, object]", value)) + ) + problems.extend(_check_literal(doc, "zarr_format", 2)) + if "attributes" in doc: + problems.extend(_validate_attributes(doc["attributes"])) + return problems + + +def is_group_metadata_v2(value: object) -> TypeIs[ZarrV2GroupMetadataJSON]: + """Whether `value` is a structurally-valid v2 group metadata document.""" + return _is_canonical_json(value) and not validate_group_metadata_v2(value) + + +def parse_group_metadata_v2(value: object) -> ZarrV2GroupMetadataJSON: + """Return `value` narrowed to `ZarrV2GroupMetadataJSON`, or raise `MetadataValidationError`.""" + normalized = arrays_to_tuples(value) + problems = validate_group_metadata_v2(normalized) + if problems: + raise MetadataValidationError(problems) + return cast(ZarrV2GroupMetadataJSON, normalized) + + +def _reject_json_constant(constant: str) -> NoReturn: + """Reject the JavaScript constants accepted by Python's JSON decoder.""" + raise ValueError(f"non-standard JSON constant {constant!r}") + + +def load_store_json(mapping: Mapping[str, bytes], key: str) -> Any: + """Decode the JSON document stored at `key` in `mapping`. + + Every ingestion failure surfaces as `MetadataValidationError`: a missing + store key is a `missing_key` problem and undecodable bytes are an + `invalid_json` problem, rather than leaking `KeyError` / + `json.JSONDecodeError` to callers. + """ + if key not in mapping: + raise MetadataValidationError( + [ValidationProblem((key,), "missing store key", "missing_key")] + ) + try: + return json.loads(mapping[key], parse_constant=_reject_json_constant) + except (UnicodeDecodeError, ValueError) as exc: + raise MetadataValidationError( + [ValidationProblem((key,), f"invalid JSON: {exc}", "invalid_json")] + ) from exc + + +def dump_store_json(value: object, *, indent: int | str | None = None) -> bytes: + """Encode a metadata document as strict RFC 8259 JSON bytes.""" + return json.dumps(value, indent=indent, allow_nan=False).encode("utf-8") + + +def arrays_to_tuples(obj: object) -> object: + """Recursively materialize mappings and convert array-like values to tuples.""" + if isinstance(obj, Sequence) and not isinstance(obj, (str, bytes, bytearray)): + sequence = cast("Sequence[object]", obj) + converted_sequence = tuple(arrays_to_tuples(item) for item in sequence) + if isinstance(obj, tuple) and all( + converted is original + for converted, original in zip(converted_sequence, sequence, strict=True) + ): + return cast("tuple[object, ...]", obj) + return converted_sequence + if isinstance(obj, Mapping): + mapping = cast("Mapping[object, object]", obj) + converted: dict[object, object] = { + key: arrays_to_tuples(value) for key, value in mapping.items() + } + if isinstance(obj, dict) and all(converted[key] is value for key, value in mapping.items()): + return cast("object", obj) + return converted + return obj diff --git a/tests/v2/__init__.py b/packages/zarr-metadata/src/zarr_metadata/py.typed similarity index 100% rename from tests/v2/__init__.py rename to packages/zarr-metadata/src/zarr_metadata/py.typed diff --git a/packages/zarr-metadata/src/zarr_metadata/pydantic.py b/packages/zarr-metadata/src/zarr_metadata/pydantic.py new file mode 100644 index 0000000000..8584efa570 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/pydantic.py @@ -0,0 +1,176 @@ +"""Optional pydantic (v2) integration: field types over the core models. + +Importing this module requires pydantic; the core package deliberately does +not depend on it, so this module is never imported by `zarr_metadata` itself. + +Each exported name is an `Annotated` field type over the corresponding core +model class β€” the instances ARE the core classes, so values interoperate +freely with non-pydantic code (equality, isinstance, nesting). Validation +delegates to the library: a raw document routes through `from_json` (the +single source of truth for structural validation and normalization, so +pydantic's field-level coercion can never bypass it), an existing model +instance passes through unchanged, and serialization emits the canonical +document via `to_json`. `MetadataValidationError` subclasses `ValueError`, +so a failed parse surfaces as a pydantic `ValidationError` carrying the +loc-annotated problem messages. + +Usage: + + import zarr_metadata.pydantic as zmp + + class ArrayManifest(BaseModel): + path: str + metadata: zmp.ZarrV3ArrayMetadata + +Static type checkers see each field type as its core model class, so +`manifest.metadata` is a `zarr_metadata.model.ZarrV3ArrayMetadata`. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Annotated, TypeVar + +from pydantic import BeforeValidator, InstanceOf, PlainSerializer + +from zarr_metadata import model as _model +from zarr_metadata._pydantic_schema import ( + ZarrV2ArrayMetadataJSON as _ZarrV2ArrayMetadataSchema, +) +from zarr_metadata._pydantic_schema import ( + ZarrV2ConsolidatedMetadataJSON as _ZarrV2ConsolidatedMetadataSchema, +) +from zarr_metadata._pydantic_schema import ( + ZarrV2GroupMetadataJSON as _ZarrV2GroupMetadataSchema, +) +from zarr_metadata._pydantic_schema import ( + ZarrV3ArrayMetadataJSON as _ZarrV3ArrayMetadataSchema, +) +from zarr_metadata._pydantic_schema import ( + ZarrV3ConsolidatedMetadataJSON as _ZarrV3ConsolidatedMetadataSchema, +) +from zarr_metadata._pydantic_schema import ( + ZarrV3GroupMetadataJSON as _ZarrV3GroupMetadataSchema, +) +from zarr_metadata._pydantic_schema import ( + ZarrV3MetadataFieldJSON as _ZarrV3MetadataFieldSchema, +) +from zarr_metadata.v2.array import ZarrV2ArrayMetadataJSON as _ZarrV2ArrayMetadataJSON +from zarr_metadata.v2.consolidated import ( + ZarrV2ConsolidatedMetadataJSON as _ZarrV2ConsolidatedMetadataJSON, +) +from zarr_metadata.v2.group import ZarrV2GroupMetadataJSON as _ZarrV2GroupMetadataJSON +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON as _ZarrV3MetadataFieldJSON +from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON as _ZarrV3ArrayMetadataJSON +from zarr_metadata.v3.consolidated import ( + ZarrV3ConsolidatedMetadataJSON as _ZarrV3ConsolidatedMetadataJSON, +) +from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON as _ZarrV3GroupMetadataJSON + +if TYPE_CHECKING: + from collections.abc import Callable + +_M = TypeVar("_M") + + +def _coerce_to(cls: type[_M], parse: Callable[[object], _M]) -> Callable[[object], _M]: + """A validator that passes instances of `cls` through and parses anything else.""" + + def coerce(value: object) -> _M: + if isinstance(value, cls): + return value + return parse(value) + + return coerce + + +ZarrV3ArrayMetadata = Annotated[ + InstanceOf[_model.ZarrV3ArrayMetadata], + BeforeValidator( + _coerce_to(_model.ZarrV3ArrayMetadata, _model.ZarrV3ArrayMetadata.from_json), + json_schema_input_type=_ZarrV3ArrayMetadataSchema, + ), + PlainSerializer(_model.ZarrV3ArrayMetadata.to_json, return_type=_ZarrV3ArrayMetadataJSON), +] +"""Field type for a v3 array metadata document (`zarr.json` content).""" + +ZarrV2ArrayMetadata = Annotated[ + InstanceOf[_model.ZarrV2ArrayMetadata], + BeforeValidator( + _coerce_to(_model.ZarrV2ArrayMetadata, _model.ZarrV2ArrayMetadata.from_json), + json_schema_input_type=_ZarrV2ArrayMetadataSchema, + ), + PlainSerializer(_model.ZarrV2ArrayMetadata.to_json, return_type=_ZarrV2ArrayMetadataJSON), +] +"""Field type for a v2 array metadata document (merged `.zarray` + `.zattrs` form).""" + +ZarrV3GroupMetadata = Annotated[ + InstanceOf[_model.ZarrV3GroupMetadata], + BeforeValidator( + _coerce_to(_model.ZarrV3GroupMetadata, _model.ZarrV3GroupMetadata.from_json), + json_schema_input_type=_ZarrV3GroupMetadataSchema, + ), + PlainSerializer(_model.ZarrV3GroupMetadata.to_json, return_type=_ZarrV3GroupMetadataJSON), +] +"""Field type for a v3 group metadata document (`zarr.json` content).""" + +ZarrV2GroupMetadata = Annotated[ + InstanceOf[_model.ZarrV2GroupMetadata], + BeforeValidator( + _coerce_to(_model.ZarrV2GroupMetadata, _model.ZarrV2GroupMetadata.from_json), + json_schema_input_type=_ZarrV2GroupMetadataSchema, + ), + PlainSerializer(_model.ZarrV2GroupMetadata.to_json, return_type=_ZarrV2GroupMetadataJSON), +] +"""Field type for a v2 group metadata document (merged `.zgroup` + `.zattrs` form).""" + +ZarrV3ConsolidatedMetadata = Annotated[ + InstanceOf[_model.ZarrV3ConsolidatedMetadata], + BeforeValidator( + _coerce_to( + _model.ZarrV3ConsolidatedMetadata, + _model.ZarrV3ConsolidatedMetadata.from_json, + ), + json_schema_input_type=_ZarrV3ConsolidatedMetadataSchema, + ), + PlainSerializer( + _model.ZarrV3ConsolidatedMetadata.to_json, + return_type=_ZarrV3ConsolidatedMetadataJSON, + ), +] +"""Field type for v3 inline consolidated metadata.""" + +ZarrV2ConsolidatedMetadata = Annotated[ + InstanceOf[_model.ZarrV2ConsolidatedMetadata], + BeforeValidator( + _coerce_to( + _model.ZarrV2ConsolidatedMetadata, + _model.ZarrV2ConsolidatedMetadata.from_json, + ), + json_schema_input_type=_ZarrV2ConsolidatedMetadataSchema, + ), + PlainSerializer( + _model.ZarrV2ConsolidatedMetadata.to_json, + return_type=_ZarrV2ConsolidatedMetadataJSON, + ), +] +"""Field type for a v2 `.zmetadata` document.""" + +ZarrV3MetadataField = Annotated[ + InstanceOf[_model.ZarrV3NamedConfig], + BeforeValidator( + _coerce_to(_model.ZarrV3NamedConfig, _model.ZarrV3NamedConfig.from_json), + json_schema_input_type=_ZarrV3MetadataFieldSchema, + ), + PlainSerializer(_model.ZarrV3NamedConfig.to_json, return_type=_ZarrV3MetadataFieldJSON), +] +"""Field type for one normalized v3 metadata extension envelope.""" + +__all__ = [ + "ZarrV2ArrayMetadata", + "ZarrV2ConsolidatedMetadata", + "ZarrV2GroupMetadata", + "ZarrV3ArrayMetadata", + "ZarrV3ConsolidatedMetadata", + "ZarrV3GroupMetadata", + "ZarrV3MetadataField", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/__init__.py b/packages/zarr-metadata/src/zarr_metadata/v2/__init__.py new file mode 100644 index 0000000000..b9001d168e --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v2/__init__.py @@ -0,0 +1,26 @@ +"""Zarr v2 metadata types.""" + +from zarr_metadata.v2.array import ( + ZarrV2ArrayDimensionSeparator, + ZarrV2ArrayMetadataJSON, + ZarrV2ArrayOrder, + ZarrV2DataTypeMetadata, + ZarrV2ZArrayJSON, +) +from zarr_metadata.v2.attributes import ZarrV2ZAttrsJSON +from zarr_metadata.v2.codec import ZarrV2CodecMetadata +from zarr_metadata.v2.consolidated import ZarrV2ConsolidatedMetadataJSON +from zarr_metadata.v2.group import ZarrV2GroupMetadataJSON, ZarrV2ZGroupJSON + +__all__ = [ + "ZarrV2ArrayDimensionSeparator", + "ZarrV2ArrayMetadataJSON", + "ZarrV2ArrayOrder", + "ZarrV2CodecMetadata", + "ZarrV2ConsolidatedMetadataJSON", + "ZarrV2DataTypeMetadata", + "ZarrV2GroupMetadataJSON", + "ZarrV2ZArrayJSON", + "ZarrV2ZAttrsJSON", + "ZarrV2ZGroupJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/array.py b/packages/zarr-metadata/src/zarr_metadata/v2/array.py new file mode 100644 index 0000000000..e026e5c655 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v2/array.py @@ -0,0 +1,170 @@ +"""Zarr v2 array metadata types.""" + +from collections.abc import Mapping +from typing import Final, Literal, NotRequired + +from typing_extensions import TypeAliasType, TypedDict + +from zarr_metadata._common import JSONValue +from zarr_metadata.v2.codec import ZarrV2CodecMetadata + +ZarrV2DataTypeMetadata = TypeAliasType( + "ZarrV2DataTypeMetadata", + str + | tuple[ + tuple[str, "ZarrV2DataTypeMetadata"] + | tuple[str, "ZarrV2DataTypeMetadata", tuple[int, ...]], + ..., + ], +) +"""The v2 dtype representation. + +Either a numpy-style dtype string (e.g. `"/.zarray` for + a v2 array. User attributes live in a sibling `.zattrs` file and are + NOT part of this type; see `ZarrV2ZAttrsJSON`. + + See https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html + """ + + zarr_format: Literal[2] + shape: tuple[int, ...] + chunks: tuple[int, ...] + dtype: ZarrV2DataTypeMetadata + compressor: ZarrV2CodecMetadata | None + fill_value: JSONValue + order: ZarrV2ArrayOrder + filters: tuple[ZarrV2CodecMetadata, ...] | None + dimension_separator: NotRequired[ZarrV2ArrayDimensionSeparator] + + +class ZarrV2ArrayMetadataJSON(TypedDict): + """ + Zarr v2 array metadata document, in-memory merged form. + + Models the union of `.zarray` (the spec-defined fields) and `.zattrs` + (user attributes). On disk, attributes live in a sibling `.zattrs` file + and are not part of `.zarray`; this type folds them in as the + `attributes` field so a single TypedDict represents the complete + in-memory state of a v2 array node. Consumers that read or write a + real `.zarray` file should split / merge `attributes` accordingly, + or use `ZarrV2ZArrayJSON` (strict on-disk) plus `ZarrV2ZAttrsJSON` directly. + + See https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html + """ + + zarr_format: Literal[2] + shape: tuple[int, ...] + chunks: tuple[int, ...] + dtype: ZarrV2DataTypeMetadata + compressor: ZarrV2CodecMetadata | None + fill_value: JSONValue + order: ZarrV2ArrayOrder + filters: tuple[ZarrV2CodecMetadata, ...] | None + dimension_separator: NotRequired[ZarrV2ArrayDimensionSeparator] + attributes: NotRequired[Mapping[str, JSONValue]] + """User attributes from the sibling `.zattrs` file (not part of `.zarray`). + + See the class docstring for the rationale behind the merged representation. + """ + + +class ZarrV2ArrayMetadataJSONPartial(TypedDict, total=False): + """ + Partial form of `ZarrV2ArrayMetadataJSON`: every field is `NotRequired`. + + Field annotations mirror `ZarrV2ArrayMetadataJSON` exactly. The only difference is + `total=False`, which makes every key optional at the type level. + + Use this when typing dicts that intentionally hold a subset of a complete + v2 array metadata document β€” e.g. test fixtures that override only a few + fields of a base template, or callers that build a fragment to be merged + into a complete document elsewhere. + + The `NotRequired[...]` wrappers on `dimension_separator` and `attributes` + are intentional: keeping them preserves byte-identical `__annotations__` + with `ZarrV2ArrayMetadataJSON` so the `==` check in + `tests/test_partial_equivalence.py` passes without special-casing those + fields (PEP 655 explicitly permits `NotRequired` inside `total=False`). + + Note: v2 array metadata has no `extra_items` setting (the v2 spec has no + extension-field concept), so this partial inherits the same closed shape. + + Drift between this type and `ZarrV2ArrayMetadataJSON` is prevented by + `tests/test_partial_equivalence.py`. + """ + + zarr_format: Literal[2] + shape: tuple[int, ...] + chunks: tuple[int, ...] + dtype: ZarrV2DataTypeMetadata + compressor: ZarrV2CodecMetadata | None + fill_value: JSONValue + order: ZarrV2ArrayOrder + filters: tuple[ZarrV2CodecMetadata, ...] | None + dimension_separator: NotRequired[ZarrV2ArrayDimensionSeparator] + attributes: NotRequired[Mapping[str, JSONValue]] + """User attributes from the sibling `.zattrs` file (not part of `.zarray`). + + See the class docstring for the rationale behind the merged representation. + """ + + +ZarrV2ArrayMetadataStoreKey = Literal[".zarray"] +"""Literal type of the store key holding a v2 array's metadata document.""" + +ZARR_V2_ARRAY_METADATA_STORE_KEY: Final[ZarrV2ArrayMetadataStoreKey] = ".zarray" +"""The store key a v2 array's metadata document is persisted under.""" + + +__all__ = [ + "ZARR_V2_ARRAY_DIMENSION_SEPARATOR", + "ZARR_V2_ARRAY_METADATA_STORE_KEY", + "ZARR_V2_ARRAY_ORDER", + "ZarrV2ArrayDimensionSeparator", + "ZarrV2ArrayMetadataJSON", + "ZarrV2ArrayMetadataJSONPartial", + "ZarrV2ArrayMetadataStoreKey", + "ZarrV2ArrayOrder", + "ZarrV2DataTypeMetadata", + "ZarrV2ZArrayJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/attributes.py b/packages/zarr-metadata/src/zarr_metadata/v2/attributes.py new file mode 100644 index 0000000000..68785d1660 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v2/attributes.py @@ -0,0 +1,36 @@ +"""Zarr v2 user-attributes file content. + +See https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html +""" + +from collections.abc import Mapping +from typing import Final, Literal + +from zarr_metadata._common import JSONValue + +ZarrV2ZAttrsJSON = Mapping[str, JSONValue] +"""On-disk `.zattrs` file content. + +A JSON object holding user-defined attributes for a v2 array or group. +Spec-defined keys for arrays / groups live in sibling `.zarray` / `.zgroup` +files (modeled by `ZarrV2ZArrayJSON` / `ZarrV2ZGroupJSON`). This type does not +constrain the keys or values of the attributes mapping. +""" + + +ZarrV2AttributesStoreKey = Literal[".zattrs"] +"""Literal type of the store key holding a v2 node's user attributes.""" + +ZARR_V2_ATTRIBUTES_STORE_KEY: Final[ZarrV2AttributesStoreKey] = ".zattrs" +"""The store key a v2 node's user attributes are persisted under. + +Shared by arrays and groups: both node types keep their attributes in a +sibling `.zattrs` file. +""" + + +__all__ = [ + "ZARR_V2_ATTRIBUTES_STORE_KEY", + "ZarrV2AttributesStoreKey", + "ZarrV2ZAttrsJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/codec.py b/packages/zarr-metadata/src/zarr_metadata/v2/codec.py new file mode 100644 index 0000000000..69125544e6 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v2/codec.py @@ -0,0 +1,29 @@ +""" +Zarr v2 codec configuration shape. + +In v2, compressors and filters are numcodecs configuration dicts: a required +`id` field naming the codec, plus arbitrary codec-specific extra fields. +""" + +from typing_extensions import TypedDict + +from zarr_metadata._common import JSONValue + + +class ZarrV2CodecMetadata(TypedDict, extra_items=JSONValue): + """ + A numcodecs configuration dict, used as a v2 compressor or filter. + + The required `id` field names the codec; codec-specific parameters + (e.g. `cname`, `clevel` for blosc) appear as extra fields. + + See the "compressor" and "filters" sections of + https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html + """ + + id: str + + +__all__ = [ + "ZarrV2CodecMetadata", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/consolidated.py b/packages/zarr-metadata/src/zarr_metadata/v2/consolidated.py new file mode 100644 index 0000000000..999c9131da --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v2/consolidated.py @@ -0,0 +1,56 @@ +"""Zarr v2 consolidated metadata (`.zmetadata` file). + +This module models the de-facto `.zmetadata` file used by the reference +Python implementation of Zarr v2. **This is NOT a spec artifact.** There +is no Zarr v2 specification that defines `.zmetadata`; it is a +canonical-implementation convention. +""" + +from collections.abc import Mapping +from typing import Final, Literal + +from typing_extensions import TypedDict + +from zarr_metadata.v2.array import ZarrV2ZArrayJSON +from zarr_metadata.v2.attributes import ZarrV2ZAttrsJSON +from zarr_metadata.v2.group import ZarrV2ZGroupJSON + + +class ZarrV2ConsolidatedMetadataJSON(TypedDict): + """ + `.zmetadata` file contents. + + The `metadata` map uses flat path keys (`"foo/bar/.zarray"`, + `"foo/.zattrs"`, etc.) pointing to the JSON contents of the file at + that path. The keys include the filename suffix, not just the node + path; the value's shape is determined by which file the key points at: + + - `/.zarray` -> `ZarrV2ZArrayJSON` + - `/.zgroup` -> `ZarrV2ZGroupJSON` + - `/.zattrs` -> `ZarrV2ZAttrsJSON` + + The TypedDict cannot discriminate the value shape on the key suffix + at the type level; consumers should narrow at runtime by inspecting + `key.endswith(".zarray")` etc. + """ + + zarr_consolidated_format: int + metadata: Mapping[str, ZarrV2ZArrayJSON | ZarrV2ZGroupJSON | ZarrV2ZAttrsJSON] + + +ZarrV2ConsolidatedMetadataStoreKey = Literal[".zmetadata"] +"""Literal type of the store key holding a v2 hierarchy's consolidated metadata.""" + +ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY: Final[ZarrV2ConsolidatedMetadataStoreKey] = ".zmetadata" +"""The store key a v2 hierarchy's consolidated metadata is persisted under. + +Like the document it names, this is a reference-implementation convention +rather than a spec artifact; see the module docstring. +""" + + +__all__ = [ + "ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY", + "ZarrV2ConsolidatedMetadataJSON", + "ZarrV2ConsolidatedMetadataStoreKey", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/group.py b/packages/zarr-metadata/src/zarr_metadata/v2/group.py new file mode 100644 index 0000000000..34d72742c2 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v2/group.py @@ -0,0 +1,90 @@ +"""Zarr v2 group metadata types. + +See https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html +""" + +from collections.abc import Mapping +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +from zarr_metadata._common import JSONValue + + +class ZarrV2ZGroupJSON(TypedDict): + """ + On-disk `.zgroup` file content. + + Strict shape of the JSON document persisted at `/.zgroup` for + a v2 group. The spec defines exactly one field. User attributes live + in a sibling `.zattrs` file and are NOT part of this type; see + `ZarrV2ZAttrsJSON`. + + See https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html + """ + + zarr_format: Literal[2] + + +class ZarrV2GroupMetadataJSON(TypedDict): + """ + Zarr v2 group metadata document, in-memory merged form. + + Models the union of `.zgroup` (the spec-defined `zarr_format` field) + and `.zattrs` (user attributes). On disk these are persisted as two + separate files; this type folds them so a single TypedDict represents + the complete in-memory state of a v2 group node. Consumers that read + or write the real on-disk files should use `ZarrV2ZGroupJSON` (strict + `.zgroup`) plus `ZarrV2ZAttrsJSON` directly. + + See https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html + """ + + zarr_format: Literal[2] + attributes: NotRequired[Mapping[str, JSONValue]] + + +class ZarrV2GroupMetadataJSONPartial(TypedDict, total=False): + """ + Partial form of `ZarrV2GroupMetadataJSON`: every field is `NotRequired`. + + Field annotations mirror `ZarrV2GroupMetadataJSON` exactly. The only difference is + `total=False`, which makes every key optional at the type level. + + Use this when typing dicts that intentionally hold a subset of a complete + v2 group metadata document β€” e.g. test fixtures that override only a few + fields of a base template, or callers that build a fragment to be merged + into a complete document elsewhere. Provided for symmetry with the other + `*Partial` types; the practical effect is that `zarr_format` becomes optional. + + The `NotRequired[...]` wrapper on `attributes` is intentional: keeping it + preserves byte-identical `__annotations__` with `ZarrV2GroupMetadataJSON` so the + `==` check in `tests/test_partial_equivalence.py` passes without + special-casing that field (PEP 655 explicitly permits `NotRequired` inside + `total=False`). + + Note: v2 group metadata has no `extra_items` setting (the v2 spec has no + extension-field concept), so this partial inherits the same closed shape. + + Drift between this type and `ZarrV2GroupMetadataJSON` is prevented by + `tests/test_partial_equivalence.py`. + """ + + zarr_format: Literal[2] + attributes: NotRequired[Mapping[str, JSONValue]] + + +ZarrV2GroupMetadataStoreKey = Literal[".zgroup"] +"""Literal type of the store key holding a v2 group's metadata document.""" + +ZARR_V2_GROUP_METADATA_STORE_KEY: Final[ZarrV2GroupMetadataStoreKey] = ".zgroup" +"""The store key a v2 group's metadata document is persisted under.""" + + +__all__ = [ + "ZARR_V2_GROUP_METADATA_STORE_KEY", + "ZarrV2GroupMetadataJSON", + "ZarrV2GroupMetadataJSONPartial", + "ZarrV2GroupMetadataStoreKey", + "ZarrV2ZGroupJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/__init__.py b/packages/zarr-metadata/src/zarr_metadata/v3/__init__.py new file mode 100644 index 0000000000..4e335f9573 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/__init__.py @@ -0,0 +1,14 @@ +"""Zarr v3 metadata types.""" + +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON +from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON, ZarrV3ExtensionField +from zarr_metadata.v3.consolidated import ZarrV3ConsolidatedMetadataJSON +from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON + +__all__ = [ + "ZarrV3ArrayMetadataJSON", + "ZarrV3ConsolidatedMetadataJSON", + "ZarrV3ExtensionField", + "ZarrV3GroupMetadataJSON", + "ZarrV3MetadataFieldJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_common.py b/packages/zarr-metadata/src/zarr_metadata/v3/_common.py new file mode 100644 index 0000000000..406b76b723 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_common.py @@ -0,0 +1,23 @@ +"""Internal cross-cutting aliases for Zarr v3 metadata. + +This module is private (underscore-prefixed) and exists to avoid circular +imports between leaf modules and sub-package `__init__.py` re-exports. +Public consumers should import `ZarrV3MetadataFieldJSON` from `zarr_metadata.v3`. +""" + +from zarr_metadata._common import ZarrV3NamedConfigJSON + +ZarrV3MetadataFieldJSON = str | ZarrV3NamedConfigJSON +"""The JSON shape of any v3 metadata extension-point entry: either a bare +short-hand name string or a `{name, configuration, must_understand}` envelope. + +Used for `data_type`, `chunk_grid`, `chunk_key_encoding`, individual +codec entries, and `storage_transformers` in v3 array metadata, and for +the inner `codecs` / `index_codecs` lists of the `sharding_indexed` +codec. +""" + + +__all__ = [ + "ZarrV3MetadataFieldJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/array.py b/packages/zarr-metadata/src/zarr_metadata/v3/array.py new file mode 100644 index 0000000000..31a5f6b755 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/array.py @@ -0,0 +1,95 @@ +"""Zarr v3 array metadata types.""" + +from collections.abc import Mapping +from typing import Final, Literal, NotRequired, TypeAlias + +from typing_extensions import TypedDict + +from zarr_metadata._common import JSONValue +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON + +ZarrV3ExtensionField: TypeAlias = JSONValue +"""The JSON value of an unknown top-level v3 metadata field. + +An object carrying the literal member `must_understand: false` may be ignored. +Every other JSON shape implicitly requires understanding; recognition itself +belongs to the reader rather than this structural type. +""" + + +class ZarrV3ArrayMetadataJSON(TypedDict, extra_items=ZarrV3ExtensionField): + """ + Zarr v3 array metadata document (the `zarr.json` content for an array). + + Extra keys may contain arbitrary JSON values. + + See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#array-metadata + """ + + zarr_format: Literal[3] + node_type: Literal["array"] + data_type: ZarrV3MetadataFieldJSON + shape: tuple[int, ...] + chunk_grid: ZarrV3MetadataFieldJSON + chunk_key_encoding: ZarrV3MetadataFieldJSON + fill_value: JSONValue + codecs: tuple[ZarrV3MetadataFieldJSON, ...] + attributes: NotRequired[Mapping[str, JSONValue]] + storage_transformers: NotRequired[tuple[ZarrV3MetadataFieldJSON, ...]] + dimension_names: NotRequired[tuple[str | None, ...]] + + +class ZarrV3ArrayMetadataJSONPartial(TypedDict, total=False, extra_items=ZarrV3ExtensionField): + """ + Partial form of `ZarrV3ArrayMetadataJSON`: every field is `NotRequired`. + + Field annotations and `extra_items=` mirror `ZarrV3ArrayMetadataJSON` exactly. + The only difference is `total=False`, which makes every key optional + at the type level. + + Use this when typing dicts that intentionally hold a subset of a complete + v3 array metadata document β€” e.g. test fixtures that override only a few + fields of a base template, or callers that build a fragment to be merged + into a complete document elsewhere. + + The `NotRequired[...]` wrappers on `attributes`, `storage_transformers`, + and `dimension_names` are intentional: keeping them preserves byte-identical + `__annotations__` with `ZarrV3ArrayMetadataJSON` so the `==` check in + `tests/test_partial_equivalence.py` passes without special-casing those + fields (PEP 655 explicitly permits `NotRequired` inside `total=False`). + + Drift between this type and `ZarrV3ArrayMetadataJSON` is prevented by + `tests/test_partial_equivalence.py`. + """ + + zarr_format: Literal[3] + node_type: Literal["array"] + data_type: ZarrV3MetadataFieldJSON + shape: tuple[int, ...] + chunk_grid: ZarrV3MetadataFieldJSON + chunk_key_encoding: ZarrV3MetadataFieldJSON + fill_value: JSONValue + codecs: tuple[ZarrV3MetadataFieldJSON, ...] + attributes: NotRequired[Mapping[str, JSONValue]] + storage_transformers: NotRequired[tuple[ZarrV3MetadataFieldJSON, ...]] + dimension_names: NotRequired[tuple[str | None, ...]] + + +ZarrV3ArrayMetadataStoreKey = Literal["zarr.json"] +"""Literal type of the store key holding a v3 array's metadata document.""" + +ZARR_V3_ARRAY_METADATA_STORE_KEY: Final[ZarrV3ArrayMetadataStoreKey] = "zarr.json" +"""The store key a v3 array's metadata document is persisted under. + +v3 uses one key for both node types; the document's `node_type` field +distinguishes an array from a group. +""" + + +__all__ = [ + "ZARR_V3_ARRAY_METADATA_STORE_KEY", + "ZarrV3ArrayMetadataJSON", + "ZarrV3ArrayMetadataJSONPartial", + "ZarrV3ArrayMetadataStoreKey", + "ZarrV3ExtensionField", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/__init__.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/__init__.py new file mode 100644 index 0000000000..22b3ab52be --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/__init__.py @@ -0,0 +1,23 @@ +""" +Zarr v3 chunk grid metadata types. + +Each chunk grid lives in its own submodule: + +- `regular` -- core v3 spec +- `rectilinear` -- zarr-extensions + +The `ChunkGridMetadata` aliases re-exported here are the canonical type +for each grid's permitted JSON shapes. For the underlying +`ChunkGridObject`, `ChunkGridConfiguration`, etc., import directly +from the leaf submodule. + +See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#chunk-grids +""" + +from zarr_metadata.v3.chunk_grid.rectilinear import RectilinearChunkGridMetadata +from zarr_metadata.v3.chunk_grid.regular import RegularChunkGridMetadata + +__all__ = [ + "RectilinearChunkGridMetadata", + "RegularChunkGridMetadata", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/rectilinear.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/rectilinear.py new file mode 100644 index 0000000000..e3551e3c72 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/rectilinear.py @@ -0,0 +1,54 @@ +""" +Rectilinear chunk grid (zarr-extensions). + +See https://github.com/zarr-developers/zarr-extensions/tree/main/chunk-grids/rectilinear +""" + +from typing import Final, Literal + +from typing_extensions import TypedDict + +RECTILINEAR_CHUNK_GRID_NAME: Final = "rectilinear" +"""The `name` field value of the rectilinear chunk grid.""" + +RectilinearChunkGridName = Literal["rectilinear"] +"""Literal type of the `name` field of the rectilinear chunk grid.""" + +RectilinearDimSpec = int | tuple[int | tuple[int, int], ...] +"""JSON shape for one dimension's rectilinear spec. + +Either a bare integer (uniform shorthand for a regular dimension within +a rectilinear grid), or a tuple of integers and/or `[value, count]` RLE +pairs. +""" + + +class RectilinearChunkGridConfiguration(TypedDict): + """Configuration for the rectilinear chunk grid.""" + + kind: Literal["inline"] + chunk_shapes: tuple[RectilinearDimSpec, ...] + + +class RectilinearChunkGridObject(TypedDict): + """Rectilinear chunk grid metadata in object form.""" + + name: RectilinearChunkGridName + configuration: RectilinearChunkGridConfiguration + + +RectilinearChunkGridMetadata = RectilinearChunkGridObject +"""Permitted JSON shape for rectilinear chunk grid metadata. + +`kind` and `chunk_shapes` are required, so only the object form is valid; +the short-hand-name form is not permitted by the spec for this grid. +""" + +__all__ = [ + "RECTILINEAR_CHUNK_GRID_NAME", + "RectilinearChunkGridConfiguration", + "RectilinearChunkGridMetadata", + "RectilinearChunkGridName", + "RectilinearChunkGridObject", + "RectilinearDimSpec", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/regular.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/regular.py new file mode 100644 index 0000000000..2f7a089934 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/regular.py @@ -0,0 +1,44 @@ +""" +Regular chunk grid (Zarr v3 core spec). + +See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#regular-grids +""" + +from typing import Final, Literal + +from typing_extensions import TypedDict + +REGULAR_CHUNK_GRID_NAME: Final = "regular" +"""The `name` field value of the regular chunk grid.""" + +RegularChunkGridName = Literal["regular"] +"""Literal type of the `name` field of the regular chunk grid.""" + + +class RegularChunkGridConfiguration(TypedDict): + """Configuration for the regular chunk grid.""" + + chunk_shape: tuple[int, ...] + + +class RegularChunkGridObject(TypedDict): + """Regular chunk grid metadata in object form.""" + + name: RegularChunkGridName + configuration: RegularChunkGridConfiguration + + +RegularChunkGridMetadata = RegularChunkGridObject +"""Permitted JSON shape for regular chunk grid metadata. + +`chunk_shape` is required and has no default, so only the object form is +valid; the short-hand-name form is not permitted by the spec for this grid. +""" + +__all__ = [ + "REGULAR_CHUNK_GRID_NAME", + "RegularChunkGridConfiguration", + "RegularChunkGridMetadata", + "RegularChunkGridName", + "RegularChunkGridObject", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/__init__.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/__init__.py new file mode 100644 index 0000000000..b6774efbe3 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/__init__.py @@ -0,0 +1,25 @@ +""" +Zarr v3 chunk key encoding metadata types. + +Each chunk key encoding lives in its own submodule: + +- `default` -- v3 default encoding (`/`-separated) +- `v2` -- v2-compatibility encoding (`.`-separated by default) + +Both are defined by the v3 core spec. + +The `ChunkKeyEncodingMetadata` aliases re-exported here are the canonical +type for each encoding's permitted JSON shapes. For the underlying +`ChunkKeyEncodingObject`, `ChunkKeyEncodingConfiguration`, etc., import +directly from the leaf submodule. + +See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#chunk-key-encoding +""" + +from zarr_metadata.v3.chunk_key_encoding.default import DefaultChunkKeyEncodingMetadata +from zarr_metadata.v3.chunk_key_encoding.v2 import V2ChunkKeyEncodingMetadata + +__all__ = [ + "DefaultChunkKeyEncodingMetadata", + "V2ChunkKeyEncodingMetadata", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/default.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/default.py new file mode 100644 index 0000000000..c783861b34 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/default.py @@ -0,0 +1,61 @@ +""" +Default chunk key encoding (Zarr v3 core spec). + +The chunk key for a chunk with grid index `(k, j, i, ...)` is formed +by appending `ckji...` (where `` is `separator`). + +See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#chunk-key-encoding +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +DEFAULT_CHUNK_KEY_ENCODING_NAME: Final = "default" +"""The `name` field value of the default chunk key encoding.""" + +DefaultChunkKeyEncodingName = Literal["default"] +"""Literal type of the `name` field of the default chunk key encoding.""" + +DefaultChunkKeyEncodingSeparator = Literal["/", "."] +"""Literal type of permitted `separator` values for the default chunk key encoding. + +Defaults to `"/"` if absent. +""" + +DEFAULT_CHUNK_KEY_ENCODING_SEPARATOR: Final = ("/", ".") +"""Tuple of permitted values for the `separator` field of the default chunk key encoding.""" + + +class DefaultChunkKeyEncodingConfiguration(TypedDict): + """Configuration for the default chunk key encoding. + + `separator` is optional and defaults to `"/"` per spec. + """ + + separator: NotRequired[DefaultChunkKeyEncodingSeparator] + + +class DefaultChunkKeyEncodingObject(TypedDict): + """Default chunk key encoding metadata in object form.""" + + name: DefaultChunkKeyEncodingName + configuration: NotRequired[DefaultChunkKeyEncodingConfiguration] + + +DefaultChunkKeyEncodingMetadata = DefaultChunkKeyEncodingObject | DefaultChunkKeyEncodingName +"""Permitted JSON shapes for the default chunk-key encoding metadata. + +The configuration has no required keys (`separator` defaults to `"/"`), +so the short-hand-name form is permitted in addition to the object form. +""" + +__all__ = [ + "DEFAULT_CHUNK_KEY_ENCODING_NAME", + "DEFAULT_CHUNK_KEY_ENCODING_SEPARATOR", + "DefaultChunkKeyEncodingConfiguration", + "DefaultChunkKeyEncodingMetadata", + "DefaultChunkKeyEncodingName", + "DefaultChunkKeyEncodingObject", + "DefaultChunkKeyEncodingSeparator", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/v2.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/v2.py new file mode 100644 index 0000000000..e2783d296d --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/v2.py @@ -0,0 +1,67 @@ +""" +v2-compatibility chunk key encoding (Zarr v3 core spec). + +Intended only to allow existing v2 arrays to be converted to v3 without +having to rename chunks. Not recommended for new arrays. + +Naming note: these are Zarr **v3** types. The leading `V2` in +`V2ChunkKeyEncodingMetadata` (and friends) is the encoding's registered +*entity name* (`"v2"`), not the format-version marker that `ZarrV2...` +names carry β€” this package's version-prefixed names always spell it +`ZarrV2` / `ZarrV3`. + +See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#chunk-key-encoding +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +V2_CHUNK_KEY_ENCODING_NAME: Final = "v2" +"""The `name` field value of the v2 chunk key encoding.""" + +V2ChunkKeyEncodingName = Literal["v2"] +"""Literal type of the `name` field of the v2 chunk key encoding.""" + +V2ChunkKeyEncodingSeparator = Literal["/", "."] +"""Literal type of permitted `separator` values for the v2 chunk key encoding. + +Defaults to `"."` if absent. +""" + +V2_CHUNK_KEY_ENCODING_SEPARATOR: Final = ("/", ".") +"""Tuple of permitted values for the `separator` field of the v2 chunk key encoding.""" + + +class V2ChunkKeyEncodingConfiguration(TypedDict): + """Configuration for the v2 chunk key encoding. + + `separator` is optional and defaults to `"."` per spec. + """ + + separator: NotRequired[V2ChunkKeyEncodingSeparator] + + +class V2ChunkKeyEncodingObject(TypedDict): + """v2-compatibility chunk key encoding metadata in object form.""" + + name: V2ChunkKeyEncodingName + configuration: NotRequired[V2ChunkKeyEncodingConfiguration] + + +V2ChunkKeyEncodingMetadata = V2ChunkKeyEncodingObject | V2ChunkKeyEncodingName +"""Permitted JSON shapes for the v2-compatibility chunk-key encoding metadata. + +The configuration has no required keys (`separator` defaults to `"."`), +so the short-hand-name form is permitted in addition to the object form. +""" + +__all__ = [ + "V2_CHUNK_KEY_ENCODING_NAME", + "V2_CHUNK_KEY_ENCODING_SEPARATOR", + "V2ChunkKeyEncodingConfiguration", + "V2ChunkKeyEncodingMetadata", + "V2ChunkKeyEncodingName", + "V2ChunkKeyEncodingObject", + "V2ChunkKeyEncodingSeparator", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/__init__.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/__init__.py new file mode 100644 index 0000000000..c8a9a150fc --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/__init__.py @@ -0,0 +1,40 @@ +""" +Zarr v3 codec spec types. + +Each codec defined by the spec or by zarr-extensions has its own submodule +(`blosc`, `bytes`, `cast_value`, `crc32c`, `gzip`, `scale_offset`, +`sharding_indexed`, `transpose`, `zstd`). + +The `CodecMetadata` aliases re-exported here are the canonical type for +each codec's permitted JSON shapes (object form plus, where the spec allows, +a bare-string short-hand form). For the underlying `CodecObject`, +`CodecConfiguration`, etc., import directly from the leaf submodule. + +For the field-level "any codec entry" alias (used in array metadata's +`codecs` list and in sharding's inner pipelines), import `ZarrV3MetadataFieldJSON` +from `zarr_metadata.v3`. + +See https://zarr-specs.readthedocs.io/en/latest/v3/codecs/index.html +""" + +from zarr_metadata.v3.codec.blosc import BloscCodecMetadata +from zarr_metadata.v3.codec.bytes import BytesCodecMetadata +from zarr_metadata.v3.codec.cast_value import CastValueCodecMetadata +from zarr_metadata.v3.codec.crc32c import Crc32cCodecMetadata +from zarr_metadata.v3.codec.gzip import GzipCodecMetadata +from zarr_metadata.v3.codec.scale_offset import ScaleOffsetCodecMetadata +from zarr_metadata.v3.codec.sharding_indexed import ShardingIndexedCodecMetadata +from zarr_metadata.v3.codec.transpose import TransposeCodecMetadata +from zarr_metadata.v3.codec.zstd import ZstdCodecMetadata + +__all__ = [ + "BloscCodecMetadata", + "BytesCodecMetadata", + "CastValueCodecMetadata", + "Crc32cCodecMetadata", + "GzipCodecMetadata", + "ScaleOffsetCodecMetadata", + "ShardingIndexedCodecMetadata", + "TransposeCodecMetadata", + "ZstdCodecMetadata", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/blosc.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/blosc.py new file mode 100644 index 0000000000..5a986c8260 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/blosc.py @@ -0,0 +1,65 @@ +""" +Blosc codec types. + +See https://zarr-specs.readthedocs.io/en/latest/v3/codecs/blosc/index.html +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +BLOSC_CODEC_NAME: Final = "blosc" +"""The `name` field value of the `blosc` codec.""" + +BloscCodecName = Literal["blosc"] +"""Literal type of the `name` field of the `blosc` codec.""" + +BloscShuffle = Literal["noshuffle", "shuffle", "bitshuffle"] +"""Literal type of blosc shuffle mode names.""" + +BLOSC_SHUFFLE: Final = ("noshuffle", "shuffle", "bitshuffle") +"""Tuple of permitted values for the `shuffle` field of the `blosc` codec.""" + +BloscCName = Literal["lz4", "lz4hc", "blosclz", "snappy", "zlib", "zstd"] +"""Literal type of blosc compressor identifiers.""" + +BLOSC_CNAME: Final = ("lz4", "lz4hc", "blosclz", "snappy", "zlib", "zstd") +"""Tuple of permitted values for the `cname` field of the `blosc` codec.""" + + +class BloscCodecConfiguration(TypedDict): + """Configuration for the Zarr v3 `blosc` codec.""" + + cname: BloscCName + clevel: int + shuffle: BloscShuffle + blocksize: int + typesize: NotRequired[int] + + +class BloscCodecObject(TypedDict): + """`blosc` codec metadata in object form.""" + + name: BloscCodecName + configuration: BloscCodecConfiguration + + +BloscCodecMetadata = BloscCodecObject +"""Permitted JSON shape for `blosc` codec metadata. + +The configuration has multiple required keys (`cname`, `clevel`, `shuffle`, +`blocksize`), so only the object form is valid; the short-hand-name form +is not permitted by the spec for this codec. +""" + +__all__ = [ + "BLOSC_CNAME", + "BLOSC_CODEC_NAME", + "BLOSC_SHUFFLE", + "BloscCName", + "BloscCodecConfiguration", + "BloscCodecMetadata", + "BloscCodecName", + "BloscCodecObject", + "BloscShuffle", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/bytes.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/bytes.py new file mode 100644 index 0000000000..04e746f898 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/bytes.py @@ -0,0 +1,64 @@ +""" +Bytes codec types. + +See https://zarr-specs.readthedocs.io/en/latest/v3/codecs/bytes/index.html +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +BYTES_CODEC_NAME: Final = "bytes" +"""The `name` field value of the `bytes` codec.""" + +BytesCodecName = Literal["bytes"] +"""Literal type of the `name` field of the `bytes` codec.""" + +Endianness = Literal["little", "big"] +"""Literal type of byte order of multi-byte numeric data.""" + +ENDIANNESS: Final = ("little", "big") +"""Tuple of permitted values for the `endian` field of the `bytes` codec.""" + + +class BytesCodecConfiguration(TypedDict): + """ + Configuration for the Zarr v3 `bytes` codec. + + The `endian` field is required for multi-byte data types. + """ + + endian: NotRequired[Endianness] + + +class BytesCodecObject(TypedDict): + """`bytes` codec metadata in object form. + + `configuration` is itself optional β€” when no configuration fields are + set, the entire `configuration` key may be omitted. This matches the + bare-string short-hand form (`BytesCodecName`) at the canonical data + level; both encodings describe a `bytes` codec with default settings. + """ + + name: BytesCodecName + configuration: NotRequired[BytesCodecConfiguration] + + +BytesCodecMetadata = BytesCodecObject | BytesCodecName +"""Permitted JSON shapes for `bytes` codec metadata. + +The configuration has no required keys (`endian` is conditionally required +at runtime based on data type), so the spec's short-hand-name form is +permitted in addition to the object form, and the object form may itself +omit `configuration` entirely. +""" + +__all__ = [ + "BYTES_CODEC_NAME", + "ENDIANNESS", + "BytesCodecConfiguration", + "BytesCodecMetadata", + "BytesCodecName", + "BytesCodecObject", + "Endianness", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/cast_value.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/cast_value.py new file mode 100644 index 0000000000..96c39e5916 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/cast_value.py @@ -0,0 +1,107 @@ +""" +Cast-value codec types. + +See https://github.com/zarr-developers/zarr-extensions/tree/main/codecs/cast_value +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +from zarr_metadata._common import JSONValue +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON + +CAST_VALUE_CODEC_NAME: Final = "cast_value" +"""The `name` field value of the `cast_value` codec.""" + +CastValueCodecName = Literal["cast_value"] +"""Literal type of the `name` field of the `cast_value` codec.""" + +CastRoundingMode = Literal[ + "nearest-even", + "towards-zero", + "towards-positive", + "towards-negative", + "nearest-away", +] +"""Literal type of permitted values for the `rounding` configuration field. + +Defaults to `"nearest-even"` if absent. +""" + +CAST_ROUNDING_MODE: Final = ( + "nearest-even", + "towards-zero", + "towards-positive", + "towards-negative", + "nearest-away", +) +"""Tuple of permitted values for the `rounding` field of the `cast_value` codec.""" + +CastOutOfRangeMode = Literal["clamp", "wrap"] +"""Literal type of permitted values for the `out_of_range` configuration field. + +If absent, out-of-range values are an encoding/decoding error. +""" + +CAST_OUT_OF_RANGE_MODE: Final = ("clamp", "wrap") +"""Tuple of permitted values for the `out_of_range` field of the `cast_value` codec.""" + +ScalarMapEntry = tuple[JSONValue, JSONValue] +"""A single `[input, output]` mapping in a `scalar_map` direction. + +Each scalar is JSON-encoded per its data type's fill-value rules (so +e.g. `"NaN"` and `"+Infinity"` are permitted). +""" + + +class ScalarMap(TypedDict): + """Optional encode/decode scalar overrides for the cast_value codec.""" + + encode: NotRequired[tuple[ScalarMapEntry, ...]] + decode: NotRequired[tuple[ScalarMapEntry, ...]] + + +class CastValueCodecConfiguration(TypedDict): + """ + Configuration for the Zarr v3 `cast_value` codec. + + `data_type` is the target data type that input values are cast to. It + is the same shape as the top-level array `data_type` field: either a + bare-string primitive name or a `{name, configuration}` envelope. + """ + + data_type: ZarrV3MetadataFieldJSON + rounding: NotRequired[CastRoundingMode] + out_of_range: NotRequired[CastOutOfRangeMode] + scalar_map: NotRequired[ScalarMap] + + +class CastValueCodecObject(TypedDict): + """`cast_value` codec metadata in object form.""" + + name: CastValueCodecName + configuration: CastValueCodecConfiguration + + +CastValueCodecMetadata = CastValueCodecObject +"""Permitted JSON shape for `cast_value` codec metadata. + +`configuration.data_type` is required, so only the object form is valid; +the short-hand-name form is not permitted by the spec for this codec. +""" + + +__all__ = [ + "CAST_OUT_OF_RANGE_MODE", + "CAST_ROUNDING_MODE", + "CAST_VALUE_CODEC_NAME", + "CastOutOfRangeMode", + "CastRoundingMode", + "CastValueCodecConfiguration", + "CastValueCodecMetadata", + "CastValueCodecName", + "CastValueCodecObject", + "ScalarMap", + "ScalarMapEntry", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/crc32c.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/crc32c.py new file mode 100644 index 0000000000..6b9b46c43d --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/crc32c.py @@ -0,0 +1,50 @@ +""" +CRC32C codec types. + +See https://zarr-specs.readthedocs.io/en/latest/v3/codecs/crc32c/index.html + +The CRC32C codec has no configuration fields, so the `configuration` +key is absent from the metadata. +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +CRC32C_CODEC_NAME: Final = "crc32c" +"""The `name` field value of the `crc32c` codec.""" + +Crc32cCodecName = Literal["crc32c"] +"""Literal type of the `name` field of the `crc32c` codec.""" + + +class Empty(TypedDict, closed=True): + """An empty mapping""" + + +class Crc32cCodecObject(TypedDict): + """`crc32c` codec metadata in object form. + + Per spec the codec has no configuration fields. `configuration` is + optional and, if present, should be an empty mapping. + """ + + name: Crc32cCodecName + configuration: NotRequired[Empty] + + +Crc32cCodecMetadata = Crc32cCodecObject | Crc32cCodecName +"""Permitted JSON shapes for `crc32c` codec metadata. + +The spec's Extension definition allows extensions with no required +configuration to be encoded as a bare short-hand name. CRC32C has no +configuration, so both forms are valid. +""" + + +__all__ = [ + "CRC32C_CODEC_NAME", + "Crc32cCodecMetadata", + "Crc32cCodecName", + "Crc32cCodecObject", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/gzip.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/gzip.py new file mode 100644 index 0000000000..3b9936f8cd --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/gzip.py @@ -0,0 +1,55 @@ +""" +Gzip codec types. + +See https://zarr-specs.readthedocs.io/en/latest/v3/codecs/gzip/index.html +""" + +from typing import Final, Literal + +from typing_extensions import TypedDict + +GZIP_CODEC_NAME: Final = "gzip" +"""The `name` field value of the `gzip` codec.""" + +GzipCodecName = Literal["gzip"] +"""Literal type of the `name` field of the `gzip` codec.""" + + +class GzipCodecConfiguration(TypedDict): + """ + Configuration for the Zarr v3 `gzip` codec. + + `level` is an integer in the range 0-9; 0 disables compression and 9 + is slowest with the best compression ratio. The codec's compressed + output depends on `level`, so metadata that omits it cannot + reproducibly identify the chunk bytes produced by a writer β€” `level` + is required for the metadata to fulfill its reproducibility role, + even though the spec text does not mark it required with RFC 2119 + keywords. + """ + + level: int + + +class GzipCodecObject(TypedDict): + """`gzip` codec metadata in object form.""" + + name: GzipCodecName + configuration: GzipCodecConfiguration + + +GzipCodecMetadata = GzipCodecObject +"""Permitted JSON shape for `gzip` codec metadata. + +`configuration.level` is required (it determines the codec's output bytes +and is therefore part of the metadata's reproducibility contract), so +only the object form is valid; the short-hand-name form is not permitted. +""" + +__all__ = [ + "GZIP_CODEC_NAME", + "GzipCodecConfiguration", + "GzipCodecMetadata", + "GzipCodecName", + "GzipCodecObject", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/scale_offset.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/scale_offset.py new file mode 100644 index 0000000000..9701db8497 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/scale_offset.py @@ -0,0 +1,61 @@ +""" +Scale-offset codec types. + +See https://github.com/zarr-developers/zarr-extensions/tree/main/codecs/scale_offset +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +from zarr_metadata._common import JSONValue + +SCALE_OFFSET_CODEC_NAME: Final = "scale_offset" +"""The `name` field value of the `scale_offset` codec.""" + +ScaleOffsetCodecName = Literal["scale_offset"] +"""Literal type of the `name` field of the `scale_offset` codec.""" + + +class ScaleOffsetCodecConfiguration(TypedDict): + """ + Configuration for the Zarr v3 `scale_offset` codec. + + Both fields are optional. A missing `offset` is the additive identity + (e.g. 0 for numeric types); a missing `scale` is the multiplicative + identity (e.g. 1). Each scalar is JSON-encoded per the input array's + fill-value rules, so `"NaN"` and `"+Infinity"` style strings are + permitted in addition to numbers. + """ + + offset: NotRequired[JSONValue] + scale: NotRequired[JSONValue] + + +class ScaleOffsetCodecObject(TypedDict): + """`scale_offset` codec metadata in object form. + + `configuration` is itself optional per spec β€” when both `offset` and + `scale` are at their identity defaults, the codec is a no-op and the + entire `configuration` field may be omitted. + """ + + name: ScaleOffsetCodecName + configuration: NotRequired[ScaleOffsetCodecConfiguration] + + +ScaleOffsetCodecMetadata = ScaleOffsetCodecObject | ScaleOffsetCodecName +"""Permitted JSON shapes for `scale_offset` codec metadata. + +The configuration has no required keys (both `offset` and `scale` are +optional, and the configuration itself is optional), so the short-hand-name +form is permitted in addition to the object form. +""" + +__all__ = [ + "SCALE_OFFSET_CODEC_NAME", + "ScaleOffsetCodecConfiguration", + "ScaleOffsetCodecMetadata", + "ScaleOffsetCodecName", + "ScaleOffsetCodecObject", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/sharding_indexed.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/sharding_indexed.py new file mode 100644 index 0000000000..a8c9247ec4 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/sharding_indexed.py @@ -0,0 +1,71 @@ +""" +Sharding-indexed codec types. + +See https://zarr-specs.readthedocs.io/en/latest/v3/codecs/sharding-indexed/index.html +""" + +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON + +SHARDING_INDEXED_CODEC_NAME: Final = "sharding_indexed" +"""The `name` field value of the `sharding_indexed` codec.""" + +ShardingIndexedCodecName = Literal["sharding_indexed"] +"""Literal type of the `name` field of the `sharding_indexed` codec.""" + +ShardingIndexLocation = Literal["start", "end"] +"""Literal type of the position of the shard index within the encoded shard.""" + +SHARDING_INDEX_LOCATION: Final = ("start", "end") +"""Tuple of permitted values for the `index_location` field of the `sharding_indexed` codec.""" + + +class ShardingIndexedCodecConfiguration(TypedDict): + """ + Configuration for the Zarr v3 `sharding_indexed` codec. + + `chunk_shape` is the shape of inner chunks along each dimension; + it must evenly divide the shard shape. + + `codecs` is the codec pipeline applied to each inner chunk; exactly + one array-to-bytes codec is required. + + `index_codecs` is the codec pipeline applied to the shard index; + it must be deterministic (no variable-size compression). + + `index_location` defaults to `"end"` per the spec. + """ + + chunk_shape: tuple[int, ...] + codecs: tuple[ZarrV3MetadataFieldJSON, ...] + index_codecs: tuple[ZarrV3MetadataFieldJSON, ...] + index_location: NotRequired[ShardingIndexLocation] + + +class ShardingIndexedCodecObject(TypedDict): + """`sharding_indexed` codec metadata in object form.""" + + name: ShardingIndexedCodecName + configuration: ShardingIndexedCodecConfiguration + + +ShardingIndexedCodecMetadata = ShardingIndexedCodecObject +"""Permitted JSON shape for `sharding_indexed` codec metadata. + +The configuration has multiple required keys (`chunk_shape`, `codecs`, +`index_codecs`), so only the object form is valid; the short-hand-name +form is not permitted by the spec for this codec. +""" + +__all__ = [ + "SHARDING_INDEXED_CODEC_NAME", + "SHARDING_INDEX_LOCATION", + "ShardingIndexLocation", + "ShardingIndexedCodecConfiguration", + "ShardingIndexedCodecMetadata", + "ShardingIndexedCodecName", + "ShardingIndexedCodecObject", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/transpose.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/transpose.py new file mode 100644 index 0000000000..ac469b356a --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/transpose.py @@ -0,0 +1,49 @@ +""" +Transpose codec types. + +See https://zarr-specs.readthedocs.io/en/latest/v3/codecs/transpose/index.html +""" + +from typing import Final, Literal + +from typing_extensions import TypedDict + +TRANSPOSE_CODEC_NAME: Final = "transpose" +"""The `name` field value of the `transpose` codec.""" + +TransposeCodecName = Literal["transpose"] +"""Literal type of the `name` field of the `transpose` codec.""" + + +class TransposeCodecConfiguration(TypedDict): + """ + Configuration for the Zarr v3 `transpose` codec. + + `order` is a permutation of the dimension indices 0..n-1 that + specifies the dimension reordering applied during encoding. + """ + + order: tuple[int, ...] + + +class TransposeCodecObject(TypedDict): + """`transpose` codec metadata in object form.""" + + name: TransposeCodecName + configuration: TransposeCodecConfiguration + + +TransposeCodecMetadata = TransposeCodecObject +"""Permitted JSON shape for `transpose` codec metadata. + +`order` is required, so only the object form is valid; the short-hand-name +form is not permitted by the spec for this codec. +""" + +__all__ = [ + "TRANSPOSE_CODEC_NAME", + "TransposeCodecConfiguration", + "TransposeCodecMetadata", + "TransposeCodecName", + "TransposeCodecObject", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/zstd.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/zstd.py new file mode 100644 index 0000000000..c0faa64bed --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/zstd.py @@ -0,0 +1,51 @@ +""" +Zstandard codec types. + +See https://github.com/zarr-developers/zarr-specs/pull/256 (unmerged at +time of writing; the configuration shape below reflects the proposed +specification). +""" + +from typing import Final, Literal + +from typing_extensions import TypedDict + +ZSTD_CODEC_NAME: Final = "zstd" +"""The `name` field value of the `zstd` codec.""" + +ZstdCodecName = Literal["zstd"] +"""Literal type of the `name` field of the `zstd` codec.""" + + +class ZstdCodecConfiguration(TypedDict): + """ + Configuration for the Zarr v3 `zstd` codec. + + Both fields are required per the proposed specification. + """ + + level: int + checksum: bool + + +class ZstdCodecObject(TypedDict): + """`zstd` codec metadata in object form.""" + + name: ZstdCodecName + configuration: ZstdCodecConfiguration + + +ZstdCodecMetadata = ZstdCodecObject +"""Permitted JSON shape for `zstd` codec metadata. + +Both `level` and `checksum` are required, so only the object form is +valid; the short-hand-name form is not permitted by the spec for this codec. +""" + +__all__ = [ + "ZSTD_CODEC_NAME", + "ZstdCodecConfiguration", + "ZstdCodecMetadata", + "ZstdCodecName", + "ZstdCodecObject", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/consolidated.py b/packages/zarr-metadata/src/zarr_metadata/v3/consolidated.py new file mode 100644 index 0000000000..a9fe0c1f8f --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/consolidated.py @@ -0,0 +1,49 @@ +"""Zarr v3 consolidated metadata types. + +There is no Zarr v3 specification for consolidated metadata. This module +models the inline-on-group convention used by the reference Python +implementation (and zarrs), where consolidated metadata is embedded as +an extension field on a group's `zarr.json`. + +This is a known non-core interoperability extension. Its +`{kind, must_understand, metadata}` payload is an unknown top-level JSON value +to the core document model; implementations that recognize the convention may +interpret it through this dedicated type. +""" + +from collections.abc import Mapping +from typing import Final, Literal + +from typing_extensions import TypedDict + +from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON +from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON + + +class ZarrV3ConsolidatedMetadataJSON(TypedDict): + """ + Inline consolidated metadata embedded in a v3 group. + + The `metadata` map contains only v3 array and group entries. V2 entries + are excluded from this interoperability convention by design; the v3 core + specification does not define consolidated metadata. + """ + + kind: Literal["inline"] + must_understand: Literal[False] + metadata: Mapping[str, ZarrV3ArrayMetadataJSON | ZarrV3GroupMetadataJSON] + + +ZARR_V3_CONSOLIDATED_METADATA_KEY: Final = "consolidated_metadata" +"""The key under which consolidated metadata is embedded in a v3 group document. + +Unlike the v2 `.zmetadata` file, this is not a store key: consolidated metadata +is carried as an extension field inside the group's own `zarr.json`. Like its v2 +counterpart it is a reference-implementation convention, not a spec artifact. +""" + + +__all__ = [ + "ZARR_V3_CONSOLIDATED_METADATA_KEY", + "ZarrV3ConsolidatedMetadataJSON", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/__init__.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/__init__.py new file mode 100644 index 0000000000..180f9c500d --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/__init__.py @@ -0,0 +1,105 @@ +""" +Zarr v3 data type spec types. + +Each v3 data type has its own submodule: + +- Core primitives: `bool`, `int8`/`16`/`32`/`64`, `uint8`/`16`/`32`/`64`, + `float16`/`32`/`64`, `complex64`/`128`, `raw` (for `r`) +- zarr-extensions: `bytes`, `string`, `numpy_datetime64`, `numpy_timedelta64`, + `struct` + +The two canonical types per dtype are re-exported here: + +- `DataTypeName` -- the literal type of the dtype's `data_type` string + (or, for named-config dtypes, the literal value of their `name` field) +- `FillValue` -- the permitted JSON shape of the `fill_value` field + +Named-config dtypes (`numpy_datetime64`, `numpy_timedelta64`, `struct`) also +expose their envelope TypedDict here. For configuration TypedDicts, branded +`HexFloat` / `Base64Bytes` types, and the corresponding validator +functions, import directly from the leaf submodule. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from zarr_metadata.v3.data_type.bool import BoolDataTypeName, BoolFillValue +from zarr_metadata.v3.data_type.bytes import BytesDataTypeName, BytesFillValue +from zarr_metadata.v3.data_type.complex64 import Complex64DataTypeName, Complex64FillValue +from zarr_metadata.v3.data_type.complex128 import ( + Complex128DataTypeName, + Complex128FillValue, +) +from zarr_metadata.v3.data_type.float16 import Float16DataTypeName, Float16FillValue +from zarr_metadata.v3.data_type.float32 import Float32DataTypeName, Float32FillValue +from zarr_metadata.v3.data_type.float64 import Float64DataTypeName, Float64FillValue +from zarr_metadata.v3.data_type.int8 import Int8DataTypeName, Int8FillValue +from zarr_metadata.v3.data_type.int16 import Int16DataTypeName, Int16FillValue +from zarr_metadata.v3.data_type.int32 import Int32DataTypeName, Int32FillValue +from zarr_metadata.v3.data_type.int64 import Int64DataTypeName, Int64FillValue +from zarr_metadata.v3.data_type.numpy_datetime64 import ( + NumpyDatetime64, + NumpyDatetime64DataTypeName, + NumpyDatetime64FillValue, +) +from zarr_metadata.v3.data_type.numpy_timedelta64 import ( + NumpyTimedelta64, + NumpyTimedelta64DataTypeName, + NumpyTimedelta64FillValue, +) +from zarr_metadata.v3.data_type.raw import RawBytesDataTypeName, RawBytesFillValue +from zarr_metadata.v3.data_type.string import StringDataTypeName, StringFillValue +from zarr_metadata.v3.data_type.struct import ( + Struct, + StructDataTypeName, + StructFillValue, +) +from zarr_metadata.v3.data_type.uint8 import Uint8DataTypeName, Uint8FillValue +from zarr_metadata.v3.data_type.uint16 import Uint16DataTypeName, Uint16FillValue +from zarr_metadata.v3.data_type.uint32 import Uint32DataTypeName, Uint32FillValue +from zarr_metadata.v3.data_type.uint64 import Uint64DataTypeName, Uint64FillValue + +__all__ = [ + "BoolDataTypeName", + "BoolFillValue", + "BytesDataTypeName", + "BytesFillValue", + "Complex64DataTypeName", + "Complex64FillValue", + "Complex128DataTypeName", + "Complex128FillValue", + "Float16DataTypeName", + "Float16FillValue", + "Float32DataTypeName", + "Float32FillValue", + "Float64DataTypeName", + "Float64FillValue", + "Int8DataTypeName", + "Int8FillValue", + "Int16DataTypeName", + "Int16FillValue", + "Int32DataTypeName", + "Int32FillValue", + "Int64DataTypeName", + "Int64FillValue", + "NumpyDatetime64", + "NumpyDatetime64DataTypeName", + "NumpyDatetime64FillValue", + "NumpyTimedelta64", + "NumpyTimedelta64DataTypeName", + "NumpyTimedelta64FillValue", + "RawBytesDataTypeName", + "RawBytesFillValue", + "StringDataTypeName", + "StringFillValue", + "Struct", + "StructDataTypeName", + "StructFillValue", + "Uint8DataTypeName", + "Uint8FillValue", + "Uint16DataTypeName", + "Uint16FillValue", + "Uint32DataTypeName", + "Uint32FillValue", + "Uint64DataTypeName", + "Uint64FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bool.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bool.py new file mode 100644 index 0000000000..e36613a154 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bool.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `bool` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +BOOL_DATA_TYPE_NAME: Final = "bool" +"""The `data_type` value for the `bool` type.""" + +BoolDataTypeName = Literal["bool"] +"""Literal type of the `data_type` field for `bool`.""" + +BoolFillValue = bool +"""Permitted JSON shape of the `fill_value` field for `bool`: a JSON boolean.""" + + +__all__ = [ + "BOOL_DATA_TYPE_NAME", + "BoolDataTypeName", + "BoolFillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bytes.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bytes.py new file mode 100644 index 0000000000..c7eed64f0f --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bytes.py @@ -0,0 +1,48 @@ +""" +Zarr `bytes` data type (variable-length raw bytes, zarr-extensions). + +See https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/bytes +""" + +import re +from typing import Final, Literal, NewType + +BYTES_DATA_TYPE_NAME: Final = "bytes" +"""The `data_type` value for the variable-length `bytes` type.""" + +BytesDataTypeName = Literal["bytes"] +"""Literal type of the `data_type` field for `bytes`.""" + +Base64Bytes = NewType("Base64Bytes", str) +"""A standard-alphabet base64-encoded byte sequence.""" + +_BASE64_RE: Final = re.compile(r"^[A-Za-z0-9+/]*={0,2}$") + + +def base64_bytes(value: str) -> Base64Bytes: + """Validate `value` as a Base64Bytes and brand it. + + Raises ValueError if `value` is not standard-alphabet base64 + (length must be a multiple of 4 once padded; only `A-Z`, `a-z`, + `0-9`, `+`, `/`, and trailing `=` padding are permitted). + """ + if len(value) % 4 != 0 or not _BASE64_RE.fullmatch(value): + raise ValueError(f"Expected standard-alphabet base64, got {value!r}") + return Base64Bytes(value) + + +BytesFillValue = tuple[int, ...] | Base64Bytes +"""Permitted JSON shape of the `fill_value` field for `bytes`. + +Either a JSON array of integers in `[0, 255]` (one per byte), or a +`Base64Bytes` string encoding the byte sequence. +""" + + +__all__ = [ + "BYTES_DATA_TYPE_NAME", + "Base64Bytes", + "BytesDataTypeName", + "BytesFillValue", + "base64_bytes", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex128.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex128.py new file mode 100644 index 0000000000..780bbbb02f --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex128.py @@ -0,0 +1,37 @@ +""" +Zarr v3 `complex128` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +from zarr_metadata.v3.data_type.float64 import Float64FillValue + +COMPLEX128_DATA_TYPE_NAME: Final = "complex128" +"""The `data_type` value for the `complex128` type.""" + +Complex128DataTypeName = Literal["complex128"] +"""Literal type of the `data_type` field for `complex128`.""" + +Complex128Component = Float64FillValue +"""One real or imaginary component of a `complex128` fill value. + +Same shape as a `float64` fill value: a JSON number, a named sentinel, +or a `HexFloat64` string. +""" + +Complex128FillValue = tuple[Complex128Component, Complex128Component] +"""Permitted JSON shape of the `fill_value` field for `complex128`. + +A two-element JSON array `[real, imag]` where each component is a +`Complex128Component`. +""" + + +__all__ = [ + "COMPLEX128_DATA_TYPE_NAME", + "Complex128Component", + "Complex128DataTypeName", + "Complex128FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex64.py new file mode 100644 index 0000000000..4aca608899 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex64.py @@ -0,0 +1,37 @@ +""" +Zarr v3 `complex64` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +from zarr_metadata.v3.data_type.float32 import Float32FillValue + +COMPLEX64_DATA_TYPE_NAME: Final = "complex64" +"""The `data_type` value for the `complex64` type.""" + +Complex64DataTypeName = Literal["complex64"] +"""Literal type of the `data_type` field for `complex64`.""" + +Complex64Component = Float32FillValue +"""One real or imaginary component of a `complex64` fill value. + +Same shape as a `float32` fill value: a JSON number, a named sentinel, +or a `HexFloat32` string. +""" + +Complex64FillValue = tuple[Complex64Component, Complex64Component] +"""Permitted JSON shape of the `fill_value` field for `complex64`. + +A two-element JSON array `[real, imag]` where each component is a +`Complex64Component`. +""" + + +__all__ = [ + "COMPLEX64_DATA_TYPE_NAME", + "Complex64Component", + "Complex64DataTypeName", + "Complex64FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float16.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float16.py new file mode 100644 index 0000000000..41eec441df --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float16.py @@ -0,0 +1,71 @@ +""" +Zarr v3 `float16` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +import re +from typing import Final, Literal, NewType + +FLOAT16_DATA_TYPE_NAME: Final = "float16" +"""The `data_type` value for the `float16` type.""" + +Float16DataTypeName = Literal["float16"] +"""Literal type of the `data_type` field for `float16`.""" + +Float16SpecialFillValue = Literal["NaN", "Infinity", "-Infinity"] +"""Named non-finite fill values permitted by the spec for IEEE 754 floats.""" + +HexFloat16 = NewType("HexFloat16", str) +"""A 6-character hex string (`0x` + 4 hex digits) encoding the +unsigned-integer representation of a float16.""" + +_HEX_FLOAT16_RE: Final = re.compile(r"^0x[0-9a-fA-F]{4}$") + + +def hex_float16(value: str) -> HexFloat16: + """Validate `value` as a HexFloat16 and brand it. + + Raises ValueError if `value` is not exactly `0x` followed by 4 hex + digits. + """ + if not _HEX_FLOAT16_RE.fullmatch(value): + raise ValueError(f"Expected '0x' followed by 4 hex digits, got {value!r}") + return HexFloat16(value) + + +Float16FillValue = float | int | Float16SpecialFillValue | HexFloat16 +"""Permitted JSON shape of the `fill_value` field for `float16`. + +Either a JSON number, one of the named non-finite sentinels (`"NaN"`, +`"Infinity"`, `"-Infinity"`), or a `HexFloat16` (`0xYYYY` string encoding +the unsigned-integer representation of the IEEE 754 value). +""" + +CANONICAL_NAN_HEX_FLOAT16: Final = "0x7e00" +"""Canonical hex form of the float16 NaN sentinel `"NaN"`. + +Per spec the named `"NaN"` sentinel denotes the float with sign=0, the +most significant mantissa bit set, and all other mantissa bits zero +(the IEEE 754 default quiet NaN). Other NaN bit patterns must be +encoded with the explicit hex-string form. +""" + +CANONICAL_POSITIVE_INFINITY_HEX_FLOAT16: Final = "0x7c00" +"""Canonical hex form of the float16 `"Infinity"` sentinel.""" + +CANONICAL_NEGATIVE_INFINITY_HEX_FLOAT16: Final = "0xfc00" +"""Canonical hex form of the float16 `"-Infinity"` sentinel.""" + + +__all__ = [ + "CANONICAL_NAN_HEX_FLOAT16", + "CANONICAL_NEGATIVE_INFINITY_HEX_FLOAT16", + "CANONICAL_POSITIVE_INFINITY_HEX_FLOAT16", + "FLOAT16_DATA_TYPE_NAME", + "Float16DataTypeName", + "Float16FillValue", + "Float16SpecialFillValue", + "HexFloat16", + "hex_float16", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float32.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float32.py new file mode 100644 index 0000000000..37b7d4f6e8 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float32.py @@ -0,0 +1,71 @@ +""" +Zarr v3 `float32` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +import re +from typing import Final, Literal, NewType + +FLOAT32_DATA_TYPE_NAME: Final = "float32" +"""The `data_type` value for the `float32` type.""" + +Float32DataTypeName = Literal["float32"] +"""Literal type of the `data_type` field for `float32`.""" + +Float32SpecialFillValue = Literal["NaN", "Infinity", "-Infinity"] +"""Named non-finite fill values permitted by the spec for IEEE 754 floats.""" + +HexFloat32 = NewType("HexFloat32", str) +"""A 10-character hex string (`0x` + 8 hex digits) encoding the +unsigned-integer representation of a float32.""" + +_HEX_FLOAT32_RE: Final = re.compile(r"^0x[0-9a-fA-F]{8}$") + + +def hex_float32(value: str) -> HexFloat32: + """Validate `value` as a HexFloat32 and brand it. + + Raises ValueError if `value` is not exactly `0x` followed by 8 hex + digits. + """ + if not _HEX_FLOAT32_RE.fullmatch(value): + raise ValueError(f"Expected '0x' followed by 8 hex digits, got {value!r}") + return HexFloat32(value) + + +Float32FillValue = float | int | Float32SpecialFillValue | HexFloat32 +"""Permitted JSON shape of the `fill_value` field for `float32`. + +Either a JSON number, one of the named non-finite sentinels (`"NaN"`, +`"Infinity"`, `"-Infinity"`), or a `HexFloat32` (`0xYYYYYYYY` string +encoding the unsigned-integer representation of the IEEE 754 value). +""" + +CANONICAL_NAN_HEX_FLOAT32: Final = "0x7fc00000" +"""Canonical hex form of the float32 NaN sentinel `"NaN"`. + +Per spec the named `"NaN"` sentinel denotes the float with sign=0, the +most significant mantissa bit set, and all other mantissa bits zero +(the IEEE 754 default quiet NaN). Other NaN bit patterns must be +encoded with the explicit hex-string form. +""" + +CANONICAL_POSITIVE_INFINITY_HEX_FLOAT32: Final = "0x7f800000" +"""Canonical hex form of the float32 `"Infinity"` sentinel.""" + +CANONICAL_NEGATIVE_INFINITY_HEX_FLOAT32: Final = "0xff800000" +"""Canonical hex form of the float32 `"-Infinity"` sentinel.""" + + +__all__ = [ + "CANONICAL_NAN_HEX_FLOAT32", + "CANONICAL_NEGATIVE_INFINITY_HEX_FLOAT32", + "CANONICAL_POSITIVE_INFINITY_HEX_FLOAT32", + "FLOAT32_DATA_TYPE_NAME", + "Float32DataTypeName", + "Float32FillValue", + "Float32SpecialFillValue", + "HexFloat32", + "hex_float32", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float64.py new file mode 100644 index 0000000000..9a5cf98288 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float64.py @@ -0,0 +1,72 @@ +""" +Zarr v3 `float64` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +import re +from typing import Final, Literal, NewType + +FLOAT64_DATA_TYPE_NAME: Final = "float64" +"""The `data_type` value for the `float64` type.""" + +Float64DataTypeName = Literal["float64"] +"""Literal type of the `data_type` field for `float64`.""" + +Float64SpecialFillValue = Literal["NaN", "Infinity", "-Infinity"] +"""Named non-finite fill values permitted by the spec for IEEE 754 floats.""" + +HexFloat64 = NewType("HexFloat64", str) +"""An 18-character hex string (`0x` + 16 hex digits) encoding the +unsigned-integer representation of a float64.""" + +_HEX_FLOAT64_RE: Final = re.compile(r"^0x[0-9a-fA-F]{16}$") + + +def hex_float64(value: str) -> HexFloat64: + """Validate `value` as a HexFloat64 and brand it. + + Raises ValueError if `value` is not exactly `0x` followed by 16 hex + digits. + """ + if not _HEX_FLOAT64_RE.fullmatch(value): + raise ValueError(f"Expected '0x' followed by 16 hex digits, got {value!r}") + return HexFloat64(value) + + +Float64FillValue = float | int | Float64SpecialFillValue | HexFloat64 +"""Permitted JSON shape of the `fill_value` field for `float64`. + +Either a JSON number, one of the named non-finite sentinels (`"NaN"`, +`"Infinity"`, `"-Infinity"`), or a `HexFloat64` (`0xYYYYYYYYYYYYYYYY` +string encoding the unsigned-integer representation of the IEEE 754 +value). +""" + +CANONICAL_NAN_HEX_FLOAT64: Final = "0x7ff8000000000000" +"""Canonical hex form of the float64 NaN sentinel `"NaN"`. + +Per spec the named `"NaN"` sentinel denotes the float with sign=0, the +most significant mantissa bit set, and all other mantissa bits zero +(the IEEE 754 default quiet NaN). Other NaN bit patterns must be +encoded with the explicit hex-string form. +""" + +CANONICAL_POSITIVE_INFINITY_HEX_FLOAT64: Final = "0x7ff0000000000000" +"""Canonical hex form of the float64 `"Infinity"` sentinel.""" + +CANONICAL_NEGATIVE_INFINITY_HEX_FLOAT64: Final = "0xfff0000000000000" +"""Canonical hex form of the float64 `"-Infinity"` sentinel.""" + + +__all__ = [ + "CANONICAL_NAN_HEX_FLOAT64", + "CANONICAL_NEGATIVE_INFINITY_HEX_FLOAT64", + "CANONICAL_POSITIVE_INFINITY_HEX_FLOAT64", + "FLOAT64_DATA_TYPE_NAME", + "Float64DataTypeName", + "Float64FillValue", + "Float64SpecialFillValue", + "HexFloat64", + "hex_float64", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int16.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int16.py new file mode 100644 index 0000000000..b76f06761a --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int16.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `int16` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +INT16_DATA_TYPE_NAME: Final = "int16" +"""The `data_type` value for the `int16` type.""" + +Int16DataTypeName = Literal["int16"] +"""Literal type of the `data_type` field for `int16`.""" + +Int16FillValue = int +"""Permitted JSON shape of the `fill_value` field for `int16`: a JSON integer in [-32768, 32767].""" + + +__all__ = [ + "INT16_DATA_TYPE_NAME", + "Int16DataTypeName", + "Int16FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int32.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int32.py new file mode 100644 index 0000000000..7b41ec6c54 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int32.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `int32` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +INT32_DATA_TYPE_NAME: Final = "int32" +"""The `data_type` value for the `int32` type.""" + +Int32DataTypeName = Literal["int32"] +"""Literal type of the `data_type` field for `int32`.""" + +Int32FillValue = int +"""Permitted JSON shape of the `fill_value` field for `int32`: a JSON integer in [-2**31, 2**31 - 1].""" + + +__all__ = [ + "INT32_DATA_TYPE_NAME", + "Int32DataTypeName", + "Int32FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int64.py new file mode 100644 index 0000000000..0005675c66 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int64.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `int64` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +INT64_DATA_TYPE_NAME: Final = "int64" +"""The `data_type` value for the `int64` type.""" + +Int64DataTypeName = Literal["int64"] +"""Literal type of the `data_type` field for `int64`.""" + +Int64FillValue = int +"""Permitted JSON shape of the `fill_value` field for `int64`: a JSON integer in [-2**63, 2**63 - 1].""" + + +__all__ = [ + "INT64_DATA_TYPE_NAME", + "Int64DataTypeName", + "Int64FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int8.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int8.py new file mode 100644 index 0000000000..a5a16de761 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/int8.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `int8` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +INT8_DATA_TYPE_NAME: Final = "int8" +"""The `data_type` value for the `int8` type.""" + +Int8DataTypeName = Literal["int8"] +"""Literal type of the `data_type` field for `int8`.""" + +Int8FillValue = int +"""Permitted JSON shape of the `fill_value` field for `int8`: a JSON integer in [-128, 127].""" + + +__all__ = [ + "INT8_DATA_TYPE_NAME", + "Int8DataTypeName", + "Int8FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_datetime64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_datetime64.py new file mode 100644 index 0000000000..8784160f71 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_datetime64.py @@ -0,0 +1,60 @@ +""" +Zarr `numpy.datetime64` data type (zarr-extensions). + +See https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/numpy.datetime64 +""" + +from typing import Final, Literal + +from typing_extensions import ReadOnly, TypedDict + +NUMPY_DATETIME64_DATA_TYPE_NAME: Final = "numpy.datetime64" +"""The `name` field value of the `numpy.datetime64` data type.""" + +NumpyDatetime64DataTypeName = Literal["numpy.datetime64"] +"""Literal type of the `name` field of the `numpy.datetime64` data type.""" + +NumpyTimeUnit = Literal[ + "Y", "M", "W", "D", "h", "m", "s", "ms", "us", "ΞΌs", "ns", "ps", "fs", "as", "generic" +] +"""Time unit codes used by numpy.datetime64.""" + + +class NumpyDatetime64Configuration(TypedDict): + """ + Configuration for the `numpy.datetime64` data type. + + Attributes + ---------- + unit + A string encoding a unit of time. + scale_factor + The multiplier relative to the unit. + """ + + unit: ReadOnly[NumpyTimeUnit] + scale_factor: ReadOnly[int] + + +class NumpyDatetime64(TypedDict): + """`numpy.datetime64` data type metadata.""" + + name: NumpyDatetime64DataTypeName + configuration: NumpyDatetime64Configuration + + +NumpyDatetime64FillValue = int | Literal["NaT"] +"""Permitted JSON shape of the `fill_value` field for `numpy.datetime64`. + +Either a JSON integer (count of `unit * scale_factor` since the epoch), +or the string `"NaT"` (equivalent to the integer `-2**63`). +""" + +__all__ = [ + "NUMPY_DATETIME64_DATA_TYPE_NAME", + "NumpyDatetime64", + "NumpyDatetime64Configuration", + "NumpyDatetime64DataTypeName", + "NumpyDatetime64FillValue", + "NumpyTimeUnit", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_timedelta64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_timedelta64.py new file mode 100644 index 0000000000..f5c8c77bf8 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_timedelta64.py @@ -0,0 +1,80 @@ +""" +Zarr `numpy.timedelta64` data type (zarr-extensions). + +See https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/numpy.timedelta64 +""" + +from typing import Final, Literal + +from typing_extensions import ReadOnly, TypedDict + +NUMPY_TIMEDELTA64_DATA_TYPE_NAME: Final = "numpy.timedelta64" +"""The `name` field value of the `numpy.timedelta64` data type.""" + +NumpyTimedelta64DataTypeName = Literal["numpy.timedelta64"] +"""Literal type of the `name` field of the `numpy.timedelta64` data type.""" + +NumpyTimeUnit = Literal[ + "Y", "M", "W", "D", "h", "m", "s", "ms", "us", "ΞΌs", "ns", "ps", "fs", "as", "generic" +] +"""Time unit codes used by numpy.timedelta64.""" + +NUMPY_TIME_UNIT: Final = ( + "Y", + "M", + "W", + "D", + "h", + "m", + "s", + "ms", + "us", + "ΞΌs", + "ns", + "ps", + "fs", + "as", + "generic", +) +"""Runtime tuple of the permitted `numpy.timedelta64`/`numpy.datetime64` unit strings.""" + + +class NumpyTimedelta64Configuration(TypedDict): + """ + Configuration for the `numpy.timedelta64` data type. + + Attributes + ---------- + unit + A string encoding a unit of time. + scale_factor + The multiplier relative to the unit. + """ + + unit: ReadOnly[NumpyTimeUnit] + scale_factor: ReadOnly[int] + + +class NumpyTimedelta64(TypedDict): + """`numpy.timedelta64` data type metadata.""" + + name: NumpyTimedelta64DataTypeName + configuration: NumpyTimedelta64Configuration + + +NumpyTimedelta64FillValue = int | Literal["NaT"] +"""Permitted JSON shape of the `fill_value` field for `numpy.timedelta64`. + +Either a JSON integer (a count of `unit * scale_factor`), or the string +`"NaT"` (equivalent to the integer `-2**63`). +""" + +__all__ = [ + "NUMPY_TIMEDELTA64_DATA_TYPE_NAME", + "NUMPY_TIME_UNIT", + "NumpyTimeUnit", + "NumpyTimedelta64", + "NumpyTimedelta64Configuration", + "NumpyTimedelta64DataTypeName", + "NumpyTimedelta64FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/raw.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/raw.py new file mode 100644 index 0000000000..c9c688c9fa --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/raw.py @@ -0,0 +1,45 @@ +""" +Zarr v3 `r` raw-bytes data type (parameterised by bit count). + +The `data_type` value is a string of the form `r` where `N` is a +positive multiple of 8 (e.g. `r8`, `r16`, `r24`). + +See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html +""" + +import re +from typing import Final, NewType + +RawBytesDataTypeName = NewType("RawBytesDataTypeName", str) +"""A spec-conformant `r` raw-bytes name (e.g. `"r8"`, `"r16"`).""" + +_RAW_BYTES_RE: Final = re.compile(r"^r(\d+)$") + + +def raw_bytes_dtype_name(value: str) -> RawBytesDataTypeName: + """Validate `value` as a `r` raw-bytes name and brand it. + + Raises ValueError if `value` is not `r` followed by a positive + multiple of 8. + """ + match = _RAW_BYTES_RE.fullmatch(value) + if match is None: + raise ValueError(f"Expected 'r' followed by a positive integer, got {value!r}") + bits = int(match.group(1)) + if bits == 0 or bits % 8 != 0: + raise ValueError(f"Expected 'r' where N is a positive multiple of 8, got {value!r}") + return RawBytesDataTypeName(value) + + +RawBytesFillValue = tuple[int, ...] +"""Permitted JSON shape of the `fill_value` field for `r`. + +A JSON array of N/8 integers in `[0, 255]` (one per byte). +""" + + +__all__ = [ + "RawBytesDataTypeName", + "RawBytesFillValue", + "raw_bytes_dtype_name", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/string.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/string.py new file mode 100644 index 0000000000..0a778ccecc --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/string.py @@ -0,0 +1,23 @@ +""" +Zarr `string` data type (variable-length utf-8, zarr-extensions). + +See https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/string +""" + +from typing import Final, Literal + +STRING_DATA_TYPE_NAME: Final = "string" +"""The `data_type` value for the `string` type.""" + +StringDataTypeName = Literal["string"] +"""Literal type of the `data_type` field for `string`.""" + +StringFillValue = str +"""Permitted JSON shape of the `fill_value` field for `string`: a JSON unicode string.""" + + +__all__ = [ + "STRING_DATA_TYPE_NAME", + "StringDataTypeName", + "StringFillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/struct.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/struct.py new file mode 100644 index 0000000000..b1b6b50308 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/struct.py @@ -0,0 +1,66 @@ +""" +Zarr `struct` data type (heterogeneous record, zarr-extensions). + +See https://github.com/zarr-developers/zarr-extensions/blob/main/data-types/struct/README.md +""" + +from collections.abc import Mapping +from typing import Final, Literal + +from typing_extensions import ReadOnly, TypedDict + +from zarr_metadata._common import JSONValue +from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON + +STRUCT_DATA_TYPE_NAME: Final = "struct" +"""The `name` field value of the `struct` data type.""" + +StructDataTypeName = Literal["struct"] +"""Literal type of the `name` field of the `struct` data type.""" + + +class StructField(TypedDict): + """ + A single field entry inside a structured dtype. + + Attributes + ---------- + name + The field name (must be unique within a struct and non-empty). + data_type + The field's data type. Recursive: may be a bare-string primitive + or a named-config envelope including another `struct`. + """ + + name: ReadOnly[str] + data_type: ReadOnly[ZarrV3MetadataFieldJSON] + + +class StructConfiguration(TypedDict): + """Configuration for the `struct` data type.""" + + fields: ReadOnly[tuple[StructField, ...]] + + +class Struct(TypedDict): + """`struct` data type metadata.""" + + name: StructDataTypeName + configuration: StructConfiguration + + +StructFillValue = Mapping[str, JSONValue] +"""Permitted JSON shape of the `fill_value` field for `struct`. + +A JSON object mapping each field name to that field's fill value. Field +fill values are themselves shaped per the field's `data_type`, recursively. +""" + +__all__ = [ + "STRUCT_DATA_TYPE_NAME", + "Struct", + "StructConfiguration", + "StructDataTypeName", + "StructField", + "StructFillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint16.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint16.py new file mode 100644 index 0000000000..37e35ec436 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint16.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `uint16` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +UINT16_DATA_TYPE_NAME: Final = "uint16" +"""The `data_type` value for the `uint16` type.""" + +Uint16DataTypeName = Literal["uint16"] +"""Literal type of the `data_type` field for `uint16`.""" + +Uint16FillValue = int +"""Permitted JSON shape of the `fill_value` field for `uint16`: a JSON integer in [0, 65535].""" + + +__all__ = [ + "UINT16_DATA_TYPE_NAME", + "Uint16DataTypeName", + "Uint16FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint32.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint32.py new file mode 100644 index 0000000000..f6cd4d447e --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint32.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `uint32` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +UINT32_DATA_TYPE_NAME: Final = "uint32" +"""The `data_type` value for the `uint32` type.""" + +Uint32DataTypeName = Literal["uint32"] +"""Literal type of the `data_type` field for `uint32`.""" + +Uint32FillValue = int +"""Permitted JSON shape of the `fill_value` field for `uint32`: a JSON integer in [0, 2**32 - 1].""" + + +__all__ = [ + "UINT32_DATA_TYPE_NAME", + "Uint32DataTypeName", + "Uint32FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint64.py new file mode 100644 index 0000000000..7151d2395a --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint64.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `uint64` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +UINT64_DATA_TYPE_NAME: Final = "uint64" +"""The `data_type` value for the `uint64` type.""" + +Uint64DataTypeName = Literal["uint64"] +"""Literal type of the `data_type` field for `uint64`.""" + +Uint64FillValue = int +"""Permitted JSON shape of the `fill_value` field for `uint64`: a JSON integer in [0, 2**64 - 1].""" + + +__all__ = [ + "UINT64_DATA_TYPE_NAME", + "Uint64DataTypeName", + "Uint64FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint8.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint8.py new file mode 100644 index 0000000000..787f1b7866 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/uint8.py @@ -0,0 +1,23 @@ +""" +Zarr v3 `uint8` data type. + +See https://zarr-specs.readthedocs.io/en/latest/v3/data-types/index.html +""" + +from typing import Final, Literal + +UINT8_DATA_TYPE_NAME: Final = "uint8" +"""The `data_type` value for the `uint8` type.""" + +Uint8DataTypeName = Literal["uint8"] +"""Literal type of the `data_type` field for `uint8`.""" + +Uint8FillValue = int +"""Permitted JSON shape of the `fill_value` field for `uint8`: a JSON integer in [0, 255].""" + + +__all__ = [ + "UINT8_DATA_TYPE_NAME", + "Uint8DataTypeName", + "Uint8FillValue", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/group.py b/packages/zarr-metadata/src/zarr_metadata/v3/group.py new file mode 100644 index 0000000000..37bfdd6934 --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/group.py @@ -0,0 +1,73 @@ +"""Zarr v3 group metadata types. + +See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#group-metadata +""" + +from collections.abc import Mapping +from typing import Final, Literal, NotRequired + +from typing_extensions import TypedDict + +from zarr_metadata._common import JSONValue +from zarr_metadata.v3.array import ZarrV3ExtensionField + + +class ZarrV3GroupMetadataJSON(TypedDict, extra_items=ZarrV3ExtensionField): + """ + Zarr v3 group metadata document (the `zarr.json` content for a group). + + Extra keys may contain arbitrary JSON values. + + See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#group-metadata + """ + + zarr_format: Literal[3] + node_type: Literal["group"] + attributes: NotRequired[Mapping[str, JSONValue]] + + +class ZarrV3GroupMetadataJSONPartial(TypedDict, total=False, extra_items=ZarrV3ExtensionField): + """ + Partial form of `ZarrV3GroupMetadataJSON`: every field is `NotRequired`. + + Field annotations and `extra_items=` mirror `ZarrV3GroupMetadataJSON` exactly. + The only difference is `total=False`, which makes every key optional + at the type level. + + Use this when typing dicts that intentionally hold a subset of a complete + v3 group metadata document β€” e.g. test fixtures that override only a few + fields of a base template, or callers that build a fragment to be merged + into a complete document elsewhere. + + The `NotRequired[...]` wrapper on `attributes` is intentional: keeping it + preserves byte-identical `__annotations__` with `ZarrV3GroupMetadataJSON` so the + `==` check in `tests/test_partial_equivalence.py` passes without + special-casing that field (PEP 655 explicitly permits `NotRequired` inside + `total=False`). + + Drift between this type and `ZarrV3GroupMetadataJSON` is prevented by + `tests/test_partial_equivalence.py`. + """ + + zarr_format: Literal[3] + node_type: Literal["group"] + attributes: NotRequired[Mapping[str, JSONValue]] + + +ZarrV3GroupMetadataStoreKey = Literal["zarr.json"] +"""Literal type of the store key holding a v3 group's metadata document.""" + +ZARR_V3_GROUP_METADATA_STORE_KEY: Final[ZarrV3GroupMetadataStoreKey] = "zarr.json" +"""The store key a v3 group's metadata document is persisted under. + +v3 uses one key for both node types; the document's `node_type` field +distinguishes a group from an array. +""" + + +__all__ = [ + "ZARR_V3_GROUP_METADATA_STORE_KEY", + "ZarrV3GroupMetadataJSON", + "ZarrV3GroupMetadataJSONPartial", + "ZarrV3GroupMetadataStoreKey", +] diff --git a/packages/zarr-metadata/tests/__init__.py b/packages/zarr-metadata/tests/__init__.py new file mode 100644 index 0000000000..d886440736 --- /dev/null +++ b/packages/zarr-metadata/tests/__init__.py @@ -0,0 +1 @@ +"""Tests for zarr-metadata.""" diff --git a/tests/v3/__init__.py b/packages/zarr-metadata/tests/model/__init__.py similarity index 100% rename from tests/v3/__init__.py rename to packages/zarr-metadata/tests/model/__init__.py diff --git a/packages/zarr-metadata/tests/model/_cases.py b/packages/zarr-metadata/tests/model/_cases.py new file mode 100644 index 0000000000..15faa65539 --- /dev/null +++ b/packages/zarr-metadata/tests/model/_cases.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import TYPE_CHECKING, Generic, TypeVar + +import pytest + +if TYPE_CHECKING: + from contextlib import AbstractContextManager + +TIn = TypeVar("TIn") +TOut = TypeVar("TOut") + + +@dataclass(frozen=True) +class Expect(Generic[TIn, TOut]): + """A test case with explicit input, expected output, and a human-readable id.""" + + input: TIn + output: TOut + id: str + + +@dataclass(frozen=True) +class ExpectFail(Generic[TIn]): + """A test case that should raise an exception. + + `msg` is a regex matched against the exception text (pytest's native + `match=` semantics). Leave it `None` to assert only the exception type. Set + `escape=True` when `msg` is a literal that contains regex metacharacters + such as `(`, `[`, or `.`; `escape` has no effect when `msg` is `None`. + """ + + input: TIn + exception: type[Exception] + id: str + msg: str | None = None + escape: bool = False + + def raises(self) -> AbstractContextManager[pytest.ExceptionInfo[Exception]]: + if self.msg is None: + return pytest.raises(self.exception) + pattern = re.escape(self.msg) if self.escape else self.msg + return pytest.raises(self.exception, match=pattern) + + +def mutate_nested_containers(value: object) -> None: + """Recursively mutate every mutable container reachable inside `value`. + + Adds a marker key to every dict and appends a marker to every list, + descending through tuples. Used to prove a `to_json` document shares no + mutable state with the model that produced it. + """ + if isinstance(value, dict): + for item in value.values(): + mutate_nested_containers(item) + value["__mutated__"] = "__mutated__" + elif isinstance(value, list): + for item in value: + mutate_nested_containers(item) + value.append("__mutated__") + elif isinstance(value, tuple): + for item in value: + mutate_nested_containers(item) diff --git a/packages/zarr-metadata/tests/model/test_array.py b/packages/zarr-metadata/tests/model/test_array.py new file mode 100644 index 0000000000..95dc7aea3a --- /dev/null +++ b/packages/zarr-metadata/tests/model/test_array.py @@ -0,0 +1,1784 @@ +"""Tests for the metadata models in ``zarr_metadata.model``.""" + +import copy +import dataclasses +import json +from collections import UserDict +from collections.abc import Callable +from typing import TYPE_CHECKING, get_args + +import pytest +from typing_extensions import Unpack + +from tests.model._cases import Expect, ExpectFail, mutate_nested_containers +from zarr_metadata.model import ( + ARRAY_METADATA_OPTIONAL_KEYS_V3, + ARRAY_METADATA_REQUIRED_KEYS_V3, + ARRAY_METADATA_STANDARD_KEYS_V3, + UNSET, + MetadataValidationError, + ValidationProblem, + ZarrV2ArrayMetadata, + ZarrV2ArrayMetadataPartial, + ZarrV3ArrayMetadata, + ZarrV3ArrayMetadataPartial, + ZarrV3MetadataField, + ZarrV3NamedConfig, + is_array_metadata_v2, + is_array_metadata_v3, + is_json, + is_metadata_field_v3, + parse_array_metadata_v2, + parse_array_metadata_v3, + parse_json, + parse_metadata_field_v3, + validate_array_metadata_v2, + validate_array_metadata_v3, + validate_json, + validate_metadata_field_v3, +) +from zarr_metadata.model._validation import _prefix, arrays_to_tuples + +if TYPE_CHECKING: + from zarr_metadata._common import JSONValue + from zarr_metadata.v2 import ZarrV2CodecMetadata + +# --- public exports -------------------------------------------------------- + + +def test_guards_exported_from_package() -> None: + """The wire-type guard/parser functions are exported from the package.""" + import zarr_metadata.model + + for name in ( + "is_json", + "parse_json", + "is_metadata_field_v3", + "parse_metadata_field_v3", + "is_array_metadata_v3", + "parse_array_metadata_v3", + "is_array_metadata_v2", + "parse_array_metadata_v2", + ): + assert name in zarr_metadata.model.__all__ + assert hasattr(zarr_metadata.model, name) + + +# `ZARR_V3_CONSOLIDATED_METADATA_KEY` is deliberately absent: it names a key +# *inside* a v3 group document, not a store key, so it has no paired `Literal` +# and no `to_key_value` signature to appear in. See `test_v3_consolidated_key_ +# is_not_a_store_key`, which pins that distinction. +STORE_KEY_PAIRS = [ + ("ZARR_V2_ARRAY_METADATA_STORE_KEY", "ZarrV2ArrayMetadataStoreKey", "zarr_metadata.v2.array"), + ("ZARR_V3_ARRAY_METADATA_STORE_KEY", "ZarrV3ArrayMetadataStoreKey", "zarr_metadata.v3.array"), + ("ZARR_V2_ATTRIBUTES_STORE_KEY", "ZarrV2AttributesStoreKey", "zarr_metadata.v2.attributes"), + ("ZARR_V2_GROUP_METADATA_STORE_KEY", "ZarrV2GroupMetadataStoreKey", "zarr_metadata.v2.group"), + ("ZARR_V3_GROUP_METADATA_STORE_KEY", "ZarrV3GroupMetadataStoreKey", "zarr_metadata.v3.group"), + ( + "ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY", + "ZarrV2ConsolidatedMetadataStoreKey", + "zarr_metadata.v2.consolidated", + ), +] + + +def test_store_key_pairs_exported_from_package() -> None: + """Each store-key constant is exported together with its Literal type + alias, and the pair cannot drift apart.""" + import zarr_metadata.model as m + + for const_name, alias_name, _ in STORE_KEY_PAIRS: + assert const_name in m.__all__ + assert alias_name in m.__all__ + assert (getattr(m, const_name),) == get_args(getattr(m, alias_name)) + + +def test_store_keys_are_defined_in_their_spec_modules() -> None: + """Store keys are facts about the on-disk specs, so each is defined in the + `v2`/`v3` module describing that document β€” not in the model layer, which + only re-exports them.""" + import importlib + + for const_name, alias_name, module_name in STORE_KEY_PAIRS: + module = importlib.import_module(module_name) + for name in (const_name, alias_name): + assert name in module.__all__, f"{name} should be exported by {module_name}" + + +def test_v3_consolidated_key_is_not_a_store_key() -> None: + """v3 consolidated metadata is embedded as a field inside the group's own + `zarr.json`, not persisted under its own store key. It therefore has no + paired `Literal` alias, unlike every true store key β€” which is why it is + excluded from `STORE_KEY_PAIRS` rather than merely forgotten.""" + import zarr_metadata.model as m + + assert "ZARR_V3_CONSOLIDATED_METADATA_KEY" in m.__all__ + assert not hasattr(m, "ZarrV3ConsolidatedMetadataKey") + assert m.ZARR_V3_CONSOLIDATED_METADATA_KEY not in { + getattr(m, const_name) for const_name, _, _ in STORE_KEY_PAIRS + } + + +def test_v3_node_store_keys_agree() -> None: + """v3 keys both node types' metadata under one store key, distinguished by + the document's `node_type`. The array and group constants are separately + typed but must name the same file; adjacency used to make that obvious, and + they now live in different modules.""" + import zarr_metadata.model as m + + assert m.ZARR_V3_ARRAY_METADATA_STORE_KEY == m.ZARR_V3_GROUP_METADATA_STORE_KEY + + +def test_validation_diagnostics_exported_from_package() -> None: + """The validation-diagnostic types and validators are exported from the package.""" + import zarr_metadata.model + + for name in ( + "ValidationProblem", + "MetadataValidationError", + "validate_json", + "validate_metadata_field_v3", + "validate_array_metadata_v3", + "validate_array_metadata_v2", + ): + assert name in zarr_metadata.model.__all__ + assert hasattr(zarr_metadata.model, name) + + +def test_expect_expectfail_smoke() -> None: + """The Expect/ExpectFail test-case dataclasses behave as expected.""" + e = Expect(input=1, output=2, id="x") + assert (e.input, e.output, e.id) == (1, 2, "x") + f = ExpectFail(input=1, exception=ValueError, id="y", msg="boom") + with f.raises(): + raise ValueError("boom") + + +def test_v3_from_json_error_lists_all_problems() -> None: + """A malformed v3 document surfaces every problem via MetadataValidationError.problems.""" + doc: dict[str, object] = dict(ZarrV3ArrayMetadata.create_default().to_json()) + del doc["shape"] + doc["data_type"] = 5 + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV3ArrayMetadata.from_json(doc) + locs = {p.loc for p in exc_info.value.problems} + assert ("shape",) in locs + assert ("data_type",) in locs + + +# --- JSON type / fill_value contract --------------------------------------- + + +def test_json_value_type_accepts_json_shapes() -> None: + # JSONValue is the package's public JSON type alias; assigning JSON-shaped + # values to it is valid. + """The JSONValue type alias accepts JSON-shaped values.""" + value: JSONValue = {"a": [1, 2.0, "x", True, None]} + assert value == {"a": [1, 2.0, "x", True, None]} + + +def test_string_nan_fill_value_roundtrips() -> None: + # Non-finite floats are represented as the spec strings ("NaN", "Infinity", + # "-Infinity") by the caller β€” the metadata layer does not interpret dtypes. + # The string form round-trips cleanly under default dataclass equality, + # unlike a raw float('nan') (which is an invalid fill_value the caller must + # not pass). + """A string 'NaN' fill_value round-trips cleanly (non-finite floats are the caller's responsibility).""" + m = ZarrV3ArrayMetadata.create_default(fill_value="NaN") + assert ZarrV3ArrayMetadata.from_json(m.to_json()) == m + assert ZarrV3ArrayMetadata.from_json(m.to_json()).fill_value == "NaN" + + +# --- ZarrV3NamedConfig.to_json ------------------------------------------------ + +ZARR_TO_JSON_CASES = [ + Expect( + ZarrV3NamedConfig(name="regular", configuration={"chunk_shape": [1]}), + {"name": "regular", "configuration": {"chunk_shape": [1]}}, + id="with-configuration", + ), + Expect( + ZarrV3NamedConfig(name="bytes", configuration={}), + "bytes", + id="empty-configuration-shorthand", + ), +] + + +@pytest.mark.parametrize("case", ZARR_TO_JSON_CASES, ids=lambda c: c.id) +def test_zarr_metadata_v3_to_json(case: Expect[ZarrV3NamedConfig, object]) -> None: + """ZarrV3NamedConfig.to_json emits the canonical extension form.""" + assert case.input.to_json() == case.output + + +def test_zarr_metadata_v3_to_json_preserves_false_obligation() -> None: + """An empty optional extension stays an object so false is not lost.""" + model = ZarrV3NamedConfig(name="optional", configuration={}, must_understand=False) + assert model.to_json() == {"name": "optional", "must_understand": False} + + +# --- ZarrV3NamedConfig.from_json ----------------------------------------------- + +ZARR_FROM_JSON_CASES = [ + Expect("bytes", ZarrV3NamedConfig(name="bytes", configuration={}), id="bare-string"), + Expect( + {"name": "regular", "configuration": {"chunk_shape": [1]}}, + ZarrV3NamedConfig(name="regular", configuration={"chunk_shape": (1,)}), + id="object-with-config", + ), + Expect( + {"name": "bytes"}, + ZarrV3NamedConfig(name="bytes", configuration={}), + id="object-without-config", + ), +] + + +@pytest.mark.parametrize("case", ZARR_FROM_JSON_CASES, ids=lambda c: c.id) +def test_zarr_metadata_v3_from_json(case: Expect[object, ZarrV3NamedConfig]) -> None: + """ZarrV3NamedConfig.from_json parses both the bare-string and object forms.""" + assert ZarrV3NamedConfig.from_json(case.input) == case.output + + +def test_zarr_metadata_v3_from_json_preserves_false_obligation() -> None: + """Explicit false is represented on the normalized model.""" + model = ZarrV3NamedConfig.from_json({"name": "optional", "must_understand": False}) + assert model.must_understand is False + + +# --- V3 baseline ----------------------------------------------------------- + + +def test_v3_to_json_emits_canonical_document() -> None: + """V3 to_json emits exactly the expected document (which covers every + spec-required key by construction).""" + out = ZarrV3ArrayMetadata.create_default( + shape=(10,), data_type=ZarrV3NamedConfig(name="int32", configuration={}) + ).to_json() + assert out == { + "zarr_format": 3, + "node_type": "array", + "shape": (10,), + "fill_value": 0, + "data_type": "int32", + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": (10,)}}, + "codecs": ("bytes",), + "chunk_key_encoding": "default", + } + + +def test_v3_dimension_names_included_when_present() -> None: + """V3 to_json includes dimension_names when they are set.""" + out: dict[str, object] = dict( + ZarrV3ArrayMetadata.create_default(dimension_names=("x",)).to_json() + ) + assert out["dimension_names"] == ("x",) + + +def test_v3_dimension_names_omitted_when_none() -> None: + """V3 to_json omits dimension_names when they are UNSET.""" + out = ZarrV3ArrayMetadata.create_default(dimension_names=UNSET).to_json() + assert "dimension_names" not in out + + +# --- BUG 1: attributes gated on dimension_names ---------------------------- + + +def test_v3_attributes_included_when_dimension_names_is_none() -> None: + """Attributes must be emitted regardless of dimension_names. + + Regression: attributes were gated on ``dimension_names is not None``, + so non-empty attributes were silently dropped when there were no + dimension names. + """ + out: dict[str, object] = dict( + ZarrV3ArrayMetadata.create_default( + dimension_names=UNSET, attributes={"foo": "bar"} + ).to_json() + ) + assert out["attributes"] == {"foo": "bar"} + + +# --- BUG 2: single storage transformer dropped ----------------------------- + + +def test_v3_single_storage_transformer_included() -> None: + """A single storage transformer must be emitted. + + Regression: the guard used ``> 1`` instead of ``> 0``, dropping a + lone storage transformer. + """ + st = ZarrV3NamedConfig(name="some_transformer", configuration={}) + out: dict[str, object] = dict( + ZarrV3ArrayMetadata.create_default(storage_transformers=(st,)).to_json() + ) + assert out["storage_transformers"] == ("some_transformer",) + + +def test_v3_no_storage_transformers_omitted() -> None: + """V3 to_json omits storage_transformers when empty.""" + out = ZarrV3ArrayMetadata.create_default(storage_transformers=()).to_json() + assert "storage_transformers" not in out + + +# --- V3 extra fields ------------------------------------------------------- + + +def test_v3_extra_fields_merged() -> None: + """V3 to_json merges extra_fields into the top-level document.""" + out = ZarrV3ArrayMetadata.create_default( + extra_fields={"my_ext": {"must_understand": False}} + ).to_json() + assert out["my_ext"] == {"must_understand": False} + + +def test_v3_extra_fields_overlapping_standard_field_rejected() -> None: + """Constructing a V3 model with an extra field that collides with a standard key is rejected.""" + with pytest.raises(ValueError): + ZarrV3ArrayMetadata.create_default(extra_fields={"shape": {"must_understand": False}}) + + +# --- V3 key/value ---------------------------------------------------------- + + +def test_v3_to_key_value_is_valid_json_under_zarr_json() -> None: + """V3 to_key_value produces valid JSON bytes under the zarr.json key.""" + kv = ZarrV3ArrayMetadata.create_default(attributes={"a": 1}).to_key_value() + assert set(kv) == {"zarr.json"} + parsed = json.loads(kv["zarr.json"].decode("utf-8")) + assert parsed["zarr_format"] == 3 + assert parsed["attributes"] == {"a": 1} + + +# --- V3 standard-key sets -------------------------------------------------- + + +def test_standard_keys_is_union_of_required_and_optional() -> None: + """The standard-key set is the union of the required and optional key sets.""" + assert ( + ARRAY_METADATA_STANDARD_KEYS_V3 + == ARRAY_METADATA_REQUIRED_KEYS_V3 | ARRAY_METADATA_OPTIONAL_KEYS_V3 + ) + + +def test_standard_keys_contains_known_fields_and_excludes_extensions() -> None: + """The standard-key set contains known fields and excludes extension keys.""" + assert { + "zarr_format", + "node_type", + "shape", + "codecs", + } <= ARRAY_METADATA_STANDARD_KEYS_V3 + assert "my_ext" not in ARRAY_METADATA_STANDARD_KEYS_V3 + + +# --- create_default -------------------------------------------------------- + + +def test_v3_create_default_is_valid_empty_array() -> None: + """V3 create_default builds a structurally valid empty array that round-trips.""" + m = ZarrV3ArrayMetadata.create_default() + assert m.shape == () + assert m.data_type == ZarrV3NamedConfig(name="uint8", configuration={}) + assert m.fill_value == 0 + assert m.attributes == {} + assert m.extra_fields == {} + # the default document is structurally valid and round-trips + assert validate_array_metadata_v3(m.to_json()) == [] + assert ZarrV3ArrayMetadata.from_json(m.to_json()) == m + + +def test_v3_create_default_applies_overrides() -> None: + """V3 create_default applies keyword overrides over the defaults.""" + m = ZarrV3ArrayMetadata.create_default(shape=(4, 4), attributes={"a": 1}) + assert m.shape == (4, 4) + assert m.attributes == {"a": 1} + # un-overridden fields keep their defaults + assert m.data_type == ZarrV3NamedConfig(name="uint8", configuration={}) + + +def test_v2_create_default_is_valid_empty_array() -> None: + """V2 create_default builds a structurally valid empty array that round-trips.""" + m = ZarrV2ArrayMetadata.create_default() + assert m.shape == () + assert m.chunks == () + assert m.fill_value == 0 + assert m.compressor is None + assert m.filters is None + assert m.attributes is UNSET + assert validate_array_metadata_v2(m.to_json()) == [] + assert ZarrV2ArrayMetadata.from_json(m.to_json()) == m + + +def test_v2_create_default_applies_overrides() -> None: + """V2 create_default applies keyword overrides over the defaults.""" + m = ZarrV2ArrayMetadata.create_default(shape=(8,), attributes={"k": "v"}) + assert m.shape == (8,) + assert m.attributes == {"k": "v"} + assert m.dtype == "|u1" # default dtype unchanged + + +# --- V3 update ------------------------------------------------------------- + +# Cluster 3: update same-shape pairs across versions β€” parametrized + +UPDATE_NEW_INSTANCE_PARAMS = [ + pytest.param(ZarrV3ArrayMetadata, id="v3"), + pytest.param(ZarrV2ArrayMetadata, id="v2"), +] + + +@pytest.mark.parametrize("model_cls", UPDATE_NEW_INSTANCE_PARAMS) +def test_update_returns_new_instance( + model_cls: type[ZarrV3ArrayMetadata | ZarrV2ArrayMetadata], +) -> None: + """update returns a new instance with the field replaced, leaving the original unchanged.""" + base = model_cls.create_default(shape=(10,)) + updated = base.update(shape=(20,)) + assert updated.shape == (20,) + assert base.shape == (10,) # original unchanged + assert isinstance(updated, model_cls) + + +UPDATE_NO_ARGS_PARAMS = [ + pytest.param(ZarrV3ArrayMetadata, id="v3"), + pytest.param(ZarrV2ArrayMetadata, id="v2"), +] + + +@pytest.mark.parametrize("model_cls", UPDATE_NO_ARGS_PARAMS) +def test_update_no_args_returns_equal_model( + model_cls: type[ZarrV3ArrayMetadata | ZarrV2ArrayMetadata], +) -> None: + """update with no arguments returns a model equal to the original.""" + base = model_cls.create_default() + assert base.update() == base + + +# V3-only update tests β€” kept direct (extra_fields is v3-specific) + + +def test_update_can_replace_extra_fields() -> None: + """update can replace the extra_fields mapping.""" + base = ZarrV3ArrayMetadata.create_default(extra_fields={}) + updated = base.update(extra_fields={"my_ext": {"must_understand": False}}) + assert updated.extra_fields == {"my_ext": {"must_understand": False}} + + +def test_update_replaces_extra_fields_rather_than_merging() -> None: + """update replaces extra_fields wholesale rather than merging.""" + base = ZarrV3ArrayMetadata.create_default(extra_fields={"a": {"must_understand": False}}) + updated = base.update(extra_fields={"b": {"must_understand": True}}) + assert updated.extra_fields == {"b": {"must_understand": True}} + + +def test_partial_keys_match_settable_model_fields() -> None: + """The partial TypedDict must list exactly the constructor-settable fields. + + Guards against drift: adding/removing a settable field on the model + without updating ``ZarrV3ArrayMetadataPartial`` fails here. + """ + settable = {f.name for f in dataclasses.fields(ZarrV3ArrayMetadata) if f.init} + assert set(ZarrV3ArrayMetadataPartial.__annotations__) == settable + + +# --- V2 model -------------------------------------------------------------- + + +def test_v2_partial_keys_match_settable_model_fields() -> None: + """The v2 partial TypedDict must list exactly the settable fields.""" + settable = {f.name for f in dataclasses.fields(ZarrV2ArrayMetadata) if f.init} + assert set(ZarrV2ArrayMetadataPartial.__annotations__) == settable + + +def test_v2_to_key_value_splits_zarray_and_zattrs() -> None: + """V2 to_key_value splits the document into .zarray and .zattrs.""" + kv = ZarrV2ArrayMetadata.create_default(attributes={"a": 1}).to_key_value() + assert set(kv) == {".zarray", ".zattrs"} + zarray = json.loads(kv[".zarray"].decode("utf-8")) + zattrs = json.loads(kv[".zattrs"].decode("utf-8")) + assert zarray["zarr_format"] == 2 + assert zattrs == {"a": 1} + + +def test_v2_zarray_excludes_attributes() -> None: + """The on-disk ``.zarray`` document must not contain user attributes. + + In v2, attributes live only in the sibling ``.zattrs`` file. The bundled + ``ZarrV2ArrayMetadataJSON`` / ``to_json()`` carry attributes for convenience, but + ``to_key_value()`` must split them out. + """ + kv = ZarrV2ArrayMetadata.create_default(attributes={"a": 1}).to_key_value() + zarray = json.loads(kv[".zarray"].decode("utf-8")) + assert "attributes" not in zarray + + +def test_v2_to_json_still_includes_attributes() -> None: + """``to_json()`` is the bundled in-memory form and keeps attributes.""" + out: dict[str, object] = dict(ZarrV2ArrayMetadata.create_default(attributes={"a": 1}).to_json()) + assert out["attributes"] == {"a": 1} + + +# --- arrays_to_tuples helper ---------------------------------------------- + +ARRAYS_TO_TUPLES_CASES = [ + Expect([1, 2, 3], (1, 2, 3), id="top-level-list"), + Expect({"a": [1, [2, 3]], "b": "x"}, {"a": (1, (2, 3)), "b": "x"}, id="nested-in-dict"), + Expect(5, 5, id="scalar-int"), + Expect("s", "s", id="scalar-str"), + Expect(None, None, id="scalar-none"), + Expect( + {"name": "bytes", "configuration": {"nums": [1, 2]}}, + {"name": "bytes", "configuration": {"nums": (1, 2)}}, + id="dict-keys-preserved", + ), +] + + +@pytest.mark.parametrize("case", ARRAYS_TO_TUPLES_CASES, ids=lambda c: c.id) +def test_arrays_to_tuples(case: Expect[object, object]) -> None: + """arrays_to_tuples recursively converts JSON arrays to tuples.""" + assert arrays_to_tuples(case.input) == case.output + + +# --- ZarrV3ArrayMetadata.from_json ---------------------------------------- + + +def test_v3_from_json_reconstructs_required_fields() -> None: + """V3 from_json reconstructs the required fields from a document.""" + doc = ZarrV3ArrayMetadata.create_default( + shape=(7,), + attributes={"a": 1}, + data_type=ZarrV3NamedConfig(name="int32", configuration={}), + ).to_json() + model = ZarrV3ArrayMetadata.from_json(doc) + assert model.shape == (7,) + assert model.data_type == ZarrV3NamedConfig(name="int32", configuration={}) + assert model.attributes == {"a": 1} + + +def test_v3_from_json_defaults_for_omitted_optionals() -> None: + """V3 from_json supplies defaults for omitted optional fields.""" + doc = ZarrV3ArrayMetadata.create_default( + attributes={}, storage_transformers=(), dimension_names=UNSET + ).to_json() + # to_json omits these entirely; from_json must restore defaults + model = ZarrV3ArrayMetadata.from_json(doc) + assert model.attributes == {} + assert model.storage_transformers == () + assert model.dimension_names is UNSET + + +def test_v3_from_json_routes_unknown_keys_to_extra_fields() -> None: + """V3 from_json routes unknown top-level keys into extra_fields.""" + doc = ZarrV3ArrayMetadata.create_default( + extra_fields={"my_ext": {"must_understand": False}} + ).to_json() + model = ZarrV3ArrayMetadata.from_json(doc) + assert model.extra_fields == {"my_ext": {"must_understand": False}} + + +def test_v3_from_json_standard_keys_not_in_extra_fields() -> None: + """V3 from_json keeps standard keys out of extra_fields.""" + doc = ZarrV3ArrayMetadata.create_default( + shape=(10,), attributes={"a": 1}, dimension_names=("x",) + ).to_json() + model = ZarrV3ArrayMetadata.from_json(doc) + assert model.extra_fields == {} + + +def test_v3_from_json_nested_arrays_in_attributes_become_tuples() -> None: + """V3 from_json converts nested arrays in attributes into tuples.""" + doc = ZarrV3ArrayMetadata.create_default(attributes={"scale": [[1, 2], [3, 4]]}).to_json() + model = ZarrV3ArrayMetadata.from_json(doc) + assert model.attributes == {"scale": ((1, 2), (3, 4))} + + +# --- ZarrV3ArrayMetadata.from_key_value ---------------------------------- + + +def test_v3_from_key_value_parses_zarr_json() -> None: + """V3 from_key_value parses the zarr.json entry into a model.""" + kv = ZarrV3ArrayMetadata.create_default(shape=(3,)).to_key_value() + model = ZarrV3ArrayMetadata.from_key_value(kv) + assert model.shape == (3,) + + +# --- Cluster 2: from_key_value missing-key raises (parametrized) ----------- + +FROM_KEY_VALUE_MISSING_PARAMS = [ + pytest.param( + ZarrV3ArrayMetadata, + ExpectFail({}, MetadataValidationError, id="v3-missing-zarr-json", msg="missing store key"), + id="v3-missing-zarr-json", + ), + pytest.param( + ZarrV2ArrayMetadata, + ExpectFail({}, MetadataValidationError, id="v2-missing-zarray", msg="missing store key"), + id="v2-missing-zarray", + ), +] + + +@pytest.mark.parametrize(("model_cls", "case"), FROM_KEY_VALUE_MISSING_PARAMS) +def test_from_key_value_missing_key_raises( + model_cls: type[ZarrV3ArrayMetadata | ZarrV2ArrayMetadata], + case: ExpectFail[dict[str, bytes]], +) -> None: + """from_key_value raises MetadataValidationError when the required store key is absent.""" + with case.raises(): + model_cls.from_key_value(case.input) + + +# --- Cluster 1: round-trips (model β†’ json β†’ model, parametrized) ----------- + +ROUNDTRIP_MODEL_JSON_PARAMS = [ + pytest.param( + ZarrV3ArrayMetadata, + ZarrV3ArrayMetadata.create_default( + shape=(10,), + attributes={"a": 1}, + dimension_names=("x",), + storage_transformers=(ZarrV3NamedConfig(name="t", configuration={}),), + extra_fields={"ext": {"must_understand": False}}, + ), + id="v3-full", + ), + pytest.param( + ZarrV3ArrayMetadata, + ZarrV3ArrayMetadata.create_default( + attributes={}, + dimension_names=UNSET, + storage_transformers=(), + extra_fields={}, + ), + id="v3-empty-optionals", + ), + pytest.param( + ZarrV2ArrayMetadata, + ZarrV2ArrayMetadata.create_default(attributes={"a": 1}, filters=None, compressor=None), + id="v2-basic", + ), +] + + +@pytest.mark.parametrize(("model_cls", "model"), ROUNDTRIP_MODEL_JSON_PARAMS) +def test_roundtrip_model_json_model( + model_cls: type[ZarrV3ArrayMetadata | ZarrV2ArrayMetadata], + model: ZarrV3ArrayMetadata | ZarrV2ArrayMetadata, +) -> None: + """A model round-trips through to_json/from_json back to an equal model.""" + assert model_cls.from_json(model.to_json()) == model + + +# --- Round-trips (model β†’ key_value β†’ model, parametrized) ----------------- + +ROUNDTRIP_KEY_VALUE_PARAMS = [ + pytest.param( + ZarrV3ArrayMetadata, + ZarrV3ArrayMetadata.create_default(attributes={"a": 1}), + id="v3", + ), + pytest.param( + ZarrV2ArrayMetadata, + ZarrV2ArrayMetadata.create_default(attributes={"a": 1}), + id="v2", + ), +] + + +@pytest.mark.parametrize(("model_cls", "model"), ROUNDTRIP_KEY_VALUE_PARAMS) +def test_roundtrip_via_key_value( + model_cls: type[ZarrV3ArrayMetadata | ZarrV2ArrayMetadata], + model: ZarrV3ArrayMetadata | ZarrV2ArrayMetadata, +) -> None: + """A model round-trips through to_key_value/from_key_value back to an equal model.""" + assert model_cls.from_key_value(model.to_key_value()) == model + + +# --- Round-trips (json β†’ model β†’ json, direction distinct β€” kept direct) --- + + +def test_v3_roundtrip_json_model_json() -> None: + """A v3 document round-trips through from_json/to_json back to an equal document.""" + doc = ZarrV3ArrayMetadata.create_default( + shape=(10,), attributes={"a": 1}, dimension_names=("x",) + ).to_json() + assert ZarrV3ArrayMetadata.from_json(doc).to_json() == doc + + +def test_v2_roundtrip_json_model_json() -> None: + """A v2 document round-trips through from_json/to_json back to an equal document.""" + doc = ZarrV2ArrayMetadata.create_default(attributes={"a": 1}).to_json() + assert ZarrV2ArrayMetadata.from_json(doc).to_json() == doc + + +# --- to_json shares no mutable state with the model ------------------------ + +TO_JSON_NO_ALIASING_PARAMS = [ + pytest.param( + ZarrV3ArrayMetadata.create_default( + shape=(2,), + attributes={"a": {"b": [1]}}, + codecs=(ZarrV3NamedConfig(name="blosc", configuration={"opts": {"level": 1}}),), + extra_fields={"ext": {"must_understand": False, "cfg": {"x": [1]}}}, + ), + id="v3", + ), + pytest.param( + ZarrV2ArrayMetadata.create_default( + attributes={"a": {"b": [1]}}, + compressor={"id": "zstd", "opts": {"level": 1}}, + filters=({"id": "delta", "cfg": [1]},), + fill_value=[0, 0], + ), + id="v2", + ), +] + + +@pytest.mark.parametrize("model", TO_JSON_NO_ALIASING_PARAMS) +def test_to_json_shares_no_mutable_state_with_model( + model: ZarrV3ArrayMetadata | ZarrV2ArrayMetadata, +) -> None: + """Mutating a document returned by to_json leaves the model unchanged.""" + baseline = copy.deepcopy(model.to_json()) + mutate_nested_containers(model.to_json()) + assert model.to_json() == baseline + + +def test_v3_parser_accepts_bare_string_data_type() -> None: + """V3 from_json accepts a bare-string data_type and re-serializes it canonically.""" + doc = ZarrV3ArrayMetadata.create_default().to_json() + doc["data_type"] = "int32" + model = ZarrV3ArrayMetadata.from_json(doc) + assert model.data_type == ZarrV3NamedConfig(name="int32", configuration={}) + assert model.to_json()["data_type"] == "int32" + + +@pytest.mark.parametrize("name", ["bytes", "ANY string", "urn:example:codec"]) +def test_metadata_field_accepts_any_string_name(name: str) -> None: + """The structural layer checks the name type, not syntax or registration.""" + assert validate_metadata_field_v3({"name": name}) == [] + + +@pytest.mark.parametrize("value", [0, 1, "false", None]) +def test_metadata_field_must_understand_must_be_boolean(value: object) -> None: + """must_understand is a JSON boolean, not a truthy scalar.""" + problems = validate_metadata_field_v3({"name": "x", "must_understand": value}) + assert [(problem.loc, problem.kind) for problem in problems] == [ + (("must_understand",), "invalid_type") + ] + + +def test_metadata_field_rejects_unknown_envelope_member() -> None: + """Unknown envelope keys cannot be silently discarded during normalization.""" + problems = validate_metadata_field_v3({"name": "x", "typo": 1}) + assert [(problem.loc, problem.kind) for problem in problems] == [(("typo",), "invalid_value")] + + +@pytest.mark.parametrize("field", ["codecs", "storage_transformers"]) +def test_optional_extension_points_allow_must_understand_false(field: str) -> None: + """Codecs and storage transformers may be explicitly ignorable.""" + doc: dict[str, object] = dict(ZarrV3ArrayMetadata.create_default().to_json()) + doc[field] = ({"name": "optional", "must_understand": False},) + assert validate_array_metadata_v3(doc) == [] + + +@pytest.mark.parametrize("field", ["data_type", "chunk_grid", "chunk_key_encoding"]) +def test_required_extension_points_reject_must_understand_false(field: str) -> None: + """Core extension points needed to locate or decode chunks cannot be ignored.""" + doc: dict[str, object] = dict(ZarrV3ArrayMetadata.create_default().to_json()) + doc[field] = {"name": "optional", "must_understand": False} + assert [(problem.loc, problem.kind) for problem in validate_array_metadata_v3(doc)] == [ + ((field, "must_understand"), "invalid_value") + ] + + +def test_v3_codecs_cannot_be_empty() -> None: + """The core document requires at least one array-to-bytes codec.""" + doc: dict[str, object] = dict(ZarrV3ArrayMetadata.create_default().to_json()) + doc["codecs"] = () + assert [(problem.loc, problem.kind) for problem in validate_array_metadata_v3(doc)] == [ + (("codecs",), "invalid_value") + ] + + +def test_v2_roundtrip_with_compressor_and_filters() -> None: + # Non-None compressor/filters must round-trip; extra assertion on .compressor. + """A v2 model with non-None compressor and filters round-trips.""" + compressor: ZarrV2CodecMetadata = {"id": "blosc", "clevel": 5} + filters: tuple[ZarrV2CodecMetadata, ...] = ({"id": "delta"},) + m = ZarrV2ArrayMetadata.create_default(compressor=compressor, filters=filters) + restored = ZarrV2ArrayMetadata.from_json(m.to_json()) + assert restored == m + assert restored.compressor == {"id": "blosc", "clevel": 5} + + +# --- ZarrV2ArrayMetadata.from_json ---------------------------------------- + + +def test_v2_from_json_reconstructs_fields() -> None: + """V2 from_json reconstructs the fields from a document.""" + doc = ZarrV2ArrayMetadata.create_default(shape=(4,), attributes={"a": 1}, dtype=" None: + """V2 from_json reads an absent attributes key as UNSET, distinct from an + explicit empty mapping.""" + absent = ZarrV2ArrayMetadata.from_json(ZarrV2ArrayMetadata.create_default().to_json()) + explicit = ZarrV2ArrayMetadata.from_json( + ZarrV2ArrayMetadata.create_default(attributes={}).to_json() + ) + assert absent.attributes is UNSET + assert explicit.attributes == {} + assert absent != explicit + + +# --- ZarrV2ArrayMetadata.from_key_value -------------------------------- + + +def test_v2_from_key_value_remerges_zattrs() -> None: + """V2 from_key_value re-merges .zattrs back into attributes.""" + kv = ZarrV2ArrayMetadata.create_default(attributes={"a": 1}, shape=(10,)).to_key_value() + model = ZarrV2ArrayMetadata.from_key_value(kv) + assert model.attributes == {"a": 1} + assert model.shape == (10,) + + +@pytest.mark.parametrize("extra_key", ["attributes", "vendor_extension"]) +def test_v2_from_key_value_rejects_zarray_extra_members(extra_key: str) -> None: + """Raw `.zarray` documents reject every non-spec member.""" + doc: dict[str, object] = dict(ZarrV2ArrayMetadata.create_default().to_json()) + doc.pop("attributes", None) + doc[extra_key] = {} + + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV2ArrayMetadata.from_key_value({".zarray": json.dumps(doc).encode()}) + + assert [(problem.loc, problem.kind) for problem in exc_info.value.problems] == [ + ((extra_key,), "invalid_value") + ] + + +def test_v2_zattrs_presence_round_trips() -> None: + """The .zattrs file's presence is part of the store: an absent file reads + as UNSET and emits no .zattrs; an explicit empty file reads as {} and + emits .zattrs β€” the two stores stay distinct through a round-trip.""" + explicit_kv = dict(ZarrV2ArrayMetadata.create_default(attributes={}).to_key_value()) + assert ".zattrs" in explicit_kv + absent_kv = dict(explicit_kv) + del absent_kv[".zattrs"] + + absent = ZarrV2ArrayMetadata.from_key_value(absent_kv) + explicit = ZarrV2ArrayMetadata.from_key_value(explicit_kv) + assert absent.attributes is UNSET + assert explicit.attributes == {} + assert ".zattrs" not in absent.to_key_value() + assert ".zattrs" in explicit.to_key_value() + + +def test_v2_from_json_nested_arrays_in_attributes_become_tuples() -> None: + """V2 from_json converts nested arrays in attributes into tuples.""" + doc = ZarrV2ArrayMetadata.create_default(attributes={"axes": [[0, 1], [2, 3]]}).to_json() + model = ZarrV2ArrayMetadata.from_json(doc) + assert model.attributes == {"axes": ((0, 1), (2, 3))} + + +# --- scalar wire-type guards (is_/validate_/parse_) ------------------------ +# +# Each value is modelled once as Expect[object, frozenset[tuple[str | int, ...]]] +# where `output` is the set of expected problem locs validate_* must report β€” +# frozenset() means VALID. Valid iff output == frozenset(). + +JSON_VALIDATE_CASES: list[Expect[object, frozenset[tuple[str | int, ...]]]] = [ + Expect("s", frozenset(), id="str"), + Expect(1, frozenset(), id="int"), + Expect(1.5, frozenset(), id="float"), + Expect(True, frozenset(), id="bool"), + Expect(None, frozenset(), id="none"), + Expect({"a": [1, {"b": None}], "c": "x"}, frozenset(), id="nested-containers"), + Expect((1, 2, 3), frozenset(), id="tuple-array"), + Expect(float("nan"), frozenset({()}), id="nan"), + Expect(float("inf"), frozenset({()}), id="inf"), + Expect(float("-inf"), frozenset({()}), id="negative-inf"), + Expect(object(), frozenset({()}), id="object"), + Expect(b"abc", frozenset({()}), id="bytes"), + Expect(bytearray(b"abc"), frozenset({()}), id="bytearray"), + Expect({1: "x"}, frozenset({()}), id="non-str-key"), + Expect([1, object()], frozenset({(1,)}), id="non-json-list-item"), + Expect({"ok": object()}, frozenset({("ok",)}), id="non-json-value"), +] + + +@pytest.mark.parametrize("case", JSON_VALIDATE_CASES, ids=lambda c: c.id) +def test_is_json(case: Expect[object, frozenset[tuple[str | int, ...]]]) -> None: + """is_json reports whether a value is JSON-serializable.""" + assert is_json(case.input) is (case.output == frozenset()) + + +@pytest.mark.parametrize("case", JSON_VALIDATE_CASES, ids=lambda c: c.id) +def test_validate_json(case: Expect[object, frozenset[tuple[str | int, ...]]]) -> None: + """validate_json reports the problems (and their locs) for a value.""" + problems = validate_json(case.input) + assert (problems == []) is (case.output == frozenset()) + assert {p.loc for p in problems} >= case.output + + +@pytest.mark.parametrize("case", JSON_VALIDATE_CASES, ids=lambda c: c.id) +def test_parse_json(case: Expect[object, frozenset[tuple[str | int, ...]]]) -> None: + """parse_json returns valid JSON values and raises on invalid ones.""" + if case.output == frozenset(): + parsed = parse_json(case.input) + assert arrays_to_tuples(parsed) == arrays_to_tuples(case.input) + else: + with pytest.raises(MetadataValidationError): + parse_json(case.input) + + +def test_parse_json_materializes_abstract_containers() -> None: + """Accepted Mapping and Sequence values normalize to JSON encoder containers.""" + value = UserDict({"values": range(3)}) + + parsed = parse_json(value) + + assert parsed == {"values": (0, 1, 2)} + assert type(parsed) is dict + assert type(parsed["values"]) is tuple + json.dumps(parsed, allow_nan=False) + + +def test_json_type_guard_rejects_abstract_sequence() -> None: + """A guard cannot narrow an abstract sequence that only the parser materializes.""" + assert not is_json(range(3)) + assert parse_json(range(3)) == (0, 1, 2) + + +def test_parse_metadata_field_materializes_abstract_containers() -> None: + """Named-config parsing produces canonical containers at every nesting level.""" + value = UserDict({"name": "example", "configuration": UserDict({"values": range(2)})}) + + parsed = parse_metadata_field_v3(value) + + assert isinstance(parsed, dict) + assert parsed == {"name": "example", "configuration": {"values": (0, 1)}} + assert type(parsed["configuration"]) is dict + + +def test_metadata_field_type_guard_rejects_abstract_mapping() -> None: + """A metadata-field guard only narrows concrete TypedDict-shaped objects.""" + value = UserDict({"name": "bytes"}) + + assert not is_metadata_field_v3(value) + assert parse_metadata_field_v3(value) == {"name": "bytes"} + + +def test_validate_json_reports_json_in_message() -> None: + """validate_json's message for a non-JSON value mentions JSON.""" + problems = validate_json(object()) + assert problems[0].loc == () + assert "JSON" in problems[0].message + + +METADATA_FIELD_VALIDATE_CASES: list[Expect[object, frozenset[tuple[str | int, ...]]]] = [ + Expect("bytes", frozenset(), id="bare-string"), + Expect({"name": "x", "configuration": {"a": 1}}, frozenset(), id="named-config"), + Expect({"name": "bytes"}, frozenset(), id="name-only"), + Expect(5, frozenset({()}), id="not-str-or-mapping"), + Expect({"configuration": {}}, frozenset({("name",)}), id="missing-name"), + Expect({"name": 3}, frozenset({("name",)}), id="non-str-name"), + Expect( + {"name": "x", "configuration": [1]}, + frozenset({("configuration",)}), + id="config-not-mapping", + ), + Expect( + {"name": "x", "configuration": {1: "y"}}, + frozenset({("configuration",)}), + id="config-non-str-key", + ), +] + + +@pytest.mark.parametrize("case", METADATA_FIELD_VALIDATE_CASES, ids=lambda c: c.id) +def test_is_metadata_field_v3(case: Expect[object, frozenset[tuple[str | int, ...]]]) -> None: + """is_metadata_field_v3 reports whether a value is a v3 metadata field.""" + assert is_metadata_field_v3(case.input) is (case.output == frozenset()) + + +@pytest.mark.parametrize("case", METADATA_FIELD_VALIDATE_CASES, ids=lambda c: c.id) +def test_validate_metadata_field_v3( + case: Expect[object, frozenset[tuple[str | int, ...]]], +) -> None: + """validate_metadata_field_v3 reports the problems for a metadata-field value.""" + problems = validate_metadata_field_v3(case.input) + assert (problems == []) is (case.output == frozenset()) + assert {p.loc for p in problems} >= case.output + + +@pytest.mark.parametrize("case", METADATA_FIELD_VALIDATE_CASES, ids=lambda c: c.id) +def test_parse_metadata_field_v3( + case: Expect[object, frozenset[tuple[str | int, ...]]], +) -> None: + """parse_metadata_field_v3 returns valid fields and raises on invalid ones.""" + if case.output == frozenset(): + assert parse_metadata_field_v3(case.input) is case.input + else: + with pytest.raises(MetadataValidationError): + parse_metadata_field_v3(case.input) + + +# --- array-document wire-type guards (is_/validate_/parse_) ---------------- +# +# Each case starts from a valid document (built by `make`) and applies a +# mutation. `expected_locs` are loc paths `validate_*` must report for the +# invalid cases (a subset check, so accumulation of OTHER problems is allowed). + + +def _build_v3(**overrides: Unpack[ZarrV3ArrayMetadataPartial]) -> dict[str, object]: + return dict(ZarrV3ArrayMetadata.create_default(**overrides).to_json()) + + +def _build_v2(**overrides: Unpack[ZarrV2ArrayMetadataPartial]) -> dict[str, object]: + return dict(ZarrV2ArrayMetadata.create_default(**overrides).to_json()) + + +def _mutate(build: Callable[[], dict], mutate: Callable[[dict], object]) -> Callable[[], dict]: + def _factory() -> dict: + doc = build() + mutate(doc) + return doc + + return _factory + + +def _del(key: str) -> Callable[[dict], object]: + return lambda doc: doc.pop(key) + + +def _set(key: str, value: object) -> Callable[[dict], object]: + return lambda doc: doc.__setitem__(key, value) + + +V3_DOC_CASES: list[Expect[Callable[[], object], frozenset[tuple[str | int, ...]]]] = [ + Expect(_build_v3, frozenset(), id="valid"), + Expect( + lambda: _build_v3(shape=(10,), attributes={"a": 1}, dimension_names=("x",)), + frozenset(), + id="valid-with-attributes-and-dim-names", + ), + Expect( + lambda: _build_v3(extra_fields={"my_ext": {"must_understand": False}}), + frozenset(), + id="valid-with-extra-fields", + ), + Expect(_mutate(_build_v3, _del("shape")), frozenset({("shape",)}), id="missing-shape"), + Expect( + _mutate(_build_v3, _set("data_type", 5)), + frozenset({("data_type",)}), + id="bad-data-type", + ), + Expect( + _mutate(_build_v3, _set("shape", "not-a-shape")), + frozenset({("shape",)}), + id="shape-not-sequence", + ), + Expect( + _mutate(_build_v3, _set("shape", [1, "x"])), + frozenset({("shape",)}), + id="shape-non-int-item", + ), + Expect( + _mutate(_build_v3, _set("codecs", (5,))), + frozenset({("codecs", 0)}), + id="bad-codec-entry", + ), + Expect(lambda: [1, 2, 3], frozenset({()}), id="non-mapping-list"), + Expect(lambda: "nope", frozenset({()}), id="non-mapping-str"), + Expect( + _mutate(_mutate(_build_v3, _del("shape")), _set("data_type", 5)), + frozenset({("shape",), ("data_type",)}), + id="missing-shape-and-bad-data-type", + ), +] + +V2_DOC_CASES: list[Expect[Callable[[], object], frozenset[tuple[str | int, ...]]]] = [ + Expect(_build_v2, frozenset(), id="valid"), + Expect(lambda: _build_v2(attributes={"a": 1}), frozenset(), id="valid-with-attributes"), + Expect( + lambda: _build_v2(compressor=None, filters=None), + frozenset(), + id="valid-none-compressor-filters", + ), + Expect( + _mutate(_build_v2, _del("chunks")), + frozenset({("chunks",)}), + id="missing-chunks", + ), + Expect( + _mutate(_build_v2, _set("shape", [1, "x"])), + frozenset({("shape",)}), + id="bad-shape", + ), + Expect( + _mutate(_mutate(_build_v2, _del("chunks")), _set("shape", [1, "x"])), + frozenset({("chunks",), ("shape",)}), + id="missing-chunks-and-bad-shape", + ), +] + +ALL_DOC_CASES = [ + *( + pytest.param( + is_array_metadata_v3, + validate_array_metadata_v3, + parse_array_metadata_v3, + c, + id=f"v3-{c.id}", + ) + for c in V3_DOC_CASES + ), + *( + pytest.param( + is_array_metadata_v2, + validate_array_metadata_v2, + parse_array_metadata_v2, + c, + id=f"v2-{c.id}", + ) + for c in V2_DOC_CASES + ), +] + + +@pytest.mark.parametrize(("is_fn", "validate_fn", "parse_fn", "case"), ALL_DOC_CASES) +def test_array_metadata_guards( + is_fn: Callable[[object], bool], + validate_fn: Callable[[object], list[ValidationProblem]], + parse_fn: Callable[[object], object], + case: Expect[Callable[[], object], frozenset[tuple[str | int, ...]]], +) -> None: + """is_/validate_/parse_ array-metadata guards agree on validity and locs for each case.""" + doc = case.input() + valid = case.output == frozenset() + assert is_fn(doc) is valid + problems = validate_fn(doc) + assert (problems == []) is valid + assert {p.loc for p in problems} >= case.output + if valid: + assert parse_fn(doc) is doc + else: + with pytest.raises(MetadataValidationError): + parse_fn(doc) + + +# --- strict from_json validation ------------------------------------------- + + +FROM_JSON_REJECT_PARAMS = [ + pytest.param( + ZarrV3ArrayMetadata, + ExpectFail(lambda: {"zarr_format": 3}, MetadataValidationError, id="x"), + id="v3-missing-required", + ), + pytest.param( + ZarrV3ArrayMetadata, + ExpectFail(_mutate(_build_v3, _set("data_type", 5)), MetadataValidationError, id="x"), + id="v3-bad-field-type", + ), + pytest.param( + ZarrV2ArrayMetadata, + ExpectFail(lambda: {"zarr_format": 2}, MetadataValidationError, id="x"), + id="v2-missing-required", + ), + pytest.param( + ZarrV3NamedConfig, + ExpectFail(lambda: 5, MetadataValidationError, id="x"), + id="zarr-metadata-bad-input", + ), +] + + +@pytest.mark.parametrize(("model", "case"), FROM_JSON_REJECT_PARAMS) +def test_from_json_rejects_malformed( + model: type[ZarrV3ArrayMetadata | ZarrV2ArrayMetadata | ZarrV3NamedConfig], + case: ExpectFail[Callable[[], object]], +) -> None: + """from_json raises MetadataValidationError on a malformed document.""" + with case.raises(): + model.from_json(case.input()) + + +# --- ValidationProblem / MetadataValidationError / _prefix ----------------- +# Small structural tests β€” not "parametrize over inputs" shaped, kept direct. + + +def test_validation_problem_str_with_loc() -> None: + """ValidationProblem.__str__ renders a non-empty loc as a dotted path.""" + p = ValidationProblem(loc=("codecs", 0, "name"), message="expected str", kind="invalid_type") + assert str(p) == "codecs.0.name: expected str" + + +def test_validation_problem_str_empty_loc() -> None: + """ValidationProblem.__str__ renders an empty loc as .""" + p = ValidationProblem(loc=(), message="not a mapping", kind="invalid_type") + assert str(p) == ": not a mapping" + + +def test_validation_problem_is_frozen() -> None: + """ValidationProblem is immutable (frozen dataclass).""" + p = ValidationProblem(loc=("shape",), message="x", kind="invalid_type") + with pytest.raises(dataclasses.FrozenInstanceError): + # setattr: assigning to a frozen field is an intentional runtime error, + # spelled dynamically so it is not also a static type error. + setattr(p, "message", "y") # noqa: B010 + + +def test_metadata_validation_error_holds_problems() -> None: + """MetadataValidationError carries its problem list and renders them in its message.""" + problems = [ + ValidationProblem(loc=("shape",), message="missing required key", kind="missing_key"), + ValidationProblem( + loc=("data_type",), message="expected a metadata field", kind="invalid_type" + ), + ] + err = MetadataValidationError(problems) + assert err.problems == problems + assert "shape: missing required key" in str(err) + assert "data_type: expected a metadata field" in str(err) + + +def test_prefix_prepends_loc_head() -> None: + """_prefix prepends a loc head to each problem's loc.""" + problems = [ValidationProblem(loc=("name",), message="expected str", kind="invalid_type")] + prefixed = _prefix(0, problems) + assert prefixed == [ + ValidationProblem(loc=(0, "name"), message="expected str", kind="invalid_type") + ] + + +# --- Stricter v2/v3 field validation and error kinds ------------------------- + + +def test_v2_dtype_must_be_string_or_records() -> None: + """A non-string, non-records v2 dtype is rejected with an invalid_type problem.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"dtype": 42} + problems = validate_array_metadata_v2(doc) + assert [(p.loc, p.kind) for p in problems] == [(("dtype",), "invalid_type")] + + +def test_v2_structured_dtype_records_accepted() -> None: + """A structured v2 dtype (field records, optionally nested/shaped) validates.""" + dtype = (("a", " None: + """A field record with the wrong arity is rejected.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"dtype": (("a",),)} + problems = validate_array_metadata_v2(doc) + assert [p.loc for p in problems] == [("dtype",)] + + +def test_v2_order_literal_enforced() -> None: + """An order other than 'C' or 'F' is rejected with an invalid_value problem.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"order": "Q"} + problems = validate_array_metadata_v2(doc) + assert [(p.loc, p.kind) for p in problems] == [(("order",), "invalid_value")] + + +def test_v2_compressor_must_be_codec_or_none() -> None: + """A compressor that is not null or a codec config mapping is rejected.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"compressor": "zlib"} + problems = validate_array_metadata_v2(doc) + assert [(p.loc, p.kind) for p in problems] == [(("compressor",), "invalid_type")] + + +def test_v2_compressor_requires_string_id() -> None: + """A compressor mapping without a string id is rejected.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"compressor": {"level": 3}} + problems = validate_array_metadata_v2(doc) + assert [p.loc for p in problems] == [("compressor",)] + + +def test_v2_filters_must_be_codec_sequence_or_none() -> None: + """Filters that are not null or a sequence of codec configs are rejected.""" + for bad in (7, (5,), "gzip"): + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"filters": bad} + problems = validate_array_metadata_v2(doc) + assert [(p.loc, p.kind) for p in problems] == [(("filters",), "invalid_type")], bad + + +def test_v2_shape_and_chunks_must_have_equal_rank() -> None: + """Raw v2 metadata requires one chunk length per array dimension.""" + doc = dict(ZarrV2ArrayMetadata.create_default(shape=(2, 3)).to_json()) + doc["chunks"] = (1,) + + assert [(p.loc, p.kind) for p in validate_array_metadata_v2(doc)] == [ + (("chunks",), "invalid_value") + ] + with pytest.raises(MetadataValidationError, match="same number of dimensions"): + ZarrV2ArrayMetadata.from_key_value({".zarray": json.dumps(doc).encode()}) + + +def test_v2_filters_must_be_nonempty_when_present() -> None: + """A non-null v2 filter sequence contains one or more codec configurations.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) + doc["filters"] = () + + assert [(p.loc, p.kind) for p in validate_array_metadata_v2(doc)] == [ + (("filters",), "invalid_value") + ] + with pytest.raises(MetadataValidationError, match="at least one filter"): + ZarrV2ArrayMetadata.from_key_value({".zarray": json.dumps(doc).encode()}) + + +def test_v2_dimension_separator_literal_enforced() -> None: + """A dimension_separator other than '.' or '/' is rejected.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"dimension_separator": "-"} + problems = validate_array_metadata_v2(doc) + assert [(p.loc, p.kind) for p in problems] == [(("dimension_separator",), "invalid_value")] + + +def test_v2_zarr_format_literal_enforced() -> None: + """A v2 document claiming zarr_format 3 is rejected with an invalid_value problem.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"zarr_format": 3} + problems = validate_array_metadata_v2(doc) + assert [(p.loc, p.kind) for p in problems] == [(("zarr_format",), "invalid_value")] + + +def test_v3_zarr_format_literal_enforced() -> None: + """A v3 document claiming zarr_format 2 is rejected with an invalid_value problem.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"zarr_format": 2} + problems = validate_array_metadata_v3(doc) + assert [(p.loc, p.kind) for p in problems] == [(("zarr_format",), "invalid_value")] + + +@pytest.mark.parametrize( + ("document", "validate"), + [ + pytest.param( + dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"zarr_format": 2.0}, + validate_array_metadata_v2, + id="v2", + ), + pytest.param( + dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"zarr_format": 3.0}, + validate_array_metadata_v3, + id="v3", + ), + ], +) +def test_array_zarr_format_rejects_float( + document: object, validate: Callable[[object], list[ValidationProblem]] +) -> None: + """Integer-valued floats do not satisfy integer format literals.""" + assert [(p.loc, p.kind) for p in validate(document)] == [(("zarr_format",), "invalid_value")] + + +def test_array_v2_rejects_unknown_document_member() -> None: + """The closed v2 merged-document shape rejects undeclared members.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"unexpected": 1} + + assert [(p.loc, p.kind) for p in validate_array_metadata_v2(doc)] == [ + (("unexpected",), "invalid_value") + ] + + +def test_array_v3_from_json_materializes_abstract_containers() -> None: + """A flexible input mapping becomes the canonical dict/tuple model shape.""" + doc = UserDict(dict(ZarrV3ArrayMetadata.create_default(shape=(2,)).to_json())) + doc["shape"] = range(2) + + model = ZarrV3ArrayMetadata.from_json(doc) + + assert model.shape == (0, 1) + assert type(model.shape) is tuple + + +def test_from_key_value_rejects_non_standard_json_constant() -> None: + """Store JSON decoding rejects JavaScript NaN/Infinity constants.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) + doc["fill_value"] = float("nan") + raw = json.dumps(doc) + + with pytest.raises(MetadataValidationError, match="invalid JSON"): + ZarrV3ArrayMetadata.from_key_value({"zarr.json": raw.encode()}) + + +def test_to_key_value_rejects_non_finite_model_value() -> None: + """Strict encoding prevents directly-constructed models from writing invalid JSON.""" + model = ZarrV3ArrayMetadata.create_default(fill_value=float("nan")) + + with pytest.raises(ValueError, match="JSON compliant"): + model.to_key_value() + + +def test_v3_node_type_literal_enforced() -> None: + """A v3 array document claiming node_type 'group' is rejected.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"node_type": "group"} + problems = validate_array_metadata_v3(doc) + assert [(p.loc, p.kind) for p in problems] == [(("node_type",), "invalid_value")] + + +def test_missing_key_kind_is_machine_readable() -> None: + """A missing required key is distinguishable by kind, without message matching.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) + del doc["chunk_key_encoding"] + problems = validate_array_metadata_v3(doc) + assert problems == [ + ValidationProblem(("chunk_key_encoding",), "missing required key", "missing_key") + ] + + +# --- Unified error channels --------------------------------------------------- + + +def test_from_key_value_invalid_json_raises_metadata_error() -> None: + """Undecodable store bytes raise MetadataValidationError (kind invalid_json), not JSONDecodeError.""" + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV3ArrayMetadata.from_key_value({"zarr.json": b"{not json"}) + assert [p.kind for p in exc_info.value.problems] == ["invalid_json"] + + +def test_from_key_value_invalid_utf8_raises_metadata_error() -> None: + """Invalid UTF-8 store bytes use the same invalid_json error channel.""" + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV3ArrayMetadata.from_key_value({"zarr.json": b"\x80"}) + assert [p.kind for p in exc_info.value.problems] == ["invalid_json"] + + +def test_v2_from_key_value_scalar_root_raises_metadata_error() -> None: + """A scalar .zarray document fails through the unified metadata error channel.""" + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV2ArrayMetadata.from_key_value({".zarray": b"null"}) + assert [(problem.loc, problem.kind) for problem in exc_info.value.problems] == [ + ((), "invalid_type") + ] + + +def test_from_key_value_missing_key_kind() -> None: + """A missing store key surfaces as a missing_key problem at the store-key loc.""" + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV2ArrayMetadata.from_key_value({}) + assert exc_info.value.problems == [ + ValidationProblem((".zarray",), "missing store key", "missing_key") + ] + + +def test_extra_fields_overlap_raises_metadata_error() -> None: + """The extra-fields overlap invariant raises MetadataValidationError (a ValueError).""" + with pytest.raises(MetadataValidationError, match="Extra fields") as exc_info: + ZarrV3ArrayMetadata.create_default(extra_fields={"shape": {"must_understand": False}}) + assert [p.kind for p in exc_info.value.problems] == ["invalid_value"] + + +def test_extension_point_fields_annotated_with_role_alias() -> None: + """Extension-point fields are annotated with ZarrV3MetadataField (the + logical role), not ZarrV3NamedConfig (the current serialized form), so a + future widening of the field union does not move annotation sites.""" + assert ZarrV3MetadataField is ZarrV3NamedConfig + annotations = ZarrV3ArrayMetadata.__annotations__ + for field_name in ("data_type", "chunk_grid", "chunk_key_encoding"): + assert annotations[field_name] == "ZarrV3MetadataField" + for field_name in ("codecs", "storage_transformers"): + assert annotations[field_name] == "tuple[ZarrV3MetadataField, ...]" + + +# --- Adversarial-probe fixes: documents that used to pass validation --------- + + +def test_shape_rejects_json_booleans() -> None: + """JSON booleans are not integers: shape/chunks containing true/false are + rejected (bool is an int subclass in Python, so isinstance alone passes).""" + v3 = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"shape": (True, True)} + assert [p.loc for p in validate_array_metadata_v3(v3)] == [("shape",)] + v2 = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"chunks": (True,)} + assert [p.loc for p in validate_array_metadata_v2(v2)] == [("chunks",)] + + +def test_shape_rejects_negative_dimensions() -> None: + """Dimension lengths must be non-negative; a negative entry is invalid_value.""" + v3 = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"shape": (-1,)} + assert [(p.loc, p.kind) for p in validate_array_metadata_v3(v3)] == [ + (("shape",), "invalid_value") + ] + v2 = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"chunks": (-5,)} + assert [(p.loc, p.kind) for p in validate_array_metadata_v2(v2)] == [ + (("chunks",), "invalid_value") + ] + + +def test_dimension_names_length_must_match_shape() -> None: + """dimension_names must have one entry per dimension of shape.""" + doc = dict(ZarrV3ArrayMetadata.create_default(shape=(10,)).to_json()) | { + "dimension_names": ("x", "y", "z") + } + assert [(p.loc, p.kind) for p in validate_array_metadata_v3(doc)] == [ + (("dimension_names",), "invalid_value") + ] + + +def test_attributes_values_must_be_json() -> None: + """Attribute values are JSON-checked recursively (like fill_value), so a + non-serializable value is a validation problem, not a later TypeError.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"attributes": {"a": {1, 2}}} + problems = validate_array_metadata_v3(doc) + assert [(p.loc, p.kind) for p in problems] == [(("attributes", "a"), "invalid_type")] + + +def test_configuration_values_must_be_json() -> None: + """Configuration values are JSON-checked recursively, so an int-keyed dict + cannot pass validation and be silently rewritten by json.dumps.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) | { + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": {1: 2}}} + } + problems = validate_array_metadata_v3(doc) + assert [(p.loc, p.kind) for p in problems] == [ + (("chunk_grid", "configuration", "chunk_shape"), "invalid_type") + ] + + +def test_v3_extension_keys_must_be_strings() -> None: + """A non-string top-level key cannot be represented by a v3 document type.""" + doc: dict[object, object] = dict(ZarrV3ArrayMetadata.create_default().to_json()) + doc[1] = {"must_understand": False} + assert [(problem.loc, problem.kind) for problem in validate_array_metadata_v3(doc)] == [ + ((), "invalid_type") + ] + + +def test_v3_extension_values_must_be_json() -> None: + """Extension payloads are JSON-checked before a model is constructed.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) + doc["ext"] = {"must_understand": False, "payload": object()} + assert [(problem.loc, problem.kind) for problem in validate_array_metadata_v3(doc)] == [ + (("ext", "payload"), "invalid_type") + ] + + +def test_v3_json_extension_without_waiver_is_preserved_as_must_understand() -> None: + """A JSON extension without an explicit false waiver remains must-understand.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) + doc["ext"] = 1 + parsed = parse_array_metadata_v3(doc) + assert is_array_metadata_v3(parsed) + model = ZarrV3ArrayMetadata.from_json(doc) + assert model.extra_fields["ext"] == 1 + assert model.must_understand_fields == {"ext": 1} + + +def test_v2_codec_configuration_values_must_be_json() -> None: + """Non-JSON codec parameters are rejected for compressors and filters.""" + for field, value, expected_loc in ( + ("compressor", {"id": "x", "payload": object()}, ("compressor", "payload")), + ("filters", ({"id": "x", "payload": object()},), ("filters", 0, "payload")), + ): + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) + doc[field] = value + assert [(problem.loc, problem.kind) for problem in validate_array_metadata_v2(doc)] == [ + (expected_loc, "invalid_type") + ] + + +def test_dimension_sequences_reject_binary_values() -> None: + """Binary buffers are not JSON arrays even though they are integer sequences.""" + v3 = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"shape": b"\x02"} + v2 = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"chunks": b"\x02"} + assert [(problem.loc, problem.kind) for problem in validate_array_metadata_v3(v3)] == [ + (("shape",), "invalid_type") + ] + assert [(problem.loc, problem.kind) for problem in validate_array_metadata_v2(v2)] == [ + (("chunks",), "invalid_type") + ] + + +def test_array_parsers_normalize_json_lists_before_narrowing() -> None: + """Parsers return tuple-backed document types while guards reject raw list forms.""" + v3_raw = json.loads(json.dumps(ZarrV3ArrayMetadata.create_default(shape=(2,)).to_json())) + v2_raw = json.loads(json.dumps(ZarrV2ArrayMetadata.create_default(shape=(2,)).to_json())) + + assert validate_array_metadata_v3(v3_raw) == [] + assert validate_array_metadata_v2(v2_raw) == [] + assert not is_array_metadata_v3(v3_raw) + assert not is_array_metadata_v2(v2_raw) + + v3_parsed = parse_array_metadata_v3(v3_raw) + v2_parsed = parse_array_metadata_v2(v2_raw) + assert isinstance(v3_parsed["shape"], tuple) + assert isinstance(v3_parsed["codecs"], tuple) + assert isinstance(v2_parsed["shape"], tuple) + assert isinstance(v2_parsed["chunks"], tuple) + + +def test_array_guards_reject_noncanonical_nested_json() -> None: + """Document guards cannot narrow values that only parsers can materialize.""" + v3 = dict(ZarrV3ArrayMetadata.create_default().to_json()) + v3["fill_value"] = range(2) + v2 = dict(ZarrV2ArrayMetadata.create_default().to_json()) + v2["fill_value"] = range(2) + + assert not is_array_metadata_v3(v3) + assert not is_array_metadata_v2(v2) + assert parse_array_metadata_v3(v3)["fill_value"] == (0, 1) + assert parse_array_metadata_v2(v2)["fill_value"] == (0, 1) + + +# --- must_understand partition (spec: MUST fail to open unrecognized fields) -- + + +def test_must_understand_fields_partition() -> None: + """must_understand_fields contains every extra field not explicitly waived + with must_understand: false, including implicitly-true and non-mapping + fields, so a reader can discharge the spec's fail-to-open duty by + subtracting the extensions it recognizes.""" + model = ZarrV3ArrayMetadata.create_default( + extra_fields={ + "ext_a": {"name": "a", "must_understand": False}, + "ext_b": {"name": "b"}, + "ext_c": {"name": "c", "must_understand": True}, + "ext_d": 123, + } + ) + assert set(model.must_understand_fields) == {"ext_b", "ext_c", "ext_d"} + recognized = {"ext_b"} + assert model.must_understand_fields.keys() - recognized == {"ext_c", "ext_d"} + + +def test_must_understand_fields_empty_when_all_waived() -> None: + """must_understand_fields is empty when every extra field is explicitly waived.""" + model = ZarrV3ArrayMetadata.create_default( + extra_fields={"ext_a": {"name": "a", "must_understand": False}} + ) + assert model.must_understand_fields == {} + + +def test_dimension_names_null_field_rejected() -> None: + """A dimension_names field whose VALUE is null is invalid: the spec permits + null as an element (an unnamed dimension), never as the field value β€” "not + specified" is spelled by omitting the key. Consumers bridging from an + in-memory None sentinel must drop the key, not write null.""" + doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"dimension_names": None} + problems = validate_array_metadata_v3(doc) + assert [(p.loc, p.kind) for p in problems] == [(("dimension_names",), "invalid_type")] + # and the model's own None spelling correctly maps to key absence + assert ( + "dimension_names" not in ZarrV3ArrayMetadata.create_default(dimension_names=UNSET).to_json() + ) + + +# --- create_default derives the chunk grid from shape ------------------------ + + +def test_v3_create_default_chunk_grid_follows_shape() -> None: + """Overriding shape without chunk_grid derives a consistent default grid: + one chunk covering the array (chunk_shape == shape), instead of silently + keeping the scalar default's 0-d grid.""" + model = ZarrV3ArrayMetadata.create_default(shape=(100, 100)) + assert model.chunk_grid == ZarrV3NamedConfig( + name="regular", configuration={"chunk_shape": (100, 100)} + ) + + +def test_v3_create_default_explicit_chunk_grid_respected() -> None: + """An explicit chunk_grid override wins over the shape-derived default.""" + grid = ZarrV3NamedConfig(name="regular", configuration={"chunk_shape": (10, 10)}) + model = ZarrV3ArrayMetadata.create_default(shape=(100, 100), chunk_grid=grid) + assert model.chunk_grid == grid + + +def test_v2_create_default_chunks_follow_shape() -> None: + """Overriding shape without chunks derives chunks == shape.""" + model = ZarrV2ArrayMetadata.create_default(shape=(100, 100)) + assert model.chunks == (100, 100) + + +def test_v2_create_default_explicit_chunks_respected() -> None: + """An explicit chunks override wins over the shape-derived default.""" + model = ZarrV2ArrayMetadata.create_default(shape=(100, 100), chunks=(10, 10)) + assert model.chunks == (10, 10) + + +def test_v3_create_default_zero_length_dimensions() -> None: + """chunk_shape == shape is spec-sound even with zero-length dimensions: + 'The chunk shape elements are non-zero when the corresponding dimensions + of the arrays have non-zero length' β€” the constraint is conditional, so a + zero chunk length is permitted exactly where the dimension is empty.""" + model = ZarrV3ArrayMetadata.create_default(shape=(0, 3)) + assert model.chunk_grid.configuration["chunk_shape"] == (0, 3) + + +def test_create_default_derivation_is_one_way() -> None: + """Overriding the chunk grid (v3) or chunks (v2) without shape leaves the + scalar default shape=() untouched: a user-supplied chunk_grid is an + extension point taken verbatim, and deriving shape from it would require + interpreting grid configurations, which the model layer never does.""" + grid = ZarrV3NamedConfig(name="regular", configuration={"chunk_shape": (10, 10)}) + v3 = ZarrV3ArrayMetadata.create_default(chunk_grid=grid) + assert v3.shape == () + assert v3.chunk_grid == grid + v2 = ZarrV2ArrayMetadata.create_default(chunks=(10, 10)) + assert v2.shape == () + assert v2.chunks == (10, 10) + + +# --- v2 dimension_separator default (roborev job 426) ------------------------- + + +def test_v2_absent_dimension_separator_means_dot() -> None: + """A .zarray that omits dimension_separator uses the v2 convention default + '.', not '/': chunk keys of real-world default-separator v2 arrays look + like '0.0'. The model normalizes the absent key to an explicit '.' β€” a + semantics-preserving spelling normalization.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) + del doc["dimension_separator"] + model = ZarrV2ArrayMetadata.from_json(doc) + assert model.dimension_separator == "." + assert model.to_json()["dimension_separator"] == "." + + +def test_v2_from_key_value_without_separator_means_dot() -> None: + """The .zarray store-file path applies the same '.' default for an absent + dimension_separator key.""" + doc = { + k: v + for k, v in ZarrV2ArrayMetadata.create_default().to_json().items() + if k not in ("dimension_separator", "attributes") + } + import json as _json + + model = ZarrV2ArrayMetadata.from_key_value({".zarray": _json.dumps(doc).encode()}) + assert model.dimension_separator == "." + + +def test_v2_null_dimension_separator_rejected() -> None: + """dimension_separator may be absent, '.', or '/' β€” never null: the + document grammar has no null spelling for this field.""" + doc = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"dimension_separator": None} + problems = validate_array_metadata_v2(doc) + assert [(p.loc, p.kind) for p in problems] == [(("dimension_separator",), "invalid_value")] + + +def test_dimension_names_absent_and_all_null_are_distinct() -> None: + """An absent dimension_names field and an explicit all-null one are + semantically different documents: the explicit form says every dimension + has a name, which is null; absence says there are no dimension names. + The model preserves the distinction (UNSET vs a tuple of Nones), and both + spellings round-trip faithfully.""" + absent_doc = dict(ZarrV3ArrayMetadata.create_default(shape=(2, 3)).to_json()) + explicit_doc = absent_doc | {"dimension_names": (None, None)} + + absent = ZarrV3ArrayMetadata.from_json(absent_doc) + explicit = ZarrV3ArrayMetadata.from_json(explicit_doc) + + assert absent.dimension_names is UNSET + assert explicit.dimension_names == (None, None) + assert absent != explicit + assert "dimension_names" not in absent.to_json() + assert absent.to_json() == absent_doc + assert explicit.to_json() == explicit_doc diff --git a/packages/zarr-metadata/tests/model/test_group.py b/packages/zarr-metadata/tests/model/test_group.py new file mode 100644 index 0000000000..4b8c22b84d --- /dev/null +++ b/packages/zarr-metadata/tests/model/test_group.py @@ -0,0 +1,572 @@ +"""Tests for the group and consolidated metadata models in `zarr_metadata.model`.""" + +import copy +import dataclasses +import json +from collections import UserDict +from collections.abc import Callable + +import pytest + +from tests.model._cases import mutate_nested_containers +from zarr_metadata.model import UNSET +from zarr_metadata.model._array import ZarrV3ArrayMetadata +from zarr_metadata.model._group import ( + ZarrV2ConsolidatedMetadata, + ZarrV2GroupMetadata, + ZarrV2GroupMetadataPartial, + ZarrV3ConsolidatedMetadata, + ZarrV3GroupMetadata, + ZarrV3GroupMetadataPartial, +) +from zarr_metadata.model._validation import ( + MetadataValidationError, + ValidationProblem, + is_group_metadata_v2, + is_group_metadata_v3, + parse_group_metadata_v2, + parse_group_metadata_v3, + validate_group_metadata_v2, + validate_group_metadata_v3, +) + +# --- ZarrV3GroupMetadata --------------------------------------------------- + + +def test_group_v3_roundtrip() -> None: + """A v3 group document round-trips through the model unchanged.""" + doc = {"zarr_format": 3, "node_type": "group", "attributes": {"a": (1, 2)}} + model = ZarrV3GroupMetadata.from_json(doc) + assert model.to_json() == doc + + +def test_group_v3_omits_empty_attributes() -> None: + """to_json omits the attributes key when attributes is empty.""" + model = ZarrV3GroupMetadata.create_default() + assert "attributes" not in model.to_json() + + +def test_group_v3_lists_become_tuples() -> None: + """from_json converts JSON arrays in attributes to tuples.""" + doc = {"zarr_format": 3, "node_type": "group", "attributes": {"a": [1, 2]}} + model = ZarrV3GroupMetadata.from_json(doc) + assert model.attributes == {"a": (1, 2)} + + +def test_group_v3_extra_fields_roundtrip() -> None: + """Unknown top-level keys land in extra_fields and reappear in to_json.""" + doc = { + "zarr_format": 3, + "node_type": "group", + "my_extension": {"name": "thing", "must_understand": False}, + } + model = ZarrV3GroupMetadata.from_json(doc) + assert model.extra_fields == {"my_extension": {"name": "thing", "must_understand": False}} + assert model.to_json() == doc + + +def test_group_v3_json_extra_field_roundtrips_as_must_understand() -> None: + """A non-object extra field is preserved and implicitly requires understanding.""" + doc = {"zarr_format": 3, "node_type": "group", "ext": [1, 2]} + model = ZarrV3GroupMetadata.from_json(doc) + assert model.to_json()["ext"] == (1, 2) + assert model.must_understand_fields == {"ext": (1, 2)} + + +def test_group_v3_extra_fields_overlap_rejected() -> None: + """Constructing a v3 group model with extra_fields shadowing a standard key raises.""" + with pytest.raises(ValueError, match="Extra fields"): + ZarrV3GroupMetadata( + attributes={}, + consolidated_metadata=UNSET, + extra_fields={"node_type": {"name": "x", "must_understand": False}}, + ) + + +def test_group_v3_consolidated_extra_field_rejected() -> None: + """extra_fields may not shadow the consolidated_metadata convention key.""" + with pytest.raises(ValueError, match="Extra fields"): + ZarrV3GroupMetadata( + attributes={}, + consolidated_metadata=UNSET, + extra_fields={"consolidated_metadata": {"name": "x", "must_understand": False}}, + ) + + +def test_group_v3_missing_required_key() -> None: + """parse_group_metadata_v3 reports each missing required key.""" + with pytest.raises(MetadataValidationError, match="node_type"): + parse_group_metadata_v3({"zarr_format": 3}) + + +def test_group_v3_bad_attributes() -> None: + """parse_group_metadata_v3 rejects a non-mapping attributes value.""" + with pytest.raises(MetadataValidationError, match="attributes"): + parse_group_metadata_v3({"zarr_format": 3, "node_type": "group", "attributes": 5}) + + +@pytest.mark.parametrize( + ("document", "validate"), + [ + pytest.param( + {"zarr_format": 2.0}, + validate_group_metadata_v2, + id="v2", + ), + pytest.param( + {"zarr_format": 3.0, "node_type": "group"}, + validate_group_metadata_v3, + id="v3", + ), + ], +) +def test_group_zarr_format_rejects_float( + document: object, validate: Callable[[object], list[ValidationProblem]] +) -> None: + """Integer-valued floats do not satisfy integer format literals.""" + assert [(p.loc, p.kind) for p in validate(document)] == [(("zarr_format",), "invalid_value")] + + +def test_group_v2_rejects_unknown_document_member() -> None: + """The closed v2 merged-document shape rejects undeclared members.""" + assert [(p.loc, p.kind) for p in validate_group_metadata_v2({"zarr_format": 2, "x": 1})] == [ + (("x",), "invalid_value") + ] + + +@pytest.mark.parametrize( + ("parse", "document"), + [ + pytest.param(parse_group_metadata_v2, {"zarr_format": 2}, id="v2"), + pytest.param( + parse_group_metadata_v3, + {"zarr_format": 3, "node_type": "group"}, + id="v3", + ), + ], +) +def test_group_parser_materializes_abstract_mapping( + parse: Callable[[object], object], document: dict[str, object] +) -> None: + """A successful group parser always returns the declared concrete TypedDict shape.""" + parsed = parse(UserDict(document)) + + assert type(parsed) is dict + assert parsed == document + + +def test_group_guards_reject_noncanonical_nested_json() -> None: + """Document guards cannot narrow values that only parsers can materialize.""" + v3 = {"zarr_format": 3, "node_type": "group", "extension": range(2)} + v2 = {"zarr_format": 2, "attributes": {"values": range(2)}} + + assert not is_group_metadata_v3(v3) + assert not is_group_metadata_v2(v2) + assert parse_group_metadata_v3(v3)["extension"] == (0, 1) + assert parse_group_metadata_v2(v2)["attributes"] == {"values": (0, 1)} + + +def test_group_v3_extension_fields_are_validated() -> None: + """Group extension payloads must be JSON values with a must-understand flag.""" + doc = { + "zarr_format": 3, + "node_type": "group", + "ext": {"must_understand": False, "payload": object()}, + } + assert [(problem.loc, problem.kind) for problem in validate_group_metadata_v3(doc)] == [ + (("ext", "payload"), "invalid_type") + ] + + +def test_group_v3_key_value_roundtrip() -> None: + """from_key_value(to_key_value()) is the identity for v3 groups.""" + model = ZarrV3GroupMetadata.create_default(attributes={"a": 1}) + assert ZarrV3GroupMetadata.from_key_value(model.to_key_value()) == model + + +def test_group_v3_update() -> None: + """update replaces the given fields and returns a new instance.""" + base = ZarrV3GroupMetadata.create_default() + updated = base.update(attributes={"a": 1}) + assert updated.attributes == {"a": 1} + assert base.attributes == {} + + +# --- ZarrV2GroupMetadata --------------------------------------------------- + + +def test_group_v2_key_value_split() -> None: + """v2 to_key_value writes .zgroup and .zattrs; from_key_value merges them.""" + model = ZarrV2GroupMetadata.create_default(attributes={"a": 1}) + kv = model.to_key_value() + assert set(kv) == {".zgroup", ".zattrs"} + assert json.loads(kv[".zgroup"]) == {"zarr_format": 2} + assert ZarrV2GroupMetadata.from_key_value(kv) == model + + +@pytest.mark.parametrize("extra_key", ["attributes", "vendor_extension"]) +def test_v2_group_from_key_value_rejects_zgroup_extra_members(extra_key: str) -> None: + """Raw `.zgroup` documents reject every non-spec member.""" + doc: dict[str, object] = {"zarr_format": 2, extra_key: {}} + + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV2GroupMetadata.from_key_value({".zgroup": json.dumps(doc).encode()}) + + assert [(problem.loc, problem.kind) for problem in exc_info.value.problems] == [ + ((extra_key,), "invalid_value") + ] + + +def test_group_v2_zattrs_presence_round_trips() -> None: + """A v2 group with no .zattrs file parses with UNSET attributes and emits + no .zattrs; an explicit empty .zattrs stays a file β€” the stores remain + distinct through a round-trip.""" + absent = ZarrV2GroupMetadata.from_key_value({".zgroup": b'{"zarr_format": 2}'}) + assert absent.attributes is UNSET + assert ".zattrs" not in absent.to_key_value() + explicit = ZarrV2GroupMetadata.from_key_value( + {".zgroup": b'{"zarr_format": 2}', ".zattrs": b"{}"} + ) + assert explicit.attributes == {} + assert ".zattrs" in explicit.to_key_value() + assert absent != explicit + + +def test_group_v2_json_roundtrip() -> None: + """A merged-form v2 group document round-trips through the model unchanged.""" + doc = {"zarr_format": 2, "attributes": {"a": 1}} + model = ZarrV2GroupMetadata.from_json(doc) + assert model.to_json() == doc + + +def test_group_v2_omits_empty_attributes() -> None: + """to_json omits the attributes key when attributes is empty.""" + assert "attributes" not in ZarrV2GroupMetadata.create_default().to_json() + + +def test_group_v2_not_a_mapping() -> None: + """parse_group_metadata_v2 rejects a non-mapping document.""" + with pytest.raises(MetadataValidationError, match="expected a mapping"): + parse_group_metadata_v2([1, 2, 3]) + + +def test_group_v2_missing_required_key() -> None: + """parse_group_metadata_v2 reports a missing zarr_format key.""" + with pytest.raises(MetadataValidationError, match="zarr_format"): + parse_group_metadata_v2({}) + + +# --- Partial TypedDict drift guards ----------------------------------------- + + +def test_group_partial_keys_match_settable_model_fields() -> None: + """Each group partial TypedDict must list exactly the settable model fields. + + Guards against drift: adding/removing a settable field on a group model + without updating its `*Partial` TypedDict fails here. + """ + for model_cls, partial_cls in ( + (ZarrV3GroupMetadata, ZarrV3GroupMetadataPartial), + (ZarrV2GroupMetadata, ZarrV2GroupMetadataPartial), + ): + settable = {f.name for f in dataclasses.fields(model_cls) if f.init} + assert set(partial_cls.__annotations__) == settable + + +# --- ZarrV3ConsolidatedMetadata -------------------------------------------- + + +def test_consolidated_v3_roundtrip() -> None: + """A v3 group with inline consolidated metadata round-trips, with child + entries parsed into array/group models.""" + child = ZarrV3ArrayMetadata.create_default(shape=(2,)).to_json() + doc = { + "zarr_format": 3, + "node_type": "group", + "consolidated_metadata": { + "kind": "inline", + "must_understand": False, + "metadata": {"a": child, "g": {"zarr_format": 3, "node_type": "group"}}, + }, + } + model = ZarrV3GroupMetadata.from_json(doc) + assert isinstance(model.consolidated_metadata, ZarrV3ConsolidatedMetadata) + assert isinstance(model.consolidated_metadata.metadata["a"], ZarrV3ArrayMetadata) + assert isinstance(model.consolidated_metadata.metadata["g"], ZarrV3GroupMetadata) + assert model.to_json() == doc + + +def test_consolidated_v3_must_understand_true_rejected() -> None: + """ZarrV3ConsolidatedMetadata enforces must_understand=False at runtime.""" + with pytest.raises(ValueError, match="must_understand"): + ZarrV3ConsolidatedMetadata(must_understand=True, metadata={}) + + +def test_consolidated_v3_from_json_must_understand_true_rejected() -> None: + """from_json rejects a consolidated document carrying must_understand=true.""" + with pytest.raises(MetadataValidationError, match="must_understand"): + ZarrV3ConsolidatedMetadata.from_json( + {"kind": "inline", "must_understand": True, "metadata": {}} + ) + + +def test_consolidated_v3_entry_without_node_type_rejected() -> None: + """from_json rejects a consolidated entry lacking a recognizable node_type.""" + with pytest.raises(MetadataValidationError, match="node_type"): + ZarrV3ConsolidatedMetadata.from_json( + {"kind": "inline", "must_understand": False, "metadata": {"a": {"zarr_format": 3}}} + ) + + +def test_consolidated_v3_not_a_mapping() -> None: + """from_json rejects a non-mapping consolidated document.""" + with pytest.raises(MetadataValidationError, match="expected a mapping"): + ZarrV3ConsolidatedMetadata.from_json(5) + + +# --- ZarrV2ConsolidatedMetadata -------------------------------------------- + + +def test_consolidated_v2_verbatim_roundtrip() -> None: + """The v2 .zmetadata model holds the flat file-keyed map verbatim, + including nodes that have no .zattrs entry.""" + doc = { + "zarr_consolidated_format": 1, + "metadata": { + ".zgroup": {"zarr_format": 2}, + "a/.zarray": { + "zarr_format": 2, + "shape": (2,), + "chunks": (2,), + "dtype": "|u1", + "fill_value": 0, + "order": "C", + "compressor": None, + "filters": None, + }, + }, + } + model = ZarrV2ConsolidatedMetadata.from_json(doc) + assert model.to_json() == doc + + +def test_consolidated_v2_key_value_roundtrip() -> None: + """from_key_value(to_key_value()) is the identity for .zmetadata documents.""" + model = ZarrV2ConsolidatedMetadata.from_json( + {"zarr_consolidated_format": 1, "metadata": {".zgroup": {"zarr_format": 2}}} + ) + assert ZarrV2ConsolidatedMetadata.from_key_value(model.to_key_value()) == model + + +def test_consolidated_v2_lists_become_tuples() -> None: + """from_json converts JSON arrays inside entries to tuples.""" + doc = { + "zarr_consolidated_format": 1, + "metadata": {"a/.zarray": {"shape": [2, 3]}}, + } + model = ZarrV2ConsolidatedMetadata.from_json(doc) + assert model.metadata == {"a/.zarray": {"shape": (2, 3)}} + + +def test_consolidated_v2_envelope_validation() -> None: + """from_json rejects a .zmetadata document missing the metadata key.""" + with pytest.raises(MetadataValidationError, match="metadata"): + ZarrV2ConsolidatedMetadata.from_json({"zarr_consolidated_format": 1}) + + +def test_consolidated_v2_not_a_mapping() -> None: + """from_json rejects a non-mapping .zmetadata document.""" + with pytest.raises(MetadataValidationError, match="expected a mapping"): + ZarrV2ConsolidatedMetadata.from_json([1]) + + +def test_consolidated_v2_format_literal_enforced() -> None: + """A .zmetadata document must declare consolidated format 1.""" + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV2ConsolidatedMetadata.from_json({"zarr_consolidated_format": 2, "metadata": {}}) + assert [(problem.loc, problem.kind) for problem in exc_info.value.problems] == [ + (("zarr_consolidated_format",), "invalid_value") + ] + + +def test_consolidated_v2_metadata_values_must_be_json() -> None: + """Non-JSON values in the flat metadata map are rejected during ingestion.""" + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV2ConsolidatedMetadata.from_json( + {"zarr_consolidated_format": 1, "metadata": {".zgroup": object()}} + ) + assert [(problem.loc, problem.kind) for problem in exc_info.value.problems] == [ + (("metadata", ".zgroup"), "invalid_type") + ] + + +def test_group_v2_from_key_value_scalar_root_raises_metadata_error() -> None: + """A scalar .zgroup document fails through the unified metadata error channel.""" + with pytest.raises(MetadataValidationError) as exc_info: + ZarrV2GroupMetadata.from_key_value({".zgroup": b"null"}) + assert [(problem.loc, problem.kind) for problem in exc_info.value.problems] == [ + ((), "invalid_type") + ] + + +# --- Literal-value enforcement ----------------------------------------------- + + +def test_group_v3_literals_enforced() -> None: + """A v3 group doc with wrong zarr_format or node_type is rejected with invalid_value.""" + base = ZarrV3GroupMetadata.create_default().to_json() + for key, bad in (("zarr_format", 2), ("node_type", "array")): + problems = validate_group_metadata_v3(dict(base) | {key: bad}) + assert [(p.loc, p.kind) for p in problems] == [((key,), "invalid_value")], key + + +def test_group_v2_zarr_format_literal_enforced() -> None: + """A v2 group doc claiming zarr_format 3 is rejected with invalid_value.""" + problems = validate_group_metadata_v2({"zarr_format": 3}) + assert [(p.loc, p.kind) for p in problems] == [(("zarr_format",), "invalid_value")] + + +# --- Consolidated envelope validated by the group validator ------------------ + + +def test_group_v3_validator_agrees_with_from_json_on_consolidated() -> None: + """The group validator validates the consolidated envelope and entries, so + is_group_metadata_v3 never vouches for a document from_json would reject.""" + bad_docs = ( + # empty envelope: missing kind/must_understand/metadata + {"zarr_format": 3, "node_type": "group", "consolidated_metadata": {}}, + # entry without a recognizable node_type + { + "zarr_format": 3, + "node_type": "group", + "consolidated_metadata": { + "kind": "inline", + "must_understand": False, + "metadata": {"a": {"zarr_format": 3}}, + }, + }, + # must_understand: true + { + "zarr_format": 3, + "node_type": "group", + "consolidated_metadata": { + "kind": "inline", + "must_understand": True, + "metadata": {}, + }, + }, + ) + for doc in bad_docs: + assert validate_group_metadata_v3(doc) != [], doc + with pytest.raises(MetadataValidationError): + ZarrV3GroupMetadata.from_json(doc) + + +def test_group_v3_valid_consolidated_passes_validator() -> None: + """A well-formed consolidated group validates cleanly (control case).""" + child = ZarrV3ArrayMetadata.create_default(shape=(2,)).to_json() + doc = { + "zarr_format": 3, + "node_type": "group", + "consolidated_metadata": { + "kind": "inline", + "must_understand": False, + "metadata": {"a": child, "g": {"zarr_format": 3, "node_type": "group"}}, + }, + } + assert validate_group_metadata_v3(doc) == [] + + +def test_v3_consolidated_rejects_unknown_envelope_member() -> None: + """The inline consolidated envelope is closed and never drops accepted members.""" + doc = { + "kind": "inline", + "must_understand": False, + "metadata": {}, + "unexpected": 1, + } + + with pytest.raises(MetadataValidationError, match="unexpected"): + ZarrV3ConsolidatedMetadata.from_json(doc) + + +def test_v2_consolidated_rejects_unknown_document_member() -> None: + """The v2 consolidated document is closed and never drops accepted members.""" + doc = {"zarr_consolidated_format": 1, "metadata": {}, "unexpected": 1} + + with pytest.raises(MetadataValidationError, match="unexpected"): + ZarrV2ConsolidatedMetadata.from_json(doc) + + +# --- must_understand partition ------------------------------------------------ + + +def test_group_must_understand_fields_partition() -> None: + """The group model partitions extra fields by the spec's implicit-true rule, + like the array model.""" + model = ZarrV3GroupMetadata.create_default( + extra_fields={ + "waived": {"name": "w", "must_understand": False}, + "implicit": {"name": "i"}, + } + ) + assert set(model.must_understand_fields) == {"implicit"} + + +def test_group_v3_null_consolidated_metadata_repaired_to_absence() -> None: + """consolidated_metadata: null was written by a historical zarr-python bug. + Those stores must remain readable, but the bug spelling is not honored: + it is read as absence (UNSET) and never written back β€” the round-trip + deliberately repairs the document rather than preserving the bug.""" + null_doc = {"zarr_format": 3, "node_type": "group", "consolidated_metadata": None} + assert validate_group_metadata_v3(null_doc) == [] + model = ZarrV3GroupMetadata.from_json(null_doc) + assert model.consolidated_metadata is UNSET + assert "consolidated_metadata" not in model.to_json() + assert model == ZarrV3GroupMetadata.from_json({"zarr_format": 3, "node_type": "group"}) + + +# --- to_json shares no mutable state with the model ------------------------ + +TO_JSON_NO_ALIASING_PARAMS = [ + pytest.param( + ZarrV3GroupMetadata.create_default( + attributes={"a": {"b": [1]}}, + consolidated_metadata=ZarrV3ConsolidatedMetadata( + metadata={ + "child": ZarrV3ArrayMetadata.create_default(attributes={"x": {"y": 1}}), + "grp": ZarrV3GroupMetadata.create_default(attributes={"x": {"y": 1}}), + } + ), + extra_fields={"ext": {"must_understand": False, "cfg": {"x": [1]}}}, + ), + id="v3-group", + ), + pytest.param( + ZarrV2GroupMetadata.create_default(attributes={"a": {"b": [1]}}), + id="v2-group", + ), + pytest.param( + ZarrV3ConsolidatedMetadata( + metadata={"child": ZarrV3ArrayMetadata.create_default(attributes={"x": {"y": 1}})} + ), + id="v3-consolidated", + ), + pytest.param( + ZarrV2ConsolidatedMetadata(metadata={"a/.zarray": {"nested": {"x": [1]}}}), + id="v2-consolidated", + ), +] + + +@pytest.mark.parametrize("model", TO_JSON_NO_ALIASING_PARAMS) +def test_to_json_shares_no_mutable_state_with_model( + model: ZarrV3GroupMetadata + | ZarrV2GroupMetadata + | ZarrV3ConsolidatedMetadata + | ZarrV2ConsolidatedMetadata, +) -> None: + """Mutating a document returned by to_json leaves the model unchanged.""" + baseline = copy.deepcopy(model.to_json()) + mutate_nested_containers(model.to_json()) + assert model.to_json() == baseline diff --git a/packages/zarr-metadata/tests/model/test_pydantic.py b/packages/zarr-metadata/tests/model/test_pydantic.py new file mode 100644 index 0000000000..e5714bb8fb --- /dev/null +++ b/packages/zarr-metadata/tests/model/test_pydantic.py @@ -0,0 +1,302 @@ +"""Executable example: integrating the metadata models with pydantic (v2). + +Pydantic's native dataclass introspection CAN be made to work (see +`test_native_dataclass_introspection_is_possible_but_diverges`): the models +keep their annotation-only imports behind `TYPE_CHECKING`, so a bare +`TypeAdapter(ZarrV3ArrayMetadata)` raises `class-not-fully-defined`, but +`rebuild(_types_namespace=...)` with the names supplied resolves the schema. +It is still the wrong tool: it validates the MODEL SHAPE, not the DOCUMENT β€” +no `from_json` normalization (a bare-string `data_type` is rejected), and +pydantic's lax coercion silently re-opens holes the library's validators +close (`shape=[True, -5]` coerces to `(1, -5)`; a wrong `dimension_names` +count passes). The recommended integration delegates wholesale β€” treat the +model as an opaque value: + +- `InstanceOf` makes pydantic's core schema an is-instance check (no field + introspection), +- validation goes through `from_json` (the single source of truth for what + a well-formed document is, including normalization: bare-string metadata + fields, arrays-to-tuples), +- serialization goes through `to_json` (the canonical document form). + +`MetadataValidationError` subclasses `ValueError`, so pydantic converts a +failed parse into its own `ValidationError` with the loc-annotated problem +messages intact. +""" + +from collections.abc import Mapping +from typing import Annotated, Generic, TypeVar + +import pytest +from pydantic import ( + BaseModel, + BeforeValidator, + ConfigDict, + InstanceOf, + PlainSerializer, + PydanticSchemaGenerationError, + PydanticUserError, + TypeAdapter, + ValidationError, + model_validator, +) + +from zarr_metadata import JSONValue +from zarr_metadata.model import ZarrV3ArrayMetadata, ZarrV3NamedConfig + +# --- the integration (this is the example) ----------------------------------- + + +def _as_array_metadata_v3(value: object) -> ZarrV3ArrayMetadata: + """Accept an existing model instance or a raw metadata document.""" + if isinstance(value, ZarrV3ArrayMetadata): + return value + return ZarrV3ArrayMetadata.from_json(value) + + +# return_type is explicit because to_json's own annotation (`ZarrV3ArrayMetadataJSON`) +# is a TYPE_CHECKING-only name pydantic cannot resolve at runtime. +ArrayMetadataV3Field = Annotated[ + InstanceOf[ZarrV3ArrayMetadata], + BeforeValidator(_as_array_metadata_v3), + PlainSerializer(ZarrV3ArrayMetadata.to_json, return_type=dict), +] +"""A pydantic-ready field type for v3 array metadata. + +Validates raw documents via `from_json`, passes model instances through, +and serializes to the canonical document form via `to_json`. +""" + + +class ArrayManifest(BaseModel): + """Example consumer model: a named array with its metadata document.""" + + path: str + metadata: ArrayMetadataV3Field + + +# --- tests pinning the example ------------------------------------------------ + +VALID_DOC = { + "zarr_format": 3, + "node_type": "array", + "shape": [10], + "data_type": "uint8", + "fill_value": 0, + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": [5]}}, + "chunk_key_encoding": {"name": "default"}, + "codecs": [{"name": "bytes"}], +} + + +def test_raw_document_is_validated_into_a_model() -> None: + """A raw metadata document on a pydantic field is parsed by from_json, + with the library's normalization applied (tuples, canonical field form).""" + manifest = ArrayManifest.model_validate({"path": "a/b", "metadata": VALID_DOC}) + assert isinstance(manifest.metadata, ZarrV3ArrayMetadata) + assert manifest.metadata.shape == (10,) + assert manifest.metadata.data_type.name == "uint8" + + +def test_model_instance_passes_through() -> None: + """An already-constructed model instance is accepted unchanged.""" + model = ZarrV3ArrayMetadata.from_json(VALID_DOC) + manifest = ArrayManifest(path="a/b", metadata=model) + assert manifest.metadata is model + + +def test_invalid_document_surfaces_problems_in_validation_error() -> None: + """A structurally-invalid document fails pydantic validation, carrying the + loc-annotated problem messages from MetadataValidationError.""" + doc = dict(VALID_DOC) + del doc["chunk_key_encoding"] + with pytest.raises(ValidationError) as exc_info: + ArrayManifest.model_validate({"path": "a/b", "metadata": doc}) + assert "chunk_key_encoding: missing required key" in str(exc_info.value) + + +def test_dump_emits_canonical_document() -> None: + """model_dump serializes the field via to_json β€” the canonical document, + not pydantic's field-by-field view of the dataclass.""" + manifest = ArrayManifest.model_validate({"path": "a/b", "metadata": VALID_DOC}) + dumped = manifest.model_dump() + assert dumped["metadata"] == manifest.metadata.to_json() + # Empty configurations use the extension-definition shorthand form. + assert dumped["metadata"]["data_type"] == "uint8" + + +def test_json_roundtrip_through_pydantic() -> None: + """model_dump_json output re-validates to an equal manifest (JSON emits + tuples as arrays; from_json converts them back).""" + manifest = ArrayManifest.model_validate({"path": "a/b", "metadata": VALID_DOC}) + revived = ArrayManifest.model_validate_json(manifest.model_dump_json()) + assert revived == manifest + + +def test_type_adapter_standalone() -> None: + """The annotated alias also works without a BaseModel, via TypeAdapter.""" + adapter = TypeAdapter(ArrayMetadataV3Field) + model = adapter.validate_python(VALID_DOC) + assert isinstance(model, ZarrV3ArrayMetadata) + assert adapter.dump_python(model) == model.to_json() + + +# --- the road not taken: native dataclass introspection ---------------------- + + +def test_native_dataclass_introspection_is_not_supported() -> None: + """Pydantic cannot field-introspect the model dataclasses: the UNSET + sentinel (PEP 661, typing_extensions.Sentinel) in the optional-field + annotations has no pydantic schema (as of pydantic 2.13), so even the + rebuild-with-namespace recipe fails. Introspection was already the wrong + tool before the sentinel existed β€” it validated the model shape rather + than the document, and its lax coercion re-opened validator holes (e.g. + shape=[True, -5] coerced to (1, -5)) β€” so the delegation patterns above + are the only supported integrations. If this test ever fails because + pydantic learned to handle sentinels, revisit whether the introspection + path needs its divergences documented again.""" + from zarr_metadata._common import JSONValue + from zarr_metadata.model import UNSET + from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON + from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON, ZarrV3ExtensionField + + def build_and_use() -> None: + adapter = TypeAdapter(ZarrV3ArrayMetadata) + adapter.rebuild( + force=True, + _types_namespace={ + "JSONValue": JSONValue, + "ZarrV3ExtensionField": ZarrV3ExtensionField, + "ZarrV3MetadataFieldJSON": ZarrV3MetadataFieldJSON, + "ZarrV3ArrayMetadataJSON": ZarrV3ArrayMetadataJSON, + "ZarrV3NamedConfig": ZarrV3NamedConfig, + "ZarrV3MetadataField": ZarrV3NamedConfig, + "UNSET": UNSET, + }, + ) + adapter.validate_python({}) + + with pytest.raises((AttributeError, PydanticSchemaGenerationError, PydanticUserError)): + build_and_use() + + +# --- a first-class pydantic model, engine-backed (the pydantic-zarr pattern) -- +# +# When a consumer wants a real BaseModel β€” JSON schema generation, and +# generics for typed attributes, as in pydantic-zarr's ArraySpec β€” the model +# fields are pydantic-native, but validation and serialization still route +# through the library: a mode="before" validator canonicalizes every input +# document with from_json(...).to_json(), so the structural validators and +# normalization run BEFORE pydantic parses fields (no coercion divergence), +# and the document form is the bridge in both directions. + +AttrsT = TypeVar("AttrsT") + + +class NamedConfig(BaseModel): + """Pydantic mirror of a normalized metadata extension envelope.""" + + name: str + configuration: dict[str, JSONValue] = {} + must_understand: bool = True + + +class ArrayMetadataV3Spec(BaseModel, Generic[AttrsT]): + """A pydantic-native, attribute-typed view of a v3 array metadata document. + + The library is the engine: every input is canonicalized and structurally + validated by `ZarrV3ArrayMetadata.from_json` before pydantic sees the + fields, and `to_document` / `to_metadata_model` emit through the library. + """ + + model_config = ConfigDict(frozen=True) + + zarr_format: int = 3 + node_type: str = "array" + shape: tuple[int, ...] + data_type: NamedConfig + chunk_grid: NamedConfig + chunk_key_encoding: NamedConfig + fill_value: JSONValue + codecs: tuple[NamedConfig, ...] + attributes: AttrsT + dimension_names: tuple[str | None, ...] | None = None + storage_transformers: tuple[NamedConfig, ...] = () + + @model_validator(mode="before") + @classmethod + def _canonicalize(cls, data: object) -> object: + """Route every input document through the library's validation and + normalization; pydantic then parses only canonical documents.""" + if isinstance(data, Mapping): + doc = dict(ZarrV3ArrayMetadata.from_json(data).to_json()) + for key in ("data_type", "chunk_grid", "chunk_key_encoding"): + if isinstance(doc[key], str): + doc[key] = {"name": doc[key]} + for key in ("codecs", "storage_transformers"): + doc[key] = tuple( + {"name": item} if isinstance(item, str) else item for item in doc.get(key, ()) + ) + doc.setdefault("attributes", {}) + return doc + return data + + def to_metadata_model(self) -> ZarrV3ArrayMetadata: + """Bridge back to the canonical model, via the document form. + + In the document, "no dimension names" is key-absence, not null; the + pydantic-side None translates to dropping the key. + """ + doc = self.model_dump() + if doc["dimension_names"] is None: + del doc["dimension_names"] + return ZarrV3ArrayMetadata.from_json(doc) + + def to_document(self) -> dict[str, object]: + """The canonical document (omit-empty conventions applied).""" + return dict(self.to_metadata_model().to_json()) + + +class MicroscopyAttrs(BaseModel): + """Example of consumer-typed attributes, pydantic-zarr style.""" + + resolution_um: float + + +def test_spec_typed_attributes() -> None: + """The generic parameter types the attributes, so consumers get validated, + attribute-level access β€” the pydantic-zarr ArraySpec pattern.""" + doc = dict(VALID_DOC) | {"attributes": {"resolution_um": 0.5}} + spec = ArrayMetadataV3Spec[MicroscopyAttrs].model_validate(doc) + assert spec.attributes.resolution_um == 0.5 + assert spec.data_type == NamedConfig(name="uint8") + + +def test_spec_engine_validates_before_pydantic() -> None: + """The library's structural validation runs before pydantic's parsing, so + coercion cannot re-open validator holes (contrast with the native + introspection test above, where [True, -5] coerced to (1, -5)).""" + with pytest.raises(ValidationError, match="shape"): + ArrayMetadataV3Spec[MicroscopyAttrs].model_validate( + dict(VALID_DOC) | {"shape": [True, -5], "attributes": {"resolution_um": 0.5}} + ) + + +def test_spec_bridges_to_canonical_model_and_document() -> None: + """to_metadata_model / to_document round-trip through the document form, + and the emitted document matches what the library itself would emit.""" + doc = dict(VALID_DOC) | {"attributes": {"resolution_um": 0.5}} + spec = ArrayMetadataV3Spec[MicroscopyAttrs].model_validate(doc) + model = spec.to_metadata_model() + assert isinstance(model, ZarrV3ArrayMetadata) + assert spec.to_document() == dict(model.to_json()) + # and back: the document revalidates to an equal spec + assert ArrayMetadataV3Spec[MicroscopyAttrs].model_validate(spec.to_document()) == spec + + +def test_spec_json_schema_generation() -> None: + """A real BaseModel means model_json_schema works β€” the capability the + opaque InstanceOf pattern cannot provide.""" + schema = ArrayMetadataV3Spec[MicroscopyAttrs].model_json_schema() + assert schema["properties"]["shape"]["type"] == "array" + assert "MicroscopyAttrs" in schema["$defs"] diff --git a/packages/zarr-metadata/tests/model/test_pydantic_module.py b/packages/zarr-metadata/tests/model/test_pydantic_module.py new file mode 100644 index 0000000000..d15b3f118c --- /dev/null +++ b/packages/zarr-metadata/tests/model/test_pydantic_module.py @@ -0,0 +1,264 @@ +"""Tests for `zarr_metadata.pydantic`, the optional pydantic field-type module. + +The hand-rolled recipes in `test_pydantic.py` document how the integration +works; this module ships it. Instances are the CORE model classes (no +parallel hierarchy), so values interoperate freely with non-pydantic code. +""" + +import json +import warnings + +import pytest +from jsonschema import Draft202012Validator +from pydantic import BaseModel, TypeAdapter, ValidationError + +import zarr_metadata.pydantic as zmp +from zarr_metadata.model import ( + ZarrV2ArrayMetadata, + ZarrV2ConsolidatedMetadata, + ZarrV2GroupMetadata, + ZarrV3ArrayMetadata, + ZarrV3ConsolidatedMetadata, + ZarrV3GroupMetadata, + ZarrV3NamedConfig, +) + +V3_ARRAY_DOC = dict(ZarrV3ArrayMetadata.create_default(shape=(4,)).to_json()) +V2_ARRAY_DOC = dict(ZarrV2ArrayMetadata.create_default(shape=(4,), chunks=(2,)).to_json()) +V3_GROUP_DOC = {"zarr_format": 3, "node_type": "group", "attributes": {"a": 1}} +V2_GROUP_DOC = {"zarr_format": 2, "attributes": {"a": 1}} +V3_CONSOLIDATED_DOC = { + "kind": "inline", + "must_understand": False, + "metadata": {"a": dict(V3_ARRAY_DOC)}, +} +V2_CONSOLIDATED_DOC = { + "zarr_consolidated_format": 1, + "metadata": {".zgroup": {"zarr_format": 2}}, +} + +FIELD_CASES = [ + pytest.param(zmp.ZarrV3ArrayMetadata, ZarrV3ArrayMetadata, V3_ARRAY_DOC, id="array-v3"), + pytest.param(zmp.ZarrV2ArrayMetadata, ZarrV2ArrayMetadata, V2_ARRAY_DOC, id="array-v2"), + pytest.param(zmp.ZarrV3GroupMetadata, ZarrV3GroupMetadata, V3_GROUP_DOC, id="group-v3"), + pytest.param(zmp.ZarrV2GroupMetadata, ZarrV2GroupMetadata, V2_GROUP_DOC, id="group-v2"), + pytest.param( + zmp.ZarrV3ConsolidatedMetadata, + ZarrV3ConsolidatedMetadata, + V3_CONSOLIDATED_DOC, + id="consolidated-v3", + ), + pytest.param( + zmp.ZarrV2ConsolidatedMetadata, + ZarrV2ConsolidatedMetadata, + V2_CONSOLIDATED_DOC, + id="consolidated-v2", + ), + pytest.param(zmp.ZarrV3MetadataField, ZarrV3NamedConfig, {"name": "bytes"}, id="field-v3"), +] + + +@pytest.mark.parametrize(("field_type", "model_cls", "doc"), FIELD_CASES) +def test_field_type_validates_and_dumps_canonically( + field_type: object, model_cls: type, doc: dict[str, object] +) -> None: + """Each field type parses its raw document into the CORE model class, + passes existing instances through unchanged, and dumps the canonical + document via to_json.""" + adapter = TypeAdapter(field_type) + model = adapter.validate_python(doc) + assert type(model) is model_cls + assert adapter.validate_python(model) is model + assert adapter.dump_python(model) == model.to_json() + + +def test_core_instances_interoperate() -> None: + """A core model instance (e.g. handed out by zarr-python) drops straight + into a pydantic field β€” the reason the module ships Annotated aliases over + the core classes rather than pydantic-aware subclasses.""" + + class Manifest(BaseModel): + metadata: zmp.ZarrV3ArrayMetadata + + core = ZarrV3ArrayMetadata.from_json(V3_ARRAY_DOC) + manifest = Manifest(metadata=core) + assert manifest.metadata is core + + +def test_validation_error_carries_problems() -> None: + """A defective document fails with the library's loc-annotated messages.""" + + class Manifest(BaseModel): + metadata: zmp.ZarrV3ArrayMetadata + + doc = dict(V3_ARRAY_DOC) + del doc["chunk_key_encoding"] + with pytest.raises(ValidationError, match="chunk_key_encoding: missing required key"): + Manifest.model_validate({"metadata": doc}) + + +def test_json_schema_generation() -> None: + """model_json_schema works, describing the document form each field accepts.""" + + class Manifest(BaseModel): + metadata: zmp.ZarrV3ArrayMetadata + codec: zmp.ZarrV3MetadataField + + schema = Manifest.model_json_schema() + metadata_schema = schema["$defs"]["ZarrV3ArrayMetadataJSON"] + assert schema["properties"]["metadata"]["$ref"] == "#/$defs/ZarrV3ArrayMetadataJSON" + assert metadata_schema["required"] == [ + "zarr_format", + "node_type", + "data_type", + "shape", + "chunk_grid", + "chunk_key_encoding", + "fill_value", + "codecs", + ] + assert metadata_schema["properties"]["zarr_format"] == { + "const": 3, + "title": "Zarr Format", + "type": "integer", + } + assert schema["properties"]["codec"]["anyOf"] == [ + {"type": "string"}, + {"$ref": "#/$defs/ZarrV3NamedConfigJSON"}, + ] + + +def test_json_schema_generation_emits_no_warnings() -> None: + """Consumers can generate every public integration schema without warning filters.""" + field_types = ( + zmp.ZarrV3ArrayMetadata, + zmp.ZarrV2ArrayMetadata, + zmp.ZarrV3GroupMetadata, + zmp.ZarrV2GroupMetadata, + zmp.ZarrV3ConsolidatedMetadata, + zmp.ZarrV2ConsolidatedMetadata, + zmp.ZarrV3MetadataField, + ) + + with warnings.catch_warnings(): + warnings.simplefilter("error") + for field_type in field_types: + TypeAdapter(field_type).json_schema() + + +def test_v2_recursive_structured_dtype_is_in_pydantic_schema() -> None: + """The schema accepts nested structured dtypes supported by the v2 specification.""" + doc = json.loads(json.dumps(V2_ARRAY_DOC)) + doc["dtype"] = [["outer", [["inner", " None: + adapter = TypeAdapter(field_type) + with pytest.raises(ValidationError): + adapter.validate_python(document) + assert list(Draft202012Validator(adapter.json_schema()).iter_errors(document)) + + +def test_v3_array_schema_rejects_empty_codecs() -> None: + """The generated schema mirrors the runtime non-empty codec pipeline rule.""" + doc = json.loads(json.dumps(V3_ARRAY_DOC)) + doc["codecs"] = [] + + _assert_runtime_and_schema_reject(zmp.ZarrV3ArrayMetadata, doc) + + +def test_array_schemas_reject_negative_dimensions() -> None: + """Both array schemas mirror the runtime non-negative dimension rule.""" + for field_type, source in ( + (zmp.ZarrV3ArrayMetadata, V3_ARRAY_DOC), + (zmp.ZarrV2ArrayMetadata, V2_ARRAY_DOC), + ): + doc = json.loads(json.dumps(source)) + doc["shape"] = [-1] + _assert_runtime_and_schema_reject(field_type, doc) + + +def test_v2_array_schema_rejects_empty_filters() -> None: + """The v2 schema mirrors the runtime one-or-more filter rule.""" + doc = json.loads(json.dumps(V2_ARRAY_DOC)) + doc["filters"] = [] + + _assert_runtime_and_schema_reject(zmp.ZarrV2ArrayMetadata, doc) + + +@pytest.mark.parametrize("field", ["data_type", "chunk_grid", "chunk_key_encoding"]) +def test_v3_array_schema_rejects_false_at_mandatory_extension_points(field: str) -> None: + """Mandatory v3 extension points cannot opt out of understanding.""" + doc = json.loads(json.dumps(V3_ARRAY_DOC)) + doc[field] = {"name": "example", "must_understand": False} + + _assert_runtime_and_schema_reject(zmp.ZarrV3ArrayMetadata, doc) + + +def test_metadata_field_schema_rejects_unknown_members() -> None: + """Named-configuration envelopes are closed in both runtime and schema validation.""" + _assert_runtime_and_schema_reject( + zmp.ZarrV3MetadataField, + {"name": "example", "unexpected": 1}, + ) + + +@pytest.mark.parametrize( + ("field_type", "source"), + [ + (zmp.ZarrV2ArrayMetadata, V2_ARRAY_DOC), + (zmp.ZarrV2GroupMetadata, V2_GROUP_DOC), + (zmp.ZarrV2ConsolidatedMetadata, V2_CONSOLIDATED_DOC), + ], +) +def test_v2_schema_rejects_unknown_document_members( + field_type: object, source: dict[str, object] +) -> None: + """Closed v2 merged documents expose their runtime boundary in JSON Schema.""" + doc = json.loads(json.dumps(source)) + doc["unexpected"] = 1 + + _assert_runtime_and_schema_reject(field_type, doc) + + +def test_v3_array_schema_allows_unknown_extension_fields() -> None: + """Schema constraints do not close the v3 top-level extension namespace.""" + doc = json.loads(json.dumps(V3_ARRAY_DOC)) + doc["vendor_extension"] = {"anything": [1, 2]} + adapter = TypeAdapter(zmp.ZarrV3ArrayMetadata) + + assert adapter.validate_python(doc).extra_fields == {"vendor_extension": {"anything": (1, 2)}} + assert Draft202012Validator(adapter.json_schema()).is_valid(doc) + + +def test_json_roundtrip() -> None: + """model_dump_json output re-validates to an equal pydantic model.""" + + class Manifest(BaseModel): + metadata: zmp.ZarrV3ArrayMetadata + + manifest = Manifest.model_validate({"metadata": V3_ARRAY_DOC}) + assert Manifest.model_validate_json(manifest.model_dump_json()) == manifest + + +def test_metadata_field_serializes_shorthand_and_false_object() -> None: + """The optional integration exposes the core model's canonical extension form.""" + adapter = TypeAdapter(zmp.ZarrV3MetadataField) + assert adapter.dump_python(adapter.validate_python({"name": "bytes"})) == "bytes" + assert adapter.dump_python( + adapter.validate_python({"name": "optional", "must_understand": False}) + ) == {"name": "optional", "must_understand": False} + + +def test_core_package_does_not_import_pydantic() -> None: + """Importing zarr_metadata (in a fresh interpreter) must not import + pydantic: the integration is opt-in via zarr_metadata.pydantic.""" + import subprocess + import sys + + code = "import sys, zarr_metadata; assert 'pydantic' not in sys.modules, 'leaked'" + subprocess.run([sys.executable, "-c", code], check=True) diff --git a/packages/zarr-metadata/tests/model/test_sentinel.py b/packages/zarr-metadata/tests/model/test_sentinel.py new file mode 100644 index 0000000000..252a4cdd30 --- /dev/null +++ b/packages/zarr-metadata/tests/model/test_sentinel.py @@ -0,0 +1,89 @@ +"""Tests for the pickling and copying behavior of the `UNSET` sentinel. + +The sentinel's contract is identity, so it must never be reconstructed from +state. typing_extensions >= 4.16 pickles sentinels by reference (a lookup of +the sentinel's name on its defining module), which preserves the singleton +across process boundaries; these tests pin that behavior, since models hold +`UNSET` as field values and must survive pickling and deep-copying. + +The model round-trip tests compare whole structures: dataclass equality +compares every field, and `UNSET` compares by identity, so an impostor +sentinel produced by state-based pickling would fail the equality check. +""" + +from __future__ import annotations + +import copy +import pickle + +import pytest +from typing_extensions import Sentinel + +from zarr_metadata.model import ( + UNSET, + ZarrV2ArrayMetadata, + ZarrV2GroupMetadata, + ZarrV3ArrayMetadata, + ZarrV3ConsolidatedMetadata, + ZarrV3GroupMetadata, +) + +# Whole-model cases covering the states we know are problematic for +# serialization: every optional-key field in the UNSET (absent) state, the +# same fields in the present state (including present-but-empty, which must +# stay distinct from absent), and UNSET nested inside consolidated metadata. +MODEL_CASES = { + "array-v3-dimension-names-unset": ZarrV3ArrayMetadata.create_default(shape=(4,)), + "array-v3-dimension-names-set": ZarrV3ArrayMetadata.create_default(shape=(2, 2)).update( + dimension_names=("x", None) + ), + "array-v2-attributes-unset": ZarrV2ArrayMetadata.create_default(shape=(4,)), + "array-v2-attributes-empty": ZarrV2ArrayMetadata.create_default(shape=(4,), attributes={}), + "group-v2-attributes-unset": ZarrV2GroupMetadata.create_default(), + "group-v2-attributes-set": ZarrV2GroupMetadata.create_default(attributes={"a": 1}), + "group-v3-consolidated-unset": ZarrV3GroupMetadata.create_default(), + "group-v3-consolidated-with-unset-inside": ZarrV3GroupMetadata.create_default( + consolidated_metadata=ZarrV3ConsolidatedMetadata( + metadata={ + "child": ZarrV3ArrayMetadata.create_default(shape=(4,)), + "subgroup": ZarrV3GroupMetadata.create_default(), + } + ) + ), +} + + +def test_unset_pickle_round_trip_preserves_identity() -> None: + restored = pickle.loads(pickle.dumps(UNSET)) + assert restored is UNSET + + +def test_unset_copy_preserves_identity() -> None: + assert copy.copy(UNSET) is UNSET + assert copy.deepcopy(UNSET) is UNSET + + +@pytest.mark.parametrize("model", MODEL_CASES.values(), ids=MODEL_CASES.keys()) +def test_model_pickle_round_trip( + model: ZarrV2ArrayMetadata | ZarrV3ArrayMetadata | ZarrV2GroupMetadata | ZarrV3GroupMetadata, +) -> None: + restored = pickle.loads(pickle.dumps(model)) + assert restored == model + + +@pytest.mark.parametrize("model", MODEL_CASES.values(), ids=MODEL_CASES.keys()) +def test_model_deepcopy( + model: ZarrV2ArrayMetadata | ZarrV3ArrayMetadata | ZarrV2GroupMetadata | ZarrV3GroupMetadata, +) -> None: + assert copy.deepcopy(model) == model + + +def test_non_importable_sentinel_fails_to_pickle() -> None: + """Sentinels pickle by reference, never by state. A sentinel that is not + an importable attribute of its module has no reference to pickle, so + dumping it must fail loudly β€” a successful dump here would mean the + implementation regressed to state-based pickling, which would produce + identity-breaking impostor objects on the receiving side.""" + local_sentinel = Sentinel("local_sentinel") + with pytest.raises((pickle.PicklingError, TypeError)): + pickle.dumps(local_sentinel) diff --git a/packages/zarr-metadata/tests/test_partial_equivalence.py b/packages/zarr-metadata/tests/test_partial_equivalence.py new file mode 100644 index 0000000000..33492b2356 --- /dev/null +++ b/packages/zarr-metadata/tests/test_partial_equivalence.py @@ -0,0 +1,42 @@ +"""Drift-prevention tests for Partial* TypedDict variants. + +Each *Partial TypedDict in the package must declare the same fields +(with the same annotations) and the same extra_items setting as its +full counterpart. The only intentional difference is total=False +(i.e. every field becomes NotRequired). This test enforces that +invariant so adding a field to the full type without mirroring it +on the partial fails CI. +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from zarr_metadata.v2.array import ZarrV2ArrayMetadataJSON, ZarrV2ArrayMetadataJSONPartial +from zarr_metadata.v2.group import ZarrV2GroupMetadataJSON, ZarrV2GroupMetadataJSONPartial +from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON, ZarrV3ArrayMetadataJSONPartial +from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON, ZarrV3GroupMetadataJSONPartial + +# (full, partial) pairs to check. Add new pairs here as more are introduced. +PAIRS: list[tuple[type, type]] = [ + (ZarrV3ArrayMetadataJSON, ZarrV3ArrayMetadataJSONPartial), + (ZarrV3GroupMetadataJSON, ZarrV3GroupMetadataJSONPartial), + (ZarrV2ArrayMetadataJSON, ZarrV2ArrayMetadataJSONPartial), + (ZarrV2GroupMetadataJSON, ZarrV2GroupMetadataJSONPartial), +] + + +@pytest.mark.parametrize(("full", "partial"), PAIRS, ids=lambda p: p.__name__) +def test_partial_matches_full(full: Any, partial: Any) -> None: + """Partial TypedDict has identical fields and extra_items, only total differs.""" + assert full.__annotations__ == partial.__annotations__, ( + f"{partial.__name__} fields drifted from {full.__name__}: " + f"full={set(full.__annotations__)}, partial={set(partial.__annotations__)}" + ) + assert getattr(full, "__extra_items__", None) == getattr(partial, "__extra_items__", None), ( + f"{partial.__name__} extra_items differs from {full.__name__}" + ) + assert full.__total__ is True, f"{full.__name__} must be declared with total=True (default)" + assert partial.__total__ is False, f"{partial.__name__} must be declared with total=False" diff --git a/packages/zarr-metadata/tests/test_public_api.py b/packages/zarr-metadata/tests/test_public_api.py new file mode 100644 index 0000000000..6613aa394b --- /dev/null +++ b/packages/zarr-metadata/tests/test_public_api.py @@ -0,0 +1,488 @@ +"""Test that the curated front-door names are accessible from the top-level zarr_metadata package.""" + +import importlib +import pkgutil +import re +from typing import Literal, get_args, get_origin + +import zarr_metadata as zm + + +def _group_rank(s: str) -> int: + """RUF022 groups `__all__` as: SCREAMING_SNAKE (0), then TitleCase (1), then dunders (2). + + The exact intra-group ordering is ruff's own natural sort and is enforced by + ruff itself (pre-commit + CI); this test only asserts the grouping, not the + fragile tie-breaking, so it can't drift out of sync with ruff's implementation. + """ + if s.startswith("__") and s.endswith("__"): + return 2 + stripped = re.sub(r"[\d_]", "", s) + return 0 if stripped.isupper() else 1 + + +EXPECTED = [ + # Category A β€” metadata-document types + "ZarrV2ArrayMetadataJSON", + "ZarrV2ArrayMetadataJSONPartial", + "ZarrV2ZArrayJSON", + "ZarrV2GroupMetadataJSON", + "ZarrV2GroupMetadataJSONPartial", + "ZarrV2ZGroupJSON", + "ZarrV2ConsolidatedMetadataJSON", + "ZarrV2ZAttrsJSON", + "ZarrV2CodecMetadata", + "ZarrV3ArrayMetadataJSON", + "ZarrV3ArrayMetadataJSONPartial", + "ZarrV3ExtensionField", + "ZarrV3GroupMetadataJSON", + "ZarrV3GroupMetadataJSONPartial", + "ZarrV3ConsolidatedMetadataJSON", + "ZarrV3NamedConfigJSON", + "ZarrV3MetadataFieldJSON", + "JSONValue", + # Category A' β€” metadata models (in-memory dataclasses over the documents) + "ZarrV2ArrayMetadata", + "ZarrV2ArrayMetadataPartial", + "ZarrV3ArrayMetadata", + "ZarrV3ArrayMetadataPartial", + "ZarrV2GroupMetadata", + "ZarrV2GroupMetadataPartial", + "ZarrV3GroupMetadata", + "ZarrV3GroupMetadataPartial", + "ZarrV2ConsolidatedMetadata", + "ZarrV3ConsolidatedMetadata", + "ZarrV3NamedConfig", + "ZarrV3MetadataField", + "ValidationProblem", + "MetadataValidationError", + "ProblemKind", + "UNSET", + # Store keys β€” the names the documents are persisted under. Defined in the + # v2/v3 spec modules, re-exported through `zarr_metadata.model`. + "ZARR_V2_ARRAY_METADATA_STORE_KEY", + "ZarrV2ArrayMetadataStoreKey", + "ZARR_V2_GROUP_METADATA_STORE_KEY", + "ZarrV2GroupMetadataStoreKey", + "ZARR_V2_ATTRIBUTES_STORE_KEY", + "ZarrV2AttributesStoreKey", + "ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY", + "ZarrV2ConsolidatedMetadataStoreKey", + "ZARR_V3_ARRAY_METADATA_STORE_KEY", + "ZarrV3ArrayMetadataStoreKey", + "ZARR_V3_GROUP_METADATA_STORE_KEY", + "ZarrV3GroupMetadataStoreKey", + # Not a store key: v3 consolidated metadata is embedded in the group's own + # `zarr.json`, so it has no paired Literal alias. + "ZARR_V3_CONSOLIDATED_METADATA_KEY", + # v2 data-type encoding union + "ZarrV2DataTypeMetadata", + # Category B β€” codec canonical unions + "BloscCodecMetadata", + "BytesCodecMetadata", + "CastValueCodecMetadata", + "Crc32cCodecMetadata", + "GzipCodecMetadata", + "ScaleOffsetCodecMetadata", + "ShardingIndexedCodecMetadata", + "TransposeCodecMetadata", + "ZstdCodecMetadata", + # Category C β€” grid/key canonical unions + "RegularChunkGridMetadata", + "RectilinearChunkGridMetadata", + "DefaultChunkKeyEncodingMetadata", + "V2ChunkKeyEncodingMetadata", + # Category D β€” dtype trios + # bool + "BoolDataTypeName", + "BOOL_DATA_TYPE_NAME", + "BoolFillValue", + # int8/16/32/64 + "Int8DataTypeName", + "INT8_DATA_TYPE_NAME", + "Int8FillValue", + "Int16DataTypeName", + "INT16_DATA_TYPE_NAME", + "Int16FillValue", + "Int32DataTypeName", + "INT32_DATA_TYPE_NAME", + "Int32FillValue", + "Int64DataTypeName", + "INT64_DATA_TYPE_NAME", + "Int64FillValue", + # uint8/16/32/64 (actual casing is Uint, not UInt) + "Uint8DataTypeName", + "UINT8_DATA_TYPE_NAME", + "Uint8FillValue", + "Uint16DataTypeName", + "UINT16_DATA_TYPE_NAME", + "Uint16FillValue", + "Uint32DataTypeName", + "UINT32_DATA_TYPE_NAME", + "Uint32FillValue", + "Uint64DataTypeName", + "UINT64_DATA_TYPE_NAME", + "Uint64FillValue", + # float16/32/64 + "Float16DataTypeName", + "FLOAT16_DATA_TYPE_NAME", + "Float16FillValue", + "Float32DataTypeName", + "FLOAT32_DATA_TYPE_NAME", + "Float32FillValue", + "Float64DataTypeName", + "FLOAT64_DATA_TYPE_NAME", + "Float64FillValue", + # complex64/128 + "Complex64DataTypeName", + "COMPLEX64_DATA_TYPE_NAME", + "Complex64FillValue", + "Complex128DataTypeName", + "COMPLEX128_DATA_TYPE_NAME", + "Complex128FillValue", + # bytes + "BytesDataTypeName", + "BYTES_DATA_TYPE_NAME", + "BytesFillValue", + # string + "StringDataTypeName", + "STRING_DATA_TYPE_NAME", + "StringFillValue", + # numpy_datetime64 + "NumpyDatetime64DataTypeName", + "NUMPY_DATETIME64_DATA_TYPE_NAME", + "NumpyDatetime64FillValue", + # numpy_timedelta64 + "NumpyTimedelta64DataTypeName", + "NUMPY_TIMEDELTA64_DATA_TYPE_NAME", + "NumpyTimedelta64FillValue", + # struct + "StructDataTypeName", + "STRUCT_DATA_TYPE_NAME", + "StructFillValue", + # raw (no _DATA_TYPE_NAME constant) + "RawBytesDataTypeName", + "RawBytesFillValue", + # Category E β€” constant+Literal pairs + "ZARR_V2_ARRAY_ORDER", + "ZarrV2ArrayOrder", + "ZARR_V2_ARRAY_DIMENSION_SEPARATOR", + "ZarrV2ArrayDimensionSeparator", + "ENDIANNESS", + "Endianness", + "BYTES_CODEC_NAME", + "BytesCodecName", + "BLOSC_CODEC_NAME", + "BloscCodecName", + "BLOSC_CNAME", + "BloscCName", + "BLOSC_SHUFFLE", + "BloscShuffle", + "CAST_ROUNDING_MODE", + "CastRoundingMode", + "CAST_OUT_OF_RANGE_MODE", + "CastOutOfRangeMode", + "CAST_VALUE_CODEC_NAME", + "CastValueCodecName", + "CRC32C_CODEC_NAME", + "Crc32cCodecName", + "GZIP_CODEC_NAME", + "GzipCodecName", + "SCALE_OFFSET_CODEC_NAME", + "ScaleOffsetCodecName", + "SHARDING_INDEX_LOCATION", + "ShardingIndexLocation", + "SHARDING_INDEXED_CODEC_NAME", + "ShardingIndexedCodecName", + "TRANSPOSE_CODEC_NAME", + "TransposeCodecName", + "ZSTD_CODEC_NAME", + "ZstdCodecName", + "REGULAR_CHUNK_GRID_NAME", + "RegularChunkGridName", + "RECTILINEAR_CHUNK_GRID_NAME", + "RectilinearChunkGridName", + "DEFAULT_CHUNK_KEY_ENCODING_NAME", + "DefaultChunkKeyEncodingName", + "DEFAULT_CHUNK_KEY_ENCODING_SEPARATOR", + "DefaultChunkKeyEncodingSeparator", + "V2_CHUNK_KEY_ENCODING_NAME", + "V2ChunkKeyEncodingName", + "V2_CHUNK_KEY_ENCODING_SEPARATOR", + "V2ChunkKeyEncodingSeparator", + "NUMPY_TIME_UNIT", + "NumpyTimeUnit", +] + + +def test_front_door_names_public() -> None: + missing = [n for n in EXPECTED if n not in zm.__all__ or not hasattr(zm, n)] + assert not missing, f"missing from top-level API: {missing}" + + +def test_front_door_is_exactly_expected() -> None: + """`__all__` must contain exactly the curated names (plus `__version__`). + + Guards against a name being promoted to the front door without a + corresponding, deliberate entry in `EXPECTED` β€” i.e. an accidental + addition to the public API surface. + """ + assert set(zm.__all__) - {"__version__"} == set(EXPECTED) + + +def test_all_is_grouped_and_unique() -> None: + ranks = [_group_rank(n) for n in zm.__all__] + assert ranks == sorted(ranks), "`__all__` groups out of order (SCREAMING, TitleCase, dunder)" + assert len(zm.__all__) == len(set(zm.__all__)) + + +# --- naming grammar --------------------------------------------------------- + +# Core document/model names: the format version comes first (`ZarrV2` / +# `ZarrV3`), then the CamelCase entity, then an optional role suffix +# (`JSON`, `JSONPartial`, `Partial`, `StoreKey`) β€” validated loosely here +# because `JSON` decomposes into single-letter words under any strict +# word-splitting regex. +_CORE_NAME = re.compile(r"^ZarrV[23](?:[A-Z][a-z0-9]*)+$") + +# Zarr v3 extension-entity names: the registered entity comes first (`Blosc`, +# `Uint8`, ... β€” `V2` here is the *entity name* of the v2-compatibility chunk +# key encoding, not a format-version marker, which is always spelled +# `ZarrV2`/`ZarrV3`), followed by exactly one role suffix. +_EXTENSION_ROLES = ( + "CodecConfiguration", + "CodecMetadata", + "CodecName", + "CodecObject", + "ChunkGridConfiguration", + "ChunkGridMetadata", + "ChunkGridName", + "ChunkGridObject", + "ChunkKeyEncodingConfiguration", + "ChunkKeyEncodingMetadata", + "ChunkKeyEncodingName", + "ChunkKeyEncodingObject", + "ChunkKeyEncodingSeparator", + "DataTypeName", + "FillValue", + "Configuration", + "Component", +) +_EXTENSION_NAME = re.compile(r"^(?:[A-Z][a-z0-9]*)+?(?:" + "|".join(_EXTENSION_ROLES) + r")$") + +# Standalone vocabulary: scalar Literal aliases, structural helper shapes, and +# the validation diagnostics. Closed by hand β€” a new name belongs here only if +# it is genuinely role-less; anything document- or entity-shaped must fit the +# grammars above instead. +_STANDALONE_VOCAB = frozenset( + { + "Base64Bytes", + "BloscCName", + "BloscShuffle", + "CastOutOfRangeMode", + "CastRoundingMode", + "Endianness", + "HexFloat16", + "HexFloat32", + "HexFloat64", + "JSONValue", + "MetadataValidationError", + "NumpyDatetime64", + "NumpyTimeUnit", + "NumpyTimedelta64", + "ProblemKind", + "RectilinearDimSpec", + "ScalarMap", + "ScalarMapEntry", + "ShardingIndexLocation", + "Struct", + "StructField", + "ValidationProblem", + } +) + + +def _iter_module_names() -> set[str]: + """Every public module in the package, including the top-level namespace.""" + module_names = {"zarr_metadata"} + for info in pkgutil.walk_packages(zm.__path__, prefix="zarr_metadata."): + if not any(part.startswith("_") for part in info.name.split(".")[1:]): + module_names.add(info.name) + return module_names + + +def _public_type_names() -> set[tuple[str, str]]: + """Every (module, CamelCase name) pair exported via a public `__all__`.""" + out: set[tuple[str, str]] = set() + for module_name in _iter_module_names(): + module = importlib.import_module(module_name) + for name in getattr(module, "__all__", ()): + if name.startswith("_") or name.isupper() or name.islower(): + continue + out.add((module_name, name)) + return out + + +def test_public_type_names_comply_with_naming_grammar() -> None: + """Every public type name parses against the package naming grammar: + version-first core names, entity-plus-role extension names, or the closed + standalone vocabulary.""" + exported = _public_type_names() + violations = [ + f"{module}.{name}" + for module, name in sorted(exported) + if name not in _STANDALONE_VOCAB + and not _CORE_NAME.match(name) + and not _EXTENSION_NAME.match(name) + ] + assert not violations, f"names outside the naming grammar: {violations}" + + +def test_standalone_vocab_is_not_stale() -> None: + """Every allowlisted vocabulary name is still actually exported.""" + exported_names = {name for _, name in _public_type_names()} + assert exported_names >= _STANDALONE_VOCAB + + +def test_promoted_pairs_drift() -> None: + """Each promoted runtime constant holds exactly the values of the `Literal` + type it manifests, so the two cannot drift apart.""" + pairs = [ + (zm.ENDIANNESS, zm.Endianness), + (zm.BLOSC_CNAME, zm.BloscCName), + (zm.BLOSC_SHUFFLE, zm.BloscShuffle), + (zm.SHARDING_INDEX_LOCATION, zm.ShardingIndexLocation), + (zm.NUMPY_TIME_UNIT, zm.NumpyTimeUnit), + (zm.CAST_ROUNDING_MODE, zm.CastRoundingMode), + (zm.CAST_OUT_OF_RANGE_MODE, zm.CastOutOfRangeMode), + (zm.ZARR_V2_ARRAY_ORDER, zm.ZarrV2ArrayOrder), + (zm.ZARR_V2_ARRAY_DIMENSION_SEPARATOR, zm.ZarrV2ArrayDimensionSeparator), + (zm.DEFAULT_CHUNK_KEY_ENCODING_SEPARATOR, zm.DefaultChunkKeyEncodingSeparator), + (zm.V2_CHUNK_KEY_ENCODING_SEPARATOR, zm.V2ChunkKeyEncodingSeparator), + ] + for const, lit in pairs: + assert set(const) == set(get_args(lit)) + + +def constant_name_for(type_name: str) -> str: + """Derive a constant's name from the name of the type it manifests. + + The transformation is purely syntactic: split at each lowercase-to-uppercase + boundary and before an uppercase run that starts a new word, then uppercase. + Digit runs stay glued to the token they follow (`Uint8` -> `UINT8`, + `Crc32c` -> `CRC32C`), because a digit boundary in CamelCase does not mark a + word boundary in the spec vocabulary these names model. + + Consecutive capitals do not split, so acronym-adjacent names derive badly: + `ZarrV2ZArrayJSON` -> `ZARR_V2ZARRAY_JSON` and `...JSONPartial` -> + `...JSONPARTIAL`. Every such name in the package today is a `TypedDict` or + `TypeAliasType` that backs no constant, so none reaches this function β€” but + a future `Literal` spelled that way would silently be held to a bad name. + Splitting acronyms correctly needs a vocabulary, not a regex, so the rule + stays syntactic and this stays a known limit. + """ + return re.sub(r"(?<=[a-z0-9])(?=[A-Z][a-z])|(?<=[a-z])(?=[A-Z])", "_", type_name).upper() + + +def _literal_backed_constants() -> list[tuple[str, str, str]]: + """Every (module, constant, type) triple where a module-level SCREAMING_SNAKE + constant holds exactly the values of a `Literal` type in the same module. + + Pairing is by value, not by proximity: a constant manifests the type whose + members it enumerates. Constants with no such type (extension-field keys, + key sets, canonical bit patterns) are exempt from the naming rule and are + simply absent from the result. + """ + out: list[tuple[str, str, str]] = [] + for module_name in _iter_module_names(): + module = importlib.import_module(module_name) + literals = { + name: frozenset(get_args(obj)) + for name, obj in vars(module).items() + if not name.startswith("_") + and not name.isupper() + and get_origin(obj) is Literal + and get_args(obj) + } + if not literals: + continue + for const_name, value in vars(module).items(): + if const_name.startswith("_") or not const_name.isupper(): + continue + members = frozenset(value) if isinstance(value, tuple) else frozenset({value}) + if not all(isinstance(m, str) for m in members): + continue + matches = [t for t, args in literals.items() if args == members] + # A single unambiguous type means this constant manifests it. Ties + # (two Literals with identical members) carry no signal about which + # name the constant should take, so they are skipped. + if len(matches) == 1: + out.append((module_name, const_name, matches[0])) + return out + + +def _value_tied_constants() -> set[str]: + """Constants whose manifested type is ambiguous because two or more `Literal` + types in the same module share its exact members. + + These are invisible to the derivation check, so they are surfaced here and + counted, rather than silently dropped inside the pairing helper.""" + tied: set[str] = set() + for module_name in _iter_module_names(): + module = importlib.import_module(module_name) + literals = [ + frozenset(get_args(obj)) + for name, obj in vars(module).items() + if not name.startswith("_") + and not name.isupper() + and get_origin(obj) is Literal + and get_args(obj) + ] + for const_name, value in vars(module).items(): + if const_name.startswith("_") or not const_name.isupper(): + continue + members = frozenset(value) if isinstance(value, tuple) else frozenset({value}) + if not all(isinstance(m, str) for m in members): + continue + if sum(1 for args in literals if args == members) > 1: + tied.add(f"{module_name}.{const_name}") + return tied + + +# Constants whose `Literal` type cannot be identified by value because another +# `Literal` in the same module has identical members. Pairing is by value, so a +# tie carries no signal about which name the constant should take. These are +# checked by eye; the count below fails if the tied set grows silently. +KNOWN_VALUE_TIES = 9 + + +def test_constant_names_derive_from_their_type_names() -> None: + """Every `Literal`-backed constant whose type can be identified by value has + a name that is the mechanical transform of that type's name. + + Constants tied to more than one identically-valued `Literal` are exempt (see + `KNOWN_VALUE_TIES`), as are constants in private modules and those backing + no `Literal` at all β€” so this pins the rule for most of the package, not all + of it.""" + pairs = _literal_backed_constants() + assert pairs, "found no Literal-backed constants to check" + violations = [ + f"{module}: {const} should be {constant_name_for(type_name)} (manifests {type_name})" + for module, const, type_name in pairs + if const != constant_name_for(type_name) + ] + assert not violations, "constants whose names do not derive from their type:\n" + "\n".join( + violations + ) + + +def test_value_tied_constants_are_a_known_set() -> None: + """The derivation check cannot see constants whose type is ambiguous by + value. Pin how many there are, so the exempt set cannot grow unnoticed and + quietly shrink the rule's coverage.""" + tied = _value_tied_constants() + assert len(tied) == KNOWN_VALUE_TIES, ( + f"value-tied constants changed (expected {KNOWN_VALUE_TIES}, got {len(tied)}); " + f"these are unchecked by the derivation rule and must be named by hand:\n" + + "\n".join(sorted(tied)) + ) diff --git a/tests/v3/test_codecs/__init__.py b/packages/zarr-metadata/tests/v2/__init__.py similarity index 100% rename from tests/v3/test_codecs/__init__.py rename to packages/zarr-metadata/tests/v2/__init__.py diff --git a/tests/v3/test_metadata.py b/packages/zarr-metadata/tests/v2/array/__init__.py similarity index 100% rename from tests/v3/test_metadata.py rename to packages/zarr-metadata/tests/v2/array/__init__.py diff --git a/packages/zarr-metadata/tests/v2/array/blosc_compressor_with_filters.json b/packages/zarr-metadata/tests/v2/array/blosc_compressor_with_filters.json new file mode 100644 index 0000000000..d7c01563e0 --- /dev/null +++ b/packages/zarr-metadata/tests/v2/array/blosc_compressor_with_filters.json @@ -0,0 +1,19 @@ +{ + "zarr_format": 2, + "shape": [200], + "chunks": [50], + "dtype": " None: + ADAPTER.validate_python(json.loads(fixture.read_text())) diff --git a/packages/zarr-metadata/tests/v2/consolidated/__init__.py b/packages/zarr-metadata/tests/v2/consolidated/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v2/consolidated/minimal.json b/packages/zarr-metadata/tests/v2/consolidated/minimal.json new file mode 100644 index 0000000000..fa5db0a584 --- /dev/null +++ b/packages/zarr-metadata/tests/v2/consolidated/minimal.json @@ -0,0 +1,4 @@ +{ + "zarr_consolidated_format": 1, + "metadata": {} +} diff --git a/packages/zarr-metadata/tests/v2/consolidated/test_fixtures.py b/packages/zarr-metadata/tests/v2/consolidated/test_fixtures.py new file mode 100644 index 0000000000..e802c5bef8 --- /dev/null +++ b/packages/zarr-metadata/tests/v2/consolidated/test_fixtures.py @@ -0,0 +1,20 @@ +"""Decode v2 consolidated metadata fixtures via pydantic.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v2.consolidated import ZarrV2ConsolidatedMetadataJSON + +FIXTURES_DIR = Path(__file__).parent +FIXTURES = sorted(FIXTURES_DIR.glob("*.json")) +ADAPTER = TypeAdapter(ZarrV2ConsolidatedMetadataJSON) + + +@pytest.mark.parametrize("fixture", FIXTURES, ids=lambda p: p.stem) +def test_validate(fixture: Path) -> None: + ADAPTER.validate_python(json.loads(fixture.read_text())) diff --git a/packages/zarr-metadata/tests/v2/consolidated/with_array_and_group.json b/packages/zarr-metadata/tests/v2/consolidated/with_array_and_group.json new file mode 100644 index 0000000000..778ede2e66 --- /dev/null +++ b/packages/zarr-metadata/tests/v2/consolidated/with_array_and_group.json @@ -0,0 +1,18 @@ +{ + "zarr_consolidated_format": 1, + "metadata": { + ".zgroup": {"zarr_format": 2}, + ".zattrs": {"description": "root group attrs"}, + "data/.zarray": { + "zarr_format": 2, + "shape": [100], + "chunks": [10], + "dtype": " None: + ADAPTER.validate_python(json.loads(fixture.read_text())) diff --git a/packages/zarr-metadata/tests/v3/__init__.py b/packages/zarr-metadata/tests/v3/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/array/__init__.py b/packages/zarr-metadata/tests/v3/array/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/array/blosc_codec.json b/packages/zarr-metadata/tests/v3/array/blosc_codec.json new file mode 100644 index 0000000000..7681474264 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/blosc_codec.json @@ -0,0 +1,27 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [1024], + "data_type": "int32", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [256]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}}, + { + "name": "blosc", + "configuration": { + "cname": "zstd", + "clevel": 5, + "shuffle": "shuffle", + "blocksize": 0, + "typesize": 4 + } + } + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/datatype_named_config.json b/packages/zarr-metadata/tests/v3/array/datatype_named_config.json new file mode 100644 index 0000000000..b98964f38e --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/datatype_named_config.json @@ -0,0 +1,20 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [10], + "data_type": { + "name": "numpy.datetime64", + "configuration": {"unit": "ns", "scale_factor": 1} + }, + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [10]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/gzip_codec.json b/packages/zarr-metadata/tests/v3/array/gzip_codec.json new file mode 100644 index 0000000000..6c4455dcff --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/gzip_codec.json @@ -0,0 +1,18 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [128], + "data_type": "uint16", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [64]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "gzip", "configuration": {"level": 5}} + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/rectilinear_grid.json b/packages/zarr-metadata/tests/v3/array/rectilinear_grid.json new file mode 100644 index 0000000000..9a33b1469c --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/rectilinear_grid.json @@ -0,0 +1,23 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [100, 100], + "data_type": "float64", + "chunk_grid": { + "name": "rectilinear", + "configuration": { + "kind": "inline", + "chunk_shapes": [ + [10, 20, 30, 40], + 50 + ] + } + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0.0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/rectilinear_grid_with_rle.json b/packages/zarr-metadata/tests/v3/array/rectilinear_grid_with_rle.json new file mode 100644 index 0000000000..c131554a36 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/rectilinear_grid_with_rle.json @@ -0,0 +1,24 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [60, 30], + "data_type": "int16", + "chunk_grid": { + "name": "rectilinear", + "configuration": { + "kind": "inline", + "chunk_shapes": [ + [[10, 5], 5, 5], + [15, 15] + ] + } + }, + "chunk_key_encoding": { + "name": "default", + "configuration": {"separator": "/"} + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/regular_grid_default_encoding.json b/packages/zarr-metadata/tests/v3/array/regular_grid_default_encoding.json new file mode 100644 index 0000000000..73eb742d9b --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/regular_grid_default_encoding.json @@ -0,0 +1,18 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [100, 100], + "data_type": "int32", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [10, 10]} + }, + "chunk_key_encoding": { + "name": "default", + "configuration": {"separator": "/"} + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/regular_grid_v2_encoding.json b/packages/zarr-metadata/tests/v3/array/regular_grid_v2_encoding.json new file mode 100644 index 0000000000..6c09fdb954 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/regular_grid_v2_encoding.json @@ -0,0 +1,18 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [50], + "data_type": "uint8", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [25]} + }, + "chunk_key_encoding": { + "name": "v2", + "configuration": {"separator": "."} + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes"} + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/sharding_indexed_codec.json b/packages/zarr-metadata/tests/v3/array/sharding_indexed_codec.json new file mode 100644 index 0000000000..271e4d75a1 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/sharding_indexed_codec.json @@ -0,0 +1,31 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [1024, 1024], + "data_type": "uint16", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [256, 256]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0, + "codecs": [ + { + "name": "sharding_indexed", + "configuration": { + "chunk_shape": [64, 64], + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "gzip", "configuration": {"level": 1}} + ], + "index_codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "crc32c"} + ], + "index_location": "end" + } + } + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/test_fixtures.py b/packages/zarr-metadata/tests/v3/array/test_fixtures.py new file mode 100644 index 0000000000..c84cc4042b --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/test_fixtures.py @@ -0,0 +1,27 @@ +"""Decode v3 array metadata fixtures via pydantic. + +Each `*.json` file in this directory is a representative on-disk +`zarr.json` that should validate cleanly as `ZarrV3ArrayMetadataJSON`. +Fixtures are named for the variant they exercise (regular vs rectilinear +grid, blosc/gzip/zstd/sharding_indexed codecs, named-config dtypes, optional +fields, extra fields). +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON + +FIXTURES_DIR = Path(__file__).parent +FIXTURES = sorted(FIXTURES_DIR.glob("*.json")) +ADAPTER = TypeAdapter(ZarrV3ArrayMetadataJSON) + + +@pytest.mark.parametrize("fixture", FIXTURES, ids=lambda p: p.stem) +def test_validate(fixture: Path) -> None: + ADAPTER.validate_python(json.loads(fixture.read_text())) diff --git a/packages/zarr-metadata/tests/v3/array/transpose_and_crc32c_codecs.json b/packages/zarr-metadata/tests/v3/array/transpose_and_crc32c_codecs.json new file mode 100644 index 0000000000..3276d5a471 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/transpose_and_crc32c_codecs.json @@ -0,0 +1,19 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [10, 20, 30], + "data_type": "float32", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [5, 10, 15]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": "NaN", + "codecs": [ + {"name": "transpose", "configuration": {"order": [2, 1, 0]}}, + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "crc32c"} + ] +} diff --git a/packages/zarr-metadata/tests/v3/array/with_extra_field.json b/packages/zarr-metadata/tests/v3/array/with_extra_field.json new file mode 100644 index 0000000000..bd7a9f5b45 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/with_extra_field.json @@ -0,0 +1,21 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [10], + "data_type": "int32", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [10]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ], + "my_custom_extension": { + "must_understand": false, + "purpose": "exercise the extra_items=ZarrV3ExtensionField path" + } +} diff --git a/packages/zarr-metadata/tests/v3/array/with_optionals.json b/packages/zarr-metadata/tests/v3/array/with_optionals.json new file mode 100644 index 0000000000..0c4c60986f --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/with_optionals.json @@ -0,0 +1,24 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [10, 20, 30], + "data_type": "float64", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [5, 10, 15]} + }, + "chunk_key_encoding": { + "name": "default", + "configuration": {"separator": "/"} + }, + "fill_value": "NaN", + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ], + "attributes": { + "description": "fixture exercising optional fields", + "tags": ["test", "metadata"] + }, + "dimension_names": ["t", "y", "x"], + "storage_transformers": [] +} diff --git a/packages/zarr-metadata/tests/v3/array/zstd_codec.json b/packages/zarr-metadata/tests/v3/array/zstd_codec.json new file mode 100644 index 0000000000..03de6a9420 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/array/zstd_codec.json @@ -0,0 +1,18 @@ +{ + "zarr_format": 3, + "node_type": "array", + "shape": [128], + "data_type": "int8", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [64]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes"}, + {"name": "zstd", "configuration": {"level": 3, "checksum": false}} + ] +} diff --git a/packages/zarr-metadata/tests/v3/chunk_grid/__init__.py b/packages/zarr-metadata/tests/v3/chunk_grid/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/__init__.py b/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/cases.json b/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/cases.json new file mode 100644 index 0000000000..c01580c17a --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/cases.json @@ -0,0 +1,32 @@ +{ + "explicit_per_dim": { + "name": "rectilinear", + "configuration": { + "kind": "inline", + "chunk_shapes": [ + [10, 20, 30, 40], + [50] + ] + } + }, + "uniform_dim_shorthand": { + "name": "rectilinear", + "configuration": { + "kind": "inline", + "chunk_shapes": [ + [10, 20, 30, 40], + 50 + ] + } + }, + "with_rle_pair": { + "name": "rectilinear", + "configuration": { + "kind": "inline", + "chunk_shapes": [ + [[10, 5], 5, 5], + [15, 15] + ] + } + } +} diff --git a/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/test_fixtures.py b/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/test_fixtures.py new file mode 100644 index 0000000000..cdef26d0a3 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_grid/rectilinear/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate rectilinear chunk grid fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.chunk_grid.rectilinear import RectilinearChunkGridMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_chunk_grid(case: object) -> None: + TypeAdapter(RectilinearChunkGridMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/chunk_grid/regular/__init__.py b/packages/zarr-metadata/tests/v3/chunk_grid/regular/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/chunk_grid/regular/cases.json b/packages/zarr-metadata/tests/v3/chunk_grid/regular/cases.json new file mode 100644 index 0000000000..2ffdef9007 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_grid/regular/cases.json @@ -0,0 +1,14 @@ +{ + "1d": { + "name": "regular", + "configuration": {"chunk_shape": [10]} + }, + "2d": { + "name": "regular", + "configuration": {"chunk_shape": [10, 20]} + }, + "3d": { + "name": "regular", + "configuration": {"chunk_shape": [5, 10, 15]} + } +} diff --git a/packages/zarr-metadata/tests/v3/chunk_grid/regular/test_fixtures.py b/packages/zarr-metadata/tests/v3/chunk_grid/regular/test_fixtures.py new file mode 100644 index 0000000000..9fba28d3ce --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_grid/regular/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate regular chunk grid fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.chunk_grid.regular import RegularChunkGridMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_chunk_grid(case: object) -> None: + TypeAdapter(RegularChunkGridMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/chunk_key_encoding/__init__.py b/packages/zarr-metadata/tests/v3/chunk_key_encoding/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/__init__.py b/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/cases.json b/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/cases.json new file mode 100644 index 0000000000..db9d8f61de --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/cases.json @@ -0,0 +1,14 @@ +{ + "no_configuration": { + "name": "default" + }, + "slash_separator": { + "name": "default", + "configuration": {"separator": "/"} + }, + "dot_separator": { + "name": "default", + "configuration": {"separator": "."} + }, + "short_hand_name": "default" +} diff --git a/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/test_fixtures.py b/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/test_fixtures.py new file mode 100644 index 0000000000..6618df0dd0 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_key_encoding/default/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate default chunk-key encoding fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.chunk_key_encoding.default import DefaultChunkKeyEncodingMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_chunk_key_encoding(case: object) -> None: + TypeAdapter(DefaultChunkKeyEncodingMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/__init__.py b/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/cases.json b/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/cases.json new file mode 100644 index 0000000000..4ba65a6730 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/cases.json @@ -0,0 +1,14 @@ +{ + "no_configuration": { + "name": "v2" + }, + "dot_separator": { + "name": "v2", + "configuration": {"separator": "."} + }, + "slash_separator": { + "name": "v2", + "configuration": {"separator": "/"} + }, + "short_hand_name": "v2" +} diff --git a/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/test_fixtures.py b/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/test_fixtures.py new file mode 100644 index 0000000000..7f43495239 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/chunk_key_encoding/v2/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate v2-compatibility chunk-key encoding fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.chunk_key_encoding.v2 import V2ChunkKeyEncodingMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_chunk_key_encoding(case: object) -> None: + TypeAdapter(V2ChunkKeyEncodingMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/__init__.py b/packages/zarr-metadata/tests/v3/codec/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/blosc/__init__.py b/packages/zarr-metadata/tests/v3/codec/blosc/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/blosc/cases.json b/packages/zarr-metadata/tests/v3/codec/blosc/cases.json new file mode 100644 index 0000000000..20b476764a --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/blosc/cases.json @@ -0,0 +1,21 @@ +{ + "with_typesize": { + "name": "blosc", + "configuration": { + "cname": "zstd", + "clevel": 5, + "shuffle": "shuffle", + "blocksize": 0, + "typesize": 4 + } + }, + "no_typesize": { + "name": "blosc", + "configuration": { + "cname": "lz4", + "clevel": 1, + "shuffle": "noshuffle", + "blocksize": 0 + } + } +} diff --git a/packages/zarr-metadata/tests/v3/codec/blosc/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/blosc/test_fixtures.py new file mode 100644 index 0000000000..bdac8c32b0 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/blosc/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate blosc codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.blosc import BloscCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(BloscCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/bytes/__init__.py b/packages/zarr-metadata/tests/v3/codec/bytes/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/bytes/cases.json b/packages/zarr-metadata/tests/v3/codec/bytes/cases.json new file mode 100644 index 0000000000..0c30d70a67 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/bytes/cases.json @@ -0,0 +1,18 @@ +{ + "little_endian": { + "name": "bytes", + "configuration": {"endian": "little"} + }, + "big_endian": { + "name": "bytes", + "configuration": {"endian": "big"} + }, + "no_endian": { + "name": "bytes", + "configuration": {} + }, + "no_configuration": { + "name": "bytes" + }, + "short_hand_name": "bytes" +} diff --git a/packages/zarr-metadata/tests/v3/codec/bytes/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/bytes/test_fixtures.py new file mode 100644 index 0000000000..ec725e9ba0 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/bytes/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate bytes codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.bytes import BytesCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(BytesCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/cast_value/__init__.py b/packages/zarr-metadata/tests/v3/codec/cast_value/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/cast_value/cases.json b/packages/zarr-metadata/tests/v3/codec/cast_value/cases.json new file mode 100644 index 0000000000..90771d5f76 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/cast_value/cases.json @@ -0,0 +1,60 @@ +{ + "minimal": { + "name": "cast_value", + "configuration": {"data_type": "uint8"} + }, + "named_config_dtype": { + "name": "cast_value", + "configuration": { + "data_type": { + "name": "numpy.datetime64", + "configuration": {"unit": "ns", "scale_factor": 1} + } + } + }, + "with_rounding": { + "name": "cast_value", + "configuration": { + "data_type": "int16", + "rounding": "towards-zero" + } + }, + "with_out_of_range_clamp": { + "name": "cast_value", + "configuration": { + "data_type": "int8", + "out_of_range": "clamp" + } + }, + "with_out_of_range_wrap": { + "name": "cast_value", + "configuration": { + "data_type": "uint8", + "out_of_range": "wrap" + } + }, + "with_scalar_map_encode_only": { + "name": "cast_value", + "configuration": { + "data_type": "uint8", + "scalar_map": { + "encode": [["NaN", 0]] + } + } + }, + "numpy_compat_full_example": { + "name": "cast_value", + "configuration": { + "data_type": "uint8", + "rounding": "towards-zero", + "out_of_range": "wrap", + "scalar_map": { + "encode": [ + ["NaN", 0], + ["+Infinity", 0], + ["-Infinity", 0] + ] + } + } + } +} diff --git a/packages/zarr-metadata/tests/v3/codec/cast_value/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/cast_value/test_fixtures.py new file mode 100644 index 0000000000..695e25f883 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/cast_value/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate cast_value codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.cast_value import CastValueCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(CastValueCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/crc32c/__init__.py b/packages/zarr-metadata/tests/v3/codec/crc32c/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/crc32c/cases.json b/packages/zarr-metadata/tests/v3/codec/crc32c/cases.json new file mode 100644 index 0000000000..af89eed012 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/crc32c/cases.json @@ -0,0 +1,10 @@ +{ + "no_configuration": { + "name": "crc32c" + }, + "empty_configuration": { + "name": "crc32c", + "configuration": {} + }, + "short_hand_name": "crc32c" +} diff --git a/packages/zarr-metadata/tests/v3/codec/crc32c/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/crc32c/test_fixtures.py new file mode 100644 index 0000000000..906daae6da --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/crc32c/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate crc32c codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.crc32c import Crc32cCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(Crc32cCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/gzip/__init__.py b/packages/zarr-metadata/tests/v3/codec/gzip/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/gzip/cases.json b/packages/zarr-metadata/tests/v3/codec/gzip/cases.json new file mode 100644 index 0000000000..7d5e1e6f94 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/gzip/cases.json @@ -0,0 +1,6 @@ +{ + "with_level": { + "name": "gzip", + "configuration": {"level": 5} + } +} diff --git a/packages/zarr-metadata/tests/v3/codec/gzip/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/gzip/test_fixtures.py new file mode 100644 index 0000000000..e198971ee7 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/gzip/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate gzip codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.gzip import GzipCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(GzipCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/scale_offset/__init__.py b/packages/zarr-metadata/tests/v3/codec/scale_offset/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/scale_offset/cases.json b/packages/zarr-metadata/tests/v3/codec/scale_offset/cases.json new file mode 100644 index 0000000000..c96e214007 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/scale_offset/cases.json @@ -0,0 +1,26 @@ +{ + "no_configuration": { + "name": "scale_offset" + }, + "empty_configuration": { + "name": "scale_offset", + "configuration": {} + }, + "offset_only": { + "name": "scale_offset", + "configuration": {"offset": 5} + }, + "scale_only": { + "name": "scale_offset", + "configuration": {"scale": 0.1} + }, + "scale_and_offset": { + "name": "scale_offset", + "configuration": {"offset": 5, "scale": 0.1} + }, + "string_encoded_scalar": { + "name": "scale_offset", + "configuration": {"offset": "NaN"} + }, + "short_hand_name": "scale_offset" +} diff --git a/packages/zarr-metadata/tests/v3/codec/scale_offset/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/scale_offset/test_fixtures.py new file mode 100644 index 0000000000..e0e62b9d56 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/scale_offset/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate scale_offset codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.scale_offset import ScaleOffsetCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(ScaleOffsetCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/sharding_indexed/__init__.py b/packages/zarr-metadata/tests/v3/codec/sharding_indexed/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/sharding_indexed/cases.json b/packages/zarr-metadata/tests/v3/codec/sharding_indexed/cases.json new file mode 100644 index 0000000000..2862dae4a7 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/sharding_indexed/cases.json @@ -0,0 +1,30 @@ +{ + "with_index_location": { + "name": "sharding_indexed", + "configuration": { + "chunk_shape": [64, 64], + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "gzip", "configuration": {"level": 1}} + ], + "index_codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "crc32c"} + ], + "index_location": "end" + } + }, + "no_index_location": { + "name": "sharding_indexed", + "configuration": { + "chunk_shape": [128], + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ], + "index_codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "crc32c"} + ] + } + } +} diff --git a/packages/zarr-metadata/tests/v3/codec/sharding_indexed/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/sharding_indexed/test_fixtures.py new file mode 100644 index 0000000000..e3e61e9e4d --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/sharding_indexed/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate sharding_indexed codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.sharding_indexed import ShardingIndexedCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(ShardingIndexedCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/transpose/__init__.py b/packages/zarr-metadata/tests/v3/codec/transpose/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/transpose/cases.json b/packages/zarr-metadata/tests/v3/codec/transpose/cases.json new file mode 100644 index 0000000000..6adcc6948a --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/transpose/cases.json @@ -0,0 +1,6 @@ +{ + "reversed_3d": { + "name": "transpose", + "configuration": {"order": [2, 1, 0]} + } +} diff --git a/packages/zarr-metadata/tests/v3/codec/transpose/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/transpose/test_fixtures.py new file mode 100644 index 0000000000..4bd7c99bc8 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/transpose/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate transpose codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.transpose import TransposeCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(TransposeCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/codec/zstd/__init__.py b/packages/zarr-metadata/tests/v3/codec/zstd/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/codec/zstd/cases.json b/packages/zarr-metadata/tests/v3/codec/zstd/cases.json new file mode 100644 index 0000000000..77733fe054 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/zstd/cases.json @@ -0,0 +1,6 @@ +{ + "default": { + "name": "zstd", + "configuration": {"level": 3, "checksum": false} + } +} diff --git a/packages/zarr-metadata/tests/v3/codec/zstd/test_fixtures.py b/packages/zarr-metadata/tests/v3/codec/zstd/test_fixtures.py new file mode 100644 index 0000000000..a1981211a3 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/codec/zstd/test_fixtures.py @@ -0,0 +1,18 @@ +"""Validate zstd codec fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.codec.zstd import ZstdCodecMetadata + +CASES: dict[str, object] = json.loads((Path(__file__).parent / "cases.json").read_text()) + + +@pytest.mark.parametrize("case", CASES.values(), ids=list(CASES)) +def test_codec(case: object) -> None: + TypeAdapter(ZstdCodecMetadata).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/consolidated/__init__.py b/packages/zarr-metadata/tests/v3/consolidated/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/consolidated/minimal.json b/packages/zarr-metadata/tests/v3/consolidated/minimal.json new file mode 100644 index 0000000000..1f2ab2ad61 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/consolidated/minimal.json @@ -0,0 +1,5 @@ +{ + "kind": "inline", + "must_understand": false, + "metadata": {} +} diff --git a/packages/zarr-metadata/tests/v3/consolidated/test_fixtures.py b/packages/zarr-metadata/tests/v3/consolidated/test_fixtures.py new file mode 100644 index 0000000000..d052b16986 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/consolidated/test_fixtures.py @@ -0,0 +1,20 @@ +"""Decode v3 consolidated metadata fixtures via pydantic.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.consolidated import ZarrV3ConsolidatedMetadataJSON + +FIXTURES_DIR = Path(__file__).parent +FIXTURES = sorted(FIXTURES_DIR.glob("*.json")) +ADAPTER = TypeAdapter(ZarrV3ConsolidatedMetadataJSON) + + +@pytest.mark.parametrize("fixture", FIXTURES, ids=lambda p: p.stem) +def test_validate(fixture: Path) -> None: + ADAPTER.validate_python(json.loads(fixture.read_text())) diff --git a/packages/zarr-metadata/tests/v3/consolidated/with_array_and_group.json b/packages/zarr-metadata/tests/v3/consolidated/with_array_and_group.json new file mode 100644 index 0000000000..65ac70f7ac --- /dev/null +++ b/packages/zarr-metadata/tests/v3/consolidated/with_array_and_group.json @@ -0,0 +1,27 @@ +{ + "kind": "inline", + "must_understand": false, + "metadata": { + "child_group": { + "zarr_format": 3, + "node_type": "group" + }, + "child_array": { + "zarr_format": 3, + "node_type": "array", + "shape": [10], + "data_type": "int32", + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [10]} + }, + "chunk_key_encoding": { + "name": "default" + }, + "fill_value": 0, + "codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}} + ] + } + } +} diff --git a/packages/zarr-metadata/tests/v3/data_type/__init__.py b/packages/zarr-metadata/tests/v3/data_type/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/bool/__init__.py b/packages/zarr-metadata/tests/v3/data_type/bool/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/bool/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/bool/fill_values.json new file mode 100644 index 0000000000..955baa58cc --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/bool/fill_values.json @@ -0,0 +1,4 @@ +{ + "true": true, + "false": false +} diff --git a/packages/zarr-metadata/tests/v3/data_type/bool/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/bool/test_fixtures.py new file mode 100644 index 0000000000..e924015b1d --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/bool/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate bool fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.bool import BoolFillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(BoolFillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/bytes/__init__.py b/packages/zarr-metadata/tests/v3/data_type/bytes/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/bytes/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/bytes/fill_values.json new file mode 100644 index 0000000000..6e55b7313c --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/bytes/fill_values.json @@ -0,0 +1,4 @@ +{ + "tuple": [1, 2, 3], + "base64": "AQID" +} diff --git a/packages/zarr-metadata/tests/v3/data_type/bytes/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/bytes/test_fixtures.py new file mode 100644 index 0000000000..9ee62fb140 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/bytes/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate variable-length bytes fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.bytes import BytesFillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(BytesFillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/bytes/test_validators.py b/packages/zarr-metadata/tests/v3/data_type/bytes/test_validators.py new file mode 100644 index 0000000000..7f41d878f8 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/bytes/test_validators.py @@ -0,0 +1,43 @@ +"""Cover the `base64_bytes` brand validator. + +The pydantic-driven fixture tests don't enforce the base64 alphabet or +length-multiple-of-4 constraint because `Base64Bytes` is a `NewType`, +which pydantic treats as plain `str`. Direct coverage of the validator +function lives here. +""" + +from __future__ import annotations + +import pytest + +from zarr_metadata.v3.data_type.bytes import base64_bytes + +VALID = [ + "", # empty is valid base64 (length 0, multiple of 4) + "AQID", # [1, 2, 3] + "AAAA", # [0, 0, 0] + "////", # [255, 255, 255] + "abcd", + "AB==", # padding + "ABC=", # padding +] +INVALID = [ + "AB", # length 2, not multiple of 4 + "ABC", # length 3, not multiple of 4 + "ABCDE", # length 5 + "AB-D", # url-safe alphabet, not standard + "AB_D", # url-safe alphabet, not standard + "AB!D", # not base64 char + "AB CD", # whitespace +] + + +@pytest.mark.parametrize("value", VALID) +def test_valid(value: str) -> None: + assert base64_bytes(value) == value + + +@pytest.mark.parametrize("value", INVALID) +def test_invalid(value: str) -> None: + with pytest.raises(ValueError, match="standard-alphabet base64"): + base64_bytes(value) diff --git a/packages/zarr-metadata/tests/v3/data_type/complex128/__init__.py b/packages/zarr-metadata/tests/v3/data_type/complex128/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/complex128/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/complex128/fill_values.json new file mode 100644 index 0000000000..c30f15a55c --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/complex128/fill_values.json @@ -0,0 +1,7 @@ +{ + "numeric": [1.5, 2.5], + "zero": [0.0, 0.0], + "with_sentinel_components": ["-Infinity", "NaN"], + "mixed_numeric_and_sentinel": [1.0, "Infinity"], + "with_hex_components": ["0x7ff8000000000000", "0x0000000000000000"] +} diff --git a/packages/zarr-metadata/tests/v3/data_type/complex128/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/complex128/test_fixtures.py new file mode 100644 index 0000000000..3536dc6ef3 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/complex128/test_fixtures.py @@ -0,0 +1,26 @@ +"""Validate complex128 fill-value fixtures. + +A v3 complex fill_value is a two-element JSON array `[real, imag]` where +each component is shaped per the corresponding float's fill value: a +number, one of the named sentinels (`"NaN"`, `"Infinity"`, +`"-Infinity"`), or a hex string of the underlying float's bits. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.complex128 import Complex128FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Complex128FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/complex64/__init__.py b/packages/zarr-metadata/tests/v3/data_type/complex64/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/complex64/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/complex64/fill_values.json new file mode 100644 index 0000000000..65d302f496 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/complex64/fill_values.json @@ -0,0 +1,7 @@ +{ + "numeric": [1.5, 2.5], + "zero": [0.0, 0.0], + "with_sentinel_components": ["-Infinity", "NaN"], + "mixed_numeric_and_sentinel": [1.0, "Infinity"], + "with_hex_components": ["0x7fc00000", "0x00000000"] +} diff --git a/packages/zarr-metadata/tests/v3/data_type/complex64/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/complex64/test_fixtures.py new file mode 100644 index 0000000000..83682c74b1 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/complex64/test_fixtures.py @@ -0,0 +1,26 @@ +"""Validate complex64 fill-value fixtures. + +A v3 complex fill_value is a two-element JSON array `[real, imag]` where +each component is shaped per the corresponding float's fill value: a +number, one of the named sentinels (`"NaN"`, `"Infinity"`, +`"-Infinity"`), or a hex string of the underlying float's bits. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.complex64 import Complex64FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Complex64FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/float16/__init__.py b/packages/zarr-metadata/tests/v3/data_type/float16/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/float16/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/float16/fill_values.json new file mode 100644 index 0000000000..07034ffba5 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float16/fill_values.json @@ -0,0 +1,8 @@ +{ + "zero": 0.0, + "nan": "NaN", + "infinity": "Infinity", + "neg_infinity": "-Infinity", + "hex_zero": "0x0000", + "hex_signaling_nan": "0x7d00" +} diff --git a/packages/zarr-metadata/tests/v3/data_type/float16/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/float16/test_fixtures.py new file mode 100644 index 0000000000..2241398fb3 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float16/test_fixtures.py @@ -0,0 +1,26 @@ +"""Validate float16 fill-value fixtures. + +A v3 float fill_value is a JSON number, one of the named non-finite +sentinels (`"NaN"`, `"Infinity"`, `"-Infinity"`), or a hex string +(`"0xYYYY"`) encoding the unsigned-integer representation of the IEEE +754 value. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.float16 import Float16FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Float16FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/float16/test_validators.py b/packages/zarr-metadata/tests/v3/data_type/float16/test_validators.py new file mode 100644 index 0000000000..c710f27ea4 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float16/test_validators.py @@ -0,0 +1,34 @@ +"""Cover the `hex_float16` brand validator. + +The pydantic-driven fixture tests don't enforce hex format because +`HexFloat16` is a `NewType`, which pydantic treats as plain `str`. +Direct coverage of the validator function lives here. +""" + +from __future__ import annotations + +import pytest + +from zarr_metadata.v3.data_type.float16 import hex_float16 + +VALID = ["0x0000", "0x7c00", "0x7d00", "0xffff", "0xFFFF", "0xAbCd"] +INVALID = [ + "", + "0000", # missing 0x + "0x000", # too short + "0x00000", # too long + "0x000g", # non-hex char + "0X0000", # uppercase X + " 0x0000 ", # whitespace +] + + +@pytest.mark.parametrize("value", VALID) +def test_valid(value: str) -> None: + assert hex_float16(value) == value + + +@pytest.mark.parametrize("value", INVALID) +def test_invalid(value: str) -> None: + with pytest.raises(ValueError, match="Expected '0x'"): + hex_float16(value) diff --git a/packages/zarr-metadata/tests/v3/data_type/float32/__init__.py b/packages/zarr-metadata/tests/v3/data_type/float32/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/float32/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/float32/fill_values.json new file mode 100644 index 0000000000..ed6502f85a --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float32/fill_values.json @@ -0,0 +1,9 @@ +{ + "zero": 0.0, + "nan": "NaN", + "infinity": "Infinity", + "neg_infinity": "-Infinity", + "hex_zero": "0x00000000", + "hex_canonical_nan": "0x7fc00000", + "hex_signaling_nan": "0x7fa00000" +} diff --git a/packages/zarr-metadata/tests/v3/data_type/float32/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/float32/test_fixtures.py new file mode 100644 index 0000000000..bd943bd96e --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float32/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate float32 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.float32 import Float32FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Float32FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/float32/test_validators.py b/packages/zarr-metadata/tests/v3/data_type/float32/test_validators.py new file mode 100644 index 0000000000..e859d91c26 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float32/test_validators.py @@ -0,0 +1,41 @@ +"""Cover the `hex_float32` brand validator. + +The pydantic-driven fixture tests don't enforce hex format because +`HexFloat32` is a `NewType`, which pydantic treats as plain `str`. +Direct coverage of the validator function lives here. +""" + +from __future__ import annotations + +import pytest + +from zarr_metadata.v3.data_type.float32 import hex_float32 + +VALID = [ + "0x00000000", + "0x7fc00000", # canonical NaN + "0x7fa00000", # signaling NaN + "0xffffffff", + "0xFFFFFFFF", + "0xDeadBeef", +] +INVALID = [ + "", + "00000000", # missing 0x + "0x0000000", # too short + "0x000000000", # too long + "0x0000000g", # non-hex char + "0X00000000", # uppercase X + " 0x00000000 ", # whitespace +] + + +@pytest.mark.parametrize("value", VALID) +def test_valid(value: str) -> None: + assert hex_float32(value) == value + + +@pytest.mark.parametrize("value", INVALID) +def test_invalid(value: str) -> None: + with pytest.raises(ValueError, match="Expected '0x'"): + hex_float32(value) diff --git a/packages/zarr-metadata/tests/v3/data_type/float64/__init__.py b/packages/zarr-metadata/tests/v3/data_type/float64/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/float64/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/float64/fill_values.json new file mode 100644 index 0000000000..76da958c63 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float64/fill_values.json @@ -0,0 +1,9 @@ +{ + "zero": 0.0, + "nan": "NaN", + "infinity": "Infinity", + "neg_infinity": "-Infinity", + "hex_zero": "0x0000000000000000", + "hex_canonical_nan": "0x7ff8000000000000", + "hex_signaling_nan": "0x7ff4000000000000" +} diff --git a/packages/zarr-metadata/tests/v3/data_type/float64/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/float64/test_fixtures.py new file mode 100644 index 0000000000..2e4566ae58 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float64/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate float64 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.float64 import Float64FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Float64FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/float64/test_validators.py b/packages/zarr-metadata/tests/v3/data_type/float64/test_validators.py new file mode 100644 index 0000000000..938bf2a1a5 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/float64/test_validators.py @@ -0,0 +1,41 @@ +"""Cover the `hex_float64` brand validator. + +The pydantic-driven fixture tests don't enforce hex format because +`HexFloat64` is a `NewType`, which pydantic treats as plain `str`. +Direct coverage of the validator function lives here. +""" + +from __future__ import annotations + +import pytest + +from zarr_metadata.v3.data_type.float64 import hex_float64 + +VALID = [ + "0x0000000000000000", + "0x7ff8000000000000", # canonical NaN + "0x7ff4000000000000", # signaling NaN + "0xffffffffffffffff", + "0xFFFFFFFFFFFFFFFF", + "0xDeadBeefCafeBabe", +] +INVALID = [ + "", + "0000000000000000", # missing 0x + "0x000000000000000", # too short + "0x00000000000000000", # too long + "0x000000000000000g", # non-hex char + "0X0000000000000000", # uppercase X + " 0x0000000000000000 ", # whitespace +] + + +@pytest.mark.parametrize("value", VALID) +def test_valid(value: str) -> None: + assert hex_float64(value) == value + + +@pytest.mark.parametrize("value", INVALID) +def test_invalid(value: str) -> None: + with pytest.raises(ValueError, match="Expected '0x'"): + hex_float64(value) diff --git a/packages/zarr-metadata/tests/v3/data_type/int16/__init__.py b/packages/zarr-metadata/tests/v3/data_type/int16/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/int16/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/int16/fill_values.json new file mode 100644 index 0000000000..af8304c51b --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int16/fill_values.json @@ -0,0 +1,6 @@ +{ + "zero": 0, + "min": -32768, + "max": 32767, + "negative": -1 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/int16/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/int16/test_fixtures.py new file mode 100644 index 0000000000..2149947c2d --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int16/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate int16 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.int16 import Int16FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Int16FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/int32/__init__.py b/packages/zarr-metadata/tests/v3/data_type/int32/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/int32/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/int32/fill_values.json new file mode 100644 index 0000000000..d0bf317770 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int32/fill_values.json @@ -0,0 +1,6 @@ +{ + "zero": 0, + "min": -2147483648, + "max": 2147483647, + "negative": -1 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/int32/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/int32/test_fixtures.py new file mode 100644 index 0000000000..b1dbb6d370 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int32/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate int32 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.int32 import Int32FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Int32FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/int64/__init__.py b/packages/zarr-metadata/tests/v3/data_type/int64/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/int64/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/int64/fill_values.json new file mode 100644 index 0000000000..a97c5b3f34 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int64/fill_values.json @@ -0,0 +1,6 @@ +{ + "zero": 0, + "min": -9223372036854775808, + "max": 9223372036854775807, + "negative": -1 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/int64/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/int64/test_fixtures.py new file mode 100644 index 0000000000..957bf2296b --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int64/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate int64 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.int64 import Int64FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Int64FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/int8/__init__.py b/packages/zarr-metadata/tests/v3/data_type/int8/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/int8/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/int8/fill_values.json new file mode 100644 index 0000000000..716f347c19 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int8/fill_values.json @@ -0,0 +1,6 @@ +{ + "zero": 0, + "min": -128, + "max": 127, + "negative": -1 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/int8/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/int8/test_fixtures.py new file mode 100644 index 0000000000..ef9438dad0 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/int8/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate int8 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.int8 import Int8FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Int8FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/__init__.py b/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/data_type.json b/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/data_type.json new file mode 100644 index 0000000000..f94c1b45da --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/data_type.json @@ -0,0 +1,7 @@ +{ + "name": "numpy.datetime64", + "configuration": { + "unit": "ns", + "scale_factor": 1 + } +} diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/fill_values.json new file mode 100644 index 0000000000..b628657396 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/fill_values.json @@ -0,0 +1,4 @@ +{ + "int": 12345, + "nat": "NaT" +} diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/test_fixtures.py new file mode 100644 index 0000000000..7609b42d70 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/numpy_datetime64/test_fixtures.py @@ -0,0 +1,26 @@ +"""Validate numpy.datetime64 dtype value and fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.numpy_datetime64 import ( + NumpyDatetime64, + NumpyDatetime64FillValue, +) + +DIR = Path(__file__).parent +FILL_VALUES: dict[str, object] = json.loads((DIR / "fill_values.json").read_text()) + + +def test_data_type() -> None: + TypeAdapter(NumpyDatetime64).validate_python(json.loads((DIR / "data_type.json").read_text())) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(NumpyDatetime64FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/__init__.py b/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/data_type.json b/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/data_type.json new file mode 100644 index 0000000000..e49ec06e39 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/data_type.json @@ -0,0 +1,7 @@ +{ + "name": "numpy.timedelta64", + "configuration": { + "unit": "s", + "scale_factor": 1 + } +} diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/fill_values.json new file mode 100644 index 0000000000..cd3c94c077 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/fill_values.json @@ -0,0 +1,4 @@ +{ + "int": 42, + "nat": "NaT" +} diff --git a/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/test_fixtures.py new file mode 100644 index 0000000000..2a6c651582 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/numpy_timedelta64/test_fixtures.py @@ -0,0 +1,33 @@ +"""Validate numpy.timedelta64 dtype value and fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import get_args + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.numpy_timedelta64 import ( + NUMPY_TIME_UNIT, + NumpyTimedelta64, + NumpyTimedelta64FillValue, + NumpyTimeUnit, +) + +DIR = Path(__file__).parent +FILL_VALUES: dict[str, object] = json.loads((DIR / "fill_values.json").read_text()) + + +def test_data_type() -> None: + TypeAdapter(NumpyTimedelta64).validate_python(json.loads((DIR / "data_type.json").read_text())) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(NumpyTimedelta64FillValue).validate_python(case) + + +def test_time_unit_constant_matches_literal() -> None: + assert set(NUMPY_TIME_UNIT) == set(get_args(NumpyTimeUnit)) diff --git a/packages/zarr-metadata/tests/v3/data_type/raw/__init__.py b/packages/zarr-metadata/tests/v3/data_type/raw/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/raw/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/raw/fill_values.json new file mode 100644 index 0000000000..60cf0760fc --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/raw/fill_values.json @@ -0,0 +1,3 @@ +{ + "all_zero_4_bytes": [0, 0, 0, 0] +} diff --git a/packages/zarr-metadata/tests/v3/data_type/raw/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/raw/test_fixtures.py new file mode 100644 index 0000000000..ee35ebe267 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/raw/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate raw-bytes (`r`) fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.raw import RawBytesFillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(RawBytesFillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/raw/test_validators.py b/packages/zarr-metadata/tests/v3/data_type/raw/test_validators.py new file mode 100644 index 0000000000..c1524aed96 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/raw/test_validators.py @@ -0,0 +1,33 @@ +"""Cover the `raw_bytes_dtype_name` brand validator. + +The pydantic-driven fixture tests don't enforce the `r` shape +because `RawBytesDataTypeName` is a `NewType`, which pydantic treats +as plain `str`. Direct coverage of the validator function lives here. +""" + +from __future__ import annotations + +import pytest + +from zarr_metadata.v3.data_type.raw import raw_bytes_dtype_name + +VALID = ["r8", "r16", "r24", "r256", "r1024"] +INVALID_FORMAT = ["", "8", "R8", "r", "r-8", "r8 ", " r8", "r8r8"] +INVALID_BITS = ["r0", "r1", "r7", "r9", "r15", "r17"] + + +@pytest.mark.parametrize("value", VALID) +def test_valid(value: str) -> None: + assert raw_bytes_dtype_name(value) == value + + +@pytest.mark.parametrize("value", INVALID_FORMAT) +def test_invalid_format(value: str) -> None: + with pytest.raises(ValueError, match="Expected 'r' followed by"): + raw_bytes_dtype_name(value) + + +@pytest.mark.parametrize("value", INVALID_BITS) +def test_invalid_bit_count(value: str) -> None: + with pytest.raises(ValueError, match="positive multiple of 8"): + raw_bytes_dtype_name(value) diff --git a/packages/zarr-metadata/tests/v3/data_type/string/__init__.py b/packages/zarr-metadata/tests/v3/data_type/string/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/string/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/string/fill_values.json new file mode 100644 index 0000000000..d9dfba1658 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/string/fill_values.json @@ -0,0 +1,6 @@ +{ + "empty": "", + "ascii": "hello", + "unicode": "hΓ©llo δΈ–η•Œ", + "with_escapes": "line1\nline2\t\"quoted\"" +} diff --git a/packages/zarr-metadata/tests/v3/data_type/string/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/string/test_fixtures.py new file mode 100644 index 0000000000..69a8038bdd --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/string/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate string fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.string import StringFillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(StringFillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/struct/__init__.py b/packages/zarr-metadata/tests/v3/data_type/struct/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/struct/data_type.json b/packages/zarr-metadata/tests/v3/data_type/struct/data_type.json new file mode 100644 index 0000000000..999326076e --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/struct/data_type.json @@ -0,0 +1,16 @@ +{ + "name": "struct", + "configuration": { + "fields": [ + {"name": "x", "data_type": "float32"}, + {"name": "y", "data_type": "float32"}, + { + "name": "when", + "data_type": { + "name": "numpy.datetime64", + "configuration": {"unit": "ns", "scale_factor": 1} + } + } + ] + } +} diff --git a/packages/zarr-metadata/tests/v3/data_type/struct/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/struct/fill_values.json new file mode 100644 index 0000000000..e658d70af0 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/struct/fill_values.json @@ -0,0 +1,7 @@ +{ + "all_fields": { + "x": 0.0, + "y": 1.0, + "when": 0 + } +} diff --git a/packages/zarr-metadata/tests/v3/data_type/struct/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/struct/test_fixtures.py new file mode 100644 index 0000000000..15e6257fc1 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/struct/test_fixtures.py @@ -0,0 +1,23 @@ +"""Validate struct dtype value and fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.struct import Struct, StructFillValue + +DIR = Path(__file__).parent +FILL_VALUES: dict[str, object] = json.loads((DIR / "fill_values.json").read_text()) + + +def test_data_type() -> None: + TypeAdapter(Struct).validate_python(json.loads((DIR / "data_type.json").read_text())) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(StructFillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/test_dtype_names.py b/packages/zarr-metadata/tests/v3/data_type/test_dtype_names.py new file mode 100644 index 0000000000..152c1b5fdc --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/test_dtype_names.py @@ -0,0 +1,61 @@ +"""Validate every primitive Zarr v3 data-type name string. + +Primitive dtypes are encoded as bare strings in the `data_type` field of a +v3 array metadata document (e.g. `"int32"`, `"float64"`). Each must +validate as its declared per-dtype `*Name` literal type. +""" + +from __future__ import annotations + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.bool import BOOL_DATA_TYPE_NAME, BoolDataTypeName +from zarr_metadata.v3.data_type.bytes import BYTES_DATA_TYPE_NAME, BytesDataTypeName +from zarr_metadata.v3.data_type.complex64 import COMPLEX64_DATA_TYPE_NAME, Complex64DataTypeName +from zarr_metadata.v3.data_type.complex128 import COMPLEX128_DATA_TYPE_NAME, Complex128DataTypeName +from zarr_metadata.v3.data_type.float16 import FLOAT16_DATA_TYPE_NAME, Float16DataTypeName +from zarr_metadata.v3.data_type.float32 import FLOAT32_DATA_TYPE_NAME, Float32DataTypeName +from zarr_metadata.v3.data_type.float64 import FLOAT64_DATA_TYPE_NAME, Float64DataTypeName +from zarr_metadata.v3.data_type.int8 import INT8_DATA_TYPE_NAME, Int8DataTypeName +from zarr_metadata.v3.data_type.int16 import INT16_DATA_TYPE_NAME, Int16DataTypeName +from zarr_metadata.v3.data_type.int32 import INT32_DATA_TYPE_NAME, Int32DataTypeName +from zarr_metadata.v3.data_type.int64 import INT64_DATA_TYPE_NAME, Int64DataTypeName +from zarr_metadata.v3.data_type.raw import raw_bytes_dtype_name +from zarr_metadata.v3.data_type.string import STRING_DATA_TYPE_NAME, StringDataTypeName +from zarr_metadata.v3.data_type.uint8 import UINT8_DATA_TYPE_NAME, Uint8DataTypeName +from zarr_metadata.v3.data_type.uint16 import UINT16_DATA_TYPE_NAME, Uint16DataTypeName +from zarr_metadata.v3.data_type.uint32 import UINT32_DATA_TYPE_NAME, Uint32DataTypeName +from zarr_metadata.v3.data_type.uint64 import UINT64_DATA_TYPE_NAME, Uint64DataTypeName + +# (name_string, per-dtype literal type) +PRIMITIVE_DTYPES = [ + (BOOL_DATA_TYPE_NAME, BoolDataTypeName), + (INT8_DATA_TYPE_NAME, Int8DataTypeName), + (INT16_DATA_TYPE_NAME, Int16DataTypeName), + (INT32_DATA_TYPE_NAME, Int32DataTypeName), + (INT64_DATA_TYPE_NAME, Int64DataTypeName), + (UINT8_DATA_TYPE_NAME, Uint8DataTypeName), + (UINT16_DATA_TYPE_NAME, Uint16DataTypeName), + (UINT32_DATA_TYPE_NAME, Uint32DataTypeName), + (UINT64_DATA_TYPE_NAME, Uint64DataTypeName), + (FLOAT16_DATA_TYPE_NAME, Float16DataTypeName), + (FLOAT32_DATA_TYPE_NAME, Float32DataTypeName), + (FLOAT64_DATA_TYPE_NAME, Float64DataTypeName), + (COMPLEX64_DATA_TYPE_NAME, Complex64DataTypeName), + (COMPLEX128_DATA_TYPE_NAME, Complex128DataTypeName), + (STRING_DATA_TYPE_NAME, StringDataTypeName), + (BYTES_DATA_TYPE_NAME, BytesDataTypeName), +] + + +@pytest.mark.parametrize(("name", "literal_type"), PRIMITIVE_DTYPES, ids=lambda x: str(x)) +def test_primitive_against_literal(name: str, literal_type: object) -> None: + """The dtype name validates against its declared Literal type.""" + TypeAdapter(literal_type).validate_python(name) + + +@pytest.mark.parametrize("raw_name", ["r8", "r16", "r24", "r256", "r1024"], ids=str) +def test_raw_bytes_name(raw_name: str) -> None: + """`r` names pass the raw_bytes_dtype_name validator.""" + raw_bytes_dtype_name(raw_name) diff --git a/packages/zarr-metadata/tests/v3/data_type/uint16/__init__.py b/packages/zarr-metadata/tests/v3/data_type/uint16/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/uint16/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/uint16/fill_values.json new file mode 100644 index 0000000000..60934f030e --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint16/fill_values.json @@ -0,0 +1,4 @@ +{ + "zero": 0, + "max": 65535 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/uint16/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/uint16/test_fixtures.py new file mode 100644 index 0000000000..f4afaafa8b --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint16/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate uint16 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.uint16 import Uint16FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Uint16FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/uint32/__init__.py b/packages/zarr-metadata/tests/v3/data_type/uint32/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/uint32/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/uint32/fill_values.json new file mode 100644 index 0000000000..1b003f6fab --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint32/fill_values.json @@ -0,0 +1,4 @@ +{ + "zero": 0, + "max": 4294967295 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/uint32/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/uint32/test_fixtures.py new file mode 100644 index 0000000000..cf94a6a829 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint32/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate uint32 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.uint32 import Uint32FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Uint32FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/uint64/__init__.py b/packages/zarr-metadata/tests/v3/data_type/uint64/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/uint64/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/uint64/fill_values.json new file mode 100644 index 0000000000..145703c360 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint64/fill_values.json @@ -0,0 +1,4 @@ +{ + "zero": 0, + "max": 18446744073709551615 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/uint64/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/uint64/test_fixtures.py new file mode 100644 index 0000000000..71851cfeec --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint64/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate uint64 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.uint64 import Uint64FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Uint64FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/data_type/uint8/__init__.py b/packages/zarr-metadata/tests/v3/data_type/uint8/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/data_type/uint8/fill_values.json b/packages/zarr-metadata/tests/v3/data_type/uint8/fill_values.json new file mode 100644 index 0000000000..70e8d5d5bc --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint8/fill_values.json @@ -0,0 +1,4 @@ +{ + "zero": 0, + "max": 255 +} diff --git a/packages/zarr-metadata/tests/v3/data_type/uint8/test_fixtures.py b/packages/zarr-metadata/tests/v3/data_type/uint8/test_fixtures.py new file mode 100644 index 0000000000..4866753971 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/data_type/uint8/test_fixtures.py @@ -0,0 +1,20 @@ +"""Validate uint8 fill-value fixtures.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.data_type.uint8 import Uint8FillValue + +FILL_VALUES: dict[str, object] = json.loads( + (Path(__file__).parent / "fill_values.json").read_text() +) + + +@pytest.mark.parametrize("case", FILL_VALUES.values(), ids=list(FILL_VALUES)) +def test_fill_value(case: object) -> None: + TypeAdapter(Uint8FillValue).validate_python(case) diff --git a/packages/zarr-metadata/tests/v3/group/__init__.py b/packages/zarr-metadata/tests/v3/group/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-metadata/tests/v3/group/minimal.json b/packages/zarr-metadata/tests/v3/group/minimal.json new file mode 100644 index 0000000000..7e86f1938a --- /dev/null +++ b/packages/zarr-metadata/tests/v3/group/minimal.json @@ -0,0 +1,4 @@ +{ + "zarr_format": 3, + "node_type": "group" +} diff --git a/packages/zarr-metadata/tests/v3/group/test_fixtures.py b/packages/zarr-metadata/tests/v3/group/test_fixtures.py new file mode 100644 index 0000000000..ffcdedef2b --- /dev/null +++ b/packages/zarr-metadata/tests/v3/group/test_fixtures.py @@ -0,0 +1,20 @@ +"""Decode v3 group metadata fixtures via pydantic.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import TypeAdapter + +from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON + +FIXTURES_DIR = Path(__file__).parent +FIXTURES = sorted(FIXTURES_DIR.glob("*.json")) +ADAPTER = TypeAdapter(ZarrV3GroupMetadataJSON) + + +@pytest.mark.parametrize("fixture", FIXTURES, ids=lambda p: p.stem) +def test_validate(fixture: Path) -> None: + ADAPTER.validate_python(json.loads(fixture.read_text())) diff --git a/packages/zarr-metadata/tests/v3/group/with_attributes.json b/packages/zarr-metadata/tests/v3/group/with_attributes.json new file mode 100644 index 0000000000..69804b3db0 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/group/with_attributes.json @@ -0,0 +1,8 @@ +{ + "zarr_format": 3, + "node_type": "group", + "attributes": { + "label": "root", + "spatial_units": ["meter", "meter"] + } +} diff --git a/packages/zarr-metadata/tests/v3/group/with_extra_field.json b/packages/zarr-metadata/tests/v3/group/with_extra_field.json new file mode 100644 index 0000000000..01696b53cf --- /dev/null +++ b/packages/zarr-metadata/tests/v3/group/with_extra_field.json @@ -0,0 +1,9 @@ +{ + "zarr_format": 3, + "node_type": "group", + "consolidated_metadata": { + "must_understand": false, + "kind": "inline", + "metadata": {} + } +} diff --git a/pyproject.toml b/pyproject.toml index 93116bede8..4cfe02b0e3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,25 @@ [build-system] -requires = ["hatchling", "hatch-vcs"] +requires = ["hatchling>=1.29.0", "hatch-vcs"] build-backend = "hatchling.build" +# An allowlist, not a blocklist: anything new β€” a subpackage under `packages/`, a +# config file in the repository root β€” stays out of the sdist unless it is named +# here. Beyond `src` and `tests`, the entries are what keeps the shipped test +# suite and docs build runnable from an unpacked sdist: `tests/test_docs.py` +# walks `docs/` and `testpaths` collects `docs/user-guide`; the pages under +# `docs/user-guide/examples/` pull their source out of `examples/` via pymdownx +# snippet includes; `mkdocs.yml` and `mkdocs_hooks.py` let `mkdocs build` run +# too. `pyproject.toml`, `README.md`, `LICENSE.txt` and `.gitignore` are added by +# hatchling itself. +[tool.hatch.build.targets.sdist] +include = [ + "/src", + "/tests", + "/docs", + "/examples", + "/mkdocs.yml", + "/mkdocs_hooks.py", +] [project] name = "zarr" @@ -18,22 +36,22 @@ maintainers = [ { name = "Juan Nunez-Iglesias", email = "juan.nunez-iglesias@monash.edu" }, { name = "Martin Durant", email = "mdurant@anaconda.com" }, { name = "Norman Rzepka" }, - { name = "Ryan Abernathey" } + { name = "Ryan Abernathey" }, + { name = "David Stansby" }, + { name = "Tom Augspurger", email = "tom.w.augspurger@gmail.com" }, + { name = "Deepak Cherian" } ] -requires-python = ">=3.10" -# If you add a new dependency here, please also add it to .pre-commit-config.yml +requires-python = ">=3.12" dependencies = [ - 'asciitree', - 'numpy>=1.24', - 'fasteners', - 'numcodecs>=0.10.0', - 'fsspec>2024', - 'crc32c', - 'zstandard', - 'typing_extensions', - 'donfig', - 'pytest' + 'packaging>=22.0', + 'numpy>=2', + 'numcodecs>=0.14', + 'google-crc32c>=1.5', + 'typing_extensions>=4.14', + 'donfig>=0.8', + 'msgspec>=0.19', ] + dynamic = [ "version", ] @@ -42,117 +60,263 @@ classifiers = [ 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'Intended Audience :: Science/Research', - 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', 'Operating System :: Unix', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.12', + 'Programming Language :: Python :: 3.13', + 'Programming Language :: Python :: 3.14', ] -license = {text = "MIT License"} +license = "MIT" +license-files = ["LICENSE.txt"] keywords = ["Python", "compressed", "ndimensional-arrays", "zarr"] [project.optional-dependencies] -jupyter = [ - 'notebook', - 'ipytree>=0.2.2', - 'ipywidgets>=8.0.0', -] -docs = [ - 'sphinx', - 'sphinx-autobuild>=2021.3.14', - 'sphinx-autoapi', - 'sphinx_design', - 'sphinx-issues', - 'sphinx-copybutton', - 'pydata-sphinx-theme', - 'numpydoc', - 'numcodecs[msgpack]', - "msgpack", - "lmdb", +# User-facing extras (shipped in package metadata) +remote = [ + "fsspec>=2023.10.0", + "obstore>=0.5.1", ] -extra = [ - 'msgpack', -] -optional = [ - 'lmdb', +gpu = [ + "cupy-cuda12x; sys_platform != 'darwin'", ] +cast-value-rs = ["cast-value-rs>=0.4.2"] +cli = ["typer"] +optional = ["universal-pathlib"] + +[project.scripts] +zarr = "zarr._cli.cli:app" + [project.urls] -"Bug Tracker" = "https://github.com/zarr-developers/zarr-python/issues" -Changelog = "https://zarr.readthedocs.io/en/stable/release.html" +issues = "https://github.com/zarr-developers/zarr-python/issues" +changelog = "https://zarr.readthedocs.io/en/stable/release-notes.html" Discussions = "https://github.com/zarr-developers/zarr-python/discussions" -Documentation = "https://zarr.readthedocs.io/" -Homepage = "https://github.com/zarr-developers/zarr-python" +documentation = "https://zarr.readthedocs.io/" +homepage = "https://github.com/zarr-developers/zarr-python" + +# Dev *tooling* is pinned to exact versions for reproducible CI: the hatch envs +# (see `tool.hatch.envs.*`) and bare `uv run` resolve these groups fresh from +# PyPI and do NOT consult uv.lock, so an unrelated tooling release can break CI +# without any change on our side (e.g. the pytest 9.1.0 `duplicate +# parametrization` regression). Runtime/integration deps (fsspec, obstore, s3fs, +# botocore, numcodecs, universal-pathlib) are intentionally left floating so the +# `optional` test matrix keeps exercising their latest releases; their floor and +# bleeding edge are covered by the `min_deps` and `upstream` hatch envs. Bump the +# pins deliberately, e.g. via dependabot or `uv lock --upgrade`. +[dependency-groups] +test = [ + "coverage==7.15.4", + "pytest==9.1.1", + "pytest-asyncio==1.4.0", + "pytest-cov==7.1.0", + "pytest-accept==0.3.0", + "numpydoc==1.10.0", + "hypothesis==6.165.5", + "pytest-reportlog==1.0.0", + "pytest-xdist==3.8.0", + "pytest-benchmark==5.2.3", + "pytest-codspeed==5.0.3", + "tomlkit==0.15.1", + "uv==0.12.3", +] +remote-tests = [ + {include-group = "test"}, + "fsspec>=2023.10.0", + "obstore>=0.5.1", + "botocore", + "s3fs>=2023.10.0", + "moto[s3,server]==5.2.2", + "requests==2.34.2", +] +release = [ + "towncrier==25.8.0", +] +docs = [ + # Doc building + "mkdocs-material[imaging]==9.7.7", + "mkdocs==1.6.1", + "mkdocstrings==1.0.6", + "mkdocstrings-python==2.0.5", + "mike==2.2.0", + "mkdocs-redirects==1.2.3", + "markdown-exec[ansi]==1.12.3", + "griffe-inherited-docstrings==1.1.3", + "ruff==0.16.2", + # Changelog generation + {include-group = "release"}, + # Optional dependencies to run examples + "numcodecs[msgpack]", + "s3fs>=2023.10.0", + "astroid==4.3.0", + "pytest==9.1.1", +] +dev = [ + {include-group = "test"}, + {include-group = "remote-tests"}, + {include-group = "docs"}, + "universal-pathlib", + "mypy==2.3.0", +] [tool.coverage.report] -exclude_lines = [ - "pragma: no cover", - "pragma: ${PY_MAJOR_VERSION} no cover", +exclude_also = [ + 'if TYPE_CHECKING:', ] [tool.coverage.run] omit = [ - "src/zarr/meta_v1.py", "bench/compress_normal.py", ] [tool.hatch] version.source = "vcs" -build.hooks.vcs.version-file = "src/zarr/_version.py" +# Only consider zarr-python's own `v*` tags when deriving the version. Without +# this filter `git describe` matches the most recent tag of any shape, +# including the `zarr_metadata-v*` and `zarr_http_server-v*` tags used to +# release the subpackages under `packages/` β€” which would make a from-source +# build report e.g. a `0.2.x` version instead of `3.x`. +version.raw-options = { git_describe_command = "git describe --dirty --tags --long --match v*" } + +[tool.hatch.build] +hooks.vcs.version-file = "src/zarr/_version.py" + +[tool.hatch.envs.dev] +dependency-groups = ["dev"] [tool.hatch.envs.test] -dependencies = [ - "numpy~={matrix:numpy}", - "universal_pathlib" -] -extra-dependencies = [ - "coverage", - "pytest", - "pytest-cov", - "msgpack", - "lmdb", - "s3fs", - "pytest-asyncio", - "moto[s3]", - "flask-cors", - "flask", - "requests", - "mypy", - "hypothesis" -] -features = ["extra"] +dependency-groups = ["test"] -[[tool.hatch.envs.test.matrix]] -python = ["3.10", "3.11", "3.12"] -numpy = ["1.24", "1.26", "2.0"] -version = ["minimal"] +[tool.hatch.envs.test.env-vars] [[tool.hatch.envs.test.matrix]] -python = ["3.10", "3.11", "3.12"] -numpy = ["1.24", "1.26", "2.0"] -features = ["optional"] +python = ["3.12", "3.13", "3.14"] +deps = ["minimal", "optional"] + +[tool.hatch.envs.test.overrides] +matrix.deps.features = [ + {value = "remote", if = ["optional"]}, + {value = "optional", if = ["optional"]}, + {value = "cli", if = ["optional"]}, + {value = "cast-value-rs", if = ["optional"]}, +] +matrix.deps.dependency-groups = [ + {value = "remote-tests", if = ["optional"]}, +] [tool.hatch.envs.test.scripts] -run-coverage = "pytest --cov-config=pyproject.toml --cov=pkg --cov=tests" -run = "run-coverage --no-cov" +run-coverage = [ + "coverage run --source=src -m pytest --ignore tests/benchmarks --junitxml=junit.xml -o junit_family=legacy {args:}", + "coverage xml", +] +run-coverage-html = [ + "coverage run --source=src -m pytest --ignore tests/benchmarks {args:}", + "coverage html", +] +run = "pytest --ignore tests/benchmarks" run-verbose = "run-coverage --verbose" -run-mypy = "mypy src" -run-hypothesis = "pytest --hypothesis-profile ci tests/v3/test_properties.py" +run-hypothesis = [ + "coverage run --source=src -m pytest -nauto --run-slow-hypothesis tests/test_properties.py tests/test_store/test_stateful* {args:}", + "coverage xml", +] +run-benchmark = "pytest --benchmark-enable tests/benchmarks" +serve-coverage-html = "python -m http.server -d htmlcov 8000" list-env = "pip list" +[tool.hatch.envs.gputest] +template = "test" +extra-dependencies = [ + "universal_pathlib", + # Needed so tests/test_docs.py is collectable under `pytest -m gpu`; otherwise its + # module-level importorskip("pytest_examples") skips the whole module and the gpu + # docs example is never executed on GPU hardware. + "pytest-examples", +] +features = ["gpu"] + +[[tool.hatch.envs.gputest.matrix]] +python = ["3.12", "3.13"] + +[tool.hatch.envs.gputest.scripts] +run-coverage = [ + "coverage run --source=src -m pytest -m gpu --junitxml=junit.xml -o junit_family=legacy --ignore tests/benchmarks {args:}", + "coverage xml", +] +run = "pytest -m gpu --ignore tests/benchmarks" + +[tool.hatch.envs.upstream] +template = 'test' +python = "3.14" +extra-dependencies = [ + 'packaging @ git+https://github.com/pypa/packaging', + 'numpy', # from scientific-python-nightly-wheels + 'numcodecs @ git+https://github.com/zarr-developers/numcodecs', + 's3fs @ git+https://github.com/fsspec/s3fs', + 'universal_pathlib @ git+https://github.com/fsspec/universal_pathlib', + 'typing_extensions @ git+https://github.com/python/typing_extensions', + 'donfig @ git+https://github.com/pytroll/donfig', + 'obstore @ git+https://github.com/developmentseed/obstore@main#subdirectory=obstore', +] + +[tool.hatch.envs.upstream.env-vars] +PIP_INDEX_URL = "https://pypi.anaconda.org/scientific-python-nightly-wheels/simple/" +PIP_EXTRA_INDEX_URL = "https://pypi.org/simple/" +PIP_PRE = "1" + +[tool.hatch.envs.min_deps] +description = """Test environment for minimum supported dependencies + +See Spec 0000 for details and drop schedule: https://scientific-python.org/specs/spec-0000/ +""" +template = "test" +python = "3.12" +features = ["remote"] +dependency-groups = ["remote-tests"] +extra-dependencies = [ + 'packaging==22.*', + 'numpy==2.0.*', + 'numcodecs==0.14.*', # 0.14 needed for zarr3 codecs + 'fsspec==2023.10.0', + 's3fs==2023.10.0', + 'universal_pathlib==0.2.0', + 'typing_extensions==4.14.*', + 'donfig==0.8.*', + 'obstore==0.5.*', + 'msgspec==0.19.*', +] + +[tool.hatch.envs.default] +installer = "uv" + [tool.hatch.envs.docs] -features = ['docs'] +features = ['remote'] +dependency-groups = ['docs'] + +[tool.hatch.envs.docs.env-vars] +DISABLE_MKDOCS_2_WARNING = "true" +NO_MKDOCS_2_WARNING = "true" [tool.hatch.envs.docs.scripts] -build = "cd docs && make html" -serve = "sphinx-autobuild docs docs/_build --host 0.0.0.0" +serve = "mkdocs serve --watch src" +build = "mkdocs build" +check = "mkdocs build --strict" +readthedocs = "rm -rf $READTHEDOCS_OUTPUT/html && cp -r site $READTHEDOCS_OUTPUT/html" + +[tool.hatch.envs.doctest] +description = "Test environment for validating executable code blocks in documentation" +features = ['remote'] +dependency-groups = ['remote-tests'] +extra-dependencies = [ + "pytest-examples", +] + +[tool.hatch.envs.doctest.scripts] +test = "pytest tests/test_docs.py -v" +list-env = "pip list" [tool.ruff] line-length = 100 -src = ["src"] force-exclude = true extend-exclude = [ ".bzr", @@ -171,55 +335,205 @@ extend-exclude = [ "dist", "venv", "docs", + "tests/test_regression/scripts/", # these are scripts that use a different version of python "src/zarr/v2/", "tests/v2/", ] [tool.ruff.lint] extend-select = [ - "B", # flake8-bugbear - "I", # isort - "ISC", - "UP", # pyupgrade - "RSE", + "ANN", # flake8-annotations + "B", # flake8-bugbear + "C4", # flake8-comprehensions + "EXE", # flake8-executable + "FA", # flake8-future-annotations + "FLY", # flynt + "FURB", # refurb + "G", # flake8-logging-format + "I", # isort + "ISC", # flake8-implicit-str-concat + "LOG", # flake8-logging + "PERF", # Perflint + "PIE", # flake8-pie + "PGH", # pygrep-hooks + "PT", # flake8-pytest-style + "PYI", # flake8-pyi + "RET", # flake8-return + "RSE", # flake8-raise "RUF", + "SIM", # flake8-simplify + "SLOT", # flake8-slots + "TC", # flake8-type-checking + "TRY", # tryceratops + "UP", # pyupgrade + "W", # pycodestyle warnings ] ignore = [ + "ANN401", + "PT011", # TODO: apply this rule + "RET505", + "RET506", "RUF005", + "RUF043", + "SIM108", + "TRY003", + # https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules + "W191", + "E111", + "E114", + "E117", + "D206", + "D300", + "Q000", + "Q001", + "Q002", + "Q003", + "COM812", + "COM819", + "TC006", ] +[tool.ruff.lint.extend-per-file-ignores] +"tests/**" = ["ANN001", "ANN201", "RUF029", "SIM117", "SIM300"] + [tool.mypy] -python_version = "3.10" +files = ["src", "tests"] +python_version = "3.12" ignore_missing_imports = true namespace_packages = false - +pretty = true +show_error_code_links = true +show_error_context = true strict = true warn_unreachable = true +enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool", "truthy-iterable"] -enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool"] +[[tool.mypy.overrides]] +module = [ + "tests.package_with_entrypoint.*", + "zarr.testing.stateful", + "tests.test_codecs.test_transpose", + "tests.test_config", + "tests.test_store.test_zip", + "tests.test_store.test_local", + "tests.test_store.test_memory", + "tests.test_codecs.test_codecs", + "tests.test_metadata.*", + "tests.test_store.test_core", + "tests.test_store.test_logging", + "tests.test_store.test_object", + "tests.test_store.test_stateful", + "tests.test_store.test_wrapper", +] +strict = false +# TODO: Move the next modules up to the strict = false section +# and fix the errors [[tool.mypy.overrides]] module = [ - "zarr.v2.*", + "tests.test_store.test_fsspec", + "tests.test_group", + "tests.test_indexing", + "tests.test_properties", + "tests.test_sync", + "tests.test_regression.scripts.*" ] ignore_errors = true [tool.pytest.ini_options] -minversion = "7" -testpaths = ["tests"] +minversion = "9" +testpaths = ["src", "tests", "docs/user-guide"] log_cli_level = "INFO" -xfail_strict = true +log_level = "INFO" +# Enables strict_config, strict_markers, strict_xfail, strict_parametrization_ids, and +# any strictness options added in future pytest releases. Note that the equivalent +# `--strict-config`/`--strict-markers` flags were silently ignored when passed via +# addopts before pytest 9.1 (pytest#14442), so this option is the reliable spelling. +strict = true +# Turn deadlocks into loud failures: if a single test exceeds this many seconds, dump +# every thread's traceback and kill the run (exit_on_timeout is new in pytest 9). Sized +# far above the slowest legitimate test (~20s locally; slower under coverage/Windows/ +# nightly stateful-hypothesis runs) so only a genuine hang can trip it. +faulthandler_timeout = 600 +faulthandler_exit_on_timeout = true asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" doctest_optionflags = [ "NORMALIZE_WHITESPACE", "ELLIPSIS", "IGNORE_EXCEPTION_DETAIL", ] addopts = [ - "--durations=10", "-ra", "--strict-config", "--strict-markers", + "--benchmark-columns", "min,mean,stddev,outliers,rounds,iterations", + "--benchmark-disable", # benchmark routines run as tests without benchmarking instrumentation + "--durations", "10", + "-ra", + "--doctest-modules", + "--ignore=tests/test_regression/scripts", + "--ignore=src/zarr/_cli", ] filterwarnings = [ - "error:::zarr.*", - "ignore:PY_SSIZE_T_CLEAN will be required.*:DeprecationWarning", - "ignore:The loop argument is deprecated since Python 3.8.*:DeprecationWarning", + "error", + "ignore:Unclosed client session None: + """ + Print version info for use in bug reports. + """ + import platform + from importlib.metadata import version + + def print_packages(packages: list[str]) -> None: + not_installed = [] + for package in packages: + try: + print(f"{package}: {version(package)}") + except ModuleNotFoundError: + not_installed.append(package) + if not_installed: + print("\n**Not Installed:**") + for package in not_installed: + print(package) + + required = [ + "packaging", + "numpy", + "numcodecs", + "typing_extensions", + "donfig", + ] + optional = [ + "botocore", + "cupy-cuda12x", + "fsspec", + "numcodecs", + "s3fs", + "gcsfs", + "universal-pathlib", + "obstore", + ] + + print(f"platform: {platform.platform()}") + print(f"python: {platform.python_version()}") + print(f"zarr: {__version__}\n") + print("**Required dependencies:**") + print_packages(required) + print("\n**Optional dependencies:**") + print_packages(optional) + + +# The decorator ensures this always returns the same handler (and it is only +# attached once). +@functools.cache +def _ensure_handler() -> logging.Handler: + """ + The first time this function is called, attach a `StreamHandler` using the + same format as `logging.basicConfig` to the Zarr-Python root logger. + + Return this handler every time this function is called. + """ + handler = logging.StreamHandler() + handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT)) + _logger.addHandler(handler) + return handler + + +def set_log_level( + level: Literal["NOTSET", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], +) -> None: + """Set the logging level for Zarr-Python. + + Zarr-Python uses the standard library `logging` framework under the root + logger 'zarr'. This is a helper function to: + + - set Zarr-Python's root logger level + - set the root logger handler's level, creating the handler + if it does not exist yet + + Parameters + ---------- + level : str + The logging level to set. + """ + _logger.setLevel(level) + _ensure_handler().setLevel(level) + + +def set_format(log_format: str) -> None: + """Set the format of logging messages from Zarr-Python. + + Zarr-Python uses the standard library `logging` framework under the root + logger 'zarr'. This sets the format of log messages from the root logger's StreamHandler. + + Parameters + ---------- + log_format : str + A string determining the log format (as defined in the standard library's `logging` module + for logging.Formatter) + """ + _ensure_handler().setFormatter(logging.Formatter(fmt=log_format)) + + __all__ = [ - "__version__", - "config", "Array", "AsyncArray", - "Group", "AsyncGroup", - "tree", + "Group", + "__version__", "array", + "config", "consolidate_metadata", "copy", "copy_all", "copy_store", "create", + "create_array", + "create_group", + "create_hierarchy", "empty", "empty_like", + "from_array", "full", "full_like", "group", @@ -60,9 +172,11 @@ "open_consolidated", "open_group", "open_like", + "print_debug_info", "save", "save_array", "save_group", + "tree", "zeros", "zeros_like", ] diff --git a/src/zarr/_cli/__init__.py b/src/zarr/_cli/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/zarr/_cli/cli.py b/src/zarr/_cli/cli.py new file mode 100644 index 0000000000..de55826582 --- /dev/null +++ b/src/zarr/_cli/cli.py @@ -0,0 +1,187 @@ +import logging +from enum import StrEnum +from typing import Annotated, Literal, cast + +import typer + +import zarr +import zarr.metadata.migrate_v3 as migrate_metadata +from zarr.core.common import ZarrFormat +from zarr.core.sync import sync +from zarr.storage._common import make_store + +app = typer.Typer() + +logger = logging.getLogger(__name__) + + +def _set_logging_level(*, verbose: bool) -> None: + if verbose: + lvl = "INFO" + else: + lvl = "WARNING" + zarr.set_log_level(cast(Literal["INFO", "WARNING"], lvl)) + zarr.set_format("%(message)s") + + +class CLIZarrFormat(StrEnum): + v2 = "v2" + v3 = "v3" + + +class CLIZarrFormatV3(StrEnum): + """Limit CLI choice to only v3""" + + v3 = "v3" + + +@app.command() # type: ignore[untyped-decorator] +def migrate( + zarr_format: Annotated[ + CLIZarrFormatV3, + typer.Argument( + help="Zarr format to migrate to. Currently only 'v3' is supported.", + ), + ], + input_store: Annotated[ + str, + typer.Argument( + help=( + "Input Zarr to migrate - should be a store, path to directory in file system or name of zip file " + "e.g. 'data/example-1.zarr', 's3://example-bucket/example'..." + ) + ), + ], + output_store: Annotated[ + str | None, + typer.Argument( + help=( + "Output location to write generated metadata (no array data will be copied). If not provided, " + "metadata will be written to input_store. Should be a store, path to directory in file system " + "or name of zip file e.g. 'data/example-1.zarr', 's3://example-bucket/example'..." + ) + ), + ] = None, + dry_run: Annotated[ + bool, + typer.Option( + help="Enable a dry-run: files that would be converted are logged, but no new files are created or changed." + ), + ] = False, + overwrite: Annotated[ + bool, + typer.Option( + help="Remove any existing v3 metadata at the output location, before migration starts." + ), + ] = False, + force: Annotated[ + bool, + typer.Option( + help=( + "Only used when --overwrite is given. Allows v3 metadata to be removed when no valid " + "v2 metadata exists at the output location." + ) + ), + ] = False, + remove_v2_metadata: Annotated[ + bool, + typer.Option( + help="Remove v2 metadata (if any) from the output location, after migration is complete." + ), + ] = False, +) -> None: + """Migrate all v2 metadata in a zarr hierarchy to v3. This will create a zarr.json file for each level + (every group / array). v2 files (.zarray, .zattrs etc.) will be left as-is. + """ + if dry_run: + _set_logging_level(verbose=True) + logger.info( + "Dry run enabled - no new files will be created or changed. Log of files that would be created on a real run:" + ) + + input_zarr_store = sync(make_store(input_store, mode="r+")) + + if output_store is not None: + output_zarr_store = sync(make_store(output_store, mode="w-")) + write_store = output_zarr_store + else: + output_zarr_store = None + write_store = input_zarr_store + + if overwrite: + sync(migrate_metadata.remove_metadata(write_store, 3, force=force, dry_run=dry_run)) + + migrate_metadata.migrate_v2_to_v3( + input_store=input_zarr_store, output_store=output_zarr_store, dry_run=dry_run + ) + + if remove_v2_metadata: + # There should always be valid v3 metadata at the output location after migration, so force=False + sync(migrate_metadata.remove_metadata(write_store, 2, force=False, dry_run=dry_run)) + + +@app.command() # type: ignore[untyped-decorator] +def remove_metadata( + zarr_format: Annotated[ + CLIZarrFormat, + typer.Argument(help="Which format's metadata to remove - v2 or v3."), + ], + store: Annotated[ + str, + typer.Argument( + help="Store or path to directory in file system or name of zip file e.g. 'data/example-1.zarr', 's3://example-bucket/example'..." + ), + ], + force: Annotated[ + bool, + typer.Option( + help=( + "Allow metadata to be deleted when no valid alternative exists e.g. allow deletion of v2 metadata, " + "when no v3 metadata is present." + ) + ), + ] = False, + dry_run: Annotated[ + bool, + typer.Option( + help="Enable a dry-run: files that would be deleted are logged, but no files are removed or changed." + ), + ] = False, +) -> None: + """Remove all v2 (.zarray, .zattrs, .zgroup, .zmetadata) or v3 (zarr.json) metadata files from the given Zarr. + Note - this will remove metadata files at all levels of the hierarchy (every group and array). + """ + if dry_run: + _set_logging_level(verbose=True) + logger.info( + "Dry run enabled - no files will be deleted or changed. Log of files that would be deleted on a real run:" + ) + input_zarr_store = sync(make_store(store, mode="r+")) + + sync( + migrate_metadata.remove_metadata( + store=input_zarr_store, + zarr_format=cast(ZarrFormat, int(zarr_format[1:])), + force=force, + dry_run=dry_run, + ) + ) + + +@app.callback() # type: ignore[untyped-decorator] +def main( + verbose: Annotated[ + bool, + typer.Option( + help="enable verbose logging - will print info about metadata files being deleted / saved." + ), + ] = False, +) -> None: + """ + See available commands below - access help for individual commands with zarr COMMAND --help. + """ + _set_logging_level(verbose=verbose) + + +if __name__ == "__main__": + app() diff --git a/src/zarr/_compat.py b/src/zarr/_compat.py new file mode 100644 index 0000000000..ce6be34c22 --- /dev/null +++ b/src/zarr/_compat.py @@ -0,0 +1,108 @@ +import warnings +from collections.abc import Callable +from functools import wraps +from inspect import Parameter, signature +from typing import TYPE_CHECKING, Any + +import numpy as np +from packaging.version import Version + +from zarr.errors import ZarrFutureWarning + +if TYPE_CHECKING: + from numpy.typing import NDArray + +# Based off https://github.com/scikit-learn/scikit-learn/blob/e87b32a81c70abed8f2e97483758eb64df8255e9/sklearn/utils/validation.py#L63 + + +def _deprecate_positional_args[T]( + func: Callable[..., T] | None = None, *, version: str = "3.1.0" +) -> Callable[..., T]: + """Decorator for methods that issues warnings for positional arguments. + + Using the keyword-only argument syntax in pep 3102, arguments after the + * will issue a warning when passed as a positional argument. + + Parameters + ---------- + func : callable, default=None + Function to check arguments on. + version : callable, default="3.1.0" + The version when positional arguments will result in error. + """ + + def _inner_deprecate_positional_args(f: Callable[..., T]) -> Callable[..., T]: + sig = signature(f) + kwonly_args = [] + all_args = [] + + for name, param in sig.parameters.items(): + if param.kind == Parameter.POSITIONAL_OR_KEYWORD: + all_args.append(name) + elif param.kind == Parameter.KEYWORD_ONLY: + kwonly_args.append(name) + + @wraps(f) + def inner_f(*args: Any, **kwargs: Any) -> T: + extra_args = len(args) - len(all_args) + if extra_args <= 0: + return f(*args, **kwargs) + + # extra_args > 0 + args_msg = [ + f"{name}={arg}" + for name, arg in zip(kwonly_args[:extra_args], args[-extra_args:], strict=False) + ] + formatted_args_msg = ", ".join(args_msg) + warnings.warn( + ( + f"Pass {formatted_args_msg} as keyword args. From version " + f"{version} passing these as positional arguments " + "will result in an error" + ), + ZarrFutureWarning, + stacklevel=2, + ) + kwargs.update(zip(sig.parameters, args, strict=False)) + return f(**kwargs) + + return inner_f + + if func is not None: + return _inner_deprecate_positional_args(func) + + return _inner_deprecate_positional_args # type: ignore[return-value] + + +def _reshape_view(arr: "NDArray[Any]", shape: tuple[int, ...]) -> "NDArray[Any]": + """Reshape an array without copying data. + + This function provides compatibility across NumPy versions for reshaping arrays + as views. On NumPy >= 2.1, it uses ``reshape(copy=False)`` which explicitly + fails if a view cannot be created. On older versions, it uses direct shape + assignment which has the same behavior but is deprecated in 2.5+. + + Parameters + ---------- + arr : NDArray + The array to reshape. + shape : tuple of int + The new shape. + + Returns + ------- + NDArray + A reshaped view of the array. + + Raises + ------ + AttributeError + If a view cannot be created (the array is not contiguous) on NumPy < 2.1. + ValueError + If a view cannot be created (the array is not contiguous) on NumPy >= 2.1. + """ + if Version(np.__version__) >= Version("2.1"): + return arr.reshape(shape, copy=False) + else: + arr.shape = shape + return arr diff --git a/src/zarr/abc/buffer.py b/src/zarr/abc/buffer.py new file mode 100644 index 0000000000..3d5ac07157 --- /dev/null +++ b/src/zarr/abc/buffer.py @@ -0,0 +1,9 @@ +from zarr.core.buffer.core import ArrayLike, Buffer, BufferPrototype, NDArrayLike, NDBuffer + +__all__ = [ + "ArrayLike", + "Buffer", + "BufferPrototype", + "NDArrayLike", + "NDBuffer", +] diff --git a/src/zarr/abc/codec.py b/src/zarr/abc/codec.py index 9223019fab..34d349e6d1 100644 --- a/src/zarr/abc/codec.py +++ b/src/zarr/abc/codec.py @@ -1,37 +1,121 @@ from __future__ import annotations from abc import abstractmethod -from collections.abc import Awaitable, Callable, Iterable -from typing import TYPE_CHECKING, Any, Generic, TypeVar +from collections.abc import Mapping +from typing import TYPE_CHECKING, Literal, Protocol, TypeGuard, runtime_checkable -import numpy as np +from typing_extensions import ReadOnly, TypedDict from zarr.abc.metadata import Metadata -from zarr.abc.store import ByteGetter, ByteSetter -from zarr.buffer import Buffer, NDBuffer -from zarr.chunk_grids import ChunkGrid -from zarr.common import ChunkCoords, concurrent_map -from zarr.config import config +from zarr.core.buffer import Buffer, NDBuffer +from zarr.core.common import NamedConfig, concurrent_map +from zarr.core.config import config if TYPE_CHECKING: - from typing_extensions import Self + from collections.abc import Awaitable, Callable, Iterable + from typing import Self - from zarr.array_spec import ArraySpec - from zarr.common import JSON - from zarr.indexing import SelectorTuple + from zarr.abc.store import ByteGetter, ByteSetter, Store + from zarr.core.array_spec import ArraySpec + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType + from zarr.core.indexing import SelectorTuple + from zarr.core.metadata import ArrayMetadata + from zarr.core.metadata.v3 import ChunkGridMetadata -CodecInput = TypeVar("CodecInput", bound=NDBuffer | Buffer) -CodecOutput = TypeVar("CodecOutput", bound=NDBuffer | Buffer) +__all__ = [ + "ArrayArrayCodec", + "ArrayBytesCodec", + "ArrayBytesCodecPartialDecodeMixin", + "ArrayBytesCodecPartialEncodeMixin", + "BaseCodec", + "BytesBytesCodec", + "CodecInput", + "CodecOutput", + "CodecPipeline", + "GetResult", + "SupportsSyncCodec", +] -class _Codec(Generic[CodecInput, CodecOutput], Metadata): +class GetResult(TypedDict): + """Metadata about a store get operation.""" + + status: Literal["present", "missing"] + + +type CodecInput = NDBuffer | Buffer +type CodecOutput = NDBuffer | Buffer + + +class CodecJSON_V2[TName: str](TypedDict): + """The JSON representation of a codec for Zarr V2""" + + id: ReadOnly[TName] + + +def _check_codecjson_v2(data: object) -> TypeGuard[CodecJSON_V2[str]]: + return isinstance(data, Mapping) and "id" in data and isinstance(data["id"], str) + + +CodecJSON_V3 = str | NamedConfig[str, Mapping[str, object]] +"""The JSON representation of a codec for Zarr V3.""" + +# The widest type we will *accept* for a codec JSON +# This covers v2 and v3 +CodecJSON = str | Mapping[str, object] +"""The widest type of JSON-like input that could specify a codec.""" + + +@runtime_checkable +class SupportsSyncCodec[CI: CodecInput, CO: CodecOutput](Protocol): + """Protocol for codecs that support synchronous encode/decode. + + Codecs implementing this protocol provide `_decode_sync` and `_encode_sync` + methods that perform encoding/decoding without requiring an async event loop. + + The type parameters mirror `BaseCodec`: `CI` is the decoded type and `CO` is + the encoded type. + """ + + def _decode_sync(self, chunk_data: CO, chunk_spec: ArraySpec) -> CI: ... + + def _encode_sync(self, chunk_data: CI, chunk_spec: ArraySpec) -> CO | None: ... + + +def _codec_supports_sync(codec: object) -> bool: + """Whether `codec` can actually run on a synchronous (no event loop) path. + + Structural membership in `SupportsSyncCodec` is necessary but not always + sufficient: a codec can provide `_decode_sync`/`_encode_sync` whose ability + to run depends on runtime configuration the type system cannot see. + `ShardingCodec` is the canonical case β€” its sync methods delegate to its + configured inner and index codec chains, so they only work when every codec + in those chains is itself sync-capable. Such codecs opt out dynamically via + a `_sync_capable` attribute/property (absent means capable). + """ + return isinstance(codec, SupportsSyncCodec) and getattr(codec, "_sync_capable", True) + + +class BaseCodec[CI: CodecInput, CO: CodecOutput](Metadata): """Generic base class for codecs. - Please use ArrayArrayCodec, ArrayBytesCodec or BytesBytesCodec for subclassing. Codecs can be registered via zarr.codecs.registry. + + Warnings + -------- + This class is not intended to be directly, please use + ArrayArrayCodec, ArrayBytesCodec or BytesBytesCodec for subclassing. """ - is_fixed_size: bool + # Whether this codec's encoded output is a fixed size given a fixed input + # size. Defaults to False (the conservative answer): a codec that does not + # explicitly opt in is treated as variable-size, which only disables + # size-dependent fast paths (e.g. the sharding bulk-decode), never + # correctness. Codecs with genuinely fixed-size output (BytesCodec, + # TransposeCodec, ...) override this with True. The default also keeps + # third-party / variable-length codecs (VLenUTF8, numcodecs wrappers) that + # never set the attribute from raising AttributeError where it is read. + is_fixed_size: bool = False @abstractmethod def compute_encoded_size(self, input_byte_length: int, chunk_spec: ArraySpec) -> int: @@ -70,7 +154,7 @@ def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: Parameters ---------- - chunk_spec : ArraySpec + array_spec : ArraySpec Returns ------- @@ -78,28 +162,33 @@ def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: """ return self - def validate(self, *, shape: ChunkCoords, dtype: np.dtype[Any], chunk_grid: ChunkGrid) -> None: + def validate( + self, + *, + shape: tuple[int, ...], + dtype: ZDType[TBaseDType, TBaseScalar], + chunk_grid: ChunkGridMetadata, + ) -> None: """Validates that the codec configuration is compatible with the array metadata. Raises errors when the codec configuration is not compatible. Parameters ---------- - shape: ChunkCoords + shape : tuple[int, ...] The array shape - dtype: np.dtype[Any] + dtype : np.dtype[Any] The array data type - chunk_grid: ChunkGrid - The array chunk grid + chunk_grid : ChunkGridMetadata + The array chunk grid metadata """ - ... - async def _decode_single(self, chunk_data: CodecOutput, chunk_spec: ArraySpec) -> CodecInput: - raise NotImplementedError + async def _decode_single(self, chunk_data: CO, chunk_spec: ArraySpec) -> CI: + raise NotImplementedError # pragma: no cover async def decode( self, - chunks_and_specs: Iterable[tuple[CodecOutput | None, ArraySpec]], - ) -> Iterable[CodecInput | None]: + chunks_and_specs: Iterable[tuple[CO | None, ArraySpec]], + ) -> Iterable[CI | None]: """Decodes a batch of chunks. Chunks can be None in which case they are ignored by the codec. @@ -110,51 +199,43 @@ async def decode( Returns ------- - Iterable[CodecInput | None] + Iterable[CI | None] """ - return await batching_helper(self._decode_single, chunks_and_specs) + return await _batching_helper(self._decode_single, chunks_and_specs) - async def _encode_single( - self, chunk_data: CodecInput, chunk_spec: ArraySpec - ) -> CodecOutput | None: - raise NotImplementedError + async def _encode_single(self, chunk_data: CI, chunk_spec: ArraySpec) -> CO | None: + raise NotImplementedError # pragma: no cover async def encode( self, - chunks_and_specs: Iterable[tuple[CodecInput | None, ArraySpec]], - ) -> Iterable[CodecOutput | None]: + chunks_and_specs: Iterable[tuple[CI | None, ArraySpec]], + ) -> Iterable[CO | None]: """Encodes a batch of chunks. Chunks can be None in which case they are ignored by the codec. Parameters ---------- - chunks_and_specs : Iterable[tuple[CodecInput | None, ArraySpec]] + chunks_and_specs : Iterable[tuple[CI | None, ArraySpec]] Ordered set of to-be-encoded chunks with their accompanying chunk spec. Returns ------- Iterable[CodecOutput | None] """ - return await batching_helper(self._encode_single, chunks_and_specs) + return await _batching_helper(self._encode_single, chunks_and_specs) -class ArrayArrayCodec(_Codec[NDBuffer, NDBuffer]): +class ArrayArrayCodec(BaseCodec[NDBuffer, NDBuffer]): """Base class for array-to-array codecs.""" - ... - -class ArrayBytesCodec(_Codec[NDBuffer, Buffer]): +class ArrayBytesCodec(BaseCodec[NDBuffer, Buffer]): """Base class for array-to-bytes codecs.""" - ... - -class BytesBytesCodec(_Codec[Buffer, Buffer]): +class BytesBytesCodec(BaseCodec[Buffer, Buffer]): """Base class for bytes-to-bytes codecs.""" - ... - Codec = ArrayArrayCodec | ArrayBytesCodec | BytesBytesCodec @@ -204,7 +285,7 @@ async def _encode_partial_single( selection: SelectorTuple, chunk_spec: ArraySpec, ) -> None: - raise NotImplementedError + raise NotImplementedError # pragma: no cover async def encode_partial( self, @@ -231,7 +312,7 @@ async def encode_partial( ) -class CodecPipeline(Metadata): +class CodecPipeline: """Base class for implementing CodecPipeline. A CodecPipeline implements the read and write paths for chunk data. On the read path, it is responsible for fetching chunks from a store (via ByteGetter), @@ -255,12 +336,12 @@ def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: @classmethod @abstractmethod - def from_list(cls, codecs: Iterable[Codec]) -> Self: - """Creates a codec pipeline from a list of codecs. + def from_codecs(cls, codecs: Iterable[Codec]) -> Self: + """Creates a codec pipeline from an iterable of codecs. Parameters ---------- - codecs : list[Codec] + codecs : Iterable[Codec] Returns ------- @@ -268,6 +349,25 @@ def from_list(cls, codecs: Iterable[Codec]) -> Self: """ ... + @classmethod + def from_array_metadata_and_store(cls, array_metadata: ArrayMetadata, store: Store) -> Self: + """Creates a codec pipeline from array metadata and a store path. + + Raises NotImplementedError by default, indicating the CodecPipeline must be created with from_codecs instead. + + Parameters + ---------- + array_metadata : ArrayMetadata + store : Store + + Returns + ------- + Self + """ + raise NotImplementedError( + f"'{type(cls).__name__}' does not implement CodecPipeline.from_array_metadata_and_store." + ) + @property @abstractmethod def supports_partial_decode(self) -> bool: ... @@ -277,18 +377,24 @@ def supports_partial_decode(self) -> bool: ... def supports_partial_encode(self) -> bool: ... @abstractmethod - def validate(self, *, shape: ChunkCoords, dtype: np.dtype[Any], chunk_grid: ChunkGrid) -> None: + def validate( + self, + *, + shape: tuple[int, ...], + dtype: ZDType[TBaseDType, TBaseScalar], + chunk_grid: ChunkGridMetadata, + ) -> None: """Validates that all codec configurations are compatible with the array metadata. Raises errors when a codec configuration is not compatible. Parameters ---------- - shape: ChunkCoords + shape : tuple[int, ...] The array shape - dtype: np.dtype[Any] + dtype : np.dtype[Any] The array data type - chunk_grid: ChunkGrid - The array chunk grid + chunk_grid : ChunkGridMetadata + The array chunk grid metadata """ ... @@ -299,7 +405,7 @@ def compute_encoded_size(self, byte_length: int, array_spec: ArraySpec) -> int: Parameters ---------- - input_byte_length : int + byte_length : int array_spec : ArraySpec Returns @@ -318,7 +424,7 @@ async def decode( Parameters ---------- - chunks_and_specs : Iterable[tuple[Buffer | None, ArraySpec]] + chunk_bytes_and_specs : Iterable[tuple[Buffer | None, ArraySpec]] Ordered set of encoded chunks with their accompanying chunk spec. Returns @@ -337,7 +443,7 @@ async def encode( Parameters ---------- - chunks_and_specs : Iterable[tuple[NDBuffer | None, ArraySpec]] + chunk_arrays_and_specs : Iterable[tuple[NDBuffer | None, ArraySpec]] Ordered set of to-be-encoded chunks with their accompanying chunk spec. Returns @@ -349,29 +455,39 @@ async def encode( @abstractmethod async def read( self, - batch_info: Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple]], + batch_info: Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], out: NDBuffer, drop_axes: tuple[int, ...] = (), - ) -> None: + ) -> tuple[GetResult, ...]: """Reads chunk data from the store, decodes it and writes it into an output array. Partial decoding may be utilized if the codecs and stores support it. Parameters ---------- - batch_info : Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple]] + batch_info : Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple, bool]] Ordered set of information about the chunks. The first slice selection determines which parts of the chunk will be fetched. The second slice selection determines where in the output array the chunk data will be written. The ByteGetter is used to fetch the necessary bytes. The chunk spec contains information about the construction of an array from the bytes. + + If the Store returns ``None`` for a chunk, then the chunk was not + written and the implementation must set the values of that chunk (or + ``out``) to the fill value for the array. + out : NDBuffer + + Returns + ------- + tuple[GetResult, ...] + One result per chunk in ``batch_info``. """ ... @abstractmethod async def write( self, - batch_info: Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple]], + batch_info: Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], value: NDBuffer, drop_axes: tuple[int, ...] = (), ) -> None: @@ -381,7 +497,7 @@ async def write( Parameters ---------- - batch_info : Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple]] + batch_info : Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple, bool]] Ordered set of information about the chunks. The first slice selection determines which parts of the chunk will be encoded. The second slice selection determines where in the value array the chunk data is located. @@ -391,31 +507,22 @@ async def write( """ ... - @classmethod - def from_dict(cls, data: Iterable[JSON | Codec]) -> Self: - """ - Create an instance of the model from a dictionary - """ - ... - - return cls(**data) - -async def batching_helper( - func: Callable[[CodecInput, ArraySpec], Awaitable[CodecOutput | None]], - batch_info: Iterable[tuple[CodecInput | None, ArraySpec]], -) -> list[CodecOutput | None]: +async def _batching_helper[CI: CodecInput, CO: CodecOutput]( + func: Callable[[CI, ArraySpec], Awaitable[CO | None]], + batch_info: Iterable[tuple[CI | None, ArraySpec]], +) -> list[CO | None]: return await concurrent_map( list(batch_info), - noop_for_none(func), + _noop_for_none(func), config.get("async.concurrency"), ) -def noop_for_none( - func: Callable[[CodecInput, ArraySpec], Awaitable[CodecOutput | None]], -) -> Callable[[CodecInput | None, ArraySpec], Awaitable[CodecOutput | None]]: - async def wrap(chunk: CodecInput | None, chunk_spec: ArraySpec) -> CodecOutput | None: +def _noop_for_none[CI: CodecInput, CO: CodecOutput]( + func: Callable[[CI, ArraySpec], Awaitable[CO | None]], +) -> Callable[[CI | None, ArraySpec], Awaitable[CO | None]]: + async def wrap(chunk: CI | None, chunk_spec: ArraySpec) -> CO | None: if chunk is None: return None return await func(chunk, chunk_spec) diff --git a/src/zarr/abc/metadata.py b/src/zarr/abc/metadata.py index a14ffb8ce9..a56f986645 100644 --- a/src/zarr/abc/metadata.py +++ b/src/zarr/abc/metadata.py @@ -4,23 +4,24 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from typing_extensions import Self + from typing import Self + + from zarr.core.common import JSON from dataclasses import dataclass, fields -from zarr.common import JSON +__all__ = ["Metadata"] @dataclass(frozen=True) class Metadata: - def to_dict(self) -> JSON: + def to_dict(self) -> dict[str, JSON]: """ Recursively serialize this model to a dictionary. This method inspects the fields of self and calls `x.to_dict()` for any fields that are instances of `Metadata`. Sequences of `Metadata` are similarly recursed into, and the output of that recursion is collected in a list. """ - ... out_dict = {} for field in fields(self): key = field.name @@ -41,6 +42,5 @@ def from_dict(cls, data: dict[str, JSON]) -> Self: """ Create an instance of the model from a dictionary """ - ... return cls(**data) diff --git a/src/zarr/abc/numcodec.py b/src/zarr/abc/numcodec.py new file mode 100644 index 0000000000..d60422209a --- /dev/null +++ b/src/zarr/abc/numcodec.py @@ -0,0 +1,99 @@ +from typing import Any, Protocol, Self, TypeGuard + + +class Numcodec(Protocol): + """ + A protocol that models the ``numcodecs.abc.Codec`` interface. + + This protocol should be considered experimental. Expect the type annotations for ``buf`` and + ``out`` to narrow in the future. + """ + + codec_id: str + + def encode(self, buf: Any) -> Any: + """Encode data from ``buf``. + + Parameters + ---------- + buf : Any + Data to be encoded. + + Returns + ------- + enc: Any + Encoded data. + """ + ... + + def decode(self, buf: Any, out: Any | None = None) -> Any: + """ + Decode data in ``buf``. + + Parameters + ---------- + buf : Any + Encoded data. + out : Any + Writeable buffer to store decoded data. If provided, this buffer must + be exactly the right size to store the decoded data. + + Returns + ------- + dec : Any + Decoded data. + """ + ... + + def get_config(self) -> Any: + """ + Return a JSON-serializable configuration dictionary for this + codec. Must include an ``'id'`` field with the codec identifier. + """ + ... + + @classmethod + def from_config(cls, config: Any) -> Self: + """ + Instantiate a codec from a configuration dictionary. + + Parameters + ---------- + config : Any + A configuration dictionary for this codec. + """ + ... + + +def _is_numcodec_cls(obj: object) -> TypeGuard[type[Numcodec]]: + """ + Check if the given object is a class implements the Numcodec protocol. + + The @runtime_checkable decorator does not allow issubclass checks for protocols with non-method + members (i.e., attributes), so we use this function to manually check for the presence of the + required attributes and methods on a given object. + """ + return ( + isinstance(obj, type) + and hasattr(obj, "codec_id") + and isinstance(obj.codec_id, str) + and hasattr(obj, "encode") + and callable(obj.encode) + and hasattr(obj, "decode") + and callable(obj.decode) + and hasattr(obj, "get_config") + and callable(obj.get_config) + and hasattr(obj, "from_config") + and callable(obj.from_config) + ) + + +def _is_numcodec(obj: object) -> TypeGuard[Numcodec]: + """ + Check if the given object implements the Numcodec protocol. + + The @runtime_checkable decorator does not allow issubclass checks for protocols with non-method + members (i.e., attributes), so we use this function to manually check for the presence of the + required attributes and methods on a given object. + """ + return _is_numcodec_cls(type(obj)) diff --git a/src/zarr/abc/store.py b/src/zarr/abc/store.py index 449816209b..af528ec533 100644 --- a/src/zarr/abc/store.py +++ b/src/zarr/abc/store.py @@ -1,89 +1,216 @@ +from __future__ import annotations + +import asyncio from abc import ABC, abstractmethod -from collections.abc import AsyncGenerator -from typing import Any, NamedTuple, Protocol, runtime_checkable +from dataclasses import dataclass +from functools import partial +from itertools import starmap +from typing import TYPE_CHECKING, Literal, Protocol, runtime_checkable -from typing_extensions import Self +if TYPE_CHECKING: + from collections.abc import AsyncGenerator, AsyncIterator, Iterable, Sequence + from types import TracebackType + from typing import Any, Self -from zarr.buffer import Buffer, BufferPrototype -from zarr.common import AccessModeLiteral, BytesLike + from zarr.core.buffer import Buffer, BufferPrototype +__all__ = [ + "ByteGetter", + "ByteSetter", + "Store", + "SupportsDeleteSync", + "SupportsGetSync", + "SupportsSetSync", + "SupportsSyncStore", + "SyncByteGetter", + "SyncByteSetter", + "set_or_delete", +] -class AccessMode(NamedTuple): - readonly: bool - overwrite: bool - create: bool - update: bool - @classmethod - def from_literal(cls, mode: AccessModeLiteral) -> Self: - if mode in ("r", "r+", "a", "w", "w-"): - return cls( - readonly=mode == "r", - overwrite=mode == "w", - create=mode in ("a", "w", "w-"), - update=mode in ("r+", "a"), - ) - raise ValueError("mode must be one of 'r', 'r+', 'w', 'w-', 'a'") +@dataclass(frozen=True, slots=True) +class RangeByteRequest: + """Request a specific byte range""" + + start: int + """The start of the byte range request (inclusive).""" + end: int + """The end of the byte range request (exclusive).""" + + +@dataclass(frozen=True, slots=True) +class OffsetByteRequest: + """Request all bytes starting from a given byte offset""" + + offset: int + """The byte offset for the offset range request.""" + + +@dataclass(frozen=True, slots=True) +class SuffixByteRequest: + """Request up to the last `n` bytes""" + + suffix: int + """The number of bytes from the suffix to request.""" + + +type ByteRequest = RangeByteRequest | OffsetByteRequest | SuffixByteRequest class Store(ABC): - _mode: AccessMode + """ + Abstract base class for Zarr stores. + """ + + _read_only: bool _is_open: bool - def __init__(self, mode: AccessModeLiteral = "r", *args: Any, **kwargs: Any): + def __init__(self, *, read_only: bool = False) -> None: self._is_open = False - self._mode = AccessMode.from_literal(mode) + self._read_only = read_only @classmethod async def open(cls, *args: Any, **kwargs: Any) -> Self: + """ + Create and open the store. + + Parameters + ---------- + *args : Any + Positional arguments to pass to the store constructor. + **kwargs : Any + Keyword arguments to pass to the store constructor. + + Returns + ------- + Store + The opened store instance. + """ store = cls(*args, **kwargs) await store._open() return store + def with_read_only(self, read_only: bool = False) -> Store: + """ + Return a new store with a new read_only setting. + + The new store points to the same location with the specified new read_only state. + The returned Store is not automatically opened, and this store is + not automatically closed. + + Parameters + ---------- + read_only + If True, the store will be created in read-only mode. Defaults to False. + + Returns + ------- + A new store of the same type with the new read only attribute. + """ + raise NotImplementedError( + f"with_read_only is not implemented for the {type(self)} store type." + ) + + def __enter__(self) -> Self: + """Enter a context manager that will close the store upon exiting.""" + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + """Close the store.""" + self.close() + async def _open(self) -> None: + """ + Open the store. + + Raises + ------ + ValueError + If the store is already open. + """ if self._is_open: raise ValueError("store is already open") - if not await self.empty(): - if self.mode.update or self.mode.readonly: - pass - elif self.mode.overwrite: - await self.clear() - else: - raise FileExistsError("Store already exists") self._is_open = True async def _ensure_open(self) -> None: + """Open the store if it is not already open.""" if not self._is_open: await self._open() - @abstractmethod - async def empty(self) -> bool: ... + async def is_empty(self, prefix: str) -> bool: + """ + Check if the directory is empty. - @abstractmethod - async def clear(self) -> None: ... + Parameters + ---------- + prefix : str + Prefix of keys to check. + + Returns + ------- + bool + True if the store is empty, False otherwise. + """ + if not self.supports_listing: + raise NotImplementedError + if prefix != "" and not prefix.endswith("/"): + prefix += "/" + async for _ in self.list_prefix(prefix): + return False + return True + + async def clear(self) -> None: + """ + Clear the store. + + Remove all keys and values from the store. + """ + if not self.supports_deletes: + raise NotImplementedError + if not self.supports_listing: + raise NotImplementedError + self._check_writable() + await self.delete_dir("") @property - def mode(self) -> AccessMode: - """Access mode of the store.""" - return self._mode + def read_only(self) -> bool: + """Is the store read-only?""" + return self._read_only def _check_writable(self) -> None: - if self.mode.readonly: - raise ValueError("store mode does not support writing") + """Raise an exception if the store is not writable.""" + if self.read_only: + raise ValueError("store was opened in read-only mode and does not support writing") + + @abstractmethod + def __eq__(self, value: object) -> bool: + """Equality comparison.""" + ... @abstractmethod async def get( self, key: str, prototype: BufferPrototype, - byte_range: tuple[int | None, int | None] | None = None, + byte_range: ByteRequest | None = None, ) -> Buffer | None: """Retrieve the value associated with a given key. Parameters ---------- key : str - byte_range : tuple[int, Optional[int]], optional + prototype : BufferPrototype + The prototype of the output buffer. Stores may support a default buffer prototype. + byte_range : ByteRequest, optional + ByteRequest may be one of the following. If not provided, all data associated with the key is retrieved. + - RangeByteRequest(int, int): Request a specific range of bytes in the form (start, end). The end is exclusive. If the given range is zero-length or starts after the end of the object, an error will be returned. Additionally, if the range ends after the end of the object, the entire remainder of the object will be returned. Otherwise, the exact requested range will be returned. + - OffsetByteRequest(int): Request all bytes starting from a given byte offset. This is equivalent to bytes={int}- as an HTTP header. + - SuffixByteRequest(int): Request the last int bytes. Note that here, int is the size of the request, not the byte offset. This is equivalent to bytes=-{int} as an HTTP header. Returns ------- @@ -95,13 +222,15 @@ async def get( async def get_partial_values( self, prototype: BufferPrototype, - key_ranges: list[tuple[str, tuple[int | None, int | None]]], + key_ranges: Iterable[tuple[str, ByteRequest | None]], ) -> list[Buffer | None]: """Retrieve possibly partial values from given key_ranges. Parameters ---------- - key_ranges : list[tuple[str, tuple[int, int]]] + prototype : BufferPrototype + The prototype of the output buffer. Stores may support a default buffer prototype. + key_ranges : Iterable[tuple[str, tuple[int | None, int | None]]] Ordered set of key, range pairs, a key may occur multiple times with different ranges Returns @@ -141,35 +270,64 @@ async def set(self, key: str, value: Buffer) -> None: """ ... - @abstractmethod - async def delete(self, key: str) -> None: - """Remove a key from the store + async def set_if_not_exists(self, key: str, value: Buffer) -> None: + """ + Store a key to ``value`` if the key is not already present. Parameters ---------- key : str + value : Buffer """ - ... + # Note for implementers: the default implementation provided here + # is not safe for concurrent writers. There's a race condition between + # the `exists` check and the `set` where another writer could set some + # value at `key` or delete `key`. + if not await self.exists(key): + await self.set(key, value) + + async def _set_many(self, values: Iterable[tuple[str, Buffer]]) -> None: + """ + Insert multiple (key, value) pairs into storage. + """ + await asyncio.gather(*starmap(self.set, values)) + + @property + def supports_consolidated_metadata(self) -> bool: + """ + Does the store support consolidated metadata?. + + If it doesn't an error will be raised on requests to consolidate the metadata. + Returning `False` can be useful for stores which implement their own + consolidation mechanism outside of the zarr-python implementation. + """ + + return True @property @abstractmethod - def supports_partial_writes(self) -> bool: - """Does the store support partial writes?""" + def supports_deletes(self) -> bool: + """Does the store support deletes?""" ... @abstractmethod - async def set_partial_values(self, key_start_values: list[tuple[str, int, BytesLike]]) -> None: - """Store values at a given key, starting at byte range_start. + async def delete(self, key: str) -> None: + """Remove a key from the store Parameters ---------- - key_start_values : list[tuple[str, int, BytesLike]] - set of key, range_start, values triples, a key may occur multiple times with different - range_starts, range_starts (considering the length of the respective values) must not - specify overlapping ranges for the same key + key : str """ ... + @property + def supports_partial_writes(self) -> Literal[False]: + """Does the store support partial writes? + + Partial writes are no longer used by Zarr, so this is always false. + """ + return False + @property @abstractmethod def supports_listing(self) -> bool: @@ -177,18 +335,22 @@ def supports_listing(self) -> bool: ... @abstractmethod - def list(self) -> AsyncGenerator[str, None]: + def list(self) -> AsyncIterator[str]: """Retrieve all keys in the store. Returns ------- - AsyncGenerator[str, None] + AsyncIterator[str] """ - ... + # This method should be async, like overridden methods in child classes. + # However, that's not straightforward: + # https://stackoverflow.com/questions/68905848 @abstractmethod - def list_prefix(self, prefix: str) -> AsyncGenerator[str, None]: - """Retrieve all keys in the store with a given prefix. + def list_prefix(self, prefix: str) -> AsyncIterator[str]: + """ + Retrieve all keys in the store that begin with a given prefix. Keys are returned relative + to the root of the store. Parameters ---------- @@ -196,12 +358,14 @@ def list_prefix(self, prefix: str) -> AsyncGenerator[str, None]: Returns ------- - AsyncGenerator[str, None] + AsyncIterator[str] """ - ... + # This method should be async, like overridden methods in child classes. + # However, that's not straightforward: + # https://stackoverflow.com/questions/68905848 @abstractmethod - def list_dir(self, prefix: str) -> AsyncGenerator[str, None]: + def list_dir(self, prefix: str) -> AsyncIterator[str]: """ Retrieve all keys and prefixes with a given prefix and which do not contain the character β€œ/” after the given prefix. @@ -212,35 +376,372 @@ def list_dir(self, prefix: str) -> AsyncGenerator[str, None]: Returns ------- - AsyncGenerator[str, None] + AsyncIterator[str] """ - ... + # This method should be async, like overridden methods in child classes. + # However, that's not straightforward: + # https://stackoverflow.com/questions/68905848 + + async def delete_dir(self, prefix: str) -> None: + """ + Remove all keys and prefixes in the store that begin with a given prefix. + """ + if not self.supports_deletes: + raise NotImplementedError + if not self.supports_listing: + raise NotImplementedError + self._check_writable() + if prefix != "" and not prefix.endswith("/"): + prefix += "/" + async for key in self.list_prefix(prefix): + await self.delete(key) def close(self) -> None: """Close the store.""" self._is_open = False - pass + + async def _get_many( + self, requests: Iterable[tuple[str, BufferPrototype, ByteRequest | None]] + ) -> AsyncGenerator[tuple[str, Buffer | None], None]: + """ + Retrieve a collection of objects from storage. In general this method does not guarantee + that objects will be retrieved in the order in which they were requested, so this method + yields tuple[str, Buffer | None] instead of just Buffer | None + """ + for req in requests: + yield (req[0], await self.get(*req)) + + async def get_ranges( + self, + key: str, + byte_ranges: Sequence[ByteRequest | None], + *, + prototype: BufferPrototype, + max_concurrency: int = 10, + max_gap_bytes: int = 1 << 20, # 1 MiB + max_coalesced_bytes: int = 16 << 20, # 16 MiB + ) -> AsyncIterator[Sequence[tuple[int, Buffer | None]]]: + """Read many byte ranges from `key`. + + Yields one batch per underlying I/O operation, each a sequence of + `(input_index, Buffer | None)` tuples. Batches across yields arrive in + completion order, not input order. The default implementation built + into `Store` runs the coalescer over `self.get`, so subclasses get a + working implementation for free; stores that have a more efficient + backend (e.g. ranged HTTP, S3 byte-range fetches) should override. + + Parameters + ---------- + key + Storage key to read from. + byte_ranges + Input ranges. `None` means "the whole value". + prototype + Buffer prototype, forwarded to `self.get`. + max_concurrency + Maximum number of merged fetches in flight at once. + max_gap_bytes + Two `RangeByteRequest`s separated by at most this many bytes may + be merged into one fetch. + max_coalesced_bytes + Upper bound on the size of a single merged fetch. + + Raises + ------ + BaseExceptionGroup + Failures from underlying fetches are reported as a + `BaseExceptionGroup` (PEP 654) and should be handled with + `except*`. Inner exceptions include `FileNotFoundError` if any + fetch returns `None` (i.e. `key` is absent), and any exception + raised by `self.get` for the corresponding range. Pending + fetches are cancelled as soon as one task fails, so the group + typically contains a single non-`CancelledError` exception even + under high concurrency. + """ + # Local import: zarr.core._coalesce imports symbols from this module. + from zarr.core._coalesce import coalesced_get + + fetch = partial(self.get, key, prototype) + async for group in coalesced_get( + fetch, + byte_ranges, + max_concurrency=max_concurrency, + max_gap_bytes=max_gap_bytes, + max_coalesced_bytes=max_coalesced_bytes, + ): + yield group + + def get_ranges_sync( + self, + key: str, + byte_ranges: Sequence[ByteRequest | None], + *, + prototype: BufferPrototype, + max_gap_bytes: int = 1 << 20, # 1 MiB + max_coalesced_bytes: int = 16 << 20, # 16 MiB + ) -> Sequence[tuple[int, Buffer | None]]: + """Synchronous, coalescing counterpart of `get_ranges`. + + Plans merged fetches with the same `coalesce_ranges` policy as the async + path, then issues one synchronous `get_sync` per merged group (or per + uncoalescable request) and slices results back into per-input buffers. + Used by the sync codec pipeline's partial-shard reads so they get the + same byte-range coalescing as the async path, without an event loop. + + Returns a list of `(input_index, Buffer | None)`. Raises + `BaseExceptionGroup` containing a `FileNotFoundError` if the key is + absent (matching `get_ranges`), so callers can handle a deleted shard + uniformly across the sync and async paths. + + Requires the store to implement `get_sync` (`SupportsGetSync`). + """ + from zarr.core._coalesce import coalesce_ranges + + if not isinstance(self, SupportsGetSync): + raise TypeError(f"{type(self).__name__} does not support synchronous reads") + + groups, uncoalescable = coalesce_ranges( + byte_ranges, max_gap_bytes=max_gap_bytes, max_coalesced_bytes=max_coalesced_bytes + ) + results: list[tuple[int, Buffer | None]] = [] + errors: list[BaseException] = [] + + def _get(req: ByteRequest | None) -> Buffer | None: + return self.get_sync(key, prototype=prototype, byte_range=req) + + for idx, req in uncoalescable: + buf = _get(req) + if buf is None: + errors.append(FileNotFoundError(key)) + else: + results.append((idx, buf)) + + for members in groups: + if len(members) == 1: + solo_idx, solo_req = members[0] + buf = _get(solo_req) + if buf is None: + errors.append(FileNotFoundError(key)) + else: + results.append((solo_idx, buf)) + continue + start = members[0][1].start + end = max(r.end for _, r in members) + big = _get(RangeByteRequest(start, end)) + if big is None: + errors.append(FileNotFoundError(key)) + continue + for member_idx, r in members: + results.append((member_idx, big[r.start - start : r.end - start])) + + if errors: + raise BaseExceptionGroup("chunk read failed", errors) + return results + + async def getsize(self, key: str) -> int: + """ + Return the size, in bytes, of a value in a Store. + + Parameters + ---------- + key : str + + Returns + ------- + nbytes : int + The size of the value (in bytes). + + Raises + ------ + FileNotFoundError + When the given key does not exist in the store. + """ + # Note to implementers: this default implementation is very inefficient since + # it requires reading the entire object. Many systems will have ways to get the + # size of an object without reading it. + # avoid circular import + from zarr.core.buffer.core import default_buffer_prototype + + value = await self.get(key, prototype=default_buffer_prototype()) + if value is None: + raise FileNotFoundError(key) + return len(value) + + async def getsize_prefix(self, prefix: str) -> int: + """ + Return the size, in bytes, of all values under a prefix. + + Parameters + ---------- + prefix : str + The prefix of the directory to measure. + + Returns + ------- + nbytes : int + The sum of the sizes of the values in the directory (in bytes). + + See Also + -------- + zarr.Array.nbytes_stored + Store.getsize + + Notes + ----- + ``getsize_prefix`` is just provided as a potentially faster alternative to + listing all the keys under a prefix calling [`Store.getsize`][zarr.abc.store.Store.getsize] on each. + + In general, ``prefix`` should be the path of an Array or Group in the Store. + Implementations may differ on the behavior when some other ``prefix`` + is provided. + """ + # TODO: Overlap listing keys with getsize calls. + # Currently, we load the list of keys into memory and only then move + # on to getting sizes. Ideally we would overlap those two, which should + # improve tail latency and might reduce memory pressure (since not all keys + # would be in memory at once). + + # avoid circular import + from zarr.core.common import concurrent_map + from zarr.core.config import config + + if prefix != "" and not prefix.endswith("/"): + prefix += "/" + keys = [(x,) async for x in self.list_prefix(prefix)] + limit = config.get("async.concurrency") + sizes = await concurrent_map(keys, self.getsize, limit=limit) + return sum(sizes) @runtime_checkable class ByteGetter(Protocol): async def get( - self, prototype: BufferPrototype, byte_range: tuple[int, int | None] | None = None + self, prototype: BufferPrototype, byte_range: ByteRequest | None = None ) -> Buffer | None: ... @runtime_checkable class ByteSetter(Protocol): async def get( - self, prototype: BufferPrototype, byte_range: tuple[int, int | None] | None = None + self, prototype: BufferPrototype, byte_range: ByteRequest | None = None ) -> Buffer | None: ... - async def set(self, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: ... + async def set(self, value: Buffer) -> None: ... async def delete(self) -> None: ... + async def set_if_not_exists(self, default: Buffer) -> None: ... + + +@runtime_checkable +class SyncByteGetter(Protocol): + """A `ByteGetter` that can also fetch synchronously, without an event loop. + + Non-StorePath byte getters (e.g. the sharding codec's in-memory + `_ShardingByteGetter`) implement this so a synchronous codec pipeline can + take its sync fast path on them instead of scheduling one coroutine per + chunk. Note that `StorePath` also *has* a `get_sync` method (so it matches + this protocol structurally) but it only works when its store supports + synchronous IO β€” callers gate `StorePath` on the store's `SupportsGetSync` + instead of on this protocol. + """ + + def get_sync( + self, prototype: BufferPrototype | None = None, byte_range: ByteRequest | None = None + ) -> Buffer | None: ... + + +@runtime_checkable +class SyncByteSetter(SyncByteGetter, Protocol): + """A `ByteSetter` that can also write synchronously. See `SyncByteGetter`.""" + + def set_sync(self, value: Buffer) -> None: ... + + def delete_sync(self) -> None: ... + + +@runtime_checkable +class SupportsGetSync(Protocol): + """Store protocol for synchronous reads (`get_sync`). + + The store sync surface is all-or-nothing: a store implementing any of the + `*_sync` methods must implement all of them (`SupportsSyncStore`), because + consumers mix sync reads, writes, and deletes within one operation. + Capability-gated callers consult `_store_supports_sync_io` rather than the + individual protocols. + """ + + def get_sync( + self, + key: str, + *, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: ... + + +@runtime_checkable +class SupportsSetSync(Protocol): + """Store protocol for synchronous writes (`set_sync`). + + See `SupportsGetSync` for the all-or-nothing contract on the store sync + surface. + """ + + def set_sync(self, key: str, value: Buffer) -> None: ... + + +@runtime_checkable +class SupportsDeleteSync(Protocol): + """Store protocol for synchronous deletes (`delete_sync`). + + See `SupportsGetSync` for the all-or-nothing contract on the store sync + surface. + """ + + def delete_sync(self, key: str) -> None: ... + + +@runtime_checkable +class SupportsSyncStore(SupportsGetSync, SupportsSetSync, SupportsDeleteSync, Protocol): + """The full store sync surface: `get_sync`, `set_sync`, and `delete_sync`.""" + + +def _store_supports_sync_io(store: object) -> bool: + """Whether `store` can serve the full synchronous IO surface right now. + + Structural membership in `SupportsSyncStore` is necessary but not always + sufficient: a store can present the `*_sync` methods while its ability to + run them depends on runtime state the type system cannot see. Wrapper + stores are the canonical case β€” `WrapperStore` delegates the sync methods + to the store it wraps, so they only work when the wrapped store is itself + sync-capable. Such stores opt out dynamically via a `_supports_sync_io` + attribute/property (absent means capable). + + This is an interim, private convention pending a formal sync/async store + architecture β€” the store-side twin of the codec-side `_sync_capable` + convention consulted by `zarr.abc.codec._codec_supports_sync`. + + Synchronous IO is all-or-nothing: consumers such as the fused codec + pipeline mix synchronous reads, writes, and deletes within one batch + (e.g. a partial-chunk write reads existing bytes and an all-fill chunk is + deleted), so a partial sync surface never satisfies this predicate. + """ + return isinstance(store, SupportsSyncStore) and getattr(store, "_supports_sync_io", True) + async def set_or_delete(byte_setter: ByteSetter, value: Buffer | None) -> None: + """Set or delete a value in a byte setter + + Parameters + ---------- + byte_setter : ByteSetter + value : Buffer | None + + Notes + ----- + If value is None, the key will be deleted. + """ if value is None: await byte_setter.delete() else: diff --git a/src/zarr/api/asynchronous.py b/src/zarr/api/asynchronous.py index 5d2e54baa3..3bdc254ea5 100644 --- a/src/zarr/api/asynchronous.py +++ b/src/zarr/api/asynchronous.py @@ -1,32 +1,128 @@ from __future__ import annotations import asyncio +import dataclasses import warnings -from collections.abc import Iterable -from typing import Any, Literal, Union, cast +from typing import TYPE_CHECKING, Any, Literal, NotRequired, TypedDict, cast import numpy as np import numpy.typing as npt - -from zarr.abc.codec import Codec -from zarr.array import Array, AsyncArray -from zarr.buffer import NDArrayLike -from zarr.chunk_key_encodings import ChunkKeyEncoding -from zarr.common import JSON, AccessModeLiteral, ChunkCoords, MemoryOrder, ZarrFormat -from zarr.group import AsyncGroup -from zarr.metadata import ArrayV2Metadata, ArrayV3Metadata -from zarr.store import ( - StoreLike, - make_store_path, +from typing_extensions import deprecated + +from zarr.abc.store import Store +from zarr.core.array import ( + DEFAULT_FILL_VALUE, + Array, + AsyncArray, + CompressorLike, + create_array, + from_array, + get_array_metadata, +) +from zarr.core.array_spec import ArrayConfigLike, parse_array_config +from zarr.core.buffer import NDArrayLike +from zarr.core.common import ( + JSON, + AccessModeLiteral, + DimensionNamesLike, + MemoryOrder, + ZarrFormat, + _default_zarr_format, + _warn_write_empty_chunks_kwarg, +) +from zarr.core.dtype import ZDTypeLike, get_data_type_from_native_dtype +from zarr.core.group import ( + AsyncGroup, + ConsolidatedMetadata, + GroupMetadata, + create_hierarchy, ) +from zarr.core.metadata import ArrayMetadataDict, ArrayV2Metadata +from zarr.errors import ( + ArrayNotFoundError, + GroupNotFoundError, + NodeTypeValidationError, + ZarrDeprecationWarning, + ZarrRuntimeWarning, + ZarrUserWarning, +) +from zarr.storage import StorePath +from zarr.storage._common import make_store_path + +if TYPE_CHECKING: + from collections.abc import Iterable + + from zarr.abc.codec import Codec + from zarr.abc.numcodec import Numcodec + from zarr.core.buffer import NDArrayLikeOrScalar + from zarr.core.chunk_key_encodings import ChunkKeyEncoding + from zarr.core.metadata.v2 import CompressorLikev2 + from zarr.storage import StoreLike + from zarr.types import AnyArray, AnyAsyncArray + + # TODO: this type could use some more thought + type ArrayLike = AnyAsyncArray | AnyArray | npt.NDArray[Any] + PathLike = str + +__all__ = [ + "array", + "consolidate_metadata", + "copy", + "copy_all", + "copy_store", + "create", + "create_array", + "create_hierarchy", + "empty", + "empty_like", + "from_array", + "full", + "full_like", + "group", + "load", + "ones", + "ones_like", + "open", + "open_array", + "open_consolidated", + "open_group", + "open_like", + "save", + "save_array", + "save_group", + "tree", + "zeros", + "zeros_like", +] + + +_READ_MODES: tuple[AccessModeLiteral, ...] = ("r", "r+", "a") +_CREATE_MODES: tuple[AccessModeLiteral, ...] = ("a", "w", "w-") +_OVERWRITE_MODES: tuple[AccessModeLiteral, ...] = ("w",) + + +def _infer_overwrite(mode: AccessModeLiteral) -> bool: + """ + Check that an `AccessModeLiteral` is compatible with overwriting an existing Zarr node. + """ + return mode in _OVERWRITE_MODES -# TODO: this type could use some more thought, noqa to avoid "Variable "asynchronous.ArrayLike" is not valid as a type" -ArrayLike = Union[AsyncArray | Array | npt.NDArray[Any]] # noqa -PathLike = str +def _warn_unimplemented_kwargs(kwargs: dict[str, Any]) -> None: + """ + Emit a "not yet implemented" warning for each provided keyword argument that is not None. + + `kwargs` maps a keyword argument name to its supplied value. The `stacklevel` is chosen + so the warning points at the caller of the public API function (the same location as an + inline `warnings.warn(..., stacklevel=2)` would). + """ + for name, value in kwargs.items(): + if value is not None: + warnings.warn(f"{name} is not yet implemented", ZarrRuntimeWarning, stacklevel=3) -def _get_shape_chunks(a: ArrayLike | Any) -> tuple[ChunkCoords | None, ChunkCoords | None]: - """helper function to get the shape and chunks from an array-like object""" + +def _get_shape_chunks(a: ArrayLike | Any) -> tuple[tuple[int, ...] | None, tuple[int, ...] | None]: + """Helper function to get the shape and chunks from an array-like object""" shape = None chunks = None @@ -43,10 +139,21 @@ def _get_shape_chunks(a: ArrayLike | Any) -> tuple[ChunkCoords | None, ChunkCoor return shape, chunks -def _like_args(a: ArrayLike, kwargs: dict[str, Any]) -> dict[str, Any]: - """set default values for shape and chunks if they are not present in the array-like object""" +class _LikeArgs(TypedDict): + shape: NotRequired[tuple[int, ...]] + chunks: NotRequired[tuple[int, ...]] + dtype: NotRequired[np.dtype[np.generic]] + order: NotRequired[Literal["C", "F"]] + filters: NotRequired[tuple[Numcodec, ...] | None] + compressor: NotRequired[CompressorLikev2] + codecs: NotRequired[tuple[Codec, ...]] + fill_value: NotRequired[Any] + + +def _like_args(a: ArrayLike) -> _LikeArgs: + """Set default values for shape and chunks if they are not present in the array-like object""" - new = kwargs.copy() + new: _LikeArgs = {} shape, chunks = _get_shape_chunks(a) if shape is not None: @@ -57,16 +164,17 @@ def _like_args(a: ArrayLike, kwargs: dict[str, Any]) -> dict[str, Any]: if hasattr(a, "dtype"): new["dtype"] = a.dtype - if isinstance(a, AsyncArray): - new["order"] = a.order + if isinstance(a, AsyncArray | Array): + new["fill_value"] = a.metadata.fill_value if isinstance(a.metadata, ArrayV2Metadata): + new["order"] = a.order new["compressor"] = a.metadata.compressor new["filters"] = a.metadata.filters - - if isinstance(a.metadata, ArrayV3Metadata): - new["codecs"] = a.metadata.codecs else: - raise ValueError(f"Unsupported zarr format: {a.metadata.zarr_format}") + # TODO: Remove type: ignore statement when type inference improves. + # mypy cannot correctly infer the type of a.metadata here for some reason. + new["codecs"] = a.metadata.codecs + else: # TODO: set default values compressor/codecs # to do this, we may need to evaluate if this is a v2 or v3 array @@ -76,41 +184,102 @@ def _like_args(a: ArrayLike, kwargs: dict[str, Any]) -> dict[str, Any]: return new -def _handle_zarr_version_or_format( - *, zarr_version: ZarrFormat | None, zarr_format: ZarrFormat | None -) -> ZarrFormat | None: - """handle the deprecated zarr_version kwarg and return zarr_format""" - if zarr_format is not None and zarr_version is not None and zarr_format != zarr_version: - raise ValueError( - f"zarr_format {zarr_format} does not match zarr_version {zarr_version}, please only set one" +async def consolidate_metadata( + store: StoreLike, + path: str | None = None, + zarr_format: ZarrFormat | None = None, +) -> AsyncGroup: + """ + Consolidate the metadata of all nodes in a hierarchy. + + Upon completion, the metadata of the root node in the Zarr hierarchy will be + updated to include all the metadata of child nodes. For Stores that do + not support consolidated metadata, this operation raises a `TypeError`. + + Parameters + ---------- + store : StoreLike + The store-like object whose metadata you wish to consolidate. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + path : str, optional + A path to a group in the store to consolidate at. Only children + below that group will be consolidated. + + By default, the root node is used so all the metadata in the + store is consolidated. + zarr_format : {2, 3, None}, optional + The zarr format of the hierarchy. By default the zarr format + is inferred. + + Returns + ------- + group: AsyncGroup + The group, with the `consolidated_metadata` field set to include + the metadata of each child node. If the Store doesn't support + consolidated metadata, this function raises a `TypeError`. + See `Store.supports_consolidated_metadata`. + """ + store_path = await make_store_path(store, path=path) + + if not store_path.store.supports_consolidated_metadata: + store_name = type(store_path.store).__name__ + raise TypeError( + f"The Zarr Store in use ({store_name}) doesn't support consolidated metadata", ) - if zarr_version is not None: + + group = await AsyncGroup.open(store_path, zarr_format=zarr_format, use_consolidated=False) + group.store_path.store._check_writable() + + members_metadata = { + k: v.metadata + async for k, v in group.members(max_depth=None, use_consolidated_for_children=False) + } + # While consolidating, we want to be explicit about when child groups + # are empty by inserting an empty dict for consolidated_metadata.metadata + for k, v in members_metadata.items(): + if isinstance(v, GroupMetadata) and v.consolidated_metadata is None: + v = dataclasses.replace(v, consolidated_metadata=ConsolidatedMetadata(metadata={})) + members_metadata[k] = v + + if any(m.zarr_format == 3 for m in members_metadata.values()): warnings.warn( - "zarr_version is deprecated, use zarr_format", DeprecationWarning, stacklevel=2 + "Consolidated metadata is currently not part in the Zarr format 3 specification. It " + "may not be supported by other zarr implementations and may change in the future.", + category=ZarrUserWarning, + stacklevel=1, ) - return zarr_version - return zarr_format + ConsolidatedMetadata._flat_to_nested(members_metadata) -def _default_zarr_version() -> ZarrFormat: - """return the default zarr_version""" - # TODO: set default value from config - return 3 - - -async def consolidate_metadata(*args: Any, **kwargs: Any) -> AsyncGroup: - raise NotImplementedError + consolidated_metadata = ConsolidatedMetadata(metadata=members_metadata) + metadata = dataclasses.replace(group.metadata, consolidated_metadata=consolidated_metadata) + group = dataclasses.replace( + group, + metadata=metadata, + ) + await group._save_metadata() + return group async def copy(*args: Any, **kwargs: Any) -> tuple[int, int, int]: + """ + Not implemented. + """ raise NotImplementedError async def copy_all(*args: Any, **kwargs: Any) -> tuple[int, int, int]: + """ + Not implemented. + """ raise NotImplementedError async def copy_store(*args: Any, **kwargs: Any) -> tuple[int, int, int]: + """ + Not implemented. + """ raise NotImplementedError @@ -119,14 +288,15 @@ async def load( store: StoreLike, path: str | None = None, zarr_format: ZarrFormat | None = None, - zarr_version: ZarrFormat | None = None, -) -> NDArrayLike | dict[str, NDArrayLike]: +) -> NDArrayLikeOrScalar | dict[str, NDArrayLikeOrScalar]: """Load data from an array or group into memory. Parameters ---------- - store : Store or string - Store or path to directory in file system or name of zip file. + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. path : str or None, optional The path within the store from which to load. @@ -139,18 +309,25 @@ async def load( See Also -------- - save, savez + save, open Notes ----- If loading data from a group of arrays, data will not be immediately loaded into memory. Rather, arrays will be loaded into memory as they are requested. + + Unlike [`open`][zarr.open], which returns a lazy [`Array`][zarr.Array] or + [`Group`][zarr.Group] backed by the store, `load` eagerly reads the data and + returns it as an in-memory array (or a dict of arrays for a group). + The array type is NumPy by default, but follows the configured + buffer prototype (for example, CuPy for GPU use cases). + Use `open` when you want to read or write data incrementally without loading it + all into memory. """ - zarr_format = _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) obj = await open(store=store, path=path, zarr_format=zarr_format) if isinstance(obj, AsyncArray): - return await obj.getitem(slice(None)) + return await obj.getitem(Ellipsis) else: raise NotImplementedError("loading groups not yet supported") @@ -158,56 +335,104 @@ async def load( async def open( *, store: StoreLike | None = None, - mode: AccessModeLiteral | None = None, # type and value changed - zarr_version: ZarrFormat | None = None, # deprecated + mode: AccessModeLiteral | None = None, zarr_format: ZarrFormat | None = None, path: str | None = None, + storage_options: dict[str, Any] | None = None, **kwargs: Any, # TODO: type kwargs as valid args to open_array -) -> AsyncArray | AsyncGroup: +) -> AnyAsyncArray | AsyncGroup: """Convenience function to open a group or array using file-mode-like semantics. Parameters ---------- - store : Store or string, optional - Store or path to directory in file system or name of zip file. + store : StoreLike or None, default=None + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. mode : {'r', 'r+', 'a', 'w', 'w-'}, optional Persistence mode: 'r' means read only (must exist); 'r+' means read/write (must exist); 'a' means read/write (create if doesn't exist); 'w' means create (overwrite if exists); 'w-' means create (fail if exists). + If the store is read-only, the default is 'r'; otherwise, it is 'a'. zarr_format : {2, 3, None}, optional The zarr format to use when saving. path : str or None, optional The path within the store to open. + storage_options : dict + If using an fsspec URL to create the store, these will be passed to + the backend implementation. Ignored otherwise. **kwargs - Additional parameters are passed through to :func:`zarr.creation.open_array` or - :func:`zarr.hierarchy.open_group`. + Additional parameters are passed through to `zarr.open_array` or + `zarr.open_group`. Returns ------- z : array or group Return type depends on what exists in the given store. + + See Also + -------- + load + + Notes + ----- + `open` returns a lazy [`Array`][zarr.Array] or [`Group`][zarr.Group] backed by + the store, so data is read and written incrementally. Use [`load`][zarr.load] + instead when you want the data eagerly read into an in-memory array (a + NumPy array by default). """ - zarr_format = _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) - store_path = await make_store_path(store, mode=mode) - if path is not None: - store_path = store_path / path + if mode is None: + if isinstance(store, (Store, StorePath)) and store.read_only: + mode = "r" + else: + mode = "a" + store_path = await make_store_path(store, mode=mode, path=path, storage_options=storage_options) + + # TODO: the mode check below seems wrong! + if "shape" not in kwargs and mode in {"a", "r", "r+", "w"}: + try: + metadata_dict = await get_array_metadata(store_path, zarr_format=zarr_format) + # TODO: remove this cast when we fix typing for array metadata dicts + _metadata_dict = cast("ArrayMetadataDict", metadata_dict) + # for v2, the above would already have raised an exception if not an array + zarr_format = _metadata_dict["zarr_format"] + is_v3_array = zarr_format == 3 and _metadata_dict.get("node_type") == "array" + if is_v3_array or zarr_format == 2: + return AsyncArray( + store_path=store_path, metadata=_metadata_dict, config=kwargs.get("config") + ) + except (AssertionError, FileNotFoundError, NodeTypeValidationError): + pass + return await open_group(store=store_path, zarr_format=zarr_format, mode=mode, **kwargs) try: return await open_array(store=store_path, zarr_format=zarr_format, mode=mode, **kwargs) - except KeyError: + except (KeyError, NodeTypeValidationError): + # KeyError for a missing key + # NodeTypeValidationError for failing to parse node metadata as an array when it's + # actually a group return await open_group(store=store_path, zarr_format=zarr_format, mode=mode, **kwargs) -async def open_consolidated(*args: Any, **kwargs: Any) -> AsyncGroup: - raise NotImplementedError +async def open_consolidated( + *args: Any, use_consolidated: Literal[True] = True, **kwargs: Any +) -> AsyncGroup: + """ + Alias for [`open_group`][zarr.api.asynchronous.open_group] with `use_consolidated=True`. + """ + if use_consolidated is not True: + raise TypeError( + "'use_consolidated' must be 'True' in 'open_consolidated'. Use 'open' with " + "'use_consolidated=False' to bypass consolidated metadata." + ) + return await open_group(*args, use_consolidated=use_consolidated, **kwargs) async def save( store: StoreLike, *args: NDArrayLike, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, path: str | None = None, **kwargs: Any, # TODO: type kwargs as valid args to save @@ -216,18 +441,19 @@ async def save( Parameters ---------- - store : Store or string - Store or path to directory in file system or name of zip file. - args : ndarray + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + *args : ndarray NumPy arrays with data to save. zarr_format : {2, 3, None}, optional The zarr format to use when saving. path : str or None, optional The path within the group where the arrays will be saved. - kwargs + **kwargs NumPy arrays with data to save. """ - zarr_format = _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) if len(args) == 0 and len(kwargs) == 0: raise ValueError("at least one array must be provided") @@ -241,9 +467,9 @@ async def save_array( store: StoreLike, arr: NDArrayLike, *, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, path: str | None = None, + storage_options: dict[str, Any] | None = None, **kwargs: Any, # TODO: type kwargs as valid args to create ) -> None: """Convenience function to save a NumPy array to the local file system, following a @@ -251,42 +477,54 @@ async def save_array( Parameters ---------- - store : Store or string - Store or path to directory in file system or name of zip file. + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. arr : ndarray NumPy array with data to save. zarr_format : {2, 3, None}, optional - The zarr format to use when saving. + The zarr format to use when saving. The default is `None`, which will + use the default Zarr format defined in the global configuration object. path : str or None, optional The path within the store where the array will be saved. - kwargs - Passed through to :func:`create`, e.g., compressor. + storage_options : dict + If using an fsspec URL to create the store, these will be passed to + the backend implementation. Ignored otherwise. + **kwargs + Passed through to [`create`][zarr.api.asynchronous.create], e.g., compressor. """ - zarr_format = ( - _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) - or _default_zarr_version() - ) - - store_path = await make_store_path(store, mode="w") - if path is not None: - store_path = store_path / path - new = await AsyncArray.create( + if zarr_format is None: + zarr_format = _default_zarr_format() + if not isinstance(arr, NDArrayLike): + raise TypeError("arr argument must be numpy or other NDArrayLike array") + + mode = kwargs.pop("mode", "a") + store_path = await make_store_path(store, path=path, mode=mode, storage_options=storage_options) + if np.isscalar(arr): + arr = np.array(arr) + shape = arr.shape + chunks = getattr(arr, "chunks", None) # for array-likes with chunks attribute + overwrite = kwargs.pop("overwrite", None) or _infer_overwrite(mode) + zarr_dtype = get_data_type_from_native_dtype(arr.dtype) + new = await AsyncArray._create( store_path, zarr_format=zarr_format, - shape=arr.shape, - dtype=arr.dtype, - chunks=arr.shape, + shape=shape, + dtype=zarr_dtype, + chunks=chunks, + overwrite=overwrite, **kwargs, ) - await new.setitem(slice(None), arr) + await new.setitem(Ellipsis, arr) async def save_group( store: StoreLike, *args: NDArrayLike, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, path: str | None = None, + storage_options: dict[str, Any] | None = None, **kwargs: NDArrayLike, ) -> None: """Convenience function to save several NumPy arrays to the local file system, following a @@ -294,43 +532,89 @@ async def save_group( Parameters ---------- - store : Store or string - Store or path to directory in file system or name of zip file. - args : ndarray + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + *args : ndarray NumPy arrays with data to save. zarr_format : {2, 3, None}, optional The zarr format to use when saving. path : str or None, optional Path within the store where the group will be saved. - kwargs + storage_options : dict + If using an fsspec URL to create the store, these will be passed to + the backend implementation. Ignored otherwise. + **kwargs NumPy arrays with data to save. """ - zarr_format = _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) + + store_path = await make_store_path(store, path=path, mode="w", storage_options=storage_options) + + if zarr_format is None: + zarr_format = _default_zarr_format() + + for arg in args: + if not isinstance(arg, NDArrayLike): + raise TypeError( + "All arguments must be numpy or other NDArrayLike arrays (except store, path, storage_options, and zarr_format)" + ) + for k, v in kwargs.items(): + if not isinstance(v, NDArrayLike): + raise TypeError(f"Keyword argument '{k}' must be a numpy or other NDArrayLike array") if len(args) == 0 and len(kwargs) == 0: raise ValueError("at least one array must be provided") aws = [] for i, arr in enumerate(args): - aws.append(save_array(store, arr, zarr_format=zarr_format, path=f"{path}/arr_{i}")) + aws.append( + save_array( + store_path, + arr, + zarr_format=zarr_format, + path=f"arr_{i}", + storage_options=storage_options, + ) + ) for k, arr in kwargs.items(): - _path = f"{path}/{k}" if path is not None else k - aws.append(save_array(store, arr, zarr_format=zarr_format, path=_path)) + aws.append(save_array(store_path, arr, zarr_format=zarr_format, path=k)) await asyncio.gather(*aws) -async def tree(*args: Any, **kwargs: Any) -> None: - raise NotImplementedError +@deprecated("Use AsyncGroup.tree instead.", category=ZarrDeprecationWarning) +async def tree(grp: AsyncGroup, expand: bool | None = None, level: int | None = None) -> Any: + """Provide a rich display of the hierarchy. + + !!! warning "Deprecated" + `zarr.tree()` is deprecated since v3.0.0 and will be removed in a future release. + Use `group.tree()` instead. + Parameters + ---------- + grp : Group + Zarr or h5py group. + expand : bool, optional + Only relevant for HTML representation. If True, tree will be fully expanded. + level : int, optional + Maximum depth to descend into hierarchy. -async def array(data: npt.ArrayLike, **kwargs: Any) -> AsyncArray: + Returns + ------- + TreeRepr + A pretty-printable object displaying the hierarchy. + """ + return await grp.tree(expand=expand, level=level) + + +async def array(data: npt.ArrayLike | AnyArray, **kwargs: Any) -> AnyAsyncArray: """Create an array filled with `data`. Parameters ---------- data : array_like The data to fill the array with. - kwargs - Passed through to :func:`create`. + **kwargs + Passed through to [`create`][zarr.api.asynchronous.create]. Returns ------- @@ -338,13 +622,16 @@ async def array(data: npt.ArrayLike, **kwargs: Any) -> AsyncArray: The new array. """ + if isinstance(data, Array): + return await from_array(data=data, **kwargs) + # ensure data is array-like if not hasattr(data, "shape") or not hasattr(data, "dtype"): data = np.asanyarray(data) # setup dtype kw_dtype = kwargs.get("dtype") - if kw_dtype is None: + if kw_dtype is None and hasattr(data, "dtype"): kwargs["dtype"] = data.dtype else: kwargs["dtype"] = kw_dtype @@ -366,7 +653,7 @@ async def array(data: npt.ArrayLike, **kwargs: Any) -> AsyncArray: z = await create(**kwargs) # fill with data - await z.setitem(slice(None), data) + await z.setitem(Ellipsis, data) return z @@ -379,95 +666,139 @@ async def group( cache_attrs: bool | None = None, # not used, default changed synchronizer: Any | None = None, # not used path: str | None = None, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, meta_array: Any | None = None, # not used attributes: dict[str, JSON] | None = None, + storage_options: dict[str, Any] | None = None, ) -> AsyncGroup: """Create a group. Parameters ---------- - store : Store or string, optional - Store or path to directory in file system. + store : StoreLike or None, default=None + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. overwrite : bool, optional If True, delete any pre-existing data in `store` at `path` before creating the group. - chunk_store : Store, optional - Separate storage for chunks. If not provided, `store` will be used - for storage of both chunks and metadata. + chunk_store : StoreLike or None, default=None + Separate storage for chunks. Not implemented. cache_attrs : bool, optional If True (default), user attributes will be cached for attribute read operations. If False, user attributes are reloaded from the store prior to all attribute read operations. synchronizer : object, optional Array synchronizer. - path : string, optional + path : str, optional Group path within store. meta_array : array-like, optional An array instance to use for determining arrays to create and return to users. Use `numpy.empty(())` by default. zarr_format : {2, 3, None}, optional The zarr format to use when saving. + storage_options : dict + If using an fsspec URL to create the store, these will be passed to + the backend implementation. Ignored otherwise. Returns ------- g : group The new group. """ - - zarr_format = ( - _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) - or _default_zarr_version() + mode: AccessModeLiteral + if overwrite: + mode = "w" + else: + mode = "a" + return await open_group( + store=store, + mode=mode, + chunk_store=chunk_store, + cache_attrs=cache_attrs, + synchronizer=synchronizer, + path=path, + zarr_format=zarr_format, + meta_array=meta_array, + attributes=attributes, + storage_options=storage_options, ) - store_path = await make_store_path(store) - if path is not None: - store_path = store_path / path - if chunk_store is not None: - warnings.warn("chunk_store is not yet implemented", RuntimeWarning, stacklevel=2) - if cache_attrs is not None: - warnings.warn("cache_attrs is not yet implemented", RuntimeWarning, stacklevel=2) - if synchronizer is not None: - warnings.warn("synchronizer is not yet implemented", RuntimeWarning, stacklevel=2) - if meta_array is not None: - warnings.warn("meta_array is not yet implemented", RuntimeWarning, stacklevel=2) +async def create_group( + *, + store: StoreLike, + path: str | None = None, + overwrite: bool = False, + zarr_format: ZarrFormat | None = None, + attributes: dict[str, Any] | None = None, + storage_options: dict[str, Any] | None = None, +) -> AsyncGroup: + """Create a group. - if attributes is None: - attributes = {} + Parameters + ---------- + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + path : str, optional + Group path within store. + overwrite : bool, optional + If True, pre-existing data at `path` will be deleted before + creating the group. + zarr_format : {2, 3, None}, optional + The zarr format to use when saving. + If no `zarr_format` is provided, the default format will be used. + This default can be changed by modifying the value of `default_zarr_format` + in [`zarr.config`][zarr.config]. + storage_options : dict + If using an fsspec URL to create the store, these will be passed to + the backend implementation. Ignored otherwise. - try: - return await AsyncGroup.open(store=store_path, zarr_format=zarr_format) - except (KeyError, FileNotFoundError): - return await AsyncGroup.create( - store=store_path, - zarr_format=zarr_format, - exists_ok=overwrite, - attributes=attributes, - ) + Returns + ------- + AsyncGroup + The new group. + """ + + if zarr_format is None: + zarr_format = _default_zarr_format() + + mode: Literal["a"] = "a" + + store_path = await make_store_path(store, path=path, mode=mode, storage_options=storage_options) + + return await AsyncGroup.from_store( + store=store_path, + zarr_format=zarr_format, + overwrite=overwrite, + attributes=attributes, + ) async def open_group( - *, # Note: this is a change from v2 store: StoreLike | None = None, - mode: AccessModeLiteral | None = None, # not used + *, # Note: this is a change from v2 + mode: AccessModeLiteral = "a", cache_attrs: bool | None = None, # not used, default changed synchronizer: Any = None, # not used path: str | None = None, chunk_store: StoreLike | None = None, # not used - storage_options: dict[str, Any] | None = None, # not used - zarr_version: ZarrFormat | None = None, # deprecated + storage_options: dict[str, Any] | None = None, zarr_format: ZarrFormat | None = None, meta_array: Any | None = None, # not used attributes: dict[str, JSON] | None = None, + use_consolidated: bool | str | None = None, ) -> AsyncGroup: """Open a group using file-mode-like semantics. Parameters ---------- - store : Store or string, optional - Store or path to directory in file system or name of zip file. + store : StoreLike or None, default=None + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. mode : {'r', 'r+', 'a', 'w', 'w-'}, optional Persistence mode: 'r' means read only (must exist); 'r+' means read/write (must exist); 'a' means read/write (create if doesn't @@ -479,16 +810,36 @@ async def open_group( to all attribute read operations. synchronizer : object, optional Array synchronizer. - path : string, optional + path : str, optional Group path within store. - chunk_store : Store or string, optional - Store or path to directory in file system or name of zip file. + chunk_store : StoreLike or None, default=None + Separate storage for chunks. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. storage_options : dict If using an fsspec URL to create the store, these will be passed to the backend implementation. Ignored otherwise. meta_array : array-like, optional An array instance to use for determining arrays to create and return to users. Use `numpy.empty(())` by default. + attributes : dict + A dictionary of JSON-serializable values with user-defined attributes. + use_consolidated : bool or str, default None + Whether to use consolidated metadata. + + By default, consolidated metadata is used if it's present in the + store (in the `zarr.json` for Zarr format 3 and in the `.zmetadata` file + for Zarr format 2). + + To explicitly require consolidated metadata, set `use_consolidated=True`, + which will raise an exception if consolidated metadata is not found. + + To explicitly *not* use consolidated metadata, set `use_consolidated=False`, + which will fall back to using the regular, non consolidated metadata. + + Zarr format 2 allowed configuring the key storing the consolidated metadata + (`.zmetadata` by default). Specify the custom key as `use_consolidated` + to load consolidated metadata from a non-default key. Returns ------- @@ -496,63 +847,64 @@ async def open_group( The new group. """ - zarr_format = ( - _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) - or _default_zarr_version() + _warn_unimplemented_kwargs( + { + "cache_attrs": cache_attrs, + "synchronizer": synchronizer, + "meta_array": meta_array, + "chunk_store": chunk_store, + } ) - if cache_attrs is not None: - warnings.warn("cache_attrs is not yet implemented", RuntimeWarning, stacklevel=2) - if synchronizer is not None: - warnings.warn("synchronizer is not yet implemented", RuntimeWarning, stacklevel=2) - if meta_array is not None: - warnings.warn("meta_array is not yet implemented", RuntimeWarning, stacklevel=2) - if chunk_store is not None: - warnings.warn("chunk_store is not yet implemented", RuntimeWarning, stacklevel=2) - if storage_options is not None: - warnings.warn("storage_options is not yet implemented", RuntimeWarning, stacklevel=2) - - store_path = await make_store_path(store, mode=mode) - if path is not None: - store_path = store_path / path - + store_path = await make_store_path(store, mode=mode, storage_options=storage_options, path=path) if attributes is None: attributes = {} try: - return await AsyncGroup.open(store_path, zarr_format=zarr_format) + if mode in _READ_MODES: + return await AsyncGroup.open( + store_path, zarr_format=zarr_format, use_consolidated=use_consolidated + ) except (KeyError, FileNotFoundError): - return await AsyncGroup.create( - store_path, zarr_format=zarr_format, exists_ok=True, attributes=attributes + pass + if mode in _CREATE_MODES: + overwrite = _infer_overwrite(mode) + _zarr_format = zarr_format or _default_zarr_format() + return await AsyncGroup.from_store( + store_path, + zarr_format=_zarr_format, + overwrite=overwrite, + attributes=attributes, ) + msg = f"No group found in store {store!r} at path {store_path.path!r}" + raise GroupNotFoundError(msg) async def create( - shape: ChunkCoords, + shape: tuple[int, ...] | int, *, # Note: this is a change from v2 - chunks: ChunkCoords | None = None, # TODO: v2 allowed chunks=True - dtype: npt.DTypeLike | None = None, - compressor: dict[str, JSON] | None = None, # TODO: default and type change - fill_value: Any = 0, # TODO: need type - order: MemoryOrder | None = None, # TODO: default change - store: str | StoreLike | None = None, + chunks: tuple[int, ...] | int | bool | None = None, + dtype: ZDTypeLike | None = None, + compressor: CompressorLike = "auto", + fill_value: Any | None = DEFAULT_FILL_VALUE, + order: MemoryOrder | None = None, + store: StoreLike | None = None, synchronizer: Any | None = None, overwrite: bool = False, path: PathLike | None = None, chunk_store: StoreLike | None = None, - filters: list[dict[str, JSON]] | None = None, # TODO: type has changed + filters: Iterable[dict[str, JSON] | Numcodec] | None = None, cache_metadata: bool | None = None, cache_attrs: bool | None = None, read_only: bool | None = None, object_codec: Codec | None = None, # TODO: type has changed dimension_separator: Literal[".", "/"] | None = None, - write_empty_chunks: bool = False, # TODO: default has changed - zarr_version: ZarrFormat | None = None, # deprecated + write_empty_chunks: bool | None = None, zarr_format: ZarrFormat | None = None, meta_array: Any | None = None, # TODO: need type attributes: dict[str, JSON] | None = None, # v3 only - chunk_shape: ChunkCoords | None = None, + chunk_shape: tuple[int, ...] | int | None = None, chunk_key_encoding: ( ChunkKeyEncoding | tuple[Literal["default"], Literal[".", "/"]] @@ -560,9 +912,11 @@ async def create( | None ) = None, codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: Iterable[str] | None = None, + dimension_names: DimensionNamesLike = None, + storage_options: dict[str, Any] | None = None, + config: ArrayConfigLike | None = None, **kwargs: Any, -) -> AsyncArray: +) -> AnyAsyncArray: """Create an array. Parameters @@ -574,28 +928,56 @@ async def create( False, will be set to `shape`, i.e., single chunk for the whole array. If an int, the chunk size in each dimension will be given by the value of `chunks`. Default is True. - dtype : string or dtype, optional + dtype : str or dtype, optional NumPy dtype. compressor : Codec, optional - Primary compressor. - fill_value : object - Default value to use for uninitialized portions of the array. + Primary compressor to compress chunk data. + Zarr format 2 only. Zarr format 3 arrays should use `codecs` instead. + + If neither `compressor` nor `filters` are provided, the default compressor + [`zarr.codecs.ZstdCodec`][] is used. + + If `compressor` is set to `None`, no compression is used. + fill_value : Any, optional + Fill value for the array. order : {'C', 'F'}, optional + Deprecated in favor of the `config` keyword argument. + Pass `{'order': }` to `create` instead of using this parameter. Memory layout to be used within each chunk. - store : Store or string - Store or path to directory in file system or name of zip file. + If not specified, the `array.order` parameter in the global config will be used. + store : StoreLike or None, default=None + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. synchronizer : object, optional Array synchronizer. overwrite : bool, optional If True, delete all pre-existing data in `store` at `path` before creating the array. - path : string, optional + path : str, optional Path under which array is stored. - chunk_store : MutableMapping, optional + chunk_store : StoreLike or None, default=None Separate storage for chunks. If not provided, `store` will be used for storage of both chunks and metadata. - filters : sequence of Codecs, optional - Sequence of filters to use to encode chunk data prior to compression. + filters : Iterable[Codec] | Literal["auto"], optional + Iterable of filters to apply to each chunk of the array, in order, before serializing that + chunk to bytes. + + For Zarr format 3, a "filter" is a codec that takes an array and returns an array, + and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a + dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. + + For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the + order of your filters is consistent with the behavior of each filter. + + The default value of `"auto"` instructs Zarr to use a default based on the data + type of the array and the Zarr format specified. For all data types in Zarr V3, and most + data types in Zarr V2, the default filters are empty. The only cases where default filters + are not empty is when the Zarr format is 2, and the data type is a variable-length data type like + [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, + the default filters contains a single element which is a codec specific to that particular data type. + + To create an array with no filters, provide an empty iterable or the value `None`. cache_metadata : bool, optional If True, array configuration metadata will be cached for the lifetime of the object. If False, array metadata will be reloaded @@ -611,111 +993,122 @@ async def create( A codec to encode object arrays, only needed if dtype=object. dimension_separator : {'.', '/'}, optional Separator placed between the dimensions of a chunk. - - .. versionadded:: 2.8 - + Zarr format 2 only. Zarr format 3 arrays should use `chunk_key_encoding` instead. write_empty_chunks : bool, optional - If True (default), all chunks will be stored regardless of their + Deprecated in favor of the `config` keyword argument. + Pass `{'write_empty_chunks': }` to `create` instead of using this parameter. + If True, all chunks will be stored regardless of their contents. If False, each chunk is compared to the array's fill value prior to storing. If a chunk is uniformly equal to the fill value, then that chunk is not be stored, and the store entry for that chunk's key - is deleted. This setting enables sparser storage, as only chunks with - non-fill-value data are stored, at the expense of overhead associated - with checking the data of each chunk. - - .. versionadded:: 2.11 - + is deleted. zarr_format : {2, 3, None}, optional - The zarr format to use when saving. + The Zarr format to use when creating an array. The default is `None`, + which instructs Zarr to choose the default Zarr format value defined in the + runtime configuration. meta_array : array-like, optional - An array instance to use for determining arrays to create and return - to users. Use `numpy.empty(())` by default. - - .. versionadded:: 2.13 + Not implemented. + attributes : dict[str, JSON], optional + A dictionary of user attributes to store with the array. + chunk_shape : int or tuple of ints, optional + The shape of the Array's chunks (default is None). + Zarr format 3 only. Zarr format 2 arrays should use `chunks` instead. + chunk_key_encoding : ChunkKeyEncoding, optional + A specification of how the chunk keys are represented in storage. + Zarr format 3 only. Zarr format 2 arrays should use `dimension_separator` instead. + Default is `("default", "/")`. + codecs : Sequence of Codecs or dicts, optional + An iterable of Codec or dict serializations of Codecs. Zarr V3 only. + + The elements of `codecs` specify the transformation from array values to stored bytes. + Zarr format 3 only. Zarr format 2 arrays should use `filters` and `compressor` instead. + + If no codecs are provided, default codecs will be used based on the data type of the array. + For most data types, the default codecs are the tuple `(BytesCodec(), ZstdCodec())`; + data types that require a special [`zarr.abc.codec.ArrayBytesCodec`][], like variable-length strings or bytes, + will use the [`zarr.abc.codec.ArrayBytesCodec`][] required for the data type instead of [`zarr.codecs.BytesCodec`][]. + dimension_names : Iterable[str | None] | None = None + An iterable of dimension names. Zarr format 3 only. + storage_options : dict + If using an fsspec URL to create the store, these will be passed to + the backend implementation. Ignored otherwise. + config : ArrayConfigLike, optional + Runtime configuration of the array. If provided, will override the + default values from `zarr.config.array`. Returns ------- z : array The array. """ - zarr_format = ( - _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) - or _default_zarr_version() + if zarr_format is None: + zarr_format = _default_zarr_format() + + _warn_unimplemented_kwargs( + { + "synchronizer": synchronizer, + "chunk_store": chunk_store, + "cache_metadata": cache_metadata, + "cache_attrs": cache_attrs, + "object_codec": object_codec, + "read_only": read_only, + "meta_array": meta_array, + } ) - if zarr_format == 2 and chunks is None: - chunks = shape - if zarr_format == 3 and chunk_shape is None: - if chunks is not None: - chunk_shape = chunks - chunks = None - else: - chunk_shape = shape + if write_empty_chunks is not None: + _warn_write_empty_chunks_kwarg() - if order is not None: - warnings.warn( - "order is deprecated, use config `array.order` instead", - DeprecationWarning, - stacklevel=2, - ) - if synchronizer is not None: - warnings.warn("synchronizer is not yet implemented", RuntimeWarning, stacklevel=2) - if chunk_store is not None: - warnings.warn("chunk_store is not yet implemented", RuntimeWarning, stacklevel=2) - if cache_metadata is not None: - warnings.warn("cache_metadata is not yet implemented", RuntimeWarning, stacklevel=2) - if cache_attrs is not None: - warnings.warn("cache_attrs is not yet implemented", RuntimeWarning, stacklevel=2) - if object_codec is not None: - warnings.warn("object_codec is not yet implemented", RuntimeWarning, stacklevel=2) - if dimension_separator is not None: - if zarr_format == 3: - raise ValueError( - "dimension_separator is not supported for zarr format 3, use chunk_key_encoding instead" - ) - else: - warnings.warn( - "dimension_separator is not yet implemented", RuntimeWarning, stacklevel=2 - ) - if write_empty_chunks: - warnings.warn("write_empty_chunks is not yet implemented", RuntimeWarning, stacklevel=2) - if meta_array is not None: - warnings.warn("meta_array is not yet implemented", RuntimeWarning, stacklevel=2) + mode = kwargs.pop("mode", None) + if mode is None: + mode = "a" + store_path = await make_store_path(store, path=path, mode=mode, storage_options=storage_options) - mode = kwargs.pop("mode", cast(AccessModeLiteral, "r" if read_only else "w")) - store_path = await make_store_path(store, mode=mode) - if path is not None: - store_path = store_path / path + config_parsed = parse_array_config(config) + + if write_empty_chunks is not None: + if config is not None: + msg = ( + "Both write_empty_chunks and config keyword arguments are set. " + "This is redundant. When both are set, write_empty_chunks will be used instead " + "of the value in config." + ) + warnings.warn(ZarrUserWarning(msg), stacklevel=1) + config_parsed = dataclasses.replace(config_parsed, write_empty_chunks=write_empty_chunks) - return await AsyncArray.create( + return await AsyncArray._create( store_path, shape=shape, chunks=chunks, - dtype=dtype, + # Legacy v2 behavior: an unspecified dtype defaults to float64. + dtype="float64" if dtype is None else dtype, compressor=compressor, fill_value=fill_value, - exists_ok=overwrite, # TODO: name change + overwrite=overwrite, filters=filters, dimension_separator=dimension_separator, + order=order, zarr_format=zarr_format, chunk_shape=chunk_shape, chunk_key_encoding=chunk_key_encoding, codecs=codecs, dimension_names=dimension_names, attributes=attributes, + config=config_parsed, **kwargs, ) -async def empty(shape: ChunkCoords, **kwargs: Any) -> AsyncArray: - """Create an empty array. +async def empty(shape: tuple[int, ...], **kwargs: Any) -> AnyAsyncArray: + """Create an empty array with the specified shape. The contents will be filled with the + specified fill value or zeros if no fill value is provided. Parameters ---------- shape : int or tuple of int Shape of the empty array. **kwargs - Keyword arguments passed to :func:`zarr.api.asynchronous.create`. + Keyword arguments passed to [`create`][zarr.api.asynchronous.create]. Notes ----- @@ -723,30 +1116,37 @@ async def empty(shape: ChunkCoords, **kwargs: Any) -> AsyncArray: retrieve data from an empty Zarr array, any values may be returned, and these are not guaranteed to be stable from one access to the next. """ - return await create(shape=shape, fill_value=None, **kwargs) + return await create(shape=shape, **kwargs) -async def empty_like(a: ArrayLike, **kwargs: Any) -> AsyncArray: - """Create an empty array like `a`. +async def empty_like(a: ArrayLike, **kwargs: Any) -> AnyAsyncArray: + """Create an empty array like `a`. The contents will be filled with the + array's fill value or zeros if no fill value is provided. Parameters ---------- a : array-like The array to create an empty array like. **kwargs - Keyword arguments passed to :func:`zarr.api.asynchronous.create`. + Keyword arguments passed to [`create`][zarr.api.asynchronous.create]. Returns ------- Array The new array. + + Notes + ----- + The contents of an empty Zarr array are not defined. On attempting to + retrieve data from an empty Zarr array, any values may be returned, + and these are not guaranteed to be stable from one access to the next. """ - like_kwargs = _like_args(a, kwargs) - return await empty(**like_kwargs) + like_kwargs = _like_args(a) | kwargs + return await empty(**like_kwargs) # type: ignore[arg-type] # TODO: add type annotations for fill_value and kwargs -async def full(shape: ChunkCoords, fill_value: Any, **kwargs: Any) -> AsyncArray: +async def full(shape: tuple[int, ...], fill_value: Any, **kwargs: Any) -> AnyAsyncArray: """Create an array, with `fill_value` being used as the default value for uninitialized portions of the array. @@ -757,7 +1157,7 @@ async def full(shape: ChunkCoords, fill_value: Any, **kwargs: Any) -> AsyncArray fill_value : scalar Fill value. **kwargs - Keyword arguments passed to :func:`zarr.api.asynchronous.create`. + Keyword arguments passed to [`create`][zarr.api.asynchronous.create]. Returns ------- @@ -768,7 +1168,7 @@ async def full(shape: ChunkCoords, fill_value: Any, **kwargs: Any) -> AsyncArray # TODO: add type annotations for kwargs -async def full_like(a: ArrayLike, **kwargs: Any) -> AsyncArray: +async def full_like(a: ArrayLike, **kwargs: Any) -> AnyAsyncArray: """Create a filled array like `a`. Parameters @@ -776,20 +1176,18 @@ async def full_like(a: ArrayLike, **kwargs: Any) -> AsyncArray: a : array-like The array to create an empty array like. **kwargs - Keyword arguments passed to :func:`zarr.api.asynchronous.create`. + Keyword arguments passed to [`zarr.api.asynchronous.create`][]. Returns ------- Array The new array. """ - like_kwargs = _like_args(a, kwargs) - if isinstance(a, AsyncArray): - kwargs.setdefault("fill_value", a.metadata.fill_value) - return await full(**like_kwargs) + like_kwargs = _like_args(a) | kwargs + return await full(**like_kwargs) # type: ignore[arg-type] -async def ones(shape: ChunkCoords, **kwargs: Any) -> AsyncArray: +async def ones(shape: tuple[int, ...], **kwargs: Any) -> AnyAsyncArray: """Create an array, with one being used as the default value for uninitialized portions of the array. @@ -798,7 +1196,7 @@ async def ones(shape: ChunkCoords, **kwargs: Any) -> AsyncArray: shape : int or tuple of int Shape of the empty array. **kwargs - Keyword arguments passed to :func:`zarr.api.asynchronous.create`. + Keyword arguments passed to [`zarr.api.asynchronous.create`][]. Returns ------- @@ -808,7 +1206,7 @@ async def ones(shape: ChunkCoords, **kwargs: Any) -> AsyncArray: return await create(shape=shape, fill_value=1, **kwargs) -async def ones_like(a: ArrayLike, **kwargs: Any) -> AsyncArray: +async def ones_like(a: ArrayLike, **kwargs: Any) -> AnyAsyncArray: """Create an array of ones like `a`. Parameters @@ -816,37 +1214,45 @@ async def ones_like(a: ArrayLike, **kwargs: Any) -> AsyncArray: a : array-like The array to create an empty array like. **kwargs - Keyword arguments passed to :func:`zarr.api.asynchronous.create`. + Keyword arguments passed to [`zarr.api.asynchronous.create`][]. Returns ------- Array The new array. """ - like_kwargs = _like_args(a, kwargs) - return await ones(**like_kwargs) + like_args = _like_args(a) + # `ones` supplies its own fill_value, so drop any inherited from `a`. + like_args.pop("fill_value", None) + like_kwargs = like_args | kwargs + return await ones(**like_kwargs) # type: ignore[arg-type] async def open_array( *, # note: this is a change from v2 store: StoreLike | None = None, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, - path: PathLike | None = None, + path: PathLike = "", + storage_options: dict[str, Any] | None = None, **kwargs: Any, # TODO: type kwargs as valid args to save -) -> AsyncArray: +) -> AnyAsyncArray: """Open an array using file-mode-like semantics. Parameters ---------- - store : Store or string - Store or path to directory in file system or name of zip file. + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. zarr_format : {2, 3, None}, optional The zarr format to use when saving. - path : string, optional + path : str, optional Path in store to array. + storage_options : dict + If using an fsspec URL to create the store, these will be passed to + the backend implementation. Ignored otherwise. **kwargs - Any keyword arguments to pass to the array constructor. + Any keyword arguments to pass to [`create`][zarr.api.asynchronous.create]. Returns ------- @@ -854,27 +1260,29 @@ async def open_array( The opened array. """ - store_path = await make_store_path(store) - if path is not None: - store_path = store_path / path + mode = kwargs.pop("mode", None) + store_path = await make_store_path(store, path=path, mode=mode, storage_options=storage_options) - zarr_format = _handle_zarr_version_or_format(zarr_version=zarr_version, zarr_format=zarr_format) + if "write_empty_chunks" in kwargs: + _warn_write_empty_chunks_kwarg() try: return await AsyncArray.open(store_path, zarr_format=zarr_format) - except FileNotFoundError as e: - if store_path.store.mode.create: + except FileNotFoundError as err: + if not store_path.read_only and mode in _CREATE_MODES: + overwrite = _infer_overwrite(mode) + _zarr_format = zarr_format or _default_zarr_format() return await create( store=store_path, - path=path, - zarr_format=zarr_format, - overwrite=store_path.store.mode.overwrite, + zarr_format=_zarr_format, + overwrite=overwrite, **kwargs, ) - raise e + msg = f"No array found in store {store_path.store} at path {store_path.path}" + raise ArrayNotFoundError(msg) from err -async def open_like(a: ArrayLike, path: str, **kwargs: Any) -> AsyncArray: +async def open_like(a: ArrayLike, path: str, **kwargs: Any) -> AnyAsyncArray: """Open a persistent array like `a`. Parameters @@ -884,20 +1292,22 @@ async def open_like(a: ArrayLike, path: str, **kwargs: Any) -> AsyncArray: path : str The path to the new array. **kwargs - Any keyword arguments to pass to the array constructor. + Additional keyword arguments passed to `open_array`. + If `mode` is omitted or `None`, it defaults to `"a"`. Pass `mode="r"` when + opening an existing array from a read-only store. Returns ------- AsyncArray The opened array. """ - like_kwargs = _like_args(a, kwargs) - if isinstance(a, (AsyncArray | Array)): - kwargs.setdefault("fill_value", a.metadata.fill_value) - return await open_array(path=path, **like_kwargs) + like_kwargs = _like_args(a) | kwargs + if like_kwargs.get("mode") is None: + like_kwargs["mode"] = "a" + return await open_array(path=path, **like_kwargs) # type: ignore[arg-type] -async def zeros(shape: ChunkCoords, **kwargs: Any) -> AsyncArray: +async def zeros(shape: tuple[int, ...], **kwargs: Any) -> AnyAsyncArray: """Create an array, with zero being used as the default value for uninitialized portions of the array. @@ -906,7 +1316,7 @@ async def zeros(shape: ChunkCoords, **kwargs: Any) -> AsyncArray: shape : int or tuple of int Shape of the empty array. **kwargs - Keyword arguments passed to :func:`zarr.api.asynchronous.create`. + Keyword arguments passed to [`zarr.api.asynchronous.create`][]. Returns ------- @@ -916,7 +1326,7 @@ async def zeros(shape: ChunkCoords, **kwargs: Any) -> AsyncArray: return await create(shape=shape, fill_value=0, **kwargs) -async def zeros_like(a: ArrayLike, **kwargs: Any) -> AsyncArray: +async def zeros_like(a: ArrayLike, **kwargs: Any) -> AnyAsyncArray: """Create an array of zeros like `a`. Parameters @@ -924,12 +1334,15 @@ async def zeros_like(a: ArrayLike, **kwargs: Any) -> AsyncArray: a : array-like The array to create an empty array like. **kwargs - Keyword arguments passed to :func:`zarr.api.asynchronous.create`. + Keyword arguments passed to [`create`][zarr.api.asynchronous.create]. Returns ------- Array The new array. """ - like_kwargs = _like_args(a, kwargs) - return await zeros(**like_kwargs) + like_args = _like_args(a) + # `zeros` supplies its own fill_value, so drop any inherited from `a`. + like_args.pop("fill_value", None) + like_kwargs = like_args | kwargs + return await zeros(**like_kwargs) # type: ignore[arg-type] diff --git a/src/zarr/api/synchronous.py b/src/zarr/api/synchronous.py index eef87aab7e..30ddf9ce6a 100644 --- a/src/zarr/api/synchronous.py +++ b/src/zarr/api/synchronous.py @@ -1,54 +1,241 @@ from __future__ import annotations -from typing import Any +from typing import TYPE_CHECKING, Any, Literal + +from typing_extensions import deprecated import zarr.api.asynchronous as async_api -from zarr.array import Array, AsyncArray -from zarr.buffer import NDArrayLike -from zarr.common import JSON, AccessModeLiteral, ChunkCoords, ZarrFormat -from zarr.group import Group -from zarr.store import StoreLike -from zarr.sync import sync +import zarr.core.array +from zarr.core.array import DEFAULT_FILL_VALUE, Array, AsyncArray, CompressorLike +from zarr.core.group import Group +from zarr.core.sync import sync +from zarr.core.sync_group import create_hierarchy +from zarr.errors import ZarrDeprecationWarning + +if TYPE_CHECKING: + from collections.abc import Iterable + + import numpy as np + import numpy.typing as npt + + from zarr.abc.codec import Codec + from zarr.abc.numcodec import Numcodec + from zarr.api.asynchronous import ArrayLike, PathLike + from zarr.core.array import ( + CompressorsLike, + FiltersLike, + SerializerLike, + ShardsLike, + ) + from zarr.core.array_spec import ArrayConfigLike + from zarr.core.buffer import NDArrayLike, NDArrayLikeOrScalar + from zarr.core.chunk_key_encodings import ChunkKeyEncoding, ChunkKeyEncodingLike + from zarr.core.common import ( + JSON, + AccessModeLiteral, + ChunksLike, + DimensionNamesLike, + MemoryOrder, + ShapeLike, + ZarrFormat, + ) + from zarr.core.dtype import ZDTypeLike + from zarr.storage import StoreLike + from zarr.types import AnyArray + +__all__ = [ + "array", + "consolidate_metadata", + "copy", + "copy_all", + "copy_store", + "create", + "create_array", + "create_hierarchy", + "empty", + "empty_like", + "from_array", + "full", + "full_like", + "group", + "load", + "ones", + "ones_like", + "open", + "open_array", + "open_consolidated", + "open_group", + "open_like", + "save", + "save_array", + "save_group", + "tree", + "zeros", + "zeros_like", +] + + +def consolidate_metadata( + store: StoreLike, + path: str | None = None, + zarr_format: ZarrFormat | None = None, +) -> Group: + """ + Consolidate the metadata of all nodes in a hierarchy. + + Upon completion, the metadata of the root node in the Zarr hierarchy will be + updated to include all the metadata of child nodes. For Stores that do + not use consolidated metadata, this operation raises a `TypeError`. + Parameters + ---------- + store : StoreLike + The store-like object whose metadata you wish to consolidate. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + path : str, optional + A path to a group in the store to consolidate at. Only children + below that group will be consolidated. -def consolidate_metadata(*args: Any, **kwargs: Any) -> Group: - return Group(sync(async_api.consolidate_metadata(*args, **kwargs))) + By default, the root node is used so all the metadata in the + store is consolidated. + zarr_format : {2, 3, None}, optional + The zarr format of the hierarchy. By default the zarr format + is inferred. + + Returns + ------- + group: Group + The group, with the `consolidated_metadata` field set to include + the metadata of each child node. If the Store doesn't support + consolidated metadata, this function raises a `TypeError`. + See `Store.supports_consolidated_metadata`. + + """ + return Group(sync(async_api.consolidate_metadata(store, path=path, zarr_format=zarr_format))) def copy(*args: Any, **kwargs: Any) -> tuple[int, int, int]: + """ + Not implemented. + """ return sync(async_api.copy(*args, **kwargs)) def copy_all(*args: Any, **kwargs: Any) -> tuple[int, int, int]: + """ + Not implemented. + """ return sync(async_api.copy_all(*args, **kwargs)) def copy_store(*args: Any, **kwargs: Any) -> tuple[int, int, int]: + """ + Not implemented. + """ return sync(async_api.copy_store(*args, **kwargs)) def load( - store: StoreLike, zarr_version: ZarrFormat | None = None, path: str | None = None -) -> NDArrayLike | dict[str, NDArrayLike]: - return sync(async_api.load(store=store, zarr_version=zarr_version, path=path)) + store: StoreLike, + path: str | None = None, + zarr_format: ZarrFormat | None = None, +) -> NDArrayLikeOrScalar | dict[str, NDArrayLikeOrScalar]: + """Load data from an array or group into memory. + + Parameters + ---------- + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + path : str or None, optional + The path within the store from which to load. + + Returns + ------- + out + If the path contains an array, out will be a numpy array. If the path contains + a group, out will be a dict-like object where keys are array names and values + are numpy arrays. + + See Also + -------- + save, savez, open + + Notes + ----- + If loading data from a group of arrays, data will not be immediately loaded into + memory. Rather, arrays will be loaded into memory as they are requested. + + Unlike [`open`][zarr.open], which returns a lazy [`Array`][zarr.Array] or + [`Group`][zarr.Group] backed by the store, `load` eagerly reads the data and + returns it as an in-memory array (or a dict of arrays for a group). + The array type is NumPy by default, but follows the configured + buffer prototype (for example, CuPy for GPU use cases). + Use `open` when you want to read or write data incrementally without loading it + all into memory. + """ + return sync(async_api.load(store=store, zarr_format=zarr_format, path=path)) def open( - *, store: StoreLike | None = None, - mode: AccessModeLiteral | None = None, # type and value changed - zarr_version: ZarrFormat | None = None, # deprecated + *, + mode: AccessModeLiteral | None = None, zarr_format: ZarrFormat | None = None, path: str | None = None, + storage_options: dict[str, Any] | None = None, **kwargs: Any, # TODO: type kwargs as valid args to async_api.open -) -> Array | Group: +) -> AnyArray | Group: + """Open a group or array using file-mode-like semantics. + + Parameters + ---------- + store : StoreLike or None, default=None + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + mode : {'r', 'r+', 'a', 'w', 'w-'}, optional + Persistence mode: 'r' means read only (must exist); 'r+' means + read/write (must exist); 'a' means read/write (create if doesn't + exist); 'w' means create (overwrite if exists); 'w-' means create + (fail if exists). + If the store is read-only, the default is 'r'; otherwise, it is 'a'. + zarr_format : {2, 3, None}, optional + The zarr format to use when saving. + path : str or None, optional + The path within the store to open. + storage_options : dict + If using an fsspec URL to create the store, these will be passed to + the backend implementation. Ignored otherwise. + **kwargs + Additional parameters are passed through to `zarr.open_array` or + `zarr.open_group`. + + Returns + ------- + z : array or group + Return type depends on what exists in the given store. + + See Also + -------- + load + + Notes + ----- + `open` returns a lazy [`Array`][zarr.Array] or [`Group`][zarr.Group] backed by + the store, so data is read and written incrementally. Use [`load`][zarr.load] + instead when you want the data eagerly read into an in-memory array (a + NumPy array by default). + """ obj = sync( async_api.open( store=store, mode=mode, - zarr_version=zarr_version, zarr_format=zarr_format, path=path, + storage_options=storage_options, **kwargs, ) ) @@ -58,41 +245,81 @@ def open( return Group(obj) -def open_consolidated(*args: Any, **kwargs: Any) -> Group: - return Group(sync(async_api.open_consolidated(*args, **kwargs))) +def open_consolidated(*args: Any, use_consolidated: Literal[True] = True, **kwargs: Any) -> Group: + """ + Alias for [`open_group`][zarr.api.synchronous.open_group] with `use_consolidated=True`. + """ + return Group( + sync(async_api.open_consolidated(*args, use_consolidated=use_consolidated, **kwargs)) + ) def save( store: StoreLike, *args: NDArrayLike, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, path: str | None = None, **kwargs: Any, # TODO: type kwargs as valid args to async_api.save ) -> None: - return sync( - async_api.save( - store, *args, zarr_version=zarr_version, zarr_format=zarr_format, path=path, **kwargs - ) - ) + """Save an array or group of arrays to the local file system. + + Parameters + ---------- + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + *args : ndarray + NumPy arrays with data to save. + zarr_format : {2, 3, None}, optional + The zarr format to use when saving. + path : str or None, optional + The path within the group where the arrays will be saved. + **kwargs + NumPy arrays with data to save. + """ + return sync(async_api.save(store, *args, zarr_format=zarr_format, path=path, **kwargs)) def save_array( store: StoreLike, arr: NDArrayLike, *, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, path: str | None = None, + storage_options: dict[str, Any] | None = None, **kwargs: Any, # TODO: type kwargs as valid args to async_api.save_array ) -> None: + """Save a NumPy array to the local file system. + + Follows a similar API to the NumPy save() function. + + Parameters + ---------- + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + arr : ndarray + NumPy array with data to save. + zarr_format : {2, 3, None}, optional + The zarr format to use when saving. The default is `None`, which will + use the default Zarr format defined in the global configuration object. + path : str or None, optional + The path within the store where the array will be saved. + storage_options : dict + If using an fsspec URL to create the store, these will be passed to + the backend implementation. Ignored otherwise. + **kwargs + Passed through to [`create`][zarr.api.asynchronous.create], e.g., compressor. + """ return sync( async_api.save_array( store=store, arr=arr, - zarr_version=zarr_version, zarr_format=zarr_format, path=path, + storage_options=storage_options, **kwargs, ) ) @@ -101,45 +328,139 @@ def save_array( def save_group( store: StoreLike, *args: NDArrayLike, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, path: str | None = None, + storage_options: dict[str, Any] | None = None, **kwargs: NDArrayLike, ) -> None: + """Save several NumPy arrays to the local file system. + + Follows a similar API to the NumPy savez()/savez_compressed() functions. + + Parameters + ---------- + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + *args : ndarray + NumPy arrays with data to save. + zarr_format : {2, 3, None}, optional + The zarr format to use when saving. + path : str or None, optional + Path within the store where the group will be saved. + storage_options : dict + If using an fsspec URL to create the store, these will be passed to + the backend implementation. Ignored otherwise. + **kwargs + NumPy arrays with data to save. + """ + return sync( async_api.save_group( store, *args, - zarr_version=zarr_version, zarr_format=zarr_format, path=path, + storage_options=storage_options, **kwargs, ) ) -def tree(*args: Any, **kwargs: Any) -> None: - return sync(async_api.tree(*args, **kwargs)) +@deprecated("Use Group.tree instead.", category=ZarrDeprecationWarning) +def tree(grp: Group, expand: bool | None = None, level: int | None = None) -> Any: + """Provide a rich display of the hierarchy. + + !!! warning "Deprecated" + `zarr.tree()` is deprecated since v3.0.0 and will be removed in a future release. + Use `group.tree()` instead. + + Parameters + ---------- + grp : Group + Zarr or h5py group. + expand : bool, optional + Only relevant for HTML representation. If True, tree will be fully expanded. + level : int, optional + Maximum depth to descend into hierarchy. + + Returns + ------- + TreeRepr + A pretty-printable object displaying the hierarchy. + """ + return sync(async_api.tree(grp._async_group, expand=expand, level=level)) # TODO: add type annotations for kwargs -def array(data: NDArrayLike, **kwargs: Any) -> Array: +def array(data: npt.ArrayLike | AnyArray, **kwargs: Any) -> AnyArray: + """Create an array filled with `data`. + + Parameters + ---------- + data : array_like + The data to fill the array with. + **kwargs + Passed through to [`create`][zarr.api.asynchronous.create]. + + Returns + ------- + array : Array + The new array. + """ + return Array(sync(async_api.array(data=data, **kwargs))) def group( - *, # Note: this is a change from v2 store: StoreLike | None = None, + *, overwrite: bool = False, - chunk_store: StoreLike | None = None, # not used in async_api - cache_attrs: bool | None = None, # default changed, not used in async_api - synchronizer: Any | None = None, # not used in async_api + chunk_store: StoreLike | None = None, # not used + cache_attrs: bool | None = None, # not used, default changed + synchronizer: Any | None = None, # not used path: str | None = None, - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, - meta_array: Any | None = None, # not used in async_api + meta_array: Any | None = None, # not used attributes: dict[str, JSON] | None = None, + storage_options: dict[str, Any] | None = None, ) -> Group: + """Create a group. + + Parameters + ---------- + store : StoreLike or None, default=None + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + overwrite : bool, optional + If True, delete any pre-existing data in `store` at `path` before + creating the group. + chunk_store : StoreLike or None, default=None + Separate storage for chunks. Not implemented. + cache_attrs : bool, optional + If True (default), user attributes will be cached for attribute read + operations. If False, user attributes are reloaded from the store prior + to all attribute read operations. + synchronizer : object, optional + Array synchronizer. + path : str, optional + Group path within store. + meta_array : array-like, optional + An array instance to use for determining arrays to create and return + to users. Use `numpy.empty(())` by default. + zarr_format : {2, 3, None}, optional + The zarr format to use when saving. + storage_options : dict + If using an fsspec URL to create the store, these will be passed to + the backend implementation. Ignored otherwise. + + Returns + ------- + g : Group + The new group. + """ return Group( sync( async_api.group( @@ -149,28 +470,84 @@ def group( cache_attrs=cache_attrs, synchronizer=synchronizer, path=path, - zarr_version=zarr_version, zarr_format=zarr_format, meta_array=meta_array, attributes=attributes, + storage_options=storage_options, ) ) ) def open_group( - *, # Note: this is a change from v2 store: StoreLike | None = None, - mode: AccessModeLiteral | None = None, # not used in async api + *, + mode: AccessModeLiteral = "a", cache_attrs: bool | None = None, # default changed, not used in async api synchronizer: Any = None, # not used in async api path: str | None = None, chunk_store: StoreLike | None = None, # not used in async api storage_options: dict[str, Any] | None = None, # not used in async api - zarr_version: ZarrFormat | None = None, # deprecated zarr_format: ZarrFormat | None = None, meta_array: Any | None = None, # not used in async api + attributes: dict[str, JSON] | None = None, + use_consolidated: bool | str | None = None, ) -> Group: + """Open a group using file-mode-like semantics. + + Parameters + ---------- + store : StoreLike or None, default=None + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + mode : {'r', 'r+', 'a', 'w', 'w-'}, optional + Persistence mode: 'r' means read only (must exist); 'r+' means + read/write (must exist); 'a' means read/write (create if doesn't + exist); 'w' means create (overwrite if exists); 'w-' means create + (fail if exists). + cache_attrs : bool, optional + If True (default), user attributes will be cached for attribute read + operations. If False, user attributes are reloaded from the store prior + to all attribute read operations. + synchronizer : object, optional + Array synchronizer. + path : str, optional + Group path within store. + chunk_store : StoreLike or None, default=None + Separate storage for chunks. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + storage_options : dict + If using an fsspec URL to create the store, these will be passed to + the backend implementation. Ignored otherwise. + meta_array : array-like, optional + An array instance to use for determining arrays to create and return + to users. Use `numpy.empty(())` by default. + attributes : dict + A dictionary of JSON-serializable values with user-defined attributes. + use_consolidated : bool or str, default None + Whether to use consolidated metadata. + + By default, consolidated metadata is used if it's present in the + store (in the `zarr.json` for Zarr format 3 and in the `.zmetadata` file + for Zarr format 2). + + To explicitly require consolidated metadata, set `use_consolidated=True`, + which will raise an exception if consolidated metadata is not found. + + To explicitly *not* use consolidated metadata, set `use_consolidated=False`, + which will fall back to using the regular, non consolidated metadata. + + Zarr format 2 allowed configuring the key storing the consolidated metadata + (`.zmetadata` by default). Specify the custom key as `use_consolidated` + to load consolidated metadata from a non-default key. + + Returns + ------- + g : Group + The new group. + """ return Group( sync( async_api.open_group( @@ -181,93 +558,892 @@ def open_group( path=path, chunk_store=chunk_store, storage_options=storage_options, - zarr_version=zarr_version, zarr_format=zarr_format, meta_array=meta_array, + attributes=attributes, + use_consolidated=use_consolidated, + ) + ) + ) + + +def create_group( + store: StoreLike, + *, + path: str | None = None, + zarr_format: ZarrFormat | None = None, + overwrite: bool = False, + attributes: dict[str, Any] | None = None, + storage_options: dict[str, Any] | None = None, +) -> Group: + """Create a group. + + Parameters + ---------- + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + path : str, optional + Group path within store. + overwrite : bool, optional + If True, pre-existing data at `path` will be deleted before + creating the group. + zarr_format : {2, 3, None}, optional + The zarr format to use when saving. + If no `zarr_format` is provided, the default format will be used. + This default can be changed by modifying the value of `default_zarr_format` + in [`zarr.config`][zarr.config]. + storage_options : dict + If using an fsspec URL to create the store, these will be passed to + the backend implementation. Ignored otherwise. + + Returns + ------- + Group + The new group. + """ + return Group( + sync( + async_api.create_group( + store=store, + path=path, + overwrite=overwrite, + storage_options=storage_options, + zarr_format=zarr_format, + attributes=attributes, ) ) ) # TODO: add type annotations for kwargs -def create(*args: Any, **kwargs: Any) -> Array: - return Array(sync(async_api.create(*args, **kwargs))) +def create( + shape: tuple[int, ...] | int, + *, # Note: this is a change from v2 + chunks: tuple[int, ...] | int | bool | None = None, + dtype: ZDTypeLike | None = None, + compressor: CompressorLike = "auto", + fill_value: Any | None = DEFAULT_FILL_VALUE, # TODO: need type + order: MemoryOrder | None = None, + store: StoreLike | None = None, + synchronizer: Any | None = None, + overwrite: bool = False, + path: PathLike | None = None, + chunk_store: StoreLike | None = None, + filters: Iterable[dict[str, JSON] | Numcodec] | None = None, + cache_metadata: bool | None = None, + cache_attrs: bool | None = None, + read_only: bool | None = None, + object_codec: Codec | None = None, # TODO: type has changed + dimension_separator: Literal[".", "/"] | None = None, + write_empty_chunks: bool | None = None, # TODO: default has changed + zarr_format: ZarrFormat | None = None, + meta_array: Any | None = None, # TODO: need type + attributes: dict[str, JSON] | None = None, + # v3 only + chunk_shape: tuple[int, ...] | int | None = None, + chunk_key_encoding: ( + ChunkKeyEncoding + | tuple[Literal["default"], Literal[".", "/"]] + | tuple[Literal["v2"], Literal[".", "/"]] + | None + ) = None, + codecs: Iterable[Codec | dict[str, JSON]] | None = None, + dimension_names: DimensionNamesLike = None, + storage_options: dict[str, Any] | None = None, + config: ArrayConfigLike | None = None, + **kwargs: Any, +) -> AnyArray: + """Create an array. + + Parameters + ---------- + shape : int or tuple of ints + Array shape. + chunks : int or tuple of ints, optional + Chunk shape. If True, will be guessed from `shape` and `dtype`. If + False, will be set to `shape`, i.e., single chunk for the whole array. + If an int, the chunk size in each dimension will be given by the value + of `chunks`. Default is True. + dtype : str or dtype, optional + NumPy dtype. + compressor : Codec, optional + Primary compressor to compress chunk data. + Zarr format 2 only. Zarr format 3 arrays should use `codecs` instead. + + If neither `compressor` nor `filters` are provided, the default compressor + [`zarr.codecs.ZstdCodec`][] is used. + + If `compressor` is set to `None`, no compression is used. + fill_value : Any, optional + Fill value for the array. + order : {'C', 'F'}, optional + Deprecated in favor of the `config` keyword argument. + Pass `{'order': }` to `create` instead of using this parameter. + Memory layout to be used within each chunk. + If not specified, the `array.order` parameter in the global config will be used. + store : StoreLike or None, default=None + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + synchronizer : object, optional + Array synchronizer. + overwrite : bool, optional + If True, delete all pre-existing data in `store` at `path` before + creating the array. + path : str, optional + Path under which array is stored. + chunk_store : StoreLike or None, default=None + Separate storage for chunks. If not provided, `store` will be used + for storage of both chunks and metadata. + filters : Iterable[Codec] | Literal["auto"], optional + Iterable of filters to apply to each chunk of the array, in order, before serializing that + chunk to bytes. + + For Zarr format 3, a "filter" is a codec that takes an array and returns an array, + and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a + dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. + + For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the + order of your filters is consistent with the behavior of each filter. + + The default value of `"auto"` instructs Zarr to use a default based on the data + type of the array and the Zarr format specified. For all data types in Zarr V3, and most + data types in Zarr V2, the default filters are empty. The only cases where default filters + are not empty is when the Zarr format is 2, and the data type is a variable-length data type like + [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, + the default filters contains a single element which is a codec specific to that particular data type. + + To create an array with no filters, provide an empty iterable or the value `None`. + cache_metadata : bool, optional + If True, array configuration metadata will be cached for the + lifetime of the object. If False, array metadata will be reloaded + prior to all data access and modification operations (may incur + overhead depending on storage and data access pattern). + cache_attrs : bool, optional + If True (default), user attributes will be cached for attribute read + operations. If False, user attributes are reloaded from the store prior + to all attribute read operations. + read_only : bool, optional + True if array should be protected against modification. + object_codec : Codec, optional + A codec to encode object arrays, only needed if dtype=object. + dimension_separator : {'.', '/'}, optional + Separator placed between the dimensions of a chunk. + Zarr format 2 only. Zarr format 3 arrays should use `chunk_key_encoding` instead. + write_empty_chunks : bool, optional + Deprecated in favor of the `config` keyword argument. + Pass `{'write_empty_chunks': }` to `create` instead of using this parameter. + If True, all chunks will be stored regardless of their + contents. If False, each chunk is compared to the array's fill value + prior to storing. If a chunk is uniformly equal to the fill value, then + that chunk is not be stored, and the store entry for that chunk's key + is deleted. + zarr_format : {2, 3, None}, optional + The Zarr format to use when creating an array. The default is `None`, + which instructs Zarr to choose the default Zarr format value defined in the + runtime configuration. + meta_array : array-like, optional + Not implemented. + attributes : dict[str, JSON], optional + A dictionary of user attributes to store with the array. + chunk_shape : int or tuple of ints, optional + The shape of the Array's chunks (default is None). + Zarr format 3 only. Zarr format 2 arrays should use `chunks` instead. + chunk_key_encoding : ChunkKeyEncoding, optional + A specification of how the chunk keys are represented in storage. + Zarr format 3 only. Zarr format 2 arrays should use `dimension_separator` instead. + Default is `("default", "/")`. + codecs : Sequence of Codecs or dicts, optional + An iterable of Codec or dict serializations of Codecs. Zarr V3 only. + + The elements of `codecs` specify the transformation from array values to stored bytes. + Zarr format 3 only. Zarr format 2 arrays should use `filters` and `compressor` instead. + + If no codecs are provided, default codecs will be used based on the data type of the array. + For most data types, the default codecs are the tuple `(BytesCodec(), ZstdCodec())`; + data types that require a special [`zarr.abc.codec.ArrayBytesCodec`][], like variable-length strings or bytes, + will use the [`zarr.abc.codec.ArrayBytesCodec`][] required for the data type instead of [`zarr.codecs.BytesCodec`][]. + dimension_names : Iterable[str | None] | None = None + An iterable of dimension names. Zarr format 3 only. + storage_options : dict + If using an fsspec URL to create the store, these will be passed to + the backend implementation. Ignored otherwise. + config : ArrayConfigLike, optional + Runtime configuration of the array. If provided, will override the + default values from `zarr.config.array`. + + Returns + ------- + z : Array + The array. + """ + return Array( + sync( + async_api.create( + shape=shape, + chunks=chunks, + dtype=dtype, + compressor=compressor, + fill_value=fill_value, + order=order, + store=store, + synchronizer=synchronizer, + overwrite=overwrite, + path=path, + chunk_store=chunk_store, + filters=filters, + cache_metadata=cache_metadata, + cache_attrs=cache_attrs, + read_only=read_only, + object_codec=object_codec, + dimension_separator=dimension_separator, + write_empty_chunks=write_empty_chunks, + zarr_format=zarr_format, + meta_array=meta_array, + attributes=attributes, + chunk_shape=chunk_shape, + chunk_key_encoding=chunk_key_encoding, + codecs=codecs, + dimension_names=dimension_names, + storage_options=storage_options, + config=config, + **kwargs, + ) + ) + ) + + +def create_array( + store: StoreLike, + *, + name: str | None = None, + shape: ShapeLike | None = None, + dtype: ZDTypeLike | None = None, + data: np.ndarray[Any, np.dtype[Any]] | None = None, + chunks: ChunksLike | Literal["auto"] = "auto", + shards: ShardsLike | None = None, + filters: FiltersLike = "auto", + compressors: CompressorsLike = "auto", + serializer: SerializerLike = "auto", + fill_value: Any | None = DEFAULT_FILL_VALUE, + order: MemoryOrder | None = None, + zarr_format: ZarrFormat | None = 3, + attributes: dict[str, JSON] | None = None, + chunk_key_encoding: ChunkKeyEncodingLike | None = None, + dimension_names: DimensionNamesLike = None, + storage_options: dict[str, Any] | None = None, + overwrite: bool = False, + config: ArrayConfigLike | None = None, + write_data: bool = True, +) -> AnyArray: + """Create an array. + + This function wraps [zarr.core.array.create_array][]. + + Parameters + ---------- + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + name : str or None, optional + The name of the array within the store. If `name` is `None`, the array will be located + at the root of the store. + shape : ShapeLike, optional + Shape of the array. Must be `None` if `data` is provided. + dtype : ZDTypeLike | None + Data type of the array. Must be `None` if `data` is provided. + data : np.ndarray, optional + Array-like data to use for initializing the array. If this parameter is provided, the + `shape` and `dtype` parameters must be `None`. + chunks : tuple[int, ...] | Sequence[Sequence[int]] | Literal["auto"], default="auto" + Chunk shape of the array. + If chunks is "auto", a chunk shape is guessed based on the shape of the array and the dtype. + A nested list of per-dimension edge sizes creates a rectilinear grid. + Rectilinear chunk grids are experimental and must be explicitly enabled + with `zarr.config.set({'array.rectilinear_chunks': True})` while the + feature is stabilizing. + shards : tuple[int, ...], optional + Shard shape of the array. The default value of `None` results in no sharding at all. + filters : Iterable[Codec] | Literal["auto"], optional + Iterable of filters to apply to each chunk of the array, in order, before serializing that + chunk to bytes. + + For Zarr format 3, a "filter" is a codec that takes an array and returns an array, + + and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a + dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. + + For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the + order of your filters is consistent with the behavior of each filter. + + The default value of `"auto"` instructs Zarr to use a default based on the data + type of the array and the Zarr format specified. For all data types in Zarr V3, and most + data types in Zarr V2, the default filters are empty. The only cases where default filters + are not empty is when the Zarr format is 2, and the data type is a variable-length data type like + [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, + the default filters contains a single element which is a codec specific to that particular data type. + + To create an array with no filters, provide an empty iterable or the value `None`. + compressors : Iterable[Codec], optional + List of compressors to apply to the array. Compressors are applied in order, and after any + filters are applied (if any are specified) and the data is serialized into bytes. + + For Zarr format 3, a "compressor" is a codec that takes a bytestream, and + returns another bytestream. Multiple compressors may be provided for Zarr format 3. + If no `compressors` are provided, a default set of compressors will be used. + These defaults can be changed by modifying the value of `array.v3_default_compressors` + in [`zarr.config`][zarr.config]. + Use `None` to omit default compressors. + + For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may + be provided for Zarr format 2. + If no `compressor` is provided, a default compressor will be used. + in [`zarr.config`][zarr.config]. + Use `None` to omit the default compressor. + serializer : dict[str, JSON] | ArrayBytesCodec, optional + Array-to-bytes codec to use for encoding the array data. + Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. + If no `serializer` is provided, a default serializer will be used. + These defaults can be changed by modifying the value of `array.v3_default_serializer` + in [`zarr.config`][zarr.config]. + fill_value : Any, optional + Fill value for the array. + order : {"C", "F"}, optional + The memory order of the array (default is "C"). + For Zarr format 2, this parameter sets the memory order of the array. + For Zarr format 3, this parameter is deprecated, because memory order + is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory + order for Zarr format 3 arrays is via the `config` parameter, e.g. `{'config': 'C'}`. + If no `order` is provided, a default order will be used. + This default can be changed by modifying the value of `array.order` in [`zarr.config`][zarr.config]. + zarr_format : {2, 3}, optional + The zarr format to use when saving. + attributes : dict, optional + Attributes for the array. + chunk_key_encoding : ChunkKeyEncodingLike, optional + A specification of how the chunk keys are represented in storage. + For Zarr format 3, the default is `{"name": "default", "separator": "/"}}`. + For Zarr format 2, the default is `{"name": "v2", "separator": "."}}`. + dimension_names : Iterable[str], optional + The names of the dimensions (default is None). + Zarr format 3 only. Zarr format 2 arrays should not use this parameter. + storage_options : dict, optional + If using an fsspec URL to create the store, these will be passed to the backend implementation. + Ignored otherwise. + overwrite : bool, default False + Whether to overwrite an array with the same name in the store, if one exists. + If `True`, all existing paths in the store will be deleted. + config : ArrayConfigLike, optional + Runtime configuration for the array. + write_data : bool + If a pre-existing array-like object was provided to this function via the `data` parameter + then `write_data` determines whether the values in that array-like object should be + written to the Zarr array created by this function. If `write_data` is `False`, then the + array will be left empty. + + Returns + ------- + Array + The array. + + Examples + -------- + ```python + import zarr + store = zarr.storage.MemoryStore() + arr = zarr.create_array( + store=store, + shape=(100,100), + chunks=(10,10), + dtype='i4', + fill_value=0) + # + ``` + """ + return Array( + sync( + zarr.core.array.create_array( + store, + name=name, + shape=shape, + dtype=dtype, + data=data, + chunks=chunks, + shards=shards, + filters=filters, + compressors=compressors, + serializer=serializer, + fill_value=fill_value, + order=order, + zarr_format=zarr_format, + attributes=attributes, + chunk_key_encoding=chunk_key_encoding, + dimension_names=dimension_names, + storage_options=storage_options, + overwrite=overwrite, + config=config, + write_data=write_data, + ) + ) + ) + + +def from_array( + store: StoreLike, + *, + data: AnyArray | npt.ArrayLike, + write_data: bool = True, + name: str | None = None, + chunks: ChunksLike | Literal["auto", "keep"] = "keep", + shards: ShardsLike | Literal["keep"] | None = "keep", + filters: FiltersLike | Literal["keep"] = "keep", + compressors: CompressorsLike | Literal["keep"] = "keep", + serializer: SerializerLike | Literal["keep"] = "keep", + fill_value: Any | None = DEFAULT_FILL_VALUE, + order: MemoryOrder | None = None, + zarr_format: ZarrFormat | None = None, + attributes: dict[str, JSON] | None = None, + chunk_key_encoding: ChunkKeyEncodingLike | None = None, + dimension_names: DimensionNamesLike = None, + storage_options: dict[str, Any] | None = None, + overwrite: bool = False, + config: ArrayConfigLike | None = None, +) -> AnyArray: + """Create an array from an existing array or array-like. + + Parameters + ---------- + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + data : Array | array-like + The array to copy. + write_data : bool, default True + Whether to copy the data from the input array to the new array. + If `write_data` is `False`, the new array will be created with the same metadata as the + input array, but without any data. + name : str or None, optional + The name of the array within the store. If `name` is `None`, the array will be located + at the root of the store. + chunks : tuple[int, ...] or Sequence[Sequence[int]] or "auto" or "keep", optional + Chunk shape of the array. + Following values are supported: + + - "auto": Automatically determine the chunk shape based on the array's shape and dtype. + - "keep": Retain the chunk grid of the data array if it is a zarr Array. + - tuple[int, ...]: A tuple of integers representing the chunk shape (regular grid). + - Sequence[Sequence[int]]: Per-dimension chunk edge lists (rectilinear grid). + Rectilinear chunk grids are experimental and must be explicitly enabled + with `zarr.config.set({'array.rectilinear_chunks': True})` while the + feature is stabilizing. + + If not specified, defaults to "keep" if data is a zarr Array, otherwise "auto". + shards : tuple[int, ...], optional + Shard shape of the array. + Following values are supported: + + - "auto": Automatically determine the shard shape based on the array's shape and chunk shape. + - "keep": Retain the shard shape of the data array if it is a zarr Array. + - tuple[int, ...]: A tuple of integers representing the shard shape. + - None: No sharding. + + If not specified, defaults to "keep" if data is a zarr Array, otherwise None. + filters : Iterable[Codec] | Literal["auto", "keep"], optional + Iterable of filters to apply to each chunk of the array, in order, before serializing that + chunk to bytes. + + For Zarr format 3, a "filter" is a codec that takes an array and returns an array, + and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a + dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. + + For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the + order of your filters is consistent with the behavior of each filter. + + The default value of `"keep"` instructs Zarr to infer `filters` from `data`. + If that inference is not possible, Zarr will fall back to the behavior specified by `"auto"`, + which is to choose default filters based on the data type of the array and the Zarr format specified. + For all data types in Zarr V3, and most data types in Zarr V2, the default filters are the empty tuple `()`. + The only cases where default filters are not empty is when the Zarr format is 2, and the + data type is a variable-length data type like [`zarr.dtype.VariableLengthUTF8`][] or + [`zarr.dtype.VariableLengthUTF8`][]. In these cases, the default filters is a tuple with a + single element which is a codec specific to that particular data type. + + To create an array with no filters, provide an empty iterable or the value `None`. + compressors : Iterable[Codec] or "auto" or "keep", optional + List of compressors to apply to the array. Compressors are applied in order, and after any + filters are applied (if any are specified) and the data is serialized into bytes. + + For Zarr format 3, a "compressor" is a codec that takes a bytestream, and + returns another bytestream. Multiple compressors may be provided for Zarr format 3. + + For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may + be provided for Zarr format 2. + + Following values are supported: + + - Iterable[Codec]: List of compressors to apply to the array. + - "auto": Automatically determine the compressors based on the array's dtype. + - "keep": Retain the compressors of the input array if it is a zarr Array. + + If no `compressors` are provided, defaults to "keep" if data is a zarr Array, otherwise "auto". + serializer : dict[str, JSON] | ArrayBytesCodec or "auto" or "keep", optional + Array-to-bytes codec to use for encoding the array data. + Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. + + Following values are supported: + + - dict[str, JSON]: A dict representation of an `ArrayBytesCodec`. + - ArrayBytesCodec: An instance of `ArrayBytesCodec`. + - "auto": a default serializer will be used. These defaults can be changed by modifying the value of + `array.v3_default_serializer` in [`zarr.config`][zarr.config]. + - "keep": Retain the serializer of the input array if it is a zarr Array. + + fill_value : Any, optional + Fill value for the array. + If not specified, defaults to the fill value of the data array. + order : {"C", "F"}, optional + The memory order of the array (default is "C"). + For Zarr format 2, this parameter sets the memory order of the array. + For Zarr format 3, this parameter is deprecated, because memory order + is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory + order for Zarr format 3 arrays is via the `config` parameter, e.g. `{'config': 'C'}`. + If not specified, defaults to the memory order of the data array. + zarr_format : {2, 3}, optional + The zarr format to use when saving. + If not specified, defaults to the zarr format of the data array. + attributes : dict, optional + Attributes for the array. + If not specified, defaults to the attributes of the data array. + chunk_key_encoding : ChunkKeyEncoding, optional + A specification of how the chunk keys are represented in storage. + For Zarr format 3, the default is `{"name": "default", "separator": "/"}}`. + For Zarr format 2, the default is `{"name": "v2", "separator": "."}}`. + If not specified and the data array has the same zarr format as the target array, + the chunk key encoding of the data array is used. + dimension_names : Iterable[str | None] | None + The names of the dimensions (default is None). + Zarr format 3 only. Zarr format 2 arrays should not use this parameter. + If not specified, defaults to the dimension names of the data array. + storage_options : dict, optional + If using an fsspec URL to create the store, these will be passed to the backend implementation. + Ignored otherwise. + overwrite : bool, default False + Whether to overwrite an array with the same name in the store, if one exists. + config : ArrayConfig or ArrayConfigLike, optional + Runtime configuration for the array. + + Returns + ------- + Array + The array. + + Examples + -------- + Create an array from an existing Array: + + >>> import asyncio + >>> import zarr + >>> store = zarr.storage.LocalStore("example_from_array.zarr") + >>> arr = zarr.create_array( + ... store={}, + ... shape=(100,100), + ... chunks=(10,10), + ... dtype="int32", + ... fill_value=0 + ... ) + >>> arr2 = zarr.from_array(store, data=arr, overwrite=True) + >>> arr2 + + >>> asyncio.run(store.clear()) # Remove files generated by test + + Create an array from an existing NumPy array: + + >>> import numpy as np + >>> zarr.from_array({}, data=np.arange(10000, dtype="i4").reshape(100, 100)) + + + Create an array from any array-like object: + + >>> arr3 = zarr.from_array({}, data=[[1, 2], [3, 4]]) + >>> arr3 + + >>> arr3[...] + array([[1, 2], [3, 4]]) + + Create an array from an existing Array without copying the data: + + >>> arr4 = zarr.from_array({}, data=[[1, 2], [3, 4]]) + >>> arr5 = zarr.from_array({}, data=arr4, write_data=False) + >>> arr5 + + >>> arr5[...] + array([[0, 0], [0, 0]]) + """ + + return Array( + sync( + zarr.core.array.from_array( + store, + data=data, + write_data=write_data, + name=name, + chunks=chunks, + shards=shards, + filters=filters, + compressors=compressors, + serializer=serializer, + fill_value=fill_value, + order=order, + zarr_format=zarr_format, + attributes=attributes, + chunk_key_encoding=chunk_key_encoding, + dimension_names=dimension_names, + storage_options=storage_options, + overwrite=overwrite, + config=config, + ) + ) + ) # TODO: add type annotations for kwargs -def empty(shape: ChunkCoords, **kwargs: Any) -> Array: +def empty(shape: tuple[int, ...], **kwargs: Any) -> AnyArray: + """Create an empty array with the specified shape. The contents will be filled with the + array's fill value or zeros if no fill value is provided. + + Parameters + ---------- + shape : int or tuple of int + Shape of the empty array. + **kwargs + Keyword arguments passed to [`create`][zarr.api.asynchronous.create]. + + Returns + ------- + Array + The new array. + + Notes + ----- + The contents of an empty Zarr array are not defined. On attempting to + retrieve data from an empty Zarr array, any values may be returned, + and these are not guaranteed to be stable from one access to the next. + """ return Array(sync(async_api.empty(shape, **kwargs))) # TODO: move ArrayLike to common module # TODO: add type annotations for kwargs -def empty_like(a: async_api.ArrayLike, **kwargs: Any) -> Array: +def empty_like(a: ArrayLike, **kwargs: Any) -> AnyArray: + """Create an empty array like another array. The contents will be filled with the + array's fill value or zeros if no fill value is provided. + + Parameters + ---------- + a : array-like + The array to create an empty array like. + **kwargs + Keyword arguments passed to [`create`][zarr.api.asynchronous.create]. + + Returns + ------- + Array + The new array. + + Notes + ----- + The contents of an empty Zarr array are not defined. On attempting to + retrieve data from an empty Zarr array, any values may be returned, + and these are not guaranteed to be stable from one access to the next. + """ return Array(sync(async_api.empty_like(a, **kwargs))) # TODO: add type annotations for kwargs and fill_value -def full(shape: ChunkCoords, fill_value: Any, **kwargs: Any) -> Array: +def full(shape: tuple[int, ...], fill_value: Any, **kwargs: Any) -> AnyArray: + """Create an array with a default fill value. + + Parameters + ---------- + shape : int or tuple of int + Shape of the empty array. + fill_value : scalar + Fill value. + **kwargs + Keyword arguments passed to [`create`][zarr.api.asynchronous.create]. + + Returns + ------- + Array + The new array. + """ return Array(sync(async_api.full(shape=shape, fill_value=fill_value, **kwargs))) # TODO: move ArrayLike to common module # TODO: add type annotations for kwargs -def full_like(a: async_api.ArrayLike, **kwargs: Any) -> Array: +def full_like(a: ArrayLike, **kwargs: Any) -> AnyArray: + """Create a filled array like another array. + + Parameters + ---------- + a : array-like + The array to create an empty array like. + **kwargs + Keyword arguments passed to [`zarr.api.asynchronous.create`][]. + + Returns + ------- + Array + The new array. + """ return Array(sync(async_api.full_like(a, **kwargs))) # TODO: add type annotations for kwargs -def ones(shape: ChunkCoords, **kwargs: Any) -> Array: +def ones(shape: tuple[int, ...], **kwargs: Any) -> AnyArray: + """Create an array with a fill value of one. + + Parameters + ---------- + shape : int or tuple of int + Shape of the empty array. + **kwargs + Keyword arguments passed to [`zarr.api.asynchronous.create`][]. + + Returns + ------- + Array + The new array. + """ return Array(sync(async_api.ones(shape, **kwargs))) # TODO: add type annotations for kwargs -def ones_like(a: async_api.ArrayLike, **kwargs: Any) -> Array: +def ones_like(a: ArrayLike, **kwargs: Any) -> AnyArray: + """Create an array of ones like another array. + + Parameters + ---------- + a : array-like + The array to create an empty array like. + **kwargs + Keyword arguments passed to [`zarr.api.asynchronous.create`][]. + + Returns + ------- + Array + The new array. + """ return Array(sync(async_api.ones_like(a, **kwargs))) # TODO: update this once async_api.open_array is fully implemented -def open_array(*args: Any, **kwargs: Any) -> Array: - return Array(sync(async_api.open_array(*args, **kwargs))) +def open_array( + store: StoreLike | None = None, + *, + zarr_format: ZarrFormat | None = None, + path: PathLike = "", + storage_options: dict[str, Any] | None = None, + **kwargs: Any, +) -> AnyArray: + """Open an array using file-mode-like semantics. + + Parameters + ---------- + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + zarr_format : {2, 3, None}, optional + The zarr format to use when saving. + path : str, optional + Path in store to array. + storage_options : dict + If using an fsspec URL to create the store, these will be passed to + the backend implementation. Ignored otherwise. + **kwargs + Any keyword arguments to pass to [`create`][zarr.api.asynchronous.create]. + + + Returns + ------- + AsyncArray + The opened array. + """ + return Array( + sync( + async_api.open_array( + store=store, + zarr_format=zarr_format, + path=path, + storage_options=storage_options, + **kwargs, + ) + ) + ) # TODO: add type annotations for kwargs -def open_like(a: async_api.ArrayLike, **kwargs: Any) -> Array: - return Array(sync(async_api.open_like(a, **kwargs))) +def open_like(a: ArrayLike, path: str, **kwargs: Any) -> AnyArray: + """Open a persistent array like another array. + + Parameters + ---------- + a : Array + The shape and data-type of a define these same attributes of the returned array. + path : str + The path to the new array. + **kwargs + Additional keyword arguments passed to `open_array`. + If `mode` is omitted or `None`, it defaults to `"a"`. Pass `mode="r"` when + opening an existing array from a read-only store. + + Returns + ------- + Array + The opened array. + """ + return Array(sync(async_api.open_like(a, path=path, **kwargs))) # TODO: add type annotations for kwargs -def zeros(*args: Any, **kwargs: Any) -> Array: - return Array(sync(async_api.zeros(*args, **kwargs))) +def zeros(shape: tuple[int, ...], **kwargs: Any) -> AnyArray: + """Create an array with a fill value of zero. + + Parameters + ---------- + shape : int or tuple of int + Shape of the empty array. + **kwargs + Keyword arguments passed to [`zarr.api.asynchronous.create`][]. + + Returns + ------- + Array + The new array. + """ + return Array(sync(async_api.zeros(shape=shape, **kwargs))) # TODO: add type annotations for kwargs -def zeros_like(a: async_api.ArrayLike, **kwargs: Any) -> Array: - return Array(sync(async_api.zeros_like(a, **kwargs))) +def zeros_like(a: ArrayLike, **kwargs: Any) -> AnyArray: + """Create an array of zeros like another array. + Parameters + ---------- + a : array-like + The array to create an empty array like. + **kwargs + Keyword arguments passed to [`create`][zarr.api.asynchronous.create]. -consolidate_metadata.__doc__ = async_api.copy.__doc__ -copy.__doc__ = async_api.copy.__doc__ -copy_all.__doc__ = async_api.copy_all.__doc__ -copy_store.__doc__ = async_api.copy_store.__doc__ -load.__doc__ = async_api.load.__doc__ -open.__doc__ = async_api.open.__doc__ -open_consolidated.__doc__ = async_api.open_consolidated.__doc__ -save.__doc__ = async_api.save.__doc__ -save_array.__doc__ = async_api.save_array.__doc__ -save_group.__doc__ = async_api.save_group.__doc__ -tree.__doc__ = async_api.tree.__doc__ -array.__doc__ = async_api.array.__doc__ -group.__doc__ = async_api.group.__doc__ -open_group.__doc__ = async_api.open_group.__doc__ -create.__doc__ = async_api.create.__doc__ -empty.__doc__ = async_api.empty.__doc__ -empty_like.__doc__ = async_api.empty_like.__doc__ -full.__doc__ = async_api.full.__doc__ -full_like.__doc__ = async_api.full_like.__doc__ -ones.__doc__ = async_api.ones.__doc__ -ones_like.__doc__ = async_api.ones_like.__doc__ -open_array.__doc__ = async_api.open_array.__doc__ -open_like.__doc__ = async_api.open_like.__doc__ -zeros.__doc__ = async_api.zeros.__doc__ -zeros_like.__doc__ = async_api.zeros_like.__doc__ + Returns + ------- + Array + The new array. + """ + return Array(sync(async_api.zeros_like(a, **kwargs))) diff --git a/src/zarr/array.py b/src/zarr/array.py deleted file mode 100644 index e41118805e..0000000000 --- a/src/zarr/array.py +++ /dev/null @@ -1,2058 +0,0 @@ -from __future__ import annotations - -import json - -# Notes on what I've changed here: -# 1. Split Array into AsyncArray and Array -# 3. Added .size and .attrs methods -# 4. Temporarily disabled the creation of ArrayV2 -# 5. Added from_dict to AsyncArray -# Questions to consider: -# 1. Was splitting the array into two classes really necessary? -from asyncio import gather -from collections.abc import Iterable -from dataclasses import dataclass, field, replace -from typing import Any, Literal, cast - -import numpy as np -import numpy.typing as npt - -from zarr.abc.codec import Codec, CodecPipeline -from zarr.abc.store import set_or_delete -from zarr.attributes import Attributes -from zarr.buffer import BufferPrototype, NDArrayLike, NDBuffer, default_buffer_prototype -from zarr.chunk_grids import RegularChunkGrid, _guess_chunks -from zarr.chunk_key_encodings import ChunkKeyEncoding, DefaultChunkKeyEncoding, V2ChunkKeyEncoding -from zarr.codecs import BytesCodec -from zarr.codecs._v2 import V2Compressor, V2Filters -from zarr.common import ( - JSON, - ZARR_JSON, - ZARRAY_JSON, - ZATTRS_JSON, - ChunkCoords, - ZarrFormat, - concurrent_map, - product, -) -from zarr.config import config, parse_indexing_order -from zarr.indexing import ( - BasicIndexer, - BasicSelection, - BlockIndex, - BlockIndexer, - CoordinateIndexer, - CoordinateSelection, - Fields, - Indexer, - MaskIndexer, - MaskSelection, - OIndex, - OrthogonalIndexer, - OrthogonalSelection, - Selection, - VIndex, - check_fields, - check_no_multi_fields, - is_pure_fancy_indexing, - is_pure_orthogonal_indexing, - is_scalar, - pop_fields, -) -from zarr.metadata import ArrayMetadata, ArrayV2Metadata, ArrayV3Metadata -from zarr.registry import get_pipeline_class -from zarr.store import StoreLike, StorePath, make_store_path -from zarr.store.core import ( - ensure_no_existing_node, -) -from zarr.sync import sync - - -def parse_array_metadata(data: Any) -> ArrayV2Metadata | ArrayV3Metadata: - if isinstance(data, ArrayV2Metadata | ArrayV3Metadata): - return data - elif isinstance(data, dict): - if data["zarr_format"] == 3: - return ArrayV3Metadata.from_dict(data) - elif data["zarr_format"] == 2: - return ArrayV2Metadata.from_dict(data) - raise TypeError - - -def create_codec_pipeline(metadata: ArrayV2Metadata | ArrayV3Metadata) -> CodecPipeline: - if isinstance(metadata, ArrayV3Metadata): - return get_pipeline_class().from_list(metadata.codecs) - elif isinstance(metadata, ArrayV2Metadata): - return get_pipeline_class().from_list( - [V2Filters(metadata.filters or []), V2Compressor(metadata.compressor)] - ) - else: - raise AssertionError - - -@dataclass(frozen=True) -class AsyncArray: - metadata: ArrayMetadata - store_path: StorePath - codec_pipeline: CodecPipeline = field(init=False) - order: Literal["C", "F"] - - def __init__( - self, - metadata: ArrayMetadata, - store_path: StorePath, - order: Literal["C", "F"] | None = None, - ): - metadata_parsed = parse_array_metadata(metadata) - order_parsed = parse_indexing_order(order or config.get("array.order")) - - object.__setattr__(self, "metadata", metadata_parsed) - object.__setattr__(self, "store_path", store_path) - object.__setattr__(self, "order", order_parsed) - object.__setattr__(self, "codec_pipeline", create_codec_pipeline(metadata=metadata_parsed)) - - @classmethod - async def create( - cls, - store: StoreLike, - *, - # v2 and v3 - shape: ChunkCoords, - dtype: npt.DTypeLike, - zarr_format: ZarrFormat = 3, - fill_value: Any | None = None, - attributes: dict[str, JSON] | None = None, - # v3 only - chunk_shape: ChunkCoords | None = None, - chunk_key_encoding: ( - ChunkKeyEncoding - | tuple[Literal["default"], Literal[".", "/"]] - | tuple[Literal["v2"], Literal[".", "/"]] - | None - ) = None, - codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: Iterable[str] | None = None, - # v2 only - chunks: ChunkCoords | None = None, - dimension_separator: Literal[".", "/"] | None = None, - order: Literal["C", "F"] | None = None, - filters: list[dict[str, JSON]] | None = None, - compressor: dict[str, JSON] | None = None, - # runtime - exists_ok: bool = False, - data: npt.ArrayLike | None = None, - ) -> AsyncArray: - store_path = await make_store_path(store) - - if chunk_shape is None: - if chunks is None: - chunk_shape = chunks = _guess_chunks(shape=shape, typesize=np.dtype(dtype).itemsize) - chunk_shape = chunks - elif chunks is not None: - raise ValueError("Only one of chunk_shape or chunks must be provided.") - - if zarr_format == 3: - if dimension_separator is not None: - raise ValueError( - "dimension_separator cannot be used for arrays with version 3. Use chunk_key_encoding instead." - ) - if order is not None: - raise ValueError( - "order cannot be used for arrays with version 3. Use a transpose codec instead." - ) - if filters is not None: - raise ValueError( - "filters cannot be used for arrays with version 3. Use array-to-array codecs instead." - ) - if compressor is not None: - raise ValueError( - "compressor cannot be used for arrays with version 3. Use bytes-to-bytes codecs instead." - ) - result = await cls._create_v3( - store_path, - shape=shape, - dtype=dtype, - chunk_shape=chunk_shape, - fill_value=fill_value, - chunk_key_encoding=chunk_key_encoding, - codecs=codecs, - dimension_names=dimension_names, - attributes=attributes, - exists_ok=exists_ok, - ) - elif zarr_format == 2: - if codecs is not None: - raise ValueError( - "codecs cannot be used for arrays with version 2. Use filters and compressor instead." - ) - if chunk_key_encoding is not None: - raise ValueError( - "chunk_key_encoding cannot be used for arrays with version 2. Use dimension_separator instead." - ) - if dimension_names is not None: - raise ValueError("dimension_names cannot be used for arrays with version 2.") - result = await cls._create_v2( - store_path, - shape=shape, - dtype=dtype, - chunks=chunk_shape, - dimension_separator=dimension_separator, - fill_value=fill_value, - order=order, - filters=filters, - compressor=compressor, - attributes=attributes, - exists_ok=exists_ok, - ) - else: - raise ValueError(f"Insupported zarr_format. Got: {zarr_format}") - - if data is not None: - # insert user-provided data - await result.setitem(..., data) - - return result - - @classmethod - async def _create_v3( - cls, - store_path: StorePath, - *, - shape: ChunkCoords, - dtype: npt.DTypeLike, - chunk_shape: ChunkCoords, - fill_value: Any | None = None, - chunk_key_encoding: ( - ChunkKeyEncoding - | tuple[Literal["default"], Literal[".", "/"]] - | tuple[Literal["v2"], Literal[".", "/"]] - | None - ) = None, - codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: Iterable[str] | None = None, - attributes: dict[str, JSON] | None = None, - exists_ok: bool = False, - ) -> AsyncArray: - if not exists_ok: - await ensure_no_existing_node(store_path, zarr_format=3) - - codecs = list(codecs) if codecs is not None else [BytesCodec()] - - if fill_value is None: - if dtype == np.dtype("bool"): - fill_value = False - else: - fill_value = 0 - - if chunk_key_encoding is None: - chunk_key_encoding = ("default", "/") - assert chunk_key_encoding is not None - - if isinstance(chunk_key_encoding, tuple): - chunk_key_encoding = ( - V2ChunkKeyEncoding(separator=chunk_key_encoding[1]) - if chunk_key_encoding[0] == "v2" - else DefaultChunkKeyEncoding(separator=chunk_key_encoding[1]) - ) - - metadata = ArrayV3Metadata( - shape=shape, - data_type=dtype, - chunk_grid=RegularChunkGrid(chunk_shape=chunk_shape), - chunk_key_encoding=chunk_key_encoding, - fill_value=fill_value, - codecs=codecs, - dimension_names=tuple(dimension_names) if dimension_names else None, - attributes=attributes or {}, - ) - - array = cls(metadata=metadata, store_path=store_path) - - await array._save_metadata(metadata) - return array - - @classmethod - async def _create_v2( - cls, - store_path: StorePath, - *, - shape: ChunkCoords, - dtype: npt.DTypeLike, - chunks: ChunkCoords, - dimension_separator: Literal[".", "/"] | None = None, - fill_value: None | int | float = None, - order: Literal["C", "F"] | None = None, - filters: list[dict[str, JSON]] | None = None, - compressor: dict[str, JSON] | None = None, - attributes: dict[str, JSON] | None = None, - exists_ok: bool = False, - ) -> AsyncArray: - import numcodecs - - if not exists_ok: - await ensure_no_existing_node(store_path, zarr_format=2) - if order is None: - order = "C" - - if dimension_separator is None: - dimension_separator = "." - - metadata = ArrayV2Metadata( - shape=shape, - dtype=np.dtype(dtype), - chunks=chunks, - order=order, - dimension_separator=dimension_separator, - fill_value=0 if fill_value is None else fill_value, - compressor=( - numcodecs.get_codec(compressor).get_config() if compressor is not None else None - ), - filters=( - [numcodecs.get_codec(filter).get_config() for filter in filters] - if filters is not None - else None - ), - attributes=attributes, - ) - array = cls(metadata=metadata, store_path=store_path) - await array._save_metadata(metadata) - return array - - @classmethod - def from_dict( - cls, - store_path: StorePath, - data: dict[str, JSON], - ) -> AsyncArray: - metadata = parse_array_metadata(data) - async_array = cls(metadata=metadata, store_path=store_path) - return async_array - - @classmethod - async def open( - cls, - store: StoreLike, - zarr_format: ZarrFormat | None = 3, - ) -> AsyncArray: - store_path = await make_store_path(store) - - if zarr_format == 2: - zarray_bytes, zattrs_bytes = await gather( - (store_path / ZARRAY_JSON).get(), (store_path / ZATTRS_JSON).get() - ) - if zarray_bytes is None: - raise FileNotFoundError(store_path) - elif zarr_format == 3: - zarr_json_bytes = await (store_path / ZARR_JSON).get() - if zarr_json_bytes is None: - raise FileNotFoundError(store_path) - elif zarr_format is None: - zarr_json_bytes, zarray_bytes, zattrs_bytes = await gather( - (store_path / ZARR_JSON).get(), - (store_path / ZARRAY_JSON).get(), - (store_path / ZATTRS_JSON).get(), - ) - if zarr_json_bytes is not None and zarray_bytes is not None: - # TODO: revisit this exception type - # alternatively, we could warn and favor v3 - raise ValueError("Both zarr.json and .zarray objects exist") - if zarr_json_bytes is None and zarray_bytes is None: - raise FileNotFoundError(store_path) - # set zarr_format based on which keys were found - if zarr_json_bytes is not None: - zarr_format = 3 - else: - zarr_format = 2 - else: - raise ValueError(f"unexpected zarr_format: {zarr_format}") - - if zarr_format == 2: - # V2 arrays are comprised of a .zarray and .zattrs objects - assert zarray_bytes is not None - zarray_dict = json.loads(zarray_bytes.to_bytes()) - zattrs_dict = json.loads(zattrs_bytes.to_bytes()) if zattrs_bytes is not None else {} - zarray_dict["attributes"] = zattrs_dict - return cls(store_path=store_path, metadata=ArrayV2Metadata.from_dict(zarray_dict)) - else: - # V3 arrays are comprised of a zarr.json object - assert zarr_json_bytes is not None - return cls( - store_path=store_path, - metadata=ArrayV3Metadata.from_dict(json.loads(zarr_json_bytes.to_bytes())), - ) - - @property - def ndim(self) -> int: - return len(self.metadata.shape) - - @property - def shape(self) -> ChunkCoords: - return self.metadata.shape - - @property - def chunks(self) -> ChunkCoords: - if isinstance(self.metadata.chunk_grid, RegularChunkGrid): - return self.metadata.chunk_grid.chunk_shape - else: - raise ValueError( - f"chunk attribute is only available for RegularChunkGrid, this array has a {self.metadata.chunk_grid}" - ) - - @property - def size(self) -> int: - return np.prod(self.metadata.shape).item() - - @property - def dtype(self) -> np.dtype[Any]: - return self.metadata.dtype - - @property - def attrs(self) -> dict[str, JSON]: - return self.metadata.attributes - - @property - def read_only(self) -> bool: - return self.store_path.store.mode.readonly - - @property - def path(self) -> str: - """Storage path.""" - return self.store_path.path - - @property - def name(self) -> str | None: - """Array name following h5py convention.""" - if self.path: - # follow h5py convention: add leading slash - name = self.path - if name[0] != "/": - name = "/" + name - return name - return None - - @property - def basename(self) -> str | None: - """Final component of name.""" - if self.name is not None: - return self.name.split("/")[-1] - return None - - async def _get_selection( - self, - indexer: Indexer, - *, - prototype: BufferPrototype, - out: NDBuffer | None = None, - fields: Fields | None = None, - ) -> NDArrayLike: - # check fields are sensible - out_dtype = check_fields(fields, self.dtype) - - # setup output buffer - if out is not None: - if isinstance(out, NDBuffer): - out_buffer = out - else: - raise TypeError(f"out argument needs to be an NDBuffer. Got {type(out)!r}") - if out_buffer.shape != indexer.shape: - raise ValueError( - f"shape of out argument doesn't match. Expected {indexer.shape}, got {out.shape}" - ) - else: - out_buffer = prototype.nd_buffer.create( - shape=indexer.shape, - dtype=out_dtype, - order=self.order, - fill_value=self.metadata.fill_value, - ) - if product(indexer.shape) > 0: - # reading chunks and decoding them - await self.codec_pipeline.read( - [ - ( - self.store_path / self.metadata.encode_chunk_key(chunk_coords), - self.metadata.get_chunk_spec(chunk_coords, self.order, prototype=prototype), - chunk_selection, - out_selection, - ) - for chunk_coords, chunk_selection, out_selection in indexer - ], - out_buffer, - drop_axes=indexer.drop_axes, - ) - return out_buffer.as_ndarray_like() - - async def getitem( - self, - selection: BasicSelection, - *, - prototype: BufferPrototype | None = None, - ) -> NDArrayLike: - if prototype is None: - prototype = default_buffer_prototype() - indexer = BasicIndexer( - selection, - shape=self.metadata.shape, - chunk_grid=self.metadata.chunk_grid, - ) - return await self._get_selection(indexer, prototype=prototype) - - async def _save_metadata(self, metadata: ArrayMetadata) -> None: - to_save = metadata.to_buffer_dict(default_buffer_prototype()) - awaitables = [set_or_delete(self.store_path / key, value) for key, value in to_save.items()] - await gather(*awaitables) - - async def _set_selection( - self, - indexer: Indexer, - value: npt.ArrayLike, - *, - prototype: BufferPrototype, - fields: Fields | None = None, - ) -> None: - # check fields are sensible - check_fields(fields, self.dtype) - fields = check_no_multi_fields(fields) - - # check value shape - if np.isscalar(value): - value = np.asanyarray(value, dtype=self.metadata.dtype) - else: - if not hasattr(value, "shape"): - value = np.asarray(value, self.metadata.dtype) - # assert ( - # value.shape == indexer.shape - # ), f"shape of value doesn't match indexer shape. Expected {indexer.shape}, got {value.shape}" - if not hasattr(value, "dtype") or value.dtype.name != self.metadata.dtype.name: - value = np.array(value, dtype=self.metadata.dtype, order="A") - value = cast(NDArrayLike, value) - # We accept any ndarray like object from the user and convert it - # to a NDBuffer (or subclass). From this point onwards, we only pass - # Buffer and NDBuffer between components. - value_buffer = prototype.nd_buffer.from_ndarray_like(value) - - # merging with existing data and encoding chunks - await self.codec_pipeline.write( - [ - ( - self.store_path / self.metadata.encode_chunk_key(chunk_coords), - self.metadata.get_chunk_spec(chunk_coords, self.order, prototype), - chunk_selection, - out_selection, - ) - for chunk_coords, chunk_selection, out_selection in indexer - ], - value_buffer, - drop_axes=indexer.drop_axes, - ) - - async def setitem( - self, - selection: BasicSelection, - value: npt.ArrayLike, - prototype: BufferPrototype | None = None, - ) -> None: - if prototype is None: - prototype = default_buffer_prototype() - indexer = BasicIndexer( - selection, - shape=self.metadata.shape, - chunk_grid=self.metadata.chunk_grid, - ) - return await self._set_selection(indexer, value, prototype=prototype) - - async def resize( - self, new_shape: ChunkCoords, delete_outside_chunks: bool = True - ) -> AsyncArray: - assert len(new_shape) == len(self.metadata.shape) - new_metadata = self.metadata.update_shape(new_shape) - - # Remove all chunks outside of the new shape - old_chunk_coords = set(self.metadata.chunk_grid.all_chunk_coords(self.metadata.shape)) - new_chunk_coords = set(self.metadata.chunk_grid.all_chunk_coords(new_shape)) - - if delete_outside_chunks: - - async def _delete_key(key: str) -> None: - await (self.store_path / key).delete() - - await concurrent_map( - [ - (self.metadata.encode_chunk_key(chunk_coords),) - for chunk_coords in old_chunk_coords.difference(new_chunk_coords) - ], - _delete_key, - config.get("async.concurrency"), - ) - - # Write new metadata - await self._save_metadata(new_metadata) - return replace(self, metadata=new_metadata) - - async def update_attributes(self, new_attributes: dict[str, JSON]) -> AsyncArray: - new_metadata = self.metadata.update_attributes(new_attributes) - - # Write new metadata - await self._save_metadata(new_metadata) - return replace(self, metadata=new_metadata) - - def __repr__(self) -> str: - return f"" - - async def info(self) -> None: - raise NotImplementedError - - -@dataclass(frozen=True) -class Array: - _async_array: AsyncArray - - @classmethod - def create( - cls, - store: StoreLike, - *, - # v2 and v3 - shape: ChunkCoords, - dtype: npt.DTypeLike, - zarr_format: ZarrFormat = 3, - fill_value: Any | None = None, - attributes: dict[str, JSON] | None = None, - # v3 only - chunk_shape: ChunkCoords | None = None, - chunk_key_encoding: ( - ChunkKeyEncoding - | tuple[Literal["default"], Literal[".", "/"]] - | tuple[Literal["v2"], Literal[".", "/"]] - | None - ) = None, - codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: Iterable[str] | None = None, - # v2 only - chunks: ChunkCoords | None = None, - dimension_separator: Literal[".", "/"] | None = None, - order: Literal["C", "F"] | None = None, - filters: list[dict[str, JSON]] | None = None, - compressor: dict[str, JSON] | None = None, - # runtime - exists_ok: bool = False, - ) -> Array: - async_array = sync( - AsyncArray.create( - store=store, - shape=shape, - dtype=dtype, - zarr_format=zarr_format, - attributes=attributes, - fill_value=fill_value, - chunk_shape=chunk_shape, - chunk_key_encoding=chunk_key_encoding, - codecs=codecs, - dimension_names=dimension_names, - chunks=chunks, - dimension_separator=dimension_separator, - order=order, - filters=filters, - compressor=compressor, - exists_ok=exists_ok, - ), - ) - return cls(async_array) - - @classmethod - def from_dict( - cls, - store_path: StorePath, - data: dict[str, JSON], - ) -> Array: - async_array = AsyncArray.from_dict(store_path=store_path, data=data) - return cls(async_array) - - @classmethod - def open( - cls, - store: StoreLike, - ) -> Array: - async_array = sync(AsyncArray.open(store)) - return cls(async_array) - - @property - def ndim(self) -> int: - return self._async_array.ndim - - @property - def shape(self) -> ChunkCoords: - return self._async_array.shape - - @property - def chunks(self) -> ChunkCoords: - return self._async_array.chunks - - @property - def size(self) -> int: - return self._async_array.size - - @property - def dtype(self) -> np.dtype[Any]: - return self._async_array.dtype - - @property - def attrs(self) -> Attributes: - return Attributes(self) - - @property - def path(self) -> str: - """Storage path.""" - return self._async_array.path - - @property - def name(self) -> str | None: - """Array name following h5py convention.""" - return self._async_array.name - - @property - def basename(self) -> str | None: - """Final component of name.""" - return self._async_array.basename - - @property - def metadata(self) -> ArrayMetadata: - return self._async_array.metadata - - @property - def store_path(self) -> StorePath: - return self._async_array.store_path - - @property - def order(self) -> Literal["C", "F"]: - return self._async_array.order - - @property - def read_only(self) -> bool: - return self._async_array.read_only - - @property - def fill_value(self) -> Any: - return self.metadata.fill_value - - def __array__( - self, dtype: npt.DTypeLike | None = None, copy: bool | None = None - ) -> NDArrayLike: - """ - This method is used by numpy when converting zarr.Array into a numpy array. - For more information, see https://numpy.org/devdocs/user/basics.interoperability.html#the-array-method - """ - if copy is False: - msg = "`copy=False` is not supported. This method always creates a copy." - raise ValueError(msg) - - arr_np = self[...] - - if dtype is not None: - arr_np = arr_np.astype(dtype) - - return arr_np - - def __getitem__(self, selection: Selection) -> NDArrayLike: - """Retrieve data for an item or region of the array. - - Parameters - ---------- - selection : tuple - An integer index or slice or tuple of int/slice objects specifying the - requested item or region for each dimension of the array. - - Returns - ------- - NDArrayLike - An array-like containing the data for the requested region. - - Examples - -------- - Setup a 1-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> data = np.arange(100, dtype="uint16") - >>> z = Array.create( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunk_shape=(10,), - >>> dtype=data.dtype, - >>> ) - >>> z[:] = data - - Retrieve a single item:: - - >>> z[5] - 5 - - Retrieve a region via slicing:: - - >>> z[:5] - array([0, 1, 2, 3, 4]) - >>> z[-5:] - array([95, 96, 97, 98, 99]) - >>> z[5:10] - array([5, 6, 7, 8, 9]) - >>> z[5:10:2] - array([5, 7, 9]) - >>> z[::2] - array([ 0, 2, 4, ..., 94, 96, 98]) - - Load the entire array into memory:: - - >>> z[...] - array([ 0, 1, 2, ..., 97, 98, 99]) - - Setup a 2-dimensional array:: - - >>> data = np.arange(100, dtype="uint16").reshape(10, 10) - >>> z = Array.create( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunk_shape=(10, 10), - >>> dtype=data.dtype, - >>> ) - >>> z[:] = data - - Retrieve an item:: - - >>> z[2, 2] - 22 - - Retrieve a region via slicing:: - - >>> z[1:3, 1:3] - array([[11, 12], - [21, 22]]) - >>> z[1:3, :] - array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], - [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]) - >>> z[:, 1:3] - array([[ 1, 2], - [11, 12], - [21, 22], - [31, 32], - [41, 42], - [51, 52], - [61, 62], - [71, 72], - [81, 82], - [91, 92]]) - >>> z[0:5:2, 0:5:2] - array([[ 0, 2, 4], - [20, 22, 24], - [40, 42, 44]]) - >>> z[::2, ::2] - array([[ 0, 2, 4, 6, 8], - [20, 22, 24, 26, 28], - [40, 42, 44, 46, 48], - [60, 62, 64, 66, 68], - [80, 82, 84, 86, 88]]) - - Load the entire array into memory:: - - >>> z[...] - array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], - [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], - [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], - [30, 31, 32, 33, 34, 35, 36, 37, 38, 39], - [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], - [50, 51, 52, 53, 54, 55, 56, 57, 58, 59], - [60, 61, 62, 63, 64, 65, 66, 67, 68, 69], - [70, 71, 72, 73, 74, 75, 76, 77, 78, 79], - [80, 81, 82, 83, 84, 85, 86, 87, 88, 89], - [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]]) - - Notes - ----- - Slices with step > 1 are supported, but slices with negative step are not. - - For arrays with a structured dtype, see zarr v2 for examples of how to use - fields - - Currently the implementation for __getitem__ is provided by - :func:`vindex` if the indexing is pure fancy indexing (ie a - broadcast-compatible tuple of integer array indices), or by - :func:`set_basic_selection` otherwise. - - Effectively, this means that the following indexing modes are supported: - - - integer indexing - - slice indexing - - mixed slice and integer indexing - - boolean indexing - - fancy indexing (vectorized list of integers) - - For specific indexing options including outer indexing, see the - methods listed under See Also. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection, - set_orthogonal_selection, get_block_selection, set_block_selection, - vindex, oindex, blocks, __setitem__ - - """ - fields, pure_selection = pop_fields(selection) - if is_pure_fancy_indexing(pure_selection, self.ndim): - return self.vindex[cast(CoordinateSelection | MaskSelection, selection)] - elif is_pure_orthogonal_indexing(pure_selection, self.ndim): - return self.get_orthogonal_selection(pure_selection, fields=fields) - else: - return self.get_basic_selection(cast(BasicSelection, pure_selection), fields=fields) - - def __setitem__(self, selection: Selection, value: npt.ArrayLike) -> None: - """Modify data for an item or region of the array. - - Parameters - ---------- - selection : tuple - An integer index or slice or tuple of int/slice specifying the requested - region for each dimension of the array. - value : npt.ArrayLike - An array-like containing the data to be stored in the selection. - - Examples - -------- - Setup a 1-dimensional array:: - - >>> import zarr - >>> z = zarr.zeros( - >>> shape=(100,), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(5,), - >>> dtype="i4", - >>> ) - - Set all array elements to the same scalar value:: - - >>> z[...] = 42 - >>> z[...] - array([42, 42, 42, ..., 42, 42, 42]) - - Set a portion of the array:: - - >>> z[:10] = np.arange(10) - >>> z[-10:] = np.arange(10)[::-1] - >>> z[...] - array([ 0, 1, 2, ..., 2, 1, 0]) - - Setup a 2-dimensional array:: - - >>> z = zarr.zeros( - >>> shape=(5, 5), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(5, 5), - >>> dtype="i4", - >>> ) - - Set all array elements to the same scalar value:: - - >>> z[...] = 42 - - Set a portion of the array:: - - >>> z[0, :] = np.arange(z.shape[1]) - >>> z[:, 0] = np.arange(z.shape[0]) - >>> z[...] - array([[ 0, 1, 2, 3, 4], - [ 1, 42, 42, 42, 42], - [ 2, 42, 42, 42, 42], - [ 3, 42, 42, 42, 42], - [ 4, 42, 42, 42, 42]]) - - Notes - ----- - Slices with step > 1 are supported, but slices with negative step are not. - - For arrays with a structured dtype, see zarr v2 for examples of how to use - fields - - Currently the implementation for __setitem__ is provided by - :func:`vindex` if the indexing is pure fancy indexing (ie a - broadcast-compatible tuple of integer array indices), or by - :func:`set_basic_selection` otherwise. - - Effectively, this means that the following indexing modes are supported: - - - integer indexing - - slice indexing - - mixed slice and integer indexing - - boolean indexing - - fancy indexing (vectorized list of integers) - - For specific indexing options including outer indexing, see the - methods listed under See Also. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection, - set_orthogonal_selection, get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__ - - """ - fields, pure_selection = pop_fields(selection) - if is_pure_fancy_indexing(pure_selection, self.ndim): - self.vindex[cast(CoordinateSelection | MaskSelection, selection)] = value - elif is_pure_orthogonal_indexing(pure_selection, self.ndim): - self.set_orthogonal_selection(pure_selection, value, fields=fields) - else: - self.set_basic_selection(cast(BasicSelection, pure_selection), value, fields=fields) - - def get_basic_selection( - self, - selection: BasicSelection = Ellipsis, - *, - out: NDBuffer | None = None, - prototype: BufferPrototype | None = None, - fields: Fields | None = None, - ) -> NDArrayLike: - """Retrieve data for an item or region of the array. - - Parameters - ---------- - selection : tuple - A tuple specifying the requested item or region for each dimension of the - array. May be any combination of int and/or slice or ellipsis for multidimensional arrays. - out : NDBuffer, optional - If given, load the selected data directly into this buffer. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to - extract data for. - prototype : BufferPrototype, optional - The prototype of the buffer to use for the output data. If not provided, the default buffer prototype is used. - - Returns - ------- - NDArrayLike - An array-like containing the data for the requested region. - - Examples - -------- - Setup a 1-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> data = np.arange(100, dtype="uint16") - >>> z = Array.create( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunk_shape=(3,), - >>> dtype=data.dtype, - >>> ) - >>> z[:] = data - - Retrieve a single item:: - - >>> z.get_basic_selection(5) - 5 - - Retrieve a region via slicing:: - - >>> z.get_basic_selection(slice(5)) - array([0, 1, 2, 3, 4]) - >>> z.get_basic_selection(slice(-5, None)) - array([95, 96, 97, 98, 99]) - >>> z.get_basic_selection(slice(5, 10)) - array([5, 6, 7, 8, 9]) - >>> z.get_basic_selection(slice(5, 10, 2)) - array([5, 7, 9]) - >>> z.get_basic_selection(slice(None, None, 2)) - array([ 0, 2, 4, ..., 94, 96, 98]) - - Setup a 3-dimensional array:: - - >>> data = np.arange(1000).reshape(10, 10, 10) - >>> z = Array.create( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunk_shape=(5, 5, 5), - >>> dtype=data.dtype, - >>> ) - >>> z[:] = data - - Retrieve an item:: - - >>> z.get_basic_selection((1, 2, 3)) - 123 - - Retrieve a region via slicing and Ellipsis:: - - >>> z.get_basic_selection((slice(1, 3), slice(1, 3), 0)) - array([[110, 120], - [210, 220]]) - >>> z.get_basic_selection(0, (slice(1, 3), slice(None))) - array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], - [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]) - >>> z.get_basic_selection((..., 5)) - array([[ 2 12 22 32 42 52 62 72 82 92] - [102 112 122 132 142 152 162 172 182 192] - ... - [802 812 822 832 842 852 862 872 882 892] - [902 912 922 932 942 952 962 972 982 992]] - - Notes - ----- - Slices with step > 1 are supported, but slices with negative step are not. - - For arrays with a structured dtype, see zarr v2 for examples of how to use - the `fields` parameter. - - This method provides the implementation for accessing data via the - square bracket notation (__getitem__). See :func:`__getitem__` for examples - using the alternative notation. - - See Also - -------- - set_basic_selection, get_mask_selection, set_mask_selection, - get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection, - set_orthogonal_selection, get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - - if prototype is None: - prototype = default_buffer_prototype() - return sync( - self._async_array._get_selection( - BasicIndexer(selection, self.shape, self.metadata.chunk_grid), - out=out, - fields=fields, - prototype=prototype, - ) - ) - - def set_basic_selection( - self, - selection: BasicSelection, - value: npt.ArrayLike, - *, - fields: Fields | None = None, - prototype: BufferPrototype | None = None, - ) -> None: - """Modify data for an item or region of the array. - - Parameters - ---------- - selection : tuple - A tuple specifying the requested item or region for each dimension of the - array. May be any combination of int and/or slice or ellipsis for multidimensional arrays. - value : npt.ArrayLike - An array-like containing values to be stored into the array. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to set - data for. - prototype : BufferPrototype, optional - The prototype of the buffer used for setting the data. If not provided, the - default buffer prototype is used. - - Examples - -------- - Setup a 1-dimensional array:: - - >>> import zarr - >>> z = zarr.zeros( - >>> shape=(100,), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(100,), - >>> dtype="i4", - >>> ) - - Set all array elements to the same scalar value:: - - >>> z.set_basic_selection(..., 42) - >>> z[...] - array([42, 42, 42, ..., 42, 42, 42]) - - Set a portion of the array:: - - >>> z.set_basic_selection(slice(10), np.arange(10)) - >>> z.set_basic_selection(slice(-10, None), np.arange(10)[::-1]) - >>> z[...] - array([ 0, 1, 2, ..., 2, 1, 0]) - - Setup a 2-dimensional array:: - - >>> z = zarr.zeros( - >>> shape=(5, 5), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(5, 5), - >>> dtype="i4", - >>> ) - - Set all array elements to the same scalar value:: - - >>> z.set_basic_selection(..., 42) - - Set a portion of the array:: - - >>> z.set_basic_selection((0, slice(None)), np.arange(z.shape[1])) - >>> z.set_basic_selection((slice(None), 0), np.arange(z.shape[0])) - >>> z[...] - array([[ 0, 1, 2, 3, 4], - [ 1, 42, 42, 42, 42], - [ 2, 42, 42, 42, 42], - [ 3, 42, 42, 42, 42], - [ 4, 42, 42, 42, 42]]) - - Notes - ----- - For arrays with a structured dtype, see zarr v2 for examples of how to use - the `fields` parameter. - - This method provides the underlying implementation for modifying data via square - bracket notation, see :func:`__setitem__` for equivalent examples using the - alternative notation. - - See Also - -------- - get_basic_selection, get_mask_selection, set_mask_selection, - get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection, - set_orthogonal_selection, get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - if prototype is None: - prototype = default_buffer_prototype() - indexer = BasicIndexer(selection, self.shape, self.metadata.chunk_grid) - sync(self._async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) - - def get_orthogonal_selection( - self, - selection: OrthogonalSelection, - *, - out: NDBuffer | None = None, - fields: Fields | None = None, - prototype: BufferPrototype | None = None, - ) -> NDArrayLike: - """Retrieve data by making a selection for each dimension of the array. For - example, if an array has 2 dimensions, allows selecting specific rows and/or - columns. The selection for each dimension can be either an integer (indexing a - single item), a slice, an array of integers, or a Boolean array where True - values indicate a selection. - - Parameters - ---------- - selection : tuple - A selection for each dimension of the array. May be any combination of int, - slice, integer array or Boolean array. - out : NDBuffer, optional - If given, load the selected data directly into this buffer. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to - extract data for. - prototype : BufferPrototype, optional - The prototype of the buffer to use for the output data. If not provided, the default buffer prototype is used. - - Returns - ------- - NDArrayLike - An array-like containing the data for the requested selection. - - Examples - -------- - Setup a 2-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> data = np.arange(100).reshape(10, 10) - >>> z = Array.create( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunk_shape=data.shape, - >>> dtype=data.dtype, - >>> ) - >>> z[:] = data - - Retrieve rows and columns via any combination of int, slice, integer array and/or - Boolean array:: - - >>> z.get_orthogonal_selection(([1, 4], slice(None))) - array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], - [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]]) - >>> z.get_orthogonal_selection((slice(None), [1, 4])) - array([[ 1, 4], - [11, 14], - [21, 24], - [31, 34], - [41, 44], - [51, 54], - [61, 64], - [71, 74], - [81, 84], - [91, 94]]) - >>> z.get_orthogonal_selection(([1, 4], [1, 4])) - array([[11, 14], - [41, 44]]) - >>> sel = np.zeros(z.shape[0], dtype=bool) - >>> sel[1] = True - >>> sel[4] = True - >>> z.get_orthogonal_selection((sel, sel)) - array([[11, 14], - [41, 44]]) - - For convenience, the orthogonal selection functionality is also available via the - `oindex` property, e.g.:: - - >>> z.oindex[[1, 4], :] - array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], - [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]]) - >>> z.oindex[:, [1, 4]] - array([[ 1, 4], - [11, 14], - [21, 24], - [31, 34], - [41, 44], - [51, 54], - [61, 64], - [71, 74], - [81, 84], - [91, 94]]) - >>> z.oindex[[1, 4], [1, 4]] - array([[11, 14], - [41, 44]]) - >>> sel = np.zeros(z.shape[0], dtype=bool) - >>> sel[1] = True - >>> sel[4] = True - >>> z.oindex[sel, sel] - array([[11, 14], - [41, 44]]) - - Notes - ----- - Orthogonal indexing is also known as outer indexing. - - Slices with step > 1 are supported, but slices with negative step are not. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_coordinate_selection, set_coordinate_selection, set_orthogonal_selection, - get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - if prototype is None: - prototype = default_buffer_prototype() - indexer = OrthogonalIndexer(selection, self.shape, self.metadata.chunk_grid) - return sync( - self._async_array._get_selection( - indexer=indexer, out=out, fields=fields, prototype=prototype - ) - ) - - def set_orthogonal_selection( - self, - selection: OrthogonalSelection, - value: npt.ArrayLike, - *, - fields: Fields | None = None, - prototype: BufferPrototype | None = None, - ) -> None: - """Modify data via a selection for each dimension of the array. - - Parameters - ---------- - selection : tuple - A selection for each dimension of the array. May be any combination of int, - slice, integer array or Boolean array. - value : npt.ArrayLike - An array-like array containing the data to be stored in the array. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to set - data for. - prototype : BufferPrototype, optional - The prototype of the buffer used for setting the data. If not provided, the - default buffer prototype is used. - - Examples - -------- - Setup a 2-dimensional array:: - - >>> import zarr - >>> z = zarr.zeros( - >>> shape=(5, 5), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(5, 5), - >>> dtype="i4", - >>> ) - - - Set data for a selection of rows:: - - >>> z.set_orthogonal_selection(([1, 4], slice(None)), 1) - >>> z[...] - array([[0, 0, 0, 0, 0], - [1, 1, 1, 1, 1], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [1, 1, 1, 1, 1]]) - - Set data for a selection of columns:: - - >>> z.set_orthogonal_selection((slice(None), [1, 4]), 2) - >>> z[...] - array([[0, 2, 0, 0, 2], - [1, 2, 1, 1, 2], - [0, 2, 0, 0, 2], - [0, 2, 0, 0, 2], - [1, 2, 1, 1, 2]]) - - Set data for a selection of rows and columns:: - - >>> z.set_orthogonal_selection(([1, 4], [1, 4]), 3) - >>> z[...] - array([[0, 2, 0, 0, 2], - [1, 3, 1, 1, 3], - [0, 2, 0, 0, 2], - [0, 2, 0, 0, 2], - [1, 3, 1, 1, 3]]) - - Set data from a 2D array:: - - >>> values = np.arange(10).reshape(2, 5) - >>> z.set_orthogonal_selection(([0, 3], ...), values) - >>> z[...] - array([[0, 1, 2, 3, 4], - [1, 3, 1, 1, 3], - [0, 2, 0, 0, 2], - [5, 6, 7, 8, 9], - [1, 3, 1, 1, 3]]) - - For convenience, this functionality is also available via the `oindex` property. - E.g.:: - - >>> z.oindex[[1, 4], [1, 4]] = 4 - >>> z[...] - array([[0, 1, 2, 3, 4], - [1, 4, 1, 1, 4], - [0, 2, 0, 0, 2], - [5, 6, 7, 8, 9], - [1, 4, 1, 1, 4]]) - - Notes - ----- - Orthogonal indexing is also known as outer indexing. - - Slices with step > 1 are supported, but slices with negative step are not. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection, - get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - if prototype is None: - prototype = default_buffer_prototype() - indexer = OrthogonalIndexer(selection, self.shape, self.metadata.chunk_grid) - return sync( - self._async_array._set_selection(indexer, value, fields=fields, prototype=prototype) - ) - - def get_mask_selection( - self, - mask: MaskSelection, - *, - out: NDBuffer | None = None, - fields: Fields | None = None, - prototype: BufferPrototype | None = None, - ) -> NDArrayLike: - """Retrieve a selection of individual items, by providing a Boolean array of the - same shape as the array against which the selection is being made, where True - values indicate a selected item. - - Parameters - ---------- - selection : ndarray, bool - A Boolean array of the same shape as the array against which the selection is - being made. - out : NDBuffer, optional - If given, load the selected data directly into this buffer. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to - extract data for. - prototype : BufferPrototype, optional - The prototype of the buffer to use for the output data. If not provided, the default buffer prototype is used. - - Returns - ------- - NDArrayLike - An array-like containing the data for the requested selection. - - Examples - -------- - Setup a 2-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> data = np.arange(100).reshape(10, 10) - >>> z = Array.create( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunk_shape=data.shape, - >>> dtype=data.dtype, - >>> ) - >>> z[:] = data - - Retrieve items by specifying a mask:: - - >>> sel = np.zeros_like(z, dtype=bool) - >>> sel[1, 1] = True - >>> sel[4, 4] = True - >>> z.get_mask_selection(sel) - array([11, 44]) - - For convenience, the mask selection functionality is also available via the - `vindex` property, e.g.:: - - >>> z.vindex[sel] - array([11, 44]) - - Notes - ----- - Mask indexing is a form of vectorized or inner indexing, and is equivalent to - coordinate indexing. Internally the mask array is converted to coordinate - arrays by calling `np.nonzero`. - - See Also - -------- - get_basic_selection, set_basic_selection, set_mask_selection, - get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection, - set_coordinate_selection, get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - """ - - if prototype is None: - prototype = default_buffer_prototype() - indexer = MaskIndexer(mask, self.shape, self.metadata.chunk_grid) - return sync( - self._async_array._get_selection( - indexer=indexer, out=out, fields=fields, prototype=prototype - ) - ) - - def set_mask_selection( - self, - mask: MaskSelection, - value: npt.ArrayLike, - *, - fields: Fields | None = None, - prototype: BufferPrototype | None = None, - ) -> None: - """Modify a selection of individual items, by providing a Boolean array of the - same shape as the array against which the selection is being made, where True - values indicate a selected item. - - Parameters - ---------- - selection : ndarray, bool - A Boolean array of the same shape as the array against which the selection is - being made. - value : npt.ArrayLike - An array-like containing values to be stored into the array. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to set - data for. - - Examples - -------- - Setup a 2-dimensional array:: - - >>> import zarr - >>> z = zarr.zeros( - >>> shape=(5, 5), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(5, 5), - >>> dtype="i4", - >>> ) - - Set data for a selection of items:: - - >>> sel = np.zeros_like(z, dtype=bool) - >>> sel[1, 1] = True - >>> sel[4, 4] = True - >>> z.set_mask_selection(sel, 1) - >>> z[...] - array([[0, 0, 0, 0, 0], - [0, 1, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 1]]) - - For convenience, this functionality is also available via the `vindex` property. - E.g.:: - - >>> z.vindex[sel] = 2 - >>> z[...] - array([[0, 0, 0, 0, 0], - [0, 2, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 2]]) - - Notes - ----- - Mask indexing is a form of vectorized or inner indexing, and is equivalent to - coordinate indexing. Internally the mask array is converted to coordinate - arrays by calling `np.nonzero`. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, - get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection, - set_coordinate_selection, get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - if prototype is None: - prototype = default_buffer_prototype() - indexer = MaskIndexer(mask, self.shape, self.metadata.chunk_grid) - sync(self._async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) - - def get_coordinate_selection( - self, - selection: CoordinateSelection, - *, - out: NDBuffer | None = None, - fields: Fields | None = None, - prototype: BufferPrototype | None = None, - ) -> NDArrayLike: - """Retrieve a selection of individual items, by providing the indices - (coordinates) for each selected item. - - Parameters - ---------- - selection : tuple - An integer (coordinate) array for each dimension of the array. - out : NDBuffer, optional - If given, load the selected data directly into this buffer. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to - extract data for. - prototype : BufferPrototype, optional - The prototype of the buffer to use for the output data. If not provided, the default buffer prototype is used. - - Returns - ------- - NDArrayLike - An array-like containing the data for the requested coordinate selection. - - Examples - -------- - Setup a 2-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> data = np.arange(0, 100, dtype="uint16").reshape((10, 10)) - >>> z = Array.create( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunk_shape=(3, 3), - >>> dtype=data.dtype, - >>> ) - >>> z[:] = data - - Retrieve items by specifying their coordinates:: - - >>> z.get_coordinate_selection(([1, 4], [1, 4])) - array([11, 44]) - - For convenience, the coordinate selection functionality is also available via the - `vindex` property, e.g.:: - - >>> z.vindex[[1, 4], [1, 4]] - array([11, 44]) - - Notes - ----- - Coordinate indexing is also known as point selection, and is a form of vectorized - or inner indexing. - - Slices are not supported. Coordinate arrays must be provided for all dimensions - of the array. - - Coordinate arrays may be multidimensional, in which case the output array will - also be multidimensional. Coordinate arrays are broadcast against each other - before being applied. The shape of the output will be the same as the shape of - each coordinate array after broadcasting. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_orthogonal_selection, set_orthogonal_selection, set_coordinate_selection, - get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - if prototype is None: - prototype = default_buffer_prototype() - indexer = CoordinateIndexer(selection, self.shape, self.metadata.chunk_grid) - out_array = sync( - self._async_array._get_selection( - indexer=indexer, out=out, fields=fields, prototype=prototype - ) - ) - - if hasattr(out_array, "shape"): - # restore shape - out_array = np.array(out_array).reshape(indexer.sel_shape) - return out_array - - def set_coordinate_selection( - self, - selection: CoordinateSelection, - value: npt.ArrayLike, - *, - fields: Fields | None = None, - prototype: BufferPrototype | None = None, - ) -> None: - """Modify a selection of individual items, by providing the indices (coordinates) - for each item to be modified. - - Parameters - ---------- - selection : tuple - An integer (coordinate) array for each dimension of the array. - value : npt.ArrayLike - An array-like containing values to be stored into the array. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to set - data for. - - Examples - -------- - Setup a 2-dimensional array:: - - >>> import zarr - >>> z = zarr.zeros( - >>> shape=(5, 5), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(5, 5), - >>> dtype="i4", - >>> ) - - Set data for a selection of items:: - - >>> z.set_coordinate_selection(([1, 4], [1, 4]), 1) - >>> z[...] - array([[0, 0, 0, 0, 0], - [0, 1, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 1]]) - - For convenience, this functionality is also available via the `vindex` property. - E.g.:: - - >>> z.vindex[[1, 4], [1, 4]] = 2 - >>> z[...] - array([[0, 0, 0, 0, 0], - [0, 2, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 2]]) - - Notes - ----- - Coordinate indexing is also known as point selection, and is a form of vectorized - or inner indexing. - - Slices are not supported. Coordinate arrays must be provided for all dimensions - of the array. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection, - get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - if prototype is None: - prototype = default_buffer_prototype() - # setup indexer - indexer = CoordinateIndexer(selection, self.shape, self.metadata.chunk_grid) - - # handle value - need ndarray-like flatten value - if not is_scalar(value, self.dtype): - try: - from numcodecs.compat import ensure_ndarray_like - - value = ensure_ndarray_like(value) # TODO replace with agnostic - except TypeError: - # Handle types like `list` or `tuple` - value = np.array(value) # TODO replace with agnostic - if hasattr(value, "shape") and len(value.shape) > 1: - value = np.array(value).reshape(-1) - - sync(self._async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) - - def get_block_selection( - self, - selection: BasicSelection, - *, - out: NDBuffer | None = None, - fields: Fields | None = None, - prototype: BufferPrototype | None = None, - ) -> NDArrayLike: - """Retrieve a selection of individual items, by providing the indices - (coordinates) for each selected item. - - Parameters - ---------- - selection : int or slice or tuple of int or slice - An integer (coordinate) or slice for each dimension of the array. - out : NDBuffer, optional - If given, load the selected data directly into this buffer. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to - extract data for. - prototype : BufferPrototype, optional - The prototype of the buffer to use for the output data. If not provided, the default buffer prototype is used. - - Returns - ------- - NDArrayLike - An array-like containing the data for the requested block selection. - - Examples - -------- - Setup a 2-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> data = np.arange(0, 100, dtype="uint16").reshape((10, 10)) - >>> z = Array.create( - >>> StorePath(MemoryStore(mode="w")), - >>> shape=data.shape, - >>> chunk_shape=(3, 3), - >>> dtype=data.dtype, - >>> ) - >>> z[:] = data - - Retrieve items by specifying their block coordinates:: - - >>> z.get_block_selection((1, slice(None))) - array([[30, 31, 32, 33, 34, 35, 36, 37, 38, 39], - [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], - [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]) - - Which is equivalent to:: - - >>> z[3:6, :] - array([[30, 31, 32, 33, 34, 35, 36, 37, 38, 39], - [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], - [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]) - - For convenience, the block selection functionality is also available via the - `blocks` property, e.g.:: - - >>> z.blocks[1] - array([[30, 31, 32, 33, 34, 35, 36, 37, 38, 39], - [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], - [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]) - - Notes - ----- - Block indexing is a convenience indexing method to work on individual chunks - with chunk index slicing. It has the same concept as Dask's `Array.blocks` - indexing. - - Slices are supported. However, only with a step size of one. - - Block index arrays may be multidimensional to index multidimensional arrays. - For example:: - - >>> z.blocks[0, 1:3] - array([[ 3, 4, 5, 6, 7, 8], - [13, 14, 15, 16, 17, 18], - [23, 24, 25, 26, 27, 28]]) - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection, - set_coordinate_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - if prototype is None: - prototype = default_buffer_prototype() - indexer = BlockIndexer(selection, self.shape, self.metadata.chunk_grid) - return sync( - self._async_array._get_selection( - indexer=indexer, out=out, fields=fields, prototype=prototype - ) - ) - - def set_block_selection( - self, - selection: BasicSelection, - value: npt.ArrayLike, - *, - fields: Fields | None = None, - prototype: BufferPrototype | None = None, - ) -> None: - """Modify a selection of individual blocks, by providing the chunk indices - (coordinates) for each block to be modified. - - Parameters - ---------- - selection : tuple - An integer (coordinate) or slice for each dimension of the array. - value : npt.ArrayLike - An array-like containing the data to be stored in the block selection. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to set - data for. - prototype : BufferPrototype, optional - The prototype of the buffer used for setting the data. If not provided, the - default buffer prototype is used. - - Examples - -------- - Set up a 2-dimensional array:: - - >>> import zarr - >>> z = zarr.zeros( - >>> shape=(6, 6), - >>> store=StorePath(MemoryStore(mode="w")), - >>> chunk_shape=(2, 2), - >>> dtype="i4", - >>> ) - - Set data for a selection of items:: - - >>> z.set_block_selection((1, 0), 1) - >>> z[...] - array([[0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0]]) - - For convenience, this functionality is also available via the `blocks` property. - E.g.:: - - >>> z.blocks[2, 1] = 4 - >>> z[...] - array([[0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0], - [0, 0, 4, 4, 0, 0], - [0, 0, 4, 4, 0, 0]]) - - >>> z.blocks[:, 2] = 7 - >>> z[...] - array([[0, 0, 0, 0, 7, 7], - [0, 0, 0, 0, 7, 7], - [1, 1, 0, 0, 7, 7], - [1, 1, 0, 0, 7, 7], - [0, 0, 4, 4, 7, 7], - [0, 0, 4, 4, 7, 7]]) - - Notes - ----- - Block indexing is a convenience indexing method to work on individual chunks - with chunk index slicing. It has the same concept as Dask's `Array.blocks` - indexing. - - Slices are supported. However, only with a step size of one. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection, - get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - if prototype is None: - prototype = default_buffer_prototype() - indexer = BlockIndexer(selection, self.shape, self.metadata.chunk_grid) - sync(self._async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) - - @property - def vindex(self) -> VIndex: - """Shortcut for vectorized (inner) indexing, see :func:`get_coordinate_selection`, - :func:`set_coordinate_selection`, :func:`get_mask_selection` and - :func:`set_mask_selection` for documentation and examples.""" - return VIndex(self) - - @property - def oindex(self) -> OIndex: - """Shortcut for orthogonal (outer) indexing, see :func:`get_orthogonal_selection` and - :func:`set_orthogonal_selection` for documentation and examples.""" - return OIndex(self) - - @property - def blocks(self) -> BlockIndex: - """Shortcut for blocked chunked indexing, see :func:`get_block_selection` and - :func:`set_block_selection` for documentation and examples.""" - return BlockIndex(self) - - def resize(self, new_shape: ChunkCoords) -> Array: - """ - Change the shape of the array by growing or shrinking one or more - dimensions. - - This method does not modify the original Array object. Instead, it returns a new Array - with the specified shape. - - Examples - -------- - >>> import zarr - >>> z = zarr.zeros(shape=(10000, 10000), - >>> chunk_shape=(1000, 1000), - >>> store=StorePath(MemoryStore(mode="w")), - >>> dtype="i4",) - >>> z.shape - (10000, 10000) - >>> z = z.resize(20000, 1000) - >>> z.shape - (20000, 1000) - >>> z2 = z.resize(50, 50) - >>> z.shape - (20000, 1000) - >>> z2.shape - (50, 50) - - Notes - ----- - When resizing an array, the data are not rearranged in any way. - - If one or more dimensions are shrunk, any chunks falling outside the - new array shape will be deleted from the underlying store. - However, it is noteworthy that the chunks partially falling inside the new array - (i.e. boundary chunks) will remain intact, and therefore, - the data falling outside the new array but inside the boundary chunks - would be restored by a subsequent resize operation that grows the array size. - """ - return type(self)( - sync( - self._async_array.resize(new_shape), - ) - ) - - def update_attributes(self, new_attributes: dict[str, JSON]) -> Array: - return type(self)( - sync( - self._async_array.update_attributes(new_attributes), - ) - ) - - def __repr__(self) -> str: - return f"" - - def info(self) -> None: - return sync( - self._async_array.info(), - ) diff --git a/src/zarr/array_spec.py b/src/zarr/array_spec.py deleted file mode 100644 index d5717944b4..0000000000 --- a/src/zarr/array_spec.py +++ /dev/null @@ -1,41 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from typing import Any, Literal - -import numpy as np - -from zarr.buffer import BufferPrototype -from zarr.common import ChunkCoords, parse_dtype, parse_fill_value, parse_order, parse_shapelike - - -@dataclass(frozen=True) -class ArraySpec: - shape: ChunkCoords - dtype: np.dtype[Any] - fill_value: Any - order: Literal["C", "F"] - prototype: BufferPrototype - - def __init__( - self, - shape: ChunkCoords, - dtype: np.dtype[Any], - fill_value: Any, - order: Literal["C", "F"], - prototype: BufferPrototype, - ) -> None: - shape_parsed = parse_shapelike(shape) - dtype_parsed = parse_dtype(dtype) - fill_value_parsed = parse_fill_value(fill_value) - order_parsed = parse_order(order) - - object.__setattr__(self, "shape", shape_parsed) - object.__setattr__(self, "dtype", dtype_parsed) - object.__setattr__(self, "fill_value", fill_value_parsed) - object.__setattr__(self, "order", order_parsed) - object.__setattr__(self, "prototype", prototype) - - @property - def ndim(self) -> int: - return len(self.shape) diff --git a/src/zarr/attributes.py b/src/zarr/attributes.py deleted file mode 100644 index 079ae38a33..0000000000 --- a/src/zarr/attributes.py +++ /dev/null @@ -1,35 +0,0 @@ -from __future__ import annotations - -from collections.abc import Iterator, MutableMapping -from typing import TYPE_CHECKING - -from zarr.common import JSON - -if TYPE_CHECKING: - from zarr.array import Array - from zarr.group import Group - - -class Attributes(MutableMapping[str, JSON]): - def __init__(self, obj: Array | Group): - # key=".zattrs", read_only=False, cache=True, synchronizer=None - self._obj = obj - - def __getitem__(self, key: str) -> JSON: - return self._obj.metadata.attributes[key] - - def __setitem__(self, key: str, value: JSON) -> None: - new_attrs = dict(self._obj.metadata.attributes) - new_attrs[key] = value - self._obj = self._obj.update_attributes(new_attrs) - - def __delitem__(self, key: str) -> None: - new_attrs = dict(self._obj.metadata.attributes) - del new_attrs[key] - self._obj = self._obj.update_attributes(new_attrs) - - def __iter__(self) -> Iterator[str]: - return iter(self._obj.metadata.attributes) - - def __len__(self) -> int: - return len(self._obj.metadata.attributes) diff --git a/src/zarr/buffer.py b/src/zarr/buffer.py deleted file mode 100644 index 9c75ba1410..0000000000 --- a/src/zarr/buffer.py +++ /dev/null @@ -1,498 +0,0 @@ -from __future__ import annotations - -import sys -from collections.abc import Callable, Iterable, Sequence -from typing import ( - TYPE_CHECKING, - Any, - Literal, - NamedTuple, - Protocol, - SupportsIndex, - runtime_checkable, -) - -import numpy as np -import numpy.typing as npt - -from zarr.common import ChunkCoords -from zarr.registry import ( - get_buffer_class, - get_ndbuffer_class, - register_buffer, - register_ndbuffer, -) - -if TYPE_CHECKING: - from typing_extensions import Self - - from zarr.codecs.bytes import Endian - from zarr.common import BytesLike - - -@runtime_checkable -class ArrayLike(Protocol): - """Protocol for the array-like type that underlie Buffer""" - - @property - def dtype(self) -> np.dtype[Any]: ... - - @property - def ndim(self) -> int: ... - - @property - def size(self) -> int: ... - - def __getitem__(self, key: slice) -> Self: ... - - def __setitem__(self, key: slice, value: Any) -> None: ... - - -@runtime_checkable -class NDArrayLike(Protocol): - """Protocol for the nd-array-like type that underlie NDBuffer""" - - @property - def dtype(self) -> np.dtype[Any]: ... - - @property - def ndim(self) -> int: ... - - @property - def size(self) -> int: ... - - @property - def shape(self) -> ChunkCoords: ... - - def __len__(self) -> int: ... - - def __getitem__(self, key: slice) -> Self: ... - - def __setitem__(self, key: slice, value: Any) -> None: ... - - def __array__(self) -> npt.NDArray[Any]: ... - - def reshape( - self, shape: ChunkCoords | Literal[-1], *, order: Literal["A", "C", "F"] = ... - ) -> Self: ... - - def view(self, dtype: npt.DTypeLike) -> Self: ... - - def astype(self, dtype: npt.DTypeLike, order: Literal["K", "A", "C", "F"] = ...) -> Self: ... - - def fill(self, value: Any) -> None: ... - - def copy(self) -> Self: ... - - def transpose(self, axes: SupportsIndex | Sequence[SupportsIndex] | None) -> Self: ... - - def ravel(self, order: Literal["K", "A", "C", "F"] = ...) -> Self: ... - - def all(self) -> bool: ... - - def __eq__(self, other: Any) -> Self: # type: ignore[explicit-override, override] - """Element-wise equal - - Notes - ----- - Type checkers such as mypy complains because the return type isn't a bool like - its supertype "object", which violates the Liskov substitution principle. - This is true, but since NumPy's ndarray is defined as an element-wise equal, - our hands are tied. - """ - - -def check_item_key_is_1d_contiguous(key: Any) -> None: - """Raises error if `key` isn't a 1d contiguous slice""" - if not isinstance(key, slice): - raise TypeError( - f"Item key has incorrect type (expected slice, got {key.__class__.__name__})" - ) - if not (key.step is None or key.step == 1): - raise ValueError("slice must be contiguous") - - -class Buffer: - """A flat contiguous memory block - - We use Buffer throughout Zarr to represent a contiguous block of memory. - - A Buffer is backed by a underlying array-like instance that represents - the memory. The memory type is unspecified; can be regular host memory, - CUDA device memory, or something else. The only requirement is that the - array-like instance can be copied/converted to a regular Numpy array - (host memory). - - Notes - ----- - This buffer is untyped, so all indexing and sizes are in bytes. - - Parameters - ---------- - array_like - array-like object that must be 1-dim, contiguous, and byte dtype. - """ - - def __init__(self, array_like: ArrayLike): - if array_like.ndim != 1: - raise ValueError("array_like: only 1-dim allowed") - if array_like.dtype != np.dtype("b"): - raise ValueError("array_like: only byte dtype allowed") - self._data = array_like - - @classmethod - def create_zero_length(cls) -> Self: - """Create an empty buffer with length zero - - Returns - ------- - New empty 0-length buffer - """ - return cls(np.array([], dtype="b")) - - @classmethod - def from_array_like(cls, array_like: ArrayLike) -> Self: - """Create a new buffer of an array-like object - - Parameters - ---------- - array_like - array-like object that must be 1-dim, contiguous, and byte dtype. - - Returns - ------- - New buffer representing `array_like` - """ - return cls(array_like) - - @classmethod - def from_buffer(cls, buffer: Buffer) -> Self: - """Create a new buffer of an existing Buffer - - This is useful if you want to ensure that an existing buffer is - of the correct subclass of Buffer. E.g., MemoryStore uses this - to return a buffer instance of the subclass specified by its - BufferPrototype argument. - - Typically, this only copies data if the data has to be moved between - memory types, such as from host to device memory. - - Parameters - ---------- - buffer - buffer object. - - Returns - ------- - A new buffer representing the content of the input buffer - """ - return cls.from_array_like(buffer.as_array_like()) - - @classmethod - def from_bytes(cls, bytes_like: BytesLike) -> Self: - """Create a new buffer of a bytes-like object (host memory) - - Parameters - ---------- - bytes_like - bytes-like object - - Returns - ------- - New buffer representing `bytes_like` - """ - return cls.from_array_like(np.frombuffer(bytes_like, dtype="b")) - - def as_array_like(self) -> ArrayLike: - """Returns the underlying array (host or device memory) of this buffer - - This will never copy data. - - Returns - ------- - The underlying 1d array such as a NumPy or CuPy array. - """ - return self._data - - def as_numpy_array(self) -> npt.NDArray[Any]: - """Returns the buffer as a NumPy array (host memory). - - Notes - ----- - Might have to copy data, consider using `.as_array_like()` instead. - - Returns - ------- - NumPy array of this buffer (might be a data copy) - """ - return np.asanyarray(self._data) - - def to_bytes(self) -> bytes: - """Returns the buffer as `bytes` (host memory). - - Warnings - -------- - Will always copy data, only use this method for small buffers such as metadata - buffers. If possible, use `.as_numpy_array()` or `.as_array_like()` instead. - - Returns - ------- - `bytes` of this buffer (data copy) - """ - return bytes(self.as_numpy_array()) - - def __getitem__(self, key: slice) -> Self: - check_item_key_is_1d_contiguous(key) - return self.__class__(self._data.__getitem__(key)) - - def __setitem__(self, key: slice, value: Any) -> None: - check_item_key_is_1d_contiguous(key) - self._data.__setitem__(key, value) - - def __len__(self) -> int: - return self._data.size - - def __add__(self, other: Buffer) -> Self: - """Concatenate two buffers""" - - other_array = other.as_array_like() - assert other_array.dtype == np.dtype("b") - return self.__class__( - np.concatenate((np.asanyarray(self._data), np.asanyarray(other_array))) - ) - - -class NDBuffer: - """An n-dimensional memory block - - We use NDBuffer throughout Zarr to represent a n-dimensional memory block. - - A NDBuffer is backed by a underlying ndarray-like instance that represents - the memory. The memory type is unspecified; can be regular host memory, - CUDA device memory, or something else. The only requirement is that the - ndarray-like instance can be copied/converted to a regular Numpy array - (host memory). - - Notes - ----- - The two buffer classes Buffer and NDBuffer are very similar. In fact, Buffer - is a special case of NDBuffer where dim=1, stride=1, and dtype="b". However, - in order to use Python's type system to differentiate between the contiguous - Buffer and the n-dim (non-contiguous) NDBuffer, we keep the definition of the - two classes separate. - - Parameters - ---------- - ndarray_like - ndarray-like object that is convertible to a regular Numpy array. - """ - - def __init__(self, array: NDArrayLike): - # assert array.ndim > 0 - assert array.dtype != object - self._data = array - - @classmethod - def create( - cls, - *, - shape: Iterable[int], - dtype: npt.DTypeLike, - order: Literal["C", "F"] = "C", - fill_value: Any | None = None, - ) -> Self: - """Create a new buffer and its underlying ndarray-like object - - Parameters - ---------- - shape - The shape of the buffer and its underlying ndarray-like object - dtype - The datatype of the buffer and its underlying ndarray-like object - order - Whether to store multi-dimensional data in row-major (C-style) or - column-major (Fortran-style) order in memory. - fill_value - If not None, fill the new buffer with a scalar value. - - Returns - ------- - New buffer representing a new ndarray_like object - - Notes - ----- - A subclass can overwrite this method to create a ndarray-like object - other then the default Numpy array. - """ - ret = cls(np.empty(shape=tuple(shape), dtype=dtype, order=order)) - if fill_value is not None: - ret.fill(fill_value) - return ret - - @classmethod - def from_ndarray_like(cls, ndarray_like: NDArrayLike) -> Self: - """Create a new buffer of a ndarray-like object - - Parameters - ---------- - ndarray_like - ndarray-like object - - Returns - ------- - New buffer representing `ndarray_like` - """ - return cls(ndarray_like) - - @classmethod - def from_numpy_array(cls, array_like: npt.ArrayLike) -> Self: - """Create a new buffer of Numpy array-like object - - Parameters - ---------- - array_like - Object that can be coerced into a Numpy array - - Returns - ------- - New buffer representing `array_like` - """ - return cls.from_ndarray_like(np.asanyarray(array_like)) - - def as_ndarray_like(self) -> NDArrayLike: - """Returns the underlying array (host or device memory) of this buffer - - This will never copy data. - - Returns - ------- - The underlying array such as a NumPy or CuPy array. - """ - return self._data - - def as_numpy_array(self) -> npt.NDArray[Any]: - """Returns the buffer as a NumPy array (host memory). - - Warnings - -------- - Might have to copy data, consider using `.as_ndarray_like()` instead. - - Returns - ------- - NumPy array of this buffer (might be a data copy) - """ - return np.asanyarray(self._data) - - @property - def dtype(self) -> np.dtype[Any]: - return self._data.dtype - - @property - def shape(self) -> tuple[int, ...]: - return self._data.shape - - @property - def byteorder(self) -> Endian: - from zarr.codecs.bytes import Endian - - if self.dtype.byteorder == "<": - return Endian.little - elif self.dtype.byteorder == ">": - return Endian.big - else: - return Endian(sys.byteorder) - - def reshape(self, newshape: ChunkCoords | Literal[-1]) -> Self: - return self.__class__(self._data.reshape(newshape)) - - def squeeze(self, axis: tuple[int, ...]) -> Self: - newshape = tuple(a for i, a in enumerate(self.shape) if i not in axis) - return self.__class__(self._data.reshape(newshape)) - - def astype(self, dtype: npt.DTypeLike, order: Literal["K", "A", "C", "F"] = "K") -> Self: - return self.__class__(self._data.astype(dtype=dtype, order=order)) - - def __getitem__(self, key: Any) -> Self: - return self.__class__(np.asanyarray(self._data.__getitem__(key))) - - def __setitem__(self, key: Any, value: Any) -> None: - if isinstance(value, NDBuffer): - value = value._data - self._data.__setitem__(key, value) - - def __len__(self) -> int: - return self._data.__len__() - - def __repr__(self) -> str: - return f"" - - def all_equal(self, other: Any) -> bool: - return bool((self._data == other).all()) - - def fill(self, value: Any) -> None: - self._data.fill(value) - - def copy(self) -> Self: - return self.__class__(self._data.copy()) - - def transpose(self, axes: SupportsIndex | Sequence[SupportsIndex] | None) -> Self: - return self.__class__(self._data.transpose(axes)) - - -def as_numpy_array_wrapper( - func: Callable[[npt.NDArray[Any]], bytes], buf: Buffer, prototype: BufferPrototype -) -> Buffer: - """Converts the input of `func` to a numpy array and the output back to `Buffer`. - - This function is useful when calling a `func` that only support host memory such - as `GZip.decode` and `Blosc.decode`. In this case, use this wrapper to convert - the input `buf` to a Numpy array and convert the result back into a `Buffer`. - - Parameters - ---------- - func - The callable that will be called with the converted `buf` as input. - `func` must return bytes, which will be converted into a `Buffer` - before returned. - buf - The buffer that will be converted to a Numpy array before given as - input to `func`. - prototype - The prototype of the output buffer. - - Returns - ------- - The result of `func` converted to a `Buffer` - """ - return prototype.buffer.from_bytes(func(buf.as_numpy_array())) - - -class BufferPrototype(NamedTuple): - """Prototype of the Buffer and NDBuffer class - - The protocol must be pickable. - - Attributes - ---------- - buffer - The Buffer class to use when Zarr needs to create new Buffer. - nd_buffer - The NDBuffer class to use when Zarr needs to create new NDBuffer. - """ - - buffer: type[Buffer] - nd_buffer: type[NDBuffer] - - -# The default buffer prototype used throughout the Zarr codebase. -def default_buffer_prototype() -> BufferPrototype: - return BufferPrototype(buffer=get_buffer_class(), nd_buffer=get_ndbuffer_class()) - - -# The numpy prototype used for E.g. when reading the shard index -def numpy_buffer_prototype() -> BufferPrototype: - return BufferPrototype(buffer=Buffer, nd_buffer=NDBuffer) - - -register_buffer(Buffer) -register_ndbuffer(NDBuffer) diff --git a/src/zarr/buffer/__init__.py b/src/zarr/buffer/__init__.py new file mode 100644 index 0000000000..db393f66c7 --- /dev/null +++ b/src/zarr/buffer/__init__.py @@ -0,0 +1,12 @@ +""" +Implementations of the Zarr Buffer interface. + +See Also +======== +zarr.abc.buffer: Abstract base class for the Zarr Buffer interface. +""" + +from zarr.buffer import cpu, gpu +from zarr.core.buffer import default_buffer_prototype + +__all__ = ["cpu", "default_buffer_prototype", "gpu"] diff --git a/src/zarr/buffer/cpu.py b/src/zarr/buffer/cpu.py new file mode 100644 index 0000000000..5307927c06 --- /dev/null +++ b/src/zarr/buffer/cpu.py @@ -0,0 +1,15 @@ +from zarr.core.buffer.cpu import ( + Buffer, + NDBuffer, + as_numpy_array_wrapper, + buffer_prototype, + numpy_buffer_prototype, +) + +__all__ = [ + "Buffer", + "NDBuffer", + "as_numpy_array_wrapper", + "buffer_prototype", + "numpy_buffer_prototype", +] diff --git a/src/zarr/buffer/gpu.py b/src/zarr/buffer/gpu.py new file mode 100644 index 0000000000..dbdc1b1357 --- /dev/null +++ b/src/zarr/buffer/gpu.py @@ -0,0 +1,7 @@ +from zarr.core.buffer.gpu import Buffer, NDBuffer, buffer_prototype + +__all__ = [ + "Buffer", + "NDBuffer", + "buffer_prototype", +] diff --git a/src/zarr/chunk_grids.py b/src/zarr/chunk_grids.py deleted file mode 100644 index b494a3e5e8..0000000000 --- a/src/zarr/chunk_grids.py +++ /dev/null @@ -1,146 +0,0 @@ -from __future__ import annotations - -import itertools -import math -import operator -from abc import abstractmethod -from collections.abc import Iterator -from dataclasses import dataclass -from functools import reduce -from typing import TYPE_CHECKING - -import numpy as np - -from zarr.abc.metadata import Metadata -from zarr.common import ( - JSON, - ChunkCoords, - ChunkCoordsLike, - parse_named_configuration, - parse_shapelike, -) -from zarr.indexing import ceildiv - -if TYPE_CHECKING: - from typing_extensions import Self - - -def _guess_chunks( - shape: ChunkCoords, - typesize: int, - *, - increment_bytes: int = 256 * 1024, - min_bytes: int = 128 * 1024, - max_bytes: int = 64 * 1024 * 1024, -) -> ChunkCoords: - """ - Iteratively guess an appropriate chunk layout for an array, given its shape and - the size of each element in bytes, and size constraints expressed in bytes. This logic is - adapted from h5py. - - Parameters - ---------- - shape: ChunkCoords - The chunk shape. - typesize: int - The size, in bytes, of each element of the chunk. - increment_bytes: int = 256 * 1024 - The number of bytes used to increment or decrement the target chunk size in bytes. - min_bytes: int = 128 * 1024 - The soft lower bound on the final chunk size in bytes. - max_bytes: int = 64 * 1024 * 1024 - The hard upper bound on the final chunk size in bytes. - - Returns - ------- - ChunkCoords - - """ - - ndims = len(shape) - # require chunks to have non-zero length for all dimensions - chunks = np.maximum(np.array(shape, dtype="=f8"), 1) - - # Determine the optimal chunk size in bytes using a PyTables expression. - # This is kept as a float. - dset_size = np.prod(chunks) * typesize - target_size = increment_bytes * (2 ** np.log10(dset_size / (1024.0 * 1024))) - - if target_size > max_bytes: - target_size = max_bytes - elif target_size < min_bytes: - target_size = min_bytes - - idx = 0 - while True: - # Repeatedly loop over the axes, dividing them by 2. Stop when: - # 1a. We're smaller than the target chunk size, OR - # 1b. We're within 50% of the target chunk size, AND - # 2. The chunk is smaller than the maximum chunk size - - chunk_bytes = np.prod(chunks) * typesize - - if ( - chunk_bytes < target_size or abs(chunk_bytes - target_size) / target_size < 0.5 - ) and chunk_bytes < max_bytes: - break - - if np.prod(chunks) == 1: - break # Element size larger than max_bytes - - chunks[idx % ndims] = math.ceil(chunks[idx % ndims] / 2.0) - idx += 1 - - return tuple(int(x) for x in chunks) - - -@dataclass(frozen=True) -class ChunkGrid(Metadata): - @classmethod - def from_dict(cls, data: dict[str, JSON] | ChunkGrid) -> ChunkGrid: - if isinstance(data, ChunkGrid): - return data - - name_parsed, _ = parse_named_configuration(data) - if name_parsed == "regular": - return RegularChunkGrid._from_dict(data) - raise ValueError(f"Unknown chunk grid. Got {name_parsed}.") - - @abstractmethod - def all_chunk_coords(self, array_shape: ChunkCoords) -> Iterator[ChunkCoords]: - pass - - @abstractmethod - def get_nchunks(self, array_shape: ChunkCoords) -> int: - pass - - -@dataclass(frozen=True) -class RegularChunkGrid(ChunkGrid): - chunk_shape: ChunkCoords - - def __init__(self, *, chunk_shape: ChunkCoordsLike) -> None: - chunk_shape_parsed = parse_shapelike(chunk_shape) - - object.__setattr__(self, "chunk_shape", chunk_shape_parsed) - - @classmethod - def _from_dict(cls, data: dict[str, JSON]) -> Self: - _, configuration_parsed = parse_named_configuration(data, "regular") - - return cls(**configuration_parsed) # type: ignore[arg-type] - - def to_dict(self) -> dict[str, JSON]: - return {"name": "regular", "configuration": {"chunk_shape": tuple(self.chunk_shape)}} - - def all_chunk_coords(self, array_shape: ChunkCoords) -> Iterator[ChunkCoords]: - return itertools.product( - *(range(0, ceildiv(s, c)) for s, c in zip(array_shape, self.chunk_shape, strict=False)) - ) - - def get_nchunks(self, array_shape: ChunkCoords) -> int: - return reduce( - operator.mul, - (ceildiv(s, c) for s, c in zip(array_shape, self.chunk_shape, strict=True)), - 1, - ) diff --git a/src/zarr/chunk_key_encodings.py b/src/zarr/chunk_key_encodings.py deleted file mode 100644 index 30db8ff5a8..0000000000 --- a/src/zarr/chunk_key_encodings.py +++ /dev/null @@ -1,90 +0,0 @@ -from __future__ import annotations - -from abc import abstractmethod -from dataclasses import dataclass -from typing import TYPE_CHECKING, Literal, cast - -from zarr.abc.metadata import Metadata -from zarr.common import ( - JSON, - ChunkCoords, - parse_named_configuration, -) - -if TYPE_CHECKING: - pass - -SeparatorLiteral = Literal[".", "/"] - - -def parse_separator(data: JSON) -> SeparatorLiteral: - if data not in (".", "/"): - raise ValueError(f"Expected an '.' or '/' separator. Got {data} instead.") - return cast(SeparatorLiteral, data) - - -@dataclass(frozen=True) -class ChunkKeyEncoding(Metadata): - name: str - separator: SeparatorLiteral = "." - - def __init__(self, *, separator: SeparatorLiteral) -> None: - separator_parsed = parse_separator(separator) - - object.__setattr__(self, "separator", separator_parsed) - - @classmethod - def from_dict(cls, data: dict[str, JSON] | ChunkKeyEncoding) -> ChunkKeyEncoding: - if isinstance(data, ChunkKeyEncoding): - return data - - # configuration is optional for chunk key encodings - name_parsed, config_parsed = parse_named_configuration(data, require_configuration=False) - if name_parsed == "default": - if config_parsed is None: - # for default, normalize missing configuration to use the "/" separator. - config_parsed = {"separator": "/"} - return DefaultChunkKeyEncoding(**config_parsed) # type: ignore[arg-type] - if name_parsed == "v2": - if config_parsed is None: - # for v2, normalize missing configuration to use the "." separator. - config_parsed = {"separator": "."} - return V2ChunkKeyEncoding(**config_parsed) # type: ignore[arg-type] - msg = f"Unknown chunk key encoding. Got {name_parsed}, expected one of ('v2', 'default')." - raise ValueError(msg) - - def to_dict(self) -> dict[str, JSON]: - return {"name": self.name, "configuration": {"separator": self.separator}} - - @abstractmethod - def decode_chunk_key(self, chunk_key: str) -> ChunkCoords: - pass - - @abstractmethod - def encode_chunk_key(self, chunk_coords: ChunkCoords) -> str: - pass - - -@dataclass(frozen=True) -class DefaultChunkKeyEncoding(ChunkKeyEncoding): - name: Literal["default"] = "default" - - def decode_chunk_key(self, chunk_key: str) -> ChunkCoords: - if chunk_key == "c": - return () - return tuple(map(int, chunk_key[1:].split(self.separator))) - - def encode_chunk_key(self, chunk_coords: ChunkCoords) -> str: - return self.separator.join(map(str, ("c",) + chunk_coords)) - - -@dataclass(frozen=True) -class V2ChunkKeyEncoding(ChunkKeyEncoding): - name: Literal["v2"] = "v2" - - def decode_chunk_key(self, chunk_key: str) -> ChunkCoords: - return tuple(map(int, chunk_key.split(self.separator))) - - def encode_chunk_key(self, chunk_coords: ChunkCoords) -> str: - chunk_identifier = self.separator.join(map(str, chunk_coords)) - return "0" if chunk_identifier == "" else chunk_identifier diff --git a/src/zarr/codecs/__init__.py b/src/zarr/codecs/__init__.py index 9394284319..9a1b47b351 100644 --- a/src/zarr/codecs/__init__.py +++ b/src/zarr/codecs/__init__.py @@ -2,24 +2,99 @@ from zarr.codecs.blosc import BloscCname, BloscCodec, BloscShuffle from zarr.codecs.bytes import BytesCodec, Endian +from zarr.codecs.cast_value import CastValue from zarr.codecs.crc32c_ import Crc32cCodec from zarr.codecs.gzip import GzipCodec -from zarr.codecs.pipeline import BatchedCodecPipeline -from zarr.codecs.sharding import ShardingCodec, ShardingCodecIndexLocation +from zarr.codecs.numcodecs import ( + BZ2, + CRC32, + CRC32C, + LZ4, + LZMA, + ZFPY, + Adler32, + AsType, + BitRound, + Blosc, + Delta, + FixedScaleOffset, + Fletcher32, + GZip, + JenkinsLookup3, + PackBits, + PCodec, + Quantize, + Shuffle, + Zlib, + Zstd, +) +from zarr.codecs.scale_offset import ScaleOffset +from zarr.codecs.sharding import ShardingCodec, ShardingCodecIndexLocation, SubchunkWriteOrder from zarr.codecs.transpose import TransposeCodec +from zarr.codecs.vlen_utf8 import VLenBytesCodec, VLenUTF8Codec from zarr.codecs.zstd import ZstdCodec +from zarr.registry import register_codec __all__ = [ - "BatchedCodecPipeline", "BloscCname", "BloscCodec", "BloscShuffle", "BytesCodec", + "CastValue", "Crc32cCodec", "Endian", "GzipCodec", + "ScaleOffset", "ShardingCodec", "ShardingCodecIndexLocation", + "SubchunkWriteOrder", "TransposeCodec", + "VLenBytesCodec", + "VLenUTF8Codec", "ZstdCodec", ] + +register_codec("blosc", BloscCodec) +register_codec("cast_value", CastValue) +register_codec("bytes", BytesCodec) + +# compatibility with earlier versions of ZEP1 +register_codec("endian", BytesCodec) +register_codec("crc32c", Crc32cCodec) +register_codec("gzip", GzipCodec) +register_codec("scale_offset", ScaleOffset) +register_codec("sharding_indexed", ShardingCodec) +register_codec("zstd", ZstdCodec) +register_codec("vlen-utf8", VLenUTF8Codec) +register_codec("vlen-bytes", VLenBytesCodec) +register_codec("transpose", TransposeCodec) + +# Register all the codecs formerly contained in numcodecs.zarr3 + +register_codec("numcodecs.bz2", BZ2, qualname="zarr.codecs.numcodecs.BZ2") +register_codec("numcodecs.crc32", CRC32, qualname="zarr.codecs.numcodecs.CRC32") +register_codec("numcodecs.crc32c", CRC32C, qualname="zarr.codecs.numcodecs.CRC32C") +register_codec("numcodecs.lz4", LZ4, qualname="zarr.codecs.numcodecs.LZ4") +register_codec("numcodecs.lzma", LZMA, qualname="zarr.codecs.numcodecs.LZMA") +register_codec("numcodecs.zfpy", ZFPY, qualname="zarr.codecs.numcodecs.ZFPY") +register_codec("numcodecs.adler32", Adler32, qualname="zarr.codecs.numcodecs.Adler32") +register_codec("numcodecs.astype", AsType, qualname="zarr.codecs.numcodecs.AsType") +register_codec("numcodecs.bitround", BitRound, qualname="zarr.codecs.numcodecs.BitRound") +register_codec("numcodecs.blosc", Blosc, qualname="zarr.codecs.numcodecs.Blosc") +register_codec("numcodecs.delta", Delta, qualname="zarr.codecs.numcodecs.Delta") +register_codec( + "numcodecs.fixedscaleoffset", + FixedScaleOffset, + qualname="zarr.codecs.numcodecs.FixedScaleOffset", +) +register_codec("numcodecs.fletcher32", Fletcher32, qualname="zarr.codecs.numcodecs.Fletcher32") +register_codec("numcodecs.gzip", GZip, qualname="zarr.codecs.numcodecs.GZip") +register_codec( + "numcodecs.jenkins_lookup3", JenkinsLookup3, qualname="zarr.codecs.numcodecs.JenkinsLookup3" +) +register_codec("numcodecs.pcodec", PCodec, qualname="zarr.codecs.numcodecs.PCodec") +register_codec("numcodecs.packbits", PackBits, qualname="zarr.codecs.numcodecs.PackBits") +register_codec("numcodecs.quantize", Quantize, qualname="zarr.codecs.numcodecs.Quantize") +register_codec("numcodecs.shuffle", Shuffle, qualname="zarr.codecs.numcodecs.Shuffle") +register_codec("numcodecs.zlib", Zlib, qualname="zarr.codecs.numcodecs.Zlib") +register_codec("numcodecs.zstd", Zstd, qualname="zarr.codecs.numcodecs.Zstd") diff --git a/src/zarr/codecs/_deprecated_enum.py b/src/zarr/codecs/_deprecated_enum.py new file mode 100644 index 0000000000..5538ae26f6 --- /dev/null +++ b/src/zarr/codecs/_deprecated_enum.py @@ -0,0 +1,59 @@ +"""Helpers for deprecating string-valued enums in favor of literal strings. + +See PR #3963 for context on the deprecation pattern. +""" + +from __future__ import annotations + +import warnings +from enum import Enum + + +class _DeprecatedStrEnumMeta(type): + """ + Metaclass for legacy enum-like classes. Accessing a member name on the + class (e.g. `LegacyShim.foo`) emits a `DeprecationWarning` and returns + the equivalent string. Members are declared by setting a `_members` + class attribute mapping each member name to its string value. + """ + + _members: dict[str, str] + + def __getattr__(cls, name: str) -> str: + members: dict[str, str] = type.__getattribute__(cls, "_members") + if name in members: + warnings.warn( + f"{cls.__name__}.{name} is deprecated; pass the string {members[name]!r} instead.", + DeprecationWarning, + stacklevel=2, + ) + return members[name] + raise AttributeError(name) + + +def _coerce_enum_input(value: object, param_name: str, codec_name: str) -> object: + """ + If `value` is a real `enum.Enum` instance, emit a deprecation warning + naming `codec_name` and return `value.value`. Otherwise return `value` + unchanged. The third argument lets the warning text name the actual + codec (e.g. `BloscCodec`, `BytesCodec`, `ShardingCodec`). + + Note that zarr's own legacy classes (e.g. `ShardingCodecIndexLocation`) + never reach the `Enum` branch here: they no longer inherit from `Enum`, + and member access on them already returns a plain string (with its own + warning) via `_DeprecatedStrEnumMeta`. This branch exists for enum + instances defined *outside* zarr β€” in particular `str`-mixin enums that + downstream code defined to mirror zarr's old enums, which the old + `parse_enum`-based codepath accepted because they are `str` instances. + Coercing them to `value.value` keeps the stored attribute a plain string + and gives those callers a migration warning. + """ + if isinstance(value, Enum): + warnings.warn( + f"Passing an enum to {codec_name}(..., {param_name}=...) is deprecated; " + "pass the equivalent literal string instead.", + DeprecationWarning, + stacklevel=3, + ) + return value.value + return value diff --git a/src/zarr/codecs/_v2.py b/src/zarr/codecs/_v2.py index 60854bee34..7fdf408d1d 100644 --- a/src/zarr/codecs/_v2.py +++ b/src/zarr/codecs/_v2.py @@ -1,106 +1,114 @@ from __future__ import annotations +import asyncio from dataclasses import dataclass +from typing import TYPE_CHECKING -import numcodecs -from numcodecs.compat import ensure_bytes, ensure_ndarray +import numpy as np +from numcodecs.compat import ensure_bytes, ensure_ndarray_like -from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec -from zarr.array_spec import ArraySpec -from zarr.buffer import Buffer, NDBuffer, default_buffer_prototype -from zarr.common import JSON, to_thread +from zarr.abc.codec import ArrayBytesCodec from zarr.registry import get_ndbuffer_class +if TYPE_CHECKING: + from zarr.abc.numcodec import Numcodec + from zarr.core.array_spec import ArraySpec + from zarr.core.buffer import Buffer, NDBuffer + @dataclass(frozen=True) -class V2Compressor(ArrayBytesCodec): - compressor: dict[str, JSON] | None +class V2Codec(ArrayBytesCodec): + filters: tuple[Numcodec, ...] | None + compressor: Numcodec | None is_fixed_size = False - async def _decode_single( + def _decode_sync( self, chunk_bytes: Buffer, chunk_spec: ArraySpec, ) -> NDBuffer: - if self.compressor is not None: - compressor = numcodecs.get_codec(self.compressor) - chunk_numpy_array = ensure_ndarray( - await to_thread(compressor.decode, chunk_bytes.as_array_like()) - ) + cdata = chunk_bytes.as_array_like() + # decompress + if self.compressor: + chunk = self.compressor.decode(cdata) else: - chunk_numpy_array = ensure_ndarray(chunk_bytes.as_array_like()) + chunk = cdata + + # apply filters + if self.filters: + for f in reversed(self.filters): + chunk = f.decode(chunk) + + # view as numpy array with correct dtype + chunk = ensure_ndarray_like(chunk) + # special case object dtype, because incorrect handling can lead to + # segfaults and other bad things happening + if chunk_spec.dtype.dtype_cls is not np.dtypes.ObjectDType: + try: + chunk = chunk.view(chunk_spec.dtype.to_native_dtype()) + except TypeError: + # this will happen if the dtype of the chunk + # does not match the dtype of the array spec i.g. if + # the dtype of the chunk_spec is a string dtype, but the chunk + # is an object array. In this case, we need to convert the object + # array to the correct dtype. + + chunk = np.array(chunk).astype(chunk_spec.dtype.to_native_dtype()) + + elif chunk.dtype != object: + # If we end up here, someone must have hacked around with the filters. + # We cannot deal with object arrays unless there is an object + # codec in the filter chain, i.e., a filter that converts from object + # array to something else during encoding, and converts back to object + # array during decoding. + raise RuntimeError("cannot read object array without object codec") - # ensure correct dtype - if str(chunk_numpy_array.dtype) != chunk_spec.dtype: - chunk_numpy_array = chunk_numpy_array.view(chunk_spec.dtype) + # ensure correct chunk shape + chunk = chunk.reshape(-1, order="A") + chunk = chunk.reshape(chunk_spec.shape, order=chunk_spec.order) - return get_ndbuffer_class().from_numpy_array(chunk_numpy_array) + return get_ndbuffer_class().from_ndarray_like(chunk) - async def _encode_single( + def _encode_sync( self, chunk_array: NDBuffer, - _chunk_spec: ArraySpec, + chunk_spec: ArraySpec, ) -> Buffer | None: - chunk_numpy_array = chunk_array.as_numpy_array() - if self.compressor is not None: - compressor = numcodecs.get_codec(self.compressor) - if ( - not chunk_numpy_array.flags.c_contiguous - and not chunk_numpy_array.flags.f_contiguous - ): - chunk_numpy_array = chunk_numpy_array.copy(order="A") - encoded_chunk_bytes = ensure_bytes( - await to_thread(compressor.encode, chunk_numpy_array) - ) + chunk = chunk_array.as_ndarray_like() + + # ensure contiguous and correct order + chunk = chunk.astype(chunk_spec.dtype.to_native_dtype(), order=chunk_spec.order, copy=False) + + # apply filters + if self.filters: + for f in self.filters: + chunk = f.encode(chunk) + # check object encoding + if ensure_ndarray_like(chunk).dtype == object: + raise RuntimeError("cannot write object array without object codec") + + # compress + if self.compressor: + cdata = self.compressor.encode(chunk) else: - encoded_chunk_bytes = ensure_bytes(chunk_numpy_array) - - return default_buffer_prototype().buffer.from_bytes(encoded_chunk_bytes) - - def compute_encoded_size(self, _input_byte_length: int, _chunk_spec: ArraySpec) -> int: - raise NotImplementedError - - -@dataclass(frozen=True) -class V2Filters(ArrayArrayCodec): - filters: list[dict[str, JSON]] - - is_fixed_size = False + cdata = chunk + cdata = ensure_bytes(cdata) + return chunk_spec.prototype.buffer.from_bytes(cdata) async def _decode_single( self, - chunk_array: NDBuffer, + chunk_bytes: Buffer, chunk_spec: ArraySpec, ) -> NDBuffer: - chunk_ndarray = chunk_array.as_ndarray_like() - # apply filters in reverse order - if self.filters is not None: - for filter_metadata in self.filters[::-1]: - filter = numcodecs.get_codec(filter_metadata) - chunk_ndarray = await to_thread(filter.decode, chunk_ndarray) - - # ensure correct chunk shape - if chunk_ndarray.shape != chunk_spec.shape: - chunk_ndarray = chunk_ndarray.reshape( - chunk_spec.shape, - order=chunk_spec.order, - ) - - return get_ndbuffer_class().from_ndarray_like(chunk_ndarray) + return await asyncio.to_thread(self._decode_sync, chunk_bytes, chunk_spec) async def _encode_single( self, chunk_array: NDBuffer, chunk_spec: ArraySpec, - ) -> NDBuffer | None: - chunk_ndarray = chunk_array.as_ndarray_like().ravel(order=chunk_spec.order) - - for filter_metadata in self.filters: - filter = numcodecs.get_codec(filter_metadata) - chunk_ndarray = await to_thread(filter.encode, chunk_ndarray) - - return get_ndbuffer_class().from_ndarray_like(chunk_ndarray) + ) -> Buffer | None: + return await asyncio.to_thread(self._encode_sync, chunk_array, chunk_spec) def compute_encoded_size(self, _input_byte_length: int, _chunk_spec: ArraySpec) -> int: raise NotImplementedError diff --git a/src/zarr/codecs/blosc.py b/src/zarr/codecs/blosc.py index d03ecbcbf2..ee45632153 100644 --- a/src/zarr/codecs/blosc.py +++ b/src/zarr/codecs/blosc.py @@ -1,100 +1,257 @@ from __future__ import annotations -from dataclasses import dataclass, replace -from enum import Enum +import asyncio +from dataclasses import dataclass, field, replace from functools import cached_property -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, ClassVar, Final, Literal, NotRequired, TypedDict import numcodecs from numcodecs.blosc import Blosc +from packaging.version import Version from zarr.abc.codec import BytesBytesCodec -from zarr.array_spec import ArraySpec -from zarr.buffer import Buffer, as_numpy_array_wrapper -from zarr.common import JSON, parse_enum, parse_named_configuration, to_thread -from zarr.registry import register_codec +from zarr.codecs._deprecated_enum import _coerce_enum_input, _DeprecatedStrEnumMeta +from zarr.core.buffer.cpu import as_numpy_array_wrapper +from zarr.core.common import JSON, NamedRequiredConfig, parse_named_configuration +from zarr.core.dtype.common import HasItemSize +from zarr.core.json_parse import parse_field if TYPE_CHECKING: - from typing_extensions import Self + from typing import Self + from zarr.core.array_spec import ArraySpec + from zarr.core.buffer import Buffer -class BloscShuffle(Enum): - noshuffle = "noshuffle" - shuffle = "shuffle" - bitshuffle = "bitshuffle" +BloscShuffleLiteral = Literal["noshuffle", "shuffle", "bitshuffle"] +"""The shuffle values permitted for the blosc codec""" - @classmethod - def from_int(cls, num: int) -> BloscShuffle: - blosc_shuffle_int_to_str = { +BLOSC_SHUFFLE: Final = ("noshuffle", "shuffle", "bitshuffle") + +BloscCnameLiteral = Literal["lz4", "lz4hc", "blosclz", "snappy", "zlib", "zstd"] +"""The codec identifiers used in the blosc codec""" + +BLOSC_CNAME: Final = ("lz4", "lz4hc", "blosclz", "snappy", "zlib", "zstd") + + +class BloscConfigV2(TypedDict): + """Configuration for the V2 Blosc codec""" + + cname: BloscCnameLiteral + clevel: int + shuffle: int + blocksize: int + typesize: NotRequired[int] + + +class BloscConfigV3(TypedDict): + """Configuration for the V3 Blosc codec""" + + cname: BloscCnameLiteral + clevel: int + shuffle: BloscShuffleLiteral + blocksize: int + typesize: int + + +class BloscJSON_V3(NamedRequiredConfig[Literal["blosc"], BloscConfigV3]): + """ + The JSON form of the Blosc codec in Zarr V3. + """ + + +class BloscShuffle(metaclass=_DeprecatedStrEnumMeta): + """ + Deprecated. Pass a literal string (`"noshuffle"`, `"shuffle"`, or + `"bitshuffle"`) directly to `BloscCodec` instead. + """ + + _members: ClassVar[dict[str, str]] = { + "noshuffle": "noshuffle", + "shuffle": "shuffle", + "bitshuffle": "bitshuffle", + } + + @staticmethod + def from_int(num: int) -> BloscShuffleLiteral: + mapping: dict[int, BloscShuffleLiteral] = { 0: "noshuffle", 1: "shuffle", 2: "bitshuffle", } - if num not in blosc_shuffle_int_to_str: + if num not in mapping: raise ValueError(f"Value must be between 0 and 2. Got {num}.") - return BloscShuffle[blosc_shuffle_int_to_str[num]] + return mapping[num] + +class BloscCname(metaclass=_DeprecatedStrEnumMeta): + """ + Deprecated. Pass a literal string (one of `"lz4"`, `"lz4hc"`, + `"blosclz"`, `"snappy"`, `"zlib"`, `"zstd"`) directly to + `BloscCodec` instead. + """ -class BloscCname(Enum): - lz4 = "lz4" - lz4hc = "lz4hc" - blosclz = "blosclz" - zstd = "zstd" - snappy = "snappy" - zlib = "zlib" + _members: ClassVar[dict[str, str]] = { + "lz4": "lz4", + "lz4hc": "lz4hc", + "blosclz": "blosclz", + "snappy": "snappy", + "zstd": "zstd", + "zlib": "zlib", + } -# See https://zarr.readthedocs.io/en/stable/tutorial.html#configuring-blosc +# See https://zarr.readthedocs.io/en/stable/user-guide/performance.html#configuring-blosc numcodecs.blosc.use_threads = False def parse_typesize(data: JSON) -> int: - if isinstance(data, int): - if data > 0: - return data - else: - raise ValueError( - f"Value must be greater than 0. Got {data}, which is less or equal to 0." - ) - raise TypeError(f"Value must be an int. Got {type(data)} instead.") + parsed: int = parse_field(data, int, "typesize", error=TypeError) + if parsed > 0: + return parsed + else: + raise ValueError( + f"Value must be greater than 0. Got {parsed}, which is less or equal to 0." + ) # todo: real validation def parse_clevel(data: JSON) -> int: - if isinstance(data, int): - return data - raise TypeError(f"Value should be an int. Got {type(data)} instead.") + parsed: int = parse_field(data, int, "clevel", error=TypeError) + return parsed def parse_blocksize(data: JSON) -> int: - if isinstance(data, int): - return data - raise TypeError(f"Value should be an int. Got {type(data)} instead.") + parsed: int = parse_field(data, int, "blocksize", error=TypeError) + return parsed + + +def _parse_cname(data: object) -> BloscCnameLiteral: + if isinstance(data, str) and data in BLOSC_CNAME: + return data # type: ignore[return-value] + raise ValueError(f"cname must be one of {list(BLOSC_CNAME)!r}. Got {data!r}.") + + +def _parse_shuffle(data: object) -> BloscShuffleLiteral: + if isinstance(data, str) and data in BLOSC_SHUFFLE: + return data # type: ignore[return-value] + raise ValueError(f"shuffle must be one of {list(BLOSC_SHUFFLE)!r}. Got {data!r}.") @dataclass(frozen=True) class BloscCodec(BytesBytesCodec): + """ + Blosc compression codec for zarr. + + Blosc is a high-performance compressor optimized for binary data. It uses a + combination of blocking, shuffling, and fast compression algorithms to achieve + excellent compression ratios and speed. + + Attributes + ---------- + is_fixed_size : bool + Always False for Blosc codec, as compression produces variable-sized output. + typesize : int + The data type size in bytes used for shuffle filtering. + cname : BloscCnameLiteral + The compression algorithm being used; one of "lz4", "lz4hc", + "blosclz", "snappy", "zlib", or "zstd". + clevel : int + The compression level (0-9). + shuffle : BloscShuffleLiteral + The shuffle filter mode; one of "noshuffle", "shuffle", or + "bitshuffle". + blocksize : int + The size of compressed blocks in bytes (0 for automatic). + + Parameters + ---------- + typesize : int, optional + The data type size in bytes. This affects how the shuffle filter processes + the data. If None, defaults to 1 and the attribute is marked as tunable. + Default: 1. + cname : BloscCnameLiteral, optional + The compression algorithm to use; one of "lz4", "lz4hc", "blosclz", + "snappy", "zlib", or "zstd". Default is "zstd". Passing a `BloscCname` + enum is deprecated. + clevel : int, optional + The compression level, from 0 (no compression) to 9 (maximum compression). + Higher values provide better compression at the cost of speed. Default: 5. + shuffle : BloscShuffleLiteral or None, optional + The shuffle filter to apply before compression; one of "noshuffle", + "shuffle", or "bitshuffle": + + - 'noshuffle': No shuffling + - 'shuffle': Byte shuffling (better for typesize > 1) + - 'bitshuffle': Bit shuffling (better for typesize == 1) + + If None, defaults to 'bitshuffle' and the attribute is marked + as tunable. Default: 'bitshuffle'. + blocksize : int, optional + The requested size of compressed blocks in bytes. A value of 0 means + automatic block size selection. Default: 0. + + Notes + ----- + **Tunable attributes**: If `typesize` or `shuffle` are set to None during + initialization, they are marked as tunable attributes. This means they can be + adjusted later based on the data type of the array being compressed. + + **Thread Safety**: This codec sets `numcodecs.blosc.use_threads = False` at + module import time to avoid threading issues in asyncio contexts. + + Examples + -------- + Create a Blosc codec with default settings: + + >>> codec = BloscCodec() + >>> codec.typesize + 1 + >>> codec.shuffle + 'bitshuffle' + + Create a codec with specific compression settings: + + >>> codec = BloscCodec(cname='zstd', clevel=9, shuffle='shuffle') + >>> codec.cname + 'zstd' + """ + + # This attribute tracks parameters were set to None at init time, and thus tunable + _tunable_attrs: set[Literal["typesize", "shuffle"]] = field(init=False) is_fixed_size = False - typesize: int | None - cname: BloscCname = BloscCname.zstd - clevel: int = 5 - shuffle: BloscShuffle | None = BloscShuffle.noshuffle - blocksize: int = 0 + typesize: int + cname: BloscCnameLiteral + clevel: int + shuffle: BloscShuffleLiteral + blocksize: int def __init__( self, *, typesize: int | None = None, - cname: BloscCname | str = BloscCname.zstd, + cname: BloscCname | BloscCnameLiteral = "zstd", clevel: int = 5, - shuffle: BloscShuffle | str | None = None, + shuffle: BloscShuffle | BloscShuffleLiteral | None = None, blocksize: int = 0, ) -> None: - typesize_parsed = parse_typesize(typesize) if typesize is not None else None - cname_parsed = parse_enum(cname, BloscCname) + object.__setattr__(self, "_tunable_attrs", set()) + + if typesize is None: + typesize = 1 + self._tunable_attrs.update({"typesize"}) + + if shuffle is None: + shuffle = "bitshuffle" + self._tunable_attrs.update({"shuffle"}) + + cname = _coerce_enum_input(cname, "cname", "BloscCodec") # type: ignore[assignment] + shuffle = _coerce_enum_input(shuffle, "shuffle", "BloscCodec") # type: ignore[assignment] + + typesize_parsed = parse_typesize(typesize) + cname_parsed = _parse_cname(cname) clevel_parsed = parse_clevel(clevel) - shuffle_parsed = parse_enum(shuffle, BloscShuffle) if shuffle is not None else None + shuffle_parsed = _parse_shuffle(shuffle) blocksize_parsed = parse_blocksize(blocksize) object.__setattr__(self, "typesize", typesize_parsed) @@ -109,11 +266,7 @@ def from_dict(cls, data: dict[str, JSON]) -> Self: return cls(**configuration_parsed) # type: ignore[arg-type] def to_dict(self) -> dict[str, JSON]: - if self.typesize is None: - raise ValueError("`typesize` needs to be set for serialization.") - if self.shuffle is None: - raise ValueError("`shuffle` needs to be set for serialization.") - return { + result: BloscJSON_V3 = { "name": "blosc", "configuration": { "typesize": self.typesize, @@ -123,62 +276,78 @@ def to_dict(self) -> dict[str, JSON]: "blocksize": self.blocksize, }, } + return result # type: ignore[return-value] def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: - dtype = array_spec.dtype + """ + Create a new codec with typesize and shuffle parameters adjusted + according to the size of each element in the data type + associated with array_spec. Parameters are only updated if they were set to + None when self.__init__ was called. + """ + item_size = 1 + if isinstance(array_spec.dtype, HasItemSize): + item_size = array_spec.dtype.item_size new_codec = self - if new_codec.typesize is None: - new_codec = replace(new_codec, typesize=dtype.itemsize) - if new_codec.shuffle is None: + if "typesize" in self._tunable_attrs: + new_codec = replace(new_codec, typesize=item_size) + if "shuffle" in self._tunable_attrs: new_codec = replace( new_codec, - shuffle=(BloscShuffle.bitshuffle if dtype.itemsize == 1 else BloscShuffle.shuffle), + shuffle=("bitshuffle" if item_size == 1 else "shuffle"), ) return new_codec @cached_property def _blosc_codec(self) -> Blosc: - if self.shuffle is None: - raise ValueError("`shuffle` needs to be set for decoding and encoding.") - map_shuffle_str_to_int = { - BloscShuffle.noshuffle: 0, - BloscShuffle.shuffle: 1, - BloscShuffle.bitshuffle: 2, + map_shuffle_str_to_int: dict[BloscShuffleLiteral, int] = { + "noshuffle": 0, + "shuffle": 1, + "bitshuffle": 2, } - config_dict = { - "cname": self.cname.name, + config_dict: BloscConfigV2 = { + "cname": self.cname, "clevel": self.clevel, "shuffle": map_shuffle_str_to_int[self.shuffle], "blocksize": self.blocksize, } + # See https://github.com/zarr-developers/numcodecs/pull/713 + if Version(numcodecs.__version__) >= Version("0.16.0"): + config_dict["typesize"] = self.typesize return Blosc.from_config(config_dict) + def _decode_sync( + self, + chunk_bytes: Buffer, + chunk_spec: ArraySpec, + ) -> Buffer: + return as_numpy_array_wrapper(self._blosc_codec.decode, chunk_bytes, chunk_spec.prototype) + async def _decode_single( self, chunk_bytes: Buffer, chunk_spec: ArraySpec, ) -> Buffer: - return await to_thread( - as_numpy_array_wrapper, self._blosc_codec.decode, chunk_bytes, chunk_spec.prototype - ) + return await asyncio.to_thread(self._decode_sync, chunk_bytes, chunk_spec) - async def _encode_single( + def _encode_sync( self, chunk_bytes: Buffer, chunk_spec: ArraySpec, ) -> Buffer | None: # Since blosc only support host memory, we convert the input and output of the encoding # between numpy array and buffer - return await to_thread( - lambda chunk: chunk_spec.prototype.buffer.from_bytes( - self._blosc_codec.encode(chunk.as_numpy_array()) - ), - chunk_bytes, + return chunk_spec.prototype.buffer.from_bytes( + self._blosc_codec.encode(chunk_bytes.as_numpy_array()) ) + async def _encode_single( + self, + chunk_bytes: Buffer, + chunk_spec: ArraySpec, + ) -> Buffer | None: + return await asyncio.to_thread(self._encode_sync, chunk_bytes, chunk_spec) + def compute_encoded_size(self, _input_byte_length: int, _chunk_spec: ArraySpec) -> int: raise NotImplementedError - - -register_codec("blosc", BloscCodec) diff --git a/src/zarr/codecs/bytes.py b/src/zarr/codecs/bytes.py index 1fe9d900eb..fae762fd08 100644 --- a/src/zarr/codecs/bytes.py +++ b/src/zarr/codecs/bytes.py @@ -1,38 +1,58 @@ from __future__ import annotations import sys +import warnings from dataclasses import dataclass, replace -from enum import Enum -from typing import TYPE_CHECKING - -import numpy as np +from typing import TYPE_CHECKING, ClassVar, Final, Literal from zarr.abc.codec import ArrayBytesCodec -from zarr.array_spec import ArraySpec -from zarr.buffer import Buffer, NDArrayLike, NDBuffer -from zarr.common import JSON, parse_enum, parse_named_configuration -from zarr.registry import register_codec +from zarr.codecs._deprecated_enum import _coerce_enum_input, _DeprecatedStrEnumMeta +from zarr.core.buffer import Buffer, NDBuffer +from zarr.core.common import JSON, parse_named_configuration +from zarr.core.dtype.common import HasEndianness +from zarr.core.dtype.npy.structured import Struct if TYPE_CHECKING: - from typing_extensions import Self + from typing import Self + + from zarr.core.array_spec import ArraySpec + + +EndianLiteral = Literal["little", "big"] +"""Byte order of multi-byte numeric data.""" +ENDIAN: Final = ("little", "big") -class Endian(Enum): - big = "big" - little = "little" +class Endian(metaclass=_DeprecatedStrEnumMeta): + """ + Deprecated. Pass a literal string (`"little"` or `"big"`) directly to + `BytesCodec` instead. + """ -default_system_endian = Endian(sys.byteorder) + _members: ClassVar[dict[str, str]] = {"little": "little", "big": "big"} + + +def _parse_endian(data: object) -> EndianLiteral: + if isinstance(data, str) and data in ENDIAN: + return data # type: ignore[return-value] + raise ValueError(f"endian must be one of {list(ENDIAN)!r}. Got {data!r}.") @dataclass(frozen=True) class BytesCodec(ArrayBytesCodec): + """bytes codec""" + is_fixed_size = True - endian: Endian | None + endian: EndianLiteral | None - def __init__(self, *, endian: Endian | str | None = default_system_endian) -> None: - endian_parsed = None if endian is None else parse_enum(endian, Endian) + def __init__(self, *, endian: Endian | EndianLiteral | None = sys.byteorder) -> None: + if endian is None: + endian_parsed: EndianLiteral | None = None + else: + coerced = _coerce_enum_input(endian, "endian", "BytesCodec") + endian_parsed = _parse_endian(coerced) object.__setattr__(self, "endian", endian_parsed) @@ -42,6 +62,7 @@ def from_dict(cls, data: dict[str, JSON]) -> Self: data, "bytes", require_configuration=False ) configuration_parsed = configuration_parsed or {} + configuration_parsed.setdefault("endian", None) return cls(**configuration_parsed) # type: ignore[arg-type] def to_dict(self) -> dict[str, JSON]: @@ -51,7 +72,20 @@ def to_dict(self) -> dict[str, JSON]: return {"name": "bytes", "configuration": {"endian": self.endian}} def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: - if array_spec.dtype.itemsize == 0: + if isinstance(array_spec.dtype, Struct): + if array_spec.dtype.has_multi_byte_fields(): + if self.endian is None: + warnings.warn( + "Missing 'endian' for structured dtype with multi-byte fields. " + "Assuming little-endian for legacy compatibility.", + UserWarning, + stacklevel=2, + ) + return replace(self, endian="little") + else: + if self.endian is not None: + return replace(self, endian=None) + elif not isinstance(array_spec.dtype, HasEndianness): if self.endian is not None: return replace(self, endian=None) elif self.endian is None: @@ -60,29 +94,34 @@ def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: ) return self - async def _decode_single( + def _decode_sync( self, chunk_bytes: Buffer, chunk_spec: ArraySpec, ) -> NDBuffer: - assert isinstance(chunk_bytes, Buffer) - if chunk_spec.dtype.itemsize > 0: - if self.endian == Endian.little: - prefix = "<" - else: - prefix = ">" - dtype = np.dtype(f"{prefix}{chunk_spec.dtype.str[1:]}") + endian_str = self.endian + dtype = chunk_spec.dtype.to_native_dtype() + # The byte order of the stored data is set by this codec's `endian` + # configuration; the byte order of the decoded array is set by the array's + # data type. The two are independent: the raw bytes are viewed with a dtype + # in the stored byte order, then converted to the declared dtype if needed. + if isinstance(chunk_spec.dtype, HasEndianness): + view_dtype = replace(chunk_spec.dtype, endianness=endian_str).to_native_dtype() # type: ignore[call-arg] + elif isinstance(chunk_spec.dtype, Struct) and endian_str is not None: + # Per the struct data type spec, all multi-byte fields are stored in the + # byte order configured on this codec. + view_dtype = dtype.newbyteorder(endian_str) else: - dtype = np.dtype(f"|{chunk_spec.dtype.str[1:]}") - + view_dtype = dtype as_array_like = chunk_bytes.as_array_like() - if isinstance(as_array_like, NDArrayLike): - as_nd_array_like = as_array_like - else: - as_nd_array_like = np.asanyarray(as_array_like) chunk_array = chunk_spec.prototype.nd_buffer.from_ndarray_like( - as_nd_array_like.view(dtype=dtype) + as_array_like.view(dtype=view_dtype) # type: ignore[attr-defined] ) + if view_dtype != dtype: + # This byte-swapping conversion copies the chunk. The dtype inequality + # guard keeps the common case, where the stored and declared byte orders + # already match, on the zero-copy view path above. + chunk_array = chunk_array.astype(dtype) # ensure correct chunk shape if chunk_array.shape != chunk_spec.shape: @@ -91,32 +130,39 @@ async def _decode_single( ) return chunk_array - async def _encode_single( + async def _decode_single( + self, + chunk_bytes: Buffer, + chunk_spec: ArraySpec, + ) -> NDBuffer: + return self._decode_sync(chunk_bytes, chunk_spec) + + def _encode_sync( self, chunk_array: NDBuffer, chunk_spec: ArraySpec, ) -> Buffer | None: assert isinstance(chunk_array, NDBuffer) - if ( - chunk_array.dtype.itemsize > 1 - and self.endian is not None - and self.endian != chunk_array.byteorder - ): - # type-ignore is a numpy bug - # see https://github.com/numpy/numpy/issues/26473 - new_dtype = chunk_array.dtype.newbyteorder(self.endian.name) # type: ignore[arg-type] - chunk_array = chunk_array.astype(new_dtype) + if chunk_array.dtype.itemsize > 1 and self.endian is not None: + # Compare full dtypes rather than the top-level byteorder: numpy reports + # byteorder '|' for structured dtypes even when their fields are + # byte-order-sensitive, so newbyteorder is the only reliable way to + # detect (and normalize) a byte-order mismatch. + new_dtype = chunk_array.dtype.newbyteorder(self.endian) + if new_dtype != chunk_array.dtype: + chunk_array = chunk_array.astype(new_dtype) nd_array = chunk_array.as_ndarray_like() # Flatten the nd-array (only copy if needed) and reinterpret as bytes - nd_array = nd_array.ravel().view(dtype="b") + nd_array = nd_array.ravel().view(dtype="B") return chunk_spec.prototype.buffer.from_array_like(nd_array) + async def _encode_single( + self, + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + ) -> Buffer | None: + return self._encode_sync(chunk_array, chunk_spec) + def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: return input_byte_length - - -register_codec("bytes", BytesCodec) - -# compatibility with earlier versions of ZEP1 -register_codec("endian", BytesCodec) diff --git a/src/zarr/codecs/cast_value.py b/src/zarr/codecs/cast_value.py new file mode 100644 index 0000000000..b19a10c873 --- /dev/null +++ b/src/zarr/codecs/cast_value.py @@ -0,0 +1,435 @@ +"""Cast-value array-to-array codec. + +Value-converts array elements to a new data type during encoding, +and back to the original data type during decoding, with configurable +rounding, out-of-range handling, and explicit scalar mappings. + +Requires the optional ``cast-value-rs`` package for the actual casting +logic. Install it with: ``pip install 'cast-value-rs>=0.4.2'``. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass, replace +from importlib.metadata import PackageNotFoundError, version +from typing import TYPE_CHECKING, Final, Literal, TypedDict, cast + +import numpy as np +from packaging.version import Version + +from zarr.abc.codec import ArrayArrayCodec +from zarr.core.common import JSON, parse_named_configuration +from zarr.core.dtype import get_data_type_from_json + +if TYPE_CHECKING: + from typing import NotRequired, Self + + from zarr.core.array_spec import ArraySpec + from zarr.core.buffer import NDBuffer + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType + from zarr.core.metadata.v3 import ChunkGridMetadata + + class ScalarMapJSON(TypedDict): + encode: NotRequired[list[tuple[object, object]]] + decode: NotRequired[list[tuple[object, object]]] + + +RoundingMode = Literal[ + "nearest-even", + "towards-zero", + "towards-positive", + "towards-negative", + "nearest-away", +] + +OutOfRangeMode = Literal["clamp", "wrap"] + + +class ScalarMap(TypedDict, total=False): + """ + The normalized, in-memory form of a scalar map. + """ + + encode: Mapping[str | float | int, str | float | int] + decode: Mapping[str | float | int, str | float | int] + + +# see https://github.com/zarr-developers/zarr-extensions/tree/main/codecs/cast_value +CAST_VALUE_INT_DTYPES: Final[set[str]] = { + # signed + "int2", + "int4", + "int8", + "int16", + "int32", + "int64", + # unsigned + "uint2", + "uint4", + "uint8", + "uint16", + "uint32", + "uint64", +} +"""Integer dtype identifiers permitted as the source or target of `cast_value`. + +Membership in this set drives the `out_of_range="wrap"` rule, which the +spec restricts to integral targets that use two's-complement representation +for modular arithmetic. +""" + +CAST_VALUE_FLOAT_DTYPES: Final[set[str]] = { + "float4_e2m1fn", + "float6_e2m3fn", + "float6_e3m2fn", + "float8_e3m4", + "float8_e4m3", + "float8_e4m3b11fnuz", + "float8_e4m3fnuz", + "float8_e5m2", + "float8_e5m2fnuz", + "float8_e8m0fnu", + "bfloat16", + "float16", + "float32", + "float64", +} +"""Floating-point dtype identifiers permitted as the source or target of `cast_value`.""" + +PERMITTED_DATA_TYPE_NAMES: Final[set[str]] = CAST_VALUE_INT_DTYPES | CAST_VALUE_FLOAT_DTYPES +"""All dtype identifiers the `cast_value` codec is defined for.""" + + +def parse_scalar_map(obj: ScalarMapJSON | ScalarMap) -> ScalarMap: + """ + Parse a scalar map into its normalized dict-of-dicts form. + + Accepts either the JSON form (lists of tuples) or an already-normalized form + (dicts). For example, ``{"encode": [("NaN", 0)]}`` becomes + ``{"encode": {"NaN": 0}}``. + """ + result: ScalarMap = {} + for direction in ("encode", "decode"): + if direction in obj: + entries = obj[direction] + if entries is not None: + if isinstance(entries, Mapping): + result[direction] = entries + else: + result[direction] = dict(entries) # type: ignore[arg-type] + return result + + +# --------------------------------------------------------------------------- +# Backend: cast-value-rs +# --------------------------------------------------------------------------- + +# Versions below this silently transpose input arrays that are not row-major - +# the layout `transpose` hands to the next codec - writing corrupted data with +# no error. Keep in sync with the `cast-value-rs` extra in pyproject.toml. +CAST_VALUE_RS_MIN_VERSION: Final = "0.4.2" + +_INSTALL_HINT: Final = f"Install it with: pip install 'cast-value-rs>={CAST_VALUE_RS_MIN_VERSION}'" + + +def _check_backend_version() -> str | None: + """Return a message describing an unusable backend version, or `None` if it is usable.""" + try: + installed = version("cast-value-rs") + except PackageNotFoundError: + # Importable but without distribution metadata, e.g. a `maturin develop` + # build. There is no version to compare, so let it through. + return None + if Version(installed) < Version(CAST_VALUE_RS_MIN_VERSION): + return ( + f"The cast_value codec requires cast-value-rs >= {CAST_VALUE_RS_MIN_VERSION}, " + f"but version {installed} is installed. Earlier versions silently corrupt data " + f"when the input array is not row-major. {_INSTALL_HINT}" + ) + return None + + +# Set once at import; raised from `_do_cast`, so an unusable backend does not +# make `import zarr` fail for users who never touch this codec. +_BACKEND_ERROR: str | None +try: + from cast_value_rs import cast_array as cast_array_rs +except ModuleNotFoundError: + _BACKEND_ERROR = f"The cast_value codec requires the 'cast-value-rs' package. {_INSTALL_HINT}" +else: + _BACKEND_ERROR = _check_backend_version() + + +def _check_representable( + value: JSON, + zdtype: ZDType[TBaseDType, TBaseScalar], + label: str, +) -> None: + """Raise ``ValueError`` if *value* cannot be parsed by *zdtype*.""" + try: + zdtype.from_json_scalar(value, zarr_format=3) + except (TypeError, ValueError, OverflowError) as e: + raise ValueError( + f"{label} {value!r} is not representable in dtype {zdtype.to_native_dtype()}." + ) from e + + +# --------------------------------------------------------------------------- +# Codec +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class CastValue(ArrayArrayCodec): + """Cast-value array-to-array codec. + + Value-converts array elements to a new data type during encoding, + and back to the original data type during decoding. + + Requires the `cast-value-rs` package for the actual casting logic. + + Parameters + ---------- + data_type : str or ZDType + Target zarr v3 data type. Strings are looked up by spec name + (e.g. "uint8", "float32"); a `ZDType` instance is used as-is. + rounding : RoundingMode + How to round when exact representation is impossible. Default is + "nearest-even". + out_of_range : OutOfRangeMode or None + What to do when a value is outside the target's range. `None` means + error; "clamp" clips to range; "wrap" uses modular arithmetic + (only valid for integer types). Default is `None`. + scalar_map : ScalarMap, ScalarMapJSON, or None + Explicit mapping from input scalars to output scalars. Default is + `None`. + + Attributes + ---------- + dtype : ZDType + Resolved target data type (a `ZDType` instance, regardless of + whether the constructor received a string or a `ZDType`). + rounding : RoundingMode + The rounding mode, as supplied to the constructor. + out_of_range : OutOfRangeMode or None + The out-of-range behaviour, as supplied to the constructor. + scalar_map : ScalarMap or None + Parsed scalar map (always normalized to `ScalarMap` form). + + References + ---------- + + - The `cast_value` codec spec: https://github.com/zarr-developers/zarr-extensions/tree/main/codecs/cast_value + """ + + is_fixed_size = True + + dtype: ZDType[TBaseDType, TBaseScalar] + rounding: RoundingMode + out_of_range: OutOfRangeMode | None + scalar_map: ScalarMap | None + + def __init__( + self, + *, + data_type: str | ZDType[TBaseDType, TBaseScalar], + rounding: RoundingMode = "nearest-even", + out_of_range: OutOfRangeMode | None = None, + scalar_map: ScalarMapJSON | ScalarMap | None = None, + ) -> None: + if isinstance(data_type, str): + zdtype = get_data_type_from_json(data_type, zarr_format=3) + else: + zdtype = data_type + if zdtype.to_json(zarr_format=3) not in PERMITTED_DATA_TYPE_NAMES: + raise ValueError( + f"Invalid target data type {data_type!r}. " + f"cast_value codec only supports integer and floating-point data types. " + f"Got {zdtype}." + ) + object.__setattr__(self, "dtype", zdtype) + object.__setattr__(self, "rounding", rounding) + object.__setattr__(self, "out_of_range", out_of_range) + if scalar_map is not None: + parsed = parse_scalar_map(scalar_map) + else: + parsed = None + object.__setattr__(self, "scalar_map", parsed) + + @classmethod + def from_dict(cls, data: dict[str, JSON]) -> Self: + _, configuration_parsed = parse_named_configuration( + data, "cast_value", require_configuration=True + ) + return cls(**configuration_parsed) # type: ignore[arg-type] + + def to_dict(self) -> dict[str, JSON]: + config: dict[str, JSON] = {"data_type": cast("JSON", self.dtype.to_json(zarr_format=3))} + if self.rounding != "nearest-even": + config["rounding"] = self.rounding + if self.out_of_range is not None: + config["out_of_range"] = self.out_of_range + if self.scalar_map is not None: + json_map: dict[str, list[tuple[object, object]]] = {} + for direction in ("encode", "decode"): + if direction in self.scalar_map: + json_map[direction] = [(k, v) for k, v in self.scalar_map[direction].items()] + config["scalar_map"] = cast("JSON", json_map) + return {"name": "cast_value", "configuration": config} + + def validate( + self, + *, + shape: tuple[int, ...], + dtype: ZDType[TBaseDType, TBaseScalar], + chunk_grid: ChunkGridMetadata, + ) -> None: + # `dtype` is the source (the array's dtype); `self.dtype` is the + # cast target. The spec requires both to be permitted, and rules + # like `out_of_range="wrap"` apply to the target. + source_name = dtype.to_json(zarr_format=3) + target_name = self.dtype.to_json(zarr_format=3) + for role, name in (("source", source_name), ("target", target_name)): + if name not in PERMITTED_DATA_TYPE_NAMES: + raise ValueError( + f"The cast_value codec only supports integer and floating-point data types. " + f"Got {role} dtype {name}." + ) + if self.out_of_range == "wrap" and target_name not in CAST_VALUE_INT_DTYPES: + raise ValueError( + f"out_of_range='wrap' is only valid for integer target types. " + f"Got target dtype {target_name}." + ) + + if self.scalar_map is not None: + self._validate_scalar_map(dtype, self.dtype) + + def _validate_scalar_map( + self, + source_zdtype: ZDType[TBaseDType, TBaseScalar], + target_zdtype: ZDType[TBaseDType, TBaseScalar], + ) -> None: + """Validate that scalar map entries are compatible with source/target dtypes.""" + assert self.scalar_map is not None + # For encode: keys are source values, values are target values. + # For decode: keys are target values, values are source values. + direction_dtypes: dict[ + str, tuple[ZDType[TBaseDType, TBaseScalar], ZDType[TBaseDType, TBaseScalar]] + ] = { + "encode": (source_zdtype, target_zdtype), + "decode": (target_zdtype, source_zdtype), + } + for direction, (key_zdtype, val_zdtype) in direction_dtypes.items(): + if direction not in self.scalar_map: + continue + sub_map = self.scalar_map[direction] # type: ignore[literal-required] + for k, v in sub_map.items(): + _check_representable(k, key_zdtype, f"scalar_map {direction} key") + _check_representable(v, val_zdtype, f"scalar_map {direction} value") + + def _do_cast( + self, + arr: np.ndarray, + *, + target_dtype: np.dtype, + scalar_map: Mapping[str | float | int, str | float | int] | None, + ) -> np.ndarray: + if _BACKEND_ERROR is not None: + raise ImportError(_BACKEND_ERROR) + scalar_map_entries: dict[float | int, float | int] | None = None + if scalar_map is not None: + src_dtype = arr.dtype + to_src = int if np.issubdtype(src_dtype, np.integer) else float + to_tgt = int if np.issubdtype(target_dtype, np.integer) else float + scalar_map_entries = {to_src(k): to_tgt(v) for k, v in scalar_map.items()} + return cast_array_rs( # type: ignore[no-any-return] + arr, + target_dtype=target_dtype, + rounding_mode=self.rounding, + out_of_range_mode=self.out_of_range, + scalar_map_entries=scalar_map_entries, + ) + + def _get_scalar_map( + self, direction: str + ) -> Mapping[str | float | int, str | float | int] | None: + """Extract the encode or decode mapping from scalar_map, or None.""" + if self.scalar_map is None: + return None + return self.scalar_map.get(direction) # type: ignore[return-value] + + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + """ + Update the fill value of the output spec by applying casting procedure. + """ + target_zdtype = self.dtype + target_native = target_zdtype.to_native_dtype() + source_native = chunk_spec.dtype.to_native_dtype() + + fill = chunk_spec.fill_value + fill_arr = np.array([fill], dtype=source_native) + + new_fill_arr = self._do_cast( + fill_arr, target_dtype=target_native, scalar_map=self._get_scalar_map("encode") + ) + new_fill = target_native.type(new_fill_arr[0]) + + return replace(chunk_spec, dtype=target_zdtype, fill_value=new_fill) + + def _encode_sync( + self, + chunk_array: NDBuffer, + _chunk_spec: ArraySpec, + ) -> NDBuffer | None: + arr = chunk_array.as_ndarray_like() + target_native = self.dtype.to_native_dtype() + + result = self._do_cast( + np.asarray(arr), target_dtype=target_native, scalar_map=self._get_scalar_map("encode") + ) + return chunk_array.__class__.from_ndarray_like(result) + + async def _encode_single( + self, + chunk_data: NDBuffer, + chunk_spec: ArraySpec, + ) -> NDBuffer | None: + return self._encode_sync(chunk_data, chunk_spec) + + def _decode_sync( + self, + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + ) -> NDBuffer: + arr = chunk_array.as_ndarray_like() + target_native = chunk_spec.dtype.to_native_dtype() + + result = self._do_cast( + np.asarray(arr), target_dtype=target_native, scalar_map=self._get_scalar_map("decode") + ) + return chunk_array.__class__.from_ndarray_like(result) + + async def _decode_single( + self, + chunk_data: NDBuffer, + chunk_spec: ArraySpec, + ) -> NDBuffer: + return self._decode_sync(chunk_data, chunk_spec) + + def compute_encoded_size(self, input_byte_length: int, chunk_spec: ArraySpec) -> int: + dtype_name = chunk_spec.dtype.to_json(zarr_format=3) + if dtype_name not in PERMITTED_DATA_TYPE_NAMES: + raise ValueError( + "cast_value codec only supports fixed-size integer and floating-point data types. " + f"Got source dtype: {chunk_spec.dtype}." + ) + source_itemsize = chunk_spec.dtype.to_native_dtype().itemsize + target_itemsize = self.dtype.to_native_dtype().itemsize + if source_itemsize == 0 or target_itemsize == 0: + raise ValueError( + "cast_value codec requires fixed-size data types. " + f"Got source itemsize={source_itemsize}, target itemsize={target_itemsize}." + ) + num_elements = input_byte_length // source_itemsize + return num_elements * target_itemsize diff --git a/src/zarr/codecs/crc32c_.py b/src/zarr/codecs/crc32c_.py index 5c94558b00..7d41e11637 100644 --- a/src/zarr/codecs/crc32c_.py +++ b/src/zarr/codecs/crc32c_.py @@ -1,23 +1,26 @@ from __future__ import annotations +from collections.abc import Buffer as ABCBuffer from dataclasses import dataclass -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, cast +import google_crc32c import numpy as np -from crc32c import crc32c from zarr.abc.codec import BytesBytesCodec -from zarr.array_spec import ArraySpec -from zarr.buffer import Buffer -from zarr.common import JSON, parse_named_configuration -from zarr.registry import register_codec +from zarr.core.common import JSON, parse_named_configuration if TYPE_CHECKING: - from typing_extensions import Self + from typing import Self + + from zarr.core.array_spec import ArraySpec + from zarr.core.buffer import Buffer @dataclass(frozen=True) class Crc32cCodec(BytesBytesCodec): + """crc32c codec""" + is_fixed_size = True @classmethod @@ -28,7 +31,7 @@ def from_dict(cls, data: dict[str, JSON]) -> Self: def to_dict(self) -> dict[str, JSON]: return {"name": "crc32c"} - async def _decode_single( + def _decode_sync( self, chunk_bytes: Buffer, chunk_spec: ArraySpec, @@ -37,7 +40,8 @@ async def _decode_single( crc32_bytes = data[-4:] inner_bytes = data[:-4] - computed_checksum = np.uint32(crc32c(inner_bytes)).tobytes() + # Need to do a manual cast until https://github.com/numpy/numpy/issues/26783 is resolved + computed_checksum = np.uint32(google_crc32c.value(cast(ABCBuffer, inner_bytes))).tobytes() stored_checksum = bytes(crc32_bytes) if computed_checksum != stored_checksum: raise ValueError( @@ -45,19 +49,30 @@ async def _decode_single( ) return chunk_spec.prototype.buffer.from_array_like(inner_bytes) - async def _encode_single( + async def _decode_single( + self, + chunk_bytes: Buffer, + chunk_spec: ArraySpec, + ) -> Buffer: + return self._decode_sync(chunk_bytes, chunk_spec) + + def _encode_sync( self, chunk_bytes: Buffer, chunk_spec: ArraySpec, ) -> Buffer | None: data = chunk_bytes.as_numpy_array() # Calculate the checksum and "cast" it to a numpy array - checksum = np.array([crc32c(data)], dtype=np.uint32) + checksum = np.array([google_crc32c.value(cast(ABCBuffer, data))], dtype=np.uint32) # Append the checksum (as bytes) to the data - return chunk_spec.prototype.buffer.from_array_like(np.append(data, checksum.view("b"))) + return chunk_spec.prototype.buffer.from_array_like(np.append(data, checksum.view("B"))) + + async def _encode_single( + self, + chunk_bytes: Buffer, + chunk_spec: ArraySpec, + ) -> Buffer | None: + return self._encode_sync(chunk_bytes, chunk_spec) def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: return input_byte_length + 4 - - -register_codec("crc32c", Crc32cCodec) diff --git a/src/zarr/codecs/gzip.py b/src/zarr/codecs/gzip.py index 915ae79832..7d86a03ba8 100644 --- a/src/zarr/codecs/gzip.py +++ b/src/zarr/codecs/gzip.py @@ -1,32 +1,37 @@ from __future__ import annotations +import asyncio from dataclasses import dataclass +from functools import cached_property from typing import TYPE_CHECKING from numcodecs.gzip import GZip from zarr.abc.codec import BytesBytesCodec -from zarr.array_spec import ArraySpec -from zarr.buffer import Buffer, as_numpy_array_wrapper -from zarr.common import JSON, parse_named_configuration, to_thread -from zarr.registry import register_codec +from zarr.core.buffer.cpu import as_numpy_array_wrapper +from zarr.core.common import JSON, parse_named_configuration +from zarr.core.json_parse import parse_field if TYPE_CHECKING: - from typing_extensions import Self + from typing import Self + + from zarr.core.array_spec import ArraySpec + from zarr.core.buffer import Buffer def parse_gzip_level(data: JSON) -> int: - if not isinstance(data, (int)): - raise TypeError(f"Expected int, got {type(data)}") - if data not in range(0, 10): + parsed: int = parse_field(data, int, "level", error=TypeError) + if parsed not in range(10): raise ValueError( - f"Expected an integer from the inclusive range (0, 9). Got {data} instead." + f"Expected an integer from the inclusive range (0, 9). Got {parsed} instead." ) - return data + return parsed @dataclass(frozen=True) class GzipCodec(BytesBytesCodec): + """gzip codec""" + is_fixed_size = False level: int = 5 @@ -44,23 +49,37 @@ def from_dict(cls, data: dict[str, JSON]) -> Self: def to_dict(self) -> dict[str, JSON]: return {"name": "gzip", "configuration": {"level": self.level}} + @cached_property + def _gzip_codec(self) -> GZip: + return GZip(self.level) + + def _decode_sync( + self, + chunk_bytes: Buffer, + chunk_spec: ArraySpec, + ) -> Buffer: + return as_numpy_array_wrapper(self._gzip_codec.decode, chunk_bytes, chunk_spec.prototype) + async def _decode_single( self, chunk_bytes: Buffer, chunk_spec: ArraySpec, ) -> Buffer: - return await to_thread( - as_numpy_array_wrapper, GZip(self.level).decode, chunk_bytes, chunk_spec.prototype - ) + return await asyncio.to_thread(self._decode_sync, chunk_bytes, chunk_spec) + + def _encode_sync( + self, + chunk_bytes: Buffer, + chunk_spec: ArraySpec, + ) -> Buffer | None: + return as_numpy_array_wrapper(self._gzip_codec.encode, chunk_bytes, chunk_spec.prototype) async def _encode_single( self, chunk_bytes: Buffer, chunk_spec: ArraySpec, ) -> Buffer | None: - return await to_thread( - as_numpy_array_wrapper, GZip(self.level).encode, chunk_bytes, chunk_spec.prototype - ) + return await asyncio.to_thread(self._encode_sync, chunk_bytes, chunk_spec) def compute_encoded_size( self, @@ -68,6 +87,3 @@ def compute_encoded_size( _chunk_spec: ArraySpec, ) -> int: raise NotImplementedError - - -register_codec("gzip", GzipCodec) diff --git a/src/zarr/codecs/numcodecs/__init__.py b/src/zarr/codecs/numcodecs/__init__.py new file mode 100644 index 0000000000..d68ad3fba6 --- /dev/null +++ b/src/zarr/codecs/numcodecs/__init__.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +from zarr.codecs.numcodecs._codecs import ( + BZ2, + CRC32, + CRC32C, + LZ4, + LZMA, + ZFPY, + Adler32, + AsType, + BitRound, + Blosc, + Delta, + FixedScaleOffset, + Fletcher32, + GZip, + JenkinsLookup3, + PackBits, + PCodec, + Quantize, + Shuffle, + Zlib, + Zstd, + _NumcodecsArrayArrayCodec, + _NumcodecsArrayBytesCodec, + _NumcodecsBytesBytesCodec, + _NumcodecsCodec, +) + +__all__ = [ + "BZ2", + "CRC32", + "CRC32C", + "LZ4", + "LZMA", + "ZFPY", + "Adler32", + "AsType", + "BitRound", + "Blosc", + "Delta", + "FixedScaleOffset", + "Fletcher32", + "GZip", + "JenkinsLookup3", + "PCodec", + "PackBits", + "Quantize", + "Shuffle", + "Zlib", + "Zstd", + "_NumcodecsArrayArrayCodec", + "_NumcodecsArrayBytesCodec", + "_NumcodecsBytesBytesCodec", + "_NumcodecsCodec", +] diff --git a/src/zarr/codecs/numcodecs/_codecs.py b/src/zarr/codecs/numcodecs/_codecs.py new file mode 100644 index 0000000000..f44c35964c --- /dev/null +++ b/src/zarr/codecs/numcodecs/_codecs.py @@ -0,0 +1,336 @@ +""" +This module provides compatibility for [numcodecs][] in Zarr version 3. + +These codecs were previously defined in [numcodecs][], and have now been moved to `zarr`. + +```python +import numpy as np +import zarr +import zarr.codecs.numcodecs as numcodecs + +store = zarr.storage.MemoryStore() +array = zarr.create_array( + store=store, + shape=(1024, 1024), + chunks=(64, 64), + dtype="uint32", + filters=[numcodecs.Delta(dtype="uint32")], + compressors=[numcodecs.BZ2(level=5)], + overwrite=True +) +array[:] = np.arange(np.prod(array.shape), dtype=array.dtype).reshape(*array.shape) +``` + +!!! note + Please note that the codecs in [zarr.codecs.numcodecs][] are not part of the Zarr version + 3 specification. Using these codecs might cause interoperability issues with other Zarr + implementations. +""" + +from __future__ import annotations + +import asyncio +import math +from dataclasses import dataclass, replace +from functools import cached_property +from typing import TYPE_CHECKING, Any, Self + +import numpy as np + +from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec +from zarr.abc.metadata import Metadata +from zarr.core.buffer.cpu import as_numpy_array_wrapper +from zarr.core.common import JSON, parse_named_configuration, product +from zarr.dtype import UInt8, ZDType, parse_dtype +from zarr.registry import get_numcodec + +if TYPE_CHECKING: + from zarr.abc.numcodec import Numcodec + from zarr.core.array_spec import ArraySpec + from zarr.core.buffer import Buffer, NDBuffer + +CODEC_PREFIX = "numcodecs." + + +def _expect_name_prefix(codec_name: str) -> str: + if not codec_name.startswith(CODEC_PREFIX): + raise ValueError( + f"Expected name to start with '{CODEC_PREFIX}'. Got {codec_name} instead." + ) # pragma: no cover + return codec_name.removeprefix(CODEC_PREFIX) + + +def _parse_codec_configuration(data: dict[str, JSON]) -> dict[str, JSON]: + parsed_name, parsed_configuration = parse_named_configuration(data) + if not parsed_name.startswith(CODEC_PREFIX): + raise ValueError( + f"Expected name to start with '{CODEC_PREFIX}'. Got {parsed_name} instead." + ) # pragma: no cover + id = _expect_name_prefix(parsed_name) + return {"id": id, **parsed_configuration} + + +@dataclass(frozen=True) +class _NumcodecsCodec(Metadata): + codec_name: str + codec_config: dict[str, JSON] + + def __init_subclass__(cls, *, codec_name: str | None = None, **kwargs: Any) -> None: + """To be used only when creating the actual public-facing codec class.""" + super().__init_subclass__(**kwargs) + if codec_name is not None: + namespace = codec_name + + cls_name = f"{CODEC_PREFIX}{namespace}.{cls.__name__}" + cls.codec_name = f"{CODEC_PREFIX}{namespace}" + cls.__doc__ = f""" + See [{cls_name}][] for more details and parameters. + """ + + def __init__(self, **codec_config: JSON) -> None: + if not self.codec_name: + raise ValueError( + "The codec name needs to be supplied through the `codec_name` attribute." + ) # pragma: no cover + unprefixed_codec_name = _expect_name_prefix(self.codec_name) + + if "id" not in codec_config: + codec_config = {"id": unprefixed_codec_name, **codec_config} + elif codec_config["id"] != unprefixed_codec_name: + raise ValueError( + f"Codec id does not match {unprefixed_codec_name}. Got: {codec_config['id']}." + ) # pragma: no cover + + object.__setattr__(self, "codec_config", codec_config) + + @cached_property + def _codec(self) -> Numcodec: + return get_numcodec(self.codec_config) # type: ignore[arg-type] + + @classmethod + def from_dict(cls, data: dict[str, JSON]) -> Self: + codec_config = _parse_codec_configuration(data) + return cls(**codec_config) + + def to_dict(self) -> dict[str, JSON]: + codec_config = self.codec_config.copy() + codec_config.pop("id", None) + return { + "name": self.codec_name, + "configuration": codec_config, + } + + def compute_encoded_size(self, input_byte_length: int, chunk_spec: ArraySpec) -> int: + raise NotImplementedError # pragma: no cover + + # Override __repr__ because dynamically constructed classes don't seem to work otherwise + def __repr__(self) -> str: + codec_config = self.codec_config.copy() + codec_config.pop("id", None) + return f"{self.__class__.__name__}(codec_name={self.codec_name!r}, codec_config={codec_config!r})" + + +class _NumcodecsBytesBytesCodec(_NumcodecsCodec, BytesBytesCodec): + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + def _decode_sync(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> Buffer: + return as_numpy_array_wrapper(self._codec.decode, chunk_data, chunk_spec.prototype) + + def _encode_sync(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> Buffer: + encoded = self._codec.encode(chunk_data.as_array_like()) + if isinstance(encoded, np.ndarray): # Required for checksum codecs + return chunk_spec.prototype.buffer.from_bytes(encoded.tobytes()) + return chunk_spec.prototype.buffer.from_bytes(encoded) + + async def _decode_single(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> Buffer: + return await asyncio.to_thread(self._decode_sync, chunk_data, chunk_spec) + + async def _encode_single(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> Buffer: + return await asyncio.to_thread(self._encode_sync, chunk_data, chunk_spec) + + +class _NumcodecsArrayArrayCodec(_NumcodecsCodec, ArrayArrayCodec): + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + def _decode_sync(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + chunk_ndarray = chunk_data.as_ndarray_like() + out = self._codec.decode(chunk_ndarray) + return chunk_spec.prototype.nd_buffer.from_ndarray_like(out.reshape(chunk_spec.shape)) + + def _encode_sync(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + # numcodecs codecs flatten with order="A", so an F-contiguous chunk + # would be encoded in transposed element order (gh-3558) + chunk_ndarray = np.ascontiguousarray(chunk_data.as_ndarray_like()) + out = self._codec.encode(chunk_ndarray) + return chunk_spec.prototype.nd_buffer.from_ndarray_like(out) + + async def _encode_single(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return await asyncio.to_thread(self._encode_sync, chunk_data, chunk_spec) + + async def _decode_single(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return await asyncio.to_thread(self._decode_sync, chunk_data, chunk_spec) + + +class _NumcodecsArrayBytesCodec(_NumcodecsCodec, ArrayBytesCodec): + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + def _decode_sync(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> NDBuffer: + chunk_bytes = chunk_data.to_bytes() + out = self._codec.decode(chunk_bytes) + return chunk_spec.prototype.nd_buffer.from_ndarray_like(out.reshape(chunk_spec.shape)) + + def _encode_sync(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> Buffer: + # numcodecs codecs flatten with order="A", so an F-contiguous chunk + # would be encoded in transposed element order (gh-3558) + chunk_ndarray = np.ascontiguousarray(chunk_data.as_ndarray_like()) + out = self._codec.encode(chunk_ndarray) + return chunk_spec.prototype.buffer.from_bytes(out) + + async def _encode_single(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> Buffer: + return await asyncio.to_thread(self._encode_sync, chunk_data, chunk_spec) + + async def _decode_single(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> NDBuffer: + return await asyncio.to_thread(self._decode_sync, chunk_data, chunk_spec) + + +# bytes-to-bytes codecs +class Blosc(_NumcodecsBytesBytesCodec, codec_name="blosc"): + pass + + +class LZ4(_NumcodecsBytesBytesCodec, codec_name="lz4"): + pass + + +class Zstd(_NumcodecsBytesBytesCodec, codec_name="zstd"): + pass + + +class Zlib(_NumcodecsBytesBytesCodec, codec_name="zlib"): + pass + + +class GZip(_NumcodecsBytesBytesCodec, codec_name="gzip"): + pass + + +class BZ2(_NumcodecsBytesBytesCodec, codec_name="bz2"): + pass + + +class LZMA(_NumcodecsBytesBytesCodec, codec_name="lzma"): + pass + + +class Shuffle(_NumcodecsBytesBytesCodec, codec_name="shuffle"): + def evolve_from_array_spec(self, array_spec: ArraySpec) -> Shuffle: + if self.codec_config.get("elementsize") is None: + dtype = array_spec.dtype.to_native_dtype() + return Shuffle(**{**self.codec_config, "elementsize": dtype.itemsize}) + return self # pragma: no cover + + +# array-to-array codecs ("filters") +class Delta(_NumcodecsArrayArrayCodec, codec_name="delta"): + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + if astype := self.codec_config.get("astype"): + dtype = parse_dtype(np.dtype(astype), zarr_format=3) # type: ignore[call-overload] + return replace(chunk_spec, dtype=dtype) + return chunk_spec + + +class BitRound(_NumcodecsArrayArrayCodec, codec_name="bitround"): + pass + + +class FixedScaleOffset(_NumcodecsArrayArrayCodec, codec_name="fixedscaleoffset"): + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + if astype := self.codec_config.get("astype"): + dtype = parse_dtype(np.dtype(astype), zarr_format=3) # type: ignore[call-overload] + return replace(chunk_spec, dtype=dtype) + return chunk_spec + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> FixedScaleOffset: + if self.codec_config.get("dtype") is None: + dtype = array_spec.dtype.to_native_dtype() + return FixedScaleOffset(**{**self.codec_config, "dtype": str(dtype)}) + return self + + +class Quantize(_NumcodecsArrayArrayCodec, codec_name="quantize"): + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> Quantize: + if self.codec_config.get("dtype") is None: + dtype = array_spec.dtype.to_native_dtype() + return Quantize(**{**self.codec_config, "dtype": str(dtype)}) + return self + + +class PackBits(_NumcodecsArrayArrayCodec, codec_name="packbits"): + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + return replace( + chunk_spec, + shape=(1 + math.ceil(product(chunk_spec.shape) / 8),), + dtype=UInt8(), + ) + + # todo: remove this type: ignore when this class can be defined w.r.t. + # a single zarr dtype API + def validate(self, *, dtype: ZDType[Any, Any], **_kwargs: Any) -> None: + # this is bugged and will fail + _dtype = dtype.to_native_dtype() + if _dtype != np.dtype("bool"): + raise ValueError(f"Packbits filter requires bool dtype. Got {dtype}.") + + +class AsType(_NumcodecsArrayArrayCodec, codec_name="astype"): + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + dtype = parse_dtype(np.dtype(self.codec_config["encode_dtype"]), zarr_format=3) # type: ignore[arg-type] + return replace(chunk_spec, dtype=dtype) + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> AsType: + if self.codec_config.get("decode_dtype") is None: + # TODO: remove these coverage exemptions the correct way, i.e. with tests + dtype = array_spec.dtype.to_native_dtype() # pragma: no cover + return AsType(**{**self.codec_config, "decode_dtype": str(dtype)}) # pragma: no cover + return self + + +# bytes-to-bytes checksum codecs +class _NumcodecsChecksumCodec(_NumcodecsBytesBytesCodec): + def compute_encoded_size(self, input_byte_length: int, chunk_spec: ArraySpec) -> int: + return input_byte_length + 4 # pragma: no cover + + +class CRC32(_NumcodecsChecksumCodec, codec_name="crc32"): + pass + + +class CRC32C(_NumcodecsChecksumCodec, codec_name="crc32c"): + pass + + +class Adler32(_NumcodecsChecksumCodec, codec_name="adler32"): + pass + + +class Fletcher32(_NumcodecsChecksumCodec, codec_name="fletcher32"): + pass + + +class JenkinsLookup3(_NumcodecsChecksumCodec, codec_name="jenkins_lookup3"): + pass + + +# array-to-bytes codecs +class PCodec(_NumcodecsArrayBytesCodec, codec_name="pcodec"): + pass + + +class ZFPY(_NumcodecsArrayBytesCodec, codec_name="zfpy"): + pass diff --git a/src/zarr/codecs/pipeline.py b/src/zarr/codecs/pipeline.py deleted file mode 100644 index 8cda04c9ff..0000000000 --- a/src/zarr/codecs/pipeline.py +++ /dev/null @@ -1,532 +0,0 @@ -from __future__ import annotations - -from collections.abc import Iterable, Iterator -from dataclasses import dataclass -from itertools import islice, pairwise -from typing import TYPE_CHECKING, Any, TypeVar -from warnings import warn - -import numpy as np - -from zarr.abc.codec import ( - ArrayArrayCodec, - ArrayBytesCodec, - ArrayBytesCodecPartialDecodeMixin, - ArrayBytesCodecPartialEncodeMixin, - BytesBytesCodec, - Codec, - CodecPipeline, -) -from zarr.abc.store import ByteGetter, ByteSetter -from zarr.buffer import Buffer, BufferPrototype, NDBuffer -from zarr.chunk_grids import ChunkGrid -from zarr.common import JSON, ChunkCoords, concurrent_map, parse_named_configuration -from zarr.config import config -from zarr.indexing import SelectorTuple, is_scalar, is_total_slice -from zarr.registry import get_codec_class, register_pipeline - -if TYPE_CHECKING: - from typing_extensions import Self - - from zarr.array_spec import ArraySpec - -T = TypeVar("T") -U = TypeVar("U") - - -def _unzip2(iterable: Iterable[tuple[T, U]]) -> tuple[list[T], list[U]]: - out0: list[T] = [] - out1: list[U] = [] - for item0, item1 in iterable: - out0.append(item0) - out1.append(item1) - return (out0, out1) - - -def batched(iterable: Iterable[T], n: int) -> Iterable[tuple[T, ...]]: - if n < 1: - raise ValueError("n must be at least one") - it = iter(iterable) - while batch := tuple(islice(it, n)): - yield batch - - -def resolve_batched(codec: Codec, chunk_specs: Iterable[ArraySpec]) -> Iterable[ArraySpec]: - return [codec.resolve_metadata(chunk_spec) for chunk_spec in chunk_specs] - - -@dataclass(frozen=True) -class BatchedCodecPipeline(CodecPipeline): - """Default codec pipeline. - - This batched codec pipeline divides the chunk batches into batches of a configurable - batch size ("mini-batch"). Fetching, decoding, encoding and storing are performed in - lock step for each mini-batch. Multiple mini-batches are processing concurrently. - """ - - array_array_codecs: tuple[ArrayArrayCodec, ...] - array_bytes_codec: ArrayBytesCodec - bytes_bytes_codecs: tuple[BytesBytesCodec, ...] - batch_size: int - - @classmethod - def from_dict(cls, data: Iterable[JSON | Codec], *, batch_size: int | None = None) -> Self: - out: list[Codec] = [] - if not isinstance(data, Iterable): - raise TypeError(f"Expected iterable, got {type(data)}") - - for c in data: - if isinstance( - c, ArrayArrayCodec | ArrayBytesCodec | BytesBytesCodec - ): # Can't use Codec here because of mypy limitation - out.append(c) - else: - name_parsed, _ = parse_named_configuration(c, require_configuration=False) - out.append(get_codec_class(name_parsed).from_dict(c)) # type: ignore[arg-type] - return cls.from_list(out, batch_size=batch_size) - - def to_dict(self) -> JSON: - return [c.to_dict() for c in self] - - def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: - return type(self).from_list([c.evolve_from_array_spec(array_spec=array_spec) for c in self]) - - @classmethod - def from_list(cls, codecs: Iterable[Codec], *, batch_size: int | None = None) -> Self: - array_array_codecs, array_bytes_codec, bytes_bytes_codecs = codecs_from_list(codecs) - - return cls( - array_array_codecs=array_array_codecs, - array_bytes_codec=array_bytes_codec, - bytes_bytes_codecs=bytes_bytes_codecs, - batch_size=batch_size or config.get("codec_pipeline.batch_size"), - ) - - @property - def supports_partial_decode(self) -> bool: - """Determines whether the codec pipeline supports partial decoding. - - Currently, only codec pipelines with a single ArrayBytesCodec that supports - partial decoding can support partial decoding. This limitation is due to the fact - that ArrayArrayCodecs can change the slice selection leading to non-contiguous - slices and BytesBytesCodecs can change the chunk bytes in a way that slice - selections cannot be attributed to byte ranges anymore which renders partial - decoding infeasible. - - This limitation may softened in the future.""" - return (len(self.array_array_codecs) + len(self.bytes_bytes_codecs)) == 0 and isinstance( - self.array_bytes_codec, ArrayBytesCodecPartialDecodeMixin - ) - - @property - def supports_partial_encode(self) -> bool: - """Determines whether the codec pipeline supports partial encoding. - - Currently, only codec pipelines with a single ArrayBytesCodec that supports - partial encoding can support partial encoding. This limitation is due to the fact - that ArrayArrayCodecs can change the slice selection leading to non-contiguous - slices and BytesBytesCodecs can change the chunk bytes in a way that slice - selections cannot be attributed to byte ranges anymore which renders partial - encoding infeasible. - - This limitation may softened in the future.""" - return (len(self.array_array_codecs) + len(self.bytes_bytes_codecs)) == 0 and isinstance( - self.array_bytes_codec, ArrayBytesCodecPartialEncodeMixin - ) - - def __iter__(self) -> Iterator[Codec]: - yield from self.array_array_codecs - yield self.array_bytes_codec - yield from self.bytes_bytes_codecs - - def validate(self, *, shape: ChunkCoords, dtype: np.dtype[Any], chunk_grid: ChunkGrid) -> None: - for codec in self: - codec.validate(shape=shape, dtype=dtype, chunk_grid=chunk_grid) - - def compute_encoded_size(self, byte_length: int, array_spec: ArraySpec) -> int: - for codec in self: - byte_length = codec.compute_encoded_size(byte_length, array_spec) - array_spec = codec.resolve_metadata(array_spec) - return byte_length - - def _codecs_with_resolved_metadata_batched( - self, chunk_specs: Iterable[ArraySpec] - ) -> tuple[ - list[tuple[ArrayArrayCodec, list[ArraySpec]]], - tuple[ArrayBytesCodec, list[ArraySpec]], - list[tuple[BytesBytesCodec, list[ArraySpec]]], - ]: - aa_codecs_with_spec: list[tuple[ArrayArrayCodec, list[ArraySpec]]] = [] - chunk_specs = list(chunk_specs) - for aa_codec in self.array_array_codecs: - aa_codecs_with_spec.append((aa_codec, chunk_specs)) - chunk_specs = [aa_codec.resolve_metadata(chunk_spec) for chunk_spec in chunk_specs] - - ab_codec_with_spec = (self.array_bytes_codec, chunk_specs) - chunk_specs = [ - self.array_bytes_codec.resolve_metadata(chunk_spec) for chunk_spec in chunk_specs - ] - - bb_codecs_with_spec: list[tuple[BytesBytesCodec, list[ArraySpec]]] = [] - for bb_codec in self.bytes_bytes_codecs: - bb_codecs_with_spec.append((bb_codec, chunk_specs)) - chunk_specs = [bb_codec.resolve_metadata(chunk_spec) for chunk_spec in chunk_specs] - - return (aa_codecs_with_spec, ab_codec_with_spec, bb_codecs_with_spec) - - async def decode_batch( - self, - chunk_bytes_and_specs: Iterable[tuple[Buffer | None, ArraySpec]], - ) -> Iterable[NDBuffer | None]: - chunk_bytes_batch: Iterable[Buffer | None] - chunk_bytes_batch, chunk_specs = _unzip2(chunk_bytes_and_specs) - - ( - aa_codecs_with_spec, - ab_codec_with_spec, - bb_codecs_with_spec, - ) = self._codecs_with_resolved_metadata_batched(chunk_specs) - - for bb_codec, chunk_spec_batch in bb_codecs_with_spec[::-1]: - chunk_bytes_batch = await bb_codec.decode( - zip(chunk_bytes_batch, chunk_spec_batch, strict=False) - ) - - ab_codec, chunk_spec_batch = ab_codec_with_spec - chunk_array_batch = await ab_codec.decode( - zip(chunk_bytes_batch, chunk_spec_batch, strict=False) - ) - - for aa_codec, chunk_spec_batch in aa_codecs_with_spec[::-1]: - chunk_array_batch = await aa_codec.decode( - zip(chunk_array_batch, chunk_spec_batch, strict=False) - ) - - return chunk_array_batch - - async def decode_partial_batch( - self, - batch_info: Iterable[tuple[ByteGetter, SelectorTuple, ArraySpec]], - ) -> Iterable[NDBuffer | None]: - assert self.supports_partial_decode - assert isinstance(self.array_bytes_codec, ArrayBytesCodecPartialDecodeMixin) - return await self.array_bytes_codec.decode_partial(batch_info) - - async def encode_batch( - self, - chunk_arrays_and_specs: Iterable[tuple[NDBuffer | None, ArraySpec]], - ) -> Iterable[Buffer | None]: - chunk_array_batch: Iterable[NDBuffer | None] - chunk_specs: Iterable[ArraySpec] - chunk_array_batch, chunk_specs = _unzip2(chunk_arrays_and_specs) - - for aa_codec in self.array_array_codecs: - chunk_array_batch = await aa_codec.encode( - zip(chunk_array_batch, chunk_specs, strict=False) - ) - chunk_specs = resolve_batched(aa_codec, chunk_specs) - - chunk_bytes_batch = await self.array_bytes_codec.encode( - zip(chunk_array_batch, chunk_specs, strict=False) - ) - chunk_specs = resolve_batched(self.array_bytes_codec, chunk_specs) - - for bb_codec in self.bytes_bytes_codecs: - chunk_bytes_batch = await bb_codec.encode( - zip(chunk_bytes_batch, chunk_specs, strict=False) - ) - chunk_specs = resolve_batched(bb_codec, chunk_specs) - - return chunk_bytes_batch - - async def encode_partial_batch( - self, - batch_info: Iterable[tuple[ByteSetter, NDBuffer, SelectorTuple, ArraySpec]], - ) -> None: - assert self.supports_partial_encode - assert isinstance(self.array_bytes_codec, ArrayBytesCodecPartialEncodeMixin) - await self.array_bytes_codec.encode_partial(batch_info) - - async def read_batch( - self, - batch_info: Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple]], - out: NDBuffer, - drop_axes: tuple[int, ...] = (), - ) -> None: - if self.supports_partial_decode: - chunk_array_batch = await self.decode_partial_batch( - [ - (byte_getter, chunk_selection, chunk_spec) - for byte_getter, chunk_spec, chunk_selection, _ in batch_info - ] - ) - for chunk_array, (_, chunk_spec, _, out_selection) in zip( - chunk_array_batch, batch_info, strict=False - ): - if chunk_array is not None: - out[out_selection] = chunk_array - else: - out[out_selection] = chunk_spec.fill_value - else: - chunk_bytes_batch = await concurrent_map( - [ - (byte_getter, array_spec.prototype) - for byte_getter, array_spec, _, _ in batch_info - ], - lambda byte_getter, prototype: byte_getter.get(prototype), - config.get("async.concurrency"), - ) - chunk_array_batch = await self.decode_batch( - [ - (chunk_bytes, chunk_spec) - for chunk_bytes, (_, chunk_spec, _, _) in zip( - chunk_bytes_batch, batch_info, strict=False - ) - ], - ) - for chunk_array, (_, chunk_spec, chunk_selection, out_selection) in zip( - chunk_array_batch, batch_info, strict=False - ): - if chunk_array is not None: - tmp = chunk_array[chunk_selection] - if drop_axes != (): - tmp = tmp.squeeze(axis=drop_axes) - out[out_selection] = tmp - else: - out[out_selection] = chunk_spec.fill_value - - def _merge_chunk_array( - self, - existing_chunk_array: NDBuffer | None, - value: NDBuffer, - out_selection: SelectorTuple, - chunk_spec: ArraySpec, - chunk_selection: SelectorTuple, - drop_axes: tuple[int, ...], - ) -> NDBuffer: - if is_total_slice(chunk_selection, chunk_spec.shape) and value.shape == chunk_spec.shape: - return value - if existing_chunk_array is None: - chunk_array = chunk_spec.prototype.nd_buffer.create( - shape=chunk_spec.shape, - dtype=chunk_spec.dtype, - order=chunk_spec.order, - fill_value=chunk_spec.fill_value, - ) - else: - chunk_array = existing_chunk_array.copy() # make a writable copy - if chunk_selection == () or is_scalar(value.as_ndarray_like(), chunk_spec.dtype): - chunk_value = value - else: - chunk_value = value[out_selection] - # handle missing singleton dimensions - if drop_axes != (): - item = tuple( - None # equivalent to np.newaxis - if idx in drop_axes - else slice(None) - for idx in range(chunk_spec.ndim) - ) - chunk_value = chunk_value[item] - chunk_array[chunk_selection] = chunk_value - return chunk_array - - async def write_batch( - self, - batch_info: Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple]], - value: NDBuffer, - drop_axes: tuple[int, ...] = (), - ) -> None: - if self.supports_partial_encode: - await self.encode_partial_batch( - [ - (byte_setter, value[out_selection], chunk_selection, chunk_spec) - for byte_setter, chunk_spec, chunk_selection, out_selection in batch_info - ], - ) - - else: - # Read existing bytes if not total slice - async def _read_key( - byte_setter: ByteSetter | None, prototype: BufferPrototype - ) -> Buffer | None: - if byte_setter is None: - return None - return await byte_setter.get(prototype=prototype) - - chunk_bytes_batch: Iterable[Buffer | None] - chunk_bytes_batch = await concurrent_map( - [ - ( - None if is_total_slice(chunk_selection, chunk_spec.shape) else byte_setter, - chunk_spec.prototype, - ) - for byte_setter, chunk_spec, chunk_selection, _ in batch_info - ], - _read_key, - config.get("async.concurrency"), - ) - chunk_array_batch = await self.decode_batch( - [ - (chunk_bytes, chunk_spec) - for chunk_bytes, (_, chunk_spec, _, _) in zip( - chunk_bytes_batch, batch_info, strict=False - ) - ], - ) - - chunk_array_batch = [ - self._merge_chunk_array( - chunk_array, value, out_selection, chunk_spec, chunk_selection, drop_axes - ) - for chunk_array, (_, chunk_spec, chunk_selection, out_selection) in zip( - chunk_array_batch, batch_info, strict=False - ) - ] - - chunk_array_batch = [ - None - if chunk_array is None or chunk_array.all_equal(chunk_spec.fill_value) - else chunk_array - for chunk_array, (_, chunk_spec, _, _) in zip( - chunk_array_batch, batch_info, strict=False - ) - ] - - chunk_bytes_batch = await self.encode_batch( - [ - (chunk_array, chunk_spec) - for chunk_array, (_, chunk_spec, _, _) in zip( - chunk_array_batch, batch_info, strict=False - ) - ], - ) - - async def _write_key(byte_setter: ByteSetter, chunk_bytes: Buffer | None) -> None: - if chunk_bytes is None: - await byte_setter.delete() - else: - await byte_setter.set(chunk_bytes) - - await concurrent_map( - [ - (byte_setter, chunk_bytes) - for chunk_bytes, (byte_setter, _, _, _) in zip( - chunk_bytes_batch, batch_info, strict=False - ) - ], - _write_key, - config.get("async.concurrency"), - ) - - async def decode( - self, - chunk_bytes_and_specs: Iterable[tuple[Buffer | None, ArraySpec]], - ) -> Iterable[NDBuffer | None]: - output: list[NDBuffer | None] = [] - for batch_info in batched(chunk_bytes_and_specs, self.batch_size): - output.extend(await self.decode_batch(batch_info)) - return output - - async def encode( - self, - chunk_arrays_and_specs: Iterable[tuple[NDBuffer | None, ArraySpec]], - ) -> Iterable[Buffer | None]: - output: list[Buffer | None] = [] - for single_batch_info in batched(chunk_arrays_and_specs, self.batch_size): - output.extend(await self.encode_batch(single_batch_info)) - return output - - async def read( - self, - batch_info: Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple]], - out: NDBuffer, - drop_axes: tuple[int, ...] = (), - ) -> None: - await concurrent_map( - [ - (single_batch_info, out, drop_axes) - for single_batch_info in batched(batch_info, self.batch_size) - ], - self.read_batch, - config.get("async.concurrency"), - ) - - async def write( - self, - batch_info: Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple]], - value: NDBuffer, - drop_axes: tuple[int, ...] = (), - ) -> None: - await concurrent_map( - [ - (single_batch_info, value, drop_axes) - for single_batch_info in batched(batch_info, self.batch_size) - ], - self.write_batch, - config.get("async.concurrency"), - ) - - -def codecs_from_list( - codecs: Iterable[Codec], -) -> tuple[tuple[ArrayArrayCodec, ...], ArrayBytesCodec, tuple[BytesBytesCodec, ...]]: - from zarr.codecs.sharding import ShardingCodec - - array_array: tuple[ArrayArrayCodec, ...] = () - array_bytes_maybe: ArrayBytesCodec | None = None - bytes_bytes: tuple[BytesBytesCodec, ...] = () - - if any(isinstance(codec, ShardingCodec) for codec in codecs) and len(tuple(codecs)) > 1: - warn( - "Combining a `sharding_indexed` codec disables partial reads and " - "writes, which may lead to inefficient performance.", - stacklevel=3, - ) - - for prev_codec, cur_codec in pairwise((None, *codecs)): - if isinstance(cur_codec, ArrayArrayCodec): - if isinstance(prev_codec, ArrayBytesCodec | BytesBytesCodec): - msg = ( - f"Invalid codec order. ArrayArrayCodec {cur_codec}" - "must be preceded by another ArrayArrayCodec. " - f"Got {type(prev_codec)} instead." - ) - raise ValueError(msg) - array_array += (cur_codec,) - - elif isinstance(cur_codec, ArrayBytesCodec): - if isinstance(prev_codec, BytesBytesCodec): - msg = ( - f"Invalid codec order. ArrayBytes codec {cur_codec}" - f" must be preceded by an ArrayArrayCodec. Got {type(prev_codec)} instead." - ) - raise ValueError(msg) - - if array_bytes_maybe is not None: - msg = ( - f"Got two instances of ArrayBytesCodec: {array_bytes_maybe} and {cur_codec}. " - "Only one array-to-bytes codec is allowed." - ) - raise ValueError(msg) - - array_bytes_maybe = cur_codec - - elif isinstance(cur_codec, BytesBytesCodec): - if isinstance(prev_codec, ArrayArrayCodec): - msg = ( - f"Invalid codec order. BytesBytesCodec {cur_codec}" - "must be preceded by either another BytesBytesCodec, or an ArrayBytesCodec. " - f"Got {type(prev_codec)} instead." - ) - bytes_bytes += (cur_codec,) - else: - raise AssertionError - - if array_bytes_maybe is None: - raise ValueError("Required ArrayBytesCodec was not found.") - else: - return array_array, array_bytes_maybe, bytes_bytes - - -register_pipeline(BatchedCodecPipeline) diff --git a/src/zarr/codecs/scale_offset.py b/src/zarr/codecs/scale_offset.py new file mode 100644 index 0000000000..f2908da1b6 --- /dev/null +++ b/src/zarr/codecs/scale_offset.py @@ -0,0 +1,418 @@ +from __future__ import annotations + +from dataclasses import dataclass, replace +from typing import TYPE_CHECKING, Any, cast + +import numpy as np +import numpy.typing as npt + +from zarr.abc.codec import ArrayArrayCodec +from zarr.core.common import JSON, parse_named_configuration + +if TYPE_CHECKING: + from typing import Self + + from zarr.core.array_spec import ArraySpec + from zarr.core.buffer import NDBuffer + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType + from zarr.core.metadata.v3 import ChunkGridMetadata + + +_WIDE_INT = np.dtype(np.int64) + + +def _encode_fits_natively(dtype: np.dtype[Any], offset: int, scale: int) -> bool: + """Static range proof: is ``(x - offset) * scale`` always in range for every ``x`` in dtype? + + Uses Python ints (unbounded) to avoid overflow in the proof itself. + """ + info = np.iinfo(dtype) + d_lo = int(info.min) - offset + d_hi = int(info.max) - offset + # Taking min/max of both products handles negative scale without a sign branch. + products = (d_lo * scale, d_hi * scale) + lo, hi = min(products), max(products) + return info.min <= lo and hi <= info.max + + +def _decode_fits_natively(dtype: np.dtype[Any], offset: int, scale: int) -> bool: + """Static range proof for decode: is ``x // scale + offset`` always in range?""" + info = np.iinfo(dtype) + # x // scale is bounded by the extremes of x / scale (integer division stays within that range) + if scale > 0: + q_lo, q_hi = int(info.min) // scale, int(info.max) // scale + else: + q_lo, q_hi = int(info.max) // scale, int(info.min) // scale + lo, hi = q_lo + offset, q_hi + offset + return info.min <= lo and hi <= info.max + + +def _check_int_range( + values: npt.NDArray[np.integer[Any]], target: np.dtype[np.integer[Any]] +) -> None: + """Raise if any value is outside the representable range of ``target``. + + Uses a single min/max pass instead of two ``np.any`` passes. + """ + info = np.iinfo(target) + lo, hi = values.min(), values.max() + if lo < info.min or hi > info.max: + raise ValueError( + f"scale_offset produced a value outside the range of dtype {target} " + f"[{info.min}, {info.max}]." + ) + + +def _check_exact_division( + arr: npt.NDArray[np.integer[Any]], scale: np.integer[Any], scale_repr: object +) -> None: + """Raise ValueError if ``arr`` has any element not exactly divisible by ``scale``.""" + if np.any(arr % scale): + raise ValueError( + f"scale_offset decode produced a non-zero remainder when dividing by " + f"scale={scale_repr!r}; result is not exactly representable in dtype {arr.dtype}." + ) + + +def _encode_int_native( + arr: npt.NDArray[np.integer[Any]], offset: np.integer[Any], scale: np.integer[Any] +) -> npt.NDArray[np.integer[Any]]: + """Compute ``(arr - offset) * scale`` directly in ``arr.dtype``. + + This is the fast path; it exists only as a separate function to make the contract with + ``_encode_fits_natively`` explicit: the caller must have already proved that no ``x`` in + ``arr.dtype``'s range can overflow, so we can skip widening and range-checking entirely. + Using it without that proof would silently wrap on overflow. + """ + return cast("npt.NDArray[np.integer[Any]]", (arr - offset) * scale) + + +def _encode_int_widened( + arr: npt.NDArray[np.integer[Any]], offset: np.integer[Any], scale: np.integer[Any] +) -> npt.NDArray[np.integer[Any]]: + """Overflow-checked integer encode for int8..int64 and uint8..uint32. + + Exists because numpy integer arithmetic silently wraps on overflow, which the spec + forbids. We widen to int64, perform the arithmetic there (int64 holds the product of any + two values from these dtypes), range-check against the target dtype, then cast back. + uint64 cannot use this path because its range exceeds int64 β€” see ``_encode_uint64``. + """ + wide_arr = arr.astype(_WIDE_INT, copy=False) + result = (wide_arr - _WIDE_INT.type(offset)) * _WIDE_INT.type(scale) + _check_int_range(result, arr.dtype) + return result.astype(arr.dtype, copy=False) + + +def _encode_float( + arr: npt.NDArray[np.floating[Any]], offset: np.floating[Any], scale: np.floating[Any] +) -> npt.NDArray[np.floating[Any]]: + """Encode float arrays in-dtype, guarding only against silent promotion. + + Float arithmetic doesn't need widening β€” float64 is already the widest supported dtype, + and ``inf``/``nan`` from overflow are representable IEEE 754 values, so no range check is + required by the spec. The one thing that can still go wrong is numpy promoting the + result to a wider float dtype (e.g. float32 * float64 scalar -> float64), which would + violate the spec's "arithmetic semantics of the input array's data type" clause. + """ + result = cast("npt.NDArray[np.floating[Any]]", (arr - offset) * scale) + if result.dtype != arr.dtype: + raise ValueError( + f"scale_offset changed dtype from {arr.dtype} to {result.dtype}. " + f"Arithmetic must preserve the data type." + ) + return result + + +def _check_py_int_range( + result: np.ndarray[tuple[Any, ...], np.dtype[Any]], + target: np.dtype[np.unsignedinteger[Any]], +) -> None: + """Range-check an ``object``-dtype ndarray holding Python ints against ``target``'s iinfo. + + Exists as a uint64-specific counterpart to ``_check_int_range``. That one compares numpy + integers against ``iinfo``; here the values are unbounded Python ints produced by + ``_encode_uint64`` / ``_decode_uint64``, so we rely on Python's arbitrary-precision + comparison to detect values outside the target dtype's range. + """ + info = np.iinfo(target) + # np.min/np.max on an object array returns a Python int (which compares correctly with iinfo). + # Works uniformly for 0-d arrays where .flat iteration is awkward. + lo = np.min(result) + hi = np.max(result) + if lo < int(info.min) or hi > int(info.max): + raise ValueError( + f"scale_offset produced a value outside the range of dtype {target} " + f"[{info.min}, {info.max}]." + ) + + +def _encode_uint64( + arr: npt.NDArray[np.unsignedinteger[Any]], offset: int, scale: int +) -> npt.NDArray[np.unsignedinteger[Any]]: + """Encode uint64 via Python-int arithmetic in an ``object``-dtype array. + + Exists because uint64's range [0, 2**64) exceeds int64, so the int64 widening used by + ``_encode_int_widened`` would itself overflow. Python ints are unbounded, so computing + via ``object`` dtype is correct by construction. The trade-off is speed: object-dtype + arithmetic is interpreted per element and is roughly 10x slower than ufunc paths. + """ + obj = arr.astype(object, copy=False) + # np.asarray restores ndarray-ness in the 0-d/scalar edge case. + result = np.asarray((obj - offset) * scale, dtype=object) + _check_py_int_range(result, arr.dtype) + return cast("npt.NDArray[np.unsignedinteger[Any]]", result.astype(arr.dtype, copy=False)) + + +def _decode_uint64( + arr: npt.NDArray[np.unsignedinteger[Any]], offset: int, scale: int +) -> npt.NDArray[np.unsignedinteger[Any]]: + """Decode uint64 via Python-int arithmetic. See ``_encode_uint64`` for why.""" + obj = arr.astype(object, copy=False) + result = np.asarray((obj // scale) + offset, dtype=object) + _check_py_int_range(result, arr.dtype) + return cast("npt.NDArray[np.unsignedinteger[Any]]", result.astype(arr.dtype, copy=False)) + + +def _decode_int_native( + arr: npt.NDArray[np.integer[Any]], offset: np.integer[Any], scale: np.integer[Any] +) -> npt.NDArray[np.integer[Any]]: + """Compute ``arr // scale + offset`` directly in ``arr.dtype``. + + Fast-path counterpart to ``_encode_int_native``; same contract. Caller must have proved + via ``_decode_fits_natively`` that the result can't overflow. Divisibility is checked + upstream in ``_decode`` before this is called, so ``//`` is exact here. + """ + return cast("npt.NDArray[np.integer[Any]]", (arr // scale) + offset) + + +def _decode_int_widened( + arr: npt.NDArray[np.integer[Any]], offset: np.integer[Any], scale: np.integer[Any] +) -> npt.NDArray[np.integer[Any]]: + """Overflow-checked integer decode for int8..int64 and uint8..uint32. + + Counterpart to ``_encode_int_widened``. Widens to int64 so the addition of ``offset`` + after division can't silently wrap, then range-checks against the target dtype. + """ + wide_arr = arr.astype(_WIDE_INT, copy=False) + result = (wide_arr // _WIDE_INT.type(scale)) + _WIDE_INT.type(offset) + _check_int_range(result, arr.dtype) + return result.astype(arr.dtype, copy=False) + + +def _decode_float( + arr: npt.NDArray[np.floating[Any]], offset: np.floating[Any], scale: np.floating[Any] +) -> npt.NDArray[np.floating[Any]]: + """Decode float arrays in-dtype, guarding only against silent promotion. + + Counterpart to ``_encode_float``; same reasoning. ``arr / scale`` is true division and + always well-defined for floats (including ``0/0 = nan`` and ``x/0 = Β±inf``), so no range + or exactness check is needed. + """ + result = cast("npt.NDArray[np.floating[Any]]", (arr / scale) + offset) + if result.dtype != arr.dtype: + raise ValueError( + f"scale_offset changed dtype from {arr.dtype} to {result.dtype}. " + f"Arithmetic must preserve the data type." + ) + return result + + +def _encode( + arr: np.ndarray[tuple[Any, ...], np.dtype[Any]], + offset: np.generic, + scale: np.generic, +) -> np.ndarray[tuple[Any, ...], np.dtype[Any]]: + """Compute ``(arr - offset) * scale`` without silent overflow, returning ``arr.dtype``.""" + # uint64 is split out first because its full range (up to 2**64-1) doesn't fit in int64, + # so the widening strategy used for every other integer dtype would itself overflow. + if arr.dtype == np.uint64: + u_arr = cast("npt.NDArray[np.unsignedinteger[Any]]", arr) + return _encode_uint64(u_arr, int(offset), int(scale)) + if np.issubdtype(arr.dtype, np.integer): + i_arr = cast("npt.NDArray[np.integer[Any]]", arr) + i_offset = cast("np.integer[Any]", offset) + i_scale = cast("np.integer[Any]", scale) + # Fast path: if a static proof shows no ``x`` in the dtype's range can overflow, + # skip the int64 widening and run the arithmetic directly in the input dtype. + if _encode_fits_natively(arr.dtype, int(offset), int(scale)): + return _encode_int_native(i_arr, i_offset, i_scale) + return _encode_int_widened(i_arr, i_offset, i_scale) + # Float path: arithmetic stays in-dtype (no widening); only guard against numpy + # silently promoting a narrower float to a wider one via scalar type mismatch. + f_arr = cast("npt.NDArray[np.floating[Any]]", arr) + f_offset = cast("np.floating[Any]", offset) + f_scale = cast("np.floating[Any]", scale) + return _encode_float(f_arr, f_offset, f_scale) + + +def _decode( + arr: np.ndarray[tuple[Any, ...], np.dtype[Any]], + offset: np.generic, + scale: np.generic, + *, + scale_repr: object, +) -> np.ndarray[tuple[Any, ...], np.dtype[Any]]: + """Compute ``arr / scale + offset`` without silent overflow, returning ``arr.dtype``.""" + # uint64: same reasoning as _encode β€” its range exceeds int64, so the Python-int path is the + # only correct option. Exactness check runs first so non-divisible inputs fail before the + # slower object-dtype arithmetic. + if arr.dtype == np.uint64: + u_arr = cast("npt.NDArray[np.unsignedinteger[Any]]", arr) + _check_exact_division(u_arr, cast("np.integer[Any]", scale), scale_repr) + return _decode_uint64(u_arr, int(offset), int(scale)) + if np.issubdtype(arr.dtype, np.integer): + i_arr = cast("npt.NDArray[np.integer[Any]]", arr) + i_offset = cast("np.integer[Any]", offset) + i_scale = cast("np.integer[Any]", scale) + # The spec requires decode to use true division and error if the result isn't + # representable. For integers that means the remainder must be zero; if any element + # isn't exactly divisible we fail here rather than silently truncating via //. + _check_exact_division(i_arr, i_scale, scale_repr) + # Fast path mirrors _encode: static proof that ``x // scale + offset`` stays in dtype. + if _decode_fits_natively(arr.dtype, int(offset), int(scale)): + return _decode_int_native(i_arr, i_offset, i_scale) + return _decode_int_widened(i_arr, i_offset, i_scale) + # Float path: division is well-defined; only guard against dtype promotion. + f_arr = cast("npt.NDArray[np.floating[Any]]", arr) + f_offset = cast("np.floating[Any]", offset) + f_scale = cast("np.floating[Any]", scale) + return _decode_float(f_arr, f_offset, f_scale) + + +@dataclass(frozen=True) +class ScaleOffset(ArrayArrayCodec): + """Scale-offset array-to-array codec. + + Encodes values with `out = (in - offset) * scale` and decodes with + `out = (in / scale) + offset`, using the input array's data type semantics. + Intermediate or final values that are not representable in that dtype are reported + as errors (integer overflow, unsigned underflow, non-exact integer division). + + Parameters + ---------- + offset : int, float, or str + Value subtracted during encoding. Strings preserve the exact JSON + representation when round-tripping metadata. Default is 0. + scale : int, float, or str + Value multiplied during encoding (after offset subtraction). Strings + preserve the exact JSON representation when round-tripping metadata. + Default is 1. + + Attributes + ---------- + offset : int, float, or str + The offset value, as supplied to the constructor. + scale : int, float, or str + The scale value, as supplied to the constructor. + + References + ---------- + + - The `scale_offset` codec spec: https://github.com/zarr-developers/zarr-extensions/tree/main/codecs/scale_offset + """ + + is_fixed_size = True + + offset: int | float | str + scale: int | float | str + + def __init__(self, *, offset: object = 0, scale: object = 1) -> None: + if not isinstance(offset, int | float | str): + raise TypeError(f"offset must be a number or string, got {type(offset).__name__}") + if not isinstance(scale, int | float | str): + raise TypeError(f"scale must be a number or string, got {type(scale).__name__}") + object.__setattr__(self, "offset", offset) + object.__setattr__(self, "scale", scale) + + @classmethod + def from_dict(cls, data: dict[str, JSON]) -> Self: + _, configuration_parsed = parse_named_configuration( + data, "scale_offset", require_configuration=False + ) + configuration_parsed = configuration_parsed or {} + return cls(**configuration_parsed) + + def to_dict(self) -> dict[str, JSON]: + if self.offset == 0 and self.scale == 1: + return {"name": "scale_offset"} + config: dict[str, JSON] = {} + if self.offset != 0: + config["offset"] = self.offset + if self.scale != 1: + config["scale"] = self.scale + return {"name": "scale_offset", "configuration": config} + + def validate( + self, + *, + shape: tuple[int, ...], + dtype: ZDType[TBaseDType, TBaseScalar], + chunk_grid: ChunkGridMetadata, + ) -> None: + native = dtype.to_native_dtype() + if not np.issubdtype(native, np.integer) and not np.issubdtype(native, np.floating): + raise ValueError( + f"scale_offset codec only supports integer and floating-point data types. " + f"Got {dtype}." + ) + parsed: dict[str, Any] = {} + for name, value in [("offset", self.offset), ("scale", self.scale)]: + try: + parsed[name] = dtype.from_json_scalar(value, zarr_format=3) + except (TypeError, ValueError, OverflowError) as e: + raise ValueError( + f"scale_offset {name} value {value!r} is not representable in dtype {native}." + ) from e + # ``scale`` may be given as a string, and no string is ever ``== 0``, so this has to + # compare the parsed scalar rather than the value as supplied. + if parsed["scale"] == 0: + raise ValueError("scale_offset scale must be non-zero.") + + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + zdtype = chunk_spec.dtype + fill = np.asarray(zdtype.cast_scalar(chunk_spec.fill_value)) + offset = cast("np.generic", zdtype.from_json_scalar(self.offset, zarr_format=3)) + scale = cast("np.generic", zdtype.from_json_scalar(self.scale, zarr_format=3)) + new_fill = _encode(fill, offset, scale) + return replace(chunk_spec, fill_value=new_fill.reshape(()).item()) + + def _decode_sync( + self, + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + ) -> NDBuffer: + arr = cast("np.ndarray[tuple[Any, ...], np.dtype[Any]]", chunk_array.as_ndarray_like()) + zdtype = chunk_spec.dtype + offset = cast("np.generic", zdtype.from_json_scalar(self.offset, zarr_format=3)) + scale = cast("np.generic", zdtype.from_json_scalar(self.scale, zarr_format=3)) + result = _decode(arr, offset, scale, scale_repr=self.scale) + return chunk_spec.prototype.nd_buffer.from_ndarray_like(result) + + async def _decode_single( + self, + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + ) -> NDBuffer: + return self._decode_sync(chunk_array, chunk_spec) + + def _encode_sync( + self, + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + ) -> NDBuffer | None: + arr = cast("np.ndarray[tuple[Any, ...], np.dtype[Any]]", chunk_array.as_ndarray_like()) + zdtype = chunk_spec.dtype + offset = cast("np.generic", zdtype.from_json_scalar(self.offset, zarr_format=3)) + scale = cast("np.generic", zdtype.from_json_scalar(self.scale, zarr_format=3)) + result = _encode(arr, offset, scale) + return chunk_spec.prototype.nd_buffer.from_ndarray_like(result) + + async def _encode_single( + self, + chunk_array: NDBuffer, + _chunk_spec: ArraySpec, + ) -> NDBuffer | None: + return self._encode_sync(chunk_array, _chunk_spec) + + def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: + return input_byte_length diff --git a/src/zarr/codecs/sharding.py b/src/zarr/codecs/sharding.py index ef8b80c02d..41780e45b4 100644 --- a/src/zarr/codecs/sharding.py +++ b/src/zarr/codecs/sharding.py @@ -1,11 +1,9 @@ from __future__ import annotations -from collections.abc import Iterable, Mapping, MutableMapping -from dataclasses import dataclass, field, replace -from enum import Enum +from collections.abc import Iterable, Mapping, MutableMapping, Sequence +from dataclasses import dataclass, replace from functools import lru_cache -from operator import itemgetter -from typing import TYPE_CHECKING, Any, NamedTuple +from typing import TYPE_CHECKING, Any, ClassVar, Final, Literal, NamedTuple import numpy as np import numpy.typing as npt @@ -16,91 +14,204 @@ ArrayBytesCodecPartialEncodeMixin, Codec, CodecPipeline, + _codec_supports_sync, ) -from zarr.abc.store import ByteGetter, ByteSetter -from zarr.array_spec import ArraySpec -from zarr.buffer import ( +from zarr.abc.store import ( + ByteGetter, + ByteRequest, + ByteSetter, + RangeByteRequest, + Store, + SuffixByteRequest, + _store_supports_sync_io, +) +from zarr.codecs._deprecated_enum import _coerce_enum_input, _DeprecatedStrEnumMeta +from zarr.codecs.bytes import BytesCodec +from zarr.codecs.crc32c_ import Crc32cCodec +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import ( Buffer, BufferPrototype, NDBuffer, default_buffer_prototype, numpy_buffer_prototype, ) -from zarr.chunk_grids import ChunkGrid, RegularChunkGrid -from zarr.codecs.bytes import BytesCodec -from zarr.codecs.crc32c_ import Crc32cCodec -from zarr.common import ( - ChunkCoords, - ChunkCoordsLike, - parse_enum, +from zarr.core.chunk_grids import ChunkGrid +from zarr.core.chunk_utils import ( + ChunkTransform, + decode_and_scatter_chunk, + encode_or_elide_chunk, + evolve_codecs, + merge_and_encode_chunk, +) +from zarr.core.common import ( + ShapeLike, parse_named_configuration, parse_shapelike, product, ) -from zarr.indexing import BasicIndexer, SelectorTuple, c_order_iter, get_indexer, morton_order_iter -from zarr.metadata import parse_codecs -from zarr.registry import get_ndbuffer_class, get_pipeline_class, register_codec +from zarr.core.config import config as zarr_config +from zarr.core.dtype.common import HasEndianness +from zarr.core.dtype.npy.int import UInt64 +from zarr.core.dtype.npy.structured import Struct +from zarr.core.indexing import ( + BasicIndexer, + ChunkProjection, + SelectorTuple, + SliceDimIndexer, + _lexicographic_order, + colexicographic_order_coords, + get_indexer, + lexicographic_order_coords, + morton_order_coords, +) +from zarr.core.metadata.v3 import ( + ChunkGridMetadata, + RectilinearChunkGridMetadata, + RegularChunkGridMetadata, + parse_codecs, +) +from zarr.registry import get_ndbuffer_class, get_pipeline_class +from zarr.storage._common import StorePath +from zarr.storage._utils import _normalize_byte_range_index if TYPE_CHECKING: - from collections.abc import Awaitable, Callable, Iterator - - from typing_extensions import Self + from collections.abc import Iterator + from typing import Self - from zarr.common import JSON + from zarr.core.common import JSON + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType MAX_UINT_64 = 2**64 - 1 -ShardMapping = Mapping[ChunkCoords, Buffer] -ShardMutableMapping = MutableMapping[ChunkCoords, Buffer] +ShardMapping = Mapping[tuple[int, ...], Buffer | None] +ShardMutableMapping = MutableMapping[tuple[int, ...], Buffer | None] -class ShardingCodecIndexLocation(Enum): - start = "start" - end = "end" +IndexLocation = Literal["start", "end"] +"""Position of the shard index within the encoded shard.""" +INDEX_LOCATION: Final = ("start", "end") -def parse_index_location(data: JSON) -> ShardingCodecIndexLocation: - return parse_enum(data, ShardingCodecIndexLocation) + +class ShardingCodecIndexLocation(metaclass=_DeprecatedStrEnumMeta): + """ + Deprecated. Pass a literal string (`"start"` or `"end"`) directly to + `ShardingCodec` instead. + """ + + _members: ClassVar[dict[str, str]] = {"start": "start", "end": "end"} + + +SubchunkWriteOrder = Literal["morton", "unordered", "lexicographic", "colexicographic"] +SUBCHUNK_WRITE_ORDER: Final[tuple[str, str, str, str]] = ( + "morton", + "unordered", + "lexicographic", + "colexicographic", +) + + +def _is_identity_full_read(indexer: Any, shard_shape: tuple[int, ...]) -> bool: + """True when `indexer` selects every element of a `shard_shape` array in + natural order: one whole-dimension, step-1 `SliceDimIndexer` per dimension. + + Structural on purpose, not `isinstance(indexer, BasicIndexer)`: a full + `arr[:]` read reaches the shard as an `OrthogonalIndexer`, so a type gate + would silently disable the bulk fast path for the most common case. Any + gather (integer-array / boolean / coordinate selection), subset, strided, + or integer-scalar selection fails the per-dimension check β€” output shape + alone is not enough, because a reordering or duplicating selection can have + the same shape as the shard while requiring `chunk_selection` / + `out_selection` to be honored. + """ + dim_indexers = getattr(indexer, "dim_indexers", None) + if dim_indexers is None or len(dim_indexers) != len(shard_shape): + return False + return all( + isinstance(dim_indexer, SliceDimIndexer) + and dim_indexer.dim_len == dim_len + and dim_indexer.start == 0 + and dim_indexer.stop == dim_len + and dim_indexer.step == 1 + for dim_indexer, dim_len in zip(dim_indexers, shard_shape, strict=True) + ) + + +def _parse_index_location(data: object) -> IndexLocation: + if isinstance(data, str) and data in INDEX_LOCATION: + return data # type: ignore[return-value] + raise ValueError(f"index_location must be one of {list(INDEX_LOCATION)!r}. Got {data!r}.") @dataclass(frozen=True) class _ShardingByteGetter(ByteGetter): + """In-memory byte getter for one inner chunk of a shard. + + Implements `SyncByteGetter` (dict access needs no event loop), so the + synchronous codec pipeline takes its sync fast path on inner chunks + instead of scheduling one coroutine per chunk; the async `get` simply + delegates to `get_sync`. + """ + shard_dict: ShardMapping - chunk_coords: ChunkCoords + chunk_coords: tuple[int, ...] + + def get_sync( + self, prototype: BufferPrototype | None = None, byte_range: ByteRequest | None = None + ) -> Buffer | None: + assert prototype is None or prototype == default_buffer_prototype(), ( + f"prototype is not supported within shards currently. diff: {prototype} != {default_buffer_prototype()}" + ) + value = self.shard_dict.get(self.chunk_coords) + if value is None: + return None + if byte_range is None: + return value + start, stop = _normalize_byte_range_index(value, byte_range) + return value[start:stop] async def get( - self, prototype: BufferPrototype, byte_range: tuple[int, int | None] | None = None + self, prototype: BufferPrototype, byte_range: ByteRequest | None = None ) -> Buffer | None: - assert byte_range is None, "byte_range is not supported within shards" - assert ( - prototype == default_buffer_prototype() - ), f"prototype is not supported within shards currently. diff: {prototype} != {default_buffer_prototype()}" - return self.shard_dict.get(self.chunk_coords) + return self.get_sync(prototype, byte_range) @dataclass(frozen=True) class _ShardingByteSetter(_ShardingByteGetter, ByteSetter): + """In-memory byte setter for one inner chunk of a shard. + + Implements `SyncByteSetter`; the async methods delegate to the sync ones. + """ + shard_dict: ShardMutableMapping - async def set(self, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: - assert byte_range is None, "byte_range is not supported within shards" + def set_sync(self, value: Buffer) -> None: self.shard_dict[self.chunk_coords] = value - async def delete(self) -> None: + def delete_sync(self) -> None: del self.shard_dict[self.chunk_coords] + async def set(self, value: Buffer, byte_range: ByteRequest | None = None) -> None: + assert byte_range is None, "byte_range is not supported within shards" + self.set_sync(value) + + async def delete(self) -> None: + self.delete_sync() + + async def set_if_not_exists(self, default: Buffer) -> None: + self.shard_dict.setdefault(self.chunk_coords, default) + class _ShardIndex(NamedTuple): + # the chunk grid shape of a single shard + chunks_per_shard: tuple[int, ...] # dtype uint64, shape (chunks_per_shard_0, chunks_per_shard_1, ..., 2) offsets_and_lengths: npt.NDArray[np.uint64] - @property - def chunks_per_shard(self) -> ChunkCoords: - return self.offsets_and_lengths.shape[0:-1] - - def _localize_chunk(self, chunk_coords: ChunkCoords) -> ChunkCoords: + def _localize_chunk(self, chunk_coords: tuple[int, ...]) -> tuple[int, ...]: return tuple( chunk_i % shard_i - for chunk_i, shard_i in zip(chunk_coords, self.offsets_and_lengths.shape, strict=False) + for chunk_i, shard_i in zip(chunk_coords, self.chunks_per_shard, strict=False) ) def is_all_empty(self) -> bool: @@ -109,15 +220,88 @@ def is_all_empty(self) -> bool: def get_full_chunk_map(self) -> npt.NDArray[np.bool_]: return np.not_equal(self.offsets_and_lengths[..., 0], MAX_UINT_64) - def get_chunk_slice(self, chunk_coords: ChunkCoords) -> tuple[int, int] | None: + def is_dense(self, chunk_byte_length: int, *, data_section_start: int) -> bool: + """True when the chunk payloads exactly tile the shard's data section. + + Every chunk must be present with length `chunk_byte_length`, and the + sorted offsets must be exactly `data_section_start + i * chunk_byte_length` + for `i` in `0..n_chunks-1`: no gaps, no overlaps, and nothing outside the + data section (a corrupt index could otherwise point chunks into the + index region or out of the blob). Used to gate the vectorized + whole-shard decode: a dense fixed-size shard is a regular grid of + equal-length payloads, so it can be reshaped/scattered in bulk rather + than decoded chunk-by-chunk. + """ + offsets = self.offsets_and_lengths[..., 0].reshape(-1) + lengths = self.offsets_and_lengths[..., 1].reshape(-1) + # all present + if bool(np.any(offsets == MAX_UINT_64)): + return False + # all the same fixed length + if not bool(np.all(lengths == chunk_byte_length)): + return False + expected = np.uint64(data_section_start) + np.arange( + offsets.size, dtype=np.uint64 + ) * np.uint64(chunk_byte_length) + return bool(np.array_equal(np.sort(offsets), expected)) + + def get_chunk_slice(self, chunk_coords: tuple[int, ...]) -> tuple[int, int] | None: localized_chunk = self._localize_chunk(chunk_coords) chunk_start, chunk_len = self.offsets_and_lengths[localized_chunk] if (chunk_start, chunk_len) == (MAX_UINT_64, MAX_UINT_64): return None else: - return (int(chunk_start), int(chunk_start) + int(chunk_len)) + return (int(chunk_start), int(chunk_start + chunk_len)) + + def get_chunk_slices_vectorized( + self, chunk_coords_array: npt.NDArray[np.integer[Any]] + ) -> tuple[npt.NDArray[np.uint64], npt.NDArray[np.uint64], npt.NDArray[np.bool_]]: + """Get chunk slices for multiple coordinates at once. + + Parameters + ---------- + chunk_coords_array : ndarray of shape (n_chunks, n_dims) + Array of chunk coordinates to look up. + + Returns + ------- + starts : ndarray of shape (n_chunks,) + Start byte positions for each chunk. + ends : ndarray of shape (n_chunks,) + End byte positions for each chunk. + valid : ndarray of shape (n_chunks,) + Boolean mask indicating which chunks are non-empty. + """ + # Handle 0-dimensional arrays (n_dims == 0): the shard holds a single + # chunk, so every coordinate maps to the same flat entry. + if chunk_coords_array.shape[1] == 0: + offsets_and_lengths = self.offsets_and_lengths.reshape(-1, 2) + offsets_and_lengths = np.broadcast_to( + offsets_and_lengths, (chunk_coords_array.shape[0], 2) + ) + else: + # Localize coordinates via modulo (vectorized) + shard_shape = np.array(self.chunks_per_shard, dtype=np.uint64) + localized = chunk_coords_array.astype(np.uint64) % shard_shape + + # Build index tuple for advanced indexing + index_tuple = tuple(localized[:, i] for i in range(localized.shape[1])) + + # Fetch all offsets and lengths at once + offsets_and_lengths = self.offsets_and_lengths[index_tuple] + + starts = offsets_and_lengths[:, 0] + lengths = offsets_and_lengths[:, 1] + + # Check for valid (non-empty) chunks + valid = starts != MAX_UINT_64 + + # Compute end positions + ends = starts + lengths + + return starts, ends, valid - def set_chunk_slice(self, chunk_coords: ChunkCoords, chunk_slice: slice | None) -> None: + def set_chunk_slice(self, chunk_coords: tuple[int, ...], chunk_slice: slice | None) -> None: localized_chunk = self._localize_chunk(chunk_coords) if chunk_slice is None: self.offsets_and_lengths[localized_chunk] = (MAX_UINT_64, MAX_UINT_64) @@ -127,32 +311,11 @@ def set_chunk_slice(self, chunk_coords: ChunkCoords, chunk_slice: slice | None) chunk_slice.stop - chunk_slice.start, ) - def is_dense(self, chunk_byte_length: int) -> bool: - sorted_offsets_and_lengths = sorted( - [ - (offset, length) - for offset, length in self.offsets_and_lengths - if offset != MAX_UINT_64 - ], - key=itemgetter(0), - ) - - # Are all non-empty offsets unique? - if len( - set(offset for offset, _ in sorted_offsets_and_lengths if offset != MAX_UINT_64) - ) != len(sorted_offsets_and_lengths): - return False - - return all( - offset % chunk_byte_length == 0 and length == chunk_byte_length - for offset, length in sorted_offsets_and_lengths - ) - @classmethod - def create_empty(cls, chunks_per_shard: ChunkCoords) -> _ShardIndex: + def create_empty(cls, chunks_per_shard: tuple[int, ...]) -> _ShardIndex: offsets_and_lengths = np.zeros(chunks_per_shard + (2,), dtype=" _ShardReader: shard_index_size = codec._shard_index_size(chunks_per_shard) obj = cls() obj.buf = buf - if codec.index_location == ShardingCodecIndexLocation.start: + if codec.index_location == "start": shard_index_bytes = obj.buf[:shard_index_size] else: shard_index_bytes = obj.buf[-shard_index_size:] @@ -176,7 +339,7 @@ async def from_bytes( @classmethod def create_empty( - cls, chunks_per_shard: ChunkCoords, buffer_prototype: BufferPrototype | None = None + cls, chunks_per_shard: tuple[int, ...], buffer_prototype: BufferPrototype | None = None ) -> _ShardReader: if buffer_prototype is None: buffer_prototype = default_buffer_prototype() @@ -186,7 +349,7 @@ def create_empty( obj.index = index return obj - def __getitem__(self, chunk_coords: ChunkCoords) -> Buffer: + def __getitem__(self, chunk_coords: tuple[int, ...]) -> Buffer: chunk_byte_slice = self.index.get_chunk_slice(chunk_coords) if chunk_byte_slice: return self.buf[chunk_byte_slice[0] : chunk_byte_slice[1]] @@ -195,164 +358,130 @@ def __getitem__(self, chunk_coords: ChunkCoords) -> Buffer: def __len__(self) -> int: return int(self.index.offsets_and_lengths.size / 2) - def __iter__(self) -> Iterator[ChunkCoords]: - return c_order_iter(self.index.offsets_and_lengths.shape[:-1]) - - def is_empty(self) -> bool: - return self.index.is_all_empty() - - -class _ShardBuilder(_ShardReader, ShardMutableMapping): - buf: Buffer - index: _ShardIndex - - @classmethod - def merge_with_morton_order( - cls, - chunks_per_shard: ChunkCoords, - tombstones: set[ChunkCoords], - *shard_dicts: ShardMapping, - ) -> _ShardBuilder: - obj = cls.create_empty(chunks_per_shard) - for chunk_coords in morton_order_iter(chunks_per_shard): - if chunk_coords in tombstones: - continue - for shard_dict in shard_dicts: - maybe_value = shard_dict.get(chunk_coords, None) - if maybe_value is not None: - obj[chunk_coords] = maybe_value - break - return obj - - @classmethod - def create_empty( - cls, chunks_per_shard: ChunkCoords, buffer_prototype: BufferPrototype | None = None - ) -> _ShardBuilder: - if buffer_prototype is None: - buffer_prototype = default_buffer_prototype() - obj = cls() - obj.buf = buffer_prototype.buffer.create_zero_length() - obj.index = _ShardIndex.create_empty(chunks_per_shard) - return obj - - def __setitem__(self, chunk_coords: ChunkCoords, value: Buffer) -> None: - chunk_start = len(self.buf) - chunk_length = len(value) - self.buf = self.buf + value - self.index.set_chunk_slice(chunk_coords, slice(chunk_start, chunk_start + chunk_length)) - - def __delitem__(self, chunk_coords: ChunkCoords) -> None: - raise NotImplementedError - - async def finalize( - self, - index_location: ShardingCodecIndexLocation, - index_encoder: Callable[[_ShardIndex], Awaitable[Buffer]], - ) -> Buffer: - index_bytes = await index_encoder(self.index) - if index_location == ShardingCodecIndexLocation.start: - self.index.offsets_and_lengths[..., 0] += len(index_bytes) - index_bytes = await index_encoder(self.index) # encode again with corrected offsets - out_buf = index_bytes + self.buf - else: - out_buf = self.buf + index_bytes - return out_buf - - -@dataclass(frozen=True) -class _MergingShardBuilder(ShardMutableMapping): - old_dict: _ShardReader - new_dict: _ShardBuilder - tombstones: set[ChunkCoords] = field(default_factory=set) - - def __getitem__(self, chunk_coords: ChunkCoords) -> Buffer: - chunk_bytes_maybe = self.new_dict.get(chunk_coords) - if chunk_bytes_maybe is not None: - return chunk_bytes_maybe - return self.old_dict[chunk_coords] - - def __setitem__(self, chunk_coords: ChunkCoords, value: Buffer) -> None: - self.new_dict[chunk_coords] = value - - def __delitem__(self, chunk_coords: ChunkCoords) -> None: - self.tombstones.add(chunk_coords) - - def __len__(self) -> int: - return self.old_dict.__len__() - - def __iter__(self) -> Iterator[ChunkCoords]: - return self.old_dict.__iter__() - - def is_empty(self) -> bool: - full_chunk_coords_map = self.old_dict.index.get_full_chunk_map() - full_chunk_coords_map = np.logical_or( - full_chunk_coords_map, self.new_dict.index.get_full_chunk_map() - ) - for tombstone in self.tombstones: - full_chunk_coords_map[tombstone] = False - return bool(np.array_equiv(full_chunk_coords_map, False)) - - async def finalize( - self, - index_location: ShardingCodecIndexLocation, - index_encoder: Callable[[_ShardIndex], Awaitable[Buffer]], - ) -> Buffer: - shard_builder = _ShardBuilder.merge_with_morton_order( - self.new_dict.index.chunks_per_shard, - self.tombstones, - self.new_dict, - self.old_dict, - ) - return await shard_builder.finalize(index_location, index_encoder) + def __iter__(self) -> Iterator[tuple[int, ...]]: + return iter(lexicographic_order_coords(self.index.chunks_per_shard)) + + def to_dict_vectorized(self) -> dict[tuple[int, ...], Buffer | None]: + """Build a dict of chunk coordinates to buffers using vectorized lookup. + + The full per-shard chunk coordinate grid (both the array used for the + vectorized index lookup and the plain tuples used as dict keys) is + cached on `chunks_per_shard`, so neither is rebuilt on every call. For a + shard with tens of thousands of chunks this avoids reconstructing that + many tuples on every partial write. + + Returns + ------- + dict mapping chunk coordinate tuples to Buffer or None + """ + chunks_per_shard = self.index.chunks_per_shard + # The same chunk-grid coordinates are needed in two forms, and neither can + # stand in for the other: + # - `chunk_coords_array`: an (n_chunks, n_dims) numpy array, fed to the + # vectorized index lookup, which does modulo + advanced indexing on it. + # A list of tuples can't be used for that without first being arrayified. + # - `chunk_coords_keys`: the same coordinates as hashable Python tuples, + # used as the result dict's keys. numpy array rows are unhashable + # (mutable), so they can't key a dict. + # Both are cached per shape (see indexing.py), so neither is rebuilt here; + # row i of the array and key i refer to the same chunk. + chunk_coords_array = _lexicographic_order(chunks_per_shard) + chunk_coords_keys = lexicographic_order_coords(chunks_per_shard) + starts, ends, valid = self.index.get_chunk_slices_vectorized(chunk_coords_array) + + result: dict[tuple[int, ...], Buffer | None] = {} + for i, coords in enumerate(chunk_coords_keys): + if valid[i]: + result[coords] = self.buf[int(starts[i]) : int(ends[i])] + else: + result[coords] = None + + return result @dataclass(frozen=True) class ShardingCodec( ArrayBytesCodec, ArrayBytesCodecPartialDecodeMixin, ArrayBytesCodecPartialEncodeMixin ): - chunk_shape: ChunkCoords + """Sharding codec. + + `subchunk_write_order` controls the physical order of subchunks within a shard. It is a + write-time setting only: it is not stored in array metadata, so reopening a sharded array + does not recover it (the setting reverts to the `morton` default per codec instance). + """ + + is_fixed_size = False + + chunk_shape: tuple[int, ...] codecs: tuple[Codec, ...] index_codecs: tuple[Codec, ...] - index_location: ShardingCodecIndexLocation = ShardingCodecIndexLocation.end + index_location: IndexLocation = "end" + subchunk_write_order: SubchunkWriteOrder = "morton" def __init__( self, *, - chunk_shape: ChunkCoordsLike, + chunk_shape: ShapeLike, codecs: Iterable[Codec | dict[str, JSON]] = (BytesCodec(),), index_codecs: Iterable[Codec | dict[str, JSON]] = (BytesCodec(), Crc32cCodec()), - index_location: ShardingCodecIndexLocation = ShardingCodecIndexLocation.end, + index_location: ShardingCodecIndexLocation | IndexLocation = "end", + subchunk_write_order: SubchunkWriteOrder = "morton", ) -> None: chunk_shape_parsed = parse_shapelike(chunk_shape) codecs_parsed = parse_codecs(codecs) index_codecs_parsed = parse_codecs(index_codecs) - index_location_parsed = parse_index_location(index_location) + index_location_coerced = _coerce_enum_input( + index_location, "index_location", "ShardingCodec" + ) + index_location_parsed = _parse_index_location(index_location_coerced) + if subchunk_write_order not in SUBCHUNK_WRITE_ORDER: + raise ValueError( + f"Unrecognized subchunk write order: {subchunk_write_order}. Only {SUBCHUNK_WRITE_ORDER} are allowed." + ) object.__setattr__(self, "chunk_shape", chunk_shape_parsed) object.__setattr__(self, "codecs", codecs_parsed) object.__setattr__(self, "index_codecs", index_codecs_parsed) object.__setattr__(self, "index_location", index_location_parsed) + object.__setattr__(self, "subchunk_write_order", subchunk_write_order) # Use instance-local lru_cache to avoid memory leaks object.__setattr__(self, "_get_chunk_spec", lru_cache()(self._get_chunk_spec)) object.__setattr__(self, "_get_index_chunk_spec", lru_cache()(self._get_index_chunk_spec)) object.__setattr__(self, "_get_chunks_per_shard", lru_cache()(self._get_chunks_per_shard)) + object.__setattr__(self, "_shard_index_size", lru_cache()(self._shard_index_size)) + object.__setattr__( + self, "_get_inner_chunk_transform", lru_cache()(self._get_inner_chunk_transform) + ) + object.__setattr__( + self, "_get_index_chunk_transform", lru_cache()(self._get_index_chunk_transform) + ) # todo: typedict return type def __getstate__(self) -> dict[str, Any]: - return self.to_dict() + # `subchunk_write_order` is not part of codec metadata (`to_dict`), so carry it + # explicitly to survive a pickle round-trip (otherwise it reverts to `morton`). + return {"subchunk_write_order": self.subchunk_write_order, **self.to_dict()} def __setstate__(self, state: dict[str, Any]) -> None: config = state["configuration"] object.__setattr__(self, "chunk_shape", parse_shapelike(config["chunk_shape"])) object.__setattr__(self, "codecs", parse_codecs(config["codecs"])) object.__setattr__(self, "index_codecs", parse_codecs(config["index_codecs"])) - object.__setattr__(self, "index_location", parse_index_location(config["index_location"])) + object.__setattr__(self, "index_location", _parse_index_location(config["index_location"])) + object.__setattr__(self, "subchunk_write_order", state["subchunk_write_order"]) # Use instance-local lru_cache to avoid memory leaks object.__setattr__(self, "_get_chunk_spec", lru_cache()(self._get_chunk_spec)) object.__setattr__(self, "_get_index_chunk_spec", lru_cache()(self._get_index_chunk_spec)) object.__setattr__(self, "_get_chunks_per_shard", lru_cache()(self._get_chunks_per_shard)) + object.__setattr__(self, "_shard_index_size", lru_cache()(self._shard_index_size)) + object.__setattr__( + self, "_get_inner_chunk_transform", lru_cache()(self._get_inner_chunk_transform) + ) + object.__setattr__( + self, "_get_index_chunk_transform", lru_cache()(self._get_index_chunk_transform) + ) @classmethod def from_dict(cls, data: dict[str, JSON]) -> Self: @@ -361,45 +490,487 @@ def from_dict(cls, data: dict[str, JSON]) -> Self: @property def codec_pipeline(self) -> CodecPipeline: - return get_pipeline_class().from_list(self.codecs) + return get_pipeline_class().from_codecs(self.codecs) + + def _get_inner_pipeline(self, shard_spec: ArraySpec) -> CodecPipeline: + """The nested pipeline for inner-chunk IO, evolved against the inner + chunk spec. + + Evolving matters for two reasons: it threads the spec through the inner + codec chain (spec-changing codecs see the spec they will actually + operate on), and β€” for a synchronous pipeline β€” it builds the sync + transform, so inner-chunk IO over the (sync-capable) sharding byte + getters takes the pipeline's sync fast path instead of scheduling one + coroutine per inner chunk. The bare `codec_pipeline` property returns an + unevolved pipeline, which a synchronous pipeline can only run through + its async fallback. + + Memoized per (pipeline class, batch size, shard_spec): evolving builds + a ChunkTransform, which is wasteful to redo on every shard operation. + The pipeline class and batch size participate in the key so the + `codec_pipeline.path` and `codec_pipeline.batch_size` configs are still + honored after the first use (`from_codecs` captures batch_size at + construction). A benign construction race between threads is possible + (last writer wins) β€” same as the other caches here. + """ + cache: dict[tuple[type[CodecPipeline], int, ArraySpec], CodecPipeline] | None = getattr( + self, "_inner_pipeline_cache", None + ) + if cache is None: + cache = {} + object.__setattr__(self, "_inner_pipeline_cache", cache) + key = (get_pipeline_class(), zarr_config.get("codec_pipeline.batch_size"), shard_spec) + pipeline = cache.get(key) + if pipeline is None: + chunk_spec = self._get_chunk_spec(shard_spec) + pipeline = self.codec_pipeline.evolve_from_array_spec(chunk_spec) + cache[key] = pipeline + return pipeline def to_dict(self) -> dict[str, JSON]: return { "name": "sharding_indexed", "configuration": { - "chunk_shape": list(self.chunk_shape), - "codecs": [s.to_dict() for s in self.codecs], - "index_codecs": [s.to_dict() for s in self.index_codecs], + "chunk_shape": self.chunk_shape, + "codecs": tuple(s.to_dict() for s in self.codecs), + "index_codecs": tuple(s.to_dict() for s in self.index_codecs), "index_location": self.index_location, }, } def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: + """Thread the spec through the inner chain. + + Each codec is evolved against the spec produced by the previous one. + Evolving every codec against the same unthreaded spec is the bug shape that + strips `BytesCodec.endian` behind a dtype-changing codec β€” and this + method runs on the real array-creation path, baking the damaged chain + into the evolved instance before the transform builders ever run. + + Parameters + ---------- + array_spec + The base spec to be evolved as we thread it. + + Returns + ------- + This codec with the evolved code chain. + """ + from zarr.core.chunk_utils import evolve_codecs + shard_spec = self._get_chunk_spec(array_spec) - evolved_codecs = tuple(c.evolve_from_array_spec(array_spec=shard_spec) for c in self.codecs) + evolved_codecs = evolve_codecs(self.codecs, shard_spec) if evolved_codecs != self.codecs: return replace(self, codecs=evolved_codecs) return self - def validate(self, *, shape: ChunkCoords, dtype: np.dtype[Any], chunk_grid: ChunkGrid) -> None: + def validate( + self, + *, + shape: tuple[int, ...], + dtype: ZDType[TBaseDType, TBaseScalar], + chunk_grid: ChunkGridMetadata, + ) -> None: if len(self.chunk_shape) != len(shape): raise ValueError( "The shard's `chunk_shape` and array's `shape` need to have the same number of dimensions." ) - if not isinstance(chunk_grid, RegularChunkGrid): - raise ValueError("Sharding is only compatible with regular chunk grids.") - if not all( - s % c == 0 - for s, c in zip( - chunk_grid.chunk_shape, - self.chunk_shape, - strict=False, + if isinstance(chunk_grid, RegularChunkGridMetadata): + edges_per_dim: tuple[tuple[int, ...], ...] = tuple((s,) for s in chunk_grid.chunk_shape) + elif isinstance(chunk_grid, RectilinearChunkGridMetadata): + edges_per_dim = tuple( + (s,) if isinstance(s, int) else s for s in chunk_grid.chunk_shapes ) - ): - raise ValueError( - "The array's `chunk_shape` needs to be divisible by the shard's inner `chunk_shape`." + else: + raise TypeError( + f"Sharding is only compatible with regular and rectilinear chunk grids, " + f"got {type(chunk_grid)}" + ) + for i, (edges, inner) in enumerate(zip(edges_per_dim, self.chunk_shape, strict=False)): + for edge in set(edges): + if edge % inner != 0: + raise ValueError( + f"Chunk edge length {edge} in dimension {i} is not " + f"divisible by the shard's inner chunk size {inner}." + ) + + def _get_inner_chunk_transform(self, shard_spec: ArraySpec) -> Any: + """The synchronous transform for the inner codec chain. + + Memoized by the instance-local `lru_cache` wrapping installed in + `__init__`/`__setstate__` (the single cache mechanism for these + builders β€” do not add another layer inside the body). + + Codecs are evolved with the spec THREADED forward (`evolve_codecs`): + each inner codec is evolved against the spec produced by the previous + one, not the original chunk spec. Evolving every codec against the same + unthreaded spec is the bug shape that stripped `BytesCodec.endian` at + the pipeline level (see `evolve_codecs`) β€” the inner chain must use the + same single source of truth. + """ + + chunk_spec = self._get_chunk_spec(shard_spec) + return ChunkTransform(codecs=evolve_codecs(self.codecs, chunk_spec)) + + def _get_index_chunk_transform(self, chunks_per_shard: tuple[int, ...]) -> Any: + """The synchronous transform for the index codec chain. + + Memoized via instance-local `lru_cache`. + """ + + index_spec = self._get_index_chunk_spec(chunks_per_shard) + return ChunkTransform(codecs=evolve_codecs(self.index_codecs, index_spec)) + + def _decode_shard_index_sync( + self, index_bytes: Buffer, chunks_per_shard: tuple[int, ...] + ) -> _ShardIndex: + """Decode shard index synchronously using ChunkTransform.""" + index_transform = self._get_index_chunk_transform(chunks_per_shard) + index_spec = self._get_index_chunk_spec(chunks_per_shard) + index_array = index_transform.decode_chunk(index_bytes, index_spec) + return _ShardIndex(chunks_per_shard, index_array.as_numpy_array()) + + def _encode_shard_index_sync(self, index: _ShardIndex) -> Buffer: + """Encode shard index synchronously using ChunkTransform.""" + index_transform = self._get_index_chunk_transform(index.chunks_per_shard) + index_spec = self._get_index_chunk_spec(index.chunks_per_shard) + index_nd = get_ndbuffer_class().from_numpy_array(index.offsets_and_lengths) + result: Buffer | None = index_transform.encode_chunk(index_nd, index_spec) + assert result is not None + return result + + def _shard_reader_from_bytes_sync( + self, buf: Buffer, chunks_per_shard: tuple[int, ...] + ) -> _ShardReader: + """Sync version of _ShardReader.from_bytes.""" + shard_index_size = self._shard_index_size(chunks_per_shard) + if self.index_location == "start": + shard_index_bytes = buf[:shard_index_size] + else: + shard_index_bytes = buf[-shard_index_size:] + index = self._decode_shard_index_sync(shard_index_bytes, chunks_per_shard) + reader = _ShardReader() + reader.buf = buf + reader.index = index + return reader + + def _decode_sync( + self, + shard_bytes: Buffer, + shard_spec: ArraySpec, + ) -> NDBuffer: + """Decode a full shard synchronously. + + Sync counterpart to `_decode_single`. Same semantics (decode every + inner chunk and assemble the full shard array) but routes through + `ChunkTransform` instead of the async codec pipeline, so it can + run on the sync codec-pipeline fast path without an event loop. + + For a partial read where the caller only needs a slice of the shard, + use `_decode_partial_sync` instead β€” it fetches only the byte + ranges that overlap the selection. + + This method does not parallelize decompression, but should. + See TODO: make issue for handling subchunk parallelism + """ + shard_shape = shard_spec.shape + chunk_shape = self.chunk_shape + chunks_per_shard = self._get_chunks_per_shard(shard_spec) + chunk_spec = self._get_chunk_spec(shard_spec) + inner_transform = self._get_inner_chunk_transform(shard_spec) + + indexer = BasicIndexer( + tuple(slice(0, s) for s in shard_shape), + shape=shard_shape, + chunk_grid=ChunkGrid.from_sizes(shard_shape, chunk_shape), + ) + + out = chunk_spec.prototype.nd_buffer.empty( + shape=shard_shape, + dtype=shard_spec.dtype.to_native_dtype(), + order=shard_spec.order, + ) + + shard_dict = self._shard_reader_from_bytes_sync(shard_bytes, chunks_per_shard) + + if shard_dict.index.is_all_empty(): + out.fill(shard_spec.fill_value) + return out + + for chunk_coords, chunk_selection, out_selection, _ in indexer: + # the GetResult status is discarded: missing INNER chunks of a + # present shard always fill (read_missing_chunks is a store-key + # level promise, applied to top-level statuses at the array layer) + decode_and_scatter_chunk( + shard_dict.get(chunk_coords), + out, + chunk_spec=chunk_spec, + chunk_selection=chunk_selection, + out_selection=out_selection, + drop_axes=(), + decode=inner_transform.decode_chunk, ) + return out + + def _encode_sync( + self, + shard_array: NDBuffer, + shard_spec: ArraySpec, + ) -> Buffer | None: + """Encode a full shard synchronously. + + Sync counterpart to `_encode_single`. This is reached when a + `ShardingCodec` is an *inner* codec of another sharding codec (nested + sharding): the outer codec encodes each inner chunk through its + `ChunkTransform`, which calls this method on the inner `ShardingCodec`. + + Each inner chunk is encoded through the inner `ChunkTransform` and + collected into an intermediate `dict`. The dict's key order is + immaterial β€” the physical on-disk layout is decided downstream by the + `subchunk_write_order` loop in `_encode_shard_dict_sync` (this method + does NOT impose a layout). Empty inner chunks become `None` entries when + `write_empty_chunks` is False, signalling `_encode_shard_dict_sync` to + elide them from the data section and mark them empty in the shard index. + + Returns `None` if every inner chunk was elided (an all-empty shard) β€” + callers treat that as "delete the shard key". + + This method does not parallelize compression, but should. + See TODO: make issue for handling subchunk parallelism + + For a partial write that only touches some inner chunks, use + `_encode_partial_sync` instead. + """ + shard_shape = shard_spec.shape + chunks_per_shard = self._get_chunks_per_shard(shard_spec) + chunk_spec = self._get_chunk_spec(shard_spec) + inner_transform = self._get_inner_chunk_transform(shard_spec) + + indexer = BasicIndexer( + tuple(slice(0, s) for s in shard_shape), + shape=shard_shape, + chunk_grid=ChunkGrid.from_sizes(shard_shape, self.chunk_shape), + ) + + # Key order here is immaterial; _encode_shard_dict_sync lays the present + # chunks out in subchunk_write_order. + shard_builder: dict[tuple[int, ...], Buffer | None] = dict.fromkeys( + lexicographic_order_coords(chunks_per_shard) + ) + + for chunk_coords, _chunk_selection, out_selection, _ in indexer: + # None = chunk normalized to missing (see encode_or_elide_chunk) + shard_builder[chunk_coords] = encode_or_elide_chunk( + shard_array[out_selection], chunk_spec, inner_transform.encode_chunk + ) + + return self._encode_shard_dict_sync( + shard_builder, + chunks_per_shard=chunks_per_shard, + buffer_prototype=default_buffer_prototype(), + ) + + def _encode_partial_sync( + self, + byte_setter: Any, + value: NDBuffer, + selection: SelectorTuple, + shard_spec: ArraySpec, + ) -> None: + """Sync equivalent of `_encode_partial_single`. + + Receives the source data for the written region (not a pre-merged + shard array) and the selection within the shard, matching the + calling convention of the async partial-encode path used by + `BatchedCodecPipeline`. + + This method does not parallelize compression, but should. + See TODO: make issue for handling subchunk parallelism + + Loads the existing shard, merges the written region into the affected + inner chunks, and rewrites the whole shard. + """ + shard_shape = shard_spec.shape + chunks_per_shard = self._get_chunks_per_shard(shard_spec) + chunk_spec = self._get_chunk_spec(shard_spec) + inner_transform = self._get_inner_chunk_transform(shard_spec) + + indexer = list( + get_indexer( + selection, + shape=shard_shape, + chunk_grid=ChunkGrid.from_sizes(shard_shape, self.chunk_shape), + ) + ) + + is_complete = self._is_complete_shard_write(indexer, chunks_per_shard) + + is_scalar = len(value.shape) == 0 + + # Load existing inner-chunk bytes into a dict (same structure as + # the async path's shard_dict). + if is_complete: + shard_dict: dict[tuple[int, ...], Buffer | None] = dict.fromkeys( + lexicographic_order_coords(chunks_per_shard) + ) + else: + existing_bytes = byte_setter.get_sync(prototype=shard_spec.prototype) + if existing_bytes is not None: + shard_reader_fb = self._shard_reader_from_bytes_sync( + existing_bytes, chunks_per_shard + ) + # Build the dict with one vectorized index lookup over all chunks, + # matching the async _encode_partial_single path. A per-coordinate + # __getitem__ loop here is O(n_chunks) Python overhead that dominates + # partial writes into shards with many inner chunks. The coordinate + # array and keys are cached on the reader, so neither is rebuilt here. + shard_dict = shard_reader_fb.to_dict_vectorized() + else: + shard_dict = dict.fromkeys(lexicographic_order_coords(chunks_per_shard)) + + # Merge, encode, and store each affected inner chunk into shard_dict via + # the canonical merge_and_encode_chunk (None = normalized to missing). + # + # Scalar fast path: when the written value is a scalar broadcast, every + # *complete* inner chunk is byte-for-byte identical β€” same fill, same + # empty-check, same encoded bytes. Compute that outcome once and reuse it + # for all complete chunks instead of re-merging, re-checking, and + # re-encoding tens of thousands of identical chunks. Incomplete (edge) + # chunks still merge against their own existing data individually. + # `_sentinel` distinguishes "not computed yet" from a memoized `None` + # (an empty chunk). + _sentinel = object() + scalar_complete_result: Buffer | object | None = _sentinel + + for chunk_coords, chunk_sel, out_sel, is_complete_chunk in indexer: + if is_scalar and is_complete_chunk: + if scalar_complete_result is _sentinel: + scalar_complete_result = merge_and_encode_chunk( + None, + value, + chunk_spec=chunk_spec, + chunk_selection=chunk_sel, + out_selection=out_sel, + is_complete=is_complete_chunk, + drop_axes=(), + decode=inner_transform.decode_chunk, + encode=inner_transform.encode_chunk, + ) + shard_dict[chunk_coords] = scalar_complete_result # type: ignore[assignment] + continue + + # A complete chunk fully overwrites: skip decoding what it replaces. + existing_raw = None if is_complete_chunk else shard_dict.get(chunk_coords) + shard_dict[chunk_coords] = merge_and_encode_chunk( + existing_raw, + value, + chunk_spec=chunk_spec, + chunk_selection=chunk_sel, + out_selection=out_sel, + is_complete=is_complete_chunk, + drop_axes=(), + decode=inner_transform.decode_chunk, + encode=inner_transform.encode_chunk, + ) + + blob = self._encode_shard_dict_sync( + shard_dict, + chunks_per_shard=chunks_per_shard, + buffer_prototype=default_buffer_prototype(), + ) + if blob is None: + byte_setter.delete_sync() + else: + byte_setter.set_sync(blob) + + def _build_shard_layout( + self, + shard_dict: ShardMapping, + chunks_per_shard: tuple[int, ...], + ) -> tuple[_ShardIndex, list[Buffer]] | None: + """Lay out the present inner chunks of a shard. Pure compute, no IO. + + Packs the encoded inner chunks (in the codec's `subchunk_write_order`) + into a contiguous data section and builds a shard index pointing each + present chunk at its ABSOLUTE byte offset within the final blob: when + the index is stored at the start, offsets are pre-shifted by the index + size (known without encoding β€” the index codecs are fixed-size, which + every index read path already relies on), so the index can be encoded + exactly once by the caller. + + Returns `(index, data_buffers)`, or `None` for an all-empty shard (no + chunks present). Shared by the sync and async `_encode_shard_dict*` so + the layout/offset logic cannot drift between them. + """ + index = _ShardIndex.create_empty(chunks_per_shard) + buffers: list[Buffer] = [] + chunk_start = ( + self._shard_index_size(chunks_per_shard) if self.index_location == "start" else 0 + ) + + for chunk_coords in self._subchunk_order_iter(chunks_per_shard, self.subchunk_write_order): + value = shard_dict.get(chunk_coords) + if value is None or len(value) == 0: + continue + chunk_length = len(value) + buffers.append(value) + index.set_chunk_slice(chunk_coords, slice(chunk_start, chunk_start + chunk_length)) + chunk_start += chunk_length + + if len(buffers) == 0: + return None + return index, buffers + + def _assemble_shard( + self, + index_bytes: Buffer, + buffers: list[Buffer], + buffer_prototype: BufferPrototype, + *, + chunks_per_shard: tuple[int, ...], + ) -> Buffer: + """Concatenate the encoded index and data buffers into the shard blob. + + The layout from `_build_shard_layout` already assumes the index size, so + the encoded index length must match `_shard_index_size` exactly β€” guard + that assumption rather than silently corrupt offsets. The guard lives + here, once, for both the sync and async encode paths. + """ + if len(index_bytes) != self._shard_index_size(chunks_per_shard): + raise RuntimeError( + "encoded shard index size does not match _shard_index_size; " + "variable-size index codecs are not supported" + ) + if self.index_location == "start": + buffers.insert(0, index_bytes) + else: + buffers.append(index_bytes) + template = buffer_prototype.buffer.create_zero_length() + return template.combine(buffers) + + def _encode_shard_dict_sync( + self, + shard_dict: ShardMapping, + chunks_per_shard: tuple[int, ...], + buffer_prototype: BufferPrototype, + ) -> Buffer | None: + """Sync version of _encode_shard_dict. + + Layout via the shared `_build_shard_layout` (offsets already absolute), + then a single index encode and concatenation. + + Returns `None` for an all-empty shard (no chunks present). + """ + layout = self._build_shard_layout(shard_dict, chunks_per_shard) + if layout is None: + return None + index, buffers = layout + index_bytes = self._encode_shard_index_sync(index) + return self._assemble_shard( + index_bytes, buffers, buffer_prototype, chunks_per_shard=chunks_per_shard + ) + async def _decode_single( self, shard_bytes: Buffer, @@ -413,12 +984,14 @@ async def _decode_single( indexer = BasicIndexer( tuple(slice(0, s) for s in shard_shape), shape=shard_shape, - chunk_grid=RegularChunkGrid(chunk_shape=chunk_shape), + chunk_grid=ChunkGrid.from_sizes(shard_shape, chunk_shape), ) # setup output array - out = chunk_spec.prototype.nd_buffer.create( - shape=shard_shape, dtype=shard_spec.dtype, order=shard_spec.order, fill_value=0 + out = chunk_spec.prototype.nd_buffer.empty( + shape=shard_shape, + dtype=shard_spec.dtype.to_native_dtype(), + order=shard_spec.order, ) shard_dict = await _ShardReader.from_bytes(shard_bytes, self, chunks_per_shard) @@ -427,15 +1000,16 @@ async def _decode_single( return out # decoding chunks and writing them into the output buffer - await self.codec_pipeline.read( + await self._get_inner_pipeline(shard_spec).read( [ ( _ShardingByteGetter(shard_dict, chunk_coords), chunk_spec, chunk_selection, out_selection, + is_complete_shard, ) - for chunk_coords, chunk_selection, out_selection in indexer + for chunk_coords, chunk_selection, out_selection, is_complete_shard in indexer ], out, ) @@ -456,19 +1030,21 @@ async def _decode_partial_single( indexer = get_indexer( selection, shape=shard_shape, - chunk_grid=RegularChunkGrid(chunk_shape=chunk_shape), + chunk_grid=ChunkGrid.from_sizes(shard_shape, chunk_shape), ) # setup output array - out = shard_spec.prototype.nd_buffer.create( - shape=indexer.shape, dtype=shard_spec.dtype, order=shard_spec.order, fill_value=0 + out = shard_spec.prototype.nd_buffer.empty( + shape=indexer.shape, + dtype=shard_spec.dtype.to_native_dtype(), + order=shard_spec.order, ) indexed_chunks = list(indexer) - all_chunk_coords = set(chunk_coords for chunk_coords, _, _ in indexed_chunks) + all_chunk_coords = {chunk_coords for chunk_coords, *_ in indexed_chunks} # reading bytes of all requested chunks - shard_dict: ShardMapping = {} + shard_dict_maybe: ShardMapping | None if self._is_total_shard(all_chunk_coords, chunks_per_shard): # read entire shard shard_dict_maybe = await self._load_full_shard_maybe( @@ -476,37 +1052,260 @@ async def _decode_partial_single( prototype=chunk_spec.prototype, chunks_per_shard=chunks_per_shard, ) - if shard_dict_maybe is None: - return None - shard_dict = shard_dict_maybe else: # read some chunks within the shard - shard_index = await self._load_shard_index_maybe(byte_getter, chunks_per_shard) - if shard_index is None: - return None - shard_dict = {} - for chunk_coords in all_chunk_coords: - chunk_byte_slice = shard_index.get_chunk_slice(chunk_coords) - if chunk_byte_slice: - chunk_bytes = await byte_getter.get( - prototype=chunk_spec.prototype, byte_range=chunk_byte_slice - ) - if chunk_bytes: - shard_dict[chunk_coords] = chunk_bytes + shard_dict_maybe = await self._load_partial_shard_maybe( + byte_getter, + chunk_spec.prototype, + chunks_per_shard, + all_chunk_coords, + max_gap_bytes=shard_spec.config.sharding_coalesce_max_gap_bytes, + max_coalesced_bytes=shard_spec.config.sharding_coalesce_max_bytes, + ) + + if shard_dict_maybe is None: + return None + shard_dict = shard_dict_maybe # decoding chunks and writing them into the output buffer - await self.codec_pipeline.read( + await self._get_inner_pipeline(shard_spec).read( [ ( _ShardingByteGetter(shard_dict, chunk_coords), chunk_spec, chunk_selection, out_selection, + is_complete_shard, ) - for chunk_coords, chunk_selection, out_selection in indexer + for chunk_coords, chunk_selection, out_selection, is_complete_shard in indexer ], out, ) + + if hasattr(indexer, "sel_shape"): + return out.reshape(indexer.sel_shape) + else: + return out + + def _subchunk_order_iter( + self, chunks_per_shard: tuple[int, ...], subchunk_write_order: SubchunkWriteOrder + ) -> Iterable[tuple[int, ...]]: + subchunk_iter: Iterable[tuple[int, ...]] + match subchunk_write_order: + case "morton": + subchunk_iter = morton_order_coords(chunks_per_shard) + case "lexicographic": + subchunk_iter = lexicographic_order_coords(chunks_per_shard) + case "colexicographic": + subchunk_iter = colexicographic_order_coords(chunks_per_shard) + case "unordered": + # "unordered" promises no particular layout; today it happens to be + # lexicographic, but callers must not rely on that. + subchunk_iter = np.ndindex(chunks_per_shard) + case _: + raise ValueError(f"Unrecognized subchunk write order: {subchunk_write_order!r}.") + return subchunk_iter + + def _decode_full_shard_bulk_if_uncompressed( + self, + shard_bytes: Buffer, + shard_spec: ArraySpec, + indexer: Any, + ) -> NDBuffer | None: + """Vectorized whole-shard decode for dense, fixed-size, uncompressed shards. + + Returns the assembled shard array, or None if the fast path does not + apply (so the caller falls back to the per-chunk loop). Conditions: + - inner codec chain is fixed-size (no compression / variable-length); + - the inner codec chain is exactly a single BytesCodec β€” decode is a + dtype/endian view with no reordering. A trailing crc32c is NOT accepted + (the bulk path can't verify per-chunk checksums, so crc shards keep the + per-chunk path's corruption detection); + - the data type is not structured (the byte-order handling below has no + `Struct` branch); + - `indexer` is an identity full-shard read (`_is_identity_full_read`); + - the stored index is dense (every chunk present, equal fixed length, + exactly tiling the data section) so the data section is a regular + grid of chunk payloads. + + Chunk positions are read from the stored index, so this is correct for + any `subchunk_write_order` (morton / lexicographic / colexicographic / + unordered). The on-disk byte order is taken from the BytesCodec's + `endian`, so big- and little-endian shards both decode correctly. + """ + # --- gate on a trivial, fixed-size inner codec chain --- + if not self._inner_codecs_fixed_size: + return None + # The inner chain must be exactly a single BytesCodec (a dtype/endian + # view, no reordering). A trailing Crc32cCodec is excluded on purpose: + # the bulk path would have to strip-and-discard the per-chunk checksum + # bytes, silently dropping the corruption detection the per-chunk path + # enforces (Crc32cCodec._decode_sync raises on mismatch). crc-protected + # shards therefore fall through to the per-chunk path. + if len(self.codecs) != 1 or not isinstance(self.codecs[0], BytesCodec): + return None + ab_codec = self.codecs[0] + + # The byte-order handling below lacks the structured-dtype branch of + # `BytesCodec._decode_sync` (which applies `newbyteorder` to multi-byte + # struct fields), so structured dtypes must take the per-chunk path. + if isinstance(shard_spec.dtype, Struct): + return None + + chunks_per_shard = self._get_chunks_per_shard(shard_spec) + chunk_spec = self._get_chunk_spec(shard_spec) + n_chunks = product(chunks_per_shard) + if n_chunks == 0: + return None + + # Only valid for an identity full-shard read, where each chunk lands at + # its natural grid position. The per-dimension check is load-bearing: + # a gather selection (an `OrthogonalIndexer` with an integer-array or + # boolean dimension, from `arr[perm, :]` / `arr.oindex[...]`, or a + # `CoordinateIndexer` from vindex) can have an output `.shape` equal to + # the shard shape while reordering or duplicating points β€” serving it + # from the bulk path would return the shard in natural order, silently + # dropping the reordering. Anything that is not a full-slice-per- + # dimension read falls through to the per-chunk path so + # chunk_selection / out_selection are honored. + if not _is_identity_full_read(indexer, shard_spec.shape): + return None + chunk_byte_length = self._inner_chunk_byte_length(chunk_spec) + + shard_index_size = self._shard_index_size(chunks_per_shard) + if len(shard_bytes) != n_chunks * chunk_byte_length + shard_index_size: + return None # not a dense fixed-size shard + + # --- decode the index; require dense layout --- + if self.index_location == "start": + index_bytes = shard_bytes[:shard_index_size] + else: + index_bytes = shard_bytes[-shard_index_size:] + index = self._decode_shard_index_sync(index_bytes, chunks_per_shard) + data_section_start = shard_index_size if self.index_location == "start" else 0 + if not index.is_dense(chunk_byte_length, data_section_start=data_section_start): + return None + + # --- bulk reconstruct --- + # The index gives each chunk's absolute byte offset within the blob; with + # a dense, crc-free, fixed-size layout the payload length is exactly the + # encoded item-bytes of one chunk. + native_dtype = shard_spec.dtype.to_native_dtype() + raw = shard_bytes.as_numpy_array().view(np.uint8) + payload = chunk_byte_length + cs = self.chunk_shape + + # On-disk byte order is carried by the BytesCodec's `endian`, NOT by the + # data type (zarr v3). Build the read-view dtype from the codec's endian + # exactly as BytesCodec._decode_sync does, so a big-endian shard read on a + # little-endian host (or vice versa) is interpreted correctly. Assigning + # into the native-dtype `out` then performs any needed byteswap. `endian` + # is now a plain Literal['little', 'big'] | None string (no longer an enum). + endian_str = ab_codec.endian + if isinstance(chunk_spec.dtype, HasEndianness): + stored_dtype = replace(chunk_spec.dtype, endianness=endian_str).to_native_dtype() # type: ignore[call-arg] + else: + stored_dtype = chunk_spec.dtype.to_native_dtype() + + offsets = index.offsets_and_lengths[..., 0].reshape(-1) # localized coords, C-order + coords_c = list(np.ndindex(chunks_per_shard)) + out = shard_spec.prototype.nd_buffer.empty( + shape=indexer.shape, dtype=native_dtype, order=shard_spec.order + ) + for flat, coord in enumerate(coords_c): + start = int(offsets[flat]) + chunk = raw[start : start + payload].view(stored_dtype).reshape(cs) + sel = tuple(slice(c * s, c * s + s) for c, s in zip(coord, cs, strict=True)) + out[sel] = chunk + return out + + def _decode_partial_sync( + self, + byte_getter: Any, + selection: SelectorTuple, + shard_spec: ArraySpec, + ) -> NDBuffer | None: + """Sync equivalent of `_decode_partial_single`. + + Reads only the inner-chunk byte ranges that overlap `selection` + (plus the shard index) and decodes them through the inner codec + chain. The store must support `get_sync` with byte ranges. + + This method does not parallelize decompression, but should. + See TODO: make issue for handling subchunk parallelism + + Two sub-paths: + - If `selection` covers the entire shard, just fetch the whole + blob β€” that's strictly cheaper than two round trips (index, then + data) plus the per-chunk overhead of partial fetches. + - Otherwise fetch the index alone, look up only the byte slices of + the inner chunks the selection touches, fetch those, and decode. + """ + shard_shape = shard_spec.shape + chunk_shape = self.chunk_shape + chunks_per_shard = self._get_chunks_per_shard(shard_spec) + chunk_spec = self._get_chunk_spec(shard_spec) + inner_transform = self._get_inner_chunk_transform(shard_spec) + + indexer = get_indexer( + selection, + shape=shard_shape, + chunk_grid=ChunkGrid.from_sizes(shard_shape, chunk_shape), + ) + + out = shard_spec.prototype.nd_buffer.empty( + shape=indexer.shape, + dtype=shard_spec.dtype.to_native_dtype(), + order=shard_spec.order, + ) + + indexed_chunks = list(indexer) + all_chunk_coords = {chunk_coords for chunk_coords, *_ in indexed_chunks} + + # Read just the inner chunks we need. + if self._is_total_shard(all_chunk_coords, chunks_per_shard): + shard_bytes = byte_getter.get_sync(prototype=chunk_spec.prototype) + if shard_bytes is None: + return None + bulk = self._decode_full_shard_bulk_if_uncompressed(shard_bytes, shard_spec, indexer) + if bulk is not None: + # The bulk path only fires for an identity full-shard read + # (`_is_identity_full_read`), so the result is already + # shard-shaped and in natural order β€” no reshape needed. + return bulk + shard_reader = self._shard_reader_from_bytes_sync(shard_bytes, chunks_per_shard) + shard_dict: ShardMapping = shard_reader + else: + # Partial read: fetch only the touched inner chunks, coalescing + # adjacent byte ranges (mirrors the async _load_partial_shard_maybe + # / #3004). Returns None if the shard is absent. + partial = self._load_partial_shard_maybe_sync( + byte_getter, + chunk_spec.prototype, + chunks_per_shard, + all_chunk_coords, + max_gap_bytes=shard_spec.config.sharding_coalesce_max_gap_bytes, + max_coalesced_bytes=shard_spec.config.sharding_coalesce_max_bytes, + ) + if partial is None: + return None + shard_dict = partial + + # Decode each needed inner chunk and scatter into out (statuses + # discarded: missing inner chunks fill, see _decode_sync). + for chunk_coords, chunk_selection, out_selection, _ in indexed_chunks: + decode_and_scatter_chunk( + shard_dict.get(chunk_coords), + out, + chunk_spec=chunk_spec, + chunk_selection=chunk_selection, + out_selection=out_selection, + drop_axes=(), + decode=inner_transform.decode_chunk, + ) + + if hasattr(indexer, "sel_shape"): + return out.reshape(indexer.sel_shape) return out async def _encode_single( @@ -523,26 +1322,30 @@ async def _encode_single( BasicIndexer( tuple(slice(0, s) for s in shard_shape), shape=shard_shape, - chunk_grid=RegularChunkGrid(chunk_shape=chunk_shape), + chunk_grid=ChunkGrid.from_sizes(shard_shape, chunk_shape), ) ) + shard_builder = dict.fromkeys(lexicographic_order_coords(chunks_per_shard)) - shard_builder = _ShardBuilder.create_empty(chunks_per_shard) - - await self.codec_pipeline.write( + await self._get_inner_pipeline(shard_spec).write( [ ( _ShardingByteSetter(shard_builder, chunk_coords), chunk_spec, chunk_selection, out_selection, + is_complete_shard, ) - for chunk_coords, chunk_selection, out_selection in indexer + for chunk_coords, chunk_selection, out_selection, is_complete_shard in indexer ], shard_array, ) - return await shard_builder.finalize(self.index_location, self._encode_shard_index) + return await self._encode_shard_dict( + shard_builder, + chunks_per_shard=chunks_per_shard, + buffer_prototype=default_buffer_prototype(), + ) async def _encode_partial_single( self, @@ -556,102 +1359,177 @@ async def _encode_partial_single( chunks_per_shard = self._get_chunks_per_shard(shard_spec) chunk_spec = self._get_chunk_spec(shard_spec) - shard_dict = _MergingShardBuilder( - await self._load_full_shard_maybe( - byte_getter=byte_setter, - prototype=chunk_spec.prototype, - chunks_per_shard=chunks_per_shard, - ) - or _ShardReader.create_empty(chunks_per_shard), - _ShardBuilder.create_empty(chunks_per_shard), - ) - indexer = list( get_indexer( - selection, shape=shard_shape, chunk_grid=RegularChunkGrid(chunk_shape=chunk_shape) + selection, + shape=shard_shape, + chunk_grid=ChunkGrid.from_sizes(shard_shape, chunk_shape), ) ) - await self.codec_pipeline.write( + if self._is_complete_shard_write(indexer, chunks_per_shard): + shard_dict = dict.fromkeys(lexicographic_order_coords(chunks_per_shard)) + else: + shard_reader = await self._load_full_shard_maybe( + byte_getter=byte_setter, + prototype=chunk_spec.prototype, + chunks_per_shard=chunks_per_shard, + ) + shard_reader = shard_reader or _ShardReader.create_empty(chunks_per_shard) + # Use vectorized lookup for better performance. The lexicographic + # coordinate array and keys are cached, so neither is rebuilt on + # every write. + shard_dict = shard_reader.to_dict_vectorized() + + await self._get_inner_pipeline(shard_spec).write( [ ( _ShardingByteSetter(shard_dict, chunk_coords), chunk_spec, chunk_selection, out_selection, + is_complete_shard, ) - for chunk_coords, chunk_selection, out_selection in indexer + for chunk_coords, chunk_selection, out_selection, is_complete_shard in indexer ], shard_array, ) + buf = await self._encode_shard_dict( + shard_dict, + chunks_per_shard=chunks_per_shard, + buffer_prototype=default_buffer_prototype(), + ) - if shard_dict.is_empty(): + if buf is None: await byte_setter.delete() else: - await byte_setter.set( - await shard_dict.finalize( - self.index_location, - self._encode_shard_index, - ) - ) + await byte_setter.set(buf) + + async def _encode_shard_dict( + self, + map: ShardMapping, + chunks_per_shard: tuple[int, ...], + buffer_prototype: BufferPrototype, + ) -> Buffer | None: + """Layout via the shared `_build_shard_layout` (offsets already + absolute), then a single index encode and concatenation. Async twin of + `_encode_shard_dict_sync`.""" + layout = self._build_shard_layout(map, chunks_per_shard) + if layout is None: + return None + index, buffers = layout + index_bytes = await self._encode_shard_index(index) + return self._assemble_shard( + index_bytes, buffers, buffer_prototype, chunks_per_shard=chunks_per_shard + ) def _is_total_shard( - self, all_chunk_coords: set[ChunkCoords], chunks_per_shard: ChunkCoords + self, all_chunk_coords: set[tuple[int, ...]], chunks_per_shard: tuple[int, ...] ) -> bool: - return len(all_chunk_coords) == product(chunks_per_shard) and all( - chunk_coords in all_chunk_coords for chunk_coords in c_order_iter(chunks_per_shard) + # `all_chunk_coords` comes from an indexer over this shard's chunk grid, so + # it is always a subset of that grid (`validate` requires the shard shape to + # be divisible by the inner chunk shape, so the indexer cannot produce an + # out-of-grid coordinate). A subset whose size equals the grid's is the + # whole grid, so the count check alone proves totality β€” no need to build + # and membership-test the full coordinate set on this hot path. + return len(all_chunk_coords) == product(chunks_per_shard) + + def _is_complete_shard_write( + self, + indexed_chunks: Sequence[ChunkProjection], + chunks_per_shard: tuple[int, ...], + ) -> bool: + all_chunk_coords = {chunk_coords for chunk_coords, *_ in indexed_chunks} + return self._is_total_shard(all_chunk_coords, chunks_per_shard) and all( + is_complete_chunk for *_, is_complete_chunk in indexed_chunks ) + @property + def _sync_capable(self) -> bool: + """Dynamic opt-out consulted by `_codec_supports_sync` / `ChunkTransform`. + + This codec structurally satisfies `SupportsSyncCodec`, but every sync + method (`_decode_sync`, `_encode_sync`, `_decode_partial_sync`, + `_encode_partial_sync`) delegates to the inner and index codec chains + through `ChunkTransform`, so it can only run synchronously when every + codec in BOTH chains is itself sync-capable. Reporting False here makes + `ChunkTransform` construction raise, which in turn makes + `FusedCodecPipeline.evolve_from_array_spec` set `sync_transform=None` β€” + the whole pipeline then declines the sync fast path and routes through + the async paths (partial shard decode / async fallback write), exactly + as it does for an async-only TOP-level codec or a non-sync store. + """ + return self._inner_codecs_sync_capable() and self._index_codecs_sync_capable() + + def _inner_codecs_sync_capable(self) -> bool: + # _codec_supports_sync (not bare isinstance) so a nested sharding codec + # with an async-only inner chain propagates its opt-out outward. + return all(_codec_supports_sync(c) for c in self.codecs) + + def _index_codecs_sync_capable(self) -> bool: + return all(_codec_supports_sync(c) for c in self.index_codecs) + async def _decode_shard_index( - self, index_bytes: Buffer, chunks_per_shard: ChunkCoords + self, index_bytes: Buffer, chunks_per_shard: tuple[int, ...] ) -> _ShardIndex: + # Pure compute (the bytes are already in hand): delegate to the sync + # implementation instead of spinning up a pipeline + per-call + # AsyncChunkTransform for a tiny fixed-size decode. The default + # (bytes + crc32c) index chain is sync-capable; an async-only + # third-party index codec falls back to the full async pipeline, which + # the synchronous read paths cannot use but this async path still can. + if self._index_codecs_sync_capable(): + return self._decode_shard_index_sync(index_bytes, chunks_per_shard) index_array = next( iter( await get_pipeline_class() - .from_list(self.index_codecs) - .decode( - [(index_bytes, self._get_index_chunk_spec(chunks_per_shard))], - ) + .from_codecs(self.index_codecs) + .decode([(index_bytes, self._get_index_chunk_spec(chunks_per_shard))]) ) ) - assert index_array is not None - return _ShardIndex(index_array.as_numpy_array()) + assert index_array is not None # the bytes are already in hand + return _ShardIndex(chunks_per_shard, index_array.as_numpy_array()) async def _encode_shard_index(self, index: _ShardIndex) -> Buffer: + # Pure compute: delegate to the sync implementation, with the same + # async-pipeline fallback as _decode_shard_index. + if self._index_codecs_sync_capable(): + return self._encode_shard_index_sync(index) index_bytes = next( iter( await get_pipeline_class() - .from_list(self.index_codecs) + .from_codecs(self.index_codecs) .encode( [ ( get_ndbuffer_class().from_numpy_array(index.offsets_and_lengths), self._get_index_chunk_spec(index.chunks_per_shard), ) - ], + ] ) ) ) assert index_bytes is not None - assert isinstance(index_bytes, Buffer) return index_bytes - def _shard_index_size(self, chunks_per_shard: ChunkCoords) -> int: + def _shard_index_size(self, chunks_per_shard: tuple[int, ...]) -> int: return ( get_pipeline_class() - .from_list(self.index_codecs) + .from_codecs(self.index_codecs) .compute_encoded_size( 16 * product(chunks_per_shard), self._get_index_chunk_spec(chunks_per_shard) ) ) - def _get_index_chunk_spec(self, chunks_per_shard: ChunkCoords) -> ArraySpec: + def _get_index_chunk_spec(self, chunks_per_shard: tuple[int, ...]) -> ArraySpec: return ArraySpec( shape=chunks_per_shard + (2,), - dtype=np.dtype(" ArraySpec: @@ -659,11 +1537,11 @@ def _get_chunk_spec(self, shard_spec: ArraySpec) -> ArraySpec: shape=self.chunk_shape, dtype=shard_spec.dtype, fill_value=shard_spec.fill_value, - order=shard_spec.order, + config=shard_spec.config, prototype=shard_spec.prototype, ) - def _get_chunks_per_shard(self, shard_spec: ArraySpec) -> ChunkCoords: + def _get_chunks_per_shard(self, shard_spec: ArraySpec) -> tuple[int, ...]: return tuple( s // c for s, c in zip( @@ -673,31 +1551,50 @@ def _get_chunks_per_shard(self, shard_spec: ArraySpec) -> ChunkCoords: ) ) + def _shard_index_byte_range( + self, chunks_per_shard: tuple[int, ...] + ) -> RangeByteRequest | SuffixByteRequest: + """Byte range of the shard index within the shard blob. + + Single source of truth for the index-location arithmetic, shared by the + sync and async index loaders so they cannot drift. + """ + shard_index_size = self._shard_index_size(chunks_per_shard) + if self.index_location == "start": + return RangeByteRequest(0, shard_index_size) + return SuffixByteRequest(shard_index_size) + + @staticmethod + def _pair_chunks_with_byte_ranges( + shard_index: _ShardIndex, all_chunk_coords: set[tuple[int, ...]] + ) -> list[tuple[tuple[int, ...], RangeByteRequest]]: + """Pair each requested chunk coord with its byte range in the shard. + + Coords whose chunk is absent from the index are omitted. Shared by the + sync and async partial-shard loaders. + """ + chunk_coord_byte_ranges: list[tuple[tuple[int, ...], RangeByteRequest]] = [] + for chunk_coord in all_chunk_coords: + chunk_byte_slice = shard_index.get_chunk_slice(chunk_coord) + if chunk_byte_slice is not None: + chunk_coord_byte_ranges.append( + (chunk_coord, RangeByteRequest(chunk_byte_slice[0], chunk_byte_slice[1])) + ) + return chunk_coord_byte_ranges + async def _load_shard_index_maybe( - self, byte_getter: ByteGetter, chunks_per_shard: ChunkCoords + self, byte_getter: ByteGetter, chunks_per_shard: tuple[int, ...] ) -> _ShardIndex | None: - shard_index_size = self._shard_index_size(chunks_per_shard) - if self.index_location == ShardingCodecIndexLocation.start: - index_bytes = await byte_getter.get( - prototype=numpy_buffer_prototype(), byte_range=(0, shard_index_size) - ) - else: - index_bytes = await byte_getter.get( - prototype=numpy_buffer_prototype(), byte_range=(-shard_index_size, None) - ) + index_bytes = await byte_getter.get( + prototype=numpy_buffer_prototype(), + byte_range=self._shard_index_byte_range(chunks_per_shard), + ) if index_bytes is not None: return await self._decode_shard_index(index_bytes, chunks_per_shard) return None - async def _load_shard_index( - self, byte_getter: ByteGetter, chunks_per_shard: ChunkCoords - ) -> _ShardIndex: - return ( - await self._load_shard_index_maybe(byte_getter, chunks_per_shard) - ) or _ShardIndex.create_empty(chunks_per_shard) - async def _load_full_shard_maybe( - self, byte_getter: ByteGetter, prototype: BufferPrototype, chunks_per_shard: ChunkCoords + self, byte_getter: ByteGetter, prototype: BufferPrototype, chunks_per_shard: tuple[int, ...] ) -> _ShardReader | None: shard_bytes = await byte_getter.get(prototype=prototype) @@ -707,9 +1604,153 @@ async def _load_full_shard_maybe( else None ) + @property + def _inner_codecs_fixed_size(self) -> bool: + """True when all inner codecs produce fixed-size output (no compression).""" + return all(c.is_fixed_size for c in self.codecs) + + def _inner_chunk_byte_length(self, chunk_spec: ArraySpec) -> int: + """Encoded byte length of a single inner chunk. Only valid when _inner_codecs_fixed_size.""" + raw_byte_length = 1 + for s in self.chunk_shape: + raw_byte_length *= s + raw_byte_length *= chunk_spec.dtype.item_size # type: ignore[attr-defined] + return int(self.codec_pipeline.compute_encoded_size(raw_byte_length, chunk_spec)) + + async def _load_partial_shard_maybe( + self, + byte_getter: ByteGetter, + prototype: BufferPrototype, + chunks_per_shard: tuple[int, ...], + all_chunk_coords: set[tuple[int, ...]], + max_gap_bytes: int, + max_coalesced_bytes: int, + ) -> ShardMapping | None: + """ + Read chunks from `byte_getter` for the case where the read is less than a full shard. + Returns a mapping of chunk coordinates to bytes or None. + + `max_gap_bytes` and `max_coalesced_bytes` are forwarded to + `Store.get_ranges` to control byte-range coalescing across the requested + chunks. + """ + shard_index = await self._load_shard_index_maybe(byte_getter, chunks_per_shard) + if shard_index is None: + return None + + chunk_coord_byte_ranges = self._pair_chunks_with_byte_ranges(shard_index, all_chunk_coords) + + if not chunk_coord_byte_ranges: + return {} + + shard_dict: ShardMutableMapping = {} + if isinstance(byte_getter, StorePath): + # External store: use Store.get_ranges for coalescing + concurrency. + byte_ranges = [byte_range for _, byte_range in chunk_coord_byte_ranges] + try: + async for group in byte_getter.store.get_ranges( + byte_getter.path, + byte_ranges, + prototype=prototype, + max_gap_bytes=max_gap_bytes, + max_coalesced_bytes=max_coalesced_bytes, + ): + for idx, buf in group: + if buf is not None: + chunk_coord, _ = chunk_coord_byte_ranges[idx] + shard_dict[chunk_coord] = buf + except BaseExceptionGroup as eg: + # `Store.get_ranges` raises FileNotFoundError (wrapped in a + # BaseExceptionGroup) if any underlying fetch indicates the key is + # absent. The shard index loaded above, so this typically means a + # race where the shard was deleted mid-read; treat it as "shard + # gone" to match the index-missing branch (return None). Anything + # else in the group (e.g. IO errors) is re-raised. + _, rest = eg.split(FileNotFoundError) + if rest is not None: + raise rest from None + return None + else: + # Any other ByteGetter. In practice only `_ShardingByteGetter` for + # nested sharding, which slices an in-memory buffer (no I/O to coalesce). + for chunk_coord, byte_range in chunk_coord_byte_ranges: + buf = await byte_getter.get(prototype, byte_range) + if buf is not None: + shard_dict[chunk_coord] = buf + + return shard_dict + + def _load_shard_index_maybe_sync( + self, byte_getter: Any, chunks_per_shard: tuple[int, ...] + ) -> _ShardIndex | None: + """Sync counterpart of `_load_shard_index_maybe`.""" + index_bytes = byte_getter.get_sync( + prototype=numpy_buffer_prototype(), + byte_range=self._shard_index_byte_range(chunks_per_shard), + ) + if index_bytes is not None: + return self._decode_shard_index_sync(index_bytes, chunks_per_shard) + return None + + def _load_partial_shard_maybe_sync( + self, + byte_getter: Any, + prototype: BufferPrototype, + chunks_per_shard: tuple[int, ...], + all_chunk_coords: set[tuple[int, ...]], + *, + max_gap_bytes: int, + max_coalesced_bytes: int, + ) -> ShardMapping | None: + """Sync counterpart of `_load_partial_shard_maybe` (the #3004 read path). + + Reads the shard index, then fetches only the touched inner chunks via the + store's coalescing `get_ranges_sync` (merging adjacent ranges into fewer + reads), matching the async path's IO shape without an event loop. + `max_gap_bytes` and `max_coalesced_bytes` control the coalescing, forwarded + from the array's `sharding_coalesce_*` config exactly as the async path. + """ + shard_index = self._load_shard_index_maybe_sync(byte_getter, chunks_per_shard) + if shard_index is None: + return None + + chunk_coord_byte_ranges = self._pair_chunks_with_byte_ranges(shard_index, all_chunk_coords) + + if not chunk_coord_byte_ranges: + return {} + + shard_dict: ShardMutableMapping = {} + store = byte_getter.store if hasattr(byte_getter, "store") else None + if isinstance(store, Store) and _store_supports_sync_io(store): + # External store: coalesce via get_ranges_sync (mirrors get_ranges). + byte_ranges = [byte_range for _, byte_range in chunk_coord_byte_ranges] + try: + for idx, buf in store.get_ranges_sync( + byte_getter.path, + byte_ranges, + prototype=prototype, + max_gap_bytes=max_gap_bytes, + max_coalesced_bytes=max_coalesced_bytes, + ): + if buf is not None: + chunk_coord, _ = chunk_coord_byte_ranges[idx] + shard_dict[chunk_coord] = buf + except BaseExceptionGroup as eg: + # Mirror the async path: a FileNotFoundError means the shard was + # deleted mid-read -> treat as "gone" (None). Re-raise anything else. + _, rest = eg.split(FileNotFoundError) + if rest is not None: + raise rest from None + return None + else: + # Nested sharding: an in-memory _ShardingByteGetter, no IO to coalesce. + for chunk_coord, byte_range in chunk_coord_byte_ranges: + buf = byte_getter.get_sync(prototype=prototype, byte_range=byte_range) + if buf is not None: + shard_dict[chunk_coord] = buf + + return shard_dict + def compute_encoded_size(self, input_byte_length: int, shard_spec: ArraySpec) -> int: chunks_per_shard = self._get_chunks_per_shard(shard_spec) return input_byte_length + self._shard_index_size(chunks_per_shard) - - -register_codec("sharding_indexed", ShardingCodec) diff --git a/src/zarr/codecs/transpose.py b/src/zarr/codecs/transpose.py index 3f9ae61676..5756fba2b4 100644 --- a/src/zarr/codecs/transpose.py +++ b/src/zarr/codecs/transpose.py @@ -7,16 +7,15 @@ import numpy as np from zarr.abc.codec import ArrayArrayCodec -from zarr.array_spec import ArraySpec -from zarr.buffer import NDBuffer -from zarr.chunk_grids import ChunkGrid -from zarr.common import JSON, ChunkCoordsLike, parse_named_configuration -from zarr.registry import register_codec +from zarr.core.array_spec import ArraySpec +from zarr.core.common import JSON, parse_named_configuration if TYPE_CHECKING: - from typing import Any + from typing import Self - from typing_extensions import Self + from zarr.core.buffer import NDBuffer + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType + from zarr.core.metadata.v3 import ChunkGridMetadata def parse_transpose_order(data: JSON | Iterable[int]) -> tuple[int, ...]: @@ -24,16 +23,18 @@ def parse_transpose_order(data: JSON | Iterable[int]) -> tuple[int, ...]: raise TypeError(f"Expected an iterable. Got {data} instead.") if not all(isinstance(a, int) for a in data): raise TypeError(f"Expected an iterable of integers. Got {data} instead.") - return tuple(cast(Iterable[int], data)) + return tuple(cast("Iterable[int]", data)) @dataclass(frozen=True) class TransposeCodec(ArrayArrayCodec): + """Transpose codec""" + is_fixed_size = True order: tuple[int, ...] - def __init__(self, *, order: ChunkCoordsLike) -> None: + def __init__(self, *, order: Iterable[int]) -> None: order_parsed = parse_transpose_order(order) object.__setattr__(self, "order", order_parsed) @@ -44,12 +45,17 @@ def from_dict(cls, data: dict[str, JSON]) -> Self: return cls(**configuration_parsed) # type: ignore[arg-type] def to_dict(self) -> dict[str, JSON]: - return {"name": "transpose", "configuration": {"order": list(self.order)}} + return {"name": "transpose", "configuration": {"order": tuple(self.order)}} - def validate(self, shape: tuple[int, ...], dtype: np.dtype[Any], chunk_grid: ChunkGrid) -> None: + def validate( + self, + shape: tuple[int, ...], + dtype: ZDType[TBaseDType, TBaseScalar], + chunk_grid: ChunkGridMetadata, + ) -> None: if len(self.order) != len(shape): raise ValueError( - f"The `order` tuple needs have as many entries as there are dimensions in the array. Got {self.order}." + f"The `order` tuple must have as many entries as there are dimensions in the array. Got {self.order}." ) if len(self.order) != len(set(self.order)): raise ValueError( @@ -64,7 +70,7 @@ def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: ndim = array_spec.ndim if len(self.order) != ndim: raise ValueError( - f"The `order` tuple needs have as many entries as there are dimensions in the array. Got {self.order}." + f"The `order` tuple must have as many entries as there are dimensions in the array. Got {self.order}." ) if len(self.order) != len(set(self.order)): raise ValueError( @@ -85,29 +91,38 @@ def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: shape=tuple(chunk_spec.shape[self.order[i]] for i in range(chunk_spec.ndim)), dtype=chunk_spec.dtype, fill_value=chunk_spec.fill_value, - order=chunk_spec.order, + config=chunk_spec.config, prototype=chunk_spec.prototype, ) + def _decode_sync( + self, + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + ) -> NDBuffer: + inverse_order = tuple(int(i) for i in np.argsort(self.order)) + return chunk_array.transpose(inverse_order) + async def _decode_single( self, chunk_array: NDBuffer, chunk_spec: ArraySpec, ) -> NDBuffer: - inverse_order = np.argsort(self.order) - chunk_array = chunk_array.transpose(inverse_order) - return chunk_array + return self._decode_sync(chunk_array, chunk_spec) + + def _encode_sync( + self, + chunk_array: NDBuffer, + _chunk_spec: ArraySpec, + ) -> NDBuffer | None: + return chunk_array.transpose(self.order) async def _encode_single( self, chunk_array: NDBuffer, _chunk_spec: ArraySpec, ) -> NDBuffer | None: - chunk_array = chunk_array.transpose(self.order) - return chunk_array + return self._encode_sync(chunk_array, _chunk_spec) def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: return input_byte_length - - -register_codec("transpose", TransposeCodec) diff --git a/src/zarr/codecs/vlen_utf8.py b/src/zarr/codecs/vlen_utf8.py new file mode 100644 index 0000000000..078e6032fc --- /dev/null +++ b/src/zarr/codecs/vlen_utf8.py @@ -0,0 +1,145 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +import numpy as np +from numcodecs.vlen import VLenBytes, VLenUTF8 + +from zarr._compat import _reshape_view +from zarr.abc.codec import ArrayBytesCodec +from zarr.core.buffer import Buffer, NDBuffer +from zarr.core.common import JSON, parse_named_configuration + +if TYPE_CHECKING: + from typing import Self + + from zarr.core.array_spec import ArraySpec + + +# can use a global because there are no parameters +_vlen_utf8_codec = VLenUTF8() +_vlen_bytes_codec = VLenBytes() + + +@dataclass(frozen=True) +class VLenUTF8Codec(ArrayBytesCodec): + """Variable-length UTF8 codec""" + + @classmethod + def from_dict(cls, data: dict[str, JSON]) -> Self: + _, configuration_parsed = parse_named_configuration( + data, "vlen-utf8", require_configuration=False + ) + configuration_parsed = configuration_parsed or {} + return cls(**configuration_parsed) + + def to_dict(self) -> dict[str, JSON]: + return {"name": "vlen-utf8", "configuration": {}} + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: + return self + + def _decode_sync( + self, + chunk_bytes: Buffer, + chunk_spec: ArraySpec, + ) -> NDBuffer: + assert isinstance(chunk_bytes, Buffer) + + raw_bytes = chunk_bytes.as_array_like() + decoded = _vlen_utf8_codec.decode(raw_bytes) + assert decoded.dtype == np.object_ + decoded = _reshape_view(decoded, chunk_spec.shape) + as_string_dtype = decoded.astype(chunk_spec.dtype.to_native_dtype(), copy=False) + return chunk_spec.prototype.nd_buffer.from_numpy_array(as_string_dtype) + + async def _decode_single( + self, + chunk_bytes: Buffer, + chunk_spec: ArraySpec, + ) -> NDBuffer: + return self._decode_sync(chunk_bytes, chunk_spec) + + def _encode_sync( + self, + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + ) -> Buffer | None: + assert isinstance(chunk_array, NDBuffer) + # numcodecs vlen codecs flatten with order="A", so an F-contiguous chunk + # would be encoded in transposed element order (gh-3558) + return chunk_spec.prototype.buffer.from_bytes( + _vlen_utf8_codec.encode(np.ascontiguousarray(chunk_array.as_numpy_array())) + ) + + async def _encode_single( + self, + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + ) -> Buffer | None: + return self._encode_sync(chunk_array, chunk_spec) + + def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: + # what is input_byte_length for an object dtype? + raise NotImplementedError("compute_encoded_size is not implemented for VLen codecs") + + +@dataclass(frozen=True) +class VLenBytesCodec(ArrayBytesCodec): + @classmethod + def from_dict(cls, data: dict[str, JSON]) -> Self: + _, configuration_parsed = parse_named_configuration( + data, "vlen-bytes", require_configuration=False + ) + configuration_parsed = configuration_parsed or {} + return cls(**configuration_parsed) + + def to_dict(self) -> dict[str, JSON]: + return {"name": "vlen-bytes", "configuration": {}} + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: + return self + + def _decode_sync( + self, + chunk_bytes: Buffer, + chunk_spec: ArraySpec, + ) -> NDBuffer: + assert isinstance(chunk_bytes, Buffer) + + raw_bytes = chunk_bytes.as_array_like() + decoded = _vlen_bytes_codec.decode(raw_bytes) + assert decoded.dtype == np.object_ + decoded = _reshape_view(decoded, chunk_spec.shape) + return chunk_spec.prototype.nd_buffer.from_numpy_array(decoded) + + async def _decode_single( + self, + chunk_bytes: Buffer, + chunk_spec: ArraySpec, + ) -> NDBuffer: + return self._decode_sync(chunk_bytes, chunk_spec) + + def _encode_sync( + self, + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + ) -> Buffer | None: + assert isinstance(chunk_array, NDBuffer) + # numcodecs vlen codecs flatten with order="A", so an F-contiguous chunk + # would be encoded in transposed element order (gh-3558) + return chunk_spec.prototype.buffer.from_bytes( + _vlen_bytes_codec.encode(np.ascontiguousarray(chunk_array.as_numpy_array())) + ) + + async def _encode_single( + self, + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + ) -> Buffer | None: + return self._encode_sync(chunk_array, chunk_spec) + + def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: + # what is input_byte_length for an object dtype? + raise NotImplementedError("compute_encoded_size is not implemented for VLen codecs") diff --git a/src/zarr/codecs/zstd.py b/src/zarr/codecs/zstd.py index b244ee703a..6d9f8910a7 100644 --- a/src/zarr/codecs/zstd.py +++ b/src/zarr/codecs/zstd.py @@ -1,43 +1,56 @@ from __future__ import annotations +import asyncio from dataclasses import dataclass -from typing import TYPE_CHECKING, Any +from functools import cached_property +from typing import TYPE_CHECKING -import numpy.typing as npt -from zstandard import ZstdCompressor, ZstdDecompressor +import numcodecs +from numcodecs.zstd import Zstd +from packaging.version import Version from zarr.abc.codec import BytesBytesCodec -from zarr.array_spec import ArraySpec -from zarr.buffer import Buffer, as_numpy_array_wrapper -from zarr.common import JSON, parse_named_configuration, to_thread -from zarr.registry import register_codec +from zarr.core.buffer.cpu import as_numpy_array_wrapper +from zarr.core.common import JSON, parse_named_configuration +from zarr.core.json_parse import parse_field if TYPE_CHECKING: - from typing_extensions import Self + from typing import Self + + from zarr.core.array_spec import ArraySpec + from zarr.core.buffer import Buffer def parse_zstd_level(data: JSON) -> int: - if isinstance(data, int): - if data >= 23: - raise ValueError(f"Value must be less than or equal to 22. Got {data} instead.") - return data - raise TypeError(f"Got value with type {type(data)}, but expected an int.") + parsed: int = parse_field(data, int, "level", error=TypeError) + if parsed >= 23: + raise ValueError(f"Value must be less than or equal to 22. Got {parsed} instead.") + return parsed def parse_checksum(data: JSON) -> bool: - if isinstance(data, bool): - return data - raise TypeError(f"Expected bool. Got {type(data)}.") + parsed: bool = parse_field(data, bool, "checksum", error=TypeError) + return parsed @dataclass(frozen=True) class ZstdCodec(BytesBytesCodec): - is_fixed_size = True + """zstd codec""" + + is_fixed_size = False level: int = 0 checksum: bool = False def __init__(self, *, level: int = 0, checksum: bool = False) -> None: + # numcodecs 0.13.0 introduces the checksum attribute for the zstd codec + _numcodecs_version = Version(numcodecs.__version__) + if _numcodecs_version < Version("0.13.0"): + raise RuntimeError( + "numcodecs version >= 0.13.0 is required to use the zstd codec. " + f"Version {_numcodecs_version} is currently installed." + ) + level_parsed = parse_zstd_level(level) checksum_parsed = parse_checksum(checksum) @@ -52,34 +65,38 @@ def from_dict(cls, data: dict[str, JSON]) -> Self: def to_dict(self) -> dict[str, JSON]: return {"name": "zstd", "configuration": {"level": self.level, "checksum": self.checksum}} - def _compress(self, data: npt.NDArray[Any]) -> bytes: - ctx = ZstdCompressor(level=self.level, write_checksum=self.checksum) - return ctx.compress(data.tobytes()) + @cached_property + def _zstd_codec(self) -> Zstd: + config_dict = {"level": self.level, "checksum": self.checksum} + return Zstd.from_config(config_dict) - def _decompress(self, data: npt.NDArray[Any]) -> bytes: - ctx = ZstdDecompressor() - return ctx.decompress(data.tobytes()) + def _decode_sync( + self, + chunk_bytes: Buffer, + chunk_spec: ArraySpec, + ) -> Buffer: + return as_numpy_array_wrapper(self._zstd_codec.decode, chunk_bytes, chunk_spec.prototype) async def _decode_single( self, chunk_bytes: Buffer, chunk_spec: ArraySpec, ) -> Buffer: - return await to_thread( - as_numpy_array_wrapper, self._decompress, chunk_bytes, chunk_spec.prototype - ) + return await asyncio.to_thread(self._decode_sync, chunk_bytes, chunk_spec) + + def _encode_sync( + self, + chunk_bytes: Buffer, + chunk_spec: ArraySpec, + ) -> Buffer | None: + return as_numpy_array_wrapper(self._zstd_codec.encode, chunk_bytes, chunk_spec.prototype) async def _encode_single( self, chunk_bytes: Buffer, chunk_spec: ArraySpec, ) -> Buffer | None: - return await to_thread( - as_numpy_array_wrapper, self._compress, chunk_bytes, chunk_spec.prototype - ) + return await asyncio.to_thread(self._encode_sync, chunk_bytes, chunk_spec) def compute_encoded_size(self, _input_byte_length: int, _chunk_spec: ArraySpec) -> int: raise NotImplementedError - - -register_codec("zstd", ZstdCodec) diff --git a/src/zarr/common.py b/src/zarr/common.py deleted file mode 100644 index aaa30cfcb8..0000000000 --- a/src/zarr/common.py +++ /dev/null @@ -1,169 +0,0 @@ -from __future__ import annotations - -import asyncio -import contextvars -import functools -import operator -from collections.abc import Iterable -from enum import Enum -from typing import ( - TYPE_CHECKING, - Any, - Literal, - ParamSpec, - TypeVar, - cast, - overload, -) - -if TYPE_CHECKING: - from collections.abc import Awaitable, Callable, Iterator - -import numpy as np -import numpy.typing as npt - -ZARR_JSON = "zarr.json" -ZARRAY_JSON = ".zarray" -ZGROUP_JSON = ".zgroup" -ZATTRS_JSON = ".zattrs" - -BytesLike = bytes | bytearray | memoryview -ChunkCoords = tuple[int, ...] -ChunkCoordsLike = Iterable[int] -ZarrFormat = Literal[2, 3] -JSON = None | str | int | float | Enum | dict[str, "JSON"] | list["JSON"] | tuple["JSON", ...] -MemoryOrder = Literal["C", "F"] -AccessModeLiteral = Literal["r", "r+", "a", "w", "w-"] - - -def product(tup: ChunkCoords) -> int: - return functools.reduce(operator.mul, tup, 1) - - -T = TypeVar("T", bound=tuple[Any, ...]) -V = TypeVar("V") - - -async def concurrent_map( - items: list[T], func: Callable[..., Awaitable[V]], limit: int | None = None -) -> list[V]: - if limit is None: - return await asyncio.gather(*[func(*item) for item in items]) - - else: - sem = asyncio.Semaphore(limit) - - async def run(item: tuple[Any]) -> V: - async with sem: - return await func(*item) - - return await asyncio.gather(*[asyncio.ensure_future(run(item)) for item in items]) - - -P = ParamSpec("P") -U = TypeVar("U") - - -async def to_thread(func: Callable[P, U], /, *args: P.args, **kwargs: P.kwargs) -> U: - loop = asyncio.get_running_loop() - ctx = contextvars.copy_context() - func_call = functools.partial(ctx.run, func, *args, **kwargs) - return await loop.run_in_executor(None, func_call) - - -E = TypeVar("E", bound=Enum) - - -def enum_names(enum: type[E]) -> Iterator[str]: - for item in enum: - yield item.name - - -def parse_enum(data: JSON, cls: type[E]) -> E: - if isinstance(data, cls): - return data - if not isinstance(data, str): - raise TypeError(f"Expected str, got {type(data)}") - if data in enum_names(cls): - return cls(data) - raise ValueError(f"Value must be one of {list(enum_names(cls))!r}. Got {data} instead.") - - -def parse_name(data: JSON, expected: str | None = None) -> str: - if isinstance(data, str): - if expected is None or data == expected: - return data - raise ValueError(f"Expected '{expected}'. Got {data} instead.") - else: - raise TypeError(f"Expected a string, got an instance of {type(data)}.") - - -def parse_configuration(data: JSON) -> JSON: - if not isinstance(data, dict): - raise TypeError(f"Expected dict, got {type(data)}") - return data - - -@overload -def parse_named_configuration( - data: JSON, expected_name: str | None = None -) -> tuple[str, dict[str, JSON]]: ... - - -@overload -def parse_named_configuration( - data: JSON, expected_name: str | None = None, *, require_configuration: bool = True -) -> tuple[str, dict[str, JSON] | None]: ... - - -def parse_named_configuration( - data: JSON, expected_name: str | None = None, *, require_configuration: bool = True -) -> tuple[str, JSON | None]: - if not isinstance(data, dict): - raise TypeError(f"Expected dict, got {type(data)}") - if "name" not in data: - raise ValueError(f"Named configuration does not have a 'name' key. Got {data}.") - name_parsed = parse_name(data["name"], expected_name) - if "configuration" in data: - configuration_parsed = parse_configuration(data["configuration"]) - elif require_configuration: - raise ValueError(f"Named configuration does not have a 'configuration' key. Got {data}.") - else: - configuration_parsed = None - return name_parsed, configuration_parsed - - -def parse_shapelike(data: int | Iterable[int]) -> tuple[int, ...]: - if isinstance(data, int): - if data < 0: - raise ValueError(f"Expected a non-negative integer. Got {data} instead") - return (data,) - try: - data_tuple = tuple(data) - except TypeError as e: - msg = f"Expected an integer or an iterable of integers. Got {data} instead." - raise TypeError(msg) from e - - if not all(isinstance(v, int) for v in data_tuple): - msg = f"Expected an iterable of integers. Got {data} instead." - raise TypeError(msg) - if not all(v > -1 for v in data_tuple): - msg = f"Expected all values to be non-negative. Got {data} instead." - raise ValueError(msg) - return data_tuple - - -def parse_dtype(data: npt.DTypeLike) -> np.dtype[Any]: - # todo: real validation - return np.dtype(data) - - -def parse_fill_value(data: Any) -> Any: - # todo: real validation - return data - - -def parse_order(data: Any) -> Literal["C", "F"]: - if data in ("C", "F"): - return cast(Literal["C", "F"], data) - raise ValueError(f"Expected one of ('C', 'F'), got {data} instead.") diff --git a/src/zarr/config.py b/src/zarr/config.py deleted file mode 100644 index ec78747a6b..0000000000 --- a/src/zarr/config.py +++ /dev/null @@ -1,74 +0,0 @@ -from __future__ import annotations - -from typing import Any, Literal, cast - -from donfig import Config as DConfig - - -class BadConfigError(ValueError): - _msg = "bad Config: %r" - - -class Config(DConfig): # type: ignore[misc] - """Will collect configuration from config files and environment variables - - Example environment variables: - Grabs environment variables of the form "ZARR_FOO__BAR_BAZ=123" and - turns these into config variables of the form ``{"foo": {"bar-baz": 123}}`` - It transforms the key and value in the following way: - - - Lower-cases the key text - - Treats ``__`` (double-underscore) as nested access - - Calls ``ast.literal_eval`` on the value - - """ - - def reset(self) -> None: - self.clear() - self.refresh() - - -""" -The config module is responsible for managing the configuration of zarr and is based on the Donfig python library. -For selecting custom implementations of codecs, pipelines, buffers and ndbuffers, first register the implementations -in the registry and then select them in the config. -e.g. an implementation of the bytes codec in a class "NewBytesCodec", requires the value of codecs.bytes.name to be -"NewBytesCodec". -Donfig can be configured programmatically, by environment variables, or from YAML files in standard locations -e.g. export ZARR_CODECS__BYTES__NAME="NewBytesCodec" -(for more information see github.com/pytroll/donfig) -Default values below point to the standard implementations of zarr-python -""" -config = Config( - "zarr", - defaults=[ - { - "array": {"order": "C"}, - "async": {"concurrency": None, "timeout": None}, - "json_indent": 2, - "codec_pipeline": { - "path": "zarr.codecs.pipeline.BatchedCodecPipeline", - "batch_size": 1, - }, - "codecs": { - "blosc": "zarr.codecs.blosc.BloscCodec", - "gzip": "zarr.codecs.gzip.GzipCodec", - "zstd": "zarr.codecs.zstd.ZstdCodec", - "bytes": "zarr.codecs.bytes.BytesCodec", - "endian": "zarr.codecs.bytes.BytesCodec", # compatibility with earlier versions of ZEP1 - "crc32c": "zarr.codecs.crc32c_.Crc32cCodec", - "sharding_indexed": "zarr.codecs.sharding.ShardingCodec", - "transpose": "zarr.codecs.transpose.TransposeCodec", - }, - "buffer": "zarr.buffer.Buffer", - "ndbuffer": "zarr.buffer.NDBuffer", - } - ], -) - - -def parse_indexing_order(data: Any) -> Literal["C", "F"]: - if data in ("C", "F"): - return cast(Literal["C", "F"], data) - msg = f"Expected one of ('C', 'F'), got {data} instead." - raise ValueError(msg) diff --git a/src/zarr/convenience.py b/src/zarr/convenience.py deleted file mode 100644 index be0a6b2813..0000000000 --- a/src/zarr/convenience.py +++ /dev/null @@ -1,35 +0,0 @@ -import warnings - -from zarr.api.synchronous import ( - consolidate_metadata, - copy, - copy_all, - copy_store, - load, - open, - open_consolidated, - save, - save_array, - save_group, - tree, -) - -warnings.warn( - "zarr.convenience is deprecated, use zarr.api.synchronous", - DeprecationWarning, - stacklevel=2, -) - -__all__ = [ - "open", - "save_array", - "save_group", - "save", - "load", - "tree", - "copy_store", - "copy", - "copy_all", - "consolidate_metadata", - "open_consolidated", -] diff --git a/src/zarr/core/__init__.py b/src/zarr/core/__init__.py new file mode 100644 index 0000000000..03a108dbbf --- /dev/null +++ b/src/zarr/core/__init__.py @@ -0,0 +1,9 @@ +""" +The ``zarr.core`` module is considered private API and should not be imported +directly by 3rd-party code. +""" + +from __future__ import annotations + +from zarr.core.buffer import Buffer, NDBuffer # noqa: F401 +from zarr.core.codec_pipeline import BatchedCodecPipeline # noqa: F401 diff --git a/src/zarr/core/_coalesce.py b/src/zarr/core/_coalesce.py new file mode 100644 index 0000000000..bfee9b4052 --- /dev/null +++ b/src/zarr/core/_coalesce.py @@ -0,0 +1,222 @@ +# src/zarr/core/_coalesce.py +from __future__ import annotations + +import asyncio +from typing import TYPE_CHECKING, NamedTuple + +from zarr.abc.store import RangeByteRequest + +if TYPE_CHECKING: + from collections.abc import AsyncGenerator, Awaitable, Callable, Sequence + + from zarr.abc.store import ByteRequest + from zarr.core.buffer import Buffer + + +class _WorkerCtx(NamedTuple): + """Shared state passed to the per-task worker coroutines. + + Bundling these lets the workers declare their dependencies as one + parameter instead of capturing them implicitly via closure. + """ + + fetch: Callable[[ByteRequest | None], Awaitable[Buffer | None]] + semaphore: asyncio.Semaphore + + +async def _fetch_single( + ctx: _WorkerCtx, idx: int, req: ByteRequest | None +) -> Sequence[tuple[int, Buffer | None]]: + """Fetch one byte range. Raises FileNotFoundError if the key is absent.""" + async with ctx.semaphore: + buf = await ctx.fetch(req) + if buf is None: + raise FileNotFoundError + return ((idx, buf),) + + +async def _fetch_group( + ctx: _WorkerCtx, members: list[tuple[int, RangeByteRequest]] +) -> Sequence[tuple[int, Buffer | None]]: + """Fetch one merged byte range and slice it back into per-input buffers. + + `members` must already be sorted by `start`; callers in this module + build it from the sorted mergeable list. Raises `FileNotFoundError` + if the key is absent. + """ + if len(members) == 1: + solo_idx, solo_req = members[0] + return await _fetch_single(ctx, solo_idx, solo_req) + + start = members[0][1].start + end = max(r.end for _, r in members) + async with ctx.semaphore: + big = await ctx.fetch(RangeByteRequest(start, end)) + if big is None: + raise FileNotFoundError + sliced = [(idx, big[r.start - start : r.end - start]) for idx, r in members] + return tuple(sliced) + + +def coalesce_ranges( + byte_ranges: Sequence[ByteRequest | None], + *, + max_gap_bytes: int, + max_coalesced_bytes: int, +) -> tuple[ + list[list[tuple[int, RangeByteRequest]]], + list[tuple[int, ByteRequest | None]], +]: + """Plan a set of byte-range fetches: which inputs merge, which stand alone. + + Pure (no I/O). The result is the I/O plan a caller would execute: each + group corresponds to one fetch of a coalesced byte range, and each + uncoalescable item corresponds to one fetch of the original request. + + All tuning knobs are required keyword arguments. `Store.get_ranges` is + the public entry point and owns the canonical default values; this + function takes them explicitly to avoid duplicating policy. + + Parameters + ---------- + byte_ranges + Input ranges. `None` means "the whole value". + max_gap_bytes + Two `RangeByteRequest`s separated by at most this many bytes may be + merged into one fetch. + max_coalesced_bytes + Upper bound on the size of a single merged fetch. + + Returns + ------- + groups + List of merged groups. Each group is a list of + `(input_index, RangeByteRequest)` pairs sorted by `start`. A + single-element group represents a `RangeByteRequest` that did not + merge with any neighbor. + uncoalescable + List of `(input_index, request)` pairs for inputs that are not + `RangeByteRequest` (`OffsetByteRequest`, `SuffixByteRequest`, + `None`). Indices are preserved from the input order. + + Notes + ----- + Only `RangeByteRequest` inputs participate in coalescing. Two ranges + merge when both: their gap (next `start` minus current group's running + `end`) is `<= max_gap_bytes`, and the resulting merged span is + `<= max_coalesced_bytes`. + """ + indexed = list(enumerate(byte_ranges)) + mergeable = [(i, r) for i, r in indexed if isinstance(r, RangeByteRequest)] + uncoalescable: list[tuple[int, ByteRequest | None]] = [ + (i, r) for i, r in indexed if not isinstance(r, RangeByteRequest) + ] + + # Sort mergeables by start offset, then merge. Track running start/end of the + # current group so each merge step is O(1) instead of O(group size). + mergeable.sort(key=lambda pair: pair[1].start) + groups: list[list[tuple[int, RangeByteRequest]]] = [] + group_start = 0 + group_end = 0 + for pair in mergeable: + _i, r = pair + if groups and r.start - group_end <= max_gap_bytes: + prospective_end = max(group_end, r.end) + if prospective_end - group_start <= max_coalesced_bytes: + groups[-1].append(pair) + group_end = prospective_end + continue + groups.append([pair]) + group_start = r.start + group_end = r.end + + return groups, uncoalescable + + +async def coalesced_get( + fetch: Callable[[ByteRequest | None], Awaitable[Buffer | None]], + byte_ranges: Sequence[ByteRequest | None], + *, + max_concurrency: int, + max_gap_bytes: int, + max_coalesced_bytes: int, +) -> AsyncGenerator[Sequence[tuple[int, Buffer | None]]]: + """Read many byte ranges through `fetch` with coalescing and concurrency. + + Nearby ranges are merged into a single underlying I/O, and merged fetches + are run concurrently. Each yield corresponds to exactly one underlying I/O + operation: a sequence of `(input_index, result)` tuples for all input + ranges served by that I/O. Tuples within a yielded sequence are ordered by + start offset. Yields across groups are in completion order, not input + order. + + All tuning knobs are required keyword arguments. `Store.get_ranges` is + the public entry point and owns the canonical default values; this + function takes them explicitly to avoid duplicating policy. + + Parameters + ---------- + fetch + Callable that reads one byte range and returns a `Buffer` (or `None` + if the underlying key does not exist). Typically constructed via + `functools.partial(store.get, key, prototype)`. + byte_ranges + Input ranges. `None` means "the whole value". + max_concurrency + Maximum number of merged fetches in flight at once. + max_gap_bytes + Forwarded to `coalesce_ranges`. + max_coalesced_bytes + Forwarded to `coalesce_ranges`. + + Yields + ------ + Sequence[tuple[int, Buffer | None]] + Per-I/O batch of `(input_index, result)` tuples. + + Notes + ----- + - Only `RangeByteRequest` inputs are coalesced. `OffsetByteRequest`, + `SuffixByteRequest`, and `None` are each treated as uncoalescable + (one fetch, one single-tuple yield per input). + - Failures from underlying fetches surface as a `BaseExceptionGroup` + (PEP 654). Inner exceptions include `FileNotFoundError` if a fetch + returns `None`, plus any exception `fetch` raises. Pending fetches are + cancelled as soon as one task fails, so the group typically contains a + single non-`CancelledError` exception even under high concurrency. + - Groups completed before the failure remain observable on the yields + preceding the raise. + - `GeneratorExit` raised by `aclose()` is filtered out so the iterator + closes cleanly; callers don't see a group containing only it. + """ + if not byte_ranges: + return + + groups, singles = coalesce_ranges( + byte_ranges, + max_gap_bytes=max_gap_bytes, + max_coalesced_bytes=max_coalesced_bytes, + ) + + ctx = _WorkerCtx(fetch=fetch, semaphore=asyncio.Semaphore(max_concurrency)) + + # Launch all work as tasks. The semaphore bounds actual I/O concurrency. + # TaskGroup wraps task exceptions in BaseExceptionGroup; we propagate the + # group unchanged as part of the public contract (callers handle batch + # failures via `except*` / PEP 654). GeneratorExit (raised when the + # consumer calls aclose()) is filtered out so close completes cleanly. + try: + async with asyncio.TaskGroup() as tg: + tasks = [ + *(tg.create_task(_fetch_group(ctx, group)) for group in groups), + *(tg.create_task(_fetch_single(ctx, i, single)) for i, single in singles), + ] + + for fut in asyncio.as_completed(tasks): + yield await fut + except BaseExceptionGroup as eg: + # Strip GeneratorExits (consumer aclose()) and propagate whatever remains. + _, other_errors = eg.split(GeneratorExit) + + if other_errors is not None: + raise other_errors from None diff --git a/src/zarr/core/_info.py b/src/zarr/core/_info.py new file mode 100644 index 0000000000..1503f05b26 --- /dev/null +++ b/src/zarr/core/_info.py @@ -0,0 +1,150 @@ +from __future__ import annotations + +import dataclasses +import textwrap +from typing import TYPE_CHECKING, Literal + +if TYPE_CHECKING: + from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec + from zarr.abc.numcodec import Numcodec + from zarr.core.common import ZarrFormat + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType + + +@dataclasses.dataclass(kw_only=True) +class GroupInfo: + """ + Visual summary for a Group. + + Note that this method and its properties is not part of + Zarr's public API. + """ + + _name: str + _type: Literal["Group"] = "Group" + _zarr_format: ZarrFormat + _read_only: bool + _store_type: str + _count_members: int | None = None + _count_arrays: int | None = None + _count_groups: int | None = None + + def __repr__(self) -> str: + template = textwrap.dedent("""\ + Name : {_name} + Type : {_type} + Zarr format : {_zarr_format} + Read-only : {_read_only} + Store type : {_store_type}""") + + if self._count_members is not None: + template += "\nNo. members : {_count_members}" + if self._count_arrays is not None: + template += "\nNo. arrays : {_count_arrays}" + if self._count_groups is not None: + template += "\nNo. groups : {_count_groups}" + return template.format(**dataclasses.asdict(self)) + + +def human_readable_size(size: int) -> str: + if size < 2**10: + return f"{size}" + elif size < 2**20: + return f"{size / float(2**10):.1f}K" + elif size < 2**30: + return f"{size / float(2**20):.1f}M" + elif size < 2**40: + return f"{size / float(2**30):.1f}G" + elif size < 2**50: + return f"{size / float(2**40):.1f}T" + else: + return f"{size / float(2**50):.1f}P" + + +def byte_info(size: int) -> str: + if size < 2**10: + return str(size) + else: + return f"{size} ({human_readable_size(size)})" + + +@dataclasses.dataclass(kw_only=True, frozen=True, slots=True) +class ArrayInfo: + """ + Visual summary for an Array. + + Note that this method and its properties is not part of + Zarr's public API. + """ + + _type: Literal["Array"] = "Array" + _zarr_format: ZarrFormat + _data_type: ZDType[TBaseDType, TBaseScalar] + _fill_value: object + _shape: tuple[int, ...] + _shard_shape: tuple[int, ...] | None = None + _chunk_shape: tuple[int, ...] | None = None + _order: Literal["C", "F"] + _read_only: bool + _store_type: str + _filters: tuple[Numcodec, ...] | tuple[ArrayArrayCodec, ...] = () + _serializer: ArrayBytesCodec | None = None + _compressors: tuple[Numcodec, ...] | tuple[BytesBytesCodec, ...] = () + _count_bytes: int | None = None + _count_bytes_stored: int | None = None + _count_chunks_initialized: int | None = None + + def __repr__(self) -> str: + template = textwrap.dedent("""\ + Type : {_type} + Zarr format : {_zarr_format} + Data type : {_data_type} + Fill value : {_fill_value} + Shape : {_shape}""") + + if self._shard_shape is not None: + template += textwrap.dedent(""" + Shard shape : {_shard_shape}""") + + template += textwrap.dedent(""" + Chunk shape : {_chunk_shape} + Order : {_order} + Read-only : {_read_only} + Store type : {_store_type}""") + + # We can't use dataclasses.asdict, because we only want a shallow dict + kwargs = {field.name: getattr(self, field.name) for field in dataclasses.fields(self)} + + if self._chunk_shape is None: + # for non-regular chunk grids + kwargs["_chunk_shape"] = "" + + template += "\nFilters : {_filters}" + + if self._serializer is not None: + template += "\nSerializer : {_serializer}" + + template += "\nCompressors : {_compressors}" + + if self._count_bytes is not None: + template += "\nNo. bytes : {_count_bytes}" + kwargs["_count_bytes"] = byte_info(self._count_bytes) + + if self._count_bytes_stored is not None: + template += "\nNo. bytes stored : {_count_bytes_stored}" + kwargs["_count_bytes_stored"] = byte_info(self._count_bytes_stored) + + if ( + self._count_bytes is not None + and self._count_bytes_stored is not None + and self._count_bytes_stored > 0 + ): + template += "\nStorage ratio : {_storage_ratio}" + kwargs["_storage_ratio"] = f"{self._count_bytes / self._count_bytes_stored:.1f}" + + if self._count_chunks_initialized is not None: + if self._shard_shape is not None: + template += "\nShards Initialized : {_count_chunks_initialized}" + else: + template += "\nChunks Initialized : {_count_chunks_initialized}" + return template.format(**kwargs) diff --git a/src/zarr/core/_json.py b/src/zarr/core/_json.py new file mode 100644 index 0000000000..efe8152a4f --- /dev/null +++ b/src/zarr/core/_json.py @@ -0,0 +1,133 @@ +"""Helpers for moving JSON documents in and out of zarr stores. + +These are free functions, deliberately not methods on the ``Store`` ABC: +reading and writing JSON is a composition of the store's ``get``/``set`` +primitives with a buffer/JSON conversion, not part of the store contract. +Keeping them as functions means stores cannot (and need not) override them, +and the ``Store`` definition stays free of any dependency on the buffer +prototype. + +These functions are pure: the JSON encoding parameters (``indent``, +``allow_nan``) are explicit arguments rather than read from the global config. +Callers that want zarr's configured indentation pass +``indent=config.get("json_indent")``. + +Two layers: + +- ``buffer_to_json`` / ``json_to_buffer`` convert between a ``Buffer`` and a + parsed JSON value. The buffer prototype lives here, at buffer construction, + where it is meaningful. +- ``get_json`` / ``set_json`` compose those with ``Store.get`` / ``Store.set``. + ``get_json`` returns ``None`` for a missing key (the contract most callers + want); callers that require presence check for ``None`` themselves. +""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, cast + +from zarr.core.buffer import default_buffer_prototype + +if TYPE_CHECKING: + from zarr.abc.store import ByteRequest, Store + from zarr.core.buffer import Buffer, BufferPrototype + from zarr.core.common import JSON + + +def buffer_to_json(buffer: Buffer) -> JSON: + """Parse the contents of a `Buffer` as a JSON value.""" + # json.loads is typed as returning Any; the result is by definition JSON. + return cast("JSON", json.loads(buffer.to_bytes())) + + +def buffer_to_json_object(buffer: Buffer) -> dict[str, JSON]: + """Parse the contents of a `Buffer` as a JSON object (a `dict`). + + Every metadata document zarr reads is a JSON object, so this narrows the + `JSON` union to `dict[str, JSON]` once, here, instead of at each call site. + + Parameters + ---------- + buffer + The buffer whose contents are parsed as a JSON object. + + Raises + ------ + TypeError + If the parsed value is not a JSON object. + """ + obj = buffer_to_json(buffer) + if not isinstance(obj, dict): + raise TypeError(f"Expected a JSON object, got {type(obj).__name__}.") + return obj + + +def json_to_buffer( + obj: JSON, + *, + prototype: BufferPrototype | None = None, + indent: int | None = None, + allow_nan: bool = True, +) -> Buffer: + """Serialize a JSON value into a `Buffer`. + + Parameters + ---------- + obj + The JSON-serializable value to encode. + prototype + The buffer prototype to construct the result with. Defaults to + `default_buffer_prototype()`. + indent + Indentation passed to `json.dumps`. `None` (the default) writes + without newline indentation, using json's default separators. + Callers that want zarr's configured indentation pass + `indent=config.get("json_indent")`. + allow_nan + Whether to permit `NaN`/`Infinity` in the output, passed to + `json.dumps`. + """ + if prototype is None: + prototype = default_buffer_prototype() + return prototype.buffer.from_bytes(json.dumps(obj, indent=indent, allow_nan=allow_nan).encode()) + + +async def get_json(store: Store, key: str, *, byte_range: ByteRequest | None = None) -> JSON | None: + """Read and parse the JSON document at `key`, or `None` if it is absent. + + Parameters + ---------- + store + The store to read from. + key + The key identifying the JSON document. + byte_range + If given, read only this portion of the value. Note that a partial + read of a JSON document may not be valid JSON. + + Returns + ------- + JSON or None + The parsed JSON value, or `None` if `key` does not exist. + """ + buffer = await store.get(key, default_buffer_prototype(), byte_range) + return None if buffer is None else buffer_to_json(buffer) + + +async def set_json( + store: Store, + key: str, + obj: JSON, + *, + prototype: BufferPrototype | None = None, + indent: int | None = None, + allow_nan: bool = True, +) -> None: + """Serialize `obj` as JSON and write it to `key` in `store`. + + `indent` and `allow_nan` are forwarded to `json_to_buffer`. + """ + await store.set( + key, json_to_buffer(obj, prototype=prototype, indent=indent, allow_nan=allow_nan) + ) diff --git a/src/zarr/core/_tree.py b/src/zarr/core/_tree.py new file mode 100644 index 0000000000..a528bf9876 --- /dev/null +++ b/src/zarr/core/_tree.py @@ -0,0 +1,134 @@ +import sys +from collections import deque +from collections.abc import Sequence +from html import escape as html_escape +from typing import Any + +from zarr.core.group import AsyncGroup + + +class TreeRepr: + """ + A simple object with a tree-like repr for the Zarr Group. + + Note that this object and it's implementation isn't considered part + of Zarr's public API. + """ + + def __init__(self, text: str, html: str, truncated: str = "") -> None: + self._text = text + self._html = html + self._truncated = truncated + + def __repr__(self) -> str: + if self._truncated: + return self._truncated + self._text + return self._text + + def _repr_mimebundle_( + self, + include: Sequence[str] | None = None, + exclude: Sequence[str] | None = None, + **kwargs: Any, + ) -> dict[str, str]: + text = self._truncated + self._text if self._truncated else self._text + # For jupyter support. + html_body = self._truncated + self._html if self._truncated else self._html + html = ( + '
"
+            f"{html_body}
\n" + ) + return {"text/plain": text, "text/html": html} + + +async def group_tree_async( + group: AsyncGroup, + max_depth: int | None = None, + *, + max_nodes: int = 500, + plain: bool = False, +) -> TreeRepr: + members: list[tuple[str, Any]] = [] + truncated = False + async for item in group.members(max_depth=max_depth): + if len(members) == max_nodes: + truncated = True + break + members.append(item) + members.sort(key=lambda key_node: key_node[0]) + + # Set up styling tokens: ANSI bold for terminals, HTML for Jupyter, + # or empty strings when plain=True (useful for LLMs, logging, files). + if plain: + ansi_open = ansi_close = html_open = html_close = "" + else: + # Avoid emitting ANSI escape codes when output is piped or in CI. + use_ansi = sys.stdout.isatty() + ansi_open = "\x1b[1m" if use_ansi else "" + ansi_close = "\x1b[0m" if use_ansi else "" + html_open = "" + html_close = "" + + # Group members by parent key so we can render the tree level by level. + nodes: dict[str, list[tuple[str, Any]]] = {} + for key, node in members: + if key.count("/") == 0: + parent_key = "" + else: + parent_key = key.rsplit("/", 1)[0] + nodes.setdefault(parent_key, []).append((key, node)) + + # Render the tree iteratively (not recursively) to avoid hitting + # Python's recursion limit on deeply nested hierarchies. + # Each stack frame is (prefix_string, remaining_children_at_this_level). + text_lines = [f"{ansi_open}{group.name}{ansi_close}"] + html_lines = [f"{html_open}{html_escape(group.name)}{html_close}"] + stack = [("", deque(nodes.get("", [])))] + while stack: + prefix, remaining = stack[-1] + if not remaining: + stack.pop() + continue + key, node = remaining.popleft() + name = key.rsplit("/")[-1] + escaped_name = html_escape(name) + # if we popped the last item then remaining will + # now be empty - that's how we got past the if not remaining + # above, but this can still be true. + is_last = not remaining + connector = "└── " if is_last else "β”œβ”€β”€ " + if isinstance(node, AsyncGroup): + text_lines.append(f"{prefix}{connector}{ansi_open}{name}{ansi_close}") + html_lines.append(f"{prefix}{connector}{html_open}{escaped_name}{html_close}") + else: + text_lines.append( + f"{prefix}{connector}{ansi_open}{name}{ansi_close} {node.shape} {node.dtype}" + ) + html_lines.append( + f"{prefix}{connector}{html_open}{escaped_name}{html_close}" + f" {html_escape(str(node.shape))} {html_escape(str(node.dtype))}" + ) + # Descend into children with an accumulated prefix: + # Example showing how prefix accumulates: + # / + # β”œβ”€β”€ a prefix = "" + # β”‚ β”œβ”€β”€ b prefix = "" + "β”‚ " + # β”‚ β”‚ └── x prefix = "" + "β”‚ " + "β”‚ " + # β”‚ └── c prefix = "" + "β”‚ " + # └── d prefix = "" + # └── e prefix = "" + " " + if children := nodes.get(key, []): + if is_last: + child_prefix = prefix + " " + else: + child_prefix = prefix + "β”‚ " + stack.append((child_prefix, deque(children))) + text = "\n".join(text_lines) + "\n" + html = "\n".join(html_lines) + "\n" + note = ( + f"Truncated at max_nodes={max_nodes}, some nodes and their children may be missing\n" + if truncated + else "" + ) + return TreeRepr(text, html, truncated=note) diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py new file mode 100644 index 0000000000..9cb66f339e --- /dev/null +++ b/src/zarr/core/array.py @@ -0,0 +1,5898 @@ +from __future__ import annotations + +import math +import warnings +from asyncio import gather +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass, field, replace +from itertools import starmap +from logging import getLogger +from typing import ( + TYPE_CHECKING, + Any, + Literal, + TypedDict, + cast, + overload, +) +from warnings import warn + +import numpy as np +from typing_extensions import Sentinel, deprecated + +import zarr +from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec, Codec +from zarr.abc.numcodec import Numcodec, _is_numcodec +from zarr.codecs._v2 import V2Codec +from zarr.codecs.bytes import BytesCodec +from zarr.codecs.vlen_utf8 import VLenBytesCodec, VLenUTF8Codec +from zarr.codecs.zstd import ZstdCodec +from zarr.core._info import ArrayInfo +from zarr.core._json import buffer_to_json_object +from zarr.core.array_spec import ArrayConfig, ArrayConfigLike, ArraySpec, parse_array_config +from zarr.core.attributes import Attributes +from zarr.core.buffer import ( + BufferPrototype, + NDArrayLike, + NDArrayLikeOrScalar, + NDBuffer, + default_buffer_prototype, +) +from zarr.core.buffer.cpu import buffer_prototype as cpu_buffer_prototype +from zarr.core.chunk_grids import ( + SHARDED_INNER_CHUNK_MAX_BYTES, + ChunkGrid, + _is_rectilinear_chunks, + as_regular_shape, + guess_chunks, + normalize_chunks_nd, + resolve_outer_and_inner_chunks, +) +from zarr.core.chunk_key_encodings import ( + ChunkKeyEncoding, + ChunkKeyEncodingLike, + DefaultChunkKeyEncoding, + V2ChunkKeyEncoding, + parse_chunk_key_encoding, +) +from zarr.core.common import ( + JSON, + ZARR_JSON, + ZARRAY_JSON, + ZATTRS_JSON, + ChunksLike, + DimensionNamesLike, + MemoryOrder, + ShapeLike, + ZarrFormat, + _default_zarr_format, + _warn_order_kwarg, + ceildiv, + concurrent_map, + parse_shapelike, + product, +) +from zarr.core.config import config as zarr_config +from zarr.core.dtype import ( + Structured, + VariableLengthBytes, + VariableLengthUTF8, + ZDType, + ZDTypeLike, + parse_dtype, +) +from zarr.core.dtype.common import HasEndianness, HasItemSize, HasObjectCodec +from zarr.core.indexing import ( + AsyncOIndex, + AsyncVIndex, + BasicIndexer, + BasicSelection, + BlockIndex, + BlockIndexer, + CoordinateIndexer, + CoordinateSelection, + Fields, + Indexer, + MaskIndexer, + MaskSelection, + OIndex, + OrthogonalIndexer, + OrthogonalSelection, + Selection, + VIndex, + _iter_grid, + _iter_regions, + check_fields, + check_no_multi_fields, + is_pure_fancy_indexing, + is_pure_orthogonal_indexing, + is_scalar, + pop_fields, +) +from zarr.core.metadata import ( + ArrayMetadata, + ArrayMetadataDict, + ArrayMetadataJSON_V3, + ArrayV2Metadata, + ArrayV2MetadataDict, + ArrayV3Metadata, +) +from zarr.core.metadata.io import save_metadata +from zarr.core.metadata.v2 import ( + CompressorLikev2, + get_object_codec_id, + parse_compressor, + parse_filters, +) +from zarr.core.metadata.v3 import ( + ChunkGridMetadata, + create_chunk_grid_metadata, + parse_node_type_array, +) +from zarr.core.sync import sync +from zarr.errors import ( + ArrayNotFoundError, + ChunkNotFoundError, + MetadataValidationError, + ZarrDeprecationWarning, + ZarrUserWarning, +) +from zarr.registry import ( + _parse_array_array_codec, + _parse_array_bytes_codec, + _parse_bytes_bytes_codec, + get_pipeline_class, +) +from zarr.storage._common import StorePath, ensure_no_existing_node, make_store_path +from zarr.storage._utils import _relativize_path + +if TYPE_CHECKING: + from collections.abc import Iterator + from typing import Self + + import numpy.typing as npt + + from zarr.abc.codec import CodecPipeline + from zarr.abc.store import Store + from zarr.codecs.sharding import IndexLocation + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar + from zarr.storage import StoreLike + from zarr.types import AnyArray, AnyAsyncArray, ArrayV2, ArrayV3, AsyncArrayV2, AsyncArrayV3 + + +# Array and AsyncArray are defined in the base `zarr` namespace +__all__ = [ + "DEFAULT_FILL_VALUE", + "create_codec_pipeline", + "parse_array_metadata", +] + +logger = getLogger(__name__) + + +DEFAULT_FILL_VALUE = Sentinel("DEFAULT_FILL_VALUE") +""" +Sentinel indicating that the default fill value should be used. + +This sentinel exists because conventional values used to convey "defaultness" like `None` or +`"auto"` are ambiguous when specifying the fill value parameter of a Zarr array. +The value `None` is ambiguous because it is a valid fill value for Zarr V2 +(resulting in `"fill_value": null` in array metadata). +A string like `"auto"` is ambiguous because such a string is a valid fill value for an array +with a string data type. +This sentinel lies outside the space of valid fill values, which means it can +unambiguously express that the default fill value should be used. +""" + + +def _chunk_sizes_from_shape( + array_shape: tuple[int, ...], chunk_shape: tuple[int, ...] +) -> tuple[tuple[int, ...], ...]: + """Compute dask-style chunk sizes from an array shape and uniform chunk shape.""" + result: list[tuple[int, ...]] = [] + for s, c in zip(array_shape, chunk_shape, strict=True): + nchunks = ceildiv(s, c) + sizes = tuple(min(c, s - i * c) for i in range(nchunks)) + result.append(sizes) + return tuple(result) + + +def parse_array_metadata(data: Any) -> ArrayMetadata: + if isinstance(data, ArrayMetadata): + return data + elif isinstance(data, dict): + zarr_format = data.get("zarr_format") + if zarr_format == 3: + meta_out = ArrayV3Metadata.from_dict(data) + if len(meta_out.storage_transformers) > 0: + msg = ( + f"Array metadata contains storage transformers: {meta_out.storage_transformers}." + "Arrays with storage transformers are not supported in zarr-python at this time." + ) + raise ValueError(msg) + return meta_out + elif zarr_format == 2: + return ArrayV2Metadata.from_dict(data) + else: + raise ValueError(f"Invalid zarr_format: {zarr_format}. Expected 2 or 3") + raise TypeError # pragma: no cover + + +def create_codec_pipeline(metadata: ArrayMetadata, *, store: Store | None = None) -> CodecPipeline: + if store is not None: + try: + return get_pipeline_class().from_array_metadata_and_store( + array_metadata=metadata, store=store + ) + except NotImplementedError: + pass + + if isinstance(metadata, ArrayV3Metadata): + # The pipeline built here is a throwaway: `evolve_from_array_spec` below + # reconstructs codecs against the evolved spec. `from_codecs` is the + # chain's first construction, so its advisory warnings (e.g. sharding's + # "disables partial reads" warning) fire here; `evolve_from_array_spec` + # re-splits the same already-warned-about chain via + # `codecs_from_list_unchecked`, so it does not re-emit them. + pipeline = get_pipeline_class().from_codecs(metadata.codecs) + from zarr.core.metadata.v3 import RegularChunkGridMetadata + + # Use the regular chunk shape if available, otherwise use a + # placeholder. The ChunkTransform is shape-agnostic β€” the actual + # chunk shape is passed per-call at decode/encode time. + if isinstance(metadata.chunk_grid, RegularChunkGridMetadata): + chunk_shape = metadata.chunk_grid.chunk_shape + else: + chunk_shape = (1,) * len(metadata.shape) + chunk_spec = ArraySpec( + shape=chunk_shape, + dtype=metadata.data_type, + fill_value=metadata.fill_value, + config=ArrayConfig.from_dict({}), + prototype=default_buffer_prototype(), + ) + return pipeline.evolve_from_array_spec(chunk_spec) + elif isinstance(metadata, ArrayV2Metadata): + v2_codec = V2Codec(filters=metadata.filters, compressor=metadata.compressor) + pipeline = get_pipeline_class().from_codecs([v2_codec]) + chunk_spec = ArraySpec( + shape=metadata.chunks, + dtype=metadata.dtype, + fill_value=metadata.fill_value, + config=ArrayConfig.from_dict({"order": metadata.order}), + prototype=default_buffer_prototype(), + ) + return pipeline.evolve_from_array_spec(chunk_spec) + raise TypeError # pragma: no cover + + +async def get_array_metadata( + store_path: StorePath, zarr_format: ZarrFormat | None = 3 +) -> dict[str, JSON]: + if zarr_format == 2: + zarray_bytes, zattrs_bytes = await gather( + (store_path / ZARRAY_JSON).get(prototype=cpu_buffer_prototype), + (store_path / ZATTRS_JSON).get(prototype=cpu_buffer_prototype), + ) + if zarray_bytes is None: + msg = ( + "A Zarr V2 array metadata document was not found in store " + f"{store_path.store!r} at path {store_path.path!r}." + ) + raise ArrayNotFoundError(msg) + elif zarr_format == 3: + zarr_json_bytes = await (store_path / ZARR_JSON).get(prototype=cpu_buffer_prototype) + if zarr_json_bytes is None: + msg = ( + "A Zarr V3 array metadata document was not found in store " + f"{store_path.store!r} at path {store_path.path!r}." + ) + raise ArrayNotFoundError(msg) + elif zarr_format is None: + zarr_json_bytes, zarray_bytes, zattrs_bytes = await gather( + (store_path / ZARR_JSON).get(prototype=cpu_buffer_prototype), + (store_path / ZARRAY_JSON).get(prototype=cpu_buffer_prototype), + (store_path / ZATTRS_JSON).get(prototype=cpu_buffer_prototype), + ) + if zarr_json_bytes is not None and zarray_bytes is not None: + # warn and favor v3 + msg = f"Both zarr.json (Zarr format 3) and .zarray (Zarr format 2) metadata objects exist at {store_path}. Zarr v3 will be used." + warnings.warn(msg, category=ZarrUserWarning, stacklevel=1) + if zarr_json_bytes is None and zarray_bytes is None: + msg = ( + f"Neither Zarr V3 nor Zarr V2 array metadata documents " + f"were found in store {store_path.store!r} at path {store_path.path!r}." + ) + raise ArrayNotFoundError(msg) + # set zarr_format based on which keys were found + if zarr_json_bytes is not None: + zarr_format = 3 + else: + zarr_format = 2 + else: + msg = f"Invalid value for 'zarr_format'. Expected 2, 3, or None. Got '{zarr_format}'." # type: ignore[unreachable] + raise MetadataValidationError(msg) + + metadata_dict: dict[str, JSON] + if zarr_format == 2: + # V2 arrays are comprised of a .zarray and .zattrs objects + assert zarray_bytes is not None + metadata_dict = buffer_to_json_object(zarray_bytes) + zattrs_dict = buffer_to_json_object(zattrs_bytes) if zattrs_bytes is not None else {} + metadata_dict["attributes"] = zattrs_dict + else: + # V3 arrays are comprised of a zarr.json object + assert zarr_json_bytes is not None + metadata_dict = buffer_to_json_object(zarr_json_bytes) + + parse_node_type_array(metadata_dict.get("node_type")) + + return metadata_dict + + +async def _prepare_overwrite( + store_path: StorePath, *, zarr_format: ZarrFormat, overwrite: bool +) -> None: + """ + Prepare a store path for writing a new node. + + If `overwrite` is true and the store supports deletes, any existing node at + `store_path` is deleted. Otherwise, the absence of an existing node is enforced + (raising if one is present). + """ + if overwrite and store_path.store.supports_deletes: + await store_path.delete_dir() + else: + await ensure_no_existing_node(store_path, zarr_format=zarr_format) + + +@dataclass(frozen=True) +class AsyncArray[T_ArrayMetadata: (ArrayV2Metadata, ArrayV3Metadata)]: + """ + An asynchronous array class representing a chunked array stored in a Zarr store. + + Parameters + ---------- + metadata : ArrayMetadata + The metadata of the array. + store_path : StorePath + The path to the Zarr store. + config : ArrayConfigLike, optional + The runtime configuration of the array, by default None. + + Attributes + ---------- + metadata : ArrayMetadata + The metadata of the array. + store_path : StorePath + The path to the Zarr store. + codec_pipeline : CodecPipeline + The codec pipeline used for encoding and decoding chunks. + config : ArrayConfig + The runtime configuration of the array. + """ + + metadata: T_ArrayMetadata + store_path: StorePath + codec_pipeline: CodecPipeline = field(init=False) + _chunk_grid: ChunkGrid = field(init=False) + config: ArrayConfig + + @overload + def __init__( + self: AsyncArrayV2, + metadata: ArrayV2Metadata | ArrayV2MetadataDict, + store_path: StorePath, + config: ArrayConfigLike | None = None, + ) -> None: ... + + @overload + def __init__( + self: AsyncArrayV3, + metadata: ArrayV3Metadata | ArrayMetadataJSON_V3, + store_path: StorePath, + config: ArrayConfigLike | None = None, + ) -> None: ... + + def __init__( + self, + metadata: ArrayMetadata | ArrayMetadataDict, + store_path: StorePath, + config: ArrayConfigLike | None = None, + ) -> None: + metadata_parsed = parse_array_metadata(metadata) + config_parsed = parse_array_config(config) + + object.__setattr__(self, "metadata", metadata_parsed) + object.__setattr__(self, "store_path", store_path) + object.__setattr__(self, "config", config_parsed) + object.__setattr__(self, "_chunk_grid", ChunkGrid.from_metadata(metadata_parsed)) + object.__setattr__( + self, + "codec_pipeline", + create_codec_pipeline(metadata=metadata_parsed, store=store_path.store), + ) + + @classmethod + async def _create( + cls, + store: StoreLike, + *, + # v2 and v3 + shape: ShapeLike, + dtype: ZDTypeLike | ZDType[TBaseDType, TBaseScalar], + zarr_format: ZarrFormat = 3, + fill_value: Any | None = DEFAULT_FILL_VALUE, + attributes: dict[str, JSON] | None = None, + # v3 only + chunk_shape: ShapeLike | None = None, + chunk_key_encoding: ( + ChunkKeyEncodingLike + | tuple[Literal["default"], Literal[".", "/"]] + | tuple[Literal["v2"], Literal[".", "/"]] + | None + ) = None, + codecs: Iterable[Codec | dict[str, JSON]] | None = None, + dimension_names: DimensionNamesLike = None, + # v2 only + chunks: ShapeLike | None = None, + dimension_separator: Literal[".", "/"] | None = None, + order: MemoryOrder | None = None, + filters: Iterable[dict[str, JSON] | Numcodec] | None = None, + compressor: CompressorLike = "auto", + # runtime + overwrite: bool = False, + data: npt.ArrayLike | None = None, + config: ArrayConfigLike | None = None, + ) -> AnyAsyncArray: + """Method to create a new asynchronous array instance. + Deprecated in favor of [`zarr.api.asynchronous.create_array`][]. + """ + + dtype_parsed = parse_dtype(dtype, zarr_format=zarr_format) + store_path = await make_store_path(store) + + shape = parse_shapelike(shape) + + if chunks is not None and chunk_shape is not None: + raise ValueError("Only one of chunk_shape or chunks can be provided.") + + # Unify the v2 (chunks) and v3 (chunk_shape) parameter names + _raw_chunks = chunks if chunks is not None else chunk_shape + + config_parsed = parse_array_config(config) + + result: AnyAsyncArray + if zarr_format == 3: + if dimension_separator is not None: + raise ValueError( + "dimension_separator cannot be used for arrays with zarr_format 3. Use chunk_key_encoding instead." + ) + if filters is not None: + raise ValueError( + "filters cannot be used for arrays with zarr_format 3. Use array-to-array codecs instead." + ) + if compressor != "auto": + raise ValueError( + "compressor cannot be used for arrays with zarr_format 3. Use bytes-to-bytes codecs instead." + ) + + if order is not None: + _warn_order_kwarg() + + item_size = 1 + if isinstance(dtype_parsed, HasItemSize): + item_size = dtype_parsed.item_size + if _raw_chunks is None: + outer_chunks = guess_chunks(shape, item_size) + else: + outer_chunks = normalize_chunks_nd(_raw_chunks, shape) + chunk_grid = create_chunk_grid_metadata(outer_chunks) + result = await cls._create_v3( + store_path, + shape=shape, + dtype=dtype_parsed, + fill_value=fill_value, + chunk_key_encoding=chunk_key_encoding, + codecs=codecs, + dimension_names=dimension_names, + attributes=attributes, + overwrite=overwrite, + config=config_parsed, + chunk_grid=chunk_grid, + ) + elif zarr_format == 2: + if codecs is not None: + raise ValueError( + "codecs cannot be used for arrays with zarr_format 2. Use filters and compressor instead." + ) + if chunk_key_encoding is not None: + raise ValueError( + "chunk_key_encoding cannot be used for arrays with zarr_format 2. Use dimension_separator instead." + ) + if dimension_names is not None: + raise ValueError("dimension_names cannot be used for arrays with zarr_format 2.") + if _is_rectilinear_chunks(_raw_chunks): + raise ValueError("Zarr format 2 does not support rectilinear chunk grids.") + + item_size = 1 + if isinstance(dtype_parsed, HasItemSize): + item_size = dtype_parsed.item_size + _raw = chunks or chunk_shape + if _raw is None: + outer_chunks = guess_chunks(shape, item_size) + else: + outer_chunks = normalize_chunks_nd(_raw, shape) + _chunks = as_regular_shape(outer_chunks) + + if order is None: + order_parsed = config_parsed.order + else: + order_parsed = order + config_parsed = replace(config_parsed, order=order) + + result = await cls._create_v2( + store_path, + shape=shape, + dtype=dtype_parsed, + chunks=_chunks, + dimension_separator=dimension_separator, + fill_value=fill_value, + order=order_parsed, + config=config_parsed, + filters=filters, + compressor=compressor, + attributes=attributes, + overwrite=overwrite, + ) + else: + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + if data is not None: + # insert user-provided data + await result.setitem(..., data) + + return result + + @staticmethod + def _create_metadata_v3( + shape: ShapeLike, + dtype: ZDType[TBaseDType, TBaseScalar], + chunk_grid: ChunkGridMetadata, + fill_value: Any | None = DEFAULT_FILL_VALUE, + chunk_key_encoding: ChunkKeyEncodingLike | None = None, + codecs: Iterable[Codec | dict[str, JSON]] | None = None, + dimension_names: DimensionNamesLike = None, + attributes: dict[str, JSON] | None = None, + ) -> ArrayV3Metadata: + """Create an instance of ArrayV3Metadata.""" + filters: tuple[ArrayArrayCodec, ...] + compressors: tuple[BytesBytesCodec, ...] + + shape = parse_shapelike(shape) + if codecs is None: + # no data types have default filters + filters = () + serializer = default_serializer_v3(dtype) + compressors = default_compressors_v3(dtype) + + codecs_parsed = (*filters, serializer, *compressors) + else: + codecs_parsed = tuple(codecs) + + chunk_key_encoding_parsed: ChunkKeyEncodingLike + if chunk_key_encoding is None: + chunk_key_encoding_parsed = {"name": "default", "separator": "/"} + else: + chunk_key_encoding_parsed = chunk_key_encoding + + if fill_value is DEFAULT_FILL_VALUE or fill_value is None: + # Use dtype's default scalar for the DEFAULT_FILL_VALUE sentinel + # For v3, None is converted to DEFAULT_FILL_VALUE behavior + fill_value_parsed = dtype.default_scalar() + else: + fill_value_parsed = fill_value + + return ArrayV3Metadata( + shape=shape, + data_type=dtype, + chunk_grid=chunk_grid, + chunk_key_encoding=chunk_key_encoding_parsed, + fill_value=fill_value_parsed, + codecs=codecs_parsed, # type: ignore[arg-type] + dimension_names=tuple(dimension_names) if dimension_names else None, + attributes=attributes or {}, + ) + + @classmethod + async def _create_v3( + cls, + store_path: StorePath, + *, + shape: ShapeLike, + dtype: ZDType[TBaseDType, TBaseScalar], + chunk_grid: ChunkGridMetadata, + config: ArrayConfig, + fill_value: Any | None = DEFAULT_FILL_VALUE, + chunk_key_encoding: ( + ChunkKeyEncodingLike + | tuple[Literal["default"], Literal[".", "/"]] + | tuple[Literal["v2"], Literal[".", "/"]] + | None + ) = None, + codecs: Iterable[Codec | dict[str, JSON]] | None = None, + dimension_names: DimensionNamesLike = None, + attributes: dict[str, JSON] | None = None, + overwrite: bool = False, + ) -> AsyncArrayV3: + await _prepare_overwrite(store_path, zarr_format=3, overwrite=overwrite) + + if isinstance(chunk_key_encoding, tuple): + chunk_key_encoding = ( + V2ChunkKeyEncoding(separator=chunk_key_encoding[1]) + if chunk_key_encoding[0] == "v2" + else DefaultChunkKeyEncoding(separator=chunk_key_encoding[1]) + ) + + metadata = cls._create_metadata_v3( + shape=shape, + dtype=dtype, + chunk_grid=chunk_grid, + fill_value=fill_value, + chunk_key_encoding=chunk_key_encoding, + codecs=codecs, + dimension_names=dimension_names, + attributes=attributes, + ) + + array = cls(metadata=metadata, store_path=store_path, config=config) + await array._save_metadata(metadata, ensure_parents=True) + return array + + @staticmethod + def _create_metadata_v2( + shape: tuple[int, ...], + dtype: ZDType[TBaseDType, TBaseScalar], + chunks: tuple[int, ...], + order: MemoryOrder, + dimension_separator: Literal[".", "/"] | None = None, + fill_value: Any | None = DEFAULT_FILL_VALUE, + filters: Iterable[dict[str, JSON] | Numcodec] | None = None, + compressor: CompressorLikev2 = None, + attributes: dict[str, JSON] | None = None, + ) -> ArrayV2Metadata: + if dimension_separator is None: + dimension_separator = "." + + # Handle the DEFAULT_FILL_VALUE sentinel + if fill_value is DEFAULT_FILL_VALUE: + fill_value_parsed: Any = dtype.default_scalar() + else: + # For v2, preserve None as-is (backward compatibility) + fill_value_parsed = fill_value + + return ArrayV2Metadata( + shape=shape, + dtype=dtype, + chunks=chunks, + order=order, + dimension_separator=dimension_separator, + fill_value=fill_value_parsed, + compressor=compressor, + filters=filters, + attributes=attributes, + ) + + @classmethod + async def _create_v2( + cls, + store_path: StorePath, + *, + shape: tuple[int, ...], + dtype: ZDType[TBaseDType, TBaseScalar], + chunks: tuple[int, ...], + order: MemoryOrder, + config: ArrayConfig, + dimension_separator: Literal[".", "/"] | None = None, + fill_value: Any | None = DEFAULT_FILL_VALUE, + filters: Iterable[dict[str, JSON] | Numcodec] | None = None, + compressor: CompressorLike = "auto", + attributes: dict[str, JSON] | None = None, + overwrite: bool = False, + ) -> AsyncArrayV2: + await _prepare_overwrite(store_path, zarr_format=2, overwrite=overwrite) + + compressor_parsed: CompressorLikev2 + if compressor == "auto": + compressor_parsed = default_compressor_v2(dtype) + elif isinstance(compressor, BytesBytesCodec): + raise ValueError( + "Cannot use a BytesBytesCodec as a compressor for zarr v2 arrays. " + "Use a numcodecs codec directly instead." + ) + else: + compressor_parsed = compressor + + if filters is None: + filters = default_filters_v2(dtype) + + metadata = cls._create_metadata_v2( + shape=shape, + dtype=dtype, + chunks=chunks, + order=order, + dimension_separator=dimension_separator, + fill_value=fill_value, + filters=filters, + compressor=compressor_parsed, + attributes=attributes, + ) + + array = cls(metadata=metadata, store_path=store_path, config=config) + await array._save_metadata(metadata, ensure_parents=True) + return array + + @classmethod + def from_dict( + cls, + store_path: StorePath, + data: dict[str, JSON], + ) -> AnyAsyncArray: + """ + Create a Zarr array from a dictionary, with support for both Zarr format 2 and 3 metadata. + + Parameters + ---------- + store_path : StorePath + The path within the store where the array should be created. + + data : dict + A dictionary representing the array data. This dictionary should include necessary metadata + for the array, such as shape, dtype, and other attributes. The format of the metadata + will determine whether a Zarr format 2 or 3 array is created. + + Returns + ------- + AsyncArrayV3 or AsyncArrayV2 + The created Zarr array, either using Zarr format 2 or 3 metadata based on the provided data. + + Raises + ------ + ValueError + If the dictionary data is invalid or incompatible with either Zarr format 2 or 3 array creation. + """ + metadata = parse_array_metadata(data) + return cls(metadata=metadata, store_path=store_path) + + @classmethod + async def open( + cls, + store: StoreLike, + zarr_format: ZarrFormat | None = 3, + ) -> AnyAsyncArray: + """ + Async method to open an existing Zarr array from a given store. + + Parameters + ---------- + store : StoreLike + The store containing the Zarr array. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + zarr_format : ZarrFormat | None, optional + The Zarr format version (default is 3). + + Returns + ------- + AsyncArray + The opened Zarr array. + + Examples + -------- + ```python + import asyncio + import zarr + from zarr.core.array import AsyncArray + + async def example(): + store = zarr.storage.MemoryStore() + # First create an array to open + await zarr.api.asynchronous.create_array( + store=store, shape=(100, 100), dtype="int32" + ) + # Now open it + async_arr = await AsyncArray.open(store) + return async_arr + + async_arr = asyncio.run(example()) + # + ``` + """ + store_path = await make_store_path(store) + metadata_dict = await get_array_metadata(store_path, zarr_format=zarr_format) + # TODO: remove this cast when we have better type hints + _metadata_dict = cast("ArrayMetadataJSON_V3", metadata_dict) + return cls(store_path=store_path, metadata=_metadata_dict) + + @property + def store(self) -> Store: + return self.store_path.store + + @property + @deprecated("Use AsyncArray.config instead.", category=ZarrDeprecationWarning) + def _config(self) -> ArrayConfig: + return self.config + + @property + def ndim(self) -> int: + """Returns the number of dimensions in the Array. + + Returns + ------- + int + The number of dimensions in the Array. + """ + return len(self.metadata.shape) + + @property + def shape(self) -> tuple[int, ...]: + """Returns the shape of the Array. + + Returns + ------- + tuple + The shape of the Array. + """ + return self.metadata.shape + + @property + def chunks(self) -> tuple[int, ...]: + """Returns the chunk shape of the Array. + If sharding is used the inner chunk shape is returned. + + Only defined for arrays using a regular chunk grid. + If array uses a rectilinear chunk grid, `NotImplementedError` is raised. + + Returns + ------- + tuple[int, ...]: + The chunk shape of the Array. + """ + # TODO: move sharding awareness out of metadata + return self.metadata.chunks + + @property + def read_chunk_sizes(self) -> tuple[tuple[int, ...], ...]: + """Per-dimension data sizes of chunks used for reading, clipped to the array extent. + + Boundary chunks that extend past the array shape are clipped, so + the last size along a dimension may be smaller than the declared + chunk size. This matches the dask `Array.chunks` convention. + + When sharding is used, returns the inner chunk sizes. + Otherwise, returns the outer chunk sizes (same as `write_chunk_sizes`). + + Returns + ------- + tuple[tuple[int, ...], ...] + One inner tuple per dimension containing the data size of each + chunk (not the encoded buffer size). + + Examples + -------- + >>> arr = zarr.create_array({}, dtype="i1", shape=(100, 80), chunks=(30, 40)) + >>> arr.read_chunk_sizes + ((30, 30, 30, 10), (40, 40)) + """ + + from zarr.codecs.sharding import ShardingCodec + + codecs: tuple[Codec, ...] = getattr(self.metadata, "codecs", ()) + if len(codecs) == 1 and isinstance(codecs[0], ShardingCodec): + inner_chunk_shape = codecs[0].chunk_shape + return _chunk_sizes_from_shape(self.shape, inner_chunk_shape) + return self._chunk_grid.chunk_sizes + + @property + def write_chunk_sizes(self) -> tuple[tuple[int, ...], ...]: + """Per-dimension data sizes of storage chunks, clipped to the array extent. + + Always returns the outer chunk sizes, regardless of sharding. + Boundary chunks that extend past the array shape are clipped, so + the last size along a dimension may be smaller than the declared + chunk size. This matches the dask `Array.chunks` convention. + + Returns + ------- + tuple[tuple[int, ...], ...] + One inner tuple per dimension containing the data size of each + chunk (not the encoded buffer size). + + Examples + -------- + >>> import zarr.storage + >>> arr = zarr.create_array({}, dtype="i1", shape=(100, 80), chunks=(30, 40)) + >>> arr.write_chunk_sizes + ((30, 30, 30, 10), (40, 40)) + """ + + return self._chunk_grid.chunk_sizes + + @property + def shards(self) -> tuple[int, ...] | None: + """Returns the shard shape of the Array. + Returns None if sharding is not used. + + Only defined for arrays using a regular chunk grid. + If array uses a rectilinear chunk grid, `NotImplementedError` is raised. + + Returns + ------- + tuple[int, ...]: + The shard shape of the Array. + """ + return self.metadata.shards + + @property + def size(self) -> int: + """Returns the total number of elements in the array + + Returns + ------- + int + Total number of elements in the array + """ + return math.prod(self.metadata.shape) + + @property + def filters(self) -> tuple[Numcodec, ...] | tuple[ArrayArrayCodec, ...]: + """ + Filters that are applied to each chunk of the array, in order, before serializing that + chunk to bytes. + """ + if self.metadata.zarr_format == 2: + filters = self.metadata.filters + if filters is None: + return () + return filters + + return tuple( + codec for codec in self.metadata.inner_codecs if isinstance(codec, ArrayArrayCodec) + ) + + @property + def serializer(self) -> ArrayBytesCodec | None: + """ + Array-to-bytes codec to use for serializing the chunks into bytes. + """ + if self.metadata.zarr_format == 2: + return None + + return next( + codec for codec in self.metadata.inner_codecs if isinstance(codec, ArrayBytesCodec) + ) + + @property + @deprecated("Use AsyncArray.compressors instead.", category=ZarrDeprecationWarning) + def compressor(self) -> Numcodec | None: + """ + Compressor that is applied to each chunk of the array. + + !!! warning "Deprecated" + `Array.compressor` is deprecated since v3.0.0 and will be removed in a future release. + Use [`Array.compressors`][zarr.AsyncArray.compressors] instead. + """ + if self.metadata.zarr_format == 2: + return self.metadata.compressor + raise TypeError("`compressor` is not available for Zarr format 3 arrays.") + + @property + def compressors(self) -> tuple[Numcodec, ...] | tuple[BytesBytesCodec, ...]: + """ + Compressors that are applied to each chunk of the array. Compressors are applied in order, and after any + filters are applied (if any are specified) and the data is serialized into bytes. + """ + if self.metadata.zarr_format == 2: + if self.metadata.compressor is not None: + return (self.metadata.compressor,) + return () + + return tuple( + codec for codec in self.metadata.inner_codecs if isinstance(codec, BytesBytesCodec) + ) + + @property + def _zdtype(self) -> ZDType[TBaseDType, TBaseScalar]: + """ + The zarr-specific representation of the array data type + """ + # `dtype` returns the zarr dtype object for both v2 and v3 metadata + # (on v3 it is an alias for `data_type`). + return self.metadata.dtype + + @property + def dtype(self) -> TBaseDType: + """Returns the data type of the array. + + Returns + ------- + np.dtype + Data type of the array + """ + return self._zdtype.to_native_dtype() + + @property + def order(self) -> MemoryOrder: + """Returns the memory order of the array. + + Returns + ------- + bool + Memory order of the array + """ + if self.metadata.zarr_format == 2: + return self.metadata.order + else: + return self.config.order + + @property + def attrs(self) -> dict[str, JSON]: + """Returns the attributes of the array. + + Returns + ------- + dict + Attributes of the array + """ + return self.metadata.attributes + + @property + def read_only(self) -> bool: + """Returns True if the array is read-only. + + Returns + ------- + bool + True if the array is read-only + """ + # Backwards compatibility for 2.x + return self.store_path.read_only + + @property + def path(self) -> str: + """Storage path. + + Returns + ------- + str + The path to the array in the Zarr store. + """ + return self.store_path.path + + @property + def name(self) -> str: + """Array name following h5py convention. + + Returns + ------- + str + The name of the array. + """ + # follow h5py convention: add leading slash + name = self.path + if not name.startswith("/"): + name = "/" + name + return name + + @property + def basename(self) -> str: + """Final component of name. + + Returns + ------- + str + The basename or final component of the array name. + """ + return self.name.split("/")[-1] + + @property + def cdata_shape(self) -> tuple[int, ...]: + """ + The number of chunks along each dimension. + + When sharding is used, this counts inner chunks (not shards) per dimension. + + Returns + ------- + tuple[int, ...] + The number of chunks along each dimension. + """ + return self._chunk_grid_shape + + @property + def _chunk_grid_shape(self) -> tuple[int, ...]: + """ + The number of chunks along each dimension. + + When sharding is used, this counts inner chunks (not shards) per dimension. + + Returns + ------- + tuple[int, ...] + The number of chunks along each dimension. + """ + # TODO: refactor β€” extract a sharding_codec property on ArrayV3Metadata + # to replace the repeated `len == 1 and isinstance` pattern. + from zarr.codecs.sharding import ShardingCodec + + codecs: tuple[Codec, ...] = getattr(self.metadata, "codecs", ()) + if len(codecs) == 1 and isinstance(codecs[0], ShardingCodec): + # When sharding, count inner chunks across the whole array + chunk_shape = codecs[0].chunk_shape + return tuple(starmap(ceildiv, zip(self.shape, chunk_shape, strict=True))) + return self._chunk_grid.grid_shape + + @property + def _shard_grid_shape(self) -> tuple[int, ...]: + """ + The shape of the shard grid for this array. + + When no shards are present this will automatically fall back to the chunk grid. + + Returns + ------- + tuple[int, ...] + The shape of the shard grid for this array. + """ + if self.shards is None: + shard_shape = self.chunks + else: + shard_shape = self.shards + return tuple(starmap(ceildiv, zip(self.shape, shard_shape, strict=True))) + + @property + def nchunks(self) -> int: + """ + The number of chunks in this array. + + Note that if a sharding codec is used, then the number of chunks may exceed the number of + stored objects supporting this array. + + Returns + ------- + int + The total number of chunks in the array. + """ + return product(self._chunk_grid_shape) + + @property + def _nshards(self) -> int: + """ + The number of shards in this array. + + If no shards are present this will fall back to giving the number of chunks + + Returns + ------- + int + The total number of shards or if absent, chunks in the array. + """ + return product(self._shard_grid_shape) + + @overload + def with_config(self: AsyncArrayV2, config: ArrayConfigLike) -> AsyncArrayV2: ... + + @overload + def with_config(self: AsyncArrayV3, config: ArrayConfigLike) -> AsyncArrayV3: ... + + def with_config(self, config: ArrayConfigLike) -> Self: + """ + Return a copy of this Array with a new runtime configuration. + + Parameters + ---------- + + config : ArrayConfigLike + The runtime config for the new Array. Any keys not specified will be inherited + from the current array's config. + + Returns + ------- + A new Array + """ + if isinstance(config, ArrayConfig): + new_config = config + else: + # Merge new config with existing config, so missing keys are inherited + # from the current array rather than from global defaults + new_config = ArrayConfig(**{**self.config.to_dict(), **config}) # type: ignore[arg-type] + return type(self)(metadata=self.metadata, store_path=self.store_path, config=new_config) + + async def nchunks_initialized(self) -> int: + """ + Calculate the number of chunks that have been initialized in storage. + + This value is calculated as the product of the number of initialized shards and the number + of chunks per shard. For arrays that do not use sharding, the number of chunks per shard is + effectively 1, and in that case the number of chunks initialized is the same as the number + of stored objects associated with an array. + + Returns + ------- + nchunks_initialized : int + The number of chunks that have been initialized. + + Notes + ----- + On [`AsyncArray`][zarr.AsyncArray] this is an asynchronous method, unlike the (synchronous) + property [`Array.nchunks_initialized`][zarr.Array.nchunks_initialized]. + + Examples + -------- + ```python + import asyncio + import zarr.api.asynchronous + + async def example(): + arr = await zarr.api.asynchronous.create(shape=(10,), chunks=(1,)) + count = await arr.nchunks_initialized() + print(f"Initial: {count}") + #> Initial: 0 + await arr.setitem(slice(5), 1) + count = await arr.nchunks_initialized() + print(f"After write: {count}") + #> After write: 5 + return count + + result = asyncio.run(example()) + ``` + """ + return await _nchunks_initialized(self) + + async def _nshards_initialized(self) -> int: + """ + Calculate the number of shards that have been initialized in storage. + + This is the number of shards that have been persisted to the storage backend. + + Returns + ------- + nshards_initialized : int + The number of shards that have been initialized. + + Notes + ----- + On [`AsyncArray`][zarr.AsyncArray] this is an asynchronous method, unlike the (synchronous) + property [`Array._nshards_initialized`][zarr.Array._nshards_initialized]. + + Examples + -------- + ```python + import asyncio + import zarr.api.asynchronous + + async def example(): + arr = await zarr.api.asynchronous.create(shape=(10,), chunks=(2,)) + count = await arr._nshards_initialized() + print(f"Initial: {count}") + #> Initial: 0 + await arr.setitem(slice(5), 1) + count = await arr._nshards_initialized() + print(f"After write: {count}") + #> After write: 3 + return count + + result = asyncio.run(example()) + ``` + """ + return await _nshards_initialized(self) + + async def nbytes_stored(self) -> int: + return await _nbytes_stored(self.store_path) + + def _iter_chunk_coords( + self, *, origin: Sequence[int] | None = None, selection_shape: Sequence[int] | None = None + ) -> Iterator[tuple[int, ...]]: + """ + Create an iterator over the coordinates of chunks in chunk grid space. + + If the `origin` keyword is used, iteration will start at the chunk index specified by `origin`. + The default behavior is to start at the origin of the grid coordinate space. + If the `selection_shape` keyword is used, iteration will be bounded over a contiguous region + ranging from `[origin, origin selection_shape]`, where the upper bound is exclusive as + per python indexing conventions. + + Parameters + ---------- + origin : Sequence[int] | None, default=None + The origin of the selection relative to the array's chunk grid. + selection_shape : Sequence[int] | None, default=None + The shape of the selection in chunk grid coordinates. + + Yields + ------ + chunk_coords: tuple[int, ...] + The coordinates of each chunk in the selection. + """ + return _iter_chunk_coords( + array=self, + origin=origin, + selection_shape=selection_shape, + ) + + def _iter_shard_coords( + self, *, origin: Sequence[int] | None = None, selection_shape: Sequence[int] | None = None + ) -> Iterator[tuple[int, ...]]: + """ + Create an iterator over the coordinates of shards in shard grid space. + + This will fall back to chunk grid space in case no shards are present. + + Note that + + If the `origin` keyword is used, iteration will start at the shard index specified by `origin`. + The default behavior is to start at the origin of the grid coordinate space. + If the `selection_shape` keyword is used, iteration will be bounded over a contiguous region + ranging from `[origin, origin selection_shape]`, where the upper bound is exclusive as + per python indexing conventions. + + Parameters + ---------- + origin : Sequence[int] | None, default=None + The origin of the selection relative to the array's shard grid. + selection_shape : Sequence[int] | None, default=None + The shape of the selection in shard grid coordinates. + + Yields + ------ + chunk_coords: tuple[int, ...] + The coordinates of each shard in the selection or chunk in case of no shard being present. + """ + return _iter_shard_coords( + array=self, + origin=origin, + selection_shape=selection_shape, + ) + + def _iter_shard_keys( + self, *, origin: Sequence[int] | None = None, selection_shape: Sequence[int] | None = None + ) -> Iterator[str]: + """ + Iterate over the keys of the stored objects supporting this array. + + Although only stored objects, e.g. shards should have keys, in case no + shards are present this automatically falls back to chunks. + + Parameters + ---------- + origin : Sequence[int] | None, default=None + The origin of the selection relative to the array's chunk grid. + selection_shape : Sequence[int] | None, default=None + The shape of the selection in shard grid coordinates. + + Yields + ------ + key: str + The storage key of each shard in the selection or in case of no shard + present of each chunk although the latter case is technically incorrect. + """ + # Iterate over the coordinates of chunks in chunk grid space. + return _iter_shard_keys( + array=self, + origin=origin, + selection_shape=selection_shape, + ) + + def _iter_chunk_regions( + self, *, origin: Sequence[int] | None = None, selection_shape: Sequence[int] | None = None + ) -> Iterator[tuple[slice, ...]]: + """ + Iterate over the regions spanned by each chunk. + + Parameters + ---------- + origin : Sequence[int] | None, default=None + The origin of the selection relative to the array's chunk grid. + selection_shape : Sequence[int] | None, default=None + The shape of the selection in chunk grid coordinates. + + Yields + ------ + region: tuple[slice, ...] + A tuple of slice objects representing the region spanned by each chunk in the selection. + """ + return _iter_chunk_regions( + array=self, + origin=origin, + selection_shape=selection_shape, + ) + + def _iter_shard_regions( + self, *, origin: Sequence[int] | None = None, selection_shape: Sequence[int] | None = None + ) -> Iterator[tuple[slice, ...]]: + """ + Iterate over the regions spanned by each shard. + + This will automatically fall back to chunks if no shards are present. + + Parameters + ---------- + origin : Sequence[int] | None, default=None + The origin of the selection relative to the array's shard grid. + selection_shape : Sequence[int] | None, default=None + The shape of the selection in shard grid coordinates. + + Yields + ------ + region: tuple[slice, ...] + A tuple of slice objects representing the region spanned by each shard in the selection or chunk in the + absence of shards. + """ + return _iter_shard_regions(array=self, origin=origin, selection_shape=selection_shape) + + @property + def nbytes(self) -> int: + """ + The total number of bytes that can be stored in the chunks of this array. + + Notes + ----- + This value is calculated by multiplying the number of elements in the array and the size + of each element, the latter of which is determined by the dtype of the array. + For this reason, `nbytes` will likely be inaccurate for arrays with variable-length + dtypes. It is not possible to determine the size of an array with variable-length elements + from the shape and dtype alone. + """ + return self.size * self.dtype.itemsize + + async def _get_selection( + self, + indexer: Indexer, + *, + prototype: BufferPrototype, + out: NDBuffer | None = None, + fields: Fields | None = None, + ) -> NDArrayLikeOrScalar: + return await _get_selection( + self.store_path, + self.metadata, + self.codec_pipeline, + self.config, + self._chunk_grid, + indexer, + prototype=prototype, + out=out, + fields=fields, + ) + + async def getitem( + self, + selection: BasicSelection, + *, + prototype: BufferPrototype | None = None, + ) -> NDArrayLikeOrScalar: + """ + Asynchronous function that retrieves a subset of the array's data based on the provided selection. + + Parameters + ---------- + selection : BasicSelection + A selection object specifying the subset of data to retrieve. + prototype : BufferPrototype, optional + A buffer prototype to use for the retrieved data (default is None). + + Returns + ------- + NDArrayLikeOrScalar + The retrieved subset of the array's data. + + Examples + -------- + >>> async def example(): + ... import zarr.api.asynchronous + ... import zarr.storage + ... + ... async_arr = await zarr.api.asynchronous.create_array( + ... store={}, + ... shape=(100,100), + ... chunks=(10,10), + ... dtype="i4", + ... fill_value=0, + ... ) + ... + ... return await async_arr.getitem((0, 1)) + + >>> import asyncio + >>> asyncio.run(example()) + np.int32(0) + """ + + return await _getitem( + self.store_path, + self.metadata, + self.codec_pipeline, + self.config, + self._chunk_grid, + selection, + prototype=prototype, + ) + + async def get_orthogonal_selection( + self, + selection: OrthogonalSelection, + *, + out: NDBuffer | None = None, + fields: Fields | None = None, + prototype: BufferPrototype | None = None, + ) -> NDArrayLikeOrScalar: + if prototype is None: + prototype = default_buffer_prototype() + indexer = OrthogonalIndexer(selection, self.metadata.shape, self._chunk_grid) + return await _get_selection( + self.store_path, + self.metadata, + self.codec_pipeline, + self.config, + self._chunk_grid, + indexer=indexer, + out=out, + fields=fields, + prototype=prototype, + ) + + async def get_mask_selection( + self, + mask: MaskSelection, + *, + out: NDBuffer | None = None, + fields: Fields | None = None, + prototype: BufferPrototype | None = None, + ) -> NDArrayLikeOrScalar: + if prototype is None: + prototype = default_buffer_prototype() + indexer = MaskIndexer(mask, self.metadata.shape, self._chunk_grid) + return await _get_selection( + self.store_path, + self.metadata, + self.codec_pipeline, + self.config, + self._chunk_grid, + indexer=indexer, + out=out, + fields=fields, + prototype=prototype, + ) + + async def get_coordinate_selection( + self, + selection: CoordinateSelection, + *, + out: NDBuffer | None = None, + fields: Fields | None = None, + prototype: BufferPrototype | None = None, + ) -> NDArrayLikeOrScalar: + if prototype is None: + prototype = default_buffer_prototype() + indexer = CoordinateIndexer(selection, self.metadata.shape, self._chunk_grid) + out_array = await _get_selection( + self.store_path, + self.metadata, + self.codec_pipeline, + self.config, + self._chunk_grid, + indexer=indexer, + out=out, + fields=fields, + prototype=prototype, + ) + if hasattr(out_array, "shape"): + # restore shape + out_array = cast("NDArrayLikeOrScalar", np.array(out_array).reshape(indexer.sel_shape)) + return out_array + + async def _save_metadata(self, metadata: ArrayMetadata, ensure_parents: bool = False) -> None: + """ + Asynchronously save the array metadata. + """ + await save_metadata(self.store_path, metadata, ensure_parents=ensure_parents) + + async def _set_selection( + self, + indexer: Indexer, + value: npt.ArrayLike, + *, + prototype: BufferPrototype, + fields: Fields | None = None, + ) -> None: + return await _set_selection( + self.store_path, + self.metadata, + self.codec_pipeline, + self.config, + self._chunk_grid, + indexer, + value, + prototype=prototype, + fields=fields, + ) + + async def setitem( + self, + selection: BasicSelection, + value: npt.ArrayLike, + prototype: BufferPrototype | None = None, + ) -> None: + """ + Asynchronously set values in the array using basic indexing. + + Parameters + ---------- + selection : BasicSelection + The selection defining the region of the array to set. + + value : numpy.typing.ArrayLike + The values to be written into the selected region of the array. + + prototype : BufferPrototype or None, optional + A prototype buffer that defines the structure and properties of the array chunks being modified. + If None, the default buffer prototype is used. Default is None. + + Returns + ------- + None + This method does not return any value. + + Raises + ------ + IndexError + If the selection is out of bounds for the array. + + ValueError + If the values are not compatible with the array's dtype or shape. + + Notes + ----- + - This method is asynchronous and should be awaited. + - Supports basic indexing, where the selection is contiguous and does not involve advanced indexing. + """ + return await _setitem( + self.store_path, + self.metadata, + self.codec_pipeline, + self.config, + self._chunk_grid, + selection, + value, + prototype=prototype, + ) + + @property + def oindex(self) -> AsyncOIndex[T_ArrayMetadata]: + """Shortcut for orthogonal (outer) indexing, see [get_orthogonal_selection][zarr.Array.get_orthogonal_selection] and + [set_orthogonal_selection][zarr.Array.set_orthogonal_selection] for documentation and examples.""" + return AsyncOIndex(self) + + @property + def vindex(self) -> AsyncVIndex[T_ArrayMetadata]: + """Shortcut for vectorized (inner) indexing, see [get_coordinate_selection][zarr.Array.get_coordinate_selection], + [set_coordinate_selection][zarr.Array.set_coordinate_selection], [get_mask_selection][zarr.Array.get_mask_selection] and + [set_mask_selection][zarr.Array.set_mask_selection] for documentation and examples.""" + return AsyncVIndex(self) + + async def resize(self, new_shape: ShapeLike, delete_outside_chunks: bool = True) -> None: + """ + Asynchronously resize the array to a new shape. + + Parameters + ---------- + new_shape : tuple[int, ...] + The desired new shape of the array. + + delete_outside_chunks : bool, optional + If True (default), chunks that fall outside the new shape will be deleted. If False, + the data in those chunks will be preserved. + + Returns + ------- + AsyncArray + The resized array. + + Raises + ------ + ValueError + If the new shape is incompatible with the current array's chunking configuration. + + Notes + ----- + - This method is asynchronous and should be awaited. + """ + return await _resize(self, new_shape, delete_outside_chunks) + + async def append(self, data: npt.ArrayLike, axis: int = 0) -> tuple[int, ...]: + """Append `data` to `axis`. + + Parameters + ---------- + data : array-like + Data to be appended. + axis : int + Axis along which to append. + + Returns + ------- + new_shape : tuple + + Notes + ----- + The size of all dimensions other than `axis` must match between this + array and `data`. + """ + return await _append(self, data, axis) + + async def update_attributes(self, new_attributes: dict[str, JSON]) -> Self: + """ + Asynchronously update the array's attributes. + + Parameters + ---------- + new_attributes : dict of str to JSON + A dictionary of new attributes to update or add to the array. The keys represent attribute + names, and the values must be JSON-compatible. + + Returns + ------- + AsyncArray + The array with the updated attributes. + + Raises + ------ + ValueError + If the attributes are invalid or incompatible with the array's metadata. + + Notes + ----- + - This method is asynchronous and should be awaited. + - The updated attributes will be merged with existing attributes, and any conflicts will be + overwritten by the new values. + """ + await _update_attributes(self, new_attributes) + return self + + def __repr__(self) -> str: + return f"" + + @property + def info(self) -> Any: + """ + Return the statically known information for an array. + + Returns + ------- + ArrayInfo + + Related + ------- + [zarr.AsyncArray.info_complete][] - All information about a group, including dynamic information + like the number of bytes and chunks written. + + Examples + -------- + >>> import asyncio + >>> arr = asyncio.run( + ... zarr.api.asynchronous.create( + ... path="array", shape=(3, 4, 5), chunks=(2, 2, 2) + ... ) + ... ) + >>> arr.info + Type : Array + Zarr format : 3 + Data type : Float64(endianness='little') + Fill value : 0.0 + Shape : (3, 4, 5) + Chunk shape : (2, 2, 2) + Order : C + Read-only : False + Store type : MemoryStore + Filters : () + Serializer : BytesCodec(endian='little') + Compressors : (ZstdCodec(level=0, checksum=False),) + No. bytes : 480 + """ + return self._info() + + async def info_complete(self) -> Any: + """ + Return all the information for an array, including dynamic information like a storage size. + + In addition to the static information, this provides + + - The count of chunks initialized + - The sum of the bytes written + + Returns + ------- + ArrayInfo + + Related + ------- + [zarr.AsyncArray.info][] - A property giving just the statically known information about an array. + """ + return await _info_complete(self) + + def _info( + self, count_chunks_initialized: int | None = None, count_bytes_stored: int | None = None + ) -> Any: + chunk_shape = self.chunks if self._chunk_grid.is_regular else None + return ArrayInfo( + _zarr_format=self.metadata.zarr_format, + _data_type=self._zdtype, + _fill_value=self.metadata.fill_value, + _shape=self.shape, + _order=self.order, + _shard_shape=self.shards, + _chunk_shape=chunk_shape, + _read_only=self.read_only, + _compressors=self.compressors, + _filters=self.filters, + _serializer=self.serializer, + _store_type=type(self.store_path.store).__name__, + _count_bytes=self.nbytes, + _count_bytes_stored=count_bytes_stored, + _count_chunks_initialized=count_chunks_initialized, + ) + + +# TODO: Array can be a frozen data class again once property setters (e.g. shape) are removed +@dataclass(frozen=False) +class Array[T_ArrayMetadata: (ArrayV2Metadata, ArrayV3Metadata)]: + """ + A Zarr array. + """ + + _async_array: AsyncArray[T_ArrayMetadata] + + @property + def async_array(self) -> AsyncArray[T_ArrayMetadata]: + """An asynchronous version of the current array. Useful for batching requests. + + Returns + ------- + An asynchronous array whose metadata + store matches that of this synchronous array. + """ + return self._async_array + + @property + def config(self) -> ArrayConfig: + """ + The runtime configuration for this array. This is a read-only property. To modify the + runtime configuration, use `Array.with_config` to create a new `Array` with the modified + configuration. + + Returns + ------- + An `ArrayConfig` object that defines the runtime configuration for the array. + """ + return self.async_array.config + + @property + def _chunk_grid(self) -> ChunkGrid: + """The chunk grid for this array, bound to the array's shape.""" + return self.async_array._chunk_grid + + @classmethod + def _create( + cls, + store: StoreLike, + *, + # v2 and v3 + shape: tuple[int, ...], + dtype: ZDTypeLike, + zarr_format: ZarrFormat = 3, + fill_value: Any | None = DEFAULT_FILL_VALUE, + attributes: dict[str, JSON] | None = None, + # v3 only + chunk_shape: tuple[int, ...] | None = None, + chunk_key_encoding: ( + ChunkKeyEncoding + | tuple[Literal["default"], Literal[".", "/"]] + | tuple[Literal["v2"], Literal[".", "/"]] + | None + ) = None, + codecs: Iterable[Codec | dict[str, JSON]] | None = None, + dimension_names: DimensionNamesLike = None, + # v2 only + chunks: tuple[int, ...] | None = None, + dimension_separator: Literal[".", "/"] | None = None, + order: MemoryOrder | None = None, + filters: list[dict[str, JSON]] | None = None, + compressor: CompressorLike = "auto", + # runtime + overwrite: bool = False, + config: ArrayConfigLike | None = None, + ) -> Self: + """Creates a new Array instance from an initialized store. + Deprecated in favor of [`zarr.create_array`][]. + """ + async_array = sync( + AsyncArray._create( + store=store, + shape=shape, + dtype=dtype, + zarr_format=zarr_format, + attributes=attributes, + fill_value=fill_value, + chunk_shape=chunk_shape, + chunk_key_encoding=chunk_key_encoding, + codecs=codecs, + dimension_names=dimension_names, + chunks=chunks, + dimension_separator=dimension_separator, + order=order, + filters=filters, + compressor=compressor, + overwrite=overwrite, + config=config, + ), + ) + return cls(async_array) + + @classmethod + def from_dict( + cls, + store_path: StorePath, + data: dict[str, JSON], + ) -> Self: + """ + Create a Zarr array from a dictionary. + + Parameters + ---------- + store_path : StorePath + The path within the store where the array should be created. + + data : dict + A dictionary representing the array data. This dictionary should include necessary metadata + for the array, such as shape, dtype, fill value, and attributes. + + Returns + ------- + Array + The created Zarr array. + + Raises + ------ + ValueError + If the dictionary data is invalid or missing required fields for array creation. + """ + async_array = AsyncArray.from_dict(store_path=store_path, data=data) + return cls(async_array) + + @classmethod + def open( + cls, + store: StoreLike, + ) -> Self: + """Opens an existing Array from a store. + + Parameters + ---------- + store : StoreLike + Store containing the Array. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + + Returns + ------- + Array + Array opened from the store. + """ + async_array = sync(AsyncArray.open(store)) + return cls(async_array) + + @property + def store(self) -> Store: + return self.async_array.store + + @property + def ndim(self) -> int: + """Returns the number of dimensions in the array. + + Returns + ------- + int + The number of dimensions in the array. + """ + return self.async_array.ndim + + @property + def shape(self) -> tuple[int, ...]: + """Returns the shape of the array. + + Returns + ------- + tuple[int, ...] + The shape of the array. + """ + return self.async_array.shape + + @shape.setter + def shape(self, value: tuple[int, ...]) -> None: + """Sets the shape of the array by calling resize.""" + self.resize(value) + + @property + def chunks(self) -> tuple[int, ...]: + """Returns a tuple of integers describing the length of each dimension of a chunk of the array. + If sharding is used the inner chunk shape is returned. + + Only defined for arrays using a regular chunk grid. + If array uses a rectilinear chunk grid, `NotImplementedError` is raised. + + Returns + ------- + tuple + A tuple of integers representing the length of each dimension of a chunk. + """ + return self.async_array.chunks + + @property + def read_chunk_sizes(self) -> tuple[tuple[int, ...], ...]: + """Per-dimension data sizes of chunks used for reading, clipped to the array extent. + + Boundary chunks that extend past the array shape are clipped, so + the last size along a dimension may be smaller than the declared + chunk size. This matches the dask `Array.chunks` convention. + + When sharding is used, returns the inner chunk sizes. + Otherwise, returns the outer chunk sizes (same as `write_chunk_sizes`). + + Returns + ------- + tuple[tuple[int, ...], ...] + One inner tuple per dimension containing the data size of each + chunk (not the encoded buffer size). + + Examples + -------- + >>> import zarr + >>> arr = zarr.create_array({}, dtype="i1", shape=(100, 80), chunks=(30, 40)) + >>> arr.read_chunk_sizes + ((30, 30, 30, 10), (40, 40)) + """ + return self.async_array.read_chunk_sizes + + @property + def write_chunk_sizes(self) -> tuple[tuple[int, ...], ...]: + """Per-dimension data sizes of storage chunks, clipped to the array extent. + + Always returns the outer chunk sizes, regardless of sharding. + Boundary chunks that extend past the array shape are clipped, so + the last size along a dimension may be smaller than the declared + chunk size. This matches the dask `Array.chunks` convention. + + Returns + ------- + tuple[tuple[int, ...], ...] + One inner tuple per dimension containing the data size of each + chunk (not the encoded buffer size). + + Examples + -------- + >>> import zarr + >>> arr = zarr.create_array({}, dtype="i1", shape=(100, 80), chunks=(30, 40)) + >>> arr.write_chunk_sizes + ((30, 30, 30, 10), (40, 40)) + """ + return self.async_array.write_chunk_sizes + + @property + def shards(self) -> tuple[int, ...] | None: + """Returns a tuple of integers describing the length of each dimension of a shard of the array. + Returns None if sharding is not used. + + Only defined for arrays using a regular chunk grid. + If array uses a rectilinear chunk grid, `NotImplementedError` is raised. + + Returns + ------- + tuple | None + A tuple of integers representing the length of each dimension of a shard or None if sharding is not used. + """ + return self.async_array.shards + + @property + def size(self) -> int: + """Returns the total number of elements in the array. + + Returns + ------- + int + Total number of elements in the array. + """ + return self.async_array.size + + @property + def dtype(self) -> np.dtype[Any]: + """Returns the NumPy data type. + + Returns + ------- + np.dtype + The NumPy data type. + """ + return self.async_array.dtype + + @property + def attrs(self) -> Attributes: + """Returns a [MutableMapping][collections.abc.MutableMapping] containing user-defined attributes. + + Returns + ------- + attrs + A [MutableMapping][collections.abc.MutableMapping] object containing user-defined attributes. + + Notes + ----- + Note that attribute values must be JSON serializable. + """ + return Attributes(self) + + @property + def path(self) -> str: + """Storage path.""" + return self.async_array.path + + @property + def name(self) -> str: + """Array name following h5py convention.""" + return self.async_array.name + + @property + def basename(self) -> str: + """Final component of name.""" + return self.async_array.basename + + @property + def metadata(self) -> ArrayMetadata: + return self.async_array.metadata + + @property + def store_path(self) -> StorePath: + return self.async_array.store_path + + @property + def order(self) -> MemoryOrder: + return self.async_array.order + + @property + def read_only(self) -> bool: + return self.async_array.read_only + + @property + def fill_value(self) -> Any: + return self.metadata.fill_value + + @property + def filters(self) -> tuple[Numcodec, ...] | tuple[ArrayArrayCodec, ...]: + """ + Filters that are applied to each chunk of the array, in order, before serializing that + chunk to bytes. + """ + return self.async_array.filters + + @property + def serializer(self) -> ArrayBytesCodec | None: + """ + Array-to-bytes codec to use for serializing the chunks into bytes. + """ + return self.async_array.serializer + + @property + @deprecated("Use Array.compressors instead.", category=ZarrDeprecationWarning) + def compressor(self) -> Numcodec | None: + """ + Compressor that is applied to each chunk of the array. + + !!! warning "Deprecated" + `array.compressor` is deprecated since v3.0.0 and will be removed in a future release. + Use [`array.compressors`][zarr.Array.compressors] instead. + """ + return self.async_array.compressor + + @property + def compressors(self) -> tuple[Numcodec, ...] | tuple[BytesBytesCodec, ...]: + """ + Compressors that are applied to each chunk of the array. Compressors are applied in order, and after any + filters are applied (if any are specified) and the data is serialized into bytes. + """ + return self.async_array.compressors + + @property + def cdata_shape(self) -> tuple[int, ...]: + """ + The number of chunks along each dimension. + + When sharding is used, this counts inner chunks (not shards) per dimension. + """ + return self._chunk_grid_shape + + @property + def _chunk_grid_shape(self) -> tuple[int, ...]: + """ + The number of chunks along each dimension. + + When sharding is used, this counts inner chunks (not shards) per dimension. + + Returns + ------- + tuple[int, ...] + The number of chunks along each dimension. + """ + return self.async_array._chunk_grid_shape + + @property + def _shard_grid_shape(self) -> tuple[int, ...]: + """ + The shape of the shard grid for this array. + """ + return self.async_array._shard_grid_shape + + @property + def nchunks(self) -> int: + """ + The number of chunks in this array. + + Note that if a sharding codec is used, then the number of chunks may exceed the number of + stored objects supporting this array. + """ + return self.async_array.nchunks + + @property + def _nshards(self) -> int: + """ + The number of shards in the stored representation of this array. + """ + return self.async_array._nshards + + @overload + def with_config(self: ArrayV2, config: ArrayConfigLike) -> ArrayV2: ... + + @overload + def with_config(self: ArrayV3, config: ArrayConfigLike) -> ArrayV3: ... + + def with_config(self, config: ArrayConfigLike) -> Self: + """ + Return a copy of this Array with a new runtime configuration. + + Parameters + ---------- + + config : ArrayConfigLike + The runtime config for the new Array. Any keys not specified will be inherited + from the current array's config. + + Returns + ------- + A new Array + """ + return type(self)(self._async_array.with_config(config)) + + @property + def nbytes(self) -> int: + """ + The total number of bytes that can be stored in the chunks of this array. + + Notes + ----- + This value is calculated by multiplying the number of elements in the array and the size + of each element, the latter of which is determined by the dtype of the array. + For this reason, `nbytes` will likely be inaccurate for arrays with variable-length + dtypes. It is not possible to determine the size of an array with variable-length elements + from the shape and dtype alone. + """ + return self.async_array.nbytes + + @property + def nchunks_initialized(self) -> int: + """ + Calculate the number of chunks that have been initialized in storage. + + This value is calculated as the product of the number of initialized shards and the number of + chunks per shard. For arrays that do not use sharding, the number of chunks per shard is effectively 1, + and in that case the number of chunks initialized is the same as the number of stored objects associated with an + array. For a direct count of the number of initialized stored objects, see `nshards_initialized`. + + Returns + ------- + nchunks_initialized : int + The number of chunks that have been initialized. + + Examples + -------- + >>> arr = zarr.create_array(store={}, dtype="i1", shape=(10,), chunks=(1,), shards=(2,)) + >>> arr.nchunks_initialized + 0 + >>> arr[:5] = 1 + >>> arr.nchunks_initialized + 6 + """ + return sync(self.async_array.nchunks_initialized()) + + @property + def _nshards_initialized(self) -> int: + """ + Calculate the number of shards that have been initialized, i.e. the number of shards that have + been persisted to the storage backend. + + Returns + ------- + nshards_initialized : int + The number of shards that have been initialized. + + Examples + -------- + >>> arr = zarr.create(shape=(10,), chunks=(2,)) + >>> arr._nshards_initialized + 0 + >>> arr[:5] = 1 + >>> arr._nshards_initialized + 3 + """ + return sync(self.async_array._nshards_initialized()) + + def nbytes_stored(self) -> int: + """ + Determine the size, in bytes, of the array actually written to the store. + + Returns + ------- + size : int + """ + return sync(self.async_array.nbytes_stored()) + + def _iter_shard_keys( + self, origin: Sequence[int] | None = None, selection_shape: Sequence[int] | None = None + ) -> Iterator[str]: + """ + Iterate over the storage keys of each shard, relative to an optional origin, and optionally + limited to a contiguous region in chunk grid coordinates. + + If no shards are present this falls back to chunks, though in this case these are then actually + not storage keys. + + Parameters + ---------- + origin : Sequence[int] | None, default=None + The origin of the selection relative to the array's shard grid. + selection_shape : Sequence[int] | None, default=None + The shape of the selection in shard grid coordinates. + + Yields + ------ + str + The storage key of each shard in the selection or chunk though chunks technically do not have + storage keys. + """ + return self.async_array._iter_shard_keys(origin=origin, selection_shape=selection_shape) + + def _iter_chunk_coords( + self, origin: Sequence[int] | None = None, selection_shape: Sequence[int] | None = None + ) -> Iterator[tuple[int, ...]]: + """ + Create an iterator over the coordinates of chunks in chunk grid space. + + If the `origin` keyword is used, iteration will start at the chunk index specified by `origin`. + The default behavior is to start at the origin of the grid coordinate space. + If the `selection_shape` keyword is used, iteration will be bounded over a contiguous region + ranging from `[origin, origin + selection_shape]`, where the upper bound is exclusive as + per python indexing conventions. + + Parameters + ---------- + origin : Sequence[int] | None, default=None + The origin of the selection relative to the array's chunk grid. + selection_shape : Sequence[int] | None, default=None + The shape of the selection in chunk grid coordinates. + + Yields + ------ + tuple[int, ...] + The coordinates of each chunk in the selection. + """ + return self.async_array._iter_chunk_coords(origin=origin, selection_shape=selection_shape) + + def _iter_shard_coords( + self, *, origin: Sequence[int] | None = None, selection_shape: Sequence[int] | None = None + ) -> Iterator[tuple[int, ...]]: + """ + Create an iterator over the coordinates of shards in shard grid space. + + If the `origin` keyword is used, iteration will start at the shard index specified by `origin`. + The default behavior is to start at the origin of the grid coordinate space. + If the `selection_shape` keyword is used, iteration will be bounded over a contiguous region + ranging from `[origin, origin selection_shape]`, where the upper bound is exclusive as + per python indexing conventions. + + Parameters + ---------- + origin : Sequence[int] | None, default=None + The origin of the selection relative to the array's shard grid. + selection_shape : Sequence[int] | None, default=None + The shape of the selection in shard grid coordinates. + + Yields + ------ + tuple[int, ...] + The coordinates of each shard in the selection. + """ + return self.async_array._iter_shard_coords(origin=origin, selection_shape=selection_shape) + + def _iter_chunk_regions( + self, origin: Sequence[int] | None = None, selection_shape: Sequence[int] | None = None + ) -> Iterator[tuple[slice, ...]]: + """ + Iterate over the regions spanned by each chunk. + + Parameters + ---------- + origin : Sequence[int] | None, default=None + The origin of the selection relative to the array's chunk grid. + selection_shape : Sequence[int] | None, default=None + The shape of the selection in chunk grid coordinates. + + Yields + ------ + tuple[slice, ...] + A tuple of slice objects representing the region spanned by each chunk in the selection. + """ + return self.async_array._iter_chunk_regions(origin=origin, selection_shape=selection_shape) + + def _iter_shard_regions( + self, origin: Sequence[int] | None = None, selection_shape: Sequence[int] | None = None + ) -> Iterator[tuple[slice, ...]]: + """ + Iterate over the regions spanned by each shard or chunk if no shard is present. + + Parameters + ---------- + origin : Sequence[int] | None, default=None + The origin of the selection relative to the array's chunk grid. + selection_shape : Sequence[int] | None, default=None + The shape of the selection in chunk grid coordinates. + + Yields + ------ + tuple[slice, ...] + A tuple of slice objects representing the region spanned by each shard or if no shard is present, + chunk in the selection. + """ + return self.async_array._iter_shard_regions(origin=origin, selection_shape=selection_shape) + + def __array__( + self, dtype: npt.DTypeLike | None = None, copy: bool | None = None + ) -> NDArrayLike: + """ + This method is used by numpy when converting zarr.Array into a numpy array. + For more information, see https://numpy.org/devdocs/user/basics.interoperability.html#the-array-method + """ + if copy is False: + msg = "`copy=False` is not supported. This method always creates a copy." + raise ValueError(msg) + + arr = self[...] + arr_np = np.array(arr, dtype=dtype) + + if dtype is not None: + arr_np = arr_np.astype(dtype) + + return arr_np + + def __getitem__(self, selection: Selection) -> NDArrayLikeOrScalar: + """Retrieve data for an item or region of the array. + + Parameters + ---------- + selection : tuple + An integer index or slice or tuple of int/slice objects specifying the + requested item or region for each dimension of the array. + + Returns + ------- + NDArrayLikeOrScalar + An array-like or scalar containing the data for the requested region. + + Examples + -------- + Setup a 1-dimensional array: + + >>> import zarr + >>> import numpy as np + >>> data = np.arange(100, dtype="uint16") + >>> z = zarr.create_array( + ... {}, + ... shape=data.shape, + ... chunks=(10,), + ... dtype=data.dtype, + ... ) + >>> z[:] = data + + Retrieve a single item: + + >>> z[5] + array(5, dtype=uint16) + + Retrieve a region via slicing: + + >>> z[:5] + array([0, 1, 2, 3, 4], dtype=uint16) + >>> z[-5:] + array([95, 96, 97, 98, 99], dtype=uint16) + >>> z[5:10] + array([5, 6, 7, 8, 9], dtype=uint16) + >>> z[5:10:2] + array([5, 7, 9], dtype=uint16) + >>> z[::2] + array([ 0, 2, 4, ..., 94, 96, 98], dtype=uint16) + + Load the entire array into memory: + + >>> z[...] + array([ 0, 1, 2, ..., 97, 98, 99], dtype=uint16) + + Setup a 2-dimensional array: + + >>> data = np.arange(100, dtype="uint16").reshape(10, 10) + >>> z = zarr.create_array( + ... {}, + ... shape=data.shape, + ... chunks=(10, 10), + ... dtype=data.dtype, + ... ) + >>> z[:] = data + + Retrieve an item: + + >>> z[2, 2] + array(22, dtype=uint16) + + Retrieve a region via slicing: + + >>> z[1:3, 1:3] + array([[11, 12], + [21, 22]], dtype=uint16) + >>> z[1:3, :] + array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], + [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]], dtype=uint16) + >>> z[:, 1:3] + array([[ 1, 2], + [11, 12], + [21, 22], + [31, 32], + [41, 42], + [51, 52], + [61, 62], + [71, 72], + [81, 82], + [91, 92]], dtype=uint16) + >>> z[0:5:2, 0:5:2] + array([[ 0, 2, 4], + [20, 22, 24], + [40, 42, 44]], dtype=uint16) + >>> z[::2, ::2] + array([[ 0, 2, 4, 6, 8], + [20, 22, 24, 26, 28], + [40, 42, 44, 46, 48], + [60, 62, 64, 66, 68], + [80, 82, 84, 86, 88]], dtype=uint16) + + Load the entire array into memory: + + >>> z[...] + array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], + [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], + [30, 31, 32, 33, 34, 35, 36, 37, 38, 39], + [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], + [50, 51, 52, 53, 54, 55, 56, 57, 58, 59], + [60, 61, 62, 63, 64, 65, 66, 67, 68, 69], + [70, 71, 72, 73, 74, 75, 76, 77, 78, 79], + [80, 81, 82, 83, 84, 85, 86, 87, 88, 89], + [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]], dtype=uint16) + + Notes + ----- + Slices with step > 1 are supported, but slices with negative step are not. + + For arrays with a structured dtype, see Zarr format 2 for examples of how to use + fields + + Currently the implementation for __getitem__ is provided by + [`vindex`][zarr.Array.vindex] if the indexing is pure fancy indexing (ie a + broadcast-compatible tuple of integer array indices), or by + [`set_basic_selection`][zarr.Array.set_basic_selection] otherwise. + + Effectively, this means that the following indexing modes are supported: + + - integer indexing + - slice indexing + - mixed slice and integer indexing + - boolean indexing + - fancy indexing (vectorized list of integers) + + For specific indexing options including outer indexing, see the + methods listed under Related. + + Related + ------- + [get_basic_selection][zarr.Array.get_basic_selection], [set_basic_selection][zarr.Array.set_basic_selection] + [get_mask_selection][zarr.Array.get_mask_selection], [set_mask_selection][zarr.Array.set_mask_selection], + [get_coordinate_selection][zarr.Array.get_coordinate_selection], [set_coordinate_selection][zarr.Array.set_coordinate_selection], + [get_orthogonal_selection][zarr.Array.get_orthogonal_selection], [set_orthogonal_selection][zarr.Array.set_orthogonal_selection], + [get_block_selection][zarr.Array.get_block_selection], [set_block_selection][zarr.Array.set_block_selection], + [vindex][zarr.Array.vindex], [oindex][zarr.Array.oindex], [blocks][zarr.Array.blocks], [__setitem__][zarr.Array.__setitem__] + """ + + fields, pure_selection = pop_fields(selection) + if is_pure_fancy_indexing(pure_selection, self.ndim): + return self.vindex[cast("CoordinateSelection | MaskSelection", selection)] + elif is_pure_orthogonal_indexing(pure_selection, self.ndim): + return self.get_orthogonal_selection(pure_selection, fields=fields) + else: + return self.get_basic_selection(cast("BasicSelection", pure_selection), fields=fields) + + def __setitem__(self, selection: Selection, value: npt.ArrayLike) -> None: + """Modify data for an item or region of the array. + + Parameters + ---------- + selection : tuple + An integer index or slice or tuple of int/slice specifying the requested + region for each dimension of the array. + value : npt.ArrayLike + An array-like containing the data to be stored in the selection. + + Examples + -------- + Setup a 1-dimensional array: + + >>> import zarr + >>> z = zarr.zeros( + ... shape=(100,), + ... store={}, + ... chunk_shape=(5,), + ... dtype="i4", + ... ) + + Set all array elements to the same scalar value: + + >>> z[...] = 42 + >>> z[...] + array([42, 42, 42, ..., 42, 42, 42], dtype=int32) + + Set a portion of the array: + + >>> z[:10] = np.arange(10) + >>> z[-10:] = np.arange(10)[::-1] + >>> z[...] + array([ 0, 1, 2, ..., 2, 1, 0], dtype=int32) + + Setup a 2-dimensional array: + + >>> z = zarr.zeros( + ... shape=(5, 5), + ... store={}, + ... chunk_shape=(5, 5), + ... dtype="i4", + ... ) + + Set all array elements to the same scalar value: + + >>> z[...] = 42 + + Set a portion of the array: + + >>> z[0, :] = np.arange(z.shape[1]) + >>> z[:, 0] = np.arange(z.shape[0]) + >>> z[...] + array([[ 0, 1, 2, 3, 4], + [ 1, 42, 42, 42, 42], + [ 2, 42, 42, 42, 42], + [ 3, 42, 42, 42, 42], + [ 4, 42, 42, 42, 42]], dtype=int32) + + Notes + ----- + Slices with step > 1 are supported, but slices with negative step are not. + + For arrays with a structured dtype, see Zarr format 2 for examples of how to use + fields + + Currently the implementation for __setitem__ is provided by + [`vindex`][zarr.Array.vindex] if the indexing is pure fancy indexing (ie a + broadcast-compatible tuple of integer array indices), or by + [`set_basic_selection`][zarr.Array.set_basic_selection] otherwise. + + Effectively, this means that the following indexing modes are supported: + + - integer indexing + - slice indexing + - mixed slice and integer indexing + - boolean indexing + - fancy indexing (vectorized list of integers) + + For specific indexing options including outer indexing, see the + methods listed under Related. + + Related + ------- + [get_basic_selection][zarr.Array.get_basic_selection], + [set_basic_selection][zarr.Array.set_basic_selection], + [get_mask_selection][zarr.Array.get_mask_selection], + [set_mask_selection][zarr.Array.set_mask_selection], + [get_coordinate_selection][zarr.Array.get_coordinate_selection], + [set_coordinate_selection][zarr.Array.set_coordinate_selection], + [get_orthogonal_selection][zarr.Array.get_orthogonal_selection], + [set_orthogonal_selection][zarr.Array.set_orthogonal_selection], + [get_block_selection][zarr.Array.get_block_selection], + [set_block_selection][zarr.Array.set_block_selection], + [vindex][zarr.Array.vindex], [oindex][zarr.Array.oindex], + [blocks][zarr.Array.blocks], [__getitem__][zarr.Array.__getitem__] + + """ + # Converting a zarr Array to numpy here avoids a SyncError that occurs when + # value.__getitem__ is called inside the async codec pipeline (which already + # runs within a running event loop). np.asarray triggers Array.__array__, + # which reads the data synchronously before we enter the async context. + if isinstance(value, Array): + value = np.asarray(value) + fields, pure_selection = pop_fields(selection) + if is_pure_fancy_indexing(pure_selection, self.ndim): + self.vindex[cast("CoordinateSelection | MaskSelection", selection)] = value + elif is_pure_orthogonal_indexing(pure_selection, self.ndim): + self.set_orthogonal_selection(pure_selection, value, fields=fields) + else: + self.set_basic_selection(cast("BasicSelection", pure_selection), value, fields=fields) + + def get_basic_selection( + self, + selection: BasicSelection = Ellipsis, + *, + out: NDBuffer | None = None, + prototype: BufferPrototype | None = None, + fields: Fields | None = None, + ) -> NDArrayLikeOrScalar: + """Retrieve data for an item or region of the array. + + Parameters + ---------- + selection : BasicSelection + A selection specifying the requested item or region for each dimension of the + array. May be any combination of int and/or slice or ellipsis for multidimensional arrays. + out : NDBuffer, optional + If given, load the selected data directly into this buffer. + prototype : BufferPrototype, optional + The prototype of the buffer to use for the output data. If not provided, the default buffer prototype is used. + fields : str or sequence of str, optional + For arrays with a structured dtype, one or more fields can be specified to + extract data for. + + Returns + ------- + NDArrayLikeOrScalar + An array-like or scalar containing the data for the requested region. + + Examples + -------- + Setup a 1-dimensional array: + + >>> import zarr + >>> import numpy as np + >>> data = np.arange(100, dtype="uint16") + >>> z = zarr.create_array( + ... {}, + ... shape=data.shape, + ... chunks=(3,), + ... dtype=data.dtype, + ... ) + >>> z[:] = data + + Retrieve a single item: + + >>> z.get_basic_selection(5) + np.uint16(5) + + Retrieve a region via slicing: + + >>> z.get_basic_selection(slice(5)) + array([0, 1, 2, 3, 4], dtype=uint16) + >>> z.get_basic_selection(slice(-5, None)) + array([95, 96, 97, 98, 99], dtype=uint16) + >>> z.get_basic_selection(slice(5, 10)) + array([5, 6, 7, 8, 9], dtype=uint16) + >>> z.get_basic_selection(slice(5, 10, 2)) + array([5, 7, 9], dtype=uint16) + >>> z.get_basic_selection(slice(None, None, 2)) + array([ 0, 2, 4, ..., 94, 96, 98], dtype=uint16) + + Setup a 3-dimensional array: + + >>> data = np.arange(1000).reshape(10, 10, 10) + >>> z = zarr.create_array( + ... {}, + ... shape=data.shape, + ... chunks=(5, 5, 5), + ... dtype=data.dtype, + ... ) + >>> z[:] = data + + Retrieve an item: + + >>> z.get_basic_selection((1, 2, 3)) + np.int64(123) + + Retrieve a region via slicing and Ellipsis: + + >>> z.get_basic_selection((slice(1, 3), slice(1, 3), 0)) + array([[110, 120], + [210, 220]]) + >>> z.get_basic_selection((0, slice(1, 3), slice(None))) + array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], + [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]) + >>> z.get_basic_selection((..., 2)) + array([[ 2, 12, 22, 32, 42, 52, 62, 72, 82, 92], + [102, 112, 122, 132, 142, 152, 162, 172, 182, 192], + ... + [802, 812, 822, 832, 842, 852, 862, 872, 882, 892], + [902, 912, 922, 932, 942, 952, 962, 972, 982, 992]]) + + Notes + ----- + Slices with step > 1 are supported, but slices with negative step are not. + + For arrays with a structured dtype, see Zarr format 2 for examples of how to use + the `fields` parameter. + + This method provides the implementation for accessing data via the + square bracket notation (__getitem__). See [`__getitem__`][zarr.Array.__getitem__] for examples + using the alternative notation. + + Related + ------- + [set_basic_selection][zarr.Array.set_basic_selection], + [get_mask_selection][zarr.Array.get_mask_selection], + [set_mask_selection][zarr.Array.set_mask_selection], + [get_coordinate_selection][zarr.Array.get_coordinate_selection], + [set_coordinate_selection][zarr.Array.set_coordinate_selection], + [get_orthogonal_selection][zarr.Array.get_orthogonal_selection], + [set_orthogonal_selection][zarr.Array.set_orthogonal_selection], + [get_block_selection][zarr.Array.get_block_selection], + [set_block_selection][zarr.Array.set_block_selection], + [vindex][zarr.Array.vindex], [oindex][zarr.Array.oindex], + [blocks][zarr.Array.blocks], [__getitem__][zarr.Array.__getitem__], + [__setitem__][zarr.Array.__setitem__] + + """ + + if prototype is None: + prototype = default_buffer_prototype() + return sync( + self.async_array._get_selection( + BasicIndexer(selection, self.shape, self._chunk_grid), + out=out, + fields=fields, + prototype=prototype, + ) + ) + + def set_basic_selection( + self, + selection: BasicSelection, + value: npt.ArrayLike, + *, + fields: Fields | None = None, + prototype: BufferPrototype | None = None, + ) -> None: + """Modify data for an item or region of the array. + + Parameters + ---------- + selection : tuple + A tuple specifying the requested item or region for each dimension of the + array. May be any combination of int and/or slice or ellipsis for multidimensional arrays. + value : npt.ArrayLike + An array-like containing values to be stored into the array. + fields : str or sequence of str, optional + For arrays with a structured dtype, one or more fields can be specified to set + data for. + prototype : BufferPrototype, optional + The prototype of the buffer used for setting the data. If not provided, the + default buffer prototype is used. + + Examples + -------- + Setup a 1-dimensional array: + + >>> import zarr + >>> z = zarr.zeros( + ... shape=(100,), + ... store={}, + ... chunk_shape=(100,), + ... dtype="i4", + ... ) + + Set all array elements to the same scalar value: + + >>> z.set_basic_selection(..., 42) + >>> z[...] + array([42, 42, 42, ..., 42, 42, 42], dtype=int32) + + Set a portion of the array: + + >>> z.set_basic_selection(slice(10), np.arange(10)) + >>> z.set_basic_selection(slice(-10, None), np.arange(10)[::-1]) + >>> z[...] + array([ 0, 1, 2, ..., 2, 1, 0], dtype=int32) + + Setup a 2-dimensional array: + + >>> z = zarr.zeros( + ... shape=(5, 5), + ... store={}, + ... chunk_shape=(5, 5), + ... dtype="i4", + ... ) + + Set all array elements to the same scalar value: + + >>> z.set_basic_selection(..., 42) + + Set a portion of the array: + + >>> z.set_basic_selection((0, slice(None)), np.arange(z.shape[1])) + >>> z.set_basic_selection((slice(None), 0), np.arange(z.shape[0])) + >>> z[...] + array([[ 0, 1, 2, 3, 4], + [ 1, 42, 42, 42, 42], + [ 2, 42, 42, 42, 42], + [ 3, 42, 42, 42, 42], + [ 4, 42, 42, 42, 42]], dtype=int32) + + Notes + ----- + For arrays with a structured dtype, see Zarr format 2 for examples of how to use + the `fields` parameter. + + This method provides the underlying implementation for modifying data via square + bracket notation, see [`__setitem__`][zarr.Array.__setitem__] for equivalent examples using the + alternative notation. + + Related + ------- + [get_basic_selection][zarr.Array.get_basic_selection], + [get_mask_selection][zarr.Array.get_mask_selection], + [set_mask_selection][zarr.Array.set_mask_selection], + [get_coordinate_selection][zarr.Array.get_coordinate_selection], + [set_coordinate_selection][zarr.Array.set_coordinate_selection], + [get_orthogonal_selection][zarr.Array.get_orthogonal_selection], + [set_orthogonal_selection][zarr.Array.set_orthogonal_selection], + [get_block_selection][zarr.Array.get_block_selection], + [set_block_selection][zarr.Array.set_block_selection], + [vindex][zarr.Array.vindex], [oindex][zarr.Array.oindex], + [blocks][zarr.Array.blocks], [__getitem__][zarr.Array.__getitem__], + [__setitem__][zarr.Array.__setitem__] + + """ + if prototype is None: + prototype = default_buffer_prototype() + indexer = BasicIndexer(selection, self.shape, self._chunk_grid) + sync(self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) + + def get_orthogonal_selection( + self, + selection: OrthogonalSelection, + *, + out: NDBuffer | None = None, + fields: Fields | None = None, + prototype: BufferPrototype | None = None, + ) -> NDArrayLikeOrScalar: + """Retrieve data by making a selection for each dimension of the array. For + example, if an array has 2 dimensions, allows selecting specific rows and/or + columns. The selection for each dimension can be either an integer (indexing a + single item), a slice, an array of integers, or a Boolean array where True + values indicate a selection. + + Parameters + ---------- + selection : tuple + A selection for each dimension of the array. May be any combination of int, + slice, integer array or Boolean array. + out : NDBuffer, optional + If given, load the selected data directly into this buffer. + fields : str or sequence of str, optional + For arrays with a structured dtype, one or more fields can be specified to + extract data for. + prototype : BufferPrototype, optional + The prototype of the buffer to use for the output data. If not provided, the default buffer prototype is used. + + Returns + ------- + NDArrayLikeOrScalar + An array-like or scalar containing the data for the requested selection. + + Examples + -------- + Setup a 2-dimensional array: + + >>> import zarr + >>> import numpy as np + >>> data = np.arange(100).reshape(10, 10) + >>> z = zarr.create_array( + ... {}, + ... shape=data.shape, + ... chunks=data.shape, + ... dtype=data.dtype, + ... ) + >>> z[:] = data + + Retrieve rows and columns via any combination of int, slice, integer array and/or + Boolean array: + + >>> z.get_orthogonal_selection(([1, 4], slice(None))) + array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], + [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]]) + >>> z.get_orthogonal_selection((slice(None), [1, 4])) + array([[ 1, 4], + [11, 14], + [21, 24], + [31, 34], + [41, 44], + [51, 54], + [61, 64], + [71, 74], + [81, 84], + [91, 94]]) + >>> z.get_orthogonal_selection(([1, 4], [1, 4])) + array([[11, 14], + [41, 44]]) + >>> sel = np.zeros(z.shape[0], dtype=bool) + >>> sel[1] = True + >>> sel[4] = True + >>> z.get_orthogonal_selection((sel, sel)) + array([[11, 14], + [41, 44]]) + + For convenience, the orthogonal selection functionality is also available via the + `oindex` property, e.g.: + + >>> z.oindex[[1, 4], :] + array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], + [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]]) + >>> z.oindex[:, [1, 4]] + array([[ 1, 4], + [11, 14], + [21, 24], + [31, 34], + [41, 44], + [51, 54], + [61, 64], + [71, 74], + [81, 84], + [91, 94]]) + >>> z.oindex[[1, 4], [1, 4]] + array([[11, 14], + [41, 44]]) + >>> sel = np.zeros(z.shape[0], dtype=bool) + >>> sel[1] = True + >>> sel[4] = True + >>> z.oindex[sel, sel] + array([[11, 14], + [41, 44]]) + + Notes + ----- + Orthogonal indexing is also known as outer indexing. + + Slices with step > 1 are supported, but slices with negative step are not. + + Related + ------- + [get_basic_selection][zarr.Array.get_basic_selection], + [set_basic_selection][zarr.Array.set_basic_selection], + [get_mask_selection][zarr.Array.get_mask_selection], + [set_mask_selection][zarr.Array.set_mask_selection], + [get_coordinate_selection][zarr.Array.get_coordinate_selection], + [set_coordinate_selection][zarr.Array.set_coordinate_selection], + [set_orthogonal_selection][zarr.Array.set_orthogonal_selection], + [get_block_selection][zarr.Array.get_block_selection], + [set_block_selection][zarr.Array.set_block_selection], + [vindex][zarr.Array.vindex], [oindex][zarr.Array.oindex], + [blocks][zarr.Array.blocks], [__getitem__][zarr.Array.__getitem__], + [__setitem__][zarr.Array.__setitem__] + + """ + if prototype is None: + prototype = default_buffer_prototype() + indexer = OrthogonalIndexer(selection, self.shape, self._chunk_grid) + return sync( + self.async_array._get_selection( + indexer=indexer, out=out, fields=fields, prototype=prototype + ) + ) + + def set_orthogonal_selection( + self, + selection: OrthogonalSelection, + value: npt.ArrayLike, + *, + fields: Fields | None = None, + prototype: BufferPrototype | None = None, + ) -> None: + """Modify data via a selection for each dimension of the array. + + Parameters + ---------- + selection : tuple + A selection for each dimension of the array. May be any combination of int, + slice, integer array or Boolean array. + value : npt.ArrayLike + An array-like array containing the data to be stored in the array. + fields : str or sequence of str, optional + For arrays with a structured dtype, one or more fields can be specified to set + data for. + prototype : BufferPrototype, optional + The prototype of the buffer used for setting the data. If not provided, the + default buffer prototype is used. + + Examples + -------- + Setup a 2-dimensional array: + + >>> import zarr + >>> z = zarr.zeros( + ... shape=(5, 5), + ... store={}, + ... chunk_shape=(5, 5), + ... dtype="i4", + ... ) + + + Set data for a selection of rows: + + >>> z.set_orthogonal_selection(([1, 4], slice(None)), 1) + >>> z[...] + array([[0, 0, 0, 0, 0], + [1, 1, 1, 1, 1], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [1, 1, 1, 1, 1]], dtype=int32) + + Set data for a selection of columns: + + >>> z.set_orthogonal_selection((slice(None), [1, 4]), 2) + >>> z[...] + array([[0, 2, 0, 0, 2], + [1, 2, 1, 1, 2], + [0, 2, 0, 0, 2], + [0, 2, 0, 0, 2], + [1, 2, 1, 1, 2]], dtype=int32) + + Set data for a selection of rows and columns: + + >>> z.set_orthogonal_selection(([1, 4], [1, 4]), 3) + >>> z[...] + array([[0, 2, 0, 0, 2], + [1, 3, 1, 1, 3], + [0, 2, 0, 0, 2], + [0, 2, 0, 0, 2], + [1, 3, 1, 1, 3]], dtype=int32) + + Set data from a 2D array: + + >>> values = np.arange(10).reshape(2, 5) + >>> z.set_orthogonal_selection(([0, 3], ...), values) + >>> z[...] + array([[0, 1, 2, 3, 4], + [1, 3, 1, 1, 3], + [0, 2, 0, 0, 2], + [5, 6, 7, 8, 9], + [1, 3, 1, 1, 3]], dtype=int32) + + For convenience, this functionality is also available via the `oindex` property: + + >>> z.oindex[[1, 4], [1, 4]] = 4 + >>> z[...] + array([[0, 1, 2, 3, 4], + [1, 4, 1, 1, 4], + [0, 2, 0, 0, 2], + [5, 6, 7, 8, 9], + [1, 4, 1, 1, 4]], dtype=int32) + + Notes + ----- + Orthogonal indexing is also known as outer indexing. + + Slices with step > 1 are supported, but slices with negative step are not. + + Related + ------- + [get_basic_selection][zarr.Array.get_basic_selection], + [set_basic_selection][zarr.Array.set_basic_selection], + [get_mask_selection][zarr.Array.get_mask_selection], + [set_mask_selection][zarr.Array.set_mask_selection], + [get_coordinate_selection][zarr.Array.get_coordinate_selection], + [set_coordinate_selection][zarr.Array.set_coordinate_selection], + [get_orthogonal_selection][zarr.Array.get_orthogonal_selection], + [get_block_selection][zarr.Array.get_block_selection], + [set_block_selection][zarr.Array.set_block_selection], + [vindex][zarr.Array.vindex], [oindex][zarr.Array.oindex], + [blocks][zarr.Array.blocks], [__getitem__][zarr.Array.__getitem__], + [__setitem__][zarr.Array.__setitem__] + """ + if prototype is None: + prototype = default_buffer_prototype() + indexer = OrthogonalIndexer(selection, self.shape, self._chunk_grid) + return sync( + self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype) + ) + + def get_mask_selection( + self, + mask: MaskSelection, + *, + out: NDBuffer | None = None, + fields: Fields | None = None, + prototype: BufferPrototype | None = None, + ) -> NDArrayLikeOrScalar: + """Retrieve a selection of individual items, by providing a Boolean array of the + same shape as the array against which the selection is being made, where True + values indicate a selected item. + + Parameters + ---------- + mask : ndarray, bool + A Boolean array of the same shape as the array against which the selection is + being made. + out : NDBuffer, optional + If given, load the selected data directly into this buffer. + fields : str or sequence of str, optional + For arrays with a structured dtype, one or more fields can be specified to + extract data for. + prototype : BufferPrototype, optional + The prototype of the buffer to use for the output data. If not provided, the default buffer prototype is used. + + Returns + ------- + NDArrayLikeOrScalar + An array-like or scalar containing the data for the requested selection. + + Examples + -------- + Setup a 2-dimensional array: + + >>> import zarr + >>> import numpy as np + >>> data = np.arange(100).reshape(10, 10) + >>> z = zarr.create_array( + ... {}, + ... shape=data.shape, + ... chunks=data.shape, + ... dtype=data.dtype, + ... ) + >>> z[:] = data + + Retrieve items by specifying a mask: + + >>> sel = np.zeros_like(z, dtype=bool) + >>> sel[1, 1] = True + >>> sel[4, 4] = True + >>> z.get_mask_selection(sel) + array([11, 44]) + + For convenience, the mask selection functionality is also available via the + `vindex` property: + + >>> z.vindex[sel] + array([11, 44]) + + Notes + ----- + Mask indexing is a form of vectorized or inner indexing, and is equivalent to + coordinate indexing. Internally the mask array is converted to coordinate + arrays by calling `np.nonzero`. + + Related + ------- + [get_basic_selection][zarr.Array.get_basic_selection], + [set_basic_selection][zarr.Array.set_basic_selection], + [set_mask_selection][zarr.Array.set_mask_selection], + [get_orthogonal_selection][zarr.Array.get_orthogonal_selection], + [set_orthogonal_selection][zarr.Array.set_orthogonal_selection], + [get_coordinate_selection][zarr.Array.get_coordinate_selection], + [set_coordinate_selection][zarr.Array.set_coordinate_selection], + [get_block_selection][zarr.Array.get_block_selection], + [set_block_selection][zarr.Array.set_block_selection], + [vindex][zarr.Array.vindex], [oindex][zarr.Array.oindex], + [blocks][zarr.Array.blocks], [__getitem__][zarr.Array.__getitem__], + [__setitem__][zarr.Array.__setitem__] + """ + + if prototype is None: + prototype = default_buffer_prototype() + indexer = MaskIndexer(mask, self.shape, self._chunk_grid) + return sync( + self.async_array._get_selection( + indexer=indexer, out=out, fields=fields, prototype=prototype + ) + ) + + def set_mask_selection( + self, + mask: MaskSelection, + value: npt.ArrayLike, + *, + fields: Fields | None = None, + prototype: BufferPrototype | None = None, + ) -> None: + """Modify a selection of individual items, by providing a Boolean array of the + same shape as the array against which the selection is being made, where True + values indicate a selected item. + + Parameters + ---------- + mask : ndarray, bool + A Boolean array of the same shape as the array against which the selection is + being made. + value : npt.ArrayLike + An array-like containing values to be stored into the array. + fields : str or sequence of str, optional + For arrays with a structured dtype, one or more fields can be specified to set + data for. + + Examples + -------- + Setup a 2-dimensional array: + + >>> import zarr + >>> z = zarr.zeros( + ... shape=(5, 5), + ... store={}, + ... chunk_shape=(5, 5), + ... dtype="i4", + ... ) + + Set data for a selection of items: + + >>> sel = np.zeros_like(z, dtype=bool) + >>> sel[1, 1] = True + >>> sel[4, 4] = True + >>> z.set_mask_selection(sel, 1) + >>> z[...] + array([[0, 0, 0, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 1]], dtype=int32) + + For convenience, this functionality is also available via the `vindex` property: + + >>> z.vindex[sel] = 2 + >>> z[...] + array([[0, 0, 0, 0, 0], + [0, 2, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 2]], dtype=int32) + + Notes + ----- + Mask indexing is a form of vectorized or inner indexing, and is equivalent to + coordinate indexing. Internally the mask array is converted to coordinate + arrays by calling `np.nonzero`. + + Related + ------- + [get_basic_selection][zarr.Array.get_basic_selection], + [set_basic_selection][zarr.Array.set_basic_selection], + [get_mask_selection][zarr.Array.get_mask_selection], + [get_orthogonal_selection][zarr.Array.get_orthogonal_selection], + [set_orthogonal_selection][zarr.Array.set_orthogonal_selection], + [get_coordinate_selection][zarr.Array.get_coordinate_selection], + [set_coordinate_selection][zarr.Array.set_coordinate_selection], + [get_block_selection][zarr.Array.get_block_selection], + [set_block_selection][zarr.Array.set_block_selection], + [vindex][zarr.Array.vindex], [oindex][zarr.Array.oindex], + [blocks][zarr.Array.blocks], [__getitem__][zarr.Array.__getitem__], + [__setitem__][zarr.Array.__setitem__] + + """ + if prototype is None: + prototype = default_buffer_prototype() + indexer = MaskIndexer(mask, self.shape, self._chunk_grid) + sync(self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) + + def get_coordinate_selection( + self, + selection: CoordinateSelection, + *, + out: NDBuffer | None = None, + fields: Fields | None = None, + prototype: BufferPrototype | None = None, + ) -> NDArrayLikeOrScalar: + """Retrieve a selection of individual items, by providing the indices + (coordinates) for each selected item. + + Parameters + ---------- + selection : tuple + An integer (coordinate) array for each dimension of the array. + out : NDBuffer, optional + If given, load the selected data directly into this buffer. + fields : str or sequence of str, optional + For arrays with a structured dtype, one or more fields can be specified to + extract data for. + prototype : BufferPrototype, optional + The prototype of the buffer to use for the output data. If not provided, the default buffer prototype is used. + + Returns + ------- + NDArrayLikeOrScalar + An array-like or scalar containing the data for the requested coordinate selection. + + Examples + -------- + Setup a 2-dimensional array: + + >>> import zarr + >>> import numpy as np + >>> data = np.arange(0, 100, dtype="uint16").reshape((10, 10)) + >>> z = zarr.create_array( + ... {}, + ... shape=data.shape, + ... chunks=(3, 3), + ... dtype=data.dtype, + ... ) + >>> z[:] = data + + Retrieve items by specifying their coordinates: + + >>> z.get_coordinate_selection(([1, 4], [1, 4])) + array([11, 44], dtype=uint16) + + For convenience, the coordinate selection functionality is also available via the + `vindex` property: + + >>> z.vindex[[1, 4], [1, 4]] + array([11, 44], dtype=uint16) + + Notes + ----- + Coordinate indexing is also known as point selection, and is a form of vectorized + or inner indexing. + + Slices are not supported. Coordinate arrays must be provided for all dimensions + of the array. + + Coordinate arrays may be multidimensional, in which case the output array will + also be multidimensional. Coordinate arrays are broadcast against each other + before being applied. The shape of the output will be the same as the shape of + each coordinate array after broadcasting. + + Related + ------- + [get_basic_selection][zarr.Array.get_basic_selection], + [set_basic_selection][zarr.Array.set_basic_selection], + [get_mask_selection][zarr.Array.get_mask_selection], + [set_mask_selection][zarr.Array.set_mask_selection], + [get_orthogonal_selection][zarr.Array.get_orthogonal_selection], + [set_orthogonal_selection][zarr.Array.set_orthogonal_selection], + [set_coordinate_selection][zarr.Array.set_coordinate_selection], + [get_block_selection][zarr.Array.get_block_selection], + [set_block_selection][zarr.Array.set_block_selection], + [vindex][zarr.Array.vindex], [oindex][zarr.Array.oindex], + [blocks][zarr.Array.blocks], [__getitem__][zarr.Array.__getitem__], + [__setitem__][zarr.Array.__setitem__] + + """ + if prototype is None: + prototype = default_buffer_prototype() + indexer = CoordinateIndexer(selection, self.shape, self._chunk_grid) + out_array = sync( + self.async_array._get_selection( + indexer=indexer, out=out, fields=fields, prototype=prototype + ) + ) + + if hasattr(out_array, "shape"): + # restore shape + out_array = np.array(out_array).reshape(indexer.sel_shape) + return out_array + + def set_coordinate_selection( + self, + selection: CoordinateSelection, + value: npt.ArrayLike, + *, + fields: Fields | None = None, + prototype: BufferPrototype | None = None, + ) -> None: + """Modify a selection of individual items, by providing the indices (coordinates) + for each item to be modified. + + Parameters + ---------- + selection : tuple + An integer (coordinate) array for each dimension of the array. + value : npt.ArrayLike + An array-like containing values to be stored into the array. + fields : str or sequence of str, optional + For arrays with a structured dtype, one or more fields can be specified to set + data for. + + Examples + -------- + Setup a 2-dimensional array: + + >>> import zarr + >>> z = zarr.zeros( + ... shape=(5, 5), + ... store={}, + ... chunk_shape=(5, 5), + ... dtype="i4", + ... ) + + Set data for a selection of items: + + >>> z.set_coordinate_selection(([1, 4], [1, 4]), 1) + >>> z[...] + array([[0, 0, 0, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 1]], dtype=int32) + + For convenience, this functionality is also available via the `vindex` property: + + >>> z.vindex[[1, 4], [1, 4]] = 2 + >>> z[...] + array([[0, 0, 0, 0, 0], + [0, 2, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 2]], dtype=int32) + + Notes + ----- + Coordinate indexing is also known as point selection, and is a form of vectorized + or inner indexing. + + Slices are not supported. Coordinate arrays must be provided for all dimensions + of the array. + + Related + ------- + [get_basic_selection][zarr.Array.get_basic_selection], + [set_basic_selection][zarr.Array.set_basic_selection], + [get_mask_selection][zarr.Array.get_mask_selection], + [set_mask_selection][zarr.Array.set_mask_selection], + [get_orthogonal_selection][zarr.Array.get_orthogonal_selection], + [set_orthogonal_selection][zarr.Array.set_orthogonal_selection], + [get_coordinate_selection][zarr.Array.get_coordinate_selection], + [get_block_selection][zarr.Array.get_block_selection], + [set_block_selection][zarr.Array.set_block_selection], + [vindex][zarr.Array.vindex], [oindex][zarr.Array.oindex], + [blocks][zarr.Array.blocks], [__getitem__][zarr.Array.__getitem__], + [__setitem__][zarr.Array.__setitem__] + + """ + if prototype is None: + prototype = default_buffer_prototype() + # setup indexer + indexer = CoordinateIndexer(selection, self.shape, self._chunk_grid) + + # handle value - need ndarray-like flatten value + if not is_scalar(value, self.dtype): + try: + from numcodecs.compat import ensure_ndarray_like + + value = ensure_ndarray_like(value) # TODO replace with agnostic + except TypeError: + # Handle types like `list` or `tuple` + value = np.array(value) # TODO replace with agnostic + if hasattr(value, "shape") and len(value.shape) > 1: + value = np.array(value).reshape(-1) + + if not is_scalar(value, self.dtype) and ( + isinstance(value, NDArrayLike) and indexer.shape != value.shape + ): + raise ValueError( + f"Attempting to set a selection of {indexer.sel_shape[0]} " + f"elements with an array of {value.shape[0]} elements." + ) + + sync(self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) + + def get_block_selection( + self, + selection: BasicSelection, + *, + out: NDBuffer | None = None, + fields: Fields | None = None, + prototype: BufferPrototype | None = None, + ) -> NDArrayLikeOrScalar: + """Retrieve a selection of individual items, by providing the indices + (coordinates) for each selected item. + + Parameters + ---------- + selection : int or slice or tuple of int or slice + An integer (coordinate) or slice for each dimension of the array. + out : NDBuffer, optional + If given, load the selected data directly into this buffer. + fields : str or sequence of str, optional + For arrays with a structured dtype, one or more fields can be specified to + extract data for. + prototype : BufferPrototype, optional + The prototype of the buffer to use for the output data. If not provided, the default buffer prototype is used. + + Returns + ------- + NDArrayLikeOrScalar + An array-like or scalar containing the data for the requested block selection. + + Examples + -------- + Setup a 2-dimensional array: + + >>> import zarr + >>> import numpy as np + >>> data = np.arange(0, 100, dtype="uint16").reshape((10, 10)) + >>> z = zarr.create_array( + ... {}, + ... shape=data.shape, + ... chunks=(3, 3), + ... dtype=data.dtype, + ... ) + >>> z[:] = data + + Retrieve items by specifying their block coordinates: + + >>> z.get_block_selection((1, slice(None))) + array([[30, 31, 32, 33, 34, 35, 36, 37, 38, 39], + [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], + [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]], dtype=uint16) + + Which is equivalent to: + + >>> z[3:6, :] + array([[30, 31, 32, 33, 34, 35, 36, 37, 38, 39], + [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], + [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]], dtype=uint16) + + For convenience, the block selection functionality is also available via the + `blocks` property: + + >>> z.blocks[1] + array([[30, 31, 32, 33, 34, 35, 36, 37, 38, 39], + [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], + [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]], dtype=uint16) + + Notes + ----- + Block indexing is a convenience indexing method to work on individual chunks + with chunk index slicing. It has the same concept as Dask's `Array.blocks` + indexing. + + Slices are supported. However, only with a step size of one. + + Block index arrays may be multidimensional to index multidimensional arrays: + + >>> z.blocks[0, 1:3] + array([[ 3, 4, 5, 6, 7, 8], + [13, 14, 15, 16, 17, 18], + [23, 24, 25, 26, 27, 28]], dtype=uint16) + + Related + ------- + [get_basic_selection][zarr.Array.get_basic_selection], + [set_basic_selection][zarr.Array.set_basic_selection], + [get_mask_selection][zarr.Array.get_mask_selection], + [set_mask_selection][zarr.Array.set_mask_selection], + [get_orthogonal_selection][zarr.Array.get_orthogonal_selection], + [set_orthogonal_selection][zarr.Array.set_orthogonal_selection], + [get_coordinate_selection][zarr.Array.get_coordinate_selection], + [set_coordinate_selection][zarr.Array.set_coordinate_selection], + [set_block_selection][zarr.Array.set_block_selection], + [vindex][zarr.Array.vindex], [oindex][zarr.Array.oindex], + [blocks][zarr.Array.blocks], [__getitem__][zarr.Array.__getitem__], + [__setitem__][zarr.Array.__setitem__] + """ + if prototype is None: + prototype = default_buffer_prototype() + indexer = BlockIndexer(selection, self.shape, self._chunk_grid) + return sync( + self.async_array._get_selection( + indexer=indexer, out=out, fields=fields, prototype=prototype + ) + ) + + def set_block_selection( + self, + selection: BasicSelection, + value: npt.ArrayLike, + *, + fields: Fields | None = None, + prototype: BufferPrototype | None = None, + ) -> None: + """Modify a selection of individual blocks, by providing the chunk indices + (coordinates) for each block to be modified. + + Parameters + ---------- + selection : tuple + An integer (coordinate) or slice for each dimension of the array. + value : npt.ArrayLike + An array-like containing the data to be stored in the block selection. + fields : str or sequence of str, optional + For arrays with a structured dtype, one or more fields can be specified to set + data for. + prototype : BufferPrototype, optional + The prototype of the buffer used for setting the data. If not provided, the + default buffer prototype is used. + + Examples + -------- + Set up a 2-dimensional array: + + >>> import zarr + >>> z = zarr.zeros( + ... shape=(6, 6), + ... store={}, + ... chunk_shape=(2, 2), + ... dtype="i4", + ... ) + + Set data for a selection of items: + + >>> z.set_block_selection((1, 0), 1) + >>> z[...] + array([[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0]], dtype=int32) + + For convenience, this functionality is also available via the `blocks` property: + + >>> z.blocks[2, 1] = 4 + >>> z[...] + array([[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 4, 4, 0, 0], + [0, 0, 4, 4, 0, 0]], dtype=int32) + + >>> z.blocks[:, 2] = 7 + >>> z[...] + array([[0, 0, 0, 0, 7, 7], + [0, 0, 0, 0, 7, 7], + [1, 1, 0, 0, 7, 7], + [1, 1, 0, 0, 7, 7], + [0, 0, 4, 4, 7, 7], + [0, 0, 4, 4, 7, 7]], dtype=int32) + + Notes + ----- + Block indexing is a convenience indexing method to work on individual chunks + with chunk index slicing. It has the same concept as Dask's `Array.blocks` + indexing. + + Slices are supported. However, only with a step size of one. + + Related + ------- + [get_basic_selection][zarr.Array.get_basic_selection], + [set_basic_selection][zarr.Array.set_basic_selection], + [get_mask_selection][zarr.Array.get_mask_selection], + [set_mask_selection][zarr.Array.set_mask_selection], + [get_orthogonal_selection][zarr.Array.get_orthogonal_selection], + [set_orthogonal_selection][zarr.Array.set_orthogonal_selection], + [get_coordinate_selection][zarr.Array.get_coordinate_selection], + [get_block_selection][zarr.Array.get_block_selection], + [set_block_selection][zarr.Array.set_block_selection], + [vindex][zarr.Array.vindex], [oindex][zarr.Array.oindex], + [blocks][zarr.Array.blocks], [__getitem__][zarr.Array.__getitem__], + [__setitem__][zarr.Array.__setitem__] + + """ + if prototype is None: + prototype = default_buffer_prototype() + indexer = BlockIndexer(selection, self.shape, self._chunk_grid) + sync(self.async_array._set_selection(indexer, value, fields=fields, prototype=prototype)) + + @property + def vindex(self) -> VIndex: + """Shortcut for vectorized (inner) indexing, see + [get_coordinate_selection][zarr.Array.get_coordinate_selection], + [set_coordinate_selection][zarr.Array.set_coordinate_selection], + [get_mask_selection][zarr.Array.get_mask_selection] and + [set_mask_selection][zarr.Array.set_mask_selection] for documentation and + examples.""" + return VIndex(self) + + @property + def oindex(self) -> OIndex: + """Shortcut for orthogonal (outer) indexing, see + [get_orthogonal_selection][zarr.Array.get_orthogonal_selection] and + [set_orthogonal_selection][zarr.Array.set_orthogonal_selection] for + documentation and examples.""" + return OIndex(self) + + @property + def blocks(self) -> BlockIndex: + """Shortcut for blocked chunked indexing, see + [get_block_selection][zarr.Array.get_block_selection] and + [set_block_selection][zarr.Array.set_block_selection] for documentation and + examples.""" + return BlockIndex(self) + + def resize(self, new_shape: ShapeLike) -> None: + """ + Change the shape of the array by growing or shrinking one or more + dimensions. This is an in-place operation that modifies the array. + + Parameters + ---------- + new_shape : tuple + New shape of the array. + + Notes + ----- + If one or more dimensions are shrunk, any chunks falling outside the + new array shape will be deleted from the underlying store. + However, it is noteworthy that the chunks partially falling inside the new array + (i.e. boundary chunks) will remain intact, and therefore, + the data falling outside the new array but inside the boundary chunks + would be restored by a subsequent resize operation that grows the array size. + + Examples + -------- + ```python + import zarr + z = zarr.zeros(shape=(10000, 10000), + chunk_shape=(1000, 1000), + dtype="int32",) + z.shape + #> (10000, 10000) + z.resize((20000, 1000)) + z.shape + #> (20000, 1000) + z.resize((50, 50)) + z.shape + #>(50, 50) + ``` + """ + sync(self.async_array.resize(new_shape)) + + def append(self, data: npt.ArrayLike, axis: int = 0) -> tuple[int, ...]: + """Append `data` to `axis`. + + Parameters + ---------- + data : array-like + Data to be appended. + axis : int + Axis along which to append. + + Returns + ------- + new_shape : tuple + + Notes + ----- + The size of all dimensions other than `axis` must match between this + array and `data`. + + Examples + -------- + >>> import numpy as np + >>> import zarr + >>> a = np.arange(10000000, dtype="i4").reshape(10000, 1000) + >>> z = zarr.array(a, chunks=(1000, 100)) + >>> z.shape + (10000, 1000) + >>> z.append(a) + (20000, 1000) + >>> z.append(np.vstack([a, a]), axis=1) + (20000, 2000) + >>> z.shape + (20000, 2000) + """ + return sync(self.async_array.append(data, axis=axis)) + + def update_attributes(self, new_attributes: dict[str, JSON]) -> Self: + """ + Update the array's attributes. + + Parameters + ---------- + new_attributes : dict + A dictionary of new attributes to update or add to the array. The keys represent attribute + names, and the values must be JSON-compatible. + + Returns + ------- + Array + The array with the updated attributes. + + Raises + ------ + ValueError + If the attributes are invalid or incompatible with the array's metadata. + + Notes + ----- + - The updated attributes will be merged with existing attributes, and any conflicts will be + overwritten by the new values. + """ + new_array = sync(self.async_array.update_attributes(new_attributes)) + return type(self)(new_array) + + def __repr__(self) -> str: + return f"" + + @property + def info(self) -> Any: + """ + Return the statically known information for an array. + + Returns + ------- + ArrayInfo + + Related + ------- + [zarr.Array.info_complete][] - All information about a group, + including dynamic information like the number of bytes and chunks written. + + Examples + -------- + >>> arr = zarr.create(shape=(10,), chunks=(2,), dtype="float32") + >>> arr.info + Type : Array + Zarr format : 3 + Data type : Float32(endianness='little') + Fill value : 0.0 + Shape : (10,) + Chunk shape : (2,) + Order : C + Read-only : False + Store type : MemoryStore + Filters : () + Serializer : BytesCodec(endian='little') + Compressors : (ZstdCodec(level=0, checksum=False),) + No. bytes : 40 + """ + return self.async_array.info + + def info_complete(self) -> Any: + """ + Returns all the information about an array, including information from the Store. + + In addition to the statically known information like `name` and `zarr_format`, + this includes additional information like the size of the array in bytes and + the number of chunks written. + + Note that this method will need to read metadata from the store. + + Returns + ------- + ArrayInfo + + Related + ------- + [zarr.Array.info][] - The statically known subset of metadata about an array. + """ + return sync(self.async_array.info_complete()) + + +async def _shards_initialized( + array: AnyAsyncArray, +) -> tuple[str, ...]: + """ + Return the keys of the shards that have been persisted to the storage backend. + + This will fall back to chunks in case no shards are present. + + Parameters + ---------- + array : AsyncArray + The array to inspect. + + Returns + ------- + chunks_initialized : tuple[str, ...] + The keys of the shards or if these are not present, chunks that have been initialized. + + Related + ------- + [nchunks_initialized][zarr.Array.nchunks_initialized] + + """ + store_contents = [ + x async for x in array.store_path.store.list_prefix(prefix=array.store_path.path) + ] + store_contents_relative = [ + _relativize_path(path=key, prefix=array.store_path.path) + for key in store_contents + # obstore can include a directory marker whose key matches the listed prefix; + # it is not an initialized shard and must be excluded before relativizing. + if array.store_path.path == "" or key != array.store_path.path + ] + return tuple( + chunk_key for chunk_key in array._iter_shard_keys() if chunk_key in store_contents_relative + ) + + +type FiltersLike = ( + Iterable[dict[str, JSON] | ArrayArrayCodec | Numcodec] + | ArrayArrayCodec + | Iterable[Numcodec] + | Numcodec + | Literal["auto"] + | None +) +# Union of acceptable types for users to pass in for both v2 and v3 compressors +type CompressorLike = dict[str, JSON] | BytesBytesCodec | Numcodec | Literal["auto"] | None + +type CompressorsLike = ( + Iterable[dict[str, JSON] | BytesBytesCodec | Numcodec] + | Mapping[str, JSON] + | BytesBytesCodec + | Numcodec + | Literal["auto"] + | None +) +type SerializerLike = dict[str, JSON] | ArrayBytesCodec | Literal["auto"] + + +class ShardsConfigParam(TypedDict): + shape: tuple[int, ...] + index_location: IndexLocation | None + + +type ShardsLike = tuple[int, ...] | Sequence[Sequence[int]] | ShardsConfigParam | Literal["auto"] + + +async def from_array( + store: StoreLike, + *, + data: AnyArray | npt.ArrayLike, + write_data: bool = True, + name: str | None = None, + chunks: ChunksLike | Literal["auto", "keep"] = "keep", + shards: ShardsLike | Literal["keep"] | None = "keep", + filters: FiltersLike | Literal["keep"] = "keep", + compressors: CompressorsLike | Literal["keep"] = "keep", + serializer: SerializerLike | Literal["keep"] = "keep", + fill_value: Any | None = DEFAULT_FILL_VALUE, + order: MemoryOrder | None = None, + zarr_format: ZarrFormat | None = None, + attributes: dict[str, JSON] | None = None, + chunk_key_encoding: ChunkKeyEncodingLike | None = None, + dimension_names: DimensionNamesLike = None, + storage_options: dict[str, Any] | None = None, + overwrite: bool = False, + config: ArrayConfigLike | None = None, +) -> AnyAsyncArray: + """Create an array from an existing array or array-like. + + Parameters + ---------- + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + data : Array | array-like + The array to copy. + write_data : bool, default True + Whether to copy the data from the input array to the new array. + If `write_data` is `False`, the new array will be created with the same metadata as the + input array, but without any data. + name : str or None, optional + The name of the array within the store. If `name` is `None`, the array will be located + at the root of the store. + chunks : tuple[int, ...] or Sequence[Sequence[int]] or "auto" or "keep", optional + Chunk shape of the array. + Following values are supported: + + - "auto": Automatically determine the chunk shape based on the array's shape and dtype. + - "keep": Retain the chunk grid of the data array if it is a zarr Array. + - tuple[int, ...]: A tuple of integers representing the chunk shape (regular grid). + - Sequence[Sequence[int]]: Per-dimension chunk edge lists (rectilinear grid). + Rectilinear chunk grids are experimental and must be explicitly enabled + with `zarr.config.set({'array.rectilinear_chunks': True})` while the + feature is stabilizing. + + If not specified, defaults to "keep" if data is a zarr Array, otherwise "auto". + shards : tuple[int, ...], optional + Shard shape of the array. + Following values are supported: + + - "auto": Automatically determine the shard shape based on the array's shape and chunk shape. + - "keep": Retain the shard shape of the data array if it is a zarr Array. + - tuple[int, ...]: A tuple of integers representing the shard shape. + - None: No sharding. + + If not specified, defaults to "keep" if data is a zarr Array, otherwise None. + filters : Iterable[Codec] | Literal["auto", "keep"], optional + Iterable of filters to apply to each chunk of the array, in order, before serializing that + chunk to bytes. + + For Zarr format 3, a "filter" is a codec that takes an array and returns an array, + and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a + dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. + + For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the + order of your filters is consistent with the behavior of each filter. + + The default value of `"keep"` instructs Zarr to infer `filters` from `data`. + If that inference is not possible, Zarr will fall back to the behavior specified by `"auto"`, + which is to choose default filters based on the data type of the array and the Zarr format specified. + For all data types in Zarr V3, and most data types in Zarr V2, the default filters are the empty tuple `()`. + The only cases where default filters are not empty is when the Zarr format is 2, and the + data type is a variable-length data type like [`zarr.dtype.VariableLengthUTF8`][] or + [`zarr.dtype.VariableLengthUTF8`][]. In these cases, the default filters is a tuple with a + single element which is a codec specific to that particular data type. + + To create an array with no filters, provide an empty iterable or the value `None`. + compressors : Iterable[Codec] or "auto" or "keep", optional + List of compressors to apply to the array. Compressors are applied in order, and after any + filters are applied (if any are specified) and the data is serialized into bytes. + + For Zarr format 3, a "compressor" is a codec that takes a bytestream, and + returns another bytestream. Multiple compressors may be provided for Zarr format 3. + + For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may + be provided for Zarr format 2. + + Following values are supported: + + - Iterable[Codec]: List of compressors to apply to the array. + - "auto": Automatically determine the compressors based on the array's dtype. + - "keep": Retain the compressors of the input array if it is a zarr Array. + + If no `compressors` are provided, defaults to "keep" if data is a zarr Array, otherwise "auto". + serializer : dict[str, JSON] | ArrayBytesCodec or "auto" or "keep", optional + Array-to-bytes codec to use for encoding the array data. + Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. + + Following values are supported: + + - dict[str, JSON]: A dict representation of an `ArrayBytesCodec`. + - ArrayBytesCodec: An instance of `ArrayBytesCodec`. + - "auto": a default serializer will be used. These defaults can be changed by modifying the value of + `array.v3_default_serializer` in [`zarr.config`][zarr.config]. + - "keep": Retain the serializer of the input array if it is a zarr Array. + + fill_value : Any, optional + Fill value for the array. + If not specified, defaults to the fill value of the data array. + order : {"C", "F"}, optional + The memory order of the array (default is "C"). + For Zarr format 2, this parameter sets the memory order of the array. + For Zarr format 3, this parameter is deprecated, because memory order + is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory + order for Zarr format 3 arrays is via the `config` parameter, e.g. `{'config': 'C'}`. + If not specified, defaults to the memory order of the data array. + zarr_format : {2, 3}, optional + The zarr format to use when saving. + If not specified, defaults to the zarr format of the data array. + attributes : dict, optional + Attributes for the array. + If not specified, defaults to the attributes of the data array. + chunk_key_encoding : ChunkKeyEncoding, optional + A specification of how the chunk keys are represented in storage. + For Zarr format 3, the default is `{"name": "default", "separator": "/"}}`. + For Zarr format 2, the default is `{"name": "v2", "separator": "."}}`. + If not specified and the data array has the same zarr format as the target array, + the chunk key encoding of the data array is used. + dimension_names : Iterable[str | None] | None + The names of the dimensions (default is None). + Zarr format 3 only. Zarr format 2 arrays should not use this parameter. + If not specified, defaults to the dimension names of the data array. + storage_options : dict, optional + If using an fsspec URL to create the store, these will be passed to the backend implementation. + Ignored otherwise. + overwrite : bool, default False + Whether to overwrite an array with the same name in the store, if one exists. + config : ArrayConfig or ArrayConfigLike, optional + Runtime configuration for the array. + + Returns + ------- + AsyncArray + The array. + + Examples + -------- + Create an array from an existing Array: + + >>> import asyncio + >>> import zarr + >>> store = zarr.storage.LocalStore("example.zarr") + >>> arr = zarr.create_array( + ... store={}, + ... shape=(100,100), + ... chunks=(10,10), + ... dtype="int32", + ... fill_value=0, + ... ) + + >>> arr2 = asyncio.run(from_array(store, data=arr, overwrite=True)) + >>> arr2 + + >>> asyncio.run(store.clear()) # Remove files generated by test + + Create an array from an existing NumPy array: + + >>> arr3 = asyncio.run( + ... from_array({}, data=np.arange(10000, dtype="i4").reshape(100, 100)) + ... ) + >>> arr3 + + + Create an array from any array-like object: + + >>> arr4 = asyncio.run(from_array({}, data=[[1, 2], [3, 4]])) + >>> arr4 + + >>> asyncio.run(arr4.getitem(...)) + array([[1, 2], + [3, 4]]) + + Create an array from an existing Array without copying the data: + + >>> arr5 = asyncio.run(from_array({}, data=Array(arr4), write_data=False)) + >>> arr5 + + >>> asyncio.run(arr5.getitem(...)) + array([[0, 0], + [0, 0]]) + """ + mode: Literal["a"] = "a" + config_parsed = parse_array_config(config) + store_path = await make_store_path(store, path=name, mode=mode, storage_options=storage_options) + + ( + chunks, + shards, + filters, + compressors, + serializer, + fill_value, + order, + zarr_format, + chunk_key_encoding, + dimension_names, + ) = _parse_keep_array_attr( + data=data, + chunks=chunks, + shards=shards, + filters=filters, + compressors=compressors, + serializer=serializer, + fill_value=fill_value, + order=order, + zarr_format=zarr_format, + chunk_key_encoding=chunk_key_encoding, + dimension_names=dimension_names, + ) + if not hasattr(data, "dtype") or not hasattr(data, "shape"): + data = np.array(data) + + result = await init_array( + store_path=store_path, + shape=data.shape, + dtype=data.dtype, + chunks=chunks, + shards=shards, + filters=filters, + compressors=compressors, + serializer=serializer, + fill_value=fill_value, + order=order, + zarr_format=zarr_format, + attributes=attributes, + chunk_key_encoding=chunk_key_encoding, + dimension_names=dimension_names, + overwrite=overwrite, + config=config_parsed, + ) + + if write_data: + if isinstance(data, Array): + + async def _copy_array_region( + chunk_coords: tuple[int, ...] | slice, _data: AnyArray + ) -> None: + arr = await _data.async_array.getitem(chunk_coords) + await result.setitem(chunk_coords, arr) + + # Stream data from the source array to the new array + await concurrent_map( + [(region, data) for region in result._iter_shard_regions()], + _copy_array_region, + zarr.core.config.config.get("async.concurrency"), + ) + else: + + async def _copy_arraylike_region(chunk_coords: slice, _data: NDArrayLike) -> None: + await result.setitem(chunk_coords, _data[chunk_coords]) + + # Stream data from the source array to the new array + await concurrent_map( + [(region, data) for region in result._iter_shard_regions()], + _copy_arraylike_region, + zarr.core.config.config.get("async.concurrency"), + ) + return result + + +async def init_array( + *, + store_path: StorePath, + shape: ShapeLike, + dtype: ZDTypeLike, + chunks: ChunksLike | Literal["auto"] = "auto", + shards: ShardsLike | None = None, + filters: FiltersLike = "auto", + compressors: CompressorsLike = "auto", + serializer: SerializerLike = "auto", + fill_value: Any | None = DEFAULT_FILL_VALUE, + order: MemoryOrder | None = None, + zarr_format: ZarrFormat | None = 3, + attributes: dict[str, JSON] | None = None, + chunk_key_encoding: ChunkKeyEncodingLike | None = None, + dimension_names: DimensionNamesLike = None, + overwrite: bool = False, + config: ArrayConfigLike | None = None, +) -> AnyAsyncArray: + """Create and persist an array metadata document. + + Parameters + ---------- + store_path : StorePath + StorePath instance. The path attribute is the name of the array to initialize. + shape : tuple[int, ...] + Shape of the array. + dtype : ZDTypeLike + Data type of the array. + chunks : tuple[int, ...], optional + Chunk shape of the array. + If not specified, default are guessed based on the shape and dtype. + shards : tuple[int, ...], optional + Shard shape of the array. The default value of `None` results in no sharding at all. + filters : Iterable[Codec] | Literal["auto"], optional + Iterable of filters to apply to each chunk of the array, in order, before serializing that + chunk to bytes. + + For Zarr format 3, a "filter" is a codec that takes an array and returns an array, + and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a + dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. + + For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the + order of your filters is consistent with the behavior of each filter. + + The default value of `"auto"` instructs Zarr to use a default based on the data + type of the array and the Zarr format specified. For all data types in Zarr V3, and most + data types in Zarr V2, the default filters are empty. The only cases where default filters + are not empty is when the Zarr format is 2, and the data type is a variable-length data type like + [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, + the default filters contains a single element which is a codec specific to that particular data type. + + To create an array with no filters, provide an empty iterable or the value `None`. + compressors : Iterable[Codec] | Literal["auto"], optional + List of compressors to apply to the array. Compressors are applied in order, and after any + filters are applied (if any are specified) and the data is serialized into bytes. + + The default value of `"auto"` instructs Zarr to use a default of [`zarr.codecs.ZstdCodec`][]. + + To create an array with no compressors, provide an empty iterable or the value `None`. + serializer : dict[str, JSON] | ArrayBytesCodec | Literal["auto"], optional + Array-to-bytes codec to use for encoding the array data. + Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. + + The default value of `"auto"` instructs Zarr to use a default codec based on the data type of the array. + For most data types this default codec is [`zarr.codecs.BytesCodec`][]. + For [`zarr.dtype.VariableLengthUTF8`][], the default codec is [`zarr.codecs.VlenUTF8Codec`][]. + For [`zarr.dtype.VariableLengthBytes`][], the default codec is [`zarr.codecs.VlenBytesCodec`][]. + fill_value : Any, optional + Fill value for the array. + order : {"C", "F"}, optional + The memory order of the array (default is "C"). + For Zarr format 2, this parameter sets the memory order of the array. + For Zarr format 3, this parameter is deprecated, because memory order + is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory + order for Zarr format 3 arrays is via the `config` parameter, e.g. `{'config': 'C'}`. + If no `order` is provided, a default order will be used. + This default can be changed by modifying the value of `array.order` in [`zarr.config`][zarr.config]. + zarr_format : {2, 3}, optional + The zarr format to use when saving. + attributes : dict, optional + Attributes for the array. + chunk_key_encoding : ChunkKeyEncodingLike, optional + A specification of how the chunk keys are represented in storage. + For Zarr format 3, the default is `{"name": "default", "separator": "/"}}`. + For Zarr format 2, the default is `{"name": "v2", "separator": "."}}`. + dimension_names : Iterable[str], optional + The names of the dimensions (default is None). + Zarr format 3 only. Zarr format 2 arrays should not use this parameter. + overwrite : bool, default False + Whether to overwrite an array with the same name in the store, if one exists. + config : ArrayConfigLike or None, default=None + Configuration for this array. + If `None`, the default array runtime configuration will be used. This default + is stored in the global configuration object. + + Returns + ------- + AsyncArray + The AsyncArray. + """ + + if zarr_format is None: + zarr_format = _default_zarr_format() + + from zarr.codecs.sharding import ShardingCodec + + zdtype = parse_dtype(dtype, zarr_format=zarr_format) + shape_parsed = parse_shapelike(shape) + item_size = zdtype.item_size if isinstance(zdtype, HasItemSize) else 1 + chunk_key_encoding_parsed = _parse_chunk_key_encoding( + chunk_key_encoding, zarr_format=zarr_format + ) + + await _prepare_overwrite(store_path, zarr_format=zarr_format, overwrite=overwrite) + + # Validate rectilinear chunks constraints + if _is_rectilinear_chunks(chunks): + if zarr_format == 2: + raise ValueError("Zarr format 2 does not support rectilinear chunk grids.") + if shards is not None: + raise ValueError( + "Rectilinear chunks with sharding is not supported. " + "Use rectilinear shards instead: " + "chunks=(inner_size, ...), shards=[[shard_sizes], ...]" + ) + + # Normalize the user's chunks into canonical ChunksTuple form + + if chunks == "auto": + max_bytes = None if shards is None else SHARDED_INNER_CHUNK_MAX_BYTES + chunks_normalized = guess_chunks(shape_parsed, item_size, max_bytes=max_bytes) + else: + chunks_normalized = normalize_chunks_nd(chunks, shape_parsed) + + # Resolve chunks + shards into outer_chunks (grid metadata) and + # inner (sub-chunk structure for ShardingCodec, None if no sharding) + outer_chunks, inner = resolve_outer_and_inner_chunks( + array_shape=shape_parsed, + chunks=chunks_normalized, + shard_shape=shards, + item_size=item_size, + ) + + meta: ArrayV2Metadata | ArrayV3Metadata + if zarr_format == 2: + if inner is not None: + msg = ( + "Zarr format 2 arrays can only be created with `shard_shape` set to `None`. " + f"Got `shard_shape={shards}` instead." + ) + + raise ValueError(msg) + if serializer != "auto": + raise ValueError("Zarr format 2 arrays do not support `serializer`.") + + filters_parsed, compressor_parsed = _parse_chunk_encoding_v2( + compressor=compressors, filters=filters, dtype=zdtype + ) + if dimension_names is not None: + raise ValueError("Zarr format 2 arrays do not support dimension names.") + if order is None: + order_parsed = zarr_config.get("array.order") + else: + order_parsed = order + chunk_key_encoding_parsed = cast("V2ChunkKeyEncoding", chunk_key_encoding_parsed) + + meta = AsyncArray._create_metadata_v2( + shape=shape_parsed, + dtype=zdtype, + chunks=as_regular_shape(outer_chunks), + dimension_separator=chunk_key_encoding_parsed.separator, + fill_value=fill_value, + order=order_parsed, + filters=filters_parsed, + compressor=compressor_parsed, + attributes=attributes, + ) + else: + array_array, array_bytes, bytes_bytes = _parse_chunk_encoding_v3( + compressors=compressors, + filters=filters, + serializer=serializer, + dtype=zdtype, + ) + sub_codecs = cast("tuple[Codec, ...]", (*array_array, array_bytes, *bytes_bytes)) + grid = create_chunk_grid_metadata(outer_chunks) + codecs_out: tuple[Codec, ...] + if inner is not None: + inner_chunks_flat = as_regular_shape(inner.outer_chunks) + index_location: IndexLocation = "end" + if isinstance(shards, dict): + index_location = cast("IndexLocation", shards.get("index_location", "end")) + sharding_codec = ShardingCodec( + chunk_shape=inner_chunks_flat, codecs=sub_codecs, index_location=index_location + ) + sharding_codec.validate( + shape=inner_chunks_flat, + dtype=zdtype, + chunk_grid=grid, + ) + codecs_out = (sharding_codec,) + else: + codecs_out = sub_codecs + + if order is not None: + _warn_order_kwarg() + meta = AsyncArray._create_metadata_v3( + shape=shape_parsed, + dtype=zdtype, + fill_value=fill_value, + chunk_grid=grid, + chunk_key_encoding=chunk_key_encoding_parsed, + codecs=codecs_out, + dimension_names=dimension_names, + attributes=attributes, + ) + + arr = AsyncArray(metadata=meta, store_path=store_path, config=config) + await arr._save_metadata(meta, ensure_parents=True) + return arr + + +async def create_array( + store: StoreLike, + *, + name: str | None = None, + shape: ShapeLike | None = None, + dtype: ZDTypeLike | None = None, + data: np.ndarray[Any, np.dtype[Any]] | None = None, + chunks: ChunksLike | Literal["auto"] = "auto", + shards: ShardsLike | None = None, + filters: FiltersLike = "auto", + compressors: CompressorsLike = "auto", + serializer: SerializerLike = "auto", + fill_value: Any | None = DEFAULT_FILL_VALUE, + order: MemoryOrder | None = None, + zarr_format: ZarrFormat | None = 3, + attributes: dict[str, JSON] | None = None, + chunk_key_encoding: ChunkKeyEncodingLike | None = None, + dimension_names: DimensionNamesLike = None, + storage_options: dict[str, Any] | None = None, + overwrite: bool = False, + config: ArrayConfigLike | None = None, + write_data: bool = True, +) -> AnyAsyncArray: + """Create an array. + + Parameters + ---------- + store : StoreLike + StoreLike object to open. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + name : str or None, optional + The name of the array within the store. If `name` is `None`, the array will be located + at the root of the store. + shape : ShapeLike, optional + Shape of the array. Must be `None` if `data` is provided. + dtype : ZDTypeLike | None + Data type of the array. Must be `None` if `data` is provided. + data : np.ndarray, optional + Array-like data to use for initializing the array. If this parameter is provided, the + `shape` and `dtype` parameters must be `None`. + chunks : tuple[int, ...] | Sequence[Sequence[int]] | Literal["auto"], default="auto" + Chunk shape of the array. + If chunks is "auto", a chunk shape is guessed based on the shape of the array and the dtype. + A nested list of per-dimension edge sizes creates a rectilinear grid. + Rectilinear chunk grids are experimental and must be explicitly enabled + with `zarr.config.set({'array.rectilinear_chunks': True})` while the + feature is stabilizing. + shards : tuple[int, ...], optional + Shard shape of the array. The default value of `None` results in no sharding at all. + filters : Iterable[Codec] | Literal["auto"], optional + Iterable of filters to apply to each chunk of the array, in order, before serializing that + chunk to bytes. + + For Zarr format 3, a "filter" is a codec that takes an array and returns an array, + + and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a + dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. + + For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the + order of your filters is consistent with the behavior of each filter. + + The default value of `"auto"` instructs Zarr to use a default based on the data + type of the array and the Zarr format specified. For all data types in Zarr V3, and most + data types in Zarr V2, the default filters are empty. The only cases where default filters + are not empty is when the Zarr format is 2, and the data type is a variable-length data type like + [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, + the default filters contains a single element which is a codec specific to that particular data type. + + To create an array with no filters, provide an empty iterable or the value `None`. + compressors : Iterable[Codec], optional + List of compressors to apply to the array. Compressors are applied in order, and after any + filters are applied (if any are specified) and the data is serialized into bytes. + + For Zarr format 3, a "compressor" is a codec that takes a bytestream, and + returns another bytestream. Multiple compressors may be provided for Zarr format 3. + If no `compressors` are provided, a default set of compressors will be used. + These defaults can be changed by modifying the value of `array.v3_default_compressors` + in [`zarr.config`][zarr.config]. + Use `None` to omit default compressors. + + For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may + be provided for Zarr format 2. + If no `compressor` is provided, a default compressor will be used. + in [`zarr.config`][zarr.config]. + Use `None` to omit the default compressor. + serializer : dict[str, JSON] | ArrayBytesCodec, optional + Array-to-bytes codec to use for encoding the array data. + Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. + If no `serializer` is provided, a default serializer will be used. + These defaults can be changed by modifying the value of `array.v3_default_serializer` + in [`zarr.config`][zarr.config]. + fill_value : Any, optional + Fill value for the array. + order : {"C", "F"}, optional + The memory order of the array (default is "C"). + For Zarr format 2, this parameter sets the memory order of the array. + For Zarr format 3, this parameter is deprecated, because memory order + is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory + order for Zarr format 3 arrays is via the `config` parameter, e.g. `{'config': 'C'}`. + If no `order` is provided, a default order will be used. + This default can be changed by modifying the value of `array.order` in [`zarr.config`][zarr.config]. + zarr_format : {2, 3}, optional + The zarr format to use when saving. + attributes : dict, optional + Attributes for the array. + chunk_key_encoding : ChunkKeyEncodingLike, optional + A specification of how the chunk keys are represented in storage. + For Zarr format 3, the default is `{"name": "default", "separator": "/"}}`. + For Zarr format 2, the default is `{"name": "v2", "separator": "."}}`. + dimension_names : Iterable[str], optional + The names of the dimensions (default is None). + Zarr format 3 only. Zarr format 2 arrays should not use this parameter. + storage_options : dict, optional + If using an fsspec URL to create the store, these will be passed to the backend implementation. + Ignored otherwise. + overwrite : bool, default False + Whether to overwrite an array with the same name in the store, if one exists. + If `True`, all existing paths in the store will be deleted. + config : ArrayConfigLike, optional + Runtime configuration for the array. + write_data : bool + If a pre-existing array-like object was provided to this function via the `data` parameter + then `write_data` determines whether the values in that array-like object should be + written to the Zarr array created by this function. If `write_data` is `False`, then the + array will be left empty. + + Returns + ------- + AsyncArray + The array. + + Examples + -------- + >>> import asyncio + >>> import zarr + >>> asyncio.run( + ... zarr.api.asynchronous.create_array( + ... store={}, + ... shape=(100,100), + ... chunks=(10,10), + ... dtype="i4", + ... fill_value=0 + ... ) + ... ) + + """ + data_parsed, shape_parsed, dtype_parsed = _parse_data_params( + data=data, shape=shape, dtype=dtype + ) + if data_parsed is not None: + return await from_array( + store, + data=data_parsed, + write_data=write_data, + name=name, + chunks=chunks, + shards=shards, + filters=filters, + compressors=compressors, + serializer=serializer, + fill_value=fill_value, + order=order, + zarr_format=zarr_format, + attributes=attributes, + chunk_key_encoding=chunk_key_encoding, + dimension_names=dimension_names, + storage_options=storage_options, + overwrite=overwrite, + config=config, + ) + else: + mode: Literal["a"] = "a" + + store_path = await make_store_path( + store, path=name, mode=mode, storage_options=storage_options + ) + return await init_array( + store_path=store_path, + shape=shape_parsed, + dtype=dtype_parsed, + chunks=chunks, + shards=shards, + filters=filters, + compressors=compressors, + serializer=serializer, + fill_value=fill_value, + order=order, + zarr_format=zarr_format, + attributes=attributes, + chunk_key_encoding=chunk_key_encoding, + dimension_names=dimension_names, + overwrite=overwrite, + config=config, + ) + + +def _parse_keep_array_attr( + data: AnyArray | npt.ArrayLike, + chunks: ChunksLike | Literal["auto", "keep"], + shards: ShardsLike | Literal["keep"] | None, + filters: FiltersLike | Literal["keep"], + compressors: CompressorsLike | Literal["keep"], + serializer: SerializerLike | Literal["keep"], + fill_value: Any | None, + order: MemoryOrder | None, + zarr_format: ZarrFormat | None, + chunk_key_encoding: ChunkKeyEncodingLike | None, + dimension_names: DimensionNamesLike, +) -> tuple[ + ChunksLike | Literal["auto"], + ShardsLike | None, + FiltersLike, + CompressorsLike, + SerializerLike, + Any | None, + MemoryOrder | None, + ZarrFormat, + ChunkKeyEncodingLike | None, + DimensionNamesLike, +]: + if isinstance(data, Array): + if chunks == "keep": + if data._chunk_grid.is_regular: + chunks = data.chunks + else: + chunks = data.write_chunk_sizes + if shards == "keep": + shards = data.shards if data._chunk_grid.is_regular else None + if zarr_format is None: + zarr_format = data.metadata.zarr_format + if filters == "keep": + if zarr_format == data.metadata.zarr_format: + filters = data.filters or None + else: + filters = "auto" + if compressors == "keep": + if zarr_format == data.metadata.zarr_format: + compressors = data.compressors or None + else: + compressors = "auto" + if serializer == "keep": + if zarr_format == 3 and data.metadata.zarr_format == 3: + serializer = cast("SerializerLike", data.serializer) + else: + serializer = "auto" + if fill_value is None: + fill_value = data.fill_value + + if data.metadata.zarr_format == 2 and zarr_format == 3 and data.order == "F": + # Can't set order="F" for v3 arrays + warnings.warn( + "The 'order' attribute of a Zarr format 2 array does not have a direct analogue in Zarr format 3. " + "The existing order='F' of the source Zarr format 2 array will be ignored.", + ZarrUserWarning, + stacklevel=2, + ) + elif order is None and zarr_format == 2: + order = data.order + + if chunk_key_encoding is None and zarr_format == data.metadata.zarr_format: + if isinstance(data.metadata, ArrayV2Metadata): + chunk_key_encoding = {"name": "v2", "separator": data.metadata.dimension_separator} + elif isinstance(data.metadata, ArrayV3Metadata): + chunk_key_encoding = data.metadata.chunk_key_encoding + if dimension_names is None and data.metadata.zarr_format == 3: + dimension_names = data.metadata.dimension_names + else: + if chunks == "keep": + chunks = "auto" + if shards == "keep": + shards = None + if zarr_format is None: + zarr_format = 3 + if filters == "keep": + filters = "auto" + if compressors == "keep": + compressors = "auto" + if serializer == "keep": + serializer = "auto" + # After resolving "keep" above, chunks is never "keep" at this point. + chunks_out: ChunksLike | Literal["auto"] = chunks + return ( + chunks_out, + shards, + filters, + compressors, + serializer, + fill_value, + order, + zarr_format, + chunk_key_encoding, + dimension_names, + ) + + +def _parse_chunk_key_encoding( + data: ChunkKeyEncodingLike | None, zarr_format: ZarrFormat +) -> ChunkKeyEncoding: + """ + Take an implicit specification of a chunk key encoding and parse it into a ChunkKeyEncoding object. + """ + if data is None: + if zarr_format == 2: + data = {"name": "v2", "configuration": {"separator": "."}} + else: + data = {"name": "default", "configuration": {"separator": "/"}} + result = parse_chunk_key_encoding(data) + + if zarr_format == 2 and result.name != "v2": + msg = ( + "Invalid chunk key encoding. For Zarr format 2 arrays, the `name` field of the " + f"chunk key encoding must be 'v2'. Got `name` = {result.name} instead." + ) + raise ValueError(msg) + return result + + +def default_compressors_v3(dtype: ZDType[Any, Any]) -> tuple[BytesBytesCodec, ...]: + """ + Given a data type, return the default compressors for that data type. + + This is just a tuple containing `ZstdCodec` + """ + return (ZstdCodec(),) + + +def default_serializer_v3(dtype: ZDType[Any, Any]) -> ArrayBytesCodec: + """ + Given a data type, return the default serializer for that data type. + + The default serializer for most data types is the `BytesCodec`, which may or may not be + parameterized with an endianness, depending on whether the data type has endianness. Variable + length strings and variable length bytes have hard-coded serializers -- `VLenUTF8Codec` and + `VLenBytesCodec`, respectively. + + Structured data types with multi-byte fields use `BytesCodec` with little-endian encoding. + """ + serializer: ArrayBytesCodec = BytesCodec(endian=None) + + if isinstance(dtype, HasEndianness) or ( + isinstance(dtype, Structured) and dtype.has_multi_byte_fields() + ): + serializer = BytesCodec(endian="little") + elif isinstance(dtype, HasObjectCodec): + if dtype.object_codec_id == "vlen-bytes": + serializer = VLenBytesCodec() + elif dtype.object_codec_id == "vlen-utf8": + serializer = VLenUTF8Codec() + else: + msg = f"Data type {dtype} requires an unknown object codec: {dtype.object_codec_id!r}." + raise ValueError(msg) + return serializer + + +def default_filters_v2(dtype: ZDType[Any, Any]) -> tuple[Numcodec] | None: + """ + Given a data type, return the default filters for that data type. + + For data types that require an object codec, namely variable length data types, + this is a tuple containing the object codec. Otherwise it's `None`. + """ + if isinstance(dtype, HasObjectCodec): + if dtype.object_codec_id == "vlen-bytes": + from numcodecs import VLenBytes + + return (VLenBytes(),) + elif dtype.object_codec_id == "vlen-utf8": + from numcodecs import VLenUTF8 + + return (VLenUTF8(),) + else: + msg = f"Data type {dtype} requires an unknown object codec: {dtype.object_codec_id!r}." + raise ValueError(msg) + return None + + +def default_compressor_v2(dtype: ZDType[Any, Any]) -> Numcodec: + """ + Given a data type, return the default compressors for that data type. + + This is just the numcodecs `Zstd` codec. + """ + from numcodecs import Zstd + + return Zstd(level=0, checksum=False) # type: ignore[no-any-return] + + +def _parse_chunk_encoding_v2( + *, + compressor: CompressorsLike, + filters: FiltersLike, + dtype: ZDType[TBaseDType, TBaseScalar], +) -> tuple[tuple[Numcodec, ...] | None, Numcodec | None]: + """ + Generate chunk encoding classes for Zarr format 2 arrays with optional defaults. + """ + _filters: tuple[Numcodec, ...] | None + _compressor: Numcodec | None + + if compressor is None or compressor == (): + _compressor = None + elif compressor == "auto": + _compressor = default_compressor_v2(dtype) + elif isinstance(compressor, tuple | list) and len(compressor) == 1: + _compressor = parse_compressor(compressor[0]) + else: + if isinstance(compressor, Iterable) and not isinstance(compressor, dict): + msg = f"For Zarr format 2 arrays, the `compressor` must be a single codec. Got an iterable with type {type(compressor)} instead." + raise TypeError(msg) + _compressor = parse_compressor(compressor) + + if filters is None: + _filters = None + elif filters == "auto": + _filters = default_filters_v2(dtype) + else: + if isinstance(filters, Iterable): + for idx, f in enumerate(filters): + if not _is_numcodec(f): + msg = ( + "For Zarr format 2 arrays, all elements of `filters` must be numcodecs codecs. " + f"Element at index {idx} has type {type(f)}, which is not a numcodecs codec." + ) + raise TypeError(msg) + _filters = parse_filters(filters) + if isinstance(dtype, HasObjectCodec): + # check the filters and the compressor for the object codec required for this data type + if _filters is None: + if _compressor is None: + object_codec_id = None + else: + object_codec_id = get_object_codec_id((_compressor.get_config(),)) + else: + object_codec_id = get_object_codec_id( + ( + *[f.get_config() for f in _filters], + _compressor.get_config() if _compressor is not None else None, + ) + ) + if object_codec_id is None: + if isinstance(dtype, VariableLengthUTF8): # type: ignore[unreachable] + codec_name = "the numcodecs.VLenUTF8 codec" # type: ignore[unreachable] + elif isinstance(dtype, VariableLengthBytes): # type: ignore[unreachable] + codec_name = "the numcodecs.VLenBytes codec" # type: ignore[unreachable] + else: + codec_name = f"an unknown object codec with id {dtype.object_codec_id!r}" + msg = ( + f"Data type {dtype} requires {codec_name}, " + "but no such codec was specified in the filters or compressor parameters for " + "this array. " + ) + raise ValueError(msg) + return _filters, _compressor + + +def _parse_chunk_encoding_v3( + *, + compressors: CompressorsLike, + filters: FiltersLike, + serializer: SerializerLike, + dtype: ZDType[TBaseDType, TBaseScalar], +) -> tuple[tuple[ArrayArrayCodec, ...], ArrayBytesCodec, tuple[BytesBytesCodec, ...]]: + """ + Generate chunk encoding classes for v3 arrays with optional defaults. + """ + + if filters is None: + out_array_array: tuple[ArrayArrayCodec, ...] = () + elif filters == "auto": + # no data types have default filters + out_array_array = () + else: + maybe_array_array: Iterable[Codec | dict[str, JSON]] + if isinstance(filters, dict | Codec): + maybe_array_array = (filters,) + else: + maybe_array_array = cast("Iterable[Codec | dict[str, JSON]]", filters) + out_array_array = tuple(_parse_array_array_codec(c) for c in maybe_array_array) + + if serializer == "auto": + out_array_bytes = default_serializer_v3(dtype) + else: + # TODO: ensure that the serializer is compatible with the ndarray produced by the + # array-array codecs. For example, if a sequence of array-array codecs produces an + # array with a single-byte data type, then the serializer should not specify endiannesss. + out_array_bytes = _parse_array_bytes_codec(serializer) + + if compressors is None: + out_bytes_bytes: tuple[BytesBytesCodec, ...] = () + elif compressors == "auto": + out_bytes_bytes = default_compressors_v3(dtype) + else: + maybe_bytes_bytes: Iterable[Codec | dict[str, JSON]] + if isinstance(compressors, dict | Codec): + maybe_bytes_bytes = (compressors,) + else: + maybe_bytes_bytes = cast("Iterable[Codec | dict[str, JSON]]", compressors) + + out_bytes_bytes = tuple(_parse_bytes_bytes_codec(c) for c in maybe_bytes_bytes) + + # TODO: ensure that the serializer is compatible with the ndarray produced by the + # array-array codecs. For example, if a sequence of array-array codecs produces an + # array with a single-byte data type, then the serializer should not specify endiannesss. + + # TODO: add checks to ensure that the right serializer is used for vlen data types + return out_array_array, out_array_bytes, out_bytes_bytes + + +def _parse_deprecated_compressor( + compressor: CompressorLike | None, compressors: CompressorsLike, zarr_format: int = 3 +) -> CompressorsLike | None: + if compressor != "auto": + if compressors != "auto": + raise ValueError("Cannot specify both `compressor` and `compressors`.") + if zarr_format == 3: + warn( + "The `compressor` argument is deprecated. Use `compressors` instead.", + category=ZarrUserWarning, + stacklevel=2, + ) + if compressor is None: + # "no compression" + compressors = () + else: + compressors = (compressor,) + elif zarr_format == 2 and compressor == compressors == "auto": + compressors = ({"id": "blosc"},) + return compressors + + +def _parse_data_params( + *, + data: np.ndarray[Any, np.dtype[Any]] | None, + shape: ShapeLike | None, + dtype: ZDTypeLike | None, +) -> tuple[np.ndarray[Any, np.dtype[Any]] | None, ShapeLike, ZDTypeLike]: + """ + Ensure an array-like `data` parameter is consistent with the `dtype` and `shape` + parameters. + """ + if data is None: + if shape is None: + msg = ( + "The data parameter was set to None, but shape was not specified. " + "Either provide a value for data, or specify shape." + ) + raise ValueError(msg) + shape_out = shape + if dtype is None: + msg = ( + "The data parameter was set to None, but dtype was not specified. " + "Either provide an array-like value for data, or specify dtype." + ) + raise ValueError(msg) + dtype_out = dtype + else: + if shape is not None: + msg = ( + "The data parameter was used, but the shape parameter was also " + "used. This is an error. Either use the data parameter, or the shape parameter, " + "but not both." + ) + raise ValueError(msg) + shape_out = data.shape + if dtype is not None: + msg = ( + "The data parameter was used, but the dtype parameter was also " + "used. This is an error. Either use the data parameter, or the dtype parameter, " + "but not both." + ) + raise ValueError(msg) + dtype_out = data.dtype + return data, shape_out, dtype_out + + +def _iter_chunk_coords( + array: AnyArray | AnyAsyncArray, + *, + origin: Sequence[int] | None = None, + selection_shape: Sequence[int] | None = None, +) -> Iterator[tuple[int, ...]]: + """ + Create an iterator over the coordinates of chunks in chunk grid space. If the `origin` + keyword is used, iteration will start at the chunk index specified by `origin`. + The default behavior is to start at the origin of the grid coordinate space. + If the `selection_shape` keyword is used, iteration will be bounded over a contiguous region + ranging from `[origin, origin selection_shape]`, where the upper bound is exclusive as + per python indexing conventions. + + Parameters + ---------- + array : Array | AsyncArray + The array to iterate over. + origin : Sequence[int] | None, default=None + The origin of the selection in grid coordinates. + selection_shape : Sequence[int] | None, default=None + The shape of the selection in grid coordinates. + + Yields + ------ + chunk_coords: tuple[int, ...] + The coordinates of each chunk in the selection. + """ + return _iter_grid(array._chunk_grid_shape, origin=origin, selection_shape=selection_shape) + + +def _iter_shard_coords( + array: AnyArray | AnyAsyncArray, + *, + origin: Sequence[int] | None = None, + selection_shape: Sequence[int] | None = None, +) -> Iterator[tuple[int, ...]]: + """ + Create an iterator over the coordinates of shards in shard grid space. If the `origin` + keyword is used, iteration will start at the shard index specified by `origin`. + The default behavior is to start at the origin of the grid coordinate space. + If the `selection_shape` keyword is used, iteration will be bounded over a contiguous region + ranging from `[origin, origin selection_shape]`, where the upper bound is exclusive as + per python indexing conventions. + If no shards are present this will iterate over the coordinates of chunks in chunk grid space + instead. + + Parameters + ---------- + array : Array | AsyncArray + The array to iterate over. + origin : Sequence[int] | None, default=None + The origin of the selection in grid coordinates. + selection_shape : Sequence[int] | None, default=None + The shape of the selection in grid coordinates. + + Yields + ------ + chunk_coords: tuple[int, ...] + The coordinates of each shard in the selection or chunks if no shards are present. + """ + return _iter_grid(array._shard_grid_shape, origin=origin, selection_shape=selection_shape) + + +def _iter_shard_keys( + array: AnyArray | AnyAsyncArray, + *, + origin: Sequence[int] | None = None, + selection_shape: Sequence[int] | None = None, +) -> Iterator[str]: + """ + Iterate over the storage keys of each shard, relative to an optional origin, and optionally + limited to a contiguous region in shard grid coordinates. + + This automatically falls back to chunks when no shards are present. + + Parameters + ---------- + array : Array | AsyncArray + The array to iterate over. + origin : Sequence[int] | None, default=None + The origin of the selection in grid coordinates. + selection_shape : Sequence[int] | None, default=None + The shape of the selection in grid coordinates. + + Yields + ------ + key: str + The storage key of each shard in the selection or chunk when no shards are present. + """ + # Iterate over the coordinates of chunks in chunk grid space. + _iter = _iter_grid(array._shard_grid_shape, origin=origin, selection_shape=selection_shape) + return (array.metadata.encode_chunk_key(k) for k in _iter) + + +def _iter_shard_regions( + array: AnyArray | AnyAsyncArray, + *, + origin: Sequence[int] | None = None, + selection_shape: Sequence[int] | None = None, +) -> Iterator[tuple[slice, ...]]: + """ + Iterate over the regions spanned by each shard. + + These are the smallest regions of the array that are safe to write concurrently. When + no shards are present this will fall back to chunks. + + Parameters + ---------- + array : Array | AsyncArray + The array to iterate over. + origin : Sequence[int] | None, default=None + The origin of the selection relative to the array's shard grid. + selection_shape : Sequence[int] | None, default=None + The shape of the selection in shard grid coordinates. + + Yields + ------ + region: tuple[slice, ...] + A tuple of slice objects representing the region spanned by each shard in the selection or chunk + when no shards are present. + """ + if array.shards is None: + shard_shape = array.chunks + else: + shard_shape = array.shards + + return _iter_regions( + array.shape, shard_shape, origin=origin, selection_shape=selection_shape, trim_excess=True + ) + + +def _iter_chunk_regions( + array: AnyArray | AnyAsyncArray, + *, + origin: Sequence[int] | None = None, + selection_shape: Sequence[int] | None = None, +) -> Iterator[tuple[slice, ...]]: + """ + Iterate over the regions spanned by each shard. + + These are the smallest regions of the array that are efficient to read concurrently. + + Parameters + ---------- + array : Array | AsyncArray + The array to iterate over. + origin : Sequence[int] | None, default=None + The origin of the selection in grid coordinates. + selection_shape : Sequence[int] | None, default=None + The shape of the selection in grid coordinates. + + Returns + ------- + region: tuple[slice, ...] + A tuple of slice objects representing the region spanned by each shard in the selection. + """ + + return array._chunk_grid.iter_chunk_regions(origin=origin, selection_shape=selection_shape) + + +async def _nchunks_initialized( + array: AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata], +) -> int: + """ + Calculate the number of chunks that have been initialized in storage. + + This value is calculated as the product of the number of initialized shards and the number + of chunks per shard. For arrays that do not use sharding, the number of chunks per shard is + effectively 1, and in that case the number of chunks initialized is the same as the number + of stored objects associated with an array. + + Parameters + ---------- + array : AsyncArray + The array to inspect. + + Returns + ------- + nchunks_initialized : int + The number of chunks that have been initialized. + """ + if array.shards is None: + chunks_per_shard = 1 + else: + chunks_per_shard = product( + tuple(a // b for a, b in zip(array.shards, array.chunks, strict=True)) + ) + return (await _nshards_initialized(array)) * chunks_per_shard + + +async def _nshards_initialized( + array: AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata], +) -> int: + """ + Calculate the number of shards that have been initialized in storage. + + This is the number of shards that have been persisted to the storage backend. + + Parameters + ---------- + array : AsyncArray + The array to inspect. + + Returns + ------- + nshards_initialized : int + The number of shards that have been initialized. + """ + return len(await _shards_initialized(array)) + + +async def _nbytes_stored( + store_path: StorePath, +) -> int: + """ + Calculate the number of bytes stored for an array. + + Parameters + ---------- + store_path : StorePath + The store path of the array. + + Returns + ------- + nbytes_stored : int + The number of bytes stored. + """ + return await store_path.store.getsize_prefix(store_path.path) + + +def _get_chunk_spec( + metadata: ArrayMetadata, + chunk_grid: ChunkGrid, + chunk_coords: tuple[int, ...], + array_config: ArrayConfig, + prototype: BufferPrototype, +) -> ArraySpec: + """Build an ArraySpec for a single chunk using the ChunkGrid.""" + spec = chunk_grid[chunk_coords] + if spec is None: + raise IndexError(f"Chunk coordinates {chunk_coords} are out of bounds.") + return ArraySpec( + shape=spec.codec_shape, + dtype=metadata.dtype, + fill_value=metadata.fill_value, + config=array_config, + prototype=prototype, + ) + + +async def _get_selection( + store_path: StorePath, + metadata: ArrayMetadata, + codec_pipeline: CodecPipeline, + config: ArrayConfig, + chunk_grid: ChunkGrid, + indexer: Indexer, + *, + prototype: BufferPrototype, + out: NDBuffer | None = None, + fields: Fields | None = None, +) -> NDArrayLikeOrScalar: + """ + Get a selection from an array. + + Parameters + ---------- + store_path : StorePath + The store path of the array. + metadata : ArrayMetadata + The array metadata. + codec_pipeline : CodecPipeline + The codec pipeline for encoding/decoding. + config : ArrayConfig + The array configuration. + indexer : Indexer + The indexer specifying the selection. + prototype : BufferPrototype + A buffer prototype to use for the retrieved data. + out : NDBuffer | None, optional + An output buffer to write the data to. + fields : Fields | None, optional + Fields to select from structured arrays. + + Returns + ------- + NDArrayLikeOrScalar + The selected data. + """ + # `dtype` returns the zarr dtype object for both v2 and v3 metadata. + zdtype = metadata.dtype + dtype = zdtype.to_native_dtype() + + # Determine memory order + if metadata.zarr_format == 2: + order = metadata.order + else: + order = config.order + + # check fields are sensible + out_dtype = check_fields(fields, dtype) + + # setup output buffer + if out is not None: + if isinstance(out, NDBuffer): + out_buffer = out + else: + raise TypeError(f"out argument needs to be an NDBuffer. Got {type(out)!r}") + if out_buffer.shape != indexer.shape: + raise ValueError( + f"shape of out argument doesn't match. Expected {indexer.shape}, got {out.shape}" + ) + else: + out_buffer = prototype.nd_buffer.empty( + shape=indexer.shape, + dtype=out_dtype, + order=order, + ) + if product(indexer.shape) > 0: + # need to use the order from the metadata for v2 + _config = config + if metadata.zarr_format == 2: + _config = replace(_config, order=order) + + # reading chunks and decoding them + indexed_chunks = list(indexer) + # For regular grids, all chunks share the same ArraySpec, so build it once + # and reuse it to avoid per-chunk ChunkGrid lookups and ArraySpec construction. + regular_grid = chunk_grid.is_regular + if regular_grid: + regular_chunk_spec = ArraySpec( + shape=chunk_grid.chunk_shape, + dtype=metadata.dtype, + fill_value=metadata.fill_value, + config=_config, + prototype=prototype, + ) + results = await codec_pipeline.read( + [ + ( + store_path / metadata.encode_chunk_key(chunk_coords), + regular_chunk_spec + if regular_grid + else _get_chunk_spec(metadata, chunk_grid, chunk_coords, _config, prototype), + chunk_selection, + out_selection, + is_complete_chunk, + ) + for chunk_coords, chunk_selection, out_selection, is_complete_chunk in indexed_chunks + ], + out_buffer, + drop_axes=indexer.drop_axes, + ) + if _config.read_missing_chunks is False: + missing_info = [] + for i, result in enumerate(results): + if result["status"] == "missing": + coords = indexed_chunks[i][0] + key = metadata.encode_chunk_key(coords) + missing_info.append(f" chunk '{key}' (grid position {coords})") + if missing_info: + chunks_str = "\n".join(missing_info) + raise ChunkNotFoundError( + f"{len(missing_info)} chunk(s) not found in store '{store_path}'.\n" + f"Set the 'array.read_missing_chunks' config to True to fill " + f"missing chunks with the fill value.\n" + f"Missing chunks:\n{chunks_str}" + ) + if isinstance(indexer, BasicIndexer) and indexer.shape == (): + return out_buffer.as_scalar() + return out_buffer.as_ndarray_like() + + +async def _getitem( + store_path: StorePath, + metadata: ArrayMetadata, + codec_pipeline: CodecPipeline, + config: ArrayConfig, + chunk_grid: ChunkGrid, + selection: BasicSelection, + *, + prototype: BufferPrototype | None = None, +) -> NDArrayLikeOrScalar: + """ + Retrieve a subset of the array's data based on the provided selection. + + Parameters + ---------- + store_path : StorePath + The store path of the array. + metadata : ArrayMetadata + The array metadata. + codec_pipeline : CodecPipeline + The codec pipeline for encoding/decoding. + config : ArrayConfig + The array configuration. + chunk_grid : ChunkGrid + The chunk grid. + selection : BasicSelection + A selection object specifying the subset of data to retrieve. + prototype : BufferPrototype, optional + A buffer prototype to use for the retrieved data (default is None). + + Returns + ------- + NDArrayLikeOrScalar + The retrieved subset of the array's data. + """ + if prototype is None: + prototype = default_buffer_prototype() + indexer = BasicIndexer( + selection, + shape=metadata.shape, + chunk_grid=chunk_grid, + ) + return await _get_selection( + store_path, metadata, codec_pipeline, config, chunk_grid, indexer, prototype=prototype + ) + + +async def _set_selection( + store_path: StorePath, + metadata: ArrayMetadata, + codec_pipeline: CodecPipeline, + config: ArrayConfig, + chunk_grid: ChunkGrid, + indexer: Indexer, + value: npt.ArrayLike, + *, + prototype: BufferPrototype, + fields: Fields | None = None, +) -> None: + """ + Set a selection in an array. + + Parameters + ---------- + store_path : StorePath + The store path of the array. + metadata : ArrayMetadata + The array metadata. + codec_pipeline : CodecPipeline + The codec pipeline for encoding/decoding. + config : ArrayConfig + The array configuration. + chunk_grid : ChunkGrid + The chunk grid. + indexer : Indexer + The indexer specifying the selection. + value : npt.ArrayLike + The values to write. + prototype : BufferPrototype + A buffer prototype to use. + fields : Fields | None, optional + Fields to select from structured arrays. + """ + # `dtype` returns the zarr dtype object for both v2 and v3 metadata. + zdtype = metadata.dtype + dtype = zdtype.to_native_dtype() + + # check fields are sensible + check_fields(fields, dtype) + fields = check_no_multi_fields(fields) + + # check value shape + if np.isscalar(value): + array_like = prototype.buffer.create_zero_length().as_array_like() + if isinstance(array_like, np._typing._SupportsArrayFunc): + # TODO: need to handle array types that don't support __array_function__ + # like PyTorch and JAX + array_like_ = cast("np._typing._SupportsArrayFunc", array_like) + value = np.asanyarray(value, dtype=dtype, like=array_like_) + else: + if not hasattr(value, "shape"): + value = np.asarray(value, dtype) + # assert ( + # value.shape == indexer.shape + # ), f"shape of value doesn't match indexer shape. Expected {indexer.shape}, got {value.shape}" + if not hasattr(value, "dtype") or value.dtype.name != dtype.name: + if hasattr(value, "astype"): + # Handle things that are already NDArrayLike more efficiently + value = value.astype(dtype=dtype, order="A") + else: + value = np.array(value, dtype=dtype, order="A") + value = cast("NDArrayLike", value) + + # We accept any ndarray like object from the user and convert it + # to an NDBuffer (or subclass). From this point onwards, we only pass + # Buffer and NDBuffer between components. + value_buffer = prototype.nd_buffer.from_ndarray_like(value) + + # Determine memory order + if metadata.zarr_format == 2: + order = metadata.order + else: + order = config.order + + # need to use the order from the metadata for v2 + _config = config + if metadata.zarr_format == 2: + _config = replace(_config, order=order) + + # merging with existing data and encoding chunks + # For regular grids, all chunks share the same ArraySpec, so build it once + # and reuse it to avoid per-chunk ChunkGrid lookups and ArraySpec construction. + regular_grid = chunk_grid.is_regular + if regular_grid: + regular_chunk_spec = ArraySpec( + shape=chunk_grid.chunk_shape, + dtype=metadata.dtype, + fill_value=metadata.fill_value, + config=_config, + prototype=prototype, + ) + await codec_pipeline.write( + [ + ( + store_path / metadata.encode_chunk_key(chunk_coords), + regular_chunk_spec + if regular_grid + else _get_chunk_spec(metadata, chunk_grid, chunk_coords, _config, prototype), + chunk_selection, + out_selection, + is_complete_chunk, + ) + for chunk_coords, chunk_selection, out_selection, is_complete_chunk in indexer + ], + value_buffer, + drop_axes=indexer.drop_axes, + ) + + +async def _setitem( + store_path: StorePath, + metadata: ArrayMetadata, + codec_pipeline: CodecPipeline, + config: ArrayConfig, + chunk_grid: ChunkGrid, + selection: BasicSelection, + value: npt.ArrayLike, + prototype: BufferPrototype | None = None, +) -> None: + """ + Set values in the array using basic indexing. + + Parameters + ---------- + store_path : StorePath + The store path of the array. + metadata : ArrayMetadata + The array metadata. + codec_pipeline : CodecPipeline + The codec pipeline for encoding/decoding. + config : ArrayConfig + The array configuration. + chunk_grid : ChunkGrid + The chunk grid. + selection : BasicSelection + The selection defining the region of the array to set. + value : npt.ArrayLike + The values to be written into the selected region of the array. + prototype : BufferPrototype or None, optional + A prototype buffer that defines the structure and properties of the array chunks being modified. + If None, the default buffer prototype is used. + """ + if prototype is None: + prototype = default_buffer_prototype() + indexer = BasicIndexer( + selection, + shape=metadata.shape, + chunk_grid=chunk_grid, + ) + return await _set_selection( + store_path, + metadata, + codec_pipeline, + config, + chunk_grid, + indexer, + value, + prototype=prototype, + ) + + +async def _resize( + array: AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata], + new_shape: ShapeLike, + delete_outside_chunks: bool = True, +) -> None: + """ + Resize an array to a new shape. + + Parameters + ---------- + array : AsyncArray + The array to resize. + new_shape : ShapeLike + The desired new shape of the array. + delete_outside_chunks : bool, optional + If True (default), chunks that fall outside the new shape will be deleted. + If False, the data in those chunks will be preserved. + """ + new_shape = parse_shapelike(new_shape) + assert len(new_shape) == len(array.metadata.shape) + + new_metadata = array.metadata.update_shape(new_shape) + new_chunk_grid = ChunkGrid.from_metadata(new_metadata) + + # ensure deletion is only run if array is shrinking as the delete_outside_chunks path is unbounded in memory + only_growing = all(new >= old for new, old in zip(new_shape, array.metadata.shape, strict=True)) + + if delete_outside_chunks and not only_growing: + # Remove all chunks outside of the new shape + old_chunk_coords = set(array._chunk_grid.all_chunk_coords()) + new_chunk_coords = set(new_chunk_grid.all_chunk_coords()) + + async def _delete_key(key: str) -> None: + await (array.store_path / key).delete() + + await concurrent_map( + [ + (array.metadata.encode_chunk_key(chunk_coords),) + for chunk_coords in old_chunk_coords.difference(new_chunk_coords) + ], + _delete_key, + zarr_config.get("async.concurrency"), + ) + + # Write new metadata + await save_metadata(array.store_path, new_metadata) + + # Update metadata and chunk_grid (in place) + object.__setattr__(array, "metadata", new_metadata) + object.__setattr__(array, "_chunk_grid", new_chunk_grid) + + +async def _append( + array: AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata], + data: npt.ArrayLike, + axis: int = 0, +) -> tuple[int, ...]: + """ + Append data to an array along the specified axis. + + Parameters + ---------- + array : AsyncArray + The array to append to. + data : npt.ArrayLike + Data to be appended. + axis : int + Axis along which to append. + + Returns + ------- + new_shape : tuple[int, ...] + The new shape of the array after appending. + + Notes + ----- + The size of all dimensions other than `axis` must match between the + array and `data`. + """ + # ensure data is array-like + if not hasattr(data, "shape"): + data = np.asanyarray(data) + + self_shape_preserved = tuple(s for i, s in enumerate(array.shape) if i != axis) + data_shape_preserved = tuple(s for i, s in enumerate(data.shape) if i != axis) + if self_shape_preserved != data_shape_preserved: + raise ValueError( + f"shape of data to append is not compatible with the array. " + f"The shape of the data is ({data_shape_preserved})" + f"and the shape of the array is ({self_shape_preserved})." + "All dimensions must match except for the dimension being " + "appended." + ) + # remember old shape + old_shape = array.shape + + # determine new shape + new_shape = tuple( + array.shape[i] if i != axis else array.shape[i] + data.shape[i] + for i in range(len(array.shape)) + ) + + # resize + await _resize(array, new_shape) + + # store data + append_selection = tuple( + slice(None) if i != axis else slice(old_shape[i], new_shape[i]) + for i in range(len(array.shape)) + ) + await _setitem( + array.store_path, + array.metadata, + array.codec_pipeline, + array.config, + array._chunk_grid, + append_selection, + data, + ) + + return new_shape + + +async def _update_attributes( + array: AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata], + new_attributes: dict[str, JSON], +) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]: + """ + Update the array's attributes. + + Parameters + ---------- + array : AsyncArray + The array whose attributes to update. + new_attributes : dict[str, JSON] + A dictionary of new attributes to update or add to the array. + + Returns + ------- + AsyncArray + The array with the updated attributes. + """ + array.metadata.attributes.update(new_attributes) + + # Write new metadata + await save_metadata(array.store_path, array.metadata) + + return array + + +async def _info_complete( + array: AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata], +) -> Any: + """ + Return all the information for an array, including dynamic information like storage size. + + Parameters + ---------- + array : AsyncArray + The array to get info for. + + Returns + ------- + ArrayInfo + Complete information about the array including: + - The count of chunks initialized + - The sum of the bytes written + """ + return array._info( + await _nshards_initialized(array), + await array.store_path.store.getsize_prefix(array.store_path.path), + ) diff --git a/src/zarr/core/array_spec.py b/src/zarr/core/array_spec.py new file mode 100644 index 0000000000..1f4ffd6f09 --- /dev/null +++ b/src/zarr/core/array_spec.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +from dataclasses import dataclass, fields +from typing import TYPE_CHECKING, Any, Literal, Self, TypedDict, cast + +import numpy as np + +from zarr.core.common import ( + MemoryOrder, + parse_bool, + parse_fill_value, + parse_int, + parse_order, + parse_shapelike, +) +from zarr.core.config import config as zarr_config + +if TYPE_CHECKING: + from typing import NotRequired + + from zarr.core.buffer import BufferPrototype + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType + + +class ArrayConfigParams(TypedDict): + """ + A TypedDict model of the attributes of an ArrayConfig class, but with no required fields. + This allows for partial construction of an ArrayConfig, with the assumption that the unset + keys will be taken from a global configuration. + """ + + order: NotRequired[MemoryOrder] + write_empty_chunks: NotRequired[bool] + read_missing_chunks: NotRequired[bool] + sharding_coalesce_max_gap_bytes: NotRequired[int] + sharding_coalesce_max_bytes: NotRequired[int] + + +@dataclass(frozen=True) +class ArrayConfig: + """ + A model of the runtime configuration of an array. + + Parameters + ---------- + order : MemoryOrder + The memory layout of the arrays returned when reading data from the store. + write_empty_chunks : bool + If True, empty chunks will be written to the store. + read_missing_chunks : bool + If True, missing chunks will be filled with the array's fill value on read. + If False, reading missing chunks will raise a ``ChunkNotFoundError``. + sharding_coalesce_max_gap_bytes : int + When reading multiple chunks from the same shard, nearby byte ranges + separated by no more than this many bytes are coalesced into a single + request to the store. + sharding_coalesce_max_bytes : int + Requests will not be coalesced if doing so would exceed this byte size. + """ + + order: MemoryOrder + write_empty_chunks: bool + read_missing_chunks: bool + sharding_coalesce_max_gap_bytes: int + sharding_coalesce_max_bytes: int + + def __init__( + self, + order: MemoryOrder, + write_empty_chunks: bool, + *, + read_missing_chunks: bool = True, + sharding_coalesce_max_gap_bytes: int = 1 << 20, # 1 MiB + sharding_coalesce_max_bytes: int = 16 << 20, # 16 MiB + ) -> None: + order_parsed = parse_order(order) + write_empty_chunks_parsed = parse_bool(write_empty_chunks) + read_missing_chunks_parsed = parse_bool(read_missing_chunks) + sharding_coalesce_max_gap_bytes_parsed = parse_int(sharding_coalesce_max_gap_bytes) + sharding_coalesce_max_bytes_parsed = parse_int(sharding_coalesce_max_bytes) + + object.__setattr__(self, "order", order_parsed) + object.__setattr__(self, "write_empty_chunks", write_empty_chunks_parsed) + object.__setattr__(self, "read_missing_chunks", read_missing_chunks_parsed) + object.__setattr__( + self, "sharding_coalesce_max_gap_bytes", sharding_coalesce_max_gap_bytes_parsed + ) + object.__setattr__(self, "sharding_coalesce_max_bytes", sharding_coalesce_max_bytes_parsed) + + @classmethod + def from_dict(cls, data: ArrayConfigParams) -> Self: + """ + Create an ArrayConfig from a dict. The keys of that dict are a subset of the + attributes of the ArrayConfig class. Any keys missing from that dict will be set to the + the values in the ``array`` namespace of ``zarr.config``. + """ + kwargs_out: ArrayConfigParams = {} + for f in fields(ArrayConfig): + field_name = cast( + "Literal['order', 'write_empty_chunks', 'read_missing_chunks', 'sharding_coalesce_max_gap_bytes', 'sharding_coalesce_max_bytes']", + f.name, + ) + if field_name not in data: + kwargs_out[field_name] = zarr_config.get(f"array.{field_name}") + else: + kwargs_out[field_name] = data[field_name] + return cls(**kwargs_out) + + def to_dict(self) -> ArrayConfigParams: + """ + Serialize an instance of this class to a dict. + """ + return { + "order": self.order, + "write_empty_chunks": self.write_empty_chunks, + "read_missing_chunks": self.read_missing_chunks, + "sharding_coalesce_max_gap_bytes": self.sharding_coalesce_max_gap_bytes, + "sharding_coalesce_max_bytes": self.sharding_coalesce_max_bytes, + } + + +ArrayConfigLike = ArrayConfig | ArrayConfigParams + + +def parse_array_config(data: ArrayConfigLike | None) -> ArrayConfig: + """ + Convert various types of data to an ArrayConfig. + """ + if data is None: + return ArrayConfig.from_dict({}) + elif isinstance(data, ArrayConfig): + return data + else: + return ArrayConfig.from_dict(data) + + +@dataclass(frozen=True, eq=False) +class ArraySpec: + shape: tuple[int, ...] + dtype: ZDType[TBaseDType, TBaseScalar] + fill_value: Any + config: ArrayConfig + prototype: BufferPrototype + + def __init__( + self, + shape: tuple[int, ...], + dtype: ZDType[TBaseDType, TBaseScalar], + fill_value: Any, + config: ArrayConfig, + prototype: BufferPrototype, + ) -> None: + shape_parsed = parse_shapelike(shape) + fill_value_parsed = parse_fill_value(fill_value) + + object.__setattr__(self, "shape", shape_parsed) + object.__setattr__(self, "dtype", dtype) + object.__setattr__(self, "fill_value", fill_value_parsed) + object.__setattr__(self, "config", config) + object.__setattr__(self, "prototype", prototype) + + def _key(self) -> tuple[object, ...]: + """Returns the tuple used for equality/hash identity.""" + fill_value = self.fill_value + if isinstance(fill_value, np.generic): + # fill_values should be byte-identical, otherwise they correspond to different values in memory / on disk. + # Importantly, this ensures np.nan == np.nan, NaT == NaT, and -0.0 != 0.0. + # It also fixes np.void fill_values being unhashable (#3054). + fill_value = fill_value.tobytes() + return (self.shape, self.dtype, fill_value, self.config, self.prototype) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ArraySpec): + return NotImplemented + return self._key() == other._key() + + def __hash__(self) -> int: + return hash(self._key()) + + @property + def ndim(self) -> int: + return len(self.shape) + + @property + def order(self) -> MemoryOrder: + return self.config.order diff --git a/src/zarr/core/attributes.py b/src/zarr/core/attributes.py new file mode 100644 index 0000000000..7f29e44365 --- /dev/null +++ b/src/zarr/core/attributes.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +from collections.abc import MutableMapping +from typing import TYPE_CHECKING + +from zarr.core.common import JSON + +if TYPE_CHECKING: + from collections.abc import Iterator + + from zarr.core.group import Group + from zarr.types import AnyArray + + +class Attributes(MutableMapping[str, JSON]): + def __init__(self, obj: AnyArray | Group) -> None: + # key=".zattrs", read_only=False, cache=True, synchronizer=None + self._obj = obj + + def __getitem__(self, key: str) -> JSON: + return self._obj.metadata.attributes[key] + + def __setitem__(self, key: str, value: JSON) -> None: + new_attrs = dict(self._obj.metadata.attributes) + new_attrs[key] = value + self._obj = self._obj.update_attributes(new_attrs) + + def __delitem__(self, key: str) -> None: + new_attrs = dict(self._obj.metadata.attributes) + del new_attrs[key] + self.put(new_attrs) + + def __iter__(self) -> Iterator[str]: + return iter(self._obj.metadata.attributes) + + def __len__(self) -> int: + return len(self._obj.metadata.attributes) + + def put(self, d: dict[str, JSON]) -> None: + """ + Overwrite all attributes with the values from `d`. + + Equivalent to the following pseudo-code, but performed atomically. + + ```python + attrs = {"a": 1, "b": 2} + attrs.clear() + attrs.update({"a": "3", "c": 4}) + print(attrs) + #> {'a': '3', 'c': 4} + ``` + """ + self._obj.metadata.attributes.clear() + self._obj = self._obj.update_attributes(d) + + def asdict(self) -> dict[str, JSON]: + return dict(self._obj.metadata.attributes) diff --git a/src/zarr/core/buffer/__init__.py b/src/zarr/core/buffer/__init__.py new file mode 100644 index 0000000000..ebec61a372 --- /dev/null +++ b/src/zarr/core/buffer/__init__.py @@ -0,0 +1,21 @@ +from zarr.core.buffer.core import ( + ArrayLike, + Buffer, + BufferPrototype, + NDArrayLike, + NDArrayLikeOrScalar, + NDBuffer, + default_buffer_prototype, +) +from zarr.core.buffer.cpu import numpy_buffer_prototype + +__all__ = [ + "ArrayLike", + "Buffer", + "BufferPrototype", + "NDArrayLike", + "NDArrayLikeOrScalar", + "NDBuffer", + "default_buffer_prototype", + "numpy_buffer_prototype", +] diff --git a/src/zarr/core/buffer/core.py b/src/zarr/core/buffer/core.py new file mode 100644 index 0000000000..b8f7f11cd4 --- /dev/null +++ b/src/zarr/core/buffer/core.py @@ -0,0 +1,594 @@ +from __future__ import annotations + +import sys +from abc import ABC, abstractmethod +from collections.abc import Iterable +from typing import ( + TYPE_CHECKING, + Any, + Literal, + NamedTuple, + Protocol, + SupportsIndex, + cast, + runtime_checkable, +) + +import numpy as np +import numpy.typing as npt + +if TYPE_CHECKING: + from collections.abc import Iterable, Sequence + from typing import Self + + from zarr.codecs.bytes import EndianLiteral + from zarr.core.common import BytesLike + +# Everything here is imported into ``zarr.core.buffer`` namespace. +__all__: list[str] = [] + + +@runtime_checkable +class ArrayLike(Protocol): + """Protocol for the array-like type that underlie Buffer""" + + @property + def dtype(self) -> np.dtype[Any]: ... + + @property + def ndim(self) -> int: ... + + @property + def size(self) -> int: ... + + def __getitem__(self, key: slice) -> Self: ... + + def __setitem__(self, key: slice, value: Any) -> None: ... + + def copy(self) -> Self: ... + + +@runtime_checkable +class NDArrayLike(Protocol): + """Protocol for the nd-array-like type that underlie NDBuffer""" + + @property + def dtype(self) -> np.dtype[Any]: ... + + @property + def ndim(self) -> int: ... + + @property + def size(self) -> int: ... + + @property + def shape(self) -> tuple[int, ...]: ... + + def __len__(self) -> int: ... + + def __getitem__(self, key: slice) -> Self: ... + + def __setitem__(self, key: slice, value: Any) -> None: ... + + def __array__(self) -> npt.NDArray[Any]: ... + + def reshape( + self, + shape: tuple[int, ...], + /, + *, + order: Literal["A", "C", "F"] | None = ..., + copy: bool | None = ..., + ) -> NDArrayLike: ... + + def view(self, dtype: npt.DTypeLike) -> Self: ... + + def astype( + self, + dtype: npt.DTypeLike, + order: Literal["K", "A", "C", "F"] = ..., + *, + copy: bool = ..., + ) -> Self: ... + + def fill(self, value: Any) -> None: ... + + def copy(self) -> Self: ... + + def transpose(self, axes: SupportsIndex | Sequence[SupportsIndex] | None) -> Self: ... + + def ravel(self, order: Literal["K", "A", "C", "F"] = ...) -> Self: ... + + def all(self) -> np.bool_: ... + + def __eq__(self, other: object) -> Self: # type: ignore[override] + """Element-wise equal + + Notes + ----- + Type checkers such as mypy complains because the return type isn't a bool like + its supertype "object", which violates the Liskov substitution principle. + This is true, but since NumPy's ndarray is defined as an element-wise equal, + our hands are tied. + """ + + +ScalarType = int | float | complex | bytes | str | bool | np.generic +NDArrayLikeOrScalar = ScalarType | NDArrayLike + + +def check_item_key_is_1d_contiguous(key: Any) -> None: + """Raises error if `key` isn't a 1d contiguous slice""" + if not isinstance(key, slice): + raise TypeError( + f"Item key has incorrect type (expected slice, got {key.__class__.__name__})" + ) + if not (key.step is None or key.step == 1): + raise ValueError("slice must be contiguous") + + +class Buffer(ABC): + """A flat contiguous memory block + + We use Buffer throughout Zarr to represent a contiguous block of memory. + + A Buffer is backed by an underlying array-like instance that represents + the memory. The memory type is unspecified; can be regular host memory, + CUDA device memory, or something else. The only requirement is that the + array-like instance can be copied/converted to a regular Numpy array + (host memory). + + Notes + ----- + This buffer is untyped, so all indexing and sizes are in bytes. + + Parameters + ---------- + array_like + array-like object that must be 1-dim, contiguous, and byte dtype. + """ + + def __init__(self, array_like: ArrayLike) -> None: + if array_like.ndim != 1: + raise ValueError("array_like: only 1-dim allowed") + if array_like.dtype != np.dtype("B"): + raise ValueError("array_like: only byte dtype allowed") + self._data = array_like + + @classmethod + @abstractmethod + def create_zero_length(cls) -> Self: + """Create an empty buffer with length zero + + Returns + ------- + New empty 0-length buffer + """ + if cls is Buffer: + raise NotImplementedError("Cannot call abstract method on the abstract class 'Buffer'") + return cls( + cast("ArrayLike", None) + ) # This line will never be reached, but it satisfies the type checker + + @classmethod + def from_array_like(cls, array_like: ArrayLike) -> Self: + """Create a new buffer of an array-like object + + Parameters + ---------- + array_like + array-like object that must be 1-dim, contiguous, and byte dtype. + + Returns + ------- + New buffer representing `array_like` + """ + return cls(array_like) + + @classmethod + @abstractmethod + def from_buffer(cls, buffer: Buffer) -> Self: + """Create a new buffer of an existing Buffer + + This is useful if you want to ensure that an existing buffer is + of the correct subclass of Buffer. E.g., MemoryStore uses this + to return a buffer instance of the subclass specified by its + BufferPrototype argument. + + Typically, this only copies data if the data has to be moved between + memory types, such as from host to device memory. + + Parameters + ---------- + buffer + buffer object. + + Returns + ------- + A new buffer representing the content of the input buffer + + Notes + ----- + Subclasses of `Buffer` must override this method to implement + more optimal conversions that avoid copies where possible + """ + if cls is Buffer: + raise NotImplementedError("Cannot call abstract method on the abstract class 'Buffer'") + return cls( + cast("ArrayLike", None) + ) # This line will never be reached, but it satisfies the type checker + + @classmethod + @abstractmethod + def from_bytes(cls, bytes_like: BytesLike) -> Self: + """Create a new buffer of a bytes-like object (host memory) + + Parameters + ---------- + bytes_like + bytes-like object + + Returns + ------- + New buffer representing `bytes_like` + """ + if cls is Buffer: + raise NotImplementedError("Cannot call abstract method on the abstract class 'Buffer'") + return cls( + cast("ArrayLike", None) + ) # This line will never be reached, but it satisfies the type checker + + def as_array_like(self) -> ArrayLike: + """Returns the underlying array (host or device memory) of this buffer + + This will never copy data. + + Returns + ------- + The underlying 1d array such as a NumPy or CuPy array. + """ + return self._data + + @abstractmethod + def as_numpy_array(self) -> npt.NDArray[Any]: + """Returns the buffer as a NumPy array (host memory). + + Notes + ----- + Might have to copy data, consider using `.as_array_like()` instead. + + Returns + ------- + NumPy array of this buffer (might be a data copy) + """ + ... + + def as_buffer_like(self) -> BytesLike: + """Returns the buffer as an object that implements the Python buffer protocol. + + Notes + ----- + Might have to copy data, since the implementation uses `.as_numpy_array()`. + + Returns + ------- + An object that implements the Python buffer protocol + """ + return memoryview(self.as_numpy_array()) + + def to_bytes(self) -> bytes: + """Returns the buffer as `bytes` (host memory). + + Warnings + -------- + Will always copy data, only use this method for small buffers such as metadata + buffers. If possible, use `.as_numpy_array()` or `.as_array_like()` instead. + + Returns + ------- + `bytes` of this buffer (data copy) + """ + return bytes(self.as_numpy_array()) + + def __getitem__(self, key: slice) -> Self: + check_item_key_is_1d_contiguous(key) + return self.__class__(self._data.__getitem__(key)) + + def __setitem__(self, key: slice, value: Any) -> None: + check_item_key_is_1d_contiguous(key) + self._data.__setitem__(key, value) + + def __len__(self) -> int: + return self._data.size + + @abstractmethod + def combine(self, others: Iterable[Buffer]) -> Self: + """Concatenate many buffers""" + ... + + def __add__(self, other: Buffer) -> Self: + """Concatenate two buffers""" + return self.combine([other]) + + def __eq__(self, other: object) -> bool: + # Another Buffer class can override this to choose a more efficient path + return isinstance(other, Buffer) and np.array_equal( + self.as_numpy_array(), other.as_numpy_array() + ) + + +class NDBuffer: + """An n-dimensional memory block + + We use NDBuffer throughout Zarr to represent a n-dimensional memory block. + + An NDBuffer is backed by an underlying ndarray-like instance that represents + the memory. The memory type is unspecified; can be regular host memory, + CUDA device memory, or something else. The only requirement is that the + ndarray-like instance can be copied/converted to a regular Numpy array + (host memory). + + Notes + ----- + The two buffer classes Buffer and NDBuffer are very similar. In fact, Buffer + is a special case of NDBuffer where dim=1, stride=1, and dtype="B". However, + in order to use Python's type system to differentiate between the contiguous + Buffer and the n-dim (non-contiguous) NDBuffer, we keep the definition of the + two classes separate. + + Parameters + ---------- + array : ndarray_like + ndarray-like object that is convertible to a regular Numpy array. + """ + + def __init__(self, array: NDArrayLike) -> None: + self._data = array + + @classmethod + @abstractmethod + def create( + cls, + *, + shape: Iterable[int], + dtype: npt.DTypeLike, + order: Literal["C", "F"] = "C", + fill_value: Any | None = None, + ) -> Self: + """Create a new buffer and its underlying ndarray-like object + + Parameters + ---------- + shape + The shape of the buffer and its underlying ndarray-like object + dtype + The datatype of the buffer and its underlying ndarray-like object + order + Whether to store multi-dimensional data in row-major (C-style) or + column-major (Fortran-style) order in memory. + fill_value + If not None, fill the new buffer with a scalar value. + + Returns + ------- + New buffer representing a new ndarray_like object + + Notes + ----- + A subclass can overwrite this method to create an ndarray-like object + other then the default Numpy array. + """ + if cls is NDBuffer: + raise NotImplementedError( + "Cannot call abstract method on the abstract class 'NDBuffer'" + ) + return cls( + cast("NDArrayLike", None) + ) # This line will never be reached, but it satisfies the type checker + + @classmethod + def empty( + cls, shape: tuple[int, ...], dtype: npt.DTypeLike, order: Literal["C", "F"] = "C" + ) -> Self: + """ + Create an empty buffer with the given shape, dtype, and order. + + This method can be faster than ``NDBuffer.create`` because it doesn't + have to initialize the memory used by the underlying ndarray-like + object. + + Parameters + ---------- + shape + The shape of the buffer and its underlying ndarray-like object + dtype + The datatype of the buffer and its underlying ndarray-like object + order + Whether to store multi-dimensional data in row-major (C-style) or + column-major (Fortran-style) order in memory. + + Returns + ------- + buffer + New buffer representing a new ndarray_like object with empty data. + + See Also + -------- + NDBuffer.create + Create a new buffer with some initial fill value. + """ + # Implementations should override this method if they have a faster way + # to allocate an empty buffer. + return cls.create(shape=shape, dtype=dtype, order=order) + + @classmethod + def from_ndarray_like(cls, ndarray_like: NDArrayLike) -> Self: + """Create a new buffer of an ndarray-like object + + Parameters + ---------- + ndarray_like + ndarray-like object + + Returns + ------- + New buffer representing `ndarray_like` + """ + return cls(ndarray_like) + + @classmethod + @abstractmethod + def from_numpy_array(cls, array_like: npt.ArrayLike) -> Self: + """Create a new buffer of Numpy array-like object + + Parameters + ---------- + array_like + Object that can be coerced into a Numpy array + + Returns + ------- + New buffer representing `array_like` + """ + if cls is NDBuffer: + raise NotImplementedError( + "Cannot call abstract method on the abstract class 'NDBuffer'" + ) + return cls( + cast("NDArrayLike", None) + ) # This line will never be reached, but it satisfies the type checker + + def as_ndarray_like(self) -> NDArrayLike: + """Returns the underlying array (host or device memory) of this buffer + + This will never copy data. + + Returns + ------- + The underlying array such as a NumPy or CuPy array. + """ + return self._data + + @abstractmethod + def as_numpy_array(self) -> npt.NDArray[Any]: + """Returns the buffer as a NumPy array (host memory). + + Warnings + -------- + Might have to copy data, consider using `.as_ndarray_like()` instead. + + Returns + ------- + NumPy array of this buffer (might be a data copy) + """ + ... + + def as_scalar(self) -> ScalarType: + """Returns the buffer as a scalar value""" + if self._data.size != 1: + raise ValueError("Buffer does not contain a single scalar value") + return cast("ScalarType", self.as_numpy_array()[()]) + + @property + def dtype(self) -> np.dtype[Any]: + return self._data.dtype + + @property + def shape(self) -> tuple[int, ...]: + return self._data.shape + + @property + def byteorder(self) -> EndianLiteral: + if self.dtype.byteorder == "<": + return "little" + elif self.dtype.byteorder == ">": + return "big" + else: + return sys.byteorder + + def reshape(self, newshape: tuple[int, ...] | Literal[-1]) -> Self: + # numpy accepts a bare -1, but the NDArrayLike protocol only types the + # tuple form; normalize so the forwarded value matches the protocol. + shape = (newshape,) if newshape == -1 else newshape + return self.__class__(self._data.reshape(shape)) + + def squeeze(self, axis: tuple[int, ...]) -> Self: + newshape = tuple(a for i, a in enumerate(self.shape) if i not in axis) + return self.__class__(self._data.reshape(newshape)) + + def astype(self, dtype: npt.DTypeLike, order: Literal["K", "A", "C", "F"] = "K") -> Self: + return self.__class__(self._data.astype(dtype=dtype, order=order)) + + @abstractmethod + def __getitem__(self, key: Any) -> Self: ... + + @abstractmethod + def __setitem__(self, key: Any, value: Any) -> None: ... + + def __len__(self) -> int: + return self._data.__len__() + + def __repr__(self) -> str: + return f"" + + def all_equal(self, other: Any, equal_nan: bool = True) -> bool: + """Compare to `other` using np.array_equal.""" + if other is None: + # Handle None fill_value for Zarr V2 + return False + # Handle positive and negative zero by comparing bit patterns: + if ( + np.asarray(other).dtype.kind == "f" + and other == 0.0 + and self._data.dtype.kind not in ("U", "S", "T", "O", "V") + ): + _data, other = np.broadcast_arrays(self._data, np.asarray(other, self._data.dtype)) + void_dtype = f"V{_data.dtype.itemsize}" + return np.array_equal(_data.view(void_dtype), other.view(void_dtype)) + # use array_equal to obtain equal_nan=True functionality + # Since fill-value is a scalar, isn't there a faster path than allocating a new array for fill value + # every single time we have to write data? + _data, other = np.broadcast_arrays(self._data, other) + return np.array_equal( + _data, + other, + equal_nan=equal_nan + if self._data.dtype.kind not in ("U", "S", "T", "O", "V") + else False, + ) + + def fill(self, value: Any) -> None: + self._data.fill(value) + + def copy(self) -> Self: + return self.__class__(self._data.copy()) + + def transpose(self, axes: SupportsIndex | Sequence[SupportsIndex] | None) -> Self: + return self.__class__(self._data.transpose(axes)) + + +class BufferPrototype(NamedTuple): + """Prototype of the Buffer and NDBuffer class + + The protocol must be pickable. + + Attributes + ---------- + buffer + The Buffer class to use when Zarr needs to create new Buffer. + nd_buffer + The NDBuffer class to use when Zarr needs to create new NDBuffer. + """ + + buffer: type[Buffer] + nd_buffer: type[NDBuffer] + + +# The default buffer prototype used throughout the Zarr codebase. +def default_buffer_prototype() -> BufferPrototype: + from zarr.registry import ( + get_buffer_class, + get_ndbuffer_class, + ) + + return BufferPrototype(buffer=get_buffer_class(), nd_buffer=get_ndbuffer_class()) diff --git a/src/zarr/core/buffer/cpu.py b/src/zarr/core/buffer/cpu.py new file mode 100644 index 0000000000..8994281b58 --- /dev/null +++ b/src/zarr/core/buffer/cpu.py @@ -0,0 +1,238 @@ +from __future__ import annotations + +from typing import ( + TYPE_CHECKING, + Any, + Literal, +) + +import numpy as np +import numpy.typing as npt + +from zarr.core.buffer import core +from zarr.registry import ( + register_buffer, + register_ndbuffer, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + from typing import Self + + from zarr.core.buffer.core import ArrayLike, NDArrayLike + from zarr.core.common import BytesLike + + +class Buffer(core.Buffer): + """A flat contiguous memory block + + We use Buffer throughout Zarr to represent a contiguous block of memory. + + A Buffer is backed by an underlying array-like instance that represents + the memory. The memory type is unspecified; can be regular host memory, + CUDA device memory, or something else. The only requirement is that the + array-like instance can be copied/converted to a regular Numpy array + (host memory). + + Notes + ----- + This buffer is untyped, so all indexing and sizes are in bytes. + + Parameters + ---------- + array_like + array-like object that must be 1-dim, contiguous, and byte dtype. + """ + + def __init__(self, array_like: ArrayLike) -> None: + super().__init__(array_like) + + @classmethod + def create_zero_length(cls) -> Self: + return cls(np.array([], dtype="B")) + + @classmethod + def from_buffer(cls, buffer: core.Buffer) -> Self: + """Create a new buffer of an existing Buffer + + This is useful if you want to ensure that an existing buffer is + of the correct subclass of Buffer. E.g., MemoryStore uses this + to return a buffer instance of the subclass specified by its + BufferPrototype argument. + + Typically, this only copies data if the data has to be moved between + memory types, such as from host to device memory. + + Parameters + ---------- + buffer + buffer object. + + Returns + ------- + A new buffer representing the content of the input buffer + + Notes + ----- + Subclasses of `Buffer` must override this method to implement + more optimal conversions that avoid copies where possible + """ + return cls.from_array_like(buffer.as_numpy_array()) + + @classmethod + def from_bytes(cls, bytes_like: BytesLike) -> Self: + """Create a new buffer of a bytes-like object (host memory) + + Parameters + ---------- + bytes_like + bytes-like object + + Returns + ------- + New buffer representing `bytes_like` + """ + return cls.from_array_like(np.frombuffer(bytes_like, dtype="B")) + + def as_numpy_array(self) -> npt.NDArray[Any]: + """Returns the buffer as a NumPy array (host memory). + + Notes + ----- + Might have to copy data, consider using `.as_array_like()` instead. + + Returns + ------- + NumPy array of this buffer (might be a data copy) + """ + return np.asanyarray(self._data) + + def combine(self, others: Iterable[core.Buffer]) -> Self: + data = [np.asanyarray(self._data)] + for buf in others: + other_array = buf.as_array_like() + assert other_array.dtype == np.dtype("B") + data.append(np.asanyarray(other_array)) + return self.__class__(np.concatenate(data)) + + +class NDBuffer(core.NDBuffer): + """An n-dimensional memory block + + We use NDBuffer throughout Zarr to represent a n-dimensional memory block. + + An NDBuffer is backed by an underlying ndarray-like instance that represents + the memory. The memory type is unspecified; can be regular host memory, + CUDA device memory, or something else. The only requirement is that the + ndarray-like instance can be copied/converted to a regular Numpy array + (host memory). + + Notes + ----- + The two buffer classes Buffer and NDBuffer are very similar. In fact, Buffer + is a special case of NDBuffer where dim=1, stride=1, and dtype="B". However, + in order to use Python's type system to differentiate between the contiguous + Buffer and the n-dim (non-contiguous) NDBuffer, we keep the definition of the + two classes separate. + + Parameters + ---------- + array + ndarray-like object that is convertible to a regular Numpy array. + """ + + def __init__(self, array: NDArrayLike) -> None: + super().__init__(array) + + @classmethod + def create( + cls, + *, + shape: Iterable[int], + dtype: npt.DTypeLike, + order: Literal["C", "F"] = "C", + fill_value: Any | None = None, + ) -> Self: + # np.zeros is much faster than np.full, and therefore using it when possible is better. + if fill_value is None or (isinstance(fill_value, int) and fill_value == 0): + return cls(np.zeros(shape=tuple(shape), dtype=dtype, order=order)) + else: + return cls(np.full(shape=tuple(shape), fill_value=fill_value, dtype=dtype, order=order)) + + @classmethod + def empty( + cls, shape: tuple[int, ...], dtype: npt.DTypeLike, order: Literal["C", "F"] = "C" + ) -> Self: + return cls(np.empty(shape=shape, dtype=dtype, order=order)) + + @classmethod + def from_numpy_array(cls, array_like: npt.ArrayLike) -> Self: + return cls.from_ndarray_like(np.asanyarray(array_like)) + + def as_numpy_array(self) -> npt.NDArray[Any]: + """Returns the buffer as a NumPy array (host memory). + + Warnings + -------- + Might have to copy data, consider using `.as_ndarray_like()` instead. + + Returns + ------- + NumPy array of this buffer (might be a data copy) + """ + return np.asanyarray(self._data) + + def __getitem__(self, key: Any) -> Self: + return self.__class__(np.asanyarray(self._data.__getitem__(key))) + + def __setitem__(self, key: Any, value: Any) -> None: + if isinstance(value, NDBuffer): + value = value._data + self._data.__setitem__(key, value) + + +def as_numpy_array_wrapper( + func: Callable[[npt.NDArray[Any]], bytes], buf: core.Buffer, prototype: core.BufferPrototype +) -> core.Buffer: + """Converts the input of `func` to a numpy array and the output back to `Buffer`. + + This function is useful when calling a `func` that only support host memory such + as `GZip.decode` and `Blosc.decode`. In this case, use this wrapper to convert + the input `buf` to a Numpy array and convert the result back into a `Buffer`. + + Parameters + ---------- + func + The callable that will be called with the converted `buf` as input. + `func` must return bytes, which will be converted into a `Buffer` + before returned. + buf + The buffer that will be converted to a Numpy array before given as + input to `func`. + prototype + The prototype of the output buffer. + + Returns + ------- + The result of `func` converted to a `Buffer` + """ + return prototype.buffer.from_bytes(func(buf.as_numpy_array())) + + +# CPU buffer prototype using numpy arrays +buffer_prototype = core.BufferPrototype(buffer=Buffer, nd_buffer=NDBuffer) +# default_buffer_prototype = buffer_prototype + + +# The numpy prototype used for E.g. when reading the shard index +def numpy_buffer_prototype() -> core.BufferPrototype: + return core.BufferPrototype(buffer=Buffer, nd_buffer=NDBuffer) + + +register_buffer(Buffer, qualname="zarr.buffer.cpu.Buffer") +register_ndbuffer(NDBuffer, qualname="zarr.buffer.cpu.NDBuffer") + + +# backwards compatibility +register_buffer(Buffer, qualname="zarr.core.buffer.cpu.Buffer") +register_ndbuffer(NDBuffer, qualname="zarr.core.buffer.cpu.NDBuffer") diff --git a/src/zarr/core/buffer/gpu.py b/src/zarr/core/buffer/gpu.py new file mode 100644 index 0000000000..8672942364 --- /dev/null +++ b/src/zarr/core/buffer/gpu.py @@ -0,0 +1,237 @@ +from __future__ import annotations + +import warnings +from typing import ( + TYPE_CHECKING, + Any, + Literal, + cast, +) + +import numpy as np +import numpy.typing as npt + +from zarr.core.buffer import core +from zarr.core.buffer.core import ArrayLike, BufferPrototype, NDArrayLike +from zarr.errors import ZarrUserWarning +from zarr.registry import ( + register_buffer, + register_ndbuffer, +) + +if TYPE_CHECKING: + from collections.abc import Iterable + from typing import Self + + from zarr.core.common import BytesLike + +try: + import cupy as cp +except ImportError: + cp = None + + +class Buffer(core.Buffer): + """A flat contiguous memory block on the GPU + + We use Buffer throughout Zarr to represent a contiguous block of memory. + + A Buffer is backed by an underlying array-like instance that represents + the memory. The memory type is unspecified; can be regular host memory, + CUDA device memory, or something else. The only requirement is that the + array-like instance can be copied/converted to a regular Numpy array + (host memory). + + Notes + ----- + This buffer is untyped, so all indexing and sizes are in bytes. + + Parameters + ---------- + array_like + array-like object that must be 1-dim, contiguous, and byte dtype. + """ + + def __init__(self, array_like: ArrayLike) -> None: + if cp is None: + raise ImportError( + "Cannot use zarr.buffer.gpu.Buffer without cupy. Please install cupy." + ) + + if array_like.ndim != 1: + raise ValueError("array_like: only 1-dim allowed") + if array_like.dtype != np.dtype("B"): + raise ValueError("array_like: only byte dtype allowed") + + if not hasattr(array_like, "__cuda_array_interface__"): + # Slow copy based path for arrays that don't support the __cuda_array_interface__ + # TODO: Add a fast zero-copy path for arrays that support the dlpack protocol + msg = ( + "Creating a zarr.buffer.gpu.Buffer with an array that does not support the " + "__cuda_array_interface__ for zero-copy transfers, " + "falling back to slow copy based path" + ) + warnings.warn( + msg, + category=ZarrUserWarning, + stacklevel=2, + ) + self._data = cp.asarray(array_like) + + @classmethod + def create_zero_length(cls) -> Self: + """Create an empty buffer with length zero + + Returns + ------- + New empty 0-length buffer + """ + return cls(cp.array([], dtype="B")) + + @classmethod + def from_buffer(cls, buffer: core.Buffer) -> Self: + """Create a GPU Buffer given an arbitrary Buffer + This will try to be zero-copy if `buffer` is already on the + GPU and will trigger a copy if not. + + Returns + ------- + New GPU Buffer constructed from `buffer` + """ + return cls(buffer.as_array_like()) + + @classmethod + def from_bytes(cls, bytes_like: BytesLike) -> Self: + return cls.from_array_like(cp.frombuffer(bytes_like, dtype="B")) + + def as_numpy_array(self) -> npt.NDArray[Any]: + return cast("npt.NDArray[Any]", cp.asnumpy(self._data)) + + def combine(self, others: Iterable[core.Buffer]) -> Self: + data = [cp.asanyarray(self._data)] + for other in others: + other_array = other.as_array_like() + assert other_array.dtype == np.dtype("B") + gpu_other = Buffer(other_array) + gpu_other_array = gpu_other.as_array_like() + data.append(cp.asanyarray(gpu_other_array)) + return self.__class__(cp.concatenate(data)) + + +class NDBuffer(core.NDBuffer): + """A n-dimensional memory block on the GPU + + We use NDBuffer throughout Zarr to represent a n-dimensional memory block. + + An NDBuffer is backed by an underlying ndarray-like instance that represents + the memory. The memory type is unspecified; can be regular host memory, + CUDA device memory, or something else. The only requirement is that the + ndarray-like instance can be copied/converted to a regular Numpy array + (host memory). + + Notes + ----- + The two buffer classes Buffer and NDBuffer are very similar. In fact, Buffer + is a special case of NDBuffer where dim=1, stride=1, and dtype="B". However, + in order to use Python's type system to differentiate between the contiguous + Buffer and the n-dim (non-contiguous) NDBuffer, we keep the definition of the + two classes separate. + + Parameters + ---------- + array + ndarray-like object that is convertible to a regular Numpy array. + """ + + def __init__(self, array: NDArrayLike) -> None: + if cp is None: + raise ImportError( + "Cannot use zarr.buffer.gpu.NDBuffer without cupy. Please install cupy." + ) + + # assert array.ndim > 0 + assert array.dtype != object + self._data = array + + if not hasattr(array, "__cuda_array_interface__"): + # Slow copy based path for arrays that don't support the __cuda_array_interface__ + # TODO: Add a fast zero-copy path for arrays that support the dlpack protocol + msg = ( + "Creating a zarr.buffer.gpu.NDBuffer with an array that does not support the " + "__cuda_array_interface__ for zero-copy transfers, " + "falling back to slow copy based path" + ) + warnings.warn( + msg, + stacklevel=2, + ) + self._data = cp.asarray(array) + + @classmethod + def create( + cls, + *, + shape: Iterable[int], + dtype: npt.DTypeLike, + order: Literal["C", "F"] = "C", + fill_value: Any | None = None, + ) -> Self: + ret = cls(cp.empty(shape=tuple(shape), dtype=dtype, order=order)) + if fill_value is not None: + ret.fill(fill_value) + return ret + + @classmethod + def empty( + cls, shape: tuple[int, ...], dtype: npt.DTypeLike, order: Literal["C", "F"] = "C" + ) -> Self: + return cls(cp.empty(shape=shape, dtype=dtype, order=order)) + + @classmethod + def from_numpy_array(cls, array_like: npt.ArrayLike) -> Self: + """Create a new buffer of Numpy array-like object + + Parameters + ---------- + array_like + Object that can be coerced into a Numpy array + + Returns + ------- + New buffer representing `array_like` + """ + return cls(cp.asarray(array_like)) + + def as_numpy_array(self) -> npt.NDArray[Any]: + """Returns the buffer as a NumPy array (host memory). + + Warnings + -------- + Might have to copy data, consider using `.as_ndarray_like()` instead. + + Returns + ------- + NumPy array of this buffer (might be a data copy) + """ + return cast("npt.NDArray[Any]", cp.asnumpy(self._data)) + + def __getitem__(self, key: Any) -> Self: + return self.__class__(self._data.__getitem__(key)) + + def __setitem__(self, key: Any, value: Any) -> None: + if isinstance(value, NDBuffer): + value = value._data + elif isinstance(value, core.NDBuffer): + gpu_value = NDBuffer(value.as_ndarray_like()) + value = gpu_value._data + self._data.__setitem__(key, value) + + +buffer_prototype = BufferPrototype(buffer=Buffer, nd_buffer=NDBuffer) + +register_buffer(Buffer, qualname="zarr.buffer.gpu.Buffer") +register_ndbuffer(NDBuffer, qualname="zarr.buffer.gpu.NDBuffer") + +# backwards compatibility +register_buffer(Buffer, qualname="zarr.core.buffer.gpu.Buffer") +register_ndbuffer(NDBuffer, qualname="zarr.core.buffer.gpu.NDBuffer") diff --git a/src/zarr/core/chunk_grids.py b/src/zarr/core/chunk_grids.py new file mode 100644 index 0000000000..584829bc6c --- /dev/null +++ b/src/zarr/core/chunk_grids.py @@ -0,0 +1,949 @@ +from __future__ import annotations + +import bisect +import itertools +import math +import numbers +import operator +import warnings +from dataclasses import dataclass, field +from functools import reduce +from typing import ( + TYPE_CHECKING, + Any, + NamedTuple, + NewType, + Protocol, + TypeGuard, + cast, + runtime_checkable, +) + +import numpy as np +import numpy.typing as npt + +import zarr +from zarr.core.common import ( + ShapeLike, + ceildiv, + parse_shapelike, +) +from zarr.errors import ZarrUserWarning + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator, Sequence + + from zarr.core.array import ShardsLike + from zarr.core.metadata import ArrayMetadata + +SHARDED_INNER_CHUNK_MAX_BYTES: int = 1048576 +"""Target ceiling in bytes for the auto-chunking heuristic when sharding is active (1 MiB). + +Applied when `chunks` is left to auto-chunking (`None` or `"auto"`) and `shards` +is not `None`. Explicit chunk sizes are not affected by this value. +""" + +ChunksTuple = NewType("ChunksTuple", tuple[np.ndarray[tuple[int], np.dtype[np.int64]], ...]) +"""Normalized chunk specification: one 1D int64 array of chunk sizes per dimension. + +Produced exclusively by `normalize_chunks_nd` and `guess_chunks`. +Consumers should use this type to ensure they receive validated, +canonical chunk specifications rather than raw user input. +""" + + +class ChunkLayout(NamedTuple): + """Result of resolving user `chunks`/`shards` into grid metadata inputs. + + outer_chunks + Chunk sizes for the chunk grid metadata. When sharding is active + these are the shard sizes; otherwise they are the user's chunk sizes. + inner + Recursive sub-structure inside each chunk. `None` means the chunk is + opaque (no sharding). When present, `inner.outer_chunks` gives the + sub-chunk sizes passed to `ShardingCodec`, and `inner.inner` gives + the next level of nesting (for nested sharding), or `None`. + """ + + outer_chunks: ChunksTuple + inner: ChunkLayout | None = None + + +@dataclass(frozen=True) +class FixedDimension: + """Uniform chunk size. Boundary chunks contain less data but are + encoded at full size by the codec pipeline.""" + + size: int # chunk edge length (>= 0) + extent: int # array dimension length + nchunks: int = field(init=False, repr=False) + ngridcells: int = field(init=False, repr=False) + + def __post_init__(self) -> None: + if self.size < 0: + raise ValueError(f"FixedDimension size must be >= 0, got {self.size}") + if self.extent < 0: + raise ValueError(f"FixedDimension extent must be >= 0, got {self.extent}") + if self.size == 0: + n = 0 + else: + n = ceildiv(self.extent, self.size) + object.__setattr__(self, "nchunks", n) + object.__setattr__(self, "ngridcells", n) + + def index_to_chunk(self, idx: int) -> int: + if idx < 0: + raise IndexError(f"Negative index {idx} is not allowed") + if idx >= self.extent: + raise IndexError(f"Index {idx} is out of bounds for extent {self.extent}") + if self.size == 0: + return 0 + return idx // self.size + + def chunk_offset(self, chunk_ix: int) -> int: + """Byte-aligned start position of chunk *chunk_ix* in array coordinates. + + Does not validate *chunk_ix* β€” callers must ensure it is in + ``[0, nchunks)``. Use ``ChunkGrid.__getitem__`` for safe access. + """ + return chunk_ix * self.size + + def chunk_size(self, chunk_ix: int) -> int: + """Buffer size for codec processing β€” always uniform. + + Does not validate *chunk_ix* β€” callers must ensure it is in + ``[0, nchunks)``. Use ``ChunkGrid.__getitem__`` for safe access. + """ + return self.size + + def data_size(self, chunk_ix: int) -> int: + """Valid data region within the buffer β€” clipped at extent. + + Does not validate *chunk_ix* β€” callers must ensure it is in + ``[0, nchunks)``. Use ``ChunkGrid.__getitem__`` for safe access. + """ + if self.size == 0: + return 0 + return max(0, min(self.size, self.extent - chunk_ix * self.size)) + + @property + def _unique_edge_lengths(self) -> Iterable[int]: + """Distinct chunk edge lengths for this dimension. + + Used by shard validation to check that every unique edge length + is divisible by the inner chunk size. O(1) for fixed dimensions + since there is only one edge length. + """ + return (self.size,) + + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: + if self.size == 0: + return np.zeros_like(indices) + return indices // self.size + + def with_extent(self, new_extent: int) -> FixedDimension: + """Re-bind to *new_extent* without modifying edges. + + Used when constructing a grid from existing metadata where edges + are already correct. Raises on + ``VaryingDimension`` if edges don't cover the new extent. + """ + return FixedDimension(size=self.size, extent=new_extent) + + def resize(self, new_extent: int) -> FixedDimension: + """Adapt for a user-initiated array resize, growing edges if needed. + + For ``FixedDimension`` this is identical to ``with_extent`` since + regular grids don't store explicit edges. + """ + return FixedDimension(size=self.size, extent=new_extent) + + @property + def _size_repr(self) -> str: + return str(self.size) + + +@dataclass(frozen=True) +class VaryingDimension: + """Explicit per-chunk sizes. The last chunk may extend past the array + extent (``extent < sum(edges)``), in which case ``data_size`` clips to + the valid region while ``chunk_size`` returns the full edge length for + codec processing. This underflow is allowed to match how regular grids + handle boundary chunks, and to support shrinking an array without + rewriting chunk edges (the spec allows trailing edges beyond the extent).""" + + edges: tuple[int, ...] # per-chunk edge lengths (all > 0) + cumulative: tuple[int, ...] # prefix sums for O(log n) lookup + extent: int # array dimension length (may be < sum(edges) after resize) + nchunks: int = field(init=False, repr=False) # cached at construction + ngridcells: int = field(init=False, repr=False) # cached at construction + + # TODO(perf): for long dimensions (O(million chunks)): + # - with_extent/resize recompute cumulative sums and nchunks from scratch; + # add a fast path that reuses the existing cumulative tuple. + # - Consider storing cumulative as ndarray so bisect calls can use + # np.searchsorted. Scalar lookups (chunk_offset, index_to_chunk) + # would need benchmarking to confirm no regression. + def __init__(self, edges: Sequence[int], extent: int) -> None: + edges_tuple = tuple(edges) + if not edges_tuple: + raise ValueError("VaryingDimension edges must not be empty") + if any(e <= 0 for e in edges_tuple): + raise ValueError(f"All edge lengths must be > 0, got {edges_tuple}") + cumulative = tuple(itertools.accumulate(edges_tuple)) + if extent < 0: + raise ValueError(f"VaryingDimension extent must be >= 0, got {extent}") + if extent > cumulative[-1]: + raise ValueError( + f"VaryingDimension extent {extent} exceeds sum of edges {cumulative[-1]}" + ) + object.__setattr__(self, "edges", edges_tuple) + object.__setattr__(self, "cumulative", cumulative) + object.__setattr__(self, "extent", extent) + # Cache nchunks: number of chunks that overlap [0, extent) + if extent == 0: + n = 0 + else: + n = bisect.bisect_left(cumulative, extent) + 1 + object.__setattr__(self, "nchunks", n) + object.__setattr__(self, "ngridcells", len(edges_tuple)) + + def index_to_chunk(self, idx: int) -> int: + if idx < 0 or idx >= self.extent: + raise IndexError(f"Index {idx} out of bounds for dimension with extent {self.extent}") + return bisect.bisect_right(self.cumulative, idx) + + def chunk_offset(self, chunk_ix: int) -> int: + """Start position of chunk *chunk_ix* in array coordinates. + + Does not validate *chunk_ix* β€” callers must ensure it is in + ``[0, ngridcells)``. Use ``ChunkGrid.__getitem__`` for safe access. + """ + return self.cumulative[chunk_ix - 1] if chunk_ix > 0 else 0 + + def chunk_size(self, chunk_ix: int) -> int: + """Buffer size for codec processing. + + Does not validate *chunk_ix* β€” callers must ensure it is in + ``[0, ngridcells)``. Use ``ChunkGrid.__getitem__`` for safe access. + """ + return self.edges[chunk_ix] + + def data_size(self, chunk_ix: int) -> int: + """Valid data region within the buffer β€” clipped at extent. + + Does not validate *chunk_ix* β€” callers must ensure it is in + ``[0, ngridcells)``. Use ``ChunkGrid.__getitem__`` for safe access. + """ + offset = self.cumulative[chunk_ix - 1] if chunk_ix > 0 else 0 + return max(0, min(self.edges[chunk_ix], self.extent - offset)) + + @property + def _unique_edge_lengths(self) -> Iterable[int]: + """Distinct chunk edge lengths for this dimension (lazily deduplicated). + + Used by shard validation to check that every unique edge length + is divisible by the inner chunk size. Lazy deduplication avoids + materializing all edges for dimensions with many repeated sizes. + """ + seen: set[int] = set() + for e in self.edges: + if e not in seen: + seen.add(e) + yield e + + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: + return np.searchsorted(self.cumulative, indices, side="right") + + def with_extent(self, new_extent: int) -> VaryingDimension: + """Re-bind to *new_extent* without modifying edges. + + Used when constructing a grid from existing metadata where edges + are already correct. Raises if the + existing edges don't cover *new_extent*. + """ + edge_sum = self.cumulative[-1] + if edge_sum < new_extent: + raise ValueError( + f"VaryingDimension edge sum {edge_sum} is less than new extent {new_extent}" + ) + return VaryingDimension(self.edges, extent=new_extent) + + def resize(self, new_extent: int) -> VaryingDimension: + """Adapt for a user-initiated array resize, growing edges if needed. + + Unlike ``with_extent``, this never fails β€” if *new_extent* exceeds + the current edge sum, a new chunk is appended to cover the gap. + Shrinking preserves all edges (the spec allows trailing edges + beyond the array extent). + """ + if new_extent == self.extent: + return self + elif new_extent > self.cumulative[-1]: + expanded_edges = list(self.edges) + [new_extent - self.cumulative[-1]] + return VaryingDimension(expanded_edges, extent=new_extent) + else: + return VaryingDimension(self.edges, extent=new_extent) + + @property + def _size_repr(self) -> str: + return repr(tuple(self.edges)) + + +@runtime_checkable +class DimensionGrid(Protocol): + """Structural interface shared by FixedDimension and VaryingDimension.""" + + @property + def nchunks(self) -> int: ... + @property + def ngridcells(self) -> int: ... + @property + def extent(self) -> int: ... + def index_to_chunk(self, idx: int) -> int: ... + def chunk_offset(self, chunk_ix: int) -> int: ... + def chunk_size(self, chunk_ix: int) -> int: ... + def data_size(self, chunk_ix: int) -> int: ... + def indices_to_chunks(self, indices: npt.NDArray[np.intp]) -> npt.NDArray[np.intp]: ... + @property + def _unique_edge_lengths(self) -> Iterable[int]: ... + def with_extent(self, new_extent: int) -> DimensionGrid: ... + def resize(self, new_extent: int) -> DimensionGrid: ... + @property + def _size_repr(self) -> str: ... + + +@dataclass(frozen=True) +class ChunkSpec: + """Specification of a single chunk's location and size. + + ``slices`` gives the valid data region in array coordinates. + ``codec_shape`` gives the buffer shape for codec processing. + For interior chunks these are equal. For boundary chunks of a regular + grid, ``codec_shape`` is the full declared chunk size while ``shape`` + is clipped. For rectilinear grids, ``shape == codec_shape`` unless the + last chunk extends past the array extent. + """ + + slices: tuple[slice, ...] + codec_shape: tuple[int, ...] + + @property + def shape(self) -> tuple[int, ...]: + return tuple(s.stop - s.start for s in self.slices) + + @property + def is_boundary(self) -> bool: + return self.shape != self.codec_shape + + +# A single dimension's rectilinear chunk spec: bare int (uniform shorthand), +# list of ints (explicit edges), or mixed RLE (e.g. [[10, 3], 5]). + + +def _is_rectilinear_chunks(chunks: Any) -> TypeGuard[Sequence[Sequence[int]]]: + """Check if chunks is a nested sequence (e.g. [[10, 20], [5, 5]]). + + Returns True for inputs like [[10, 20], [5, 5]] or [(10, 20), (5, 5)]. + Returns False for flat sequences like (10, 10) or [10, 10]. + """ + if isinstance(chunks, (str, int, ChunkGrid)): + return False + if not hasattr(chunks, "__iter__"): + return False + try: + first_elem = next(iter(chunks), None) + if first_elem is None: + return False + return hasattr(first_elem, "__iter__") and not isinstance(first_elem, (str, bytes, int)) + except (TypeError, StopIteration): + return False + + +def is_regular_1d( + dim_chunks: Sequence[int] | np.ndarray[tuple[int], np.dtype[np.int64]], +) -> bool: + """Check if a single dimension's chunk sizes represent a regular grid. + + A regular dimension has either all chunks the same size, or all + but the last chunk the same size with the last chunk smaller + (boundary chunk). + """ + if len(dim_chunks) <= 1: + return True + first = dim_chunks[0] + if isinstance(dim_chunks, np.ndarray): + # Vectorized comparison avoids per-element Python iteration over int64 arrays. + return bool((dim_chunks[1:-1] == first).all() and dim_chunks[-1] <= first) + for c in dim_chunks[1:-1]: + if c != first: + return False + # Last chunk must be the same size or a smaller boundary chunk + return dim_chunks[-1] <= first + + +def is_regular_nd( + chunks: Iterable[Sequence[int] | np.ndarray[tuple[int], np.dtype[np.int64]]], +) -> bool: + """Check if an N-dimensional chunk specification represents a regular grid.""" + return all(is_regular_1d(d) for d in chunks) + + +def as_regular_shape(chunks: ChunksTuple) -> tuple[int, ...]: + """Flatten a regular ChunksTuple to one int per dimension.""" + assert is_regular_nd(chunks), f"expected regular chunks, got {chunks}" + return tuple(int(dim[0]) for dim in chunks) + + +@dataclass(frozen=True) +class ChunkGrid: + """ + Unified chunk grid supporting both regular and rectilinear chunking. + + A chunk grid is a concrete arrangement of chunks for a specific array. + It stores the extent (array dimension length) per dimension, enabling + ``grid[coords]`` to return a ``ChunkSpec`` without external parameters. + + Internally represents each dimension as either FixedDimension (uniform chunks) + or VaryingDimension (per-chunk edge lengths with prefix sums). + """ + + _dimensions: tuple[DimensionGrid, ...] + _is_regular: bool + + def __init__(self, *, dimensions: tuple[DimensionGrid, ...]) -> None: + object.__setattr__(self, "_dimensions", dimensions) + object.__setattr__( + self, "_is_regular", all(isinstance(d, FixedDimension) for d in dimensions) + ) + + def __repr__(self) -> str: + sizes = ", ".join(d._size_repr for d in self._dimensions) + shape = tuple(d.extent for d in self._dimensions) + return f"ChunkGrid(chunk_sizes=({sizes}), array_shape={shape})" + + @classmethod + def from_metadata(cls, metadata: ArrayMetadata) -> ChunkGrid: + """Construct a ChunkGrid from array metadata. + + For v2 metadata, builds from shape and chunks. + For v3 metadata, dispatches on the chunk grid type. + """ + from zarr.core.metadata import ArrayV2Metadata + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata, RegularChunkGridMetadata + + if isinstance(metadata, ArrayV2Metadata): + return cls.from_sizes(metadata.shape, tuple(metadata.chunks)) + chunk_grid_meta = metadata.chunk_grid + if isinstance(chunk_grid_meta, RegularChunkGridMetadata): + return cls.from_sizes(metadata.shape, tuple(chunk_grid_meta.chunk_shape)) + elif isinstance(chunk_grid_meta, RectilinearChunkGridMetadata): + return cls.from_sizes(metadata.shape, chunk_grid_meta.chunk_shapes) + else: + raise TypeError(f"Unknown chunk grid metadata type: {type(chunk_grid_meta)}") + + @classmethod + def from_sizes( + cls, + array_shape: ShapeLike, + chunk_sizes: Sequence[int | Sequence[int]], + ) -> ChunkGrid: + """Create a ChunkGrid from per-dimension chunk size specifications. + + Parameters + ---------- + array_shape + The array shape (one extent per dimension). + chunk_sizes + Per-dimension chunk sizes. Each element is either: + + - An ``int`` β€” regular (fixed) chunk size for that dimension. + - A ``Sequence[int]`` β€” explicit per-chunk edge lengths. If all + edges are identical and cover the extent, the dimension is + stored as ``FixedDimension``; otherwise as ``VaryingDimension``. + """ + extents = parse_shapelike(array_shape) + if len(extents) != len(chunk_sizes): + raise ValueError( + f"array_shape has {len(extents)} dimensions but chunk_sizes " + f"has {len(chunk_sizes)} dimensions" + ) + dims: list[DimensionGrid] = [] + for dim_spec, extent in zip(chunk_sizes, extents, strict=True): + if isinstance(dim_spec, int): + dims.append(FixedDimension(size=dim_spec, extent=extent)) + else: + edges_list = list(dim_spec) + if not edges_list: + raise ValueError("Each dimension must have at least one chunk") + edge_sum = sum(edges_list) + if ( + edges_list[0] > 0 + and all(e == edges_list[0] for e in edges_list) + and (extent == edge_sum or len(edges_list) == ceildiv(extent, edges_list[0])) + ): + dims.append(FixedDimension(size=edges_list[0], extent=extent)) + else: + dims.append(VaryingDimension(edges_list, extent=extent)) + return cls(dimensions=tuple(dims)) + + # -- Properties -- + + @property + def ndim(self) -> int: + return len(self._dimensions) + + @property + def is_regular(self) -> bool: + return self._is_regular + + @property + def grid_shape(self) -> tuple[int, ...]: + """Number of chunks per dimension.""" + return tuple(d.nchunks for d in self._dimensions) + + @property + def chunk_shape(self) -> tuple[int, ...]: + """Return the uniform chunk shape. Raises if grid is not regular.""" + if not self.is_regular: + raise ValueError( + "chunk_shape is only available for regular chunk grids. " + "Use grid[coords] for per-chunk sizes." + ) + return tuple(d.size for d in self._dimensions if isinstance(d, FixedDimension)) + + @property + def chunk_sizes(self) -> tuple[tuple[int, ...], ...]: + """Per-dimension chunk sizes, including the final boundary chunk. + + Returns the actual data size of each chunk (clipped at the array + extent), matching the dask ``Array.chunks`` convention. Works for + both regular and rectilinear grids. + + Returns + ------- + tuple[tuple[int, ...], ...] + One inner tuple per dimension, each containing the data size + of every chunk along that dimension. + """ + return tuple(tuple(d.data_size(i) for i in range(d.nchunks)) for d in self._dimensions) + + # -- Collection interface -- + + def __getitem__(self, coords: int | tuple[int, ...]) -> ChunkSpec | None: + """Return the ChunkSpec for a chunk at the given grid position, or None if OOB.""" + if isinstance(coords, int): + coords = (coords,) + if len(coords) != self.ndim: + raise ValueError( + f"Expected {self.ndim} coordinate(s) for a {self.ndim}-d chunk grid, " + f"got {len(coords)}." + ) + slices: list[slice] = [] + codec_shape: list[int] = [] + for dim, ix in zip(self._dimensions, coords, strict=True): + if ix < 0 or ix >= dim.nchunks: + return None + offset = dim.chunk_offset(ix) + slices.append(slice(offset, offset + dim.data_size(ix), 1)) + codec_shape.append(dim.chunk_size(ix)) + return ChunkSpec(tuple(slices), tuple(codec_shape)) + + def __iter__(self) -> Iterator[ChunkSpec]: + """Iterate all chunks, yielding ChunkSpec for each.""" + for coords in itertools.product(*(range(d.nchunks) for d in self._dimensions)): + spec = self[coords] + if spec is not None: + yield spec + + def all_chunk_coords( + self, + *, + origin: Sequence[int] | None = None, + selection_shape: Sequence[int] | None = None, + ) -> Iterator[tuple[int, ...]]: + """Iterate over chunk coordinates, optionally restricted to a subregion. + + Parameters + ---------- + origin : Sequence[int] | None + The first chunk coordinate to return. Defaults to the grid origin. + selection_shape : Sequence[int] | None + The number of chunks per dimension to iterate. Defaults to the + remaining extent from origin. + """ + if origin is None: + origin_parsed = (0,) * self.ndim + else: + origin_parsed = tuple(origin) + if selection_shape is None: + selection_shape_parsed = tuple( + g - o for o, g in zip(origin_parsed, self.grid_shape, strict=True) + ) + else: + selection_shape_parsed = tuple(selection_shape) + ranges = tuple( + range(o, o + s) for o, s in zip(origin_parsed, selection_shape_parsed, strict=True) + ) + return itertools.product(*ranges) + + def iter_chunk_regions( + self, + *, + origin: Sequence[int] | None = None, + selection_shape: Sequence[int] | None = None, + ) -> Iterator[tuple[slice, ...]]: + """Iterate over the data regions (slices) spanned by each chunk. + + Parameters + ---------- + origin : Sequence[int] | None + The first chunk coordinate to return. Defaults to the grid origin. + selection_shape : Sequence[int] | None + The number of chunks per dimension to iterate. Defaults to the + remaining extent from origin. + """ + for coords in self.all_chunk_coords(origin=origin, selection_shape=selection_shape): + spec = self[coords] + if spec is not None: + yield spec.slices + + def get_nchunks(self) -> int: + return reduce(operator.mul, (d.nchunks for d in self._dimensions), 1) + + # -- Resize -- + + def update_shape(self, new_shape: tuple[int, ...]) -> ChunkGrid: + """Return a new ChunkGrid adjusted for *new_shape*. + + For regular (FixedDimension) axes the extent is simply re-bound. + For varying (VaryingDimension) axes: + * **grow**: a new chunk whose size equals the growth is appended. + * **shrink**: trailing chunks that lie entirely beyond *new_shape* are + dropped; the last retained chunk is the one whose cumulative offset + first reaches or exceeds the new extent. + * **no change**: the dimension is kept as-is. + + Raises + ------ + ValueError + If *new_shape* has the wrong number of dimensions. + """ + if len(new_shape) != self.ndim: + raise ValueError( + f"new_shape has {len(new_shape)} dimensions but " + f"chunk grid has {self.ndim} dimensions" + ) + dims = tuple( + dim.resize(new_extent) + for dim, new_extent in zip(self._dimensions, new_shape, strict=True) + ) + return ChunkGrid(dimensions=dims) + + +def _guess_regular_chunks( + shape: tuple[int, ...] | int, + typesize: int, + *, + increment_bytes: int = 256 * 1024, + min_bytes: int = 128 * 1024, + max_bytes: int = 64 * 1024 * 1024, +) -> tuple[int, ...]: + """ + Iteratively guess an appropriate chunk layout for an array, given its shape and + the size of each element in bytes, and size constraints expressed in bytes. This logic is + adapted from h5py. + + Parameters + ---------- + shape : tuple[int, ...] + The chunk shape. + typesize : int + The size, in bytes, of each element of the chunk. + increment_bytes : int = 256 * 1024 + The number of bytes used to increment or decrement the target chunk size in bytes. + min_bytes : int = 128 * 1024 + The soft lower bound on the final chunk size in bytes. + max_bytes : int = 64 * 1024 * 1024 + The hard upper bound on the final chunk size in bytes. + + Returns + ------- + tuple[int, ...] + + """ + if min_bytes >= max_bytes: + raise ValueError(f"Cannot have more min_bytes ({min_bytes}) than max_bytes ({max_bytes})") + if isinstance(shape, int): + shape = (shape,) + + if typesize == 0: + return shape + + ndims = len(shape) + # require chunks to have non-zero length for all dimensions + chunks = np.maximum(np.array(shape, dtype="=f8"), 1) + + # Determine the optimal chunk size in bytes using a PyTables expression. + # This is kept as a float. + dset_size = np.prod(chunks) * typesize + target_size = increment_bytes * (2 ** np.log10(dset_size / (1024.0 * 1024))) + + if target_size > max_bytes: + target_size = max_bytes + elif target_size < min_bytes: + target_size = min_bytes + + idx = 0 + while True: + # Repeatedly loop over the axes, dividing them by 2. Stop when: + # 1a. We're smaller than the target chunk size, OR + # 1b. We're within 50% of the target chunk size, AND + # 2. The chunk is smaller than the maximum chunk size + + chunk_bytes = np.prod(chunks) * typesize + + if ( + chunk_bytes < target_size or abs(chunk_bytes - target_size) / target_size < 0.5 + ) and chunk_bytes < max_bytes: + break + + if np.prod(chunks) == 1: + break # Element size larger than max_bytes + + chunks[idx % ndims] = math.ceil(chunks[idx % ndims] / 2.0) + idx += 1 + + return tuple(int(x) for x in chunks) + + +def normalize_chunks_1d( + chunks: int | Iterable[object], span: int +) -> np.ndarray[tuple[int], np.dtype[np.int64]]: + """ + Normalize a one-dimensional chunk specification into a 1D int64 array of + chunk sizes that cover the span. + + `-1` means "one chunk covering the entire span." + For an integer chunk size, all chunks are uniform β€” the last chunk may + overhang the span. The actual data extent of each chunk is determined + by the chunk grid at runtime, not by this function. + """ + # `numbers.Integral` rather than `int` so that numpy integer scalars (which are not + # `int` subclasses) take the uniform-chunk path instead of being treated as a sequence. + if isinstance(chunks, numbers.Integral): + chunk_size = int(chunks) + if chunk_size == -1: + return np.array([span], dtype=np.int64) + if chunk_size <= 0: + raise ValueError(f"Chunk size must be positive, got {chunk_size}") + if span == 0: + return np.array([chunk_size], dtype=np.int64) + n = ceildiv(span, chunk_size) + return np.full(n, chunk_size, dtype=np.int64) + else: + try: + chunk_list = list(chunks) # type: ignore[arg-type] + except TypeError: + raise TypeError( + f"Chunk specification must be an integer or an iterable of integers; got " + f"{chunks!r} of type {type(chunks).__name__}." + ) from None + if not chunk_list: + raise ValueError("Chunk specification must not be empty") + non_int = [ + (idx, c) for idx, c in enumerate(chunk_list) if not isinstance(c, numbers.Integral) + ] + if non_int: + non_int_idxs, non_int_vals = [*zip(*non_int, strict=False)] + raise TypeError( + f"Each chunk size must be an integer; got non-integer element(s) {non_int_vals!r} " + f"at indices {non_int_idxs!r}. Chunk sizes must be declared as a flat sequence of " + f"positive integers (e.g. [3, 3, 1])." + ) + ints: list[int] = [int(c) for c in chunk_list] # type: ignore[call-overload] + if any(c <= 0 for c in ints): + raise ValueError(f"All chunk sizes must be positive, got {ints}") + if sum(ints) != span: + raise ValueError(f"Chunk sizes {ints} do not sum to span {span}") + return np.asarray(ints, dtype=np.int64) + + +def normalize_chunks_nd( + chunks: Any, + shape: tuple[int, ...], +) -> ChunksTuple: + """ + Normalize a chunk specification into a `ChunksTuple`. + + This is a mechanical transformation β€” no heuristics, no guessing. + Handles `False` ("all data in one chunk"), scalar ints, `-1` sentinels (one chunk + per dimension covering the full span), and explicit per-dimension lists + of chunk sizes (regular or rectilinear). + + For auto-chunking, use `guess_chunks` which returns a + `ChunksTuple` directly. `chunks=None` and `chunks=True` are rejected + here β€” the caller is responsible for choosing between explicit sizes + and auto-chunking. + """ + if chunks is None or chunks is True: + raise ValueError( + f'{chunks!r} is not a valid chunk input. Use chunks=None or chunks="auto" from the top-level API for auto-chunking, or pass an int / tuple of ints.' + ) + + # handle no chunking + if chunks is False: + return ChunksTuple(tuple(np.array([s], dtype=np.int64) for s in shape)) + + # handle 1D convenience form. bool is excluded above so this only catches actual ints. + if isinstance(chunks, numbers.Integral): + chunks = tuple(int(chunks) for _ in shape) + + # handle bad dimensionality + if len(chunks) != len(shape): + raise ValueError( + f"chunks has {len(chunks)} dimensions but shape has {len(shape)} dimensions" + ) + + return ChunksTuple( + tuple(normalize_chunks_1d(c, span=s) for c, s in zip(chunks, shape, strict=True)) + ) + + +def guess_chunks( + shape: tuple[int, ...], typesize: int, *, max_bytes: int | None = None +) -> ChunksTuple: + """ + Heuristically determine chunk sizes for an array. + + This is the policy function β€” it makes opinionated choices about + chunk sizes based on array shape and element size, and returns a + normalized `ChunksTuple`. + + Parameters + ---------- + shape : tuple[int, ...] + Array shape. + typesize : int + Size of one element in bytes. + max_bytes : int or None + Target maximum chunk size in bytes. If None, uses the default + heuristic from `_guess_regular_chunks`. + """ + if max_bytes is not None: + flat = _guess_regular_chunks(shape, typesize, max_bytes=max_bytes) + else: + flat = _guess_regular_chunks(shape, typesize) + return normalize_chunks_nd(flat, shape) + + +def _guess_num_chunks_per_axis_shard( + chunk_shape: tuple[int, ...], item_size: int, max_bytes: int, array_shape: tuple[int, ...] +) -> int: + """Generate the number of chunks per axis to hit a target max byte size for a shard. + + For example, for a (2,2,2) chunk size and item size 4, maximum bytes of 256 would return 2. + In other words the shard would be a (2,2,2) grid of (2,2,2) chunks + i.e., prod(chunk_shape) * (returned_val * len(chunk_shape)) * item_size = 256 bytes. + + Parameters + ---------- + chunk_shape + The shape of the (inner) chunks. + item_size + The item size of the data i.e., 2 for uint16. + max_bytes + The maximum number of bytes per shard to allow. + array_shape + The shape of the underlying array. + + Returns + ------- + The number of chunks per axis. + """ + bytes_per_chunk = math.prod(chunk_shape) * item_size + if max_bytes < bytes_per_chunk: + return 1 + num_axes = len(chunk_shape) + chunks_per_shard = 1 + # First check for byte size, second check to make sure we don't go bigger than the array shape + while (bytes_per_chunk * ((chunks_per_shard + 1) ** num_axes)) <= max_bytes and all( + c * (chunks_per_shard + 1) <= a for c, a in zip(chunk_shape, array_shape, strict=True) + ): + chunks_per_shard += 1 + return chunks_per_shard + + +def resolve_outer_and_inner_chunks( + *, + array_shape: tuple[int, ...], + chunks: ChunksTuple, + shard_shape: ShardsLike | None, + item_size: int, +) -> ChunkLayout: + """Resolve user `chunks`/`shards` into outer and inner chunk specs. + + Parameters + ---------- + array_shape + The array shape. + chunks + Normalized chunk specification (the user's `chunks=`). + shard_shape + Raw shard specification (the user's `shards=`). + `None` means no sharding, `"auto"` triggers heuristic inference, + a nested sequence is treated as rectilinear shard boundaries, + and anything else is used as a regular shard shape. + item_size + Element size in bytes. + + Returns + ------- + ChunkLayout + `outer_chunks` is the `ChunksTuple` for chunk grid + metadata. `inner` holds the sub-chunk structure for + `ShardingCodec`, or is `None` when sharding is not active. + """ + if shard_shape is None: + return ChunkLayout(outer_chunks=chunks) + + # Rectilinear shards: normalize the nested sequence directly. + if _is_rectilinear_chunks(shard_shape): + outer = normalize_chunks_nd(shard_shape, array_shape) + return ChunkLayout(outer_chunks=outer, inner=ChunkLayout(outer_chunks=chunks)) + + # Extract the flat chunk shape (first size per dimension) for arithmetic. + chunk_shape_flat = as_regular_shape(chunks) + + if shard_shape == "auto": + warnings.warn( + "Automatic shard shape inference is experimental and may change without notice.", + ZarrUserWarning, + stacklevel=2, + ) + _shards_out: tuple[int, ...] = () + target_shard_size_bytes = zarr.config.get("array.target_shard_size_bytes", None) + num_chunks_per_shard_axis = ( + _guess_num_chunks_per_axis_shard( + chunk_shape=chunk_shape_flat, + item_size=item_size, + max_bytes=target_shard_size_bytes, + array_shape=array_shape, + ) + if (has_auto_shard := (target_shard_size_bytes is not None)) + else 2 + ) + for a_shape, c_shape in zip(array_shape, chunk_shape_flat, strict=True): + can_shard_axis = a_shape // c_shape > 8 if not has_auto_shard else True + if can_shard_axis: + _shards_out += (c_shape * num_chunks_per_shard_axis,) + else: + _shards_out += (c_shape,) + shard_flat = _shards_out + elif isinstance(shard_shape, dict): + shard_flat = tuple(shard_shape["shape"]) + else: + shard_flat = cast("tuple[int, ...]", shard_shape) + + outer = normalize_chunks_nd(shard_flat, array_shape) + return ChunkLayout(outer_chunks=outer, inner=ChunkLayout(outer_chunks=chunks)) diff --git a/src/zarr/core/chunk_key_encodings.py b/src/zarr/core/chunk_key_encodings.py new file mode 100644 index 0000000000..d871e279d2 --- /dev/null +++ b/src/zarr/core/chunk_key_encodings.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, ClassVar, Literal, TypedDict, cast + +if TYPE_CHECKING: + from typing import NotRequired, Self + +from zarr.abc.metadata import Metadata +from zarr.core.common import ( + JSON, + NamedConfig, + parse_named_configuration, +) +from zarr.core.json_parse import parse_field +from zarr.registry import get_chunk_key_encoding_class, register_chunk_key_encoding + +SeparatorLiteral = Literal[".", "/"] + + +def parse_separator(data: JSON) -> SeparatorLiteral: + return cast("SeparatorLiteral", parse_field(data, Literal[".", "/"], "separator")) + + +class ChunkKeyEncodingParams(TypedDict): + name: Literal["v2", "default"] + separator: NotRequired[SeparatorLiteral] + + +@dataclass(frozen=True) +class ChunkKeyEncoding(ABC, Metadata): + """ + Defines how chunk coordinates are mapped to store keys. + + Subclasses must define a class variable `name` and implement `encode_chunk_key`. + """ + + name: ClassVar[str] + + @classmethod + def from_dict(cls, data: dict[str, JSON]) -> Self: + _, config_parsed = parse_named_configuration(data, require_configuration=False) + return cls(**config_parsed or {}) + + def to_dict(self) -> dict[str, JSON]: + return {"name": self.name, "configuration": super().to_dict()} + + def decode_chunk_key(self, chunk_key: str) -> tuple[int, ...]: + """ + Optional: decode a chunk key string into chunk coordinates. + Not required for normal operation; override if needed for testing or debugging. + """ + raise NotImplementedError(f"{self.__class__.__name__} does not implement decode_chunk_key.") + + @abstractmethod + def encode_chunk_key(self, chunk_coords: tuple[int, ...]) -> str: + """ + Encode chunk coordinates into a chunk key string. + Must be implemented by subclasses. + """ + + +type ChunkKeyEncodingLike = ( + dict[str, JSON] | ChunkKeyEncodingParams | ChunkKeyEncoding | NamedConfig[str, Any] +) + + +@dataclass(frozen=True) +class DefaultChunkKeyEncoding(ChunkKeyEncoding): + name: ClassVar[Literal["default"]] = "default" + separator: SeparatorLiteral = "/" + + def __post_init__(self) -> None: + separator_parsed = parse_separator(self.separator) + object.__setattr__(self, "separator", separator_parsed) + + def decode_chunk_key(self, chunk_key: str) -> tuple[int, ...]: + if chunk_key == "c": + return () + # Strip the "c" prefix (e.g. "c/" or "c.") before splitting. + prefix = "c" + self.separator + if chunk_key.startswith(prefix): + return tuple(map(int, chunk_key[len(prefix) :].split(self.separator))) + raise ValueError(f"Invalid chunk key for default encoding: {chunk_key!r}") + + def encode_chunk_key(self, chunk_coords: tuple[int, ...]) -> str: + return self.separator.join(map(str, ("c",) + chunk_coords)) + + +@dataclass(frozen=True) +class V2ChunkKeyEncoding(ChunkKeyEncoding): + name: ClassVar[Literal["v2"]] = "v2" + separator: SeparatorLiteral = "." + + def __post_init__(self) -> None: + separator_parsed = parse_separator(self.separator) + object.__setattr__(self, "separator", separator_parsed) + + def decode_chunk_key(self, chunk_key: str) -> tuple[int, ...]: + return tuple(map(int, chunk_key.split(self.separator))) + + def encode_chunk_key(self, chunk_coords: tuple[int, ...]) -> str: + chunk_identifier = self.separator.join(map(str, chunk_coords)) + return "0" if chunk_identifier == "" else chunk_identifier + + +def parse_chunk_key_encoding(data: ChunkKeyEncodingLike) -> ChunkKeyEncoding: + """ + Take an implicit specification of a chunk key encoding and parse it into a ChunkKeyEncoding object. + """ + if isinstance(data, ChunkKeyEncoding): + return data + + # handle ChunkKeyEncodingParams + if "name" in data and "separator" in data: + data = {"name": data["name"], "configuration": {"separator": data["separator"]}} # type: ignore[typeddict-item] + + # Now must be a named config + data = cast("dict[str, JSON]", data) + + name_parsed, _ = parse_named_configuration(data, require_configuration=False) + try: + chunk_key_encoding = get_chunk_key_encoding_class(name_parsed).from_dict(data) + except KeyError as e: + raise ValueError(f"Unknown chunk key encoding: {e.args[0]!r}") from e + + return chunk_key_encoding + + +register_chunk_key_encoding("default", DefaultChunkKeyEncoding) +register_chunk_key_encoding("v2", V2ChunkKeyEncoding) diff --git a/src/zarr/core/chunk_utils.py b/src/zarr/core/chunk_utils.py new file mode 100644 index 0000000000..b26d5478b2 --- /dev/null +++ b/src/zarr/core/chunk_utils.py @@ -0,0 +1,369 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, cast + +from zarr.abc.codec import GetResult, SupportsSyncCodec, _codec_supports_sync +from zarr.core.indexing import is_scalar + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + + from zarr.abc.codec import Codec + from zarr.core.array_spec import ArraySpec + from zarr.core.buffer import Buffer, NDBuffer + from zarr.core.indexing import SelectorTuple + + +def evolve_codecs(codecs: Iterable[Codec], array_spec: ArraySpec) -> tuple[Codec, ...]: + """Evolve a codec chain against ``array_spec``, threading the spec forward. + + Each codec is evolved against the spec produced by the previous one β€” NOT + the original ``array_spec`` β€” because earlier array->array codecs may + transform the chunk spec (e.g. ``cast_value`` widening int8 -> int16). A + later codec (notably the array->bytes serializer) must be evolved against + the spec it will actually see at run time; evolving every codec against the + unthreaded original spec would, for example, strip a ``BytesCodec``'s + ``endian`` (it sees the single-byte source dtype) and then fail at decode + time on the multi-byte target. + + This is the single source of truth for pipeline-construction-time codec + evolution, shared by every ``CodecPipeline.evolve_from_array_spec``. (The + per-chunk decode/encode counterpart is ``resolve_aa_specs``.) + """ + evolved: list[Codec] = [] + spec = array_spec + for codec in codecs: + evolved_codec = codec.evolve_from_array_spec(array_spec=spec) + evolved.append(evolved_codec) + spec = evolved_codec.resolve_metadata(spec) + return tuple(evolved) + + +def encode_or_elide_chunk( + chunk_array: NDBuffer, + chunk_spec: ArraySpec, + encode: Callable[[NDBuffer, ArraySpec], Buffer | None], +) -> Buffer | None: + """Encode a merged chunk, normalizing empties to missing. + + Returns the bytes to store, or ``None`` meaning the chunk must NOT be + stored (either it normalized to empty per `chunk_is_empty`, or the codec + chain elided it). ``None`` is the single "missing" convention shared by + the chunk write paths and the shard dicts. + """ + + if chunk_is_empty(chunk_array, chunk_spec): + return None + return encode(chunk_array, chunk_spec) + + +def fill_value_or_default(chunk_spec: ArraySpec) -> Any: + fill_value = chunk_spec.fill_value + if fill_value is None: + # Zarr V2 allowed `fill_value` to be null in the metadata. + # Zarr V3 requires it to be set. This has already been + # validated when decoding the metadata, but we support reading + # Zarr V2 data and need to support the case where fill_value + # is None. + return chunk_spec.dtype.default_scalar() + else: + return fill_value + + +def chunk_is_empty(chunk_array: NDBuffer, chunk_spec: ArraySpec) -> bool: + """THE empty-chunk normalization rule, in one place. + + With ``write_empty_chunks=False`` (the default), a chunk whose decoded + content equals the fill value normalizes to *missing*: it must not be + stored, and readers reconstruct it from the fill value. Every write path + (fused, async fallback, shard inner chunks) must apply this same rule β€” + scattering inline ``all_equal`` checks is how the rule drifts. + """ + return not chunk_spec.config.write_empty_chunks and chunk_array.all_equal( + fill_value_or_default(chunk_spec) + ) + + +def scatter_chunk( + selected: NDBuffer | None, + out: NDBuffer, + *, + chunk_spec: ArraySpec, + out_selection: SelectorTuple, + drop_axes: tuple[int, ...], +) -> GetResult: + """Scatter one chunk's (already-selected) decoded region into ``out``. + + ``None`` = the chunk is missing: the fill value is scattered instead and a + ``missing`` status is returned. POLICY-FREE by design: whether a missing + chunk is an error (``read_missing_chunks=False``) is decided by the array + layer from the returned statuses β€” which is also what makes missing INNER + chunks of a present shard fill rather than raise (the sharding codec + discards the nested read's statuses; only top-level statuses reach the + array layer). + """ + if selected is None: + out[out_selection] = fill_value_or_default(chunk_spec) + return GetResult(status="missing") + if drop_axes: + selected = selected.squeeze(axis=drop_axes) + out[out_selection] = selected + return GetResult(status="present") + + +def _merge_chunk_array( + existing_chunk_array: NDBuffer | None, + value: NDBuffer, + out_selection: SelectorTuple, + chunk_spec: ArraySpec, + chunk_selection: SelectorTuple, + is_complete_chunk: bool, + drop_axes: tuple[int, ...], +) -> NDBuffer: + """Merge `value` into a full-chunk-shaped NDBuffer at `chunk_selection`. + + If `is_complete_chunk` and `value[out_selection]` is exactly chunk-shaped, + that VIEW of the caller's `value` is returned without copying β€” callers + (and the codecs they pass it to) must treat it as read-only, since + mutating it would corrupt the user's source array. Otherwise, a writable + buffer is materialized β€” either from `existing_chunk_array.copy()` if + one was read from the store, or freshly allocated and filled with the + chunk's fill value β€” and the relevant slice of `value` is written into it. + """ + if is_complete_chunk and value.shape != (): + selected = value[out_selection] + # The shape check guards against a partial edge chunk arriving with + # is_complete_chunk=True, and against dropped axes (size-1 integer + # dims), where the selection is not exactly chunk-shaped. + if selected.shape == chunk_spec.shape: + return selected + if existing_chunk_array is None: + chunk_array = chunk_spec.prototype.nd_buffer.create( + shape=chunk_spec.shape, + dtype=chunk_spec.dtype.to_native_dtype(), + order=chunk_spec.order, + fill_value=fill_value_or_default(chunk_spec), + ) + else: + chunk_array = existing_chunk_array.copy() + if chunk_selection == () or is_scalar( + value.as_ndarray_like(), chunk_spec.dtype.to_native_dtype() + ): + chunk_value = value + else: + chunk_value = value[out_selection] + if drop_axes: + item = tuple( + None if idx in drop_axes else slice(None) for idx in range(chunk_spec.ndim) + ) + chunk_value = chunk_value[item] + chunk_array[chunk_selection] = chunk_value + return chunk_array + + +def merge_and_encode_chunk( + existing_bytes: Buffer | None, + value: NDBuffer, + *, + chunk_spec: ArraySpec, + chunk_selection: SelectorTuple, + out_selection: SelectorTuple, + is_complete: bool, + drop_axes: tuple[int, ...], + decode: Callable[[Buffer, ArraySpec], NDBuffer], + encode: Callable[[NDBuffer, ArraySpec], Buffer | None], +) -> Buffer | None: + """The canonical single-chunk write: merge, normalize, encode. + + decode existing (``None`` = chunk currently missing) -> merge ``value`` at + ``chunk_selection`` -> normalize empties to missing -> encode. Returns the + bytes to store or ``None`` = do not store / delete. This is the one + state-transition every per-chunk write path expresses; only the IO around + it (where ``existing_bytes`` comes from, where the result goes) differs. + """ + + existing_array = decode(existing_bytes, chunk_spec) if existing_bytes is not None else None + merged = _merge_chunk_array( + existing_array, value, out_selection, chunk_spec, chunk_selection, is_complete, drop_axes + ) + return encode_or_elide_chunk(merged, chunk_spec, encode) + + +def decode_and_scatter_chunk( + chunk_bytes: Buffer | None, + out: NDBuffer, + *, + chunk_spec: ArraySpec, + chunk_selection: SelectorTuple, + out_selection: SelectorTuple, + drop_axes: tuple[int, ...], + decode: Callable[[Buffer, ArraySpec], NDBuffer], +) -> GetResult: + """The canonical single-chunk read: decode stored bytes (``None`` = + missing), select, and scatter into ``out`` via `scatter_chunk`. The read + twin of `merge_and_encode_chunk`. + """ + if chunk_bytes is None: + return scatter_chunk( + None, out, chunk_spec=chunk_spec, out_selection=out_selection, drop_axes=drop_axes + ) + selected = decode(chunk_bytes, chunk_spec)[chunk_selection] + return scatter_chunk( + selected, out, chunk_spec=chunk_spec, out_selection=out_selection, drop_axes=drop_axes + ) + + +@dataclass(slots=True, kw_only=True) +class ChunkTransform: + """A synchronous codec chain. + + Provides `encode_chunk` and `decode_chunk` for pure-compute codec + operations (no IO, no threading, no batching). The `chunk_spec` is + supplied per call so the same transform can be reused across chunks + with different shapes, prototypes, etc. + + All codecs must implement `SupportsSyncCodec`. Construction will + raise `TypeError` if any codec does not. + """ + + codecs: tuple[Codec, ...] + + _aa_codecs: tuple[SupportsSyncCodec[NDBuffer, NDBuffer], ...] = field( + init=False, repr=False, compare=False + ) + _ab_codec: SupportsSyncCodec[NDBuffer, Buffer] = field(init=False, repr=False, compare=False) + _bb_codecs: tuple[SupportsSyncCodec[Buffer, Buffer], ...] = field( + init=False, repr=False, compare=False + ) + + def __post_init__(self) -> None: + from zarr.core.codec_pipeline import codecs_from_list_unchecked + + # _codec_supports_sync, not a bare isinstance check: a codec can satisfy + # the SupportsSyncCodec protocol structurally yet be unable to run + # synchronously (ShardingCodec whose inner/index chain contains an + # async-only codec). Such codecs opt out via `_sync_capable`, and the + # TypeError here is what makes FusedCodecPipeline.evolve_from_array_spec + # decline the sync fast path and fall back to the async pipeline. + non_sync = [c for c in self.codecs if not _codec_supports_sync(c)] + if non_sync: + names = ", ".join(type(c).__name__ for c in non_sync) + raise TypeError( + f"All codecs must implement SupportsSyncCodec. The following do not: {names}" + ) + + # `ChunkTransform` is built from a codec chain that already went + # through `codecs_from_list` when the owning pipeline was constructed + # (see `FusedCodecPipeline.evolve_from_array_spec`), so re-splitting it + # here must not re-emit that chain's advisory warnings. + aa, ab, bb = codecs_from_list_unchecked(list(self.codecs)) + # SupportsSyncCodec was verified above; the cast is purely for mypy. + self._aa_codecs = cast("tuple[SupportsSyncCodec[NDBuffer, NDBuffer], ...]", tuple(aa)) + self._ab_codec = cast("SupportsSyncCodec[NDBuffer, Buffer]", ab) + self._bb_codecs = cast("tuple[SupportsSyncCodec[Buffer, Buffer], ...]", tuple(bb)) + + # The whole cache entry β€” (key, aa_specs, ab_spec) β€” is stored as ONE field + # and replaced with a single attribute write. A `ChunkTransform` is shared + # across thread-pool workers (read_sync/write_sync with max_workers > 1), and + # storing the key separately from the specs would race: a worker could read a + # freshly-set key while the matching specs were still the previous (or None) + # value. A single tuple assignment is atomic under the GIL, so a reader sees + # either the complete old entry or the complete new one β€” never a torn mix. + _cache: tuple[ArraySpec, tuple[ArraySpec, ...], ArraySpec] | None = field( + init=False, repr=False, compare=False, default=None + ) + + def _resolve_specs(self, chunk_spec: ArraySpec) -> tuple[tuple[ArraySpec, ...], ArraySpec]: + """Return per-AA-codec input specs and the AB spec for `chunk_spec`. + + The resolved chain depends only on the value of `chunk_spec`, so we cache + it keyed on `chunk_spec` itself (ArraySpec is a frozen, hashable dataclass + β€” value identity). Keying on `id(chunk_spec)` would be unsafe: ids are + recycled after garbage collection, so a freed spec's id reused by a + different spec (same shape, different prototype/dtype/config) could yield + a stale hit. Value identity avoids that entirely. + + Thread-safety: a benign construction race is possible (two workers with + different specs may each compute and overwrite the single-entry cache β€” + last writer wins), but a torn read is not, because the entry is written + atomically as one tuple. Worst case is a recompute, never a wrong result. + """ + from zarr.core.codec_pipeline import resolve_aa_specs + + if not self._aa_codecs: + return (), chunk_spec + cache = self._cache + if cache is not None and cache[0] == chunk_spec: + return cache[1], cache[2] + + aa_specs_t, spec = resolve_aa_specs(cast("tuple[Codec, ...]", self._aa_codecs), chunk_spec) + self._cache = (chunk_spec, aa_specs_t, spec) + return aa_specs_t, spec + + def decode_chunk(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> NDBuffer: + """Decode a single chunk through the full codec chain, synchronously. + + Pure compute -- no IO. + + Parameters + ---------- + chunk_bytes : Buffer + The encoded chunk bytes. + chunk_spec : ArraySpec + The array spec describing shape, dtype, fill value, and codec + configuration for this chunk. + """ + aa_specs, ab_spec = self._resolve_specs(chunk_spec) + + data: Buffer = chunk_bytes + for bb_codec in reversed(self._bb_codecs): + data = bb_codec._decode_sync(data, ab_spec) + + chunk_array: NDBuffer = self._ab_codec._decode_sync(data, ab_spec) + + for aa_codec, aa_spec in zip(reversed(self._aa_codecs), reversed(aa_specs), strict=True): + chunk_array = aa_codec._decode_sync(chunk_array, aa_spec) + + return chunk_array + + def encode_chunk(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer | None: + """Encode a single chunk through the full codec chain, synchronously. + + Pure compute -- no IO. + + Parameters + ---------- + chunk_array : NDBuffer + The chunk data to encode. + chunk_spec : ArraySpec + The array spec describing shape, dtype, fill value, and codec + configuration for this chunk. + """ + aa_specs, ab_spec = self._resolve_specs(chunk_spec) + + aa_data: NDBuffer = chunk_array + for aa_codec, aa_spec in zip(self._aa_codecs, aa_specs, strict=True): + aa_result = aa_codec._encode_sync(aa_data, aa_spec) + if aa_result is None: + return None + aa_data = aa_result + + ab_result = self._ab_codec._encode_sync(aa_data, ab_spec) + if ab_result is None: + return None + + bb_data: Buffer = ab_result + for bb_codec in self._bb_codecs: + bb_result = bb_codec._encode_sync(bb_data, ab_spec) + if bb_result is None: + return None + bb_data = bb_result + + return bb_data + + def compute_encoded_size(self, byte_length: int, array_spec: ArraySpec) -> int: + for codec in self.codecs: + byte_length = codec.compute_encoded_size(byte_length, array_spec) + array_spec = codec.resolve_metadata(array_spec) + return byte_length diff --git a/src/zarr/core/codec_pipeline.py b/src/zarr/core/codec_pipeline.py new file mode 100644 index 0000000000..597f338c42 --- /dev/null +++ b/src/zarr/core/codec_pipeline.py @@ -0,0 +1,1355 @@ +from __future__ import annotations + +import asyncio +import threading +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass, field +from itertools import batched, chain, pairwise +from typing import TYPE_CHECKING, Any, cast +from warnings import warn + +from zarr.abc.codec import ( + ArrayArrayCodec, + ArrayBytesCodec, + ArrayBytesCodecPartialDecodeMixin, + ArrayBytesCodecPartialEncodeMixin, + BytesBytesCodec, + Codec, + CodecPipeline, + GetResult, +) +from zarr.core.chunk_utils import ( + ChunkTransform, + _merge_chunk_array, + chunk_is_empty, + decode_and_scatter_chunk, + evolve_codecs, + fill_value_or_default, + merge_and_encode_chunk, + scatter_chunk, +) +from zarr.core.common import concurrent_iter, concurrent_map +from zarr.core.config import config +from zarr.errors import ZarrUserWarning +from zarr.registry import register_pipeline + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator, Sequence + from typing import Self + + from zarr.abc.store import ByteGetter, ByteSetter + from zarr.core.array_spec import ArraySpec + from zarr.core.buffer import Buffer, BufferPrototype, NDBuffer + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType + from zarr.core.indexing import SelectorTuple + from zarr.core.metadata.v3 import ChunkGridMetadata + + +_pool: ThreadPoolExecutor | None = None +_pool_size: int = 0 +_pool_lock = threading.Lock() + + +def _resolve_max_workers() -> int: + """Helper for getting the maximum number of workers available to the `FusedCodecPipeline`""" + import os as _os + + default = _os.cpu_count() or 1 + cfg = config.get("codec_pipeline.max_workers", default=None) + if cfg is None: + return default + try: + return max(1, int(cfg)) + except (TypeError, ValueError): + # This value arrives via the config/env layer (e.g. + # `ZARR_CODEC_PIPELINE__MAX_WORKERS`), so tolerate bad input here + # instead of raising mid-read. + warn( + f"Ignoring invalid `codec_pipeline.max_workers` config value {cfg!r}; " + f"falling back to {default}.", + category=ZarrUserWarning, + stacklevel=2, + ) + return default + + +def _get_pool(max_workers: int) -> ThreadPoolExecutor: + """Get or create the module-level thread pool, sized to `max_workers`. + + The pool grows on demand β€” if a request arrives for more workers than the + current pool has, it is replaced with a larger one. The previous pool is NOT + shut down here: another thread may be holding a reference to it and about to + submit (`shutdown` would make its `pool.map` raise "cannot schedule new + futures after shutdown"). The orphaned pool finishes its in-flight tasks and + is garbage-collected once no caller references it. The pool only grows, never + shrinks (a shrink request reuses the larger pool, leaving workers idle). + + Callers that want sequential execution should not call this β€” they + should run the task list inline. `max_workers` must be >= 1. + """ + global _pool, _pool_size + if max_workers < 1: + raise ValueError(f"max_workers must be >= 1, got {max_workers}") + if _pool is None or _pool_size < max_workers: + with _pool_lock: + if _pool is None or _pool_size < max_workers: + # Replace without shutting down the old pool (see docstring): + # avoids a race with a concurrent in-flight pool.map on it. + _pool = ThreadPoolExecutor(max_workers=max_workers) + _pool_size = max_workers + return _pool + + +def _unzip2[T, U](iterable: Iterable[tuple[T, U]]) -> tuple[list[T], list[U]]: + out0: list[T] = [] + out1: list[U] = [] + for item0, item1 in iterable: + out0.append(item0) + out1.append(item1) + return (out0, out1) + + +def resolve_batched(codec: Codec, chunk_specs: Iterable[ArraySpec]) -> Iterable[ArraySpec]: + return [codec.resolve_metadata(chunk_spec) for chunk_spec in chunk_specs] + + +def resolve_aa_specs( + aa_codecs: tuple[Codec, ...], chunk_spec: ArraySpec +) -> tuple[tuple[ArraySpec, ...], ArraySpec]: + """Resolve the per-stage chunk specs for a single chunk's codec chain. + + Threads `chunk_spec` forward through the array->array codecs via + `resolve_metadata` (each codec sees the spec produced by the previous one), + returning `(aa_specs, ab_spec)`: + + * `aa_specs[i]` is the spec the i-th AA codec operates on (its *input* on + encode / *output* on decode); + * `ab_spec` is the spec after all AA codecs β€” what the array->bytes codec + and the bytes->bytes codecs operate on. + + This is the single source of truth for per-stage spec evolution, shared by + the synchronous `ChunkTransform` and the asynchronous + `AsyncChunkTransform`. It is pure metadata (only `resolve_metadata`), so + it places no synchronous-codec requirement on the codecs. + """ + aa_specs: list[ArraySpec] = [] + spec = chunk_spec + for aa_codec in aa_codecs: + aa_specs.append(spec) + spec = aa_codec.resolve_metadata(spec) + return tuple(aa_specs), spec + + +def pipeline_supports_partial_decode( + array_bytes_codec: ArrayBytesCodec, + *, + array_array_codecs: tuple[ArrayArrayCodec, ...], + bytes_bytes_codecs: tuple[BytesBytesCodec, ...], + require_no_aa_bb: bool, +) -> bool: + """Whether a codec pipeline can decode a partial selection without a full read. + + Requires the array->bytes codec to implement + ``ArrayBytesCodecPartialDecodeMixin``. When ``require_no_aa_bb`` is True it + additionally requires no array->array / bytes->bytes codecs, because those + can change the slice<->byte-range correspondence (an AA codec can make the + selection non-contiguous, a BB codec can rewrite the bytes), making partial + decode infeasible. + + Both pipelines pass `require_no_aa_bb=True`: an outer AA/BB codec (e.g. a + compressor wrapping a sharding serializer) must see every byte of the + chunk, so a partial branch that only re-decodes/re-encodes the inner + sharding codec would silently bypass it. + """ + if require_no_aa_bb and (len(array_array_codecs) + len(bytes_bytes_codecs)) != 0: + return False + return isinstance(array_bytes_codec, ArrayBytesCodecPartialDecodeMixin) + + +def pipeline_supports_partial_encode( + array_bytes_codec: ArrayBytesCodec, + *, + array_array_codecs: tuple[ArrayArrayCodec, ...], + bytes_bytes_codecs: tuple[BytesBytesCodec, ...], + require_no_aa_bb: bool, +) -> bool: + """Whether a codec pipeline can encode a partial selection without a full rewrite. + + Mirror of `pipeline_supports_partial_decode` for encoding. + """ + if require_no_aa_bb and (len(array_array_codecs) + len(bytes_bytes_codecs)) != 0: + return False + return isinstance(array_bytes_codec, ArrayBytesCodecPartialEncodeMixin) + + +async def _cancel_and_drain(futures: Iterable[asyncio.Future[Any]]) -> None: + """Cancel every not-yet-done future/task and await its outcome. + + Used to clean up work spawned by a drain loop (`asyncio.as_completed` + + `await`) when the loop exits early via exception. Without this, tasks + already spawned keep running unattended after the caller has moved on, + and an eventual failure surfaces as an unraisable "exception was never + retrieved" warning instead of being observed here. + """ + pending = [f for f in futures if not f.done()] + if len(pending) == 0: + return + for f in pending: + f.cancel() + await asyncio.gather(*pending, return_exceptions=True) + + +async def _fetch_and_decode_as_completed( + batch: Sequence[tuple[ByteGetter | None, ArraySpec]], + transform: ChunkTransform, +) -> list[NDBuffer | None]: + """Concurrently fetch each chunk's bytes and decode it as fetches complete. + + Decoding overlaps with in-flight fetches: each chunk is decoded the moment + its bytes arrive (in a thread pool when one is available, otherwise inline) + rather than waiting for the whole batch to land. A `None` byte getter fetches + nothing and decodes to `None`. Results are returned in input order. + """ + max_workers = _resolve_max_workers() + pool = _get_pool(max_workers) if max_workers > 1 else None + loop = asyncio.get_running_loop() + decode_futures: list[asyncio.Future[NDBuffer | None]] = [loop.create_future() for _ in batch] + + async def _fetch( + idx: int, byte_getter: ByteGetter | None, prototype: BufferPrototype + ) -> tuple[int, Buffer | None]: + return idx, None if byte_getter is None else await byte_getter.get(prototype) + + def _decode(buffer: Buffer | None, chunk_spec: ArraySpec) -> NDBuffer | None: + return None if buffer is None else transform.decode_chunk(buffer, chunk_spec) + + fetch_tasks = concurrent_iter( + [ + (idx, byte_getter, chunk_spec.prototype) + for idx, (byte_getter, chunk_spec) in enumerate(batch) + ], + _fetch, + config.get("async.concurrency"), + ) + try: + for fetch_coro in asyncio.as_completed(fetch_tasks): + idx, buffer = await fetch_coro + chunk_spec = batch[idx][1] + # Bridge both paths to asyncio.Future so the final collection loop + # can `await` uniformly without blocking the event loop. For the + # pool path that means `wrap_future` (not `pool.submit(...).result()`, + # which would block the loop thread for the duration of every decode + # β€” freezing any unrelated coroutines sharing this loop). + if pool is None: + decode_futures[idx].set_result(_decode(buffer, chunk_spec)) + else: + decode_futures[idx] = asyncio.wrap_future(pool.submit(_decode, buffer, chunk_spec)) + + return await asyncio.gather(*decode_futures) + finally: + # On the happy path every future here is already done, so this is a + # no-op; on failure it stops abandoned fetches/decodes from + # continuing to run unattended after this function has raised. A + # single call over both iterables (not two sequential calls) so that + # outer-task cancellation during the first drain can't skip the + # second, leaving its futures/tasks unobserved. + await _cancel_and_drain(chain(fetch_tasks, decode_futures)) + + +async def _encode_and_write_as_completed( + batch: Sequence[tuple[ByteSetter, NDBuffer | None, ArraySpec]], + transform: ChunkTransform, +) -> None: + """Encode each chunk and write it out as encodes complete. + + The reverse of `_fetch_and_decode_as_completed`: each chunk is encoded (in a + thread pool when one is available, otherwise inline) and its write is launched + the moment that chunk's encode finishes β€” overlapping IO writes with + still-running encodes rather than waiting for the whole batch to encode. + A `None` chunk array encodes to `None` and is `delete`d. Writes are bounded + by `async.concurrency`. + """ + max_workers = _resolve_max_workers() + pool = _get_pool(max_workers) if max_workers > 1 else None + loop = asyncio.get_running_loop() + semaphore = asyncio.Semaphore(config.get("async.concurrency")) + + def _encode( + idx: int, chunk_array: NDBuffer | None, chunk_spec: ArraySpec + ) -> tuple[int, Buffer | None]: + return idx, None if chunk_array is None else transform.encode_chunk(chunk_array, chunk_spec) + + async def _write(idx: int, chunk_bytes: Buffer | None) -> None: + byte_setter = batch[idx][0] + async with semaphore: + if chunk_bytes is None: + await byte_setter.delete() + else: + await byte_setter.set(chunk_bytes) + + # Submit every encode up front. The pool path bridges to asyncio.Future via + # `wrap_future` (not `pool.submit(...).result()`, which would block the loop + # thread); the inline path resolves immediately. + encode_futures: list[asyncio.Future[tuple[int, Buffer | None]]] = [] + for idx, (_, chunk_array, chunk_spec) in enumerate(batch): + if pool is None: + fut: asyncio.Future[tuple[int, Buffer | None]] = loop.create_future() + fut.set_result(_encode(idx, chunk_array, chunk_spec)) + else: + fut = asyncio.wrap_future(pool.submit(_encode, idx, chunk_array, chunk_spec)) + encode_futures.append(fut) + + # Kick off each chunk's write the instant its encode lands, so writes of + # already-compressed chunks proceed while the rest are still encoding. + write_tasks: list[asyncio.Task[None]] = [] + try: + for encode_coro in asyncio.as_completed(encode_futures): + idx, chunk_bytes = await encode_coro + write_tasks.append(asyncio.ensure_future(_write(idx, chunk_bytes))) + await asyncio.gather(*write_tasks) + finally: + # On the happy path every future here is already done, so this is a + # no-op; on failure (an encode or a write raising) it stops + # already-spawned writes from continuing in the background after + # this function has raised. A single call over both iterables (not + # two sequential calls) so that outer-task cancellation during the + # first drain can't skip the second, leaving its futures/tasks + # unobserved. + await _cancel_and_drain(chain(write_tasks, encode_futures)) + + +async def _async_read_fallback( + pipeline: CodecPipeline, + batch: list[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + out: NDBuffer, + drop_axes: tuple[int, ...], +) -> tuple[GetResult, ...]: + """Async fallback read used when no fast-path is available. + + Fetches every chunk's bytes via `concurrent_map` (sized by + `async.concurrency`), decodes the batch through `pipeline.decode`, + then scatters each decoded chunk into `out` at its `out_selection`. + + Used by both `BatchedCodecPipeline.read_batch` (non-partial-decode + branch) and `FusedCodecPipeline.read` (when the store does not advertise + sync IO / sync transform is unavailable). + """ + + chunk_array_batch: list[NDBuffer | None] + + if isinstance(pipeline, FusedCodecPipeline) and pipeline.sync_transform is not None: + chunk_array_batch = await _fetch_and_decode_as_completed( + [(byte_getter, chunk_spec) for byte_getter, chunk_spec, *_ in batch], + pipeline.sync_transform, + ) + else: + chunk_bytes_batch = await concurrent_map( + [(byte_getter, array_spec.prototype) for byte_getter, array_spec, *_ in batch], + lambda byte_getter, prototype: byte_getter.get(prototype), + config.get("async.concurrency"), + ) + chunk_array_batch = list( + await pipeline.decode( + [ + (chunk_bytes, chunk_spec) + for chunk_bytes, (_, chunk_spec, *_) in zip( + chunk_bytes_batch, batch, strict=False + ) + ], + ) + ) + + results: list[GetResult] = [] + for chunk_array, (_, chunk_spec, chunk_selection, out_selection, _) in zip( + chunk_array_batch, batch, strict=True + ): + selected = None if chunk_array is None else chunk_array[chunk_selection] + results.append( + scatter_chunk( + selected, + out, + chunk_spec=chunk_spec, + out_selection=out_selection, + drop_axes=drop_axes, + ) + ) + return tuple(results) + + +async def _async_write_fallback( + pipeline: CodecPipeline, + batch: list[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + value: NDBuffer, + drop_axes: tuple[int, ...], +) -> None: + """Async fallback write used when no fast-path is available. + + For each chunk in `batch`: read its existing bytes from the store + (skipping the read for complete chunks), decode the batch via + `pipeline.decode`, merge `value` into each decoded chunk via + `_merge_chunk_array`, drop chunks that are all-fill when + `write_empty_chunks` is False, encode the surviving chunks via + `pipeline.encode`, then `set` the encoded bytes (or `delete` + if encoding produced `None` or the chunk dropped). + + Used by both `BatchedCodecPipeline.write_batch` (non-partial-encode + branch) and `FusedCodecPipeline.write` (when the store does not advertise + sync IO / sync transform is unavailable). + """ + + if use_sync := ( + isinstance(pipeline, FusedCodecPipeline) and pipeline.sync_transform is not None + ): + # Read each chunk's existing bytes (skipping complete chunks) and decode + # as fetches complete, overlapping the sync decode with in-flight reads. + chunk_array_decoded: Iterable[NDBuffer | None] = await _fetch_and_decode_as_completed( + [ + (None if is_complete_chunk else byte_setter, chunk_spec) + for byte_setter, chunk_spec, _, _, is_complete_chunk in batch + ], + pipeline.sync_transform, + ) + else: + + async def _read_key( + byte_setter: ByteSetter | None, prototype: BufferPrototype + ) -> Buffer | None: + if byte_setter is None: + return None + return await byte_setter.get(prototype=prototype) + + chunk_bytes_batch: Iterable[Buffer | None] = await concurrent_map( + [ + ( + None if is_complete_chunk else byte_setter, + chunk_spec.prototype, + ) + for byte_setter, chunk_spec, chunk_selection, _, is_complete_chunk in batch + ], + _read_key, + config.get("async.concurrency"), + ) + chunk_array_decoded = await pipeline.decode( + [ + (chunk_bytes, chunk_spec) + for chunk_bytes, (_, chunk_spec, *_) in zip(chunk_bytes_batch, batch, strict=False) + ], + ) + chunk_array_merged = [ + _merge_chunk_array( + chunk_array, + value, + out_selection, + chunk_spec, + chunk_selection, + is_complete_chunk, + drop_axes, + ) + for chunk_array, ( + _, + chunk_spec, + chunk_selection, + out_selection, + is_complete_chunk, + ) in zip(chunk_array_decoded, batch, strict=False) + ] + # _merge_chunk_array always returns a real NDBuffer (never None), so the only + # way a chunk drops to None here is the empty-chunk normalization. + chunk_array_batch: list[NDBuffer | None] = [ + None if chunk_is_empty(chunk_array, chunk_spec) else chunk_array + for chunk_array, (_, chunk_spec, *_) in zip(chunk_array_merged, batch, strict=False) + ] + + if use_sync: + sync_transform = cast(FusedCodecPipeline, pipeline).sync_transform + assert sync_transform is not None + await _encode_and_write_as_completed( + [ + (byte_setter, chunk_array, chunk_spec) + for chunk_array, (byte_setter, chunk_spec, *_) in zip( + chunk_array_batch, batch, strict=False + ) + ], + sync_transform, + ) + else: + chunk_bytes_batch = await pipeline.encode( + [ + (chunk_array, chunk_spec) + for chunk_array, (_, chunk_spec, *_) in zip(chunk_array_batch, batch, strict=False) + ], + ) + + async def _write_key(byte_setter: ByteSetter, chunk_bytes: Buffer | None) -> None: + if chunk_bytes is None: + await byte_setter.delete() + else: + await byte_setter.set(chunk_bytes) + + await concurrent_map( + [ + (byte_setter, chunk_bytes) + for chunk_bytes, (byte_setter, *_) in zip(chunk_bytes_batch, batch, strict=False) + ], + _write_key, + config.get("async.concurrency"), + ) + + +@dataclass(slots=True, kw_only=True) +class AsyncChunkTransform: + """A per-chunk asynchronous codec chain β€” the async mirror of ChunkTransform. + + Decodes/encodes a SINGLE chunk through the full codec chain, awaiting each + codec's per-chunk async method (`_decode_single`/`_encode_single`) with the + correctly-evolved per-stage spec (via the shared `resolve_aa_specs`). + + Unlike ChunkTransform it places no `SupportsSyncCodec` requirement on the + codecs, so it works for async-only codecs. Unlike the batched codec API it + operates on one chunk at a time β€” the mini-batch fan-out is a + BatchedCodecPipeline concern and deliberately not reintroduced here. + """ + + codecs: tuple[Codec, ...] + + _aa_codecs: tuple[ArrayArrayCodec, ...] = field(init=False, repr=False, compare=False) + _ab_codec: ArrayBytesCodec = field(init=False, repr=False, compare=False) + _bb_codecs: tuple[BytesBytesCodec, ...] = field(init=False, repr=False, compare=False) + + def __post_init__(self) -> None: + # `AsyncChunkTransform` is (re)constructed per decode/encode call from a + # codec chain that already went through `codecs_from_list` when the + # pipeline itself was built, so re-splitting it here must not re-emit + # that chain's advisory warnings on every call. + aa, ab, bb = codecs_from_list_unchecked(list(self.codecs)) + self._aa_codecs = aa + self._ab_codec = ab + self._bb_codecs = bb + + async def decode_chunk(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> NDBuffer: + """Decode one chunk through the chain (bb -> ab -> aa), async.""" + aa_specs, ab_spec = resolve_aa_specs(self._aa_codecs, chunk_spec) + + data: Buffer = chunk_bytes + for bb_codec in reversed(self._bb_codecs): + data = await bb_codec._decode_single(data, ab_spec) + + chunk_array: NDBuffer = await self._ab_codec._decode_single(data, ab_spec) + + for aa_codec, aa_spec in zip(reversed(self._aa_codecs), reversed(aa_specs), strict=True): + chunk_array = await aa_codec._decode_single(chunk_array, aa_spec) + + return chunk_array + + async def encode_chunk(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer | None: + """Encode one chunk through the chain (aa -> ab -> bb), async. + + Returns None if any stage drops the chunk (e.g. an all-fill chunk under + write_empty_chunks=False), matching ChunkTransform.encode_chunk. + """ + aa_specs, ab_spec = resolve_aa_specs(self._aa_codecs, chunk_spec) + + aa_data: NDBuffer = chunk_array + for aa_codec, aa_spec in zip(self._aa_codecs, aa_specs, strict=True): + aa_result = await aa_codec._encode_single(aa_data, aa_spec) + if aa_result is None: + return None + aa_data = aa_result + + ab_result = await self._ab_codec._encode_single(aa_data, ab_spec) + if ab_result is None: + return None + + bb_data: Buffer = ab_result + for bb_codec in self._bb_codecs: + bb_result = await bb_codec._encode_single(bb_data, ab_spec) + if bb_result is None: + return None + bb_data = bb_result + + return bb_data + + +@dataclass(frozen=True) +class BatchedCodecPipeline(CodecPipeline): + """Default codec pipeline. + + This batched codec pipeline divides the chunk batches into batches of a configurable + batch size ("mini-batch"). Fetching, decoding, encoding and storing are performed in + lock step for each mini-batch. Multiple mini-batches are processing concurrently. + """ + + array_array_codecs: tuple[ArrayArrayCodec, ...] + array_bytes_codec: ArrayBytesCodec + bytes_bytes_codecs: tuple[BytesBytesCodec, ...] + batch_size: int + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: + # Re-splits an already-`codecs_from_list`-validated (and warned-about) + # chain against the evolved spec, so this uses the quiet variant rather + # than routing through `from_codecs` (which would re-warn). + evolved_codecs = evolve_codecs(self, array_spec) + array_array_codecs, array_bytes_codec, bytes_bytes_codecs = codecs_from_list_unchecked( + evolved_codecs + ) + return type(self)( + array_array_codecs=array_array_codecs, + array_bytes_codec=array_bytes_codec, + bytes_bytes_codecs=bytes_bytes_codecs, + batch_size=self.batch_size, + ) + + @classmethod + def from_codecs(cls, codecs: Iterable[Codec], *, batch_size: int | None = None) -> Self: + array_array_codecs, array_bytes_codec, bytes_bytes_codecs = codecs_from_list(codecs) + + return cls( + array_array_codecs=array_array_codecs, + array_bytes_codec=array_bytes_codec, + bytes_bytes_codecs=bytes_bytes_codecs, + batch_size=batch_size or config.get("codec_pipeline.batch_size"), + ) + + @property + def supports_partial_decode(self) -> bool: + # Only a single ArrayBytesCodec that supports partial decoding, and no + # AA/BB codecs (they break the slice<->byte-range correspondence). + return pipeline_supports_partial_decode( + self.array_bytes_codec, + array_array_codecs=self.array_array_codecs, + bytes_bytes_codecs=self.bytes_bytes_codecs, + require_no_aa_bb=True, + ) + + @property + def supports_partial_encode(self) -> bool: + return pipeline_supports_partial_encode( + self.array_bytes_codec, + array_array_codecs=self.array_array_codecs, + bytes_bytes_codecs=self.bytes_bytes_codecs, + require_no_aa_bb=True, + ) + + def __iter__(self) -> Iterator[Codec]: + yield from self.array_array_codecs + yield self.array_bytes_codec + yield from self.bytes_bytes_codecs + + def validate( + self, + *, + shape: tuple[int, ...], + dtype: ZDType[TBaseDType, TBaseScalar], + chunk_grid: ChunkGridMetadata, + ) -> None: + for codec in self: + codec.validate(shape=shape, dtype=dtype, chunk_grid=chunk_grid) + + def compute_encoded_size(self, byte_length: int, array_spec: ArraySpec) -> int: + for codec in self: + byte_length = codec.compute_encoded_size(byte_length, array_spec) + array_spec = codec.resolve_metadata(array_spec) + return byte_length + + def _codecs_with_resolved_metadata_batched( + self, chunk_specs: Iterable[ArraySpec] + ) -> tuple[ + list[tuple[ArrayArrayCodec, list[ArraySpec]]], + tuple[ArrayBytesCodec, list[ArraySpec]], + list[tuple[BytesBytesCodec, list[ArraySpec]]], + ]: + aa_codecs_with_spec: list[tuple[ArrayArrayCodec, list[ArraySpec]]] = [] + chunk_specs = list(chunk_specs) + for aa_codec in self.array_array_codecs: + aa_codecs_with_spec.append((aa_codec, chunk_specs)) + chunk_specs = [aa_codec.resolve_metadata(chunk_spec) for chunk_spec in chunk_specs] + + ab_codec_with_spec = (self.array_bytes_codec, chunk_specs) + chunk_specs = [ + self.array_bytes_codec.resolve_metadata(chunk_spec) for chunk_spec in chunk_specs + ] + + bb_codecs_with_spec: list[tuple[BytesBytesCodec, list[ArraySpec]]] = [] + for bb_codec in self.bytes_bytes_codecs: + bb_codecs_with_spec.append((bb_codec, chunk_specs)) + chunk_specs = [bb_codec.resolve_metadata(chunk_spec) for chunk_spec in chunk_specs] + + return (aa_codecs_with_spec, ab_codec_with_spec, bb_codecs_with_spec) + + async def decode_batch( + self, + chunk_bytes_and_specs: Iterable[tuple[Buffer | None, ArraySpec]], + ) -> Iterable[NDBuffer | None]: + chunk_bytes_batch: Iterable[Buffer | None] + chunk_bytes_batch, chunk_specs = _unzip2(chunk_bytes_and_specs) + ( + aa_codecs_with_spec, + ab_codec_with_spec, + bb_codecs_with_spec, + ) = self._codecs_with_resolved_metadata_batched(chunk_specs) + + for bb_codec, chunk_spec_batch in bb_codecs_with_spec[::-1]: + chunk_bytes_batch = await bb_codec.decode( + zip(chunk_bytes_batch, chunk_spec_batch, strict=False) + ) + + ab_codec, chunk_spec_batch = ab_codec_with_spec + chunk_array_batch = await ab_codec.decode( + zip(chunk_bytes_batch, chunk_spec_batch, strict=False) + ) + + for aa_codec, chunk_spec_batch in aa_codecs_with_spec[::-1]: + chunk_array_batch = await aa_codec.decode( + zip(chunk_array_batch, chunk_spec_batch, strict=False) + ) + + return chunk_array_batch + + async def decode_partial_batch( + self, + batch_info: Iterable[tuple[ByteGetter, SelectorTuple, ArraySpec]], + ) -> Iterable[NDBuffer | None]: + assert self.supports_partial_decode + assert isinstance(self.array_bytes_codec, ArrayBytesCodecPartialDecodeMixin) + return await self.array_bytes_codec.decode_partial(batch_info) + + async def encode_batch( + self, + chunk_arrays_and_specs: Iterable[tuple[NDBuffer | None, ArraySpec]], + ) -> Iterable[Buffer | None]: + chunk_array_batch: Iterable[NDBuffer | None] + chunk_specs: Iterable[ArraySpec] + chunk_array_batch, chunk_specs = _unzip2(chunk_arrays_and_specs) + + for aa_codec in self.array_array_codecs: + chunk_array_batch = await aa_codec.encode( + zip(chunk_array_batch, chunk_specs, strict=False) + ) + chunk_specs = resolve_batched(aa_codec, chunk_specs) + + chunk_bytes_batch = await self.array_bytes_codec.encode( + zip(chunk_array_batch, chunk_specs, strict=False) + ) + chunk_specs = resolve_batched(self.array_bytes_codec, chunk_specs) + + for bb_codec in self.bytes_bytes_codecs: + chunk_bytes_batch = await bb_codec.encode( + zip(chunk_bytes_batch, chunk_specs, strict=False) + ) + chunk_specs = resolve_batched(bb_codec, chunk_specs) + + return chunk_bytes_batch + + async def encode_partial_batch( + self, + batch_info: Iterable[tuple[ByteSetter, NDBuffer, SelectorTuple, ArraySpec]], + ) -> None: + assert self.supports_partial_encode + assert isinstance(self.array_bytes_codec, ArrayBytesCodecPartialEncodeMixin) + await self.array_bytes_codec.encode_partial(batch_info) + + async def read_batch( + self, + batch_info: Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + out: NDBuffer, + drop_axes: tuple[int, ...] = (), + ) -> tuple[GetResult, ...]: + if self.supports_partial_decode: + results: list[GetResult] = [] + batch_info_list = list(batch_info) + chunk_array_batch = await self.decode_partial_batch( + [ + (byte_getter, chunk_selection, chunk_spec) + for byte_getter, chunk_spec, chunk_selection, *_ in batch_info_list + ] + ) + for chunk_array, (_, chunk_spec, _, out_selection, _) in zip( + chunk_array_batch, batch_info_list, strict=False + ): + if chunk_array is not None: + if drop_axes: + chunk_array = chunk_array.squeeze(axis=drop_axes) + out[out_selection] = chunk_array + results.append(GetResult(status="present")) + else: + out[out_selection] = fill_value_or_default(chunk_spec) + results.append(GetResult(status="missing")) + return tuple(results) + return await _async_read_fallback(self, list(batch_info), out, drop_axes) + + async def write_batch( + self, + batch_info: Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + value: NDBuffer, + drop_axes: tuple[int, ...] = (), + ) -> None: + if self.supports_partial_encode: + # Pass scalar values as is + if len(value.shape) == 0: + await self.encode_partial_batch( + [ + (byte_setter, value, chunk_selection, chunk_spec) + for byte_setter, chunk_spec, chunk_selection, out_selection, _ in batch_info + ], + ) + else: + await self.encode_partial_batch( + [ + (byte_setter, value[out_selection], chunk_selection, chunk_spec) + for byte_setter, chunk_spec, chunk_selection, out_selection, _ in batch_info + ], + ) + + return + await _async_write_fallback(self, list(batch_info), value, drop_axes) + + async def decode( + self, + chunk_bytes_and_specs: Iterable[tuple[Buffer | None, ArraySpec]], + ) -> Iterable[NDBuffer | None]: + output: list[NDBuffer | None] = [] + for batch_info in batched(chunk_bytes_and_specs, self.batch_size): + output.extend(await self.decode_batch(batch_info)) + return output + + async def encode( + self, + chunk_arrays_and_specs: Iterable[tuple[NDBuffer | None, ArraySpec]], + ) -> Iterable[Buffer | None]: + output: list[Buffer | None] = [] + for single_batch_info in batched(chunk_arrays_and_specs, self.batch_size): + output.extend(await self.encode_batch(single_batch_info)) + return output + + async def read( + self, + batch_info: Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + out: NDBuffer, + drop_axes: tuple[int, ...] = (), + ) -> tuple[GetResult, ...]: + batch_results = await concurrent_map( + [ + (single_batch_info, out, drop_axes) + for single_batch_info in batched(batch_info, self.batch_size) + ], + self.read_batch, + config.get("async.concurrency"), + ) + results: list[GetResult] = [] + for batch in batch_results: + results.extend(batch) + return tuple(results) + + async def write( + self, + batch_info: Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + value: NDBuffer, + drop_axes: tuple[int, ...] = (), + ) -> None: + await concurrent_map( + [ + (single_batch_info, value, drop_axes) + for single_batch_info in batched(batch_info, self.batch_size) + ], + self.write_batch, + config.get("async.concurrency"), + ) + + +def codecs_from_list( + codecs: Iterable[Codec], +) -> tuple[tuple[ArrayArrayCodec, ...], ArrayBytesCodec, tuple[BytesBytesCodec, ...]]: + """Split `codecs` into `(array_array, array_bytes, bytes_bytes)`, validating order. + + Emits user-facing advisory warnings about the codec chain (e.g. sharding's + "disables partial reads" warning). Use this for the FIRST construction of a + codec chain from user-supplied codecs. Use `codecs_from_list_unchecked` when + re-splitting a chain that was already validated and warned about by a prior + `codecs_from_list` call (e.g. `evolve_from_array_spec` re-splitting the same + codecs against an evolved spec) β€” re-warning there would fire the same + advisory once per reconstruction instead of once per user-facing chain. + """ + from zarr.codecs.sharding import ShardingCodec + + codecs = tuple(codecs) # materialize to avoid generator consumption issues + + if any(isinstance(codec, ShardingCodec) for codec in codecs) and len(codecs) > 1: + warn( + "Combining a `sharding_indexed` codec disables partial reads and " + "writes, which may lead to inefficient performance.", + category=ZarrUserWarning, + stacklevel=3, + ) + return codecs_from_list_unchecked(codecs) + + +def codecs_from_list_unchecked( + codecs: Iterable[Codec], +) -> tuple[tuple[ArrayArrayCodec, ...], ArrayBytesCodec, tuple[BytesBytesCodec, ...]]: + """Split `codecs` into `(array_array, array_bytes, bytes_bytes)`, validating order. + + Same structural validation as `codecs_from_list` (raises on bad codec + ordering or a missing/duplicate array-bytes codec) but does NOT emit + user-facing advisory warnings. See `codecs_from_list` for when to use each. + """ + codecs = tuple(codecs) # materialize to avoid generator consumption issues + + array_array: tuple[ArrayArrayCodec, ...] = () + array_bytes_maybe: ArrayBytesCodec | None = None + bytes_bytes: tuple[BytesBytesCodec, ...] = () + + for prev_codec, cur_codec in pairwise((None, *codecs)): + if isinstance(cur_codec, ArrayArrayCodec): + if isinstance(prev_codec, ArrayBytesCodec | BytesBytesCodec): + msg = ( + f"Invalid codec order. ArrayArrayCodec {cur_codec}" + "must be preceded by another ArrayArrayCodec. " + f"Got {type(prev_codec)} instead." + ) + raise TypeError(msg) + array_array += (cur_codec,) + + elif isinstance(cur_codec, ArrayBytesCodec): + if isinstance(prev_codec, BytesBytesCodec): + msg = ( + f"Invalid codec order. ArrayBytes codec {cur_codec}" + f" must be preceded by an ArrayArrayCodec. Got {type(prev_codec)} instead." + ) + raise TypeError(msg) + + if array_bytes_maybe is not None: + msg = ( + f"Got two instances of ArrayBytesCodec: {array_bytes_maybe} and {cur_codec}. " + "Only one array-to-bytes codec is allowed." + ) + raise ValueError(msg) + + array_bytes_maybe = cur_codec + + elif isinstance(cur_codec, BytesBytesCodec): + if isinstance(prev_codec, ArrayArrayCodec): + msg = ( + f"Invalid codec order. BytesBytesCodec {cur_codec}" + "must be preceded by either another BytesBytesCodec, or an ArrayBytesCodec. " + f"Got {type(prev_codec)} instead." + ) + raise TypeError(msg) + bytes_bytes += (cur_codec,) + else: + raise TypeError + + if array_bytes_maybe is None: + raise ValueError("Required ArrayBytesCodec was not found.") + else: + return array_array, array_bytes_maybe, bytes_bytes + + +register_pipeline(BatchedCodecPipeline) + + +@dataclass(frozen=True) +class FusedCodecPipeline(CodecPipeline): + """Codec pipeline that runs codec compute synchronously, in bulk. + + This is an opt-in alternative to `BatchedCodecPipeline`. The win is NOT + "separating IO from compute" β€” the codecs (notably `ShardingCodec`) still + perform their own storage IO. The win is replacing the batched pipeline's + per-chunk *async scheduling* (β‰ˆone coroutine per chunk, which dominates real + codec work) with synchronous, batched/coalesced execution: + + 1. When every codec implements `SupportsSyncCodec`, a `ChunkTransform` + runs the codec chain synchronously (no event loop, no per-chunk coroutine) + β€” optionally across a thread pool for CPU-heavy decode/encode. + 2. Sharded reads use the codec's synchronous IO methods: byte-range reads + coalesced via `Store.get_ranges_sync`, and a vectorized whole-shard bulk + decode for dense, fixed-size, uncompressed shards. Sharded writes go + through the codec's synchronous full-shard-rewrite path. + 3. When the store lacks synchronous IO (e.g. ZipStore) the pipeline falls + back to the async path, equivalent to `BatchedCodecPipeline`. + + IO ownership: the sharding codec holds the byte getter/setter and reads/ + writes storage directly (the same model as zarrs; unlike tensorstore, which + keeps codecs storage-free). A storage-free codec is a possible future + direction (see the pure-codec design notes) but is explicitly NOT what this + pipeline does. + """ + + codecs: tuple[Codec, ...] + array_array_codecs: tuple[ArrayArrayCodec, ...] + array_bytes_codec: ArrayBytesCodec + bytes_bytes_codecs: tuple[BytesBytesCodec, ...] + sync_transform: ChunkTransform | None + batch_size: int + + @classmethod + def from_codecs(cls, codecs: Iterable[Codec], *, batch_size: int | None = None) -> Self: + codec_list = tuple(codecs) + aa, ab, bb = codecs_from_list(codec_list) + + if batch_size is None: + batch_size = config.get("codec_pipeline.batch_size") + + return cls( + codecs=codec_list, + array_array_codecs=aa, + array_bytes_codec=ab, + bytes_bytes_codecs=bb, + sync_transform=None, + batch_size=batch_size, + ) + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: + # Re-splits an already-`codecs_from_list`-validated (and warned-about) + # chain against the evolved spec, so this uses the quiet variant to + # avoid re-emitting the same advisory warning on every array open. + evolved_codecs = evolve_codecs(self.codecs, array_spec) + aa, ab, bb = codecs_from_list_unchecked(evolved_codecs) + + try: + sync_transform: ChunkTransform | None = ChunkTransform(codecs=evolved_codecs) + except TypeError: + sync_transform = None + + return type(self)( + codecs=evolved_codecs, + array_array_codecs=aa, + array_bytes_codec=ab, + bytes_bytes_codecs=bb, + sync_transform=sync_transform, + batch_size=self.batch_size, + ) + + def __iter__(self) -> Iterator[Codec]: + return iter(self.codecs) + + @property + def supports_partial_decode(self) -> bool: + return pipeline_supports_partial_decode( + self.array_bytes_codec, + array_array_codecs=self.array_array_codecs, + bytes_bytes_codecs=self.bytes_bytes_codecs, + require_no_aa_bb=True, + ) + + @property + def supports_partial_encode(self) -> bool: + return pipeline_supports_partial_encode( + self.array_bytes_codec, + array_array_codecs=self.array_array_codecs, + bytes_bytes_codecs=self.bytes_bytes_codecs, + require_no_aa_bb=True, + ) + + def validate( + self, + *, + shape: tuple[int, ...], + dtype: ZDType[TBaseDType, TBaseScalar], + chunk_grid: ChunkGridMetadata, + ) -> None: + for codec in self.codecs: + codec.validate(shape=shape, dtype=dtype, chunk_grid=chunk_grid) + + def compute_encoded_size(self, byte_length: int, array_spec: ArraySpec) -> int: + for codec in self: + byte_length = codec.compute_encoded_size(byte_length, array_spec) + array_spec = codec.resolve_metadata(array_spec) + return byte_length + + # -- async decode/encode (required by ABC) and sync versions -- + + async def decode( + self, + chunk_bytes_and_specs: Iterable[tuple[Buffer | None, ArraySpec]], + ) -> Iterable[NDBuffer | None]: + # Decode each chunk through AsyncChunkTransform, which threads the + # per-stage spec correctly (via resolve_aa_specs). This is the single + # source of truth for async per-chunk decode; earlier this method + # reused one flat `chunk_specs` across every codec stage, which silently + # corrupted/crashed spec-changing codecs (transpose/cast/scale_offset) + # on the async fallback path. + async_transform = AsyncChunkTransform(codecs=self.codecs) + out: list[NDBuffer | None] = [] + for chunk_bytes, chunk_spec in chunk_bytes_and_specs: + if chunk_bytes is None: + out.append(None) + else: + out.append(await async_transform.decode_chunk(chunk_bytes, chunk_spec)) + return out + + async def encode( + self, + chunk_arrays_and_specs: Iterable[tuple[NDBuffer | None, ArraySpec]], + ) -> Iterable[Buffer | None]: + async_transform = AsyncChunkTransform(codecs=self.codecs) + out: list[Buffer | None] = [] + for chunk_array, chunk_spec in chunk_arrays_and_specs: + if chunk_array is None: + out.append(None) + else: + out.append(await async_transform.encode_chunk(chunk_array, chunk_spec)) + return out + + # -- sync read/write -- + + def read_sync( + self, + batch_info: Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + out: NDBuffer, + drop_axes: tuple[int, ...] = (), + max_workers: int = 1, + ) -> tuple[GetResult, ...]: + """Synchronous read: fetch -> decode -> scatter, per chunk. + + When `max_workers > 1` and there are multiple chunks, each + chunk's full lifecycle (fetch + decode + scatter) runs as one + task on a thread pool sized to `max_workers` β€” overlapping IO + of one chunk with decode/scatter of another. Scatter is + thread-safe because the chunks have non-overlapping output + selections. + + `max_workers=1` runs everything sequentially in the calling + thread (no pool involvement). + + Mirrors `BatchedCodecPipeline.read_batch`: when the AB codec + supports partial decoding (e.g. sharding), the codec handles its + own IO and only fetches the inner-chunk byte ranges that overlap + the read selection. Otherwise the pipeline fetches the full + blob and decodes the whole chunk. + """ + assert self.sync_transform is not None + transform = self.sync_transform + + batch = list(batch_info) + if not batch: + return () + + # Partial-decode fast path: the AB codec owns IO (read only the + # byte ranges needed for the requested selection). Same condition + # and dispatch as BatchedCodecPipeline.read_batch, plus a gate on the + # sync partial method: the public partial-decode contract + # (`ArrayBytesCodecPartialDecodeMixin`) only requires the async + # `_decode_partial_single`, so a codec may support partial decode + # without `_decode_partial_sync` β€” such codecs take the full-chunk + # path below instead. + codec = self.array_bytes_codec + if self.supports_partial_decode and hasattr(codec, "_decode_partial_sync"): + + def _read_one( + item: tuple[Any, ArraySpec, SelectorTuple, SelectorTuple, bool], + ) -> GetResult: + byte_getter, chunk_spec, chunk_selection, out_selection, _ = item + # the partial decode returns the already-selected region + decoded = codec._decode_partial_sync(byte_getter, chunk_selection, chunk_spec) + return scatter_chunk( + decoded, + out, + chunk_spec=chunk_spec, + out_selection=out_selection, + drop_axes=drop_axes, + ) + + else: + # Per-chunk fused path: fetch + decode + scatter as one task. + def _read_one( + item: tuple[Any, ArraySpec, SelectorTuple, SelectorTuple, bool], + ) -> GetResult: + byte_getter, chunk_spec, chunk_selection, out_selection, _ = item + raw = byte_getter.get_sync(prototype=chunk_spec.prototype) + return decode_and_scatter_chunk( + raw, + out, + chunk_spec=chunk_spec, + chunk_selection=chunk_selection, + out_selection=out_selection, + drop_axes=drop_axes, + decode=transform.decode_chunk, + ) + + if max_workers > 1 and len(batch) > 1: + pool = _get_pool(max_workers) + return tuple(pool.map(_read_one, batch)) + return tuple(_read_one(item) for item in batch) + + def write_sync( + self, + batch_info: Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + value: NDBuffer, + drop_axes: tuple[int, ...] = (), + max_workers: int = 1, + ) -> None: + """Synchronous write: fetch existing -> merge+encode -> store. + + When `max_workers > 1` and there are multiple chunks, each + chunk's full lifecycle (get-existing + merge + encode + set/delete) + runs as one task on a thread pool sized to `max_workers` β€” + overlapping IO of one chunk with compute of another. + + `max_workers=1` runs everything sequentially in the calling + thread (no pool involvement). + + When the codec pipeline supports partial encoding (e.g. a + sharding codec with no outer AA/BB codecs), the AB codec handles + the full write cycle β€” reading existing data, merging, encoding, + and writing β€” matching the async `BatchedCodecPipeline` path. + """ + assert self.sync_transform is not None + transform = self.sync_transform + + batch = list(batch_info) + if not batch: + return + + # Partial-encode path: the AB codec owns IO (read, merge, encode, + # write). Same condition and calling convention as + # BatchedCodecPipeline.write_batch, plus a gate on the sync partial + # method: the public partial-encode contract + # (`ArrayBytesCodecPartialEncodeMixin`) only requires the async + # `_encode_partial_single`, so a codec may support partial encode + # without `_encode_partial_sync` β€” such codecs take the full-chunk + # path below instead. + codec = self.array_bytes_codec + if self.supports_partial_encode and hasattr(codec, "_encode_partial_sync"): + scalar = len(value.shape) == 0 + + def _write_one( + item: tuple[Any, ArraySpec, SelectorTuple, SelectorTuple, bool], + ) -> None: + bs, chunk_spec, chunk_selection, out_selection, _is_complete = item + chunk_value = value if scalar else value[out_selection] + codec._encode_partial_sync(bs, chunk_value, chunk_selection, chunk_spec) + + else: + # Per-chunk fused path: get-existing + merge + encode + set/delete as one task. + def _write_one( + item: tuple[Any, ArraySpec, SelectorTuple, SelectorTuple, bool], + ) -> None: + bs, chunk_spec, chunk_selection, out_selection, is_complete = item + existing_bytes: Buffer | None = None + if not is_complete: + existing_bytes = bs.get_sync(prototype=chunk_spec.prototype) + + encoded = merge_and_encode_chunk( + existing_bytes, + value, + chunk_spec=chunk_spec, + chunk_selection=chunk_selection, + out_selection=out_selection, + is_complete=is_complete, + drop_axes=drop_axes, + decode=transform.decode_chunk, + encode=transform.encode_chunk, + ) + if encoded is None: + bs.delete_sync() + else: + bs.set_sync(encoded) + + if max_workers > 1 and len(batch) > 1: + pool = _get_pool(max_workers) + list(pool.map(_write_one, batch)) + else: + for item in batch: + _write_one(item) + + # -- async read/write -- + + async def read( + self, + batch_info: Iterable[tuple[ByteGetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + out: NDBuffer, + drop_axes: tuple[int, ...] = (), + ) -> tuple[GetResult, ...]: + batch = list(batch_info) + if not batch: + return () + + # Fast path: sync transform plus synchronous IO. For StorePath the gate + # is the STORE's sync-IO capability (`_store_supports_sync_io`) (StorePath always has a + # get_sync method, but it only works when its store implements the full + # sync surface); for other byte getters (e.g. the sharding codec's + # in-memory _ShardingByteGetter) the SyncByteGetter protocol is the + # gate. + from zarr.abc.store import SyncByteGetter, _store_supports_sync_io + from zarr.storage._common import StorePath + + first_bg = batch[0][0] + if self.sync_transform is not None and ( + (isinstance(first_bg, StorePath) and _store_supports_sync_io(first_bg.store)) + or (not isinstance(first_bg, StorePath) and isinstance(first_bg, SyncByteGetter)) + ): + # One thread hop for the WHOLE batch β€” not per chunk, so the fused + # design's win over per-chunk async scheduling is preserved. Running + # read_sync inline here would block the event loop for the duration + # of the batch's IO+compute; every sync-API call from every user + # thread shares this one loop, so inline execution serializes + # concurrent callers behind each other's codec compute. + return await asyncio.to_thread( + self.read_sync, batch, out, drop_axes, max_workers=_resolve_max_workers() + ) + + # Non-sync store (e.g. ZipStore): can't use the sync fast path. But if the + # array-bytes codec supports partial decoding (sharding), still route + # through the async partial-decode path β€” it fetches only the needed + # inner-chunk byte ranges (coalesced via get_ranges), matching + # BatchedCodecPipeline. Without this, the whole-shard _async_read_fallback + # below would over-read and diverge from the batched pipeline's IO. + if self.supports_partial_decode: + assert isinstance(self.array_bytes_codec, ArrayBytesCodecPartialDecodeMixin) + chunk_array_batch = await self.array_bytes_codec.decode_partial( + [ + (byte_getter, chunk_selection, chunk_spec) + for byte_getter, chunk_spec, chunk_selection, *_ in batch + ] + ) + results: list[GetResult] = [] + for chunk_array, (_, chunk_spec, _, out_selection, _) in zip( + chunk_array_batch, batch, strict=False + ): + if chunk_array is not None: + if drop_axes: + chunk_array = chunk_array.squeeze(axis=drop_axes) + out[out_selection] = chunk_array + results.append(GetResult(status="present")) + else: + out[out_selection] = fill_value_or_default(chunk_spec) + results.append(GetResult(status="missing")) + return tuple(results) + + return await _async_read_fallback(self, batch, out, drop_axes) + + async def write( + self, + batch_info: Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + value: NDBuffer, + drop_axes: tuple[int, ...] = (), + ) -> None: + batch = list(batch_info) + if not batch: + return + + # Fast path: sync transform plus synchronous IO. Mirrors `read`: gate + # StorePath on the store's sync-IO capability (`_store_supports_sync_io`) β€” write_sync + # needs the FULL sync surface (get_sync for partial-chunk + # read-modify-write, delete_sync for all-fill chunks), not just + # set_sync β€” and other byte setters (e.g. the sharding codec's + # in-memory _ShardingByteSetter) on SyncByteSetter. + from zarr.abc.store import SyncByteSetter, _store_supports_sync_io + from zarr.storage._common import StorePath + + first_bs = batch[0][0] + if self.sync_transform is not None and ( + (isinstance(first_bs, StorePath) and _store_supports_sync_io(first_bs.store)) + or (not isinstance(first_bs, StorePath) and isinstance(first_bs, SyncByteSetter)) + ): + # One thread hop for the whole batch; see the matching comment in + # `read` for why write_sync must not run inline on the event loop. + await asyncio.to_thread( + self.write_sync, batch, value, drop_axes, max_workers=_resolve_max_workers() + ) + return + + await _async_write_fallback(self, batch, value, drop_axes) + + +register_pipeline(FusedCodecPipeline) diff --git a/src/zarr/core/common.py b/src/zarr/core/common.py new file mode 100644 index 0000000000..3da5c108b6 --- /dev/null +++ b/src/zarr/core/common.py @@ -0,0 +1,355 @@ +from __future__ import annotations + +import asyncio +import math +import warnings +from collections.abc import Iterable, Mapping, Sequence +from enum import Enum +from typing import ( + TYPE_CHECKING, + Any, + Final, + Literal, + NotRequired, + TypedDict, + cast, + overload, +) + +import numpy as np +from typing_extensions import ReadOnly + +from zarr.core.config import config as zarr_config +from zarr.core.json_parse import convert, parse_field +from zarr.errors import ZarrRuntimeWarning + +if TYPE_CHECKING: + from collections.abc import Awaitable, Callable, Iterator + + +ZARR_JSON = "zarr.json" +ZARRAY_JSON = ".zarray" +ZGROUP_JSON = ".zgroup" +ZATTRS_JSON = ".zattrs" +ZMETADATA_V2_JSON = ".zmetadata" + +BytesLike = bytes | bytearray | memoryview +ShapeLike = Iterable[int | np.integer[Any]] | int | np.integer[Any] +ChunksLike = ShapeLike | Iterable[Iterable[int]] +# For backwards compatibility +ChunkCoords = tuple[int, ...] +ZarrFormat = Literal[2, 3] +NodeType = Literal["array", "group"] +JSON = str | int | float | bool | Mapping[str, "JSON"] | Sequence["JSON"] | None +MemoryOrder = Literal["C", "F"] +AccessModeLiteral = Literal["r", "r+", "a", "w", "w-"] +ANY_ACCESS_MODE: Final = "r", "r+", "a", "w", "w-" +DimensionNamesLike = Iterable[str | None] | None +DimensionNames = DimensionNamesLike # for backwards compatibility + + +class NamedConfig[TName: str, TConfig: Mapping[str, object]](TypedDict): + """ + A typed dictionary representing an object with a name and configuration, where the configuration + is an optional mapping of string keys to values, e.g. another typed dictionary or a JSON object. + + This class is generic with two type parameters: the type of the name (``TName``) and the type of + the configuration (``TConfig``). + """ + + name: ReadOnly[TName] + """The name of the object.""" + + configuration: NotRequired[ReadOnly[TConfig]] + """The configuration of the object. Not required.""" + + +class NamedRequiredConfig[TName: str, TConfig: Mapping[str, object]](TypedDict): + """ + A typed dictionary representing an object with a name and configuration, where the configuration + is a mapping of string keys to values, e.g. another typed dictionary or a JSON object. + + This class is generic with two type parameters: the type of the name (``TName``) and the type of + the configuration (``TConfig``). + """ + + name: ReadOnly[TName] + """The name of the object.""" + + configuration: ReadOnly[TConfig] + """The configuration of the object.""" + + +def product(tup: tuple[int, ...]) -> int: + return math.prod(tup) + + +def ceildiv(a: float, b: float) -> int: + if a == 0: + return 0 + return math.ceil(a / b) + + +def concurrent_iter[T: tuple[Any, ...], V]( + items: Iterable[T], + func: Callable[..., Awaitable[V]], + limit: int | None = None, +) -> list[asyncio.Task[V]]: + """Launch `func(*item)` for each item concurrently, returning the tasks. + + When `limit` is set, no more than `limit` calls are in flight at once. + Tasks are returned in input order; callers that want completion order + should wrap the result in `asyncio.as_completed`. + + Every task is scheduled (via `ensure_future`) before this function + returns, not on first iteration of the result. That matters for callers + that await the returned tasks one at a time β€” without eager scheduling, + each coroutine would only start when individually awaited, serializing + the work and defeating the semaphore. It also makes the return type + honest (real `Task`s support `.cancel()`, `.done()`, callbacks) rather + than bare coroutines. + + See https://docs.python.org/3/library/asyncio-task.html#coroutines: + "Note that simply calling a coroutine will not schedule it to be executed:" + """ + if limit is None: + return [asyncio.ensure_future(func(*item)) for item in items] + + sem = asyncio.Semaphore(limit) + + async def run(item: T) -> V: + async with sem: + return await func(*item) + + return [asyncio.ensure_future(run(item)) for item in items] + + +async def concurrent_map[T: tuple[Any, ...], V]( + items: Iterable[T], + func: Callable[..., Awaitable[V]], + limit: int | None = None, +) -> list[V]: + return await asyncio.gather(*concurrent_iter(items, func, limit)) + + +def enum_names[E: Enum](enum: type[E]) -> Iterator[str]: + for item in enum: + yield item.name + + +def parse_enum[E: Enum](data: object, cls: type[E]) -> E: + if isinstance(data, cls): + return data + if not isinstance(data, str): + raise TypeError(f"Expected str, got {type(data)}") + if data in enum_names(cls): + return cls(data) + raise ValueError(f"Value must be one of {list(enum_names(cls))!r}. Got {data} instead.") + + +def parse_name(data: JSON, expected: str | None = None) -> str: + try: + data = cast("str", convert(data, str)) + except (ValueError, TypeError) as exc: + raise TypeError(f"Expected a string, got an instance of {type(data)}.") from exc + if expected is None or data == expected: + return data + raise ValueError(f"Expected '{expected}'. Got {data} instead.") + + +def parse_configuration(data: JSON) -> JSON: + if not isinstance(data, dict): + raise TypeError(f"Expected dict, got {type(data)}") + return data + + +@overload +def parse_named_configuration( + data: JSON | NamedConfig[str, Any], expected_name: str | None = None +) -> tuple[str, dict[str, JSON]]: ... + + +@overload +def parse_named_configuration( + data: JSON | NamedConfig[str, Any], + expected_name: str | None = None, + *, + require_configuration: bool = True, +) -> tuple[str, dict[str, JSON] | None]: ... + + +def parse_named_configuration( + data: JSON | NamedConfig[str, Any], + expected_name: str | None = None, + *, + require_configuration: bool = True, +) -> tuple[str, JSON | None]: + if not isinstance(data, dict): + raise TypeError(f"Expected dict, got {type(data)}") + if "name" not in data: + raise ValueError(f"Named configuration does not have a 'name' key. Got {data}.") + name_parsed = parse_name(data["name"], expected_name) + if "configuration" in data: + configuration_parsed = parse_configuration(data["configuration"]) + elif require_configuration: + raise ValueError(f"Named configuration does not have a 'configuration' key. Got {data}.") + else: + configuration_parsed = None + return name_parsed, configuration_parsed + + +def parse_shapelike(data: ShapeLike) -> tuple[int, ...]: + """ + Parse a shape-like input into an explicit shape. + """ + if isinstance(data, int | np.integer): + if data < 0: + raise ValueError(f"Expected a non-negative integer. Got {data} instead") + return (int(data),) + try: + data_tuple = tuple(data) + except TypeError as e: + msg = f"Expected an integer or an iterable of integers. Got {data} instead." + raise TypeError(msg) from e + + if not all(isinstance(v, int | np.integer) for v in data_tuple): + msg = f"Expected an iterable of integers. Got {data} instead." + raise TypeError(msg) + if not all(v > -1 for v in data_tuple): + msg = f"Expected all values to be non-negative. Got {data} instead." + raise ValueError(msg) + + # cast NumPy scalars to plain python ints + return tuple(int(x) for x in data_tuple) + + +def parse_fill_value(data: Any) -> Any: + # todo: real validation + return data + + +def parse_order(data: Any) -> Literal["C", "F"]: + return cast("Literal['C', 'F']", parse_field(data, Literal["C", "F"], "order")) + + +def parse_bool(data: Any) -> bool: + return cast("bool", convert(data, bool)) + + +def parse_int(data: Any) -> int: + if isinstance(data, int) and not isinstance(data, bool): + return data + raise ValueError(f"Expected int, got {data} instead.") + + +def _warn_write_empty_chunks_kwarg() -> None: + # TODO: link to docs page on array configuration in this message + msg = ( + "The `write_empty_chunks` keyword argument is deprecated and will be removed in future versions. " + "To control whether empty chunks are written to storage, either use the `config` keyword " + "argument, as in `config={'write_empty_chunks': True}`," + "or change the global 'array.write_empty_chunks' configuration variable." + ) + warnings.warn(msg, ZarrRuntimeWarning, stacklevel=2) + + +def _warn_order_kwarg() -> None: + # TODO: link to docs page on array configuration in this message + msg = ( + "The `order` keyword argument has no effect for Zarr format 3 arrays. " + "To control the memory layout of the array, either use the `config` keyword " + "argument, as in `config={'order': 'C'}`," + "or change the global 'array.order' configuration variable." + ) + warnings.warn(msg, ZarrRuntimeWarning, stacklevel=2) + + +def _default_zarr_format() -> ZarrFormat: + """Return the default zarr_format.""" + return cast("ZarrFormat", int(zarr_config.get("default_zarr_format", 3))) + + +def expand_rle(data: Sequence[int | list[int]]) -> list[int]: + """Expand a mixed array of bare integers and RLE pairs. + + Per the rectilinear chunk grid spec, each element can be: + - a bare integer (an explicit edge length) + - a two-element array ``[value, count]`` (run-length encoded) + """ + result: list[int] = [] + for item in data: + if isinstance(item, (int, float)) and not isinstance(item, bool): + val = int(item) + if val < 1: + raise ValueError(f"Chunk edge length must be >= 1, got {val}") + result.append(val) + elif isinstance(item, list) and len(item) == 2: + size, count = int(item[0]), int(item[1]) + if size < 1: + raise ValueError(f"Chunk edge length must be >= 1, got {size}") + if count < 1: + raise ValueError(f"RLE repeat count must be >= 1, got {count}") + result.extend([size] * count) + else: + raise ValueError(f"RLE entries must be an integer or [size, count], got {item}") + return result + + +def compress_rle(sizes: Sequence[int]) -> list[int | list[int]]: + """Compress chunk sizes to mixed RLE format per the rectilinear spec. + + Runs of length > 1 are emitted as ``[value, count]`` pairs; runs of + length 1 are emitted as bare integers:: + + [10, 10, 10, 5] -> [[10, 3], 5] + """ + if not sizes: + return [] + result: list[int | list[int]] = [] + current = sizes[0] + count = 1 + for s in sizes[1:]: + if s == current: + count += 1 + else: + result.append([current, count] if count > 1 else current) + current = s + count = 1 + result.append([current, count] if count > 1 else current) + return result + + +def validate_rectilinear_kind(kind: str | None) -> None: + """Validate the ``kind`` field of a rectilinear chunk grid configuration. + + The rectilinear spec requires ``kind: "inline"``. + """ + if kind is None: + raise ValueError( + "Rectilinear chunk grid configuration requires a 'kind' field. " + "Only 'inline' is currently supported." + ) + if kind != "inline": + raise ValueError( + f"Unsupported rectilinear chunk grid kind: {kind!r}. " + "Only 'inline' is currently supported." + ) + + +def validate_rectilinear_edges( + chunk_shapes: Sequence[int | Sequence[int]], array_shape: Sequence[int] +) -> None: + """Validate that rectilinear chunk edges cover the array extent per dimension. + + Bare-int dimensions (regular step) always cover any extent, so they are + skipped. Explicit edge lists must sum to at least the array extent. + """ + for i, (dim_spec, extent) in enumerate(zip(chunk_shapes, array_shape, strict=True)): + if isinstance(dim_spec, int): + continue + edge_sum = sum(dim_spec) + if edge_sum < extent: + raise ValueError( + f"Rectilinear chunk edges for dimension {i} sum to {edge_sum} " + f"but array shape extent is {extent} (edge sum must be >= extent)" + ) diff --git a/src/zarr/core/config.py b/src/zarr/core/config.py new file mode 100644 index 0000000000..c0ebb31353 --- /dev/null +++ b/src/zarr/core/config.py @@ -0,0 +1,164 @@ +""" +The config module is responsible for managing the configuration of zarr and is based on the Donfig python library. +For selecting custom implementations of codecs, pipelines, buffers and ndbuffers, first register the implementations +in the registry and then select them in the config. + +Example: + An implementation of the bytes codec in a class ``your.module.NewBytesCodec`` requires the value of ``codecs.bytes`` + to be ``your.module.NewBytesCodec``. Donfig can be configured programmatically, by environment variables, or from + YAML files in standard locations. + + ```python + from your.module import NewBytesCodec + from zarr.core.config import register_codec, config + + register_codec("bytes", NewBytesCodec) + config.set({"codecs.bytes": "your.module.NewBytesCodec"}) + ``` + + Instead of setting the value programmatically with ``config.set``, you can also set the value with an environment + variable. The environment variable ``ZARR_CODECS__BYTES`` can be set to ``your.module.NewBytesCodec``. The double + underscore ``__`` is used to indicate nested access. + + ```bash + export ZARR_CODECS__BYTES="your.module.NewBytesCodec" + ``` + +For more information, see the Donfig documentation at https://github.com/pytroll/donfig. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, cast + +from donfig import Config as DConfig + +from zarr.core.json_parse import parse_field + +if TYPE_CHECKING: + from donfig.config_obj import ConfigSet + + +class BadConfigError(ValueError): + _msg = "bad Config: %r" + + +class Config(DConfig): # type: ignore[misc] + """The Config will collect configuration from config files and environment variables + + Example environment variables: + Grabs environment variables of the form "ZARR_FOO__BAR_BAZ=123" and + turns these into config variables of the form ``{"foo": {"bar-baz": 123}}`` + It transforms the key and value in the following way: + + - Lower-cases the key text + - Treats ``__`` (double-underscore) as nested access + - Calls ``ast.literal_eval`` on the value + + """ + + def reset(self) -> None: + self.clear() + self.refresh() + + def enable_gpu(self) -> ConfigSet: + """ + Configure Zarr to use GPUs where possible. + """ + return self.set( + {"buffer": "zarr.buffer.gpu.Buffer", "ndbuffer": "zarr.buffer.gpu.NDBuffer"} + ) + + +# these keys were removed from the config as part of the 3.1.0 release. +# these deprecations should be removed in 3.1.1 or thereabouts. +deprecations = { + "array.v2_default_compressor.numeric": None, + "array.v2_default_compressor.string": None, + "array.v2_default_compressor.bytes": None, + "array.v2_default_filters.string": None, + "array.v2_default_filters.bytes": None, + "array.v3_default_filters.numeric": None, + "array.v3_default_filters.raw": None, + "array.v3_default_filters.bytes": None, + "array.v3_default_serializer.numeric": None, + "array.v3_default_serializer.string": None, + "array.v3_default_serializer.bytes": None, + "array.v3_default_compressors.string": None, + "array.v3_default_compressors.bytes": None, + "array.v3_default_compressors": None, +} + +# The default configuration for zarr +config = Config( + "zarr", + defaults=[ + { + "default_zarr_format": 3, + "array": { + "order": "C", + "write_empty_chunks": False, + "read_missing_chunks": True, + "target_shard_size_bytes": None, + "rectilinear_chunks": False, + "sharding_coalesce_max_gap_bytes": 1 << 20, # 1 MiB + "sharding_coalesce_max_bytes": 16 << 20, # 16 MiB + }, + "async": {"concurrency": 10, "timeout": None}, + "threading": {"max_workers": None}, + "json_indent": 2, + "codec_pipeline": { + # FusedCodecPipeline is the faster synchronous pipeline, but it stays + # opt-in for now so behavior is unchanged for existing users. Early + # adopters can switch with + # zarr.config.set( + # {"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"} + # ) + "path": "zarr.core.codec_pipeline.BatchedCodecPipeline", + "batch_size": 1, + # Only read by FusedCodecPipeline (BatchedCodecPipeline ignores it). + "max_workers": None, + }, + "codecs": { + "blosc": "zarr.codecs.blosc.BloscCodec", + "gzip": "zarr.codecs.gzip.GzipCodec", + "zstd": "zarr.codecs.zstd.ZstdCodec", + "bytes": "zarr.codecs.bytes.BytesCodec", + "endian": "zarr.codecs.bytes.BytesCodec", # compatibility with earlier versions of ZEP1 + "crc32c": "zarr.codecs.crc32c_.Crc32cCodec", + "sharding_indexed": "zarr.codecs.sharding.ShardingCodec", + "transpose": "zarr.codecs.transpose.TransposeCodec", + "vlen-utf8": "zarr.codecs.vlen_utf8.VLenUTF8Codec", + "vlen-bytes": "zarr.codecs.vlen_utf8.VLenBytesCodec", + "numcodecs.bz2": "zarr.codecs.numcodecs.BZ2", + "numcodecs.crc32": "zarr.codecs.numcodecs.CRC32", + "numcodecs.crc32c": "zarr.codecs.numcodecs.CRC32C", + "numcodecs.lz4": "zarr.codecs.numcodecs.LZ4", + "numcodecs.lzma": "zarr.codecs.numcodecs.LZMA", + "numcodecs.zfpy": "zarr.codecs.numcodecs.ZFPY", + "numcodecs.adler32": "zarr.codecs.numcodecs.Adler32", + "numcodecs.astype": "zarr.codecs.numcodecs.AsType", + "numcodecs.bitround": "zarr.codecs.numcodecs.BitRound", + "numcodecs.blosc": "zarr.codecs.numcodecs.Blosc", + "numcodecs.delta": "zarr.codecs.numcodecs.Delta", + "numcodecs.fixedscaleoffset": "zarr.codecs.numcodecs.FixedScaleOffset", + "numcodecs.fletcher32": "zarr.codecs.numcodecs.Fletcher32", + "numcodecs.gzip": "zarr.codecs.numcodecs.GZip", + "numcodecs.jenkins_lookup3": "zarr.codecs.numcodecs.JenkinsLookup3", + "numcodecs.pcodec": "zarr.codecs.numcodecs.PCodec", + "numcodecs.packbits": "zarr.codecs.numcodecs.PackBits", + "numcodecs.shuffle": "zarr.codecs.numcodecs.Shuffle", + "numcodecs.quantize": "zarr.codecs.numcodecs.Quantize", + "numcodecs.zlib": "zarr.codecs.numcodecs.Zlib", + "numcodecs.zstd": "zarr.codecs.numcodecs.Zstd", + }, + "buffer": "zarr.buffer.cpu.Buffer", + "ndbuffer": "zarr.buffer.cpu.NDBuffer", + } + ], + deprecations=deprecations, +) + + +def parse_indexing_order(data: Any) -> Literal["C", "F"]: + return cast("Literal['C', 'F']", parse_field(data, Literal["C", "F"], "order")) diff --git a/src/zarr/core/dtype/__init__.py b/src/zarr/core/dtype/__init__.py new file mode 100644 index 0000000000..d1dbd6e2c8 --- /dev/null +++ b/src/zarr/core/dtype/__init__.py @@ -0,0 +1,301 @@ +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING, Final + +from zarr.core.dtype.npy.bool import Bool +from zarr.core.dtype.npy.bytes import ( + NullTerminatedBytes, + NullterminatedBytesJSON_V2, + NullTerminatedBytesJSON_V3, + RawBytes, + RawBytesJSON_V2, + RawBytesJSON_V3, + VariableLengthBytes, + VariableLengthBytesJSON_V2, +) +from zarr.core.dtype.npy.complex import Complex64, Complex128 +from zarr.core.dtype.npy.float import Float16, Float32, Float64 +from zarr.core.dtype.npy.int import Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64 +from zarr.core.dtype.npy.structured import ( + Struct, + StructJSON_V3, + Structured, + StructuredJSON_V2, + StructuredJSON_V3, +) +from zarr.core.dtype.npy.time import ( + DateTime64, + DateTime64JSON_V2, + DateTime64JSON_V3, + TimeDelta64, + TimeDelta64JSON_V2, + TimeDelta64JSON_V3, +) + +if TYPE_CHECKING: + from zarr.core.common import ZarrFormat + from zarr.core.dtype.common import DTypeJSON + +from collections.abc import Mapping + +import numpy as np +import numpy.typing as npt + +from zarr.core.common import JSON +from zarr.core.dtype.npy.string import ( + FixedLengthUTF32, + FixedLengthUTF32JSON_V2, + FixedLengthUTF32JSON_V3, + VariableLengthUTF8, + VariableLengthUTF8JSON_V2, +) +from zarr.core.dtype.registry import DataTypeRegistry +from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType + +__all__ = [ + "Bool", + "Complex64", + "Complex128", + "DataTypeRegistry", + "DateTime64", + "DateTime64JSON_V2", + "DateTime64JSON_V3", + "FixedLengthUTF32", + "FixedLengthUTF32JSON_V2", + "FixedLengthUTF32JSON_V3", + "Float16", + "Float32", + "Float64", + "Int8", + "Int16", + "Int32", + "Int64", + "NullTerminatedBytes", + "NullTerminatedBytesJSON_V3", + "NullterminatedBytesJSON_V2", + "RawBytes", + "RawBytesJSON_V2", + "RawBytesJSON_V3", + "Struct", + "StructJSON_V3", + "Structured", + "StructuredJSON_V2", + "StructuredJSON_V3", + "TBaseDType", + "TBaseScalar", + "TimeDelta64", + "TimeDelta64JSON_V2", + "TimeDelta64JSON_V3", + "UInt8", + "UInt16", + "UInt32", + "UInt64", + "VariableLengthBytes", + "VariableLengthBytesJSON_V2", + "VariableLengthUTF8", + "VariableLengthUTF8JSON_V2", + "ZDType", + "data_type_registry", + "parse_data_type", + "parse_dtype", +] + +data_type_registry = DataTypeRegistry() + +IntegerDType = Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64 +INTEGER_DTYPE: Final = Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64 + +FloatDType = Float16 | Float32 | Float64 +FLOAT_DTYPE: Final = Float16, Float32, Float64 + +ComplexFloatDType = Complex64 | Complex128 +COMPLEX_FLOAT_DTYPE: Final = Complex64, Complex128 + +StringDType = FixedLengthUTF32 | VariableLengthUTF8 +STRING_DTYPE: Final = FixedLengthUTF32, VariableLengthUTF8 + +TimeDType = DateTime64 | TimeDelta64 +TIME_DTYPE: Final = DateTime64, TimeDelta64 + +BytesDType = RawBytes | NullTerminatedBytes | VariableLengthBytes +BYTES_DTYPE: Final = RawBytes, NullTerminatedBytes, VariableLengthBytes + +AnyDType = ( + Bool + | IntegerDType + | FloatDType + | ComplexFloatDType + | StringDType + | BytesDType + | Struct + | TimeDType + | VariableLengthBytes +) +# mypy has trouble inferring the type of variablelengthstring dtype, because its class definition +# depends on the installed numpy version. That's why the type: ignore statement is needed here. +ANY_DTYPE: Final = ( + Bool, + *INTEGER_DTYPE, + *FLOAT_DTYPE, + *COMPLEX_FLOAT_DTYPE, + *STRING_DTYPE, + *BYTES_DTYPE, + Struct, + *TIME_DTYPE, + VariableLengthBytes, +) + +# These are aliases for variable-length UTF-8 strings +# We handle them when a user requests a data type instead of using NumPy's dtype inferece because +# the default NumPy behavior -- to inspect the user-provided array data and choose +# an appropriately sized U dtype -- is unworkable for Zarr. +VLEN_UTF8_ALIAS: Final = ("str", str, "string") + +# This type models inputs that can be coerced to a ZDType +type ZDTypeLike = npt.DTypeLike | ZDType[TBaseDType, TBaseScalar] | Mapping[str, JSON] | str + +for dtype in ANY_DTYPE: + # mypy does not know that all the elements of ANY_DTYPE are subclasses of ZDType + data_type_registry.register(dtype._zarr_v3_name, dtype) # type: ignore[arg-type] + + +# TODO: find a better name for this function +def get_data_type_from_native_dtype(dtype: npt.DTypeLike) -> ZDType[TBaseDType, TBaseScalar]: + """ + Get a data type wrapper (an instance of ``ZDType``) from a native data type, e.g. a numpy dtype. + """ + if not isinstance(dtype, np.dtype): + na_dtype: np.dtype[np.generic] + if isinstance(dtype, list): + # this is a valid _VoidDTypeLike check + na_dtype = np.dtype([tuple(d) for d in dtype]) + else: + na_dtype = np.dtype(dtype) + else: + na_dtype = dtype + return data_type_registry.match_dtype(dtype=na_dtype) + + +def get_data_type_from_json( + dtype_spec: DTypeJSON, *, zarr_format: ZarrFormat +) -> ZDType[TBaseDType, TBaseScalar]: + """ + Given a JSON representation of a data type and a Zarr format version, + attempt to create a ZDType instance from the registered ZDType classes. + """ + return data_type_registry.match_json(dtype_spec, zarr_format=zarr_format) + + +def parse_data_type( + dtype_spec: ZDTypeLike, + *, + zarr_format: ZarrFormat, +) -> ZDType[TBaseDType, TBaseScalar]: + """ + Interpret the input as a ZDType. + + This function wraps ``parse_dtype``. The only difference is the function name. This function may + be deprecated in a future version of Zarr Python in favor of ``parse_dtype``. + + Parameters + ---------- + dtype_spec : ZDTypeLike + The input to be interpreted as a ZDType. This could be a ZDType, which will be returned + directly, or a JSON representation of a ZDType, or a native dtype, or a python object that + can be converted into a native dtype. + zarr_format : ZarrFormat + The Zarr format version. This parameter is required because this function will attempt to + parse the JSON representation of a data type, and the JSON representation of data types + varies between Zarr 2 and Zarr 3. + + Returns + ------- + ZDType[TBaseDType, TBaseScalar] + The ZDType corresponding to the input. + + Examples + -------- + ```python + from zarr.dtype import parse_data_type + import numpy as np + parse_data_type("int32", zarr_format=2) + # Int32(endianness='little') + parse_data_type(np.dtype('S10'), zarr_format=2) + # NullTerminatedBytes(length=10) + parse_data_type({"name": "numpy.datetime64", "configuration": {"unit": "s", "scale_factor": 10}}, zarr_format=3) + # DateTime64(endianness='little', scale_factor=10, unit='s') + ``` + """ + return parse_dtype(dtype_spec, zarr_format=zarr_format) + + +def parse_dtype( + dtype_spec: ZDTypeLike, + *, + zarr_format: ZarrFormat, +) -> ZDType[TBaseDType, TBaseScalar]: + """ + Convert the input as a ZDType. + + Parameters + ---------- + dtype_spec : ZDTypeLike + The input to be converted to a ZDType. This could be a ZDType, which will be returned + directly, or a JSON representation of a ZDType, or a numpy dtype, or a python object that + can be converted into a native dtype. + zarr_format : ZarrFormat + The Zarr format version. This parameter is required because this function will attempt to + parse the JSON representation of a data type, and the JSON representation of data types + varies between Zarr 2 and Zarr 3. + + Returns + ------- + ZDType[TBaseDType, TBaseScalar] + The ZDType corresponding to the input. + + Examples + -------- + ```python + from zarr.dtype import parse_dtype + import numpy as np + parse_dtype("int32", zarr_format=2) + # Int32(endianness='little') + parse_dtype(np.dtype('S10'), zarr_format=2) + # NullTerminatedBytes(length=10) + parse_dtype({"name": "numpy.datetime64", "configuration": {"unit": "s", "scale_factor": 10}}, zarr_format=3) + # DateTime64(endianness='little', scale_factor=10, unit='s') + ``` + """ + if isinstance(dtype_spec, ZDType): + return dtype_spec + # First attempt to interpret the input as JSON + if isinstance(dtype_spec, Mapping | str | Sequence): + try: + return get_data_type_from_json(dtype_spec, zarr_format=zarr_format) + except ValueError: + # no data type matched this JSON-like input + pass + if dtype_spec in VLEN_UTF8_ALIAS: + # If the dtype request is one of the aliases for variable-length UTF-8 strings, + # return that dtype. + return VariableLengthUTF8() # type: ignore[return-value] + # otherwise, we have either a numpy dtype string, or a zarr v3 dtype string, and in either case + # we can create a native dtype from it, and do the dtype inference from that + return get_data_type_from_native_dtype(dtype_spec) # type: ignore[arg-type] + + +def __getattr__(name: str) -> object: + if name == "DataTypeValidationError": + import warnings + + from zarr.errors import DataTypeValidationError, ZarrDeprecationWarning + + warnings.warn( + "Importing DataTypeValidationError from zarr.core.dtype is deprecated. " + "Use zarr.errors.DataTypeValidationError instead.", + ZarrDeprecationWarning, + stacklevel=2, + ) + return DataTypeValidationError + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/src/zarr/core/dtype/common.py b/src/zarr/core/dtype/common.py new file mode 100644 index 0000000000..61cbfe0360 --- /dev/null +++ b/src/zarr/core/dtype/common.py @@ -0,0 +1,241 @@ +from __future__ import annotations + +import warnings +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import ( + ClassVar, + Final, + Literal, + TypedDict, + TypeGuard, +) + +from typing_extensions import ReadOnly + +from zarr.core.common import NamedConfig +from zarr.errors import UnstableSpecificationWarning + +EndiannessStr = Literal["little", "big"] +ENDIANNESS_STR: Final = "little", "big" + +SpecialFloatStrings = Literal["NaN", "Infinity", "-Infinity"] +SPECIAL_FLOAT_STRINGS: Final = ("NaN", "Infinity", "-Infinity") + +JSONFloatV2 = float | SpecialFloatStrings +JSONFloatV3 = float | SpecialFloatStrings | str + +ObjectCodecID = Literal["vlen-utf8", "vlen-bytes", "vlen-array", "pickle", "json2", "msgpack2"] +# These are the ids of the known object codecs for zarr v2. +OBJECT_CODEC_IDS: Final = ("vlen-utf8", "vlen-bytes", "vlen-array", "pickle", "json2", "msgpack2") + +# This is a wider type than our standard JSON type because we need +# to work with typeddict objects which are assignable to Mapping[str, object] +DTypeJSON = str | int | float | Sequence["DTypeJSON"] | None | Mapping[str, object] + +# The DTypeJSON_V2 type exists because ZDType.from_json takes a single argument, which must contain +# all the information necessary to decode the data type. Zarr v2 supports multiple distinct +# data types that all used the "|O" data type identifier. These data types can only be +# discriminated on the basis of their "object codec", i.e. a special data type specific +# compressor or filter. So to figure out what data type a zarr v2 array has, we need the +# data type identifier from metadata, as well as an object codec id if the data type identifier +# is "|O". +# So we will pack the name of the dtype alongside the name of the object codec id, if applicable, +# in a single dict, and pass that to the data type inference logic. +# These type variables have a very wide bound because the individual zdtype +# classes can perform a very specific type check. + +# This is the JSON representation of a structured dtype in zarr v2 +StructuredName_V2 = Sequence["str | StructuredName_V2"] + +# This models the type of the name a dtype might have in zarr v2 array metadata +DTypeName_V2 = StructuredName_V2 | str + + +class DTypeConfig_V2[TDTypeNameV2: DTypeName_V2, TObjectCodecID: str | None](TypedDict): + name: ReadOnly[TDTypeNameV2] + object_codec_id: ReadOnly[TObjectCodecID] + + +DTypeSpec_V2 = DTypeConfig_V2[DTypeName_V2, None | str] + + +def check_structured_dtype_v2_inner(data: object) -> TypeGuard[StructuredName_V2]: + """ + A type guard for the inner elements of a structured dtype. This is a recursive check because + the type is itself recursive. + + This check ensures that all the elements are 2-element sequences beginning with a string + and ending with either another string or another 2-element sequence beginning with a string and + ending with another instance of that type. + """ + if isinstance(data, (str, Mapping)): + return False + if not isinstance(data, Sequence): + return False + if len(data) != 2: + return False + if not (isinstance(data[0], str)): + return False + if isinstance(data[-1], str): + return True + elif isinstance(data[-1], Sequence): + return check_structured_dtype_v2_inner(data[-1]) + return False + + +def check_structured_dtype_name_v2(data: Sequence[object]) -> TypeGuard[StructuredName_V2]: + """ + Check that all the elements of a sequence are valid zarr v2 structured dtype identifiers + """ + return all(check_structured_dtype_v2_inner(d) for d in data) + + +def check_dtype_name_v2(data: object) -> TypeGuard[DTypeName_V2]: + """ + Type guard for narrowing the type of a python object to a valid zarr v2 dtype name. + """ + if isinstance(data, str): + return True + elif isinstance(data, Sequence): + return check_structured_dtype_name_v2(data) + return False + + +def check_dtype_spec_v2(data: object) -> TypeGuard[DTypeSpec_V2]: + """ + Type guard for narrowing a python object to an instance of DTypeSpec_V2 + """ + if not isinstance(data, Mapping): + return False + if set(data.keys()) != {"name", "object_codec_id"}: + return False + if not check_dtype_name_v2(data["name"]): + return False + return isinstance(data["object_codec_id"], str | None) + + +# By comparison, The JSON representation of a dtype in zarr v3 is much simpler. +# It's either a string, or a structured dict +DTypeSpec_V3 = str | NamedConfig[str, Mapping[str, object]] + + +def check_dtype_spec_v3(data: object) -> TypeGuard[DTypeSpec_V3]: + """ + Type guard for narrowing the type of a python object to an instance of + DTypeSpec_V3, i.e either a string or a dict with a "name" field that's a string and a + "configuration" field that's a mapping with string keys. + """ + if isinstance(data, str) or ( # noqa: SIM103 + isinstance(data, Mapping) + and set(data.keys()) == {"name", "configuration"} + and isinstance(data["configuration"], Mapping) + and all(isinstance(k, str) for k in data["configuration"]) + ): + return True + return False + + +def unpack_dtype_json(data: DTypeSpec_V2 | DTypeSpec_V3) -> DTypeJSON: + """ + Return the array metadata form of the dtype JSON representation. For the Zarr V3 form of dtype + metadata, this is a no-op. For the Zarr V2 form of dtype metadata, this unpacks the dtype name. + """ + if isinstance(data, Mapping) and set(data.keys()) == {"name", "object_codec_id"}: + return data["name"] + return data + + +def __getattr__(name: str) -> object: + if name == "DataTypeValidationError": + import warnings + + from zarr.errors import DataTypeValidationError, ZarrDeprecationWarning + + warnings.warn( + "Importing DataTypeValidationError from zarr.core.dtype.common is deprecated. " + "Use zarr.errors.DataTypeValidationError or zarr.dtype.DataTypeValidationError instead.", + ZarrDeprecationWarning, + stacklevel=2, + ) + return DataTypeValidationError + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +class ScalarTypeValidationError(ValueError): ... + + +@dataclass(frozen=True, kw_only=True) +class HasLength: + """ + A mix-in class for data types with a length attribute, such as fixed-size collections + of unicode strings, or bytes. + + Attributes + ---------- + length : int + The length of the scalars belonging to this data type. Note that this class does not assign + a unit to the length. Child classes may assign units. + """ + + length: int + + +@dataclass(frozen=True, kw_only=True) +class HasEndianness: + """ + A mix-in class for data types with an endianness attribute + """ + + endianness: EndiannessStr = "little" + + +@dataclass(frozen=True, kw_only=True) +class HasItemSize: + """ + A mix-in class for data types with an item size attribute. + This mix-in bears a property ``item_size``, which denotes the size of each element of the data + type, in bytes. + """ + + @property + def item_size(self) -> int: + raise NotImplementedError + + +@dataclass(frozen=True, kw_only=True) +class HasObjectCodec: + """ + A mix-in class for data types that require an object codec id. + This class bears the property ``object_codec_id``, which is the string name of an object + codec that is required to encode and decode the data type. + + In zarr-python 2.x certain data types like variable-length strings or variable-length arrays + used the catch-all numpy "object" data type for their in-memory representation. But these data + types cannot be stored as numpy object data types, because the object data type does not define + a fixed memory layout. So these data types required a special codec, called an "object codec", + that effectively defined a compact representation for the data type, which was used to encode + and decode the data type. + + Zarr-python 2.x would not allow the creation of arrays with the "object" data type if an object + codec was not specified, and thus the name of the object codec is effectively part of the data + type model. + """ + + object_codec_id: ClassVar[str] + + +def v3_unstable_dtype_warning(dtype: object) -> None: + """ + Emit this warning when a data type does not have a stable zarr v3 spec + """ + msg = ( + f"The data type ({dtype}) does not have a Zarr V3 specification. " + "That means that the representation of arrays saved with this data type may change without " + "warning in a future version of Zarr Python. " + "Arrays stored with this data type may be unreadable by other Zarr libraries. " + "Use this data type at your own risk! " + "Check https://github.com/zarr-developers/zarr-extensions/tree/main/data-types for the " + "status of data type specifications for Zarr V3." + ) + warnings.warn(msg, category=UnstableSpecificationWarning, stacklevel=2) diff --git a/src/zarr/core/dtype/npy/__init__.py b/src/zarr/core/dtype/npy/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/zarr/core/dtype/npy/bool.py b/src/zarr/core/dtype/npy/bool.py new file mode 100644 index 0000000000..f92476a455 --- /dev/null +++ b/src/zarr/core/dtype/npy/bool.py @@ -0,0 +1,319 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, ClassVar, Literal, Self, TypeGuard, overload + +import numpy as np + +from zarr.core.dtype.common import ( + DTypeConfig_V2, + DTypeJSON, + HasItemSize, + check_dtype_spec_v2, +) +from zarr.core.dtype.wrapper import TBaseDType, ZDType +from zarr.errors import DataTypeValidationError + +if TYPE_CHECKING: + from zarr.core.common import JSON, ZarrFormat + + +@dataclass(frozen=True, kw_only=True, slots=True) +class Bool(ZDType[np.dtypes.BoolDType, np.bool_], HasItemSize): + """ + A Zarr data type for arrays containing booleans. + + Wraps the [`np.dtypes.BoolDType`][numpy.dtypes.BoolDType] data type. Scalars for this data type are instances of + [`np.bool_`][numpy.bool_]. + + Attributes + ---------- + + _zarr_v3_name : Literal["bool"] = "bool" + The Zarr v3 name of the dtype. + _zarr_v2_name : ``Literal["|b1"]`` = ``"|b1"`` + The Zarr v2 name of the dtype, which is also a string representation + of the boolean dtype used by NumPy. + dtype_cls : ClassVar[type[np.dtypes.BoolDType]] = np.dtypes.BoolDType + The NumPy dtype class. + + References + ---------- + This class implements the boolean data type defined in Zarr V2 and V3. + + See the [Zarr V2](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding)and [Zarr V3](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v3/data-types/index.rst) specification documents for details. + """ + + _zarr_v3_name: ClassVar[Literal["bool"]] = "bool" + _zarr_v2_name: ClassVar[Literal["|b1"]] = "|b1" + dtype_cls = np.dtypes.BoolDType + + @classmethod + def from_native_dtype(cls, dtype: TBaseDType) -> Self: + """ + Create an instance of Bool from an instance of np.dtypes.BoolDType. + + Parameters + ---------- + dtype : TBaseDType + The NumPy boolean dtype instance to convert. + + Returns + ------- + Bool + An instance of Bool. + + Raises + ------ + DataTypeValidationError + If the provided dtype is not compatible with this ZDType. + """ + if cls._check_native_dtype(dtype): + return cls() + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self: Self) -> np.dtypes.BoolDType: + """ + Create a NumPy boolean dtype instance from this ZDType. + + Returns + ------- + np.dtypes.BoolDType + The NumPy boolean dtype. + """ + return self.dtype_cls() + + @classmethod + def _check_json_v2( + cls, + data: DTypeJSON, + ) -> TypeGuard[DTypeConfig_V2[Literal["|b1"], None]]: + """ + Check that the input is a valid JSON representation of a Bool. + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + ``TypeGuard[DTypeConfig_V2[Literal["|b1"], None]]`` + True if the input is a valid JSON representation, False otherwise. + """ + return ( + check_dtype_spec_v2(data) + and data["name"] == cls._zarr_v2_name + and data["object_codec_id"] is None + ) + + @classmethod + def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[Literal["bool"]]: + """ + Check that the input is a valid JSON representation of this class in Zarr V3. + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + bool + True if the input is a valid JSON representation, False otherwise. + """ + return data == cls._zarr_v3_name + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an instance of Bool from Zarr V2-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Bool + An instance of Bool. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class. + """ + if cls._check_json_v2(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v2_name!r}" + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls: type[Self], data: DTypeJSON) -> Self: + """ + Create an instance of Bool from Zarr V3-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Bool + An instance of Bool. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class. + """ + if cls._check_json_v3(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[Literal["|b1"], None]: ... + + @overload + def to_json(self, zarr_format: Literal[3]) -> Literal["bool"]: ... + + def to_json( + self, zarr_format: ZarrFormat + ) -> DTypeConfig_V2[Literal["|b1"], None] | Literal["bool"]: + """ + Serialize this Bool instance to JSON. + + Parameters + ---------- + zarr_format : ZarrFormat + The Zarr format version (2 or 3). + + Returns + ------- + ``DTypeConfig_V2[Literal["|b1"], None] | Literal["bool"]`` + The JSON representation of the Bool instance. + + Raises + ------ + ValueError + If the zarr_format is not 2 or 3. + """ + if zarr_format == 2: + return {"name": self._zarr_v2_name, "object_codec_id": None} + elif zarr_format == 3: + return self._zarr_v3_name + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + def _check_scalar(self, data: object) -> bool: + """ + Check if the input can be cast to a boolean scalar. + + Parameters + ---------- + data : object + The data to check. + + Returns + ------- + bool + True if the input can be cast to a boolean scalar, False otherwise. + """ + return True + + def cast_scalar(self, data: object) -> np.bool_: + """ + Cast the input to a numpy boolean scalar. + + Parameters + ---------- + data : object + The data to cast. + + Returns + ------- + bool : np.bool_ + The numpy boolean scalar. + + Raises + ------ + TypeError + If the input cannot be converted to a numpy boolean. + """ + if self._check_scalar(data): + return np.bool_(data) + msg = ( # pragma: no cover + f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the " + f"data type {self}." + ) + raise TypeError(msg) # pragma: no cover + + def default_scalar(self) -> np.bool_: + """ + Get the default value for the boolean dtype. + + Returns + ------- + bool : np.bool_ + The default value. + """ + return np.False_ + + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> bool: + """ + Convert a scalar to a python bool. + + Parameters + ---------- + data : object + The value to convert. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + bool + The JSON-serializable format. + """ + return bool(data) + + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.bool_: + """ + Read a JSON-serializable value as a numpy boolean scalar. + + Parameters + ---------- + data : JSON + The JSON-serializable value. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + bool : np.bool_ + The numpy boolean scalar. + + Raises + ------ + TypeError + If the input is not a valid boolean type. + """ + if self._check_scalar(data): + return np.bool_(data) + raise TypeError(f"Invalid type: {data}. Expected a boolean.") # pragma: no cover + + @property + def item_size(self) -> int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return 1 diff --git a/src/zarr/core/dtype/npy/bytes.py b/src/zarr/core/dtype/npy/bytes.py new file mode 100644 index 0000000000..e60f3c6c48 --- /dev/null +++ b/src/zarr/core/dtype/npy/bytes.py @@ -0,0 +1,1279 @@ +from __future__ import annotations + +import base64 +import re +from dataclasses import dataclass +from typing import ClassVar, Literal, Self, TypedDict, TypeGuard, cast, overload + +import numpy as np + +from zarr.core.common import JSON, NamedConfig, ZarrFormat +from zarr.core.dtype.common import ( + DTypeConfig_V2, + DTypeJSON, + HasItemSize, + HasLength, + HasObjectCodec, + check_dtype_spec_v2, + v3_unstable_dtype_warning, +) +from zarr.core.dtype.npy.common import check_json_str +from zarr.core.dtype.wrapper import TBaseDType, ZDType +from zarr.errors import DataTypeValidationError + +BytesLike = np.bytes_ | str | bytes | int + + +class FixedLengthBytesConfig(TypedDict): + """ + A configuration for a data type that takes a ``length_bytes`` parameter. + + Attributes + ---------- + + length_bytes : int + The length in bytes of the data associated with this configuration. + + Examples + -------- + ```python + { + "length_bytes": 12 + } + ``` + """ + + length_bytes: int + + +class NullterminatedBytesJSON_V2(DTypeConfig_V2[str, None]): + """ + A wrapper around the JSON representation of the ``NullTerminatedBytes`` data type in Zarr V2. + + The ``name`` field of this class contains the value that would appear under the + ``dtype`` field in Zarr V2 array metadata. + + References + ---------- + The structure of the ``name`` field is defined in the Zarr V2 + [specification document](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding). + + + Examples + -------- + ```python + { + "name": "|S10", + "object_codec_id": None + } + ``` + """ + + +class NullTerminatedBytesJSON_V3( + NamedConfig[Literal["null_terminated_bytes"], FixedLengthBytesConfig] +): + """ + The JSON representation of the ``NullTerminatedBytes`` data type in Zarr V3. + + References + ---------- + This representation is not currently defined in an external specification. + + + Examples + -------- + ```python + { + "name": "null_terminated_bytes", + "configuration": { + "length_bytes": 12 + } + } + ``` + + """ + + +class RawBytesJSON_V2(DTypeConfig_V2[str, None]): + """ + A wrapper around the JSON representation of the ``RawBytes`` data type in Zarr V2. + + The ``name`` field of this class contains the value that would appear under the + ``dtype`` field in Zarr V2 array metadata. + + References + ---------- + The structure of the ``name`` field is defined in the Zarr V2 + [specification document](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding). + + + Examples + -------- + ```python + + { + "name": "|V10", + "object_codec_id": None + } + ``` + """ + + +class RawBytesJSON_V3(NamedConfig[Literal["raw_bytes"], FixedLengthBytesConfig]): + """ + The JSON representation of the ``RawBytes`` data type in Zarr V3. + + References + ---------- + This representation is not currently defined in an external specification. + + + Examples + -------- + ```python + { + "name": "raw_bytes", + "configuration": { + "length_bytes": 12 + } + } + ``` + """ + + +class VariableLengthBytesJSON_V2(DTypeConfig_V2[Literal["|O"], Literal["vlen-bytes"]]): + """ + A wrapper around the JSON representation of the ``VariableLengthBytes`` data type in Zarr V2. + + The ``name`` field of this class contains the value that would appear under the + ``dtype`` field in Zarr V2 array metadata. The ``object_codec_id`` field is always ``"vlen-bytes"`` + + References + ---------- + The structure of the ``name`` field is defined in the Zarr V2 + [specification document](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding). + + Examples + -------- + ```python + { + "name": "|O", + "object_codec_id": "vlen-bytes" + } + ``` + """ + + +@dataclass(frozen=True, kw_only=True) +class NullTerminatedBytes(ZDType[np.dtypes.BytesDType[int], np.bytes_], HasLength, HasItemSize): + """ + A Zarr data type for arrays containing fixed-length null-terminated byte sequences. + + Wraps the [`np.dtypes.BytesDType`][numpy.dtypes.BytesDType] data type. Scalars for this data type are instances of + [`np.bytes_`][numpy.bytes_]. + + This data type is parametrized by an integral length which specifies size in bytes of each + scalar. Because this data type uses null-terminated semantics, indexing into + NumPy arrays with this data type may return fewer than ``length`` bytes. + + Attributes + ---------- + dtype_cls: ClassVar[type[np.dtypes.BytesDType[int]]] = np.dtypes.BytesDType + The NumPy data type wrapped by this ZDType. + _zarr_v3_name : ClassVar[Literal["null_terminated_bytes"]] + length : int + The length of the bytes. + + Notes + ----- + This data type is designed for compatibility with NumPy arrays that use the NumPy ``bytes`` data type. + It may not be desirable for usage outside of that context. If compatibility + with the NumPy ``bytes`` data type is not essential, consider using the ``RawBytes`` + or ``VariableLengthBytes`` data types instead. + """ + + dtype_cls = np.dtypes.BytesDType + _zarr_v3_name: ClassVar[Literal["null_terminated_bytes"]] = "null_terminated_bytes" + + def __post_init__(self) -> None: + """ + We don't allow instances of this class with length less than 1 because there is no way such + a data type can contain actual data. + """ + if self.length < 1: + raise ValueError(f"length must be >= 1, got {self.length}.") + + @classmethod + def from_native_dtype(cls, dtype: TBaseDType) -> Self: + """ + Create an instance of NullTerminatedBytes from an instance of np.dtypes.BytesDType. + + This method checks if the provided data type is an instance of np.dtypes.BytesDType. + If so, it returns a new instance of NullTerminatedBytes with a length equal to the + length of input data type. + + Parameters + ---------- + dtype : TBaseDType + The native dtype to convert. + + Returns + ------- + NullTerminatedBytes + An instance of NullTerminatedBytes with the specified length. + + Raises + ------ + DataTypeValidationError + If the dtype is not compatible with NullTerminatedBytes. + """ + + if cls._check_native_dtype(dtype): + return cls(length=dtype.itemsize) + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self) -> np.dtypes.BytesDType[int]: + """ + Create a NumPy bytes dtype from this NullTerminatedBytes ZDType. + + Returns + ------- + np.dtypes.BytesDType[int] + A NumPy data type object representing null-terminated bytes with a specified length. + """ + + return self.dtype_cls(self.length) + + @classmethod + def _check_json_v2(cls, data: DTypeJSON) -> TypeGuard[NullterminatedBytesJSON_V2]: + """ + Check that the input is a valid JSON representation of NullTerminatedBytes in Zarr V2. + + The input data must be a mapping that contains a "name" key that matches the pattern + "|S" and an "object_codec_id" key that is None. + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + bool + True if the input data is a valid representation, False otherwise. + """ + + return ( + check_dtype_spec_v2(data) + and isinstance(data["name"], str) + and re.match(r"^\|S\d+$", data["name"]) is not None + and data["object_codec_id"] is None + ) + + @classmethod + def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[NullTerminatedBytesJSON_V3]: + """ + Check that the input is a valid JSON representation of this class in Zarr V3. + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + TypeGuard[NullTerminatedBytesJSON_V3] + True if the input is a valid representation of this class in Zarr V3, False + otherwise. + """ + return ( + isinstance(data, dict) + and set(data.keys()) == {"name", "configuration"} + and data["name"] == cls._zarr_v3_name + and isinstance(data["configuration"], dict) + and "length_bytes" in data["configuration"] + and isinstance(data["configuration"]["length_bytes"], int) + ) + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this class from Zarr V2-flavored JSON. + + This method checks if the input data is a valid representation of + this class in Zarr V2. If so, it returns a new instance of + this class with a ``length`` as specified in the input data. + + Parameters + ---------- + data : DTypeJSON + The JSON data to parse. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input data is not a valid representation of this class. + """ + + if cls._check_json_v2(data): + name = data["name"] + return cls(length=int(name[2:])) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected a string like '|S1', '|S2', etc" + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this class from Zarr V3-flavored JSON. + + This method checks if the input data is a valid representation of + this class in Zarr V3. If so, it returns a new instance of + this class with a ``length`` as specified in the input data. + + Parameters + ---------- + data : DTypeJSON + The JSON data to parse. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input data is not a valid representation of this class. + """ + if cls._check_json_v3(data): + return cls(length=data["configuration"]["length_bytes"]) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> NullterminatedBytesJSON_V2: ... + + @overload + def to_json(self, zarr_format: Literal[3]) -> NullTerminatedBytesJSON_V3: ... + + def to_json( + self, zarr_format: ZarrFormat + ) -> DTypeConfig_V2[str, None] | NullTerminatedBytesJSON_V3: + """ + Generate a JSON representation of this data type. + + Parameters + ---------- + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + NullterminatedBytesJSON_V2 | NullTerminatedBytesJSON_V3 + The JSON-serializable representation of the data type + """ + if zarr_format == 2: + return {"name": self.to_native_dtype().str, "object_codec_id": None} + elif zarr_format == 3: + v3_unstable_dtype_warning(self) + return { + "name": self._zarr_v3_name, + "configuration": {"length_bytes": self.length}, + } + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + def _check_scalar(self, data: object) -> TypeGuard[BytesLike]: + """ + Check if the provided data is of type BytesLike. + + This method is used to verify if the input data can be considered as a + scalar of bytes-like type, which includes NumPy bytes, strings, bytes, + and integers. + + Parameters + ---------- + data : object + The data to check. + + Returns + ------- + TypeGuard[BytesLike] + True if the data is bytes-like, False otherwise. + """ + + return isinstance(data, BytesLike) + + def _cast_scalar_unchecked(self, data: BytesLike) -> np.bytes_: + """ + Cast the provided scalar data to [`np.bytes_`][numpy.bytes_], truncating if necessary. + + Parameters + ---------- + data : BytesLike + The data to cast. + + Returns + ------- + bytes : [`np.bytes_`][numpy.bytes_] + The casted data as a NumPy bytes scalar. + + Notes + ----- + This method does not perform any type checking. + The input data must be bytes-like. + """ + if isinstance(data, int): + return self.to_native_dtype().type(str(data)[: self.length]) + else: + return self.to_native_dtype().type(data[: self.length]) + + def cast_scalar(self, data: object) -> np.bytes_: + """ + Attempt to cast a given object to a NumPy bytes scalar. + + This method first checks if the provided data is a valid scalar that can be + converted to a NumPy bytes scalar. If the check succeeds, the unchecked casting + operation is performed. If the data is not valid, a TypeError is raised. + + Parameters + ---------- + data : object + The data to be cast to a NumPy bytes scalar. + + Returns + ------- + bytes : [`np.bytes_`][numpy.bytes_] + The data cast as a NumPy bytes scalar. + + Raises + ------ + TypeError + If the data cannot be converted to a NumPy bytes scalar. + """ + + if self._check_scalar(data): + return self._cast_scalar_unchecked(data) + msg = ( + f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the " + f"data type {self}." + ) + raise TypeError(msg) + + def default_scalar(self) -> np.bytes_: + """ + Return a default scalar value, which for this data type is an empty byte string. + + Returns + ------- + bytes : [`np.bytes_`][numpy.bytes_] + The default scalar value. + """ + return np.bytes_(b"") + + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> str: + """ + Convert a scalar to a JSON-serializable string representation. + + This method encodes the given scalar as a NumPy bytes scalar and then + encodes the bytes as a base64-encoded string. + + Parameters + ---------- + data : object + The scalar to convert. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + str + A string representation of the scalar. + """ + as_bytes = self.cast_scalar(data) + return base64.standard_b64encode(as_bytes).decode("ascii") + + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.bytes_: + """ + Read a JSON-serializable value as [`np.bytes_`][numpy.bytes_]. + + Parameters + ---------- + data : JSON + The JSON-serializable base64-encoded string. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + bytes : [`np.bytes_`][numpy.bytes_] + The NumPy bytes scalar obtained from decoding the base64 string. + + Raises + ------ + TypeError + If the input data is not a base64-encoded string. + """ + + if check_json_str(data): + return self.to_native_dtype().type(base64.standard_b64decode(data.encode("ascii"))) + raise TypeError( + f"Invalid type: {data}. Expected a base64-encoded string." + ) # pragma: no cover + + @property + def item_size(self) -> int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return self.length + + +@dataclass(frozen=True, kw_only=True) +class RawBytes(ZDType[np.dtypes.VoidDType[int], np.void], HasLength, HasItemSize): + """ + A Zarr data type for arrays containing fixed-length sequences of raw bytes. + + Wraps the NumPy ``void`` data type. Scalars for this data type are instances of [`np.void`][numpy.void]. + + This data type is parametrized by an integral length which specifies size in bytes of each + scalar belonging to this data type. + + Attributes + ---------- + dtype_cls: ClassVar[type[np.dtypes.VoidDType[int]]] = np.dtypes.VoidDtype + The NumPy data type wrapped by this ZDType. + _zarr_v3_name : ClassVar[Literal["raw_bytes"]] + length : int + The length of the bytes. + + Notes + ----- + Although the NumPy "Void" data type is used to create "structured" data types in NumPy, this + class does not support structured data types. + + See the ``Structured`` data type for this functionality. + + """ + + # np.dtypes.VoidDType is specified in an odd way in NumPy + # it cannot be used to create instances of the dtype + # so we have to tell mypy to ignore this here + dtype_cls = np.dtypes.VoidDType # type: ignore[assignment] + _zarr_v3_name: ClassVar[Literal["raw_bytes"]] = "raw_bytes" + + def __post_init__(self) -> None: + """ + We don't allow instances of this class with length less than 1 because there is no way such + a data type can contain actual data. + """ + if self.length < 1: + raise ValueError(f"length must be >= 1, got {self.length}.") + + @classmethod + def _check_native_dtype( + cls: type[Self], dtype: TBaseDType + ) -> TypeGuard[np.dtypes.VoidDType[int]]: + """ + Check that the input is a NumPy void dtype with no fields. + + + Numpy void dtype comes in two forms: + * If the ``fields`` attribute is ``None``, then the dtype represents N raw bytes. + * If the ``fields`` attribute is not ``None``, then the dtype represents a structured dtype, + + In this check we ensure that ``fields`` is ``None``. + + Parameters + ---------- + dtype : TDBaseDType + The dtype to check. + + Returns + ------- + Bool + True if the dtype is an instance of np.dtypes.VoidDType with no fields, False otherwise. + """ + return cls.dtype_cls is type(dtype) and dtype.fields is None + + @classmethod + def from_native_dtype(cls, dtype: TBaseDType) -> Self: + """ + Create an instance of RawBytes from an instance of np.dtypes.VoidDType. + + This method checks if the provided data type is compatible with RawBytes. The input + must be an instance of np.dtypes.VoidDType, and have no fields. If the input is compatible, + this method returns an instance of RawBytes with the specified length. + + + Parameters + ---------- + dtype : TBaseDType + The native dtype to convert. + + Returns + ------- + RawBytes + An instance of RawBytes with the specified length. + + Raises + ------ + DataTypeValidationError + If the dtype is not compatible with RawBytes. + """ + + if cls._check_native_dtype(dtype): + return cls(length=dtype.itemsize) + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self) -> np.dtypes.VoidDType[int]: + """ + Create a NumPy void dtype from this RawBytes ZDType. + + Returns + ------- + np.dtypes.VoidDType[int] + A NumPy data type object representing raw bytes with a specified length. + """ + # Numpy does not allow creating a void type + # by invoking np.dtypes.VoidDType directly + return cast("np.dtypes.VoidDType[int]", np.dtype(f"V{self.length}")) + + @classmethod + def _check_json_v2(cls, data: DTypeJSON) -> TypeGuard[RawBytesJSON_V2]: + """ + Check that the input is a valid representation of this class in Zarr V2. + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + True if the input is a valid representation of this class in Zarr V3, False otherwise. + + """ + return ( + check_dtype_spec_v2(data) + and isinstance(data["name"], str) + and re.match(r"^\|V\d+$", data["name"]) is not None + and data["object_codec_id"] is None + ) + + @classmethod + def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[RawBytesJSON_V3]: + """ + Check that the input is a valid JSON representation of this class in Zarr V3. + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + TypeGuard[RawBytesJSON_V3] + True if the input is a valid representation of this class in Zarr V3, False + otherwise. + """ + return ( + isinstance(data, dict) + and set(data.keys()) == {"name", "configuration"} + and data["name"] == cls._zarr_v3_name + and isinstance(data["configuration"], dict) + and set(data["configuration"].keys()) == {"length_bytes"} + and isinstance(data["configuration"]["length_bytes"], int) + ) + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an instance of RawBytes from Zarr V2-flavored JSON. + + This method checks if the input data is a valid representation of + RawBytes in Zarr V2. If so, it returns a new instance of + RawBytes with a ``length`` as specified in the input data. + + Parameters + ---------- + data : DTypeJSON + The JSON data to parse. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input data is not a valid representation of this class. + """ + if cls._check_json_v2(data): + name = data["name"] + return cls(length=int(name[2:])) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected a string like '|V1', '|V2', etc" + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create an instance of RawBytes from Zarr V3-flavored JSON. + + This method checks if the input data is a valid representation of + RawBytes in Zarr V3. If so, it returns a new instance of + RawBytes with a ``length`` as specified in the input data. + + Parameters + ---------- + data : DTypeJSON + The JSON data to parse. + + Returns + ------- + RawBytes + An instance of RawBytes. + + Raises + ------ + DataTypeValidationError + If the input data is not a valid representation of this class. + """ + if cls._check_json_v3(data): + return cls(length=data["configuration"]["length_bytes"]) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> RawBytesJSON_V2: ... + + @overload + def to_json(self, zarr_format: Literal[3]) -> RawBytesJSON_V3: ... + + def to_json(self, zarr_format: ZarrFormat) -> RawBytesJSON_V2 | RawBytesJSON_V3: + """ + Generate a JSON representation of this data type. + + Parameters + ---------- + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + RawBytesJSON_V2 | RawBytesJSON_V3 + The JSON-serializable representation of the data type. + """ + if zarr_format == 2: + return {"name": self.to_native_dtype().str, "object_codec_id": None} + elif zarr_format == 3: + v3_unstable_dtype_warning(self) + return {"name": self._zarr_v3_name, "configuration": {"length_bytes": self.length}} + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + def _check_scalar(self, data: object) -> TypeGuard[np.bytes_ | str | bytes | np.void]: + """ + Check if the provided data can be cast to np.void. + + This method is used to verify if the input data can be considered as a + scalar of bytes-like type, which includes np.bytes_, np.void, strings, and bytes objects. + + Parameters + ---------- + data : object + The data to check. + + Returns + ------- + TypeGuard[np.bytes_ | str | bytes | np.void] + True if the data is void-scalar-like, False otherwise. + """ + return isinstance(data, np.bytes_ | str | bytes | np.void) + + def _cast_scalar_unchecked(self, data: object) -> np.void: + """ + Cast the provided scalar data to np.void. + + Parameters + ---------- + data : BytesLike + The data to cast. + + Returns + ------- + np.void + The casted data as a NumPy void scalar. + + Notes + ----- + This method does not perform any type checking. + The input data must be castable to np.void. + """ + native_dtype = self.to_native_dtype() + # Without the second argument, NumPy will return a void scalar for dtype V1. + # The second argument ensures that, if native_dtype is something like V10, + # the result will actually be a V10 scalar. + return native_dtype.type(data, native_dtype) + + def cast_scalar(self, data: object) -> np.void: + """ + Attempt to cast a given object to a NumPy void scalar. + + This method first checks if the provided data is a valid scalar that can be + converted to a NumPy void scalar. If the check succeeds, the unchecked casting + operation is performed. If the data is not valid, a TypeError is raised. + + Parameters + ---------- + data : object + The data to be cast to a NumPy void scalar. + + Returns + ------- + np.void + The data cast as a NumPy void scalar. + + Raises + ------ + TypeError + If the data cannot be converted to a NumPy void scalar. + """ + if self._check_scalar(data): + return self._cast_scalar_unchecked(data) + msg = ( + f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the " + f"data type {self}." + ) + raise TypeError(msg) + + def default_scalar(self) -> np.void: + """ + Return the default scalar value for this data type. + + The default scalar is a NumPy void scalar of the same length as the data type, + filled with zero bytes. + + Returns + ------- + np.void + The default scalar value. + """ + return self.to_native_dtype().type(("\x00" * self.length).encode("ascii")) + + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> str: + """ + Convert a scalar to a JSON-serializable string representation. + + This method converts the given scalar to bytes and then + encodes the bytes as a base64-encoded string. + + Parameters + ---------- + data : object + The scalar to convert. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + str + A string representation of the scalar. + """ + as_bytes = self.cast_scalar(data) + return base64.standard_b64encode(as_bytes.tobytes()).decode("ascii") + + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.void: + """ + Read a JSON-serializable value as an np.void. + + Parameters + ---------- + data : JSON + The JSON-serializable value. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + np.void + The NumPy void scalar. + + Raises + ------ + TypeError + If the data is not a string, or if the string is not a valid base64 encoding. + """ + if check_json_str(data): + return self.to_native_dtype().type(base64.standard_b64decode(data)) + raise TypeError(f"Invalid type: {data}. Expected a string.") # pragma: no cover + + @property + def item_size(self) -> int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return self.length + + +@dataclass(frozen=True, kw_only=True) +class VariableLengthBytes(ZDType[np.dtypes.ObjectDType, bytes], HasObjectCodec): + """ + A Zarr data type for arrays containing variable-length sequences of bytes. + + Wraps the NumPy "object" data type. Scalars for this data type are instances of ``bytes``. + + Attributes + ---------- + dtype_cls: ClassVar[type[np.dtypes.ObjectDType]] = np.dtypes.ObjectDType + The NumPy data type wrapped by this ZDType. + _zarr_v3_name: ClassVar[Literal["variable_length_bytes"]] = "variable_length_bytes" + The name of this data type in Zarr V3. + object_codec_id: ClassVar[Literal["vlen-bytes"]] = "vlen-bytes" + The object codec ID for this data type. + + Notes + ----- + Because this data type uses the NumPy "object" data type, it does not guarantee a compact memory + representation of array data. Therefore a "vlen-bytes" codec is needed to ensure that the array + data can be persisted to storage. + """ + + dtype_cls = np.dtypes.ObjectDType + _zarr_v3_name: ClassVar[Literal["variable_length_bytes"]] = "variable_length_bytes" + object_codec_id: ClassVar[Literal["vlen-bytes"]] = "vlen-bytes" + + @classmethod + def from_native_dtype(cls, dtype: TBaseDType) -> Self: + """ + Create an instance of VariableLengthBytes from an instance of np.dtypes.ObjectDType. + + This method checks if the provided data type is an instance of np.dtypes.ObjectDType. + If so, it returns an instance of VariableLengthBytes. + + Parameters + ---------- + dtype : TBaseDType + The native dtype to convert. + + Returns + ------- + VariableLengthBytes + An instance of VariableLengthBytes. + + Raises + ------ + DataTypeValidationError + If the dtype is not compatible with VariableLengthBytes. + """ + if cls._check_native_dtype(dtype): + return cls() + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self) -> np.dtypes.ObjectDType: + """ + Create a NumPy object dtype from this VariableLengthBytes ZDType. + + Returns + ------- + np.dtypes.ObjectDType + A NumPy data type object representing variable-length bytes. + """ + return self.dtype_cls() + + @classmethod + def _check_json_v2( + cls, + data: DTypeJSON, + ) -> TypeGuard[VariableLengthBytesJSON_V2]: + """ + Check that the input is a valid JSON representation of a NumPy O dtype, and that the + object codec id is appropriate for variable-length bytes strings. + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + True if the input is a valid representation of this class in Zarr V2, False + otherwise. + """ + # Check that the input is a valid JSON representation of a Zarr v2 data type spec. + if not check_dtype_spec_v2(data): + return False + + # Check that the object codec id is appropriate for variable-length bytes strings. + if data["name"] != "|O": + return False + return data["object_codec_id"] == cls.object_codec_id + + @classmethod + def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[Literal["variable_length_bytes"]]: + """ + Check that the input is a valid JSON representation of this class in Zarr V3. + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + TypeGuard[Literal["variable_length_bytes"]] + True if the input is a valid representation of this class in Zarr V3, False otherwise. + """ + + return data in (cls._zarr_v3_name, "bytes") + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this VariableLengthBytes from Zarr V2-flavored JSON. + + This method checks if the input data is a valid representation of this class + in Zarr V2. If so, it returns a new instance this class. + + Parameters + ---------- + data : DTypeJSON + The JSON data to parse. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input data is not a valid representation of this class. + """ + + if cls._check_json_v2(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string '|O' and an object_codec_id of {cls.object_codec_id}" + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create an instance of VariableLengthBytes from Zarr V3-flavored JSON. + + This method checks if the input data is a valid representation of + VariableLengthBytes in Zarr V3. If so, it returns a new instance of + VariableLengthBytes. + + Parameters + ---------- + data : DTypeJSON + The JSON data to parse. + + Returns + ------- + VariableLengthBytes + An instance of VariableLengthBytes. + + Raises + ------ + DataTypeValidationError + If the input data is not a valid representation of this class. + """ + + if cls._check_json_v3(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> VariableLengthBytesJSON_V2: ... + + @overload + def to_json(self, zarr_format: Literal[3]) -> Literal["variable_length_bytes"]: ... + + def to_json( + self, zarr_format: ZarrFormat + ) -> VariableLengthBytesJSON_V2 | Literal["variable_length_bytes"]: + """ + Convert the variable-length bytes data type to a JSON-serializable form. + + Parameters + ---------- + zarr_format : ZarrFormat + The zarr format version. Accepted values are 2 and 3. + + Returns + ------- + ``DTypeConfig_V2[Literal["|O"], Literal["vlen-bytes"]] | Literal["variable_length_bytes"]`` + The JSON-serializable representation of the variable-length bytes data type. + For zarr_format 2, returns a dictionary with "name" and "object_codec_id". + For zarr_format 3, returns a string identifier "variable_length_bytes". + + Raises + ------ + ValueError + If zarr_format is not 2 or 3. + """ + + if zarr_format == 2: + return {"name": "|O", "object_codec_id": self.object_codec_id} + elif zarr_format == 3: + v3_unstable_dtype_warning(self) + return self._zarr_v3_name + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + def default_scalar(self) -> bytes: + """ + Return the default scalar value for the variable-length bytes data type. + + Returns + ------- + bytes + The default scalar value, which is an empty byte string. + """ + + return b"" + + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> str: + """ + Convert a scalar to a JSON-serializable string representation. + + This method encodes the given scalar as bytes and then + encodes the bytes as a base64-encoded string. + + Parameters + ---------- + data : object + The scalar to convert. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + str + A string representation of the scalar. + """ + return base64.standard_b64encode(data).decode("ascii") # type: ignore[arg-type] + + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> bytes: + """ + Decode a base64-encoded JSON string to bytes. + + Parameters + ---------- + data : JSON + The JSON-serializable base64-encoded string. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + bytes + The decoded bytes from the base64 string. + + Raises + ------ + TypeError + If the input data is not a base64-encoded string. + """ + + if check_json_str(data): + return base64.standard_b64decode(data.encode("ascii")) + raise TypeError(f"Invalid type: {data}. Expected a string.") # pragma: no cover + + def _check_scalar(self, data: object) -> TypeGuard[BytesLike]: + """ + Check if the provided data is of type BytesLike. + + This method is used to verify if the input data can be considered as a + scalar of bytes-like type, which includes NumPy bytes, strings, bytes, + and integers. + + Parameters + ---------- + data : object + The data to check. + + Returns + ------- + TypeGuard[BytesLike] + True if the data is bytes-like, False otherwise. + """ + return isinstance(data, BytesLike) + + def _cast_scalar_unchecked(self, data: BytesLike) -> bytes: + """ + Cast the provided scalar data to bytes. + + Parameters + ---------- + data : BytesLike + The data to cast. + + Returns + ------- + bytes + The casted data as bytes. + + Notes + ----- + This method does not perform any type checking. + The input data must be bytes-like. + """ + if isinstance(data, str): + return bytes(data, encoding="utf-8") + return bytes(data) + + def cast_scalar(self, data: object) -> bytes: + """ + Attempt to cast a given object to a bytes scalar. + + This method first checks if the provided data is a valid scalar that can be + converted to a bytes scalar. If the check succeeds, the unchecked casting + operation is performed. If the data is not valid, a TypeError is raised. + + Parameters + ---------- + data : object + The data to be cast to a bytes scalar. + + Returns + ------- + bytes + The data cast as a bytes scalar. + + Raises + ------ + TypeError + If the data cannot be converted to a bytes scalar. + """ + + if self._check_scalar(data): + return self._cast_scalar_unchecked(data) + msg = ( + f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the " + f"data type {self}." + ) + raise TypeError(msg) diff --git a/src/zarr/core/dtype/npy/common.py b/src/zarr/core/dtype/npy/common.py new file mode 100644 index 0000000000..f413f5f678 --- /dev/null +++ b/src/zarr/core/dtype/npy/common.py @@ -0,0 +1,566 @@ +from __future__ import annotations + +import base64 +import struct +import sys +from collections.abc import Sequence +from typing import ( + TYPE_CHECKING, + Any, + Final, + Literal, + NewType, + SupportsComplex, + SupportsFloat, + SupportsIndex, + SupportsInt, + TypeGuard, +) + +import numpy as np + +from zarr.core.dtype.common import ( + ENDIANNESS_STR, + SPECIAL_FLOAT_STRINGS, + EndiannessStr, + JSONFloatV2, + JSONFloatV3, +) + +if TYPE_CHECKING: + from zarr.core.common import JSON, ZarrFormat + +IntLike = SupportsInt | SupportsIndex | bytes | str +FloatLike = SupportsIndex | SupportsFloat | bytes | str +ComplexLike = SupportsFloat | SupportsIndex | SupportsComplex | bytes | str | None +DateTimeUnit = Literal[ + "Y", "M", "W", "D", "h", "m", "s", "ms", "us", "ΞΌs", "ns", "ps", "fs", "as", "generic" +] +DATETIME_UNIT: Final = ( + "Y", + "M", + "W", + "D", + "h", + "m", + "s", + "ms", + "us", + "ΞΌs", + "ns", + "ps", + "fs", + "as", + "generic", +) + +IntishFloat = NewType("IntishFloat", float) +"""A type for floats that represent integers, like 1.0 (but not 1.1).""" + +IntishStr = NewType("IntishStr", str) +"""A type for strings that represent integers, like "0" or "42".""" + +FloatishStr = NewType("FloatishStr", str) +"""A type for strings that represent floats, like "3.14" or "-2.5".""" + +NumpyEndiannessStr = Literal[">", "<", "="] +NUMPY_ENDIANNESS_STR: Final = ">", "<", "=" + + +def endianness_from_numpy_str(endianness: NumpyEndiannessStr) -> EndiannessStr: + """ + Convert a numpy endianness string literal to a human-readable literal value. + + Parameters + ---------- + endianness : Literal[">", "<", "="] + The numpy string representation of the endianness. + + Returns + ------- + Endianness + The human-readable representation of the endianness. + + Raises + ------ + ValueError + If the endianness is invalid. + """ + match endianness: + case "=": + # Use the local system endianness + return sys.byteorder + case "<": + return "little" + case ">": + return "big" + raise ValueError(f"Invalid endianness: {endianness!r}. Expected one of {NUMPY_ENDIANNESS_STR}") + + +def endianness_to_numpy_str(endianness: EndiannessStr) -> NumpyEndiannessStr: + """ + Convert an endianness literal to its numpy string representation. + + Parameters + ---------- + endianness : Endianness + The endianness to convert. + + Returns + ------- + Literal[">", "<"] + The numpy string representation of the endianness. + + Raises + ------ + ValueError + If the endianness is invalid. + """ + match endianness: + case "little": + return "<" + case "big": + return ">" + raise ValueError( + f"Invalid endianness: {endianness!r}. Expected one of {ENDIANNESS_STR} or None" + ) + + +def get_endianness_from_numpy_dtype(dtype: np.dtype[np.generic]) -> EndiannessStr: + """ + Gets the endianness from a numpy dtype that has an endianness. This function will + raise a ValueError if the numpy data type does not have a concrete endianness. + """ + endianness = dtype.byteorder + if dtype.byteorder in NUMPY_ENDIANNESS_STR: + return endianness_from_numpy_str(endianness) # type: ignore [arg-type] + raise ValueError(f"The dtype {dtype} has an unsupported endianness: {endianness}") + + +def float_from_json_v2(data: JSONFloatV2) -> float: + """ + Convert a JSON float to a float (Zarr v2). + + Parameters + ---------- + data : JSONFloat + The JSON float to convert. + + Returns + ------- + float + The float value. + """ + match data: + case "NaN": + return float("nan") + case "Infinity": + return float("inf") + case "-Infinity": + return float("-inf") + case _: + return float(data) + + +def float_from_json_v3(data: JSONFloatV3) -> float: + """ + Convert a JSON float to a float (v3). + + Parameters + ---------- + data : JSONFloat + The JSON float to convert. + + Returns + ------- + float + The float value. + + Notes + ----- + Zarr V3 allows floats to be stored as hex strings. To quote the spec: + "...for float32, "NaN" is equivalent to "0x7fc00000". + This representation is the only way to specify a NaN value other than the specific NaN value + denoted by "NaN"." + """ + + if isinstance(data, str): + if data in SPECIAL_FLOAT_STRINGS: + return float_from_json_v2(data) # type: ignore[arg-type] + if not data.startswith("0x"): + msg = ( + f"Invalid float value: {data!r}. Expected a string starting with the hex prefix" + " '0x', or one of 'NaN', 'Infinity', or '-Infinity'." + ) + raise ValueError(msg) + if len(data[2:]) == 4: + dtype_code = ">e" + elif len(data[2:]) == 8: + dtype_code = ">f" + elif len(data[2:]) == 16: + dtype_code = ">d" + else: + msg = ( + f"Invalid hexadecimal float value: {data!r}. " + "Expected the '0x' prefix to be followed by 4, 8, or 16 numeral characters" + ) + raise ValueError(msg) + return float(struct.unpack(dtype_code, bytes.fromhex(data[2:]))[0]) + return float_from_json_v2(data) + + +def bytes_from_json(data: str, *, zarr_format: ZarrFormat) -> bytes: + """ + Convert a JSON string to bytes + + Parameters + ---------- + data : str + The JSON string to convert. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + bytes + The bytes. + """ + if zarr_format == 2: + return base64.b64decode(data.encode("ascii")) + # TODO: differentiate these as needed. This is a spec question. + if zarr_format == 3: + return base64.b64decode(data.encode("ascii")) + raise ValueError(f"Invalid zarr format: {zarr_format}. Expected 2 or 3.") # pragma: no cover + + +def bytes_to_json(data: bytes, zarr_format: ZarrFormat) -> str: + """ + Convert bytes to JSON. + + Parameters + ---------- + data : bytes + The bytes to store. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + str + The bytes encoded as ascii using the base64 alphabet. + """ + # TODO: decide if we are going to make this implementation zarr format-specific + return base64.b64encode(data).decode("ascii") + + +def float_to_json_v2(data: float | np.floating[Any]) -> JSONFloatV2: + """ + Convert a float to JSON (v2). + + Parameters + ---------- + data : float or np.floating + The float value to convert. + + Returns + ------- + JSONFloat + The JSON representation of the float. + """ + if np.isnan(data): + return "NaN" + elif np.isinf(data): + return "Infinity" if data > 0 else "-Infinity" + return float(data) + + +def float_to_json_v3(data: float | np.floating[Any]) -> JSONFloatV3: + """ + Convert a float to JSON (v3). + + Parameters + ---------- + data : float or np.floating + The float value to convert. + + Returns + ------- + JSONFloat + The JSON representation of the float. + """ + # v3 can in principle handle distinct NaN values, but numpy does not represent these explicitly + # so we just reuse the v2 routine here + return float_to_json_v2(data) + + +def complex_float_to_json_v3( + data: complex | np.complexfloating[Any, Any], +) -> tuple[JSONFloatV3, JSONFloatV3]: + """ + Convert a complex number to JSON as defined by the Zarr V3 spec. + + Parameters + ---------- + data : complex or np.complexfloating + The complex value to convert. + + Returns + ------- + tuple[JSONFloat, JSONFloat] + The JSON representation of the complex number. + """ + return float_to_json_v3(data.real), float_to_json_v3(data.imag) + + +def complex_float_to_json_v2( + data: complex | np.complexfloating[Any, Any], +) -> tuple[JSONFloatV2, JSONFloatV2]: + """ + Convert a complex number to JSON as defined by the Zarr V2 spec. + + Parameters + ---------- + data : complex | np.complexfloating + The complex value to convert. + + Returns + ------- + tuple[JSONFloat, JSONFloat] + The JSON representation of the complex number. + """ + return float_to_json_v2(data.real), float_to_json_v2(data.imag) + + +def complex_float_from_json_v2(data: tuple[JSONFloatV2, JSONFloatV2]) -> complex: + """ + Convert a JSON complex float to a complex number (v2). + + Parameters + ---------- + data : tuple[JSONFloat, JSONFloat] + The JSON complex float to convert. + + Returns + ------- + np.complexfloating + The complex number. + """ + return complex(float_from_json_v2(data[0]), float_from_json_v2(data[1])) + + +def complex_float_from_json_v3(data: tuple[JSONFloatV3, JSONFloatV3]) -> complex: + """ + Convert a JSON complex float to a complex number (v3). + + Parameters + ---------- + data : tuple[JSONFloat, JSONFloat] + The JSON complex float to convert. + + Returns + ------- + np.complexfloating + The complex number. + """ + return complex(float_from_json_v3(data[0]), float_from_json_v3(data[1])) + + +def check_json_float_v2(data: JSON) -> TypeGuard[JSONFloatV2]: + """ + Check if a JSON value represents a float (v2). + + Parameters + ---------- + data : JSON + The JSON value to check. + + Returns + ------- + Bool + True if the data is a float, False otherwise. + """ + return data in ("NaN", "Infinity", "-Infinity") or isinstance(data, float | int) + + +def check_json_float_v3(data: JSON) -> TypeGuard[JSONFloatV3]: + """ + Check if a JSON value represents a float (v3). + + Parameters + ---------- + data : JSON + The JSON value to check. + + Returns + ------- + Bool + True if the data is a float, False otherwise. + """ + return check_json_float_v2(data) or (isinstance(data, str) and data.startswith("0x")) + + +def check_json_complex_float_v2(data: JSON) -> TypeGuard[tuple[JSONFloatV2, JSONFloatV2]]: + """ + Check if a JSON value represents a complex float, as per the behavior of zarr-python 2.x + + Parameters + ---------- + data : JSON + The JSON value to check. + + Returns + ------- + Bool + True if the data is a complex float, False otherwise. + """ + return ( + not isinstance(data, str) + and isinstance(data, Sequence) + and len(data) == 2 + and check_json_float_v2(data[0]) + and check_json_float_v2(data[1]) + ) + + +def check_json_complex_float_v3(data: JSON) -> TypeGuard[tuple[JSONFloatV3, JSONFloatV3]]: + """ + Check if a JSON value represents a complex float, as per the zarr v3 spec + + Parameters + ---------- + data : JSON + The JSON value to check. + + Returns + ------- + Bool + True if the data is a complex float, False otherwise. + """ + return ( + not isinstance(data, str) + and isinstance(data, Sequence) + and len(data) == 2 + and check_json_float_v3(data[0]) + and check_json_float_v3(data[1]) + ) + + +def check_json_int(data: JSON) -> TypeGuard[int]: + """ + Check if a JSON value is an integer. + + Parameters + ---------- + data : JSON + The JSON value to check. + + Returns + ------- + Bool + True if the data is an integer, False otherwise. + """ + return bool(isinstance(data, int)) + + +def check_json_intish_float(data: JSON) -> TypeGuard[IntishFloat]: + """ + Check if a JSON value is an "intish float", i.e. a float that represents an integer, like 0.0. + + Parameters + ---------- + data : JSON + The JSON value to check. + + Returns + ------- + Bool + True if the data is an intish float, False otherwise. + """ + return isinstance(data, float) and data.is_integer() + + +def check_json_intish_str(data: JSON) -> TypeGuard[IntishStr]: + """ + Check if a JSON value is a string that represents an integer, like "0", "42", or "-5". + + Parameters + ---------- + data : JSON + The JSON value to check. + + Returns + ------- + bool + True if the data is a string representing an integer, False otherwise. + """ + if not isinstance(data, str): + return False + + try: + int(data) + except ValueError: + return False + else: + return True + + +def check_json_floatish_str(data: JSON) -> TypeGuard[FloatishStr]: + """ + Check if a JSON value is a string that represents a float, like "3.14", "-2.5", or "0.0". + + Note: This function is intended to be used AFTER check_json_float_v2/v3, so it only + handles regular string representations that those functions don't cover. + + Parameters + ---------- + data : JSON + The JSON value to check. + + Returns + ------- + bool + True if the data is a string representing a regular float, False otherwise. + """ + if not isinstance(data, str): + return False + + try: + float(data) + except ValueError: + return False + else: + return True + + +def check_json_str(data: JSON) -> TypeGuard[str]: + """ + Check if a JSON value is a string. + + Parameters + ---------- + data : JSON + The JSON value to check. + + Returns + ------- + Bool + True if the data is a string, False otherwise. + """ + return bool(isinstance(data, str)) + + +def check_json_bool(data: JSON) -> TypeGuard[bool]: + """ + Check if a JSON value is a boolean. + + Parameters + ---------- + data : JSON + The JSON value to check. + + Returns + ------- + Bool + True if the data is a boolean, False otherwise. + """ + return isinstance(data, bool) diff --git a/src/zarr/core/dtype/npy/complex.py b/src/zarr/core/dtype/npy/complex.py new file mode 100644 index 0000000000..0286d42380 --- /dev/null +++ b/src/zarr/core/dtype/npy/complex.py @@ -0,0 +1,419 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import ( + TYPE_CHECKING, + ClassVar, + Literal, + Self, + TypeGuard, + overload, +) + +import numpy as np + +from zarr.core.dtype.common import ( + DTypeConfig_V2, + DTypeJSON, + HasEndianness, + HasItemSize, + check_dtype_spec_v2, +) +from zarr.core.dtype.npy.common import ( + ComplexLike, + check_json_complex_float_v2, + check_json_complex_float_v3, + complex_float_from_json_v2, + complex_float_from_json_v3, + complex_float_to_json_v2, + complex_float_to_json_v3, + endianness_to_numpy_str, + get_endianness_from_numpy_dtype, +) +from zarr.core.dtype.wrapper import TBaseDType, ZDType +from zarr.errors import DataTypeValidationError + +if TYPE_CHECKING: + from zarr.core.common import JSON, ZarrFormat + + +@dataclass(frozen=True) +class BaseComplex[ + DType: np.dtypes.Complex64DType | np.dtypes.Complex128DType, + Scalar: np.complex64 | np.complex128, +](ZDType[DType, Scalar], HasEndianness, HasItemSize): + """ + A base class for Zarr data types that wrap NumPy complex float data types. + """ + + # This attribute holds the possible zarr v2 JSON names for the data type + _zarr_v2_names: ClassVar[tuple[str, ...]] + + @classmethod + def from_native_dtype(cls, dtype: TBaseDType) -> Self: + """ + Create an instance of this data type from a NumPy complex dtype. + + Parameters + ---------- + dtype : TBaseDType + The native dtype to convert. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the dtype is not compatible with this data type. + """ + if cls._check_native_dtype(dtype): + return cls(endianness=get_endianness_from_numpy_dtype(dtype)) + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self) -> DType: + """ + Convert this class to a NumPy complex dtype with the appropriate byte order. + + Returns + ------- + DType + A NumPy data type object representing the complex data type with the specified byte order. + """ + + byte_order = endianness_to_numpy_str(self.endianness) + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[no-any-return,call-overload] + + @classmethod + def _check_json_v2(cls, data: DTypeJSON) -> TypeGuard[DTypeConfig_V2[str, None]]: + """ + Check that the input is a valid JSON representation of this data type. + + The input data must be a mapping that contains a "name" key that is one of + the strings from cls._zarr_v2_names and an "object_codec_id" key that is None. + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + bool + True if the input is a valid JSON representation, False otherwise. + """ + return ( + check_dtype_spec_v2(data) + and data["name"] in cls._zarr_v2_names + and data["object_codec_id"] is None + ) + + @classmethod + def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[str]: + """ + Check that the input is a valid JSON representation of this data type in Zarr V3. + + This method verifies that the provided data matches the expected Zarr V3 + representation, which is the string specified by the class-level attribute _zarr_v3_name. + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + TypeGuard[str] + True if the input is a valid representation of this class in Zarr V3, False otherwise. + """ + + return data == cls._zarr_v3_name + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this class from Zarr V2-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this class. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class. + """ + if cls._check_json_v2(data): + # Going via numpy ensures that we get the endianness correct without + # annoying string parsing. + name = data["name"] + return cls.from_native_dtype(np.dtype(name)) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected one of the strings {cls._zarr_v2_names}." + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this class from Zarr V3-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class. + """ + if cls._check_json_v3(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected {cls._zarr_v3_name}." + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[str, None]: ... + + @overload + def to_json(self, zarr_format: Literal[3]) -> str: ... + + def to_json(self, zarr_format: ZarrFormat) -> DTypeConfig_V2[str, None] | str: + """ + Serialize this object to a JSON-serializable representation. + + Parameters + ---------- + zarr_format : ZarrFormat + The Zarr format version. Supported values are 2 and 3. + + Returns + ------- + DTypeConfig_V2[str, None] | str + If ``zarr_format`` is 2, a dictionary with ``"name"`` and ``"object_codec_id"`` keys is + returned. + If ``zarr_format`` is 3, a string representation of the complex data type is returned. + + Raises + ------ + ValueError + If `zarr_format` is not 2 or 3. + """ + + if zarr_format == 2: + return {"name": self.to_native_dtype().str, "object_codec_id": None} + elif zarr_format == 3: + return self._zarr_v3_name + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + def _check_scalar(self, data: object) -> TypeGuard[ComplexLike]: + """ + Check that the input is a scalar complex value. + + Parameters + ---------- + data : object + The value to check. + + Returns + ------- + TypeGuard[ComplexLike] + True if the input is a scalar complex value, False otherwise. + """ + return isinstance(data, ComplexLike) + + def _cast_scalar_unchecked(self, data: ComplexLike) -> Scalar: + """ + Cast the provided scalar data to the native scalar type of this class. + + Parameters + ---------- + data : ComplexLike + The data to cast. + + Returns + ------- + Scalar + The casted data as a numpy complex scalar. + + Notes + ----- + This method does not perform any type checking. + The input data must be a scalar complex value. + """ + return self.to_native_dtype().type(data) # type: ignore[return-value] + + def cast_scalar(self, data: object) -> Scalar: + """ + Attempt to cast a given object to a numpy complex scalar. + + Parameters + ---------- + data : object + The data to be cast to a numpy complex scalar. + + Returns + ------- + Scalar + The data cast as a numpy complex scalar. + + Raises + ------ + TypeError + If the data cannot be converted to a numpy complex scalar. + """ + if self._check_scalar(data): + return self._cast_scalar_unchecked(data) + msg = ( + f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the " + f"data type {self}." + ) + raise TypeError(msg) + + def default_scalar(self) -> Scalar: + """ + Get the default value, which is 0 cast to this dtype + + Returns + ------- + Int scalar + The default value. + """ + return self._cast_scalar_unchecked(0) + + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> Scalar: + """ + Read a JSON-serializable value as a numpy float. + + Parameters + ---------- + data : JSON + The JSON-serializable value. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + Scalar + The numpy float. + """ + if zarr_format == 2: + if check_json_complex_float_v2(data): + return self._cast_scalar_unchecked(complex_float_from_json_v2(data)) + raise TypeError( + f"Invalid type: {data}. Expected a float or a special string encoding of a float." + ) + elif zarr_format == 3: + if check_json_complex_float_v3(data): + return self._cast_scalar_unchecked(complex_float_from_json_v3(data)) + raise TypeError( + f"Invalid type: {data}. Expected a float or a special string encoding of a float." + ) + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> JSON: + """ + Convert an object to a JSON-serializable float. + + Parameters + ---------- + data : _BaseScalar + The value to convert. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + JSON + The JSON-serializable form of the complex number, which is a list of two floats, + each of which is encoding according to a zarr-format-specific encoding. + """ + if zarr_format == 2: + return complex_float_to_json_v2(self.cast_scalar(data)) + elif zarr_format == 3: + return complex_float_to_json_v3(self.cast_scalar(data)) + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + +@dataclass(frozen=True, kw_only=True) +class Complex64(BaseComplex[np.dtypes.Complex64DType, np.complex64]): + """ + A Zarr data type for arrays containing 64 bit complex floats. + + Wraps the [`np.dtypes.Complex64DType`][numpy.dtypes.Complex64DType] data type. Scalars for this data type + are instances of [`np.complex64`][numpy.complex64]. + + Attributes + ---------- + dtype_cls : Type[np.dtypes.Complex64DType] + The numpy dtype class for this data type. + _zarr_v3_name : ClassVar[Literal["complex64"]] + The name of this data type in Zarr V3. + _zarr_v2_names : ClassVar[tuple[Literal[">c8"], Literal["c8"], Literal["c8", " int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return 8 + + +@dataclass(frozen=True, kw_only=True) +class Complex128(BaseComplex[np.dtypes.Complex128DType, np.complex128], HasEndianness): + """ + A Zarr data type for arrays containing 64 bit complex floats. + + Wraps the [`np.dtypes.Complex128DType`][numpy.dtypes.Complex128DType] data type. Scalars for this data type + are instances of [`np.complex128`][numpy.complex128]. + + Attributes + ---------- + dtype_cls : Type[np.dtypes.Complex128DType] + The numpy dtype class for this data type. + _zarr_v3_name : ClassVar[Literal["complex128"]] + The name of this data type in Zarr V3. + _zarr_v2_names : ClassVar[tuple[Literal[">c16"], Literal["c16"], Literal["c16", " int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return 16 diff --git a/src/zarr/core/dtype/npy/float.py b/src/zarr/core/dtype/npy/float.py new file mode 100644 index 0000000000..d041416b81 --- /dev/null +++ b/src/zarr/core/dtype/npy/float.py @@ -0,0 +1,436 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, ClassVar, Literal, Self, TypeGuard, overload + +import numpy as np + +from zarr.core.dtype.common import ( + DTypeConfig_V2, + DTypeJSON, + HasEndianness, + HasItemSize, + check_dtype_spec_v2, +) +from zarr.core.dtype.npy.common import ( + FloatLike, + check_json_float_v2, + check_json_float_v3, + check_json_floatish_str, + endianness_to_numpy_str, + float_from_json_v2, + float_from_json_v3, + float_to_json_v2, + float_to_json_v3, + get_endianness_from_numpy_dtype, +) +from zarr.core.dtype.wrapper import TBaseDType, ZDType +from zarr.errors import DataTypeValidationError + +if TYPE_CHECKING: + from zarr.core.common import JSON, ZarrFormat + + +@dataclass(frozen=True) +class BaseFloat[ + DType: np.dtypes.Float16DType | np.dtypes.Float32DType | np.dtypes.Float64DType, + Scalar: np.float16 | np.float32 | np.float64, +](ZDType[DType, Scalar], HasEndianness, HasItemSize): + """ + A base class for Zarr data types that wrap NumPy float data types. + """ + + # This attribute holds the possible zarr v2 JSON names for the data type + _zarr_v2_names: ClassVar[tuple[str, ...]] + + @classmethod + def from_native_dtype(cls, dtype: TBaseDType) -> Self: + """ + Create an instance of this ZDType from a NumPy data type. + + Parameters + ---------- + dtype : TBaseDType + The NumPy data type. + + Returns + ------- + Self + An instance of this data type. + """ + if cls._check_native_dtype(dtype): + return cls(endianness=get_endianness_from_numpy_dtype(dtype)) + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self) -> DType: + """ + Convert the wrapped data type to a NumPy data type. + + Returns + ------- + DType + The NumPy data type. + """ + byte_order = endianness_to_numpy_str(self.endianness) + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[no-any-return,call-overload] + + @classmethod + def _check_json_v2(cls, data: DTypeJSON) -> TypeGuard[DTypeConfig_V2[str, None]]: + """ + Check that the input is a valid JSON representation of this data type. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + TypeGuard[DTypeConfig_V2[str, None]] + True if the input is a valid JSON representation of this data type, False otherwise. + """ + return ( + check_dtype_spec_v2(data) + and data["name"] in cls._zarr_v2_names + and data["object_codec_id"] is None + ) + + @classmethod + def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[str]: + """ + Check that the input is a valid JSON representation of this class in Zarr V3. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + TypeGuard[str] + True if the input is a valid JSON representation of this class, False otherwise. + """ + return data == cls._zarr_v3_name + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this ZDType from Zarr v2-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + """ + if cls._check_json_v2(data): + # Going via NumPy ensures that we get the endianness correct without + # annoying string parsing. + name = data["name"] + return cls.from_native_dtype(np.dtype(name)) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected one of the strings {cls._zarr_v2_names}." + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this ZDType from Zarr v3-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + """ + if cls._check_json_v3(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected {cls._zarr_v3_name}." + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[str, None]: ... + + @overload + def to_json(self, zarr_format: Literal[3]) -> str: ... + + def to_json(self, zarr_format: ZarrFormat) -> DTypeConfig_V2[str, None] | str: + """ + Convert the wrapped data type to a JSON-serializable form. + + Parameters + ---------- + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + DTypeConfig_V2[str, None] or str + The JSON-serializable representation of the wrapped data type. + + Raises + ------ + ValueError + If zarr_format is not 2 or 3. + """ + if zarr_format == 2: + return {"name": self.to_native_dtype().str, "object_codec_id": None} + elif zarr_format == 3: + return self._zarr_v3_name + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + def _check_scalar(self, data: object) -> TypeGuard[FloatLike]: + """ + Check that the input is a valid scalar value. + + Parameters + ---------- + data : object + The input to check. + + Returns + ------- + TypeGuard[FloatLike] + True if the input is a valid scalar value, False otherwise. + """ + if isinstance(data, str): + # Only accept strings that are valid float representations (e.g. "NaN", "inf"). + # Plain strings that cannot be converted should return False so that cast_scalar + # raises TypeError rather than a confusing ValueError. + try: + self.to_native_dtype().type(data) + except (ValueError, OverflowError): + return False + else: + return True + return isinstance(data, FloatLike) + + def _cast_scalar_unchecked(self, data: FloatLike) -> Scalar: + """ + Cast a scalar value to a NumPy float scalar. + + Parameters + ---------- + data : FloatLike + The scalar value to cast. + + Returns + ------- + Scalar + The NumPy float scalar. + """ + return self.to_native_dtype().type(data) # type: ignore[return-value] + + def cast_scalar(self, data: object) -> Scalar: + """ + Cast a scalar value to a NumPy float scalar. + + Parameters + ---------- + data : object + The scalar value to cast. + + Returns + ------- + Scalar + The NumPy float scalar. + """ + if self._check_scalar(data): + return self._cast_scalar_unchecked(data) + msg = ( + f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the " + f"data type {self}." + ) + raise TypeError(msg) + + def default_scalar(self) -> Scalar: + """ + Get the default value, which is 0 cast to this zdtype. + + Returns + ------- + Scalar + The default value. + """ + return self._cast_scalar_unchecked(0) + + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> Scalar: + """ + Read a JSON-serializable value as a NumPy float scalar. + + Parameters + ---------- + data : JSON + The JSON-serializable value. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + Scalar + The NumPy float scalar. + """ + if zarr_format == 2: + if check_json_float_v2(data): + return self._cast_scalar_unchecked(float_from_json_v2(data)) + elif check_json_floatish_str(data): + return self._cast_scalar_unchecked(float(data)) + else: + raise TypeError( + f"Invalid type: {data}. Expected a float or a special string encoding of a float." + ) + elif zarr_format == 3: + if check_json_float_v3(data): + return self._cast_scalar_unchecked(float_from_json_v3(data)) + elif check_json_floatish_str(data): + return self._cast_scalar_unchecked(float(data)) + else: + raise TypeError( + f"Invalid type: {data}. Expected a float or a special string encoding of a float." + ) + else: + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> float | str: + """ + Convert an object to a JSON-serializable float. + + Parameters + ---------- + data : _BaseScalar + The value to convert. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + JSON + The JSON-serializable form of the float, which is potentially a number or a string. + See the zarr specifications for details on the JSON encoding for floats. + """ + if zarr_format == 2: + return float_to_json_v2(self.cast_scalar(data)) + elif zarr_format == 3: + return float_to_json_v3(self.cast_scalar(data)) + else: + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + +@dataclass(frozen=True, kw_only=True) +class Float16(BaseFloat[np.dtypes.Float16DType, np.float16]): + """ + A Zarr data type for arrays containing 16-bit floating point numbers. + + Wraps the [`np.dtypes.Float16DType`][numpy.dtypes.Float16DType] data type. Scalars for this data type are instances + of [`np.float16`][numpy.float16]. + + Attributes + ---------- + dtype_cls : Type[np.dtypes.Float16DType] + The NumPy dtype class for this data type. + + References + ---------- + This class implements the float16 data type defined in Zarr V2 and V3. + + See the [Zarr V2](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding) and [Zarr V3](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v3/data-types/index.rst) specification documents for details. + """ + + dtype_cls = np.dtypes.Float16DType + _zarr_v3_name = "float16" + _zarr_v2_names: ClassVar[tuple[Literal[">f2"], Literal["f2", " int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return 2 + + +@dataclass(frozen=True, kw_only=True) +class Float32(BaseFloat[np.dtypes.Float32DType, np.float32]): + """ + A Zarr data type for arrays containing 32-bit floating point numbers. + + Wraps the [`np.dtypes.Float32DType`][numpy.dtypes.Float32DType] data type. Scalars for this data type are instances + of [`np.float32`][numpy.float32]. + + Attributes + ---------- + dtype_cls : Type[np.dtypes.Float32DType] + The NumPy dtype class for this data type. + + References + ---------- + This class implements the float32 data type defined in Zarr V2 and V3. + + See the [Zarr V2](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding) and [Zarr V3](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v3/data-types/index.rst) specification documents for details. + """ + + dtype_cls = np.dtypes.Float32DType + _zarr_v3_name = "float32" + _zarr_v2_names: ClassVar[tuple[Literal[">f4"], Literal["f4", " int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return 4 + + +@dataclass(frozen=True, kw_only=True) +class Float64(BaseFloat[np.dtypes.Float64DType, np.float64]): + """ + A Zarr data type for arrays containing 64-bit floating point numbers. + + Wraps the [`np.dtypes.Float64DType`][numpy.dtypes.Float64DType] data type. Scalars for this data type are instances + of [`np.float64`][numpy.float64]. + + Attributes + ---------- + dtype_cls : Type[np.dtypes.Float64DType] + The NumPy dtype class for this data type. + + References + ---------- + This class implements the float64 data type defined in Zarr V2 and V3. + + See the [Zarr V2](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding) and [Zarr V3](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v3/data-types/index.rst) specification documents for details. + """ + + dtype_cls = np.dtypes.Float64DType + _zarr_v3_name = "float64" + _zarr_v2_names: ClassVar[tuple[Literal[">f8"], Literal["f8", " int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return 8 diff --git a/src/zarr/core/dtype/npy/int.py b/src/zarr/core/dtype/npy/int.py new file mode 100644 index 0000000000..c18fd01dd8 --- /dev/null +++ b/src/zarr/core/dtype/npy/int.py @@ -0,0 +1,1550 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import ( + TYPE_CHECKING, + ClassVar, + Literal, + Self, + SupportsIndex, + SupportsInt, + TypeGuard, + overload, +) + +import numpy as np + +from zarr.core.dtype.common import ( + DTypeConfig_V2, + DTypeJSON, + HasEndianness, + HasItemSize, + check_dtype_spec_v2, +) +from zarr.core.dtype.npy.common import ( + check_json_int, + check_json_intish_float, + check_json_intish_str, + endianness_to_numpy_str, + get_endianness_from_numpy_dtype, +) +from zarr.core.dtype.wrapper import TBaseDType, ZDType +from zarr.errors import DataTypeValidationError + +if TYPE_CHECKING: + from zarr.core.common import JSON, ZarrFormat + +_NumpyIntDType = ( + np.dtypes.Int8DType + | np.dtypes.Int16DType + | np.dtypes.Int32DType + | np.dtypes.Int64DType + | np.dtypes.UInt8DType + | np.dtypes.UInt16DType + | np.dtypes.UInt32DType + | np.dtypes.UInt64DType +) +_NumpyIntScalar = ( + np.int8 | np.int16 | np.int32 | np.int64 | np.uint8 | np.uint16 | np.uint32 | np.uint64 +) + +IntLike = SupportsInt | SupportsIndex | bytes | str + + +@dataclass(frozen=True) +class BaseInt[ + DType: _NumpyIntDType, + Scalar: np.int8 | np.int16 | np.int32 | np.int64 | np.uint8 | np.uint16 | np.uint32 | np.uint64, +](ZDType[DType, Scalar], HasItemSize): + """ + A base class for integer data types in Zarr. + + This class provides methods for serialization and deserialization of integer types + in both Zarr v2 and v3 formats, as well as methods for checking and casting scalars. + """ + + _zarr_v2_names: ClassVar[tuple[str, ...]] + + @classmethod + def _check_json_v2(cls, data: object) -> TypeGuard[DTypeConfig_V2[str, None]]: + """ + Check that the input is a valid JSON representation of this integer data type in Zarr V2. + + This method verifies that the provided data matches the expected Zarr V2 representation + for this data type. The input data must be a mapping that contains a "name" key that is + one of the strings from cls._zarr_v2_names and an "object_codec_id" key that is None. + + Parameters + ---------- + data : object + The JSON data to check. + + Returns + ------- + TypeGuard[DTypeConfig_V2[str, None]] + True if the input is a valid representation of this class in Zarr V2, + False otherwise. + """ + + return ( + check_dtype_spec_v2(data) + and data["name"] in cls._zarr_v2_names + and data["object_codec_id"] is None + ) + + @classmethod + def _check_json_v3(cls, data: object) -> TypeGuard[str]: + """ + Check that the input is a valid JSON representation of this class in Zarr V3. + + Parameters + ---------- + data : object + The JSON data to check. + + Returns + ------- + TypeGuard[str] + True if the input is a valid representation of this class in Zarr v3, + False otherwise. + """ + return data == cls._zarr_v3_name + + def _check_scalar(self, data: object) -> TypeGuard[IntLike]: + """ + Check if the input object is of an IntLike type. + + This method verifies whether the provided data can be considered as an integer-like + value, which includes objects supporting integer conversion. + + Parameters + ---------- + data : object + The data to check. + + Returns + ------- + TypeGuard[IntLike] + True if the data is IntLike, False otherwise. + """ + + return isinstance(data, IntLike) + + def _cast_scalar_unchecked(self, data: IntLike) -> Scalar: + """ + Casts a given scalar value to the native integer scalar type without type checking. + + Parameters + ---------- + data : IntLike + The scalar value to cast. + + Returns + ------- + Scalar + The casted integer scalar of the native dtype. + """ + + return self.to_native_dtype().type(data) # type: ignore[return-value] + + def cast_scalar(self, data: object) -> Scalar: + """ + Attempt to cast a given object to a NumPy integer scalar. + + Parameters + ---------- + data : object + The data to be cast to a NumPy integer scalar. + + Returns + ------- + Scalar + The data cast as a NumPy integer scalar. + + Raises + ------ + TypeError + If the data cannot be converted to a NumPy integer scalar. + """ + + if self._check_scalar(data): + return self._cast_scalar_unchecked(data) + msg = ( + f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the " + f"data type {self}." + ) + raise TypeError(msg) + + def default_scalar(self) -> Scalar: + """ + Get the default value, which is 0 cast to this dtype. + + Returns + ------- + Scalar + The default value. + """ + return self._cast_scalar_unchecked(0) + + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> Scalar: + """ + Read a JSON-serializable value as a NumPy int scalar. + + Parameters + ---------- + data : JSON + The JSON-serializable value. + zarr_format : ZarrFormat + The Zarr format version. + + Returns + ------- + Scalar + The NumPy int scalar. + + Raises + ------ + TypeError + If the input is not a valid integer type. + """ + if check_json_int(data): + return self._cast_scalar_unchecked(data) + if check_json_intish_float(data): + return self._cast_scalar_unchecked(int(data)) + + if check_json_intish_str(data): + return self._cast_scalar_unchecked(int(data)) + + raise TypeError(f"Invalid type: {data}. Expected an integer.") + + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> int: + """ + Convert an object to a JSON serializable scalar. For the integer data types, + the JSON form is a plain integer. + + Parameters + ---------- + data : object + The value to convert. + zarr_format : ZarrFormat + The Zarr format version. + + Returns + ------- + int + The JSON-serializable form of the scalar. + """ + return int(self.cast_scalar(data)) + + +@dataclass(frozen=True, kw_only=True) +class Int8(BaseInt[np.dtypes.Int8DType, np.int8]): + """ + A Zarr data type for arrays containing 8-bit signed integers. + + Wraps the [`np.dtypes.Int8DType`][numpy.dtypes.Int8DType] data type. Scalars for this data type are + instances of [`np.int8`][numpy.int8]. + + Attributes + ---------- + dtype_cls : np.dtypes.Int8DType + The class of the underlying NumPy dtype. + + References + ---------- + This class implements the 8-bit signed integer data type defined in Zarr V2 and V3. + + See the [Zarr V2](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding) and [Zarr V3](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v3/data-types/index.rst) specification documents for details. + """ + + dtype_cls = np.dtypes.Int8DType + _zarr_v3_name: ClassVar[Literal["int8"]] = "int8" + _zarr_v2_names: ClassVar[tuple[Literal["|i1"]]] = ("|i1",) + + @classmethod + def from_native_dtype(cls, dtype: TBaseDType) -> Self: + """ + Create an Int8 from an np.dtype('int8') instance. + + Parameters + ---------- + dtype : TBaseDType + The np.dtype('int8') instance. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input data type is not a valid representation of this class Int8. + """ + if cls._check_native_dtype(dtype): + return cls() + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self: Self) -> np.dtypes.Int8DType: + """ + Convert the Int8 instance to an np.dtype('int8') instance. + + Returns + ------- + np.dtypes.Int8DType + The np.dtype('int8') instance. + """ + return self.dtype_cls() + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an Int8 from Zarr V2-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class Int8. + """ + if cls._check_json_v2(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v2_names[0]!r}" + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create an Int8 from Zarr V3-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class Int8. + """ + if cls._check_json_v3(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[Literal["|i1"], None]: ... + + @overload + def to_json(self, zarr_format: Literal[3]) -> Literal["int8"]: ... + + def to_json( + self, zarr_format: ZarrFormat + ) -> DTypeConfig_V2[Literal["|i1"], None] | Literal["int8"]: + """ + Convert the data type to a JSON-serializable form. + + Parameters + ---------- + zarr_format : ZarrFormat + The Zarr format version. + + Returns + ------- + ``DTypeConfig_V2[Literal["|i1"], None] | Literal["int8"]`` + The JSON-serializable representation of the data type. + + Raises + ------ + ValueError + If the zarr_format is not 2 or 3. + """ + if zarr_format == 2: + return {"name": self._zarr_v2_names[0], "object_codec_id": None} + elif zarr_format == 3: + return self._zarr_v3_name + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + @property + def item_size(self) -> int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return 1 + + +@dataclass(frozen=True, kw_only=True) +class UInt8(BaseInt[np.dtypes.UInt8DType, np.uint8]): + """ + A Zarr data type for arrays containing 8-bit unsigned integers. + + Wraps the [`np.dtypes.UInt8DType`][numpy.dtypes.UInt8DType] data type. Scalars for this data type are instances of [`np.uint8`][numpy.uint8]. + + Attributes + ---------- + dtype_cls : np.dtypes.UInt8DType + The class of the underlying NumPy dtype. + + References + ---------- + This class implements the 8-bit unsigned integer data type defined in Zarr V2 and V3. + + See the [Zarr V2](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding) and [Zarr V3](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v3/data-types/index.rst) specification documents for details. + """ + + dtype_cls = np.dtypes.UInt8DType + _zarr_v3_name: ClassVar[Literal["uint8"]] = "uint8" + _zarr_v2_names: ClassVar[tuple[Literal["|u1"]]] = ("|u1",) + + @classmethod + def from_native_dtype(cls, dtype: TBaseDType) -> Self: + """ + Create a UInt8 from an np.dtype('uint8') instance. + """ + if cls._check_native_dtype(dtype): + return cls() + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self: Self) -> np.dtypes.UInt8DType: + """ + Create a NumPy unsigned 8-bit integer dtype instance from this UInt8 ZDType. + + Returns + ------- + np.dtypes.UInt8DType + The NumPy unsigned 8-bit integer dtype. + """ + + return self.dtype_cls() + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this data type from Zarr V2-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class. + """ + + if cls._check_json_v2(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v2_names[0]!r}" + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this data type from Zarr V3-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class. + """ + if cls._check_json_v3(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[Literal["|u1"], None]: ... + + @overload + def to_json(self, zarr_format: Literal[3]) -> Literal["uint8"]: ... + + def to_json( + self, zarr_format: ZarrFormat + ) -> DTypeConfig_V2[Literal["|u1"], None] | Literal["uint8"]: + """ + Convert the data type to a JSON-serializable form. + + Parameters + ---------- + zarr_format : ZarrFormat + The Zarr format version. Supported values are 2 and 3. + + Returns + ------- + ``DTypeConfig_V2[Literal["|u1"], None] | Literal["uint8"]`` + The JSON-serializable representation of the data type. + + Raises + ------ + ValueError + If `zarr_format` is not 2 or 3. + """ + if zarr_format == 2: + # For Zarr format version 2, return a dictionary with the name and object codec ID. + return {"name": self._zarr_v2_names[0], "object_codec_id": None} + elif zarr_format == 3: + # For Zarr format version 3, return the v3 name as a string. + return self._zarr_v3_name + # Raise an error if the zarr_format is neither 2 nor 3. + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + @property + def item_size(self) -> int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return 1 + + +@dataclass(frozen=True, kw_only=True) +class Int16(BaseInt[np.dtypes.Int16DType, np.int16], HasEndianness): + """ + A Zarr data type for arrays containing 16-bit signed integers. + + Wraps the [`np.dtypes.Int16DType`][numpy.dtypes.Int16DType] data type. Scalars for this data type are instances of + [`np.int16`][numpy.int16]. + + Attributes + ---------- + dtype_cls : np.dtypes.Int16DType + The class of the underlying NumPy dtype. + + References + ---------- + This class implements the 16-bit signed integer data type defined in Zarr V2 and V3. + + See the [Zarr V2](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding) and [Zarr V3](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v3/data-types/index.rst) specification documents for details. + """ + + dtype_cls = np.dtypes.Int16DType + _zarr_v3_name: ClassVar[Literal["int16"]] = "int16" + _zarr_v2_names: ClassVar[tuple[Literal[">i2"], Literal["i2", " Self: + """ + Create an instance of this data type from an np.dtype('int16') instance. + + Parameters + ---------- + dtype : np.dtype + The instance of np.dtype('int16') to create from. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input data type is not an instance of np.dtype('int16'). + """ + if cls._check_native_dtype(dtype): + return cls(endianness=get_endianness_from_numpy_dtype(dtype)) + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self) -> np.dtypes.Int16DType: + """ + Convert the data type to an np.dtype('int16') instance. + + Returns + ------- + np.dtype + The np.dtype('int16') instance. + """ + byte_order = endianness_to_numpy_str(self.endianness) + # numpy 2.x stub: newbyteorder widens to base dtype, runtime preserves the concrete subclass + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[return-value] + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this data type from Zarr V2-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class. + """ + if cls._check_json_v2(data): + # Going via NumPy ensures that we get the endianness correct without + # annoying string parsing. + name = data["name"] + return cls.from_native_dtype(np.dtype(name)) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected one of the strings {cls._zarr_v2_names!r}." + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this data type from Zarr V3-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class. + """ + if cls._check_json_v3(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[Literal[">i2", " Literal["int16"]: ... + + def to_json( + self, zarr_format: ZarrFormat + ) -> DTypeConfig_V2[Literal[">i2", "i2", " int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return 2 + + +@dataclass(frozen=True, kw_only=True) +class UInt16(BaseInt[np.dtypes.UInt16DType, np.uint16], HasEndianness): + """ + A Zarr data type for arrays containing 16-bit unsigned integers. + + Wraps the [`np.dtypes.UInt16DType`][numpy.dtypes.UInt16DType] data type. Scalars for this data type are instances of + [`np.uint16`][numpy.uint16]. + + Attributes + ---------- + dtype_cls : np.dtypes.UInt16DType + The class of the underlying NumPy dtype. + + References + ---------- + This class implements the unsigned 16-bit unsigned integer data type defined in Zarr V2 and V3. + + See the [Zarr V2](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding) and [Zarr V3](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v3/data-types/index.rst) specification documents for details. + """ + + dtype_cls = np.dtypes.UInt16DType + _zarr_v3_name: ClassVar[Literal["uint16"]] = "uint16" + _zarr_v2_names: ClassVar[tuple[Literal[">u2"], Literal["u2", " Self: + """ + Create an instance of this data type from an np.dtype('uint16') instance. + + Parameters + ---------- + dtype : np.dtype + The NumPy data type. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input data type is not an instance of np.dtype('uint16'). + """ + if cls._check_native_dtype(dtype): + return cls(endianness=get_endianness_from_numpy_dtype(dtype)) + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self) -> np.dtypes.UInt16DType: + """ + Convert the data type to an np.dtype('uint16') instance. + + Returns + ------- + np.dtype + The np.dtype('uint16') instance. + """ + byte_order = endianness_to_numpy_str(self.endianness) + # numpy 2.x stub: newbyteorder widens to base dtype, runtime preserves the concrete subclass + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[return-value] + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this data type from Zarr V2-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class. + """ + if cls._check_json_v2(data): + # Going via NumPy ensures that we get the endianness correct without + # annoying string parsing. + name = data["name"] + return cls.from_native_dtype(np.dtype(name)) + msg = f"Invalid JSON representation of UInt16. Got {data!r}, expected one of the strings {cls._zarr_v2_names}." + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this data type from Zarr V3-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class. + """ + if cls._check_json_v3(data): + return cls() + msg = f"Invalid JSON representation of UInt16. Got {data!r}, expected the string {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[Literal[">u2", " Literal["uint16"]: ... + + def to_json( + self, zarr_format: ZarrFormat + ) -> DTypeConfig_V2[Literal[">u2", "u2", " int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return 2 + + +@dataclass(frozen=True, kw_only=True) +class Int32(BaseInt[np.dtypes.Int32DType, np.int32], HasEndianness): + """ + A Zarr data type for arrays containing 32-bit signed integers. + + Wraps the [`np.dtypes.Int32DType`][numpy.dtypes.Int32DType] data type. Scalars for this data type are instances of + [`np.int32`][numpy.int32]. + + Attributes + ---------- + dtype_cls : np.dtypes.Int32DType + The class of the underlying NumPy dtype. + + References + ---------- + This class implements the 32-bit signed integer data type defined in Zarr V2 and V3. + + See the [Zarr V2](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding) and [Zarr V3](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v3/data-types/index.rst) specification documents for details. + """ + + dtype_cls = np.dtypes.Int32DType + _zarr_v3_name: ClassVar[Literal["int32"]] = "int32" + _zarr_v2_names: ClassVar[tuple[Literal[">i4"], Literal["i4", " TypeGuard[np.dtypes.Int32DType]: + """ + A type guard that checks if the input is assignable to the type of ``cls.dtype_class`` + + This method is overridden for this particular data type because of a Windows-specific issue + where np.dtype('i') creates an instance of ``np.dtypes.IntDType``, rather than an + instance of ``np.dtypes.Int32DType``, even though both represent 32-bit signed integers. + + Parameters + ---------- + dtype : TDType + The dtype to check. + + Returns + ------- + Bool + True if the dtype matches, False otherwise. + """ + return super()._check_native_dtype(dtype) or dtype == np.dtypes.Int32DType() + + @classmethod + def from_native_dtype(cls: type[Self], dtype: TBaseDType) -> Self: + """ + Create an Int32 from an np.dtype('int32') instance. + + Parameters + ---------- + dtype : TBaseDType + The np.dtype('int32') instance. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class Int32. + """ + if cls._check_native_dtype(dtype): + return cls(endianness=get_endianness_from_numpy_dtype(dtype)) + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self: Self) -> np.dtypes.Int32DType: + """ + Convert the Int32 instance to an np.dtype('int32') instance. + + Returns + ------- + np.dtypes.Int32DType + The np.dtype('int32') instance. + """ + byte_order = endianness_to_numpy_str(self.endianness) + # numpy 2.x stub: newbyteorder widens to base dtype, runtime preserves the concrete subclass + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[return-value] + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an Int32 from Zarr V2-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class Int32. + """ + if cls._check_json_v2(data): + # Going via NumPy ensures that we get the endianness correct without + # annoying string parsing. + name = data["name"] + return cls.from_native_dtype(np.dtype(name)) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected one of the strings {cls._zarr_v2_names!r}." + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create an Int32 from Zarr V3-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class Int32. + """ + if cls._check_json_v3(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[Literal[">i4", " Literal["int32"]: ... + + def to_json( + self, zarr_format: ZarrFormat + ) -> DTypeConfig_V2[Literal[">i4", "i4", " int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return 4 + + +@dataclass(frozen=True, kw_only=True) +class UInt32(BaseInt[np.dtypes.UInt32DType, np.uint32], HasEndianness): + """ + A Zarr data type for arrays containing 32-bit unsigned integers. + + Wraps the [`np.dtypes.UInt32DType`][numpy.dtypes.UInt32DType] data type. Scalars for this data type are instances of + [`np.uint32`][numpy.uint32]. + + Attributes + ---------- + dtype_cls : np.dtypes.UInt32DType + The class of the underlying NumPy dtype. + + References + ---------- + This class implements the 32-bit unsigned integer data type defined in Zarr V2 and V3. + + See the [Zarr V2](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding) and [Zarr V3](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v3/data-types/index.rst) specification documents for details. + """ + + dtype_cls = np.dtypes.UInt32DType + _zarr_v3_name: ClassVar[Literal["uint32"]] = "uint32" + _zarr_v2_names: ClassVar[tuple[Literal[">u4"], Literal["u4", " TypeGuard[np.dtypes.UInt32DType]: + """ + A type guard that checks if the input is assignable to the type of ``cls.dtype_class`` + + This method is overridden for this particular data type because of a Windows-specific issue + where ``np.array([1], dtype=np.uint32) & 1`` creates an instance of ``np.dtypes.UIntDType``, + rather than an instance of ``np.dtypes.UInt32DType``, even though both represent 32-bit + unsigned integers. (In contrast to ``np.dtype('i')``, ``np.dtype('u')`` raises an error.) + + Parameters + ---------- + dtype : TDType + The dtype to check. + + Returns + ------- + Bool + True if the dtype matches, False otherwise. + """ + return super()._check_native_dtype(dtype) or dtype == np.dtypes.UInt32DType() + + @classmethod + def from_native_dtype(cls, dtype: TBaseDType) -> Self: + """ + Create a UInt32 from an np.dtype('uint32') instance. + + Parameters + ---------- + dtype : TBaseDType + The NumPy data type. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input data type is not a valid representation of this class 32-bit unsigned + integer. + """ + if cls._check_native_dtype(dtype): + return cls(endianness=get_endianness_from_numpy_dtype(dtype)) + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self) -> np.dtypes.UInt32DType: + """ + Create a NumPy unsigned 32-bit integer dtype instance from this UInt32 ZDType. + + Returns + ------- + np.dtypes.UInt32DType + The NumPy unsigned 32-bit integer dtype. + """ + byte_order = endianness_to_numpy_str(self.endianness) + # numpy 2.x stub: newbyteorder widens to base dtype, runtime preserves the concrete subclass + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[return-value] + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this data type from Zarr V2-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class 32-bit unsigned + integer. + """ + if cls._check_json_v2(data): + # Going via NumPy ensures that we get the endianness correct without + # annoying string parsing. + name = data["name"] + return cls.from_native_dtype(np.dtype(name)) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected one of the strings {cls._zarr_v2_names}." + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this data type from Zarr V3-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class 32-bit unsigned + integer. + """ + if cls._check_json_v3(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[Literal[">u4", " Literal["uint32"]: ... + def to_json( + self, zarr_format: ZarrFormat + ) -> DTypeConfig_V2[Literal[">u4", "u4", " int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return 4 + + +@dataclass(frozen=True, kw_only=True) +class Int64(BaseInt[np.dtypes.Int64DType, np.int64], HasEndianness): + """ + A Zarr data type for arrays containing 64-bit signed integers. + + Wraps the [`np.dtypes.Int64DType`][numpy.dtypes.Int64DType] data type. Scalars for this data type are instances of + [`np.int64`][numpy.int64]. + + Attributes + ---------- + dtype_cls : np.dtypes.Int64DType + The class of the underlying NumPy dtype. + + References + ---------- + This class implements the 64-bit signed integer data type defined in Zarr V2 and V3. + + See the [Zarr V2](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding) and [Zarr V3](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v3/data-types/index.rst) specification documents for details. + """ + + dtype_cls = np.dtypes.Int64DType + _zarr_v3_name: ClassVar[Literal["int64"]] = "int64" + _zarr_v2_names: ClassVar[tuple[Literal[">i8"], Literal["i8", " Self: + """ + Create an Int64 from an np.dtype('int64') instance. + + Parameters + ---------- + dtype : TBaseDType + The NumPy data type. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input data type is not a valid representation of this class 64-bit signed + integer. + """ + if cls._check_native_dtype(dtype): + return cls(endianness=get_endianness_from_numpy_dtype(dtype)) + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self) -> np.dtypes.Int64DType: + """ + Create a NumPy signed 64-bit integer dtype instance from this Int64 ZDType. + + Returns + ------- + np.dtypes.Int64DType + The NumPy signed 64-bit integer dtype. + """ + byte_order = endianness_to_numpy_str(self.endianness) + # numpy 2.x stub: newbyteorder widens to base dtype, runtime preserves the concrete subclass + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[return-value] + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this data type from Zarr V2-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class 64-bit signed + integer. + """ + if cls._check_json_v2(data): + # Going via NumPy ensures that we get the endianness correct without + # annoying string parsing. + name = data["name"] + return cls.from_native_dtype(np.dtype(name)) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected one of the strings {cls._zarr_v2_names}." + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this data type from Zarr V3-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class 64-bit signed + integer. + """ + if cls._check_json_v3(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[Literal[">i8", " Literal["int64"]: ... + def to_json( + self, zarr_format: ZarrFormat + ) -> DTypeConfig_V2[Literal[">i8", "i8", " int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return 8 + + +@dataclass(frozen=True, kw_only=True) +class UInt64(BaseInt[np.dtypes.UInt64DType, np.uint64], HasEndianness): + """ + A Zarr data type for arrays containing 64-bit unsigned integers. + + Wraps the [`np.dtypes.UInt64DType`][numpy.dtypes.UInt64DType] data type. Scalars for this data type + are instances of [`np.uint64`][numpy.uint64]. + + Attributes + ---------- + dtype_cls: np.dtypes.UInt64DType + The class of the underlying NumPy dtype. + + References + ---------- + This class implements the unsigned 64-bit integer data type defined in Zarr V2 and V3. + + See the [Zarr V2](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding) and [Zarr V3](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v3/data-types/index.rst) specification documents for details. + """ + + dtype_cls = np.dtypes.UInt64DType + _zarr_v3_name: ClassVar[Literal["uint64"]] = "uint64" + _zarr_v2_names: ClassVar[tuple[Literal[">u8"], Literal["u8", " np.dtypes.UInt64DType: + """ + Convert the data type to a native NumPy dtype. + + Returns + ------- + np.dtypes.UInt64DType + The native NumPy dtype.eeeeeeeeeeeeeeeee + """ + byte_order = endianness_to_numpy_str(self.endianness) + # numpy 2.x stub: newbyteorder widens to base dtype, runtime preserves the concrete subclass + return self.dtype_cls().newbyteorder(byte_order) # type: ignore[return-value] + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this data type from Zarr V2-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class unsigned 64-bit + integer. + """ + if cls._check_json_v2(data): + # Going via NumPy ensures that we get the endianness correct without + # annoying string parsing. + name = data["name"] + return cls.from_native_dtype(np.dtype(name)) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected one of the strings {cls._zarr_v2_names}." + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this data type from Zarr V3-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class unsigned 64-bit + integer. + """ + if cls._check_json_v3(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[Literal[">u8", " Literal["uint64"]: ... + + def to_json( + self, zarr_format: ZarrFormat + ) -> DTypeConfig_V2[Literal[">u8", "u8", " Self: + """ + Create an instance of this data type from a native NumPy dtype. + + Parameters + ---------- + dtype : TBaseDType + The native NumPy dtype. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input dtype is not a valid representation of this class unsigned 64-bit + integer. + """ + if cls._check_native_dtype(dtype): + return cls(endianness=get_endianness_from_numpy_dtype(dtype)) + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + @property + def item_size(self) -> int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return 8 diff --git a/src/zarr/core/dtype/npy/string.py b/src/zarr/core/dtype/npy/string.py new file mode 100644 index 0000000000..3f84e8123f --- /dev/null +++ b/src/zarr/core/dtype/npy/string.py @@ -0,0 +1,743 @@ +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import ( + TYPE_CHECKING, + ClassVar, + Literal, + Protocol, + Self, + TypedDict, + TypeGuard, + overload, + runtime_checkable, +) + +import numpy as np + +from zarr.core.common import NamedConfig +from zarr.core.dtype.common import ( + DTypeConfig_V2, + DTypeJSON, + HasEndianness, + HasItemSize, + HasLength, + HasObjectCodec, + check_dtype_spec_v2, +) +from zarr.core.dtype.npy.common import ( + check_json_str, + endianness_to_numpy_str, + get_endianness_from_numpy_dtype, +) +from zarr.core.dtype.wrapper import ZDType +from zarr.errors import DataTypeValidationError + +if TYPE_CHECKING: + from zarr.core.common import JSON, ZarrFormat + from zarr.core.dtype.wrapper import TBaseDType + + +@runtime_checkable +class SupportsStr(Protocol): + def __str__(self) -> str: ... + + +class LengthBytesConfig(TypedDict): + """ + Configuration for a fixed-length string data type in Zarr V3. + + Attributes + ---------- + length_bytes : int + The length in bytes of the data associated with this configuration. + """ + + length_bytes: int + + +class FixedLengthUTF32JSON_V2(DTypeConfig_V2[str, None]): + """ + A wrapper around the JSON representation of the ``FixedLengthUTF32`` data type in Zarr V2. + + The ``name`` field of this class contains the value that would appear under the + ``dtype`` field in Zarr V2 array metadata. + + References + ---------- + The structure of the ``name`` field is defined in the Zarr V2 + [specification document](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding). + + Examples + -------- + + ```python + { + "name": " None: + """ + We don't allow instances of this class with length less than 1 because there is no way such + a data type can contain actual data. + """ + if self.length < 1: + raise ValueError(f"length must be >= 1, got {self.length}.") + + @classmethod + def from_native_dtype(cls, dtype: TBaseDType) -> Self: + """ + Create a FixedLengthUTF32 from a NumPy data type. + + Parameters + ---------- + dtype : TBaseDType + The NumPy data type. + + Returns + ------- + Self + An instance of this data type. + """ + if cls._check_native_dtype(dtype): + endianness = get_endianness_from_numpy_dtype(dtype) + return cls( + length=dtype.itemsize // (cls.code_point_bytes), + endianness=endianness, + ) + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self) -> np.dtypes.StrDType[int]: + """ + Convert the FixedLengthUTF32 instance to a NumPy data type. + + Returns + ------- + np.dtypes.StrDType[int] + The NumPy data type. + """ + byte_order = endianness_to_numpy_str(self.endianness) + # numpy 2.x stub: newbyteorder widens to base dtype, runtime preserves the concrete subclass + return self.dtype_cls(self.length).newbyteorder(byte_order) # type: ignore[return-value] + + @classmethod + def _check_json_v2(cls, data: DTypeJSON) -> TypeGuard[FixedLengthUTF32JSON_V2]: + """ + Check that the input is a valid JSON representation of a NumPy U dtype. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + TypeGuard[FixedLengthUTF32JSON_V2] + Whether the input is a valid JSON representation of a NumPy U dtype. + """ + return ( + check_dtype_spec_v2(data) + and isinstance(data["name"], str) + and re.match(r"^[><]U\d+$", data["name"]) is not None + and data["object_codec_id"] is None + ) + + @classmethod + def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[FixedLengthUTF32JSON_V3]: + """ + Check that the input is a valid JSON representation of this class in Zarr V3. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + TypeGuard[FixedLengthUTF32JSONV3] + Whether the input is a valid JSON representation of a NumPy U dtype. + """ + return ( + isinstance(data, dict) + and set(data.keys()) == {"name", "configuration"} + and data["name"] == cls._zarr_v3_name + and "configuration" in data + and isinstance(data["configuration"], dict) + and set(data["configuration"].keys()) == {"length_bytes"} + and isinstance(data["configuration"]["length_bytes"], int) + ) + + @overload + def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[str, None]: ... + + @overload + def to_json(self, zarr_format: Literal[3]) -> FixedLengthUTF32JSON_V3: ... + + def to_json( + self, zarr_format: ZarrFormat + ) -> DTypeConfig_V2[str, None] | FixedLengthUTF32JSON_V3: + """ + Convert the FixedLengthUTF32 instance to a JSON representation. + + Parameters + ---------- + zarr_format : ZarrFormat + The Zarr format to use. + + Returns + ------- + DTypeConfig_V2[str, None] | FixedLengthUTF32JSON_V3 + The JSON representation of the data type. + """ + if zarr_format == 2: + return {"name": self.to_native_dtype().str, "object_codec_id": None} + elif zarr_format == 3: + return { + "name": self._zarr_v3_name, + "configuration": {"length_bytes": self.length * self.code_point_bytes}, + } + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create a FixedLengthUTF32 from a JSON representation of a NumPy U dtype. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + """ + if cls._check_json_v2(data): + # Construct the NumPy dtype instead of string parsing. + name = data["name"] + return cls.from_native_dtype(np.dtype(name)) + raise DataTypeValidationError( + f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected a string representation of a NumPy U dtype." + ) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create a FixedLengthUTF32 from a JSON representation of a NumPy U dtype. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + Self + An instance of this data type. + """ + if cls._check_json_v3(data): + return cls(length=data["configuration"]["length_bytes"] // cls.code_point_bytes) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected {cls._zarr_v3_name}." + raise DataTypeValidationError(msg) + + def default_scalar(self) -> np.str_: + """ + Return the default scalar value for this data type. + + Returns + ------- + ``np.str_`` + The default scalar value. + """ + return np.str_("") + + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> str: + """ + Convert the scalar value to a JSON representation. + + Parameters + ---------- + data : object + The scalar value. + zarr_format : ZarrFormat + The Zarr format to use. + + Returns + ------- + str + The JSON representation of the scalar value. + """ + return str(data) + + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.str_: + """ + Convert the JSON representation of a scalar value to the native scalar value. + + Parameters + ---------- + data : JSON + The JSON data. + zarr_format : ZarrFormat + The Zarr format to use. + + Returns + ------- + ``np.str_`` + The native scalar value. + """ + if check_json_str(data): + return self.to_native_dtype().type(data) + raise TypeError(f"Invalid type: {data}. Expected a string.") # pragma: no cover + + def _check_scalar(self, data: object) -> TypeGuard[SupportsStr]: + """ + Check that the input is a valid scalar value for this data type. + + Parameters + ---------- + data : object + The scalar value. + + Returns + ------- + TypeGuard[SupportsStr] + Whether the input is a valid scalar value for this data type. + """ + # this is generous for backwards compatibility + return isinstance(data, SupportsStr) + + def cast_scalar(self, data: object) -> np.str_: + """ + Cast the scalar value to the native scalar value. + + Parameters + ---------- + data : object + The scalar value. + + Returns + ------- + ``np.str_`` + The native scalar value. + """ + if self._check_scalar(data): + # We explicitly truncate before casting because of the following NumPy behavior: + # >>> x = np.dtype('U3').type('hello world') + # >>> x + # np.str_('hello world') + # >>> x.dtype + # dtype('U11') + + return self.to_native_dtype().type(str(data)[: self.length]) + + msg = ( # pragma: no cover + f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the " + f"data type {self}." + ) + raise TypeError(msg) # pragma: no-cover + + @property + def item_size(self) -> int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return self.length * self.code_point_bytes + + +def check_vlen_string_json_scalar(data: object) -> TypeGuard[int | str | float]: + """ + Check if the input is a valid JSON scalar for a variable-length string. + + This function is generous for backwards compatibility, as Zarr Python v2 would use ints for + variable-length string fill values. + + Parameters + ---------- + data : object + The JSON value to check. + + Returns + ------- + TypeGuard[int | str | float] + True if the input is a valid scalar for a variable-length string. + """ + return isinstance(data, int | str | float) + + +class VariableLengthUTF8JSON_V2(DTypeConfig_V2[Literal["|O"], Literal["vlen-utf8"]]): + """ + A wrapper around the JSON representation of the ``VariableLengthUTF8`` data type in Zarr V2. + + The ``name`` field of this class contains the value that would appear under the + ``dtype`` field in Zarr V2 array metadata. The ``object_codec_id`` field is always ``"vlen-utf8"``. + + References + ---------- + The structure of the ``name`` field is defined in the Zarr V2 + [specification document](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding). + + + Examples + -------- + ```python + { + "name": "|O", + "object_codec_id": "vlen-utf8" + } + ``` + """ + + +@dataclass(frozen=True, kw_only=True) +class VariableLengthUTF8(ZDType[np.dtypes.StringDType, str], HasObjectCodec): # type: ignore[type-var] + """ + A Zarr data type for arrays containing variable-length UTF-8 strings. + + Wraps the ``np.dtypes.StringDType`` data type. Scalars for this data type are instances + of ``str``. + + + Attributes + ---------- + dtype_cls : Type[np.dtypes.StringDType] + The NumPy dtype class for this data type. + _zarr_v3_name : ClassVar[Literal["variable_length_utf8"]] = "variable_length_utf8" + The name of this data type in Zarr V3. + object_codec_id : ClassVar[Literal["vlen-utf8"]] = "vlen-utf8" + The object codec ID for this data type. + + References + ---------- + https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/string + + """ + + dtype_cls = np.dtypes.StringDType # type: ignore[assignment] + _zarr_v3_name: ClassVar[Literal["string"]] = "string" + object_codec_id: ClassVar[Literal["vlen-utf8"]] = "vlen-utf8" + + @classmethod + def from_native_dtype(cls, dtype: TBaseDType) -> Self: + """ + Create an instance of this data type from a compatible NumPy data type. + We reject NumPy StringDType instances that have the `na_object` field set, + because this is not representable by the Zarr `string` data type. + + Parameters + ---------- + dtype : TBaseDType + The native data type. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input is not compatible with this data type. + ValueError + If the input is `numpy.dtypes.StringDType` and has `na_object` set. + """ + if cls._check_native_dtype(dtype): + if hasattr(dtype, "na_object"): + msg = ( + f"Zarr data type resolution from {dtype} failed. " + "Attempted to resolve a zarr data type from a `numpy.dtypes.StringDType` " + "with `na_object` set, which is not supported." + ) + raise ValueError(msg) + return cls() + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self) -> np.dtypes.StringDType: + """ + Create a NumPy string dtype from this VariableLengthUTF8 ZDType. + + Returns + ------- + np.dtypes.StringDType + The NumPy string dtype. + """ + return self.dtype_cls() + + @classmethod + def _check_json_v2( + cls, + data: DTypeJSON, + ) -> TypeGuard[VariableLengthUTF8JSON_V2]: + """ + "Check if the input is a valid JSON representation of a variable-length UTF-8 string dtype + for Zarr v2." + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + ``TypeGuard[VariableLengthUTF8JSON_V2]`` + Whether the input is a valid JSON representation of a NumPy "object" data type, and that the + object codec id is appropriate for variable-length UTF-8 strings. + """ + return ( + check_dtype_spec_v2(data) + and data["name"] == "|O" + and data["object_codec_id"] == cls.object_codec_id + ) + + @classmethod + def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[Literal["variable_length_utf8"]]: + """ + Check that the input is a valid JSON representation of this class in Zarr V3. + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + TypeGuard[Literal["variable_length_utf8"]] + Whether the input is a valid JSON representation of a variable length UTF-8 string + data type. + """ + return data == cls._zarr_v3_name + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this class from a JSON representation of a NumPy "object" dtype. + + Parameters + ---------- + data : DTypeJSON + The JSON data to create an instance from. + + Returns + ------- + Self + An instance of this data type. + """ + if cls._check_json_v2(data): + return cls() + msg = ( + f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string '|O'" + ) + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this class from a JSON representation of a variable length UTF-8 + string data type. + + Parameters + ---------- + data : DTypeJSON + The JSON data to create an instance from. + + Returns + ------- + Self + An instance of this data type. + """ + if cls._check_json_v3(data): + return cls() + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected {cls._zarr_v3_name}." + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> VariableLengthUTF8JSON_V2: ... + @overload + def to_json(self, zarr_format: Literal[3]) -> Literal["string"]: ... + + def to_json(self, zarr_format: ZarrFormat) -> VariableLengthUTF8JSON_V2 | Literal["string"]: + """ + Convert this data type to a JSON representation. + + Parameters + ---------- + zarr_format : int + The zarr format to use for the JSON representation. + + Returns + ------- + ``VariableLengthUTF8JSON_V2 | Literal["string"]`` + The JSON representation of this data type. + """ + if zarr_format == 2: + return {"name": "|O", "object_codec_id": self.object_codec_id} + elif zarr_format == 3: + return self._zarr_v3_name + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + def default_scalar(self) -> str: + """ + Return the default scalar value for this data type. + + Returns + ------- + str + The default scalar value. + """ + return "" + + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> str: + """ + Convert a scalar value to a JSON representation. + + Parameters + ---------- + data : object + The scalar value to convert. + zarr_format : int + The zarr format to use for the JSON representation. + + Returns + ------- + str + The JSON representation of the scalar value. + """ + if self._check_scalar(data): + return self._cast_scalar_unchecked(data) + raise TypeError(f"Invalid type: {data}. Expected a string.") + + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> str: + """ + Convert a JSON representation of a scalar value to the native scalar type. + + Parameters + ---------- + data : JSON + The JSON representation of the scalar value. + zarr_format : int + The zarr format to use for the JSON representation. + + Returns + ------- + str + The native scalar type of the scalar value. + """ + if not check_vlen_string_json_scalar(data): + raise TypeError(f"Invalid type: {data}. Expected a string or number.") + return str(data) + + def _check_scalar(self, data: object) -> TypeGuard[SupportsStr]: + """ + Check that the input is a valid scalar value for this data type. + + Parameters + ---------- + data : object + The scalar value to check. + + Returns + ------- + TypeGuard[SupportsStr] + Whether the input is a valid scalar value for this data type. + """ + return isinstance(data, SupportsStr) + + def _cast_scalar_unchecked(self, data: SupportsStr) -> str: + """ + Cast a scalar value to a string. + + Parameters + ---------- + data : object + The scalar value to cast. + + Returns + ------- + str + The string representation of the scalar value. + """ + return str(data) + + def cast_scalar(self, data: object) -> str: + """ + Cast an object to a string. + + Parameters + ---------- + data : object + The value to cast. + + Returns + ------- + str + The input cast to str. + """ + if self._check_scalar(data): + return self._cast_scalar_unchecked(data) + msg = ( # pragma: no cover + f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the " + f"data type {self}." + ) + raise TypeError(msg) # pragma: no cover diff --git a/src/zarr/core/dtype/npy/structured.py b/src/zarr/core/dtype/npy/structured.py new file mode 100644 index 0000000000..dcc523d1d2 --- /dev/null +++ b/src/zarr/core/dtype/npy/structured.py @@ -0,0 +1,669 @@ +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +from typing import TYPE_CHECKING, ClassVar, Literal, Self, TypeGuard, cast, overload + +import numpy as np + +from zarr.core.common import NamedConfig +from zarr.core.dtype.common import ( + DTypeConfig_V2, + DTypeJSON, + HasItemSize, + StructuredName_V2, + check_dtype_spec_v2, + check_structured_dtype_name_v2, + v3_unstable_dtype_warning, +) +from zarr.core.dtype.npy.common import ( + bytes_from_json, + bytes_to_json, + check_json_str, +) +from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType +from zarr.errors import DataTypeValidationError + +if TYPE_CHECKING: + from zarr.core.common import JSON, ZarrFormat + +StructuredScalarLike = list[object] | tuple[object, ...] | bytes | int + + +class StructuredJSON_V2(DTypeConfig_V2[StructuredName_V2, None]): + """ + A wrapper around the JSON representation of the ``Structured`` data type in Zarr V2. + + The ``name`` field is a sequence of sequences, where each inner sequence has two values: + the field name and the data type name for that field (which could be another sequence). + The data type names are strings, and the object codec ID is always None. + + References + ---------- + The structure of the ``name`` field is defined in the Zarr V2 + [specification document](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding). + + Examples + -------- + ```python + { + "name": [ + ["f0", " None: + if len(self.fields) < 1: + raise ValueError(f"must have at least one field. Got {self.fields!r}") + + @classmethod + def _check_native_dtype(cls, dtype: TBaseDType) -> TypeGuard[np.dtypes.VoidDType[int]]: + """ + Check that this dtype is a numpy structured dtype + + Parameters + ---------- + dtype : np.dtypes.DTypeLike + The dtype to check. + + Returns + ------- + TypeGuard[np.dtypes.VoidDType] + True if the dtype matches, False otherwise. + """ + return isinstance(dtype, cls.dtype_cls) and dtype.fields is not None + + @classmethod + def from_native_dtype(cls, dtype: TBaseDType) -> Self: + """ + Create a Structured ZDType from a native NumPy data type. + + Parameters + ---------- + dtype : TBaseDType + The native data type. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input data type is not an instance of np.dtypes.VoidDType with a non-null + ``fields`` attribute. + + Notes + ----- + This method attempts to resolve the fields of the structured dtype using the data type + registry. + """ + from zarr.core.dtype import get_data_type_from_native_dtype + + fields: list[tuple[str, ZDType[TBaseDType, TBaseScalar]]] = [] + if cls._check_native_dtype(dtype): + # fields of a structured numpy dtype are either 2-tuples or 3-tuples. we only + # care about the first element in either case. + for key, (dtype_instance, *_) in dtype.fields.items(): # type: ignore[union-attr] + dtype_wrapped = get_data_type_from_native_dtype(dtype_instance) + fields.append((key, dtype_wrapped)) + + return cls(fields=tuple(fields)) + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self) -> np.dtypes.VoidDType[int]: + """ + Convert the structured Zarr data type to a native NumPy void dtype. + + This method constructs a NumPy dtype with fields corresponding to the + fields of the structured Zarr data type, by converting each field's + data type to its native dtype representation. + + Returns + ------- + np.dtypes.VoidDType[int] + The native NumPy void dtype representing the structured data type. + """ + + return cast( + "np.dtypes.VoidDType[int]", + np.dtype([(key, dtype.to_native_dtype()) for (key, dtype) in self.fields]), + ) + + @classmethod + def _check_json_v2( + cls, + data: DTypeJSON, + ) -> TypeGuard[StructuredJSON_V2]: + """ + Check if the input is a valid JSON representation of a Structured data type + for Zarr V2. + + The input data must be a mapping that contains a "name" key that is not a str, + and an "object_codec_id" key that is None. + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + TypeGuard[StructuredJSON_V2] + True if the input is a valid JSON representation of a Structured data type + for Zarr V2, False otherwise. + """ + return ( + check_dtype_spec_v2(data) + and not isinstance(data["name"], str) + and check_structured_dtype_name_v2(data["name"]) + and data["object_codec_id"] is None + ) + + @classmethod + def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[StructuredJSON_V3]: + """ + Check that the input is a valid JSON representation of this class in Zarr V3. + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + TypeGuard[StructuredJSON_V3] + True if the input is a valid JSON representation of a structured data type for Zarr V3, + False otherwise. + """ + return ( + isinstance(data, dict) + and set(data.keys()) == {"name", "configuration"} + and data["name"] == cls._zarr_v3_name + and isinstance(data["configuration"], dict) + and set(data["configuration"].keys()) == {"fields"} + ) + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + # avoid circular import + from zarr.core.dtype import get_data_type_from_json + + if cls._check_json_v2(data): + # structured dtypes are constructed directly from a list of lists + # note that we do not handle the object codec here! this will prevent structured + # dtypes from containing object dtypes. + name = data["name"] + return cls( + fields=tuple( # type: ignore[str-unpack] + ( # type: ignore[misc] + f_name, + get_data_type_from_json( + {"name": f_dtype, "object_codec_id": None}, zarr_format=2 + ), + ) + for f_name, f_dtype in name + ) + ) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected a JSON array of arrays" + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + from zarr.core.dtype import get_data_type_from_json + + if cls._check_json_v3(data): + config = data["configuration"] + meta_fields = config["fields"] + return cls( + fields=tuple( + (f_name, get_data_type_from_json(f_dtype, zarr_format=3)) # type: ignore[misc] + for f_name, f_dtype in meta_fields + ) + ) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected a JSON object with the key {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> StructuredJSON_V2: ... + + @overload + def to_json(self, zarr_format: Literal[3]) -> StructuredJSON_V3: ... + + def to_json(self, zarr_format: ZarrFormat) -> StructuredJSON_V2 | StructuredJSON_V3: + """ + Convert the structured data type to a JSON-serializable form. + + Parameters + ---------- + zarr_format : ZarrFormat + The Zarr format version. Accepted values are 2 and 3. + + Returns + ------- + StructuredJSON_V2 | StructuredJSON_V3 + The JSON representation of the structured data type. + + Raises + ------ + ValueError + If the zarr_format is not 2 or 3. + """ + if zarr_format == 2: + fields = [ + [f_name, f_dtype.to_json(zarr_format=zarr_format)["name"]] + for f_name, f_dtype in self.fields + ] + return {"name": fields, "object_codec_id": None} + elif zarr_format == 3: + v3_unstable_dtype_warning(self) + fields = [ + [f_name, f_dtype.to_json(zarr_format=zarr_format)] # type: ignore[list-item] + for f_name, f_dtype in self.fields + ] + base_dict = { + "name": self._zarr_v3_name, + "configuration": {"fields": fields}, + } + return cast("StructuredJSON_V3", base_dict) + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + def _check_scalar(self, data: object) -> TypeGuard[StructuredScalarLike]: + # TODO: implement something more precise here! + """ + Check that the input is a valid scalar value for this structured data type. + + Parameters + ---------- + data : object + The scalar value to check. + + Returns + ------- + TypeGuard[StructuredScalarLike] + Whether the input is a valid scalar value for this structured data type. + """ + return isinstance(data, (bytes, list, tuple, int, np.void)) + + def _cast_scalar_unchecked(self, data: StructuredScalarLike) -> np.void: + """ + Cast a python object to a numpy structured scalar without type checking. + + Parameters + ---------- + data : StructuredScalarLike + The data to cast. + + Returns + ------- + np.void + The casted data as a numpy structured scalar. + + Notes + ----- + This method does not perform any type checking. + The input data must be castable to a numpy structured scalar. + + """ + na_dtype = self.to_native_dtype() + if isinstance(data, bytes): + res = np.frombuffer(data, dtype=na_dtype)[0] + elif isinstance(data, list | tuple): + res = np.array([tuple(data)], dtype=na_dtype)[0] + else: + res = np.array([data], dtype=na_dtype)[0] + return cast("np.void", res) + + def cast_scalar(self, data: object) -> np.void: + """ + Cast a Python object to a NumPy structured scalar. + + This function attempts to cast the provided data to a NumPy structured scalar. + If the data is compatible with the structured scalar type, it is cast without + type checking. Otherwise, a TypeError is raised. + + Parameters + ---------- + data : object + The data to be cast to a NumPy structured scalar. + + Returns + ------- + np.void + The data cast as a NumPy structured scalar. + + Raises + ------ + TypeError + If the data cannot be converted to a NumPy structured scalar. + """ + + if self._check_scalar(data): + return self._cast_scalar_unchecked(data) + msg = ( + f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the " + f"data type {self}." + ) + raise TypeError(msg) + + def default_scalar(self) -> np.void: + """ + Get the default scalar value for this structured data type. + + Returns + ------- + np.void + The default scalar value, which is the scalar representation of 0 + cast to this structured data type. + """ + + return self._cast_scalar_unchecked(0) + + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.void: + """ + Read a JSON-serializable value as a NumPy structured scalar. + + Parameters + ---------- + data : JSON + The JSON-serializable value. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + np.void + The NumPy structured scalar. + + Raises + ------ + TypeError + If the input is not a base64-encoded string. + """ + if check_json_str(data): + as_bytes = bytes_from_json(data, zarr_format=zarr_format) + dtype = self.to_native_dtype() + return cast("np.void", np.array([as_bytes]).view(dtype)[0]) + raise TypeError(f"Invalid type: {data}. Expected a string.") + + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> str | dict[str, JSON]: + """ + Convert a scalar to a JSON-serializable string representation. + + Parameters + ---------- + data : object + The scalar to convert. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + str | dict[str, JSON] + A string representation of the scalar, which is a base64-encoded + string of the bytes that make up the scalar. Subclasses may return + a dict for V3 format. + """ + return bytes_to_json(self.cast_scalar(data).tobytes(), zarr_format) + + @property + def item_size(self) -> int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return self.to_native_dtype().itemsize + + def has_multi_byte_fields(self) -> bool: + """ + Check if this structured dtype has any fields with item_size > 1. + + Returns + ------- + bool + True if any field has item_size > 1, False otherwise. + """ + return any( + isinstance(field_dtype, HasItemSize) and field_dtype.item_size > 1 + for _, field_dtype in self.fields + ) + + +@dataclass(frozen=True, kw_only=True) +class Struct(Structured): + """ + A Zarr data type for arrays containing structured scalars, AKA "record arrays". + + Wraps the NumPy `np.dtypes.VoidDType` if the data type has fields. Scalars for this data + type are instances of `np.void`, with a ``fields`` attribute. + + This is the canonical data type registered for structured arrays. It reads both + the canonical ``"struct"`` format (object-style fields) and the legacy ``"structured"`` + format (tuple-style fields), but always writes the canonical ``"struct"`` format. + + Attributes + ---------- + fields : Sequence[tuple[str, ZDType]] + The fields of the structured dtype. + + References + ---------- + The Zarr V3 specification for this data type is defined in the zarr-extensions repository: + https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/struct + + The Zarr V2 data type specification can be found [here](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding). + """ + + _zarr_v3_name: ClassVar[Literal["struct"]] = "struct" # type: ignore[assignment] + + @classmethod + def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[StructJSON_V3]: # type: ignore[override] + return ( + isinstance(data, dict) + and set(data.keys()) == {"name", "configuration"} + and data["name"] in ("struct", "structured") + and isinstance(data["configuration"], dict) + and set(data["configuration"].keys()) == {"fields"} + ) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + from zarr.core.dtype import get_data_type_from_json + + if cls._check_json_v3(data): + config = data["configuration"] + meta_fields = config["fields"] + parsed_fields: list[tuple[str, ZDType[TBaseDType, TBaseScalar]]] = [] + for field in meta_fields: + if isinstance(field, dict): + f_name = field["name"] + f_dtype = field["data_type"] + else: + # Legacy tuple-style field format from "structured" dtype + f_name, f_dtype = field # type: ignore[unreachable] + parsed_fields.append((f_name, get_data_type_from_json(f_dtype, zarr_format=3))) # type: ignore[arg-type] + return cls(fields=tuple(parsed_fields)) + msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected a JSON object with the key {cls._zarr_v3_name!r}" + raise DataTypeValidationError(msg) + + @overload # type: ignore[override] + def to_json(self, zarr_format: Literal[2]) -> StructuredJSON_V2: ... + + @overload + def to_json(self, zarr_format: Literal[3]) -> StructJSON_V3: ... + + def to_json(self, zarr_format: ZarrFormat) -> StructuredJSON_V2 | StructJSON_V3: + if zarr_format == 2: + fields_v2 = [ + [f_name, f_dtype.to_json(zarr_format=zarr_format)["name"]] + for f_name, f_dtype in self.fields + ] + return {"name": fields_v2, "object_codec_id": None} + elif zarr_format == 3: + # The "struct" data type has a stable Zarr V3 specification + # (https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/struct), + # so unlike the legacy "structured" alias it does not emit an unstable-spec warning. + fields_v3 = [ + {"name": f_name, "data_type": f_dtype.to_json(zarr_format=zarr_format)} + for f_name, f_dtype in self.fields + ] + return cast( + "StructJSON_V3", + {"name": self._zarr_v3_name, "configuration": {"fields": fields_v3}}, + ) + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.void: + """ + Read a JSON-serializable value as a NumPy structured scalar. + + Parameters + ---------- + data : JSON + The JSON-serializable value. Can be either: + - A dict mapping field names to values (primary format for V3) + - A base64-encoded string (legacy format, for backward compatibility) + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + np.void + The NumPy structured scalar. + + Raises + ------ + TypeError + If the input is not a dict or base64-encoded string. + """ + if isinstance(data, dict): + field_values = [] + for field_name, field_dtype in self.fields: + if field_name in data: + field_values.append( + field_dtype.from_json_scalar(data[field_name], zarr_format=zarr_format) + ) + else: + field_values.append(field_dtype.default_scalar()) + return self._cast_scalar_unchecked(tuple(field_values)) + elif check_json_str(data): + as_bytes = bytes_from_json(data, zarr_format=zarr_format) + dtype = self.to_native_dtype() + return cast("np.void", np.array([as_bytes]).view(dtype)[0]) + raise TypeError(f"Invalid type: {data}. Expected a dict or base64-encoded string.") + + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> str | dict[str, JSON]: + """ + Convert a scalar to a JSON-serializable representation. + + Parameters + ---------- + data : object + The scalar to convert. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + str | dict[str, JSON] + For V2: A base64-encoded string of the bytes that make up the scalar. + For V3: A dict mapping field names to their JSON-serialized values. + """ + scalar = self.cast_scalar(data) + if zarr_format == 2: + return bytes_to_json(scalar.tobytes(), zarr_format) + result: dict[str, JSON] = {} + for field_name, field_dtype in self.fields: + result[field_name] = field_dtype.to_json_scalar( + scalar[field_name], zarr_format=zarr_format + ) + return result diff --git a/src/zarr/core/dtype/npy/time.py b/src/zarr/core/dtype/npy/time.py new file mode 100644 index 0000000000..4efa0be7bb --- /dev/null +++ b/src/zarr/core/dtype/npy/time.py @@ -0,0 +1,888 @@ +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime, timedelta +from typing import ( + TYPE_CHECKING, + ClassVar, + Literal, + Self, + TypedDict, + TypeGuard, + cast, + get_args, + overload, +) + +import numpy as np +from typing_extensions import ReadOnly + +from zarr.core.common import NamedRequiredConfig +from zarr.core.dtype.common import ( + DTypeConfig_V2, + DTypeJSON, + HasEndianness, + HasItemSize, + check_dtype_spec_v2, +) +from zarr.core.dtype.npy.common import ( + DATETIME_UNIT, + DateTimeUnit, + check_json_int, + endianness_to_numpy_str, + get_endianness_from_numpy_dtype, +) +from zarr.core.dtype.wrapper import TBaseDType, ZDType +from zarr.errors import DataTypeValidationError + +if TYPE_CHECKING: + from zarr.core.common import JSON, ZarrFormat + +TimeDeltaLike = str | int | bytes | np.timedelta64 | timedelta | None +DateTimeLike = str | int | bytes | np.datetime64 | datetime | None + + +def datetime_from_int(data: int, *, unit: DateTimeUnit, scale_factor: int) -> np.datetime64: + """ + Convert an integer to a datetime64. + + Parameters + ---------- + data : int + The integer to convert. + unit : DateTimeUnit + The unit of the datetime64. + scale_factor : int + The scale factor of the datetime64. + + Returns + ------- + numpy.datetime64 + The datetime64 value. + """ + dtype_name = f"datetime64[{scale_factor}{unit}]" + return cast("np.datetime64", np.int64(data).view(dtype_name)) + + +def datetimelike_to_int(data: np.datetime64 | np.timedelta64) -> int: + """ + Convert a datetime64 or a timedelta64 to an integer. + + Parameters + ---------- + data : np.datetime64 | numpy.timedelta64 + The value to convert. + + Returns + ------- + int + An integer representation of the scalar. + """ + return data.view(np.int64).item() + + +def check_json_time(data: JSON) -> TypeGuard[Literal["NaT"] | int]: + """ + Type guard to check if the input JSON data is the literal string "NaT" + or an integer. + """ + return check_json_int(data) or data == "NaT" + + +class TimeConfig(TypedDict): + """ + The configuration for the numpy.timedelta64 or numpy.datetime64 data type in Zarr V3. + + Attributes + ---------- + unit : ReadOnly[DateTimeUnit] + A string encoding a unit of time. + scale_factor : ReadOnly[int] + A scale factor. + + Examples + -------- + ```python + {"unit": "ms", "scale_factor": 1} + ``` + """ + + unit: ReadOnly[DateTimeUnit] + scale_factor: ReadOnly[int] + + +class DateTime64JSON_V3(NamedRequiredConfig[Literal["numpy.datetime64"], TimeConfig]): + """ + The JSON representation of the ``numpy.datetime64`` data type in Zarr V3. + + References + ---------- + This representation is defined in the ``numpy.datetime64`` + [specification document](https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/numpy.datetime64). + + Examples + -------- + ```python + { + "name": "numpy.datetime64", + "configuration": { + "unit": "ms", + "scale_factor": 1 + } + } + ``` + """ + + +class TimeDelta64JSON_V3(NamedRequiredConfig[Literal["numpy.timedelta64"], TimeConfig]): + """ + The JSON representation of the ``TimeDelta64`` data type in Zarr V3. + + References + ---------- + This representation is defined in the numpy.timedelta64 + [specification document](https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/numpy.timedelta64). + + Examples + -------- + ```python + { + "name": "numpy.timedelta64", + "configuration": { + "unit": "ms", + "scale_factor": 1 + } + } + ``` + """ + + +class TimeDelta64JSON_V2(DTypeConfig_V2[str, None]): + """ + A wrapper around the JSON representation of the ``TimeDelta64`` data type in Zarr V2. + + The ``name`` field of this class contains the value that would appear under the + ``dtype`` field in Zarr V2 array metadata. + + References + ---------- + The structure of the ``name`` field is defined in the Zarr V2 + [specification document](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding). + + + Examples + -------- + ```python + { + "name": " None: + if self.scale_factor < 1: + raise ValueError(f"scale_factor must be > 0, got {self.scale_factor}.") + if self.scale_factor >= 2**31: + raise ValueError(f"scale_factor must be < 2147483648, got {self.scale_factor}.") + if self.unit not in get_args(DateTimeUnit): + raise ValueError(f"unit must be one of {get_args(DateTimeUnit)}, got {self.unit!r}.") + + @classmethod + def from_native_dtype(cls, dtype: TBaseDType) -> Self: + """ + Create an instance of this class from a native NumPy data type. + + Parameters + ---------- + dtype : TBaseDType + The native NumPy dtype to convert. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the dtype is not a valid representation of this class. + """ + + if cls._check_native_dtype(dtype): + unit, scale_factor = np.datetime_data(dtype.name) + unit = cast("DateTimeUnit", unit) + return cls( + unit=unit, + scale_factor=scale_factor, + endianness=get_endianness_from_numpy_dtype(dtype), + ) + raise DataTypeValidationError( + f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}" + ) + + def to_native_dtype(self) -> DType: + # Numpy does not allow creating datetime64 or timedelta64 via + # np.dtypes.{dtype_name}() + # so we use np.dtype with a formatted string. + """ + Convert this data type to a NumPy temporal data type with the appropriate + unit and scale factor. + + Returns + ------- + DType + A NumPy data type object representing the time data type with + the specified unit, scale factor, and byte order. + """ + + dtype_string = f"{self._numpy_name}[{self.scale_factor}{self.unit}]" + return np.dtype(dtype_string).newbyteorder(endianness_to_numpy_str(self.endianness)) # type: ignore[return-value] + + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> int: + """ + Convert a python object to a JSON representation of a datetime64 or timedelta64 scalar. + + Parameters + ---------- + data : object + The python object to convert. + zarr_format : ZarrFormat + The Zarr format version (2 or 3). + + Returns + ------- + int + The JSON representation of the scalar. + """ + return datetimelike_to_int(data) # type: ignore[arg-type] + + @property + def item_size(self) -> int: + """ + The size of a single scalar in bytes. + + Returns + ------- + int + The size of a single scalar in bytes. + """ + return 8 + + +@dataclass(frozen=True, kw_only=True, slots=True) +class TimeDelta64(TimeDTypeBase[np.dtypes.TimeDelta64DType, np.timedelta64], HasEndianness): + """ + A Zarr data type for arrays containing NumPy TimeDelta64 data. + + Wraps the ``np.dtypesTimeDelta64DType`` data type. Scalars for this data type + are instances of `np.timedelta64`. + + Attributes + ---------- + dtype_cls : Type[np.dtypesTimeDelta64DType] + The NumPy dtype class for this data type. + scale_factor : int + The scale factor for this data type. + unit : DateTimeUnit + The unit for this data type. + + References + ---------- + The Zarr V2 representation of this data type is defined in the Zarr V2 + [specification document](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding). + + The Zarr V3 representation of this data type is defined in the ``numpy.timedelta64`` + [specification document](https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/numpy.timedelta64) + """ + + # mypy infers the type of np.dtypes.TimeDelta64DType to be + # "Callable[[Literal['Y', 'M', 'W', 'D'] | Literal['h', 'm', 's', 'ms', 'us', 'ns', 'ps', 'fs', 'as']], Never]" + dtype_cls = np.dtypes.TimeDelta64DType # type: ignore[assignment] + unit: DateTimeUnit = "generic" + scale_factor: int = 1 + _zarr_v3_name: ClassVar[Literal["numpy.timedelta64"]] = "numpy.timedelta64" + _zarr_v2_names: ClassVar[tuple[Literal[">m8"], Literal["m8", " TypeGuard[TimeDelta64JSON_V2]: + """ + Validate that the provided JSON input accurately represents a NumPy timedelta64 data type, + which could be in the form of strings like "m8[10s]". This method serves as a type + guard, helping to refine the type of unknown JSON input by confirming its adherence to the + expected format for NumPy timedelta64 data types. + + The JSON input should contain a "name" key with a value that matches the expected string + pattern for NumPy timedelta64 data types. The pattern includes an optional unit enclosed + within square brackets, following the base type identifier. + + Returns + ------- + bool + True if the JSON input is a valid representation of this class, + otherwise False. + """ + if not check_dtype_spec_v2(data): + return False + name = data["name"] + # match m[M], etc + # consider making this a standalone function + if not isinstance(name, str): + return False + if not name.startswith(cls._zarr_v2_names): + return False + if len(name) == 3: + # no unit, and + # we already checked that this string is either m8 + return True + else: + return name[4:-1].endswith(DATETIME_UNIT) and name[-1] == "]" + + @classmethod + def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[DateTime64JSON_V3]: + """ + Check that the input is a valid JSON representation of this class in Zarr V3. + + Returns + ------- + TypeGuard[DateTime64JSON_V3] + True if the JSON input is a valid representation of this class, + otherwise False. + """ + return ( + isinstance(data, dict) + and set(data.keys()) == {"name", "configuration"} + and data["name"] == cls._zarr_v3_name + and isinstance(data["configuration"], dict) + and set(data["configuration"].keys()) == {"unit", "scale_factor"} + ) + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create a TimeDelta64 from a Zarr V2-flavored JSON. + + Parameters + ---------- + data : DTypeJSON + The JSON data. + + Returns + ------- + TimeDelta64 + An instance of TimeDelta64. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class. + """ + if cls._check_json_v2(data): + name = data["name"] + return cls.from_native_dtype(np.dtype(name)) + msg = ( + f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected a string " + f"representation of an instance of {cls.dtype_cls}" + ) + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create a TimeDelta64 from a Zarr V3-flavored JSON. + + The JSON representation of a TimeDelta64 in Zarr V3 is a dict with a 'name' key + with the value 'numpy.timedelta64', and a 'configuration' key with a value of a dict + with a 'unit' key and a 'scale_factor' key. + + For example: + + ```json + { + "name": "numpy.timedelta64", + "configuration": { + "unit": "generic", + "scale_factor": 1 + } + } + ``` + + """ + if cls._check_json_v3(data): + unit = data["configuration"]["unit"] + scale_factor = data["configuration"]["scale_factor"] + return cls(unit=unit, scale_factor=scale_factor) + msg = ( + f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected a dict " + f"with a 'name' key with the value 'numpy.timedelta64', " + "and a 'configuration' key with a value of a dict with a 'unit' key and a " + "'scale_factor' key" + ) + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> TimeDelta64JSON_V2: ... + @overload + def to_json(self, zarr_format: Literal[3]) -> TimeDelta64JSON_V3: ... + + def to_json(self, zarr_format: ZarrFormat) -> TimeDelta64JSON_V2 | TimeDelta64JSON_V3: + """ + Serialize this data type to JSON. + + Parameters + ---------- + zarr_format : ZarrFormat + The Zarr format version (2 or 3). + + Returns + ------- + TimeDelta64JSON_V2 | TimeDelta64JSON_V3 + The JSON representation of the data type. + + Raises + ------ + ValueError + If the zarr_format is not 2 or 3. + """ + if zarr_format == 2: + name = self.to_native_dtype().str + return {"name": name, "object_codec_id": None} + elif zarr_format == 3: + return { + "name": self._zarr_v3_name, + "configuration": {"unit": self.unit, "scale_factor": self.scale_factor}, + } + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + def _check_scalar(self, data: object) -> TypeGuard[TimeDeltaLike]: + """ + Check if the input is a scalar of this data type. + + Parameters + ---------- + data : object + The object to check. + + Returns + ------- + TypeGuard[TimeDeltaLike] + True if the input is a scalar of this data type, False otherwise. + """ + if data is None: + return True + return isinstance(data, str | int | bytes | np.timedelta64 | timedelta) + + def _cast_scalar_unchecked(self, data: TimeDeltaLike) -> np.timedelta64: + """ + Cast the provided scalar input to a numpy timedelta64 without any type checking. + + This method assumes that the input data is already a valid scalar of this data type, + and does not perform any validation or type checks. It directly casts the input + to a numpy timedelta64 scalar using the unit and scale factor defined in the class. + + Parameters + ---------- + data : TimeDeltaLike + The scalar input data to cast. + + Returns + ------- + numpy.timedelta64 + The input data cast as a numpy timedelta64 scalar. + """ + # numpy 2.x stub: timedelta64(scalar, formatted_unit_str) is runtime-valid + # but no overload matches the dynamic f-string unit argument. + return self.to_native_dtype().type(data, f"{self.scale_factor}{self.unit}") # type: ignore[call-overload, no-any-return] + + def cast_scalar(self, data: object) -> np.timedelta64: + """ + Cast the input to a numpy timedelta64 scalar. If the input is not a scalar of this data type, + raise a TypeError. + """ + if self._check_scalar(data): + if isinstance(data, np.timedelta64) and np.isnat(data): + # numpy 2.x stub: 'generic' is a runtime-valid unit but not in the Literal overload. + return np.timedelta64("NaT", self.unit) # type: ignore[arg-type] + return self._cast_scalar_unchecked(data) + msg = ( + f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the " + f"data type {self}." + ) + raise TypeError(msg) + + def default_scalar(self) -> np.timedelta64: + """ + Return a default scalar of this data type. + + This method provides a default value for the timedelta64 scalar, which is + a 'Not-a-Time' (NaT) value. + """ + # numpy 2.x stub: 'generic' is a runtime-valid unit but not in the Literal overload. + return np.timedelta64("NaT", self.unit) # type: ignore[arg-type] + + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.timedelta64: + """ + Create a scalar of this data type from JSON input. + + Parameters + ---------- + data : JSON + The JSON representation of the scalar value. + zarr_format : int + The zarr format to use for the JSON representation. + + Returns + ------- + numpy.timedelta64 + The scalar value of this data type. + + Raises + ------ + TypeError + If the input JSON is not a valid representation of a scalar for this data type. + """ + if check_json_time(data): + # numpy 2.x stub: timedelta64(scalar, formatted_unit_str) is runtime-valid + # but no overload matches the dynamic f-string unit argument. + return self.to_native_dtype().type(data, f"{self.scale_factor}{self.unit}") # type: ignore[call-overload, no-any-return] + raise TypeError(f"Invalid type: {data}. Expected an integer.") # pragma: no cover + + +@dataclass(frozen=True, kw_only=True, slots=True) +class DateTime64(TimeDTypeBase[np.dtypes.DateTime64DType, np.datetime64], HasEndianness): + """ + A Zarr data type for arrays containing NumPy Datetime64 data. + + Wraps the ``np.dtypes.TimeDelta64DType`` data type. Scalars for this data type + are instances of ``np.datetime64``. + + Attributes + ---------- + dtype_cls : Type[np.dtypesTimeDelta64DType] + The numpy dtype class for this data type. + unit : DateTimeUnit + The unit of time for this data type. + scale_factor : int + The scale factor for the time unit. + + References + ---------- + The Zarr V2 representation of this data type is defined in the Zarr V2 + [specification document](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding). + + The Zarr V3 representation of this data type is defined in the ``numpy.datetime64`` + [specification document](https://github.com/zarr-developers/zarr-extensions/tree/main/data-types/numpy.datetime64) + """ + + dtype_cls = np.dtypes.DateTime64DType # type: ignore[assignment] + _zarr_v3_name: ClassVar[Literal["numpy.datetime64"]] = "numpy.datetime64" + _zarr_v2_names: ClassVar[tuple[Literal[">M8"], Literal["M8", " TypeGuard[DateTime64JSON_V2]: + """ + Check that the input is a valid JSON representation of this data type. + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + TypeGuard[DateTime64JSON_V2] + True if the input is a valid JSON representation of a NumPy datetime64 data type, + otherwise False. + """ + if not check_dtype_spec_v2(data): + return False + name = data["name"] + if not isinstance(name, str): + return False + if not name.startswith(cls._zarr_v2_names): + return False + if len(name) == 3: + # no unit, and + # we already checked that this string is either M8 + return True + else: + return name[4:-1].endswith(DATETIME_UNIT) and name[-1] == "]" + + @classmethod + def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[DateTime64JSON_V3]: + """ + Check that the input is a valid JSON representation of this class in Zarr V3. + + Parameters + ---------- + data : DTypeJSON + The JSON data to check. + + Returns + ------- + TypeGuard[DateTime64JSON_V3] + True if the input is a valid JSON representation of a numpy datetime64 data type in Zarr V3, False otherwise. + """ + + return ( + isinstance(data, dict) + and set(data.keys()) == {"name", "configuration"} + and data["name"] == cls._zarr_v3_name + and isinstance(data["configuration"], dict) + and set(data["configuration"].keys()) == {"unit", "scale_factor"} + ) + + @classmethod + def _from_json_v2(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this data type from a Zarr V2-flavored JSON representation. + + This method checks if the provided JSON data is a valid representation of this class. + If valid, it creates an instance using the native NumPy dtype. Otherwise, it raises a + DataTypeValidationError. + + Parameters + ---------- + data : DTypeJSON + The JSON data to parse. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class. + """ + + if cls._check_json_v2(data): + name = data["name"] + return cls.from_native_dtype(np.dtype(name)) + msg = ( + f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected a string " + f"representation of an instance of {cls.dtype_cls}" + ) + raise DataTypeValidationError(msg) + + @classmethod + def _from_json_v3(cls, data: DTypeJSON) -> Self: + """ + Create an instance of this data type from a Zarr V3-flavored JSON representation. + + This method checks if the provided JSON data is a valid representation of this class. + If valid, it creates an instance using the native NumPy dtype. Otherwise, it raises a + DataTypeValidationError. + + Parameters + ---------- + data : DTypeJSON + The JSON data to parse. + + Returns + ------- + Self + An instance of this data type. + + Raises + ------ + DataTypeValidationError + If the input JSON is not a valid representation of this class. + """ + if cls._check_json_v3(data): + unit = data["configuration"]["unit"] + scale_factor = data["configuration"]["scale_factor"] + return cls(unit=unit, scale_factor=scale_factor) + msg = ( + f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected a dict " + f"with a 'name' key with the value 'numpy.datetime64', " + "and a 'configuration' key with a value of a dict with a 'unit' key and a " + "'scale_factor' key" + ) + raise DataTypeValidationError(msg) + + @overload + def to_json(self, zarr_format: Literal[2]) -> DateTime64JSON_V2: ... + @overload + def to_json(self, zarr_format: Literal[3]) -> DateTime64JSON_V3: ... + + def to_json(self, zarr_format: ZarrFormat) -> DateTime64JSON_V2 | DateTime64JSON_V3: + """ + Serialize this data type to JSON. + + Parameters + ---------- + zarr_format : ZarrFormat + The Zarr format version (2 or 3). + + Returns + ------- + DateTime64JSON_V2 | DateTime64JSON_V3 + The JSON representation of the data type. + + Raises + ------ + ValueError + If the zarr_format is not 2 or 3. + """ + if zarr_format == 2: + name = self.to_native_dtype().str + return {"name": name, "object_codec_id": None} + elif zarr_format == 3: + return { + "name": self._zarr_v3_name, + "configuration": {"unit": self.unit, "scale_factor": self.scale_factor}, + } + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + def _check_scalar(self, data: object) -> TypeGuard[DateTimeLike]: + """ + Check if the input is convertible to a scalar of this data type. + + Parameters + ---------- + data : object + The object to check. + + Returns + ------- + TypeGuard[DateTimeLike] + True if the input is a scalar of this data type, False otherwise. + """ + if data is None: + return True + return isinstance(data, str | int | bytes | np.datetime64 | datetime) + + def _cast_scalar_unchecked(self, data: DateTimeLike) -> np.datetime64: + """ + Cast the input to a scalar of this data type without any type checking. + + Parameters + ---------- + data : DateTimeLike + The scalar data to cast. + + Returns + ------- + numpy.datetime64 + The input cast to a NumPy datetime scalar. + """ + # numpy 2.x stub: datetime64(scalar, formatted_unit_str) is runtime-valid + # but no overload matches the dynamic f-string unit argument. + return self.to_native_dtype().type(data, f"{self.scale_factor}{self.unit}") # type: ignore[call-overload, no-any-return] + + def cast_scalar(self, data: object) -> np.datetime64: + """ + Cast the input to a scalar of this data type after a type check. + + Parameters + ---------- + data : object + The scalar value to cast. + + Returns + ------- + numpy.datetime64 + The input cast to a NumPy datetime scalar. + + Raises + ------ + TypeError + If the data cannot be converted to a numpy datetime scalar. + """ + if self._check_scalar(data): + return self._cast_scalar_unchecked(data) + msg = ( + f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the " + f"data type {self}." + ) + raise TypeError(msg) + + def default_scalar(self) -> np.datetime64: + """ + Return the default scalar value for this data type. + + Returns + ------- + numpy.datetime64 + The default scalar value, which is a 'Not-a-Time' (NaT) value + """ + + # numpy 2.x stub: 'generic' is a runtime-valid unit but not in the Literal overload. + return np.datetime64("NaT", self.unit) # type: ignore[arg-type] + + def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.datetime64: + """ + Read a JSON-serializable value as a scalar. + + Parameters + ---------- + data : JSON + The JSON-serializable value. + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + numpy.datetime64 + The numpy datetime scalar. + + Raises + ------ + TypeError + If the input is not a valid integer type. + """ + if check_json_time(data): + return self._cast_scalar_unchecked(data) + raise TypeError(f"Invalid type: {data}. Expected an integer.") # pragma: no cover diff --git a/src/zarr/core/dtype/registry.py b/src/zarr/core/dtype/registry.py new file mode 100644 index 0000000000..0a9b2aa64a --- /dev/null +++ b/src/zarr/core/dtype/registry.py @@ -0,0 +1,210 @@ +from __future__ import annotations + +import contextlib +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Self + +import numpy as np + +from zarr.errors import DataTypeValidationError + +if TYPE_CHECKING: + from importlib.metadata import EntryPoint + + from zarr.core.common import ZarrFormat + from zarr.core.dtype.common import DTypeJSON + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType + + +# This class is different from the other registry classes, which inherit from +# dict. IMO it's simpler to just do a dataclass. But long-term we should +# have just 1 registry class in use. +@dataclass(frozen=True, kw_only=True) +class DataTypeRegistry: + """ + A registry for ZDType classes. + + This registry is a mapping from Zarr data type names to their + corresponding ZDType classes. + + Attributes + ---------- + contents : dict[str, type[ZDType[TBaseDType, TBaseScalar]]] + The mapping from Zarr data type names to their corresponding + ZDType classes. + """ + + contents: dict[str, type[ZDType[TBaseDType, TBaseScalar]]] = field( + default_factory=dict, init=False + ) + + _lazy_load_list: list[EntryPoint] = field(default_factory=list, init=False) + + def _lazy_load(self) -> None: + """ + Load all data types from the lazy load list and register them with + the registry. After loading, clear the lazy load list. + """ + for e in self._lazy_load_list: + self.register(e.load()._zarr_v3_name, e.load()) + + self._lazy_load_list.clear() + + def register(self: Self, key: str, cls: type[ZDType[TBaseDType, TBaseScalar]]) -> None: + """ + Register a data type with the registry. + + Parameters + ---------- + key : str + The Zarr V3 name of the data type. + cls : type[ZDType[TBaseDType, TBaseScalar]] + The class of the data type to register. + + Notes + ----- + This method is idempotent. If the data type is already registered, this + method does nothing. + """ + if key not in self.contents or self.contents[key] != cls: + self.contents[key] = cls + + def unregister(self, key: str) -> None: + """ + Unregister a data type from the registry. + + Parameters + ---------- + key : str + The key associated with the ZDType class to be unregistered. + + Returns + ------- + None + + Raises + ------ + KeyError + If the data type is not found in the registry. + """ + if key in self.contents: + del self.contents[key] + else: + raise KeyError(f"Data type '{key}' not found in registry.") + + def get(self, key: str) -> type[ZDType[TBaseDType, TBaseScalar]]: + """ + Retrieve a registered ZDType class by its key. + + Parameters + ---------- + key : str + The key associated with the desired ZDType class. + + Returns + ------- + type[ZDType[TBaseDType, TBaseScalar]] + The ZDType class registered under the given key. + + Raises + ------ + KeyError + If the key is not found in the registry. + """ + + return self.contents[key] + + def match_dtype(self, dtype: TBaseDType) -> ZDType[TBaseDType, TBaseScalar]: + """ + Match a native data type, e.g. a NumPy data type, to a registered ZDType. + + Parameters + ---------- + dtype : TBaseDType + The native data type to match. + + Returns + ------- + ZDType[TBaseDType, TBaseScalar] + The matched ZDType corresponding to the provided NumPy data type. + + Raises + ------ + ValueError + If the data type is a NumPy "Object" type, which is ambiguous, or if multiple + or no Zarr data types are found that match the provided dtype. + + Notes + ----- + This function attempts to resolve a Zarr data type from a given native data type. + If the dtype is a NumPy "Object" data type, it raises a ValueError, as this type + can represent multiple Zarr data types. In such cases, a specific Zarr data type + should be explicitly constructed instead of relying on dynamic resolution. + + If multiple matches are found, it will also raise a ValueError. In this case + conflicting data types must be unregistered, or the Zarr data type should be explicitly + constructed. + """ + + if dtype == np.dtype("O"): + msg = ( + f"Zarr data type resolution from {dtype} failed. " + 'Attempted to resolve a zarr data type from a numpy "Object" data type, which is ' + 'ambiguous, as multiple zarr data types can be represented by the numpy "Object" ' + "data type. " + "In this case you should construct your array by providing a specific Zarr data " + 'type. For a list of Zarr data types that are compatible with the numpy "Object"' + "data type, see https://github.com/zarr-developers/zarr-python/issues/3117" + ) + raise ValueError(msg) + matched: list[ZDType[TBaseDType, TBaseScalar]] = [] + for val in self.contents.values(): + # DataTypeValidationError means "this dtype doesn't match me", which is + # expected and suppressed. Other exceptions (e.g. ValueError for a dtype + # that matches the type but has an invalid configuration) are propagated + # to the caller. + with contextlib.suppress(DataTypeValidationError): + matched.append(val.from_native_dtype(dtype)) + if len(matched) == 1: + return matched[0] + elif len(matched) > 1: + msg = ( + f"Zarr data type resolution from {dtype} failed. " + f"Multiple data type wrappers found that match dtype '{dtype}': {matched}. " + "You should unregister one of these data types, or avoid Zarr data type inference " + "entirely by providing a specific Zarr data type when creating your array." + "For more information, see https://github.com/zarr-developers/zarr-python/issues/3117" + ) + raise ValueError(msg) + raise ValueError(f"No Zarr data type found that matches dtype '{dtype!r}'") + + def match_json( + self, data: DTypeJSON, *, zarr_format: ZarrFormat + ) -> ZDType[TBaseDType, TBaseScalar]: + """ + Match a JSON representation of a data type to a registered ZDType. + + Parameters + ---------- + data : DTypeJSON + The JSON representation of a data type to match. + zarr_format : ZarrFormat + The Zarr format version to consider when matching data types. + + Returns + ------- + ZDType[TBaseDType, TBaseScalar] + The matched ZDType corresponding to the JSON representation. + + Raises + ------ + ValueError + If no matching Zarr data type is found for the given JSON data. + """ + + for val in self.contents.values(): + try: + return val.from_json(data, zarr_format=zarr_format) + except DataTypeValidationError: + pass + raise ValueError(f"No Zarr data type found that matches {data!r}") diff --git a/src/zarr/core/dtype/wrapper.py b/src/zarr/core/dtype/wrapper.py new file mode 100644 index 0000000000..42d5d88473 --- /dev/null +++ b/src/zarr/core/dtype/wrapper.py @@ -0,0 +1,292 @@ +""" +Wrapper for native array data types. + +The ``ZDType`` class is an abstract base class for wrapping native array data types, e.g. NumPy dtypes. +``ZDType`` provides a common interface for working with data types in a way that is independent of the +underlying data type system. + +The wrapper class encapsulates a native data type. Instances of the class can be created from a +native data type instance, and a native data type instance can be created from an instance of the +wrapper class. + +The wrapper class is responsible for: +- Serializing and deserializing a native data type to Zarr V2 or Zarr V3 metadata. + This ensures that the data type can be properly stored and retrieved from array metadata. +- Serializing and deserializing scalar values to Zarr V2 or Zarr V3 metadata. This is important for + storing a fill value for an array in a manner that is valid for the data type. + +You can add support for a new data type in Zarr by subclassing ``ZDType`` wrapper class and adapt its methods +to support your native data type. The wrapper class must be added to a data type registry +(defined elsewhere) before array creation routines or array reading routines can use your new data +type. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from dataclasses import dataclass +from typing import ( + TYPE_CHECKING, + ClassVar, + Literal, + Self, + TypeGuard, + overload, +) + +import numpy as np + +if TYPE_CHECKING: + from zarr.core.common import JSON, ZarrFormat + from zarr.core.dtype.common import DTypeJSON, DTypeSpec_V2, DTypeSpec_V3 + +# This the upper bound for the scalar types we support. It's numpy scalars + str, +# because the new variable-length string dtype in numpy does not have a corresponding scalar type +type TBaseScalar = np.generic | str | bytes +# This is the bound for the dtypes that we support. If we support non-numpy dtypes, +# then this bound will need to be widened. +type TBaseDType = np.dtype[np.generic] + + +@dataclass(frozen=True, kw_only=True, slots=True) +class ZDType[DType: TBaseDType, Scalar: TBaseScalar](ABC): + """ + Abstract base class for wrapping native array data types, e.g. numpy dtypes + + Attributes + ---------- + dtype_cls : ClassVar[type[TDType]] + The wrapped dtype class. This is a class variable. + _zarr_v3_name : ClassVar[str] + The name given to the data type by a Zarr v3 data type specification. This is a + class variable, and it should generally be unique across different data types. + """ + + # this class will create a native data type + dtype_cls: ClassVar[type[TBaseDType]] + _zarr_v3_name: ClassVar[str] + + @classmethod + def _check_native_dtype(cls: type[Self], dtype: TBaseDType) -> TypeGuard[DType]: + """ + Check that a native data type matches the dtype_cls class attribute. + + Used as a type guard. + + Parameters + ---------- + dtype : TDType + The dtype to check. + + Returns + ------- + Bool + True if the dtype matches, False otherwise. + """ + return type(dtype) is cls.dtype_cls + + @classmethod + @abstractmethod + def from_native_dtype(cls: type[Self], dtype: TBaseDType) -> Self: + """ + Create a ZDType instance from a native data type. + + This method is used when taking a user-provided native data type, like a NumPy data type, + and creating the corresponding ZDType instance from them. + + Parameters + ---------- + dtype : TDType + The native data type object to wrap. + + Returns + ------- + Self + The ZDType that wraps the native data type. + + Raises + ------ + TypeError + If the native data type is not consistent with the wrapped data type. + """ + raise NotImplementedError # pragma: no cover + + @abstractmethod + def to_native_dtype(self: Self) -> DType: + """ + Return an instance of the wrapped data type. This operation inverts ``from_native_dtype``. + + Returns + ------- + TDType + The native data type wrapped by this ZDType. + """ + raise NotImplementedError # pragma: no cover + + @classmethod + @abstractmethod + def _from_json_v2(cls: type[Self], data: DTypeJSON) -> Self: + raise NotImplementedError # pragma: no cover + + @classmethod + @abstractmethod + def _from_json_v3(cls: type[Self], data: DTypeJSON) -> Self: + raise NotImplementedError # pragma: no cover + + @classmethod + def from_json(cls: type[Self], data: DTypeJSON, *, zarr_format: ZarrFormat) -> Self: + """ + Create an instance of this ZDType from JSON data. + + Parameters + ---------- + data : DTypeJSON + The JSON representation of the data type. + + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + Self + An instance of this data type. + """ + if zarr_format == 2: + return cls._from_json_v2(data) + if zarr_format == 3: + return cls._from_json_v3(data) + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + @overload + def to_json(self, zarr_format: Literal[2]) -> DTypeSpec_V2: ... + + @overload + def to_json(self, zarr_format: Literal[3]) -> DTypeSpec_V3: ... + + @abstractmethod + def to_json(self, zarr_format: ZarrFormat) -> DTypeSpec_V2 | DTypeSpec_V3: + """ + Serialize this ZDType to JSON. + + Parameters + ---------- + zarr_format : ZarrFormat + The zarr format version. + + Returns + ------- + DTypeJSON_V2 | DTypeJSON_V3 + The JSON-serializable representation of the wrapped data type + """ + raise NotImplementedError # pragma: no cover + + @abstractmethod + def _check_scalar(self, data: object) -> bool: + """ + Check that a python object is a valid scalar value for the wrapped data type. + + Parameters + ---------- + data : object + A value to check. + + Returns + ------- + Bool + True if the object is valid, False otherwise. + """ + raise NotImplementedError # pragma: no cover + + @abstractmethod + def cast_scalar(self, data: object) -> Scalar: + """ + Cast a python object to the wrapped scalar type. + + The type of the provided scalar is first checked for compatibility. + If it's incompatible with the associated scalar type, a ``TypeError`` will be raised. + + Parameters + ---------- + data : object + The python object to cast. + + Returns + ------- + TScalar + The cast value. + """ + raise NotImplementedError # pragma: no cover + + @abstractmethod + def default_scalar(self) -> Scalar: + """ + Get the default scalar value for the wrapped data type. + + This is a method, rather than an attribute, because the default value for some data types depends on parameters that are + not known until a concrete data type is wrapped. For example, data types parametrized by a + length like fixed-length strings or bytes will generate scalars consistent with that length. + + Returns + ------- + TScalar + The default value for this data type. + """ + raise NotImplementedError # pragma: no cover + + @abstractmethod + def from_json_scalar(self: Self, data: JSON, *, zarr_format: ZarrFormat) -> Scalar: + """ + Read a JSON-serializable value as a scalar. + + Parameters + ---------- + data : JSON + A JSON representation of a scalar value. + zarr_format : ZarrFormat + The zarr format version. This is specified because the JSON serialization of scalars + differs between Zarr V2 and Zarr V3. + + Returns + ------- + TScalar + The deserialized scalar value. + """ + raise NotImplementedError # pragma: no cover + + @abstractmethod + def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> JSON: + """ + Serialize a python object to the JSON representation of a scalar. + + The value will first be cast to the scalar type associated with this ZDType, then serialized + to JSON. + + Parameters + ---------- + data : object + The value to convert. + zarr_format : ZarrFormat + The zarr format version. This is specified because the JSON serialization of scalars + differs between Zarr V2 and Zarr V3. + + Returns + ------- + JSON + The JSON-serialized scalar. + """ + raise NotImplementedError # pragma: no cover + + +def scalar_failed_type_check_msg( + cls_instance: ZDType[TBaseDType, TBaseScalar], bad_scalar: object +) -> str: + """ + Generate an error message reporting that a particular value failed a type check when attempting + to cast that value to a scalar. + """ + return ( + f"The value {bad_scalar!r} failed a type check. " + f"It cannot be safely cast to a scalar compatible with {cls_instance}. " + f"Consult the documentation for {cls_instance} to determine the possible values that can " + "be cast to scalars of the wrapped data type." + ) diff --git a/src/zarr/core/group.py b/src/zarr/core/group.py new file mode 100644 index 0000000000..d061e1a5c6 --- /dev/null +++ b/src/zarr/core/group.py @@ -0,0 +1,3763 @@ +from __future__ import annotations + +import asyncio +import logging +import unicodedata +import warnings +from collections import defaultdict +from dataclasses import asdict, dataclass, field, fields, replace +from itertools import accumulate +from typing import TYPE_CHECKING, Literal, assert_never, cast, overload + +import numpy as np + +import zarr.api.asynchronous as async_api +from zarr.abc.metadata import Metadata +from zarr.abc.store import Store, set_or_delete +from zarr.core._info import GroupInfo +from zarr.core._json import buffer_to_json_object, json_to_buffer +from zarr.core.array import ( + DEFAULT_FILL_VALUE, + Array, + AsyncArray, + CompressorLike, + CompressorsLike, + FiltersLike, + SerializerLike, + ShardsLike, + _parse_deprecated_compressor, + create_array, +) +from zarr.core.attributes import Attributes +from zarr.core.buffer import default_buffer_prototype +from zarr.core.common import ( + JSON, + ZARR_JSON, + ZARRAY_JSON, + ZATTRS_JSON, + ZGROUP_JSON, + ZMETADATA_V2_JSON, + ChunksLike, + DimensionNamesLike, + NodeType, + ShapeLike, + ZarrFormat, + parse_shapelike, +) +from zarr.core.config import config +from zarr.core.dtype import parse_data_type +from zarr.core.json_parse import parse_field +from zarr.core.metadata import ArrayV2Metadata, ArrayV3Metadata +from zarr.core.metadata.io import save_metadata +from zarr.core.sync import SyncMixin, sync +from zarr.errors import ( + ArrayNotFoundError, + ContainsArrayError, + ContainsGroupError, + GroupNotFoundError, + MetadataValidationError, + ZarrUserWarning, +) +from zarr.storage import StoreLike, StorePath +from zarr.storage._common import ensure_no_existing_node, make_store_path +from zarr.storage._utils import _join_paths, _normalize_path_keys, normalize_path + +if TYPE_CHECKING: + from collections.abc import ( + AsyncGenerator, + AsyncIterator, + Coroutine, + Generator, + Iterable, + Iterator, + Mapping, + ) + from typing import Any + + from zarr.core.array_spec import ArrayConfigLike + from zarr.core.buffer import Buffer, BufferPrototype + from zarr.core.chunk_key_encodings import ChunkKeyEncodingLike + from zarr.core.common import MemoryOrder + from zarr.core.dtype import ZDTypeLike + from zarr.types import AnyArray, AnyAsyncArray, ArrayV2, ArrayV3, AsyncArrayV2, AsyncArrayV3 + +logger = logging.getLogger("zarr.group") + + +def parse_zarr_format(data: Any) -> ZarrFormat: + """Parse the zarr_format field from metadata.""" + return cast("ZarrFormat", parse_field(data, Literal[2, 3], "zarr_format")) + + +def parse_node_type(data: Any) -> NodeType: + """Parse the node_type field from metadata.""" + return cast( + "Literal['array', 'group']", + parse_field(data, Literal["array", "group"], "node_type", error=MetadataValidationError), + ) + + +# todo: convert None to empty dict +def parse_attributes(data: Any) -> dict[str, Any]: + """Parse the attributes field from metadata.""" + if data is None: + return {} + elif isinstance(data, dict) and all(isinstance(k, str) for k in data): + return dict(data) + msg = f"Expected dict with string keys. Got {type(data)} instead." + raise TypeError(msg) + + +@overload +def _parse_async_node(node: AsyncArrayV3) -> ArrayV3: ... + + +@overload +def _parse_async_node(node: AsyncArrayV2) -> ArrayV2: ... + + +@overload +def _parse_async_node(node: AsyncGroup) -> Group: ... + + +def _parse_async_node( + node: AnyAsyncArray | AsyncGroup, +) -> AnyArray | Group: + """Wrap an AsyncArray in an Array, or an AsyncGroup in a Group.""" + if isinstance(node, AsyncArray): + return Array(node) + elif isinstance(node, AsyncGroup): + return Group(node) + else: + raise TypeError(f"Unknown node type, got {type(node)}") + + +@dataclass(frozen=True) +class ConsolidatedMetadata: + """ + Consolidated Metadata for this Group. + + This stores the metadata of child nodes below this group. Any child groups + will have their consolidated metadata set appropriately. + """ + + metadata: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata] + kind: Literal["inline"] = "inline" + must_understand: Literal[False] = False + + def to_dict(self) -> dict[str, JSON]: + return { + "kind": self.kind, + "must_understand": self.must_understand, + "metadata": { + k: v.to_dict() + for k, v in sorted( + self.flattened_metadata.items(), + key=lambda item: ( + item[0].count("/"), + unicodedata.normalize("NFKC", item[0]).casefold(), + ), + ) + }, + } + + @classmethod + def from_dict(cls, data: dict[str, JSON]) -> ConsolidatedMetadata: + data = dict(data) + + kind = data.get("kind") + if kind != "inline": + raise ValueError(f"Consolidated metadata kind='{kind}' is not supported.") + + raw_metadata = data.get("metadata") + if not isinstance(raw_metadata, dict): + raise TypeError(f"Unexpected type for 'metadata': {type(raw_metadata)}") + + metadata: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata] = {} + if raw_metadata: + for k, v in raw_metadata.items(): + if not isinstance(v, dict): + raise TypeError( + f"Invalid value for metadata items. key='{k}', type='{type(v).__name__}'" + ) + + # zarr_format is present in v2 and v3. + zarr_format = parse_zarr_format(v["zarr_format"]) + + if zarr_format == 3: + node_type = parse_node_type(v.get("node_type", None)) + if node_type == "group": + metadata[k] = GroupMetadata.from_dict(v) + elif node_type == "array": + metadata[k] = ArrayV3Metadata.from_dict(v) + else: + assert_never(node_type) + elif zarr_format == 2: + if "shape" in v: + metadata[k] = ArrayV2Metadata.from_dict(v) + else: + metadata[k] = GroupMetadata.from_dict(v) + else: + assert_never(zarr_format) + + cls._flat_to_nested(metadata) + + return cls(metadata=metadata) + + @staticmethod + def _flat_to_nested( + metadata: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata], + ) -> None: + """ + Convert a flat metadata representation to a nested one. + + Notes + ----- + Flat metadata is used when persisting the consolidated metadata. The keys + include the full path, not just the node name. The key prefixes can be + used to determine which nodes are children of which other nodes. + + Nested metadata is used in-memory. The outermost level will only have the + *immediate* children of the Group. All nested child groups will be stored + under the consolidated metadata of their immediate parent. + """ + # We have a flat mapping from {k: v} where the keys include the *full* + # path segment: + # { + # "/a/b": { group_metadata }, + # "/a/b/array-0": { array_metadata }, + # "/a/b/array-1": { array_metadata }, + # } + # + # We want to reorganize the metadata such that each Group contains the + # array metadata of its immediate children. + # In the example, the group at `/a/b` will have consolidated metadata + # for its children `array-0` and `array-1`. + + # Group keys by their parent path. This must not rely on same-parent keys + # being adjacent: the persisted key order is arbitrary, so accumulate + # instead of using itertools.groupby, which only groups consecutive runs. + grouped: dict[str, list[str]] = defaultdict(list) + for k in sorted(metadata, key=lambda k: k.count("/")): + grouped[k.rsplit("/", 1)[0]].append(k) + + # we go top down and directly manipulate metadata. + for key, children_keys in grouped.items(): + # key is a key like "a", "a/b", "a/b/c" + # The basic idea is to find the immediate parent (so "", "a", or "a/b") + # and update that node's consolidated metadata to include the metadata + # in children_keys + *prefixes, name = key.split("/") + parent = metadata + + while prefixes: + # e.g. a/b/c has a parent "a/b". Walk through to get + # metadata["a"]["b"] + part = prefixes.pop(0) + # we can assume that parent[part] here is a group + # otherwise we wouldn't have a node with this `part` prefix. + # We can also assume that the parent node will have consolidated metadata, + # because we're walking top to bottom. + parent = parent[part].consolidated_metadata.metadata # type: ignore[union-attr] + + node = parent[name] + children_keys = list(children_keys) + + if isinstance(node, ArrayV2Metadata | ArrayV3Metadata): + # These are already present, either thanks to being an array in the + # root, or by being collected as a child in the else clause + continue + children: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata] = {} + # We pop from metadata, since we're *moving* this under group. + # While doing this, normalize leaf groups to carry empty consolidated metadata. + for child_key in children_keys: + if child_key == key: + continue + child = metadata.pop(child_key) + if isinstance(child, GroupMetadata) and child.consolidated_metadata is None: + child = replace(child, consolidated_metadata=ConsolidatedMetadata(metadata={})) + children[child_key.split("/")[-1]] = child + + parent[name] = replace( + node, consolidated_metadata=ConsolidatedMetadata(metadata=children) + ) + + @property + def flattened_metadata(self) -> dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata]: + """ + Return the flattened representation of Consolidated Metadata. + + The returned dictionary will have a key for each child node in the hierarchy + under this group. Under the default (nested) representation available through + ``self.metadata``, the dictionary only contains keys for immediate children. + + The keys of the dictionary will include the full path to a child node from + the current group, where segments are joined by ``/``. + + Examples + -------- + ```python + from zarr.core.group import ConsolidatedMetadata, GroupMetadata + cm = ConsolidatedMetadata( + metadata={ + "group-0": GroupMetadata( + consolidated_metadata=ConsolidatedMetadata( + { + "group-0-0": GroupMetadata(), + } + ) + ), + "group-1": GroupMetadata(), + } + ) + # {'group-0': GroupMetadata(attributes={}, zarr_format=3, consolidated_metadata=None, node_type='group'), + # 'group-0/group-0-0': GroupMetadata(attributes={}, zarr_format=3, consolidated_metadata=None, node_type='group'), + # 'group-1': GroupMetadata(attributes={}, zarr_format=3, consolidated_metadata=None, node_type='group')} + ``` + """ + metadata = {} + + def flatten( + key: str, group: GroupMetadata | ArrayV2Metadata | ArrayV3Metadata + ) -> dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata]: + children: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata] = {} + if isinstance(group, ArrayV2Metadata | ArrayV3Metadata): + children[key] = group + else: + if group.consolidated_metadata and group.consolidated_metadata.metadata is not None: + children[key] = replace( + group, consolidated_metadata=ConsolidatedMetadata(metadata={}) + ) + for name, val in group.consolidated_metadata.metadata.items(): + full_key = f"{key}/{name}" + if isinstance(val, GroupMetadata): + children.update(flatten(full_key, val)) + else: + children[full_key] = val + else: + children[key] = replace(group, consolidated_metadata=None) + return children + + for k, v in self.metadata.items(): + metadata.update(flatten(k, v)) + + return metadata + + +@dataclass(frozen=True) +class GroupMetadata(Metadata): + """ + Metadata for a Group. + """ + + attributes: dict[str, Any] = field(default_factory=dict) + zarr_format: ZarrFormat = 3 + consolidated_metadata: ConsolidatedMetadata | None = None + node_type: Literal["group"] = field(default="group", init=False) + + def to_buffer_dict(self, prototype: BufferPrototype) -> dict[str, Buffer]: + indent = config.get("json_indent") + if self.zarr_format == 3: + return {ZARR_JSON: json_to_buffer(self.to_dict(), prototype=prototype, indent=indent)} + else: + items = { + ZGROUP_JSON: json_to_buffer( + {"zarr_format": self.zarr_format}, prototype=prototype, indent=indent + ), + ZATTRS_JSON: json_to_buffer(self.attributes, prototype=prototype, indent=indent), + } + if self.consolidated_metadata: + d = { + ZGROUP_JSON: {"zarr_format": self.zarr_format}, + ZATTRS_JSON: self.attributes, + } + consolidated_metadata = self.consolidated_metadata.to_dict()["metadata"] + assert isinstance(consolidated_metadata, dict) + for k, v in consolidated_metadata.items(): + attrs = v.pop("attributes", {}) + d[f"{k}/{ZATTRS_JSON}"] = attrs + if "shape" in v: + # it's an array + d[f"{k}/{ZARRAY_JSON}"] = v + else: + d[f"{k}/{ZGROUP_JSON}"] = { + "zarr_format": self.zarr_format, + "consolidated_metadata": { + "metadata": {}, + "must_understand": False, + "kind": "inline", + }, + } + + # The consolidated metadata blob is written compactly (no indent). + items[ZMETADATA_V2_JSON] = json_to_buffer( + {"metadata": d, "zarr_consolidated_format": 1}, prototype=prototype + ) + + return items + + def __init__( + self, + attributes: dict[str, Any] | None = None, + zarr_format: ZarrFormat = 3, + consolidated_metadata: ConsolidatedMetadata | None = None, + ) -> None: + attributes_parsed = parse_attributes(attributes) + zarr_format_parsed = parse_zarr_format(zarr_format) + + object.__setattr__(self, "attributes", attributes_parsed) + object.__setattr__(self, "zarr_format", zarr_format_parsed) + object.__setattr__(self, "consolidated_metadata", consolidated_metadata) + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> GroupMetadata: + data = dict(data) + assert data.pop("node_type", None) in ("group", None) + consolidated_metadata = data.pop("consolidated_metadata", None) + if consolidated_metadata: + data["consolidated_metadata"] = ConsolidatedMetadata.from_dict(consolidated_metadata) + + zarr_format = data.get("zarr_format") + if zarr_format == 2 or zarr_format is None: + # zarr v2 allowed arbitrary keys here. + # We don't want the GroupMetadata constructor to fail just because someone put an + # extra key in the metadata. + expected = {x.name for x in fields(cls)} + data = {k: v for k, v in data.items() if k in expected} + + return cls(**data) + + def to_dict(self) -> dict[str, Any]: + result = asdict(replace(self, consolidated_metadata=None)) + if self.consolidated_metadata is not None: + result["consolidated_metadata"] = self.consolidated_metadata.to_dict() + else: + # Leave consolidated metadata unset if it's None + result.pop("consolidated_metadata") + return result + + +@dataclass(frozen=True) +class ImplicitGroupMarker(GroupMetadata): + """ + Marker for an implicit group. Instances of this class are only used in the context of group + creation as a placeholder to represent groups that should only be created if they do not + already exist in storage + """ + + +@dataclass(frozen=True) +class AsyncGroup: + """ + Asynchronous Group object. + """ + + metadata: GroupMetadata + store_path: StorePath + + # TODO: make this correct and work + # TODO: ensure that this can be bound properly to subclass of AsyncGroup + + @classmethod + async def from_store( + cls, + store: StoreLike, + *, + attributes: dict[str, Any] | None = None, + overwrite: bool = False, + zarr_format: ZarrFormat = 3, + ) -> AsyncGroup: + store_path = await make_store_path(store) + + if overwrite: + if store_path.store.supports_deletes: + await store_path.delete_dir() + else: + await ensure_no_existing_node(store_path, zarr_format=zarr_format) + else: + await ensure_no_existing_node(store_path, zarr_format=zarr_format) + attributes = attributes or {} + group = cls( + metadata=GroupMetadata(attributes=attributes, zarr_format=zarr_format), + store_path=store_path, + ) + await group._save_metadata(ensure_parents=True) + return group + + @classmethod + async def open( + cls, + store: StoreLike, + zarr_format: ZarrFormat | None = 3, + use_consolidated: bool | str | None = None, + ) -> AsyncGroup: + """Open a new AsyncGroup + + Parameters + ---------- + store : StoreLike + zarr_format : {2, 3}, optional + use_consolidated : bool or str, default None + Whether to use consolidated metadata. + + By default, consolidated metadata is used if it's present in the + store (in the ``zarr.json`` for Zarr format 3 and in the ``.zmetadata`` file + for Zarr format 2) and the Store supports it. + + To explicitly require consolidated metadata, set ``use_consolidated=True``. + In this case, if the Store doesn't support consolidation or consolidated metadata is + not found, a ``ValueError`` exception is raised. + + To explicitly *not* use consolidated metadata, set ``use_consolidated=False``, + which will fall back to using the regular, non consolidated metadata. + + Zarr format 2 allowed configuring the key storing the consolidated metadata + (``.zmetadata`` by default). Specify the custom key as ``use_consolidated`` + to load consolidated metadata from a non-default key. + """ + store_path = await make_store_path(store) + if not store_path.store.supports_consolidated_metadata: + # Fail if consolidated metadata was requested but the Store doesn't support it + if use_consolidated: + store_name = type(store_path.store).__name__ + raise ValueError( + f"The Zarr store in use ({store_name}) doesn't support consolidated metadata." + ) + + # if use_consolidated was None (optional), the Store dictates it doesn't want consolidation + use_consolidated = False + + consolidated_key = ZMETADATA_V2_JSON + + if (zarr_format == 2 or zarr_format is None) and isinstance(use_consolidated, str): + consolidated_key = use_consolidated + + if zarr_format == 2: + paths = [store_path / ZGROUP_JSON, store_path / ZATTRS_JSON] + if use_consolidated or use_consolidated is None: + paths.append(store_path / consolidated_key) + + zgroup_bytes, zattrs_bytes, *rest = await asyncio.gather( + *[path.get() for path in paths] + ) + if zgroup_bytes is None: + raise FileNotFoundError(store_path) + + if use_consolidated or use_consolidated is None: + maybe_consolidated_metadata_bytes = rest[0] + + else: + maybe_consolidated_metadata_bytes = None + + elif zarr_format == 3: + zarr_json_bytes = await (store_path / ZARR_JSON).get() + if zarr_json_bytes is None: + raise FileNotFoundError(store_path) + elif zarr_format is None: + ( + zarr_json_bytes, + zgroup_bytes, + zattrs_bytes, + maybe_consolidated_metadata_bytes, + ) = await asyncio.gather( + (store_path / ZARR_JSON).get(), + (store_path / ZGROUP_JSON).get(), + (store_path / ZATTRS_JSON).get(), + (store_path / str(consolidated_key)).get(), + ) + if zarr_json_bytes is not None and zgroup_bytes is not None: + # warn and favor v3 + msg = f"Both zarr.json (Zarr format 3) and .zgroup (Zarr format 2) metadata objects exist at {store_path}. Zarr format 3 will be used." + warnings.warn(msg, category=ZarrUserWarning, stacklevel=1) + if zarr_json_bytes is None and zgroup_bytes is None: + raise FileNotFoundError( + f"could not find zarr.json or .zgroup objects in {store_path}" + ) + # set zarr_format based on which keys were found + if zarr_json_bytes is not None: + zarr_format = 3 + else: + zarr_format = 2 + else: + msg = f"Invalid value for 'zarr_format'. Expected 2, 3, or None. Got '{zarr_format}'." # type: ignore[unreachable] + raise MetadataValidationError(msg) + + if zarr_format == 2: + # this is checked above, asserting here for mypy + assert zgroup_bytes is not None + + if use_consolidated and maybe_consolidated_metadata_bytes is None: + # the user requested consolidated metadata, but it was missing + raise ValueError(consolidated_key) + + elif use_consolidated is False: + # the user explicitly opted out of consolidated_metadata. + # Discard anything we might have read. + maybe_consolidated_metadata_bytes = None + + return cls._from_bytes_v2( + store_path, zgroup_bytes, zattrs_bytes, maybe_consolidated_metadata_bytes + ) + else: + # V3 groups are comprised of a zarr.json object + assert zarr_json_bytes is not None + if not isinstance(use_consolidated, bool | None): + raise TypeError("use_consolidated must be a bool or None for Zarr format 3.") + + return cls._from_bytes_v3( + store_path, + zarr_json_bytes, + use_consolidated=use_consolidated, + ) + + @classmethod + def _from_bytes_v2( + cls, + store_path: StorePath, + zgroup_bytes: Buffer, + zattrs_bytes: Buffer | None, + consolidated_metadata_bytes: Buffer | None, + ) -> AsyncGroup: + # V2 groups are comprised of a .zgroup and .zattrs objects + zgroup = buffer_to_json_object(zgroup_bytes) + zattrs = buffer_to_json_object(zattrs_bytes) if zattrs_bytes is not None else {} + group_metadata: dict[str, Any] = {**zgroup, "attributes": zattrs} + + if consolidated_metadata_bytes is not None: + v2_consolidated_doc = buffer_to_json_object(consolidated_metadata_bytes) + v2_consolidated_metadata = cast("dict[str, Any]", v2_consolidated_doc["metadata"]) + # We already read zattrs and zgroup. Should we ignore these? + v2_consolidated_metadata.pop(".zattrs", None) + v2_consolidated_metadata.pop(".zgroup", None) + + consolidated_metadata: defaultdict[str, dict[str, Any]] = defaultdict(dict) + + # keys like air/.zarray, air/.zattrs + for k, v in v2_consolidated_metadata.items(): + path, kind = k.rsplit("/.", 1) + + if kind == "zarray": + consolidated_metadata[path].update(v) + elif kind == "zattrs": + consolidated_metadata[path]["attributes"] = v + elif kind == "zgroup": + consolidated_metadata[path].update(v) + else: + raise ValueError(f"Invalid file type '{kind}' at path '{path}") + + group_metadata["consolidated_metadata"] = { + "metadata": dict(consolidated_metadata), + "kind": "inline", + "must_understand": False, + } + + return cls.from_dict(store_path, group_metadata) + + @classmethod + def _from_bytes_v3( + cls, + store_path: StorePath, + zarr_json_bytes: Buffer, + use_consolidated: bool | None, + ) -> AsyncGroup: + group_metadata = buffer_to_json_object(zarr_json_bytes) + if use_consolidated and group_metadata.get("consolidated_metadata") is None: + msg = f"Consolidated metadata requested with 'use_consolidated=True' but not found in '{store_path.path}'." + raise ValueError(msg) + + elif use_consolidated is False: + # Drop consolidated metadata if it's there. + group_metadata.pop("consolidated_metadata", None) + + return cls.from_dict(store_path, group_metadata) + + @classmethod + def from_dict( + cls, + store_path: StorePath, + data: dict[str, Any], + ) -> AsyncGroup: + node_type = data.pop("node_type", None) + if node_type == "array": + msg = f"An array already exists in store {store_path.store} at path {store_path.path}." + raise ContainsArrayError(msg) + elif node_type not in ("group", None): + msg = f"Node type in metadata ({node_type}) is not 'group'" + raise GroupNotFoundError(msg) + return cls( + metadata=GroupMetadata.from_dict(data), + store_path=store_path, + ) + + async def setitem(self, key: str, value: Any) -> None: + """ + Fastpath for creating a new array + New arrays will be created with default array settings for the array type. + + Parameters + ---------- + key : str + Array name + value : array-like + Array data + """ + path = self.store_path / key + await async_api.save_array( + store=path, arr=value, zarr_format=self.metadata.zarr_format, overwrite=True + ) + + async def getitem( + self, + key: str, + ) -> AnyAsyncArray | AsyncGroup: + """ + Get a subarray or subgroup from the group. + + Parameters + ---------- + key : str + Array or group name + + Returns + ------- + AsyncArray or AsyncGroup + """ + store_path = self.store_path / key + logger.debug("key=%s, store_path=%s", key, store_path) + + # Consolidated metadata lets us avoid some I/O operations so try that first. + if self.metadata.consolidated_metadata is not None: + return self._getitem_consolidated(store_path, key, prefix=self.name) + try: + return await get_node( + store=store_path.store, path=store_path.path, zarr_format=self.metadata.zarr_format + ) + except FileNotFoundError as e: + raise KeyError(key) from e + + def _getitem_consolidated( + self, store_path: StorePath, key: str, prefix: str + ) -> AnyAsyncArray | AsyncGroup: + # getitem, in the special case where we have consolidated metadata. + # Note that this is a regular def (non async) function. + # This shouldn't do any additional I/O. + + # the caller needs to verify this! + assert self.metadata.consolidated_metadata is not None + + # we support nested getitems like group/subgroup/array + indexers = normalize_path(key).split("/") + indexers.reverse() + metadata: ArrayV2Metadata | ArrayV3Metadata | GroupMetadata = self.metadata + + while indexers: + indexer = indexers.pop() + if isinstance(metadata, ArrayV2Metadata | ArrayV3Metadata): + # we've indexed into an array with group["array/subarray"]. Invalid. + raise KeyError(key) + if metadata.consolidated_metadata is None: + # we've indexed into a group without consolidated metadata. + # This isn't normal; typically, consolidated metadata + # will include explicit markers for when there are no child + # nodes as metadata={}. + # We have some freedom in exactly how we interpret this case. + # For now, we treat None as the same as {}, i.e. we don't + # have any children. + raise KeyError(key) + try: + metadata = metadata.consolidated_metadata.metadata[indexer] + except KeyError as e: + # The Group Metadata has consolidated metadata, but the key + # isn't present. We trust this to mean that the key isn't in + # the hierarchy, and *don't* fall back to checking the store. + msg = f"'{key}' not found in consolidated metadata." + raise KeyError(msg) from e + + # update store_path to ensure that AsyncArray/Group.name is correct + if prefix != "/": + key = "/".join([prefix.lstrip("/"), key]) + store_path = StorePath(store=store_path.store, path=key) + + if isinstance(metadata, GroupMetadata): + return AsyncGroup(metadata=metadata, store_path=store_path) + else: + return AsyncArray(metadata=metadata, store_path=store_path) + + async def delitem(self, key: str) -> None: + """Delete a group member. + + Parameters + ---------- + key : str + Array or group name + """ + store_path = self.store_path / key + + await store_path.delete_dir() + if self.metadata.consolidated_metadata: + self.metadata.consolidated_metadata.metadata.pop(key, None) + await self._save_metadata() + + async def get[DefaultT]( + self, key: str, default: DefaultT | None = None + ) -> AnyAsyncArray | AsyncGroup | DefaultT | None: + """Obtain a group member, returning default if not found. + + Parameters + ---------- + key : str + Group member name. + default : object + Default value to return if key is not found (default: None). + + Returns + ------- + object + Group member (AsyncArray or AsyncGroup) or default if not found. + """ + try: + return await self.getitem(key) + except KeyError: + return default + + async def get_array(self, path: str) -> AnyAsyncArray: + """Obtain an array member of this group, raising if it is absent or not an array. + + Parameters + ---------- + path : str + Path of the array relative to this group. May contain `/` to reference + a member of a subgroup, e.g. `subgroup/subarray`. + + Returns + ------- + AsyncArray + The array at the given path. + + Raises + ------ + ArrayNotFoundError + If no node exists at the given path. + ContainsGroupError + If the node at the given path is a group rather than an array. + """ + store_path = self.store_path / path + try: + node = await self.getitem(path) + except KeyError as e: + msg = f"No array found in store {store_path.store!r} at path {store_path.path!r}" + raise ArrayNotFoundError(msg) from e + if isinstance(node, AsyncGroup): + msg = f"A group exists in store {store_path.store!r} at path {store_path.path!r}." + raise ContainsGroupError(msg) + return node + + async def get_group(self, path: str) -> AsyncGroup: + """Obtain a group member of this group, raising if it is absent or not a group. + + Parameters + ---------- + path : str + Path of the group relative to this group. May contain `/` to reference + a member of a subgroup, e.g. `subgroup/subsubgroup`. + + Returns + ------- + AsyncGroup + The group at the given path. + + Raises + ------ + GroupNotFoundError + If no node exists at the given path. + ContainsArrayError + If the node at the given path is an array rather than a group. + """ + store_path = self.store_path / path + try: + node = await self.getitem(path) + except KeyError as e: + msg = f"No group found in store {store_path.store!r} at path {store_path.path!r}" + raise GroupNotFoundError(msg) from e + if isinstance(node, AsyncArray): + msg = f"An array exists in store {store_path.store!r} at path {store_path.path!r}." + raise ContainsArrayError(msg) + return node + + async def _save_metadata(self, ensure_parents: bool = False) -> None: + await save_metadata(self.store_path, self.metadata, ensure_parents=ensure_parents) + + @property + def path(self) -> str: + """Storage path.""" + return self.store_path.path + + @property + def name(self) -> str: + """Group name following h5py convention.""" + if self.path: + # follow h5py convention: add leading slash + name = self.path + if name[0] != "/": + name = f"/{name}" + return name + return "/" + + @property + def basename(self) -> str: + """Final component of name.""" + return self.name.split("/")[-1] + + @property + def attrs(self) -> dict[str, Any]: + return self.metadata.attributes + + @property + def info(self) -> Any: + """ + Return a visual representation of the statically known information about a group. + + Note that this doesn't include dynamic information, like the number of child + Groups or Arrays. + + Returns + ------- + GroupInfo + + Related + ------- + [zarr.AsyncGroup.info_complete][] + All information about a group, including dynamic information + """ + + if self.metadata.consolidated_metadata: + members = list(self.metadata.consolidated_metadata.flattened_metadata.values()) + else: + members = None + return self._info(members=members) + + async def info_complete(self) -> Any: + """ + Return all the information for a group. + + This includes dynamic information like the number + of child Groups or Arrays. If this group doesn't contain consolidated + metadata then this will need to read from the backing Store. + + Returns + ------- + GroupInfo + + Related + ------- + [zarr.AsyncGroup.info][] + """ + members = [x[1].metadata async for x in self.members(max_depth=None)] + return self._info(members=members) + + def _info( + self, members: list[ArrayV2Metadata | ArrayV3Metadata | GroupMetadata] | None = None + ) -> Any: + kwargs = {} + if members is not None: + kwargs["_count_members"] = len(members) + count_arrays = 0 + count_groups = 0 + for member in members: + if isinstance(member, GroupMetadata): + count_groups += 1 + else: + count_arrays += 1 + kwargs["_count_arrays"] = count_arrays + kwargs["_count_groups"] = count_groups + + return GroupInfo( + _name=self.store_path.path, + _read_only=self.read_only, + _store_type=type(self.store_path.store).__name__, + _zarr_format=self.metadata.zarr_format, + # maybe do a typeddict + **kwargs, # type: ignore[arg-type] + ) + + @property + def store(self) -> Store: + return self.store_path.store + + @property + def read_only(self) -> bool: + # Backwards compatibility for 2.x + return self.store_path.read_only + + @property + def synchronizer(self) -> None: + # Backwards compatibility for 2.x + # Not implemented in 3.x yet. + return None + + async def create_group( + self, + name: str, + *, + overwrite: bool = False, + attributes: dict[str, Any] | None = None, + ) -> AsyncGroup: + """Create a sub-group. + + Parameters + ---------- + name : str + Group name. + overwrite : bool, optional + If True, do not raise an error if the group already exists. + attributes : dict, optional + Group attributes. + + Returns + ------- + g : AsyncGroup + """ + attributes = attributes or {} + return await type(self).from_store( + self.store_path / name, + attributes=attributes, + overwrite=overwrite, + zarr_format=self.metadata.zarr_format, + ) + + async def require_group(self, name: str, overwrite: bool = False) -> AsyncGroup: + """Obtain a sub-group, creating one if it doesn't exist. + + Parameters + ---------- + name : str + Group name. + overwrite : bool, optional + Overwrite any existing group with given `name` if present. + + Returns + ------- + g : AsyncGroup + """ + if overwrite: + # TODO: check that overwrite=True errors if an array exists where the group is being created + grp = await self.create_group(name, overwrite=True) + else: + try: + item: AsyncGroup | AnyAsyncArray = await self.getitem(name) + if not isinstance(item, AsyncGroup): + raise TypeError( + f"Incompatible object ({item.__class__.__name__}) already exists" + ) + assert isinstance(item, AsyncGroup) # make mypy happy + grp = item + except KeyError: + grp = await self.create_group(name) + return grp + + async def require_groups(self, *names: str) -> tuple[AsyncGroup, ...]: + """Convenience method to require multiple groups in a single call. + + Parameters + ---------- + *names : str + Group names. + + Returns + ------- + Tuple[AsyncGroup, ...] + """ + if not names: + return () + return tuple(await asyncio.gather(*(self.require_group(name) for name in names))) + + async def create_array( + self, + name: str, + *, + shape: ShapeLike | None = None, + dtype: ZDTypeLike | None = None, + data: np.ndarray[Any, np.dtype[Any]] | None = None, + chunks: ChunksLike | Literal["auto"] = "auto", + shards: ShardsLike | None = None, + filters: FiltersLike = "auto", + compressors: CompressorsLike = "auto", + compressor: CompressorLike = "auto", + serializer: SerializerLike = "auto", + fill_value: Any | None = DEFAULT_FILL_VALUE, + order: MemoryOrder | None = None, + attributes: dict[str, JSON] | None = None, + chunk_key_encoding: ChunkKeyEncodingLike | None = None, + dimension_names: DimensionNamesLike = None, + storage_options: dict[str, Any] | None = None, + overwrite: bool = False, + config: ArrayConfigLike | None = None, + write_data: bool = True, + ) -> AnyAsyncArray: + """Create an array within this group. + + This method lightly wraps [zarr.core.array.create_array][]. + + Parameters + ---------- + name : str + The name of the array relative to the group. If ``path`` is ``None``, the array will be located + at the root of the store. + shape : tuple[int, ...] + Shape of the array. + dtype : npt.DTypeLike + Data type of the array. + chunks : tuple[int, ...], optional + Chunk shape of the array. + If not specified, default are guessed based on the shape and dtype. + shards : tuple[int, ...], optional + Shard shape of the array. The default value of ``None`` results in no sharding at all. + filters : Iterable[Codec] | Literal["auto"], optional + Iterable of filters to apply to each chunk of the array, in order, before serializing that + chunk to bytes. + + For Zarr format 3, a "filter" is a codec that takes an array and returns an array, + and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a + dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. + + For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the + order of your filters is consistent with the behavior of each filter. + + The default value of ``"auto"`` instructs Zarr to use a default based on the data + type of the array and the Zarr format specified. For all data types in Zarr V3, and most + data types in Zarr V2, the default filters are empty. The only cases where default filters + are not empty is when the Zarr format is 2, and the data type is a variable-length data type like + [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, + the default filters contains a single element which is a codec specific to that particular data type. + + To create an array with no filters, provide an empty iterable or the value ``None``. + compressors : Iterable[Codec], optional + List of compressors to apply to the array. Compressors are applied in order, and after any + filters are applied (if any are specified) and the data is serialized into bytes. + + For Zarr format 3, a "compressor" is a codec that takes a bytestream, and + returns another bytestream. Multiple compressors may be provided for Zarr format 3. + If no ``compressors`` are provided, a default set of compressors will be used. + These defaults can be changed by modifying the value of ``array.v3_default_compressors`` + in [`zarr.config`][zarr.config]. + Use ``None`` to omit default compressors. + + For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may + be provided for Zarr format 2. + If no ``compressor`` is provided, a default compressor will be used. + in [`zarr.config`][zarr.config]. + Use ``None`` to omit the default compressor. + compressor : Codec, optional + Deprecated in favor of ``compressors``. + serializer : dict[str, JSON] | ArrayBytesCodec, optional + Array-to-bytes codec to use for encoding the array data. + Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. + If no ``serializer`` is provided, a default serializer will be used. + These defaults can be changed by modifying the value of ``array.v3_default_serializer`` + in [`zarr.config`][zarr.config]. + fill_value : Any, optional + Fill value for the array. + order : {"C", "F"}, optional + The memory order of the array (default is "C"). + For Zarr format 2, this parameter sets the memory order of the array. + For Zarr format 3, this parameter is deprecated, because memory order + is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory + order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``. + If no ``order`` is provided, a default order will be used. + This default can be changed by modifying the value of ``array.order`` in [`zarr.config`][zarr.config]. + attributes : dict, optional + Attributes for the array. + chunk_key_encoding : ChunkKeyEncoding, optional + A specification of how the chunk keys are represented in storage. + For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``. + For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``. + dimension_names : Iterable[str], optional + The names of the dimensions (default is None). + Zarr format 3 only. Zarr format 2 arrays should not use this parameter. + storage_options : dict, optional + If using an fsspec URL to create the store, these will be passed to the backend implementation. + Ignored otherwise. + overwrite : bool, default False + Whether to overwrite an array with the same name in the store, if one exists. + config : ArrayConfig or ArrayConfigLike, optional + Runtime configuration for the array. + write_data : bool + If a pre-existing array-like object was provided to this function via the ``data`` parameter + then ``write_data`` determines whether the values in that array-like object should be + written to the Zarr array created by this function. If ``write_data`` is ``False``, then the + array will be left empty. + + Returns + ------- + AsyncArray + + """ + compressors = _parse_deprecated_compressor( + compressor, compressors, zarr_format=self.metadata.zarr_format + ) + return await create_array( + store=self.store_path, + name=name, + shape=shape, + dtype=dtype, + data=data, + chunks=chunks, + shards=shards, + filters=filters, + compressors=compressors, + serializer=serializer, + fill_value=fill_value, + order=order, + zarr_format=self.metadata.zarr_format, + attributes=attributes, + chunk_key_encoding=chunk_key_encoding, + dimension_names=dimension_names, + storage_options=storage_options, + overwrite=overwrite, + config=config, + write_data=write_data, + ) + + async def require_array( + self, + name: str, + *, + shape: ShapeLike, + dtype: ZDTypeLike | None = None, + exact: bool = False, + **kwargs: Any, + ) -> AnyAsyncArray: + """Obtain an array, creating if it doesn't exist. + + Other `kwargs` are as per [zarr.AsyncGroup.create_array][]. + + Parameters + ---------- + name : str + Array name. + shape : int or tuple of ints + Array shape. + dtype : ZDTypeLike, optional + The data type of the array, given as a string, a NumPy dtype, or a + Zarr data type. + exact : bool, optional + If True, require `dtype` to match exactly. If false, require + `dtype` can be cast from array dtype. + + Returns + ------- + a : AsyncArray + """ + try: + ds = await self.getitem(name) + if not isinstance(ds, AsyncArray): + raise TypeError(f"Incompatible object ({ds.__class__.__name__}) already exists") + + shape = parse_shapelike(shape) + if shape != ds.shape: + raise TypeError(f"Incompatible shape ({ds.shape} vs {shape})") + + # `np.dtype(None)` used to resolve to float64 here; keep that default. + dtype = parse_data_type( + "float64" if dtype is None else dtype, + zarr_format=self.metadata.zarr_format, + ).to_native_dtype() + if exact: + if ds.dtype != dtype: + raise TypeError(f"Incompatible dtype ({ds.dtype} vs {dtype})") + else: + if not np.can_cast(ds.dtype, dtype): + raise TypeError(f"Incompatible dtype ({ds.dtype} vs {dtype})") + except KeyError: + ds = await self.create_array(name, shape=shape, dtype=dtype, **kwargs) + + return ds + + async def update_attributes(self, new_attributes: dict[str, Any]) -> AsyncGroup: + """Update group attributes. + + Parameters + ---------- + new_attributes : dict + New attributes to set on the group. + + Returns + ------- + self : AsyncGroup + """ + self.metadata.attributes.update(new_attributes) + + # Write new metadata + await self._save_metadata() + + return self + + def __repr__(self) -> str: + return f"" + + async def nmembers( + self, + max_depth: int | None = 0, + ) -> int: + """Count the number of members in this group. + + Parameters + ---------- + max_depth : int, default 0 + The maximum number of levels of the hierarchy to include. By + default, (``max_depth=0``) only immediate children are included. Set + ``max_depth=None`` to include all nodes, and some positive integer + to consider children within that many levels of the root Group. + + Returns + ------- + count : int + """ + # check if we can use consolidated metadata, which requires that we have non-None + # consolidated metadata at all points in the hierarchy. + if self.metadata.consolidated_metadata is not None: + if max_depth is not None and max_depth < 0: + raise ValueError(f"max_depth must be None or >= 0. Got '{max_depth}' instead") + if max_depth is None: + return len(self.metadata.consolidated_metadata.flattened_metadata) + else: + return len( + [ + x + for x in self.metadata.consolidated_metadata.flattened_metadata + if x.count("/") <= max_depth + ] + ) + # TODO: consider using aioitertools.builtins.sum for this + # return await aioitertools.builtins.sum((1 async for _ in self.members()), start=0) + n = 0 + async for _ in self.members(max_depth=max_depth): + n += 1 + return n + + async def members( + self, + max_depth: int | None = 0, + *, + use_consolidated_for_children: bool = True, + ) -> AsyncGenerator[ + tuple[str, AnyAsyncArray | AsyncGroup], + None, + ]: + """ + Returns an AsyncGenerator over the arrays and groups contained in this group. + This method requires that `store_path.store` supports directory listing. + + The results are not guaranteed to be ordered. + + Parameters + ---------- + max_depth : int, default 0 + The maximum number of levels of the hierarchy to include. By + default, (``max_depth=0``) only immediate children are included. Set + ``max_depth=None`` to include all nodes, and some positive integer + to consider children within that many levels of the root Group. + use_consolidated_for_children : bool, default True + Whether to use the consolidated metadata of child groups loaded + from the store. Note that this only affects groups loaded from the + store. If the current Group already has consolidated metadata, it + will always be used. + + Returns + ------- + path: + A string giving the path to the target, relative to the Group ``self``. + value: AsyncArray or AsyncGroup + The AsyncArray or AsyncGroup that is a child of ``self``. + """ + if max_depth is not None and max_depth < 0: + raise ValueError(f"max_depth must be None or >= 0. Got '{max_depth}' instead") + async for item in self._members( + max_depth=max_depth, use_consolidated_for_children=use_consolidated_for_children + ): + yield item + + def _members_consolidated( + self, max_depth: int | None, prefix: str = "" + ) -> Generator[ + tuple[str, AnyAsyncArray | AsyncGroup], + None, + ]: + consolidated_metadata = self.metadata.consolidated_metadata + + do_recursion = max_depth is None or max_depth > 0 + + # we kind of just want the top-level keys. + if consolidated_metadata is not None: + for key in consolidated_metadata.metadata: + obj = self._getitem_consolidated( + self.store_path, key, prefix=self.name + ) # Metadata -> Group/Array + key = f"{prefix}/{key}".lstrip("/") + yield key, obj + + if do_recursion and isinstance(obj, AsyncGroup): + if max_depth is None: + new_depth = None + else: + new_depth = max_depth - 1 + yield from obj._members_consolidated(new_depth, prefix=key) + + async def _members( + self, max_depth: int | None, *, use_consolidated_for_children: bool = True + ) -> AsyncGenerator[tuple[str, AnyAsyncArray | AsyncGroup], None]: + skip_keys: tuple[str, ...] + if self.metadata.zarr_format == 2: + skip_keys = (".zattrs", ".zgroup", ".zarray", ".zmetadata") + elif self.metadata.zarr_format == 3: + skip_keys = ("zarr.json",) + else: + raise ValueError(f"Unknown Zarr format: {self.metadata.zarr_format}") + + if self.metadata.consolidated_metadata is not None: + members = self._members_consolidated(max_depth=max_depth) + for member in members: + yield member + return + + if not self.store_path.store.supports_listing: + msg = ( + f"The store associated with this group ({type(self.store_path.store)}) " + "does not support listing, " + "specifically via the `list_dir` method. " + "This function requires a store that supports listing." + ) + + raise ValueError(msg) + # enforce a concurrency limit by passing a semaphore to all the recursive functions + semaphore = asyncio.Semaphore(config.get("async.concurrency")) + async for member in _iter_members_deep( + self, + max_depth=max_depth, + skip_keys=skip_keys, + semaphore=semaphore, + use_consolidated_for_children=use_consolidated_for_children, + ): + yield member + + async def create_hierarchy( + self, + nodes: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata], + *, + overwrite: bool = False, + ) -> AsyncIterator[tuple[str, AsyncGroup | AnyAsyncArray]]: + """ + Create a hierarchy of arrays or groups rooted at this group. + + This function will parse its input to ensure that the hierarchy is complete. Any implicit groups + will be inserted as needed. For example, an input like + ```{'a/b': GroupMetadata}``` will be parsed to + ```{'': GroupMetadata, 'a': GroupMetadata, 'b': Groupmetadata}```. + + Explicitly specifying a root group, e.g. with ``nodes = {'': GroupMetadata()}`` is an error + because this group instance is the root group. + + After input parsing, this function then creates all the nodes in the hierarchy concurrently. + + Arrays and Groups are yielded in the order they are created. This order is not stable and + should not be relied on. + + Parameters + ---------- + nodes : dict[str, GroupMetadata | ArrayV3Metadata | ArrayV2Metadata] + A dictionary defining the hierarchy. The keys are the paths of the nodes in the hierarchy, + relative to the path of the group. The values are instances of ``GroupMetadata`` or ``ArrayMetadata``. Note that + all values must have the same ``zarr_format`` as the parent group -- it is an error to mix zarr versions in the + same hierarchy. + + Leading "/" characters from keys will be removed. + overwrite : bool + Whether to overwrite existing nodes. Defaults to ``False``, in which case an error is + raised instead of overwriting an existing array or group. + + This function will not erase an existing group unless that group is explicitly named in + ``nodes``. If ``nodes`` defines implicit groups, e.g. ``{`'a/b/c': GroupMetadata}``, and a + group already exists at path ``a``, then this function will leave the group at ``a`` as-is. + + Yields + ------ + tuple[str, AsyncArray | AsyncGroup]. + """ + # check that all the nodes have the same zarr_format as Self + prefix = self.path + nodes_parsed = {} + for key, value in nodes.items(): + if value.zarr_format != self.metadata.zarr_format: + msg = ( + "The zarr_format of the nodes must be the same as the parent group. " + f"The node at {key} has zarr_format {value.zarr_format}, but the parent group" + f" has zarr_format {self.metadata.zarr_format}." + ) + raise ValueError(msg) + if normalize_path(key) == "": + msg = ( + "The input defines a root node, but a root node already exists, namely this Group instance." + "It is an error to use this method to create a root node. " + "Remove the root node from the input dict, or use a function like " + "create_rooted_hierarchy to create a rooted hierarchy." + ) + raise ValueError(msg) + else: + nodes_parsed[_join_paths([prefix, key])] = value + + async for key, node in create_hierarchy( + store=self.store, + nodes=nodes_parsed, + overwrite=overwrite, + ): + if prefix == "": + out_key = key + else: + out_key = key.removeprefix(prefix + "/") + yield out_key, node + + async def keys(self) -> AsyncGenerator[str, None]: + """Iterate over member names.""" + async for key, _ in self.members(): + yield key + + async def contains(self, member: str) -> bool: + """Check if a member exists in the group. + + Parameters + ---------- + member : str + Member name. + + Returns + ------- + bool + """ + # TODO: this can be made more efficient. + try: + await self.getitem(member) + except KeyError: + return False + else: + return True + + async def groups(self) -> AsyncGenerator[tuple[str, AsyncGroup], None]: + """Iterate over subgroups.""" + async for name, value in self.members(): + if isinstance(value, AsyncGroup): + yield name, value + + async def group_keys(self) -> AsyncGenerator[str, None]: + """Iterate over group names.""" + async for key, _ in self.groups(): + yield key + + async def group_values(self) -> AsyncGenerator[AsyncGroup, None]: + """Iterate over group values.""" + async for _, group in self.groups(): + yield group + + async def arrays( + self, + ) -> AsyncGenerator[tuple[str, AnyAsyncArray], None]: + """Iterate over arrays.""" + async for key, value in self.members(): + if isinstance(value, AsyncArray): + yield key, value + + async def array_keys(self) -> AsyncGenerator[str, None]: + """Iterate over array names.""" + async for key, _ in self.arrays(): + yield key + + async def array_values( + self, + ) -> AsyncGenerator[AnyAsyncArray, None]: + """Iterate over array values.""" + async for _, array in self.arrays(): + yield array + + async def tree( + self, + expand: bool | None = None, + level: int | None = None, + *, + max_nodes: int = 500, + plain: bool = False, + ) -> Any: + """ + Return a tree-like representation of a hierarchy. + + Parameters + ---------- + expand : bool, optional + This keyword is not yet supported. A NotImplementedError is raised if + it's used. + level : int, optional + The maximum depth below this Group to display in the tree. + max_nodes : int + Maximum number of nodes to display before truncating. Default is 500. + plain : bool, optional + If True, return a plain-text tree without ANSI styling. This is + useful when the output will be consumed by an LLM or written to a + file. Default is False. + + Returns + ------- + TreeRepr + A pretty-printable object displaying the hierarchy. + """ + from zarr.core._tree import group_tree_async + + if expand is not None: + raise NotImplementedError("'expand' is not yet implemented.") + return await group_tree_async(self, max_depth=level, max_nodes=max_nodes, plain=plain) + + async def empty(self, *, name: str, shape: tuple[int, ...], **kwargs: Any) -> AnyAsyncArray: + """Create an empty array with the specified shape in this Group. The contents will + be filled with the array's fill value or zeros if no fill value is provided. + + Parameters + ---------- + name : str + Name of the array. + shape : int or tuple of int + Shape of the empty array. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Notes + ----- + The contents of an empty Zarr array are not defined. On attempting to + retrieve data from an empty Zarr array, any values may be returned, + and these are not guaranteed to be stable from one access to the next. + """ + return await async_api.empty(shape=shape, store=self.store_path, path=name, **kwargs) + + async def zeros(self, *, name: str, shape: tuple[int, ...], **kwargs: Any) -> AnyAsyncArray: + """Create an array, with zero being used as the default value for uninitialized portions of the array. + + Parameters + ---------- + name : str + Name of the array. + shape : int or tuple of int + Shape of the empty array. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Returns + ------- + AsyncArray + The new array. + """ + return await async_api.zeros(shape=shape, store=self.store_path, path=name, **kwargs) + + async def ones(self, *, name: str, shape: tuple[int, ...], **kwargs: Any) -> AnyAsyncArray: + """Create an array, with one being used as the default value for uninitialized portions of the array. + + Parameters + ---------- + name : str + Name of the array. + shape : int or tuple of int + Shape of the empty array. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Returns + ------- + AsyncArray + The new array. + """ + return await async_api.ones(shape=shape, store=self.store_path, path=name, **kwargs) + + async def full( + self, *, name: str, shape: tuple[int, ...], fill_value: Any | None, **kwargs: Any + ) -> AnyAsyncArray: + """Create an array, with "fill_value" being used as the default value for uninitialized portions of the array. + + Parameters + ---------- + name : str + Name of the array. + shape : int or tuple of int + Shape of the empty array. + fill_value : scalar + Value to fill the array with. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Returns + ------- + AsyncArray + The new array. + """ + return await async_api.full( + shape=shape, + fill_value=fill_value, + store=self.store_path, + path=name, + **kwargs, + ) + + async def empty_like( + self, *, name: str, data: async_api.ArrayLike, **kwargs: Any + ) -> AnyAsyncArray: + """Create an empty sub-array like `data`. The contents will be filled with + the array's fill value or zeros if no fill value is provided. + + Parameters + ---------- + name : str + Name of the array. + data : array-like + The array to create an empty array like. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Returns + ------- + AsyncArray + The new array. + """ + return await async_api.empty_like(a=data, store=self.store_path, path=name, **kwargs) + + async def zeros_like( + self, *, name: str, data: async_api.ArrayLike, **kwargs: Any + ) -> AnyAsyncArray: + """Create a sub-array of zeros like `data`. + + Parameters + ---------- + name : str + Name of the array. + data : array-like + The array to create the new array like. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Returns + ------- + AsyncArray + The new array. + """ + return await async_api.zeros_like(a=data, store=self.store_path, path=name, **kwargs) + + async def ones_like( + self, *, name: str, data: async_api.ArrayLike, **kwargs: Any + ) -> AnyAsyncArray: + """Create a sub-array of ones like `data`. + + Parameters + ---------- + name : str + Name of the array. + data : array-like + The array to create the new array like. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Returns + ------- + AsyncArray + The new array. + """ + return await async_api.ones_like(a=data, store=self.store_path, path=name, **kwargs) + + async def full_like( + self, *, name: str, data: async_api.ArrayLike, **kwargs: Any + ) -> AnyAsyncArray: + """Create a sub-array like `data` filled with the `fill_value` of `data` . + + Parameters + ---------- + name : str + Name of the array. + data : array-like + The array to create the new array like. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Returns + ------- + AsyncArray + The new array. + """ + return await async_api.full_like(a=data, store=self.store_path, path=name, **kwargs) + + async def move(self, source: str, dest: str) -> None: + """Move a sub-group or sub-array from one path to another. + + Notes + ----- + Not implemented + """ + raise NotImplementedError + + +@dataclass(frozen=True) +class Group(SyncMixin): + """ + A Zarr group. + """ + + _async_group: AsyncGroup + + @classmethod + def from_store( + cls, + store: StoreLike, + *, + attributes: dict[str, Any] | None = None, + zarr_format: ZarrFormat = 3, + overwrite: bool = False, + ) -> Group: + """Instantiate a group from an initialized store. + + Parameters + ---------- + store : StoreLike + StoreLike containing the Group. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + attributes : dict, optional + A dictionary of JSON-serializable values with user-defined attributes. + zarr_format : {2, 3}, optional + Zarr storage format version. + overwrite : bool, optional + If True, do not raise an error if the group already exists. + + Returns + ------- + Group + Group instantiated from the store. + + Raises + ------ + ContainsArrayError, ContainsGroupError, ContainsArrayAndGroupError + """ + attributes = attributes or {} + obj = sync( + AsyncGroup.from_store( + store, + attributes=attributes, + overwrite=overwrite, + zarr_format=zarr_format, + ), + ) + + return cls(obj) + + @classmethod + def open( + cls, + store: StoreLike, + zarr_format: ZarrFormat | None = 3, + ) -> Group: + """Open a group from an initialized store. + + Parameters + ---------- + store : StoreLike + Store containing the Group. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + zarr_format : {2, 3, None}, optional + Zarr storage format version. + + Returns + ------- + Group + Group instantiated from the store. + """ + obj = sync(AsyncGroup.open(store, zarr_format=zarr_format)) + return cls(obj) + + def __getitem__(self, path: str) -> AnyArray | Group: + """Obtain a group member. + + Parameters + ---------- + path : str + Group member name. + + Returns + ------- + Array | Group + Group member (Array or Group) at the specified key + + Examples + -------- + ```python + import zarr + from zarr.core.group import Group + group = Group.from_store(zarr.storage.MemoryStore()) + group.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="float64") + group.create_group(name="subgroup").create_array(name="subarray", shape=(10,), chunks=(10,), dtype="float64") + group["subarray"] + # + group["subgroup"] + # + group["subgroup"]["subarray"] + # + ``` + + """ + obj = self._sync(self._async_group.getitem(path)) + if isinstance(obj, AsyncArray): + return Array(obj) + else: + return Group(obj) + + def get[DefaultT]( + self, path: str, default: DefaultT | None = None + ) -> AnyArray | Group | DefaultT | None: + """Obtain a group member, returning default if not found. + + Parameters + ---------- + path : str + Group member name. + default : object + Default value to return if key is not found (default: None). + + Returns + ------- + object + Group member (Array or Group) or default if not found. + + Examples + -------- + ```python + import zarr + from zarr.core.group import Group + group = Group.from_store(zarr.storage.MemoryStore()) + group.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="float64") + group.create_group(name="subgroup") + group.get("subarray") + # + group.get("subgroup") + # + group.get("nonexistent", None) + # None + ``` + + """ + try: + return self[path] + except KeyError: + return default + + def get_array(self, path: str) -> AnyArray: + """Obtain an array member of this group, raising if it is absent or not an array. + + Parameters + ---------- + path : str + Path of the array relative to this group. May contain `/` to reference + a member of a subgroup, e.g. `subgroup/subarray`. + + Returns + ------- + Array + The array at the given path. + + Raises + ------ + ArrayNotFoundError + If no node exists at the given path. + ContainsGroupError + If the node at the given path is a group rather than an array. + + Examples + -------- + ```python + import zarr + from zarr.core.group import Group + group = Group.from_store(zarr.storage.MemoryStore()) + group.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="float64") + group.get_array("subarray") + # + ``` + """ + return Array(self._sync(self._async_group.get_array(path))) + + def get_group(self, path: str) -> Group: + """Obtain a group member of this group, raising if it is absent or not a group. + + Parameters + ---------- + path : str + Path of the group relative to this group. May contain `/` to reference + a member of a subgroup, e.g. `subgroup/subsubgroup`. + + Returns + ------- + Group + The group at the given path. + + Raises + ------ + GroupNotFoundError + If no node exists at the given path. + ContainsArrayError + If the node at the given path is an array rather than a group. + + Examples + -------- + ```python + import zarr + from zarr.core.group import Group + group = Group.from_store(zarr.storage.MemoryStore()) + group.create_group(name="subgroup") + group.get_group("subgroup") + # + ``` + """ + return Group(self._sync(self._async_group.get_group(path))) + + def __delitem__(self, key: str) -> None: + """Delete a group member. + + Parameters + ---------- + key : str + Group member name. + + Examples + -------- + >>> import zarr + >>> group = Group.from_store(zarr.storage.MemoryStore()) + >>> a = group.create_array(name="subarray", dtype="i1", shape=(10,), chunks=(10,)) + >>> del group["subarray"] + >>> "subarray" in group + False + """ + + self._sync(self._async_group.delitem(key)) + + def __iter__(self) -> Iterator[str]: + """Return an iterator over group member names. + Examples + -------- + >>> import zarr + >>> g1 = zarr.group() + >>> g2 = g1.create_group('foo') + >>> g3 = g1.create_group('bar') + >>> d1 = g1.create_array('baz', dtype="i1", shape=(10,), chunks=(10,)) + >>> d2 = g1.create_array('quux', dtype="i1", shape=(10,), chunks=(10,)) + >>> sorted(g1) + ['bar', 'baz', 'foo', 'quux'] + """ + yield from self.keys() + + def __len__(self) -> int: + """Number of members.""" + return self.nmembers() + + def __setitem__(self, key: str, value: Any) -> None: + """Fastpath for creating a new array. + + New arrays will be created using default settings for the array type. + If you need to create an array with custom settings, use the `create_array` method. + + Parameters + ---------- + key : str + Array name. + value : Any + Array data. + + Examples + -------- + >>> import numpy as np + >>> import zarr + >>> group = zarr.group() + >>> group["foo"] = np.array(zarr.zeros((10,))) + >>> group["foo"] + + """ + self._sync(self._async_group.setitem(key, value)) + + def __repr__(self) -> str: + return f"" + + async def update_attributes_async(self, new_attributes: dict[str, Any]) -> Group: + """Update the attributes of this group. + + Examples + -------- + >>> async def example(): + ... import zarr + ... + ... group = zarr.group() + ... new_group = await group.update_attributes_async({"foo": "bar"}) + ... return new_group.attrs.asdict() + + >>> import asyncio + >>> asyncio.run(example()) + {'foo': 'bar'} + """ + new_metadata = replace(self.metadata, attributes=new_attributes) + + # Write new metadata + to_save = new_metadata.to_buffer_dict(default_buffer_prototype()) + awaitables = [set_or_delete(self.store_path / key, value) for key, value in to_save.items()] + await asyncio.gather(*awaitables) + + async_group = replace(self._async_group, metadata=new_metadata) + return replace(self, _async_group=async_group) + + @property + def store_path(self) -> StorePath: + """Path-like interface for the Store.""" + return self._async_group.store_path + + @property + def metadata(self) -> GroupMetadata: + """Group metadata.""" + return self._async_group.metadata + + @property + def path(self) -> str: + """Storage path.""" + return self._async_group.path + + @property + def name(self) -> str: + """Group name following h5py convention.""" + return self._async_group.name + + @property + def basename(self) -> str: + """Final component of name.""" + return self._async_group.basename + + @property + def attrs(self) -> Attributes: + """Attributes of this Group""" + return Attributes(self) + + @property + def info(self) -> Any: + """ + Return the statically known information for a group. + + Returns + ------- + GroupInfo + + Related + ------- + [zarr.Group.info_complete][] + All information about a group, including dynamic information + like the children members. + """ + return self._async_group.info + + def info_complete(self) -> Any: + """ + Return information for a group. + + If this group doesn't contain consolidated metadata then + this will need to read from the backing Store. + + Returns + ------- + GroupInfo + + Related + ------- + [zarr.Group.info][] + """ + return self._sync(self._async_group.info_complete()) + + @property + def store(self) -> Store: + # Backwards compatibility for 2.x + return self._async_group.store + + @property + def read_only(self) -> bool: + # Backwards compatibility for 2.x + return self._async_group.read_only + + @property + def synchronizer(self) -> None: + # Backwards compatibility for 2.x + # Not implemented in 3.x yet. + return self._async_group.synchronizer + + def update_attributes(self, new_attributes: dict[str, Any]) -> Group: + """Update the attributes of this group. + + Examples + -------- + >>> import zarr + >>> group = zarr.group().update_attributes({"foo": "bar"}) + >>> group.attrs.asdict() + {'foo': 'bar'} + """ + self._sync(self._async_group.update_attributes(new_attributes)) + return self + + def nmembers(self, max_depth: int | None = 0) -> int: + """Count the number of members in this group. + + Parameters + ---------- + max_depth : int, default 0 + The maximum number of levels of the hierarchy to include. By + default, (``max_depth=0``) only immediate children are included. Set + ``max_depth=None`` to include all nodes, and some positive integer + to consider children within that many levels of the root Group. + + Returns + ------- + count : int + """ + + return self._sync(self._async_group.nmembers(max_depth=max_depth)) + + def members( + self, max_depth: int | None = 0, *, use_consolidated_for_children: bool = True + ) -> tuple[tuple[str, AnyArray | Group], ...]: + """ + Returns an AsyncGenerator over the arrays and groups contained in this group. + This method requires that `store_path.store` supports directory listing. + + The results are not guaranteed to be ordered. + + Parameters + ---------- + max_depth : int, default 0 + The maximum number of levels of the hierarchy to include. By + default, (``max_depth=0``) only immediate children are included. Set + ``max_depth=None`` to include all nodes, and some positive integer + to consider children within that many levels of the root Group. + use_consolidated_for_children : bool, default True + Whether to use the consolidated metadata of child groups loaded + from the store. Note that this only affects groups loaded from the + store. If the current Group already has consolidated metadata, it + will always be used. + + Returns + ------- + path: + A string giving the path to the target, relative to the Group ``self``. + value: AsyncArray or AsyncGroup + The AsyncArray or AsyncGroup that is a child of ``self``. + """ + _members = self._sync_iter(self._async_group.members(max_depth=max_depth)) + + return tuple((kv[0], _parse_async_node(kv[1])) for kv in _members) + + def create_hierarchy( + self, + nodes: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata], + *, + overwrite: bool = False, + ) -> Iterator[tuple[str, Group | AnyArray]]: + """ + Create a hierarchy of arrays or groups rooted at this group. + + This function will parse its input to ensure that the hierarchy is complete. Any implicit groups + will be inserted as needed. For example, an input like + ```{'a/b': GroupMetadata}``` will be parsed to + ```{'': GroupMetadata, 'a': GroupMetadata, 'b': Groupmetadata}```. + + Explicitly specifying a root group, e.g. with ``nodes = {'': GroupMetadata()}`` is an error + because this group instance is the root group. + + After input parsing, this function then creates all the nodes in the hierarchy concurrently. + + Arrays and Groups are yielded in the order they are created. This order is not stable and + should not be relied on. + + Parameters + ---------- + nodes : dict[str, GroupMetadata | ArrayV3Metadata | ArrayV2Metadata] + A dictionary defining the hierarchy. The keys are the paths of the nodes in the hierarchy, + relative to the path of the group. The values are instances of ``GroupMetadata`` or ``ArrayMetadata``. Note that + all values must have the same ``zarr_format`` as the parent group -- it is an error to mix zarr versions in the + same hierarchy. + + Leading "/" characters from keys will be removed. + overwrite : bool + Whether to overwrite existing nodes. Defaults to ``False``, in which case an error is + raised instead of overwriting an existing array or group. + + This function will not erase an existing group unless that group is explicitly named in + ``nodes``. If ``nodes`` defines implicit groups, e.g. ``{`'a/b/c': GroupMetadata}``, and a + group already exists at path ``a``, then this function will leave the group at ``a`` as-is. + + Yields + ------ + tuple[str, Array | Group]. + + Examples + -------- + >>> import zarr + >>> from zarr.core.group import GroupMetadata + >>> root = zarr.create_group(store={}) + >>> sorted(root.create_hierarchy({'a/b/c': GroupMetadata()})) + [('a', ), + ('a/b', ), + ('a/b/c', )] + """ + for key, node in self._sync_iter( + self._async_group.create_hierarchy(nodes, overwrite=overwrite) + ): + yield (key, _parse_async_node(node)) + + def keys(self) -> Generator[str]: + """Return an iterator over group member names. + + Examples + -------- + >>> import zarr + >>> g1 = zarr.group() + >>> g2 = g1.create_group('foo') + >>> g3 = g1.create_group('bar') + >>> d1 = g1.create_array('baz', dtype="i1", shape=(10,), chunks=(10,)) + >>> d2 = g1.create_array('quux', dtype="i1", shape=(10,), chunks=(10,)) + >>> sorted(g1.keys()) + ['bar', 'baz', 'foo', 'quux'] + """ + yield from self._sync_iter(self._async_group.keys()) + + def __contains__(self, member: str) -> bool: + """Test for group membership. + + Examples + -------- + >>> import zarr + >>> g1 = zarr.group() + >>> g2 = g1.create_group('foo') + >>> d1 = g1.create_array('bar', dtype="i1", shape=(10,), chunks=(10,)) + >>> 'foo' in g1 + True + >>> 'bar' in g1 + True + >>> 'baz' in g1 + False + """ + return self._sync(self._async_group.contains(member)) + + def groups(self) -> Generator[tuple[str, Group], None]: + """Return the sub-groups of this group as a generator of (name, group) pairs. + + Examples + -------- + >>> import zarr + >>> group = zarr.group() + >>> subgroup = group.create_group("subgroup") + >>> list(group.groups()) + [('subgroup', )] + """ + for name, async_group in self._sync_iter(self._async_group.groups()): + yield name, Group(async_group) + + def group_keys(self) -> Generator[str, None]: + """Return an iterator over group member names. + + Examples + -------- + >>> import zarr + >>> group = zarr.group() + >>> subgroup = group.create_group("subgroup") + >>> list(group.group_keys()) + ['subgroup'] + """ + for name, _ in self.groups(): + yield name + + def group_values(self) -> Generator[Group, None]: + """Return an iterator over group members. + + Examples + -------- + >>> import zarr + >>> group = zarr.group() + >>> subgroup = group.create_group("subgroup") + >>> list(group.group_values()) + [] + """ + for _, group in self.groups(): + yield group + + def arrays(self) -> Generator[tuple[str, AnyArray], None]: + """Return the sub-arrays of this group as a generator of (name, array) pairs + + Examples + -------- + >>> import zarr + >>> group = zarr.group() + >>> subarray = group.create_array("subarray", dtype="i1", shape=(10,), chunks=(10,)) + >>> list(group.arrays()) + [('subarray', )] + """ + for name, async_array in self._sync_iter(self._async_group.arrays()): + yield name, Array(async_array) + + def array_keys(self) -> Generator[str, None]: + """Return an iterator over group member names. + + Examples + -------- + >>> import zarr + >>> group = zarr.group() + >>> subarray = group.create_array("subarray", dtype="i1", shape=(10,), chunks=(10,)) + >>> list(group.array_keys()) + ['subarray'] + """ + + for name, _ in self.arrays(): + yield name + + def array_values(self) -> Generator[AnyArray, None]: + """Return an iterator over group members. + + Examples + -------- + >>> import zarr + >>> group = zarr.group() + >>> subarray = group.create_array("subarray", dtype="i1", shape=(10,), chunks=(10,)) + >>> list(group.array_values()) + [] + """ + for _, array in self.arrays(): + yield array + + def tree( + self, + expand: bool | None = None, + level: int | None = None, + *, + max_nodes: int = 500, + plain: bool = False, + ) -> Any: + """ + Return a tree-like representation of a hierarchy. + + Parameters + ---------- + expand : bool, optional + This keyword is not yet supported. A NotImplementedError is raised if + it's used. + level : int, optional + The maximum depth below this Group to display in the tree. + max_nodes : int + Maximum number of nodes to display before truncating. Default is 500. + plain : bool, optional + If True, return a plain-text tree without ANSI styling. This is + useful when the output will be consumed by an LLM or written to a + file. Default is False. + + Returns + ------- + TreeRepr + A pretty-printable object displaying the hierarchy. + """ + return self._sync( + self._async_group.tree(expand=expand, level=level, max_nodes=max_nodes, plain=plain) + ) + + def create_group(self, name: str, **kwargs: Any) -> Group: + """Create a sub-group. + + Parameters + ---------- + name : str + Name of the new subgroup. + + Returns + ------- + Group + + Examples + -------- + >>> import zarr + >>> group = zarr.group() + >>> subgroup = group.create_group("subgroup") + >>> subgroup + + """ + return Group(self._sync(self._async_group.create_group(name, **kwargs))) + + def require_group(self, name: str, **kwargs: Any) -> Group: + """Obtain a sub-group, creating one if it doesn't exist. + + Parameters + ---------- + name : str + Group name. + + Returns + ------- + g : Group + """ + return Group(self._sync(self._async_group.require_group(name, **kwargs))) + + def require_groups(self, *names: str) -> tuple[Group, ...]: + """Convenience method to require multiple groups in a single call. + + Parameters + ---------- + *names : str + Group names. + + Returns + ------- + groups : tuple of Groups + """ + return tuple(map(Group, self._sync(self._async_group.require_groups(*names)))) + + def create( + self, + name: str, + *, + shape: ShapeLike | None = None, + dtype: ZDTypeLike | None = None, + data: np.ndarray[Any, np.dtype[Any]] | None = None, + chunks: ChunksLike | Literal["auto"] = "auto", + shards: ShardsLike | None = None, + filters: FiltersLike = "auto", + compressors: CompressorsLike = "auto", + compressor: CompressorLike = "auto", + serializer: SerializerLike = "auto", + fill_value: Any | None = DEFAULT_FILL_VALUE, + order: MemoryOrder | None = None, + attributes: dict[str, JSON] | None = None, + chunk_key_encoding: ChunkKeyEncodingLike | None = None, + dimension_names: DimensionNamesLike = None, + storage_options: dict[str, Any] | None = None, + overwrite: bool = False, + config: ArrayConfigLike | None = None, + write_data: bool = True, + ) -> AnyArray: + """Create an array within this group. + + This method lightly wraps [`zarr.core.array.create_array`][]. + + Parameters + ---------- + name : str + The name of the array relative to the group. If ``path`` is ``None``, the array will be located + at the root of the store. + shape : ShapeLike, optional + Shape of the array. Must be ``None`` if ``data`` is provided. + dtype : npt.DTypeLike | None + Data type of the array. Must be ``None`` if ``data`` is provided. + data : Array-like data to use for initializing the array. If this parameter is provided, the + ``shape`` and ``dtype`` parameters must be ``None``. + chunks : tuple[int, ...], optional + Chunk shape of the array. + If not specified, default are guessed based on the shape and dtype. + shards : tuple[int, ...], optional + Shard shape of the array. The default value of ``None`` results in no sharding at all. + filters : Iterable[Codec] | Literal["auto"], optional + Iterable of filters to apply to each chunk of the array, in order, before serializing that + chunk to bytes. + + For Zarr format 3, a "filter" is a codec that takes an array and returns an array, + and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a + dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. + + For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the + order of your filters is consistent with the behavior of each filter. + + The default value of ``"auto"`` instructs Zarr to use a default based on the data + type of the array and the Zarr format specified. For all data types in Zarr V3, and most + data types in Zarr V2, the default filters are empty. The only cases where default filters + are not empty is when the Zarr format is 2, and the data type is a variable-length data type like + [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, + the default filters contains a single element which is a codec specific to that particular data type. + + To create an array with no filters, provide an empty iterable or the value ``None``. + compressors : Iterable[Codec], optional + List of compressors to apply to the array. Compressors are applied in order, and after any + filters are applied (if any are specified) and the data is serialized into bytes. + + For Zarr format 3, a "compressor" is a codec that takes a bytestream, and + returns another bytestream. Multiple compressors may be provided for Zarr format 3. + If no ``compressors`` are provided, a default set of compressors will be used. + These defaults can be changed by modifying the value of ``array.v3_default_compressors`` + in [`zarr.config`][]. + Use ``None`` to omit default compressors. + + For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may + be provided for Zarr format 2. + If no ``compressor`` is provided, a default compressor will be used. + in [`zarr.config`][]. + Use ``None`` to omit the default compressor. + compressor : Codec, optional + Deprecated in favor of ``compressors``. + serializer : dict[str, JSON] | ArrayBytesCodec, optional + Array-to-bytes codec to use for encoding the array data. + Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. + If no ``serializer`` is provided, a default serializer will be used. + These defaults can be changed by modifying the value of ``array.v3_default_serializer`` + in [`zarr.config`][]. + fill_value : Any, optional + Fill value for the array. + order : {"C", "F"}, optional + The memory order of the array (default is "C"). + For Zarr format 2, this parameter sets the memory order of the array. + For Zarr format 3, this parameter is deprecated, because memory order + is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory + order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``. + If no ``order`` is provided, a default order will be used. + This default can be changed by modifying the value of ``array.order`` in [`zarr.config`][]. + attributes : dict, optional + Attributes for the array. + chunk_key_encoding : ChunkKeyEncoding, optional + A specification of how the chunk keys are represented in storage. + For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``. + For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``. + dimension_names : Iterable[str], optional + The names of the dimensions (default is None). + Zarr format 3 only. Zarr format 2 arrays should not use this parameter. + storage_options : dict, optional + If using an fsspec URL to create the store, these will be passed to the backend implementation. + Ignored otherwise. + overwrite : bool, default False + Whether to overwrite an array with the same name in the store, if one exists. + config : ArrayConfig or ArrayConfigLike, optional + Runtime configuration for the array. + write_data : bool + If a pre-existing array-like object was provided to this function via the ``data`` parameter + then ``write_data`` determines whether the values in that array-like object should be + written to the Zarr array created by this function. If ``write_data`` is ``False``, then the + array will be left empty. + + Returns + ------- + AsyncArray + """ + return self.create_array( + name, + shape=shape, + dtype=dtype, + data=data, + chunks=chunks, + shards=shards, + filters=filters, + compressors=compressors, + compressor=compressor, + serializer=serializer, + fill_value=fill_value, + order=order, + attributes=attributes, + chunk_key_encoding=chunk_key_encoding, + dimension_names=dimension_names, + storage_options=storage_options, + overwrite=overwrite, + config=config, + write_data=write_data, + ) + + def create_array( + self, + name: str, + *, + shape: ShapeLike | None = None, + dtype: ZDTypeLike | None = None, + data: np.ndarray[Any, np.dtype[Any]] | None = None, + chunks: ChunksLike | Literal["auto"] = "auto", + shards: ShardsLike | None = None, + filters: FiltersLike = "auto", + compressors: CompressorsLike = "auto", + compressor: CompressorLike = "auto", + serializer: SerializerLike = "auto", + fill_value: Any | None = DEFAULT_FILL_VALUE, + order: MemoryOrder | None = None, + attributes: dict[str, JSON] | None = None, + chunk_key_encoding: ChunkKeyEncodingLike | None = None, + dimension_names: DimensionNamesLike = None, + storage_options: dict[str, Any] | None = None, + overwrite: bool = False, + config: ArrayConfigLike | None = None, + write_data: bool = True, + ) -> AnyArray: + """Create an array within this group. + + This method lightly wraps [zarr.core.array.create_array][]. + + Parameters + ---------- + name : str + The name of the array relative to the group. If ``path`` is ``None``, the array will be located + at the root of the store. + shape : ShapeLike, optional + Shape of the array. Must be ``None`` if ``data`` is provided. + dtype : npt.DTypeLike | None + Data type of the array. Must be ``None`` if ``data`` is provided. + data : Array-like data to use for initializing the array. If this parameter is provided, the + ``shape`` and ``dtype`` parameters must be ``None``. + chunks : tuple[int, ...], optional + Chunk shape of the array. + If not specified, default are guessed based on the shape and dtype. + shards : tuple[int, ...], optional + Shard shape of the array. The default value of ``None`` results in no sharding at all. + filters : Iterable[Codec] | Literal["auto"], optional + Iterable of filters to apply to each chunk of the array, in order, before serializing that + chunk to bytes. + + For Zarr format 3, a "filter" is a codec that takes an array and returns an array, + and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a + dict representations of [`zarr.abc.codec.ArrayArrayCodec`][]. + + For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the + order of your filters is consistent with the behavior of each filter. + + The default value of ``"auto"`` instructs Zarr to use a default based on the data + type of the array and the Zarr format specified. For all data types in Zarr V3, and most + data types in Zarr V2, the default filters are empty. The only cases where default filters + are not empty is when the Zarr format is 2, and the data type is a variable-length data type like + [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases, + the default filters contains a single element which is a codec specific to that particular data type. + + To create an array with no filters, provide an empty iterable or the value ``None``. + compressors : Iterable[Codec], optional + List of compressors to apply to the array. Compressors are applied in order, and after any + filters are applied (if any are specified) and the data is serialized into bytes. + + For Zarr format 3, a "compressor" is a codec that takes a bytestream, and + returns another bytestream. Multiple compressors may be provided for Zarr format 3. + If no ``compressors`` are provided, a default set of compressors will be used. + These defaults can be changed by modifying the value of ``array.v3_default_compressors`` + in [`zarr.config`][zarr.config]. + Use ``None`` to omit default compressors. + + For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may + be provided for Zarr format 2. + If no ``compressor`` is provided, a default compressor will be used. + in [`zarr.config`][zarr.config]. + Use ``None`` to omit the default compressor. + compressor : Codec, optional + Deprecated in favor of ``compressors``. + serializer : dict[str, JSON] | ArrayBytesCodec, optional + Array-to-bytes codec to use for encoding the array data. + Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. + If no ``serializer`` is provided, a default serializer will be used. + These defaults can be changed by modifying the value of ``array.v3_default_serializer`` + in [`zarr.config`][zarr.config]. + fill_value : Any, optional + Fill value for the array. + order : {"C", "F"}, optional + The memory order of the array (default is "C"). + For Zarr format 2, this parameter sets the memory order of the array. + For Zarr format 3, this parameter is deprecated, because memory order + is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory + order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``. + If no ``order`` is provided, a default order will be used. + This default can be changed by modifying the value of ``array.order`` in [`zarr.config`][zarr.config]. + attributes : dict, optional + Attributes for the array. + chunk_key_encoding : ChunkKeyEncoding, optional + A specification of how the chunk keys are represented in storage. + For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``. + For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``. + dimension_names : Iterable[str], optional + The names of the dimensions (default is None). + Zarr format 3 only. Zarr format 2 arrays should not use this parameter. + storage_options : dict, optional + If using an fsspec URL to create the store, these will be passed to the backend implementation. + Ignored otherwise. + overwrite : bool, default False + Whether to overwrite an array with the same name in the store, if one exists. + config : ArrayConfig or ArrayConfigLike, optional + Runtime configuration for the array. + write_data : bool + If a pre-existing array-like object was provided to this function via the ``data`` parameter + then ``write_data`` determines whether the values in that array-like object should be + written to the Zarr array created by this function. If ``write_data`` is ``False``, then the + array will be left empty. + + Returns + ------- + AsyncArray + """ + compressors = _parse_deprecated_compressor( + compressor, compressors, zarr_format=self.metadata.zarr_format + ) + return Array( + self._sync( + self._async_group.create_array( + name=name, + shape=shape, + dtype=dtype, + data=data, + chunks=chunks, + shards=shards, + fill_value=fill_value, + attributes=attributes, + chunk_key_encoding=chunk_key_encoding, + compressors=compressors, + serializer=serializer, + dimension_names=dimension_names, + order=order, + filters=filters, + overwrite=overwrite, + storage_options=storage_options, + config=config, + write_data=write_data, + ) + ) + ) + + def require_array(self, name: str, *, shape: ShapeLike, **kwargs: Any) -> AnyArray: + """Obtain an array, creating if it doesn't exist. + + Other `kwargs` are as per [zarr.Group.create_array][]. + + Parameters + ---------- + name : str + Array name. + **kwargs : + See [zarr.Group.create_array][]. + + Returns + ------- + a : Array + """ + return Array(self._sync(self._async_group.require_array(name, shape=shape, **kwargs))) + + def empty(self, *, name: str, shape: tuple[int, ...], **kwargs: Any) -> AnyArray: + """Create an empty array with the specified shape in this Group. The contents will be filled with + the array's fill value or zeros if no fill value is provided. + + Parameters + ---------- + name : str + Name of the array. + shape : int or tuple of int + Shape of the empty array. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Notes + ----- + The contents of an empty Zarr array are not defined. On attempting to + retrieve data from an empty Zarr array, any values may be returned, + and these are not guaranteed to be stable from one access to the next. + """ + return Array(self._sync(self._async_group.empty(name=name, shape=shape, **kwargs))) + + def zeros(self, *, name: str, shape: tuple[int, ...], **kwargs: Any) -> AnyArray: + """Create an array, with zero being used as the default value for uninitialized portions of the array. + + Parameters + ---------- + name : str + Name of the array. + shape : int or tuple of int + Shape of the empty array. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Returns + ------- + Array + The new array. + """ + return Array(self._sync(self._async_group.zeros(name=name, shape=shape, **kwargs))) + + def ones(self, *, name: str, shape: tuple[int, ...], **kwargs: Any) -> AnyArray: + """Create an array, with one being used as the default value for uninitialized portions of the array. + + Parameters + ---------- + name : str + Name of the array. + shape : int or tuple of int + Shape of the empty array. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Returns + ------- + Array + The new array. + """ + return Array(self._sync(self._async_group.ones(name=name, shape=shape, **kwargs))) + + def full( + self, *, name: str, shape: tuple[int, ...], fill_value: Any | None, **kwargs: Any + ) -> AnyArray: + """Create an array, with "fill_value" being used as the default value for uninitialized portions of the array. + + Parameters + ---------- + name : str + Name of the array. + shape : int or tuple of int + Shape of the empty array. + fill_value : scalar + Value to fill the array with. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Returns + ------- + Array + The new array. + """ + return Array( + self._sync( + self._async_group.full(name=name, shape=shape, fill_value=fill_value, **kwargs) + ) + ) + + def empty_like(self, *, name: str, data: async_api.ArrayLike, **kwargs: Any) -> AnyArray: + """Create an empty sub-array like `data`. The contents will be filled + with the array's fill value or zeros if no fill value is provided. + + Parameters + ---------- + name : str + Name of the array. + data : array-like + The array to create an empty array like. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Returns + ------- + Array + The new array. + + Notes + ----- + The contents of an empty Zarr array are not defined. On attempting to + retrieve data from an empty Zarr array, any values may be returned, + and these are not guaranteed to be stable from one access to the next. + """ + return Array(self._sync(self._async_group.empty_like(name=name, data=data, **kwargs))) + + def zeros_like(self, *, name: str, data: async_api.ArrayLike, **kwargs: Any) -> AnyArray: + """Create a sub-array of zeros like `data`. + + Parameters + ---------- + name : str + Name of the array. + data : array-like + The array to create the new array like. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Returns + ------- + Array + The new array. + """ + + return Array(self._sync(self._async_group.zeros_like(name=name, data=data, **kwargs))) + + def ones_like(self, *, name: str, data: async_api.ArrayLike, **kwargs: Any) -> AnyArray: + """Create a sub-array of ones like `data`. + + Parameters + ---------- + name : str + Name of the array. + data : array-like + The array to create the new array like. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Returns + ------- + Array + The new array. + """ + return Array(self._sync(self._async_group.ones_like(name=name, data=data, **kwargs))) + + def full_like(self, *, name: str, data: async_api.ArrayLike, **kwargs: Any) -> AnyArray: + """Create a sub-array like `data` filled with the `fill_value` of `data` . + + Parameters + ---------- + name : str + Name of the array. + data : array-like + The array to create the new array like. + **kwargs + Keyword arguments passed to [zarr.api.asynchronous.create][]. + + Returns + ------- + Array + The new array. + """ + return Array(self._sync(self._async_group.full_like(name=name, data=data, **kwargs))) + + def move(self, source: str, dest: str) -> None: + """Move a sub-group or sub-array from one path to another. + + Notes + ----- + Not implemented + """ + return self._sync(self._async_group.move(source, dest)) + + +async def create_hierarchy( + *, + store: Store, + nodes: dict[str, GroupMetadata | ArrayV2Metadata | ArrayV3Metadata], + overwrite: bool = False, +) -> AsyncIterator[tuple[str, AsyncGroup | AnyAsyncArray]]: + """ + Create a complete zarr hierarchy from a collection of metadata objects. + + This function will parse its input to ensure that the hierarchy is complete. Any implicit groups + will be inserted as needed. For example, an input like + ```{'a/b': GroupMetadata}``` will be parsed to + ```{'': GroupMetadata, 'a': GroupMetadata, 'b': Groupmetadata}``` + + After input parsing, this function then creates all the nodes in the hierarchy concurrently. + + Arrays and Groups are yielded in the order they are created. This order is not stable and + should not be relied on. + + Parameters + ---------- + store : Store + The storage backend to use. + nodes : dict[str, GroupMetadata | ArrayV3Metadata | ArrayV2Metadata] + A dictionary defining the hierarchy. The keys are the paths of the nodes in the hierarchy, + relative to the root of the ``Store``. The root of the store can be specified with the empty + string ``''``. The values are instances of ``GroupMetadata`` or ``ArrayMetadata``. Note that + all values must have the same ``zarr_format`` -- it is an error to mix zarr versions in the + same hierarchy. + + Leading "/" characters from keys will be removed. + overwrite : bool + Whether to overwrite existing nodes. Defaults to ``False``, in which case an error is + raised instead of overwriting an existing array or group. + + This function will not erase an existing group unless that group is explicitly named in + ``nodes``. If ``nodes`` defines implicit groups, e.g. ``{`'a/b/c': GroupMetadata}``, and a + group already exists at path ``a``, then this function will leave the group at ``a`` as-is. + + Yields + ------ + tuple[str, AsyncGroup | AsyncArray] + Yields (path, node) pairs, in the order the nodes were created. + + Examples + -------- + >>> async def example(): + ... from zarr.api.asynchronous import create_hierarchy + ... from zarr.core.group import GroupMetadata + ... from zarr.storage import MemoryStore + ... + ... store = MemoryStore() + ... nodes = {'a': GroupMetadata(attributes={'name': 'leaf'})} + ... return sorted([x async for x in create_hierarchy(store=store, nodes=nodes)]) + + >>> import asyncio + >>> asyncio.run(example()) + [('', ), ('a', )] + """ + + # normalize the keys to be valid paths + nodes_normed_keys = _normalize_path_keys(nodes) + + # ensure that all nodes have the same zarr_format, and add implicit groups as needed + nodes_parsed = _parse_hierarchy_dict(data=nodes_normed_keys) + redundant_implicit_groups = [] + + # empty hierarchies should be a no-op + if len(nodes_parsed) > 0: + # figure out which zarr format we are using + zarr_format = next(iter(nodes_parsed.values())).zarr_format + + # check which implicit groups will require materialization + implicit_group_keys = tuple( + filter(lambda k: isinstance(nodes_parsed[k], ImplicitGroupMarker), nodes_parsed) + ) + # read potential group metadata for each implicit group + maybe_extant_group_coros = ( + _read_group_metadata(store, k, zarr_format=zarr_format) for k in implicit_group_keys + ) + maybe_extant_groups = await asyncio.gather( + *maybe_extant_group_coros, return_exceptions=True + ) + + for key, value in zip(implicit_group_keys, maybe_extant_groups, strict=True): + if isinstance(value, BaseException): + if isinstance(value, FileNotFoundError): + # this is fine -- there was no group there, so we will create one + pass + else: + raise value + else: + # a loop exists already at ``key``, so we can avoid creating anything there + redundant_implicit_groups.append(key) + + if overwrite: + # we will remove any nodes that collide with arrays and non-implicit groups defined in + # nodes + + # track the keys of nodes we need to delete + to_delete_keys = [] + to_delete_keys.extend( + [k for k, v in nodes_parsed.items() if k not in implicit_group_keys] + ) + await asyncio.gather(*(store.delete_dir(key) for key in to_delete_keys)) + else: + # This type is long. + coros: ( + Generator[Coroutine[Any, Any, ArrayV2Metadata | GroupMetadata], None, None] + | Generator[Coroutine[Any, Any, ArrayV3Metadata | GroupMetadata], None, None] + ) + if zarr_format == 2: + coros = (_read_metadata_v2(store=store, path=key) for key in nodes_parsed) + elif zarr_format == 3: + coros = (_read_metadata_v3(store=store, path=key) for key in nodes_parsed) + else: # pragma: no cover + raise ValueError(f"Invalid zarr_format: {zarr_format}") # pragma: no cover + + extant_node_query = dict( + zip( + nodes_parsed.keys(), + await asyncio.gather(*coros, return_exceptions=True), + strict=False, + ) + ) + # iterate over the existing arrays / groups and figure out which of them conflict + # with the arrays / groups we want to create + for key, extant_node in extant_node_query.items(): + proposed_node = nodes_parsed[key] + if isinstance(extant_node, BaseException): + if isinstance(extant_node, FileNotFoundError): + # ignore FileNotFoundError, because they represent nodes we can safely create + pass + else: + # Any other exception is a real error + raise extant_node + else: + # this is a node that already exists, but a node with the same key was specified + # in nodes_parsed. + if isinstance(extant_node, GroupMetadata): + # a group already exists where we want to create a group + if isinstance(proposed_node, ImplicitGroupMarker): + # we have proposed an implicit group, which is OK -- we will just skip + # creating this particular metadata document + redundant_implicit_groups.append(key) + else: + # we have proposed an explicit group, which is an error, given that a + # group already exists. + msg = f"A group exists in store {store!r} at path {key!r}." + raise ContainsGroupError(msg) + elif isinstance(extant_node, ArrayV2Metadata | ArrayV3Metadata): + # we are trying to overwrite an existing array. this is an error. + msg = f"An array exists in store {store!r} at path {key!r}." + raise ContainsArrayError(msg) + + nodes_explicit: dict[str, GroupMetadata | ArrayV2Metadata | ArrayV3Metadata] = {} + + for k, v in nodes_parsed.items(): + if k not in redundant_implicit_groups: + if isinstance(v, ImplicitGroupMarker): + nodes_explicit[k] = GroupMetadata(zarr_format=v.zarr_format) + else: + nodes_explicit[k] = v + + async for key, node in create_nodes(store=store, nodes=nodes_explicit): + yield key, node + + +async def create_nodes( + *, + store: Store, + nodes: dict[str, GroupMetadata | ArrayV2Metadata | ArrayV3Metadata], +) -> AsyncIterator[tuple[str, AsyncGroup | AnyAsyncArray]]: + """Create a collection of arrays and / or groups concurrently. + + Note: no attempt is made to validate that these arrays and / or groups collectively form a + valid Zarr hierarchy. It is the responsibility of the caller of this function to ensure that + the ``nodes`` parameter satisfies any correctness constraints. + + Parameters + ---------- + store : Store + The storage backend to use. + nodes : dict[str, GroupMetadata | ArrayV3Metadata | ArrayV2Metadata] + A dictionary defining the hierarchy. The keys are the paths of the nodes + in the hierarchy, and the values are the metadata of the nodes. The + metadata must be either an instance of GroupMetadata, ArrayV3Metadata + or ArrayV2Metadata. + + Yields + ------ + AsyncGroup | AsyncArray + The created nodes in the order they are created. + """ + + # Note: the only way to alter this value is via the config. If that's undesirable for some reason, + # then we should consider adding a keyword argument to this function + semaphore = asyncio.Semaphore(config.get("async.concurrency")) + create_tasks: list[Coroutine[None, None, str]] = [] + + for key, value in nodes.items(): + # make the key absolute + create_tasks.extend(_persist_metadata(store, key, value, semaphore=semaphore)) + + created_object_keys = [] + + for coro in asyncio.as_completed(create_tasks): + created_key = await coro + # we need this to track which metadata documents were written so that we can yield a + # complete v2 Array / Group class after both .zattrs and the metadata JSON was created. + created_object_keys.append(created_key) + + # get the node name from the object key + if len(created_key.split("/")) == 1: + # this is the root node + meta_out = nodes[""] + node_name = "" + else: + # turn "foo/" into "foo" + node_name = created_key[: created_key.rfind("/")] + meta_out = nodes[node_name] + if meta_out.zarr_format == 3: + yield node_name, _build_node(store=store, path=node_name, metadata=meta_out) + else: + # For zarr v2 + # we only want to yield when both the metadata and attributes are created + # so we track which keys have been created, and wait for both the meta key and + # the attrs key to be created before yielding back the AsyncArray / AsyncGroup + + attrs_done = _join_paths([node_name, ZATTRS_JSON]) in created_object_keys + + if isinstance(meta_out, GroupMetadata): + meta_done = _join_paths([node_name, ZGROUP_JSON]) in created_object_keys + else: + meta_done = _join_paths([node_name, ZARRAY_JSON]) in created_object_keys + + if meta_done and attrs_done: + yield node_name, _build_node(store=store, path=node_name, metadata=meta_out) + + continue + + +def _get_roots( + data: Iterable[str], +) -> tuple[str, ...]: + """ + Return the keys of the root(s) of the hierarchy. A root is a key with the fewest number of + path segments. + """ + if "" in data: + return ("",) + keys_split = sorted((key.split("/") for key in data), key=len) + groups: defaultdict[int, list[str]] = defaultdict(list) + for key_split in keys_split: + groups[len(key_split)].append("/".join(key_split)) + return tuple(groups[min(groups.keys())]) + + +def _parse_hierarchy_dict( + *, + data: Mapping[str, ImplicitGroupMarker | GroupMetadata | ArrayV2Metadata | ArrayV3Metadata], +) -> dict[str, ImplicitGroupMarker | GroupMetadata | ArrayV2Metadata | ArrayV3Metadata]: + """ + Take an input with type Mapping[str, ArrayMetadata | GroupMetadata] and parse it into + a dict of str: node pairs that models a valid, complete Zarr hierarchy. + + If the input represents a complete Zarr hierarchy, i.e. one with no implicit groups, + then return a dict with the exact same data as the input. + + Otherwise, return a dict derived from the input with GroupMetadata inserted as needed to make + the hierarchy complete. + + For example, an input of {'a/b': ArrayMetadata} is incomplete, because it references two + groups (the root group '' and a group at 'a') that are not specified in the input. Applying this function + to that input will result in a return value of + {'': GroupMetadata, 'a': GroupMetadata, 'a/b': ArrayMetadata}, i.e. the implied groups + were added. + + The input is also checked for the following conditions; an error is raised if any are violated: + + - No arrays can contain group or arrays (i.e., all arrays must be leaf nodes). + - All arrays and groups must have the same ``zarr_format`` value. + + This function ensures that the input is transformed into a specification of a complete and valid + Zarr hierarchy. + """ + + # ensure that all nodes have the same zarr format + data_purified = _ensure_consistent_zarr_format(data) + + # ensure that keys are normalized to zarr paths + data_normed_keys = _normalize_path_keys(data_purified) + + # insert an implicit root group if a root was not specified + # but not if an empty dict was provided, because any empty hierarchy has no nodes + if len(data_normed_keys) > 0 and "" not in data_normed_keys: + z_format = next(iter(data_normed_keys.values())).zarr_format + data_normed_keys = data_normed_keys | {"": ImplicitGroupMarker(zarr_format=z_format)} + + out: dict[str, GroupMetadata | ArrayV2Metadata | ArrayV3Metadata] = {**data_normed_keys} + + for k, v in data_normed_keys.items(): + key_split = k.split("/") + + # get every parent path + *subpaths, _ = accumulate(key_split, lambda a, b: _join_paths([a, b])) + + for subpath in subpaths: + # If a component is not already in the output dict, add ImplicitGroupMetadata + if subpath not in out: + out[subpath] = ImplicitGroupMarker(zarr_format=v.zarr_format) + else: + if not isinstance(out[subpath], GroupMetadata | ImplicitGroupMarker): + msg = ( + f"The node at {subpath} contains other nodes, but it is not a Zarr group. " + "This is invalid. Only Zarr groups can contain other nodes." + ) + raise ValueError(msg) + return out + + +def _ensure_consistent_zarr_format( + data: Mapping[str, GroupMetadata | ArrayV2Metadata | ArrayV3Metadata], +) -> Mapping[str, GroupMetadata | ArrayV2Metadata] | Mapping[str, GroupMetadata | ArrayV3Metadata]: + """ + Ensure that all values of the input dict have the same zarr format. If any do not, + then a value error is raised. + """ + observed_zarr_formats: dict[ZarrFormat, list[str]] = {2: [], 3: []} + + for k, v in data.items(): + observed_zarr_formats[v.zarr_format].append(k) + + if len(observed_zarr_formats[2]) > 0 and len(observed_zarr_formats[3]) > 0: + msg = ( + "Got data with both Zarr v2 and Zarr v3 nodes, which is invalid. " + f"The following keys map to Zarr v2 nodes: {observed_zarr_formats.get(2)}. " + f"The following keys map to Zarr v3 nodes: {observed_zarr_formats.get(3)}." + "Ensure that all nodes have the same Zarr format." + ) + raise ValueError(msg) + + return cast( + "Mapping[str, GroupMetadata | ArrayV2Metadata] | Mapping[str, GroupMetadata | ArrayV3Metadata]", + data, + ) + + +async def _getitem_semaphore( + node: AsyncGroup, key: str, semaphore: asyncio.Semaphore | None +) -> AnyAsyncArray | AsyncGroup: + """ + Wrap Group.getitem with an optional semaphore. + + If the semaphore parameter is an + asyncio.Semaphore instance, then the getitem operation is performed inside an async context + manager provided by that semaphore. If the semaphore parameter is None, then getitem is invoked + without a context manager. + """ + if semaphore is not None: + async with semaphore: + return await node.getitem(key) + else: + return await node.getitem(key) + + +async def _iter_members( + node: AsyncGroup, + skip_keys: tuple[str, ...], + semaphore: asyncio.Semaphore | None, +) -> AsyncGenerator[tuple[str, AnyAsyncArray | AsyncGroup], None]: + """ + Iterate over the arrays and groups contained in a group. + + Parameters + ---------- + node : AsyncGroup + The group to traverse. + skip_keys : tuple[str, ...] + A tuple of keys to skip when iterating over the possible members of the group. + semaphore : asyncio.Semaphore | None + An optional semaphore to use for concurrency control. + + Yields + ------ + tuple[str, AnyAsyncArray | AsyncGroup] + """ + + # retrieve keys from storage + keys = [key async for key in node.store.list_dir(node.path)] + keys_filtered = tuple(filter(lambda v: v not in skip_keys, keys)) + + node_tasks = tuple( + asyncio.create_task(_getitem_semaphore(node, key, semaphore), name=key) + for key in keys_filtered + ) + + for fetched_node_coro in asyncio.as_completed(node_tasks): + try: + fetched_node = await fetched_node_coro + except KeyError as e: + # keyerror is raised when `key` names an object (in the object storage sense), + # as opposed to a prefix, in the store under the prefix associated with this group + # in which case `key` cannot be the name of a sub-array or sub-group. + warnings.warn( + f"Object at {e.args[0]} is not recognized as a component of a Zarr hierarchy.", + ZarrUserWarning, + stacklevel=1, + ) + continue + match fetched_node: + case AsyncArray() | AsyncGroup(): + yield fetched_node.basename, fetched_node + case _: + raise ValueError(f"Unexpected type: {type(fetched_node)}") + + +async def _iter_members_deep( + group: AsyncGroup, + *, + max_depth: int | None, + skip_keys: tuple[str, ...], + semaphore: asyncio.Semaphore | None = None, + use_consolidated_for_children: bool = True, +) -> AsyncGenerator[tuple[str, AnyAsyncArray | AsyncGroup], None]: + """ + Iterate over the arrays and groups contained in a group, and optionally the + arrays and groups contained in those groups. + + Parameters + ---------- + group : AsyncGroup + The group to traverse. + max_depth : int | None + The maximum depth of recursion. + skip_keys : tuple[str, ...] + A tuple of keys to skip when iterating over the possible members of the group. + semaphore : asyncio.Semaphore | None + An optional semaphore to use for concurrency control. + use_consolidated_for_children : bool, default True + Whether to use the consolidated metadata of child groups loaded + from the store. Note that this only affects groups loaded from the + store. If the current Group already has consolidated metadata, it + will always be used. + + Yields + ------ + tuple[str, AnyAsyncArray | AsyncGroup] + """ + + to_recurse = {} + do_recursion = max_depth is None or max_depth > 0 + + if max_depth is None: + new_depth = None + else: + new_depth = max_depth - 1 + async for name, node in _iter_members(group, skip_keys=skip_keys, semaphore=semaphore): + is_group = isinstance(node, AsyncGroup) + if ( + is_group + and not use_consolidated_for_children + and node.metadata.consolidated_metadata is not None + ): + node = cast("AsyncGroup", node) + # We've decided not to trust consolidated metadata at this point, because we're + # reconsolidating the metadata, for example. + node = replace(node, metadata=replace(node.metadata, consolidated_metadata=None)) + yield name, node + if is_group and do_recursion: + node = cast("AsyncGroup", node) + to_recurse[name] = _iter_members_deep( + node, max_depth=new_depth, skip_keys=skip_keys, semaphore=semaphore + ) + + for prefix, subgroup_iter in to_recurse.items(): + async for name, node in subgroup_iter: + key = f"{prefix}/{name}".lstrip("/") + yield key, node + + +async def _read_metadata_v3(store: Store, path: str) -> ArrayV3Metadata | GroupMetadata: + """ + Given a store_path, return ArrayV3Metadata or GroupMetadata defined by the metadata + document stored at store_path.path / zarr.json. If no such document is found, raise a + FileNotFoundError. + """ + zarr_json_bytes = await store.get( + _join_paths([path, ZARR_JSON]), prototype=default_buffer_prototype() + ) + if zarr_json_bytes is None: + raise FileNotFoundError(path) + return _build_metadata_v3(buffer_to_json_object(zarr_json_bytes)) + + +async def _read_metadata_v2(store: Store, path: str) -> ArrayV2Metadata | GroupMetadata: + """ + Given a store_path, return ArrayV2Metadata or GroupMetadata defined by the metadata + document stored at store_path.path / (.zgroup | .zarray). If no such document is found, + raise a FileNotFoundError. + """ + # TODO: consider first fetching array metadata, and only fetching group metadata when we don't + # find an array + zarray_bytes, zgroup_bytes, zattrs_bytes = await asyncio.gather( + store.get(_join_paths([path, ZARRAY_JSON]), prototype=default_buffer_prototype()), + store.get(_join_paths([path, ZGROUP_JSON]), prototype=default_buffer_prototype()), + store.get(_join_paths([path, ZATTRS_JSON]), prototype=default_buffer_prototype()), + ) + + zattrs: dict[str, JSON] + if zattrs_bytes is None: + zattrs = {} + else: + zattrs = buffer_to_json_object(zattrs_bytes) + + # TODO: decide how to handle finding both array and group metadata. The spec does not seem to + # consider this situation. A practical approach would be to ignore that combination, and only + # return the array metadata. + if zarray_bytes is not None: + zmeta = buffer_to_json_object(zarray_bytes) + else: + if zgroup_bytes is None: + # neither .zarray or .zgroup were found results in KeyError + raise FileNotFoundError(path) + else: + zmeta = buffer_to_json_object(zgroup_bytes) + + return _build_metadata_v2(zmeta, zattrs) + + +async def _read_group_metadata_v2(store: Store, path: str) -> GroupMetadata: + """ + Read group metadata or error + """ + meta = await _read_metadata_v2(store=store, path=path) + if not isinstance(meta, GroupMetadata): + raise FileNotFoundError(f"Group metadata was not found in {store} at {path}") + return meta + + +async def _read_group_metadata_v3(store: Store, path: str) -> GroupMetadata: + """ + Read group metadata or error + """ + meta = await _read_metadata_v3(store=store, path=path) + if not isinstance(meta, GroupMetadata): + raise FileNotFoundError(f"Group metadata was not found in {store} at {path}") + return meta + + +async def _read_group_metadata( + store: Store, path: str, *, zarr_format: ZarrFormat +) -> GroupMetadata: + if zarr_format == 2: + return await _read_group_metadata_v2(store=store, path=path) + return await _read_group_metadata_v3(store=store, path=path) + + +def _build_metadata_v3(zarr_json: dict[str, JSON]) -> ArrayV3Metadata | GroupMetadata: + """ + Convert a dict representation of Zarr V3 metadata into the corresponding metadata class. + """ + if "node_type" not in zarr_json: + msg = "Required key 'node_type' is missing from the provided metadata document." + raise MetadataValidationError(msg) + match zarr_json: + case {"node_type": "array"}: + return ArrayV3Metadata.from_dict(zarr_json) + case {"node_type": "group"}: + return GroupMetadata.from_dict(zarr_json) + case _: # pragma: no cover + raise ValueError( + "invalid value for `node_type` key in metadata document" + ) # pragma: no cover + + +def _build_metadata_v2( + zarr_json: dict[str, JSON], attrs_json: dict[str, JSON] +) -> ArrayV2Metadata | GroupMetadata: + """ + Convert a dict representation of Zarr V2 metadata into the corresponding metadata class. + """ + match zarr_json: + case {"shape": _}: + return ArrayV2Metadata.from_dict(zarr_json | {"attributes": attrs_json}) + case _: # pragma: no cover + return GroupMetadata.from_dict(zarr_json | {"attributes": attrs_json}) + + +@overload +def _build_node(*, store: Store, path: str, metadata: ArrayV2Metadata) -> AsyncArrayV2: ... + + +@overload +def _build_node(*, store: Store, path: str, metadata: ArrayV3Metadata) -> AsyncArrayV3: ... + + +@overload +def _build_node(*, store: Store, path: str, metadata: GroupMetadata) -> AsyncGroup: ... + + +def _build_node( + *, store: Store, path: str, metadata: ArrayV3Metadata | ArrayV2Metadata | GroupMetadata +) -> AnyAsyncArray | AsyncGroup: + """ + Take a metadata object and return a node (AsyncArray or AsyncGroup). + """ + store_path = StorePath(store=store, path=path) + match metadata: + case ArrayV2Metadata() | ArrayV3Metadata(): + return AsyncArray(metadata, store_path=store_path) + case GroupMetadata(): + return AsyncGroup(metadata, store_path=store_path) + case _: # pragma: no cover + raise ValueError(f"Unexpected metadata type: {type(metadata)}") # pragma: no cover + + +async def _get_node_v2(store: Store, path: str) -> AsyncArrayV2 | AsyncGroup: + """ + Read a Zarr v2 AsyncArray or AsyncGroup from a path in a Store. + + Parameters + ---------- + store : Store + The store-like object to read from. + path : str + The path to the node to read. + + Returns + ------- + AsyncArray | AsyncGroup + """ + metadata = await _read_metadata_v2(store=store, path=path) + return _build_node(store=store, path=path, metadata=metadata) + + +async def _get_node_v3(store: Store, path: str) -> AsyncArrayV3 | AsyncGroup: + """ + Read a Zarr v3 AsyncArray or AsyncGroup from a path in a Store. + + Parameters + ---------- + store : Store + The store-like object to read from. + path : str + The path to the node to read. + + Returns + ------- + AsyncArray | AsyncGroup + """ + metadata = await _read_metadata_v3(store=store, path=path) + return _build_node(store=store, path=path, metadata=metadata) + + +async def get_node(store: Store, path: str, zarr_format: ZarrFormat) -> AnyAsyncArray | AsyncGroup: + """ + Get an AsyncArray or AsyncGroup from a path in a Store. + + Parameters + ---------- + store : Store + The store-like object to read from. + path : str + The path to the node to read. + zarr_format : {2, 3} + The zarr format of the node to read. + + Returns + ------- + AsyncArray | AsyncGroup + """ + + match zarr_format: + case 2: + return await _get_node_v2(store=store, path=path) + case 3: + return await _get_node_v3(store=store, path=path) + case _: # pragma: no cover + raise ValueError(f"Unexpected zarr format: {zarr_format}") # pragma: no cover + + +async def _set_return_key( + *, store: Store, key: str, value: Buffer, semaphore: asyncio.Semaphore | None = None +) -> str: + """ + Write a value to storage at the given key. The key is returned. + Useful when saving values via routines that return results in execution order, + like asyncio.as_completed, because in this case we need to know which key was saved in order + to yield the right object to the caller. + + Parameters + ---------- + store : Store + The store to save the value to. + key : str + The key to save the value to. + value : Buffer + The value to save. + semaphore : asyncio.Semaphore | None + An optional semaphore to use to limit the number of concurrent writes. + """ + + if semaphore is not None: + async with semaphore: + await store.set(key, value) + else: + await store.set(key, value) + return key + + +def _persist_metadata( + store: Store, + path: str, + metadata: ArrayV2Metadata | ArrayV3Metadata | GroupMetadata, + semaphore: asyncio.Semaphore | None = None, +) -> tuple[Coroutine[None, None, str], ...]: + """ + Prepare to save a metadata document to storage, returning a tuple of coroutines that must be awaited. + """ + + to_save = metadata.to_buffer_dict(default_buffer_prototype()) + return tuple( + _set_return_key(store=store, key=_join_paths([path, key]), value=value, semaphore=semaphore) + for key, value in to_save.items() + ) + + +async def create_rooted_hierarchy( + *, + store: Store, + nodes: dict[str, GroupMetadata | ArrayV2Metadata | ArrayV3Metadata], + overwrite: bool = False, +) -> AsyncGroup | AnyAsyncArray: + """ + Create an ``AsyncGroup`` or ``AsyncArray`` from a store and a dict of metadata documents. + This function ensures that its input contains a specification of a root node, + calls ``create_hierarchy`` to create nodes, and returns the root node of the hierarchy. + """ + roots = _get_roots(nodes.keys()) + if len(roots) != 1: + msg = ( + "The input does not specify a root node. " + "This function can only create hierarchies that contain a root node, which is " + "defined as a group that is ancestral to all the other arrays and " + "groups in the hierarchy, or a single array." + ) + raise ValueError(msg) + else: + root_key = roots[0] + + nodes_created = [ + x async for x in create_hierarchy(store=store, nodes=nodes, overwrite=overwrite) + ] + return dict(nodes_created)[root_key] diff --git a/src/zarr/core/indexing.py b/src/zarr/core/indexing.py new file mode 100644 index 0000000000..a1b050cb7b --- /dev/null +++ b/src/zarr/core/indexing.py @@ -0,0 +1,1707 @@ +from __future__ import annotations + +import itertools +import math +import numbers +from collections.abc import Iterator, Sequence +from dataclasses import dataclass +from enum import Enum +from functools import lru_cache +from types import EllipsisType +from typing import ( + TYPE_CHECKING, + Any, + Literal, + NamedTuple, + Protocol, + TypeGuard, + cast, + runtime_checkable, +) + +import numpy as np +import numpy.typing as npt + +from zarr.core.chunk_grids import FixedDimension +from zarr.core.common import ceildiv, product +from zarr.core.metadata.v2 import ArrayV2Metadata +from zarr.core.metadata.v3 import ArrayV3Metadata +from zarr.errors import ( + ArrayIndexError, + BoundsCheckError, + NegativeStepError, + VindexInvalidSelectionError, +) + +if TYPE_CHECKING: + from zarr.core.array import AsyncArray + from zarr.core.buffer import NDArrayLikeOrScalar + from zarr.core.chunk_grids import ChunkGrid, DimensionGrid + from zarr.types import AnyArray + + +IntSequence = list[int] | npt.NDArray[np.intp] +ArrayOfIntOrBool = npt.NDArray[np.intp] | npt.NDArray[np.bool_] +BasicSelector = int | slice | EllipsisType +Selector = BasicSelector | ArrayOfIntOrBool +BasicSelection = BasicSelector | tuple[BasicSelector, ...] # also used for BlockIndex +CoordinateSelection = IntSequence | tuple[IntSequence, ...] +MaskSelection = npt.NDArray[np.bool_] +OrthogonalSelection = Selector | tuple[Selector, ...] +Selection = BasicSelection | CoordinateSelection | MaskSelection | OrthogonalSelection +CoordinateSelectionNormalized = tuple[npt.NDArray[np.intp], ...] +SelectionNormalized = tuple[Selector, ...] | ArrayOfIntOrBool +SelectionWithFields = Selection | str | Sequence[str] +SelectorTuple = tuple[Selector, ...] | npt.NDArray[np.intp] | slice +Fields = str | list[str] | tuple[str, ...] + + +def err_too_many_indices(selection: Any, shape: tuple[int, ...]) -> None: + raise IndexError(f"too many indices for array; expected {len(shape)}, got {len(selection)}") + + +def _zarr_array_to_int_or_bool_array(arr: AnyArray) -> npt.NDArray[np.intp] | npt.NDArray[np.bool_]: + if arr.dtype.kind in ("i", "b"): + return np.asarray(arr) + else: + raise IndexError( + f"Invalid array dtype: {arr.dtype}. Arrays used as indices must be of integer or boolean type" + ) + + +@runtime_checkable +class Indexer(Protocol): + shape: tuple[int, ...] + drop_axes: tuple[int, ...] + + def __iter__(self) -> Iterator[ChunkProjection]: ... + + +type _ArrayIndexingOrder = Literal["lexicographic"] + + +def _iter_grid( + grid_shape: Sequence[int], + *, + origin: Sequence[int] | None = None, + selection_shape: Sequence[int] | None = None, + order: _ArrayIndexingOrder = "lexicographic", +) -> Iterator[tuple[int, ...]]: + """ + Iterate over the elements of grid of integers, with the option to restrict the domain of + iteration to a contiguous subregion of that grid. + + Parameters + ---------- + grid_shape : Sequence[int] + The size of the domain to iterate over. + origin : Sequence[int] | None, default=None + The first coordinate of the domain to return. + selection_shape : Sequence[int] | None, default=None + The shape of the selection. + order : Literal["lexicographic"], default="lexicographic" + The linear indexing order to use. + + Returns + ------- + + Iterator[tuple[int, ...]] + An iterator over tuples of integers + + Examples + -------- + ```python + from zarr.core.indexing import _iter_grid + tuple(_iter_grid((1,))) + # ((0,),) + + tuple(_iter_grid((2,3))) + # ((0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)) + + tuple(_iter_grid((2,3), origin=(1,1))) + # ((1, 1), (1, 2)) + + tuple(_iter_grid((2,3), origin=(0,0), selection_shape=(2,2))) + # ((0, 0), (0, 1), (1, 0), (1, 1)) + ``` + """ + if origin is None: + origin_parsed = (0,) * len(grid_shape) + else: + if len(origin) != len(grid_shape): + msg = ( + "Shape and origin parameters must have the same length." + f"Got {len(grid_shape)} elements in shape, but {len(origin)} elements in origin." + ) + raise ValueError(msg) + origin_parsed = tuple(origin) + if selection_shape is None: + selection_shape_parsed = tuple( + g - o for o, g in zip(origin_parsed, grid_shape, strict=True) + ) + else: + selection_shape_parsed = tuple(selection_shape) + if order == "lexicographic": + dimensions: tuple[range, ...] = () + for idx, (o, gs, ss) in enumerate( + zip(origin_parsed, grid_shape, selection_shape_parsed, strict=True) + ): + if o + ss > gs: + raise IndexError( + f"Invalid selection shape ({ss}) for origin ({o}) and grid shape ({gs}) at axis {idx}." + ) + dimensions += (range(o, o + ss),) + return itertools.product(*(dimensions)) + + else: + msg = f"Indexing order {order} is not supported at this time." # type: ignore[unreachable] # pragma: no cover + raise NotImplementedError(msg) # pragma: no cover + + +def _iter_regions( + domain_shape: Sequence[int], + region_shape: Sequence[int], + *, + origin: Sequence[int] | None = None, + selection_shape: Sequence[int] | None = None, + order: _ArrayIndexingOrder = "lexicographic", + trim_excess: bool = True, +) -> Iterator[tuple[slice, ...]]: + """ + Iterate over contiguous regions on a grid of integers, with the option to restrict the + domain of iteration to a contiguous subregion of that grid. + + Parameters + ---------- + domain_shape : Sequence[int] + The size of the domain to iterate over. + region_shape : Sequence[int] + The shape of the region to iterate over. + origin : Sequence[int] | None, default=None + The location, in grid coordinates, of the first region to return. + selection_shape : Sequence[int] | None, default=None + The shape of the selection, in grid coordinates. + order : Literal["lexicographic"], default="lexicographic" + The linear indexing order to use. + + Yields + ------ + + Iterator[tuple[slice, ...]] + An iterator over tuples of slices, where each slice spans a separate contiguous region + + Examples + -------- + ```python + from zarr.core.indexing import _iter_regions + tuple(_iter_regions((1,), (1,))) + # ((slice(0, 1, 1),),) + + tuple(_iter_regions((2, 3), (1, 2))) + # ((slice(0, 1, 1), slice(0, 2, 1)), (slice(1, 2, 1), slice(0, 2, 1))) + + tuple(_iter_regions((2,3), (1,2), origin=(1,1))) + # ((slice(1, 2, 1), slice(1, 3, 1)), (slice(2, 3, 1), slice(1, 3, 1))) + + tuple(_iter_regions((2,3), (1,2), origin=(0,0), selection_shape=(2,2))) + # ((slice(0, 1, 1), slice(0, 2, 1)), (slice(1, 2, 1), slice(0, 2, 1))) + ``` + """ + grid_shape = tuple(itertools.starmap(ceildiv, zip(domain_shape, region_shape, strict=True))) + for grid_position in _iter_grid( + grid_shape=grid_shape, origin=origin, selection_shape=selection_shape, order=order + ): + out: list[slice] = [] + for g_pos, r_shape, d_shape in zip(grid_position, region_shape, domain_shape, strict=True): + start = g_pos * r_shape + stop = start + r_shape + if trim_excess: + stop = min(stop, d_shape) + out.append(slice(start, stop, 1)) + yield tuple(out) + + +def is_integer(x: Any) -> TypeGuard[int]: + """True if x is an integer (both pure Python or NumPy).""" + return isinstance(x, numbers.Integral) and not is_bool(x) + + +def is_bool(x: Any) -> TypeGuard[bool | np.bool_]: + """True if x is a boolean (both pure Python or NumPy).""" + return type(x) in [bool, np.bool_] + + +def is_integer_list(x: Any) -> TypeGuard[list[int]]: + """True if x is a list of integers.""" + return isinstance(x, list) and len(x) > 0 and all(is_integer(i) for i in x) + + +def is_bool_list(x: Any) -> TypeGuard[list[bool | np.bool_]]: + """True if x is a list of boolean.""" + return isinstance(x, list) and len(x) > 0 and all(is_bool(i) for i in x) + + +def is_integer_array(x: Any, ndim: int | None = None) -> TypeGuard[npt.NDArray[np.intp]]: + t = not np.isscalar(x) and hasattr(x, "shape") and hasattr(x, "dtype") and x.dtype.kind in "ui" + if ndim is not None: + t = t and hasattr(x, "shape") and len(x.shape) == ndim + return t + + +def is_bool_array(x: Any, ndim: int | None = None) -> TypeGuard[npt.NDArray[np.bool_]]: + t = hasattr(x, "shape") and hasattr(x, "dtype") and x.dtype == bool + if ndim is not None: + t = t and hasattr(x, "shape") and len(x.shape) == ndim + return t + + +def is_int_or_bool_iterable(x: Any) -> bool: + return is_integer_list(x) or is_integer_array(x) or is_bool_array(x) or is_bool_list(x) + + +def is_scalar(value: Any, dtype: np.dtype[Any]) -> bool: + if np.isscalar(value): + return True + if hasattr(value, "shape") and value.shape == (): + return True + return isinstance(value, tuple) and dtype.names is not None and len(value) == len(dtype.names) + + +def is_pure_fancy_indexing(selection: Any, ndim: int) -> bool: + """Check whether a selection contains only scalars or integer/bool array-likes. + + Parameters + ---------- + selection : tuple, slice, or scalar + A valid selection value for indexing into arrays. + + Returns + ------- + is_pure : bool + True if the selection is a pure fancy indexing expression (ie not mixed + with boolean or slices). + """ + if is_bool_array(selection): + # is mask selection + return True + + if ndim == 1 and ( + is_integer_list(selection) or is_integer_array(selection) or is_bool_list(selection) + ): + return True + + # if not, we go through the normal path below, because a 1-tuple + # of integers is also allowed. + no_slicing = ( + isinstance(selection, tuple) + and len(selection) == ndim + and not (any(isinstance(elem, slice) or elem is Ellipsis for elem in selection)) + ) + return ( + no_slicing + and all( + is_integer(elem) or is_integer_list(elem) or is_integer_array(elem) + for elem in selection + ) + and any(is_integer_list(elem) or is_integer_array(elem) for elem in selection) + ) + + +def is_pure_orthogonal_indexing(selection: Selection, ndim: int) -> TypeGuard[OrthogonalSelection]: + if not ndim: + return False + + selection_normalized = (selection,) if not isinstance(selection, tuple) else selection + + # Case 1: Selection contains of iterable of integers or boolean + if len(selection_normalized) == ndim and all( + is_int_or_bool_iterable(s) for s in selection_normalized + ): + return True + + # Case 2: selection contains either zero or one integer iterables. + # All other selection elements are slices or integers + return ( + len(selection_normalized) <= ndim + and sum(is_int_or_bool_iterable(s) for s in selection_normalized) <= 1 + and all( + is_int_or_bool_iterable(s) or isinstance(s, int | slice) for s in selection_normalized + ) + ) + + +def normalize_integer_selection(dim_sel: int, dim_len: int) -> int: + # normalize type to int + dim_sel = int(dim_sel) + + # handle wraparound + if dim_sel < 0: + dim_sel = dim_len + dim_sel + + # handle out of bounds + if dim_sel >= dim_len or dim_sel < 0: + msg = f"index out of bounds for dimension with length {dim_len}" + raise BoundsCheckError(msg) + + return dim_sel + + +class ChunkDimProjection(NamedTuple): + """A mapping from chunk to output array for a single dimension. + + Attributes + ---------- + dim_chunk_ix + Index of chunk. + dim_chunk_sel + Selection of items from chunk array. + dim_out_sel + Selection of items in target (output) array. + """ + + dim_chunk_ix: int + dim_chunk_sel: Selector + dim_out_sel: Selector | None + is_complete_chunk: bool + + +@dataclass(frozen=True) +class IntDimIndexer: + dim_sel: int + dim_len: int + dim_grid: DimensionGrid + nitems: int = 1 + + def __init__(self, dim_sel: int, dim_len: int, dim_grid: DimensionGrid) -> None: + object.__setattr__(self, "dim_sel", normalize_integer_selection(dim_sel, dim_len)) + object.__setattr__(self, "dim_len", dim_len) + object.__setattr__(self, "dim_grid", dim_grid) + + def __iter__(self) -> Iterator[ChunkDimProjection]: + g = self.dim_grid + dim_chunk_ix = g.index_to_chunk(self.dim_sel) + dim_offset = g.chunk_offset(dim_chunk_ix) + dim_chunk_sel = self.dim_sel - dim_offset + dim_out_sel = None + is_complete_chunk = g.data_size(dim_chunk_ix) == 1 + yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel, is_complete_chunk) + + +@dataclass(frozen=True) +class SliceDimIndexer: + dim_len: int + nitems: int + nchunks: int + dim_grid: DimensionGrid + + start: int + stop: int + step: int + + def __init__( + self, + dim_sel: slice, + dim_len: int, + dim_grid: DimensionGrid, + ) -> None: + # normalize + start, stop, step = dim_sel.indices(dim_len) + if step < 1: + raise NegativeStepError("only slices with step >= 1 are supported.") + + object.__setattr__(self, "start", start) + object.__setattr__(self, "stop", stop) + object.__setattr__(self, "step", step) + + object.__setattr__(self, "dim_len", dim_len) + object.__setattr__(self, "dim_grid", dim_grid) + object.__setattr__(self, "nitems", max(0, ceildiv((stop - start), step))) + object.__setattr__(self, "nchunks", dim_grid.nchunks) + + def __iter__(self) -> Iterator[ChunkDimProjection]: + # figure out the range of chunks we need to visit + if self.start >= self.stop: + return # empty slice + g = self.dim_grid + dim_chunk_ix_from = g.index_to_chunk(self.start) if self.start > 0 else 0 + dim_chunk_ix_to = g.index_to_chunk(self.stop - 1) + 1 if self.stop > 0 else 0 + + # iterate over chunks in range + for dim_chunk_ix in range(dim_chunk_ix_from, dim_chunk_ix_to): + # compute offsets for chunk within overall array + dim_offset = g.chunk_offset(dim_chunk_ix) + # determine chunk length, accounting for trailing chunk + dim_chunk_len = g.data_size(dim_chunk_ix) + dim_limit = dim_offset + dim_chunk_len + + if self.start < dim_offset: + # selection starts before current chunk + dim_chunk_sel_start = 0 + remainder = (dim_offset - self.start) % self.step + if remainder: + dim_chunk_sel_start += self.step - remainder + # compute number of previous items, provides offset into output array + dim_out_offset = ceildiv((dim_offset - self.start), self.step) + else: + # selection starts within current chunk + dim_chunk_sel_start = self.start - dim_offset + dim_out_offset = 0 + + if self.stop > dim_limit: + # selection ends after current chunk + dim_chunk_sel_stop = dim_chunk_len + else: + # selection ends within current chunk + dim_chunk_sel_stop = self.stop - dim_offset + + dim_chunk_sel = slice(dim_chunk_sel_start, dim_chunk_sel_stop, self.step) + dim_chunk_nitems = ceildiv((dim_chunk_sel_stop - dim_chunk_sel_start), self.step) + + # If there are no elements on the selection within this chunk, then skip + if dim_chunk_nitems == 0: + continue + + dim_out_sel = slice(dim_out_offset, dim_out_offset + dim_chunk_nitems) + is_complete_chunk = ( + dim_chunk_sel_start == 0 and (self.stop >= dim_limit) and self.step in [1, None] + ) + yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel, is_complete_chunk) + + +def check_selection_length(selection: SelectionNormalized, shape: tuple[int, ...]) -> None: + if len(selection) > len(shape): + err_too_many_indices(selection, shape) + + +def replace_ellipsis(selection: Any, shape: tuple[int, ...]) -> SelectionNormalized: + selection = ensure_tuple(selection) + + # count number of ellipsis present + n_ellipsis = sum(1 for i in selection if i is Ellipsis) + + if n_ellipsis > 1: + # more than 1 is an error + raise IndexError("an index can only have a single ellipsis ('...')") + + elif n_ellipsis == 1: + # locate the ellipsis, count how many items to left and right + n_items_l = selection.index(Ellipsis) # items to left of ellipsis + n_items_r = len(selection) - (n_items_l + 1) # items to right of ellipsis + n_items = len(selection) - 1 # all non-ellipsis items + + if n_items >= len(shape): + # ellipsis does nothing, just remove it + selection = tuple(i for i in selection if i != Ellipsis) + + else: + # replace ellipsis with as many slices are needed for number of dims + new_item = selection[:n_items_l] + ((slice(None),) * (len(shape) - n_items)) + if n_items_r: + new_item += selection[-n_items_r:] + selection = new_item + + # fill out selection if not completely specified + if len(selection) < len(shape): + selection += (slice(None),) * (len(shape) - len(selection)) + + # check selection not too long + check_selection_length(selection, shape) + + return cast("SelectionNormalized", selection) + + +def replace_lists(selection: SelectionNormalized) -> SelectionNormalized: + return tuple( + cast("ArrayOfIntOrBool", np.asarray(dim_sel)) if isinstance(dim_sel, list) else dim_sel + for dim_sel in selection + ) + + +def ensure_tuple(v: Any) -> SelectionNormalized: + if not isinstance(v, tuple): + v = (v,) + return cast("SelectionNormalized", v) + + +class ChunkProjection(NamedTuple): + """A mapping of items from chunk to output array. Can be used to extract items from the + chunk array for loading into an output array. Can also be used to extract items from a + value array for setting/updating in a chunk array. + + Attributes + ---------- + chunk_coords + Indices of chunk. + chunk_selection + Selection of items from chunk array. + out_selection + Selection of items in target (output) array. + is_complete_chunk: + True if a complete chunk is indexed + """ + + chunk_coords: tuple[int, ...] + chunk_selection: tuple[Selector, ...] | npt.NDArray[np.intp] + out_selection: tuple[Selector, ...] | npt.NDArray[np.intp] | slice + is_complete_chunk: bool + + +def is_slice(s: Any) -> TypeGuard[slice]: + return isinstance(s, slice) + + +def is_contiguous_slice(s: Any) -> TypeGuard[slice]: + return is_slice(s) and (s.step is None or s.step == 1) + + +def is_positive_slice(s: Any) -> TypeGuard[slice]: + return is_slice(s) and (s.step is None or s.step >= 1) + + +def is_contiguous_selection(selection: Any) -> TypeGuard[slice]: + selection = ensure_tuple(selection) + return all((is_integer_array(s) or is_contiguous_slice(s) or s == Ellipsis) for s in selection) + + +def is_basic_selection(selection: Any) -> TypeGuard[BasicSelection]: + selection = ensure_tuple(selection) + return all(is_integer(s) or is_positive_slice(s) for s in selection) + + +@dataclass(frozen=True) +class BasicIndexer(Indexer): + dim_indexers: list[IntDimIndexer | SliceDimIndexer] + shape: tuple[int, ...] + drop_axes: tuple[int, ...] + + def __init__( + self, + selection: BasicSelection, + shape: tuple[int, ...], + chunk_grid: ChunkGrid, + ) -> None: + dim_grids = chunk_grid._dimensions + # handle ellipsis + selection_normalized = replace_ellipsis(selection, shape) + + # setup per-dimension indexers + dim_indexers: list[IntDimIndexer | SliceDimIndexer] = [] + for dim_sel, dim_len, dim_grid in zip(selection_normalized, shape, dim_grids, strict=True): + dim_indexer: IntDimIndexer | SliceDimIndexer + if is_integer(dim_sel): + dim_indexer = IntDimIndexer(dim_sel, dim_len, dim_grid) + + elif is_slice(dim_sel): + dim_indexer = SliceDimIndexer(dim_sel, dim_len, dim_grid) + + else: + raise IndexError( + "unsupported selection item for basic indexing; " + f"expected integer or slice, got {type(dim_sel)!r}" + ) + + dim_indexers.append(dim_indexer) + + object.__setattr__(self, "dim_indexers", dim_indexers) + object.__setattr__( + self, + "shape", + tuple(s.nitems for s in self.dim_indexers if not isinstance(s, IntDimIndexer)), + ) + object.__setattr__(self, "drop_axes", ()) + + def __iter__(self) -> Iterator[ChunkProjection]: + for dim_projections in itertools.product(*self.dim_indexers): + chunk_coords = tuple(p.dim_chunk_ix for p in dim_projections) + chunk_selection = tuple(p.dim_chunk_sel for p in dim_projections) + out_selection = tuple( + p.dim_out_sel for p in dim_projections if p.dim_out_sel is not None + ) + is_complete_chunk = all(p.is_complete_chunk for p in dim_projections) + yield ChunkProjection(chunk_coords, chunk_selection, out_selection, is_complete_chunk) + + +@dataclass(frozen=True) +class BoolArrayDimIndexer: + dim_sel: npt.NDArray[np.bool_] + dim_len: int + dim_grid: DimensionGrid + nchunks: int + + chunk_nitems: npt.NDArray[Any] + chunk_nitems_cumsum: npt.NDArray[Any] + nitems: int + dim_chunk_ixs: npt.NDArray[np.intp] + + def __init__( + self, + dim_sel: npt.NDArray[np.bool_], + dim_len: int, + dim_grid: DimensionGrid, + ) -> None: + # check number of dimensions + if not is_bool_array(dim_sel, 1): + raise IndexError("Boolean arrays in an orthogonal selection must be 1-dimensional only") + + # check shape + if dim_sel.shape[0] != dim_len: + raise IndexError( + f"Boolean array has the wrong length for dimension; expected {dim_len}, got {dim_sel.shape[0]}" + ) + + g = dim_grid + nchunks = g.nchunks + + # precompute number of selected items for each chunk + chunk_nitems = np.zeros(nchunks, dtype="i8") + for dim_chunk_ix in range(nchunks): + dim_offset = g.chunk_offset(dim_chunk_ix) + chunk_len = g.data_size(dim_chunk_ix) + chunk_nitems[dim_chunk_ix] = np.count_nonzero( + dim_sel[dim_offset : dim_offset + chunk_len] + ) + chunk_nitems_cumsum = np.cumsum(chunk_nitems) + nitems = chunk_nitems_cumsum[-1] + dim_chunk_ixs = np.nonzero(chunk_nitems)[0] + + # store attributes + object.__setattr__(self, "dim_sel", dim_sel) + object.__setattr__(self, "dim_len", dim_len) + object.__setattr__(self, "dim_grid", dim_grid) + object.__setattr__(self, "nchunks", nchunks) + object.__setattr__(self, "chunk_nitems", chunk_nitems) + object.__setattr__(self, "chunk_nitems_cumsum", chunk_nitems_cumsum) + object.__setattr__(self, "nitems", nitems) + object.__setattr__(self, "dim_chunk_ixs", dim_chunk_ixs) + + def __iter__(self) -> Iterator[ChunkDimProjection]: + g = self.dim_grid + + # iterate over chunks with at least one item + for dim_chunk_ix in self.dim_chunk_ixs: + # find region in chunk + dim_offset = g.chunk_offset(dim_chunk_ix) + chunk_len = g.data_size(dim_chunk_ix) + dim_chunk_sel = self.dim_sel[dim_offset : dim_offset + chunk_len] + + # pad out if boundary chunk (codec buffer may be larger than valid data region) + codec_size = g.chunk_size(dim_chunk_ix) + if dim_chunk_sel.shape[0] < codec_size: + tmp = np.zeros(codec_size, dtype=bool) + tmp[: dim_chunk_sel.shape[0]] = dim_chunk_sel + dim_chunk_sel = tmp + + # find region in output + if dim_chunk_ix == 0: + start = 0 + else: + start = self.chunk_nitems_cumsum[dim_chunk_ix - 1] + stop = self.chunk_nitems_cumsum[dim_chunk_ix] + dim_out_sel = slice(start, stop) + is_complete_chunk = False # TODO + + yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel, is_complete_chunk) + + +class Order(Enum): + """ + Enum for indexing order. + """ + + UNKNOWN = 0 + INCREASING = 1 + DECREASING = 2 + UNORDERED = 3 + + @staticmethod + def check(a: npt.NDArray[Any]) -> Order: + diff = np.diff(a) + diff_positive = diff >= 0 + n_diff_positive = np.count_nonzero(diff_positive) + all_increasing = n_diff_positive == len(diff_positive) + any_increasing = n_diff_positive > 0 + if all_increasing: + order = Order.INCREASING + elif any_increasing: + order = Order.UNORDERED + else: + order = Order.DECREASING + return order + + +def wraparound_indices(x: npt.NDArray[Any], dim_len: int) -> None: + loc_neg = x < 0 + if np.any(loc_neg): + x[loc_neg] += dim_len + + +def boundscheck_indices(x: npt.NDArray[Any], dim_len: int) -> None: + if np.any(x < 0) or np.any(x >= dim_len): + msg = f"index out of bounds for dimension with length {dim_len}" + raise BoundsCheckError(msg) + + +@dataclass(frozen=True) +class IntArrayDimIndexer: + """Integer array selection against a single dimension.""" + + dim_len: int + dim_grid: DimensionGrid + nchunks: int + nitems: int + order: Order + dim_sel: npt.NDArray[np.intp] + dim_out_sel: npt.NDArray[np.intp] + chunk_nitems: int + dim_chunk_ixs: npt.NDArray[np.intp] + chunk_nitems_cumsum: npt.NDArray[np.intp] + + def __init__( + self, + dim_sel: npt.NDArray[np.intp], + dim_len: int, + dim_grid: DimensionGrid, + wraparound: bool = True, + boundscheck: bool = True, + order: Order = Order.UNKNOWN, + ) -> None: + # ensure 1d array + dim_sel = np.asanyarray(dim_sel) + if not is_integer_array(dim_sel, 1): + raise IndexError("integer arrays in an orthogonal selection must be 1-dimensional only") + + nitems = len(dim_sel) + g = dim_grid + nchunks = g.nchunks + + # handle wraparound + if wraparound: + wraparound_indices(dim_sel, dim_len) + + # handle out of bounds + if boundscheck: + boundscheck_indices(dim_sel, dim_len) + + # determine which chunk is needed for each selection item + # note: for dense integer selections, the division operation here is the + # bottleneck + dim_sel_chunk = g.indices_to_chunks(dim_sel) + + # determine order of indices + if order == Order.UNKNOWN: + order = Order.check(dim_sel) + order = Order(order) + + if order == Order.INCREASING: + dim_out_sel = None + elif order == Order.DECREASING: + dim_sel = dim_sel[::-1] + # TODO should be possible to do this without creating an arange + dim_out_sel = np.arange(nitems - 1, -1, -1) + else: + # sort indices to group by chunk + dim_out_sel = np.argsort(dim_sel_chunk) + dim_sel = np.take(dim_sel, dim_out_sel) + + # precompute number of selected items for each chunk + chunk_nitems = np.bincount(dim_sel_chunk, minlength=nchunks) + + # find chunks that we need to visit + dim_chunk_ixs = np.nonzero(chunk_nitems)[0] + + # compute offsets into the output array + chunk_nitems_cumsum = np.cumsum(chunk_nitems) + + # store attributes + object.__setattr__(self, "dim_len", dim_len) + object.__setattr__(self, "dim_grid", dim_grid) + object.__setattr__(self, "nchunks", nchunks) + object.__setattr__(self, "nitems", nitems) + object.__setattr__(self, "order", order) + object.__setattr__(self, "dim_sel", dim_sel) + object.__setattr__(self, "dim_out_sel", dim_out_sel) + object.__setattr__(self, "chunk_nitems", chunk_nitems) + object.__setattr__(self, "dim_chunk_ixs", dim_chunk_ixs) + object.__setattr__(self, "chunk_nitems_cumsum", chunk_nitems_cumsum) + + def __iter__(self) -> Iterator[ChunkDimProjection]: + g = self.dim_grid + + for dim_chunk_ix in self.dim_chunk_ixs: + dim_out_sel: slice | npt.NDArray[np.intp] + # find region in output + if dim_chunk_ix == 0: + start = 0 + else: + start = self.chunk_nitems_cumsum[dim_chunk_ix - 1] + stop = self.chunk_nitems_cumsum[dim_chunk_ix] + if self.order == Order.INCREASING: + dim_out_sel = slice(start, stop) + else: + dim_out_sel = self.dim_out_sel[start:stop] + + # find region in chunk + dim_offset = g.chunk_offset(dim_chunk_ix) + dim_chunk_sel = self.dim_sel[start:stop] - dim_offset + is_complete_chunk = False # TODO + yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel, is_complete_chunk) + + +def slice_to_range(s: slice, length: int) -> range: + return range(*s.indices(length)) + + +def ix_(selection: Any, shape: tuple[int, ...]) -> npt.NDArray[np.intp]: + """Convert an orthogonal selection to a numpy advanced (fancy) selection, like ``numpy.ix_`` + but with support for slices and single ints.""" + + # normalisation + selection = replace_ellipsis(selection, shape) + + # replace slice and int as these are not supported by numpy.ix_ + selection = [ + slice_to_range(dim_sel, dim_len) + if isinstance(dim_sel, slice) + else [dim_sel] + if is_integer(dim_sel) + else dim_sel + for dim_sel, dim_len in zip(selection, shape, strict=True) + ] + + # now get numpy to convert to a coordinate selection + selection = np.ix_(*selection) + + return cast("npt.NDArray[np.intp]", selection) + + +def oindex(a: npt.NDArray[Any], selection: Selection) -> npt.NDArray[Any]: + """Implementation of orthogonal indexing with slices and ints.""" + selection = replace_ellipsis(selection, a.shape) + drop_axes = tuple(i for i, s in enumerate(selection) if is_integer(s)) + selection = ix_(selection, a.shape) + result = a[selection] + if drop_axes: + result = result.squeeze(axis=drop_axes) + return result + + +def oindex_set(a: npt.NDArray[Any], selection: Selection, value: Any) -> None: + selection = replace_ellipsis(selection, a.shape) + drop_axes = tuple(i for i, s in enumerate(selection) if is_integer(s)) + selection = ix_(selection, a.shape) + if not np.isscalar(value) and drop_axes: + value = np.asanyarray(value) + value_selection: list[Selector | None] = [slice(None)] * len(a.shape) + for i in drop_axes: + value_selection[i] = np.newaxis + value = value[tuple(value_selection)] + a[selection] = value + + +@dataclass(frozen=True) +class OrthogonalIndexer(Indexer): + dim_indexers: list[IntDimIndexer | SliceDimIndexer | IntArrayDimIndexer | BoolArrayDimIndexer] + dim_grids: tuple[DimensionGrid, ...] + shape: tuple[int, ...] + is_advanced: bool + drop_axes: tuple[int, ...] + + def __init__(self, selection: Selection, shape: tuple[int, ...], chunk_grid: ChunkGrid) -> None: + dim_grids = chunk_grid._dimensions + + # handle ellipsis + selection = replace_ellipsis(selection, shape) + + # normalize list to array + selection = replace_lists(selection) + + # setup per-dimension indexers + dim_indexers: list[ + IntDimIndexer | SliceDimIndexer | IntArrayDimIndexer | BoolArrayDimIndexer + ] = [] + for dim_sel, dim_len, dim_grid in zip(selection, shape, dim_grids, strict=True): + dim_indexer: IntDimIndexer | SliceDimIndexer | IntArrayDimIndexer | BoolArrayDimIndexer + if is_integer(dim_sel): + dim_indexer = IntDimIndexer(dim_sel, dim_len, dim_grid) + + elif isinstance(dim_sel, slice): + dim_indexer = SliceDimIndexer(dim_sel, dim_len, dim_grid) + + elif is_integer_array(dim_sel): + dim_indexer = IntArrayDimIndexer(dim_sel, dim_len, dim_grid) + + elif is_bool_array(dim_sel): + dim_indexer = BoolArrayDimIndexer(dim_sel, dim_len, dim_grid) + + else: + raise IndexError( + "unsupported selection item for orthogonal indexing; " + "expected integer, slice, integer array or Boolean " + f"array, got {type(dim_sel)!r}" + ) + + dim_indexers.append(dim_indexer) + + shape = tuple(s.nitems for s in dim_indexers if not isinstance(s, IntDimIndexer)) + is_advanced = not is_basic_selection(selection) + if is_advanced: + drop_axes = tuple( + i + for i, dim_indexer in enumerate(dim_indexers) + if isinstance(dim_indexer, IntDimIndexer) + ) + else: + drop_axes = () + + object.__setattr__(self, "dim_indexers", dim_indexers) + object.__setattr__(self, "dim_grids", dim_grids) + object.__setattr__(self, "shape", shape) + object.__setattr__(self, "is_advanced", is_advanced) + object.__setattr__(self, "drop_axes", drop_axes) + + def __iter__(self) -> Iterator[ChunkProjection]: + for dim_projections in itertools.product(*self.dim_indexers): + chunk_coords = tuple(p.dim_chunk_ix for p in dim_projections) + chunk_selection: tuple[Selector, ...] | npt.NDArray[Any] = tuple( + p.dim_chunk_sel for p in dim_projections + ) + out_selection: tuple[Selector, ...] | npt.NDArray[Any] = tuple( + p.dim_out_sel for p in dim_projections if p.dim_out_sel is not None + ) + + # handle advanced indexing arrays orthogonally + if self.is_advanced: + # NumPy can handle a single array-indexed dimension directly, + # which preserves full slices and avoids an + # unnecessary advanced-indexing copy. Integer-indexed + # dimensions still need the ix_ path for downstream squeezing. + # Example: we skip `ix_` for array[:, :, [1, 2, 3]] + n_array_dims = sum(isinstance(sel, np.ndarray) for sel in chunk_selection) + + if n_array_dims > 1 or self.drop_axes: + # N.B., numpy doesn't support orthogonal indexing directly + # for multiple array-indexed dimensions, so we need to + # convert the orthogonal selection into coordinate arrays. + chunk_shape = tuple( + g.chunk_size(p.dim_chunk_ix) + for g, p in zip(self.dim_grids, dim_projections, strict=True) + ) + chunk_selection = ix_(chunk_selection, chunk_shape) + + # special case for non-monotonic indices + if not is_basic_selection(out_selection): + out_selection = ix_(out_selection, self.shape) + + is_complete_chunk = all(p.is_complete_chunk for p in dim_projections) + yield ChunkProjection(chunk_coords, chunk_selection, out_selection, is_complete_chunk) + + +@dataclass(frozen=True) +class OIndex: + array: AnyArray + + # TODO: develop Array generic and move zarr.Array[np.intp] | zarr.Array[np.bool_] to ArrayOfIntOrBool + def __getitem__(self, selection: OrthogonalSelection | AnyArray) -> NDArrayLikeOrScalar: + from zarr.core.array import Array + + # if input is a Zarr array, we materialize it now. + if isinstance(selection, Array): + selection = _zarr_array_to_int_or_bool_array(selection) + + fields, new_selection = pop_fields(selection) + new_selection = ensure_tuple(new_selection) + new_selection = replace_lists(new_selection) + return self.array.get_orthogonal_selection( + cast("OrthogonalSelection", new_selection), fields=fields + ) + + def __setitem__(self, selection: OrthogonalSelection, value: npt.ArrayLike) -> None: + fields, new_selection = pop_fields(selection) + new_selection = ensure_tuple(new_selection) + new_selection = replace_lists(new_selection) + return self.array.set_orthogonal_selection( + cast("OrthogonalSelection", new_selection), value, fields=fields + ) + + +@dataclass(frozen=True) +class AsyncOIndex[T_ArrayMetadata: (ArrayV2Metadata, ArrayV3Metadata)]: + array: AsyncArray[T_ArrayMetadata] + + async def getitem(self, selection: OrthogonalSelection | AnyArray) -> NDArrayLikeOrScalar: + from zarr.core.array import Array + + # if input is a Zarr array, we materialize it now. + if isinstance(selection, Array): + selection = _zarr_array_to_int_or_bool_array(selection) + + fields, new_selection = pop_fields(selection) + new_selection = ensure_tuple(new_selection) + new_selection = replace_lists(new_selection) + return await self.array.get_orthogonal_selection( + cast(OrthogonalSelection, new_selection), fields=fields + ) + + +@dataclass(frozen=True) +class BlockIndexer(Indexer): + dim_indexers: list[SliceDimIndexer] + shape: tuple[int, ...] + drop_axes: tuple[int, ...] + + def __init__( + self, selection: BasicSelection, shape: tuple[int, ...], chunk_grid: ChunkGrid + ) -> None: + dim_grids = chunk_grid._dimensions + + # handle ellipsis + selection_normalized = replace_ellipsis(selection, shape) + + # normalize list to array + selection_normalized = replace_lists(selection_normalized) + + # setup per-dimension indexers + dim_indexers = [] + for dim_sel, dim_len, dim_grid in zip(selection_normalized, shape, dim_grids, strict=True): + dim_numchunks = dim_grid.nchunks + + if is_integer(dim_sel): + if dim_sel < 0: + dim_sel = dim_numchunks + dim_sel + + if dim_sel < 0 or dim_sel >= dim_numchunks: + raise BoundsCheckError( + f"block index out of bounds for dimension with {dim_numchunks} chunk(s)" + ) + + start = dim_grid.chunk_offset(dim_sel) + stop = start + dim_grid.chunk_size(dim_sel) + slice_ = slice(start, stop) + + elif is_slice(dim_sel): + start = dim_sel.start if dim_sel.start is not None else 0 + stop = dim_sel.stop if dim_sel.stop is not None else dim_numchunks + + if dim_sel.step not in {1, None}: + raise IndexError( + "unsupported selection item for block indexing; " + f"expected integer or slice with step=1, got {type(dim_sel)!r}" + ) + + # Can't reuse wraparound_indices because it expects a numpy array + # We have integers here. + if start < 0: + start = dim_numchunks + start + if stop < 0: + stop = dim_numchunks + stop + + start = dim_grid.chunk_offset(start) if start < dim_numchunks else dim_len + stop = dim_grid.chunk_offset(stop) if stop < dim_numchunks else dim_len + slice_ = slice(start, stop) + + else: + raise IndexError( + "unsupported selection item for block indexing; " + f"expected integer or slice, got {type(dim_sel)!r}" + ) + + dim_indexer = SliceDimIndexer(slice_, dim_len, dim_grid) + dim_indexers.append(dim_indexer) + + if slice_.start >= dim_len or slice_.start < 0: + msg = f"index out of bounds for dimension with length {dim_len}" + raise BoundsCheckError(msg) + + shape = tuple(s.nitems for s in dim_indexers) + + object.__setattr__(self, "dim_indexers", dim_indexers) + object.__setattr__(self, "shape", shape) + object.__setattr__(self, "drop_axes", ()) + + def __iter__(self) -> Iterator[ChunkProjection]: + for dim_projections in itertools.product(*self.dim_indexers): + chunk_coords = tuple(p.dim_chunk_ix for p in dim_projections) + chunk_selection = tuple(p.dim_chunk_sel for p in dim_projections) + out_selection = tuple( + p.dim_out_sel for p in dim_projections if p.dim_out_sel is not None + ) + is_complete_chunk = all(p.is_complete_chunk for p in dim_projections) + yield ChunkProjection(chunk_coords, chunk_selection, out_selection, is_complete_chunk) + + +@dataclass(frozen=True) +class BlockIndex: + array: AnyArray + + def __getitem__(self, selection: BasicSelection) -> NDArrayLikeOrScalar: + fields, new_selection = pop_fields(selection) + new_selection = ensure_tuple(new_selection) + new_selection = replace_lists(new_selection) + return self.array.get_block_selection(cast("BasicSelection", new_selection), fields=fields) + + def __setitem__(self, selection: BasicSelection, value: npt.ArrayLike) -> None: + fields, new_selection = pop_fields(selection) + new_selection = ensure_tuple(new_selection) + new_selection = replace_lists(new_selection) + return self.array.set_block_selection( + cast("BasicSelection", new_selection), value, fields=fields + ) + + +def is_coordinate_selection( + selection: SelectionNormalized, shape: tuple[int, ...] +) -> TypeGuard[CoordinateSelectionNormalized]: + return ( + isinstance(selection, tuple) + and len(selection) == len(shape) + and all(is_integer(dim_sel) or is_integer_array(dim_sel) for dim_sel in selection) + ) + + +def is_mask_selection(selection: Selection, shape: tuple[int, ...]) -> TypeGuard[MaskSelection]: + return ( + isinstance(selection, tuple) + and len(selection) == 1 + and is_bool_array(selection[0]) + and selection[0].shape == shape + ) + + +@dataclass(frozen=True) +class CoordinateIndexer(Indexer): + sel_shape: tuple[int, ...] + selection: CoordinateSelectionNormalized + sel_sort: npt.NDArray[np.intp] | None + chunk_nitems_cumsum: npt.NDArray[np.intp] + chunk_rixs: npt.NDArray[np.intp] + chunk_mixs: tuple[npt.NDArray[np.intp], ...] + shape: tuple[int, ...] + dim_grids: tuple[DimensionGrid, ...] + drop_axes: tuple[int, ...] + + def __init__( + self, selection: CoordinateSelection, shape: tuple[int, ...], chunk_grid: ChunkGrid + ) -> None: + dim_grids = chunk_grid._dimensions + + cdata_shape: tuple[int, ...] + if shape == (): + cdata_shape = (1,) + else: + cdata_shape = tuple(g.nchunks for g in dim_grids) + nchunks = math.prod(cdata_shape) + + # some initial normalization + selection_normalized = cast("CoordinateSelectionNormalized", ensure_tuple(selection)) + selection_normalized = tuple( + np.asarray([i], dtype=np.intp) if is_integer(i) else i for i in selection_normalized + ) + selection_normalized = cast( + "CoordinateSelectionNormalized", replace_lists(selection_normalized) + ) + + # validation + if not is_coordinate_selection(selection_normalized, shape): + raise IndexError( + "invalid coordinate selection; expected one integer " + "(coordinate) array per dimension of the target array, " + f"got {selection!r}" + ) + + # Optimization for a single sorted, in-bounds, 1-D integer coordinate array over a + # regular (fixed-size) chunk grid. The general path below makes several full passes over + # the flat selection. For sufficiently dense selections, locating the internal chunk + # boundaries with searchsorted is cheaper. + if len(selection_normalized) == 1: + (coords,) = selection_normalized + g0 = dim_grids[0] + # coords is an integer ndarray here: is_coordinate_selection() validated above, and + # the normalization turned ints/lists into arrays. Only the sorted-1D-over-regular-grid + # shape is special-cased; everything else falls through to the general path below. + if ( + isinstance(g0, FixedDimension) + and g0.size > 0 # guard the divide below + and coords.ndim == 1 + and coords.size > 0 + and coords[0] >= 0 + and coords[-1] < shape[0] + and coords[0] <= coords[-1] + ): + size = g0.size + first = int(coords[0]) // size + last = int(coords[-1]) // size + chunk_span = last - first + 1 + # searchsorted does O(log n) work per chunk in the spanned range. Fall through + # when directly processing the coordinates is expected to be cheaper. + if ( + chunk_span * coords.size.bit_length() < coords.size + and bool((coords[:-1] <= coords[1:]).all()) # sorted -> grouped by chunk + ): + # Search only internal boundaries. Derive the first and last counts from the + # selection bounds so that the boundary after the last chunk cannot overflow. + if first == last: + counts = np.array([coords.size], dtype=np.intp) + else: + edges = np.arange(first + 1, last + 1, dtype=coords.dtype) * size + cuts = np.searchsorted(coords, edges) + counts = np.diff(cuts, prepend=0, append=coords.size) + chunk_rixs = (first + np.nonzero(counts)[0]).astype(np.intp) + chunk_nitems = np.zeros(nchunks, dtype=np.intp) + chunk_nitems[first : last + 1] = counts + chunk_nitems_cumsum = np.cumsum(chunk_nitems) + + object.__setattr__(self, "sel_shape", coords.shape) + object.__setattr__(self, "selection", (coords,)) + object.__setattr__(self, "sel_sort", None) + object.__setattr__(self, "chunk_nitems_cumsum", chunk_nitems_cumsum) + object.__setattr__(self, "chunk_rixs", chunk_rixs) + object.__setattr__(self, "chunk_mixs", (chunk_rixs,)) + object.__setattr__(self, "dim_grids", dim_grids) + object.__setattr__(self, "shape", coords.shape) + object.__setattr__(self, "drop_axes", ()) + return + + # handle wraparound, boundscheck + for dim_sel, dim_len in zip(selection_normalized, shape, strict=True): + # handle wraparound + wraparound_indices(dim_sel, dim_len) + + # handle out of bounds + boundscheck_indices(dim_sel, dim_len) + + # compute chunk index for each point in the selection + chunks_multi_index = tuple( + g.indices_to_chunks(dim_sel) + for (dim_sel, g) in zip(selection_normalized, dim_grids, strict=True) + ) + + # broadcast selection - this will raise error if array dimensions don't match + selection_broadcast = tuple(np.broadcast_arrays(*selection_normalized)) + chunks_multi_index_broadcast = np.broadcast_arrays(*chunks_multi_index) + + # remember shape of selection, because we will flatten indices for processing + sel_shape = selection_broadcast[0].shape or (1,) + + # flatten selection + selection_broadcast = tuple(dim_sel.reshape(-1) for dim_sel in selection_broadcast) + chunks_multi_index_broadcast = tuple( + dim_chunks.reshape(-1) for dim_chunks in chunks_multi_index_broadcast + ) + + # ravel chunk indices + chunks_raveled_indices = np.ravel_multi_index( + chunks_multi_index_broadcast, dims=cdata_shape + ) + + # group points by chunk + if np.any(np.diff(chunks_raveled_indices) < 0): + # optimisation, only sort if needed + sel_sort = np.argsort(chunks_raveled_indices) + selection_broadcast = tuple(dim_sel[sel_sort] for dim_sel in selection_broadcast) + else: + sel_sort = None + + shape = selection_broadcast[0].shape or (1,) + + # precompute number of selected items for each chunk + chunk_nitems = np.bincount(chunks_raveled_indices, minlength=nchunks) + chunk_nitems_cumsum = np.cumsum(chunk_nitems) + # locate the chunks we need to process + chunk_rixs = np.nonzero(chunk_nitems)[0] + + # unravel chunk indices + chunk_mixs = np.unravel_index(chunk_rixs, cdata_shape) + + object.__setattr__(self, "sel_shape", sel_shape) + object.__setattr__(self, "selection", selection_broadcast) + object.__setattr__(self, "sel_sort", sel_sort) + object.__setattr__(self, "chunk_nitems_cumsum", chunk_nitems_cumsum) + object.__setattr__(self, "chunk_rixs", chunk_rixs) + object.__setattr__(self, "chunk_mixs", chunk_mixs) + object.__setattr__(self, "dim_grids", dim_grids) + object.__setattr__(self, "shape", shape) + object.__setattr__(self, "drop_axes", ()) + + def __iter__(self) -> Iterator[ChunkProjection]: + # iterate over chunks + for i, chunk_rix in enumerate(self.chunk_rixs): + chunk_coords = tuple(m[i] for m in self.chunk_mixs) + if chunk_rix == 0: + start = 0 + else: + start = self.chunk_nitems_cumsum[chunk_rix - 1] + stop = self.chunk_nitems_cumsum[chunk_rix] + out_selection: slice | npt.NDArray[np.intp] + if self.sel_sort is None: + out_selection = slice(start, stop) + else: + out_selection = self.sel_sort[start:stop] + + chunk_offsets = tuple( + g.chunk_offset(dim_chunk_ix) + for dim_chunk_ix, g in zip(chunk_coords, self.dim_grids, strict=True) + ) + chunk_selection = tuple( + dim_sel[start:stop] - dim_chunk_offset + for (dim_sel, dim_chunk_offset) in zip(self.selection, chunk_offsets, strict=True) + ) + + is_complete_chunk = False # TODO + yield ChunkProjection(chunk_coords, chunk_selection, out_selection, is_complete_chunk) + + +@dataclass(frozen=True) +class MaskIndexer(CoordinateIndexer): + def __init__( + self, selection: MaskSelection, shape: tuple[int, ...], chunk_grid: ChunkGrid + ) -> None: + # some initial normalization + selection_normalized = cast("tuple[MaskSelection]", ensure_tuple(selection)) + selection_normalized = cast("tuple[MaskSelection]", replace_lists(selection_normalized)) + + # validation + if not is_mask_selection(selection_normalized, shape): + raise IndexError( + "invalid mask selection; expected one Boolean (mask)" + f"array with the same shape as the target array, got {selection_normalized!r}" + ) + + # convert to indices + selection_indices = np.nonzero(selection_normalized[0]) + + # delegate the rest to superclass + super().__init__(selection_indices, shape, chunk_grid) + + +@dataclass(frozen=True) +class VIndex: + array: AnyArray + + # TODO: develop Array generic and move zarr.Array[np.intp] | zarr.Array[np.bool_] to ArrayOfIntOrBool + def __getitem__( + self, selection: CoordinateSelection | MaskSelection | AnyArray + ) -> NDArrayLikeOrScalar: + from zarr.core.array import Array + + # if input is a Zarr array, we materialize it now. + if isinstance(selection, Array): + selection = _zarr_array_to_int_or_bool_array(selection) + fields, new_selection = pop_fields(selection) + new_selection = ensure_tuple(new_selection) + new_selection = replace_lists(new_selection) + if is_coordinate_selection(new_selection, self.array.shape): + return self.array.get_coordinate_selection(new_selection, fields=fields) + elif is_mask_selection(new_selection, self.array.shape): + return self.array.get_mask_selection(new_selection, fields=fields) + else: + msg = ( + "unsupported selection type for vectorized indexing; only " + "coordinate selection (tuple of integer arrays) and mask selection " + f"(single Boolean array) are supported; got {new_selection!r}" + ) + raise VindexInvalidSelectionError(msg) + + def __setitem__( + self, selection: CoordinateSelection | MaskSelection, value: npt.ArrayLike + ) -> None: + fields, new_selection = pop_fields(selection) + new_selection = ensure_tuple(new_selection) + new_selection = replace_lists(new_selection) + if is_coordinate_selection(new_selection, self.array.shape): + self.array.set_coordinate_selection(new_selection, value, fields=fields) + elif is_mask_selection(new_selection, self.array.shape): + self.array.set_mask_selection(new_selection, value, fields=fields) + else: + msg = ( + "unsupported selection type for vectorized indexing; only " + "coordinate selection (tuple of integer arrays) and mask selection " + f"(single Boolean array) are supported; got {new_selection!r}" + ) + raise VindexInvalidSelectionError(msg) + + +@dataclass(frozen=True) +class AsyncVIndex[T_ArrayMetadata: (ArrayV2Metadata, ArrayV3Metadata)]: + array: AsyncArray[T_ArrayMetadata] + + # TODO: develop Array generic and move zarr.Array[np.intp] | zarr.Array[np.bool_] to ArrayOfIntOrBool + async def getitem( + self, selection: CoordinateSelection | MaskSelection | AnyArray + ) -> NDArrayLikeOrScalar: + # TODO deduplicate these internals with the sync version of getitem + # TODO requires solving this circular sync issue: https://github.com/zarr-developers/zarr-python/pull/3083#discussion_r2230737448 + from zarr.core.array import Array + + # if input is a Zarr array, we materialize it now. + if isinstance(selection, Array): + selection = _zarr_array_to_int_or_bool_array(selection) + fields, new_selection = pop_fields(selection) + new_selection = ensure_tuple(new_selection) + new_selection = replace_lists(new_selection) + if is_coordinate_selection(new_selection, self.array.shape): + return await self.array.get_coordinate_selection(new_selection, fields=fields) + elif is_mask_selection(new_selection, self.array.shape): + return await self.array.get_mask_selection(new_selection, fields=fields) + else: + msg = ( + "unsupported selection type for vectorized indexing; only " + "coordinate selection (tuple of integer arrays) and mask selection " + f"(single Boolean array) are supported; got {new_selection!r}" + ) + raise VindexInvalidSelectionError(msg) + + +def check_fields(fields: Fields | None, dtype: np.dtype[Any]) -> np.dtype[Any]: + # early out + if fields is None: + return dtype + # check type + if not isinstance(fields, str | list | tuple): + raise IndexError( + f"'fields' argument must be a string or list of strings; found {type(fields)!r}" + ) + if fields: + if dtype.names is None: + raise IndexError("invalid 'fields' argument, array does not have any fields") + try: + if isinstance(fields, str): + # single field selection + out_dtype = dtype[fields] + else: + # multiple field selection + out_dtype = np.dtype([(f, dtype[f]) for f in fields]) + except KeyError as e: + raise IndexError(f"invalid 'fields' argument, field not found: {e!r}") from e + else: + return out_dtype + else: + return dtype + + +def check_no_multi_fields(fields: Fields | None) -> Fields | None: + if isinstance(fields, list): + if len(fields) == 1: + return fields[0] + elif len(fields) > 1: + raise IndexError("multiple fields are not supported for this operation") + return fields + + +def pop_fields(selection: SelectionWithFields) -> tuple[Fields | None, Selection]: + if isinstance(selection, str): + # single field selection + return selection, () + elif not isinstance(selection, tuple): + # single selection item, no fields + # leave selection as-is + return None, cast("Selection", selection) + else: + # multiple items, split fields from selection items + fields: Fields = [f for f in selection if isinstance(f, str)] + fields = fields[0] if len(fields) == 1 else fields + selection_tuple = tuple(s for s in selection if not isinstance(s, str)) + selection = cast( + "Selection", selection_tuple[0] if len(selection_tuple) == 1 else selection_tuple + ) + return fields, selection + + +def make_slice_selection(selection: Any) -> list[slice]: + ls: list[slice] = [] + for dim_selection in selection: + if is_integer(dim_selection): + ls.append(slice(int(dim_selection), int(dim_selection) + 1, 1)) + elif isinstance(dim_selection, np.ndarray): + if len(dim_selection) == 1: + ls.append(slice(int(dim_selection[0]), int(dim_selection[0]) + 1, 1)) + else: + raise ArrayIndexError + else: + ls.append(dim_selection) + return ls + + +def decode_morton(z: int, chunk_shape: tuple[int, ...]) -> tuple[int, ...]: + # Inspired by compressed morton code as implemented in Neuroglancer + # https://github.com/google/neuroglancer/blob/master/src/neuroglancer/datasource/precomputed/volume.md#compressed-morton-code + bits = tuple((c - 1).bit_length() for c in chunk_shape) + max_coords_bits = max(bits) + input_bit = 0 + input_value = z + out = [0] * len(chunk_shape) + + for coord_bit in range(max_coords_bits): + for dim in range(len(chunk_shape)): + if coord_bit < bits[dim]: + bit = (input_value >> input_bit) & 1 + out[dim] |= bit << coord_bit + input_bit += 1 + return tuple(out) + + +def decode_morton_vectorized( + z: npt.NDArray[np.intp], chunk_shape: tuple[int, ...] +) -> npt.NDArray[np.intp]: + """Vectorized Morton code decoding for multiple z values. + + Parameters + ---------- + z : ndarray + 1D array of Morton codes to decode. + chunk_shape : tuple of int + Shape defining the coordinate space. + + Returns + ------- + ndarray + 2D array of shape (len(z), len(chunk_shape)) containing decoded coordinates. + """ + n_dims = len(chunk_shape) + bits = tuple((c - 1).bit_length() for c in chunk_shape) + + max_coords_bits = max(bits) if bits else 0 + out = np.zeros((len(z), n_dims), dtype=np.intp) + + input_bit = 0 + for coord_bit in range(max_coords_bits): + for dim in range(n_dims): + if coord_bit < bits[dim]: + # Extract bit at position input_bit from all z values + bit_values = (z >> input_bit) & 1 + # Place bit at coord_bit position in dimension dim + out[:, dim] |= bit_values << coord_bit + input_bit += 1 + + return out + + +@lru_cache(maxsize=16) +def _morton_order(shape: tuple[int, ...]) -> npt.NDArray[np.intp]: + n_total = product(shape) + n_dims = len(shape) + if n_total == 0: + out = np.empty((0, n_dims), dtype=np.intp) + out.flags.writeable = False + return out + + # Ceiling hypercube: smallest power-of-2 hypercube whose Morton codes span + # all valid coordinates in shape. (c-1).bit_length() gives the number + # of bits needed to index c values (0 for singleton dims). n_z = 2**total_bits + # is the size of this hypercube. + total_bits = sum((c - 1).bit_length() for c in shape) + n_z = 1 << total_bits if total_bits > 0 else 1 + + # Decode all Morton codes in the ceiling hypercube, then filter to valid coords. + # This is fully vectorized. For shapes with n_z >> n_total (e.g. (33,33,33): + # n_z=262144, n_total=35937), consider the argsort strategy below. + order: npt.NDArray[np.intp] + if n_z <= 4 * n_total: + # Ceiling strategy: decode all n_z codes vectorized, filter in-bounds. + # Works well when the overgeneration ratio n_z/n_total is small (≀4). + z_values = np.arange(n_z, dtype=np.intp) + all_coords = decode_morton_vectorized(z_values, shape) + shape_arr = np.array(shape, dtype=np.intp) + valid_mask = np.all(all_coords < shape_arr, axis=1) + order = all_coords[valid_mask] + else: + # Argsort strategy: enumerate all n_total valid coordinates directly, + # encode each to a Morton code, then sort by code. Avoids the 8x or + # larger overgeneration penalty for near-miss shapes like (33,33,33). + # Cost: O(n_total * bits) encode + O(n_total log n_total) sort, + # vs O(n_z * bits) = O(8 * n_total * bits) for ceiling. + grids = np.meshgrid(*[np.arange(c, dtype=np.intp) for c in shape], indexing="ij") + all_coords = np.stack([g.ravel() for g in grids], axis=1) + + # Encode all coordinates to Morton codes (vectorized). + bits_per_dim = tuple((c - 1).bit_length() for c in shape) + max_coord_bits = max(bits_per_dim) + z_codes = np.zeros(n_total, dtype=np.intp) + output_bit = 0 + for coord_bit in range(max_coord_bits): + for dim in range(n_dims): + if coord_bit < bits_per_dim[dim]: + z_codes |= ((all_coords[:, dim] >> coord_bit) & 1) << output_bit + output_bit += 1 + + sort_idx: npt.NDArray[np.intp] = np.argsort(z_codes, kind="stable") + order = np.asarray(all_coords[sort_idx], dtype=np.intp) + + order.flags.writeable = False + return order + + +@lru_cache(maxsize=16) +def morton_order_coords(shape: tuple[int, ...]) -> tuple[tuple[int, ...], ...]: + # The grid coordinates in Morton (Z) order, as a cached sequence. The + # coordinate set of a finite grid has a known length and is reused in full on + # every shard write, so it is built once (vectorized, via `_morton_order`) and + # cached per shape rather than recomputed. Indexable and `len`-able; iterate it + # directly where an iterator is needed. + # + # `.tolist()` converts the whole array to native Python ints in one C-level + # call; building the tuples row-by-row with `int(x)` is ~9x slower. + return tuple(map(tuple, _morton_order(shape).tolist())) + + +@lru_cache(maxsize=16) +def _lexicographic_order(shape: tuple[int, ...]) -> npt.NDArray[np.intp]: + # Lexicographic (C-order) coordinates, computed vectorized and cached so that + # the sharding codec's per-shard chunk grid is not rebuilt on every call. + # Equivalent to `np.array(list(np.ndindex(shape)))` but without the + # Python-level iteration over every coordinate. + n_dims = len(shape) + if n_dims == 0: + # A 0-d shard holds a single chunk addressed by the empty coordinate, so + # the coordinate array has one row and zero columns. np.indices(()) cannot + # express this, so build it directly. Matches list(np.ndindex(())) == [()]. + order = np.empty((1, 0), dtype=np.intp) + else: + order = np.indices(shape, dtype=np.intp).reshape(n_dims, -1).T + order.flags.writeable = False + return order + + +@lru_cache(maxsize=16) +def lexicographic_order_coords(shape: tuple[int, ...]) -> tuple[tuple[int, ...], ...]: + # The grid coordinates in lexicographic (row-major / C) order, as a cached + # sequence. The coordinate set of a finite grid has a known length and is + # reused in full on every shard write, so it is built once (vectorized, via + # `_lexicographic_order`) and cached per shape. Indexable and `len`-able; + # iterate it directly where an iterator is needed. + # + # `.tolist()` converts the whole array to native Python ints in one C-level + # call; building the tuples row-by-row with `int(x)` is ~9x slower. + return tuple(map(tuple, _lexicographic_order(shape).tolist())) + + +@lru_cache(maxsize=16) +def colexicographic_order_coords(shape: tuple[int, ...]) -> tuple[tuple[int, ...], ...]: + # The grid coordinates in colexicographic (column-major / F) order, as a cached + # sequence: the first axis varies fastest. Equivalent to reversing each axis, + # taking lexicographic order, and reversing the coordinates back. Cached per + # shape like its siblings so shard writes don't rebuild it. + return tuple(c[::-1] for c in lexicographic_order_coords(shape[::-1])) + + +def get_indexer( + selection: SelectionWithFields, shape: tuple[int, ...], chunk_grid: ChunkGrid +) -> Indexer: + _, pure_selection = pop_fields(selection) + if is_pure_fancy_indexing(pure_selection, len(shape)): + new_selection = ensure_tuple(selection) + new_selection = replace_lists(new_selection) + if is_coordinate_selection(new_selection, shape): + return CoordinateIndexer(cast("CoordinateSelection", selection), shape, chunk_grid) + elif is_mask_selection(new_selection, shape): + return MaskIndexer(cast("MaskSelection", selection), shape, chunk_grid) + else: + msg = ( + "unsupported selection type for vectorized indexing; only " + "coordinate selection (tuple of integer arrays) and mask selection " + f"(single Boolean array) are supported; got {new_selection!r}" + ) + raise VindexInvalidSelectionError(msg) + elif is_pure_orthogonal_indexing(pure_selection, len(shape)): + return OrthogonalIndexer(cast("OrthogonalSelection", selection), shape, chunk_grid) + else: + return BasicIndexer(cast("BasicSelection", selection), shape, chunk_grid) diff --git a/src/zarr/core/json_parse.py b/src/zarr/core/json_parse.py new file mode 100644 index 0000000000..09c5ca074e --- /dev/null +++ b/src/zarr/core/json_parse.py @@ -0,0 +1,103 @@ +"""Helpers for validating JSON-decoded metadata. + +Most JSON metadata validation is delegated to +[`msgspec.convert`][msgspec.convert], which handles the type coercions Zarr +needs (``Literal`` membership, ``int``/``bool`` strictness, list-to-tuple, +``TypedDict`` with ``NotRequired``). ``convert`` is a thin wrapper that +translates [`msgspec.ValidationError`][msgspec.ValidationError] into the +``TypeError`` the rest of the codebase already raises. + +msgspec cannot handle two things in Zarr's metadata types: + +* the recursive ``JSON`` / ``JSONValue`` aliases, which it rejects at + schema-build time, and +* PEP 728 ``extra_items=`` extension fields, which it silently drops. + +``validate_json_value`` is the small hand-written fallback for the first of +those. See https://github.com/zarr-developers/zarr-python/issues/3285. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, Final, cast, get_origin + +import msgspec + +if TYPE_CHECKING: + from zarr.core.common import JSON + +__all__ = ["MAX_JSON_DEPTH", "convert", "parse_field", "validate_json_value"] + +MAX_JSON_DEPTH: Final = 64 +"""Maximum nesting depth accepted by ``validate_json_value``.""" + + +def _type_name(type_: Any) -> str: + """Render ``type_`` for an error message. + + Parameterized types keep their arguments, so a ``Literal`` reports its + members (``Literal[2, 3]``) rather than the bare origin name. ``__name__`` + would drop them, which loses the most useful part of the message. + """ + if get_origin(type_) is not None: + return str(type_).replace("typing.", "") + return getattr(type_, "__name__", None) or str(type_).replace("typing.", "") + + +def convert(value: object, type_: Any, *, strict: bool = True) -> Any: + """Validate and coerce ``value`` against ``type_`` via [`msgspec.convert`][msgspec.convert]. + + On a mismatch msgspec raises + [`msgspec.ValidationError`][msgspec.ValidationError]; this re-raises + a plain, field-agnostic ``ValueError`` naming the expected type, so callers + can add their own field context (see ``parse_field``). + """ + try: + return msgspec.convert(value, type_, strict=strict) + except msgspec.ValidationError as exc: + raise ValueError(f"Expected instance of {_type_name(type_)}, got {value!r}.") from exc + + +def parse_field( + data: object, type_: Any, field: str, *, error: type[Exception] = ValueError +) -> Any: + """Validate ``data`` for metadata field ``field`` against ``type_``. + + Wraps ``convert`` and, on failure, re-raises ``error`` with field + context, chaining the underlying type error. This keeps the + ``convert``-then-re-raise pattern in one place rather than repeating it in + every per-field parser. + """ + try: + return convert(data, type_) + except ValueError as exc: + raise error( + f"Failed to parse input for {field!r}: expected {_type_name(type_)}, got {data!r}." + ) from exc + + +def validate_json_value(value: object, *, max_depth: int = MAX_JSON_DEPTH, _depth: int = 0) -> JSON: + """Check that ``value`` is a JSON value and return it unchanged. + + msgspec cannot build a schema for Zarr's recursive ``JSON`` / ``JSONValue`` + aliases, so this covers the fields typed that way (``attributes``, + ``fill_value``, extension-field values). Unlike the previous per-field + parsers it also enforces ``max_depth``: a pathologically nested document + could otherwise exhaust the interpreter stack. + """ + if _depth > max_depth: + raise ValueError(f"JSON value nesting exceeds the maximum depth of {max_depth}.") + if value is None or isinstance(value, (bool, int, float, str)): + return cast("JSON", value) + if isinstance(value, (list, tuple)): + for item in value: + validate_json_value(item, max_depth=max_depth, _depth=_depth + 1) + return cast("JSON", value) + if isinstance(value, Mapping): + for key, item in value.items(): + if not isinstance(key, str): + raise TypeError(f"JSON object keys must be str, got {type(key).__name__}.") + validate_json_value(item, max_depth=max_depth, _depth=_depth + 1) + return cast("JSON", value) + raise TypeError(f"Value {value!r} is not a valid JSON value.") diff --git a/src/zarr/core/metadata/__init__.py b/src/zarr/core/metadata/__init__.py new file mode 100644 index 0000000000..cacfc933b5 --- /dev/null +++ b/src/zarr/core/metadata/__init__.py @@ -0,0 +1,14 @@ +from .v2 import ArrayV2Metadata, ArrayV2MetadataDict +from .v3 import ArrayMetadataJSON_V3, ArrayV3Metadata + +ArrayMetadata = ArrayV2Metadata | ArrayV3Metadata +type ArrayMetadataDict = ArrayV2MetadataDict | ArrayMetadataJSON_V3 + +__all__ = [ + "ArrayMetadata", + "ArrayMetadataDict", + "ArrayMetadataJSON_V3", + "ArrayV2Metadata", + "ArrayV2MetadataDict", + "ArrayV3Metadata", +] diff --git a/src/zarr/core/metadata/common.py b/src/zarr/core/metadata/common.py new file mode 100644 index 0000000000..6367bdb28a --- /dev/null +++ b/src/zarr/core/metadata/common.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from zarr.core.common import JSON + + +def parse_attributes(data: dict[str, JSON] | None) -> dict[str, JSON]: + if data is None: + return {} + + return dict(data) diff --git a/src/zarr/core/metadata/io.py b/src/zarr/core/metadata/io.py new file mode 100644 index 0000000000..7b63f5493b --- /dev/null +++ b/src/zarr/core/metadata/io.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +import asyncio +from typing import TYPE_CHECKING + +from zarr.abc.store import set_or_delete +from zarr.core.buffer.core import default_buffer_prototype +from zarr.errors import ContainsArrayError +from zarr.storage._common import StorePath, ensure_no_existing_node + +if TYPE_CHECKING: + from zarr.core.common import ZarrFormat + from zarr.core.group import GroupMetadata + from zarr.core.metadata import ArrayMetadata + + +def _build_parents(store_path: StorePath, zarr_format: ZarrFormat) -> dict[str, GroupMetadata]: + from zarr.core.group import GroupMetadata + + path = store_path.path + if not path: + return {} + + required_parts = path.split("/")[:-1] + + # the root group + parents = {"": GroupMetadata(zarr_format=zarr_format)} + + for i, part in enumerate(required_parts): + parent_path = "/".join(required_parts[:i] + [part]) + parents[parent_path] = GroupMetadata(zarr_format=zarr_format) + + return parents + + +async def save_metadata( + store_path: StorePath, metadata: ArrayMetadata | GroupMetadata, ensure_parents: bool = False +) -> None: + """Asynchronously save the array or group metadata. + + Parameters + ---------- + store_path : StorePath + Location to save metadata. + metadata : ArrayMetadata | GroupMetadata + Metadata to save. + ensure_parents : bool, optional + Create any missing parent groups, and check no existing parents are arrays. + + Raises + ------ + ValueError + """ + to_save = metadata.to_buffer_dict(default_buffer_prototype()) + set_awaitables = [set_or_delete(store_path / key, value) for key, value in to_save.items()] + + if ensure_parents: + # To enable zarr.create(store, path="a/b/c"), we need to create all the intermediate groups. + parents = _build_parents(store_path, metadata.zarr_format) + ensure_array_awaitables = [] + + for parent_path, parent_metadata in parents.items(): + parent_store_path = StorePath(store_path.store, parent_path) + + # Error if an array already exists at any parent location. Only groups can have child nodes. + ensure_array_awaitables.append( + ensure_no_existing_node( + parent_store_path, parent_metadata.zarr_format, node_type="array" + ) + ) + set_awaitables.extend( + [ + (parent_store_path / key).set_if_not_exists(value) + for key, value in parent_metadata.to_buffer_dict( + default_buffer_prototype() + ).items() + ] + ) + + # Checks for parent arrays must happen first, before any metadata is modified + try: + await asyncio.gather(*ensure_array_awaitables) + except ContainsArrayError as e: + # clear awaitables to avoid RuntimeWarning: coroutine was never awaited + for awaitable in set_awaitables: + awaitable.close() + + raise ValueError( + f"A parent of {store_path} is an array - only groups may have child nodes." + ) from e + + await asyncio.gather(*set_awaitables) diff --git a/src/zarr/core/metadata/v2.py b/src/zarr/core/metadata/v2.py new file mode 100644 index 0000000000..70d4e1e59c --- /dev/null +++ b/src/zarr/core/metadata/v2.py @@ -0,0 +1,353 @@ +from __future__ import annotations + +import json +import warnings +from collections.abc import Iterable, Sequence +from functools import cached_property +from typing import TYPE_CHECKING, Any, TypedDict, cast + +from zarr.abc.metadata import Metadata +from zarr.abc.numcodec import Numcodec, _is_numcodec +from zarr.core.dtype import get_data_type_from_json +from zarr.core.dtype.common import OBJECT_CODEC_IDS, DTypeSpec_V2 +from zarr.errors import ZarrUserWarning +from zarr.registry import get_numcodec + +if TYPE_CHECKING: + from typing import Literal, Self + + import numpy.typing as npt + + from zarr.core.buffer import Buffer, BufferPrototype + from zarr.core.chunk_grids import ChunkGrid + from zarr.core.dtype.wrapper import ( + TBaseDType, + TBaseScalar, + ZDType, + ) + +from dataclasses import dataclass, field, fields, replace + +import numpy as np + +from zarr.core._json import json_to_buffer +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.chunk_key_encodings import parse_separator +from zarr.core.common import ( + JSON, + ZARRAY_JSON, + ZATTRS_JSON, + MemoryOrder, + parse_shapelike, +) +from zarr.core.config import config, parse_indexing_order +from zarr.core.json_parse import parse_field +from zarr.core.metadata.common import parse_attributes + + +class ArrayV2MetadataDict(TypedDict): + """ + A typed dictionary model for Zarr format 2 metadata. + """ + + zarr_format: Literal[2] + attributes: dict[str, JSON] + + +# Union of acceptable types for v2 compressors +type CompressorLikev2 = dict[str, JSON] | Numcodec | None + + +@dataclass(frozen=True, kw_only=True) +class ArrayV2Metadata(Metadata): + shape: tuple[int, ...] + chunks: tuple[int, ...] + dtype: ZDType[TBaseDType, TBaseScalar] + fill_value: int | float | str | bytes | None = None + order: MemoryOrder = "C" + filters: tuple[Numcodec, ...] | None = None + dimension_separator: Literal[".", "/"] = "." + compressor: Numcodec | None + attributes: dict[str, JSON] = field(default_factory=dict) + zarr_format: Literal[2] = field(init=False, default=2) + + def __init__( + self, + *, + shape: tuple[int, ...], + dtype: ZDType[TBaseDType, TBaseScalar], + chunks: tuple[int, ...], + fill_value: Any, + order: MemoryOrder, + dimension_separator: Literal[".", "/"] = ".", + compressor: CompressorLikev2 = None, + filters: Iterable[Numcodec | dict[str, JSON]] | None = None, + attributes: dict[str, JSON] | None = None, + ) -> None: + """ + Metadata for a Zarr format 2 array. + """ + shape_parsed = parse_shapelike(shape) + chunks_parsed = parse_shapelike(chunks) + compressor_parsed = parse_compressor(compressor) + order_parsed = parse_indexing_order(order) + dimension_separator_parsed = parse_separator(dimension_separator) + filters_parsed = parse_filters(filters) + fill_value_parsed: TBaseScalar | None + if fill_value is not None: + fill_value_parsed = dtype.cast_scalar(fill_value) + else: + fill_value_parsed = fill_value + attributes_parsed = parse_attributes(attributes) + + object.__setattr__(self, "shape", shape_parsed) + object.__setattr__(self, "dtype", dtype) + object.__setattr__(self, "chunks", chunks_parsed) + object.__setattr__(self, "compressor", compressor_parsed) + object.__setattr__(self, "order", order_parsed) + object.__setattr__(self, "dimension_separator", dimension_separator_parsed) + object.__setattr__(self, "filters", filters_parsed) + object.__setattr__(self, "fill_value", fill_value_parsed) + object.__setattr__(self, "attributes", attributes_parsed) + + # ensure that the metadata document is consistent + _ = parse_metadata(self) + + @property + def ndim(self) -> int: + return len(self.shape) + + @cached_property + def chunk_grid(self) -> ChunkGrid: + """Backwards-compatible chunk grid property. + + !!! warning "Deprecated" + Access the chunk grid via the array layer instead. + This property will be removed in a future release. + """ + from zarr.core.chunk_grids import ChunkGrid + + warnings.warn( + "ArrayV2Metadata.chunk_grid is deprecated. " + "Use ChunkGrid.from_metadata(metadata) instead.", + DeprecationWarning, + stacklevel=2, + ) + return ChunkGrid.from_sizes(self.shape, tuple(self.chunks)) + + @property + def shards(self) -> tuple[int, ...] | None: + return None + + def to_buffer_dict(self, prototype: BufferPrototype) -> dict[str, Buffer]: + zarray_dict = self.to_dict() + zattrs_dict = zarray_dict.pop("attributes", {}) + indent = config.get("json_indent") + return { + ZARRAY_JSON: json_to_buffer(zarray_dict, prototype=prototype, indent=indent), + ZATTRS_JSON: json_to_buffer(zattrs_dict, prototype=prototype, indent=indent), + } + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> ArrayV2Metadata: + # Make a copy to protect the original from modification. + _data = data.copy() + # Check that the zarr_format attribute is correct. + _ = parse_zarr_format(_data.pop("zarr_format")) + + # To resolve a numpy object dtype array, we need to search for an object codec, + # which could be in filters or as a compressor. + # we will reference a hard-coded collection of object codec ids for this search. + + _filters, _compressor = (data.get("filters"), data.get("compressor")) + if _filters is not None: + _filters = cast("tuple[dict[str, JSON], ...]", _filters) + object_codec_id = get_object_codec_id(tuple(_filters) + (_compressor,)) + else: + object_codec_id = get_object_codec_id((_compressor,)) + # we add a layer of indirection here around the dtype attribute of the array metadata + # because we also need to know the object codec id, if any, to resolve the data type + dtype_spec: DTypeSpec_V2 = { + "name": data["dtype"], + "object_codec_id": object_codec_id, + } + dtype = get_data_type_from_json(dtype_spec, zarr_format=2) + + _data["dtype"] = dtype + fill_value_encoded = _data.get("fill_value") + if fill_value_encoded is not None: + fill_value = dtype.from_json_scalar(fill_value_encoded, zarr_format=2) + _data["fill_value"] = fill_value + + # zarr v2 allowed arbitrary keys here. + # We don't want the ArrayV2Metadata constructor to fail just because someone put an + # extra key in the metadata. + expected = {x.name for x in fields(cls)} + expected |= {"dtype", "chunks"} + + # check if `filters` is an empty sequence; if so use None instead and raise a warning + filters = _data.get("filters") + if ( + isinstance(filters, Sequence) + and not isinstance(filters, (str, bytes)) + and len(filters) == 0 + ): + msg = ( + "Found an empty list of filters in the array metadata document. " + "This is contrary to the Zarr V2 specification, and will cause an error in the future. " + "Use None (or Null in a JSON document) instead of an empty list of filters." + ) + warnings.warn(msg, ZarrUserWarning, stacklevel=1) + _data["filters"] = None + + _data = {k: v for k, v in _data.items() if k in expected} + + return cls(**_data) + + def to_dict(self) -> dict[str, JSON]: + zarray_dict = super().to_dict() + if _is_numcodec(zarray_dict["compressor"]): + codec_config = zarray_dict["compressor"].get_config() + # Hotfix for https://github.com/zarr-developers/zarr-python/issues/2647 + if codec_config["id"] == "zstd" and not codec_config.get("checksum", False): + codec_config.pop("checksum") + zarray_dict["compressor"] = codec_config + + if zarray_dict["filters"] is not None: + raw_filters = zarray_dict["filters"] + # TODO: remove this when we can stratically type the output JSON data structure + # entirely + if not isinstance(raw_filters, list | tuple): + raise TypeError("Invalid type for filters. Expected a list or tuple.") + new_filters = [] + for f in raw_filters: + if _is_numcodec(f): + new_filters.append(f.get_config()) + else: + new_filters.append(f) + zarray_dict["filters"] = new_filters + + # serialize the fill value after dtype-specific JSON encoding + if self.fill_value is not None: + fill_value = self.dtype.to_json_scalar(self.fill_value, zarr_format=2) + zarray_dict["fill_value"] = fill_value + + # pull the "name" attribute out of the dtype spec returned by self.dtype.to_json + zarray_dict["dtype"] = self.dtype.to_json(zarr_format=2)["name"] + + return zarray_dict + + def __eq__(self, other: object) -> bool: + # The default dataclass __eq__ compares fields directly, which is wrong for a NaN + # fill_value: NaN != NaN under IEEE 754. Comparing the JSON-serialized form instead + # treats matching NaN (and inf) fill values as equal. See issue #2929. + if not isinstance(other, ArrayV2Metadata): + return NotImplemented + return self.to_dict() == other.to_dict() + + def __hash__(self) -> int: + # Hash the JSON-serialized form to stay consistent with __eq__: equal metadata + # must hash equally, which a field-based hash violates for a NaN fill_value. + return hash(json.dumps(self.to_dict(), sort_keys=True)) + + def get_chunk_spec( + self, _chunk_coords: tuple[int, ...], array_config: ArrayConfig, prototype: BufferPrototype + ) -> ArraySpec: + return ArraySpec( + shape=self.chunks, + dtype=self.dtype, + fill_value=self.fill_value, + config=array_config, + prototype=prototype, + ) + + def encode_chunk_key(self, chunk_coords: tuple[int, ...]) -> str: + chunk_identifier = self.dimension_separator.join(map(str, chunk_coords)) + return "0" if chunk_identifier == "" else chunk_identifier + + def update_shape(self, shape: tuple[int, ...]) -> Self: + return replace(self, shape=shape) + + def update_attributes(self, attributes: dict[str, JSON]) -> Self: + return replace(self, attributes=attributes) + + +def parse_dtype(data: npt.DTypeLike) -> np.dtype[Any]: + if isinstance(data, list): # this is a valid _VoidDTypeLike check + data = [tuple(d) for d in data] + return np.dtype(data) + + +def parse_zarr_format(data: object) -> Literal[2]: + from typing import Literal + + return cast("Literal[2]", parse_field(data, Literal[2], "zarr_format")) + + +def parse_filters(data: object) -> tuple[Numcodec, ...] | None: + """ + Parse a potential tuple of filters + """ + out: list[Numcodec] = [] + + if data is None: + return data + if isinstance(data, Iterable): + for idx, val in enumerate(data): + if _is_numcodec(val): + out.append(val) + elif isinstance(val, dict): + out.append(get_numcodec(val)) # type: ignore[arg-type] + else: + msg = f"Invalid filter at index {idx}. Expected a numcodecs.abc.Codec or a dict representation of numcodecs.abc.Codec. Got {type(val)} instead." + raise TypeError(msg) + if len(out) == 0: + # Per the v2 spec, an empty tuple is not allowed -- use None to express "no filters" + return None + else: + return tuple(out) + # take a single codec instance and wrap it in a tuple + if _is_numcodec(data): + return (data,) + msg = f"Invalid filters. Expected None, an iterable of numcodecs.abc.Codec or dict representations of numcodecs.abc.Codec. Got {type(data)} instead." + raise TypeError(msg) + + +def parse_compressor(data: object) -> Numcodec | None: + """ + Parse a potential compressor. + """ + if data is None or _is_numcodec(data): + return data + if isinstance(data, dict): + return get_numcodec(data) # type: ignore[arg-type] + msg = f"Invalid compressor. Expected None, a numcodecs.abc.Codec, or a dict representation of a numcodecs.abc.Codec. Got {type(data)} instead." + raise ValueError(msg) + + +def parse_metadata(data: ArrayV2Metadata) -> ArrayV2Metadata: + if (l_chunks := len(data.chunks)) != (l_shape := len(data.shape)): + msg = ( + f"The `shape` and `chunks` attributes must have the same length. " + f"`chunks` has length {l_chunks}, but `shape` has length {l_shape}." + ) + raise ValueError(msg) + return data + + +def get_object_codec_id(maybe_object_codecs: Sequence[JSON]) -> str | None: + """ + Inspect a sequence of codecs / filters for an "object codec", i.e. a codec + that can serialize object arrays to contiguous bytes. Zarr python + maintains a hard-coded set of object codec ids. If any element from the input + has an id that matches one of the hard-coded object codec ids, that id + is returned immediately. + """ + object_codec_id = None + for maybe_object_codec in maybe_object_codecs: + if ( + isinstance(maybe_object_codec, dict) + and maybe_object_codec.get("id") in OBJECT_CODEC_IDS + ): + return cast("str", maybe_object_codec["id"]) + return object_codec_id diff --git a/src/zarr/core/metadata/v3.py b/src/zarr/core/metadata/v3.py new file mode 100644 index 0000000000..fc47f8fc95 --- /dev/null +++ b/src/zarr/core/metadata/v3.py @@ -0,0 +1,715 @@ +from __future__ import annotations + +import json +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass, field, replace +from typing import TYPE_CHECKING, Any, Final, Literal, NotRequired, TypeGuard, cast + +from typing_extensions import TypedDict + +from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec, Codec +from zarr.abc.metadata import Metadata +from zarr.core._json import json_to_buffer +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer.core import default_buffer_prototype +from zarr.core.chunk_grids import is_regular_nd +from zarr.core.chunk_key_encodings import ( + ChunkKeyEncoding, + ChunkKeyEncodingLike, + parse_chunk_key_encoding, +) +from zarr.core.common import ( + JSON, + ZARR_JSON, + DimensionNamesLike, + NamedConfig, + NamedRequiredConfig, + compress_rle, + expand_rle, + parse_named_configuration, + parse_shapelike, + validate_rectilinear_edges, + validate_rectilinear_kind, +) +from zarr.core.config import config +from zarr.core.dtype import VariableLengthUTF8, ZDType, get_data_type_from_json +from zarr.core.dtype.common import check_dtype_spec_v3 +from zarr.core.json_parse import parse_field, validate_json_value +from zarr.core.metadata.common import parse_attributes +from zarr.errors import MetadataValidationError, NodeTypeValidationError, UnknownCodecError +from zarr.registry import get_codec_class + +if TYPE_CHECKING: + from typing import Self + + from zarr.core.buffer import Buffer, BufferPrototype + from zarr.core.chunk_grids import ChunksTuple + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar + + +def parse_zarr_format(data: object) -> Literal[3]: + return cast( + "Literal[3]", parse_field(data, Literal[3], "zarr_format", error=MetadataValidationError) + ) + + +def parse_node_type_array(data: object) -> Literal["array"]: + return cast( + 'Literal["array"]', + parse_field(data, Literal["array"], "node_type", error=NodeTypeValidationError), + ) + + +def parse_codecs(data: object) -> tuple[Codec, ...]: + out: tuple[Codec, ...] = () + + if not isinstance(data, Iterable): + raise TypeError(f"Expected iterable, got {type(data)}") + + for c in data: + if isinstance( + c, ArrayArrayCodec | ArrayBytesCodec | BytesBytesCodec + ): # Can't use Codec here because of mypy limitation + out += (c,) + else: + name_parsed, _ = parse_named_configuration(c, require_configuration=False) + + try: + out += (get_codec_class(name_parsed).from_dict(c),) + except KeyError as e: + raise UnknownCodecError(f"Unknown codec: {e.args[0]!r}") from e + + return out + + +def validate_array_bytes_codec(codecs: tuple[Codec, ...]) -> ArrayBytesCodec: + # ensure that we have at least one ArrayBytesCodec + abcs: list[ArrayBytesCodec] = [codec for codec in codecs if isinstance(codec, ArrayBytesCodec)] + if len(abcs) == 0: + raise ValueError("At least one ArrayBytesCodec is required.") + elif len(abcs) > 1: + raise ValueError("Only one ArrayBytesCodec is allowed.") + + return abcs[0] + + +def validate_codecs(codecs: tuple[Codec, ...], dtype: ZDType[TBaseDType, TBaseScalar]) -> None: + """Check that the codecs are valid for the given dtype""" + from zarr.codecs.sharding import ShardingCodec + + abc = validate_array_bytes_codec(codecs) + + # Recursively resolve array-bytes codecs within sharding codecs + while isinstance(abc, ShardingCodec): + abc = validate_array_bytes_codec(abc.codecs) + + # we need to have special codecs if we are decoding vlen strings or bytestrings + # TODO: use codec ID instead of class name + codec_class_name = abc.__class__.__name__ + # TODO: Fix typing here + if isinstance(dtype, VariableLengthUTF8) and not codec_class_name == "VLenUTF8Codec": # type: ignore[unreachable] + raise ValueError( + f"For string dtype, ArrayBytesCodec must be `VLenUTF8Codec`, got `{codec_class_name}`." + ) + + +def parse_dimension_names(data: object) -> tuple[str | None, ...] | None: + if data is None: + return data + elif isinstance(data, Iterable) and all(isinstance(x, type(None) | str) for x in data): + return tuple(data) + else: + msg = f"Expected either None or an iterable of str, got {type(data)}" + raise TypeError(msg) + + +def parse_storage_transformers(data: object) -> tuple[dict[str, JSON], ...]: + """ + Parse storage_transformers. Zarr python cannot use storage transformers + at this time, so this function doesn't attempt to validate them. + """ + if data is None: + return () + if isinstance(data, Iterable) and not isinstance(data, (str, bytes)): + # Materialise once. The previous implementation called ``len(tuple(data))`` + # and then returned ``data`` itself, which exhausted (and discarded) a + # one-shot iterable and could return a value typed as a tuple that was not + # actually a tuple. + return tuple(data) + raise TypeError( + f"Invalid storage_transformers. Expected an iterable of dicts. Got {type(data)} instead." + ) + + +class AllowedExtraField(TypedDict, extra_items=JSON): # type: ignore[call-arg] + """ + This class models allowed extra fields in array metadata. + They must have ``must_understand`` set to ``False``, and may contain + arbitrary additional JSON data. + """ + + must_understand: Literal[False] + + +def check_allowed_extra_field(data: object) -> TypeGuard[AllowedExtraField]: + """ + Check if the extra field is allowed according to the Zarr v3 spec. The object + must be a mapping with a "must_understand" key set to `False`. + """ + return isinstance(data, Mapping) and data.get("must_understand") is False + + +def parse_extra_fields( + data: Mapping[str, AllowedExtraField] | None, +) -> dict[str, AllowedExtraField]: + if data is None: + return {} + else: + conflict_keys = ARRAY_METADATA_KEYS & set(data.keys()) + if len(conflict_keys) > 0: + msg = ( + "Invalid extra fields. " + "The following keys: " + f"{sorted(conflict_keys)} " + "are invalid because they collide with keys reserved for use by the " + "array metadata document." + ) + raise ValueError(msg) + return dict(data) + + +# JSON type for a single dimension's rectilinear spec: +# bare int (uniform shorthand), or list of ints / [value, count] RLE pairs. +RectilinearDimSpecJSON = int | list[int | list[int]] + + +class RegularChunkGridMetadataConfig(TypedDict): + chunk_shape: Sequence[int] + + +class RectilinearChunkGridMetadataConfig(TypedDict): + kind: Literal["inline"] + chunk_shapes: Sequence[RectilinearDimSpecJSON] + + +RegularChunkGridMetadataJSON = NamedRequiredConfig[ + Literal["regular"], RegularChunkGridMetadataConfig +] +RectilinearChunkGridMetadataJSON = NamedRequiredConfig[ + Literal["rectilinear"], RectilinearChunkGridMetadataConfig +] + + +def _parse_chunk_shape(chunk_shape: Iterable[int]) -> tuple[int, ...]: + """Validate and normalize a regular chunk shape. + + Delegates to ``_validate_chunk_shapes`` β€” a regular chunk shape is just + a sequence of bare ints (one per dimension), each of which must be >= 1. + """ + result = _validate_chunk_shapes(tuple(chunk_shape)) + # Regular grids only have bare ints β€” cast is safe after validation + return cast(tuple[int, ...], result) + + +def _validate_chunk_shapes( + chunk_shapes: Sequence[int | Sequence[int]], +) -> tuple[int | tuple[int, ...], ...]: + """Validate per-dimension chunk specifications. + + Each element is either a bare ``int`` (regular step size, must be >= 1) + or a sequence of explicit edge lengths (all must be >= 1, non-empty). + """ + result: list[int | tuple[int, ...]] = [] + for dim_idx, dim_spec in enumerate(chunk_shapes): + if isinstance(dim_spec, int): + if dim_spec < 1: + raise ValueError( + f"Dimension {dim_idx}: integer chunk edge length must be >= 1, got {dim_spec}" + ) + result.append(dim_spec) + else: + edges = tuple(dim_spec) + if not edges: + raise ValueError(f"Dimension {dim_idx} has no chunk edges.") + bad = [i for i, e in enumerate(edges) if e < 1] + if bad: + raise ValueError( + f"Dimension {dim_idx} has invalid edge lengths at indices {bad}: " + f"{[edges[i] for i in bad]}" + ) + result.append(edges) + return tuple(result) + + +@dataclass(frozen=True, kw_only=True) +class RegularChunkGridMetadata(Metadata): + """Metadata-only description of a regular chunk grid. + + Stores just the chunk shape β€” no array extent, no runtime logic. + This is what lives on ``ArrayV3Metadata.chunk_grid``. + """ + + chunk_shape: tuple[int, ...] + + def __post_init__(self) -> None: + chunk_shape_parsed = _parse_chunk_shape(self.chunk_shape) + object.__setattr__(self, "chunk_shape", chunk_shape_parsed) + + @property + def ndim(self) -> int: + return len(self.chunk_shape) + + def to_dict(self) -> RegularChunkGridMetadataJSON: # type: ignore[override] + return { + "name": "regular", + "configuration": {"chunk_shape": self.chunk_shape}, + } + + @classmethod + def from_dict(cls, data: RegularChunkGridMetadataJSON) -> Self: # type: ignore[override] + parse_named_configuration(data, "regular") # validate name + configuration = data["configuration"] + return cls(chunk_shape=_parse_chunk_shape(configuration["chunk_shape"])) + + +@dataclass(frozen=True, kw_only=True) +class RectilinearChunkGridMetadata(Metadata): + """Metadata-only description of a rectilinear chunk grid. + + Each element of ``chunk_shapes`` is either: + + - A bare ``int`` β€” a regular step size that repeats to cover the axis + (the spec's single-integer shorthand). + - A ``tuple[int, ...]`` β€” explicit per-chunk edge lengths (already + expanded from any RLE encoding). + + This distinction matters for faithful round-tripping: a bare int + serializes back as a bare int, while a single-element tuple serializes + as a list. + """ + + chunk_shapes: tuple[int | tuple[int, ...], ...] + + def __post_init__(self) -> None: + if not config.get("array.rectilinear_chunks"): + raise ValueError( + "Rectilinear chunk grids are experimental and disabled by default. " + "Enable them with: zarr.config.set({'array.rectilinear_chunks': True}) " + "or set the environment variable ZARR_ARRAY__RECTILINEAR_CHUNKS=True" + ) + object.__setattr__(self, "chunk_shapes", _validate_chunk_shapes(self.chunk_shapes)) + + @property + def ndim(self) -> int: + return len(self.chunk_shapes) + + def to_dict(self) -> RectilinearChunkGridMetadataJSON: # type: ignore[override] + serialized_dims: list[RectilinearDimSpecJSON] = [] + for dim_spec in self.chunk_shapes: + if isinstance(dim_spec, int): + # Bare int shorthand β€” serialize as-is + serialized_dims.append(dim_spec) + else: + rle = compress_rle(dim_spec) + # Use RLE only if it's actually shorter + if len(rle) < len(dim_spec): + serialized_dims.append(rle) + else: + serialized_dims.append(list(dim_spec)) + return { + "name": "rectilinear", + "configuration": { + "kind": "inline", + "chunk_shapes": tuple(serialized_dims), + }, + } + + def update_shape( + self, old_shape: tuple[int, ...], new_shape: tuple[int, ...] + ) -> RectilinearChunkGridMetadata: + """Return a new RectilinearChunkGridMetadata with edges adjusted for *new_shape*. + + - Bare-int dimensions stay as bare ints (they cover any extent). + - Explicit-edge dimensions: if the new extent exceeds the sum of + edges, a new chunk is appended to cover the additional extent. + Otherwise edges are kept as-is (the spec allows trailing edges + beyond the array extent). + """ + new_chunk_shapes: list[int | tuple[int, ...]] = [] + for dim_spec, new_ext in zip(self.chunk_shapes, new_shape, strict=True): + if isinstance(dim_spec, int): + # Bare int covers any extent β€” no change needed + new_chunk_shapes.append(dim_spec) + else: + edge_sum = sum(dim_spec) + if new_ext > edge_sum: + new_chunk_shapes.append((*dim_spec, new_ext - edge_sum)) + else: + new_chunk_shapes.append(dim_spec) + return RectilinearChunkGridMetadata(chunk_shapes=tuple(new_chunk_shapes)) + + @classmethod + def from_dict(cls, data: RectilinearChunkGridMetadataJSON) -> Self: # type: ignore[override] + parse_named_configuration(data, "rectilinear") # validate name + configuration = data["configuration"] + validate_rectilinear_kind(configuration.get("kind")) + raw_shapes = configuration["chunk_shapes"] + parsed: list[int | tuple[int, ...]] = [] + for dim_spec in raw_shapes: + if isinstance(dim_spec, int): + if dim_spec < 1: + raise ValueError(f"Integer chunk edge length must be >= 1, got {dim_spec}") + parsed.append(dim_spec) + elif isinstance(dim_spec, list): + parsed.append(tuple(expand_rle(dim_spec))) + else: + raise TypeError( + f"Invalid chunk_shapes entry: expected int or list, got {type(dim_spec)}" + ) + return cls(chunk_shapes=tuple(parsed)) + + +ChunkGridMetadata = RegularChunkGridMetadata | RectilinearChunkGridMetadata + + +def create_chunk_grid_metadata( + chunks: ChunksTuple, +) -> ChunkGridMetadata: + """Construct a chunk grid metadata object from a normalized `ChunksTuple`. + + Regular chunks produce a `RegularChunkGridMetadata`. + Rectilinear chunks produce a `RectilinearChunkGridMetadata`. + + Parameters + ---------- + chunks : ChunksTuple + Normalized chunk specification, as returned by + `normalize_chunks_nd` or `guess_chunks`. + + See Also + -------- + parse_chunk_grid : Deserialize a chunk grid from stored JSON metadata. + """ + if is_regular_nd(chunks): + # If we know the chunks specification is regular, then we can take the first + # chunk size for each dimension as the chunk shape. + chunk_shape = tuple(int(dim_chunks[0]) for dim_chunks in chunks) + return RegularChunkGridMetadata(chunk_shape=chunk_shape) + else: + return RectilinearChunkGridMetadata( + chunk_shapes=tuple(tuple(int(x) for x in d) for d in chunks) + ) + + +def parse_chunk_grid( + data: dict[str, JSON] | ChunkGridMetadata | NamedConfig[str, Any], +) -> ChunkGridMetadata: + """Deserialize a chunk grid from stored JSON metadata or pass through an existing instance. + + See Also + -------- + create_chunk_grid_metadata : Construct a chunk grid from user-facing input. + """ + if isinstance(data, (RegularChunkGridMetadata, RectilinearChunkGridMetadata)): + return data + + name, _ = parse_named_configuration(data) + if name == "regular": + return RegularChunkGridMetadata.from_dict(data) # type: ignore[arg-type] + if name == "rectilinear": + return RectilinearChunkGridMetadata.from_dict(data) # type: ignore[arg-type] + raise ValueError(f"Unknown chunk grid name: {name!r}") + + +class ArrayMetadataJSON_V3(TypedDict, extra_items=AllowedExtraField): # type: ignore[call-arg] + """ + A typed dictionary model for zarr v3 array metadata. + + Extra keys are permitted if they conform to ``AllowedExtraField`` + (i.e. they are mappings with ``must_understand: false``). + """ + + zarr_format: Literal[3] + node_type: Literal["array"] + data_type: str | NamedConfig[str, Mapping[str, JSON]] + shape: tuple[int, ...] + chunk_grid: str | NamedConfig[str, Mapping[str, JSON]] + chunk_key_encoding: str | NamedConfig[str, Mapping[str, JSON]] + fill_value: JSON + codecs: tuple[str | NamedConfig[str, Mapping[str, JSON]], ...] + attributes: NotRequired[Mapping[str, JSON]] + storage_transformers: NotRequired[tuple[str | NamedConfig[str, Mapping[str, JSON]], ...]] + dimension_names: NotRequired[tuple[str | None, ...]] + + +""" +The names of the fields of the array metadata document defined in the zarr V3 spec. +""" +ARRAY_METADATA_KEYS: Final[set[str]] = { + "zarr_format", + "node_type", + "data_type", + "shape", + "chunk_grid", + "chunk_key_encoding", + "fill_value", + "codecs", + "attributes", + "storage_transformers", + "dimension_names", +} + + +@dataclass(frozen=True, kw_only=True) +class ArrayV3Metadata(Metadata): + shape: tuple[int, ...] + data_type: ZDType[TBaseDType, TBaseScalar] + chunk_grid: ChunkGridMetadata + chunk_key_encoding: ChunkKeyEncoding + fill_value: Any + codecs: tuple[Codec, ...] + attributes: dict[str, Any] = field(default_factory=dict) + dimension_names: tuple[str | None, ...] | None = None + zarr_format: Literal[3] = field(default=3, init=False) + node_type: Literal["array"] = field(default="array", init=False) + storage_transformers: tuple[dict[str, JSON], ...] + extra_fields: dict[str, AllowedExtraField] + + def __init__( + self, + *, + shape: Iterable[int], + data_type: ZDType[TBaseDType, TBaseScalar], + chunk_grid: dict[str, JSON] | ChunkGridMetadata | NamedConfig[str, Any], + chunk_key_encoding: ChunkKeyEncodingLike, + fill_value: object, + codecs: Iterable[Codec | dict[str, JSON] | NamedConfig[str, Any] | str], + attributes: dict[str, JSON] | None, + dimension_names: DimensionNamesLike, + storage_transformers: Iterable[dict[str, JSON]] | None = None, + extra_fields: Mapping[str, AllowedExtraField] | None = None, + ) -> None: + """ + Because the class is a frozen dataclass, we set attributes using object.__setattr__ + """ + + shape_parsed = parse_shapelike(shape) + chunk_grid_parsed = parse_chunk_grid(chunk_grid) + chunk_key_encoding_parsed = parse_chunk_key_encoding(chunk_key_encoding) + dimension_names_parsed = parse_dimension_names(dimension_names) + # Note: relying on a type method is numpy-specific + fill_value_parsed = data_type.cast_scalar(fill_value) + attributes_parsed = parse_attributes(attributes) + codecs_parsed_partial = parse_codecs(codecs) + storage_transformers_parsed = parse_storage_transformers(storage_transformers) + extra_fields_parsed = parse_extra_fields(extra_fields) + array_spec = ArraySpec( + shape=shape_parsed, + dtype=data_type, + fill_value=fill_value_parsed, + config=ArrayConfig.from_dict({}), # TODO: config is not needed here. + prototype=default_buffer_prototype(), # TODO: prototype is not needed here. + ) + # Thread the spec through evolution: each codec must be evolved against + # the spec it will actually see at run-time, not the original array spec. + # Earlier array->array codecs may transform the dtype (e.g. cast_value), + # so the spec passed to later codecs must reflect those transformations. + # Per-codec validate() must run before resolve_metadata(), since the + # latter may rely on invariants the former checks (e.g. cast_value + # rejects complex source dtypes that would otherwise crash _do_cast). + evolved: list[Codec] = [] + spec = array_spec + for c in codecs_parsed_partial: + evolved_codec = c.evolve_from_array_spec(spec) + evolved_codec.validate(shape=spec.shape, dtype=spec.dtype, chunk_grid=chunk_grid_parsed) + evolved.append(evolved_codec) + spec = evolved_codec.resolve_metadata(spec) + codecs_parsed = tuple(evolved) + validate_codecs(codecs_parsed_partial, data_type) + + object.__setattr__(self, "shape", shape_parsed) + object.__setattr__(self, "data_type", data_type) + object.__setattr__(self, "chunk_grid", chunk_grid_parsed) + object.__setattr__(self, "chunk_key_encoding", chunk_key_encoding_parsed) + object.__setattr__(self, "codecs", codecs_parsed) + object.__setattr__(self, "dimension_names", dimension_names_parsed) + object.__setattr__(self, "fill_value", fill_value_parsed) + object.__setattr__(self, "attributes", attributes_parsed) + object.__setattr__(self, "storage_transformers", storage_transformers_parsed) + object.__setattr__(self, "extra_fields", extra_fields_parsed) + + self._validate_metadata() + + def _validate_metadata(self) -> None: + if len(self.shape) != self.chunk_grid.ndim: + raise ValueError("`chunk_grid` and `shape` need to have the same number of dimensions.") + if isinstance(self.chunk_grid, RectilinearChunkGridMetadata): + validate_rectilinear_edges(self.chunk_grid.chunk_shapes, self.shape) + if self.dimension_names is not None and len(self.shape) != len(self.dimension_names): + raise ValueError( + "`dimension_names` and `shape` need to have the same number of dimensions." + ) + if self.fill_value is None: + raise ValueError("`fill_value` is required.") + for codec in self.codecs: + codec.validate(shape=self.shape, dtype=self.data_type, chunk_grid=self.chunk_grid) + + @property + def ndim(self) -> int: + return len(self.shape) + + @property + def dtype(self) -> ZDType[TBaseDType, TBaseScalar]: + return self.data_type + + # TODO: move these properties to the Array class. + # They require knowledge of codecs (ShardingCodec) and don't belong on a metadata DTO. + + @property + def chunks(self) -> tuple[int, ...]: + if not isinstance(self.chunk_grid, RegularChunkGridMetadata): + msg = ( + "The `chunks` attribute is only defined for arrays using regular chunk grids. " + "This array has a rectilinear chunk grid. Use `read_chunk_sizes` for general access." + ) + raise NotImplementedError(msg) + + from zarr.codecs.sharding import ShardingCodec + + if len(self.codecs) == 1 and isinstance(self.codecs[0], ShardingCodec): + return self.codecs[0].chunk_shape + return self.chunk_grid.chunk_shape + + @property + def shards(self) -> tuple[int, ...] | None: + from zarr.codecs.sharding import ShardingCodec + + if len(self.codecs) == 1 and isinstance(self.codecs[0], ShardingCodec): + if not isinstance(self.chunk_grid, RegularChunkGridMetadata): + msg = ( + "The `shards` attribute is only defined for arrays using regular chunk grids. " + "This array has a rectilinear chunk grid. Use `write_chunk_sizes` for general access." + ) + raise NotImplementedError(msg) + return self.chunk_grid.chunk_shape + return None + + @property + def inner_codecs(self) -> tuple[Codec, ...]: + from zarr.codecs.sharding import ShardingCodec + + if len(self.codecs) == 1 and isinstance(self.codecs[0], ShardingCodec): + return self.codecs[0].codecs + return self.codecs + + def encode_chunk_key(self, chunk_coords: tuple[int, ...]) -> str: + return self.chunk_key_encoding.encode_chunk_key(chunk_coords) + + def to_buffer_dict(self, prototype: BufferPrototype) -> dict[str, Buffer]: + indent = config.get("json_indent") + return {ZARR_JSON: json_to_buffer(self.to_dict(), prototype=prototype, indent=indent)} + + @classmethod + def from_dict(cls, data: dict[str, JSON]) -> Self: + # make a copy because we are modifying the dict + _data = data.copy() + + # check that the zarr_format attribute is correct + _ = parse_zarr_format(_data.pop("zarr_format")) + # check that the node_type attribute is correct + _ = parse_node_type_array(_data.pop("node_type")) + + data_type_json = _data.pop("data_type") + if not check_dtype_spec_v3(data_type_json): + raise ValueError(f"Invalid data_type: {data_type_json!r}") + data_type = get_data_type_from_json(data_type_json, zarr_format=3) + + # check that the fill value is consistent with the data type + try: + fill = _data.pop("fill_value") + fill_value_parsed = data_type.from_json_scalar(fill, zarr_format=3) + except ValueError as e: + raise TypeError(f"Invalid fill_value: {fill!r}") from e + + # check if there are extra keys + extra_keys = set(_data.keys()) - ARRAY_METADATA_KEYS + allowed_extra_fields: dict[str, AllowedExtraField] = {} + invalid_extra_fields = {} + for key in extra_keys: + val = _data[key] + if check_allowed_extra_field(val): + allowed_extra_fields[key] = val + else: + invalid_extra_fields[key] = val + if len(invalid_extra_fields) > 0: + msg = ( + "Got a Zarr V3 metadata document with the following disallowed extra fields:" + f"{sorted(invalid_extra_fields.keys())}." + 'Extra fields are not allowed unless they are a dict with a "must_understand" key' + "which is assigned the value `False`." + ) + raise MetadataValidationError(msg) + # TODO: replace this with a real type check! + _data_typed = cast(ArrayMetadataJSON_V3, _data) + + return cls( + shape=_data_typed["shape"], + chunk_grid=_data_typed["chunk_grid"], # type: ignore[arg-type] + chunk_key_encoding=_data_typed["chunk_key_encoding"], # type: ignore[arg-type] + codecs=_data_typed["codecs"], + attributes=validate_json_value(_data_typed.get("attributes", {})), # type: ignore[arg-type] + dimension_names=_data_typed.get("dimension_names", None), + fill_value=fill_value_parsed, + data_type=data_type, + extra_fields=allowed_extra_fields, + storage_transformers=_data_typed.get("storage_transformers", ()), # type: ignore[arg-type] + ) + + def to_dict(self) -> dict[str, JSON]: + out_dict = super().to_dict() + extra_fields = out_dict.pop("extra_fields") + out_dict = out_dict | extra_fields # type: ignore[operator] + + out_dict["chunk_grid"] = self.chunk_grid.to_dict() + + out_dict["fill_value"] = self.data_type.to_json_scalar( + self.fill_value, zarr_format=self.zarr_format + ) + if not isinstance(out_dict, dict): + raise TypeError(f"Expected dict. Got {type(out_dict)}.") + + # if `dimension_names` is `None`, we do not include it in + # the metadata document + if out_dict["dimension_names"] is None: + out_dict.pop("dimension_names") + + # TODO: replace the `to_dict` / `from_dict` on the `Metadata`` class with + # to_json, from_json, and have ZDType inherit from `Metadata` + # until then, we have this hack here, which relies on the fact that to_dict will pass through + # any non-`Metadata` fields as-is. + dtype_meta = out_dict["data_type"] + if isinstance(dtype_meta, ZDType): + out_dict["data_type"] = dtype_meta.to_json(zarr_format=3) # type: ignore[unreachable] + return out_dict + + def __eq__(self, other: object) -> bool: + # The default dataclass __eq__ compares fields directly, which is wrong for a NaN + # fill_value: NaN != NaN under IEEE 754. Comparing the JSON-serialized form instead + # treats matching NaN (and inf) fill values as equal. See issue #2929. + if not isinstance(other, ArrayV3Metadata): + return NotImplemented + return self.to_dict() == other.to_dict() + + def __hash__(self) -> int: + # Hash the JSON-serialized form to stay consistent with __eq__: equal metadata + # must hash equally, which a field-based hash violates for a NaN fill_value. + return hash(json.dumps(self.to_dict(), sort_keys=True)) + + def update_shape(self, shape: tuple[int, ...]) -> Self: + chunk_grid = self.chunk_grid + if isinstance(chunk_grid, RectilinearChunkGridMetadata): + chunk_grid = chunk_grid.update_shape(self.shape, shape) + return replace(self, shape=shape, chunk_grid=chunk_grid) + + def update_attributes(self, attributes: dict[str, JSON]) -> Self: + return replace(self, attributes=attributes) diff --git a/src/zarr/core/sync.py b/src/zarr/core/sync.py new file mode 100644 index 0000000000..724b31a464 --- /dev/null +++ b/src/zarr/core/sync.py @@ -0,0 +1,224 @@ +from __future__ import annotations + +import asyncio +import atexit +import logging +import os +import threading +from concurrent.futures import ThreadPoolExecutor, wait +from typing import TYPE_CHECKING + +from zarr.core.config import config + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine + from typing import Any + +logger = logging.getLogger(__name__) + + +# From https://github.com/fsspec/filesystem_spec/blob/master/fsspec/asyn.py + +iothread: list[threading.Thread | None] = [None] # dedicated IO thread +loop: list[asyncio.AbstractEventLoop | None] = [ + None +] # global event loop for any non-async instance +_lock: threading.Lock | None = None # global lock placeholder +_executor: ThreadPoolExecutor | None = None # global executor placeholder + + +class SyncError(Exception): + pass + + +def _get_lock() -> threading.Lock: + """Allocate or return a threading lock. + + The lock is allocated on first use to allow setting one lock per forked process. + """ + global _lock + if not _lock: + _lock = threading.Lock() + return _lock + + +def _get_executor() -> ThreadPoolExecutor: + """Return Zarr Thread Pool Executor + + The executor is allocated on first use. + """ + global _executor + if not _executor: + max_workers = config.get("threading.max_workers", None) + logger.debug("Creating Zarr ThreadPoolExecutor with max_workers=%s", max_workers) + _executor = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="zarr_pool") + _get_loop().set_default_executor(_executor) + return _executor + + +def cleanup_resources() -> None: + global _executor + if _executor: + _executor.shutdown(wait=True, cancel_futures=True) + _executor = None + + if loop[0] is not None: + with _get_lock(): + # Stop the event loop safely + loop[0].call_soon_threadsafe(loop[0].stop) # Stop loop from another thread + if iothread[0] is not None: + iothread[0].join(timeout=0.2) # Add a timeout to avoid hanging + + if iothread[0].is_alive(): + logger.warning( + "Thread did not finish cleanly; forcefully closing the event loop." + ) + + # Forcefully close the event loop to release resources + loop[0].close() + + # dereference the loop and iothread + loop[0] = None + iothread[0] = None + + +atexit.register(cleanup_resources) + + +def reset_resources_after_fork() -> None: + """ + Ensure that global resources are reset after a fork. Without this function, + forked processes will retain invalid references to the parent process's resources. + """ + # `loop` and `iothread` are mutated in place rather than rebound, so only + # `_executor` needs the global declaration. + global _executor + # These lines are excluded from coverage because this function only runs in a child process, + # which is not observed by the test coverage instrumentation. Despite the apparent lack of + # test coverage, this function should be adequately tested by any test that uses Zarr IO with + # multiprocessing. + loop[0] = None # pragma: no cover + iothread[0] = None # pragma: no cover + _executor = None # pragma: no cover + + +# this is only available on certain operating systems +if hasattr(os, "register_at_fork"): + os.register_at_fork(after_in_child=reset_resources_after_fork) + + +async def _runner[T](coro: Coroutine[Any, Any, T]) -> T | BaseException: + """ + Await a coroutine and return the result of running it. If awaiting the coroutine raises an + exception, the exception will be returned. + """ + try: + return await coro + except Exception as ex: # noqa: BLE001 -- the caller re-raises the returned exception + return ex + + +def sync[T]( + coro: Coroutine[Any, Any, T], + loop: asyncio.AbstractEventLoop | None = None, + timeout: float | None = None, +) -> T: + """ + Make loop run coroutine until it returns. Runs in other thread + """ + if loop is None: + # NB: if the loop is not running *yet*, it is OK to submit work + # and we will wait for it + loop = _get_loop() + if _executor is None and config.get("threading.max_workers", None) is not None: + # trigger executor creation and attach to loop + _ = _get_executor() + if not isinstance(loop, asyncio.AbstractEventLoop): + raise TypeError(f"loop cannot be of type {type(loop)}") + if loop.is_closed(): + raise RuntimeError("Loop is not running") + try: + loop0 = asyncio.events.get_running_loop() + if loop0 is loop: + raise SyncError("Calling sync() from within a running loop") + except RuntimeError: + pass + + future = asyncio.run_coroutine_threadsafe(_runner(coro), loop) + + finished, unfinished = wait([future], return_when=asyncio.ALL_COMPLETED, timeout=timeout) + if len(unfinished) > 0: + raise TimeoutError(f"Coroutine {coro} failed to finish within {timeout} s") + assert len(finished) == 1 + return_result = next(iter(finished)).result() + + if isinstance(return_result, BaseException): + raise return_result + else: + return return_result + + +def _get_loop() -> asyncio.AbstractEventLoop: + """Create or return the default fsspec IO loop + + The loop will be running on a separate thread. + """ + if loop[0] is None: + with _get_lock(): + # repeat the check just in case the loop got filled between the + # previous two calls from another thread + if loop[0] is None: + logger.debug("Creating Zarr event loop") + new_loop = asyncio.new_event_loop() + loop[0] = new_loop + iothread[0] = threading.Thread(target=new_loop.run_forever, name="zarr_io") + assert iothread[0] is not None + iothread[0].daemon = True + iothread[0].start() + assert loop[0] is not None + return loop[0] + + +async def _collect_aiterator[T](data: AsyncIterator[T]) -> tuple[T, ...]: + """ + Collect an entire async iterator into a tuple + """ + result = [x async for x in data] + return tuple(result) + + +def collect_aiterator[T](data: AsyncIterator[T]) -> tuple[T, ...]: + """ + Synchronously collect an entire async iterator into a tuple. + """ + return sync(_collect_aiterator(data)) + + +class SyncMixin: + def _sync[T](self, coroutine: Coroutine[Any, Any, T]) -> T: + # TODO: refactor this to take *args and **kwargs and pass those to the method + # this should allow us to better type the sync wrapper + return sync( + coroutine, + timeout=config.get("async.timeout"), + ) + + def _sync_iter[T](self, async_iterator: AsyncIterator[T]) -> list[T]: + async def iter_to_list() -> list[T]: + return [item async for item in async_iterator] + + return self._sync(iter_to_list()) + + +async def _with_semaphore[T]( + func: Callable[[], Awaitable[T]], semaphore: asyncio.Semaphore | None = None +) -> T: + """ + Await the result of invoking the no-argument-callable ``func`` within the context manager + provided by a Semaphore, if one is provided. Otherwise, just await the result of invoking + ``func``. + """ + if semaphore is None: + return await func() + async with semaphore: + return await func() diff --git a/src/zarr/core/sync_group.py b/src/zarr/core/sync_group.py new file mode 100644 index 0000000000..8af514e938 --- /dev/null +++ b/src/zarr/core/sync_group.py @@ -0,0 +1,163 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from zarr.core.group import Group, GroupMetadata, _parse_async_node +from zarr.core.group import create_hierarchy as create_hierarchy_async +from zarr.core.group import create_nodes as create_nodes_async +from zarr.core.group import create_rooted_hierarchy as create_rooted_hierarchy_async +from zarr.core.group import get_node as get_node_async +from zarr.core.sync import _collect_aiterator, sync + +if TYPE_CHECKING: + from collections.abc import Iterator + + from zarr.abc.store import Store + from zarr.core.common import ZarrFormat + from zarr.core.metadata import ArrayV2Metadata, ArrayV3Metadata + from zarr.types import AnyArray + + +def create_nodes( + *, store: Store, nodes: dict[str, GroupMetadata | ArrayV2Metadata | ArrayV3Metadata] +) -> Iterator[tuple[str, Group | AnyArray]]: + """Create a collection of arrays and / or groups concurrently. + + Note: no attempt is made to validate that these arrays and / or groups collectively form a + valid Zarr hierarchy. It is the responsibility of the caller of this function to ensure that + the ``nodes`` parameter satisfies any correctness constraints. + + Parameters + ---------- + store : Store + The storage backend to use. + nodes : dict[str, GroupMetadata | ArrayV3Metadata | ArrayV2Metadata] + A dictionary defining the hierarchy. The keys are the paths of the nodes + in the hierarchy, and the values are the metadata of the nodes. The + metadata must be either an instance of GroupMetadata, ArrayV3Metadata + or ArrayV2Metadata. + + Yields + ------ + Group | Array + The created nodes. + """ + coro = create_nodes_async(store=store, nodes=nodes) + + for key, value in sync(_collect_aiterator(coro)): + yield key, _parse_async_node(value) + + +def create_hierarchy( + *, + store: Store, + nodes: dict[str, GroupMetadata | ArrayV2Metadata | ArrayV3Metadata], + overwrite: bool = False, +) -> Iterator[tuple[str, Group | AnyArray]]: + """ + Create a complete zarr hierarchy from a collection of metadata objects. + + This function will parse its input to ensure that the hierarchy is complete. Any implicit groups + will be inserted as needed. For example, an input like + ```{'a/b': GroupMetadata}``` will be parsed to + ```{'': GroupMetadata, 'a': GroupMetadata, 'b': Groupmetadata}``` + + After input parsing, this function then creates all the nodes in the hierarchy concurrently. + + Arrays and Groups are yielded in the order they are created. This order is not stable and + should not be relied on. + + Parameters + ---------- + store : Store + The storage backend to use. + nodes : dict[str, GroupMetadata | ArrayV3Metadata | ArrayV2Metadata] + A dictionary defining the hierarchy. The keys are the paths of the nodes in the hierarchy, + relative to the root of the ``Store``. The root of the store can be specified with the empty + string ``''``. The values are instances of ``GroupMetadata`` or ``ArrayMetadata``. Note that + all values must have the same ``zarr_format`` -- it is an error to mix zarr versions in the + same hierarchy. + + Leading "/" characters from keys will be removed. + overwrite : bool + Whether to overwrite existing nodes. Defaults to ``False``, in which case an error is + raised instead of overwriting an existing array or group. + + This function will not erase an existing group unless that group is explicitly named in + ``nodes``. If ``nodes`` defines implicit groups, e.g. ``{`'a/b/c': GroupMetadata}``, and a + group already exists at path ``a``, then this function will leave the group at ``a`` as-is. + + Yields + ------ + tuple[str, Group | Array] + This function yields (path, node) pairs, in the order the nodes were created. + + Examples + -------- + ```python + from zarr import create_hierarchy + from zarr.storage import MemoryStore + from zarr.core.group import GroupMetadata + + store = MemoryStore() + nodes = {'a': GroupMetadata(attributes={'name': 'leaf'})} + nodes_created = dict(create_hierarchy(store=store, nodes=nodes)) + print(nodes) + # {'a': GroupMetadata(attributes={'name': 'leaf'}, zarr_format=3, consolidated_metadata=None, node_type='group')} + ``` + """ + coro = create_hierarchy_async(store=store, nodes=nodes, overwrite=overwrite) + + for key, value in sync(_collect_aiterator(coro)): + yield key, _parse_async_node(value) + + +def create_rooted_hierarchy( + *, + store: Store, + nodes: dict[str, GroupMetadata | ArrayV2Metadata | ArrayV3Metadata], + overwrite: bool = False, +) -> Group | AnyArray: + """ + Create a Zarr hierarchy with a root, and return the root node, which could be a ``Group`` + or ``Array`` instance. + + Parameters + ---------- + store : Store + The storage backend to use. + nodes : dict[str, GroupMetadata | ArrayV3Metadata | ArrayV2Metadata] + A dictionary defining the hierarchy. The keys are the paths of the nodes + in the hierarchy, and the values are the metadata of the nodes. The + metadata must be either an instance of GroupMetadata, ArrayV3Metadata + or ArrayV2Metadata. + overwrite : bool + Whether to overwrite existing nodes. Default is ``False``. + + Returns + ------- + Group | Array + """ + async_node = sync(create_rooted_hierarchy_async(store=store, nodes=nodes, overwrite=overwrite)) + return _parse_async_node(async_node) + + +def get_node(store: Store, path: str, zarr_format: ZarrFormat) -> AnyArray | Group: + """ + Get an Array or Group from a path in a Store. + + Parameters + ---------- + store : Store + The store-like object to read from. + path : str + The path to the node to read. + zarr_format : {2, 3} + The zarr format of the node to read. + + Returns + ------- + Array | Group + """ + + return _parse_async_node(sync(get_node_async(store=store, path=path, zarr_format=zarr_format))) diff --git a/src/zarr/creation.py b/src/zarr/creation.py deleted file mode 100644 index df3f764610..0000000000 --- a/src/zarr/creation.py +++ /dev/null @@ -1,37 +0,0 @@ -import warnings - -from zarr.api.synchronous import ( - array, - create, - empty, - empty_like, - full, - full_like, - ones, - ones_like, - open_array, - open_like, - zeros, - zeros_like, -) - -warnings.warn( - "zarr.creation is deprecated, use zarr.api.synchronous", - DeprecationWarning, - stacklevel=2, -) - -__all__ = [ - "create", - "empty", - "zeros", - "ones", - "full", - "array", - "open_array", - "empty_like", - "zeros_like", - "ones_like", - "full_like", - "open_like", -] diff --git a/src/zarr/dtype.py b/src/zarr/dtype.py new file mode 100644 index 0000000000..0c271b6c90 --- /dev/null +++ b/src/zarr/dtype.py @@ -0,0 +1,109 @@ +from zarr.core.dtype import ( + Bool, + Complex64, + Complex128, + DateTime64, + DateTime64JSON_V2, + DateTime64JSON_V3, + FixedLengthUTF32, + FixedLengthUTF32JSON_V2, + FixedLengthUTF32JSON_V3, + Float16, + Float32, + Float64, + Int8, + Int16, + Int32, + Int64, + NullTerminatedBytes, + NullterminatedBytesJSON_V2, + NullTerminatedBytesJSON_V3, + RawBytes, + RawBytesJSON_V2, + RawBytesJSON_V3, + Struct, + StructJSON_V3, + Structured, + StructuredJSON_V2, + StructuredJSON_V3, + TimeDelta64, + TimeDelta64JSON_V2, + TimeDelta64JSON_V3, + UInt8, + UInt16, + UInt32, + UInt64, + VariableLengthBytes, + VariableLengthBytesJSON_V2, + VariableLengthUTF8, + VariableLengthUTF8JSON_V2, + ZDType, + data_type_registry, + # Import for backwards compatibility, but not included in __all__ + # so it doesn't show up in the docs + parse_data_type, # noqa: F401 + parse_dtype, +) +from zarr.core.dtype.common import DTypeSpec_V2, check_dtype_spec_v2 + +__all__ = [ + "Bool", + "Complex64", + "Complex128", + "DTypeSpec_V2", + "DateTime64", + "DateTime64JSON_V2", + "DateTime64JSON_V3", + "FixedLengthUTF32", + "FixedLengthUTF32JSON_V2", + "FixedLengthUTF32JSON_V3", + "Float16", + "Float32", + "Float64", + "Int8", + "Int16", + "Int32", + "Int64", + "NullTerminatedBytes", + "NullTerminatedBytesJSON_V3", + "NullterminatedBytesJSON_V2", + "RawBytes", + "RawBytesJSON_V2", + "RawBytesJSON_V3", + "Struct", + "StructJSON_V3", + "Structured", + "StructuredJSON_V2", + "StructuredJSON_V3", + "TimeDelta64", + "TimeDelta64JSON_V2", + "TimeDelta64JSON_V3", + "UInt8", + "UInt16", + "UInt32", + "UInt64", + "VariableLengthBytes", + "VariableLengthBytesJSON_V2", + "VariableLengthUTF8", + "VariableLengthUTF8JSON_V2", + "ZDType", + "check_dtype_spec_v2", + "data_type_registry", + "parse_dtype", +] + + +def __getattr__(name: str) -> object: + if name == "DataTypeValidationError": + import warnings + + from zarr.errors import DataTypeValidationError, ZarrDeprecationWarning + + warnings.warn( + "Importing DataTypeValidationError from zarr.dtype is deprecated. " + "Use zarr.errors.DataTypeValidationError instead.", + ZarrDeprecationWarning, + stacklevel=2, + ) + return DataTypeValidationError + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/src/zarr/errors.py b/src/zarr/errors.py index 140229b2eb..781bebe534 100644 --- a/src/zarr/errors.py +++ b/src/zarr/errors.py @@ -1,25 +1,157 @@ -from typing import Any +__all__ = [ + "ArrayIndexError", + "ArrayNotFoundError", + "BaseZarrError", + "BoundsCheckError", + "ChunkNotFoundError", + "ContainsArrayAndGroupError", + "ContainsArrayError", + "ContainsGroupError", + "DataTypeValidationError", + "GroupNotFoundError", + "MetadataValidationError", + "NegativeStepError", + "NodeTypeValidationError", + "UnstableSpecificationWarning", + "VindexInvalidSelectionError", + "ZarrDeprecationWarning", + "ZarrFutureWarning", + "ZarrRuntimeWarning", +] -class _BaseZarrError(ValueError): - _msg = "" +class BaseZarrError(ValueError): + """ + Base error which all zarr errors are sub-classed from. + """ - def __init__(self, *args: Any) -> None: - super().__init__(self._msg.format(*args)) + _msg: str = "{}" + def __init__(self, *args: object) -> None: + """ + If a single argument is passed, treat it as a pre-formatted message. -class ContainsGroupError(_BaseZarrError): - _msg = "A group exists in store {0!r} at path {1!r}." + If multiple arguments are passed, they are used as arguments for a template string class + variable. This behavior is deprecated. + """ + if len(args) == 1: + super().__init__(args[0]) + else: + super().__init__(self._msg.format(*args)) -class ContainsArrayError(_BaseZarrError): - _msg = "An array exists in store {0!r} at path {1!r}." +class NodeNotFoundError(BaseZarrError, FileNotFoundError): + """ + Raised when a node (array or group) is not found at a certain path. + """ -class ContainsArrayAndGroupError(_BaseZarrError): +class ArrayNotFoundError(NodeNotFoundError): + """ + Raised when an array isn't found at a certain path. + """ + + _msg = "No array found in store {!r} at path {!r}" + + +class GroupNotFoundError(NodeNotFoundError): + """ + Raised when a group isn't found at a certain path. + """ + + _msg = "No group found in store {!r} at path {!r}" + + +class ContainsGroupError(BaseZarrError): + """Raised when a group already exists at a certain path.""" + + _msg = "A group exists in store {!r} at path {!r}." + + +class ContainsArrayError(BaseZarrError): + """Raised when an array already exists at a certain path.""" + + _msg = "An array exists in store {!r} at path {!r}." + + +class ContainsArrayAndGroupError(BaseZarrError): + """Raised when both array and group metadata are found at the same path.""" + _msg = ( "Array and group metadata documents (.zarray and .zgroup) were both found in store " - "{0!r} at path {1!r}." + "{!r} at path {!r}. " "Only one of these files may be present in a given directory / prefix. " "Remove the .zarray file, or the .zgroup file, or both." ) + + +class DataTypeValidationError(ValueError): ... + + +class MetadataValidationError(BaseZarrError): + """Raised when the Zarr metadata is invalid in some way""" + + _msg = "Invalid value for '{}'. Expected '{}'. Got '{}'." + + +class UnknownCodecError(BaseZarrError): + """ + Raised when an unknown codec was used. + """ + + +class NodeTypeValidationError(MetadataValidationError): + """ + Specialized exception when the node_type of the metadata document is incorrect. + + This can be raised when the value is invalid or unexpected given the context, + for example an 'array' node when we expected a 'group'. + """ + + +class ZarrFutureWarning(FutureWarning): + """ + A warning intended for end users raised to indicate deprecated features. + """ + + +class UnstableSpecificationWarning(ZarrFutureWarning): + """ + A warning raised to indicate that a feature is outside the Zarr specification. + """ + + +class ZarrDeprecationWarning(DeprecationWarning): + """ + A warning raised to indicate that a feature will be removed in a future release. + """ + + +class ZarrUserWarning(UserWarning): + """ + A warning raised to report problems with user code. + """ + + +class ZarrRuntimeWarning(RuntimeWarning): + """ + A warning for dubious runtime behavior. + """ + + +class VindexInvalidSelectionError(IndexError): ... + + +class NegativeStepError(IndexError): ... + + +class BoundsCheckError(IndexError): ... + + +class ArrayIndexError(IndexError): ... + + +class ChunkNotFoundError(BaseZarrError): + """ + Raised when a chunk that was expected to exist in storage was not retrieved successfully. + """ diff --git a/src/zarr/experimental/__init__.py b/src/zarr/experimental/__init__.py new file mode 100644 index 0000000000..f7caaf96a1 --- /dev/null +++ b/src/zarr/experimental/__init__.py @@ -0,0 +1,5 @@ +"""The experimental module is a site for exporting new or experimental Zarr features.""" + +from zarr.core.chunk_grids import ChunkGrid, ChunkSpec + +__all__ = ["ChunkGrid", "ChunkSpec"] diff --git a/src/zarr/experimental/cache_store.py b/src/zarr/experimental/cache_store.py new file mode 100644 index 0000000000..20cb4d4c0f --- /dev/null +++ b/src/zarr/experimental/cache_store.py @@ -0,0 +1,461 @@ +from __future__ import annotations + +import asyncio +import logging +import time +from collections import OrderedDict +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Literal, Self + +from zarr.abc.store import ByteRequest, Store +from zarr.storage._wrapper import WrapperStore + +logger = logging.getLogger(__name__) + +if TYPE_CHECKING: + from zarr.core.buffer.core import Buffer, BufferPrototype + +# A cache entry identifier. Plain ``str`` for full-key entries that live in +# the Store-backed cache; ``(str, ByteRequest)`` for byte-range entries that +# live in the in-memory range cache. +_CacheEntryKey = str | tuple[str, ByteRequest] + + +@dataclass(slots=True) +class _CacheState: + cache_order: OrderedDict[_CacheEntryKey, None] = field(default_factory=OrderedDict) + current_size: int = 0 + key_sizes: dict[_CacheEntryKey, int] = field(default_factory=dict) + lock: asyncio.Lock = field(default_factory=asyncio.Lock) + hits: int = 0 + misses: int = 0 + evictions: int = 0 + key_insert_times: dict[_CacheEntryKey, float] = field(default_factory=dict) + range_cache: dict[str, dict[ByteRequest, Buffer]] = field(default_factory=dict) + + +class CacheStore(WrapperStore[Store]): + """ + A dual-store caching implementation for Zarr stores. + + This cache wraps any Store implementation and uses a separate Store instance + as the cache backend. This provides persistent caching capabilities with + time-based expiration, size-based eviction, and flexible cache storage options. + + Full-key reads are cached in the Store-backed cache. Byte-range reads are + cached in a separate in-memory dictionary so that partial reads never + pollute the filesystem (or other persistent backend). Both caches share + the same ``max_size`` budget and LRU eviction policy. + + Parameters + ---------- + store : Store + The underlying store to wrap with caching + cache_store : Store + The store to use for caching (can be any Store implementation that + supports deletes) + max_age_seconds : int or "infinity", optional + Maximum age of cached entries in seconds. The string "infinity" means + entries never expire. Default is "infinity". + max_size : int | None, optional + Maximum size of the cache in bytes. When exceeded, least recently used + items are evicted. None means unlimited size. Default is None. + Note: Individual values larger than max_size will not be cached. + cache_set_data : bool, optional + Whether to cache data when it's written to the store. Default is True. + + Examples + -------- + ```python + import zarr + from zarr.storage import MemoryStore + from zarr.experimental.cache_store import CacheStore + + # Create a cached store + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore( + store=source_store, + cache_store=cache_store, + max_age_seconds=60, + max_size=1024*1024 + ) + + # Use it like any other store + array = zarr.create(shape=(100,), store=cached_store) + array[:] = 42 + ``` + + """ + + _cache: Store + max_age_seconds: int | Literal["infinity"] + max_size: int | None + cache_set_data: bool + _state: _CacheState + + def __init__( + self, + store: Store, + *, + cache_store: Store, + max_age_seconds: int | str = "infinity", + max_size: int | None = None, + cache_set_data: bool = True, + ) -> None: + super().__init__(store) + + if not cache_store.supports_deletes: + msg = ( + f"The provided cache store {cache_store} does not support deletes. " + "The cache_store must support deletes for CacheStore to function properly." + ) + raise ValueError(msg) + + self._cache = cache_store + # Validate and set max_age_seconds + if isinstance(max_age_seconds, str): + if max_age_seconds != "infinity": + raise ValueError("max_age_seconds string value must be 'infinity'") + self.max_age_seconds = "infinity" + else: + self.max_age_seconds = max_age_seconds + self.max_size = max_size + self.cache_set_data = cache_set_data + self._state = _CacheState() + + def _with_store(self, store: Store) -> Self: + # Cannot support this operation because it would share a cache, but have a new store + # So cache keys would conflict + raise NotImplementedError("CacheStore does not support this operation.") + + def with_read_only(self, read_only: bool = False) -> Self: + # Create a new cache store that shares the same cache and mutable state + store = type(self)( + store=self._store.with_read_only(read_only), + cache_store=self._cache, + max_age_seconds=self.max_age_seconds, + max_size=self.max_size, + cache_set_data=self.cache_set_data, + ) + store._state = self._state + return store + + def _is_key_fresh(self, entry_key: _CacheEntryKey) -> bool: + """Check if a cached entry is still fresh based on max_age_seconds. + + Uses monotonic time for accurate elapsed time measurement. + """ + if self.max_age_seconds == "infinity": + return True + now = time.monotonic() + elapsed = now - self._state.key_insert_times.get(entry_key, 0) + return elapsed < self.max_age_seconds + + async def _accommodate_value(self, value_size: int) -> None: + """Ensure there is enough space in the cache for a new value. + + Must be called while holding self._state.lock. + """ + if self.max_size is None: + return + + # Remove least recently used items until we have enough space + while self._state.current_size + value_size > self.max_size and self._state.cache_order: + # Get the least recently used key (first in OrderedDict) + lru_key = next(iter(self._state.cache_order)) + await self._evict_key(lru_key) + + async def _evict_key(self, entry_key: _CacheEntryKey) -> None: + """Evict a cache entry. + + Must be called while holding self._state.lock. + + For ``str`` keys the entry is deleted from the Store-backed cache. + For ``(str, ByteRequest)`` keys the entry is removed from the + in-memory range cache. + """ + key_size = self._state.key_sizes.get(entry_key, 0) + + if isinstance(entry_key, str): + await self._cache.delete(entry_key) + else: + base_key, byte_range = entry_key + per_key = self._state.range_cache.get(base_key) + if per_key is not None: + per_key.pop(byte_range, None) + if not per_key: + del self._state.range_cache[base_key] + + self._state.cache_order.pop(entry_key, None) + self._state.key_insert_times.pop(entry_key, None) + self._state.key_sizes.pop(entry_key, None) + self._state.current_size = max(0, self._state.current_size - key_size) + self._state.evictions += 1 + + async def _track_entry(self, entry_key: _CacheEntryKey, value: Buffer) -> bool: + """Register *entry_key* in the shared size / LRU tracking. + + Returns ``True`` if the entry was tracked, ``False`` if the value + exceeds ``max_size`` and was skipped. Callers should roll back any + data they already stored when this returns ``False``. + + This method holds the lock for the entire operation to ensure atomicity. + """ + value_size = len(value) + + # Check if value exceeds max size + if self.max_size is not None and value_size > self.max_size: + return False + + async with self._state.lock: + # If key already exists, subtract old size first + if entry_key in self._state.key_sizes: + old_size = self._state.key_sizes[entry_key] + self._state.current_size -= old_size + + # Make room for the new value + await self._accommodate_value(value_size) + + # Update tracking atomically + self._state.cache_order[entry_key] = None + self._state.current_size += value_size + self._state.key_sizes[entry_key] = value_size + self._state.key_insert_times[entry_key] = time.monotonic() + + return True + + async def _update_access_order(self, entry_key: _CacheEntryKey) -> None: + """Update the access order for LRU tracking.""" + if entry_key in self._state.cache_order: + async with self._state.lock: + self._state.cache_order.move_to_end(entry_key) + + def _remove_from_tracking(self, entry_key: _CacheEntryKey) -> None: + """Remove an entry from all tracking structures. + + Must be called while holding self._state.lock. + """ + self._state.cache_order.pop(entry_key, None) + self._state.key_insert_times.pop(entry_key, None) + self._state.key_sizes.pop(entry_key, None) + + def _invalidate_range_entries(self, key: str) -> None: + """Remove all byte-range entries for *key* from the range cache and tracking. + + Must be called while holding self._state.lock. + """ + per_key = self._state.range_cache.pop(key, None) + if per_key is not None: + for byte_range in per_key: + entry_key: _CacheEntryKey = (key, byte_range) + entry_size = self._state.key_sizes.pop(entry_key, 0) + self._state.cache_order.pop(entry_key, None) + self._state.key_insert_times.pop(entry_key, None) + self._state.current_size = max(0, self._state.current_size - entry_size) + + # ------------------------------------------------------------------ + # get helpers + # ------------------------------------------------------------------ + + async def _cache_miss( + self, key: str, byte_range: ByteRequest | None, result: Buffer | None + ) -> None: + """Handle a cache miss by storing or cleaning up after a source-store fetch.""" + if result is None: + if byte_range is None: + await self._cache.delete(key) + async with self._state.lock: + self._remove_from_tracking(key) + else: + entry_key: _CacheEntryKey = (key, byte_range) + async with self._state.lock: + per_key = self._state.range_cache.get(key) + if per_key is not None: + per_key.pop(byte_range, None) + if not per_key: + del self._state.range_cache[key] + self._remove_from_tracking(entry_key) + else: + if byte_range is None: + await self._cache.set(key, result) + await self._track_entry(key, result) + else: + entry_key = (key, byte_range) + self._state.range_cache.setdefault(key, {})[byte_range] = result + tracked = await self._track_entry(entry_key, result) + if not tracked: + # Value too large for the cache β€” roll back the insertion + per_key = self._state.range_cache.get(key) + if per_key is not None: + per_key.pop(byte_range, None) + if not per_key: + del self._state.range_cache[key] + + async def _get_try_cache( + self, key: str, prototype: BufferPrototype, byte_range: ByteRequest | None = None + ) -> Buffer | None: + """Try to get data from cache first, falling back to source store.""" + if byte_range is None: + # Full-key read β€” use Store-backed cache + maybe_cached = await self._cache.get(key, prototype) + if maybe_cached is not None: + self._state.hits += 1 + await self._update_access_order(key) + return maybe_cached + else: + # Byte-range read β€” use in-memory range cache + entry_key: _CacheEntryKey = (key, byte_range) + per_key = self._state.range_cache.get(key) + if per_key is not None: + cached_buf = per_key.get(byte_range) + if cached_buf is not None: + self._state.hits += 1 + await self._update_access_order(entry_key) + return cached_buf + + # Cache miss β€” fetch from source store + self._state.misses += 1 + result = await super().get(key, prototype, byte_range) + await self._cache_miss(key, byte_range, result) + return result + + async def _get_no_cache( + self, key: str, prototype: BufferPrototype, byte_range: ByteRequest | None = None + ) -> Buffer | None: + """Get data directly from source store and update cache.""" + self._state.misses += 1 + result = await super().get(key, prototype, byte_range) + await self._cache_miss(key, byte_range, result) + return result + + @property + def _supports_sync_io(self) -> bool: + # The caching logic lives only in the async get/set/delete overrides; + # the sync methods inherited from `WrapperStore` delegate straight to + # the source store, so a sync-capable consumer (the fused codec + # pipeline) would write and delete around the cache, leaving stale + # entries that later async reads serve as current data. Opt out of + # sync IO until the sync surface is cache-aware. + return False + + async def get( + self, + key: str, + prototype: BufferPrototype, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + """ + Retrieve data from the store, using cache when appropriate. + + Parameters + ---------- + key : str + The key to retrieve + prototype : BufferPrototype + Buffer prototype for creating the result buffer + byte_range : ByteRequest, optional + Byte range to retrieve + + Returns + ------- + Buffer | None + The retrieved data, or None if not found + """ + entry_key: _CacheEntryKey = (key, byte_range) if byte_range is not None else key + if not self._is_key_fresh(entry_key): + return await self._get_no_cache(key, prototype, byte_range) + else: + return await self._get_try_cache(key, prototype, byte_range) + + async def set(self, key: str, value: Buffer) -> None: + """ + Store data in the underlying store and optionally in cache. + + Parameters + ---------- + key : str + The key to store under + value : Buffer + The data to store + """ + await super().set(key, value) + # Invalidate all cached byte-range entries (source data changed) + async with self._state.lock: + self._invalidate_range_entries(key) + if self.cache_set_data: + await self._cache.set(key, value) + await self._track_entry(key, value) + else: + await self._cache.delete(key) + async with self._state.lock: + self._remove_from_tracking(key) + + async def delete(self, key: str) -> None: + """ + Delete data from both the underlying store and cache. + + Parameters + ---------- + key : str + The key to delete + """ + await super().delete(key) + # Invalidate all cached byte-range entries + async with self._state.lock: + self._invalidate_range_entries(key) + await self._cache.delete(key) + async with self._state.lock: + self._remove_from_tracking(key) + + def cache_info(self) -> dict[str, Any]: + """Return information about the cache state.""" + return { + "cache_store_type": type(self._cache).__name__, + "max_age_seconds": "infinity" + if self.max_age_seconds == "infinity" + else self.max_age_seconds, + "max_size": self.max_size, + "current_size": self._state.current_size, + "cache_set_data": self.cache_set_data, + "tracked_keys": len(self._state.key_insert_times), + "cached_keys": len(self._state.cache_order), + } + + def cache_stats(self) -> dict[str, Any]: + """Return cache performance statistics.""" + total_requests = self._state.hits + self._state.misses + hit_rate = self._state.hits / total_requests if total_requests > 0 else 0.0 + return { + "hits": self._state.hits, + "misses": self._state.misses, + "evictions": self._state.evictions, + "total_requests": total_requests, + "hit_rate": hit_rate, + } + + async def clear_cache(self) -> None: + """Clear all cached data and tracking information.""" + # Clear the cache store if it supports clear + if hasattr(self._cache, "clear"): + await self._cache.clear() + + # Reset tracking + async with self._state.lock: + self._state.key_insert_times.clear() + self._state.cache_order.clear() + self._state.key_sizes.clear() + self._state.range_cache.clear() + self._state.current_size = 0 + + def __repr__(self) -> str: + """Return string representation of the cache store.""" + return ( + f"{self.__class__.__name__}(" + f"store={self._store!r}, " + f"cache_store={self._cache!r}, " + f"max_age_seconds={self.max_age_seconds}, " + f"max_size={self.max_size}, " + f"current_size={self._state.current_size}, " + f"cached_keys={len(self._state.cache_order)})" + ) diff --git a/src/zarr/group.py b/src/zarr/group.py deleted file mode 100644 index 432ebc4604..0000000000 --- a/src/zarr/group.py +++ /dev/null @@ -1,880 +0,0 @@ -from __future__ import annotations - -import asyncio -import json -import logging -from collections.abc import Iterator -from dataclasses import asdict, dataclass, field, replace -from typing import TYPE_CHECKING, Literal, cast, overload - -import numpy.typing as npt -from typing_extensions import deprecated - -from zarr.abc.codec import Codec -from zarr.abc.metadata import Metadata -from zarr.abc.store import set_or_delete -from zarr.array import Array, AsyncArray -from zarr.attributes import Attributes -from zarr.buffer import Buffer, BufferPrototype, default_buffer_prototype -from zarr.chunk_key_encodings import ChunkKeyEncoding -from zarr.common import ( - JSON, - ZARR_JSON, - ZARRAY_JSON, - ZATTRS_JSON, - ZGROUP_JSON, - ChunkCoords, - ZarrFormat, -) -from zarr.config import config -from zarr.store import StoreLike, StorePath, make_store_path -from zarr.store.core import ensure_no_existing_node -from zarr.sync import SyncMixin, sync - -if TYPE_CHECKING: - from collections.abc import AsyncGenerator, Iterable - from typing import Any - -logger = logging.getLogger("zarr.group") - - -def parse_zarr_format(data: Any) -> ZarrFormat: - if data in (2, 3): - return cast(Literal[2, 3], data) - msg = msg = f"Invalid zarr_format. Expected one 2 or 3. Got {data}." - raise ValueError(msg) - - -# todo: convert None to empty dict -def parse_attributes(data: Any) -> dict[str, Any]: - if data is None: - return {} - elif isinstance(data, dict) and all(map(lambda v: isinstance(v, str), data.keys())): - return data - msg = f"Expected dict with string keys. Got {type(data)} instead." - raise TypeError(msg) - - -@overload -def _parse_async_node(node: AsyncArray) -> Array: ... - - -@overload -def _parse_async_node(node: AsyncGroup) -> Group: ... - - -def _parse_async_node(node: AsyncArray | AsyncGroup) -> Array | Group: - """ - Wrap an AsyncArray in an Array, or an AsyncGroup in a Group. - """ - if isinstance(node, AsyncArray): - return Array(node) - elif isinstance(node, AsyncGroup): - return Group(node) - else: - raise TypeError(f"Unknown node type, got {type(node)}") - - -@dataclass(frozen=True) -class GroupMetadata(Metadata): - attributes: dict[str, Any] = field(default_factory=dict) - zarr_format: ZarrFormat = 3 - node_type: Literal["group"] = field(default="group", init=False) - - def to_buffer_dict(self, prototype: BufferPrototype) -> dict[str, Buffer]: - json_indent = config.get("json_indent") - if self.zarr_format == 3: - return { - ZARR_JSON: prototype.buffer.from_bytes( - json.dumps(self.to_dict(), indent=json_indent).encode() - ) - } - else: - return { - ZGROUP_JSON: prototype.buffer.from_bytes( - json.dumps({"zarr_format": self.zarr_format}, indent=json_indent).encode() - ), - ZATTRS_JSON: prototype.buffer.from_bytes( - json.dumps(self.attributes, indent=json_indent).encode() - ), - } - - def __init__(self, attributes: dict[str, Any] | None = None, zarr_format: ZarrFormat = 3): - attributes_parsed = parse_attributes(attributes) - zarr_format_parsed = parse_zarr_format(zarr_format) - - object.__setattr__(self, "attributes", attributes_parsed) - object.__setattr__(self, "zarr_format", zarr_format_parsed) - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> GroupMetadata: - assert data.pop("node_type", None) in ("group", None) - return cls(**data) - - def to_dict(self) -> dict[str, Any]: - return asdict(self) - - -@dataclass(frozen=True) -class AsyncGroup: - metadata: GroupMetadata - store_path: StorePath - - @classmethod - async def create( - cls, - store: StoreLike, - *, - attributes: dict[str, Any] | None = None, - exists_ok: bool = False, - zarr_format: ZarrFormat = 3, - ) -> AsyncGroup: - store_path = await make_store_path(store) - if not exists_ok: - await ensure_no_existing_node(store_path, zarr_format=zarr_format) - attributes = attributes or {} - group = cls( - metadata=GroupMetadata(attributes=attributes, zarr_format=zarr_format), - store_path=store_path, - ) - await group._save_metadata() - return group - - @classmethod - async def open( - cls, - store: StoreLike, - zarr_format: Literal[2, 3, None] = 3, - ) -> AsyncGroup: - store_path = await make_store_path(store) - - if zarr_format == 2: - zgroup_bytes, zattrs_bytes = await asyncio.gather( - (store_path / ZGROUP_JSON).get(), (store_path / ZATTRS_JSON).get() - ) - if zgroup_bytes is None: - raise FileNotFoundError(store_path) - elif zarr_format == 3: - zarr_json_bytes = await (store_path / ZARR_JSON).get() - if zarr_json_bytes is None: - raise FileNotFoundError(store_path) - elif zarr_format is None: - zarr_json_bytes, zgroup_bytes, zattrs_bytes = await asyncio.gather( - (store_path / ZARR_JSON).get(), - (store_path / ZGROUP_JSON).get(), - (store_path / ZATTRS_JSON).get(), - ) - if zarr_json_bytes is not None and zgroup_bytes is not None: - # TODO: revisit this exception type - # alternatively, we could warn and favor v3 - raise ValueError("Both zarr.json and .zgroup objects exist") - if zarr_json_bytes is None and zgroup_bytes is None: - raise FileNotFoundError(store_path) - # set zarr_format based on which keys were found - if zarr_json_bytes is not None: - zarr_format = 3 - else: - zarr_format = 2 - else: - raise ValueError(f"unexpected zarr_format: {zarr_format}") - - if zarr_format == 2: - # V2 groups are comprised of a .zgroup and .zattrs objects - assert zgroup_bytes is not None - zgroup = json.loads(zgroup_bytes.to_bytes()) - zattrs = json.loads(zattrs_bytes.to_bytes()) if zattrs_bytes is not None else {} - group_metadata = {**zgroup, "attributes": zattrs} - else: - # V3 groups are comprised of a zarr.json object - assert zarr_json_bytes is not None - group_metadata = json.loads(zarr_json_bytes.to_bytes()) - - return cls.from_dict(store_path, group_metadata) - - @classmethod - def from_dict( - cls, - store_path: StorePath, - data: dict[str, Any], - ) -> AsyncGroup: - group = cls( - metadata=GroupMetadata.from_dict(data), - store_path=store_path, - ) - return group - - async def getitem( - self, - key: str, - ) -> AsyncArray | AsyncGroup: - store_path = self.store_path / key - logger.debug("key=%s, store_path=%s", key, store_path) - - # Note: - # in zarr-python v2, we first check if `key` references an Array, else if `key` references - # a group,using standalone `contains_array` and `contains_group` functions. These functions - # are reusable, but for v3 they would perform redundant I/O operations. - # Not clear how much of that strategy we want to keep here. - - if self.metadata.zarr_format == 3: - zarr_json_bytes = await (store_path / ZARR_JSON).get() - if zarr_json_bytes is None: - raise KeyError(key) - else: - zarr_json = json.loads(zarr_json_bytes.to_bytes()) - if zarr_json["node_type"] == "group": - return type(self).from_dict(store_path, zarr_json) - elif zarr_json["node_type"] == "array": - return AsyncArray.from_dict(store_path, zarr_json) - else: - raise ValueError(f"unexpected node_type: {zarr_json['node_type']}") - elif self.metadata.zarr_format == 2: - # Q: how do we like optimistically fetching .zgroup, .zarray, and .zattrs? - # This guarantees that we will always make at least one extra request to the store - zgroup_bytes, zarray_bytes, zattrs_bytes = await asyncio.gather( - (store_path / ZGROUP_JSON).get(), - (store_path / ZARRAY_JSON).get(), - (store_path / ZATTRS_JSON).get(), - ) - - if zgroup_bytes is None and zarray_bytes is None: - raise KeyError(key) - - # unpack the zarray, if this is None then we must be opening a group - zarray = json.loads(zarray_bytes.to_bytes()) if zarray_bytes else None - # unpack the zattrs, this can be None if no attrs were written - zattrs = json.loads(zattrs_bytes.to_bytes()) if zattrs_bytes is not None else {} - - if zarray is not None: - # TODO: update this once the V2 array support is part of the primary array class - zarr_json = {**zarray, "attributes": zattrs} - return AsyncArray.from_dict(store_path, zarray) - else: - zgroup = ( - json.loads(zgroup_bytes.to_bytes()) - if zgroup_bytes is not None - else {"zarr_format": self.metadata.zarr_format} - ) - zarr_json = {**zgroup, "attributes": zattrs} - return type(self).from_dict(store_path, zarr_json) - else: - raise ValueError(f"unexpected zarr_format: {self.metadata.zarr_format}") - - async def delitem(self, key: str) -> None: - store_path = self.store_path / key - if self.metadata.zarr_format == 3: - await (store_path / ZARR_JSON).delete() - elif self.metadata.zarr_format == 2: - await asyncio.gather( - (store_path / ZGROUP_JSON).delete(), # TODO: missing_ok=False - (store_path / ZARRAY_JSON).delete(), # TODO: missing_ok=False - (store_path / ZATTRS_JSON).delete(), # TODO: missing_ok=True - ) - else: - raise ValueError(f"unexpected zarr_format: {self.metadata.zarr_format}") - - async def _save_metadata(self) -> None: - to_save = self.metadata.to_buffer_dict(default_buffer_prototype()) - awaitables = [set_or_delete(self.store_path / key, value) for key, value in to_save.items()] - await asyncio.gather(*awaitables) - - @property - def path(self) -> str: - """Storage path.""" - return self.store_path.path - - @property - def name(self) -> str: - """Group name following h5py convention.""" - if self.path: - # follow h5py convention: add leading slash - name = self.path - if name[0] != "/": - name = "/" + name - return name - return "/" - - @property - def basename(self) -> str: - """Final component of name.""" - return self.name.split("/")[-1] - - @property - def attrs(self) -> dict[str, Any]: - return self.metadata.attributes - - @property - def info(self) -> None: - raise NotImplementedError - - async def create_group( - self, - path: str, - exists_ok: bool = False, - attributes: dict[str, Any] | None = None, - ) -> AsyncGroup: - attributes = attributes or {} - return await type(self).create( - self.store_path / path, - attributes=attributes, - exists_ok=exists_ok, - zarr_format=self.metadata.zarr_format, - ) - - async def create_array( - self, - path: str, - shape: ChunkCoords, - dtype: npt.DTypeLike = "float64", - fill_value: Any | None = None, - attributes: dict[str, JSON] | None = None, - # v3 only - chunk_shape: ChunkCoords | None = None, - chunk_key_encoding: ( - ChunkKeyEncoding - | tuple[Literal["default"], Literal[".", "/"]] - | tuple[Literal["v2"], Literal[".", "/"]] - | None - ) = None, - codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: Iterable[str] | None = None, - # v2 only - chunks: ChunkCoords | None = None, - dimension_separator: Literal[".", "/"] | None = None, - order: Literal["C", "F"] | None = None, - filters: list[dict[str, JSON]] | None = None, - compressor: dict[str, JSON] | None = None, - # runtime - exists_ok: bool = False, - data: npt.ArrayLike | None = None, - ) -> AsyncArray: - """ - Create a Zarr array within this AsyncGroup. - This method lightly wraps AsyncArray.create. - - Parameters - ---------- - path: str - The name of the array. - shape: tuple[int, ...] - The shape of the array. - dtype: np.DtypeLike = float64 - The data type of the array. - chunk_shape: tuple[int, ...] | None = None - The shape of the chunks of the array. V3 only. - chunk_key_encoding: ChunkKeyEncoding | tuple[Literal["default"], Literal[".", "/"]] | tuple[Literal["v2"], Literal[".", "/"]] | None = None - A specification of how the chunk keys are represented in storage. - codecs: Iterable[Codec | dict[str, JSON]] | None = None - An iterable of Codec or dict serializations thereof. The elements of - this collection specify the transformation from array values to stored bytes. - dimension_names: Iterable[str] | None = None - The names of the dimensions of the array. V3 only. - chunks: ChunkCoords | None = None - The shape of the chunks of the array. V2 only. - dimension_separator: Literal[".", "/"] | None = None - The delimiter used for the chunk keys. - order: Literal["C", "F"] | None = None - The memory order of the array. - filters: list[dict[str, JSON]] | None = None - Filters for the array. - compressor: dict[str, JSON] | None = None - The compressor for the array. - exists_ok: bool = False - If True, a pre-existing array or group at the path of this array will - be overwritten. If False, the presence of a pre-existing array or group is - an error. - - Returns - ------- - AsyncArray - - """ - return await AsyncArray.create( - self.store_path / path, - shape=shape, - dtype=dtype, - chunk_shape=chunk_shape, - fill_value=fill_value, - chunk_key_encoding=chunk_key_encoding, - codecs=codecs, - dimension_names=dimension_names, - attributes=attributes, - chunks=chunks, - dimension_separator=dimension_separator, - order=order, - filters=filters, - compressor=compressor, - exists_ok=exists_ok, - zarr_format=self.metadata.zarr_format, - data=data, - ) - - async def update_attributes(self, new_attributes: dict[str, Any]) -> AsyncGroup: - # metadata.attributes is "frozen" so we simply clear and update the dict - self.metadata.attributes.clear() - self.metadata.attributes.update(new_attributes) - - # Write new metadata - await self._save_metadata() - - return self - - def __repr__(self) -> str: - return f"" - - async def nmembers(self) -> int: - # TODO: consider using aioitertools.builtins.sum for this - # return await aioitertools.builtins.sum((1 async for _ in self.members()), start=0) - n = 0 - async for _ in self.members(): - n += 1 - return n - - async def members(self) -> AsyncGenerator[tuple[str, AsyncArray | AsyncGroup], None]: - """ - Returns an AsyncGenerator over the arrays and groups contained in this group. - This method requires that `store_path.store` supports directory listing. - - The results are not guaranteed to be ordered. - """ - if not self.store_path.store.supports_listing: - msg = ( - f"The store associated with this group ({type(self.store_path.store)}) " - "does not support listing, " - "specifically via the `list_dir` method. " - "This function requires a store that supports listing." - ) - - raise ValueError(msg) - # would be nice to make these special keys accessible programmatically, - # and scoped to specific zarr versions - _skip_keys = ("zarr.json", ".zgroup", ".zattrs") - - async for key in self.store_path.store.list_dir(self.store_path.path): - if key in _skip_keys: - continue - try: - yield (key, await self.getitem(key)) - except KeyError: - # keyerror is raised when `key` names an object (in the object storage sense), - # as opposed to a prefix, in the store under the prefix associated with this group - # in which case `key` cannot be the name of a sub-array or sub-group. - logger.warning( - "Object at %s is not recognized as a component of a Zarr hierarchy.", key - ) - - async def contains(self, member: str) -> bool: - # TODO: this can be made more efficient. - try: - await self.getitem(member) - return True - except KeyError: - return False - - # todo: decide if this method should be separate from `groups` - async def group_keys(self) -> AsyncGenerator[str, None]: - async for key, value in self.members(): - if isinstance(value, AsyncGroup): - yield key - - # todo: decide if this method should be separate from `group_keys` - async def groups(self) -> AsyncGenerator[AsyncGroup, None]: - async for _, value in self.members(): - if isinstance(value, AsyncGroup): - yield value - - # todo: decide if this method should be separate from `arrays` - async def array_keys(self) -> AsyncGenerator[str, None]: - async for key, value in self.members(): - if isinstance(value, AsyncArray): - yield key - - # todo: decide if this method should be separate from `array_keys` - async def arrays(self) -> AsyncGenerator[AsyncArray, None]: - async for _, value in self.members(): - if isinstance(value, AsyncArray): - yield value - - async def tree(self, expand: bool = False, level: int | None = None) -> Any: - raise NotImplementedError - - async def empty(self, **kwargs: Any) -> AsyncArray: - raise NotImplementedError - - async def zeros(self, **kwargs: Any) -> AsyncArray: - raise NotImplementedError - - async def ones(self, **kwargs: Any) -> AsyncArray: - raise NotImplementedError - - async def full(self, **kwargs: Any) -> AsyncArray: - raise NotImplementedError - - async def empty_like(self, prototype: AsyncArray, **kwargs: Any) -> AsyncArray: - raise NotImplementedError - - async def zeros_like(self, prototype: AsyncArray, **kwargs: Any) -> AsyncArray: - raise NotImplementedError - - async def ones_like(self, prototype: AsyncArray, **kwargs: Any) -> AsyncArray: - raise NotImplementedError - - async def full_like(self, prototype: AsyncArray, **kwargs: Any) -> AsyncArray: - raise NotImplementedError - - async def move(self, source: str, dest: str) -> None: - raise NotImplementedError - - -@dataclass(frozen=True) -class Group(SyncMixin): - _async_group: AsyncGroup - - @classmethod - def create( - cls, - store: StoreLike, - *, - attributes: dict[str, Any] | None = None, - zarr_format: ZarrFormat = 3, - exists_ok: bool = False, - ) -> Group: - attributes = attributes or {} - obj = sync( - AsyncGroup.create( - store, - attributes=attributes, - exists_ok=exists_ok, - zarr_format=zarr_format, - ), - ) - - return cls(obj) - - @classmethod - def open( - cls, - store: StoreLike, - ) -> Group: - obj = sync(AsyncGroup.open(store)) - return cls(obj) - - def __getitem__(self, path: str) -> Array | Group: - obj = self._sync(self._async_group.getitem(path)) - if isinstance(obj, AsyncArray): - return Array(obj) - else: - return Group(obj) - - def __delitem__(self, key: str) -> None: - self._sync(self._async_group.delitem(key)) - - def __iter__(self) -> Iterator[str]: - raise NotImplementedError - - def __len__(self) -> int: - raise NotImplementedError - - def __setitem__(self, key: str, value: Any) -> None: - """__setitem__ is not supported in v3""" - raise NotImplementedError - - async def update_attributes_async(self, new_attributes: dict[str, Any]) -> Group: - new_metadata = replace(self.metadata, attributes=new_attributes) - - # Write new metadata - to_save = new_metadata.to_buffer_dict(default_buffer_prototype()) - awaitables = [set_or_delete(self.store_path / key, value) for key, value in to_save.items()] - await asyncio.gather(*awaitables) - - async_group = replace(self._async_group, metadata=new_metadata) - return replace(self, _async_group=async_group) - - @property - def store_path(self) -> StorePath: - return self._async_group.store_path - - @property - def metadata(self) -> GroupMetadata: - return self._async_group.metadata - - @property - def path(self) -> str: - """Storage path.""" - return self._async_group.path - - @property - def name(self) -> str: - """Group name following h5py convention.""" - return self._async_group.name - - @property - def basename(self) -> str: - """Final component of name.""" - return self._async_group.basename - - @property - def attrs(self) -> Attributes: - return Attributes(self) - - @property - def info(self) -> None: - raise NotImplementedError - - def update_attributes(self, new_attributes: dict[str, Any]) -> Group: - self._sync(self._async_group.update_attributes(new_attributes)) - return self - - @property - def nmembers(self) -> int: - return self._sync(self._async_group.nmembers()) - - @property - def members(self) -> tuple[tuple[str, Array | Group], ...]: - """ - Return the sub-arrays and sub-groups of this group as a tuple of (name, array | group) - pairs - """ - _members = self._sync_iter(self._async_group.members()) - - result = tuple(map(lambda kv: (kv[0], _parse_async_node(kv[1])), _members)) - return result - - def __contains__(self, member: str) -> bool: - return self._sync(self._async_group.contains(member)) - - def group_keys(self) -> tuple[str, ...]: - return tuple(self._sync_iter(self._async_group.group_keys())) - - def groups(self) -> tuple[Group, ...]: - # TODO: in v2 this was a generator that return key: Group - return tuple(Group(obj) for obj in self._sync_iter(self._async_group.groups())) - - def array_keys(self) -> tuple[str, ...]: - return tuple(self._sync_iter(self._async_group.array_keys())) - - def arrays(self) -> tuple[Array, ...]: - return tuple(Array(obj) for obj in self._sync_iter(self._async_group.arrays())) - - def tree(self, expand: bool = False, level: int | None = None) -> Any: - return self._sync(self._async_group.tree(expand=expand, level=level)) - - def create_group(self, name: str, **kwargs: Any) -> Group: - return Group(self._sync(self._async_group.create_group(name, **kwargs))) - - def create_array( - self, - name: str, - *, - shape: ChunkCoords, - dtype: npt.DTypeLike = "float64", - fill_value: Any | None = None, - attributes: dict[str, JSON] | None = None, - # v3 only - chunk_shape: ChunkCoords | None = None, - chunk_key_encoding: ( - ChunkKeyEncoding - | tuple[Literal["default"], Literal[".", "/"]] - | tuple[Literal["v2"], Literal[".", "/"]] - | None - ) = None, - codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: Iterable[str] | None = None, - # v2 only - chunks: ChunkCoords | None = None, - dimension_separator: Literal[".", "/"] | None = None, - order: Literal["C", "F"] | None = None, - filters: list[dict[str, JSON]] | None = None, - compressor: dict[str, JSON] | None = None, - # runtime - exists_ok: bool = False, - data: npt.ArrayLike | None = None, - ) -> Array: - """ - Create a zarr array within this AsyncGroup. - This method lightly wraps AsyncArray.create. - - Parameters - ---------- - name: str - The name of the array. - shape: tuple[int, ...] - The shape of the array. - dtype: np.DtypeLike = float64 - The data type of the array. - chunk_shape: tuple[int, ...] | None = None - The shape of the chunks of the array. V3 only. - chunk_key_encoding: ChunkKeyEncoding | tuple[Literal["default"], Literal[".", "/"]] | tuple[Literal["v2"], Literal[".", "/"]] | None = None - A specification of how the chunk keys are represented in storage. - codecs: Iterable[Codec | dict[str, JSON]] | None = None - An iterable of Codec or dict serializations thereof. The elements of this collection - specify the transformation from array values to stored bytes. - dimension_names: Iterable[str] | None = None - The names of the dimensions of the array. V3 only. - chunks: ChunkCoords | None = None - The shape of the chunks of the array. V2 only. - dimension_separator: Literal[".", "/"] | None = None - The delimiter used for the chunk keys. - order: Literal["C", "F"] | None = None - The memory order of the array. - filters: list[dict[str, JSON]] | None = None - Filters for the array. - compressor: dict[str, JSON] | None = None - The compressor for the array. - exists_ok: bool = False - If True, a pre-existing array or group at the path of this array will - be overwritten. If False, the presence of a pre-existing array or group is - an error. - data: npt.ArrayLike | None = None - Array data to initialize the array with. - - Returns - ------- - Array - - """ - return Array( - self._sync( - self._async_group.create_array( - path=name, - shape=shape, - dtype=dtype, - fill_value=fill_value, - attributes=attributes, - chunk_shape=chunk_shape, - chunk_key_encoding=chunk_key_encoding, - codecs=codecs, - dimension_names=dimension_names, - chunks=chunks, - dimension_separator=dimension_separator, - order=order, - filters=filters, - compressor=compressor, - exists_ok=exists_ok, - data=data, - ) - ) - ) - - def empty(self, **kwargs: Any) -> Array: - return Array(self._sync(self._async_group.empty(**kwargs))) - - def zeros(self, **kwargs: Any) -> Array: - return Array(self._sync(self._async_group.zeros(**kwargs))) - - def ones(self, **kwargs: Any) -> Array: - return Array(self._sync(self._async_group.ones(**kwargs))) - - def full(self, **kwargs: Any) -> Array: - return Array(self._sync(self._async_group.full(**kwargs))) - - def empty_like(self, prototype: AsyncArray, **kwargs: Any) -> Array: - return Array(self._sync(self._async_group.empty_like(prototype, **kwargs))) - - def zeros_like(self, prototype: AsyncArray, **kwargs: Any) -> Array: - return Array(self._sync(self._async_group.zeros_like(prototype, **kwargs))) - - def ones_like(self, prototype: AsyncArray, **kwargs: Any) -> Array: - return Array(self._sync(self._async_group.ones_like(prototype, **kwargs))) - - def full_like(self, prototype: AsyncArray, **kwargs: Any) -> Array: - return Array(self._sync(self._async_group.full_like(prototype, **kwargs))) - - def move(self, source: str, dest: str) -> None: - return self._sync(self._async_group.move(source, dest)) - - @deprecated("Use Group.create_array instead.") - def array( - self, - name: str, - *, - shape: ChunkCoords, - dtype: npt.DTypeLike = "float64", - fill_value: Any | None = None, - attributes: dict[str, JSON] | None = None, - # v3 only - chunk_shape: ChunkCoords | None = None, - chunk_key_encoding: ( - ChunkKeyEncoding - | tuple[Literal["default"], Literal[".", "/"]] - | tuple[Literal["v2"], Literal[".", "/"]] - | None - ) = None, - codecs: Iterable[Codec | dict[str, JSON]] | None = None, - dimension_names: Iterable[str] | None = None, - # v2 only - chunks: ChunkCoords | None = None, - dimension_separator: Literal[".", "/"] | None = None, - order: Literal["C", "F"] | None = None, - filters: list[dict[str, JSON]] | None = None, - compressor: dict[str, JSON] | None = None, - # runtime - exists_ok: bool = False, - data: npt.ArrayLike | None = None, - ) -> Array: - """ - Create a zarr array within this AsyncGroup. - This method lightly wraps `AsyncArray.create`. - - Parameters - ---------- - name: str - The name of the array. - shape: tuple[int, ...] - The shape of the array. - dtype: np.DtypeLike = float64 - The data type of the array. - chunk_shape: tuple[int, ...] | None = None - The shape of the chunks of the array. V3 only. - chunk_key_encoding: ChunkKeyEncoding | tuple[Literal["default"], Literal[".", "/"]] | tuple[Literal["v2"], Literal[".", "/"]] | None = None - A specification of how the chunk keys are represented in storage. - codecs: Iterable[Codec | dict[str, JSON]] | None = None - An iterable of Codec or dict serializations thereof. The elements of - this collection specify the transformation from array values to stored bytes. - dimension_names: Iterable[str] | None = None - The names of the dimensions of the array. V3 only. - chunks: ChunkCoords | None = None - The shape of the chunks of the array. V2 only. - dimension_separator: Literal[".", "/"] | None = None - The delimiter used for the chunk keys. - order: Literal["C", "F"] | None = None - The memory order of the array. - filters: list[dict[str, JSON]] | None = None - Filters for the array. - compressor: dict[str, JSON] | None = None - The compressor for the array. - exists_ok: bool = False - If True, a pre-existing array or group at the path of this array will - be overwritten. If False, the presence of a pre-existing array or group is - an error. - data: npt.ArrayLike | None = None - Array data to initialize the array with. - - Returns - ------- - - Array - - """ - return Array( - self._sync( - self._async_group.create_array( - path=name, - shape=shape, - dtype=dtype, - fill_value=fill_value, - attributes=attributes, - chunk_shape=chunk_shape, - chunk_key_encoding=chunk_key_encoding, - codecs=codecs, - dimension_names=dimension_names, - chunks=chunks, - dimension_separator=dimension_separator, - order=order, - filters=filters, - compressor=compressor, - exists_ok=exists_ok, - data=data, - ) - ) - ) diff --git a/src/zarr/indexing.py b/src/zarr/indexing.py deleted file mode 100644 index 6987f69c11..0000000000 --- a/src/zarr/indexing.py +++ /dev/null @@ -1,1289 +0,0 @@ -from __future__ import annotations - -import itertools -import math -import numbers -import operator -from collections.abc import Iterator, Sequence -from dataclasses import dataclass -from enum import Enum -from functools import reduce -from types import EllipsisType -from typing import ( - TYPE_CHECKING, - Any, - NamedTuple, - Protocol, - TypeGuard, - TypeVar, - cast, - runtime_checkable, -) - -import numpy as np -import numpy.typing as npt - -from zarr.buffer import NDArrayLike -from zarr.common import ChunkCoords, product - -if TYPE_CHECKING: - from zarr.array import Array - from zarr.chunk_grids import ChunkGrid - -IntSequence = list[int] | npt.NDArray[np.intp] -ArrayOfIntOrBool = npt.NDArray[np.intp] | npt.NDArray[np.bool_] -BasicSelector = int | slice | EllipsisType -Selector = BasicSelector | ArrayOfIntOrBool - -BasicSelection = BasicSelector | tuple[BasicSelector, ...] # also used for BlockIndex -CoordinateSelection = IntSequence | tuple[IntSequence, ...] -MaskSelection = npt.NDArray[np.bool_] -OrthogonalSelection = Selector | tuple[Selector, ...] -Selection = BasicSelection | CoordinateSelection | MaskSelection | OrthogonalSelection -CoordinateSelectionNormalized = tuple[npt.NDArray[np.intp], ...] -SelectionNormalized = tuple[Selector, ...] | ArrayOfIntOrBool -SelectionWithFields = Selection | str | Sequence[str] -SelectorTuple = tuple[Selector, ...] | npt.NDArray[np.intp] | slice -Fields = str | list[str] | tuple[str, ...] - - -class ArrayIndexError(IndexError): - pass - - -class BoundsCheckError(IndexError): - _msg = "" - - def __init__(self, dim_len: int): - self._msg = f"index out of bounds for dimension with length {dim_len}" - - -class NegativeStepError(IndexError): - _msg = "only slices with step >= 1 are supported" - - -class VindexInvalidSelectionError(IndexError): - _msg = ( - "unsupported selection type for vectorized indexing; only " - "coordinate selection (tuple of integer arrays) and mask selection " - "(single Boolean array) are supported; got {0!r}" - ) - - -def err_too_many_indices(selection: Any, shape: ChunkCoords) -> None: - raise IndexError(f"too many indices for array; expected {len(shape)}, got {len(selection)}") - - -@runtime_checkable -class Indexer(Protocol): - shape: ChunkCoords - drop_axes: ChunkCoords - - def __iter__(self) -> Iterator[ChunkProjection]: ... - - -def ceildiv(a: float, b: float) -> int: - return math.ceil(a / b) - - -def is_integer(x: Any) -> TypeGuard[int]: - """True if x is an integer (both pure Python or NumPy).""" - return isinstance(x, numbers.Integral) and not is_bool(x) - - -def is_bool(x: Any) -> TypeGuard[bool | np.bool_]: - """True if x is a boolean (both pure Python or NumPy).""" - return type(x) in [bool, np.bool_] - - -def is_integer_list(x: Any) -> TypeGuard[list[int]]: - """True if x is a list of integers.""" - return isinstance(x, list) and len(x) > 0 and all(is_integer(i) for i in x) - - -def is_bool_list(x: Any) -> TypeGuard[list[bool | np.bool_]]: - """True if x is a list of boolean.""" - return isinstance(x, list) and len(x) > 0 and all(is_bool(i) for i in x) - - -def is_integer_array(x: Any, ndim: int | None = None) -> TypeGuard[npt.NDArray[np.intp]]: - t = not np.isscalar(x) and hasattr(x, "shape") and hasattr(x, "dtype") and x.dtype.kind in "ui" - if ndim is not None: - t = t and hasattr(x, "shape") and len(x.shape) == ndim - return t - - -def is_bool_array(x: Any, ndim: int | None = None) -> TypeGuard[npt.NDArray[np.bool_]]: - t = hasattr(x, "shape") and hasattr(x, "dtype") and x.dtype == bool - if ndim is not None: - t = t and hasattr(x, "shape") and len(x.shape) == ndim - return t - - -def is_int_or_bool_iterable(x: Any) -> bool: - return is_integer_list(x) or is_integer_array(x) or is_bool_array(x) or is_bool_list(x) - - -def is_scalar(value: Any, dtype: np.dtype[Any]) -> bool: - if np.isscalar(value): - return True - if hasattr(value, "shape") and value.shape == (): - return True - if isinstance(value, tuple) and dtype.names and len(value) == len(dtype.names): - return True - return False - - -def is_pure_fancy_indexing(selection: Any, ndim: int) -> bool: - """Check whether a selection contains only scalars or integer/bool array-likes. - - Parameters - ---------- - selection : tuple, slice, or scalar - A valid selection value for indexing into arrays. - - Returns - ------- - is_pure : bool - True if the selection is a pure fancy indexing expression (ie not mixed - with boolean or slices). - """ - if is_bool_array(selection): - # is mask selection - return True - - if ndim == 1: - if is_integer_list(selection) or is_integer_array(selection) or is_bool_list(selection): - return True - - # if not, we go through the normal path below, because a 1-tuple - # of integers is also allowed. - no_slicing = ( - isinstance(selection, tuple) - and len(selection) == ndim - and not (any(isinstance(elem, slice) or elem is Ellipsis for elem in selection)) - ) - return ( - no_slicing - and all( - is_integer(elem) or is_integer_list(elem) or is_integer_array(elem) - for elem in selection - ) - and any(is_integer_list(elem) or is_integer_array(elem) for elem in selection) - ) - - -def is_pure_orthogonal_indexing(selection: Selection, ndim: int) -> TypeGuard[OrthogonalSelection]: - if not ndim: - return False - - selection_normalized = (selection,) if not isinstance(selection, tuple) else selection - - # Case 1: Selection contains of iterable of integers or boolean - if len(selection_normalized) == ndim and all( - is_int_or_bool_iterable(s) for s in selection_normalized - ): - return True - - # Case 2: selection contains either zero or one integer iterables. - # All other selection elements are slices or integers - return ( - len(selection_normalized) <= ndim - and sum(is_int_or_bool_iterable(s) for s in selection_normalized) <= 1 - and all( - is_int_or_bool_iterable(s) or isinstance(s, int | slice) for s in selection_normalized - ) - ) - - -def get_chunk_shape(chunk_grid: ChunkGrid) -> ChunkCoords: - from zarr.chunk_grids import RegularChunkGrid - - assert isinstance( - chunk_grid, RegularChunkGrid - ), "Only regular chunk grid is supported, currently." - return chunk_grid.chunk_shape - - -def normalize_integer_selection(dim_sel: int, dim_len: int) -> int: - # normalize type to int - dim_sel = int(dim_sel) - - # handle wraparound - if dim_sel < 0: - dim_sel = dim_len + dim_sel - - # handle out of bounds - if dim_sel >= dim_len or dim_sel < 0: - raise BoundsCheckError(dim_len) - - return dim_sel - - -class ChunkDimProjection(NamedTuple): - """A mapping from chunk to output array for a single dimension. - - Parameters - ---------- - dim_chunk_ix - Index of chunk. - dim_chunk_sel - Selection of items from chunk array. - dim_out_sel - Selection of items in target (output) array. - - """ - - dim_chunk_ix: int - dim_chunk_sel: Selector - dim_out_sel: Selector | None - - -@dataclass(frozen=True) -class IntDimIndexer: - dim_sel: int - dim_len: int - dim_chunk_len: int - nitems: int = 1 - - def __init__(self, dim_sel: int, dim_len: int, dim_chunk_len: int): - object.__setattr__(self, "dim_sel", normalize_integer_selection(dim_sel, dim_len)) - object.__setattr__(self, "dim_len", dim_len) - object.__setattr__(self, "dim_chunk_len", dim_chunk_len) - - def __iter__(self) -> Iterator[ChunkDimProjection]: - dim_chunk_ix = self.dim_sel // self.dim_chunk_len - dim_offset = dim_chunk_ix * self.dim_chunk_len - dim_chunk_sel = self.dim_sel - dim_offset - dim_out_sel = None - yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel) - - -@dataclass(frozen=True) -class SliceDimIndexer: - dim_len: int - dim_chunk_len: int - nitems: int - nchunks: int - - start: int - stop: int - step: int - - def __init__(self, dim_sel: slice, dim_len: int, dim_chunk_len: int): - # normalize - start, stop, step = dim_sel.indices(dim_len) - if step < 1: - raise NegativeStepError - - object.__setattr__(self, "start", start) - object.__setattr__(self, "stop", stop) - object.__setattr__(self, "step", step) - - object.__setattr__(self, "dim_len", dim_len) - object.__setattr__(self, "dim_chunk_len", dim_chunk_len) - object.__setattr__(self, "nitems", max(0, ceildiv((stop - start), step))) - object.__setattr__(self, "nchunks", ceildiv(dim_len, dim_chunk_len)) - - def __iter__(self) -> Iterator[ChunkDimProjection]: - # figure out the range of chunks we need to visit - dim_chunk_ix_from = self.start // self.dim_chunk_len - dim_chunk_ix_to = ceildiv(self.stop, self.dim_chunk_len) - - # iterate over chunks in range - for dim_chunk_ix in range(dim_chunk_ix_from, dim_chunk_ix_to): - # compute offsets for chunk within overall array - dim_offset = dim_chunk_ix * self.dim_chunk_len - dim_limit = min(self.dim_len, (dim_chunk_ix + 1) * self.dim_chunk_len) - - # determine chunk length, accounting for trailing chunk - dim_chunk_len = dim_limit - dim_offset - - if self.start < dim_offset: - # selection starts before current chunk - dim_chunk_sel_start = 0 - remainder = (dim_offset - self.start) % self.step - if remainder: - dim_chunk_sel_start += self.step - remainder - # compute number of previous items, provides offset into output array - dim_out_offset = ceildiv((dim_offset - self.start), self.step) - - else: - # selection starts within current chunk - dim_chunk_sel_start = self.start - dim_offset - dim_out_offset = 0 - - if self.stop > dim_limit: - # selection ends after current chunk - dim_chunk_sel_stop = dim_chunk_len - - else: - # selection ends within current chunk - dim_chunk_sel_stop = self.stop - dim_offset - - dim_chunk_sel = slice(dim_chunk_sel_start, dim_chunk_sel_stop, self.step) - dim_chunk_nitems = ceildiv((dim_chunk_sel_stop - dim_chunk_sel_start), self.step) - - # If there are no elements on the selection within this chunk, then skip - if dim_chunk_nitems == 0: - continue - - dim_out_sel = slice(dim_out_offset, dim_out_offset + dim_chunk_nitems) - - yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel) - - -def check_selection_length(selection: SelectionNormalized, shape: ChunkCoords) -> None: - if len(selection) > len(shape): - err_too_many_indices(selection, shape) - - -def replace_ellipsis(selection: Any, shape: ChunkCoords) -> SelectionNormalized: - selection = ensure_tuple(selection) - - # count number of ellipsis present - n_ellipsis = sum(1 for i in selection if i is Ellipsis) - - if n_ellipsis > 1: - # more than 1 is an error - raise IndexError("an index can only have a single ellipsis ('...')") - - elif n_ellipsis == 1: - # locate the ellipsis, count how many items to left and right - n_items_l = selection.index(Ellipsis) # items to left of ellipsis - n_items_r = len(selection) - (n_items_l + 1) # items to right of ellipsis - n_items = len(selection) - 1 # all non-ellipsis items - - if n_items >= len(shape): - # ellipsis does nothing, just remove it - selection = tuple(i for i in selection if i != Ellipsis) - - else: - # replace ellipsis with as many slices are needed for number of dims - new_item = selection[:n_items_l] + ((slice(None),) * (len(shape) - n_items)) - if n_items_r: - new_item += selection[-n_items_r:] - selection = new_item - - # fill out selection if not completely specified - if len(selection) < len(shape): - selection += (slice(None),) * (len(shape) - len(selection)) - - # check selection not too long - check_selection_length(selection, shape) - - return cast(SelectionNormalized, selection) - - -def replace_lists(selection: SelectionNormalized) -> SelectionNormalized: - return tuple( - np.asarray(dim_sel) if isinstance(dim_sel, list) else dim_sel for dim_sel in selection - ) - - -T = TypeVar("T") - - -def ensure_tuple(v: Any) -> SelectionNormalized: - if not isinstance(v, tuple): - v = (v,) - return cast(SelectionNormalized, v) - - -class ChunkProjection(NamedTuple): - """A mapping of items from chunk to output array. Can be used to extract items from the - chunk array for loading into an output array. Can also be used to extract items from a - value array for setting/updating in a chunk array. - - Parameters - ---------- - chunk_coords - Indices of chunk. - chunk_selection - Selection of items from chunk array. - out_selection - Selection of items in target (output) array. - - """ - - chunk_coords: ChunkCoords - chunk_selection: tuple[Selector, ...] | npt.NDArray[np.intp] - out_selection: tuple[Selector, ...] | npt.NDArray[np.intp] | slice - - -def is_slice(s: Any) -> TypeGuard[slice]: - return isinstance(s, slice) - - -def is_contiguous_slice(s: Any) -> TypeGuard[slice]: - return is_slice(s) and (s.step is None or s.step == 1) - - -def is_positive_slice(s: Any) -> TypeGuard[slice]: - return is_slice(s) and (s.step is None or s.step >= 1) - - -def is_contiguous_selection(selection: Any) -> TypeGuard[slice]: - selection = ensure_tuple(selection) - return all((is_integer_array(s) or is_contiguous_slice(s) or s == Ellipsis) for s in selection) - - -def is_basic_selection(selection: Any) -> TypeGuard[BasicSelection]: - selection = ensure_tuple(selection) - return all(is_integer(s) or is_positive_slice(s) for s in selection) - - -@dataclass(frozen=True) -class BasicIndexer(Indexer): - dim_indexers: list[IntDimIndexer | SliceDimIndexer] - shape: ChunkCoords - drop_axes: ChunkCoords - - def __init__( - self, - selection: BasicSelection, - shape: ChunkCoords, - chunk_grid: ChunkGrid, - ): - chunk_shape = get_chunk_shape(chunk_grid) - # handle ellipsis - selection_normalized = replace_ellipsis(selection, shape) - - # setup per-dimension indexers - dim_indexers: list[IntDimIndexer | SliceDimIndexer] = [] - for dim_sel, dim_len, dim_chunk_len in zip( - selection_normalized, shape, chunk_shape, strict=True - ): - dim_indexer: IntDimIndexer | SliceDimIndexer - if is_integer(dim_sel): - dim_indexer = IntDimIndexer(dim_sel, dim_len, dim_chunk_len) - - elif is_slice(dim_sel): - dim_indexer = SliceDimIndexer(dim_sel, dim_len, dim_chunk_len) - - else: - raise IndexError( - "unsupported selection item for basic indexing; " - f"expected integer or slice, got {type(dim_sel)!r}" - ) - - dim_indexers.append(dim_indexer) - - object.__setattr__(self, "dim_indexers", dim_indexers) - object.__setattr__( - self, - "shape", - tuple(s.nitems for s in self.dim_indexers if not isinstance(s, IntDimIndexer)), - ) - object.__setattr__(self, "drop_axes", ()) - - def __iter__(self) -> Iterator[ChunkProjection]: - for dim_projections in itertools.product(*self.dim_indexers): - chunk_coords = tuple(p.dim_chunk_ix for p in dim_projections) - chunk_selection = tuple(p.dim_chunk_sel for p in dim_projections) - out_selection = tuple( - p.dim_out_sel for p in dim_projections if p.dim_out_sel is not None - ) - - yield ChunkProjection(chunk_coords, chunk_selection, out_selection) - - -@dataclass(frozen=True) -class BoolArrayDimIndexer: - dim_sel: npt.NDArray[np.bool_] - dim_len: int - dim_chunk_len: int - nchunks: int - - chunk_nitems: npt.NDArray[Any] - chunk_nitems_cumsum: npt.NDArray[Any] - nitems: int - dim_chunk_ixs: npt.NDArray[np.intp] - - def __init__(self, dim_sel: npt.NDArray[np.bool_], dim_len: int, dim_chunk_len: int): - # check number of dimensions - if not is_bool_array(dim_sel, 1): - raise IndexError("Boolean arrays in an orthogonal selection must be 1-dimensional only") - - # check shape - if dim_sel.shape[0] != dim_len: - raise IndexError( - f"Boolean array has the wrong length for dimension; expected {dim_len}, got {dim_sel.shape[0]}" - ) - - # precompute number of selected items for each chunk - nchunks = ceildiv(dim_len, dim_chunk_len) - chunk_nitems = np.zeros(nchunks, dtype="i8") - for dim_chunk_ix in range(nchunks): - dim_offset = dim_chunk_ix * dim_chunk_len - chunk_nitems[dim_chunk_ix] = np.count_nonzero( - dim_sel[dim_offset : dim_offset + dim_chunk_len] - ) - chunk_nitems_cumsum = np.cumsum(chunk_nitems) - nitems = chunk_nitems_cumsum[-1] - dim_chunk_ixs = np.nonzero(chunk_nitems)[0] - - # store attributes - object.__setattr__(self, "dim_sel", dim_sel) - object.__setattr__(self, "dim_len", dim_len) - object.__setattr__(self, "dim_chunk_len", dim_chunk_len) - object.__setattr__(self, "nchunks", nchunks) - object.__setattr__(self, "chunk_nitems", chunk_nitems) - object.__setattr__(self, "chunk_nitems_cumsum", chunk_nitems_cumsum) - object.__setattr__(self, "nitems", nitems) - object.__setattr__(self, "dim_chunk_ixs", dim_chunk_ixs) - - def __iter__(self) -> Iterator[ChunkDimProjection]: - # iterate over chunks with at least one item - for dim_chunk_ix in self.dim_chunk_ixs: - # find region in chunk - dim_offset = dim_chunk_ix * self.dim_chunk_len - dim_chunk_sel = self.dim_sel[dim_offset : dim_offset + self.dim_chunk_len] - - # pad out if final chunk - if dim_chunk_sel.shape[0] < self.dim_chunk_len: - tmp = np.zeros(self.dim_chunk_len, dtype=bool) - tmp[: dim_chunk_sel.shape[0]] = dim_chunk_sel - dim_chunk_sel = tmp - - # find region in output - if dim_chunk_ix == 0: - start = 0 - else: - start = self.chunk_nitems_cumsum[dim_chunk_ix - 1] - stop = self.chunk_nitems_cumsum[dim_chunk_ix] - dim_out_sel = slice(start, stop) - - yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel) - - -class Order(Enum): - UNKNOWN = 0 - INCREASING = 1 - DECREASING = 2 - UNORDERED = 3 - - @staticmethod - def check(a: npt.NDArray[Any]) -> Order: - diff = np.diff(a) - diff_positive = diff >= 0 - n_diff_positive = np.count_nonzero(diff_positive) - all_increasing = n_diff_positive == len(diff_positive) - any_increasing = n_diff_positive > 0 - if all_increasing: - order = Order.INCREASING - elif any_increasing: - order = Order.UNORDERED - else: - order = Order.DECREASING - return order - - -def wraparound_indices(x: npt.NDArray[Any], dim_len: int) -> None: - loc_neg = x < 0 - if np.any(loc_neg): - x[loc_neg] = x[loc_neg] + dim_len - - -def boundscheck_indices(x: npt.NDArray[Any], dim_len: int) -> None: - if np.any(x < 0) or np.any(x >= dim_len): - raise BoundsCheckError(dim_len) - - -@dataclass(frozen=True) -class IntArrayDimIndexer: - """Integer array selection against a single dimension.""" - - dim_len: int - dim_chunk_len: int - nchunks: int - nitems: int - order: Order - dim_sel: npt.NDArray[np.intp] - dim_out_sel: npt.NDArray[np.intp] - chunk_nitems: int - dim_chunk_ixs: npt.NDArray[np.intp] - chunk_nitems_cumsum: npt.NDArray[np.intp] - - def __init__( - self, - dim_sel: npt.NDArray[np.intp], - dim_len: int, - dim_chunk_len: int, - wraparound: bool = True, - boundscheck: bool = True, - order: Order = Order.UNKNOWN, - ): - # ensure 1d array - dim_sel = np.asanyarray(dim_sel) - if not is_integer_array(dim_sel, 1): - raise IndexError("integer arrays in an orthogonal selection must be 1-dimensional only") - - nitems = len(dim_sel) - nchunks = ceildiv(dim_len, dim_chunk_len) - - # handle wraparound - if wraparound: - wraparound_indices(dim_sel, dim_len) - - # handle out of bounds - if boundscheck: - boundscheck_indices(dim_sel, dim_len) - - # determine which chunk is needed for each selection item - # note: for dense integer selections, the division operation here is the - # bottleneck - dim_sel_chunk = dim_sel // dim_chunk_len - - # determine order of indices - if order == Order.UNKNOWN: - order = Order.check(dim_sel) - order = Order(order) - - if order == Order.INCREASING: - dim_sel = dim_sel - dim_out_sel = None - elif order == Order.DECREASING: - dim_sel = dim_sel[::-1] - # TODO should be possible to do this without creating an arange - dim_out_sel = np.arange(nitems - 1, -1, -1) - else: - # sort indices to group by chunk - dim_out_sel = np.argsort(dim_sel_chunk) - dim_sel = np.take(dim_sel, dim_out_sel) - - # precompute number of selected items for each chunk - chunk_nitems = np.bincount(dim_sel_chunk, minlength=nchunks) - - # find chunks that we need to visit - dim_chunk_ixs = np.nonzero(chunk_nitems)[0] - - # compute offsets into the output array - chunk_nitems_cumsum = np.cumsum(chunk_nitems) - - # store attributes - object.__setattr__(self, "dim_len", dim_len) - object.__setattr__(self, "dim_chunk_len", dim_chunk_len) - object.__setattr__(self, "nchunks", nchunks) - object.__setattr__(self, "nitems", nitems) - object.__setattr__(self, "order", order) - object.__setattr__(self, "dim_sel", dim_sel) - object.__setattr__(self, "dim_out_sel", dim_out_sel) - object.__setattr__(self, "chunk_nitems", chunk_nitems) - object.__setattr__(self, "dim_chunk_ixs", dim_chunk_ixs) - object.__setattr__(self, "chunk_nitems_cumsum", chunk_nitems_cumsum) - - def __iter__(self) -> Iterator[ChunkDimProjection]: - for dim_chunk_ix in self.dim_chunk_ixs: - dim_out_sel: slice | npt.NDArray[np.intp] - # find region in output - if dim_chunk_ix == 0: - start = 0 - else: - start = self.chunk_nitems_cumsum[dim_chunk_ix - 1] - stop = self.chunk_nitems_cumsum[dim_chunk_ix] - if self.order == Order.INCREASING: - dim_out_sel = slice(start, stop) - else: - dim_out_sel = self.dim_out_sel[start:stop] - - # find region in chunk - dim_offset = dim_chunk_ix * self.dim_chunk_len - dim_chunk_sel = self.dim_sel[start:stop] - dim_offset - - yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel) - - -def slice_to_range(s: slice, length: int) -> range: - return range(*s.indices(length)) - - -def ix_(selection: Any, shape: ChunkCoords) -> npt.NDArray[np.intp]: - """Convert an orthogonal selection to a numpy advanced (fancy) selection, like numpy.ix_ - but with support for slices and single ints.""" - - # normalisation - selection = replace_ellipsis(selection, shape) - - # replace slice and int as these are not supported by numpy.ix_ - selection = [ - slice_to_range(dim_sel, dim_len) - if isinstance(dim_sel, slice) - else [dim_sel] - if is_integer(dim_sel) - else dim_sel - for dim_sel, dim_len in zip(selection, shape, strict=True) - ] - - # now get numpy to convert to a coordinate selection - selection = np.ix_(*selection) - - return cast(npt.NDArray[np.intp], selection) - - -def oindex(a: npt.NDArray[Any], selection: Selection) -> npt.NDArray[Any]: - """Implementation of orthogonal indexing with slices and ints.""" - selection = replace_ellipsis(selection, a.shape) - drop_axes = tuple(i for i, s in enumerate(selection) if is_integer(s)) - selection = ix_(selection, a.shape) - result = a[selection] - if drop_axes: - result = result.squeeze(axis=drop_axes) - return result - - -def oindex_set(a: npt.NDArray[Any], selection: Selection, value: Any) -> None: - selection = replace_ellipsis(selection, a.shape) - drop_axes = tuple(i for i, s in enumerate(selection) if is_integer(s)) - selection = ix_(selection, a.shape) - if not np.isscalar(value) and drop_axes: - value = np.asanyarray(value) - value_selection: list[Selector | None] = [slice(None)] * len(a.shape) - for i in drop_axes: - value_selection[i] = np.newaxis - value = value[tuple(value_selection)] - a[selection] = value - - -@dataclass(frozen=True) -class OrthogonalIndexer(Indexer): - dim_indexers: list[IntDimIndexer | SliceDimIndexer | IntArrayDimIndexer | BoolArrayDimIndexer] - shape: ChunkCoords - chunk_shape: ChunkCoords - is_advanced: bool - drop_axes: tuple[int, ...] - - def __init__(self, selection: Selection, shape: ChunkCoords, chunk_grid: ChunkGrid): - chunk_shape = get_chunk_shape(chunk_grid) - - # handle ellipsis - selection = replace_ellipsis(selection, shape) - - # normalize list to array - selection = replace_lists(selection) - - # setup per-dimension indexers - dim_indexers: list[ - IntDimIndexer | SliceDimIndexer | IntArrayDimIndexer | BoolArrayDimIndexer - ] = [] - for dim_sel, dim_len, dim_chunk_len in zip(selection, shape, chunk_shape, strict=True): - dim_indexer: IntDimIndexer | SliceDimIndexer | IntArrayDimIndexer | BoolArrayDimIndexer - if is_integer(dim_sel): - dim_indexer = IntDimIndexer(dim_sel, dim_len, dim_chunk_len) - - elif isinstance(dim_sel, slice): - dim_indexer = SliceDimIndexer(dim_sel, dim_len, dim_chunk_len) - - elif is_integer_array(dim_sel): - dim_indexer = IntArrayDimIndexer(dim_sel, dim_len, dim_chunk_len) - - elif is_bool_array(dim_sel): - dim_indexer = BoolArrayDimIndexer(dim_sel, dim_len, dim_chunk_len) - - else: - raise IndexError( - "unsupported selection item for orthogonal indexing; " - "expected integer, slice, integer array or Boolean " - f"array, got {type(dim_sel)!r}" - ) - - dim_indexers.append(dim_indexer) - - dim_indexers = dim_indexers - shape = tuple(s.nitems for s in dim_indexers if not isinstance(s, IntDimIndexer)) - chunk_shape = chunk_shape - is_advanced = not is_basic_selection(selection) - if is_advanced: - drop_axes = tuple( - i - for i, dim_indexer in enumerate(dim_indexers) - if isinstance(dim_indexer, IntDimIndexer) - ) - else: - drop_axes = () - - object.__setattr__(self, "dim_indexers", dim_indexers) - object.__setattr__(self, "shape", shape) - object.__setattr__(self, "chunk_shape", chunk_shape) - object.__setattr__(self, "is_advanced", is_advanced) - object.__setattr__(self, "drop_axes", drop_axes) - - def __iter__(self) -> Iterator[ChunkProjection]: - for dim_projections in itertools.product(*self.dim_indexers): - chunk_coords = tuple(p.dim_chunk_ix for p in dim_projections) - chunk_selection: tuple[Selector, ...] | npt.NDArray[Any] = tuple( - p.dim_chunk_sel for p in dim_projections - ) - out_selection: tuple[Selector, ...] | npt.NDArray[Any] = tuple( - p.dim_out_sel for p in dim_projections if p.dim_out_sel is not None - ) - - # handle advanced indexing arrays orthogonally - if self.is_advanced: - # N.B., numpy doesn't support orthogonal indexing directly as yet, - # so need to work around via np.ix_. Also np.ix_ does not support a - # mixture of arrays and slices or integers, so need to convert slices - # and integers into ranges. - chunk_selection = ix_(chunk_selection, self.chunk_shape) - - # special case for non-monotonic indices - if not is_basic_selection(out_selection): - out_selection = ix_(out_selection, self.shape) - - yield ChunkProjection(chunk_coords, chunk_selection, out_selection) - - -@dataclass(frozen=True) -class OIndex: - array: Array - - def __getitem__(self, selection: OrthogonalSelection) -> NDArrayLike: - fields, new_selection = pop_fields(selection) - new_selection = ensure_tuple(new_selection) - new_selection = replace_lists(new_selection) - return self.array.get_orthogonal_selection( - cast(OrthogonalSelection, new_selection), fields=fields - ) - - def __setitem__(self, selection: OrthogonalSelection, value: npt.ArrayLike) -> None: - fields, new_selection = pop_fields(selection) - new_selection = ensure_tuple(new_selection) - new_selection = replace_lists(new_selection) - return self.array.set_orthogonal_selection( - cast(OrthogonalSelection, new_selection), value, fields=fields - ) - - -@dataclass(frozen=True) -class BlockIndexer(Indexer): - dim_indexers: list[SliceDimIndexer] - shape: ChunkCoords - drop_axes: ChunkCoords - - def __init__(self, selection: BasicSelection, shape: ChunkCoords, chunk_grid: ChunkGrid): - chunk_shape = get_chunk_shape(chunk_grid) - - # handle ellipsis - selection_normalized = replace_ellipsis(selection, shape) - - # normalize list to array - selection_normalized = replace_lists(selection_normalized) - - # setup per-dimension indexers - dim_indexers = [] - for dim_sel, dim_len, dim_chunk_size in zip( - selection_normalized, shape, chunk_shape, strict=True - ): - dim_numchunks = int(np.ceil(dim_len / dim_chunk_size)) - - if is_integer(dim_sel): - if dim_sel < 0: - dim_sel = dim_numchunks + dim_sel - - start = dim_sel * dim_chunk_size - stop = start + dim_chunk_size - slice_ = slice(start, stop) - - elif is_slice(dim_sel): - start = dim_sel.start if dim_sel.start is not None else 0 - stop = dim_sel.stop if dim_sel.stop is not None else dim_numchunks - - if dim_sel.step not in {1, None}: - raise IndexError( - "unsupported selection item for block indexing; " - f"expected integer or slice with step=1, got {type(dim_sel)!r}" - ) - - # Can't reuse wraparound_indices because it expects a numpy array - # We have integers here. - if start < 0: - start = dim_numchunks + start - if stop < 0: - stop = dim_numchunks + stop - - start = start * dim_chunk_size - stop = stop * dim_chunk_size - slice_ = slice(start, stop) - - else: - raise IndexError( - "unsupported selection item for block indexing; " - f"expected integer or slice, got {type(dim_sel)!r}" - ) - - dim_indexer = SliceDimIndexer(slice_, dim_len, dim_chunk_size) - dim_indexers.append(dim_indexer) - - if start >= dim_len or start < 0: - raise BoundsCheckError(dim_len) - - dim_indexers = dim_indexers - shape = tuple(s.nitems for s in dim_indexers) - - object.__setattr__(self, "dim_indexers", dim_indexers) - object.__setattr__(self, "shape", shape) - object.__setattr__(self, "drop_axes", ()) - - def __iter__(self) -> Iterator[ChunkProjection]: - for dim_projections in itertools.product(*self.dim_indexers): - chunk_coords = tuple(p.dim_chunk_ix for p in dim_projections) - chunk_selection = tuple(p.dim_chunk_sel for p in dim_projections) - out_selection = tuple( - p.dim_out_sel for p in dim_projections if p.dim_out_sel is not None - ) - - yield ChunkProjection(chunk_coords, chunk_selection, out_selection) - - -@dataclass(frozen=True) -class BlockIndex: - array: Array - - def __getitem__(self, selection: BasicSelection) -> NDArrayLike: - fields, new_selection = pop_fields(selection) - new_selection = ensure_tuple(new_selection) - new_selection = replace_lists(new_selection) - return self.array.get_block_selection(cast(BasicSelection, new_selection), fields=fields) - - def __setitem__(self, selection: BasicSelection, value: npt.ArrayLike) -> None: - fields, new_selection = pop_fields(selection) - new_selection = ensure_tuple(new_selection) - new_selection = replace_lists(new_selection) - return self.array.set_block_selection( - cast(BasicSelection, new_selection), value, fields=fields - ) - - -def is_coordinate_selection( - selection: SelectionNormalized, shape: ChunkCoords -) -> TypeGuard[CoordinateSelectionNormalized]: - return ( - isinstance(selection, tuple) - and len(selection) == len(shape) - and all(is_integer(dim_sel) or is_integer_array(dim_sel) for dim_sel in selection) - ) - - -def is_mask_selection(selection: Selection, shape: ChunkCoords) -> TypeGuard[MaskSelection]: - return ( - isinstance(selection, tuple) - and len(selection) == 1 - and is_bool_array(selection[0]) - and selection[0].shape == shape - ) - - -@dataclass(frozen=True) -class CoordinateIndexer(Indexer): - sel_shape: ChunkCoords - selection: CoordinateSelectionNormalized - sel_sort: npt.NDArray[np.intp] | None - chunk_nitems_cumsum: npt.NDArray[np.intp] - chunk_rixs: npt.NDArray[np.intp] - chunk_mixs: tuple[npt.NDArray[np.intp], ...] - shape: ChunkCoords - chunk_shape: ChunkCoords - drop_axes: ChunkCoords - - def __init__(self, selection: CoordinateSelection, shape: ChunkCoords, chunk_grid: ChunkGrid): - chunk_shape = get_chunk_shape(chunk_grid) - - cdata_shape: ChunkCoords - if shape == (): - cdata_shape = (1,) - else: - cdata_shape = tuple(math.ceil(s / c) for s, c in zip(shape, chunk_shape, strict=True)) - nchunks = reduce(operator.mul, cdata_shape, 1) - - # some initial normalization - selection_normalized = cast(CoordinateSelectionNormalized, ensure_tuple(selection)) - selection_normalized = tuple( - np.asarray([i]) if is_integer(i) else i for i in selection_normalized - ) - selection_normalized = cast( - CoordinateSelectionNormalized, replace_lists(selection_normalized) - ) - - # validation - if not is_coordinate_selection(selection_normalized, shape): - raise IndexError( - "invalid coordinate selection; expected one integer " - "(coordinate) array per dimension of the target array, " - f"got {selection!r}" - ) - - # handle wraparound, boundscheck - for dim_sel, dim_len in zip(selection_normalized, shape, strict=True): - # handle wraparound - wraparound_indices(dim_sel, dim_len) - - # handle out of bounds - boundscheck_indices(dim_sel, dim_len) - - # compute chunk index for each point in the selection - chunks_multi_index = tuple( - dim_sel // dim_chunk_len - for (dim_sel, dim_chunk_len) in zip(selection_normalized, chunk_shape, strict=True) - ) - - # broadcast selection - this will raise error if array dimensions don't match - selection_broadcast = tuple(np.broadcast_arrays(*selection_normalized)) - chunks_multi_index_broadcast = np.broadcast_arrays(*chunks_multi_index) - - # remember shape of selection, because we will flatten indices for processing - sel_shape = selection_broadcast[0].shape if selection_broadcast[0].shape else (1,) - - # flatten selection - selection_broadcast = tuple(dim_sel.reshape(-1) for dim_sel in selection_broadcast) - chunks_multi_index_broadcast = tuple( - dim_chunks.reshape(-1) for dim_chunks in chunks_multi_index_broadcast - ) - - # ravel chunk indices - chunks_raveled_indices = np.ravel_multi_index( - chunks_multi_index_broadcast, dims=cdata_shape - ) - - # group points by chunk - if np.any(np.diff(chunks_raveled_indices) < 0): - # optimisation, only sort if needed - sel_sort = np.argsort(chunks_raveled_indices) - selection_broadcast = tuple(dim_sel[sel_sort] for dim_sel in selection_broadcast) - else: - sel_sort = None - - shape = selection_broadcast[0].shape if selection_broadcast[0].shape else (1,) - - # precompute number of selected items for each chunk - chunk_nitems = np.bincount(chunks_raveled_indices, minlength=nchunks) - chunk_nitems_cumsum = np.cumsum(chunk_nitems) - # locate the chunks we need to process - chunk_rixs = np.nonzero(chunk_nitems)[0] - - # unravel chunk indices - chunk_mixs = np.unravel_index(chunk_rixs, cdata_shape) - - object.__setattr__(self, "sel_shape", sel_shape) - object.__setattr__(self, "selection", selection_broadcast) - object.__setattr__(self, "sel_sort", sel_sort) - object.__setattr__(self, "chunk_nitems_cumsum", chunk_nitems_cumsum) - object.__setattr__(self, "chunk_rixs", chunk_rixs) - object.__setattr__(self, "chunk_mixs", chunk_mixs) - object.__setattr__(self, "chunk_shape", chunk_shape) - object.__setattr__(self, "shape", shape) - object.__setattr__(self, "drop_axes", ()) - - def __iter__(self) -> Iterator[ChunkProjection]: - # iterate over chunks - for i, chunk_rix in enumerate(self.chunk_rixs): - chunk_coords = tuple(m[i] for m in self.chunk_mixs) - if chunk_rix == 0: - start = 0 - else: - start = self.chunk_nitems_cumsum[chunk_rix - 1] - stop = self.chunk_nitems_cumsum[chunk_rix] - out_selection: slice | npt.NDArray[np.intp] - if self.sel_sort is None: - out_selection = slice(start, stop) - else: - out_selection = self.sel_sort[start:stop] - - chunk_offsets = tuple( - dim_chunk_ix * dim_chunk_len - for dim_chunk_ix, dim_chunk_len in zip(chunk_coords, self.chunk_shape, strict=True) - ) - chunk_selection = tuple( - dim_sel[start:stop] - dim_chunk_offset - for (dim_sel, dim_chunk_offset) in zip(self.selection, chunk_offsets, strict=True) - ) - - yield ChunkProjection(chunk_coords, chunk_selection, out_selection) - - -@dataclass(frozen=True) -class MaskIndexer(CoordinateIndexer): - def __init__(self, selection: MaskSelection, shape: ChunkCoords, chunk_grid: ChunkGrid): - # some initial normalization - selection_normalized = cast(tuple[MaskSelection], ensure_tuple(selection)) - selection_normalized = cast(tuple[MaskSelection], replace_lists(selection_normalized)) - - # validation - if not is_mask_selection(selection_normalized, shape): - raise IndexError( - "invalid mask selection; expected one Boolean (mask)" - f"array with the same shape as the target array, got {selection_normalized!r}" - ) - - # convert to indices - selection_indices = np.nonzero(selection_normalized[0]) - - # delegate the rest to superclass - super().__init__(selection_indices, shape, chunk_grid) - - -@dataclass(frozen=True) -class VIndex: - array: Array - - def __getitem__(self, selection: CoordinateSelection | MaskSelection) -> NDArrayLike: - fields, new_selection = pop_fields(selection) - new_selection = ensure_tuple(new_selection) - new_selection = replace_lists(new_selection) - if is_coordinate_selection(new_selection, self.array.shape): - return self.array.get_coordinate_selection(new_selection, fields=fields) - elif is_mask_selection(new_selection, self.array.shape): - return self.array.get_mask_selection(new_selection, fields=fields) - else: - raise VindexInvalidSelectionError(new_selection) - - def __setitem__( - self, selection: CoordinateSelection | MaskSelection, value: npt.ArrayLike - ) -> None: - fields, new_selection = pop_fields(selection) - new_selection = ensure_tuple(new_selection) - new_selection = replace_lists(new_selection) - if is_coordinate_selection(new_selection, self.array.shape): - self.array.set_coordinate_selection(new_selection, value, fields=fields) - elif is_mask_selection(new_selection, self.array.shape): - self.array.set_mask_selection(new_selection, value, fields=fields) - else: - raise VindexInvalidSelectionError(new_selection) - - -def check_fields(fields: Fields | None, dtype: np.dtype[Any]) -> np.dtype[Any]: - # early out - if fields is None: - return dtype - # check type - if not isinstance(fields, str | list | tuple): - raise IndexError( - f"'fields' argument must be a string or list of strings; found {type(fields)!r}" - ) - if fields: - if dtype.names is None: - raise IndexError("invalid 'fields' argument, array does not have any fields") - try: - if isinstance(fields, str): - # single field selection - out_dtype = dtype[fields] - else: - # multiple field selection - out_dtype = np.dtype([(f, dtype[f]) for f in fields]) - except KeyError as e: - raise IndexError(f"invalid 'fields' argument, field not found: {e!r}") from e - else: - return out_dtype - else: - return dtype - - -def check_no_multi_fields(fields: Fields | None) -> Fields | None: - if isinstance(fields, list): - if len(fields) == 1: - return fields[0] - elif len(fields) > 1: - raise IndexError("multiple fields are not supported for this operation") - return fields - - -def pop_fields(selection: SelectionWithFields) -> tuple[Fields | None, Selection]: - if isinstance(selection, str): - # single field selection - return selection, () - elif not isinstance(selection, tuple): - # single selection item, no fields - # leave selection as-is - return None, cast(Selection, selection) - else: - # multiple items, split fields from selection items - fields: Fields = [f for f in selection if isinstance(f, str)] - fields = fields[0] if len(fields) == 1 else fields - selection_tuple = tuple(s for s in selection if not isinstance(s, str)) - selection = cast( - Selection, selection_tuple[0] if len(selection_tuple) == 1 else selection_tuple - ) - return fields, selection - - -def make_slice_selection(selection: Any) -> list[slice]: - ls: list[slice] = [] - for dim_selection in selection: - if is_integer(dim_selection): - ls.append(slice(int(dim_selection), int(dim_selection) + 1, 1)) - elif isinstance(dim_selection, np.ndarray): - if len(dim_selection) == 1: - ls.append(slice(int(dim_selection[0]), int(dim_selection[0]) + 1, 1)) - else: - raise ArrayIndexError - else: - ls.append(dim_selection) - return ls - - -def decode_morton(z: int, chunk_shape: ChunkCoords) -> ChunkCoords: - # Inspired by compressed morton code as implemented in Neuroglancer - # https://github.com/google/neuroglancer/blob/master/src/neuroglancer/datasource/precomputed/volume.md#compressed-morton-code - bits = tuple(math.ceil(math.log2(c)) for c in chunk_shape) - max_coords_bits = max(bits) - input_bit = 0 - input_value = z - out = [0] * len(chunk_shape) - - for coord_bit in range(max_coords_bits): - for dim in range(len(chunk_shape)): - if coord_bit < bits[dim]: - bit = (input_value >> input_bit) & 1 - out[dim] |= bit << coord_bit - input_bit += 1 - return tuple(out) - - -def morton_order_iter(chunk_shape: ChunkCoords) -> Iterator[ChunkCoords]: - for i in range(product(chunk_shape)): - yield decode_morton(i, chunk_shape) - - -def c_order_iter(chunks_per_shard: ChunkCoords) -> Iterator[ChunkCoords]: - return itertools.product(*(range(x) for x in chunks_per_shard)) - - -def is_total_slice(item: Selection, shape: ChunkCoords) -> bool: - """Determine whether `item` specifies a complete slice of array with the - given `shape`. Used to optimize __setitem__ operations on the Chunk - class.""" - - # N.B., assume shape is normalized - if item == slice(None): - return True - if isinstance(item, slice): - item = (item,) - if isinstance(item, tuple): - return all( - isinstance(dim_sel, slice) - and ( - (dim_sel == slice(None)) - or ((dim_sel.stop - dim_sel.start == dim_len) and (dim_sel.step in [1, None])) - ) - for dim_sel, dim_len in zip(item, shape, strict=False) - ) - else: - raise TypeError(f"expected slice or tuple of slices, found {item!r}") - - -def get_indexer( - selection: SelectionWithFields, shape: ChunkCoords, chunk_grid: ChunkGrid -) -> Indexer: - _, pure_selection = pop_fields(selection) - if is_pure_fancy_indexing(pure_selection, len(shape)): - new_selection = ensure_tuple(selection) - new_selection = replace_lists(new_selection) - if is_coordinate_selection(new_selection, shape): - return CoordinateIndexer(cast(CoordinateSelection, selection), shape, chunk_grid) - elif is_mask_selection(new_selection, shape): - return MaskIndexer(cast(MaskSelection, selection), shape, chunk_grid) - else: - raise VindexInvalidSelectionError(new_selection) - elif is_pure_orthogonal_indexing(pure_selection, len(shape)): - return OrthogonalIndexer(cast(OrthogonalSelection, selection), shape, chunk_grid) - else: - return BasicIndexer(cast(BasicSelection, selection), shape, chunk_grid) diff --git a/src/zarr/metadata.py b/src/zarr/metadata.py deleted file mode 100644 index e801a6f966..0000000000 --- a/src/zarr/metadata.py +++ /dev/null @@ -1,638 +0,0 @@ -from __future__ import annotations - -import json -from abc import ABC, abstractmethod -from collections.abc import Iterable, Sequence -from dataclasses import dataclass, field, replace -from enum import Enum -from typing import TYPE_CHECKING, Any, Literal, cast, overload - -import numpy as np -import numpy.typing as npt - -from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec, Codec, CodecPipeline -from zarr.abc.metadata import Metadata -from zarr.buffer import Buffer, BufferPrototype, default_buffer_prototype -from zarr.chunk_grids import ChunkGrid, RegularChunkGrid -from zarr.chunk_key_encodings import ChunkKeyEncoding, parse_separator -from zarr.config import config -from zarr.registry import get_codec_class, get_pipeline_class - -if TYPE_CHECKING: - from typing_extensions import Self - -import numcodecs.abc - -from zarr.array_spec import ArraySpec -from zarr.common import ( - JSON, - ZARR_JSON, - ZARRAY_JSON, - ZATTRS_JSON, - ChunkCoords, - ZarrFormat, - parse_dtype, - parse_named_configuration, - parse_shapelike, -) -from zarr.config import parse_indexing_order - -# For type checking -_bool = bool - -__all__ = ["ArrayMetadata"] - - -class DataType(Enum): - bool = "bool" - int8 = "int8" - int16 = "int16" - int32 = "int32" - int64 = "int64" - uint8 = "uint8" - uint16 = "uint16" - uint32 = "uint32" - uint64 = "uint64" - float32 = "float32" - float64 = "float64" - - @property - def byte_count(self) -> int: - data_type_byte_counts = { - DataType.bool: 1, - DataType.int8: 1, - DataType.int16: 2, - DataType.int32: 4, - DataType.int64: 8, - DataType.uint8: 1, - DataType.uint16: 2, - DataType.uint32: 4, - DataType.uint64: 8, - DataType.float32: 4, - DataType.float64: 8, - } - return data_type_byte_counts[self] - - @property - def has_endianness(self) -> _bool: - # This might change in the future, e.g. for a complex with 2 8-bit floats - return self.byte_count != 1 - - def to_numpy_shortname(self) -> str: - data_type_to_numpy = { - DataType.bool: "bool", - DataType.int8: "i1", - DataType.int16: "i2", - DataType.int32: "i4", - DataType.int64: "i8", - DataType.uint8: "u1", - DataType.uint16: "u2", - DataType.uint32: "u4", - DataType.uint64: "u8", - DataType.float32: "f4", - DataType.float64: "f8", - } - return data_type_to_numpy[self] - - @classmethod - def from_dtype(cls, dtype: np.dtype[Any]) -> DataType: - dtype_to_data_type = { - "|b1": "bool", - "bool": "bool", - "|i1": "int8", - " np.dtype[Any]: - pass - - @property - @abstractmethod - def ndim(self) -> int: - pass - - @abstractmethod - def get_chunk_spec( - self, _chunk_coords: ChunkCoords, order: Literal["C", "F"], prototype: BufferPrototype - ) -> ArraySpec: - pass - - @abstractmethod - def encode_chunk_key(self, chunk_coords: ChunkCoords) -> str: - pass - - @abstractmethod - def to_buffer_dict(self, prototype: BufferPrototype) -> dict[str, Buffer]: - pass - - @abstractmethod - def update_shape(self, shape: ChunkCoords) -> Self: - pass - - @abstractmethod - def update_attributes(self, attributes: dict[str, JSON]) -> Self: - pass - - -@dataclass(frozen=True, kw_only=True) -class ArrayV3Metadata(ArrayMetadata): - shape: ChunkCoords - data_type: np.dtype[Any] - chunk_grid: ChunkGrid - chunk_key_encoding: ChunkKeyEncoding - fill_value: Any - codecs: tuple[Codec, ...] - attributes: dict[str, Any] = field(default_factory=dict) - dimension_names: tuple[str, ...] | None = None - zarr_format: Literal[3] = field(default=3, init=False) - node_type: Literal["array"] = field(default="array", init=False) - - def __init__( - self, - *, - shape: Iterable[int], - data_type: npt.DTypeLike, - chunk_grid: dict[str, JSON] | ChunkGrid, - chunk_key_encoding: dict[str, JSON] | ChunkKeyEncoding, - fill_value: Any, - codecs: Iterable[Codec | dict[str, JSON]], - attributes: None | dict[str, JSON], - dimension_names: None | Iterable[str], - ) -> None: - """ - Because the class is a frozen dataclass, we set attributes using object.__setattr__ - """ - shape_parsed = parse_shapelike(shape) - data_type_parsed = parse_dtype(data_type) - chunk_grid_parsed = ChunkGrid.from_dict(chunk_grid) - chunk_key_encoding_parsed = ChunkKeyEncoding.from_dict(chunk_key_encoding) - dimension_names_parsed = parse_dimension_names(dimension_names) - fill_value_parsed = parse_fill_value_v3(fill_value, dtype=data_type_parsed) - attributes_parsed = parse_attributes(attributes) - codecs_parsed_partial = parse_codecs(codecs) - - array_spec = ArraySpec( - shape=shape_parsed, - dtype=data_type_parsed, - fill_value=fill_value_parsed, - order="C", # TODO: order is not needed here. - prototype=default_buffer_prototype(), # TODO: prototype is not needed here. - ) - codecs_parsed = [c.evolve_from_array_spec(array_spec) for c in codecs_parsed_partial] - - object.__setattr__(self, "shape", shape_parsed) - object.__setattr__(self, "data_type", data_type_parsed) - object.__setattr__(self, "chunk_grid", chunk_grid_parsed) - object.__setattr__(self, "chunk_key_encoding", chunk_key_encoding_parsed) - object.__setattr__(self, "codecs", codecs_parsed) - object.__setattr__(self, "dimension_names", dimension_names_parsed) - object.__setattr__(self, "fill_value", fill_value_parsed) - object.__setattr__(self, "attributes", attributes_parsed) - - self._validate_metadata() - - def _validate_metadata(self) -> None: - if isinstance(self.chunk_grid, RegularChunkGrid) and len(self.shape) != len( - self.chunk_grid.chunk_shape - ): - raise ValueError( - "`chunk_shape` and `shape` need to have the same number of dimensions." - ) - if self.dimension_names is not None and len(self.shape) != len(self.dimension_names): - raise ValueError( - "`dimension_names` and `shape` need to have the same number of dimensions." - ) - if self.fill_value is None: - raise ValueError("`fill_value` is required.") - for codec in self.codecs: - codec.validate(shape=self.shape, dtype=self.data_type, chunk_grid=self.chunk_grid) - - @property - def dtype(self) -> np.dtype[Any]: - return self.data_type - - @property - def ndim(self) -> int: - return len(self.shape) - - def get_chunk_spec( - self, _chunk_coords: ChunkCoords, order: Literal["C", "F"], prototype: BufferPrototype - ) -> ArraySpec: - assert isinstance( - self.chunk_grid, RegularChunkGrid - ), "Currently, only regular chunk grid is supported" - return ArraySpec( - shape=self.chunk_grid.chunk_shape, - dtype=self.dtype, - fill_value=self.fill_value, - order=order, - prototype=prototype, - ) - - def encode_chunk_key(self, chunk_coords: ChunkCoords) -> str: - return self.chunk_key_encoding.encode_chunk_key(chunk_coords) - - def to_buffer_dict(self, prototype: BufferPrototype) -> dict[str, Buffer]: - def _json_convert(o: Any) -> Any: - if isinstance(o, np.dtype): - return str(o) - if np.isscalar(o): - # convert numpy scalar to python type, and pass - # python types through - out = getattr(o, "item", lambda: o)() - if isinstance(out, complex): - # python complex types are not JSON serializable, so we use the - # serialization defined in the zarr v3 spec - return [out.real, out.imag] - return out - if isinstance(o, Enum): - return o.name - # this serializes numcodecs compressors - # todo: implement to_dict for codecs - elif isinstance(o, numcodecs.abc.Codec): - config: dict[str, Any] = o.get_config() - return config - raise TypeError - - json_indent = config.get("json_indent") - return { - ZARR_JSON: prototype.buffer.from_bytes( - json.dumps(self.to_dict(), default=_json_convert, indent=json_indent).encode() - ) - } - - @classmethod - def from_dict(cls, data: dict[str, JSON]) -> ArrayV3Metadata: - # make a copy because we are modifying the dict - _data = data.copy() - # TODO: Remove the type: ignores[] comments below and use a TypedDict to type `data` - # check that the zarr_format attribute is correct - _ = parse_zarr_format_v3(_data.pop("zarr_format")) # type: ignore[arg-type] - # check that the node_type attribute is correct - _ = parse_node_type_array(_data.pop("node_type")) # type: ignore[arg-type] - - # dimension_names key is optional, normalize missing to `None` - _data["dimension_names"] = _data.pop("dimension_names", None) - # attributes key is optional, normalize missing to `None` - _data["attributes"] = _data.pop("attributes", None) - return cls(**_data) # type: ignore[arg-type] - - def to_dict(self) -> dict[str, Any]: - out_dict = super().to_dict() - - if not isinstance(out_dict, dict): - raise TypeError(f"Expected dict. Got {type(out_dict)}.") - - # if `dimension_names` is `None`, we do not include it in - # the metadata document - if out_dict["dimension_names"] is None: - out_dict.pop("dimension_names") - return out_dict - - def update_shape(self, shape: ChunkCoords) -> Self: - return replace(self, shape=shape) - - def update_attributes(self, attributes: dict[str, JSON]) -> Self: - return replace(self, attributes=attributes) - - -@dataclass(frozen=True, kw_only=True) -class ArrayV2Metadata(ArrayMetadata): - shape: ChunkCoords - chunk_grid: RegularChunkGrid - data_type: np.dtype[Any] - fill_value: None | int | float = 0 - order: Literal["C", "F"] = "C" - filters: list[dict[str, JSON]] | None = None - dimension_separator: Literal[".", "/"] = "." - compressor: dict[str, JSON] | None = None - attributes: dict[str, JSON] = field(default_factory=dict) - zarr_format: Literal[2] = field(init=False, default=2) - - def __init__( - self, - *, - shape: ChunkCoords, - dtype: npt.DTypeLike, - chunks: ChunkCoords, - fill_value: Any, - order: Literal["C", "F"], - dimension_separator: Literal[".", "/"] = ".", - compressor: dict[str, JSON] | None = None, - filters: list[dict[str, JSON]] | None = None, - attributes: dict[str, JSON] | None = None, - ): - """ - Metadata for a Zarr version 2 array. - """ - shape_parsed = parse_shapelike(shape) - data_type_parsed = parse_dtype(dtype) - chunks_parsed = parse_shapelike(chunks) - compressor_parsed = parse_compressor(compressor) - order_parsed = parse_indexing_order(order) - dimension_separator_parsed = parse_separator(dimension_separator) - filters_parsed = parse_filters(filters) - fill_value_parsed = parse_fill_value_v2(fill_value, dtype=data_type_parsed) - attributes_parsed = parse_attributes(attributes) - - object.__setattr__(self, "shape", shape_parsed) - object.__setattr__(self, "data_type", data_type_parsed) - object.__setattr__(self, "chunk_grid", RegularChunkGrid(chunk_shape=chunks_parsed)) - object.__setattr__(self, "compressor", compressor_parsed) - object.__setattr__(self, "order", order_parsed) - object.__setattr__(self, "dimension_separator", dimension_separator_parsed) - object.__setattr__(self, "filters", filters_parsed) - object.__setattr__(self, "fill_value", fill_value_parsed) - object.__setattr__(self, "attributes", attributes_parsed) - - # ensure that the metadata document is consistent - _ = parse_v2_metadata(self) - - @property - def ndim(self) -> int: - return len(self.shape) - - @property - def dtype(self) -> np.dtype[Any]: - return self.data_type - - @property - def chunks(self) -> ChunkCoords: - return self.chunk_grid.chunk_shape - - def to_buffer_dict(self, prototype: BufferPrototype) -> dict[str, Buffer]: - def _json_convert( - o: Any, - ) -> Any: - if isinstance(o, np.dtype): - if o.fields is None: - return o.str - else: - return o.descr - if np.isscalar(o): - # convert numpy scalar to python type, and pass - # python types through - return getattr(o, "item", lambda: o)() - raise TypeError - - zarray_dict = self.to_dict() - assert isinstance(zarray_dict, dict) - zattrs_dict = zarray_dict.pop("attributes", {}) - assert isinstance(zattrs_dict, dict) - json_indent = config.get("json_indent") - return { - ZARRAY_JSON: prototype.buffer.from_bytes( - json.dumps(zarray_dict, default=_json_convert, indent=json_indent).encode() - ), - ZATTRS_JSON: prototype.buffer.from_bytes( - json.dumps(zattrs_dict, indent=json_indent).encode() - ), - } - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> ArrayV2Metadata: - # make a copy to protect the original from modification - _data = data.copy() - # check that the zarr_format attribute is correct - _ = parse_zarr_format_v2(_data.pop("zarr_format")) - return cls(**_data) - - def to_dict(self) -> JSON: - zarray_dict = super().to_dict() - - assert isinstance(zarray_dict, dict) - - _ = zarray_dict.pop("chunk_grid") - zarray_dict["chunks"] = self.chunk_grid.chunk_shape - - _ = zarray_dict.pop("data_type") - zarray_dict["dtype"] = self.data_type.str - - return zarray_dict - - def get_chunk_spec( - self, _chunk_coords: ChunkCoords, order: Literal["C", "F"], prototype: BufferPrototype - ) -> ArraySpec: - return ArraySpec( - shape=self.chunk_grid.chunk_shape, - dtype=self.dtype, - fill_value=self.fill_value, - order=order, - prototype=prototype, - ) - - def encode_chunk_key(self, chunk_coords: ChunkCoords) -> str: - chunk_identifier = self.dimension_separator.join(map(str, chunk_coords)) - return "0" if chunk_identifier == "" else chunk_identifier - - def update_shape(self, shape: ChunkCoords) -> Self: - return replace(self, shape=shape) - - def update_attributes(self, attributes: dict[str, JSON]) -> Self: - return replace(self, attributes=attributes) - - -def parse_dimension_names(data: None | Iterable[str | None]) -> tuple[str | None, ...] | None: - if data is None: - return data - elif all(isinstance(x, type(None) | str) for x in data): - return tuple(data) - else: - msg = f"Expected either None or a iterable of str, got {type(data)}" - raise TypeError(msg) - - -# todo: real validation -def parse_attributes(data: None | dict[str, JSON]) -> dict[str, JSON]: - if data is None: - return {} - - return data - - -# todo: move to its own module and drop _v3 suffix -# todo: consider folding all the literal parsing into a single function -# that takes 2 arguments -def parse_zarr_format_v3(data: Literal[3]) -> Literal[3]: - if data == 3: - return data - raise ValueError(f"Invalid value. Expected 3. Got {data}.") - - -# todo: move to its own module and drop _v2 suffix -def parse_zarr_format_v2(data: Literal[2]) -> Literal[2]: - if data == 2: - return data - raise ValueError(f"Invalid value. Expected 2. Got {data}.") - - -def parse_node_type_array(data: Literal["array"]) -> Literal["array"]: - if data == "array": - return data - raise ValueError(f"Invalid value. Expected 'array'. Got {data}.") - - -# todo: real validation -def parse_filters(data: list[dict[str, JSON]] | None) -> list[dict[str, JSON]] | None: - return data - - -# todo: real validation -def parse_compressor(data: dict[str, JSON] | None) -> dict[str, JSON] | None: - return data - - -def parse_v2_metadata(data: ArrayV2Metadata) -> ArrayV2Metadata: - if (l_chunks := len(data.chunks)) != (l_shape := len(data.shape)): - msg = ( - f"The `shape` and `chunks` attributes must have the same length. " - f"`chunks` has length {l_chunks}, but `shape` has length {l_shape}." - ) - raise ValueError(msg) - return data - - -def create_pipeline(data: Iterable[Codec | JSON]) -> CodecPipeline: - if not isinstance(data, Iterable): - raise TypeError(f"Expected iterable, got {type(data)}") - return get_pipeline_class().from_dict(data) - - -def parse_codecs(data: Iterable[Codec | dict[str, JSON]]) -> tuple[Codec, ...]: - out: tuple[Codec, ...] = () - - if not isinstance(data, Iterable): - raise TypeError(f"Expected iterable, got {type(data)}") - - for c in data: - if isinstance( - c, ArrayArrayCodec | ArrayBytesCodec | BytesBytesCodec - ): # Can't use Codec here because of mypy limitation - out += (c,) - else: - name_parsed, _ = parse_named_configuration(c, require_configuration=False) - out += (get_codec_class(name_parsed).from_dict(c),) - - return out - - -def parse_fill_value_v2(fill_value: Any, dtype: np.dtype[Any]) -> Any: - """ - Parse a potential fill value into a value that is compatible with the provided dtype. - - This is a light wrapper around zarr.v2.util.normalize_fill_value. - - Parameters - ---------- - fill_value: Any - A potential fill value. - dtype: np.dtype[Any] - A numpy dtype. - - Returns - An instance of `dtype`, or `None`, or any python object (in the case of an object dtype) - """ - from zarr.v2.util import normalize_fill_value - - return normalize_fill_value(fill_value=fill_value, dtype=dtype) - - -BOOL = np.bool_ -BOOL_DTYPE = np.dtypes.BoolDType - -INTEGER_DTYPE = ( - np.dtypes.Int8DType - | np.dtypes.Int16DType - | np.dtypes.Int32DType - | np.dtypes.Int64DType - | np.dtypes.UByteDType - | np.dtypes.UInt16DType - | np.dtypes.UInt32DType - | np.dtypes.UInt64DType -) - -INTEGER = np.int8 | np.int16 | np.int32 | np.int64 | np.uint8 | np.uint16 | np.uint32 | np.uint64 -FLOAT_DTYPE = np.dtypes.Float16DType | np.dtypes.Float32DType | np.dtypes.Float64DType -FLOAT = np.float16 | np.float32 | np.float64 -COMPLEX_DTYPE = np.dtypes.Complex64DType | np.dtypes.Complex128DType -COMPLEX = np.complex64 | np.complex128 -# todo: r* dtypes - - -@overload -def parse_fill_value_v3(fill_value: Any, dtype: BOOL_DTYPE) -> BOOL: ... - - -@overload -def parse_fill_value_v3(fill_value: Any, dtype: INTEGER_DTYPE) -> INTEGER: ... - - -@overload -def parse_fill_value_v3(fill_value: Any, dtype: FLOAT_DTYPE) -> FLOAT: ... - - -@overload -def parse_fill_value_v3(fill_value: Any, dtype: COMPLEX_DTYPE) -> COMPLEX: ... - - -def parse_fill_value_v3( - fill_value: Any, dtype: BOOL_DTYPE | INTEGER_DTYPE | FLOAT_DTYPE | COMPLEX_DTYPE -) -> BOOL | INTEGER | FLOAT | COMPLEX: - """ - Parse `fill_value`, a potential fill value, into an instance of `dtype`, a data type. - If `fill_value` is `None`, then this function will return the result of casting the value 0 - to the provided data type. Otherwise, `fill_value` will be cast to the provided data type. - - Note that some numpy dtypes use very permissive casting rules. For example, - `np.bool_({'not remotely a bool'})` returns `True`. Thus this function should not be used for - validating that the provided fill value is a valid instance of the data type. - - Parameters - ---------- - fill_value: Any - A potential fill value. - dtype: BOOL_DTYPE | INTEGER_DTYPE | FLOAT_DTYPE | COMPLEX_DTYPE - A numpy data type that models a data type defined in the Zarr V3 specification. - - Returns - ------- - A scalar instance of `dtype` - """ - if fill_value is None: - return dtype.type(0) - if isinstance(fill_value, Sequence) and not isinstance(fill_value, str): - if dtype in (np.complex64, np.complex128): - dtype = cast(COMPLEX_DTYPE, dtype) - if len(fill_value) == 2: - # complex datatypes serialize to JSON arrays with two elements - return dtype.type(complex(*fill_value)) - else: - msg = ( - f"Got an invalid fill value for complex data type {dtype}." - f"Expected a sequence with 2 elements, but {fill_value} has " - f"length {len(fill_value)}." - ) - raise ValueError(msg) - msg = f"Cannot parse non-string sequence {fill_value} as a scalar with type {dtype}." - raise TypeError(msg) - return dtype.type(fill_value) diff --git a/src/zarr/metadata/__init__.py b/src/zarr/metadata/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/zarr/metadata/migrate_v3.py b/src/zarr/metadata/migrate_v3.py new file mode 100644 index 0000000000..370af75a6d --- /dev/null +++ b/src/zarr/metadata/migrate_v3.py @@ -0,0 +1,295 @@ +import asyncio +import logging +from typing import cast + +import numcodecs.abc + +import zarr +from zarr import Group +from zarr.abc.codec import ArrayArrayCodec, BytesBytesCodec, Codec +from zarr.abc.store import Store +from zarr.codecs.blosc import BloscCodec, BloscShuffle +from zarr.codecs.bytes import BytesCodec +from zarr.codecs.gzip import GzipCodec +from zarr.codecs.transpose import TransposeCodec +from zarr.codecs.zstd import ZstdCodec +from zarr.core.buffer.core import default_buffer_prototype +from zarr.core.chunk_key_encodings import V2ChunkKeyEncoding +from zarr.core.common import ( + ZARR_JSON, + ZARRAY_JSON, + ZATTRS_JSON, + ZGROUP_JSON, + ZMETADATA_V2_JSON, + ZarrFormat, +) +from zarr.core.dtype.common import HasEndianness +from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType +from zarr.core.group import GroupMetadata +from zarr.core.metadata.v2 import ArrayV2Metadata +from zarr.core.metadata.v3 import ArrayV3Metadata, RegularChunkGridMetadata +from zarr.core.sync import sync +from zarr.registry import get_codec_class +from zarr.storage import StorePath +from zarr.types import AnyArray + +_logger = logging.getLogger(__name__) + + +def migrate_v2_to_v3( + *, + input_store: Store, + output_store: Store | None = None, + dry_run: bool = False, +) -> None: + """Migrate all v2 metadata in a Zarr store to v3. + + This will create a zarr.json file at each level of a Zarr hierarchy (for every group / array). + v2 files (.zarray, .zattrs etc.) will be left as-is. + + Parameters + ---------- + input_store : Store + Input Zarr to migrate. + output_store : Store, optional + Output location to write v3 metadata (no array data will be copied). If not provided, v3 metadata will be + written to input_store. + dry_run : bool, optional + Enable a 'dry run' - files that would be created are logged, but no files are created or changed. + """ + + zarr_v2 = zarr.open(store=input_store, mode="r+") + + if output_store is not None: + # w- access to not allow overwrite of existing data + output_path = sync(StorePath.open(output_store, path="", mode="w-")) + else: + output_path = zarr_v2.store_path + + migrate_to_v3(zarr_v2, output_path, dry_run=dry_run) + + +def migrate_to_v3(zarr_v2: AnyArray | Group, output_path: StorePath, dry_run: bool = False) -> None: + """Migrate all v2 metadata in a Zarr array/group to v3. + + Note - if a group is provided, then all arrays / groups within this group will also be converted. + A zarr.json file will be created for each level and written to output_path, with any v2 files + (.zarray, .zattrs etc.) left as-is. + + Parameters + ---------- + zarr_v2 : Array | Group + An array or group with zarr_format = 2 + output_path : StorePath + The store path to write generated v3 metadata to. + dry_run : bool, optional + Enable a 'dry run' - files that would be created are logged, but no files are created or changed. + """ + if not zarr_v2.metadata.zarr_format == 2: + raise TypeError("Only arrays / groups with zarr v2 metadata can be converted") + + if isinstance(zarr_v2.metadata, GroupMetadata): + _convert_group(zarr_v2, output_path, dry_run) + else: + _convert_array(zarr_v2, output_path, dry_run) + + +async def remove_metadata( + store: Store, + zarr_format: ZarrFormat, + force: bool = False, + dry_run: bool = False, +) -> None: + """Remove all v2 (.zarray, .zattrs, .zgroup, .zmetadata) or v3 (zarr.json) metadata files from the given Zarr. + + Note - this will remove metadata files at all levels of the hierarchy (every group and array). + + Parameters + ---------- + store : Store + Zarr to remove metadata from. + zarr_format : ZarrFormat + Which format's metadata to remove - 2 or 3. + force : bool, optional + When False, metadata can only be removed if a valid alternative exists e.g. deletion of v2 metadata will + only be allowed when v3 metadata is also present. When True, metadata can be removed when there is no + alternative. + dry_run : bool, optional + Enable a 'dry run' - files that would be deleted are logged, but no files are removed or changed. + """ + + if not store.supports_deletes: + raise ValueError("Store must support deletes to remove metadata") + store_path = await StorePath.open(store, path="", mode="r+") + + metadata_files_all = { + 2: [ZARRAY_JSON, ZATTRS_JSON, ZGROUP_JSON, ZMETADATA_V2_JSON], + 3: [ZARR_JSON], + } + + if zarr_format == 2: + alternative_metadata = 3 + else: + alternative_metadata = 2 + + awaitables = [] + async for file_path in store.list(): + parent_path, _, file_name = file_path.rpartition("/") + + if file_name not in metadata_files_all[zarr_format]: + continue + + if force or await _metadata_exists( + cast(ZarrFormat, alternative_metadata), store_path / parent_path + ): + _logger.info("Deleting metadata at %s", store_path / file_path) + if not dry_run: + awaitables.append((store_path / file_path).delete()) + else: + raise ValueError( + f"Cannot remove v{zarr_format} metadata at {store_path / file_path} - no v{alternative_metadata} " + "metadata exists. To delete anyway, use the 'force' option." + ) + + await asyncio.gather(*awaitables) + + +def _convert_group(zarr_v2: Group, output_path: StorePath, dry_run: bool) -> None: + if zarr_v2.metadata.consolidated_metadata is not None: + raise NotImplementedError("Migration of consolidated metadata isn't supported.") + + # process members of the group + for key in zarr_v2: + migrate_to_v3(zarr_v2[key], output_path=output_path / key, dry_run=dry_run) + + # write group's converted metadata + group_metadata_v3 = GroupMetadata( + attributes=zarr_v2.metadata.attributes, zarr_format=3, consolidated_metadata=None + ) + sync(_save_v3_metadata(group_metadata_v3, output_path, dry_run=dry_run)) + + +def _convert_array(zarr_v2: AnyArray, output_path: StorePath, dry_run: bool) -> None: + array_metadata_v3 = _convert_array_metadata(cast(ArrayV2Metadata, zarr_v2.metadata)) + sync(_save_v3_metadata(array_metadata_v3, output_path, dry_run=dry_run)) + + +async def _metadata_exists(zarr_format: ZarrFormat, store_path: StorePath) -> bool: + metadata_files_required = {2: [ZARRAY_JSON, ZGROUP_JSON], 3: [ZARR_JSON]} + + for metadata_file in metadata_files_required[zarr_format]: + if await (store_path / metadata_file).exists(): + return True + + return False + + +def _convert_array_metadata(metadata_v2: ArrayV2Metadata) -> ArrayV3Metadata: + chunk_key_encoding = V2ChunkKeyEncoding(separator=metadata_v2.dimension_separator) + + codecs: list[Codec] = [] + + # array-array codecs + if metadata_v2.order == "F": + # F is equivalent to order: n-1, ... 1, 0 + codecs.append(TransposeCodec(order=list(range(len(metadata_v2.shape) - 1, -1, -1)))) + + if metadata_v2.filters is not None: + codecs.extend(_convert_filters(metadata_v2.filters)) + + # array-bytes codecs + if not isinstance(metadata_v2.dtype, HasEndianness): + codecs.append(BytesCodec(endian=None)) + else: + codecs.append(BytesCodec(endian=metadata_v2.dtype.endianness)) + + # bytes-bytes codecs + if metadata_v2.compressor is not None: + bytes_bytes_codec = _convert_compressor(metadata_v2.compressor, metadata_v2.dtype) + codecs.append(bytes_bytes_codec) + + return ArrayV3Metadata( + shape=metadata_v2.shape, + data_type=metadata_v2.dtype, + chunk_grid=RegularChunkGridMetadata(chunk_shape=metadata_v2.chunks), + chunk_key_encoding=chunk_key_encoding, + fill_value=metadata_v2.fill_value, + codecs=codecs, + attributes=metadata_v2.attributes, + dimension_names=None, + storage_transformers=None, + ) + + +def _convert_filters(filters: tuple[numcodecs.abc.Codec, ...]) -> list[ArrayArrayCodec]: + filters_codecs = [_find_numcodecs_zarr3(filter) for filter in filters] + for codec in filters_codecs: + if not isinstance(codec, ArrayArrayCodec): + raise TypeError(f"Filter {type(codec)} is not an ArrayArrayCodec") + + return cast(list[ArrayArrayCodec], filters_codecs) + + +def _convert_compressor( + compressor: numcodecs.abc.Codec, dtype: ZDType[TBaseDType, TBaseScalar] +) -> BytesBytesCodec: + match compressor.codec_id: + case "blosc": + return BloscCodec( + typesize=dtype.to_native_dtype().itemsize, + cname=compressor.cname, + clevel=compressor.clevel, + shuffle=BloscShuffle.from_int(compressor.shuffle), + blocksize=compressor.blocksize, + ) + + case "zstd": + return ZstdCodec( + level=compressor.level, + checksum=compressor.checksum, + ) + + case "gzip": + return GzipCodec(level=compressor.level) + + case _: + # If possible, find matching zarr.codecs.numcodecs codec + compressor_codec = _find_numcodecs_zarr3(compressor) + + if not isinstance(compressor_codec, BytesBytesCodec): + raise TypeError(f"Compressor {type(compressor_codec)} is not a BytesBytesCodec") + + return compressor_codec + + +def _find_numcodecs_zarr3(numcodecs_codec: numcodecs.abc.Codec) -> Codec: + """Find matching zarr.codecs.numcodecs codec (if it exists)""" + + numcodec_name = f"numcodecs.{numcodecs_codec.codec_id}" + numcodec_dict = { + "name": numcodec_name, + "configuration": numcodecs_codec.get_config(), + } + + try: + codec_v3 = get_codec_class(numcodec_name) + except KeyError as exc: + raise ValueError( + f"Couldn't find corresponding zarr.codecs.numcodecs codec for {numcodecs_codec.codec_id}" + ) from exc + + return codec_v3.from_dict(numcodec_dict) + + +async def _save_v3_metadata( + metadata_v3: ArrayV3Metadata | GroupMetadata, output_path: StorePath, dry_run: bool = False +) -> None: + zarr_json_path = output_path / ZARR_JSON + if await zarr_json_path.exists(): + raise ValueError(f"{ZARR_JSON} already exists at {zarr_json_path}") + + _logger.info("Saving metadata to %s", zarr_json_path) + to_save = metadata_v3.to_buffer_dict(default_buffer_prototype()) + + if not dry_run: + await zarr_json_path.set_if_not_exists(to_save[ZARR_JSON]) diff --git a/src/zarr/registry.py b/src/zarr/registry.py index ac373f401d..c2c0eb2921 100644 --- a/src/zarr/registry.py +++ b/src/zarr/registry.py @@ -2,49 +2,79 @@ import warnings from collections import defaultdict -from typing import TYPE_CHECKING, Any, Generic, TypeVar - -if TYPE_CHECKING: - from zarr.abc.codec import Codec, CodecPipeline - from zarr.buffer import Buffer, NDBuffer - -from importlib.metadata import EntryPoint from importlib.metadata import entry_points as get_entry_points +from typing import TYPE_CHECKING, Any -from zarr.config import BadConfigError, config +from zarr.core.config import BadConfigError, config +from zarr.core.dtype import data_type_registry +from zarr.errors import ZarrUserWarning -T = TypeVar("T") - - -class Registry(Generic[T], dict[str, type[T]]): +if TYPE_CHECKING: + from importlib.metadata import EntryPoint + + from zarr.abc.codec import ( + ArrayArrayCodec, + ArrayBytesCodec, + BytesBytesCodec, + Codec, + CodecJSON_V2, + CodecPipeline, + ) + from zarr.abc.numcodec import Numcodec + from zarr.core.buffer import Buffer, NDBuffer + from zarr.core.chunk_key_encodings import ChunkKeyEncoding + from zarr.core.common import JSON + +__all__ = [ + "Registry", + "get_buffer_class", + "get_chunk_key_encoding_class", + "get_codec_class", + "get_ndbuffer_class", + "get_pipeline_class", + "register_buffer", + "register_chunk_key_encoding", + "register_codec", + "register_ndbuffer", + "register_pipeline", +] + + +class Registry[T](dict[str, type[T]]): def __init__(self) -> None: super().__init__() self.lazy_load_list: list[EntryPoint] = [] - def lazy_load(self) -> None: + def lazy_load(self, use_entrypoint_name: bool = False) -> None: for e in self.lazy_load_list: - self.register(e.load()) + self.register(e.load(), qualname=e.name if use_entrypoint_name else None) + self.lazy_load_list.clear() - def register(self, cls: type[T]) -> None: - self[fully_qualified_name(cls)] = cls + def register(self, cls: type[T], qualname: str | None = None) -> None: + if qualname is None: + qualname = fully_qualified_name(cls) + self[qualname] = cls -__codec_registries: dict[str, Registry[Codec]] = defaultdict(Registry) -__pipeline_registry: Registry[CodecPipeline] = Registry() -__buffer_registry: Registry[Buffer] = Registry() -__ndbuffer_registry: Registry[NDBuffer] = Registry() +_codec_registries: dict[str, Registry[Codec]] = defaultdict(Registry) +_pipeline_registry: Registry[CodecPipeline] = Registry() +_buffer_registry: Registry[Buffer] = Registry() +_ndbuffer_registry: Registry[NDBuffer] = Registry() +_chunk_key_encoding_registry: Registry[ChunkKeyEncoding] = Registry() """ -The registry module is responsible for managing implementations of codecs, pipelines, buffers and ndbuffers and -collecting them from entrypoints. -The implementation used is determined by the config +The registry module is responsible for managing implementations of codecs, +pipelines, buffers, ndbuffers, and chunk key encodings and collecting them from entrypoints. +The implementation used is determined by the config. + +The registry module is also responsible for managing dtypes. """ def _collect_entrypoints() -> list[Registry[Any]]: """ - Collects codecs, pipelines, buffers and ndbuffers from entrypoints. + Collects codecs, pipelines, dtypes, buffers and ndbuffers from entrypoints. Entry points can either be single items or groups of items. Allowed syntax for entry_points.txt is e.g. @@ -63,25 +93,37 @@ def _collect_entrypoints() -> list[Registry[Any]]: """ entry_points = get_entry_points() - __buffer_registry.lazy_load_list.extend(entry_points.select(group="zarr.buffer")) - __buffer_registry.lazy_load_list.extend(entry_points.select(group="zarr", name="buffer")) - __ndbuffer_registry.lazy_load_list.extend(entry_points.select(group="zarr.ndbuffer")) - __ndbuffer_registry.lazy_load_list.extend(entry_points.select(group="zarr", name="ndbuffer")) - __pipeline_registry.lazy_load_list.extend(entry_points.select(group="zarr.codec_pipeline")) - __pipeline_registry.lazy_load_list.extend( + _buffer_registry.lazy_load_list.extend(entry_points.select(group="zarr.buffer")) + _buffer_registry.lazy_load_list.extend(entry_points.select(group="zarr", name="buffer")) + _ndbuffer_registry.lazy_load_list.extend(entry_points.select(group="zarr.ndbuffer")) + _ndbuffer_registry.lazy_load_list.extend(entry_points.select(group="zarr", name="ndbuffer")) + + data_type_registry._lazy_load_list.extend(entry_points.select(group="zarr.data_type")) + data_type_registry._lazy_load_list.extend(entry_points.select(group="zarr", name="data_type")) + + _chunk_key_encoding_registry.lazy_load_list.extend( + entry_points.select(group="zarr.chunk_key_encoding") + ) + _chunk_key_encoding_registry.lazy_load_list.extend( + entry_points.select(group="zarr", name="chunk_key_encoding") + ) + + _pipeline_registry.lazy_load_list.extend(entry_points.select(group="zarr.codec_pipeline")) + _pipeline_registry.lazy_load_list.extend( entry_points.select(group="zarr", name="codec_pipeline") ) for e in entry_points.select(group="zarr.codecs"): - __codec_registries[e.name].lazy_load_list.append(e) + _codec_registries[e.name].lazy_load_list.append(e) for group in entry_points.groups: if group.startswith("zarr.codecs."): codec_name = group.split(".")[2] - __codec_registries[codec_name].lazy_load_list.extend(entry_points.select(group=group)) + _codec_registries[codec_name].lazy_load_list.extend(entry_points.select(group=group)) return [ - *__codec_registries.values(), - __pipeline_registry, - __buffer_registry, - __ndbuffer_registry, + *_codec_registries.values(), + _pipeline_registry, + _buffer_registry, + _ndbuffer_registry, + _chunk_key_encoding_registry, ] @@ -91,43 +133,50 @@ def _reload_config() -> None: def fully_qualified_name(cls: type) -> str: module = cls.__module__ - return module + "." + cls.__qualname__ + return f"{module}.{cls.__qualname__}" -def register_codec(key: str, codec_cls: type[Codec]) -> None: - if key not in __codec_registries.keys(): - __codec_registries[key] = Registry() - __codec_registries[key].register(codec_cls) +def register_codec(key: str, codec_cls: type[Codec], *, qualname: str | None = None) -> None: + if key not in _codec_registries: + _codec_registries[key] = Registry() + _codec_registries[key].register(codec_cls, qualname=qualname) def register_pipeline(pipe_cls: type[CodecPipeline]) -> None: - __pipeline_registry.register(pipe_cls) + _pipeline_registry.register(pipe_cls) + +def register_ndbuffer(cls: type[NDBuffer], qualname: str | None = None) -> None: + _ndbuffer_registry.register(cls, qualname) -def register_ndbuffer(cls: type[NDBuffer]) -> None: - __ndbuffer_registry.register(cls) +def register_buffer(cls: type[Buffer], qualname: str | None = None) -> None: + _buffer_registry.register(cls, qualname) -def register_buffer(cls: type[Buffer]) -> None: - __buffer_registry.register(cls) + +def register_chunk_key_encoding(key: str, cls: type) -> None: + _chunk_key_encoding_registry.register(cls, key) def get_codec_class(key: str, reload_config: bool = False) -> type[Codec]: if reload_config: _reload_config() - if key in __codec_registries: + if key in _codec_registries: # logger.debug("Auto loading codec '%s' from entrypoint", codec_id) - __codec_registries[key].lazy_load() + _codec_registries[key].lazy_load() - codec_classes = __codec_registries[key] + codec_classes = _codec_registries[key] if not codec_classes: raise KeyError(key) - config_entry = config.get("codecs", {}).get(key) if config_entry is None: + if len(codec_classes) == 1: + return next(iter(codec_classes.values())) warnings.warn( - f"Codec '{key}' not configured in config. Selecting any implementation.", stacklevel=2 + f"Codec '{key}' not configured in config. Selecting any implementation.", + stacklevel=2, + category=ZarrUserWarning, ) return list(codec_classes.values())[-1] selected_codec_cls = codec_classes[config_entry] @@ -137,44 +186,151 @@ def get_codec_class(key: str, reload_config: bool = False) -> type[Codec]: raise KeyError(key) +def _resolve_codec(data: dict[str, JSON]) -> Codec: + """ + Get a codec instance from a dict representation of that codec. + """ + # TODO: narrow the type of the input to only those dicts that map on to codec class instances. + return get_codec_class(data["name"]).from_dict(data) # type: ignore[arg-type] + + +def _parse_bytes_bytes_codec(data: dict[str, JSON] | Codec) -> BytesBytesCodec: + """ + Normalize the input to a `BytesBytesCodec` instance. + If the input is already a `BytesBytesCodec`, it is returned as is. If the input is a dict, it + is converted to a `BytesBytesCodec` instance via the `_resolve_codec` function. + """ + from zarr.abc.codec import BytesBytesCodec + + if isinstance(data, dict): + result = _resolve_codec(data) + if not isinstance(result, BytesBytesCodec): + msg = f"Expected a dict representation of a BytesBytesCodec; got a dict representation of a {type(result)} instead." + raise TypeError(msg) + else: + if not isinstance(data, BytesBytesCodec): + raise TypeError(f"Expected a BytesBytesCodec. Got {type(data)} instead.") + result = data + return result + + +def _parse_array_bytes_codec(data: dict[str, JSON] | Codec) -> ArrayBytesCodec: + """ + Normalize the input to a `ArrayBytesCodec` instance. + If the input is already a `ArrayBytesCodec`, it is returned as is. If the input is a dict, it + is converted to a `ArrayBytesCodec` instance via the `_resolve_codec` function. + """ + from zarr.abc.codec import ArrayBytesCodec + + if isinstance(data, dict): + result = _resolve_codec(data) + if not isinstance(result, ArrayBytesCodec): + msg = f"Expected a dict representation of an ArrayBytesCodec; got a dict representation of a {type(result)} instead." + raise TypeError(msg) + else: + if not isinstance(data, ArrayBytesCodec): + raise TypeError(f"Expected an ArrayBytesCodec. Got {type(data)} instead.") + result = data + return result + + +def _parse_array_array_codec(data: dict[str, JSON] | Codec) -> ArrayArrayCodec: + """ + Normalize the input to a `ArrayArrayCodec` instance. + If the input is already a `ArrayArrayCodec`, it is returned as is. If the input is a dict, it + is converted to a `ArrayArrayCodec` instance via the `_resolve_codec` function. + """ + from zarr.abc.codec import ArrayArrayCodec + + if isinstance(data, dict): + result = _resolve_codec(data) + if not isinstance(result, ArrayArrayCodec): + msg = f"Expected a dict representation of an ArrayArrayCodec; got a dict representation of a {type(result)} instead." + raise TypeError(msg) + else: + if not isinstance(data, ArrayArrayCodec): + raise TypeError(f"Expected an ArrayArrayCodec. Got {type(data)} instead.") + result = data + return result + + def get_pipeline_class(reload_config: bool = False) -> type[CodecPipeline]: if reload_config: _reload_config() - __pipeline_registry.lazy_load() + _pipeline_registry.lazy_load() path = config.get("codec_pipeline.path") - pipeline_class = __pipeline_registry.get(path) + pipeline_class = _pipeline_registry.get(path) if pipeline_class: return pipeline_class raise BadConfigError( - f"Pipeline class '{path}' not found in registered pipelines: {list(__pipeline_registry.keys())}." + f"Pipeline class '{path}' not found in registered pipelines: {list(_pipeline_registry)}." ) def get_buffer_class(reload_config: bool = False) -> type[Buffer]: if reload_config: _reload_config() - __buffer_registry.lazy_load() + _buffer_registry.lazy_load() path = config.get("buffer") - buffer_class = __buffer_registry.get(path) + buffer_class = _buffer_registry.get(path) if buffer_class: return buffer_class raise BadConfigError( - f"Buffer class '{path}' not found in registered buffers: {list(__buffer_registry.keys())}." + f"Buffer class '{path}' not found in registered buffers: {list(_buffer_registry)}." ) def get_ndbuffer_class(reload_config: bool = False) -> type[NDBuffer]: if reload_config: _reload_config() - __ndbuffer_registry.lazy_load() + _ndbuffer_registry.lazy_load() path = config.get("ndbuffer") - ndbuffer_class = __ndbuffer_registry.get(path) + ndbuffer_class = _ndbuffer_registry.get(path) if ndbuffer_class: return ndbuffer_class raise BadConfigError( - f"NDBuffer class '{path}' not found in registered buffers: {list(__ndbuffer_registry.keys())}." + f"NDBuffer class '{path}' not found in registered buffers: {list(_ndbuffer_registry)}." ) +def get_chunk_key_encoding_class(key: str) -> type[ChunkKeyEncoding]: + _chunk_key_encoding_registry.lazy_load(use_entrypoint_name=True) + if key not in _chunk_key_encoding_registry: + raise KeyError( + f"Chunk key encoding '{key}' not found in registered chunk key encodings: {list(_chunk_key_encoding_registry)}." + ) + return _chunk_key_encoding_registry[key] + + _collect_entrypoints() + + +def get_numcodec(data: CodecJSON_V2[str]) -> Numcodec: + """ + Resolve a numcodec codec from the numcodecs registry. + + This requires the Numcodecs package to be installed. + + Parameters + ---------- + data : CodecJSON_V2 + The JSON metadata for the codec. + + Returns + ------- + codec : Numcodec + + Examples + -------- + ```python + from zarr.registry import get_numcodec + codec = get_numcodec({'id': 'zlib', 'level': 1}) + codec + # Zlib(level=1) + ``` + """ + + from numcodecs.registry import get_codec + + return get_codec(data) # type: ignore[no-any-return] diff --git a/src/zarr/storage/__init__.py b/src/zarr/storage/__init__.py new file mode 100644 index 0000000000..f1bd1724af --- /dev/null +++ b/src/zarr/storage/__init__.py @@ -0,0 +1,45 @@ +import sys +import warnings +from types import ModuleType +from typing import Any + +from zarr.errors import ZarrDeprecationWarning +from zarr.storage._common import StoreLike, StorePath +from zarr.storage._fsspec import FsspecStore +from zarr.storage._local import LocalStore +from zarr.storage._logging import LoggingStore +from zarr.storage._memory import GpuMemoryStore, ManagedMemoryStore, MemoryStore +from zarr.storage._obstore import ObjectStore +from zarr.storage._wrapper import WrapperStore +from zarr.storage._zip import ZipStore + +__all__ = [ + "FsspecStore", + "GpuMemoryStore", + "LocalStore", + "LoggingStore", + "ManagedMemoryStore", + "MemoryStore", + "ObjectStore", + "StoreLike", + "StorePath", + "WrapperStore", + "ZipStore", +] + + +class VerboseModule(ModuleType): + def __setattr__(self, attr: str, value: Any) -> None: + if attr == "default_compressor": + warnings.warn( + "setting zarr.storage.default_compressor is deprecated, use " + "zarr.config to configure array.v2_default_compressor " + "e.g. config.set({'codecs.zstd':'numcodecs.Zstd', 'array.v2_default_compressor.numeric': 'zstd'})", + ZarrDeprecationWarning, + stacklevel=1, + ) + else: + super().__setattr__(attr, value) + + +sys.modules[__name__].__class__ = VerboseModule diff --git a/src/zarr/storage/_common.py b/src/zarr/storage/_common.py new file mode 100644 index 0000000000..72b5fc8a40 --- /dev/null +++ b/src/zarr/storage/_common.py @@ -0,0 +1,662 @@ +from __future__ import annotations + +import importlib.util +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal, Self + +from zarr.abc.store import ( + ByteRequest, + Store, + SupportsDeleteSync, + SupportsGetSync, + SupportsSetSync, +) +from zarr.core._json import buffer_to_json_object, get_json +from zarr.core.buffer import Buffer, default_buffer_prototype +from zarr.core.common import ( + ANY_ACCESS_MODE, + ZARR_JSON, + ZARRAY_JSON, + ZGROUP_JSON, + AccessModeLiteral, + ZarrFormat, +) +from zarr.errors import ContainsArrayAndGroupError, ContainsArrayError, ContainsGroupError +from zarr.storage._local import LocalStore +from zarr.storage._memory import ManagedMemoryStore, MemoryStore +from zarr.storage._utils import UPath, _join_paths, normalize_path, parse_store_url + +_has_fsspec = importlib.util.find_spec("fsspec") +if _has_fsspec: + from fsspec.mapping import FSMap +else: + FSMap = None + +if TYPE_CHECKING: + from zarr.core.buffer import BufferPrototype + from zarr.core.common import JSON + + +class StorePath: + """ + Path-like interface for a Store. + + Parameters + ---------- + store : Store + The store to use. + path : str + The path within the store. + """ + + store: Store + path: str + + def __init__(self, store: Store, path: str = "") -> None: + self.store = store + self.path = normalize_path(path) + + @property + def read_only(self) -> bool: + return self.store.read_only + + @classmethod + async def _create_open_instance(cls, store: Store, path: str) -> Self: + """Helper to create and return a StorePath instance.""" + await store._ensure_open() + return cls(store, path) + + @classmethod + async def open(cls, store: Store, path: str, mode: AccessModeLiteral | None = None) -> Self: + """ + Open StorePath based on the provided mode. + + * If the mode is None, return an opened version of the store with no changes. + * If the mode is 'r+', 'w-', 'w', or 'a' and the store is read-only, raise a ValueError. + * If the mode is 'r' and the store is not read-only, return a copy of the store with read_only set to True. + * If the mode is 'w-' and the store is not read-only and the StorePath contains keys, raise a FileExistsError. + * If the mode is 'w' and the store is not read-only, delete all keys nested within the StorePath. + + Parameters + ---------- + mode : AccessModeLiteral + The mode to use when initializing the store path. + + The accepted values are: + + - `'r'`: read only (must exist) + - `'r+'`: read/write (must exist) + - `'a'`: read/write (create if doesn't exist) + - `'w'`: read/write (overwrite if exists) + - `'w-'`: read/write (create if doesn't exist). + + Raises + ------ + FileExistsError + If the mode is 'w-' and the store path already exists. + ValueError + If the mode is not "r" and the store is read-only, or + """ + + # fastpath if mode is None + if mode is None: + return await cls._create_open_instance(store, path) + + if mode not in ANY_ACCESS_MODE: + raise ValueError(f"Invalid mode: {mode}, expected one of {ANY_ACCESS_MODE}") + + if store.read_only: + # Don't allow write operations on a read-only store + if mode != "r": + raise ValueError( + f"Store is read-only but mode is {mode!r}. Create a writable store or use 'r' mode." + ) + self = await cls._create_open_instance(store, path) + elif mode == "r": + # Create read-only copy for read mode on writable store + try: + read_only_store = store.with_read_only(True) + except NotImplementedError as e: + raise ValueError( + "Store is not read-only but mode is 'r'. Unable to create a read-only copy of the store. " + "Please use a read-only store or a storage class that implements .with_read_only()." + ) from e + self = await cls._create_open_instance(read_only_store, path) + else: + # writable store and writable mode + self = await cls._create_open_instance(store, path) + + # Handle mode-specific operations + match mode: + case "w-": + if not await self.is_empty(): + raise FileExistsError( + f"Cannot create '{path}' with mode 'w-' because it already contains data. " + f"Use mode 'w' to overwrite or 'a' to append." + ) + case "w": + await self.delete_dir() + return self + + async def get( + self, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + """ + Read bytes from the store. + + Parameters + ---------- + prototype : BufferPrototype, optional + The buffer prototype to use when reading the bytes. + byte_range : ByteRequest, optional + The range of bytes to read. + + Returns + ------- + buffer : Buffer or None + The read bytes, or None if the key does not exist. + """ + if prototype is None: + prototype = default_buffer_prototype() + return await self.store.get(self.path, prototype=prototype, byte_range=byte_range) + + async def get_json(self, *, byte_range: ByteRequest | None = None) -> JSON | None: + """ + Read and parse the JSON document at this path, or None if it is absent. + + Parameters + ---------- + byte_range : ByteRequest, optional + If given, read only this portion of the value. Note that a partial + read of a JSON document may not be valid JSON. + + Returns + ------- + JSON or None + The parsed JSON value, or None if this path does not exist. + """ + return await get_json(self.store, self.path, byte_range=byte_range) + + async def set(self, value: Buffer) -> None: + """ + Write bytes to the store. + + Parameters + ---------- + value : Buffer + The buffer to write. + """ + await self.store.set(self.path, value) + + async def delete(self) -> None: + """ + Delete the key from the store. + + Raises + ------ + NotImplementedError + If the store does not support deletion. + """ + await self.store.delete(self.path) + + async def delete_dir(self) -> None: + """ + Delete all keys with the given prefix from the store. + """ + await self.store.delete_dir(self.path) + + async def set_if_not_exists(self, default: Buffer) -> None: + """ + Store a key to `value` if the key is not already present. + + Parameters + ---------- + default : Buffer + The buffer to store if the key is not already present. + """ + await self.store.set_if_not_exists(self.path, default) + + async def exists(self) -> bool: + """ + Check if the key exists in the store. + + Returns + ------- + bool + True if the key exists in the store, False otherwise. + """ + return await self.store.exists(self.path) + + async def is_empty(self) -> bool: + """ + Check if any keys exist in the store with the given prefix. + + Returns + ------- + bool + True if no keys exist in the store with the given prefix, False otherwise. + """ + return await self.store.is_empty(self.path) + + # ------------------------------------------------------------------- + # Synchronous IO delegation + # ------------------------------------------------------------------- + + def get_sync( + self, + *, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + """Synchronous read β€” delegates to `self.store.get_sync(self.path, ...)`.""" + if not isinstance(self.store, SupportsGetSync): + raise TypeError(f"Store {type(self.store).__name__} does not support synchronous get.") + if prototype is None: + prototype = default_buffer_prototype() + return self.store.get_sync(self.path, prototype=prototype, byte_range=byte_range) + + def set_sync(self, value: Buffer) -> None: + """Synchronous write β€” delegates to `self.store.set_sync(self.path, value)`.""" + if not isinstance(self.store, SupportsSetSync): + raise TypeError(f"Store {type(self.store).__name__} does not support synchronous set.") + self.store.set_sync(self.path, value) + + def delete_sync(self) -> None: + """Synchronous delete β€” delegates to `self.store.delete_sync(self.path)`.""" + if not isinstance(self.store, SupportsDeleteSync): + raise TypeError( + f"Store {type(self.store).__name__} does not support synchronous delete." + ) + self.store.delete_sync(self.path) + + def __truediv__(self, other: str) -> StorePath: + """Combine this store path with another path""" + return self.__class__(self.store, _join_paths([self.path, other])) + + def __str__(self) -> str: + return _join_paths([str(self.store), self.path]) + + def __repr__(self) -> str: + return f"StorePath({self.store.__class__.__name__}, '{self}')" + + def __eq__(self, other: object) -> bool: + """ + Check if two StorePath objects are equal. + + Returns + ------- + bool + True if the two objects are equal, False otherwise. + + Notes + ----- + Two StorePath objects are considered equal if their stores are equal + and their paths are equal. + """ + try: + return self.store == other.store and self.path == other.path # type: ignore[attr-defined, no-any-return] + except AttributeError: + return False + + +type StoreLike = Store | StorePath | FSMap | Path | UPath | str | dict[str, Buffer] + + +async def make_store( + store_like: StoreLike | None, + *, + mode: AccessModeLiteral | None = None, + storage_options: dict[str, Any] | None = None, +) -> Store: + """ + Convert a `StoreLike` object into a Store object. + + `StoreLike` objects are converted to `Store` as follows: + + - `Store` or `StorePath` = `Store` object. + - `Path` or `str` = `LocalStore` object. + - `str` that starts with a protocol = `FsspecStore` object. + - `dict[str, Buffer]` = `MemoryStore` object. + - `None` = `MemoryStore` object. + - `FSMap` = `FsspecStore` object. + - `UPath` = `FsspecStore` object, or `LocalStore` for a local `UPath`. + + Parameters + ---------- + store_like : StoreLike | None + The `StoreLike` object to convert to a `Store` object. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + mode : StoreAccessMode | None, optional + The mode to use when creating the `Store` object. If None, the + default mode is 'r'. + storage_options : dict[str, Any] | None, optional + The storage options to use when creating the `RemoteStore` object. If + None, the default storage options are used. + + Returns + ------- + Store + The converted Store object. + + Raises + ------ + TypeError + If the StoreLike object is not one of the supported types, or if storage_options is provided but not used. + """ + from zarr.storage._fsspec import FsspecStore # circular import + + # Parse URL early so we can reuse the result for both validation and routing + parsed = parse_store_url(store_like) if isinstance(store_like, str) else None + + # Check if storage_options is valid for this store_like + if storage_options is not None: + is_fsspec_uri = parsed is not None and parsed.scheme not in ("", "memory", "file") + if not is_fsspec_uri: + raise TypeError( + "'storage_options' was provided but unused. " + "'storage_options' is only used when the store is passed as an FSSpec URI string.", + ) + + assert mode in (None, "r", "r+", "a", "w", "w-") + _read_only = mode == "r" + + if isinstance(store_like, StorePath): + # Get underlying store + return store_like.store + + elif isinstance(store_like, Store): + # Already a Store + return store_like + + elif isinstance(store_like, dict): + # Already a dictionary that can be a MemoryStore + # + # We deliberate only consider dict[str, Buffer] here, and not arbitrary mutable mappings. + # By only allowing dictionaries, which are in-memory, we know that MemoryStore appropriate. + return await MemoryStore.open(store_dict=store_like, read_only=_read_only) + + elif store_like is None: + # Create a new in-memory store + return await make_store({}, mode=mode, storage_options=storage_options) + + elif isinstance(store_like, UPath): + # This must be checked before Path: in universal-pathlib < 0.3 every UPath, including + # remote ones like S3Path, subclasses pathlib.Path, and would otherwise be misrouted to a + # LocalStore. Local UPaths get a LocalStore so that UPath("/data") and Path("/data") agree, + # mirroring how the equivalent strings are routed below. + if store_like.protocol in ("", "file"): + return await make_store( + Path(store_like.path), mode=mode, storage_options=storage_options + ) + return FsspecStore.from_upath(store_like, read_only=_read_only) + + elif isinstance(store_like, Path): + # Create a new LocalStore + return await LocalStore.open(root=store_like, mode=mode, read_only=_read_only) + + elif isinstance(store_like, str) and parsed is not None: + if parsed.scheme == "memory" and not _has_fsspec: + # Create or get a ManagedMemoryStore + return ManagedMemoryStore(name=parsed.name, path=parsed.path, read_only=_read_only) + elif parsed.scheme == "file" or not parsed.scheme: + # Local filesystem path β€” use parsed.path to strip the file:// scheme + return await make_store(Path(parsed.path), mode=mode, storage_options=storage_options) + else: + # Assume fsspec can handle it (s3://, gs://, http://, etc.) + return FsspecStore.from_url( + store_like, storage_options=storage_options, read_only=_read_only + ) + + elif _has_fsspec and isinstance(store_like, FSMap): + return FsspecStore.from_mapper(store_like, read_only=_read_only) + + else: + raise TypeError(f"Unsupported type for store_like: '{type(store_like).__name__}'") + + +async def make_store_path( + store_like: StoreLike | None, + *, + path: str | None = "", + mode: AccessModeLiteral | None = None, + storage_options: dict[str, Any] | None = None, +) -> StorePath: + """ + Convert a `StoreLike` object into a StorePath object. + + This function takes a `StoreLike` object and returns a `StorePath` object. See `make_store` for details + of which `Store` is used for each type of `store_like` object. + + Parameters + ---------- + store_like : StoreLike or None, default=None + The `StoreLike` object to convert to a `StorePath` object. See the + [storage documentation in the user guide][user-guide-store-like] + for a description of all valid StoreLike values. + path : str | None, optional + The path to use when creating the `StorePath` object. If None, the + default path is the empty string. + mode : StoreAccessMode | None, optional + The mode to use when creating the `StorePath` object. If None, the + default mode is 'r'. + storage_options : dict[str, Any] | None, optional + The storage options to use when creating the `RemoteStore` object. If + None, the default storage options are used. + + Returns + ------- + StorePath + The converted StorePath object. + + Raises + ------ + TypeError + If the StoreLike object is not one of the supported types, or if storage_options is provided but not used. + ValueError + If path is provided for a store that does not support it. + + See Also + -------- + make_store + """ + path_normalized = normalize_path(path) + + if isinstance(store_like, StorePath): + # Already a StorePath + if storage_options: + raise TypeError( + "'storage_options' was provided but unused. " + "'storage_options' is only used when the store is passed as an FSSpec URI string.", + ) + return store_like / path_normalized + + elif _has_fsspec and isinstance(store_like, FSMap) and path: + raise ValueError( + "'path' was provided but is not used for FSMap store_like objects. Specify the path when creating the FSMap instance instead." + ) + + else: + store = await make_store(store_like, mode=mode, storage_options=storage_options) + return await StorePath.open(store, path=path_normalized, mode=mode) + + +async def ensure_no_existing_node( + store_path: StorePath, + zarr_format: ZarrFormat, + node_type: Literal["array", "group"] | None = None, +) -> None: + """ + Check if a store_path is safe for array / group creation. + Returns `None` or raises an exception. + + Parameters + ---------- + store_path : StorePath + The storage location to check. + zarr_format : ZarrFormat + The Zarr format to check. + node_type : str | None, optional + Raise an error if an "array", or "group" exists. By default (when None), raises an error for either. + + Raises + ------ + ContainsArrayError, ContainsGroupError, ContainsArrayAndGroupError + """ + if zarr_format == 2: + extant_node = await _contains_node_v2(store_path) + elif zarr_format == 3: + extant_node = await _contains_node_v3(store_path) + + match extant_node: + case "array": + if node_type != "group": + msg = f"An array exists in store {store_path.store!r} at path {store_path.path!r}." + raise ContainsArrayError(msg) + + case "group": + if node_type != "array": + msg = f"A group exists in store {store_path.store!r} at path {store_path.path!r}." + raise ContainsGroupError(msg) + + case "nothing": + return + + case _: + msg = f"Invalid value for extant_node: {extant_node}" # type: ignore[unreachable] + raise ValueError(msg) + + +async def _contains_node_v3(store_path: StorePath) -> Literal["array", "group", "nothing"]: + """ + Check if a store_path contains nothing, an array, or a group. This function + returns the string "array", "group", or "nothing" to denote containing an array, a group, or + nothing. + + Parameters + ---------- + store_path : StorePath + The location in storage to check. + + Returns + ------- + Literal["array", "group", "nothing"] + A string representing the zarr node found at store_path. + """ + result: Literal["array", "group", "nothing"] = "nothing" + extant_meta_bytes = await (store_path / ZARR_JSON).get() + # if no metadata document could be loaded, then we just return "nothing" + if extant_meta_bytes is not None: + try: + extant_meta_json = buffer_to_json_object(extant_meta_bytes) + # avoid constructing a full metadata document here in the name of speed. + if extant_meta_json["node_type"] == "array": + result = "array" + elif extant_meta_json["node_type"] == "group": + result = "group" + except (KeyError, TypeError, ValueError): + # any of these errors is consistent with no array or group present. `ValueError` + # covers both malformed JSON (`json.JSONDecodeError`) and non-UTF-8 bytes + # (`UnicodeDecodeError`), each a `ValueError` subclass. + pass + return result + + +async def _contains_node_v2(store_path: StorePath) -> Literal["array", "group", "nothing"]: + """ + Check if a store_path contains nothing, an array, a group, or both. If both an array and a + group are detected, a `ContainsArrayAndGroup` exception is raised. Otherwise, this function + returns the string "array", "group", or "nothing" to denote containing an array, a group, or + nothing. + + Parameters + ---------- + store_path : StorePath + The location in storage to check. + + Returns + ------- + Literal["array", "group", "nothing"] + A string representing the zarr node found at store_path. + """ + _array = await contains_array(store_path=store_path, zarr_format=2) + _group = await contains_group(store_path=store_path, zarr_format=2) + + if _array and _group: + msg = ( + "Array and group metadata documents (.zarray and .zgroup) were both found in store " + f"{store_path.store!r} at path {store_path.path!r}. " + "Only one of these files may be present in a given directory / prefix. " + "Remove the .zarray file, or the .zgroup file, or both." + ) + raise ContainsArrayAndGroupError(msg) + elif _array: + return "array" + elif _group: + return "group" + else: + return "nothing" + + +async def contains_array(store_path: StorePath, zarr_format: ZarrFormat) -> bool: + """ + Check if an array exists at a given StorePath. + + Parameters + ---------- + store_path : StorePath + The StorePath to check for an existing group. + zarr_format : + The zarr format to check for. + + Returns + ------- + bool + True if the StorePath contains a group, False otherwise. + + """ + if zarr_format == 3: + extant_meta_bytes = await (store_path / ZARR_JSON).get() + if extant_meta_bytes is None: + return False + else: + try: + extant_meta_json = buffer_to_json_object(extant_meta_bytes) + # we avoid constructing a full metadata document here in the name of speed. + if extant_meta_json["node_type"] == "array": + return True + except (ValueError, KeyError, TypeError): + return False + elif zarr_format == 2: + return await (store_path / ZARRAY_JSON).exists() + msg = f"Invalid zarr_format provided. Got {zarr_format}, expected 2 or 3" + raise ValueError(msg) + + +async def contains_group(store_path: StorePath, zarr_format: ZarrFormat) -> bool: + """ + Check if a group exists at a given StorePath. + + Parameters + ---------- + + store_path : StorePath + The StorePath to check for an existing group. + zarr_format : + The zarr format to check for. + + Returns + ------- + + bool + True if the StorePath contains a group, False otherwise + + """ + if zarr_format == 3: + return (await _contains_node_v3(store_path)) == "group" + elif zarr_format == 2: + return await (store_path / ZGROUP_JSON).exists() + msg = f"Invalid zarr_format provided. Got {zarr_format}, expected 2 or 3" # type: ignore[unreachable] + raise ValueError(msg) diff --git a/src/zarr/storage/_fsspec.py b/src/zarr/storage/_fsspec.py new file mode 100644 index 0000000000..a212e95f2f --- /dev/null +++ b/src/zarr/storage/_fsspec.py @@ -0,0 +1,455 @@ +from __future__ import annotations + +import warnings +from contextlib import suppress +from typing import TYPE_CHECKING, Any + +from packaging.version import parse as parse_version + +from zarr.abc.store import ( + ByteRequest, + OffsetByteRequest, + RangeByteRequest, + Store, + SuffixByteRequest, +) +from zarr.core.buffer import Buffer +from zarr.errors import ZarrUserWarning +from zarr.storage._utils import _dereference_path + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Iterable + + from fsspec import AbstractFileSystem + from fsspec.asyn import AsyncFileSystem + from fsspec.mapping import FSMap + + from zarr.core.buffer import BufferPrototype + + +ALLOWED_EXCEPTIONS: tuple[type[Exception], ...] = ( + FileNotFoundError, + IsADirectoryError, + NotADirectoryError, +) + + +def _make_async(fs: AbstractFileSystem) -> AsyncFileSystem: + """Convert a sync FSSpec filesystem to an async FFSpec filesystem + + If the filesystem class supports async operations, a new async instance is created + from the existing instance. + + If the filesystem class does not support async operations, the existing instance + is wrapped with AsyncFileSystemWrapper. + """ + import fsspec + + fsspec_version = parse_version(fsspec.__version__) + if fs.async_impl and fs.asynchronous: + # Already an async instance of an async filesystem, nothing to do + return fs + if fs.async_impl: + # Convert sync instance of an async fs to an async instance. Reuse the original + # constructor arguments rather than round-tripping through JSON, since storage + # options may hold objects that are not JSON-serializable (e.g. credentials). + return type(fs)(*fs.storage_args, **{**fs.storage_options, "asynchronous": True}) + + if fsspec_version < parse_version("2024.12.0"): + raise ImportError( + f"The filesystem '{fs}' is synchronous, and the required " + "AsyncFileSystemWrapper is not available. Upgrade fsspec to version " + "2024.12.0 or later to enable this functionality." + ) + from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper + + return AsyncFileSystemWrapper(fs, asynchronous=True) + + +class FsspecStore(Store): + """ + Store for remote data based on FSSpec. + + Parameters + ---------- + fs : AsyncFileSystem + The Async FSSpec filesystem to use with this store. + read_only : bool + Whether the store is read-only + path : str + The root path of the store. This should be a relative path and must not include the + filesystem scheme. + allowed_exceptions : tuple[type[Exception], ...] + When fetching data, these cases will be deemed to correspond to missing keys. + + Attributes + ---------- + fs + allowed_exceptions + supports_writes + supports_deletes + supports_listing + + Raises + ------ + TypeError + If the Filesystem does not support async operations. + ValueError + If the path argument includes a scheme. + + Warns + ----- + ZarrUserWarning + If the file system (fs) was not created with `asynchronous=True`. + + Notes + ----- + Closing the store does not close the underlying filesystem or its network + session. fsspec caches and shares filesystem instances across callers, so + the store cannot know whether it is the only user, and closing a shared + session would break other stores. The filesystem's lifecycle belongs to + whoever created it; use fsspec's own tools (e.g. `clear_instance_cache`) + to release it. + + See Also + -------- + FsspecStore.from_upath + FsspecStore.from_url + """ + + # based on FSSpec + supports_writes: bool = True + supports_deletes: bool = True + supports_listing: bool = True + + fs: AsyncFileSystem + allowed_exceptions: tuple[type[Exception], ...] + path: str + + def __init__( + self, + fs: AsyncFileSystem, + read_only: bool = False, + path: str = "/", + allowed_exceptions: tuple[type[Exception], ...] = ALLOWED_EXCEPTIONS, + ) -> None: + super().__init__(read_only=read_only) + self.fs = fs + self.path = path + self.allowed_exceptions = allowed_exceptions + + if not self.fs.async_impl: + raise TypeError("Filesystem needs to support async operations.") + if not self.fs.asynchronous: + warnings.warn( + f"fs ({fs}) was not created with `asynchronous=True`, this may lead to surprising behavior", + category=ZarrUserWarning, + stacklevel=2, + ) + + @classmethod + def from_upath( + cls, + upath: Any, + read_only: bool = False, + allowed_exceptions: tuple[type[Exception], ...] = ALLOWED_EXCEPTIONS, + ) -> FsspecStore: + """ + Create an FsspecStore from a upath object. + + Parameters + ---------- + upath : UPath + The upath to the root of the store. + read_only : bool + Whether the store is read-only, defaults to False. + allowed_exceptions : tuple, optional + The exceptions that are allowed to be raised when accessing the + store. Defaults to ALLOWED_EXCEPTIONS. + + Returns + ------- + FsspecStore + """ + # A UPath hands back a filesystem in whatever mode it was constructed with, which is + # synchronous unless the caller passed asynchronous=True. Route it through _make_async so + # that sync-mode instances of async filesystems are re-created in async mode, and + # genuinely synchronous filesystems are wrapped. + return cls( + fs=_make_async(upath.fs), + path=upath.path.rstrip("/"), + read_only=read_only, + allowed_exceptions=allowed_exceptions, + ) + + @classmethod + def from_mapper( + cls, + fs_map: FSMap, + read_only: bool = False, + allowed_exceptions: tuple[type[Exception], ...] = ALLOWED_EXCEPTIONS, + ) -> FsspecStore: + """ + Create an FsspecStore from an FSMap object. + + Parameters + ---------- + fs_map : FSMap + Fsspec mutable mapping object. + read_only : bool + Whether the store is read-only, defaults to False. + allowed_exceptions : tuple, optional + The exceptions that are allowed to be raised when accessing the + store. Defaults to ALLOWED_EXCEPTIONS. + + Returns + ------- + FsspecStore + """ + fs = _make_async(fs_map.fs) + return cls( + fs=fs, + path=fs_map.root, + read_only=read_only, + allowed_exceptions=allowed_exceptions, + ) + + @classmethod + def from_url( + cls, + url: str, + storage_options: dict[str, Any] | None = None, + read_only: bool = False, + allowed_exceptions: tuple[type[Exception], ...] = ALLOWED_EXCEPTIONS, + ) -> FsspecStore: + """ + Create an FsspecStore from a URL. The type of store is determined from the URL scheme. + + Parameters + ---------- + url : str + The URL to the root of the store. + storage_options : dict, optional + The options to pass to fsspec when creating the filesystem. + read_only : bool + Whether the store is read-only, defaults to False. + allowed_exceptions : tuple, optional + The exceptions that are allowed to be raised when accessing the + store. Defaults to ALLOWED_EXCEPTIONS. + + Returns + ------- + FsspecStore + """ + try: + from fsspec import url_to_fs + except ImportError: + # before fsspec==2024.3.1 + from fsspec.core import url_to_fs + + opts = storage_options or {} + opts = {"asynchronous": True, **opts} + + fs, path = url_to_fs(url, **opts) + if not fs.async_impl: + fs = _make_async(fs) + + return cls(fs=fs, path=path, read_only=read_only, allowed_exceptions=allowed_exceptions) + + def with_read_only(self, read_only: bool = False) -> FsspecStore: + # docstring inherited + return type(self)( + fs=self.fs, + path=self.path, + allowed_exceptions=self.allowed_exceptions, + read_only=read_only, + ) + + async def clear(self) -> None: + # docstring inherited + try: + for subpath in await self.fs._find(self.path, withdirs=True): + if subpath != self.path: + await self.fs._rm(subpath, recursive=True) + except FileNotFoundError: + pass + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, type(self)) + and self.path == other.path + and self.read_only == other.read_only + and self.fs == other.fs + ) + + async def get( + self, + key: str, + prototype: BufferPrototype, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + # docstring inherited + if not self._is_open: + await self._open() + path = _dereference_path(self.path, key) + + try: + if byte_range is None: + value = prototype.buffer.from_bytes(await self.fs._cat_file(path)) + elif isinstance(byte_range, RangeByteRequest): + value = prototype.buffer.from_bytes( + await self.fs._cat_file( + path, + start=byte_range.start, + end=byte_range.end, + ) + ) + elif isinstance(byte_range, OffsetByteRequest): + value = prototype.buffer.from_bytes( + await self.fs._cat_file(path, start=byte_range.offset, end=None) + ) + elif isinstance(byte_range, SuffixByteRequest): + value = prototype.buffer.from_bytes( + await self.fs._cat_file(path, start=-byte_range.suffix, end=None) + ) + else: + raise ValueError(f"Unexpected byte_range, got {byte_range}.") + except self.allowed_exceptions: + return None + except OSError as e: + if "not satisfiable" in str(e): + # this is an s3-specific condition we probably don't want to leak + return prototype.buffer.from_bytes(b"") + raise + else: + return value + + async def set( + self, + key: str, + value: Buffer, + byte_range: tuple[int, int] | None = None, + ) -> None: + # docstring inherited + if not self._is_open: + await self._open() + self._check_writable() + if not isinstance(value, Buffer): + raise TypeError( + f"FsspecStore.set(): `value` must be a Buffer instance. Got an instance of {type(value)} instead." + ) + path = _dereference_path(self.path, key) + # write data + if byte_range: + raise NotImplementedError + await self.fs._pipe_file(path, value.to_bytes()) + + async def delete(self, key: str) -> None: + # docstring inherited + self._check_writable() + path = _dereference_path(self.path, key) + try: + await self.fs._rm(path) + except FileNotFoundError: + pass + except self.allowed_exceptions: + pass + + async def delete_dir(self, prefix: str) -> None: + # docstring inherited + if not self.supports_deletes: + raise NotImplementedError( + "This method is only available for stores that support deletes." + ) + self._check_writable() + + path_to_delete = _dereference_path(self.path, prefix) + + with suppress(*self.allowed_exceptions): + await self.fs._rm(path_to_delete, recursive=True) + + async def exists(self, key: str) -> bool: + # docstring inherited + path = _dereference_path(self.path, key) + exists: bool = await self.fs._exists(path) + return exists + + async def get_partial_values( + self, + prototype: BufferPrototype, + key_ranges: Iterable[tuple[str, ByteRequest | None]], + ) -> list[Buffer | None]: + # docstring inherited + # Materialise first: key_ranges may be a one-shot iterable, so a bare + # truthiness check (e.g. `if key_ranges`) would be unreliable for an + # empty generator. _cat_ranges also expects lists of paths/starts/stops. + key_ranges = list(key_ranges) + if not key_ranges: + return [] + paths: list[str] = [] + starts: list[int | None] = [] + stops: list[int | None] = [] + for key, byte_range in key_ranges: + paths.append(_dereference_path(self.path, key)) + if byte_range is None: + starts.append(None) + stops.append(None) + elif isinstance(byte_range, RangeByteRequest): + starts.append(byte_range.start) + stops.append(byte_range.end) + elif isinstance(byte_range, OffsetByteRequest): + starts.append(byte_range.offset) + stops.append(None) + elif isinstance(byte_range, SuffixByteRequest): + starts.append(-byte_range.suffix) + stops.append(None) + else: + raise ValueError(f"Unexpected byte_range, got {byte_range}.") + # TODO: expectations for exceptions or missing keys? + res = await self.fs._cat_ranges(paths, starts, stops, on_error="return") + # the following is an s3-specific condition we probably don't want to leak + res = [b"" if (isinstance(r, OSError) and "not satisfiable" in str(r)) else r for r in res] + for r in res: + if isinstance(r, Exception) and not isinstance(r, self.allowed_exceptions): + raise r + + return [None if isinstance(r, Exception) else prototype.buffer.from_bytes(r) for r in res] + + async def list(self) -> AsyncIterator[str]: + # docstring inherited + allfiles = await self.fs._find(self.path, detail=False, withdirs=False) + for onefile in (a.removeprefix(f"{self.path}/") for a in allfiles): + yield onefile + + async def list_dir(self, prefix: str) -> AsyncIterator[str]: + # docstring inherited + prefix = f"{self.path}/{prefix.rstrip('/')}" + try: + allfiles = await self.fs._ls(prefix, detail=False) + except FileNotFoundError: + return + for onefile in (a.replace(f"{prefix}/", "") for a in allfiles): + yield onefile.removeprefix(self.path).removeprefix("/") + + async def list_prefix(self, prefix: str) -> AsyncIterator[str]: + # docstring inherited + for onefile in await self.fs._find( + f"{self.path}/{prefix}", detail=False, maxdepth=None, withdirs=False + ): + yield onefile.removeprefix(f"{self.path}/") + + async def getsize(self, key: str) -> int: + path = _dereference_path(self.path, key) + info = await self.fs._info(path) + + size = info.get("size") + + if size is None: + # Not all filesystems support size. Fall back to reading the entire object + return await super().getsize(key) + else: + # fsspec doesn't have typing. We'll need to assume or verify this is true + return int(size) diff --git a/src/zarr/storage/_local.py b/src/zarr/storage/_local.py new file mode 100644 index 0000000000..1627c1a6b5 --- /dev/null +++ b/src/zarr/storage/_local.py @@ -0,0 +1,372 @@ +from __future__ import annotations + +import asyncio +import contextlib +import io +import os +import shutil +import sys +import uuid +from pathlib import Path +from typing import TYPE_CHECKING, BinaryIO, Literal, Self + +from zarr.abc.store import ( + ByteRequest, + OffsetByteRequest, + RangeByteRequest, + Store, + SuffixByteRequest, +) +from zarr.core.buffer import Buffer +from zarr.core.buffer.core import default_buffer_prototype +from zarr.core.common import AccessModeLiteral, concurrent_map + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Iterable, Iterator + + from zarr.core.buffer import BufferPrototype + + +def _get(path: Path, prototype: BufferPrototype, byte_range: ByteRequest | None) -> Buffer: + if byte_range is None: + return prototype.buffer.from_bytes(path.read_bytes()) + with path.open("rb") as f: + size = f.seek(0, io.SEEK_END) + if isinstance(byte_range, RangeByteRequest): + f.seek(byte_range.start) + return prototype.buffer.from_bytes(f.read(byte_range.end - f.tell())) + elif isinstance(byte_range, OffsetByteRequest): + f.seek(byte_range.offset) + elif isinstance(byte_range, SuffixByteRequest): + f.seek(max(0, size - byte_range.suffix)) + else: + raise TypeError(f"Unexpected byte_range, got {byte_range}.") + return prototype.buffer.from_bytes(f.read()) + + +if sys.platform == "win32": + # Per the os.rename docs: + # On Windows, if dst exists a FileExistsError is always raised. + _safe_move = os.rename +else: + # On Unix, os.rename silently replace files, so instead we use os.link like + # atomicwrites: + # https://github.com/untitaker/python-atomicwrites/blob/1.4.1/atomicwrites/__init__.py#L59-L60 + # This also raises FileExistsError if dst exists. + def _safe_move(src: Path, dst: Path) -> None: + os.link(src, dst) + os.unlink(src) + + +@contextlib.contextmanager +def _atomic_write( + path: Path, + mode: Literal["r+b", "wb"], + exclusive: bool = False, +) -> Iterator[BinaryIO]: + tmp_path = path.with_suffix(f".{uuid.uuid4().hex}.partial") + try: + with tmp_path.open(mode) as f: + yield f + if exclusive: + _safe_move(tmp_path, path) + else: + tmp_path.replace(path) + except Exception: + tmp_path.unlink(missing_ok=True) + raise + + +def _put(path: Path, value: Buffer, exclusive: bool = False) -> int: + path.parent.mkdir(parents=True, exist_ok=True) + # write takes any object supporting the buffer protocol + view = value.as_buffer_like() + with _atomic_write(path, "wb", exclusive=exclusive) as f: + return f.write(view) + + +class LocalStore(Store): + """ + Store for the local file system. + + Parameters + ---------- + root : str or Path + Directory to use as root of store. + read_only : bool + Whether the store is read-only + + Attributes + ---------- + supports_writes + supports_deletes + supports_listing + root + """ + + supports_writes: bool = True + supports_deletes: bool = True + supports_listing: bool = True + + root: Path + + def __init__(self, root: Path | str, *, read_only: bool = False) -> None: + super().__init__(read_only=read_only) + if isinstance(root, str): + root = Path(root) + if not isinstance(root, Path): + raise TypeError( + f"'root' must be a string or Path instance. Got an instance of {type(root)} instead." + ) + self.root = root + + def with_read_only(self, read_only: bool = False) -> Self: + # docstring inherited + return type(self)( + root=self.root, + read_only=read_only, + ) + + @classmethod + async def open( + cls, root: Path | str, *, read_only: bool = False, mode: AccessModeLiteral | None = None + ) -> Self: + """ + Create and open the store. + + Parameters + ---------- + root : str or Path + Directory to use as root of store. + read_only : bool + Whether the store is read-only + mode : + Mode in which to create the store. This only affects opening the store, + and the final read-only state of the store is controlled through the + read_only parameter. + + Returns + ------- + Store + The opened store instance. + """ + # If mode = 'r+', want to open in read only mode (fail if exists), + # but return a writeable store + if mode is not None: + read_only_creation = mode in ["r", "r+"] + else: + read_only_creation = read_only + store = cls(root, read_only=read_only_creation) + await store._open() + + # Set read_only state + store = store.with_read_only(read_only) + await store._open() + return store + + async def _open(self, *, mode: AccessModeLiteral | None = None) -> None: + if not self.read_only: + self.root.mkdir(parents=True, exist_ok=True) + + if not self.root.exists(): + raise FileNotFoundError(f"{self.root} does not exist") + return await super()._open() + + async def clear(self) -> None: + # docstring inherited + self._check_writable() + shutil.rmtree(self.root) + self.root.mkdir() + + def __str__(self) -> str: + return f"file://{self.root.as_posix()}" + + def __repr__(self) -> str: + return f"LocalStore('{self}')" + + def __eq__(self, other: object) -> bool: + return isinstance(other, type(self)) and self.root == other.root + + # ------------------------------------------------------------------- + # Synchronous store methods + # ------------------------------------------------------------------- + + def _ensure_open_sync(self) -> None: + if not self._is_open: + if not self.read_only: + self.root.mkdir(parents=True, exist_ok=True) + if not self.root.exists(): + raise FileNotFoundError(f"{self.root} does not exist") + self._is_open = True + + def get_sync( + self, + key: str, + *, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + if prototype is None: + prototype = default_buffer_prototype() + self._ensure_open_sync() + assert isinstance(key, str) + path = self.root / key + try: + return _get(path, prototype, byte_range) + except (FileNotFoundError, IsADirectoryError, NotADirectoryError): + return None + + def set_sync(self, key: str, value: Buffer) -> None: + self._ensure_open_sync() + self._check_writable() + assert isinstance(key, str) + if not isinstance(value, Buffer): + raise TypeError( + f"LocalStore.set(): `value` must be a Buffer instance. " + f"Got an instance of {type(value)} instead." + ) + path = self.root / key + _put(path, value) + + def delete_sync(self, key: str) -> None: + self._ensure_open_sync() + self._check_writable() + path = self.root / key + if path.is_dir(): + shutil.rmtree(path) + else: + path.unlink(missing_ok=True) + + async def get( + self, + key: str, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + # docstring inherited + if prototype is None: + prototype = default_buffer_prototype() + if not self._is_open: + await self._open() + assert isinstance(key, str) + path = self.root / key + + try: + return await asyncio.to_thread(_get, path, prototype, byte_range) + except (FileNotFoundError, IsADirectoryError, NotADirectoryError): + return None + + async def get_partial_values( + self, + prototype: BufferPrototype, + key_ranges: Iterable[tuple[str, ByteRequest | None]], + ) -> list[Buffer | None]: + # docstring inherited + args = [] + for key, byte_range in key_ranges: + assert isinstance(key, str) + path = self.root / key + args.append((_get, path, prototype, byte_range)) + return await concurrent_map(args, asyncio.to_thread, limit=None) # TODO: fix limit + + async def set(self, key: str, value: Buffer) -> None: + # docstring inherited + return await self._set(key, value) + + async def set_if_not_exists(self, key: str, value: Buffer) -> None: + # docstring inherited + try: + return await self._set(key, value, exclusive=True) + except FileExistsError: + pass + + async def _set(self, key: str, value: Buffer, exclusive: bool = False) -> None: + if not self._is_open: + await self._open() + self._check_writable() + assert isinstance(key, str) + if not isinstance(value, Buffer): + raise TypeError( + f"LocalStore.set(): `value` must be a Buffer instance. Got an instance of {type(value)} instead." + ) + path = self.root / key + await asyncio.to_thread(_put, path, value, exclusive=exclusive) + + async def delete(self, key: str) -> None: + """ + Remove a key from the store. + + Parameters + ---------- + key : str + + Notes + ----- + If ``key`` is a directory within this store, the entire directory + at ``store.root / key`` is deleted. + """ + # docstring inherited + self._check_writable() + path = self.root / key + if path.is_dir(): # TODO: support deleting directories? shutil.rmtree? + shutil.rmtree(path) + else: + await asyncio.to_thread(path.unlink, True) # Q: we may want to raise if path is missing + + async def delete_dir(self, prefix: str) -> None: + # docstring inherited + self._check_writable() + path = self.root / prefix + if path.is_dir(): + shutil.rmtree(path) + elif path.is_file(): + raise ValueError(f"delete_dir was passed a {prefix=!r} that is a file") + else: + # Non-existent directory + # This path is tested by test_group:test_create_creates_parents for one + pass + + async def exists(self, key: str) -> bool: + # docstring inherited + path = self.root / key + return await asyncio.to_thread(path.is_file) + + async def list(self) -> AsyncIterator[str]: + # docstring inherited + to_strip = self.root.as_posix() + "/" + for p in list(self.root.rglob("*")): + if p.is_file(): + yield p.as_posix().replace(to_strip, "") + + async def list_prefix(self, prefix: str) -> AsyncIterator[str]: + # docstring inherited + to_strip = self.root.as_posix() + "/" + prefix = prefix.rstrip("/") + for p in (self.root / prefix).rglob("*"): + if p.is_file(): + yield p.as_posix().replace(to_strip, "") + + async def list_dir(self, prefix: str) -> AsyncIterator[str]: + # docstring inherited + base = self.root / prefix + try: + key_iter = base.iterdir() + for key in key_iter: + yield key.relative_to(base).as_posix() + except (FileNotFoundError, NotADirectoryError): + pass + + async def move(self, dest_root: Path | str) -> None: + """ + Move the store to another path. The old root directory is deleted. + """ + if isinstance(dest_root, str): + dest_root = Path(dest_root) + os.makedirs(dest_root.parent, exist_ok=True) + if dest_root.exists(): + raise FileExistsError(f"Destination root {dest_root} already exists.") + shutil.move(self.root, dest_root) + self.root = dest_root + + async def getsize(self, key: str) -> int: + return (self.root / key).stat().st_size diff --git a/src/zarr/storage/_logging.py b/src/zarr/storage/_logging.py new file mode 100644 index 0000000000..cdf0731430 --- /dev/null +++ b/src/zarr/storage/_logging.py @@ -0,0 +1,257 @@ +from __future__ import annotations + +import inspect +import logging +import sys +import time +from collections import defaultdict +from contextlib import contextmanager +from typing import TYPE_CHECKING, Any, Self + +from zarr.abc.store import Store +from zarr.storage._wrapper import WrapperStore + +if TYPE_CHECKING: + from collections.abc import AsyncGenerator, Generator, Iterable + + from zarr.abc.store import ByteRequest + from zarr.core.buffer import Buffer, BufferPrototype + + counter: defaultdict[str, int] + + +class LoggingStore[T_Store: Store](WrapperStore[T_Store]): + """ + Store that logs all calls to another wrapped store. + + Parameters + ---------- + store : Store + Store to wrap + log_level : str + Log level + log_handler : logging.Handler + Log handler + + Attributes + ---------- + counter : dict + Counter of number of times each method has been called + """ + + counter: defaultdict[str, int] + + def __init__( + self, + store: T_Store, + log_level: str = "DEBUG", + log_handler: logging.Handler | None = None, + ) -> None: + super().__init__(store) + self.counter = defaultdict(int) + self.log_level = log_level + self.log_handler = log_handler + self._configure_logger(log_level, log_handler) + + def _configure_logger( + self, log_level: str = "DEBUG", log_handler: logging.Handler | None = None + ) -> None: + self.log_level = log_level + self.logger = logging.getLogger(f"LoggingStore({self._store})") + self.logger.setLevel(log_level) + + if not self.logger.hasHandlers(): + if not log_handler: + log_handler = self._default_handler() + # Add handler to logger + self.logger.addHandler(log_handler) + + def _default_handler(self) -> logging.Handler: + """Define a default log handler""" + handler = logging.StreamHandler(stream=sys.stdout) + handler.setLevel(self.log_level) + handler.setFormatter( + logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") + ) + return handler + + def _with_store(self, store: T_Store) -> Self: + return type(self)(store=store, log_level=self.log_level, log_handler=self.log_handler) + + @contextmanager + def log(self, hint: Any = "") -> Generator[None, None, None]: + """Context manager to log method calls + + Each call to the wrapped store is logged to the configured logger and added to + the counter dict. + """ + method = inspect.stack()[2].function + op = f"{type(self._store).__name__}.{method}" + if hint: + op = f"{op}({hint})" + self.logger.info(" Calling %s", op) + start_time = time.time() + try: + self.counter[method] += 1 + yield + finally: + end_time = time.time() + self.logger.info("Finished %s [%.2f s]", op, end_time - start_time) + + @classmethod + async def open(cls: type[Self], store_cls: type[T_Store], *args: Any, **kwargs: Any) -> Self: + log_level = kwargs.pop("log_level", "DEBUG") + log_handler = kwargs.pop("log_handler", None) + store = store_cls(*args, **kwargs) + await store._open() + return cls(store=store, log_level=log_level, log_handler=log_handler) + + @property + def supports_writes(self) -> bool: + with self.log(): + return self._store.supports_writes + + @property + def supports_deletes(self) -> bool: + with self.log(): + return self._store.supports_deletes + + @property + def supports_listing(self) -> bool: + with self.log(): + return self._store.supports_listing + + @property + def read_only(self) -> bool: + with self.log(): + return self._store.read_only + + @property + def _is_open(self) -> bool: + with self.log(): + return self._store._is_open + + @_is_open.setter + def _is_open(self, value: bool) -> None: + raise NotImplementedError("LoggingStore must be opened via the `_open` method") + + async def _open(self) -> None: + with self.log(): + return await self._store._open() + + async def _ensure_open(self) -> None: + with self.log(): + return await self._store._ensure_open() + + async def is_empty(self, prefix: str = "") -> bool: + # docstring inherited + with self.log(): + return await self._store.is_empty(prefix=prefix) + + async def clear(self) -> None: + # docstring inherited + with self.log(): + return await self._store.clear() + + def __str__(self) -> str: + return f"logging-{self._store}" + + def __repr__(self) -> str: + return f"LoggingStore({self._store.__class__.__name__}, '{self._store}')" + + def __eq__(self, other: object) -> bool: + with self.log(other): + return type(self) is type(other) and self._store.__eq__(other._store) + + async def get( + self, + key: str, + prototype: BufferPrototype, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + # docstring inherited + with self.log(key): + return await self._store.get(key=key, prototype=prototype, byte_range=byte_range) + + async def get_partial_values( + self, + prototype: BufferPrototype, + key_ranges: Iterable[tuple[str, ByteRequest | None]], + ) -> list[Buffer | None]: + # docstring inherited + key_ranges = list(key_ranges) + keys = ",".join([k[0] for k in key_ranges]) + with self.log(keys): + return await self._store.get_partial_values(prototype=prototype, key_ranges=key_ranges) + + async def exists(self, key: str) -> bool: + # docstring inherited + with self.log(key): + return await self._store.exists(key) + + async def set(self, key: str, value: Buffer) -> None: + # docstring inherited + with self.log(key): + return await self._store.set(key=key, value=value) + + async def set_if_not_exists(self, key: str, value: Buffer) -> None: + # docstring inherited + with self.log(key): + return await self._store.set_if_not_exists(key=key, value=value) + + async def delete(self, key: str) -> None: + # docstring inherited + with self.log(key): + return await self._store.delete(key=key) + + def get_sync( + self, + key: str, + *, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + # docstring inherited + with self.log(key): + return super().get_sync(key, prototype=prototype, byte_range=byte_range) + + def set_sync(self, key: str, value: Buffer) -> None: + # docstring inherited + with self.log(key): + return super().set_sync(key, value) + + def delete_sync(self, key: str) -> None: + # docstring inherited + with self.log(key): + return super().delete_sync(key) + + async def list(self) -> AsyncGenerator[str, None]: + # docstring inherited + with self.log(): + async for key in self._store.list(): + yield key + + async def list_prefix(self, prefix: str) -> AsyncGenerator[str, None]: + # docstring inherited + with self.log(prefix): + async for key in self._store.list_prefix(prefix=prefix): + yield key + + async def list_dir(self, prefix: str) -> AsyncGenerator[str, None]: + # docstring inherited + with self.log(prefix): + async for key in self._store.list_dir(prefix=prefix): + yield key + + async def delete_dir(self, prefix: str) -> None: + # docstring inherited + with self.log(prefix): + await self._store.delete_dir(prefix=prefix) + + async def getsize(self, key: str) -> int: + with self.log(key): + return await self._store.getsize(key) + + async def getsize_prefix(self, prefix: str) -> int: + with self.log(prefix): + return await self._store.getsize_prefix(prefix) diff --git a/src/zarr/storage/_memory.py b/src/zarr/storage/_memory.py new file mode 100644 index 0000000000..f42c38df69 --- /dev/null +++ b/src/zarr/storage/_memory.py @@ -0,0 +1,709 @@ +from __future__ import annotations + +import os +import threading +import weakref +from logging import getLogger +from typing import TYPE_CHECKING, Any, Self + +from zarr.abc.store import ByteRequest, Store +from zarr.core.buffer import Buffer, gpu +from zarr.core.buffer.core import default_buffer_prototype +from zarr.core.common import concurrent_map +from zarr.storage._utils import ( + _join_paths, + _normalize_byte_range_index, + normalize_path, + parse_store_url, +) + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Iterable, MutableMapping + + from zarr.core.buffer import BufferPrototype + + +logger = getLogger(__name__) + + +def _copy_buffer(value: Buffer) -> Buffer: + """Copy `value` so the store does not retain the caller's memory. + + Encoding a chunk can hand the store a zero-copy view of the user's array + (an uncompressed write is the common case), and unlike stores that + serialize on write, this one keeps whatever it is given alive in a dict. + Without this copy a later mutation of the user's array would rewrite + chunks already committed to the store. + """ + return type(value).from_array_like(value.as_array_like().copy()) + + +class MemoryStore(Store): + """ + Store for local memory. + + Parameters + ---------- + store_dict : dict + Initial data + read_only : bool + Whether the store is read-only + + Attributes + ---------- + supports_writes + supports_deletes + supports_listing + + Notes + ----- + Writes copy the buffer they are given, so the store never aliases the + caller's memory. Buffers passed via `store_dict` are the caller's + responsibility and are stored as-is. + """ + + supports_writes: bool = True + supports_deletes: bool = True + supports_listing: bool = True + + _store_dict: MutableMapping[str, Buffer] + + def __init__( + self, + store_dict: MutableMapping[str, Buffer] | None = None, + *, + read_only: bool = False, + ) -> None: + super().__init__(read_only=read_only) + if store_dict is None: + store_dict = {} + self._store_dict = store_dict + + def with_read_only(self, read_only: bool = False) -> MemoryStore: + # docstring inherited + return type(self)( + store_dict=self._store_dict, + read_only=read_only, + ) + + async def clear(self) -> None: + # docstring inherited + self._store_dict.clear() + + def __str__(self) -> str: + return f"memory://{id(self._store_dict)}" + + def __repr__(self) -> str: + return f"MemoryStore('{self}')" + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, type(self)) + and self._store_dict == other._store_dict + and self.read_only == other.read_only + ) + + # ------------------------------------------------------------------- + # Synchronous store methods + # ------------------------------------------------------------------- + + def get_sync( + self, + key: str, + *, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + if prototype is None: + prototype = default_buffer_prototype() + if not self._is_open: + self._is_open = True + assert isinstance(key, str) + try: + value = self._store_dict[key] + start, stop = _normalize_byte_range_index(value, byte_range) + return prototype.buffer.from_buffer(value[start:stop]) + except KeyError: + return None + + def set_sync(self, key: str, value: Buffer) -> None: + self._check_writable() + if not self._is_open: + self._is_open = True + assert isinstance(key, str) + if not isinstance(value, Buffer): + raise TypeError( + f"MemoryStore.set(): `value` must be a Buffer instance. Got an instance of {type(value)} instead." + ) + self._store_dict[key] = _copy_buffer(value) + + def delete_sync(self, key: str) -> None: + self._check_writable() + if not self._is_open: + self._is_open = True + try: + del self._store_dict[key] + except KeyError: + logger.debug("Key %s does not exist.", key) + + async def get( + self, + key: str, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + # docstring inherited + if prototype is None: + prototype = default_buffer_prototype() + if not self._is_open: + await self._open() + assert isinstance(key, str) + try: + value = self._store_dict[key] + start, stop = _normalize_byte_range_index(value, byte_range) + return prototype.buffer.from_buffer(value[start:stop]) + except KeyError: + return None + + async def get_partial_values( + self, + prototype: BufferPrototype, + key_ranges: Iterable[tuple[str, ByteRequest | None]], + ) -> list[Buffer | None]: + # docstring inherited + + # All the key-ranges arguments goes with the same prototype + async def _get(key: str, byte_range: ByteRequest | None) -> Buffer | None: + return await self.get(key, prototype=prototype, byte_range=byte_range) + + return await concurrent_map(key_ranges, _get, limit=None) + + async def exists(self, key: str) -> bool: + # docstring inherited + return key in self._store_dict + + async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: + # docstring inherited + self._check_writable() + await self._ensure_open() + assert isinstance(key, str) + if not isinstance(value, Buffer): + raise TypeError( + f"MemoryStore.set(): `value` must be a Buffer instance. Got an instance of {type(value)} instead." + ) + if byte_range is not None: + buf = self._store_dict[key] + buf[byte_range[0] : byte_range[1]] = value + self._store_dict[key] = buf + else: + self._store_dict[key] = _copy_buffer(value) + + async def set_if_not_exists(self, key: str, value: Buffer) -> None: + # docstring inherited + self._check_writable() + await self._ensure_open() + self._store_dict.setdefault(key, _copy_buffer(value)) + + async def delete(self, key: str) -> None: + # docstring inherited + self._check_writable() + try: + del self._store_dict[key] + except KeyError: + logger.debug("Key %s does not exist.", key) + + async def list(self) -> AsyncIterator[str]: + # docstring inherited + for key in self._store_dict: + yield key + + async def list_prefix(self, prefix: str) -> AsyncIterator[str]: + # docstring inherited + # note: we materialize all dict keys into a list here so we can mutate the dict in-place (e.g. in delete_prefix) + for key in list(self._store_dict): + if key.startswith(prefix): + yield key + + async def list_dir(self, prefix: str) -> AsyncIterator[str]: + # docstring inherited + prefix = prefix.rstrip("/") + + if prefix == "": + keys_unique = {k.split("/")[0] for k in self._store_dict} + else: + # Our dictionary doesn't contain directory markers, but we want to include + # a pseudo directory when there's a nested item and we're listing an + # intermediate level. + keys_unique = { + key.removeprefix(f"{prefix}/").split("/")[0] + for key in self._store_dict + if key.startswith(f"{prefix}/") and key not in {prefix, f"{prefix}/"} + } + + for key in keys_unique: + yield key + + +class GpuMemoryStore(MemoryStore): + """ + Store for GPU memory. + + Stores every chunk in GPU memory irrespective of the original location. + + The dictionary of buffers to initialize this memory store with *must* be + GPU Buffers. + + Writing data to this store through ``.set`` will move the buffer to the GPU + if necessary. + + Parameters + ---------- + store_dict : MutableMapping, optional + A mutable mapping with string keys and [zarr.core.buffer.gpu.Buffer][] + values. + read_only : bool + Whether to open the store in read-only mode. + """ + + _store_dict: MutableMapping[str, gpu.Buffer] # type: ignore[assignment] + + def __init__( + self, + store_dict: MutableMapping[str, gpu.Buffer] | None = None, + *, + read_only: bool = False, + ) -> None: + super().__init__(store_dict=store_dict, read_only=read_only) # type: ignore[arg-type] + + def __str__(self) -> str: + return f"gpumemory://{id(self._store_dict)}" + + def __repr__(self) -> str: + return f"GpuMemoryStore('{self}')" + + @classmethod + def from_dict(cls, store_dict: MutableMapping[str, Buffer]) -> Self: + """ + Create a GpuMemoryStore from a dictionary of buffers at any location. + + The dictionary backing the newly created ``GpuMemoryStore`` will not be + the same as ``store_dict``. + + Parameters + ---------- + store_dict : mapping + A mapping of strings keys to arbitrary Buffers. The buffer data + will be moved into a [`gpu.Buffer`][zarr.core.buffer.gpu.Buffer]. + + Returns + ------- + GpuMemoryStore + """ + gpu_store_dict = {k: gpu.Buffer.from_buffer(v) for k, v in store_dict.items()} + return cls(gpu_store_dict) + + async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: + # docstring inherited + self._check_writable() + assert isinstance(key, str) + if not isinstance(value, Buffer): + raise TypeError( + f"GpuMemoryStore.set(): `value` must be a Buffer instance. Got an instance of {type(value)} instead." + ) + # Convert to gpu.Buffer + gpu_value = value if isinstance(value, gpu.Buffer) else gpu.Buffer.from_buffer(value) + await super().set(key, gpu_value, byte_range=byte_range) + + def set_sync(self, key: str, value: Buffer) -> None: + # docstring inherited + self._check_writable() + assert isinstance(key, str) + if not isinstance(value, Buffer): + raise TypeError( + f"GpuMemoryStore.set(): `value` must be a Buffer instance. Got an instance of {type(value)} instead." + ) + # Convert to gpu.Buffer, mirroring `set` above: every value in this store's + # backing dict must be a gpu.Buffer, regardless of which API wrote it. + gpu_value = value if isinstance(value, gpu.Buffer) else gpu.Buffer.from_buffer(value) + super().set_sync(key, gpu_value) + + +# ----------------------------------------------------------------------------- +# ManagedMemoryStore and its registry +# ----------------------------------------------------------------------------- +# ManagedMemoryStore owns the lifecycle of its backing dict, enabling proper +# weakref-based tracking. This allows memory:// URLs to be resolved back to +# the store's dict within the same process. + + +class _ManagedStoreDict(dict[str, Buffer]): + """ + A dict subclass that supports weak references. + + Regular dicts don't support weakrefs, but we need to track managed store dicts + in a WeakValueDictionary so they can be garbage collected when no longer + referenced. This subclass adds the necessary __weakref__ slot. + """ + + __slots__ = ("__weakref__",) + + +class _ManagedStoreDictRegistry: + """ + Registry for managed store dicts. + + This registry is the source of truth for managed store dicts. It creates + new dicts, tracks them via weak references, and looks them up by name. + """ + + def __init__(self) -> None: + self._registry: weakref.WeakValueDictionary[str, _ManagedStoreDict] = ( + weakref.WeakValueDictionary() + ) + self._counter = 0 + self._lock = threading.Lock() + + def _generate_name(self) -> str: + """Generate a unique name for a store. + + Must be called while holding `self._lock`. + """ + name = str(self._counter) + self._counter += 1 + return name + + def get_or_create(self, name: str | None = None) -> tuple[_ManagedStoreDict, str]: + """ + Get an existing managed dict by name, or create a new one. + + Thread-safe: uses a lock to prevent TOCTOU races between + checking for an existing entry and inserting a new one. + + Parameters + ---------- + name : str | None + The name for the store. If None, a unique name is auto-generated. + If a store with this name already exists, returns the existing store. + Names cannot contain '/' characters. + + Returns + ------- + tuple[_ManagedStoreDict, str] + The store dict and its name. + + Raises + ------ + ValueError + If the name contains '/' characters. + """ + with self._lock: + if name is None: + name = self._generate_name() + elif "/" in name: + raise ValueError( + f"Store name cannot contain '/': {name!r}. " + "Use the 'path' parameter to specify a path within the store." + ) + + existing = self._registry.get(name) + if existing is not None: + return existing, name + + store_dict = _ManagedStoreDict() + self._registry[name] = store_dict + return store_dict, name + + def get(self, name: str) -> _ManagedStoreDict | None: + """ + Look up a managed store dict by name. + + Parameters + ---------- + name : str + The name of the store. + + Returns + ------- + _ManagedStoreDict | None + The store dict if found, None otherwise. + """ + return self._registry.get(name) + + +_managed_store_dict_registry = _ManagedStoreDictRegistry() + + +class ManagedMemoryStore(MemoryStore): + """ + A memory store that owns and manages the lifecycle of its backing dict. + + Unlike ``MemoryStore`` which accepts any ``MutableMapping``, this store + creates and owns its backing dict internally. This enables proper lifecycle + management and allows the store to be looked up by its ``memory://`` URL + within the same process. + + Parameters + ---------- + name : str | None + The name for this store, used in the ``memory://`` URL. If None, a unique + name is auto-generated. If a store with this name already exists, the + new store will share the same backing dict. + path : str + The root path for this store. All keys will be prefixed with this path. + read_only : bool + Whether the store is read-only. + + Attributes + ---------- + name : str + The name of this store. + path : str + The root path of this store. + + Notes + ----- + The backing dict is tracked via weak references and will be garbage collected + when no ``ManagedMemoryStore`` instances reference it. URLs pointing to a + garbage-collected store will fail to resolve. + + See Also + -------- + MemoryStore : A memory store that accepts any MutableMapping. + + Examples + -------- + >>> store = ManagedMemoryStore(name="my-data") + >>> str(store) + 'memory://my-data' + >>> # Later, resolve the URL back to the store's dict + >>> store2 = ManagedMemoryStore.from_url("memory://my-data") + >>> store2._store_dict is store._store_dict + True + >>> # Create a store with a path prefix + >>> store3 = ManagedMemoryStore.from_url("memory://my-data/subdir") + >>> store3.path + 'subdir' + """ + + _store_dict: _ManagedStoreDict + _name: str + path: str + + def __init__(self, name: str | None = None, *, path: str = "", read_only: bool = False) -> None: + # Skip MemoryStore.__init__ and call Store.__init__ directly + # because we manage _store_dict via the registry, not via a user-supplied + # MutableMapping. If MemoryStore.__init__ ever adds logic beyond setting + # _store_dict, that logic must be replicated here. + Store.__init__(self, read_only=read_only) + + # Get or create a managed dict from the registry + self._store_dict, self._name = _managed_store_dict_registry.get_or_create(name) + self.path = normalize_path(path) + + def __str__(self) -> str: + return _join_paths([f"memory://{self._name}", self.path]) + + def __repr__(self) -> str: + return f"ManagedMemoryStore('{self}')" + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, type(self)) + and self._store_dict is other._store_dict + and self.path == other.path + and self.read_only == other.read_only + ) + + @property + def name(self) -> str: + """The name of this store, used in the memory:// URL.""" + return self._name + + @classmethod + def _from_managed_dict( + cls, + managed_dict: _ManagedStoreDict, + name: str, + *, + path: str = "", + read_only: bool = False, + ) -> ManagedMemoryStore: + """Internal: create a store from an existing managed dict.""" + store = object.__new__(cls) + Store.__init__(store, read_only=read_only) + store._store_dict = managed_dict + store._name = name + store.path = normalize_path(path) + return store + + def with_read_only(self, read_only: bool = False) -> ManagedMemoryStore: + # docstring inherited + return type(self)._from_managed_dict( + self._store_dict, self._name, path=self.path, read_only=read_only + ) + + @classmethod + def from_url(cls, url: str, *, read_only: bool = False) -> ManagedMemoryStore: + """ + Create a ManagedMemoryStore from a memory:// URL. + + This looks up the backing dict in the process-wide registry and creates + a new store instance that shares the same dict. + + Parameters + ---------- + url : str + A URL like "memory://my-store" or "memory://my-store/path/to/data" + identifying the store and optional path prefix. + read_only : bool + Whether the new store should be read-only. + + Returns + ------- + ManagedMemoryStore + A store sharing the same backing dict as the original. + + Raises + ------ + ValueError + If the URL is not a valid memory:// URL or the store has been + garbage collected. + """ + parsed = parse_store_url(url) + if parsed.scheme != "memory": + raise ValueError( + f"Expected a 'memory://' URL, got scheme {parsed.scheme!r} in '{url}'." + ) + name = parsed.name or "" + managed_dict = _managed_store_dict_registry.get(name) + if managed_dict is None: + raise ValueError( + f"Memory store not found for URL '{url}'. " + "The store may have been garbage collected." + ) + return cls._from_managed_dict(managed_dict, name, path=parsed.path, read_only=read_only) + + # Override MemoryStore methods to use path prefix and check process + + def get_sync( + self, + key: str, + *, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + # docstring inherited + return super().get_sync( + _join_paths([self.path, key]), prototype=prototype, byte_range=byte_range + ) + + def set_sync(self, key: str, value: Buffer) -> None: + # docstring inherited + super().set_sync(_join_paths([self.path, key]), value) + + def delete_sync(self, key: str) -> None: + # docstring inherited + super().delete_sync(_join_paths([self.path, key])) + + async def get( + self, + key: str, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + # docstring inherited + return await super().get( + _join_paths([self.path, key]), prototype=prototype, byte_range=byte_range + ) + + # get_partial_values is intentionally NOT overridden here: MemoryStore.get_partial_values + # dispatches per-key through `self.get`, which already resolves to the override above. + # Re-prefixing the keys here as well would apply `self.path` twice. + + async def exists(self, key: str) -> bool: + # docstring inherited + return await super().exists(_join_paths([self.path, key])) + + async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: + # docstring inherited + return await super().set(_join_paths([self.path, key]), value, byte_range=byte_range) + + async def set_if_not_exists(self, key: str, value: Buffer) -> None: + # docstring inherited + return await super().set_if_not_exists(_join_paths([self.path, key]), value) + + async def delete(self, key: str) -> None: + # docstring inherited + return await super().delete(_join_paths([self.path, key])) + + async def list(self) -> AsyncIterator[str]: + # docstring inherited + prefix = f"{self.path}/" if self.path else "" + async for key in super().list(): + if key.startswith(prefix): + yield key.removeprefix(prefix) + + async def list_prefix(self, prefix: str) -> AsyncIterator[str]: + # docstring inherited + # Manual concatenation instead of _join_paths because we need "path/" + # as the prefix when prefix is empty (to list all keys under self.path) + full_prefix = f"{self.path}/{prefix}" if self.path else prefix + path_prefix = f"{self.path}/" if self.path else "" + async for key in super().list_prefix(full_prefix): + yield key.removeprefix(path_prefix) + + async def list_dir(self, prefix: str) -> AsyncIterator[str]: + # docstring inherited + full_prefix = _join_paths([self.path, prefix]) + async for key in super().list_dir(full_prefix): + yield key + + def __reduce__( + self, + ) -> tuple[type[ManagedMemoryStore], tuple[str | None], dict[str, Any]]: + """ + Support pickling of ManagedMemoryStore. + + On unpickle, the store will reconnect to an existing store with the same + name if one exists in the registry, or create a new empty store otherwise. + + Note that the backing dict data is NOT serialized - only the store's + identity (name, path, read_only) is preserved. If the original store has + been garbage collected, the unpickled store will have an empty dict. + + The current process ID is preserved so that cross-process unpickling can be + detected and will raise an error at unpickle time. + """ + return ( + self.__class__, + (self._name,), + { + "path": self.path, + "read_only": self.read_only, + "created_pid": os.getpid(), + }, + ) + + def __setstate__(self, state: dict[str, Any]) -> None: + """Restore state after unpickling. + + The pickle protocol calls ``cls(name)`` (via ``__reduce__``'s args) + then ``__setstate__(state)``. ``__init__`` already set up + ``_store_dict`` and ``_name`` from the registry β€” we just restore + path and read_only here. + """ + # Check for cross-process usage first, before mutating state + created_pid = state.get("created_pid") + if created_pid is not None and created_pid != os.getpid(): + raise RuntimeError( + f"ManagedMemoryStore '{self._name}' was created in process {created_pid} " + f"but is being unpickled in process {os.getpid()}. " + "ManagedMemoryStore instances cannot be shared across processes because " + "their backing dict is not serialized. Use a persistent store (e.g., " + "LocalStore, ZipStore) for cross-process data sharing." + ) + + self.path = normalize_path(state.get("path", "")) + # Use the Store-level _read_only attribute directly because + # Store.__init__ was already called by __init__ during unpickling + self._read_only = state.get("read_only", False) diff --git a/src/zarr/storage/_obstore.py b/src/zarr/storage/_obstore.py new file mode 100644 index 0000000000..b34a5f624d --- /dev/null +++ b/src/zarr/storage/_obstore.py @@ -0,0 +1,513 @@ +from __future__ import annotations + +import asyncio +import contextlib +import pickle +from collections import defaultdict +from itertools import chain +from operator import itemgetter +from typing import TYPE_CHECKING, Self, TypedDict + +from zarr.abc.store import ( + ByteRequest, + OffsetByteRequest, + RangeByteRequest, + Store, + SuffixByteRequest, +) +from zarr.core.common import concurrent_map +from zarr.core.config import config +from zarr.storage._utils import _relativize_path + +if TYPE_CHECKING: + from collections.abc import AsyncGenerator, Coroutine, Iterable, Sequence + from typing import Any + + from obstore import ListResult, ListStream, ObjectMeta, OffsetRange, SuffixRange + from obstore.store import ObjectStore as _UpstreamObjectStore + + from zarr.core.buffer import Buffer, BufferPrototype + +__all__ = ["ObjectStore"] + +_ALLOWED_EXCEPTIONS: tuple[type[Exception], ...] = ( + FileNotFoundError, + IsADirectoryError, + NotADirectoryError, +) + + +class ObjectStore[T_Store: "_UpstreamObjectStore"](Store): + """ + Store that uses obstore for fast read/write from AWS, GCP, Azure. + + Parameters + ---------- + store : obstore.store.ObjectStore + An obstore store instance that is set up with the proper credentials. + read_only : bool + Whether to open the store in read-only mode. + + Warnings + -------- + ObjectStore is experimental and subject to API changes without notice. Please + raise an issue with any comments/concerns about the store. + """ + + store: T_Store + """The underlying obstore instance.""" + + def __eq__(self, value: object) -> bool: + if not isinstance(value, ObjectStore): + return False + + if not self.read_only == value.read_only: + return False + + return self.store == value.store # type: ignore[no-any-return] + + def __init__(self, store: T_Store, *, read_only: bool = False) -> None: + if not store.__class__.__module__.startswith("obstore"): + raise TypeError(f"expected ObjectStore class, got {store!r}") + super().__init__(read_only=read_only) + self.store = store + + def with_read_only(self, read_only: bool = False) -> Self: + # docstring inherited + return type(self)( + store=self.store, + read_only=read_only, + ) + + def __str__(self) -> str: + return f"object_store://{self.store}" + + def __repr__(self) -> str: + return f"{type(self).__name__}({self})" + + def __getstate__(self) -> dict[Any, Any]: + state = self.__dict__.copy() + state["store"] = pickle.dumps(self.store) + return state + + def __setstate__(self, state: dict[Any, Any]) -> None: + state["store"] = pickle.loads(state["store"]) + self.__dict__.update(state) + + async def get( + self, key: str, prototype: BufferPrototype, byte_range: ByteRequest | None = None + ) -> Buffer | None: + # docstring inherited + import obstore as obs + + try: + if byte_range is None: + resp = await obs.get_async(self.store, key) + return prototype.buffer.from_bytes(await resp.bytes_async()) # type: ignore[arg-type] + elif isinstance(byte_range, RangeByteRequest): + bytes = await obs.get_range_async( + self.store, key, start=byte_range.start, end=byte_range.end + ) + return prototype.buffer.from_bytes(bytes) # type: ignore[arg-type] + elif isinstance(byte_range, OffsetByteRequest): + resp = await obs.get_async( + self.store, key, options={"range": {"offset": byte_range.offset}} + ) + return prototype.buffer.from_bytes(await resp.bytes_async()) # type: ignore[arg-type] + elif isinstance(byte_range, SuffixByteRequest): + # some object stores (Azure) don't support suffix requests. In this + # case, our workaround is to first get the length of the object and then + # manually request the byte range at the end. + try: + resp = await obs.get_async( + self.store, key, options={"range": {"suffix": byte_range.suffix}} + ) + return prototype.buffer.from_bytes(await resp.bytes_async()) # type: ignore[arg-type] + except obs.exceptions.NotSupportedError: + head_resp = await obs.head_async(self.store, key) + file_size = head_resp["size"] + suffix_len = byte_range.suffix + buffer = await obs.get_range_async( + self.store, + key, + start=file_size - suffix_len, + length=suffix_len, + ) + return prototype.buffer.from_bytes(buffer) # type: ignore[arg-type] + else: + raise ValueError(f"Unexpected byte_range, got {byte_range}") + except _ALLOWED_EXCEPTIONS: + return None + + async def get_partial_values( + self, + prototype: BufferPrototype, + key_ranges: Iterable[tuple[str, ByteRequest | None]], + ) -> list[Buffer | None]: + # docstring inherited + return await _get_partial_values(self.store, prototype=prototype, key_ranges=key_ranges) + + async def exists(self, key: str) -> bool: + # docstring inherited + import obstore as obs + + try: + await obs.head_async(self.store, key) + except FileNotFoundError: + return False + else: + return True + + @property + def supports_writes(self) -> bool: + # docstring inherited + return True + + async def set(self, key: str, value: Buffer) -> None: + # docstring inherited + import obstore as obs + + self._check_writable() + + buf = value.as_buffer_like() + await obs.put_async(self.store, key, buf) + + async def set_if_not_exists(self, key: str, value: Buffer) -> None: + # docstring inherited + import obstore as obs + + self._check_writable() + buf = value.as_buffer_like() + with contextlib.suppress(obs.exceptions.AlreadyExistsError): + await obs.put_async(self.store, key, buf, mode="create") + + @property + def supports_deletes(self) -> bool: + # docstring inherited + return True + + async def delete(self, key: str) -> None: + # docstring inherited + import obstore as obs + + self._check_writable() + + # Some obstore stores such as local filesystems, GCP and Azure raise an error + # when deleting a non-existent key, while others such as S3 and in-memory do + # not. We suppress the error to make the behavior consistent across all obstore + # stores. This is also in line with the behavior of the other Zarr store adapters. + with contextlib.suppress(FileNotFoundError): + await obs.delete_async(self.store, key) + + async def delete_dir(self, prefix: str) -> None: + # docstring inherited + import obstore as obs + + self._check_writable() + if prefix != "" and not prefix.endswith("/"): + prefix += "/" + + metas = await obs.list(self.store, prefix).collect_async() + keys = [(m["path"],) for m in metas] + await concurrent_map(keys, self.delete, limit=config.get("async.concurrency")) + + @property + def supports_listing(self) -> bool: + # docstring inherited + return True + + async def _list(self, prefix: str | None = None) -> AsyncGenerator[ObjectMeta, None]: + import obstore as obs + + objects: ListStream[Sequence[ObjectMeta]] = obs.list(self.store, prefix=prefix) + async for batch in objects: + for item in batch: + yield item + + def list(self) -> AsyncGenerator[str, None]: + # docstring inherited + return (obj["path"] async for obj in self._list()) + + def list_prefix(self, prefix: str) -> AsyncGenerator[str, None]: + # docstring inherited + return (obj["path"] async for obj in self._list(prefix)) + + def list_dir(self, prefix: str) -> AsyncGenerator[str, None]: + # docstring inherited + import obstore as obs + + coroutine = obs.list_with_delimiter_async(self.store, prefix=prefix) + return _transform_list_dir(coroutine, prefix) + + async def getsize(self, key: str) -> int: + # docstring inherited + import obstore as obs + + resp = await obs.head_async(self.store, key) + return resp["size"] + + async def getsize_prefix(self, prefix: str) -> int: + # docstring inherited + sizes = [obj["size"] async for obj in self._list(prefix=prefix)] + return sum(sizes) + + +async def _transform_list_dir( + list_result_coroutine: Coroutine[Any, Any, ListResult[Sequence[ObjectMeta]]], prefix: str +) -> AsyncGenerator[str, None]: + """ + Transform the result of list_with_delimiter into an async generator of paths. + """ + list_result = await list_result_coroutine + + # We assume that the underlying object-store implementation correctly handles the + # prefix, so we don't double-check that the returned results actually start with the + # given prefix. + prefix = prefix.rstrip("/") + for path in chain( + list_result["common_prefixes"], map(itemgetter("path"), list_result["objects"]) + ): + if prefix != "" and path == prefix: + continue + relpath = _relativize_path(path=path, prefix=prefix) + if relpath: + yield relpath + + +class _BoundedRequest(TypedDict): + """Range request with a known start and end byte. + + These requests can be multiplexed natively on the Rust side with + `obstore.get_ranges_async`. + """ + + original_request_index: int + """The positional index in the original key_ranges input""" + + start: int + """Start byte offset.""" + + end: int + """End byte offset.""" + + +class _OtherRequest(TypedDict): + """Offset or suffix range requests. + + These requests cannot be concurrent on the Rust side, and each need their own call + to `obstore.get_async`, passing in the `range` parameter. + """ + + original_request_index: int + """The positional index in the original key_ranges input""" + + path: str + """The path to request from.""" + + range: OffsetRange | None + # Note: suffix requests are handled separately because some object stores (Azure) + # don't support them + """The range request type.""" + + +class _SuffixRequest(TypedDict): + """Offset or suffix range requests. + + These requests cannot be concurrent on the Rust side, and each need their own call + to `obstore.get_async`, passing in the `range` parameter. + """ + + original_request_index: int + """The positional index in the original key_ranges input""" + + path: str + """The path to request from.""" + + range: SuffixRange + """The suffix range.""" + + +class _Response(TypedDict): + """A response buffer associated with the original index that it should be restored to.""" + + original_request_index: int + """The positional index in the original key_ranges input""" + + buffer: Buffer + """The buffer returned from obstore's range request.""" + + +async def _make_bounded_requests( + store: _UpstreamObjectStore, + path: str, + requests: list[_BoundedRequest], + prototype: BufferPrototype, + semaphore: asyncio.Semaphore, +) -> list[_Response]: + """Make all bounded requests for a specific file. + + `obstore.get_ranges_async` allows for making concurrent requests for multiple ranges + within a single file, and will e.g. merge concurrent requests. This only uses one + single Python coroutine. + """ + import obstore as obs + + starts = [r["start"] for r in requests] + ends = [r["end"] for r in requests] + async with semaphore: + responses = await obs.get_ranges_async(store, path=path, starts=starts, ends=ends) + + buffer_responses: list[_Response] = [] + for request, response in zip(requests, responses, strict=True): + buffer_responses.append( + { + "original_request_index": request["original_request_index"], + "buffer": prototype.buffer.from_bytes(response), # type: ignore[arg-type] + } + ) + + return buffer_responses + + +async def _make_other_request( + store: _UpstreamObjectStore, + request: _OtherRequest, + prototype: BufferPrototype, + semaphore: asyncio.Semaphore, +) -> list[_Response]: + """Make offset or full-file requests. + + We return a `list[_Response]` for symmetry with `_make_bounded_requests` so that all + futures can be gathered together. + """ + import obstore as obs + + async with semaphore: + if request["range"] is None: + resp = await obs.get_async(store, request["path"]) + else: + resp = await obs.get_async(store, request["path"], options={"range": request["range"]}) + buffer = await resp.bytes_async() + + return [ + { + "original_request_index": request["original_request_index"], + "buffer": prototype.buffer.from_bytes(buffer), # type: ignore[arg-type] + } + ] + + +async def _make_suffix_request( + store: _UpstreamObjectStore, + request: _SuffixRequest, + prototype: BufferPrototype, + semaphore: asyncio.Semaphore, +) -> list[_Response]: + """Make suffix requests. + + This is separated out from `_make_other_request` because some object stores (Azure) + don't support suffix requests. In this case, our workaround is to first get the + length of the object and then manually request the byte range at the end. + + We return a `list[_Response]` for symmetry with `_make_bounded_requests` so that all + futures can be gathered together. + """ + import obstore as obs + + async with semaphore: + try: + resp = await obs.get_async(store, request["path"], options={"range": request["range"]}) + buffer = await resp.bytes_async() + except obs.exceptions.NotSupportedError: + head_resp = await obs.head_async(store, request["path"]) + file_size = head_resp["size"] + suffix_len = request["range"]["suffix"] + buffer = await obs.get_range_async( + store, + request["path"], + start=file_size - suffix_len, + length=suffix_len, + ) + + return [ + { + "original_request_index": request["original_request_index"], + "buffer": prototype.buffer.from_bytes(buffer), # type: ignore[arg-type] + } + ] + + +async def _get_partial_values( + store: _UpstreamObjectStore, + prototype: BufferPrototype, + key_ranges: Iterable[tuple[str, ByteRequest | None]], +) -> list[Buffer | None]: + """Make multiple range requests. + + ObjectStore has a `get_ranges` method that will additionally merge nearby ranges, + but it's _per_ file. So we need to split these key_ranges into **per-file** key + ranges, and then reassemble the results in the original order. + + We separate into different requests: + + - One call to `obstore.get_ranges_async` **per target file** + - One call to `obstore.get_async` for each other request. + """ + key_ranges = list(key_ranges) + per_file_bounded_requests: dict[str, list[_BoundedRequest]] = defaultdict(list) + other_requests: list[_OtherRequest] = [] + suffix_requests: list[_SuffixRequest] = [] + + for idx, (path, byte_range) in enumerate(key_ranges): + if byte_range is None: + other_requests.append( + { + "original_request_index": idx, + "path": path, + "range": None, + } + ) + elif isinstance(byte_range, RangeByteRequest): + per_file_bounded_requests[path].append( + {"original_request_index": idx, "start": byte_range.start, "end": byte_range.end} + ) + elif isinstance(byte_range, OffsetByteRequest): + other_requests.append( + { + "original_request_index": idx, + "path": path, + "range": {"offset": byte_range.offset}, + } + ) + elif isinstance(byte_range, SuffixByteRequest): + suffix_requests.append( + { + "original_request_index": idx, + "path": path, + "range": {"suffix": byte_range.suffix}, + } + ) + else: + raise ValueError(f"Unsupported range input: {byte_range}") + + semaphore = asyncio.Semaphore(config.get("async.concurrency")) + + futs: list[Coroutine[Any, Any, list[_Response]]] = [] + for path, bounded_ranges in per_file_bounded_requests.items(): + futs.append( + _make_bounded_requests(store, path, bounded_ranges, prototype, semaphore=semaphore) + ) + + for request in other_requests: + futs.append(_make_other_request(store, request, prototype, semaphore=semaphore)) # noqa: PERF401 + + for suffix_request in suffix_requests: + futs.append(_make_suffix_request(store, suffix_request, prototype, semaphore=semaphore)) # noqa: PERF401 + + buffers: list[Buffer | None] = [None] * len(key_ranges) + + for responses in await asyncio.gather(*futs): + for resp in responses: + buffers[resp["original_request_index"]] = resp["buffer"] + + return buffers diff --git a/src/zarr/storage/_utils.py b/src/zarr/storage/_utils.py new file mode 100644 index 0000000000..ca10b0679e --- /dev/null +++ b/src/zarr/storage/_utils.py @@ -0,0 +1,305 @@ +from __future__ import annotations + +import importlib +import re +from pathlib import Path, PureWindowsPath +from urllib.parse import urlparse + +if importlib.util.find_spec("upath"): + # Re-exported for zarr.storage._common, which needs it to recognize UPath store_like values. + # The redundant-looking alias is the explicit re-export mypy requires under strict mode. + from upath.core import UPath as UPath # noqa: PLC0414 +else: + + class UPath: # type: ignore[no-redef] + pass + + +import sys +from typing import TYPE_CHECKING, NamedTuple + +from zarr.abc.store import OffsetByteRequest, RangeByteRequest, SuffixByteRequest + +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping + + from zarr.abc.store import ByteRequest + from zarr.core.buffer import Buffer + + +class ParsedStoreUrl(NamedTuple): + """ + Parsed components of a store URL. + + Attributes + ---------- + scheme : str + The URL scheme (e.g., "memory", "file", "s3"). Empty string for local paths. + name : str | None + The store name/host component. For memory:// URLs this is the store name. + None if empty. + path : str + The path component within the store. + raw : str + The original URL string. + """ + + scheme: str + name: str | None + path: str + raw: str + + +def parse_store_url(url: str) -> ParsedStoreUrl: + """ + Parse a store URL into its components. + + Parameters + ---------- + url : str + A URL like "memory://store-name/path" or "s3://bucket/key" or a local path. + + Returns + ------- + ParsedStoreUrl + Named tuple with scheme, name, path, and raw URL. + + Examples + -------- + >>> parse_store_url("memory://mystore") + ParsedStoreUrl(scheme='memory', name='mystore', path='', raw='memory://mystore') + + >>> parse_store_url("memory://mystore/path/to/data") + ParsedStoreUrl(scheme='memory', name='mystore', path='path/to/data', raw='memory://mystore/path/to/data') + + >>> parse_store_url("s3://bucket/key") + ParsedStoreUrl(scheme='s3', name='bucket', path='key', raw='s3://bucket/key') + + >>> parse_store_url("/local/path") + ParsedStoreUrl(scheme='', name=None, path='/local/path', raw='/local/path') + + Note that ``memory://name/path`` and ``memory:///path`` are different: + the first has ``name="name"`` and ``path="path"``, while the second has + ``name=None`` and ``path="/path"`` (no host component between ``//`` and ``/``). + """ + # On Windows, bare paths like "C:\foo" or "C:/foo" cause urlparse to + # misinterpret the drive letter as a URL scheme. Detect this early and + # return a local-path result without going through urlparse. + if sys.platform == "win32" and PureWindowsPath(url).drive: + return ParsedStoreUrl(scheme="", name=None, path=url, raw=url) + + parsed = urlparse(url) + + # netloc is the "host" part (store name for memory://, bucket for s3://, etc.) + name = parsed.netloc or None + + # For URLs with a scheme and netloc (like memory://store/path or s3://bucket/key), + # strip the leading slash from the path component. + # For local paths (no scheme), preserve the path as-is. + if parsed.scheme and parsed.netloc: + path = parsed.path.lstrip("/") + else: + path = parsed.path + + return ParsedStoreUrl(scheme=parsed.scheme, name=name, path=path, raw=url) + + +def normalize_path(path: str | bytes | Path | None) -> str: + if path is None: + result = "" + elif isinstance(path, bytes): + result = str(path, "ascii") + + # handle pathlib.Path + + elif isinstance(path, Path | UPath): + result = str(path) + + elif isinstance(path, str): + result = path + + else: + raise TypeError(f'Object {path} has an invalid type for "path": {type(path).__name__}') + + # convert backslash to forward slash + result = result.replace("\\", "/") + + # remove leading and trailing slashes + result = result.strip("/") + + # collapse any repeated slashes + pat = re.compile(r"//+") + result = pat.sub("/", result) + + # disallow path segments with just '.' or '..' + segments = result.split("/") + if any(s in {".", ".."} for s in segments): + raise ValueError( + f"The path {path!r} is invalid because its string representation contains '.' or '..' segments." + ) + + return result + + +def _normalize_byte_range_index(data: Buffer, byte_range: ByteRequest | None) -> tuple[int, int]: + """ + Convert a ByteRequest into an explicit start and stop + """ + if byte_range is None: + start = 0 + stop = len(data) + 1 + elif isinstance(byte_range, RangeByteRequest): + start = byte_range.start + stop = byte_range.end + elif isinstance(byte_range, OffsetByteRequest): + start = byte_range.offset + stop = len(data) + 1 + elif isinstance(byte_range, SuffixByteRequest): + start = max(0, len(data) - byte_range.suffix) + stop = len(data) + 1 + else: + raise ValueError(f"Unexpected byte_range, got {byte_range}.") + return (start, stop) + + +def _join_paths(paths: Iterable[str]) -> str: + """ + Filter out instances of '' and join the remaining strings with '/'. + + Parameters + ---------- + paths : Iterable[str] + + Returns + ------- + str + + Examples + -------- + ```python + from zarr.storage._utils import _join_paths + _join_paths(["", "a", "b"]) + # 'a/b' + _join_paths(["a", "b", "c"]) + # 'a/b/c' + ``` + """ + return "/".join(filter(lambda v: v != "", paths)) + + +def _dereference_path(root: str, path: str) -> str: + """ + Combine a store-side root with a key into a single fully-qualified path. + + Unlike `_join_paths`, this is purpose-built for the case where `root` is + an opaque backend-side prefix that may use `"/"` as a sentinel for "root + of the filesystem" (notably for fsspec's `ReferenceFileSystem`). A + trailing `"/"` is stripped from `root` before joining; if `root` is then + empty, the bare `path` is returned so that joining `"/"` with `"key"` + yields `"key"` rather than `"//key"`. A trailing `"/"` on the result is + also stripped. + + Leading slashes on `root` are preserved -- a backend-side path like + `"/home/foo/data.zarr"` is an absolute filesystem path for + `LocalFileSystem` and must not lose its leading separator. + + Parameters + ---------- + root : str + The backend-side root of a store. May be `""`, `"/"`, an absolute + filesystem path, or a backend-specific prefix. + path : str + The key within the store, typically a zarr key like `"zarr.json"` + or `"a/b/c/zarr.json"`. + + Returns + ------- + str + `root` and `path` joined by a single `"/"`, with the `"/"` sentinel + collapsed and trailing slashes removed. + + Examples + -------- + ```python + from zarr.storage._utils import _dereference_path + _dereference_path("/", "zarr.json") # 'zarr.json' + _dereference_path("", "zarr.json") # 'zarr.json' + _dereference_path("/home/foo", "zarr.json") # '/home/foo/zarr.json' + _dereference_path("/home/foo/", "zarr.json") # '/home/foo/zarr.json' + _dereference_path("bucket/p", "zarr.json") # 'bucket/p/zarr.json' + ``` + """ + root = root.rstrip("/") + path = f"{root}/{path}" if root else path + return path.rstrip("/") + + +def _relativize_path(*, path: str, prefix: str) -> str: + """ + Make a "/"-delimited path relative to some prefix. If the prefix is '', then the path is + returned as-is. Otherwise, the prefix is removed from the path as well as the separator + string "/". + + If ``prefix`` is not the empty string and ``path`` does not start with ``prefix`` + followed by a "/" character, then an error is raised. + + This function assumes that the prefix does not end with "/". + + Parameters + ---------- + path : str + The path to make relative to the prefix. + prefix : str + The prefix to make the path relative to. + + Returns + ------- + str + + Examples + -------- + ```python + from zarr.storage._utils import _relativize_path + _relativize_path(path="a/b", prefix="") + # 'a/b' + _relativize_path(path="a/b/c", prefix="a/b") + # 'c' + ``` + """ + if prefix == "": + return path + else: + _prefix = f"{prefix}/" + if not path.startswith(_prefix): + raise ValueError(f"The first component of {path} does not start with {prefix}.") + return path.removeprefix(_prefix) + + +def _normalize_paths(paths: Iterable[str]) -> tuple[str, ...]: + """ + Normalize the input paths according to the normalization scheme used for zarr node paths. + If any two paths normalize to the same value, raise a ValueError. + """ + path_map: dict[str, str] = {} + for path in paths: + parsed = normalize_path(path) + if parsed in path_map: + msg = ( + f"After normalization, the value '{path}' collides with '{path_map[parsed]}'. " + f"Both '{path}' and '{path_map[parsed]}' normalize to the same value: '{parsed}'. " + f"You should use either '{path}' or '{path_map[parsed]}', but not both." + ) + raise ValueError(msg) + path_map[parsed] = path + return tuple(path_map.keys()) + + +def _normalize_path_keys[T](data: Mapping[str, T]) -> dict[str, T]: + """ + Normalize the keys of the input dict according to the normalization scheme used for zarr node + paths. If any two keys in the input normalize to the same value, raise a ValueError. + Returns a dict where the keys are the elements of the input and the values are the + normalized form of each key. + """ + parsed_keys = _normalize_paths(data.keys()) + return dict(zip(parsed_keys, data.values(), strict=True)) diff --git a/src/zarr/storage/_wrapper.py b/src/zarr/storage/_wrapper.py new file mode 100644 index 0000000000..6f498a655d --- /dev/null +++ b/src/zarr/storage/_wrapper.py @@ -0,0 +1,218 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, cast + +if TYPE_CHECKING: + from collections.abc import AsyncGenerator, AsyncIterator, Iterable, Sequence + from types import TracebackType + from typing import Any, Self + + from zarr.abc.buffer import Buffer + from zarr.abc.store import ByteRequest + from zarr.core.buffer import BufferPrototype + +from zarr.abc.store import ( + Store, + SupportsDeleteSync, + SupportsGetSync, + SupportsSetSync, + _store_supports_sync_io, +) + + +class WrapperStore[T_Store: Store](Store): + """ + Store that wraps an existing Store. + + By default all of the store methods are delegated to the wrapped store instance, which is + accessible via the ``._store`` attribute of this class. + + Use this class to modify or extend the behavior of the other store classes. + """ + + _store: T_Store + + def __init__(self, store: T_Store) -> None: + self._store = store + + def _with_store(self, store: T_Store) -> Self: + """ + Constructs a new instance of the wrapper store with the same details but a new store. + """ + return type(self)(store=store) + + @classmethod + async def open(cls: type[Self], store_cls: type[T_Store], *args: Any, **kwargs: Any) -> Self: + store = store_cls(*args, **kwargs) + await store._open() + return cls(store=store) + + def with_read_only(self, read_only: bool = False) -> Self: + return self._with_store(cast(T_Store, self._store.with_read_only(read_only))) + + def __enter__(self) -> Self: + return self._with_store(self._store.__enter__()) + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + return self._store.__exit__(exc_type, exc_value, traceback) + + async def _open(self) -> None: + await self._store._open() + + async def _ensure_open(self) -> None: + await self._store._ensure_open() + + async def is_empty(self, prefix: str) -> bool: + return await self._store.is_empty(prefix) + + @property + def _is_open(self) -> bool: + return self._store._is_open + + @_is_open.setter + def _is_open(self, value: bool) -> None: + raise NotImplementedError("WrapperStore must be opened via the `_open` method") + + async def clear(self) -> None: + return await self._store.clear() + + @property + def read_only(self) -> bool: + return self._store.read_only + + def _check_writable(self) -> None: + return self._store._check_writable() + + def __eq__(self, value: object) -> bool: + return type(self) is type(value) and self._store.__eq__(value._store) + + def __str__(self) -> str: + return f"wrapping-{self._store}" + + def __repr__(self) -> str: + return f"WrapperStore({self._store.__class__.__name__}, '{self._store}')" + + async def get( + self, key: str, prototype: BufferPrototype, byte_range: ByteRequest | None = None + ) -> Buffer | None: + return await self._store.get(key, prototype, byte_range) + + async def get_partial_values( + self, + prototype: BufferPrototype, + key_ranges: Iterable[tuple[str, ByteRequest | None]], + ) -> list[Buffer | None]: + return await self._store.get_partial_values(prototype, key_ranges) + + async def get_ranges( + self, + key: str, + byte_ranges: Sequence[ByteRequest | None], + *, + prototype: BufferPrototype, + max_concurrency: int | None = None, + max_gap_bytes: int | None = None, + max_coalesced_bytes: int | None = None, + ) -> AsyncIterator[Sequence[tuple[int, Buffer | None]]]: + """Forward `get_ranges` to the wrapped store. + + Default values for the coalescing kwargs are not declared here; the + wrapped store decides them. `None` means "don't override the wrapped + store's default". + """ + kwargs: dict[str, int] = {} + if max_concurrency is not None: + kwargs["max_concurrency"] = max_concurrency + if max_gap_bytes is not None: + kwargs["max_gap_bytes"] = max_gap_bytes + if max_coalesced_bytes is not None: + kwargs["max_coalesced_bytes"] = max_coalesced_bytes + async for group in self._store.get_ranges(key, byte_ranges, prototype=prototype, **kwargs): + yield group + + async def exists(self, key: str) -> bool: + return await self._store.exists(key) + + async def set(self, key: str, value: Buffer) -> None: + await self._store.set(key, value) + + async def set_if_not_exists(self, key: str, value: Buffer) -> None: + return await self._store.set_if_not_exists(key, value) + + async def _set_many(self, values: Iterable[tuple[str, Buffer]]) -> None: + await self._store._set_many(values) + + @property + def supports_writes(self) -> bool: + return self._store.supports_writes + + @property + def supports_deletes(self) -> bool: + return self._store.supports_deletes + + @property + def _supports_sync_io(self) -> bool: + # The delegating `*_sync` methods below make every wrapper structurally + # satisfy `SupportsSyncStore`; whether they can actually run depends on + # the wrapped store, so forward its capability (see + # `zarr.abc.store._store_supports_sync_io`). + return _store_supports_sync_io(self._store) + + def get_sync( + self, + key: str, + *, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + """Forward `get_sync` to the wrapped store.""" + if not isinstance(self._store, SupportsGetSync): + raise TypeError(f"Store {type(self._store).__name__} does not support synchronous get.") + return self._store.get_sync(key, prototype=prototype, byte_range=byte_range) # type: ignore[unreachable] + + def set_sync(self, key: str, value: Buffer) -> None: + """Forward `set_sync` to the wrapped store.""" + if not isinstance(self._store, SupportsSetSync): + raise TypeError(f"Store {type(self._store).__name__} does not support synchronous set.") + self._store.set_sync(key, value) # type: ignore[unreachable] + + def delete_sync(self, key: str) -> None: + """Forward `delete_sync` to the wrapped store.""" + if not isinstance(self._store, SupportsDeleteSync): + raise TypeError( + f"Store {type(self._store).__name__} does not support synchronous delete." + ) + self._store.delete_sync(key) # type: ignore[unreachable] + + async def delete(self, key: str) -> None: + await self._store.delete(key) + + @property + def supports_listing(self) -> bool: + return self._store.supports_listing + + def list(self) -> AsyncIterator[str]: + return self._store.list() + + def list_prefix(self, prefix: str) -> AsyncIterator[str]: + return self._store.list_prefix(prefix) + + def list_dir(self, prefix: str) -> AsyncIterator[str]: + return self._store.list_dir(prefix) + + async def delete_dir(self, prefix: str) -> None: + return await self._store.delete_dir(prefix) + + def close(self) -> None: + self._store.close() + + async def _get_many( + self, requests: Iterable[tuple[str, BufferPrototype, ByteRequest | None]] + ) -> AsyncGenerator[tuple[str, Buffer | None], None]: + async for req in self._store._get_many(requests): + yield req diff --git a/src/zarr/storage/_zip.py b/src/zarr/storage/_zip.py new file mode 100644 index 0000000000..69ae18bc2c --- /dev/null +++ b/src/zarr/storage/_zip.py @@ -0,0 +1,402 @@ +from __future__ import annotations + +import io +import os +import shutil +import threading +import time +import zipfile +from pathlib import Path +from typing import IO, TYPE_CHECKING, Any, Literal + +from zarr.abc.store import ( + ByteRequest, + OffsetByteRequest, + RangeByteRequest, + Store, + SuffixByteRequest, +) +from zarr.core.buffer import Buffer, BufferPrototype + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Iterable + +ZipStoreAccessModeLiteral = Literal["r", "w", "a"] + + +class _RawReaderAdapter(io.RawIOBase): + """ + Adapt a minimal seekable reader to the `io` interface `zipfile` needs. + + Some file-like objects (e.g. `obstore.ReadableFile`) implement + `read`/`seek`/`tell` but are not `io.IOBase` instances, and their + `read` may return a buffer-protocol object rather than `bytes`. + Wrapping in this adapter plus `io.BufferedReader` yields real `bytes`. + + Reads are clamped to the bytes remaining before EOF: some readers + (obstore < 0.6) raise on short reads rather than returning fewer bytes. + The size is cached, which is safe because the adapter is only used for + read-only access. + """ + + def __init__(self, fileobj: IO[bytes]) -> None: + self._fileobj = fileobj + self._size: int | None = None + + def _get_size(self) -> int: + if self._size is None: + pos = self._fileobj.tell() + self._size = self._fileobj.seek(0, os.SEEK_END) + self._fileobj.seek(pos) + return self._size + + def readable(self) -> bool: + return True + + def seekable(self) -> bool: + return True + + def seek(self, pos: int, whence: int = 0) -> int: + return self._fileobj.seek(pos, whence) + + def tell(self) -> int: + return self._fileobj.tell() + + def readinto(self, b: Any) -> int: + n_requested = min(len(b), self._get_size() - self._fileobj.tell()) + if n_requested <= 0: + return 0 + data = self._fileobj.read(n_requested) + n = len(data) + b[:n] = memoryview(data) + return n + + +class ZipStore(Store): + """ + Store using a ZIP file. + + Parameters + ---------- + path : str, Path, or IO[bytes] + Location of file, or an open binary file object. A file object must + support `read`, `seek`, and `tell`; objects that are not `io.IOBase` + instances (e.g. an `obstore` reader) are adapted automatically but + can only be used for reading (`mode="r"`). The file object must stay + open for the lifetime of the store, and operations that require a + filesystem location (`clear`, `move`, pickling) are not supported. + mode : str, optional + One of 'r' to read an existing file, 'w' to truncate and write a new + file, 'a' to append to an existing file, or 'x' to exclusively create + and write a new file. + compression : int, optional + Compression method to use when writing to the archive. + allowZip64 : bool, optional + If True (the default) will create ZIP files that use the ZIP64 + extensions when the zipfile is larger than 2 GiB. If False + will raise an exception when the ZIP file would require ZIP64 + extensions. + + Attributes + ---------- + allowed_exceptions + supports_writes + supports_deletes + supports_listing + path + compression + allowZip64 + """ + + supports_writes: bool = True + supports_deletes: bool = False + supports_listing: bool = True + + path: Path | None + compression: int + allowZip64: bool + + _zf: zipfile.ZipFile + _lock: threading.RLock + _fileobj: IO[bytes] | None + + def __init__( + self, + path: Path | str | IO[bytes], + *, + mode: ZipStoreAccessModeLiteral = "r", + read_only: bool | None = None, + compression: int = zipfile.ZIP_STORED, + allowZip64: bool = True, + ) -> None: + if read_only is None: + read_only = mode == "r" + + super().__init__(read_only=read_only) + + if isinstance(path, str): + path = Path(path) + if isinstance(path, Path): + self.path = path # root? + self._fileobj = None + else: + self.path = None + if not isinstance(path, io.IOBase): + if not all( + callable(getattr(path, attr, None)) for attr in ("read", "seek", "tell") + ): + raise TypeError( + f"expected a path or an open binary file object supporting " + f"read/seek/tell, got {type(path).__name__}" + ) + if mode != "r": + raise TypeError( + f"a file object that is not an io.IOBase instance can only be " + f"opened for reading (mode='r', got mode={mode!r})" + ) + # e.g. an obstore ReadableFile: readable and seekable, but + # not an io object and reads may not return bytes + path = io.BufferedReader(_RawReaderAdapter(path)) + self._fileobj = path + + self._zmode = mode + self.compression = compression + self.allowZip64 = allowZip64 + + def _sync_open(self) -> None: + if self._is_open: + raise ValueError("store is already open") + + self._lock = threading.RLock() + + self._zf = zipfile.ZipFile( + self.path if self.path is not None else self._fileobj, # type: ignore[arg-type] + mode=self._zmode, + compression=self.compression, + allowZip64=self.allowZip64, + ) + + self._is_open = True + + async def _open(self) -> None: + self._sync_open() + + def __getstate__(self) -> dict[str, Any]: + if self.path is None: + # A path-backed store pickles its path and reopens the file on + # unpickling; an open file object cannot be serialized that way. + raise TypeError( + "cannot pickle a ZipStore backed by a file-like object; " + "construct the store from a path instead" + ) + # We need a copy to not modify the state of the original store + state = self.__dict__.copy() + for attr in ["_zf", "_lock"]: + state.pop(attr, None) + return state + + def __setstate__(self, state: dict[str, Any]) -> None: + self.__dict__ = state + self._is_open = False + self._sync_open() + + def close(self) -> None: + # docstring inherited + if not self._is_open: + return + super().close() + with self._lock: + self._zf.close() + + async def clear(self) -> None: + # docstring inherited + with self._lock: + self._check_writable() + if self.path is None: + raise NotImplementedError( + "clear() is not supported for a ZipStore backed by a file-like object" + ) + self._zf.close() + os.remove(self.path) + self._zf = zipfile.ZipFile( + self.path, mode="w", compression=self.compression, allowZip64=self.allowZip64 + ) + + def __str__(self) -> str: + if self.path is None: + return f"zip://{self._fileobj!r}" + return f"zip://{self.path}" + + def __repr__(self) -> str: + return f"ZipStore('{self}')" + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, type(self)) + and self.path == other.path + and self._fileobj is other._fileobj + ) + + def _get( + self, + key: str, + prototype: BufferPrototype, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + if not self._is_open: + self._sync_open() + # docstring inherited + try: + with self._zf.open(key) as f: # will raise KeyError + if byte_range is None: + return prototype.buffer.from_bytes(f.read()) + elif isinstance(byte_range, RangeByteRequest): + f.seek(byte_range.start) + return prototype.buffer.from_bytes(f.read(byte_range.end - f.tell())) + size = f.seek(0, os.SEEK_END) + if isinstance(byte_range, OffsetByteRequest): + f.seek(byte_range.offset) + elif isinstance(byte_range, SuffixByteRequest): + f.seek(max(0, size - byte_range.suffix)) + else: + raise TypeError(f"Unexpected byte_range, got {byte_range}.") + return prototype.buffer.from_bytes(f.read()) + except KeyError: + return None + + async def get( + self, + key: str, + prototype: BufferPrototype, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + # docstring inherited + assert isinstance(key, str) + + with self._lock: + return self._get(key, prototype=prototype, byte_range=byte_range) + + async def get_partial_values( + self, + prototype: BufferPrototype, + key_ranges: Iterable[tuple[str, ByteRequest | None]], + ) -> list[Buffer | None]: + # docstring inherited + out = [] + with self._lock: + for key, byte_range in key_ranges: + out.append(self._get(key, prototype=prototype, byte_range=byte_range)) + return out + + def _set(self, key: str, value: Buffer) -> None: + if not self._is_open: + self._sync_open() + # generally, this should be called inside a lock + keyinfo = zipfile.ZipInfo(filename=key, date_time=time.localtime(time.time())[:6]) + keyinfo.compress_type = self.compression + if keyinfo.filename[-1] == os.sep: + keyinfo.external_attr = 0o40775 << 16 # drwxrwxr-x + keyinfo.external_attr |= 0x10 # MS-DOS directory flag + else: + keyinfo.external_attr = 0o644 << 16 # ?rw-r--r-- + self._zf.writestr(keyinfo, value.to_bytes()) + + async def set(self, key: str, value: Buffer) -> None: + # docstring inherited + self._check_writable() + if not self._is_open: + self._sync_open() + assert isinstance(key, str) + if not isinstance(value, Buffer): + raise TypeError( + f"ZipStore.set(): `value` must be a Buffer instance. Got an instance of {type(value)} instead." + ) + with self._lock: + self._set(key, value) + + async def set_if_not_exists(self, key: str, value: Buffer) -> None: + self._check_writable() + with self._lock: + members = self._zf.namelist() + if key not in members: + self._set(key, value) + + async def delete_dir(self, prefix: str) -> None: + # only raise NotImplementedError if any keys are found + self._check_writable() + if prefix != "" and not prefix.endswith("/"): + prefix += "/" + async for _ in self.list_prefix(prefix): + raise NotImplementedError + + async def delete(self, key: str) -> None: + # docstring inherited + # we choose to only raise NotImplementedError here if the key exists + # this allows the array/group APIs to avoid the overhead of existence checks + self._check_writable() + if await self.exists(key): + raise NotImplementedError + + async def exists(self, key: str) -> bool: + # docstring inherited + if not self._is_open: + self._sync_open() + with self._lock: + try: + self._zf.getinfo(key) + except KeyError: + return False + else: + return True + + async def list(self) -> AsyncIterator[str]: + # docstring inherited + if not self._is_open: + self._sync_open() + with self._lock: + for key in self._zf.namelist(): + yield key + + async def list_prefix(self, prefix: str) -> AsyncIterator[str]: + # docstring inherited + async for key in self.list(): + if key.startswith(prefix): + yield key + + async def list_dir(self, prefix: str) -> AsyncIterator[str]: + # docstring inherited + if not self._is_open: + self._sync_open() + prefix = prefix.rstrip("/") + + keys = self._zf.namelist() + seen = set() + if prefix == "": + keys_unique = {k.split("/")[0] for k in keys} + for key in keys_unique: + if key not in seen: + seen.add(key) + yield key + else: + for key in keys: + if key.startswith(f"{prefix}/") and key.strip("/") != prefix: + k = key.removeprefix(f"{prefix}/").split("/")[0] + if k not in seen: + seen.add(k) + yield k + + async def move(self, path: Path | str) -> None: + """ + Move the store to another path. + """ + if self.path is None: + raise NotImplementedError( + "move() is not supported for a ZipStore backed by a file-like object" + ) + if isinstance(path, str): + path = Path(path) + self.close() + os.makedirs(path.parent, exist_ok=True) + shutil.move(self.path, path) + self.path = path + await self._open() diff --git a/src/zarr/store/__init__.py b/src/zarr/store/__init__.py deleted file mode 100644 index fbdcdb9255..0000000000 --- a/src/zarr/store/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from zarr.store.core import StoreLike, StorePath, make_store_path -from zarr.store.local import LocalStore -from zarr.store.memory import MemoryStore -from zarr.store.remote import RemoteStore - -__all__ = ["StorePath", "StoreLike", "make_store_path", "RemoteStore", "LocalStore", "MemoryStore"] diff --git a/src/zarr/store/core.py b/src/zarr/store/core.py deleted file mode 100644 index fa35879308..0000000000 --- a/src/zarr/store/core.py +++ /dev/null @@ -1,260 +0,0 @@ -from __future__ import annotations - -import json -from pathlib import Path -from typing import Any, Literal - -from zarr.abc.store import AccessMode, Store -from zarr.buffer import Buffer, BufferPrototype, default_buffer_prototype -from zarr.common import ZARR_JSON, ZARRAY_JSON, ZGROUP_JSON, AccessModeLiteral, ZarrFormat -from zarr.errors import ContainsArrayAndGroupError, ContainsArrayError, ContainsGroupError -from zarr.store.local import LocalStore -from zarr.store.memory import MemoryStore - - -def _dereference_path(root: str, path: str) -> str: - assert isinstance(root, str) - assert isinstance(path, str) - root = root.rstrip("/") - path = f"{root}/{path}" if root else path - path = path.rstrip("/") - return path - - -class StorePath: - store: Store - path: str - - def __init__(self, store: Store, path: str | None = None): - self.store = store - self.path = path or "" - - async def get( - self, - prototype: BufferPrototype | None = None, - byte_range: tuple[int, int | None] | None = None, - ) -> Buffer | None: - if prototype is None: - prototype = default_buffer_prototype() - return await self.store.get(self.path, prototype=prototype, byte_range=byte_range) - - async def set(self, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: - if byte_range is not None: - raise NotImplementedError("Store.set does not have partial writes yet") - await self.store.set(self.path, value) - - async def delete(self) -> None: - await self.store.delete(self.path) - - async def exists(self) -> bool: - return await self.store.exists(self.path) - - def __truediv__(self, other: str) -> StorePath: - return self.__class__(self.store, _dereference_path(self.path, other)) - - def __str__(self) -> str: - return _dereference_path(str(self.store), self.path) - - def __repr__(self) -> str: - return f"StorePath({self.store.__class__.__name__}, {str(self)!r})" - - def __eq__(self, other: Any) -> bool: - try: - if self.store == other.store and self.path == other.path: - return True - except Exception: - pass - return False - - -StoreLike = Store | StorePath | Path | str - - -async def make_store_path( - store_like: StoreLike | None, *, mode: AccessModeLiteral | None = None -) -> StorePath: - if isinstance(store_like, StorePath): - if mode is not None: - assert AccessMode.from_literal(mode) == store_like.store.mode - return store_like - elif isinstance(store_like, Store): - if mode is not None: - assert AccessMode.from_literal(mode) == store_like.mode - await store_like._ensure_open() - return StorePath(store_like) - elif store_like is None: - if mode is None: - mode = "w" # exception to the default mode = 'r' - return StorePath(await MemoryStore.open(mode=mode)) - elif isinstance(store_like, Path): - return StorePath(await LocalStore.open(root=store_like, mode=mode or "r")) - elif isinstance(store_like, str): - return StorePath(await LocalStore.open(root=Path(store_like), mode=mode or "r")) - raise TypeError - - -async def ensure_no_existing_node(store_path: StorePath, zarr_format: ZarrFormat) -> None: - """ - Check if a store_path is safe for array / group creation. - Returns `None` or raises an exception. - - Parameters - ---------- - store_path: StorePath - The storage location to check. - zarr_format: ZarrFormat - The Zarr format to check. - - Raises - ------ - ContainsArrayError, ContainsGroupError, ContainsArrayAndGroupError - """ - if zarr_format == 2: - extant_node = await _contains_node_v2(store_path) - elif zarr_format == 3: - extant_node = await _contains_node_v3(store_path) - - if extant_node == "array": - raise ContainsArrayError(store_path.store, store_path.path) - elif extant_node == "group": - raise ContainsGroupError(store_path.store, store_path.path) - elif extant_node == "nothing": - return - msg = f"Invalid value for extant_node: {extant_node}" # type: ignore[unreachable] - raise ValueError(msg) - - -async def _contains_node_v3(store_path: StorePath) -> Literal["array", "group", "nothing"]: - """ - Check if a store_path contains nothing, an array, or a group. This function - returns the string "array", "group", or "nothing" to denote containing an array, a group, or - nothing. - - Parameters - ---------- - store_path: StorePath - The location in storage to check. - - Returns - ------- - Literal["array", "group", "nothing"] - A string representing the zarr node found at store_path. - """ - result: Literal["array", "group", "nothing"] = "nothing" - extant_meta_bytes = await (store_path / ZARR_JSON).get() - # if no metadata document could be loaded, then we just return "nothing" - if extant_meta_bytes is not None: - try: - extant_meta_json = json.loads(extant_meta_bytes.to_bytes()) - # avoid constructing a full metadata document here in the name of speed. - if extant_meta_json["node_type"] == "array": - result = "array" - elif extant_meta_json["node_type"] == "group": - result = "group" - except (KeyError, json.JSONDecodeError): - # either of these errors is consistent with no array or group present. - pass - return result - - -async def _contains_node_v2(store_path: StorePath) -> Literal["array", "group", "nothing"]: - """ - Check if a store_path contains nothing, an array, a group, or both. If both an array and a - group are detected, a `ContainsArrayAndGroup` exception is raised. Otherwise, this function - returns the string "array", "group", or "nothing" to denote containing an array, a group, or - nothing. - - Parameters - ---------- - store_path: StorePath - The location in storage to check. - - Returns - ------- - Literal["array", "group", "nothing"] - A string representing the zarr node found at store_path. - """ - _array = await contains_array(store_path=store_path, zarr_format=2) - _group = await contains_group(store_path=store_path, zarr_format=2) - - if _array and _group: - raise ContainsArrayAndGroupError(store_path.store, store_path.path) - elif _array: - return "array" - elif _group: - return "group" - else: - return "nothing" - - -async def contains_array(store_path: StorePath, zarr_format: ZarrFormat) -> bool: - """ - Check if an array exists at a given StorePath. - - Parameters - ---------- - store_path: StorePath - The StorePath to check for an existing group. - zarr_format: - The zarr format to check for. - - Returns - ------- - bool - True if the StorePath contains a group, False otherwise. - - """ - if zarr_format == 3: - extant_meta_bytes = await (store_path / ZARR_JSON).get() - if extant_meta_bytes is None: - return False - else: - try: - extant_meta_json = json.loads(extant_meta_bytes.to_bytes()) - # we avoid constructing a full metadata document here in the name of speed. - if extant_meta_json["node_type"] == "array": - return True - except (ValueError, KeyError): - return False - elif zarr_format == 2: - result = await (store_path / ZARRAY_JSON).exists() - return result - msg = f"Invalid zarr_format provided. Got {zarr_format}, expected 2 or 3" - raise ValueError(msg) - - -async def contains_group(store_path: StorePath, zarr_format: ZarrFormat) -> bool: - """ - Check if a group exists at a given StorePath. - - Parameters - ---------- - - store_path: StorePath - The StorePath to check for an existing group. - zarr_format: - The zarr format to check for. - - Returns - ------- - - bool - True if the StorePath contains a group, False otherwise - - """ - if zarr_format == 3: - extant_meta_bytes = await (store_path / ZARR_JSON).get() - if extant_meta_bytes is None: - return False - else: - try: - extant_meta_json = json.loads(extant_meta_bytes.to_bytes()) - # we avoid constructing a full metadata document here in the name of speed. - result: bool = extant_meta_json["node_type"] == "group" - return result - except (ValueError, KeyError): - return False - elif zarr_format == 2: - return await (store_path / ZGROUP_JSON).exists() - msg = f"Invalid zarr_format provided. Got {zarr_format}, expected 2 or 3" # type: ignore[unreachable] - raise ValueError(msg) diff --git a/src/zarr/store/local.py b/src/zarr/store/local.py deleted file mode 100644 index 25fd9fc13a..0000000000 --- a/src/zarr/store/local.py +++ /dev/null @@ -1,227 +0,0 @@ -from __future__ import annotations - -import io -import os -import shutil -from collections.abc import AsyncGenerator -from pathlib import Path - -from zarr.abc.store import Store -from zarr.buffer import Buffer, BufferPrototype -from zarr.common import AccessModeLiteral, concurrent_map, to_thread - - -def _get( - path: Path, prototype: BufferPrototype, byte_range: tuple[int | None, int | None] | None -) -> Buffer: - """ - Fetch a contiguous region of bytes from a file. - - Parameters - ---------- - path: Path - The file to read bytes from. - byte_range: tuple[int, int | None] | None = None - The range of bytes to read. If `byte_range` is `None`, then the entire file will be read. - If `byte_range` is a tuple, the first value specifies the index of the first byte to read, - and the second value specifies the total number of bytes to read. If the total value is - `None`, then the entire file after the first byte will be read. - """ - if byte_range is not None: - if byte_range[0] is None: - start = 0 - else: - start = byte_range[0] - - end = (start + byte_range[1]) if byte_range[1] is not None else None - else: - return prototype.buffer.from_bytes(path.read_bytes()) - with path.open("rb") as f: - size = f.seek(0, io.SEEK_END) - if start is not None: - if start >= 0: - f.seek(start) - else: - f.seek(max(0, size + start)) - if end is not None: - if end < 0: - end = size + end - return prototype.buffer.from_bytes(f.read(end - f.tell())) - return prototype.buffer.from_bytes(f.read()) - - -def _put( - path: Path, - value: Buffer, - start: int | None = None, -) -> int | None: - path.parent.mkdir(parents=True, exist_ok=True) - if start is not None: - with path.open("r+b") as f: - f.seek(start) - f.write(value.as_numpy_array().tobytes()) - return None - else: - return path.write_bytes(value.as_numpy_array().tobytes()) - - -class LocalStore(Store): - supports_writes: bool = True - supports_partial_writes: bool = True - supports_listing: bool = True - - root: Path - - def __init__(self, root: Path | str, *, mode: AccessModeLiteral = "r"): - super().__init__(mode=mode) - if isinstance(root, str): - root = Path(root) - assert isinstance(root, Path) - self.root = root - - async def clear(self) -> None: - self._check_writable() - shutil.rmtree(self.root) - self.root.mkdir() - - async def empty(self) -> bool: - try: - subpaths = os.listdir(self.root) - return not subpaths - except FileNotFoundError: - return True - - def __str__(self) -> str: - return f"file://{self.root}" - - def __repr__(self) -> str: - return f"LocalStore({str(self)!r})" - - def __eq__(self, other: object) -> bool: - return isinstance(other, type(self)) and self.root == other.root - - async def get( - self, - key: str, - prototype: BufferPrototype, - byte_range: tuple[int | None, int | None] | None = None, - ) -> Buffer | None: - if not self._is_open: - await self._open() - assert isinstance(key, str) - path = self.root / key - - try: - return await to_thread(_get, path, prototype, byte_range) - except (FileNotFoundError, IsADirectoryError, NotADirectoryError): - return None - - async def get_partial_values( - self, - prototype: BufferPrototype, - key_ranges: list[tuple[str, tuple[int | None, int | None]]], - ) -> list[Buffer | None]: - """ - Read byte ranges from multiple keys. - - Parameters - ---------- - key_ranges: List[Tuple[str, Tuple[int, int]]] - A list of (key, (start, length)) tuples. The first element of the tuple is the name of - the key in storage to fetch bytes from. The second element the tuple defines the byte - range to retrieve. These values are arguments to `get`, as this method wraps - concurrent invocation of `get`. - """ - args = [] - for key, byte_range in key_ranges: - assert isinstance(key, str) - path = self.root / key - args.append((_get, path, prototype, byte_range)) - return await concurrent_map(args, to_thread, limit=None) # TODO: fix limit - - async def set(self, key: str, value: Buffer) -> None: - if not self._is_open: - await self._open() - self._check_writable() - assert isinstance(key, str) - if not isinstance(value, Buffer): - raise TypeError("LocalStore.set(): `value` must a Buffer instance") - path = self.root / key - await to_thread(_put, path, value) - - async def set_partial_values(self, key_start_values: list[tuple[str, int, bytes]]) -> None: - self._check_writable() - args = [] - for key, start, value in key_start_values: - assert isinstance(key, str) - path = self.root / key - args.append((_put, path, value, start)) - await concurrent_map(args, to_thread, limit=None) # TODO: fix limit - - async def delete(self, key: str) -> None: - self._check_writable() - path = self.root / key - if path.is_dir(): # TODO: support deleting directories? shutil.rmtree? - shutil.rmtree(path) - else: - await to_thread(path.unlink, True) # Q: we may want to raise if path is missing - - async def exists(self, key: str) -> bool: - path = self.root / key - return await to_thread(path.is_file) - - async def list(self) -> AsyncGenerator[str, None]: - """Retrieve all keys in the store. - - Returns - ------- - AsyncGenerator[str, None] - """ - to_strip = str(self.root) + "/" - for p in list(self.root.rglob("*")): - if p.is_file(): - yield str(p).replace(to_strip, "") - - async def list_prefix(self, prefix: str) -> AsyncGenerator[str, None]: - """Retrieve all keys in the store with a given prefix. - - Parameters - ---------- - prefix : str - - Returns - ------- - AsyncGenerator[str, None] - """ - for p in (self.root / prefix).rglob("*"): - if p.is_file(): - yield str(p) - - to_strip = str(self.root) + "/" - for p in (self.root / prefix).rglob("*"): - if p.is_file(): - yield str(p).replace(to_strip, "") - - async def list_dir(self, prefix: str) -> AsyncGenerator[str, None]: - """ - Retrieve all keys and prefixes with a given prefix and which do not contain the character - β€œ/” after the given prefix. - - Parameters - ---------- - prefix : str - - Returns - ------- - AsyncGenerator[str, None] - """ - - base = self.root / prefix - to_strip = str(base) + "/" - - try: - key_iter = base.iterdir() - for key in key_iter: - yield str(key).replace(to_strip, "") - except (FileNotFoundError, NotADirectoryError): - pass diff --git a/src/zarr/store/memory.py b/src/zarr/store/memory.py deleted file mode 100644 index dd3e52e703..0000000000 --- a/src/zarr/store/memory.py +++ /dev/null @@ -1,117 +0,0 @@ -from __future__ import annotations - -from collections.abc import AsyncGenerator, MutableMapping - -from zarr.abc.store import Store -from zarr.buffer import Buffer, BufferPrototype -from zarr.common import AccessModeLiteral, concurrent_map -from zarr.store.utils import _normalize_interval_index - - -# TODO: this store could easily be extended to wrap any MutableMapping store from v2 -# When that is done, the `MemoryStore` will just be a store that wraps a dict. -class MemoryStore(Store): - supports_writes: bool = True - supports_partial_writes: bool = True - supports_listing: bool = True - - _store_dict: MutableMapping[str, Buffer] - - def __init__( - self, - store_dict: MutableMapping[str, Buffer] | None = None, - *, - mode: AccessModeLiteral = "r", - ): - super().__init__(mode=mode) - self._store_dict = store_dict or {} - - async def empty(self) -> bool: - return not self._store_dict - - async def clear(self) -> None: - self._store_dict.clear() - - def __str__(self) -> str: - return f"memory://{id(self._store_dict)}" - - def __repr__(self) -> str: - return f"MemoryStore({str(self)!r})" - - async def get( - self, - key: str, - prototype: BufferPrototype, - byte_range: tuple[int | None, int | None] | None = None, - ) -> Buffer | None: - if not self._is_open: - await self._open() - assert isinstance(key, str) - try: - value = self._store_dict[key] - start, length = _normalize_interval_index(value, byte_range) - return prototype.buffer.from_buffer(value[start : start + length]) - except KeyError: - return None - - async def get_partial_values( - self, - prototype: BufferPrototype, - key_ranges: list[tuple[str, tuple[int | None, int | None]]], - ) -> list[Buffer | None]: - # All the key-ranges arguments goes with the same prototype - async def _get(key: str, byte_range: tuple[int, int | None]) -> Buffer | None: - return await self.get(key, prototype=prototype, byte_range=byte_range) - - vals = await concurrent_map(key_ranges, _get, limit=None) - return vals - - async def exists(self, key: str) -> bool: - return key in self._store_dict - - async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: - if not self._is_open: - await self._open() - self._check_writable() - assert isinstance(key, str) - if not isinstance(value, Buffer): - raise TypeError(f"Expected Buffer. Got {type(value)}.") - - if byte_range is not None: - buf = self._store_dict[key] - buf[byte_range[0] : byte_range[1]] = value - self._store_dict[key] = buf - else: - self._store_dict[key] = value - - async def delete(self, key: str) -> None: - self._check_writable() - try: - del self._store_dict[key] - except KeyError: - pass # Q(JH): why not raise? - - async def set_partial_values(self, key_start_values: list[tuple[str, int, bytes]]) -> None: - raise NotImplementedError - - async def list(self) -> AsyncGenerator[str, None]: - for key in self._store_dict: - yield key - - async def list_prefix(self, prefix: str) -> AsyncGenerator[str, None]: - for key in self._store_dict: - if key.startswith(prefix): - yield key - - async def list_dir(self, prefix: str) -> AsyncGenerator[str, None]: - if prefix.endswith("/"): - prefix = prefix[:-1] - - if prefix == "": - keys_unique = set(k.split("/")[0] for k in self._store_dict.keys()) - for key in keys_unique: - yield key - else: - for key in self._store_dict: - if key.startswith(prefix + "/") and key != prefix: - yield key.removeprefix(prefix + "/").split("/")[0] diff --git a/src/zarr/store/remote.py b/src/zarr/store/remote.py deleted file mode 100644 index c742d9e567..0000000000 --- a/src/zarr/store/remote.py +++ /dev/null @@ -1,209 +0,0 @@ -from __future__ import annotations - -from collections.abc import AsyncGenerator -from typing import TYPE_CHECKING, Any - -import fsspec - -from zarr.abc.store import Store -from zarr.buffer import BufferPrototype -from zarr.common import AccessModeLiteral -from zarr.store.core import _dereference_path - -if TYPE_CHECKING: - from fsspec.asyn import AsyncFileSystem - from upath import UPath - - from zarr.buffer import Buffer, BufferPrototype - from zarr.common import BytesLike - - -class RemoteStore(Store): - # based on FSSpec - supports_writes: bool = True - supports_partial_writes: bool = False - supports_listing: bool = True - - _fs: AsyncFileSystem - _url: str - path: str - allowed_exceptions: tuple[type[Exception], ...] - - def __init__( - self, - url: UPath | str, - mode: AccessModeLiteral = "r", - allowed_exceptions: tuple[type[Exception], ...] = ( - FileNotFoundError, - IsADirectoryError, - NotADirectoryError, - ), - **storage_options: Any, - ): - """ - Parameters - ---------- - url: root of the datastore. In fsspec notation, this is usually like "protocol://path/to". - Can also be a upath.UPath instance/ - allowed_exceptions: when fetching data, these cases will be deemed to correspond to missing - keys, rather than some other IO failure - storage_options: passed on to fsspec to make the filesystem instance. If url is a UPath, - this must not be used. - """ - super().__init__(mode=mode) - if isinstance(url, str): - self._url = url.rstrip("/") - self._fs, _path = fsspec.url_to_fs(url, **storage_options) - self.path = _path.rstrip("/") - elif hasattr(url, "protocol") and hasattr(url, "fs"): - # is UPath-like - but without importing - if storage_options: - raise ValueError( - "If constructed with a UPath object, no additional " - "storage_options are allowed" - ) - # n.b. UPath returns the url and path attributes with a trailing /, at least for s3 - # that trailing / must be removed to compose with the store interface - self._url = str(url).rstrip("/") - self.path = url.path.rstrip("/") - self._fs = url.fs - else: - raise ValueError(f"URL not understood, {url}") - self.allowed_exceptions = allowed_exceptions - # test instantiate file system - if not self._fs.async_impl: - raise TypeError("FileSystem needs to support async operations") - - async def clear(self) -> None: - try: - for subpath in await self._fs._find(self.path, withdirs=True): - if subpath != self.path: - await self._fs._rm(subpath, recursive=True) - except FileNotFoundError: - pass - - async def empty(self) -> bool: - return not await self._fs._find(self.path, withdirs=True) - - def __str__(self) -> str: - return f"{self._url}" - - def __repr__(self) -> str: - return f"" - - async def get( - self, - key: str, - prototype: BufferPrototype, - byte_range: tuple[int | None, int | None] | None = None, - ) -> Buffer | None: - if not self._is_open: - await self._open() - path = _dereference_path(self.path, key) - - try: - if byte_range: - # fsspec uses start/end, not start/length - start, length = byte_range - if start is not None and length is not None: - end = start + length - elif length is not None: - end = length - else: - end = None - value = prototype.buffer.from_bytes( - await ( - self._fs._cat_file(path, start=byte_range[0], end=end) - if byte_range - else self._fs._cat_file(path) - ) - ) - return value - - except self.allowed_exceptions: - return None - except OSError as e: - if "not satisfiable" in str(e): - # this is an s3-specific condition we probably don't want to leak - return prototype.buffer.from_bytes(b"") - raise - - async def set( - self, - key: str, - value: Buffer, - byte_range: tuple[int, int] | None = None, - ) -> None: - if not self._is_open: - await self._open() - self._check_writable() - path = _dereference_path(self.path, key) - # write data - if byte_range: - raise NotImplementedError - await self._fs._pipe_file(path, value.to_bytes()) - - async def delete(self, key: str) -> None: - self._check_writable() - path = _dereference_path(self.path, key) - try: - await self._fs._rm(path) - except FileNotFoundError: - pass - except self.allowed_exceptions: - pass - - async def exists(self, key: str) -> bool: - path = _dereference_path(self.path, key) - exists: bool = await self._fs._exists(path) - return exists - - async def get_partial_values( - self, - prototype: BufferPrototype, - key_ranges: list[tuple[str, tuple[int | None, int | None]]], - ) -> list[Buffer | None]: - if key_ranges: - paths, starts, stops = zip( - *( - ( - _dereference_path(self.path, k[0]), - k[1][0], - ((k[1][0] or 0) + k[1][1]) if k[1][1] is not None else None, - ) - for k in key_ranges - ), - strict=False, - ) - else: - return [] - # TODO: expectations for exceptions or missing keys? - res = await self._fs._cat_ranges(list(paths), starts, stops, on_error="return") - # the following is an s3-specific condition we probably don't want to leak - res = [b"" if (isinstance(r, OSError) and "not satisfiable" in str(r)) else r for r in res] - for r in res: - if isinstance(r, Exception) and not isinstance(r, self.allowed_exceptions): - raise r - - return [None if isinstance(r, Exception) else prototype.buffer.from_bytes(r) for r in res] - - async def set_partial_values(self, key_start_values: list[tuple[str, int, BytesLike]]) -> None: - raise NotImplementedError - - async def list(self) -> AsyncGenerator[str, None]: - allfiles = await self._fs._find(self.path, detail=False, withdirs=False) - for onefile in (a.replace(self.path + "/", "") for a in allfiles): - yield onefile - - async def list_dir(self, prefix: str) -> AsyncGenerator[str, None]: - prefix = f"{self.path}/{prefix.rstrip('/')}" - try: - allfiles = await self._fs._ls(prefix, detail=False) - except FileNotFoundError: - return - for onefile in (a.replace(prefix + "/", "") for a in allfiles): - yield onefile - - async def list_prefix(self, prefix: str) -> AsyncGenerator[str, None]: - for onefile in await self._fs._ls(prefix, detail=False): - yield onefile diff --git a/src/zarr/store/utils.py b/src/zarr/store/utils.py deleted file mode 100644 index 17c9234221..0000000000 --- a/src/zarr/store/utils.py +++ /dev/null @@ -1,25 +0,0 @@ -from zarr.buffer import Buffer - - -def _normalize_interval_index( - data: Buffer, interval: None | tuple[int | None, int | None] -) -> tuple[int, int]: - """ - Convert an implicit interval into an explicit start and length - """ - if interval is None: - start = 0 - length = len(data) - else: - maybe_start, maybe_len = interval - if maybe_start is None: - start = 0 - else: - start = maybe_start - - if maybe_len is None: - length = len(data) - start - else: - length = maybe_len - - return (start, length) diff --git a/src/zarr/strategies.py b/src/zarr/strategies.py deleted file mode 100644 index 91a8542ce9..0000000000 --- a/src/zarr/strategies.py +++ /dev/null @@ -1,145 +0,0 @@ -from typing import Any - -import hypothesis.extra.numpy as npst -import hypothesis.strategies as st -import numpy as np -from hypothesis import given, settings # noqa - -from .array import Array -from .group import Group -from .store import MemoryStore, StoreLike - -# Copied from Xarray -_attr_keys = st.text(st.characters(), min_size=1) -_attr_values = st.recursive( - st.none() | st.booleans() | st.text(st.characters(), max_size=5), - lambda children: st.lists(children) | st.dictionaries(_attr_keys, children), - max_leaves=3, -) - -# From https://zarr-specs.readthedocs.io/en/latest/v3/core/v3.0.html#node-names -# 1. must not be the empty string ("") -# 2. must not include the character "/" -# 3. must not be a string composed only of period characters, e.g. "." or ".." -# 4. must not start with the reserved prefix "__" -zarr_key_chars = st.sampled_from( - ".-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz" -) -node_names = st.text(zarr_key_chars, min_size=1).filter( - lambda t: t not in (".", "..") and not t.startswith("__") -) -array_names = node_names -attrs = st.none() | st.dictionaries(_attr_keys, _attr_values) -paths = st.lists(node_names, min_size=1).map(lambda x: "/".join(x)) | st.just("/") -np_arrays = npst.arrays( - # TODO: re-enable timedeltas once they are supported - dtype=npst.scalar_dtypes().filter(lambda x: x.kind != "m"), - shape=npst.array_shapes(max_dims=4), -) -stores = st.builds(MemoryStore, st.just({}), mode=st.just("w")) -compressors = st.sampled_from([None, "default"]) - - -@st.composite # type: ignore[misc] -def np_array_and_chunks( - draw: st.DrawFn, *, arrays: st.SearchStrategy[np.ndarray] = np_arrays -) -> tuple[np.ndarray, tuple[int]]: # type: ignore[type-arg] - """A hypothesis strategy to generate small sized random arrays. - - Returns: a tuple of the array and a suitable random chunking for it. - """ - array = draw(arrays) - # We want this strategy to shrink towards arrays with smaller number of chunks - # 1. st.integers() shrinks towards smaller values. So we use that to generate number of chunks - numchunks = draw(st.tuples(*[st.integers(min_value=1, max_value=size) for size in array.shape])) - # 2. and now generate the chunks tuple - chunks = tuple(size // nchunks for size, nchunks in zip(array.shape, numchunks, strict=True)) - return (array, chunks) - - -@st.composite # type: ignore[misc] -def arrays( - draw: st.DrawFn, - *, - compressors: st.SearchStrategy = compressors, - stores: st.SearchStrategy[StoreLike] = stores, - arrays: st.SearchStrategy[np.ndarray] = np_arrays, - paths: st.SearchStrategy[None | str] = paths, - array_names: st.SearchStrategy = array_names, - attrs: st.SearchStrategy = attrs, -) -> Array: - store = draw(stores) - nparray, chunks = draw(np_array_and_chunks(arrays=arrays)) - path = draw(paths) - name = draw(array_names) - attributes = draw(attrs) - # compressor = draw(compressors) - - # TODO: clean this up - # if path is None and name is None: - # array_path = None - # array_name = None - # elif path is None and name is not None: - # array_path = f"{name}" - # array_name = f"/{name}" - # elif path is not None and name is None: - # array_path = path - # array_name = None - # elif path == "/": - # assert name is not None - # array_path = name - # array_name = "/" + name - # else: - # assert name is not None - # array_path = f"{path}/{name}" - # array_name = "/" + array_path - - expected_attrs = {} if attributes is None else attributes - - array_path = path + ("/" if not path.endswith("/") else "") + name - root = Group.create(store) - fill_value_args: tuple[Any, ...] = tuple() - if nparray.dtype.kind == "M": - fill_value_args = ("ns",) - - a = root.create_array( - array_path, - shape=nparray.shape, - chunks=chunks, - dtype=nparray.dtype.str, - attributes=attributes, - # compressor=compressor, # TODO: FIXME - fill_value=nparray.dtype.type(0, *fill_value_args), - ) - - assert isinstance(a, Array) - assert nparray.shape == a.shape - assert chunks == a.chunks - assert array_path == a.path, (path, name, array_path, a.name, a.path) - # assert array_path == a.name, (path, name, array_path, a.name, a.path) - # assert a.basename is None # TODO - # assert a.store == normalize_store_arg(store) - assert dict(a.attrs) == expected_attrs - - a[:] = nparray - - return a - - -def is_negative_slice(idx: Any) -> bool: - return isinstance(idx, slice) and idx.step is not None and idx.step < 0 - - -@st.composite # type: ignore[misc] -def basic_indices(draw: st.DrawFn, *, shape: tuple[int], **kwargs): # type: ignore[no-untyped-def] - """Basic indices without unsupported negative slices.""" - return draw( - npst.basic_indices(shape=shape, **kwargs).filter( - lambda idxr: ( - not ( - is_negative_slice(idxr) - or (isinstance(idxr, tuple) and any(is_negative_slice(idx) for idx in idxr)) - ) - ) - ) - ) diff --git a/src/zarr/sync.py b/src/zarr/sync.py deleted file mode 100644 index 8af14f602e..0000000000 --- a/src/zarr/sync.py +++ /dev/null @@ -1,130 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING, TypeVar - -if TYPE_CHECKING: - from collections.abc import AsyncIterator, Coroutine - from typing import Any - -import asyncio -import threading -from concurrent.futures import wait - -from typing_extensions import ParamSpec - -from zarr.config import config - -P = ParamSpec("P") -T = TypeVar("T") - -# From https://github.com/fsspec/filesystem_spec/blob/master/fsspec/asyn.py - -iothread: list[threading.Thread | None] = [None] # dedicated IO thread -loop: list[asyncio.AbstractEventLoop | None] = [ - None -] # global event loop for any non-async instance -_lock: threading.Lock | None = None # global lock placeholder -get_running_loop = asyncio.get_running_loop - - -class SyncError(Exception): - pass - - -def _get_lock() -> threading.Lock: - """Allocate or return a threading lock. - - The lock is allocated on first use to allow setting one lock per forked process. - """ - global _lock - if not _lock: - _lock = threading.Lock() - return _lock - - -async def _runner(coro: Coroutine[Any, Any, T]) -> T | BaseException: - """ - Await a coroutine and return the result of running it. If awaiting the coroutine raises an - exception, the exception will be returned. - """ - try: - return await coro - except Exception as ex: - return ex - - -def sync( - coro: Coroutine[Any, Any, T], - loop: asyncio.AbstractEventLoop | None = None, - timeout: float | None = None, -) -> T: - """ - Make loop run coroutine until it returns. Runs in other thread - - Examples - -------- - >>> sync(async_function(), existing_loop) - """ - if loop is None: - # NB: if the loop is not running *yet*, it is OK to submit work - # and we will wait for it - loop = _get_loop() - if not isinstance(loop, asyncio.AbstractEventLoop): - raise TypeError(f"loop cannot be of type {type(loop)}") - if loop.is_closed(): - raise RuntimeError("Loop is not running") - try: - loop0 = asyncio.events.get_running_loop() - if loop0 is loop: - raise SyncError("Calling sync() from within a running loop") - except RuntimeError: - pass - - future = asyncio.run_coroutine_threadsafe(_runner(coro), loop) - - finished, unfinished = wait([future], return_when=asyncio.ALL_COMPLETED, timeout=timeout) - if len(unfinished) > 0: - raise asyncio.TimeoutError(f"Coroutine {coro} failed to finish in within {timeout}s") - assert len(finished) == 1 - return_result = next(iter(finished)).result() - - if isinstance(return_result, BaseException): - raise return_result - else: - return return_result - - -def _get_loop() -> asyncio.AbstractEventLoop: - """Create or return the default fsspec IO loop - - The loop will be running on a separate thread. - """ - if loop[0] is None: - with _get_lock(): - # repeat the check just in case the loop got filled between the - # previous two calls from another thread - if loop[0] is None: - new_loop = asyncio.new_event_loop() - loop[0] = new_loop - th = threading.Thread(target=new_loop.run_forever, name="zarrIO") - th.daemon = True - th.start() - iothread[0] = th - assert loop[0] is not None - return loop[0] - - -class SyncMixin: - def _sync(self, coroutine: Coroutine[Any, Any, T]) -> T: - # TODO: refactor this to to take *args and **kwargs and pass those to the method - # this should allow us to better type the sync wrapper - return sync( - coroutine, - timeout=config.get("async.timeout"), - ) - - def _sync_iter(self, async_iterator: AsyncIterator[T]) -> list[T]: - async def iter_to_list() -> list[T]: - return [item async for item in async_iterator] - - return self._sync(iter_to_list()) diff --git a/src/zarr/testing/__init__.py b/src/zarr/testing/__init__.py index 35b91f9167..823c508052 100644 --- a/src/zarr/testing/__init__.py +++ b/src/zarr/testing/__init__.py @@ -1,9 +1,29 @@ import importlib.util import warnings +from typing import TYPE_CHECKING + +from zarr.errors import ZarrUserWarning if importlib.util.find_spec("pytest") is not None: from zarr.testing.store import StoreTests + from zarr.testing.utils import assert_bytes_equal else: - warnings.warn("pytest not installed, skipping test suite", stacklevel=2) + warnings.warn( + "pytest not installed, skipping test suite", category=ZarrUserWarning, stacklevel=2 + ) + +if TYPE_CHECKING: + import pytest + + +def pytest_configure(config: "pytest.Config") -> None: + # The tests in zarr.testing are intended to be run by downstream projects. + # To allow those downstream projects to run with `--strict-markers`, we need + # to register an entry point with pytest11 and register our "plugin" with it, + # which just registers the markers used in zarr.testing + config.addinivalue_line("markers", "gpu: mark a test as requiring CuPy and GPU") + + +# TODO: import public buffer tests? -__all__ = ["StoreTests"] +__all__ = ["StoreTests", "assert_bytes_equal"] diff --git a/src/zarr/testing/buffer.py b/src/zarr/testing/buffer.py index d2da1c5a6e..f666801694 100644 --- a/src/zarr/testing/buffer.py +++ b/src/zarr/testing/buffer.py @@ -1,28 +1,41 @@ # mypy: ignore-errors from __future__ import annotations -from collections.abc import Iterable from typing import TYPE_CHECKING, Any, Literal import numpy as np import numpy.typing as npt -from zarr.buffer import Buffer, BufferPrototype, NDBuffer -from zarr.store import MemoryStore +from zarr.core.buffer import Buffer, BufferPrototype, cpu +from zarr.storage import MemoryStore if TYPE_CHECKING: - from typing_extensions import Self + from collections.abc import Iterable + from typing import Self + + from zarr.abc.store import ByteRequest + + +__all__ = [ + "NDBufferUsingTestNDArrayLike", + "StoreExpectingTestBuffer", + "TestBuffer", +] class TestNDArrayLike(np.ndarray): - """An example of a ndarray-like class""" + """An example of an ndarray-like class""" + __test__ = False -class TestBuffer(Buffer): + +class TestBuffer(cpu.Buffer): """Example of a custom Buffer that handles ArrayLike""" + __test__ = False + -class NDBufferUsingTestNDArrayLike(NDBuffer): +class NDBufferUsingTestNDArrayLike(cpu.NDBuffer): """Example of a custom NDBuffer that handles MyNDArrayLike""" @classmethod @@ -34,12 +47,21 @@ def create( order: Literal["C", "F"] = "C", fill_value: Any | None = None, ) -> Self: - """Overwrite `NDBuffer.create` to create an TestNDArrayLike instance""" + """Overwrite `NDBuffer.create` to create a TestNDArrayLike instance""" ret = cls(TestNDArrayLike(shape=shape, dtype=dtype, order=order)) if fill_value is not None: ret.fill(fill_value) return ret + @classmethod + def empty( + cls, + shape: tuple[int, ...], + dtype: npt.DTypeLike, + order: Literal["C", "F"] = "C", + ) -> Self: + return super(cpu.NDBuffer, cls).empty(shape=shape, dtype=dtype, order=order) + class StoreExpectingTestBuffer(MemoryStore): """Example of a custom Store that expect MyBuffer for all its non-metadata @@ -52,6 +74,13 @@ async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None assert isinstance(value, TestBuffer) await super().set(key, value, byte_range) + def set_sync(self, key: str, value: Buffer) -> None: + # Synchronous counterpart of `set`, used by FusedCodecPipeline. Mirror the + # same buffer-type guard so the invariant holds whichever pipeline writes. + if "json" not in key: + assert isinstance(value, TestBuffer) + super().set_sync(key, value) + async def get( self, key: str, @@ -64,3 +93,18 @@ async def get( if ret is not None: assert isinstance(ret, prototype.buffer) return ret + + def get_sync( + self, + key: str, + *, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + # Synchronous counterpart of `get`, used by FusedCodecPipeline. + if "json" not in key and prototype is not None: + assert prototype.buffer is TestBuffer + ret = super().get_sync(key=key, prototype=prototype, byte_range=byte_range) + if ret is not None and prototype is not None: + assert isinstance(ret, prototype.buffer) + return ret diff --git a/src/zarr/testing/stateful.py b/src/zarr/testing/stateful.py new file mode 100644 index 0000000000..9105b8234e --- /dev/null +++ b/src/zarr/testing/stateful.py @@ -0,0 +1,686 @@ +import builtins +import functools +from collections.abc import Callable, Iterable +from typing import Any, cast + +import hypothesis.extra.numpy as npst +import hypothesis.strategies as st +import numpy as np +from hypothesis import assume, note +from hypothesis.stateful import ( + RuleBasedStateMachine, + initialize, + invariant, + precondition, + rule, +) +from hypothesis.strategies import DataObject + +import zarr +from zarr import Array +from zarr.abc.store import ( + OffsetByteRequest, + RangeByteRequest, + Store, + SuffixByteRequest, +) +from zarr.codecs.bytes import BytesCodec +from zarr.core.buffer import Buffer, BufferPrototype, cpu, default_buffer_prototype +from zarr.core.sync import SyncMixin +from zarr.storage import LocalStore, MemoryStore +from zarr.testing.strategies import ( + arrays as zarr_arrays, +) +from zarr.testing.strategies import ( + basic_indices, + chunk_paths, + key_ranges, + node_names, + orthogonal_indices, +) +from zarr.testing.strategies import keys as zarr_keys + +MAX_BINARY_SIZE = 100 + + +def with_frequency[F: Callable[..., Any]](frequency: float) -> Callable[[F], F]: + """This needs to be deterministic for hypothesis replaying""" + + def decorator(func: F) -> F: + counter_attr = f"__{func.__name__}_counter" + + @functools.wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> Any: + return func(*args, **kwargs) + + @precondition + def frequency_check(f: Any) -> Any: + if not hasattr(f, counter_attr): + setattr(f, counter_attr, 0) + + current_count = getattr(f, counter_attr) + 1 + setattr(f, counter_attr, current_count) + + return (current_count * frequency) % 1.0 >= (1.0 - frequency) + + return cast(F, frequency_check(wrapper)) + + return decorator + + +def split_prefix_name(path: str) -> tuple[str, str]: + split = path.rsplit("/", maxsplit=1) + if len(split) > 1: + prefix, name = split + else: + prefix = "" + (name,) = split + return prefix, name + + +class ZarrHierarchyStateMachine(SyncMixin, RuleBasedStateMachine): + """ + This state machine models operations that modify a zarr store's + hierarchy. That is, user actions that modify arrays/groups as well + as list operations. It is intended to be used by external stores, and + compares their results to a MemoryStore that is assumed to be perfect. + """ + + def __init__(self, store: Store) -> None: + super().__init__() + + self.store = store + + self.model = MemoryStore() + zarr.group(store=self.model) + + # Track state of the hierarchy, these should contain fully qualified paths + self.all_groups: set[str] = set() + self.all_arrays: set[str] = set() + + @initialize() + def init_store(self) -> None: + # This lets us reuse the fixture provided store. + self._sync(self.store.clear()) + zarr.group(store=self.store) + + def can_add(self, path: str) -> bool: + return path not in self.all_groups and path not in self.all_arrays + + # -------------------- store operations ----------------------- + @rule(name=node_names, data=st.data()) + def add_group(self, name: str, data: DataObject) -> None: + # Handle possible case-insensitive file systems (e.g. MacOS) + if isinstance(self.store, LocalStore): + name = name.lower() + if self.all_groups: + parent = data.draw(st.sampled_from(sorted(self.all_groups)), label="Group parent") + else: + parent = "" + path = f"{parent}/{name}".lstrip("/") + assume(self.can_add(path)) + note(f"Adding group: path='{path}'") + self.all_groups.add(path) + zarr.group(store=self.store, path=path) + zarr.group(store=self.model, path=path) + + @rule(data=st.data(), name=node_names) + def add_array(self, data: DataObject, name: str) -> None: + # Handle possible case-insensitive file systems (e.g. MacOS) + if isinstance(self.store, LocalStore): + name = name.lower() + if self.all_groups: + parent = data.draw(st.sampled_from(sorted(self.all_groups)), label="Array parent") + else: + parent = "" + # TODO: support creating deeper paths + # TODO: support overwriting potentially by just skipping `self.can_add` + path = f"{parent}/{name}".lstrip("/") + assume(self.can_add(path)) + + # Generate array on the model store using the arrays strategy + a = data.draw( + zarr_arrays( + stores=st.just(self.model), + paths=st.just(parent), + array_names=st.just(name), + zarr_formats=st.just(3), + compressors=st.just(BytesCodec()), + open_mode="a", + ), + label="generated array", + ) + note(f"Adding array: path='{path}' shape={a.shape} chunks={a.metadata.chunk_grid}") + + # Recreate the same array in the store under test + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata, RegularChunkGridMetadata + + chunk_grid = a.metadata.chunk_grid + chunks_param: tuple[int, ...] | list[list[int]] + if isinstance(chunk_grid, RectilinearChunkGridMetadata): + chunks_param = [ + list(dim) if isinstance(dim, tuple) else [dim] for dim in chunk_grid.chunk_shapes + ] + elif isinstance(chunk_grid, RegularChunkGridMetadata): + chunks_param = chunk_grid.chunk_shape + else: + chunks_param = a.chunks + + root = zarr.open_group(store=self.store, mode="a") + arr = root.create_array( + path, + shape=a.shape, + chunks=chunks_param, + dtype=a.dtype, + fill_value=a.fill_value, + dimension_names=a.metadata.dimension_names, # type: ignore[union-attr] + compressors=None, + ) + arr[:] = a[:] + self.all_arrays.add(path) + + @rule() + @with_frequency(0.25) + def clear(self) -> None: + note("clearing") + import zarr + + self._sync(self.store.clear()) + self._sync(self.model.clear()) + + assert self._sync(self.store.is_empty("/")) + assert self._sync(self.model.is_empty("/")) + + self.all_groups.clear() + self.all_arrays.clear() + + zarr.group(store=self.store) + zarr.group(store=self.model) + + # TODO: MemoryStore is broken? + # assert not self._sync(self.store.is_empty("/")) + # assert not self._sync(self.model.is_empty("/")) + + def draw_directory(self, data: DataObject) -> str: + group_st = st.sampled_from(sorted(self.all_groups)) if self.all_groups else st.nothing() + array_st = st.sampled_from(sorted(self.all_arrays)) if self.all_arrays else st.nothing() + array_or_group = data.draw(st.one_of(group_st, array_st)) + if data.draw(st.booleans()) and array_or_group in self.all_arrays: + arr = zarr.open_array(path=array_or_group, store=self.model) + path = data.draw( + st.one_of( + st.sampled_from([array_or_group]), + chunk_paths(ndim=arr.ndim, numblocks=arr.cdata_shape).map( + lambda x: f"{array_or_group}/c/" + ), + ) + ) + else: + path = array_or_group + return path + + @precondition(lambda self: bool(self.all_groups)) + @rule(data=st.data()) + def check_list_dir(self, data: DataObject) -> None: + path = self.draw_directory(data) + note(f"list_dir for {path=!r}") + # Consider .list_dir("path/to/array") for an array with a single chunk. + # The MemoryStore model will return `"c", "zarr.json"` only if the chunk exists + # If that chunk was deleted, then `"c"` is not returned. + # LocalStore will not have this behaviour :/ + # There are similar consistency issues with delete_dir("/path/to/array/c/0/0") + assume(not isinstance(self.store, LocalStore)) + model_ls = sorted(self._sync_iter(self.model.list_dir(path))) + store_ls = sorted(self._sync_iter(self.store.list_dir(path))) + assert model_ls == store_ls, (model_ls, store_ls) + + @precondition(lambda self: bool(self.all_arrays)) + @rule(data=st.data()) + def delete_chunk(self, data: DataObject) -> None: + array = data.draw(st.sampled_from(sorted(self.all_arrays))) + arr = zarr.open_array(path=array, store=self.model) + chunk_path = data.draw(chunk_paths(ndim=arr.ndim, numblocks=arr.cdata_shape, subset=False)) + path = f"{array}/c/{chunk_path}" + note(f"deleting chunk {path=!r}") + self._sync(self.model.delete(path)) + self._sync(self.store.delete(path)) + + @precondition(lambda self: bool(self.all_arrays)) + @rule(data=st.data()) + def check_array(self, data: DataObject) -> None: + path = data.draw(st.sampled_from(sorted(self.all_arrays))) + actual = zarr.open_array(self.store, path=path)[:] + expected = zarr.open_array(self.model, path=path)[:] + np.testing.assert_equal(actual, expected) + + @precondition(lambda self: bool(self.all_arrays)) + @rule(data=st.data()) + def overwrite_array_basic_indexing(self, data: DataObject) -> None: + array = data.draw(st.sampled_from(sorted(self.all_arrays))) + model_array = zarr.open_array(path=array, store=self.model) + store_array = zarr.open_array(path=array, store=self.store) + slicer = data.draw(basic_indices(shape=model_array.shape)) + note(f"overwriting array with basic indexer: {slicer=}") + new_data = data.draw( + npst.arrays(shape=np.shape(model_array[slicer]), dtype=model_array.dtype) + ) + model_array[slicer] = new_data + store_array[slicer] = new_data + + @precondition(lambda self: bool(self.all_arrays)) + @rule(data=st.data()) + def overwrite_array_orthogonal_indexing(self, data: DataObject) -> None: + array = data.draw(st.sampled_from(sorted(self.all_arrays))) + model_array = zarr.open_array(path=array, store=self.model) + store_array = zarr.open_array(path=array, store=self.store) + indexer, _ = data.draw(orthogonal_indices(shape=model_array.shape)) + note(f"overwriting array orthogonal {indexer=}") + new_data = data.draw( + npst.arrays(shape=model_array.oindex[indexer].shape, dtype=model_array.dtype) # type: ignore[union-attr] + ) + model_array.oindex[indexer] = new_data + store_array.oindex[indexer] = new_data + + @precondition(lambda self: bool(self.all_arrays)) + @rule(data=st.data()) + def resize_array(self, data: DataObject) -> None: + array = data.draw(st.sampled_from(sorted(self.all_arrays))) + model_array = zarr.open_array(path=array, store=self.model) + store_array = zarr.open_array(path=array, store=self.store) + ndim = model_array.ndim + new_shape = tuple( + 0 if oldsize == 0 else newsize + for newsize, oldsize in zip( + data.draw(npst.array_shapes(max_dims=ndim, min_dims=ndim, min_side=0)), + model_array.shape, + strict=True, + ) + ) + + note(f"resizing array from {model_array.shape} to {new_shape}") + model_array.resize(new_shape) + store_array.resize(new_shape) + + @precondition(lambda self: bool(self.all_arrays) or bool(self.all_groups)) + @rule(data=st.data()) + def delete_dir(self, data: DataObject) -> None: + path = self.draw_directory(data) + note(f"delete_dir with {path=!r}") + self._sync(self.model.delete_dir(path)) + self._sync(self.store.delete_dir(path)) + + matches = set() + for node in self.all_groups | self.all_arrays: + if node == path or node.startswith(path + "/"): + matches.add(node) + self.all_groups = self.all_groups - matches + self.all_arrays = self.all_arrays - matches + + # @precondition(lambda self: bool(self.all_groups)) + # @precondition(lambda self: bool(self.all_arrays)) + # @rule(data=st.data()) + # def move_array(self, data): + # array_path = data.draw(st.sampled_from(self.all_arrays), label="Array move source") + # to_group = data.draw(st.sampled_from(self.all_groups), label="Array move destination") + + # # fixme renaming to self? + # array_name = os.path.basename(array_path) + # assume(self.model.can_add(to_group, array_name)) + # new_path = f"{to_group}/{array_name}".lstrip("/") + # note(f"moving array '{array_path}' -> '{new_path}'") + # self.model.rename(array_path, new_path) + # self.repo.store.rename(array_path, new_path) + + # @precondition(lambda self: len(self.all_groups) >= 2) + # @rule(data=st.data()) + # def move_group(self, data): + # from_group = data.draw(st.sampled_from(self.all_groups), label="Group move source") + # to_group = data.draw(st.sampled_from(self.all_groups), label="Group move destination") + # assume(not to_group.startswith(from_group)) + + # from_group_name = os.path.basename(from_group) + # assume(self.model.can_add(to_group, from_group_name)) + # # fixme renaming to self? + # new_path = f"{to_group}/{from_group_name}".lstrip("/") + # note(f"moving group '{from_group}' -> '{new_path}'") + # self.model.rename(from_group, new_path) + # self.repo.store.rename(from_group, new_path) + + @precondition(lambda self: self.store.supports_deletes) + @precondition(lambda self: len(self.all_arrays) >= 1) + @rule(data=st.data()) + def delete_array_using_del(self, data: DataObject) -> None: + array_path = data.draw( + st.sampled_from(sorted(self.all_arrays)), label="Array deletion target" + ) + prefix, array_name = split_prefix_name(array_path) + note(f"Deleting array '{array_path}' ({prefix=!r}, {array_name=!r}) using del") + for store in [self.model, self.store]: + group = zarr.open_group(path=prefix, store=store) + group[array_name] # check that it exists + del group[array_name] + self.all_arrays.remove(array_path) + + @precondition(lambda self: self.store.supports_deletes) + @precondition(lambda self: bool(self.all_groups)) + @rule(data=st.data()) + def delete_group_using_del(self, data: DataObject) -> None: + group_path = data.draw( + st.sampled_from(sorted(self.all_groups)), + label="Group deletion target", + ) + prefix, group_name = split_prefix_name(group_path) + note(f"Deleting group '{group_path=!r}', {prefix=!r}, {group_name=!r} using delete") + members = zarr.open_group(store=self.model, path=group_path).members(max_depth=None) + for _, obj in members: + if isinstance(obj, Array): + self.all_arrays.remove(obj.path) + else: + self.all_groups.remove(obj.path) + for store in [self.store, self.model]: + group = zarr.open_group(store=store, path=prefix) + group[group_name] # check that it exists + del group[group_name] + self.all_groups.remove(group_path) + + # # --------------- assertions ----------------- + # def check_group_arrays(self, group): + # # note(f"Checking arrays of '{group}'") + # g1 = self.model.get_group(group) + # g2 = zarr.open_group(path=group, mode="r", store=self.repo.store) + # model_arrays = sorted(g1.arrays(), key=itemgetter(0)) + # our_arrays = sorted(g2.arrays(), key=itemgetter(0)) + # for (n1, a1), (n2, a2) in zip_longest(model_arrays, our_arrays): + # assert n1 == n2 + # assert_array_equal(a1, a2) + + # def check_subgroups(self, group_path): + # g1 = self.model.get_group(group_path) + # g2 = zarr.open_group(path=group_path, mode="r", store=self.repo.store) + # g1_children = [name for (name, _) in g1.groups()] + # g2_children = [name for (name, _) in g2.groups()] + # # note(f"Checking {len(g1_children)} subgroups of group '{group_path}'") + # assert g1_children == g2_children + + # def check_list_prefix_from_group(self, group): + # prefix = f"meta/root/{group}" + # model_list = sorted(self.model.list_prefix(prefix)) + # al_list = sorted(self.repo.store.list_prefix(prefix)) + # # note(f"Checking {len(model_list)} keys under '{prefix}'") + # assert model_list == al_list + + # prefix = f"data/root/{group}" + # model_list = sorted(self.model.list_prefix(prefix)) + # al_list = sorted(self.repo.store.list_prefix(prefix)) + # # note(f"Checking {len(model_list)} keys under '{prefix}'") + # assert model_list == al_list + + # @precondition(lambda self: self.model.is_persistent_session()) + # @rule(data=st.data()) + # def check_group_path(self, data): + # t0 = time.time() + # group = data.draw(st.sampled_from(self.all_groups)) + # self.check_list_prefix_from_group(group) + # self.check_subgroups(group) + # self.check_group_arrays(group) + # t1 = time.time() + # note(f"Checks took {t1 - t0} sec.") + @invariant() + def check_list_prefix_from_root(self) -> None: + model_list = self._sync_iter(self.model.list_prefix("")) + store_list = self._sync_iter(self.store.list_prefix("")) + note(f"Checking {len(model_list)} expected keys vs {len(store_list)} actual keys") + assert sorted(model_list) == sorted(store_list), ( + sorted(model_list), + sorted(store_list), + ) + + # check that our internal state matches that of the store and model + assert all(f"{path}/zarr.json" in model_list for path in self.all_groups | self.all_arrays) + assert all(f"{path}/zarr.json" in store_list for path in self.all_groups | self.all_arrays) + + +class SyncStoreWrapper(zarr.core.sync.SyncMixin): + def __init__(self, store: Store) -> None: + """Synchronous Store wrapper + + This class holds synchronous methods that map to async methods of Store classes. + The synchronous wrapper is needed because hypothesis' stateful testing infra does + not support asyncio so we redefine sync versions of the Store API. + https://github.com/HypothesisWorks/hypothesis/issues/3712#issuecomment-1668999041 + """ + self.store = store + + @property + def read_only(self) -> bool: + return self.store.read_only + + def set(self, key: str, data_buffer: Buffer) -> None: + return self._sync(self.store.set(key, data_buffer)) + + def list(self) -> builtins.list[str]: + return self._sync_iter(self.store.list()) + + def get(self, key: str, prototype: BufferPrototype) -> Buffer | None: + return self._sync(self.store.get(key, prototype=prototype)) + + def get_partial_values( + self, key_ranges: Iterable[Any], prototype: BufferPrototype + ) -> builtins.list[Buffer | None]: + return self._sync(self.store.get_partial_values(prototype=prototype, key_ranges=key_ranges)) + + def delete(self, path: str) -> None: + return self._sync(self.store.delete(path)) + + def is_empty(self, prefix: str) -> bool: + return self._sync(self.store.is_empty(prefix=prefix)) + + def clear(self) -> None: + return self._sync(self.store.clear()) + + def exists(self, key: str) -> bool: + return self._sync(self.store.exists(key)) + + def getsize_prefix(self, prefix: str) -> int: + return self._sync(self.store.getsize_prefix(prefix)) + + def list_dir(self, prefix: str) -> None: + raise NotImplementedError + + def list_prefix(self, prefix: str) -> None: + raise NotImplementedError + + @property + def supports_listing(self) -> bool: + return self.store.supports_listing + + @property + def supports_writes(self) -> bool: + return self.store.supports_writes + + @property + def supports_deletes(self) -> bool: + return self.store.supports_deletes + + +class ZarrStoreStateMachine(RuleBasedStateMachine): + """ " + Zarr store state machine + + This is a subclass of a Hypothesis RuleBasedStateMachine. + It is testing a framework to ensure that the state of a Zarr store matches + an expected state after a set of random operations. It contains a store + (currently, a Zarr MemoryStore) and a model, a simplified version of a + zarr store (in this case, a dict). It also contains rules which represent + actions that can be applied to a zarr store. Rules apply an action to both + the store and the model, and invariants assert that the state of the model + is equal to the state of the store. Hypothesis then generates sequences of + rules, running invariants after each rule. It raises an error if a sequence + produces discontinuity between state of the model and state of the store + (ie. an invariant is violated). + https://hypothesis.readthedocs.io/en/latest/stateful.html + """ + + def __init__(self, store: Store) -> None: + super().__init__() + self.model: dict[str, Buffer] = {} + self.store = SyncStoreWrapper(store) + self.prototype = default_buffer_prototype() + + @initialize() + def init_store(self) -> None: + self.store.clear() + + @rule(key=zarr_keys(), data=st.binary(min_size=0, max_size=MAX_BINARY_SIZE)) + def set(self, key: str, data: bytes) -> None: + note(f"(set) Setting {key!r} with {data!r}") + assert not self.store.read_only + data_buf = cpu.Buffer.from_bytes(data) + self.store.set(key, data_buf) + self.model[key] = data_buf + + @precondition(lambda self: len(self.model.keys()) > 0) + @rule(key=zarr_keys(), data=st.data()) + def get(self, key: str, data: DataObject) -> None: + key = data.draw( + st.sampled_from(sorted(self.model.keys())) + ) # hypothesis wants to sample from sorted list + note("(get)") + store_value = self.store.get(key, self.prototype) + # to bytes here necessary because data_buf set to model in set() + assert self.model[key] == store_value + + @rule(key=zarr_keys(), data=st.data()) + def get_invalid_zarr_keys(self, key: str, data: DataObject) -> None: + note("(get_invalid)") + assume(key not in self.model) + assert self.store.get(key, self.prototype) is None + + @precondition(lambda self: len(self.model.keys()) > 0) + @rule(data=st.data()) + def get_partial_values(self, data: DataObject) -> None: + key_range = data.draw( + key_ranges(keys=st.sampled_from(sorted(self.model.keys())), max_size=MAX_BINARY_SIZE) + ) + note(f"(get partial) {key_range=}") + # Pass a one-shot generator rather than a list: stores (and wrappers such + # as LoggingStore) must not exhaust the iterable before using it. + obs_maybe = self.store.get_partial_values((kr for kr in key_range), self.prototype) + observed = [] + + for obs in obs_maybe: + assert obs is not None + observed.append(obs.to_bytes()) + + model_vals_ls = [] + + for key, byte_range in key_range: + # Independently model each ByteRequest variant (do NOT reuse the + # store's _normalize_byte_range_index helper, so this stays an + # independent oracle). Bounds may exceed the value length. + value = self.model[key] + n = len(value) + if byte_range is None: + expected = value[:] + elif isinstance(byte_range, RangeByteRequest): + expected = value[byte_range.start : byte_range.end] + elif isinstance(byte_range, OffsetByteRequest): + expected = value[byte_range.offset :] + elif isinstance(byte_range, SuffixByteRequest): + # "last suffix bytes"; suffix > n means the whole value. + expected = value[max(0, n - byte_range.suffix) :] + else: + raise AssertionError(f"unexpected byte_range {byte_range!r}") + model_vals_ls.append(expected) + + assert all( + obs == exp.to_bytes() for obs, exp in zip(observed, model_vals_ls, strict=True) + ), ( + observed, + model_vals_ls, + ) + + @precondition(lambda self: self.store.supports_deletes) + @precondition(lambda self: len(self.model.keys()) > 0) + @rule(data=st.data()) + def delete(self, data: DataObject) -> None: + key = data.draw(st.sampled_from(sorted(self.model.keys()))) + note(f"(delete) Deleting {key=}") + + self.store.delete(key) + del self.model[key] + + @rule() + def clear(self) -> None: + assert not self.store.read_only + note("(clear)") + self.store.clear() + self.model.clear() + + assert self.store.is_empty("") + + assert len(self.model.keys()) == len(list(self.store.list())) == 0 + + @rule() + # Local store can be non-empty when there are subdirectories but no files + @precondition(lambda self: not isinstance(self.store.store, LocalStore)) + def is_empty(self) -> None: + note("(is_empty)") + + # make sure they either both are or both aren't empty (same state) + assert self.store.is_empty("") == (not self.model) + + @rule(key=zarr_keys()) + def exists(self, key: str) -> None: + note("(exists)") + + assert self.store.exists(key) == (key in self.model) + + @precondition(lambda self: len(self.model.keys()) > 0) + @rule(data=st.data()) + def getsize_prefix(self, data: DataObject) -> None: + # Measure the size under the first path segment of some existing key. + # getsize_prefix(node) must count only keys under the directory "node/", + # not sibling keys that merely share the string prefix (e.g. measuring + # "a" must not include a sibling key "ab/..."). + key = data.draw(st.sampled_from(sorted(self.model.keys()))) + node = key.split("/")[0] + note(f"(getsize_prefix) {node=}") + + observed = self.store.getsize_prefix(node) + expected = sum(len(value) for k, value in self.model.items() if k.startswith(node + "/")) + assert observed == expected, (observed, expected, node) + + @invariant() + def check_paths_equal(self) -> None: + note("Checking that paths are equal") + paths = sorted(self.store.list()) + + assert sorted(self.model.keys()) == paths + + @invariant() + def check_vals_equal(self) -> None: + note("Checking values equal") + for key, val in self.model.items(): + store_item = self.store.get(key, self.prototype) + assert val == store_item + + @invariant() + def check_num_zarr_keys_equal(self) -> None: + note("check num zarr_keys equal") + + assert len(self.model) == len(list(self.store.list())) + + @invariant() + def check_zarr_keys(self) -> None: + keys = list(self.store.list()) + + if not keys: + assert self.store.is_empty("") is True + + else: + assert self.store.is_empty("") is False + + for key in keys: + assert self.store.exists(key) is True + note("checking keys / exists / empty") diff --git a/src/zarr/testing/store.py b/src/zarr/testing/store.py index 4fdf497a68..4c948a783c 100644 --- a/src/zarr/testing/store.py +++ b/src/zarr/testing/store.py @@ -1,129 +1,398 @@ -from typing import Any, Generic, TypeVar +from __future__ import annotations + +import asyncio +import pickle +import time +from abc import abstractmethod +from typing import TYPE_CHECKING, Self + +import numpy as np + +from zarr.storage import WrapperStore + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Iterable, Sequence + from typing import Any + + from zarr.core.buffer.core import BufferPrototype import pytest -from zarr.abc.store import AccessMode, Store -from zarr.buffer import Buffer, default_buffer_prototype -from zarr.store.utils import _normalize_interval_index +from zarr.abc.store import ( + ByteRequest, + OffsetByteRequest, + RangeByteRequest, + Store, + SuffixByteRequest, + SupportsDeleteSync, + SupportsGetSync, + SupportsSetSync, +) +from zarr.core.buffer import Buffer, default_buffer_prototype +from zarr.core.sync import _collect_aiterator, sync +from zarr.storage._utils import _normalize_byte_range_index from zarr.testing.utils import assert_bytes_equal -S = TypeVar("S", bound=Store) +__all__ = ["StoreTests"] -class StoreTests(Generic[S]): +class StoreTests[S: Store, B: Buffer]: store_cls: type[S] - - def set(self, store: S, key: str, value: Buffer) -> None: + buffer_cls: type[B] + + @staticmethod + def _require_get_sync(store: S) -> SupportsGetSync: + """Skip unless *store* implements [`SupportsGetSync`][zarr.abc.store.SupportsGetSync].""" + if not isinstance(store, SupportsGetSync): + pytest.skip("store does not implement SupportsGetSync") + return store # type: ignore[unreachable] + + @staticmethod + def _require_set_sync(store: S) -> SupportsSetSync: + """Skip unless *store* implements [`SupportsSetSync`][zarr.abc.store.SupportsSetSync].""" + if not isinstance(store, SupportsSetSync): + pytest.skip("store does not implement SupportsSetSync") + return store # type: ignore[unreachable] + + @staticmethod + def _require_delete_sync(store: S) -> SupportsDeleteSync: + """Skip unless *store* implements [`SupportsDeleteSync`][zarr.abc.store.SupportsDeleteSync].""" + if not isinstance(store, SupportsDeleteSync): + pytest.skip("store does not implement SupportsDeleteSync") + return store # type: ignore[unreachable] + + @abstractmethod + async def set(self, store: S, key: str, value: Buffer) -> None: """ Insert a value into a storage backend, with a specific key. - This should not not use any store methods. Bypassing the store methods allows them to be + This should not use any store methods. Bypassing the store methods allows them to be tested. """ - raise NotImplementedError + ... - def get(self, store: S, key: str) -> Buffer: + @abstractmethod + async def get(self, store: S, key: str) -> Buffer: """ Retrieve a value from a storage backend, by key. - This should not not use any store methods. Bypassing the store methods allows them to be + This should not use any store methods. Bypassing the store methods allows them to be tested. """ + ... + + @abstractmethod + @pytest.fixture + def store_kwargs(self, *args: Any, **kwargs: Any) -> dict[str, Any]: + """Kwargs for instantiating a store""" + ... + + @abstractmethod + def test_store_repr(self, store: S) -> None: ... + + @abstractmethod + def test_store_supports_writes(self, store: S) -> None: ... + + def test_store_supports_partial_writes(self, store: S) -> None: + assert not store.supports_partial_writes - raise NotImplementedError + @abstractmethod + def test_store_supports_listing(self, store: S) -> None: ... - @pytest.fixture(scope="function") - def store_kwargs(self) -> dict[str, Any]: - return {"mode": "r+"} + @pytest.fixture + def open_kwargs(self, store_kwargs: dict[str, Any]) -> dict[str, Any]: + return store_kwargs - @pytest.fixture(scope="function") - async def store(self, store_kwargs: dict[str, Any]) -> Store: - return await self.store_cls.open(**store_kwargs) + @pytest.fixture + async def store(self, open_kwargs: dict[str, Any]) -> Store: + return await self.store_cls.open(**open_kwargs) + + @pytest.fixture + async def store_not_open(self, store_kwargs: dict[str, Any]) -> Store: + return self.store_cls(**store_kwargs) def test_store_type(self, store: S) -> None: assert isinstance(store, Store) assert isinstance(store, self.store_cls) - def test_store_mode(self, store: S, store_kwargs: dict[str, Any]) -> None: - assert store.mode == AccessMode.from_literal("r+") - assert not store.mode.readonly + def test_store_eq(self, store: S, store_kwargs: dict[str, Any]) -> None: + # check self equality + assert store == store # noqa: PLR0124 -- self-equality is the property under test + + # check store equality with same inputs + # asserting this is important for being able to compare (de)serialized stores + store2 = self.store_cls(**store_kwargs) + assert store == store2 + + async def test_serializable_store(self, store: S) -> None: + new_store: S = pickle.loads(pickle.dumps(store)) + assert new_store == store + assert new_store.read_only == store.read_only + # quickly roundtrip data to a key to test that new store works + data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") + key = "foo" + await store.set(key, data_buf) + observed = await store.get(key, prototype=default_buffer_prototype()) + assert_bytes_equal(observed, data_buf) + + def test_store_read_only(self, store: S) -> None: + assert not store.read_only with pytest.raises(AttributeError): - store.mode = AccessMode.from_literal("w") # type: ignore[misc] - - async def test_not_writable_store_raises(self, store_kwargs: dict[str, Any]) -> None: - kwargs = {**store_kwargs, "mode": "r"} + store.read_only = False # type: ignore[misc] + + @pytest.mark.parametrize("read_only", [True, False]) + async def test_store_open_read_only(self, open_kwargs: dict[str, Any], read_only: bool) -> None: + open_kwargs["read_only"] = read_only + store = await self.store_cls.open(**open_kwargs) + assert store._is_open + assert store.read_only == read_only + + async def test_store_context_manager(self, open_kwargs: dict[str, Any]) -> None: + # Test that the context manager closes the store + with await self.store_cls.open(**open_kwargs) as store: + assert store._is_open + # Test trying to open an already open store + with pytest.raises(ValueError, match="store is already open"): + await store._open() + assert not store._is_open + + async def test_read_only_store_raises(self, open_kwargs: dict[str, Any]) -> None: + kwargs = {**open_kwargs, "read_only": True} store = await self.store_cls.open(**kwargs) - assert store.mode == AccessMode.from_literal("r") - assert store.mode.readonly + assert store.read_only # set - with pytest.raises(ValueError): - await store.set("foo", Buffer.from_bytes(b"bar")) + with pytest.raises( + ValueError, match="store was opened in read-only mode and does not support writing" + ): + await store.set("foo", self.buffer_cls.from_bytes(b"bar")) # delete - with pytest.raises(ValueError): + with pytest.raises( + ValueError, match="store was opened in read-only mode and does not support writing" + ): await store.delete("foo") - def test_store_repr(self, store: S) -> None: - raise NotImplementedError - - def test_store_supports_writes(self, store: S) -> None: - raise NotImplementedError - - def test_store_supports_partial_writes(self, store: S) -> None: - raise NotImplementedError + async def test_with_read_only_store(self, open_kwargs: dict[str, Any]) -> None: + kwargs = {**open_kwargs, "read_only": True} + store = await self.store_cls.open(**kwargs) + assert store.read_only + + # Test that you cannot write to a read-only store + with pytest.raises( + ValueError, match="store was opened in read-only mode and does not support writing" + ): + await store.set("foo", self.buffer_cls.from_bytes(b"bar")) + + # Check if the store implements with_read_only + try: + writer = store.with_read_only(read_only=False) + except NotImplementedError: + # Test that stores that do not implement with_read_only raise NotImplementedError with the correct message + with pytest.raises( + NotImplementedError, + match=f"with_read_only is not implemented for the {type(store)} store type.", + ): + store.with_read_only(read_only=False) + return + + # Test that you can write to a new store copy + assert not writer._is_open + assert not writer.read_only + await writer.set("foo", self.buffer_cls.from_bytes(b"bar")) + await writer.delete("foo") + + # Test that you cannot write to the original store + assert store.read_only + with pytest.raises( + ValueError, match="store was opened in read-only mode and does not support writing" + ): + await store.set("foo", self.buffer_cls.from_bytes(b"bar")) + with pytest.raises( + ValueError, match="store was opened in read-only mode and does not support writing" + ): + await store.delete("foo") - def test_store_supports_listing(self, store: S) -> None: - raise NotImplementedError + # Test that you cannot write to a read-only store copy + reader = store.with_read_only(read_only=True) + assert reader.read_only + with pytest.raises( + ValueError, match="store was opened in read-only mode and does not support writing" + ): + await reader.set("foo", self.buffer_cls.from_bytes(b"bar")) + with pytest.raises( + ValueError, match="store was opened in read-only mode and does not support writing" + ): + await reader.delete("foo") @pytest.mark.parametrize("key", ["c/0", "foo/c/0.0", "foo/0/0"]) - @pytest.mark.parametrize("data", [b"\x01\x02\x03\x04", b""]) - @pytest.mark.parametrize("byte_range", (None, (0, None), (1, None), (1, 2), (None, 1))) - async def test_get( - self, store: S, key: str, data: bytes, byte_range: None | tuple[int | None, int | None] - ) -> None: + @pytest.mark.parametrize( + ("data", "byte_range"), + [ + (b"\x01\x02\x03\x04", None), + (b"\x01\x02\x03\x04", RangeByteRequest(1, 4)), + (b"\x01\x02\x03\x04", OffsetByteRequest(1)), + (b"\x01\x02\x03\x04", SuffixByteRequest(1)), + (b"", None), + ], + ) + async def test_get(self, store: S, key: str, data: bytes, byte_range: ByteRequest) -> None: """ Ensure that data can be read from the store using the store.get method. """ - data_buf = Buffer.from_bytes(data) - self.set(store, key, data_buf) + data_buf = self.buffer_cls.from_bytes(data) + await self.set(store, key, data_buf) observed = await store.get(key, prototype=default_buffer_prototype(), byte_range=byte_range) - start, length = _normalize_interval_index(data_buf, interval=byte_range) - expected = data_buf[start : start + length] + start, stop = _normalize_byte_range_index(data_buf, byte_range=byte_range) + expected = data_buf[start:stop] assert_bytes_equal(observed, expected) + async def test_get_not_open(self, store_not_open: S) -> None: + """ + Ensure that data can be read from the store that isn't yet open using the store.get method. + """ + assert not store_not_open._is_open + data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") + key = "c/0" + await self.set(store_not_open, key, data_buf) + observed = await store_not_open.get(key, prototype=default_buffer_prototype()) + assert_bytes_equal(observed, data_buf) + + async def test_get_raises(self, store: S) -> None: + """ + Ensure that a ValueError is raise for invalid byte range syntax + """ + data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") + await self.set(store, "c/0", data_buf) + with pytest.raises((ValueError, TypeError), match=r"Unexpected byte_range, got.*"): + await store.get("c/0", prototype=default_buffer_prototype(), byte_range=(0, 2)) # type: ignore[arg-type] + + async def test_get_many(self, store: S) -> None: + """ + Ensure that multiple keys can be retrieved at once with the _get_many method. + """ + keys = tuple(map(str, range(10))) + values = tuple(f"{k}".encode() for k in keys) + for k, v in zip(keys, values, strict=False): + await self.set(store, k, self.buffer_cls.from_bytes(v)) + observed_buffers = await _collect_aiterator( + store._get_many( + zip( + keys, + (default_buffer_prototype(),) * len(keys), + (None,) * len(keys), + strict=False, + ) + ) + ) + observed_kvs = sorted(((k, b.to_bytes()) for k, b in observed_buffers)) # type: ignore[union-attr] + expected_kvs = sorted(((k, b) for k, b in zip(keys, values, strict=False))) + assert observed_kvs == expected_kvs + + @pytest.mark.parametrize("key", ["c/0", "foo/c/0.0", "foo/0/0"]) + @pytest.mark.parametrize("data", [b"\x01\x02\x03\x04", b""]) + async def test_getsize(self, store: S, key: str, data: bytes) -> None: + """ + Test the result of store.getsize(). + """ + data_buf = self.buffer_cls.from_bytes(data) + expected = len(data_buf) + await self.set(store, key, data_buf) + observed = await store.getsize(key) + assert observed == expected + + async def test_getsize_prefix(self, store: S) -> None: + """ + Test the result of store.getsize_prefix(). + + Includes a sibling key ("cc/0") that shares the string prefix "c" but + belongs to a different directory: getsize_prefix("c") must not count it, + i.e. the prefix is matched as a directory ("c/...") not a raw substring. + """ + data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") + keys = ["c/0/0", "c/0/1", "c/1/0", "c/1/1"] + # Sibling directory sharing the "c" string prefix; must be excluded. + sibling_keys = ["cc/0"] + keys_values = [(k, data_buf) for k in keys + sibling_keys] + await store._set_many(keys_values) + expected = len(data_buf) * len(keys) + observed = await store.getsize_prefix("c") + assert observed == expected + + async def test_getsize_raises(self, store: S) -> None: + """ + Test that getsize() raise a FileNotFoundError if the key doesn't exist. + """ + with pytest.raises(FileNotFoundError): + await store.getsize("c/1000") + @pytest.mark.parametrize("key", ["zarr.json", "c/0", "foo/c/0.0", "foo/0/0"]) @pytest.mark.parametrize("data", [b"\x01\x02\x03\x04", b""]) async def test_set(self, store: S, key: str, data: bytes) -> None: """ Ensure that data can be written to the store using the store.set method. """ - assert not store.mode.readonly - data_buf = Buffer.from_bytes(data) + assert not store.read_only + data_buf = self.buffer_cls.from_bytes(data) await store.set(key, data_buf) - observed = self.get(store, key) + observed = await self.get(store, key) assert_bytes_equal(observed, data_buf) + async def test_set_not_open(self, store_not_open: S) -> None: + """ + Ensure that data can be written to the store that's not yet open using the store.set method. + """ + assert not store_not_open._is_open + data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") + key = "c/0" + await store_not_open.set(key, data_buf) + observed = await self.get(store_not_open, key) + assert_bytes_equal(observed, data_buf) + + async def test_set_many(self, store: S) -> None: + """ + Test that a dict of key : value pairs can be inserted into the store via the + `_set_many` method. + """ + keys = ["zarr.json", "c/0", "foo/c/0.0", "foo/0/0"] + data_buf = [self.buffer_cls.from_bytes(k.encode()) for k in keys] + store_dict = dict(zip(keys, data_buf, strict=True)) + await store._set_many(store_dict.items()) + for k, v in store_dict.items(): + assert (await self.get(store, k)).to_bytes() == v.to_bytes() + @pytest.mark.parametrize( "key_ranges", - ( + [ [], - [("zarr.json", (0, 1))], - [("c/0", (0, 1)), ("zarr.json", (0, None))], - [("c/0/0", (0, 1)), ("c/0/1", (None, 2)), ("c/0/2", (0, 3))], - ), + [("zarr.json", RangeByteRequest(0, 2))], + [("c/0", RangeByteRequest(0, 2)), ("zarr.json", None)], + [ + ("c/0/0", RangeByteRequest(0, 2)), + ("c/0/1", SuffixByteRequest(2)), + ("c/0/2", OffsetByteRequest(2)), + ], + ], ) async def test_get_partial_values( - self, store: S, key_ranges: list[tuple[str, tuple[int | None, int | None]]] + self, store: S, key_ranges: list[tuple[str, ByteRequest]] ) -> None: # put all of the data for key, _ in key_ranges: - self.set(store, key, Buffer.from_bytes(bytes(key, encoding="utf-8"))) + await self.set(store, key, self.buffer_cls.from_bytes(bytes(key, encoding="utf-8"))) - # read back just part of it + # read back just part of it. Pass key_ranges as a one-shot generator + # (a valid Iterable per the method signature) to ensure stores and + # wrappers do not exhaust the iterable before handing it to the backend. observed_maybe = await store.get_partial_values( - prototype=default_buffer_prototype(), key_ranges=key_ranges + prototype=default_buffer_prototype(), + key_ranges=(kr for kr in key_ranges), ) + # One result must be returned per requested key range. Checking this + # explicitly guards against a store/wrapper exhausting the key_ranges + # iterable early and silently returning fewer (or no) results. + assert len(observed_maybe) == len(key_ranges) + observed: list[Buffer] = [] expected: list[Buffer] = [] @@ -131,8 +400,7 @@ async def test_get_partial_values( assert obs is not None observed.append(obs) - for idx in range(len(observed)): - key, byte_range = key_ranges[idx] + for key, byte_range in key_ranges: result = await store.get( key, prototype=default_buffer_prototype(), byte_range=byte_range ) @@ -145,57 +413,431 @@ async def test_get_partial_values( async def test_exists(self, store: S) -> None: assert not await store.exists("foo") - await store.set("foo/zarr.json", Buffer.from_bytes(b"bar")) + await store.set("foo/zarr.json", self.buffer_cls.from_bytes(b"bar")) assert await store.exists("foo/zarr.json") async def test_delete(self, store: S) -> None: - await store.set("foo/zarr.json", Buffer.from_bytes(b"bar")) + if not store.supports_deletes: + pytest.skip("store does not support deletes") + await store.set("foo/zarr.json", self.buffer_cls.from_bytes(b"bar")) assert await store.exists("foo/zarr.json") await store.delete("foo/zarr.json") assert not await store.exists("foo/zarr.json") - async def test_empty(self, store: S) -> None: - assert await store.empty() - self.set(store, "key", Buffer.from_bytes(bytes("something", encoding="utf-8"))) - assert not await store.empty() + async def test_delete_dir(self, store: S) -> None: + if not store.supports_deletes: + pytest.skip("store does not support deletes") + await store.set("zarr.json", self.buffer_cls.from_bytes(b"root")) + await store.set("foo-bar/zarr.json", self.buffer_cls.from_bytes(b"root")) + await store.set("foo/zarr.json", self.buffer_cls.from_bytes(b"bar")) + await store.set("foo/c/0", self.buffer_cls.from_bytes(b"chunk")) + await store.delete_dir("foo") + assert await store.exists("zarr.json") + assert await store.exists("foo-bar/zarr.json") + assert not await store.exists("foo/zarr.json") + assert not await store.exists("foo/c/0") + + async def test_delete_nonexistent_key_does_not_raise(self, store: S) -> None: + if not store.supports_deletes: + pytest.skip("store does not support deletes") + await store.delete("nonexistent_key") + + async def test_is_empty(self, store: S) -> None: + assert await store.is_empty("") + await self.set( + store, "foo/bar", self.buffer_cls.from_bytes(bytes("something", encoding="utf-8")) + ) + assert not await store.is_empty("") + assert await store.is_empty("fo") + assert not await store.is_empty("foo/") + assert not await store.is_empty("foo") + assert await store.is_empty("spam/") async def test_clear(self, store: S) -> None: - self.set(store, "key", Buffer.from_bytes(bytes("something", encoding="utf-8"))) + await self.set( + store, "key", self.buffer_cls.from_bytes(bytes("something", encoding="utf-8")) + ) await store.clear() - assert await store.empty() + assert await store.is_empty("") async def test_list(self, store: S) -> None: - assert [k async for k in store.list()] == [] - await store.set("foo/zarr.json", Buffer.from_bytes(b"bar")) - keys = [k async for k in store.list()] - assert keys == ["foo/zarr.json"], keys - - expected = ["foo/zarr.json"] - for i in range(10): - key = f"foo/c/{i}" - expected.append(key) - await store.set( - f"foo/c/{i}", Buffer.from_bytes(i.to_bytes(length=3, byteorder="little")) - ) + assert await _collect_aiterator(store.list()) == () + prefix = "foo" + data = self.buffer_cls.from_bytes(b"") + store_dict = { + f"{prefix}/zarr.json": data, + **{f"{prefix}/c/{idx}": data for idx in range(10)}, + } + await store._set_many(store_dict.items()) + expected_sorted = sorted(store_dict.keys()) + observed = await _collect_aiterator(store.list()) + observed_sorted = sorted(observed) + assert observed_sorted == expected_sorted - @pytest.mark.xfail async def test_list_prefix(self, store: S) -> None: - # TODO: we currently don't use list_prefix anywhere - raise NotImplementedError + """ + Test that the `list_prefix` method works as intended. Given a prefix, it should return + all the keys in storage that start with this prefix. + """ + prefixes = ("", "a/", "a/b/", "a/b/c/") + data = self.buffer_cls.from_bytes(b"") + fname = "zarr.json" + store_dict = {p + fname: data for p in prefixes} + + await store._set_many(store_dict.items()) + + for prefix in prefixes: + observed = tuple(sorted(await _collect_aiterator(store.list_prefix(prefix)))) + expected: tuple[str, ...] = () + for key in store_dict: + if key.startswith(prefix): + expected += (key,) + expected = tuple(sorted(expected)) + assert observed == expected + + async def test_list_empty_path(self, store: S) -> None: + """ + Verify that list and list_prefix work correctly when path is an empty string, + i.e. no unwanted replacement occurs. + """ + data = self.buffer_cls.from_bytes(b"") + store_dict = { + "foo/bar/zarr.json": data, + "foo/bar/c/1": data, + "foo/baz/c/0": data, + } + await store._set_many(store_dict.items()) + + # Test list() + observed_list = await _collect_aiterator(store.list()) + observed_list_sorted = sorted(observed_list) + expected_list_sorted = sorted(store_dict.keys()) + assert observed_list_sorted == expected_list_sorted + + # Test list_prefix() with an empty prefix + observed_prefix_empty = await _collect_aiterator(store.list_prefix("")) + observed_prefix_empty_sorted = sorted(observed_prefix_empty) + expected_prefix_empty_sorted = sorted(store_dict.keys()) + assert observed_prefix_empty_sorted == expected_prefix_empty_sorted + + # Test list_prefix() with a non-empty prefix + observed_prefix = await _collect_aiterator(store.list_prefix("foo/bar/")) + observed_prefix_sorted = sorted(observed_prefix) + expected_prefix_sorted = sorted(k for k in store_dict if k.startswith("foo/bar/")) + assert observed_prefix_sorted == expected_prefix_sorted async def test_list_dir(self, store: S) -> None: - out = [k async for k in store.list_dir("")] - assert out == [] - assert [k async for k in store.list_dir("foo")] == [] - await store.set("foo/zarr.json", Buffer.from_bytes(b"bar")) - await store.set("foo/c/1", Buffer.from_bytes(b"\x01")) + roots_and_keys: list[tuple[str, dict[str, Buffer]]] = [ + ( + "foo", + { + "foo/zarr.json": self.buffer_cls.from_bytes(b"bar"), + "foo/c/1": self.buffer_cls.from_bytes(b"\x01"), + }, + ), + ( + "foo/bar", + { + "foo/bar/foobar_first_child": self.buffer_cls.from_bytes(b"1"), + "foo/bar/foobar_second_child/zarr.json": self.buffer_cls.from_bytes(b"2"), + }, + ), + ] + + assert await _collect_aiterator(store.list_dir("")) == () + + for root, store_dict in roots_and_keys: + assert await _collect_aiterator(store.list_dir(root)) == () + + await store._set_many(store_dict.items()) + + keys_observed = await _collect_aiterator(store.list_dir(root)) + keys_expected = {k.removeprefix(f"{root}/").split("/")[0] for k in store_dict} + assert sorted(keys_observed) == sorted(keys_expected) + + keys_observed = await _collect_aiterator(store.list_dir(f"{root}/")) + assert sorted(keys_expected) == sorted(keys_observed) + + async def test_set_if_not_exists(self, store: S) -> None: + key = "k" + data_buf = self.buffer_cls.from_bytes(b"0000") + await self.set(store, key, data_buf) + + new = self.buffer_cls.from_bytes(b"1111") + await store.set_if_not_exists("k", new) # no error + + result = await store.get(key, default_buffer_prototype()) + assert result == data_buf + + await store.set_if_not_exists("k2", new) # no error + + result = await store.get("k2", default_buffer_prototype()) + assert result == new + + # ------------------------------------------------------------------- + # Synchronous store methods (SupportsSyncStore protocol) + # ------------------------------------------------------------------- + + def test_get_sync(self, store: S) -> None: + getter = self._require_get_sync(store) + data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") + key = "sync_get" + sync(self.set(store, key, data_buf)) + result = getter.get_sync(key) + assert result is not None + assert_bytes_equal(result, data_buf) + + def test_get_sync_missing(self, store: S) -> None: + getter = self._require_get_sync(store) + result = getter.get_sync("nonexistent") + assert result is None + + def test_set_sync(self, store: S) -> None: + setter = self._require_set_sync(store) + data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") + key = "sync_set" + setter.set_sync(key, data_buf) + result = sync(self.get(store, key)) + assert_bytes_equal(result, data_buf) + + def test_delete_sync(self, store: S) -> None: + setter = self._require_set_sync(store) + deleter = self._require_delete_sync(store) + getter = self._require_get_sync(store) + if not store.supports_deletes: + pytest.skip("store does not support deletes") + data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") + key = "sync_delete" + setter.set_sync(key, data_buf) + deleter.delete_sync(key) + result = getter.get_sync(key) + assert result is None + + def test_delete_sync_missing(self, store: S) -> None: + deleter = self._require_delete_sync(store) + if not store.supports_deletes: + pytest.skip("store does not support deletes") + # should not raise + deleter.delete_sync("nonexistent_sync") + + # ------------------------------------------------------------------- + # Sync/async parity laws + # ------------------------------------------------------------------- + # A store's sync and async methods must observe the same key the same + # way. This is stronger than the individual test_get_sync/test_set_sync/ + # test_delete_sync tests above: those write and read back through the + # *same* API (sync-only or, via `self.set`/`self.get`, bypassing the + # store entirely), so a sync method that skips logic the async method + # applies (e.g. a path prefix) can still pass them. These laws write + # through one API and observe through the other. + + @pytest.mark.parametrize("direction", ["set_async_get_sync", "set_sync_get_async"]) + async def test_sync_async_set_get_parity(self, store: S, direction: str) -> None: + setter = self._require_set_sync(store) + getter = self._require_get_sync(store) + data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") + key = "parity_set_get" + if direction == "set_async_get_sync": + await store.set(key, data_buf) + result = getter.get_sync(key) + else: + setter.set_sync(key, data_buf) + result = await store.get(key, prototype=default_buffer_prototype()) + assert result is not None + assert_bytes_equal(result, data_buf) + + async def test_delete_sync_visible_to_async_get(self, store: S) -> None: + deleter = self._require_delete_sync(store) + if not store.supports_deletes: + pytest.skip("store does not support deletes") + data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") + key = "parity_delete" + await store.set(key, data_buf) + deleter.delete_sync(key) + result = await store.get(key, prototype=default_buffer_prototype()) + assert result is None - keys_expected = ["zarr.json", "c"] - keys_observed = [k async for k in store.list_dir("foo")] + @pytest.mark.parametrize( + "byte_range", + [ + None, + RangeByteRequest(1, 4), + OffsetByteRequest(1), + SuffixByteRequest(1), + RangeByteRequest(10, 20), + ], + ids=["none", "range", "offset", "suffix", "range-past-eof"], + ) + async def test_get_sync_byte_range_parity( + self, store: S, byte_range: ByteRequest | None + ) -> None: + getter = self._require_get_sync(store) + data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") + key = "parity_byte_range" + await store.set(key, data_buf) + sync_result = getter.get_sync(key, byte_range=byte_range) + async_result = await store.get( + key, prototype=default_buffer_prototype(), byte_range=byte_range + ) + if async_result is None: + assert sync_result is None + else: + assert sync_result is not None + assert_bytes_equal(sync_result, async_result) + + +class LatencyStore(WrapperStore[Store]): + """ + A wrapper class that takes any store class in its constructor and + adds latency to the `set` and `get` methods. This can be used for + performance testing. + """ + + _get_latency: float | tuple[float, float] + _set_latency: float | tuple[float, float] + + def __init__( + self, + store: Store, + *, + get_latency: float | tuple[float, float] = 0, + set_latency: float | tuple[float, float] = 0, + ) -> None: + super().__init__(store) + self._get_latency = get_latency if isinstance(get_latency, tuple) else float(get_latency) + self._set_latency = set_latency if isinstance(set_latency, tuple) else float(set_latency) + + @property + def get_latency(self) -> float: + if isinstance(self._get_latency, float): + return self._get_latency + return max(0.0, np.random.normal(loc=self._get_latency[0], scale=self._get_latency[1])) + + @property + def set_latency(self) -> float: + if isinstance(self._set_latency, float): + return self._set_latency + return max(0.0, np.random.normal(loc=self._set_latency[0], scale=self._set_latency[1])) + + def _with_store(self, store: Store) -> Self: + # Pass the raw latency config, not the sampled `get_latency`/`set_latency` + # properties β€” sampling would freeze a `(loc, scale)` distribution into + # one fixed float on derived stores (e.g. via `with_read_only`). + return type(self)(store, get_latency=self._get_latency, set_latency=self._set_latency) + + async def set(self, key: str, value: Buffer) -> None: + """ + Add latency to the ``set`` method. + + Calls ``asyncio.sleep(self.set_latency)`` before invoking the wrapped ``set`` method. - assert len(keys_observed) == len(keys_expected), keys_observed - assert set(keys_observed) == set(keys_expected), keys_observed + Parameters + ---------- + key : str + The key to set + value : Buffer + The value to set + + Returns + ------- + None + """ + await asyncio.sleep(self.set_latency) + await self._store.set(key, value) - keys_observed = [k async for k in store.list_dir("foo/")] - assert len(keys_expected) == len(keys_observed), keys_observed - assert set(keys_observed) == set(keys_expected), keys_observed + async def get( + self, key: str, prototype: BufferPrototype, byte_range: ByteRequest | None = None + ) -> Buffer | None: + """ + Add latency to the ``get`` method. + + Calls ``asyncio.sleep(self.get_latency)`` before invoking the wrapped ``get`` method. + + Parameters + ---------- + key : str + The key to get + prototype : BufferPrototype + The BufferPrototype to use. + byte_range : ByteRequest, optional + An optional byte range. + + Returns + ------- + buffer : Buffer or None + """ + await asyncio.sleep(self.get_latency) + return await self._store.get(key, prototype=prototype, byte_range=byte_range) + + def get_sync( + self, + key: str, + *, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + """Add latency to `get_sync`. + + Sleeps `self.get_latency` on the calling thread (the sync path runs on + worker threads, not the event loop) before delegating to the wrapped + store. + """ + time.sleep(self.get_latency) + return super().get_sync(key, prototype=prototype, byte_range=byte_range) + + def set_sync(self, key: str, value: Buffer) -> None: + """Add latency to `set_sync`. + + Sleeps `self.set_latency` on the calling thread (the sync path runs on + worker threads, not the event loop) before delegating to the wrapped + store. + """ + time.sleep(self.set_latency) + super().set_sync(key, value) + + async def get_ranges( + self, + key: str, + byte_ranges: Sequence[ByteRequest | None], + *, + prototype: BufferPrototype, + max_concurrency: int | None = None, + max_gap_bytes: int | None = None, + max_coalesced_bytes: int | None = None, + ) -> AsyncIterator[Sequence[tuple[int, Buffer | None]]]: + """Byte-range reads built on `self.get`, so each fetch pays latency. + + Routes through the coalescing `Store.get_ranges` default instead of the + `WrapperStore` delegation, which would bypass this wrapper's `get` and + therefore the synthetic latency. `None` for a coalescing kwarg means + "use the `Store` default". + """ + kwargs: dict[str, int] = {} + if max_concurrency is not None: + kwargs["max_concurrency"] = max_concurrency + if max_gap_bytes is not None: + kwargs["max_gap_bytes"] = max_gap_bytes + if max_coalesced_bytes is not None: + kwargs["max_coalesced_bytes"] = max_coalesced_bytes + async for group in Store.get_ranges(self, key, byte_ranges, prototype=prototype, **kwargs): + yield group + + async def get_partial_values( + self, + prototype: BufferPrototype, + key_ranges: Iterable[tuple[str, ByteRequest | None]], + ) -> list[Buffer | None]: + """Partial-value reads built on `self.get`, so each fetch pays latency. + + Issues one `self.get` per `(key, byte_range)` pair instead of the + `WrapperStore` delegation, which would bypass this wrapper's `get` and + therefore the synthetic latency. + """ + return list( + await asyncio.gather( + *( + self.get(key, prototype=prototype, byte_range=byte_range) + for key, byte_range in key_ranges + ) + ) + ) diff --git a/src/zarr/testing/strategies.py b/src/zarr/testing/strategies.py new file mode 100644 index 0000000000..6679dbcee4 --- /dev/null +++ b/src/zarr/testing/strategies.py @@ -0,0 +1,826 @@ +import itertools +import math +import sys +from collections.abc import Callable, Mapping +from typing import Any, Literal + +import hypothesis.extra.numpy as npst +import hypothesis.strategies as st +import numpy as np +import numpy.typing as npt +from hypothesis import event +from hypothesis.strategies import SearchStrategy + +import zarr +from zarr.abc.store import ( + ByteRequest, + OffsetByteRequest, + RangeByteRequest, + Store, + SuffixByteRequest, +) +from zarr.codecs.bytes import BytesCodec +from zarr.codecs.crc32c_ import Crc32cCodec +from zarr.codecs.sharding import SUBCHUNK_WRITE_ORDER, ShardingCodec, SubchunkWriteOrder +from zarr.codecs.zstd import ZstdCodec +from zarr.core.array import Array, CompressorsLike, SerializerLike +from zarr.core.chunk_key_encodings import DefaultChunkKeyEncoding +from zarr.core.common import JSON, AccessModeLiteral, ZarrFormat +from zarr.core.dtype import get_data_type_from_native_dtype +from zarr.core.metadata import ArrayV2Metadata, ArrayV3Metadata +from zarr.core.metadata.v3 import RectilinearChunkGridMetadata, RegularChunkGridMetadata +from zarr.core.sync import sync +from zarr.storage import MemoryStore, StoreLike +from zarr.storage._utils import _join_paths, normalize_path +from zarr.types import AnyArray + +TrueOrFalse = Literal[True, False] + +# Copied from Xarray +_attr_keys = st.text(st.characters(), min_size=1) +_attr_values = st.recursive( + st.none() | st.booleans() | st.text(st.characters(), max_size=5), + lambda children: st.lists(children) | st.dictionaries(_attr_keys, children), + max_leaves=3, +) + + +@st.composite +def keys(draw: st.DrawFn, *, max_num_nodes: int | None = None) -> str: + return draw(st.lists(node_names, min_size=1, max_size=max_num_nodes).map("/".join)) + + +@st.composite +def paths(draw: st.DrawFn, *, max_num_nodes: int | None = None) -> str: + return draw(st.just("/") | keys(max_num_nodes=max_num_nodes)) + + +def dtypes() -> st.SearchStrategy[np.dtype[Any]]: + return ( + npst.boolean_dtypes() + | npst.integer_dtypes(endianness="=") + | npst.unsigned_integer_dtypes(endianness="=") + | npst.floating_dtypes(endianness="=") + | npst.complex_number_dtypes(endianness="=") + | npst.byte_string_dtypes(endianness="=") + | npst.unicode_string_dtypes(endianness="=") + | npst.datetime64_dtypes(endianness="=") + | npst.timedelta64_dtypes(endianness="=") + ) + + +def v3_dtypes() -> st.SearchStrategy[np.dtype[Any]]: + return dtypes() + + +def v2_dtypes() -> st.SearchStrategy[np.dtype[Any]]: + return dtypes() + + +def safe_unicode_for_dtype(dtype: np.dtype[np.str_]) -> st.SearchStrategy[str]: + """Generate UTF-8-safe text constrained to max_len of dtype.""" + # account for utf-32 encoding (i.e. 4 bytes/character) + max_len = max(1, dtype.itemsize // 4) + + return st.text( + alphabet=st.characters( + exclude_categories=["Cs"], # Avoid *technically allowed* surrogates + min_codepoint=32, + ), + min_size=1, + max_size=max_len, + ) + + +def clear_store(x: Store) -> Store: + sync(x.clear()) + return x + + +# From https://zarr-specs.readthedocs.io/en/latest/v3/core/v3.0.html#node-names +# 1. must not be the empty string ("") +# 2. must not include the character "/" +# 3. must not be a string composed only of period characters, e.g. "." or ".." +# 4. must not start with the reserved prefix "__" +zarr_key_chars = st.sampled_from( + ".-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz" +) +node_names = ( + st.text(zarr_key_chars, min_size=1) + .filter(lambda t: t not in (".", "..") and not t.startswith("__")) + .filter(lambda name: name.lower() != "zarr.json") +) +short_node_names = ( + st.text(zarr_key_chars, max_size=3, min_size=1) + .filter(lambda t: t not in (".", "..") and not t.startswith("__")) + .filter(lambda name: name.lower() != "zarr.json") +) +array_names = node_names +attrs: st.SearchStrategy[Mapping[str, JSON] | None] = st.none() | st.dictionaries( + _attr_keys, _attr_values +) +# st.builds will only call a new store constructor for different keyword arguments +# i.e. stores.examples() will always return the same object per Store class. +# So we map a clear to reset the store. +stores = st.builds(MemoryStore, st.just({})).map(clear_store) +compressors = st.sampled_from([None, "default"]) +zarr_formats: st.SearchStrategy[ZarrFormat] = st.sampled_from([3, 2]) +# We de-prioritize arrays having dim sizes 0, 1, 2 +array_shapes = npst.array_shapes(max_dims=4, min_side=3, max_side=5) | npst.array_shapes( + max_dims=4, min_side=0 +) + + +@st.composite +def dimension_names(draw: st.DrawFn, *, ndim: int | None = None) -> list[str | None] | None: + simple_text = st.text(zarr_key_chars, min_size=0) + return draw(st.none() | st.lists(st.none() | simple_text, min_size=ndim, max_size=ndim)) # type: ignore[arg-type] + + +subchunk_write_orders: st.SearchStrategy[SubchunkWriteOrder] = st.sampled_from(SUBCHUNK_WRITE_ORDER) + +# Inner codec chains for a ShardingCodec. We MUST sample the uncompressed, +# single-BytesCodec configuration (no Zstd) β€” that is the only configuration in +# which the FusedCodecPipeline's vectorized whole-shard "bulk decode" fast path +# engages, so it is the only one that can exercise (and regress-guard) that path +# against arbitrary indexing. Freezing the inner codecs to [BytesCodec, ZstdCodec] +# silently disables the fast path under every property test. +sharding_inner_codecs: st.SearchStrategy[list[BytesCodec | ZstdCodec]] = st.sampled_from( + [ + [BytesCodec()], + [BytesCodec(), ZstdCodec()], + ] +) + + +@st.composite +def array_metadata( + draw: st.DrawFn, + *, + array_shapes: Callable[..., st.SearchStrategy[tuple[int, ...]]] = npst.array_shapes, + zarr_formats: st.SearchStrategy[ZarrFormat] = zarr_formats, + attributes: SearchStrategy[Mapping[str, JSON] | None] = attrs, +) -> ArrayV2Metadata | ArrayV3Metadata: + zarr_format = draw(zarr_formats) + # separator = draw(st.sampled_from(['/', '\\'])) + shape = draw(array_shapes()) + ndim = len(shape) + np_dtype = draw(dtypes()) + dtype = get_data_type_from_native_dtype(np_dtype) + fill_value = draw(npst.from_dtype(np_dtype)) + if zarr_format == 2: + chunk_shape = draw(array_shapes(min_dims=ndim, max_dims=ndim, min_side=1)) + return ArrayV2Metadata( + shape=shape, + chunks=chunk_shape, + dtype=dtype, + fill_value=fill_value, + order=draw(st.sampled_from(["C", "F"])), + attributes=draw(attributes), # type: ignore[arg-type] + dimension_separator=draw(st.sampled_from([".", "/"])), + filters=None, + compressor=None, + ) + else: + chunk_grid = draw(chunk_grids(shape=shape)) + return ArrayV3Metadata( + shape=shape, + data_type=dtype, + chunk_grid=chunk_grid, + fill_value=fill_value, + attributes=draw(attributes), # type: ignore[arg-type] + dimension_names=draw(dimension_names(ndim=ndim)), + chunk_key_encoding=DefaultChunkKeyEncoding(separator="/"), # FIXME + codecs=[BytesCodec()], + storage_transformers=(), + ) + + +@st.composite +def numpy_arrays( + draw: st.DrawFn, + *, + shapes: st.SearchStrategy[tuple[int, ...]] = array_shapes, + dtype: np.dtype[Any] | None = None, +) -> npt.NDArray[Any]: + """ + Generate numpy arrays that can be saved in the provided Zarr format. + """ + if dtype is None: + dtype = draw(dtypes()) + if np.issubdtype(dtype, np.str_): + safe_unicode_strings = safe_unicode_for_dtype(dtype) + return draw(npst.arrays(dtype=dtype, shape=shapes, elements=safe_unicode_strings)) + + return draw(npst.arrays(dtype=dtype, shape=shapes)) + + +@st.composite +def chunk_shapes(draw: st.DrawFn, *, shape: tuple[int, ...]) -> tuple[int, ...]: + # We want this strategy to shrink towards arrays with smaller number of chunks + # 1. st.integers() shrinks towards smaller values. So we use that to generate number of chunks + numchunks = draw( + st.tuples( + *[ + st.integers(min_value=0 if size == 0 else 1, max_value=max(size, 1)) + for size in shape + ] + ) + ) + # 2. and now generate the chunks tuple + # Chunk sizes must be >= 1 per spec; for zero-extent dimensions use 1. + chunks = tuple( + max(1, size // nchunks) if nchunks > 0 else 1 + for size, nchunks in zip(shape, numchunks, strict=True) + ) + + for c in chunks: + event("chunk size", c) + + if any((c != 0 and s % c != 0) for s, c in zip(shape, chunks, strict=True)): + event("smaller last chunk") + + return chunks + + +@st.composite +def shard_shapes( + draw: st.DrawFn, *, shape: tuple[int, ...], chunk_shape: tuple[int, ...] +) -> tuple[int, ...]: + # We want this strategy to shrink towards arrays with smaller number of shards + # shards must be an integral number of chunks + assert all(c != 0 for c in chunk_shape) + numchunks = tuple(s // c for s, c in zip(shape, chunk_shape, strict=True)) + multiples = tuple(draw(st.integers(min_value=1, max_value=nc)) for nc in numchunks) + return tuple(m * c for m, c in zip(multiples, chunk_shape, strict=True)) + + +@st.composite +def np_array_and_chunks( + draw: st.DrawFn, + *, + arrays: st.SearchStrategy[npt.NDArray[Any]] = numpy_arrays(), # noqa: B008 +) -> tuple[np.ndarray[Any, Any], tuple[int, ...]]: + """A hypothesis strategy to generate small sized random arrays. + + Returns: a tuple of the array and a suitable random chunking for it. + """ + array = draw(arrays) + return (array, draw(chunk_shapes(shape=array.shape))) + + +@st.composite +def arrays( + draw: st.DrawFn, + *, + shapes: st.SearchStrategy[tuple[int, ...]] = array_shapes, + compressors: st.SearchStrategy = compressors, + stores: st.SearchStrategy[StoreLike] = stores, + paths: st.SearchStrategy[str] = paths(), # noqa: B008 + array_names: st.SearchStrategy = array_names, + arrays: st.SearchStrategy | None = None, + attrs: st.SearchStrategy = attrs, + zarr_formats: st.SearchStrategy = zarr_formats, + subchunk_write_orders: SearchStrategy[SubchunkWriteOrder] = subchunk_write_orders, + open_mode: AccessModeLiteral = "w", +) -> AnyArray: + store = draw(stores, label="store") + path = draw(paths, label="array parent") + name = draw(array_names, label="array name") + attributes = draw(attrs, label="attributes") + zarr_format = draw(zarr_formats, label="zarr format") + if arrays is None: + arrays = numpy_arrays(shapes=shapes) + nparray = draw(arrays, label="array data") + dim_names: list[str | None] | None = None + serializer: SerializerLike = "auto" + compressors_unsearched: CompressorsLike = "auto" + + # For v3 arrays, optionally use RectilinearChunkGridMetadata + chunk_grid_meta: RegularChunkGridMetadata | RectilinearChunkGridMetadata | None = None + + # test that None works too. + fill_value = draw(st.one_of([st.none(), npst.from_dtype(nparray.dtype)])) + # compressor = draw(compressors) + + expected_attrs = {} if attributes is None else attributes + + array_path = _join_paths([path, name]) + root = zarr.open_group(store, mode=open_mode, zarr_format=zarr_format) + + # Convert chunk grid metadata to a form create_array accepts: + # - RegularChunkGridMetadata -> flat tuple of ints + # - RectilinearChunkGridMetadata -> nested list of ints (triggers rectilinear path) + # - v2 -> flat tuple of ints + chunks_param: tuple[int, ...] | list[list[int]] + shard_shape = None + dim_names = None + if zarr_format == 3: + chunk_grid_meta = draw(st.none() | chunk_grids(shape=nparray.shape), label="chunk grid") + dim_names = draw(dimension_names(ndim=nparray.ndim), label="dimension names") + if isinstance(chunk_grid_meta, RectilinearChunkGridMetadata): + chunks_param = [ + list(dim) if isinstance(dim, tuple) else [dim] + for dim in chunk_grid_meta.chunk_shapes + ] + elif isinstance(chunk_grid_meta, RegularChunkGridMetadata): + chunks_param = chunk_grid_meta.chunk_shape + else: + chunks_param = draw(chunk_shapes(shape=nparray.shape), label="chunk shape") + + if all(s > c > 1 for s, c in zip(nparray.shape, chunks_param, strict=True)): + shard_shape = draw( + st.none() | shard_shapes(shape=nparray.shape, chunk_shape=chunks_param), + label="shard shape", + ) + if shard_shape is not None: + subchunk_write_order = draw(subchunk_write_orders) + inner_codecs = draw(sharding_inner_codecs, label="sharding inner codecs") + serializer = ShardingCodec( + subchunk_write_order=subchunk_write_order, + codecs=inner_codecs, + index_codecs=[BytesCodec(), Crc32cCodec()], + chunk_shape=chunks_param, + ) + compressors_unsearched = None + else: + chunks_param = draw(chunk_shapes(shape=nparray.shape), label="chunk shape") + a = root.create_array( + array_path, + shape=nparray.shape, + chunks=chunks_param, + shards=shard_shape, + dtype=nparray.dtype, + attributes=attributes, + compressors=compressors_unsearched, # FIXME + fill_value=fill_value, + dimension_names=dim_names, + serializer=serializer, + ) + + assert isinstance(a, Array) + if a.metadata.zarr_format == 3: + assert a.fill_value is not None + assert a.name is not None + assert a.path == normalize_path(array_path) + assert a.name == f"/{a.path}" + assert isinstance(root[array_path], Array) + assert nparray.shape == a.shape + + # Verify chunks β€” for rectilinear grids, .chunks raises + if zarr_format == 3: + assert shard_shape == a.shards + if isinstance(a.metadata.chunk_grid, RegularChunkGridMetadata): + assert a.metadata.chunk_grid.chunk_shape == ( + a.shards if shard_shape is not None else a.chunks + ) + assert shard_shape == a.shards + else: + assert isinstance(a.metadata.chunk_grid, RectilinearChunkGridMetadata) + assert shard_shape is None + + assert a.basename == name, (a.basename, name) + assert dict(a.attrs) == expected_attrs + + a[:] = nparray + + return a + + +@st.composite +def simple_arrays( + draw: st.DrawFn, + *, + shapes: st.SearchStrategy[tuple[int, ...]] = array_shapes, +) -> Any: + return draw( + arrays( + shapes=shapes, + paths=paths(max_num_nodes=2), + array_names=short_node_names, + attrs=st.none(), + compressors=st.sampled_from([None, "default"]), + ) + ) + + +@st.composite +def rectilinear_chunks(draw: st.DrawFn, *, shape: tuple[int, ...]) -> list[list[int]]: + """Generate valid rectilinear chunk shapes for a given array shape. + + Uses two modes per dimension: + - "expanded": random divider points create arbitrary chunk sizes + - "rle": uniform chunks with optional remainder, optionally shuffled + + Keeps max chunks per dimension <= 20 to avoid performance issues + in property tests. With higher dimensions, the total chunk count + grows multiplicatively. + """ + chunk_shapes: list[list[int]] = [] + for size in shape: + assert size > 0 + if size > 1: + mode = draw(st.sampled_from(["expanded", "rle"])) + if mode == "expanded": + event("rectilinear expanded") + max_chunks = min(size - 1, 20) + nchunks = draw(st.integers(min_value=1, max_value=max_chunks)) + dividers = sorted( + draw( + st.lists( + st.integers(min_value=1, max_value=size - 1), + min_size=nchunks - 1, + max_size=nchunks - 1, + unique=True, + ) + ) + ) + chunk_shapes.append( + [a - b for a, b in zip(dividers + [size], [0] + dividers, strict=False)] + ) + else: + # RLE mode: uniform chunks with optional remainder + max_chunk_size = min(size, 20) + chunk_size = draw(st.integers(min_value=1, max_value=max_chunk_size)) + n_full = size // chunk_size + remainder = size % chunk_size + chunks_list = [chunk_size] * n_full + if remainder > 0: + chunks_list.append(remainder) + # Optionally shuffle to create non-contiguous duplicate patterns + if draw(st.booleans()): + event("rectilinear rle shuffled") + chunks_list = draw(st.permutations(chunks_list)) + else: + event("rectilinear rle") + chunk_shapes.append(list(chunks_list)) + else: + chunk_shapes.append([1]) + return chunk_shapes + + +@st.composite +def chunk_grids( + draw: st.DrawFn, *, shape: tuple[int, ...] +) -> RegularChunkGridMetadata | RectilinearChunkGridMetadata: + """Generate either a RegularChunkGridMetadata or RectilinearChunkGridMetadata. + + This strategy depends on the global state of the config having rectilinear chunk grids enabled or not. + This means that it may be a possible source of a hypothesis FlakyStrategy error due dependence + on global state. However, in practice this seems unlikely to happen. + + This allows property tests to exercise both chunk grid types. + """ + # RectilinearChunkGridMetadata doesn't support zero-sized dimensions, + # so use RegularChunkGridMetadata if any dimension is 0 + if any(s == 0 for s in shape): + event("using RegularChunkGridMetadata (zero-sized dimensions)") + return RegularChunkGridMetadata(chunk_shape=draw(chunk_shapes(shape=shape))) + + if zarr.config.get("array.rectilinear_chunks") and draw(st.booleans()): + chunks = draw(rectilinear_chunks(shape=shape)) + event("using RectilinearChunkGridMetadata") + return RectilinearChunkGridMetadata(chunk_shapes=tuple(tuple(dim) for dim in chunks)) + else: + event("using RegularChunkGridMetadata") + return RegularChunkGridMetadata(chunk_shape=draw(chunk_shapes(shape=shape))) + + +# Rectilinear arrays need min_side >= 1 so every dimension has at least one element +_rectilinear_shapes = npst.array_shapes(max_dims=3, min_side=1, max_side=20) + + +@st.composite +def rectilinear_arrays( + draw: st.DrawFn, + *, + shapes: st.SearchStrategy[tuple[int, ...]] = _rectilinear_shapes, +) -> Any: + """Generate a zarr v3 array with rectilinear (variable) chunk grid.""" + shape = draw(shapes) + chunk_shapes = draw(rectilinear_chunks(shape=shape)) + + np_dtype = draw(dtypes()) + nparray = draw(numpy_arrays(shapes=st.just(shape), dtype=np_dtype)) + fill_value = draw(st.one_of([st.none(), npst.from_dtype(np_dtype)])) + dim_names = draw(dimension_names(ndim=len(shape))) + + store = MemoryStore() + with zarr.config.set({"array.rectilinear_chunks": True}): + a = zarr.create_array( + store=store, + shape=shape, + chunks=chunk_shapes, + dtype=np_dtype, + fill_value=fill_value, + dimension_names=dim_names, + ) + a[:] = nparray + + return a + + +def is_negative_slice(idx: Any) -> bool: + return isinstance(idx, slice) and idx.step is not None and idx.step < 0 + + +@st.composite +def end_slices(draw: st.DrawFn, *, shape: tuple[int, ...]) -> Any: + """ + A strategy that slices ranges that include the last chunk. + This is intended to stress-test handling of a possibly smaller last chunk. + """ + slicers = [] + for size in shape: + start = draw(st.integers(min_value=size // 2, max_value=size - 1)) + length = draw(st.integers(min_value=0, max_value=size - start)) + slicers.append(slice(start, start + length)) + event("drawing end slice") + return tuple(slicers) + + +@st.composite +def basic_indices( + draw: st.DrawFn, + *, + shape: tuple[int, ...], + min_dims: int = 0, + max_dims: int | None = None, + allow_newaxis: TrueOrFalse = False, + allow_ellipsis: TrueOrFalse = True, +) -> Any: + """Basic indices without unsupported negative slices.""" + strategy = npst.basic_indices( + shape=shape, + min_dims=min_dims, + max_dims=max_dims, + allow_newaxis=allow_newaxis, + allow_ellipsis=allow_ellipsis, + ).filter( + lambda idxr: ( + not ( + is_negative_slice(idxr) + or (isinstance(idxr, tuple) and any(is_negative_slice(idx) for idx in idxr)) + ) + ) + ) + if math.prod(shape) >= 3: + strategy = end_slices(shape=shape) | strategy + return draw(strategy) + + +@st.composite +def orthogonal_indices( + draw: st.DrawFn, *, shape: tuple[int, ...] +) -> tuple[tuple[np.ndarray[Any, Any], ...], tuple[np.ndarray[Any, Any], ...]]: + """ + Strategy that returns + (1) a tuple of integer arrays used for orthogonal indexing of Zarr arrays. + (2) a tuple of integer arrays that can be used for equivalent indexing of numpy arrays + """ + zindexer = [] + npindexer = [] + ndim = len(shape) + for axis, size in enumerate(shape): + if size != 0: + strategy = npst.integer_array_indices( + shape=(size,), result_shape=npst.array_shapes(min_side=1, max_side=size, max_dims=1) + ) | basic_indices(min_dims=1, shape=(size,), allow_ellipsis=False) + else: + strategy = basic_indices(min_dims=1, shape=(size,), allow_ellipsis=False) + + val = draw( + strategy + # bare ints, slices + .map(lambda x: (x,) if not isinstance(x, tuple) else x) + # skip empty tuple + .filter(bool) + ) + (idxr,) = val + if isinstance(idxr, int): + idxr = np.array([idxr]) + zindexer.append(idxr) + if isinstance(idxr, slice): + idxr = np.arange(*idxr.indices(size)) + elif isinstance(idxr, (tuple, int)): + idxr = np.array(idxr) + newshape = [1] * ndim + newshape[axis] = idxr.size + npindexer.append(idxr.reshape(newshape)) + + # casting the output of broadcast_arrays is needed for numpy < 2 + return tuple(zindexer), tuple(np.broadcast_arrays(*npindexer)) + + +@st.composite +def block_indices( + draw: st.DrawFn, *, chunk_sizes: tuple[tuple[int, ...], ...] +) -> tuple[tuple[int | slice, ...], tuple[slice, ...]]: + """ + Strategy for block-selection indexers over a chunk grid. + + Block indexing is basic indexing applied to the block grid (the grid of + chunks), so each axis is drawn with ``basic_indices`` over that axis's chunk + count, mirroring how ``orthogonal_indices`` reuses ``basic_indices`` per + axis. ``chunk_sizes`` gives the per-chunk data sizes of the array's *outer* + (block) grid for every axis β€” i.e. ``Array.write_chunk_sizes``, the grid that + ``Array.blocks`` addresses (the shard grid when sharding is used). For + example ``(3, 3, 3, 1)`` for a length-10 axis with a regular chunk size of 3, + or the explicit edges of a rectilinear axis; ``nchunks`` for an axis is + ``len(chunk_sizes[axis])``. + + The array-space translation uses the cumulative sum of those sizes, matching + ``BlockIndexer``'s use of ``dim_grid.chunk_offset``. Because the sizes are + clipped to the array extent, the final offset equals the extent and the + translation is exact for regular (uniform), rectilinear, and sharded grids + alike. + + Block indexing only supports integers and step-1 slices whose start + references an existing chunk, so strided slices and slices starting at the + grid edge are filtered out. + + Returns + ------- + block_indexer + A per-axis tuple of ints / step-1 slices addressing whole chunks, + suitable for ``Array.blocks`` / ``get_block_selection`` / ``set_block_selection``. + array_indexer + The equivalent array-space selection (a tuple of slices) for indexing + the corresponding numpy array, used as the comparison oracle. + """ + + def supported(nchunks: int) -> Callable[[tuple[Any, ...]], bool]: + # Block indexing only accepts step-1 slices whose start references an + # existing chunk (a slice starting at nchunks raises, unlike numpy). + def predicate(value: tuple[Any, ...]) -> bool: + dim_sel = value[0] + if isinstance(dim_sel, slice): + if dim_sel.step not in (None, 1): + return False + start = dim_sel.start or 0 + return 0 <= (start + nchunks if start < 0 else start) < nchunks + return True + + return predicate + + block_indexer: list[int | slice] = [] + array_indexer: list[slice] = [] + for sizes in chunk_sizes: + nchunks = len(sizes) + # offsets[i] is the array-space start of chunk i; length nchunks + 1. + offsets = list(itertools.accumulate(sizes, initial=0)) + dim_strategy = ( + basic_indices(min_dims=1, shape=(nchunks,), allow_ellipsis=False) + # normalize bare ints / slices to a 1-tuple, skip the empty tuple + .map(lambda x: (x,) if not isinstance(x, tuple) else x) + .filter(bool) + .filter(supported(nchunks)) + ) + # basic_indices draws slices far more often than bare integers, so the + # integer (single-block) branch below would only be hit on rare draws. + # Union in an explicit integer so it is reliably exercised β€” keeping + # coverage deterministic under the derandomized ``ci`` Hypothesis profile. + (dim_sel,) = draw( + dim_strategy | st.integers(min_value=0, max_value=nchunks - 1).map(lambda i: (i,)) + ) + block_indexer.append(dim_sel) + if isinstance(dim_sel, slice): + start, stop, _ = dim_sel.indices(nchunks) + array_indexer.append(slice(offsets[start], offsets[stop])) + else: + block = dim_sel % nchunks + array_indexer.append(slice(offsets[block], offsets[block + 1])) + return tuple(block_indexer), tuple(array_indexer) + + +@st.composite +def block_test_arrays( + draw: st.DrawFn, +) -> tuple[Array[Any], np.ndarray[Any, Any]]: + """Draw an array for block-indexing property tests, with its source contents. + + Two arms, selected with equal probability: + + - **regular**: a regular chunk grid, optionally wrapped in sharding. + - **rectilinear**: a variable (rectilinear) chunk grid, always unsharded. + + Returns ``(zarray, nparray)``. The per-axis block sizes the oracle needs are + ``zarray.write_chunk_sizes`` β€” the array's *outer* (block / shard) grid, which + is exactly the grid ``Array.blocks`` addresses; the caller reads it directly. + """ + chunks: tuple[int, ...] | list[list[int]] + if draw(st.booleans()): + # regular arm, optionally sharded + nparray, chunks = draw( + np_array_and_chunks( + arrays=numpy_arrays(shapes=npst.array_shapes(max_dims=4, min_side=1)) + ) + ) + # min_side=1 chunking guarantees shape // chunk >= 1 on every axis, which + # shard_shapes requires. + shards = draw(st.none() | shard_shapes(shape=nparray.shape, chunk_shape=chunks)) + event("block regular sharded" if shards is not None else "block regular unsharded") + rectilinear = False + else: + # rectilinear arm, always unsharded + event("block rectilinear") + shape = draw(_rectilinear_shapes) + chunks = draw(rectilinear_chunks(shape=shape)) + nparray = draw(numpy_arrays(shapes=st.just(shape), dtype=draw(dtypes()))) + shards, rectilinear = None, True + + store = draw(stores) + with zarr.config.set({"array.rectilinear_chunks": rectilinear}): + zarray = zarr.create_array( + store=store, + shape=nparray.shape, + chunks=chunks, + shards=shards, + dtype=nparray.dtype, + ) + zarray[...] = nparray + return zarray, nparray + + +def key_ranges( + keys: SearchStrategy[str] = node_names, max_size: int = sys.maxsize +) -> SearchStrategy[list[tuple[str, ByteRequest | None]]]: + """ + Function to generate key_ranges strategy for get_partial_values() + returns list strategy w/ form:: + + [(key, byte_request), + (key, byte_request),...] + + where ``byte_request`` is ``None`` or any of the concrete ``ByteRequest`` + subtypes. The bounds are drawn independently of each value's length, so the + offsets/suffixes routinely exceed the data and exercise the clamping logic + in ``_normalize_byte_range_index``. + """ + + def make_range(start: int, length: int) -> RangeByteRequest: + return RangeByteRequest(start, end=min(start + length, max_size)) + + bound = st.integers(min_value=0, max_value=max_size) + byte_ranges: SearchStrategy[ByteRequest | None] = st.one_of( + st.none(), + st.builds(make_range, start=bound, length=bound), + st.builds(OffsetByteRequest, offset=bound), + st.builds(SuffixByteRequest, suffix=bound), + ) + key_tuple = st.tuples(keys, byte_ranges) + return st.lists(key_tuple, min_size=1, max_size=10) + + +@st.composite +def complex_rectilinear_arrays( + draw: st.DrawFn, + *, + stores: st.SearchStrategy[StoreLike] = stores, + paths: st.SearchStrategy[str] = paths(), # noqa: B008 + array_names: st.SearchStrategy = array_names, + attrs: st.SearchStrategy = attrs, +) -> tuple[npt.NDArray[Any], AnyArray]: + """Generate a rectilinear array with many small chunks. + + The shape is derived from the chunk edges (5-10 chunks per dim, + sizes 1-5), exercising higher chunk counts than ``rectilinear_arrays``. + """ + ndim = draw(st.integers(min_value=1, max_value=3)) + nchunks = draw(st.integers(min_value=5, max_value=10)) + dim_chunks = st.lists(st.integers(min_value=1, max_value=5), min_size=nchunks, max_size=nchunks) + chunk_shapes = draw(st.lists(dim_chunks, min_size=ndim, max_size=ndim)) + + shape = tuple(sum(dim) for dim in chunk_shapes) + nparray = draw(numpy_arrays(shapes=st.just(shape))) + dim_names = draw(dimension_names(ndim=ndim)) + fill_value = draw(st.one_of([st.none(), npst.from_dtype(nparray.dtype)])) + attributes = draw(attrs) + + store = draw(stores, label="store") + path = draw(paths, label="array parent") + name = draw(array_names, label="array name") + array_path = _join_paths([path, name]) + + root = zarr.open_group(store, mode="w", zarr_format=3) + with zarr.config.set({"array.rectilinear_chunks": True}): + a = root.create_array( + array_path, + shape=shape, + chunks=chunk_shapes, + dtype=nparray.dtype, + fill_value=fill_value, + dimension_names=dim_names, + attributes=attributes, + ) + a[:] = nparray + return nparray, a + + +@st.composite +def chunk_paths(draw: st.DrawFn, ndim: int, numblocks: tuple[int, ...], subset: bool = True) -> str: + blockidx = draw( + st.tuples(*tuple(st.integers(min_value=0, max_value=max(0, b - 1)) for b in numblocks)) + ) + subset_slicer = slice(draw(st.integers(min_value=0, max_value=ndim))) if subset else slice(None) + return "/".join(map(str, blockidx[subset_slicer])) diff --git a/src/zarr/testing/utils.py b/src/zarr/testing/utils.py index 67c6c72de7..94f73f6798 100644 --- a/src/zarr/testing/utils.py +++ b/src/zarr/testing/utils.py @@ -1,7 +1,15 @@ from __future__ import annotations -from zarr.buffer import Buffer -from zarr.common import BytesLike +from typing import TYPE_CHECKING, cast + +import pytest + +from zarr.core.buffer import Buffer + +if TYPE_CHECKING: + from zarr.core.common import BytesLike + +__all__ = ["assert_bytes_equal"] def assert_bytes_equal(b1: Buffer | BytesLike | None, b2: Buffer | BytesLike | None) -> None: @@ -16,3 +24,23 @@ def assert_bytes_equal(b1: Buffer | BytesLike | None, b2: Buffer | BytesLike | N if isinstance(b2, Buffer): b2 = b2.to_bytes() assert b1 == b2 + + +def has_cupy() -> bool: + try: + import cupy + + return cast("bool", cupy.cuda.runtime.getDeviceCount() > 0) + except ImportError: + return False + except cupy.cuda.runtime.CUDARuntimeError: + return False + + +gpu_mark = pytest.mark.gpu +skip_if_no_gpu = pytest.mark.skipif(not has_cupy(), reason="CuPy not installed or no GPU available") + + +# Decorator for GPU tests +def gpu_test[T](func: T) -> T: + return cast(T, gpu_mark(skip_if_no_gpu(func))) diff --git a/src/zarr/types.py b/src/zarr/types.py new file mode 100644 index 0000000000..8b77d344b2 --- /dev/null +++ b/src/zarr/types.py @@ -0,0 +1,38 @@ +from typing import Any + +from zarr.core.array import Array, AsyncArray +from zarr.core.common import JSON, ZarrFormat +from zarr.core.dtype.common import DTypeConfig_V2, DTypeJSON +from zarr.core.metadata.v2 import ArrayV2Metadata +from zarr.core.metadata.v3 import ArrayV3Metadata + +type AnyAsyncArray = AsyncArray[Any] +"""A Zarr format 2 or 3 `AsyncArray`""" + +type AsyncArrayV2 = AsyncArray[ArrayV2Metadata] +"""A Zarr format 2 `AsyncArray`""" + +type AsyncArrayV3 = AsyncArray[ArrayV3Metadata] +"""A Zarr format 3 `AsyncArray`""" + +type AnyArray = Array[Any] +"""A Zarr format 2 or 3 `Array`""" + +type ArrayV2 = Array[ArrayV2Metadata] +"""A Zarr format 2 `Array`""" + +type ArrayV3 = Array[ArrayV3Metadata] +"""A Zarr format 3 `Array`""" + +__all__ = ( + "JSON", + "AnyArray", + "AnyAsyncArray", + "ArrayV2", + "ArrayV3", + "AsyncArrayV2", + "AsyncArrayV3", + "DTypeConfig_V2", + "DTypeJSON", + "ZarrFormat", +) diff --git a/src/zarr/v2/__init__.py b/src/zarr/v2/__init__.py deleted file mode 100644 index 27c7595580..0000000000 --- a/src/zarr/v2/__init__.py +++ /dev/null @@ -1,54 +0,0 @@ -# flake8: noqa -from zarr.v2.codecs import * -from zarr.v2.convenience import ( - consolidate_metadata, - copy, - copy_all, - copy_store, - load, - open, - open_consolidated, - save, - save_array, - save_group, - tree, -) -from zarr.v2.core import Array -from zarr.v2.creation import ( - array, - create, - empty, - empty_like, - full, - full_like, - ones, - ones_like, - open_array, - open_like, - zeros, - zeros_like, -) -from zarr.v2.errors import CopyError, MetadataError -from zarr.v2.hierarchy import Group, group, open_group -from zarr.v2.n5 import N5Store, N5FSStore -from zarr.v2.storage import ( - ABSStore, - DBMStore, - DictStore, - DirectoryStore, - KVStore, - LMDBStore, - LRUStoreCache, - MemoryStore, - MongoDBStore, - NestedDirectoryStore, - RedisStore, - SQLiteStore, - TempStore, - ZipStore, -) -from zarr.v2.sync import ProcessSynchronizer, ThreadSynchronizer -from zarr._version import version as __version__ - -# in case setuptools scm screw up and find version to be 0.0.0 -assert not __version__.startswith("0.0.0") diff --git a/src/zarr/v2/_storage/absstore.py b/src/zarr/v2/_storage/absstore.py deleted file mode 100644 index c04ad240da..0000000000 --- a/src/zarr/v2/_storage/absstore.py +++ /dev/null @@ -1,224 +0,0 @@ -"""This module contains storage classes related to Azure Blob Storage (ABS)""" - -import warnings -from numcodecs.compat import ensure_bytes -from zarr.v2.util import normalize_storage_path -from zarr.v2._storage.store import Store - -__doctest_requires__ = { - ("ABSStore", "ABSStore.*"): ["azure.storage.blob"], -} - - -class ABSStore(Store): - """Storage class using Azure Blob Storage (ABS). - - Parameters - ---------- - container : string - The name of the ABS container to use. - - .. deprecated:: - Use ``client`` instead. - - prefix : string - Location of the "directory" to use as the root of the storage hierarchy - within the container. - - account_name : string - The Azure blob storage account name. - - .. deprecated:: 2.8.3 - Use ``client`` instead. - - account_key : string - The Azure blob storage account access key. - - .. deprecated:: 2.8.3 - Use ``client`` instead. - - blob_service_kwargs : dictionary - Extra arguments to be passed into the azure blob client, for e.g. when - using the emulator, pass in blob_service_kwargs={'is_emulated': True}. - - .. deprecated:: 2.8.3 - Use ``client`` instead. - - dimension_separator : {'.', '/'}, optional - Separator placed between the dimensions of a chunk. - - client : azure.storage.blob.ContainerClient, optional - And ``azure.storage.blob.ContainerClient`` to connect with. See - `here `_ # noqa - for more. - - .. versionadded:: 2.8.3 - - Notes - ----- - In order to use this store, you must install the Microsoft Azure Storage SDK for Python, - ``azure-storage-blob>=12.5.0``. - """ - - def __init__( - self, - container=None, - prefix="", - account_name=None, - account_key=None, - blob_service_kwargs=None, - dimension_separator=None, - client=None, - ): - self._dimension_separator = dimension_separator - self.prefix = normalize_storage_path(prefix) - if client is None: - # deprecated option, try to construct the client for them - msg = ( - "Providing 'container', 'account_name', 'account_key', and 'blob_service_kwargs'" - "is deprecated. Provide and instance of 'azure.storage.blob.ContainerClient' " - "'client' instead." - ) - warnings.warn(msg, FutureWarning, stacklevel=2) - from azure.storage.blob import ContainerClient - - blob_service_kwargs = blob_service_kwargs or {} - client = ContainerClient( - "https://{}.blob.core.windows.net/".format(account_name), - container, - credential=account_key, - **blob_service_kwargs, - ) - - self.client = client - self._container = container - self._account_name = account_name - self._account_key = account_key - - @staticmethod - def _warn_deprecated(property_): - msg = ( - "The {} property is deprecated and will be removed in a future " - "version. Get the property from 'ABSStore.client' instead." - ) - warnings.warn(msg.format(property_), FutureWarning, stacklevel=3) - - @property - def container(self): - self._warn_deprecated("container") - return self._container - - @property - def account_name(self): - self._warn_deprecated("account_name") - return self._account_name - - @property - def account_key(self): - self._warn_deprecated("account_key") - return self._account_key - - def _append_path_to_prefix(self, path): - if self.prefix == "": - return normalize_storage_path(path) - else: - return "/".join([self.prefix, normalize_storage_path(path)]) - - @staticmethod - def _strip_prefix_from_path(path, prefix): - # normalized things will not have any leading or trailing slashes - path_norm = normalize_storage_path(path) - prefix_norm = normalize_storage_path(prefix) - if prefix: - return path_norm[(len(prefix_norm) + 1) :] - else: - return path_norm - - def __getitem__(self, key): - from azure.core.exceptions import ResourceNotFoundError - - blob_name = self._append_path_to_prefix(key) - try: - return self.client.download_blob(blob_name).readall() - except ResourceNotFoundError: - raise KeyError("Blob %s not found" % blob_name) - - def __setitem__(self, key, value): - value = ensure_bytes(value) - blob_name = self._append_path_to_prefix(key) - self.client.upload_blob(blob_name, value, overwrite=True) - - def __delitem__(self, key): - from azure.core.exceptions import ResourceNotFoundError - - try: - self.client.delete_blob(self._append_path_to_prefix(key)) - except ResourceNotFoundError: - raise KeyError("Blob %s not found" % key) - - def __eq__(self, other): - return ( - isinstance(other, ABSStore) - and self.client == other.client - and self.prefix == other.prefix - ) - - def keys(self): - return list(self.__iter__()) - - def __iter__(self): - if self.prefix: - list_blobs_prefix = self.prefix + "/" - else: - list_blobs_prefix = None - for blob in self.client.list_blobs(list_blobs_prefix): - yield self._strip_prefix_from_path(blob.name, self.prefix) - - def __len__(self): - return len(self.keys()) - - def __contains__(self, key): - blob_name = self._append_path_to_prefix(key) - return self.client.get_blob_client(blob_name).exists() - - def listdir(self, path=None): - dir_path = normalize_storage_path(self._append_path_to_prefix(path)) - if dir_path: - dir_path += "/" - items = [ - self._strip_prefix_from_path(blob.name, dir_path) - for blob in self.client.walk_blobs(name_starts_with=dir_path, delimiter="/") - ] - return items - - def rmdir(self, path=None): - dir_path = normalize_storage_path(self._append_path_to_prefix(path)) - if dir_path: - dir_path += "/" - for blob in self.client.list_blobs(name_starts_with=dir_path): - self.client.delete_blob(blob) - - def getsize(self, path=None): - store_path = normalize_storage_path(path) - fs_path = self._append_path_to_prefix(store_path) - if fs_path: - blob_client = self.client.get_blob_client(fs_path) - else: - blob_client = None - - if blob_client and blob_client.exists(): - return blob_client.get_blob_properties().size - else: - size = 0 - if fs_path == "": - fs_path = None - elif not fs_path.endswith("/"): - fs_path += "/" - for blob in self.client.walk_blobs(name_starts_with=fs_path, delimiter="/"): - blob_client = self.client.get_blob_client(blob) - if blob_client.exists(): - size += blob_client.get_blob_properties().size - return size - - def clear(self): - self.rmdir() diff --git a/src/zarr/v2/_storage/store.py b/src/zarr/v2/_storage/store.py deleted file mode 100644 index ec1dbf0565..0000000000 --- a/src/zarr/v2/_storage/store.py +++ /dev/null @@ -1,226 +0,0 @@ -from collections.abc import MutableMapping -from typing import Any, List, Mapping, Optional, Sequence, Union - -from zarr.v2.meta import Metadata2 -from zarr.v2.util import normalize_storage_path -from zarr.v2.context import Context - - -# v2 store keys -array_meta_key = ".zarray" -group_meta_key = ".zgroup" -attrs_key = ".zattrs" - -DEFAULT_ZARR_VERSION = 2 - - -class BaseStore(MutableMapping[str, Any]): - """Abstract base class for store implementations. - - This is a thin wrapper over MutableMapping that provides methods to check - whether a store is readable, writeable, eraseable and or listable. - - Stores cannot be mutable mapping as they do have a couple of other - requirements that would break Liskov substitution principle (stores only - allow strings as keys, mutable mapping are more generic). - - Having no-op base method also helps simplifying store usage and do not need - to check the presence of attributes and methods, like `close()`. - - Stores can be used as context manager to make sure they close on exit. - - .. added: 2.11.0 - - """ - - _readable = True - _writeable = True - _erasable = True - _listable = True - _store_version = 2 - _metadata_class = Metadata2 - - def is_readable(self): - return self._readable - - def is_writeable(self): - return self._writeable - - def is_listable(self): - return self._listable - - def is_erasable(self): - return self._erasable - - def __enter__(self): - if not hasattr(self, "_open_count"): - self._open_count = 0 - self._open_count += 1 - return self - - def __exit__(self, exc_type, exc_value, traceback): - self._open_count -= 1 - if self._open_count == 0: - self.close() - - def close(self) -> None: - """Do nothing by default""" - pass - - def rename(self, src_path: str, dst_path: str) -> None: - if not self.is_erasable(): - raise NotImplementedError( - f'{type(self)} is not erasable, cannot call "rename"' - ) # pragma: no cover - _rename_from_keys(self, src_path, dst_path) - - @staticmethod - def _ensure_store(store: Any): - """ - We want to make sure internally that zarr stores are always a class - with a specific interface derived from ``BaseStore``, which is slightly - different than ``MutableMapping``. - - We'll do this conversion in a few places automatically - """ - from zarr.v2.storage import KVStore # avoid circular import - - if isinstance(store, BaseStore): - if not store._store_version == 2: - raise ValueError( - f"cannot initialize a v2 store with a v{store._store_version} store" - ) - return store - elif isinstance(store, MutableMapping): - return KVStore(store) - else: - for attr in [ - "keys", - "values", - "get", - "__setitem__", - "__getitem__", - "__delitem__", - "__contains__", - ]: - if not hasattr(store, attr): - break - else: - return KVStore(store) - - raise ValueError( - "Starting with Zarr 2.11.0, stores must be subclasses of " - "BaseStore, if your store exposes the MutableMapping interface " - f"wrap it in zarr.v2.storage.KVStore. Got {store}" - ) - - def getitems( - self, keys: Sequence[str], *, contexts: Mapping[str, Context] - ) -> Mapping[str, Any]: - """Retrieve data from multiple keys. - - Parameters - ---------- - keys : Iterable[str] - The keys to retrieve - contexts: Mapping[str, Context] - A mapping of keys to their context. Each context is a mapping of store - specific information. E.g. a context could be a dict telling the store - the preferred output array type: `{"meta_array": cupy.empty(())}` - - Returns - ------- - Mapping - A collection mapping the input keys to their results. - - Notes - ----- - This default implementation uses __getitem__() to read each key sequentially and - ignores contexts. Overwrite this method to implement concurrent reads of multiple - keys and/or to utilize the contexts. - """ - return {k: self[k] for k in keys if k in self} - - -class Store(BaseStore): - """Abstract store class used by implementations following the Zarr v2 spec. - - Adds public `listdir`, `rename`, and `rmdir` methods on top of BaseStore. - - .. added: 2.11.0 - - """ - - def listdir(self, path: str = "") -> List[str]: - path = normalize_storage_path(path) - return _listdir_from_keys(self, path) - - def rmdir(self, path: str = "") -> None: - if not self.is_erasable(): - raise NotImplementedError( - f'{type(self)} is not erasable, cannot call "rmdir"' - ) # pragma: no cover - path = normalize_storage_path(path) - _rmdir_from_keys(self, path) - - -# allow MutableMapping for backwards compatibility -StoreLike = Union[BaseStore, MutableMapping[str, Any]] - - -def _path_to_prefix(path: Optional[str]) -> str: - # assume path already normalized - if path: - prefix = path + "/" - else: - prefix = "" - return prefix - - -def _rename_from_keys(store: BaseStore, src_path: str, dst_path: str) -> None: - # assume path already normalized - src_prefix = _path_to_prefix(src_path) - dst_prefix = _path_to_prefix(dst_path) - version = getattr(store, "_store_version", 2) - if version == 2: - for key in list(store.keys()): - if key.startswith(src_prefix): - new_key = dst_prefix + key.lstrip(src_prefix) - store[new_key] = store.pop(key) - else: - raise NotImplementedError("This function only supports Zarr version 2.") - - -def _rmdir_from_keys(store: StoreLike, path: Optional[str] = None) -> None: - # assume path already normalized - prefix = _path_to_prefix(path) - for key in list(store.keys()): - if key.startswith(prefix): - del store[key] - - -def _listdir_from_keys(store: BaseStore, path: Optional[str] = None) -> List[str]: - # assume path already normalized - prefix = _path_to_prefix(path) - children = set() - for key in list(store.keys()): - if key.startswith(prefix) and len(key) > len(prefix): - suffix = key[len(prefix) :] - child = suffix.split("/")[0] - children.add(child) - return sorted(children) - - -def _prefix_to_array_key(store: StoreLike, prefix: str) -> str: - key = prefix + array_meta_key - return key - - -def _prefix_to_group_key(store: StoreLike, prefix: str) -> str: - key = prefix + group_meta_key - return key - - -def _prefix_to_attrs_key(store: StoreLike, prefix: str) -> str: - key = prefix + attrs_key - return key diff --git a/src/zarr/v2/attrs.py b/src/zarr/v2/attrs.py deleted file mode 100644 index af23d43b9e..0000000000 --- a/src/zarr/v2/attrs.py +++ /dev/null @@ -1,158 +0,0 @@ -from typing import Any -import warnings -from collections.abc import MutableMapping - -from zarr.v2._storage.store import Store -from zarr.v2.util import json_dumps - - -class Attributes(MutableMapping[str, Any]): - """Class providing access to user attributes on an array or group. Should not be - instantiated directly, will be available via the `.attrs` property of an array or - group. - - Parameters - ---------- - store : MutableMapping - The store in which to store the attributes. - key : str, optional - The key under which the attributes will be stored. - read_only : bool, optional - If True, attributes cannot be modified. - cache : bool, optional - If True (default), attributes will be cached locally. - synchronizer : Synchronizer - Only necessary if attributes may be modified from multiple threads or processes. - - """ - - def __init__(self, store, key=".zattrs", read_only=False, cache=True, synchronizer=None): - _Store = Store - self.store = _Store._ensure_store(store) - self.key = key - self.read_only = read_only - self.cache = cache - self._cached_asdict = None - self.synchronizer = synchronizer - - def _get_nosync(self): - try: - data = self.store[self.key] - except KeyError: - d: dict[str, Any] = dict() - else: - d = self.store._metadata_class.parse_metadata(data) - return d - - def asdict(self): - """Retrieve all attributes as a dictionary.""" - if self.cache and self._cached_asdict is not None: - return self._cached_asdict - d = self._get_nosync() - if self.cache: - self._cached_asdict = d - return d - - def refresh(self): - """Refresh cached attributes from the store.""" - if self.cache: - self._cached_asdict = self._get_nosync() - - def __contains__(self, x): - return x in self.asdict() - - def __getitem__(self, item): - return self.asdict()[item] - - def _write_op(self, f, *args, **kwargs): - # guard condition - if self.read_only: - raise PermissionError("attributes are read-only") - - # synchronization - if self.synchronizer is None: - return f(*args, **kwargs) - else: - with self.synchronizer[self.key]: - return f(*args, **kwargs) - - def __setitem__(self, item, value): - self._write_op(self._setitem_nosync, item, value) - - def _setitem_nosync(self, item, value): - # load existing data - d = self._get_nosync() - - # set key value - - d[item] = value - - # _put modified data - self._put_nosync(d) - - def __delitem__(self, item): - self._write_op(self._delitem_nosync, item) - - def _delitem_nosync(self, key): - # load existing data - d = self._get_nosync() - - # delete key value - del d[key] - - # _put modified data - self._put_nosync(d) - - def put(self, d): - """Overwrite all attributes with the key/value pairs in the provided dictionary - `d` in a single operation.""" - self._write_op(self._put_nosync, d) - - def _put_nosync(self, d): - d_to_check = d - if not all(isinstance(item, str) for item in d_to_check): - # TODO: Raise an error for non-string keys - # raise TypeError("attribute keys must be strings") - warnings.warn( - "only attribute keys of type 'string' will be allowed in the future", - DeprecationWarning, - stacklevel=2, - ) - - try: - d_to_check = {str(k): v for k, v in d_to_check.items()} - except TypeError as ex: # pragma: no cover - raise TypeError("attribute keys can not be stringified") from ex - - d = d_to_check - - self.store[self.key] = json_dumps(d) - if self.cache: - self._cached_asdict = d - - # noinspection PyMethodOverriding - def update(self, *args, **kwargs): - """Update the values of several attributes in a single operation.""" - self._write_op(self._update_nosync, *args, **kwargs) - - def _update_nosync(self, *args, **kwargs): - # load existing data - d = self._get_nosync() - - # update - d.update(*args, **kwargs) - - # _put modified data - self._put_nosync(d) - - def keys(self): - return self.asdict().keys() - - def __iter__(self): - return iter(self.asdict()) - - def __len__(self): - return len(self.asdict()) - - def _ipython_key_completions_(self): - return sorted(self) diff --git a/src/zarr/v2/codecs.py b/src/zarr/v2/codecs.py deleted file mode 100644 index 4ad68b8627..0000000000 --- a/src/zarr/v2/codecs.py +++ /dev/null @@ -1,4 +0,0 @@ -# flake8: noqa -from numcodecs import * -from numcodecs import get_codec, Blosc, Pickle, Zlib, Delta, AsType, BZ2 -from numcodecs.registry import codec_registry diff --git a/src/zarr/v2/context.py b/src/zarr/v2/context.py deleted file mode 100644 index 4eb1db7491..0000000000 --- a/src/zarr/v2/context.py +++ /dev/null @@ -1,19 +0,0 @@ -from typing import TypedDict - -from numcodecs.compat import NDArrayLike - - -class Context(TypedDict, total=False): - """A context for component specific information - - All keys are optional. Any component reading the context must provide - a default implementation in the case a key cannot be found. - - Attributes - ---------- - meta_array : array-like, optional - An array-like instance to use for determining the preferred output - array type. - """ - - meta_array: NDArrayLike diff --git a/src/zarr/v2/convenience.py b/src/zarr/v2/convenience.py deleted file mode 100644 index c066ee59e0..0000000000 --- a/src/zarr/v2/convenience.py +++ /dev/null @@ -1,1284 +0,0 @@ -"""Convenience functions for storing and loading data.""" - -import itertools -import os -import re -from collections.abc import Mapping, MutableMapping -from zarr.v2.core import Array -from zarr.v2.creation import array as _create_array -from zarr.v2.creation import open_array -from zarr.v2.errors import CopyError, PathNotFoundError -from zarr.v2.hierarchy import Group -from zarr.v2.hierarchy import group as _create_group -from zarr.v2.hierarchy import open_group -from zarr.v2.meta import json_dumps, json_loads -from zarr.v2.storage import ( - contains_array, - contains_group, - normalize_store_arg, - BaseStore, - ConsolidatedMetadataStore, -) -from zarr.v2.util import TreeViewer, buffer_size, normalize_storage_path - -from typing import Any, Union - -StoreLike = Union[BaseStore, MutableMapping[str, Any], str, None] - -_builtin_open = open # builtin open is later shadowed by a local open function - - -def _check_and_update_path(store: BaseStore, path): - if getattr(store, "_store_version", 2) > 2 and not path: - raise ValueError("path must be provided for v3 stores") - return normalize_storage_path(path) - - -# noinspection PyShadowingBuiltins -def open(store: StoreLike = None, mode: str = "a", *, path=None, **kwargs): - """Convenience function to open a group or array using file-mode-like semantics. - - Parameters - ---------- - store : Store or string, optional - Store or path to directory in file system or name of zip file. - mode : {'r', 'r+', 'a', 'w', 'w-'}, optional - Persistence mode: 'r' means read only (must exist); 'r+' means - read/write (must exist); 'a' means read/write (create if doesn't - exist); 'w' means create (overwrite if exists); 'w-' means create - (fail if exists). - path : str or None, optional - The path within the store to open. - **kwargs - Additional parameters are passed through to :func:`zarr.v2.creation.open_array` or - :func:`zarr.v2.hierarchy.open_group`. - - Returns - ------- - z : :class:`zarr.v2.core.Array` or :class:`zarr.v2.hierarchy.Group` - Array or group, depending on what exists in the given store. - - See Also - -------- - zarr.v2.creation.open_array, zarr.v2.hierarchy.open_group - - Examples - -------- - - Storing data in a directory 'data/example.zarr' on the local file system:: - - >>> import zarr - >>> store = 'data/example.zarr' - >>> zw = zarr.v2.open(store, mode='w', shape=100, dtype='i4') # open new array - >>> zw - - >>> za = zarr.v2.open(store, mode='a') # open existing array for reading and writing - >>> za - - >>> zr = zarr.v2.open(store, mode='r') # open existing array read-only - >>> zr - - >>> gw = zarr.v2.open(store, mode='w') # open new group, overwriting previous data - >>> gw - - >>> ga = zarr.v2.open(store, mode='a') # open existing group for reading and writing - >>> ga - - >>> gr = zarr.v2.open(store, mode='r') # open existing group read-only - >>> gr - - - """ - - # handle polymorphic store arg - # we pass storage options explicitly, since normalize_store_arg might construct - # a store if the input is a fsspec-compatible URL - _store: BaseStore = normalize_store_arg( - store, storage_options=kwargs.pop("storage_options", {}), mode=mode - ) - # path = _check_and_update_path(_store, path) - path = normalize_storage_path(path) - kwargs["path"] = path - - if mode in {"w", "w-", "x"}: - if "shape" in kwargs: - return open_array(_store, mode=mode, **kwargs) - else: - return open_group(_store, mode=mode, **kwargs) - - elif mode == "a": - if "shape" in kwargs or contains_array(_store, path): - return open_array(_store, mode=mode, **kwargs) - else: - return open_group(_store, mode=mode, **kwargs) - - else: - if contains_array(_store, path): - return open_array(_store, mode=mode, **kwargs) - elif contains_group(_store, path): - return open_group(_store, mode=mode, **kwargs) - else: - raise PathNotFoundError(path) - - -def _might_close(path): - return isinstance(path, (str, os.PathLike)) - - -def save_array(store: StoreLike, arr, *, path=None, **kwargs): - """Convenience function to save a NumPy array to the local file system, following a - similar API to the NumPy save() function. - - Parameters - ---------- - store : MutableMapping or string - Store or path to directory in file system or name of zip file. - arr : ndarray - NumPy array with data to save. - path : str or None, optional - The path within the store where the array will be saved. - kwargs - Passed through to :func:`create`, e.g., compressor. - - Examples - -------- - Save an array to a directory on the file system (uses a :class:`DirectoryStore`):: - - >>> import zarr - >>> import numpy as np - >>> arr = np.arange(10000) - >>> zarr.v2.save_array('data/example.zarr', arr) - >>> zarr.v2.load('data/example.zarr') - array([ 0, 1, 2, ..., 9997, 9998, 9999]) - - Save an array to a single file (uses a :class:`ZipStore`):: - - >>> zarr.v2.save_array('data/example.zip', arr) - >>> zarr.v2.load('data/example.zip') - array([ 0, 1, 2, ..., 9997, 9998, 9999]) - - """ - may_need_closing = _might_close(store) - _store: BaseStore = normalize_store_arg(store, mode="w") - path = _check_and_update_path(_store, path) - try: - _create_array(arr, store=_store, overwrite=True, path=path, **kwargs) - finally: - if may_need_closing: - # needed to ensure zip file records are written - _store.close() - - -def save_group(store: StoreLike, *args, path=None, **kwargs): - """Convenience function to save several NumPy arrays to the local file system, following a - similar API to the NumPy savez()/savez_compressed() functions. - - Parameters - ---------- - store : MutableMapping or string - Store or path to directory in file system or name of zip file. - args : ndarray - NumPy arrays with data to save. - path : str or None, optional - Path within the store where the group will be saved. - kwargs - NumPy arrays with data to save. - - Examples - -------- - Save several arrays to a directory on the file system (uses a - :class:`DirectoryStore`): - - >>> import zarr - >>> import numpy as np - >>> a1 = np.arange(10000) - >>> a2 = np.arange(10000, 0, -1) - >>> zarr.v2.save_group('data/example.zarr', a1, a2) - >>> loader = zarr.v2.load('data/example.zarr') - >>> loader - - >>> loader['arr_0'] - array([ 0, 1, 2, ..., 9997, 9998, 9999]) - >>> loader['arr_1'] - array([10000, 9999, 9998, ..., 3, 2, 1]) - - Save several arrays using named keyword arguments:: - - >>> zarr.v2.save_group('data/example.zarr', foo=a1, bar=a2) - >>> loader = zarr.v2.load('data/example.zarr') - >>> loader - - >>> loader['foo'] - array([ 0, 1, 2, ..., 9997, 9998, 9999]) - >>> loader['bar'] - array([10000, 9999, 9998, ..., 3, 2, 1]) - - Store several arrays in a single zip file (uses a :class:`ZipStore`):: - - >>> zarr.v2.save_group('data/example.zip', foo=a1, bar=a2) - >>> loader = zarr.v2.load('data/example.zip') - >>> loader - - >>> loader['foo'] - array([ 0, 1, 2, ..., 9997, 9998, 9999]) - >>> loader['bar'] - array([10000, 9999, 9998, ..., 3, 2, 1]) - - Notes - ----- - Default compression options will be used. - - """ - if len(args) == 0 and len(kwargs) == 0: - raise ValueError("at least one array must be provided") - # handle polymorphic store arg - may_need_closing = _might_close(store) - _store: BaseStore = normalize_store_arg(store, mode="w") - path = _check_and_update_path(_store, path) - try: - grp = _create_group(_store, path=path, overwrite=True) - for i, arr in enumerate(args): - k = "arr_{}".format(i) - grp.create_dataset(k, data=arr, overwrite=True) - for k, arr in kwargs.items(): - grp.create_dataset(k, data=arr, overwrite=True) - finally: - if may_need_closing: - # needed to ensure zip file records are written - _store.close() - - -def save(store: StoreLike, *args, path=None, **kwargs): - """Convenience function to save an array or group of arrays to the local file system. - - Parameters - ---------- - store : MutableMapping or string - Store or path to directory in file system or name of zip file. - args : ndarray - NumPy arrays with data to save. - path : str or None, optional - The path within the group where the arrays will be saved. - kwargs - NumPy arrays with data to save. - - Examples - -------- - Save an array to a directory on the file system (uses a :class:`DirectoryStore`):: - - >>> import zarr - >>> import numpy as np - >>> arr = np.arange(10000) - >>> zarr.v2.save('data/example.zarr', arr) - >>> zarr.v2.load('data/example.zarr') - array([ 0, 1, 2, ..., 9997, 9998, 9999]) - - Save an array to a Zip file (uses a :class:`ZipStore`):: - - >>> zarr.v2.save('data/example.zip', arr) - >>> zarr.v2.load('data/example.zip') - array([ 0, 1, 2, ..., 9997, 9998, 9999]) - - Save several arrays to a directory on the file system (uses a - :class:`DirectoryStore` and stores arrays in a group):: - - >>> import zarr - >>> import numpy as np - >>> a1 = np.arange(10000) - >>> a2 = np.arange(10000, 0, -1) - >>> zarr.v2.save('data/example.zarr', a1, a2) - >>> loader = zarr.v2.load('data/example.zarr') - >>> loader - - >>> loader['arr_0'] - array([ 0, 1, 2, ..., 9997, 9998, 9999]) - >>> loader['arr_1'] - array([10000, 9999, 9998, ..., 3, 2, 1]) - - Save several arrays using named keyword arguments:: - - >>> zarr.v2.save('data/example.zarr', foo=a1, bar=a2) - >>> loader = zarr.v2.load('data/example.zarr') - >>> loader - - >>> loader['foo'] - array([ 0, 1, 2, ..., 9997, 9998, 9999]) - >>> loader['bar'] - array([10000, 9999, 9998, ..., 3, 2, 1]) - - Store several arrays in a single zip file (uses a :class:`ZipStore`):: - - >>> zarr.v2.save('data/example.zip', foo=a1, bar=a2) - >>> loader = zarr.v2.load('data/example.zip') - >>> loader - - >>> loader['foo'] - array([ 0, 1, 2, ..., 9997, 9998, 9999]) - >>> loader['bar'] - array([10000, 9999, 9998, ..., 3, 2, 1]) - - See Also - -------- - save_array, save_group - - """ - if len(args) == 0 and len(kwargs) == 0: - raise ValueError("at least one array must be provided") - if len(args) == 1 and len(kwargs) == 0: - save_array(store, args[0], path=path) - else: - save_group(store, *args, path=path, **kwargs) - - -class LazyLoader(Mapping): - def __init__(self, grp): - self.grp = grp - self.cache = dict() - - def __getitem__(self, item): - try: - return self.cache[item] - except KeyError: - arr = self.grp[item][...] - self.cache[item] = arr - return arr - - def __len__(self): - return len(self.grp) - - def __iter__(self): - return iter(self.grp) - - def __contains__(self, item): - return item in self.grp - - def __repr__(self): - r = ">> import zarr - >>> g1 = zarr.v2.group() - >>> g2 = g1.create_group('foo') - >>> g3 = g1.create_group('bar') - >>> g4 = g3.create_group('baz') - >>> g5 = g3.create_group('qux') - >>> d1 = g5.create_dataset('baz', shape=100, chunks=10) - >>> g1.tree() - / - β”œβ”€β”€ bar - β”‚ β”œβ”€β”€ baz - β”‚ └── qux - β”‚ └── baz (100,) float64 - └── foo - >>> import h5py - >>> h5f = h5py.File('data/example.h5', mode='w') - >>> zarr.v2.copy_all(g1, h5f) - (5, 0, 800) - >>> zarr.v2.tree(h5f) - / - β”œβ”€β”€ bar - β”‚ β”œβ”€β”€ baz - β”‚ └── qux - β”‚ └── baz (100,) float64 - └── foo - - See Also - -------- - zarr.v2.hierarchy.Group.tree - - Notes - ----- - Please note that this is an experimental feature. The behaviour of this - function is still evolving and the default output and/or parameters may change - in future versions. - - """ - - return TreeViewer(grp, expand=expand, level=level) - - -class _LogWriter: - def __init__(self, log): - self.log_func = None - self.log_file = None - self.needs_closing = False - if log is None: - # don't do any logging - pass - elif callable(log): - self.log_func = log - elif isinstance(log, str): - self.log_file = _builtin_open(log, mode="w") - self.needs_closing = True - elif hasattr(log, "write"): - self.log_file = log - else: - raise TypeError( - "log must be a callable function, file path or file-like object, found %r" % log - ) - - def __enter__(self): - return self - - def __exit__(self, *args): - if self.log_file is not None and self.needs_closing: - self.log_file.close() - - def __call__(self, *args, **kwargs): - if self.log_file is not None: - kwargs["file"] = self.log_file - print(*args, **kwargs) - if hasattr(self.log_file, "flush"): - # get immediate feedback - self.log_file.flush() - elif self.log_func is not None: - self.log_func(*args, **kwargs) - - -def _log_copy_summary(log, dry_run, n_copied, n_skipped, n_bytes_copied): - # log a final message with a summary of what happened - if dry_run: - message = "dry run: " - else: - message = "all done: " - message += "{:,} copied, {:,} skipped".format(n_copied, n_skipped) - if not dry_run: - message += ", {:,} bytes copied".format(n_bytes_copied) - log(message) - - -def copy_store( - source, - dest, - source_path="", - dest_path="", - excludes=None, - includes=None, - flags=0, - if_exists="raise", - dry_run=False, - log=None, -): - """Copy data directly from the `source` store to the `dest` store. Use this - function when you want to copy a group or array in the most efficient way, - preserving all configuration and attributes. This function is more efficient - than the copy() or copy_all() functions because it avoids de-compressing and - re-compressing data, rather the compressed chunk data for each array are - copied directly between stores. - - Parameters - ---------- - source : Mapping - Store to copy data from. - dest : MutableMapping - Store to copy data into. - source_path : str, optional - Only copy data from under this path in the source store. - dest_path : str, optional - Copy data into this path in the destination store. - excludes : sequence of str, optional - One or more regular expressions which will be matched against keys in - the source store. Any matching key will not be copied. - includes : sequence of str, optional - One or more regular expressions which will be matched against keys in - the source store and will override any excludes also matching. - flags : int, optional - Regular expression flags used for matching excludes and includes. - if_exists : {'raise', 'replace', 'skip'}, optional - How to handle keys that already exist in the destination store. If - 'raise' then a CopyError is raised on the first key already present - in the destination store. If 'replace' then any data will be replaced in - the destination. If 'skip' then any existing keys will not be copied. - dry_run : bool, optional - If True, don't actually copy anything, just log what would have - happened. - log : callable, file path or file-like object, optional - If provided, will be used to log progress information. - - Returns - ------- - n_copied : int - Number of items copied. - n_skipped : int - Number of items skipped. - n_bytes_copied : int - Number of bytes of data that were actually copied. - - Examples - -------- - - >>> import zarr - >>> store1 = zarr.v2.DirectoryStore('data/example.zarr') - >>> root = zarr.v2.group(store1, overwrite=True) - >>> foo = root.create_group('foo') - >>> bar = foo.create_group('bar') - >>> baz = bar.create_dataset('baz', shape=100, chunks=50, dtype='i8') - >>> import numpy as np - >>> baz[:] = np.arange(100) - >>> root.tree() - / - └── foo - └── bar - └── baz (100,) int64 - >>> from sys import stdout - >>> store2 = zarr.v2.ZipStore('data/example.zip', mode='w') - >>> zarr.v2.copy_store(store1, store2, log=stdout) - copy .zgroup - copy foo/.zgroup - copy foo/bar/.zgroup - copy foo/bar/baz/.zarray - copy foo/bar/baz/0 - copy foo/bar/baz/1 - all done: 6 copied, 0 skipped, 566 bytes copied - (6, 0, 566) - >>> new_root = zarr.v2.group(store2) - >>> new_root.tree() - / - └── foo - └── bar - └── baz (100,) int64 - >>> new_root['foo/bar/baz'][:] - array([ 0, 1, 2, ..., 97, 98, 99]) - >>> store2.close() # zip stores need to be closed - - Notes - ----- - Please note that this is an experimental feature. The behaviour of this - function is still evolving and the default behaviour and/or parameters may change - in future versions. - - """ - - # normalize paths - source_path = normalize_storage_path(source_path) - dest_path = normalize_storage_path(dest_path) - if source_path: - source_path = source_path + "/" - if dest_path: - dest_path = dest_path + "/" - - # normalize excludes and includes - if excludes is None: - excludes = [] - elif isinstance(excludes, str): - excludes = [excludes] - if includes is None: - includes = [] - elif isinstance(includes, str): - includes = [includes] - excludes = [re.compile(e, flags) for e in excludes] - includes = [re.compile(i, flags) for i in includes] - - # check if_exists parameter - valid_if_exists = ["raise", "replace", "skip"] - if if_exists not in valid_if_exists: - raise ValueError( - "if_exists must be one of {!r}; found {!r}".format(valid_if_exists, if_exists) - ) - - # setup counting variables - n_copied = n_skipped = n_bytes_copied = 0 - - source_store_version = getattr(source, "_store_version", 2) - dest_store_version = getattr(dest, "_store_version", 2) - if source_store_version != dest_store_version: - raise ValueError("zarr stores must share the same protocol version") - - if source_store_version > 2: - raise NotImplementedError("This function only supports Zarr version 2.") - - # setup logging - with _LogWriter(log) as log: - # iterate over source keys - for source_key in sorted(source.keys()): - # filter to keys under source path - if source_store_version == 2: - if not source_key.startswith(source_path): - continue - elif source_store_version == 3: - raise NotImplementedError("This function only supports Zarr version 2.") - # process excludes and includes - exclude = False - for prog in excludes: - if prog.search(source_key): - exclude = True - break - if exclude: - for prog in includes: - if prog.search(source_key): - exclude = False - break - if exclude: - continue - - # map key to destination path - if source_store_version == 2: - key_suffix = source_key[len(source_path) :] - dest_key = dest_path + key_suffix - elif source_store_version == 3: - raise NotImplementedError("This function only supports Zarr version 2.") - # create a descriptive label for this operation - descr = source_key - if dest_key != source_key: - descr = descr + " -> " + dest_key - - # decide what to do - do_copy = True - if if_exists != "replace" and dest_key in dest: - if if_exists == "raise": - raise CopyError("key {!r} exists in destination".format(dest_key)) - elif if_exists == "skip": - do_copy = False - - # take action - if do_copy: - log("copy {}".format(descr)) - if not dry_run: - data = source[source_key] - n_bytes_copied += buffer_size(data) - dest[dest_key] = data - n_copied += 1 - else: - log("skip {}".format(descr)) - n_skipped += 1 - - # log a final message with a summary of what happened - _log_copy_summary(log, dry_run, n_copied, n_skipped, n_bytes_copied) - - return n_copied, n_skipped, n_bytes_copied - - -def _check_dest_is_group(dest): - if not hasattr(dest, "create_dataset"): - raise ValueError("dest must be a group, got {!r}".format(dest)) - - -def copy( - source, - dest, - name=None, - shallow=False, - without_attrs=False, - log=None, - if_exists="raise", - dry_run=False, - **create_kws, -): - """Copy the `source` array or group into the `dest` group. - - Parameters - ---------- - source : group or array/dataset - A zarr group or array, or an h5py group or dataset. - dest : group - A zarr or h5py group. - name : str, optional - Name to copy the object to. - shallow : bool, optional - If True, only copy immediate children of `source`. - without_attrs : bool, optional - Do not copy user attributes. - log : callable, file path or file-like object, optional - If provided, will be used to log progress information. - if_exists : {'raise', 'replace', 'skip', 'skip_initialized'}, optional - How to handle arrays that already exist in the destination group. If - 'raise' then a CopyError is raised on the first array already present - in the destination group. If 'replace' then any array will be - replaced in the destination. If 'skip' then any existing arrays will - not be copied. If 'skip_initialized' then any existing arrays with - all chunks initialized will not be copied (not available when copying to - h5py). - dry_run : bool, optional - If True, don't actually copy anything, just log what would have - happened. - **create_kws - Passed through to the create_dataset method when copying an array/dataset. - - Returns - ------- - n_copied : int - Number of items copied. - n_skipped : int - Number of items skipped. - n_bytes_copied : int - Number of bytes of data that were actually copied. - - Examples - -------- - Here's an example of copying a group named 'foo' from an HDF5 file to a - Zarr group:: - - >>> import h5py - >>> import zarr - >>> import numpy as np - >>> source = h5py.File('data/example.h5', mode='w') - >>> foo = source.create_group('foo') - >>> baz = foo.create_dataset('bar/baz', data=np.arange(100), chunks=(50,)) - >>> spam = source.create_dataset('spam', data=np.arange(100, 200), chunks=(30,)) - >>> zarr.v2.tree(source) - / - β”œβ”€β”€ foo - β”‚ └── bar - β”‚ └── baz (100,) int64 - └── spam (100,) int64 - >>> dest = zarr.v2.group() - >>> from sys import stdout - >>> zarr.v2.copy(source['foo'], dest, log=stdout) - copy /foo - copy /foo/bar - copy /foo/bar/baz (100,) int64 - all done: 3 copied, 0 skipped, 800 bytes copied - (3, 0, 800) - >>> dest.tree() # N.B., no spam - / - └── foo - └── bar - └── baz (100,) int64 - >>> source.close() - - The ``if_exists`` parameter provides options for how to handle pre-existing data in - the destination. Here are some examples of these options, also using - ``dry_run=True`` to find out what would happen without actually copying anything:: - - >>> source = zarr.v2.group() - >>> dest = zarr.v2.group() - >>> baz = source.create_dataset('foo/bar/baz', data=np.arange(100)) - >>> spam = source.create_dataset('foo/spam', data=np.arange(1000)) - >>> existing_spam = dest.create_dataset('foo/spam', data=np.arange(1000)) - >>> from sys import stdout - >>> try: - ... zarr.v2.copy(source['foo'], dest, log=stdout, dry_run=True) - ... except zarr.v2.CopyError as e: - ... print(e) - ... - copy /foo - copy /foo/bar - copy /foo/bar/baz (100,) int64 - an object 'spam' already exists in destination '/foo' - >>> zarr.v2.copy(source['foo'], dest, log=stdout, if_exists='replace', dry_run=True) - copy /foo - copy /foo/bar - copy /foo/bar/baz (100,) int64 - copy /foo/spam (1000,) int64 - dry run: 4 copied, 0 skipped - (4, 0, 0) - >>> zarr.v2.copy(source['foo'], dest, log=stdout, if_exists='skip', dry_run=True) - copy /foo - copy /foo/bar - copy /foo/bar/baz (100,) int64 - skip /foo/spam (1000,) int64 - dry run: 3 copied, 1 skipped - (3, 1, 0) - - Notes - ----- - Please note that this is an experimental feature. The behaviour of this - function is still evolving and the default behaviour and/or parameters may change - in future versions. - - """ - - # value checks - _check_dest_is_group(dest) - - # setup logging - with _LogWriter(log) as log: - # do the copying - n_copied, n_skipped, n_bytes_copied = _copy( - log, - source, - dest, - name=name, - root=True, - shallow=shallow, - without_attrs=without_attrs, - if_exists=if_exists, - dry_run=dry_run, - **create_kws, - ) - - # log a final message with a summary of what happened - _log_copy_summary(log, dry_run, n_copied, n_skipped, n_bytes_copied) - - return n_copied, n_skipped, n_bytes_copied - - -def _copy(log, source, dest, name, root, shallow, without_attrs, if_exists, dry_run, **create_kws): - # N.B., if this is a dry run, dest may be None - - # setup counting variables - n_copied = n_skipped = n_bytes_copied = 0 - - # are we copying to/from h5py? - source_h5py = source.__module__.startswith("h5py.") - dest_h5py = dest is not None and dest.__module__.startswith("h5py.") - - # check if_exists parameter - valid_if_exists = ["raise", "replace", "skip", "skip_initialized"] - if if_exists not in valid_if_exists: - raise ValueError( - "if_exists must be one of {!r}; found {!r}".format(valid_if_exists, if_exists) - ) - if dest_h5py and if_exists == "skip_initialized": - raise ValueError("{!r} can only be used when copying to zarr".format(if_exists)) - - # determine name to copy to - if name is None: - name = source.name.split("/")[-1] - if not name: - # this can happen if source is the root group - raise TypeError( - "source has no name, please provide the `name` " - "parameter to indicate a name to copy to" - ) - - if hasattr(source, "shape"): - # copy a dataset/array - - # check if already exists, decide what to do - do_copy = True - exists = dest is not None and name in dest - if exists: - if if_exists == "raise": - raise CopyError( - "an object {!r} already exists in destination {!r}".format(name, dest.name) - ) - elif if_exists == "skip": - do_copy = False - elif if_exists == "skip_initialized": - ds = dest[name] - if ds.nchunks_initialized == ds.nchunks: - do_copy = False - - # take action - if do_copy: - # log a message about what we're going to do - log("copy {} {} {}".format(source.name, source.shape, source.dtype)) - - if not dry_run: - # clear the way - if exists: - del dest[name] - - # setup creation keyword arguments - kws = create_kws.copy() - - # setup chunks option, preserve by default - kws.setdefault("chunks", source.chunks) - - # setup compression options - if source_h5py: - if dest_h5py: - # h5py -> h5py; preserve compression options by default - kws.setdefault("compression", source.compression) - kws.setdefault("compression_opts", source.compression_opts) - kws.setdefault("shuffle", source.shuffle) - kws.setdefault("fletcher32", source.fletcher32) - kws.setdefault("fillvalue", source.fillvalue) - else: - # h5py -> zarr; use zarr default compression options - kws.setdefault("fill_value", source.fillvalue) - else: - if dest_h5py: - # zarr -> h5py; use some vaguely sensible defaults - kws.setdefault("chunks", True) - kws.setdefault("compression", "gzip") - kws.setdefault("compression_opts", 1) - kws.setdefault("shuffle", False) - kws.setdefault("fillvalue", source.fill_value) - else: - # zarr -> zarr; preserve compression options by default - kws.setdefault("compressor", source.compressor) - kws.setdefault("filters", source.filters) - kws.setdefault("order", source.order) - kws.setdefault("fill_value", source.fill_value) - - # create new dataset in destination - ds = dest.create_dataset(name, shape=source.shape, dtype=source.dtype, **kws) - - # copy data - N.B., go chunk by chunk to avoid loading - # everything into memory - shape = ds.shape - chunks = ds.chunks - chunk_offsets = [range(0, s, c) for s, c in zip(shape, chunks)] - for offset in itertools.product(*chunk_offsets): - sel = tuple(slice(o, min(s, o + c)) for o, s, c in zip(offset, shape, chunks)) - ds[sel] = source[sel] - n_bytes_copied += ds.size * ds.dtype.itemsize - - # copy attributes - if not without_attrs: - if dest_h5py and "filters" in source.attrs: - # No filters key in v3 metadata so it was stored in the - # attributes instead. We cannot copy this key to - # HDF5 attrs, though! - source_attrs = source.attrs.asdict().copy() - source_attrs.pop("filters", None) - else: - source_attrs = source.attrs - ds.attrs.update(source_attrs) - - n_copied += 1 - - else: - log("skip {} {} {}".format(source.name, source.shape, source.dtype)) - n_skipped += 1 - - elif root or not shallow: - # copy a group - - # check if an array is in the way - do_copy = True - exists_array = dest is not None and name in dest and hasattr(dest[name], "shape") - if exists_array: - if if_exists == "raise": - raise CopyError( - "an array {!r} already exists in destination {!r}".format(name, dest.name) - ) - elif if_exists == "skip": - do_copy = False - - # take action - if do_copy: - # log action - log("copy {}".format(source.name)) - - if not dry_run: - # clear the way - if exists_array: - del dest[name] - - # require group in destination - grp = dest.require_group(name) - - # copy attributes - if not without_attrs: - grp.attrs.update(source.attrs) - - else: - # setup for dry run without creating any groups in the - # destination - if dest is not None: - grp = dest.get(name, None) - else: - grp = None - - # recurse - for k in source.keys(): - c, s, b = _copy( - log, - source[k], - grp, - name=k, - root=False, - shallow=shallow, - without_attrs=without_attrs, - if_exists=if_exists, - dry_run=dry_run, - **create_kws, - ) - n_copied += c - n_skipped += s - n_bytes_copied += b - - n_copied += 1 - - else: - log("skip {}".format(source.name)) - n_skipped += 1 - - return n_copied, n_skipped, n_bytes_copied - - -def copy_all( - source, - dest, - shallow=False, - without_attrs=False, - log=None, - if_exists="raise", - dry_run=False, - **create_kws, -): - """Copy all children of the `source` group into the `dest` group. - - Parameters - ---------- - source : group or array/dataset - A zarr group or array, or an h5py group or dataset. - dest : group - A zarr or h5py group. - shallow : bool, optional - If True, only copy immediate children of `source`. - without_attrs : bool, optional - Do not copy user attributes. - log : callable, file path or file-like object, optional - If provided, will be used to log progress information. - if_exists : {'raise', 'replace', 'skip', 'skip_initialized'}, optional - How to handle arrays that already exist in the destination group. If - 'raise' then a CopyError is raised on the first array already present - in the destination group. If 'replace' then any array will be - replaced in the destination. If 'skip' then any existing arrays will - not be copied. If 'skip_initialized' then any existing arrays with - all chunks initialized will not be copied (not available when copying to - h5py). - dry_run : bool, optional - If True, don't actually copy anything, just log what would have - happened. - **create_kws - Passed through to the create_dataset method when copying an - array/dataset. - - Returns - ------- - n_copied : int - Number of items copied. - n_skipped : int - Number of items skipped. - n_bytes_copied : int - Number of bytes of data that were actually copied. - - Examples - -------- - >>> import h5py - >>> import zarr - >>> import numpy as np - >>> source = h5py.File('data/example.h5', mode='w') - >>> foo = source.create_group('foo') - >>> baz = foo.create_dataset('bar/baz', data=np.arange(100), chunks=(50,)) - >>> spam = source.create_dataset('spam', data=np.arange(100, 200), chunks=(30,)) - >>> zarr.v2.tree(source) - / - β”œβ”€β”€ foo - β”‚ └── bar - β”‚ └── baz (100,) int64 - └── spam (100,) int64 - >>> dest = zarr.v2.group() - >>> import sys - >>> zarr.v2.copy_all(source, dest, log=sys.stdout) - copy /foo - copy /foo/bar - copy /foo/bar/baz (100,) int64 - copy /spam (100,) int64 - all done: 4 copied, 0 skipped, 1,600 bytes copied - (4, 0, 1600) - >>> dest.tree() - / - β”œβ”€β”€ foo - β”‚ └── bar - β”‚ └── baz (100,) int64 - └── spam (100,) int64 - >>> source.close() - - Notes - ----- - Please note that this is an experimental feature. The behaviour of this - function is still evolving and the default behaviour and/or parameters may change - in future versions. - - """ - - # value checks - _check_dest_is_group(dest) - - # setup counting variables - n_copied = n_skipped = n_bytes_copied = 0 - - # setup logging - with _LogWriter(log) as log: - for k in source.keys(): - c, s, b = _copy( - log, - source[k], - dest, - name=k, - root=False, - shallow=shallow, - without_attrs=without_attrs, - if_exists=if_exists, - dry_run=dry_run, - **create_kws, - ) - n_copied += c - n_skipped += s - n_bytes_copied += b - - dest.attrs.update(**source.attrs) - - # log a final message with a summary of what happened - _log_copy_summary(log, dry_run, n_copied, n_skipped, n_bytes_copied) - - return n_copied, n_skipped, n_bytes_copied - - -def consolidate_metadata(store: BaseStore, metadata_key=".zmetadata", *, path=""): - """ - Consolidate all metadata for groups and arrays within the given store - into a single resource and put it under the given key. - - This produces a single object in the backend store, containing all the - metadata read from all the zarr-related keys that can be found. After - metadata have been consolidated, use :func:`open_consolidated` to open - the root group in optimised, read-only mode, using the consolidated - metadata to reduce the number of read operations on the backend store. - - Note, that if the metadata in the store is changed after this - consolidation, then the metadata read by :func:`open_consolidated` - would be incorrect unless this function is called again. - - .. note:: This is an experimental feature. - - Parameters - ---------- - store : MutableMapping or string - Store or path to directory in file system or name of zip file. - metadata_key : str - Key to put the consolidated metadata under. - path : str or None - Path corresponding to the group that is being consolidated. Not required - for zarr v2 stores. - - Returns - ------- - g : :class:`zarr.v2.hierarchy.Group` - Group instance, opened with the new consolidated metadata. - - See Also - -------- - open_consolidated - - """ - store = normalize_store_arg(store, mode="w") - - version = store._store_version - - if version == 2: - - def is_zarr_key(key): - return key.endswith(".zarray") or key.endswith(".zgroup") or key.endswith(".zattrs") - - else: - raise NotImplementedError("This function only supports Zarr version 2.") - out = { - "zarr_consolidated_format": 1, - "metadata": {key: json_loads(store[key]) for key in store if is_zarr_key(key)}, - } - store[metadata_key] = json_dumps(out) - return open_consolidated(store, metadata_key=metadata_key, path=path) - - -def open_consolidated(store: StoreLike, metadata_key=".zmetadata", mode="r+", **kwargs): - """Open group using metadata previously consolidated into a single key. - - This is an optimised method for opening a Zarr group, where instead of - traversing the group/array hierarchy by accessing the metadata keys at - each level, a single key contains all of the metadata for everything. - For remote data sources where the overhead of accessing a key is large - compared to the time to read data. - - The group accessed must have already had its metadata consolidated into a - single key using the function :func:`consolidate_metadata`. - - This optimised method only works in modes which do not change the - metadata, although the data may still be written/updated. - - Parameters - ---------- - store : MutableMapping or string - Store or path to directory in file system or name of zip file. - metadata_key : str - Key to read the consolidated metadata from. The default (.zmetadata) - corresponds to the default used by :func:`consolidate_metadata`. - mode : {'r', 'r+'}, optional - Persistence mode: 'r' means read only (must exist); 'r+' means - read/write (must exist) although only writes to data are allowed, - changes to metadata including creation of new arrays or group - are not allowed. - **kwargs - Additional parameters are passed through to :func:`zarr.v2.creation.open_array` or - :func:`zarr.v2.hierarchy.open_group`. - - Returns - ------- - g : :class:`zarr.v2.hierarchy.Group` - Group instance, opened with the consolidated metadata. - - See Also - -------- - consolidate_metadata - - """ - - # normalize parameters - store = normalize_store_arg(store, storage_options=kwargs.get("storage_options"), mode=mode) - if mode not in {"r", "r+"}: - raise ValueError("invalid mode, expected either 'r' or 'r+'; found {!r}".format(mode)) - - path = kwargs.pop("path", None) - if store._store_version == 2: - ConsolidatedStoreClass = ConsolidatedMetadataStore - else: - raise NotImplementedError("This function only supports Zarr version 2.") - - # setup metadata store - meta_store = ConsolidatedStoreClass(store, metadata_key=metadata_key) - - # pass through - chunk_store = kwargs.pop("chunk_store", None) or store - return open(store=meta_store, chunk_store=chunk_store, mode=mode, path=path, **kwargs) diff --git a/src/zarr/v2/core.py b/src/zarr/v2/core.py deleted file mode 100644 index 9eeb467d68..0000000000 --- a/src/zarr/v2/core.py +++ /dev/null @@ -1,2855 +0,0 @@ -import binascii -import hashlib -import itertools -import math -import operator -import re -from functools import reduce -from typing import Any - -import numpy as np -from numcodecs import AsType, get_codec -from numcodecs.compat import ensure_bytes, ensure_ndarray_like - -from zarr.v2._storage.store import _prefix_to_attrs_key -from zarr.v2.attrs import Attributes -from zarr.v2.context import Context -from zarr.v2.errors import ArrayNotFoundError, ReadOnlyError, ArrayIndexError -from zarr.v2.indexing import ( - BasicIndexer, - CoordinateIndexer, - MaskIndexer, - OIndex, - OrthogonalIndexer, - VIndex, - BlockIndex, - BlockIndexer, - PartialChunkIterator, - check_fields, - check_no_multi_fields, - ensure_tuple, - err_too_many_indices, - is_contiguous_selection, - is_pure_fancy_indexing, - is_pure_orthogonal_indexing, - is_scalar, - pop_fields, -) -from zarr.v2.storage import ( - _prefix_to_array_key, - KVStore, - getsize, - listdir, - normalize_store_arg, -) -from zarr.v2.util import ( - ConstantMap, - UncompressedPartialReadBufferV3, - all_equal, - InfoReporter, - check_array_shape, - human_readable_size, - is_total_slice, - nolock, - normalize_chunks, - normalize_resize_args, - normalize_shape, - normalize_storage_path, - PartialReadBuffer, -) - -__all__ = ["Array"] - - -# noinspection PyUnresolvedReferences -class Array: - """Instantiate an array from an initialized store. - - Parameters - ---------- - store : MutableMapping - Array store, already initialized. - path : string, optional - Storage path. - read_only : bool, optional - True if array should be protected against modification. - chunk_store : MutableMapping, optional - Separate storage for chunks. If not provided, `store` will be used - for storage of both chunks and metadata. - synchronizer : object, optional - Array synchronizer. - cache_metadata : bool, optional - If True (default), array configuration metadata will be cached for the - lifetime of the object. If False, array metadata will be reloaded - prior to all data access and modification operations (may incur - overhead depending on storage and data access pattern). - cache_attrs : bool, optional - If True (default), user attributes will be cached for attribute read - operations. If False, user attributes are reloaded from the store prior - to all attribute read operations. - partial_decompress : bool, optional - If True and while the chunk_store is a FSStore and the compression used - is Blosc, when getting data from the array chunks will be partially - read and decompressed when possible. - - .. versionadded:: 2.7 - - write_empty_chunks : bool, optional - If True, all chunks will be stored regardless of their contents. If - False (default), each chunk is compared to the array's fill value prior - to storing. If a chunk is uniformly equal to the fill value, then that - chunk is not be stored, and the store entry for that chunk's key is - deleted. This setting enables sparser storage, as only chunks with - non-fill-value data are stored, at the expense of overhead associated - with checking the data of each chunk. - - .. versionadded:: 2.11 - - meta_array : array-like, optional - An array instance to use for determining arrays to create and return - to users. Use `numpy.empty(())` by default. - - .. versionadded:: 2.13 - """ - - def __init__( - self, - store: Any, # BaseStore not strictly required due to normalize_store_arg - path=None, - read_only=False, - chunk_store=None, - synchronizer=None, - cache_metadata=True, - cache_attrs=True, - partial_decompress=False, - write_empty_chunks=True, - meta_array=None, - ): - # N.B., expect at this point store is fully initialized with all - # configuration metadata fully specified and normalized - store = normalize_store_arg(store) - - if chunk_store is not None: - chunk_store = normalize_store_arg(chunk_store) - - self._store = store - self._chunk_store = chunk_store - self._transformed_chunk_store = None - self._path = normalize_storage_path(path) - if self._path: - self._key_prefix = self._path + "/" - else: - self._key_prefix = "" - self._read_only = bool(read_only) - self._synchronizer = synchronizer - self._cache_metadata = cache_metadata - self._is_view = False - self._partial_decompress = partial_decompress - self._write_empty_chunks = write_empty_chunks - if meta_array is not None: - self._meta_array = np.empty_like(meta_array, shape=()) - else: - self._meta_array = np.empty(()) - - # initialize metadata - self._load_metadata() - - # initialize attributes - akey = _prefix_to_attrs_key(self._store, self._key_prefix) - self._attrs = Attributes( - store, key=akey, read_only=read_only, synchronizer=synchronizer, cache=cache_attrs - ) - - # initialize info reporter - self._info_reporter = InfoReporter(self) - - # initialize indexing helpers - self._oindex = OIndex(self) - self._vindex = VIndex(self) - self._blocks = BlockIndex(self) - - def _load_metadata(self): - """(Re)load metadata from store.""" - if self._synchronizer is None: - self._load_metadata_nosync() - else: - mkey = _prefix_to_array_key(self._store, self._key_prefix) - with self._synchronizer[mkey]: - self._load_metadata_nosync() - - def _load_metadata_nosync(self): - try: - mkey = _prefix_to_array_key(self._store, self._key_prefix) - meta_bytes = self._store[mkey] - except KeyError: - raise ArrayNotFoundError(self._path) - else: - # decode and store metadata as instance members - meta = self._store._metadata_class.decode_array_metadata(meta_bytes) - self._meta = meta - self._shape = meta["shape"] - self._fill_value = meta["fill_value"] - dimension_separator = meta.get("dimension_separator", None) - - self._chunks = meta["chunks"] - self._dtype = meta["dtype"] - self._order = meta["order"] - if dimension_separator is None: - try: - dimension_separator = self._store._dimension_separator - except (AttributeError, KeyError): - pass - - # Fallback for any stores which do not choose a default - if dimension_separator is None: - dimension_separator = "." - - self._dimension_separator = dimension_separator - - # setup compressor - compressor = meta.get("compressor", None) - if compressor is None: - self._compressor = None - else: - self._compressor = get_codec(compressor) - - # setup filters - - filters = meta.get("filters", []) - - if filters: - filters = [get_codec(config) for config in filters] - self._filters = filters - - def _refresh_metadata(self): - if not self._cache_metadata: - self._load_metadata() - - def _refresh_metadata_nosync(self): - if not self._cache_metadata and not self._is_view: - self._load_metadata_nosync() - - def _flush_metadata_nosync(self): - if self._is_view: - raise PermissionError("operation not permitted for views") - - if self._compressor: - compressor_config = self._compressor.get_config() - else: - compressor_config = None - if self._filters: - filters_config = [f.get_config() for f in self._filters] - else: - filters_config = None - _compressor = compressor_config - meta = dict( - shape=self._shape, - compressor=_compressor, - fill_value=self._fill_value, - filters=filters_config, - ) - - meta.update( - dict( - chunks=self._chunks, - dtype=self._dtype, - order=self._order, - dimension_separator=self._dimension_separator, - ) - ) - mkey = _prefix_to_array_key(self._store, self._key_prefix) - self._store[mkey] = self._store._metadata_class.encode_array_metadata(meta) - - @property - def store(self): - """A MutableMapping providing the underlying storage for the array.""" - return self._store - - @property - def path(self): - """Storage path.""" - return self._path - - @property - def name(self): - """Array name following h5py convention.""" - if self.path: - # follow h5py convention: add leading slash - name = self.path - if name[0] != "/": - name = "/" + name - return name - return None - - @property - def basename(self): - """Final component of name.""" - if self.name is not None: - return self.name.split("/")[-1] - return None - - @property - def read_only(self): - """A boolean, True if modification operations are not permitted.""" - return self._read_only - - @read_only.setter - def read_only(self, value): - self._read_only = bool(value) - - @property - def chunk_store(self): - """A MutableMapping providing the underlying storage for array chunks.""" - if self._transformed_chunk_store is not None: - return self._transformed_chunk_store - elif self._chunk_store is not None: - return self._chunk_store - else: - return self._store - - @property - def shape(self): - """A tuple of integers describing the length of each dimension of - the array.""" - # N.B., shape may change if array is resized, hence need to refresh - # metadata - self._refresh_metadata() - return self._shape - - @shape.setter - def shape(self, value): - self.resize(value) - - @property - def chunks(self): - """A tuple of integers describing the length of each dimension of a - chunk of the array.""" - return self._chunks - - @property - def dtype(self): - """The NumPy data type.""" - return self._dtype - - @property - def compressor(self): - """Primary compression codec.""" - return self._compressor - - @property - def fill_value(self): - """A value used for uninitialized portions of the array.""" - return self._fill_value - - @fill_value.setter - def fill_value(self, new): - self._fill_value = new - self._flush_metadata_nosync() - - @property - def order(self): - """A string indicating the order in which bytes are arranged within - chunks of the array.""" - return self._order - - @property - def filters(self): - """One or more codecs used to transform data prior to compression.""" - return self._filters - - @property - def synchronizer(self): - """Object used to synchronize write access to the array.""" - return self._synchronizer - - @property - def attrs(self): - """A MutableMapping containing user-defined attributes. Note that - attribute values must be JSON serializable.""" - return self._attrs - - @property - def ndim(self): - """Number of dimensions.""" - return len(self._shape) - - @property - def _size(self): - return reduce(operator.mul, self._shape, 1) - - @property - def size(self): - """The total number of elements in the array.""" - # N.B., this property depends on shape, and shape may change if array - # is resized, hence need to refresh metadata - self._refresh_metadata() - return self._size - - @property - def itemsize(self): - """The size in bytes of each item in the array.""" - return self.dtype.itemsize - - @property - def _nbytes(self): - return self._size * self.itemsize - - @property - def nbytes(self): - """The total number of bytes that would be required to store the - array without compression.""" - # N.B., this property depends on shape, and shape may change if array - # is resized, hence need to refresh metadata - self._refresh_metadata() - return self._nbytes - - @property - def nbytes_stored(self): - """The total number of stored bytes of data for the array. This - includes storage required for configuration metadata and user - attributes.""" - m = getsize(self._store, self._path) - if self._chunk_store is None: - return m - else: - n = getsize(self._chunk_store, self._path) - if m < 0 or n < 0: - return -1 - else: - return m + n - - @property - def _cdata_shape(self): - if self._shape == (): - return (1,) - else: - return tuple(math.ceil(s / c) for s, c in zip(self._shape, self._chunks)) - - @property - def cdata_shape(self): - """A tuple of integers describing the number of chunks along each - dimension of the array.""" - self._refresh_metadata() - return self._cdata_shape - - @property - def _nchunks(self): - return reduce(operator.mul, self._cdata_shape, 1) - - @property - def nchunks(self): - """Total number of chunks.""" - self._refresh_metadata() - return self._nchunks - - @property - def nchunks_initialized(self): - """The number of chunks that have been initialized with some data.""" - - # key pattern for chunk keys - prog = re.compile(r"\.".join([r"\d+"] * min(1, self.ndim))) - - # count chunk keys - return sum(1 for k in listdir(self.chunk_store, self._path) if prog.match(k)) - - # backwards compatibility - initialized = nchunks_initialized - - @property - def is_view(self): - """A boolean, True if this array is a view on another array.""" - return self._is_view - - @property - def oindex(self): - """Shortcut for orthogonal (outer) indexing, see :func:`get_orthogonal_selection` and - :func:`set_orthogonal_selection` for documentation and examples.""" - return self._oindex - - @property - def vindex(self): - """Shortcut for vectorized (inner) indexing, see :func:`get_coordinate_selection`, - :func:`set_coordinate_selection`, :func:`get_mask_selection` and - :func:`set_mask_selection` for documentation and examples.""" - return self._vindex - - @property - def blocks(self): - """Shortcut for blocked chunked indexing, see :func:`get_block_selection` and - :func:`set_block_selection` for documentation and examples.""" - return self._blocks - - @property - def write_empty_chunks(self) -> bool: - """A Boolean, True if chunks composed of the array's fill value - will be stored. If False, such chunks will not be stored. - """ - return self._write_empty_chunks - - @property - def meta_array(self): - """An array-like instance to use for determining arrays to create and return - to users. - """ - return self._meta_array - - def __eq__(self, other): - return ( - isinstance(other, Array) - and self.store == other.store - and self.read_only == other.read_only - and self.path == other.path - and not self._is_view - # N.B., no need to compare other properties, should be covered by - # store comparison - ) - - def __array__(self, *args): - a = self[...] - if args: - a = a.astype(args[0]) - return a - - def islice(self, start=None, end=None): - """ - Yield a generator for iterating over the entire or parts of the - array. Uses a cache so chunks only have to be decompressed once. - - Parameters - ---------- - start : int, optional - Start index for the generator to start at. Defaults to 0. - end : int, optional - End index for the generator to stop at. Defaults to self.shape[0]. - - Yields - ------ - out : generator - A generator that can be used to iterate over the requested region - the array. - - Examples - -------- - Setup a 1-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> z = zarr.v2.array(np.arange(100)) - - Iterate over part of the array: - >>> for value in z.islice(25, 30): value; - 25 - 26 - 27 - 28 - 29 - """ - - if len(self.shape) == 0: - # Same error as numpy - raise TypeError("iteration over a 0-d array") - if start is None: - start = 0 - if end is None or end > self.shape[0]: - end = self.shape[0] - - if not isinstance(start, int) or start < 0: - raise ValueError("start must be a nonnegative integer") - - if not isinstance(end, int) or end < 0: - raise ValueError("end must be a nonnegative integer") - - # Avoid repeatedly decompressing chunks by iterating over the chunks - # in the first dimension. - chunk_size = self.chunks[0] - chunk = None - for j in range(start, end): - if j % chunk_size == 0: - chunk = self[j : j + chunk_size] - # init chunk if we start offset of chunk borders - elif chunk is None: - chunk_start = j - j % chunk_size - chunk_end = chunk_start + chunk_size - chunk = self[chunk_start:chunk_end] - yield chunk[j % chunk_size] - - def __iter__(self): - return self.islice() - - def __len__(self): - if self.shape: - return self.shape[0] - else: - # 0-dimensional array, same error message as numpy - raise TypeError("len() of unsized object") - - def __getitem__(self, selection): - """Retrieve data for an item or region of the array. - - Parameters - ---------- - selection : tuple - An integer index or slice or tuple of int/slice objects specifying the - requested item or region for each dimension of the array. - - Returns - ------- - out : ndarray - A NumPy array containing the data for the requested region. - - Examples - -------- - Setup a 1-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> z = zarr.v2.array(np.arange(100)) - - Retrieve a single item:: - - >>> z[5] - 5 - - Retrieve a region via slicing:: - - >>> z[:5] - array([0, 1, 2, 3, 4]) - >>> z[-5:] - array([95, 96, 97, 98, 99]) - >>> z[5:10] - array([5, 6, 7, 8, 9]) - >>> z[5:10:2] - array([5, 7, 9]) - >>> z[::2] - array([ 0, 2, 4, ..., 94, 96, 98]) - - Load the entire array into memory:: - - >>> z[...] - array([ 0, 1, 2, ..., 97, 98, 99]) - - Setup a 2-dimensional array:: - - >>> z = zarr.v2.array(np.arange(100).reshape(10, 10)) - - Retrieve an item:: - - >>> z[2, 2] - 22 - - Retrieve a region via slicing:: - - >>> z[1:3, 1:3] - array([[11, 12], - [21, 22]]) - >>> z[1:3, :] - array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], - [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]) - >>> z[:, 1:3] - array([[ 1, 2], - [11, 12], - [21, 22], - [31, 32], - [41, 42], - [51, 52], - [61, 62], - [71, 72], - [81, 82], - [91, 92]]) - >>> z[0:5:2, 0:5:2] - array([[ 0, 2, 4], - [20, 22, 24], - [40, 42, 44]]) - >>> z[::2, ::2] - array([[ 0, 2, 4, 6, 8], - [20, 22, 24, 26, 28], - [40, 42, 44, 46, 48], - [60, 62, 64, 66, 68], - [80, 82, 84, 86, 88]]) - - Load the entire array into memory:: - - >>> z[...] - array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], - [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], - [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], - [30, 31, 32, 33, 34, 35, 36, 37, 38, 39], - [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], - [50, 51, 52, 53, 54, 55, 56, 57, 58, 59], - [60, 61, 62, 63, 64, 65, 66, 67, 68, 69], - [70, 71, 72, 73, 74, 75, 76, 77, 78, 79], - [80, 81, 82, 83, 84, 85, 86, 87, 88, 89], - [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]]) - - For arrays with a structured dtype, specific fields can be retrieved, e.g.:: - - >>> a = np.array([(b'aaa', 1, 4.2), - ... (b'bbb', 2, 8.4), - ... (b'ccc', 3, 12.6)], - ... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')]) - >>> z = zarr.v2.array(a) - >>> z['foo'] - array([b'aaa', b'bbb', b'ccc'], - dtype='|S3') - - Notes - ----- - Slices with step > 1 are supported, but slices with negative step are not. - - Currently the implementation for __getitem__ is provided by - :func:`vindex` if the indexing is pure fancy indexing (ie a - broadcast-compatible tuple of integer array indices), or by - :func:`set_basic_selection` otherwise. - - Effectively, this means that the following indexing modes are supported: - - - integer indexing - - slice indexing - - mixed slice and integer indexing - - boolean indexing - - fancy indexing (vectorized list of integers) - - For specific indexing options including outer indexing, see the - methods listed under See Also. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection, - set_orthogonal_selection, get_block_selection, set_block_selection, - vindex, oindex, blocks, __setitem__ - - """ - fields, pure_selection = pop_fields(selection) - if is_pure_fancy_indexing(pure_selection, self.ndim): - result = self.vindex[selection] - elif is_pure_orthogonal_indexing(pure_selection, self.ndim): - result = self.get_orthogonal_selection(pure_selection, fields=fields) - else: - result = self.get_basic_selection(pure_selection, fields=fields) - return result - - def get_basic_selection(self, selection=Ellipsis, out=None, fields=None): - """Retrieve data for an item or region of the array. - - Parameters - ---------- - selection : tuple - A tuple specifying the requested item or region for each dimension of the - array. May be any combination of int and/or slice for multidimensional arrays. - out : ndarray, optional - If given, load the selected data directly into this array. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to - extract data for. - - Returns - ------- - out : ndarray - A NumPy array containing the data for the requested region. - - Examples - -------- - Setup a 1-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> z = zarr.v2.array(np.arange(100)) - - Retrieve a single item:: - - >>> z.get_basic_selection(5) - 5 - - Retrieve a region via slicing:: - - >>> z.get_basic_selection(slice(5)) - array([0, 1, 2, 3, 4]) - >>> z.get_basic_selection(slice(-5, None)) - array([95, 96, 97, 98, 99]) - >>> z.get_basic_selection(slice(5, 10)) - array([5, 6, 7, 8, 9]) - >>> z.get_basic_selection(slice(5, 10, 2)) - array([5, 7, 9]) - >>> z.get_basic_selection(slice(None, None, 2)) - array([ 0, 2, 4, ..., 94, 96, 98]) - - Setup a 2-dimensional array:: - - >>> z = zarr.v2.array(np.arange(100).reshape(10, 10)) - - Retrieve an item:: - - >>> z.get_basic_selection((2, 2)) - 22 - - Retrieve a region via slicing:: - - >>> z.get_basic_selection((slice(1, 3), slice(1, 3))) - array([[11, 12], - [21, 22]]) - >>> z.get_basic_selection((slice(1, 3), slice(None))) - array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], - [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]) - >>> z.get_basic_selection((slice(None), slice(1, 3))) - array([[ 1, 2], - [11, 12], - [21, 22], - [31, 32], - [41, 42], - [51, 52], - [61, 62], - [71, 72], - [81, 82], - [91, 92]]) - >>> z.get_basic_selection((slice(0, 5, 2), slice(0, 5, 2))) - array([[ 0, 2, 4], - [20, 22, 24], - [40, 42, 44]]) - >>> z.get_basic_selection((slice(None, None, 2), slice(None, None, 2))) - array([[ 0, 2, 4, 6, 8], - [20, 22, 24, 26, 28], - [40, 42, 44, 46, 48], - [60, 62, 64, 66, 68], - [80, 82, 84, 86, 88]]) - - For arrays with a structured dtype, specific fields can be retrieved, e.g.:: - - >>> a = np.array([(b'aaa', 1, 4.2), - ... (b'bbb', 2, 8.4), - ... (b'ccc', 3, 12.6)], - ... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')]) - >>> z = zarr.v2.array(a) - >>> z.get_basic_selection(slice(2), fields='foo') - array([b'aaa', b'bbb'], - dtype='|S3') - - Notes - ----- - Slices with step > 1 are supported, but slices with negative step are not. - - Currently this method provides the implementation for accessing data via the - square bracket notation (__getitem__). See :func:`__getitem__` for examples - using the alternative notation. - - See Also - -------- - set_basic_selection, get_mask_selection, set_mask_selection, - get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection, - set_orthogonal_selection, get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - - # refresh metadata - if not self._cache_metadata: - self._load_metadata() - - # check args - check_fields(fields, self._dtype) - - # handle zero-dimensional arrays - if self._shape == (): - return self._get_basic_selection_zd(selection=selection, out=out, fields=fields) - else: - return self._get_basic_selection_nd(selection=selection, out=out, fields=fields) - - def _get_basic_selection_zd(self, selection, out=None, fields=None): - # special case basic selection for zero-dimensional array - - # check selection is valid - selection = ensure_tuple(selection) - if selection not in ((), (Ellipsis,)): - err_too_many_indices(selection, ()) - - try: - # obtain encoded data for chunk - ckey = self._chunk_key((0,)) - cdata = self.chunk_store[ckey] - - except KeyError: - # chunk not initialized - chunk = np.zeros_like(self._meta_array, shape=(), dtype=self._dtype) - if self._fill_value is not None: - chunk.fill(self._fill_value) - - else: - chunk = self._decode_chunk(cdata) - - # handle fields - if fields: - chunk = chunk[fields] - - # handle selection of the scalar value via empty tuple - if out is None: - out = chunk[selection] - else: - out[selection] = chunk[selection] - - return out - - def _get_basic_selection_nd(self, selection, out=None, fields=None): - # implementation of basic selection for array with at least one dimension - - # setup indexer - indexer = BasicIndexer(selection, self) - - return self._get_selection(indexer=indexer, out=out, fields=fields) - - def get_orthogonal_selection(self, selection, out=None, fields=None): - """Retrieve data by making a selection for each dimension of the array. For - example, if an array has 2 dimensions, allows selecting specific rows and/or - columns. The selection for each dimension can be either an integer (indexing a - single item), a slice, an array of integers, or a Boolean array where True - values indicate a selection. - - Parameters - ---------- - selection : tuple - A selection for each dimension of the array. May be any combination of int, - slice, integer array or Boolean array. - out : ndarray, optional - If given, load the selected data directly into this array. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to - extract data for. - - Returns - ------- - out : ndarray - A NumPy array containing the data for the requested selection. - - Examples - -------- - Setup a 2-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> z = zarr.v2.array(np.arange(100).reshape(10, 10)) - - Retrieve rows and columns via any combination of int, slice, integer array and/or - Boolean array:: - - >>> z.get_orthogonal_selection(([1, 4], slice(None))) - array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], - [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]]) - >>> z.get_orthogonal_selection((slice(None), [1, 4])) - array([[ 1, 4], - [11, 14], - [21, 24], - [31, 34], - [41, 44], - [51, 54], - [61, 64], - [71, 74], - [81, 84], - [91, 94]]) - >>> z.get_orthogonal_selection(([1, 4], [1, 4])) - array([[11, 14], - [41, 44]]) - >>> sel = np.zeros(z.shape[0], dtype=bool) - >>> sel[1] = True - >>> sel[4] = True - >>> z.get_orthogonal_selection((sel, sel)) - array([[11, 14], - [41, 44]]) - - For convenience, the orthogonal selection functionality is also available via the - `oindex` property, e.g.:: - - >>> z.oindex[[1, 4], :] - array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], - [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]]) - >>> z.oindex[:, [1, 4]] - array([[ 1, 4], - [11, 14], - [21, 24], - [31, 34], - [41, 44], - [51, 54], - [61, 64], - [71, 74], - [81, 84], - [91, 94]]) - >>> z.oindex[[1, 4], [1, 4]] - array([[11, 14], - [41, 44]]) - >>> sel = np.zeros(z.shape[0], dtype=bool) - >>> sel[1] = True - >>> sel[4] = True - >>> z.oindex[sel, sel] - array([[11, 14], - [41, 44]]) - - Notes - ----- - Orthogonal indexing is also known as outer indexing. - - Slices with step > 1 are supported, but slices with negative step are not. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_coordinate_selection, set_coordinate_selection, set_orthogonal_selection, - get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - - # refresh metadata - if not self._cache_metadata: - self._load_metadata() - - # check args - check_fields(fields, self._dtype) - - # setup indexer - indexer = OrthogonalIndexer(selection, self) - - return self._get_selection(indexer=indexer, out=out, fields=fields) - - def get_coordinate_selection(self, selection, out=None, fields=None): - """Retrieve a selection of individual items, by providing the indices - (coordinates) for each selected item. - - Parameters - ---------- - selection : tuple - An integer (coordinate) array for each dimension of the array. - out : ndarray, optional - If given, load the selected data directly into this array. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to - extract data for. - - Returns - ------- - out : ndarray - A NumPy array containing the data for the requested selection. - - Examples - -------- - Setup a 2-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> z = zarr.v2.array(np.arange(100).reshape(10, 10)) - - Retrieve items by specifying their coordinates:: - - >>> z.get_coordinate_selection(([1, 4], [1, 4])) - array([11, 44]) - - For convenience, the coordinate selection functionality is also available via the - `vindex` property, e.g.:: - - >>> z.vindex[[1, 4], [1, 4]] - array([11, 44]) - - Notes - ----- - Coordinate indexing is also known as point selection, and is a form of vectorized - or inner indexing. - - Slices are not supported. Coordinate arrays must be provided for all dimensions - of the array. - - Coordinate arrays may be multidimensional, in which case the output array will - also be multidimensional. Coordinate arrays are broadcast against each other - before being applied. The shape of the output will be the same as the shape of - each coordinate array after broadcasting. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_orthogonal_selection, set_orthogonal_selection, set_coordinate_selection, - get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - - # refresh metadata - if not self._cache_metadata: - self._load_metadata() - - # check args - check_fields(fields, self._dtype) - - # setup indexer - indexer = CoordinateIndexer(selection, self) - - # handle output - need to flatten - if out is not None: - out = out.reshape(-1) - - out = self._get_selection(indexer=indexer, out=out, fields=fields) - - # restore shape - out = out.reshape(indexer.sel_shape) - - return out - - def get_block_selection(self, selection, out=None, fields=None): - """Retrieve a selection of individual chunk blocks, by providing the indices - (coordinates) for each chunk block. - - Parameters - ---------- - selection : tuple - An integer (coordinate) or slice for each dimension of the array. - out : ndarray, optional - If given, load the selected data directly into this array. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to - extract data for. - - Returns - ------- - out : ndarray - A NumPy array containing the data for the requested selection. - - Examples - -------- - Setup a 2-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> z = zarr.v2.array(np.arange(100).reshape(10, 10), chunks=(3, 3)) - - Retrieve items by specifying their block coordinates:: - - >>> z.get_block_selection((1, slice(None))) - array([[30, 31, 32, 33, 34, 35, 36, 37, 38, 39], - [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], - [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]) - - Which is equivalent to:: - - >>> z[3:6, :] - array([[30, 31, 32, 33, 34, 35, 36, 37, 38, 39], - [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], - [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]) - - For convenience, the block selection functionality is also available via the - `blocks` property, e.g.:: - - >>> z.blocks[1] - array([[30, 31, 32, 33, 34, 35, 36, 37, 38, 39], - [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], - [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]) - - Notes - ----- - Block indexing is a convenience indexing method to work on individual chunks - with chunk index slicing. It has the same concept as Dask's `Array.blocks` - indexing. - - Slices are supported. However, only with a step size of one. - - Block index arrays may be multidimensional to index multidimensional arrays. - For example:: - - >>> z.blocks[0, 1:3] - array([[ 3, 4, 5, 6, 7, 8], - [13, 14, 15, 16, 17, 18], - [23, 24, 25, 26, 27, 28]]) - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection, - set_coordinate_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - if not self._cache_metadata: - self._load_metadata() - - # check args - check_fields(fields, self._dtype) - - # setup indexer - indexer = BlockIndexer(selection, self) - - return self._get_selection(indexer=indexer, out=out, fields=fields) - - def get_mask_selection(self, selection, out=None, fields=None): - """Retrieve a selection of individual items, by providing a Boolean array of the - same shape as the array against which the selection is being made, where True - values indicate a selected item. - - Parameters - ---------- - selection : ndarray, bool - A Boolean array of the same shape as the array against which the selection is - being made. - out : ndarray, optional - If given, load the selected data directly into this array. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to - extract data for. - - Returns - ------- - out : ndarray - A NumPy array containing the data for the requested selection. - - Examples - -------- - Setup a 2-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> z = zarr.v2.array(np.arange(100).reshape(10, 10)) - - Retrieve items by specifying a mask:: - - >>> sel = np.zeros_like(z, dtype=bool) - >>> sel[1, 1] = True - >>> sel[4, 4] = True - >>> z.get_mask_selection(sel) - array([11, 44]) - - For convenience, the mask selection functionality is also available via the - `vindex` property, e.g.:: - - >>> z.vindex[sel] - array([11, 44]) - - Notes - ----- - Mask indexing is a form of vectorized or inner indexing, and is equivalent to - coordinate indexing. Internally the mask array is converted to coordinate - arrays by calling `np.nonzero`. - - See Also - -------- - get_basic_selection, set_basic_selection, set_mask_selection, - get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection, - set_coordinate_selection, get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - """ - - # refresh metadata - if not self._cache_metadata: - self._load_metadata() - - # check args - check_fields(fields, self._dtype) - - # setup indexer - indexer = MaskIndexer(selection, self) - - return self._get_selection(indexer=indexer, out=out, fields=fields) - - def _get_selection(self, indexer, out=None, fields=None): - # We iterate over all chunks which overlap the selection and thus contain data - # that needs to be extracted. Each chunk is processed in turn, extracting the - # necessary data and storing into the correct location in the output array. - - # N.B., it is an important optimisation that we only visit chunks which overlap - # the selection. This minimises the number of iterations in the main for loop. - - # check fields are sensible - out_dtype = check_fields(fields, self._dtype) - - # determine output shape - out_shape = indexer.shape - - # setup output array - if out is None: - out = np.empty_like( - self._meta_array, shape=out_shape, dtype=out_dtype, order=self._order - ) - else: - check_array_shape("out", out, out_shape) - - # iterate over chunks - - if math.prod(out_shape) > 0: - # allow storage to get multiple items at once - lchunk_coords, lchunk_selection, lout_selection = zip(*indexer) - self._chunk_getitems( - lchunk_coords, - lchunk_selection, - out, - lout_selection, - drop_axes=indexer.drop_axes, - fields=fields, - ) - if out.shape: - return out - else: - return out[()] - - def __setitem__(self, selection, value): - """Modify data for an item or region of the array. - - Parameters - ---------- - selection : tuple - An integer index or slice or tuple of int/slice specifying the requested - region for each dimension of the array. - value : scalar or array-like - Value to be stored into the array. - - Examples - -------- - Setup a 1-dimensional array:: - - >>> import zarr - >>> z = zarr.v2.zeros(100, dtype=int) - - Set all array elements to the same scalar value:: - - >>> z[...] = 42 - >>> z[...] - array([42, 42, 42, ..., 42, 42, 42]) - - Set a portion of the array:: - - >>> z[:10] = np.arange(10) - >>> z[-10:] = np.arange(10)[::-1] - >>> z[...] - array([ 0, 1, 2, ..., 2, 1, 0]) - - Setup a 2-dimensional array:: - - >>> z = zarr.v2.zeros((5, 5), dtype=int) - - Set all array elements to the same scalar value:: - - >>> z[...] = 42 - - Set a portion of the array:: - - >>> z[0, :] = np.arange(z.shape[1]) - >>> z[:, 0] = np.arange(z.shape[0]) - >>> z[...] - array([[ 0, 1, 2, 3, 4], - [ 1, 42, 42, 42, 42], - [ 2, 42, 42, 42, 42], - [ 3, 42, 42, 42, 42], - [ 4, 42, 42, 42, 42]]) - - For arrays with a structured dtype, specific fields can be modified, e.g.:: - - >>> a = np.array([(b'aaa', 1, 4.2), - ... (b'bbb', 2, 8.4), - ... (b'ccc', 3, 12.6)], - ... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')]) - >>> z = zarr.v2.array(a) - >>> z['foo'] = b'zzz' - >>> z[...] - array([(b'zzz', 1, 4.2), (b'zzz', 2, 8.4), (b'zzz', 3, 12.6)], - dtype=[('foo', 'S3'), ('bar', ' 1 are supported, but slices with negative step are not. - - Currently the implementation for __setitem__ is provided by - :func:`vindex` if the indexing is pure fancy indexing (ie a - broadcast-compatible tuple of integer array indices), or by - :func:`set_basic_selection` otherwise. - - Effectively, this means that the following indexing modes are supported: - - - integer indexing - - slice indexing - - mixed slice and integer indexing - - boolean indexing - - fancy indexing (vectorized list of integers) - - For specific indexing options including outer indexing, see the - methods listed under See Also. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection, - set_orthogonal_selection, get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__ - - """ - fields, pure_selection = pop_fields(selection) - if is_pure_fancy_indexing(pure_selection, self.ndim): - self.vindex[selection] = value - elif is_pure_orthogonal_indexing(pure_selection, self.ndim): - self.set_orthogonal_selection(pure_selection, value, fields=fields) - else: - self.set_basic_selection(pure_selection, value, fields=fields) - - def set_basic_selection(self, selection, value, fields=None): - """Modify data for an item or region of the array. - - Parameters - ---------- - selection : tuple - An integer index or slice or tuple of int/slice specifying the requested - region for each dimension of the array. - value : scalar or array-like - Value to be stored into the array. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to set - data for. - - Examples - -------- - Setup a 1-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> z = zarr.v2.zeros(100, dtype=int) - - Set all array elements to the same scalar value:: - - >>> z.set_basic_selection(..., 42) - >>> z[...] - array([42, 42, 42, ..., 42, 42, 42]) - - Set a portion of the array:: - - >>> z.set_basic_selection(slice(10), np.arange(10)) - >>> z.set_basic_selection(slice(-10, None), np.arange(10)[::-1]) - >>> z[...] - array([ 0, 1, 2, ..., 2, 1, 0]) - - Setup a 2-dimensional array:: - - >>> z = zarr.v2.zeros((5, 5), dtype=int) - - Set all array elements to the same scalar value:: - - >>> z.set_basic_selection(..., 42) - - Set a portion of the array:: - - >>> z.set_basic_selection((0, slice(None)), np.arange(z.shape[1])) - >>> z.set_basic_selection((slice(None), 0), np.arange(z.shape[0])) - >>> z[...] - array([[ 0, 1, 2, 3, 4], - [ 1, 42, 42, 42, 42], - [ 2, 42, 42, 42, 42], - [ 3, 42, 42, 42, 42], - [ 4, 42, 42, 42, 42]]) - - For arrays with a structured dtype, the `fields` parameter can be used to set - data for a specific field, e.g.:: - - >>> a = np.array([(b'aaa', 1, 4.2), - ... (b'bbb', 2, 8.4), - ... (b'ccc', 3, 12.6)], - ... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')]) - >>> z = zarr.v2.array(a) - >>> z.set_basic_selection(slice(0, 2), b'zzz', fields='foo') - >>> z[:] - array([(b'zzz', 1, 4.2), (b'zzz', 2, 8.4), (b'ccc', 3, 12.6)], - dtype=[('foo', 'S3'), ('bar', '>> import zarr - >>> import numpy as np - >>> z = zarr.v2.zeros((5, 5), dtype=int) - - Set data for a selection of rows:: - - >>> z.set_orthogonal_selection(([1, 4], slice(None)), 1) - >>> z[...] - array([[0, 0, 0, 0, 0], - [1, 1, 1, 1, 1], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [1, 1, 1, 1, 1]]) - - Set data for a selection of columns:: - - >>> z.set_orthogonal_selection((slice(None), [1, 4]), 2) - >>> z[...] - array([[0, 2, 0, 0, 2], - [1, 2, 1, 1, 2], - [0, 2, 0, 0, 2], - [0, 2, 0, 0, 2], - [1, 2, 1, 1, 2]]) - - Set data for a selection of rows and columns:: - - >>> z.set_orthogonal_selection(([1, 4], [1, 4]), 3) - >>> z[...] - array([[0, 2, 0, 0, 2], - [1, 3, 1, 1, 3], - [0, 2, 0, 0, 2], - [0, 2, 0, 0, 2], - [1, 3, 1, 1, 3]]) - - For convenience, this functionality is also available via the `oindex` property. - E.g.:: - - >>> z.oindex[[1, 4], [1, 4]] = 4 - >>> z[...] - array([[0, 2, 0, 0, 2], - [1, 4, 1, 1, 4], - [0, 2, 0, 0, 2], - [0, 2, 0, 0, 2], - [1, 4, 1, 1, 4]]) - - Notes - ----- - Orthogonal indexing is also known as outer indexing. - - Slices with step > 1 are supported, but slices with negative step are not. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection, - get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - - # guard conditions - if self._read_only: - raise ReadOnlyError - - # refresh metadata - if not self._cache_metadata: - self._load_metadata_nosync() - - # setup indexer - indexer = OrthogonalIndexer(selection, self) - - self._set_selection(indexer, value, fields=fields) - - def set_coordinate_selection(self, selection, value, fields=None): - """Modify a selection of individual items, by providing the indices (coordinates) - for each item to be modified. - - Parameters - ---------- - selection : tuple - An integer (coordinate) array for each dimension of the array. - value : scalar or array-like - Value to be stored into the array. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to set - data for. - - Examples - -------- - Setup a 2-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> z = zarr.v2.zeros((5, 5), dtype=int) - - Set data for a selection of items:: - - >>> z.set_coordinate_selection(([1, 4], [1, 4]), 1) - >>> z[...] - array([[0, 0, 0, 0, 0], - [0, 1, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 1]]) - - For convenience, this functionality is also available via the `vindex` property. - E.g.:: - - >>> z.vindex[[1, 4], [1, 4]] = 2 - >>> z[...] - array([[0, 0, 0, 0, 0], - [0, 2, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 2]]) - - Notes - ----- - Coordinate indexing is also known as point selection, and is a form of vectorized - or inner indexing. - - Slices are not supported. Coordinate arrays must be provided for all dimensions - of the array. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection, - get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - - # guard conditions - if self._read_only: - raise ReadOnlyError - - # refresh metadata - if not self._cache_metadata: - self._load_metadata_nosync() - - # setup indexer - indexer = CoordinateIndexer(selection, self) - - # handle value - need ndarray-like flatten value - if not is_scalar(value, self._dtype): - try: - value = ensure_ndarray_like(value) - except TypeError: - # Handle types like `list` or `tuple` - value = np.array(value, like=self._meta_array) - if hasattr(value, "shape") and len(value.shape) > 1: - value = value.reshape(-1) - - self._set_selection(indexer, value, fields=fields) - - def set_block_selection(self, selection, value, fields=None): - """Modify a selection of individual blocks, by providing the chunk indices - (coordinates) for each block to be modified. - - Parameters - ---------- - selection : tuple - An integer (coordinate) or slice for each dimension of the array. - value : scalar or array-like - Value to be stored into the array. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to set - data for. - - Examples - -------- - Set up a 2-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> z = zarr.v2.zeros((6, 6), dtype=int, chunks=2) - - Set data for a selection of items:: - - >>> z.set_block_selection((1, 0), 1) - >>> z[...] - array([[0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0]]) - - For convenience, this functionality is also available via the `blocks` property. - E.g.:: - - >>> z.blocks[2, 1] = 4 - >>> z[...] - array([[0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0], - [0, 0, 4, 4, 0, 0], - [0, 0, 4, 4, 0, 0]]) - - >>> z.blocks[:, 2] = 7 - >>> z[...] - array([[0, 0, 0, 0, 7, 7], - [0, 0, 0, 0, 7, 7], - [1, 1, 0, 0, 7, 7], - [1, 1, 0, 0, 7, 7], - [0, 0, 4, 4, 7, 7], - [0, 0, 4, 4, 7, 7]]) - - Notes - ----- - Block indexing is a convenience indexing method to work on individual chunks - with chunk index slicing. It has the same concept as Dask's `Array.blocks` - indexing. - - Slices are supported. However, only with a step size of one. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, - get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection, - get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - # guard conditions - if self._read_only: - raise ReadOnlyError - - # refresh metadata - if not self._cache_metadata: - self._load_metadata_nosync() - - # setup indexer - indexer = BlockIndexer(selection, self) - - self._set_selection(indexer, value, fields=fields) - - def set_mask_selection(self, selection, value, fields=None): - """Modify a selection of individual items, by providing a Boolean array of the - same shape as the array against which the selection is being made, where True - values indicate a selected item. - - Parameters - ---------- - selection : ndarray, bool - A Boolean array of the same shape as the array against which the selection is - being made. - value : scalar or array-like - Value to be stored into the array. - fields : str or sequence of str, optional - For arrays with a structured dtype, one or more fields can be specified to set - data for. - - Examples - -------- - Setup a 2-dimensional array:: - - >>> import zarr - >>> import numpy as np - >>> z = zarr.v2.zeros((5, 5), dtype=int) - - Set data for a selection of items:: - - >>> sel = np.zeros_like(z, dtype=bool) - >>> sel[1, 1] = True - >>> sel[4, 4] = True - >>> z.set_mask_selection(sel, 1) - >>> z[...] - array([[0, 0, 0, 0, 0], - [0, 1, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 1]]) - - For convenience, this functionality is also available via the `vindex` property. - E.g.:: - - >>> z.vindex[sel] = 2 - >>> z[...] - array([[0, 0, 0, 0, 0], - [0, 2, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 0], - [0, 0, 0, 0, 2]]) - - Notes - ----- - Mask indexing is a form of vectorized or inner indexing, and is equivalent to - coordinate indexing. Internally the mask array is converted to coordinate - arrays by calling `np.nonzero`. - - See Also - -------- - get_basic_selection, set_basic_selection, get_mask_selection, - get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection, - set_coordinate_selection, get_block_selection, set_block_selection, - vindex, oindex, blocks, __getitem__, __setitem__ - - """ - - # guard conditions - if self._read_only: - raise ReadOnlyError - - # refresh metadata - if not self._cache_metadata: - self._load_metadata_nosync() - - # setup indexer - indexer = MaskIndexer(selection, self) - - self._set_selection(indexer, value, fields=fields) - - def _set_basic_selection_zd(self, selection, value, fields=None): - # special case __setitem__ for zero-dimensional array - - # check selection is valid - selection = ensure_tuple(selection) - if selection not in ((), (Ellipsis,)): - err_too_many_indices(selection, self._shape) - - # check fields - check_fields(fields, self._dtype) - fields = check_no_multi_fields(fields) - - # obtain key for chunk - ckey = self._chunk_key((0,)) - - # setup chunk - try: - # obtain compressed data for chunk - cdata = self.chunk_store[ckey] - - except KeyError: - # chunk not initialized - chunk = np.zeros_like(self._meta_array, shape=(), dtype=self._dtype) - if self._fill_value is not None: - chunk.fill(self._fill_value) - - else: - # decode chunk - chunk = self._decode_chunk(cdata).copy() - - # set value - if fields: - chunk[fields][selection] = value - else: - chunk[selection] = value - - # remove chunk if write_empty_chunks is false and it only contains the fill value - if (not self.write_empty_chunks) and all_equal(self.fill_value, chunk): - try: - del self.chunk_store[ckey] - return - except Exception: # pragma: no cover - # deleting failed, fallback to overwriting - pass - else: - # encode and store - cdata = self._encode_chunk(chunk) - self.chunk_store[ckey] = cdata - - def _set_basic_selection_nd(self, selection, value, fields=None): - # implementation of __setitem__ for array with at least one dimension - - # setup indexer - indexer = BasicIndexer(selection, self) - - self._set_selection(indexer, value, fields=fields) - - def _set_selection(self, indexer, value, fields=None): - # We iterate over all chunks which overlap the selection and thus contain data - # that needs to be replaced. Each chunk is processed in turn, extracting the - # necessary data from the value array and storing into the chunk array. - - # N.B., it is an important optimisation that we only visit chunks which overlap - # the selection. This minimises the number of iterations in the main for loop. - - # check fields are sensible - check_fields(fields, self._dtype) - fields = check_no_multi_fields(fields) - - # determine indices of chunks overlapping the selection - sel_shape = indexer.shape - - # check value shape - if sel_shape == (): - # setting a single item - pass - elif is_scalar(value, self._dtype): - # setting a scalar value - pass - else: - if not hasattr(value, "shape"): - value = np.asanyarray(value, like=self._meta_array) - check_array_shape("value", value, sel_shape) - - # iterate over chunks in range - if ( - not hasattr(self.chunk_store, "setitems") - or self._synchronizer is not None - or any(map(lambda x: x == 0, self.shape)) - ): - # iterative approach - for chunk_coords, chunk_selection, out_selection in indexer: - # extract data to store - if sel_shape == (): - chunk_value = value - elif is_scalar(value, self._dtype): - chunk_value = value - else: - chunk_value = value[out_selection] - # handle missing singleton dimensions - if indexer.drop_axes: - item = [slice(None)] * self.ndim - for a in indexer.drop_axes: - item[a] = np.newaxis - item = tuple(item) - chunk_value = chunk_value[item] - - # put data - self._chunk_setitem(chunk_coords, chunk_selection, chunk_value, fields=fields) - else: - lchunk_coords, lchunk_selection, lout_selection = zip(*indexer) - chunk_values = [] - for out_selection in lout_selection: - if sel_shape == (): - chunk_values.append(value) - elif is_scalar(value, self._dtype): - chunk_values.append(value) - else: - cv = value[out_selection] - # handle missing singleton dimensions - if indexer.drop_axes: # pragma: no cover - item = [slice(None)] * self.ndim - for a in indexer.drop_axes: - item[a] = np.newaxis - item = tuple(item) - cv = chunk_value[item] - chunk_values.append(cv) - - self._chunk_setitems(lchunk_coords, lchunk_selection, chunk_values, fields=fields) - - def _process_chunk( - self, - out, - cdata, - chunk_selection, - drop_axes, - out_is_ndarray, - fields, - out_selection, - partial_read_decode=False, - ): - """Take binary data from storage and fill output array""" - if ( - out_is_ndarray - and not fields - and is_contiguous_selection(out_selection) - and is_total_slice(chunk_selection, self._chunks) - and not self._filters - and self._dtype != object - ): - dest = out[out_selection] - # Assume that array-like objects that doesn't have a - # `writeable` flag is writable. - dest_is_writable = getattr(dest, "writeable", True) - write_direct = dest_is_writable and ( - (self._order == "C" and dest.flags.c_contiguous) - or (self._order == "F" and dest.flags.f_contiguous) - ) - - if write_direct: - # optimization: we want the whole chunk, and the destination is - # contiguous, so we can decompress directly from the chunk - # into the destination array - if self._compressor: - if isinstance(cdata, PartialReadBuffer): - cdata = cdata.read_full() - self._compressor.decode(cdata, dest) - else: - chunk = ensure_ndarray_like(cdata).view(self._dtype) - chunk = chunk.reshape(self._chunks, order=self._order) - np.copyto(dest, chunk) - return - - # decode chunk - try: - if partial_read_decode: - cdata.prepare_chunk() - # size of chunk - tmp = np.empty_like(self._meta_array, shape=self._chunks, dtype=self.dtype) - index_selection = PartialChunkIterator(chunk_selection, self.chunks) - for start, nitems, partial_out_selection in index_selection: - expected_shape = [ - len(range(*partial_out_selection[i].indices(self.chunks[0] + 1))) - if i < len(partial_out_selection) - else dim - for i, dim in enumerate(self.chunks) - ] - cdata.read_part(start, nitems) - chunk_partial = self._decode_chunk( - cdata.buff, - start=start, - nitems=nitems, - expected_shape=expected_shape, - ) - tmp[partial_out_selection] = chunk_partial - out[out_selection] = tmp[chunk_selection] - return - except ArrayIndexError: - cdata = cdata.read_full() - chunk = self._decode_chunk(cdata) - - # select data from chunk - if fields: - chunk = chunk[fields] - tmp = chunk[chunk_selection] - if drop_axes: - tmp = np.squeeze(tmp, axis=drop_axes) - - # store selected data in output - out[out_selection] = tmp - - def _chunk_getitems( - self, lchunk_coords, lchunk_selection, out, lout_selection, drop_axes=None, fields=None - ): - """Obtain part or whole of chunks. - - Parameters - ---------- - chunk_coords : list of tuple of ints - Indices of the chunks. - chunk_selection : list of selections - Location of region within the chunks to extract. - out : ndarray - Array to store result in. - out_selection : list of selections - Location of regions within output array to store results in. - drop_axes : tuple of ints - Axes to squeeze out of the chunk. - fields - TODO - """ - - out_is_ndarray = True - try: - out = ensure_ndarray_like(out) - except TypeError: # pragma: no cover - out_is_ndarray = False - - # Keys to retrieve - ckeys = [self._chunk_key(ch) for ch in lchunk_coords] - - # Check if we can do a partial read - if ( - self._partial_decompress - and self._compressor - and self._compressor.codec_id == "blosc" - and hasattr(self._compressor, "decode_partial") - and not fields - and self.dtype != object - and hasattr(self.chunk_store, "getitems") - ): - partial_read_decode = True - cdatas = { - ckey: PartialReadBuffer(ckey, self.chunk_store) - for ckey in ckeys - if ckey in self.chunk_store - } - elif ( - self._partial_decompress - and not self._compressor - and not fields - and self.dtype != object - and hasattr(self.chunk_store, "get_partial_values") - and self.chunk_store.supports_efficient_get_partial_values - ): - partial_read_decode = True - cdatas = { - ckey: UncompressedPartialReadBufferV3( - ckey, self.chunk_store, itemsize=self.itemsize - ) - for ckey in ckeys - if ckey in self.chunk_store - } - elif hasattr(self.chunk_store, "get_partial_values"): - partial_read_decode = False - values = self.chunk_store.get_partial_values([(ckey, (0, None)) for ckey in ckeys]) - cdatas = {key: value for key, value in zip(ckeys, values) if value is not None} - else: - partial_read_decode = False - contexts = {} - if not isinstance(self._meta_array, np.ndarray): - contexts = ConstantMap(ckeys, constant=Context(meta_array=self._meta_array)) - cdatas = self.chunk_store.getitems(ckeys, contexts=contexts) - - for ckey, chunk_select, out_select in zip(ckeys, lchunk_selection, lout_selection): - if ckey in cdatas: - self._process_chunk( - out, - cdatas[ckey], - chunk_select, - drop_axes, - out_is_ndarray, - fields, - out_select, - partial_read_decode=partial_read_decode, - ) - else: - # check exception type - if self._fill_value is not None: - if fields: - fill_value = self._fill_value[fields] - else: - fill_value = self._fill_value - out[out_select] = fill_value - - def _chunk_setitems(self, lchunk_coords, lchunk_selection, values, fields=None): - ckeys = map(self._chunk_key, lchunk_coords) - cdatas = { - key: self._process_for_setitem(key, sel, val, fields=fields) - for key, sel, val in zip(ckeys, lchunk_selection, values) - } - to_store = {} - if not self.write_empty_chunks: - empty_chunks = {k: v for k, v in cdatas.items() if all_equal(self.fill_value, v)} - self._chunk_delitems(empty_chunks.keys()) - nonempty_keys = cdatas.keys() - empty_chunks.keys() - to_store = {k: self._encode_chunk(cdatas[k]) for k in nonempty_keys} - else: - to_store = {k: self._encode_chunk(v) for k, v in cdatas.items()} - self.chunk_store.setitems(to_store) - - def _chunk_delitems(self, ckeys): - if hasattr(self.store, "delitems"): - self.store.delitems(ckeys) - else: # pragma: no cover - # exempting this branch from coverage as there are no extant stores - # that will trigger this condition, but it's possible that they - # will be developed in the future. - tuple(map(self._chunk_delitem, ckeys)) - - def _chunk_delitem(self, ckey): - """ - Attempt to delete the value associated with ckey. - """ - try: - del self.chunk_store[ckey] - except KeyError: - pass - - def _chunk_setitem(self, chunk_coords, chunk_selection, value, fields=None): - """Replace part or whole of a chunk. - - Parameters - ---------- - chunk_coords : tuple of ints - Indices of the chunk. - chunk_selection : tuple of slices - Location of region within the chunk. - value : scalar or ndarray - Value to set. - - """ - - if self._synchronizer is None: - # no synchronization - lock = nolock - else: - # synchronize on the chunk - ckey = self._chunk_key(chunk_coords) - lock = self._synchronizer[ckey] - - with lock: - self._chunk_setitem_nosync(chunk_coords, chunk_selection, value, fields=fields) - - def _chunk_setitem_nosync(self, chunk_coords, chunk_selection, value, fields=None): - ckey = self._chunk_key(chunk_coords) - cdata = self._process_for_setitem(ckey, chunk_selection, value, fields=fields) - - # attempt to delete chunk if it only contains the fill value - if (not self.write_empty_chunks) and all_equal(self.fill_value, cdata): - self._chunk_delitem(ckey) - else: - self.chunk_store[ckey] = self._encode_chunk(cdata) - - def _process_for_setitem(self, ckey, chunk_selection, value, fields=None): - if is_total_slice(chunk_selection, self._chunks) and not fields: - # totally replace chunk - - # optimization: we are completely replacing the chunk, so no need - # to access the existing chunk data - - if is_scalar(value, self._dtype): - # setup array filled with value - chunk = np.empty_like( - self._meta_array, shape=self._chunks, dtype=self._dtype, order=self._order - ) - chunk.fill(value) - - else: - # ensure array is contiguous - chunk = value.astype(self._dtype, order=self._order, copy=False) - - else: - # partially replace the contents of this chunk - - try: - # obtain compressed data for chunk - cdata = self.chunk_store[ckey] - - except KeyError: - # chunk not initialized - if self._fill_value is not None: - chunk = np.empty_like( - self._meta_array, shape=self._chunks, dtype=self._dtype, order=self._order - ) - chunk.fill(self._fill_value) - elif self._dtype == object: - chunk = np.empty(self._chunks, dtype=self._dtype, order=self._order) - else: - # N.B., use zeros here so any region beyond the array has consistent - # and compressible data - chunk = np.zeros_like( - self._meta_array, shape=self._chunks, dtype=self._dtype, order=self._order - ) - - else: - # decode chunk - chunk = self._decode_chunk(cdata) - if not chunk.flags.writeable: - chunk = chunk.copy(order="K") - - # modify - if fields: - # N.B., currently multi-field assignment is not supported in numpy, so - # this only works for a single field - chunk[fields][chunk_selection] = value - else: - chunk[chunk_selection] = value - - return chunk - - def _chunk_key(self, chunk_coords): - return self._key_prefix + self._dimension_separator.join(map(str, chunk_coords)) - - def _decode_chunk(self, cdata, start=None, nitems=None, expected_shape=None): - # decompress - if self._compressor: - # only decode requested items - if ( - all(x is not None for x in [start, nitems]) and self._compressor.codec_id == "blosc" - ) and hasattr(self._compressor, "decode_partial"): - chunk = self._compressor.decode_partial(cdata, start, nitems) - else: - chunk = self._compressor.decode(cdata) - else: - chunk = cdata - - # apply filters - if self._filters: - for f in reversed(self._filters): - chunk = f.decode(chunk) - - # view as numpy array with correct dtype - chunk = ensure_ndarray_like(chunk) - # special case object dtype, because incorrect handling can lead to - # segfaults and other bad things happening - if self._dtype != object: - chunk = chunk.view(self._dtype) - elif chunk.dtype != object: - # If we end up here, someone must have hacked around with the filters. - # We cannot deal with object arrays unless there is an object - # codec in the filter chain, i.e., a filter that converts from object - # array to something else during encoding, and converts back to object - # array during decoding. - raise RuntimeError("cannot read object array without object codec") - - # ensure correct chunk shape - chunk = chunk.reshape(-1, order="A") - chunk = chunk.reshape(expected_shape or self._chunks, order=self._order) - - return chunk - - def _encode_chunk(self, chunk): - # apply filters - if self._filters: - for f in self._filters: - chunk = f.encode(chunk) - - # check object encoding - if ensure_ndarray_like(chunk).dtype == object: - raise RuntimeError("cannot write object array without object codec") - - # compress - if self._compressor: - cdata = self._compressor.encode(chunk) - else: - cdata = chunk - - # ensure in-memory data is immutable and easy to compare - if isinstance(self.chunk_store, KVStore) or isinstance(self._chunk_store, KVStore): - cdata = ensure_bytes(cdata) - - return cdata - - def __repr__(self): - t = type(self) - r = "<{}.{}".format(t.__module__, t.__name__) - if self.name: - r += " %r" % self.name - r += " %s" % str(self.shape) - r += " %s" % self.dtype - if self._read_only: - r += " read-only" - r += ">" - return r - - @property - def info(self): - """Report some diagnostic information about the array. - - Examples - -------- - >>> import zarr - >>> z = zarr.v2.zeros(1000000, chunks=100000, dtype='i4') - >>> z.info - Type : zarr.v2.core.Array - Data type : int32 - Shape : (1000000,) - Chunk shape : (100000,) - Order : C - Read-only : False - Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0) - Store type : zarr.v2.storage.KVStore - No. bytes : 4000000 (3.8M) - No. bytes stored : 320 - Storage ratio : 12500.0 - Chunks initialized : 0/10 - - """ - return self._info_reporter - - def info_items(self): - return self._synchronized_op(self._info_items_nosync) - - def _info_items_nosync(self): - def typestr(o): - return "{}.{}".format(type(o).__module__, type(o).__name__) - - def bytestr(n): - if n > 2**10: - return "{} ({})".format(n, human_readable_size(n)) - else: - return str(n) - - items = [] - - # basic info - if self.name is not None: - items += [("Name", self.name)] - items += [ - ("Type", typestr(self)), - ("Data type", "%s" % self.dtype), - ("Shape", str(self.shape)), - ("Chunk shape", str(self.chunks)), - ("Order", self.order), - ("Read-only", str(self.read_only)), - ] - - # filters - if self.filters: - for i, f in enumerate(self.filters): - items += [("Filter [%s]" % i, repr(f))] - - # compressor - items += [("Compressor", repr(self.compressor))] - - # synchronizer - if self._synchronizer is not None: - items += [("Synchronizer type", typestr(self._synchronizer))] - - # storage info - items += [("Store type", typestr(self._store))] - if self._chunk_store is not None: - items += [("Chunk store type", typestr(self._chunk_store))] - items += [("No. bytes", bytestr(self.nbytes))] - if self.nbytes_stored > 0: - items += [ - ("No. bytes stored", bytestr(self.nbytes_stored)), - ("Storage ratio", "%.1f" % (self.nbytes / self.nbytes_stored)), - ] - items += [("Chunks initialized", "{}/{}".format(self.nchunks_initialized, self.nchunks))] - - return items - - def digest(self, hashname="sha1"): - """ - Compute a checksum for the data. Default uses sha1 for speed. - - Examples - -------- - >>> import binascii - >>> import zarr - >>> z = zarr.v2.empty(shape=(10000, 10000), chunks=(1000, 1000)) - >>> binascii.hexlify(z.digest()) - b'041f90bc7a571452af4f850a8ca2c6cddfa8a1ac' - >>> z = zarr.v2.zeros(shape=(10000, 10000), chunks=(1000, 1000)) - >>> binascii.hexlify(z.digest()) - b'7162d416d26a68063b66ed1f30e0a866e4abed60' - >>> z = zarr.v2.zeros(shape=(10000, 10000), dtype="u1", chunks=(1000, 1000)) - >>> binascii.hexlify(z.digest()) - b'cb387af37410ae5a3222e893cf3373e4e4f22816' - """ - - h = hashlib.new(hashname) - - for i in itertools.product(*[range(s) for s in self.cdata_shape]): - h.update(self.chunk_store.get(self._chunk_key(i), b"")) - - mkey = _prefix_to_array_key(self._store, self._key_prefix) - h.update(self.store.get(mkey, b"")) - - h.update(self.store.get(self.attrs.key, b"")) - - checksum = h.digest() - - return checksum - - def hexdigest(self, hashname="sha1"): - """ - Compute a checksum for the data. Default uses sha1 for speed. - - Examples - -------- - >>> import zarr - >>> z = zarr.v2.empty(shape=(10000, 10000), chunks=(1000, 1000)) - >>> z.hexdigest() - '041f90bc7a571452af4f850a8ca2c6cddfa8a1ac' - >>> z = zarr.v2.zeros(shape=(10000, 10000), chunks=(1000, 1000)) - >>> z.hexdigest() - '7162d416d26a68063b66ed1f30e0a866e4abed60' - >>> z = zarr.v2.zeros(shape=(10000, 10000), dtype="u1", chunks=(1000, 1000)) - >>> z.hexdigest() - 'cb387af37410ae5a3222e893cf3373e4e4f22816' - """ - - checksum = binascii.hexlify(self.digest(hashname=hashname)) - - # This is a bytes object on Python 3 and we want a str. - if not isinstance(checksum, str): - checksum = checksum.decode("utf8") - - return checksum - - def __getstate__(self): - return { - "store": self._store, - "path": self._path, - "read_only": self._read_only, - "chunk_store": self._chunk_store, - "synchronizer": self._synchronizer, - "cache_metadata": self._cache_metadata, - "cache_attrs": self._attrs.cache, - "partial_decompress": self._partial_decompress, - "write_empty_chunks": self._write_empty_chunks, - "meta_array": self._meta_array, - } - - def __setstate__(self, state): - self.__init__(**state) - - def _synchronized_op(self, f, *args, **kwargs): - if self._synchronizer is None: - # no synchronization - lock = nolock - - else: - # synchronize on the array - mkey = _prefix_to_array_key(self._store, self._key_prefix) - lock = self._synchronizer[mkey] - - with lock: - self._refresh_metadata_nosync() - result = f(*args, **kwargs) - - return result - - def _write_op(self, f, *args, **kwargs): - # guard condition - if self._read_only: - raise ReadOnlyError - - return self._synchronized_op(f, *args, **kwargs) - - def resize(self, *args): - """Change the shape of the array by growing or shrinking one or more - dimensions. - - Examples - -------- - >>> import zarr - >>> z = zarr.v2.zeros(shape=(10000, 10000), chunks=(1000, 1000)) - >>> z.shape - (10000, 10000) - >>> z.resize(20000, 10000) - >>> z.shape - (20000, 10000) - >>> z.resize(30000, 1000) - >>> z.shape - (30000, 1000) - - Notes - ----- - When resizing an array, the data are not rearranged in any way. - - If one or more dimensions are shrunk, any chunks falling outside the - new array shape will be deleted from the underlying store. - However, it is noteworthy that the chunks partially falling inside the new array - (i.e. boundary chunks) will remain intact, and therefore, - the data falling outside the new array but inside the boundary chunks - would be restored by a subsequent resize operation that grows the array size. - - """ - - return self._write_op(self._resize_nosync, *args) - - def _resize_nosync(self, *args): - # normalize new shape argument - old_shape = self._shape - new_shape = normalize_resize_args(old_shape, *args) - old_cdata_shape = self._cdata_shape - - # update metadata - self._shape = new_shape - self._flush_metadata_nosync() - - # determine the new number and arrangement of chunks - chunks = self._chunks - new_cdata_shape = tuple(math.ceil(s / c) for s, c in zip(new_shape, chunks)) - - # remove any chunks not within range - # The idea is that, along each dimension, - # only find and remove the chunk slices that exist in 'old' but not 'new' data. - # Note that a mutable list ('old_cdata_shape_working_list') is introduced here - # to dynamically adjust the number of chunks along the already-processed dimensions - # in order to avoid duplicate chunk removal. - chunk_store = self.chunk_store - old_cdata_shape_working_list = list(old_cdata_shape) - for idx_cdata, (val_old_cdata, val_new_cdata) in enumerate( - zip(old_cdata_shape_working_list, new_cdata_shape) - ): - for cidx in itertools.product( - *[ - range(n_new, n_old) if (idx == idx_cdata) else range(n_old) - for idx, (n_old, n_new) in enumerate( - zip(old_cdata_shape_working_list, new_cdata_shape) - ) - ] - ): - key = self._chunk_key(cidx) - try: - del chunk_store[key] - except KeyError: - # chunk not initialized - pass - old_cdata_shape_working_list[idx_cdata] = min(val_old_cdata, val_new_cdata) - - def append(self, data, axis=0): - """Append `data` to `axis`. - - Parameters - ---------- - data : array-like - Data to be appended. - axis : int - Axis along which to append. - - Returns - ------- - new_shape : tuple - - Notes - ----- - The size of all dimensions other than `axis` must match between this - array and `data`. - - Examples - -------- - >>> import numpy as np - >>> import zarr - >>> a = np.arange(10000000, dtype='i4').reshape(10000, 1000) - >>> z = zarr.v2.array(a, chunks=(1000, 100)) - >>> z.shape - (10000, 1000) - >>> z.append(a) - (20000, 1000) - >>> z.append(np.vstack([a, a]), axis=1) - (20000, 2000) - >>> z.shape - (20000, 2000) - - """ - return self._write_op(self._append_nosync, data, axis=axis) - - def _append_nosync(self, data, axis=0): - # ensure data is array-like - if not hasattr(data, "shape"): - data = np.asanyarray(data, like=self._meta_array) - - # ensure shapes are compatible for non-append dimensions - self_shape_preserved = tuple(s for i, s in enumerate(self._shape) if i != axis) - data_shape_preserved = tuple(s for i, s in enumerate(data.shape) if i != axis) - if self_shape_preserved != data_shape_preserved: - raise ValueError( - "shape of data to append is not compatible with the array; " - "all dimensions must match except for the dimension being " - "appended" - ) - - # remember old shape - old_shape = self._shape - - # determine new shape - new_shape = tuple( - self._shape[i] if i != axis else self._shape[i] + data.shape[i] - for i in range(len(self._shape)) - ) - - # resize - self._resize_nosync(new_shape) - - # store data - # noinspection PyTypeChecker - append_selection = tuple( - slice(None) if i != axis else slice(old_shape[i], new_shape[i]) - for i in range(len(self._shape)) - ) - self[append_selection] = data - - return new_shape - - def view( - self, - shape=None, - chunks=None, - dtype=None, - fill_value=None, - filters=None, - read_only=None, - synchronizer=None, - ): - """Return an array sharing the same data. - - Parameters - ---------- - shape : int or tuple of ints - Array shape. - chunks : int or tuple of ints, optional - Chunk shape. - dtype : string or dtype, optional - NumPy dtype. - fill_value : object - Default value to use for uninitialized portions of the array. - filters : sequence, optional - Sequence of filters to use to encode chunk data prior to - compression. - read_only : bool, optional - True if array should be protected against modification. - synchronizer : object, optional - Array synchronizer. - - Notes - ----- - WARNING: This is an experimental feature and should be used with care. - There are plenty of ways to generate errors and/or cause data - corruption. - - Examples - -------- - - Bypass filters: - - >>> import zarr - >>> import numpy as np - >>> np.random.seed(42) - >>> labels = ['female', 'male'] - >>> data = np.random.choice(labels, size=10000) - >>> filters = [zarr.v2.Categorize(labels=labels, - ... dtype=data.dtype, - ... astype='u1')] - >>> a = zarr.v2.array(data, chunks=1000, filters=filters) - >>> a[:] - array(['female', 'male', 'female', ..., 'male', 'male', 'female'], - dtype='>> v = a.view(dtype='u1', filters=[]) - >>> v.is_view - True - >>> v[:] - array([1, 2, 1, ..., 2, 2, 1], dtype=uint8) - - Views can be used to modify data: - - >>> x = v[:] - >>> x.sort() - >>> v[:] = x - >>> v[:] - array([1, 1, 1, ..., 2, 2, 2], dtype=uint8) - >>> a[:] - array(['female', 'female', 'female', ..., 'male', 'male', 'male'], - dtype='>> data = np.random.randint(0, 2, size=10000, dtype='u1') - >>> a = zarr.v2.array(data, chunks=1000) - >>> a[:] - array([0, 0, 1, ..., 1, 0, 0], dtype=uint8) - >>> v = a.view(dtype=bool) - >>> v[:] - array([False, False, True, ..., True, False, False]) - >>> np.all(a[:].view(dtype=bool) == v[:]) - True - - An array can be viewed with a dtype with a different item size, however - some care is needed to adjust the shape and chunk shape so that chunk - data is interpreted correctly: - - >>> data = np.arange(10000, dtype='u2') - >>> a = zarr.v2.array(data, chunks=1000) - >>> a[:10] - array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint16) - >>> v = a.view(dtype='u1', shape=20000, chunks=2000) - >>> v[:10] - array([0, 0, 1, 0, 2, 0, 3, 0, 4, 0], dtype=uint8) - >>> np.all(a[:].view('u1') == v[:]) - True - - Change fill value for uninitialized chunks: - - >>> a = zarr.v2.full(10000, chunks=1000, fill_value=-1, dtype='i1') - >>> a[:] - array([-1, -1, -1, ..., -1, -1, -1], dtype=int8) - >>> v = a.view(fill_value=42) - >>> v[:] - array([42, 42, 42, ..., 42, 42, 42], dtype=int8) - - Note that resizing or appending to views is not permitted: - - >>> a = zarr.v2.empty(10000) - >>> v = a.view() - >>> try: - ... v.resize(20000) - ... except PermissionError as e: - ... print(e) - operation not permitted for views - - """ - - store = self._store - chunk_store = self._chunk_store - path = self._path - if read_only is None: - read_only = self._read_only - if synchronizer is None: - synchronizer = self._synchronizer - a = Array( - store=store, - path=path, - chunk_store=chunk_store, - read_only=read_only, - synchronizer=synchronizer, - cache_metadata=True, - ) - a._is_view = True - - # allow override of some properties - if dtype is None: - dtype = self._dtype - else: - dtype = np.dtype(dtype) - a._dtype = dtype - if shape is None: - shape = self._shape - else: - shape = normalize_shape(shape) - a._shape = shape - if chunks is not None: - chunks = normalize_chunks(chunks, shape, dtype.itemsize) - a._chunks = chunks - if fill_value is not None: - a._fill_value = fill_value - if filters is not None: - a._filters = filters - - return a - - def astype(self, dtype): - """Returns a view that does on the fly type conversion of the underlying data. - - Parameters - ---------- - dtype : string or dtype - NumPy dtype. - - Notes - ----- - This method returns a new Array object which is a view on the same - underlying chunk data. Modifying any data via the view is currently - not permitted and will result in an error. This is an experimental - feature and its behavior is subject to change in the future. - - See Also - -------- - Array.view - - Examples - -------- - - >>> import zarr - >>> import numpy as np - >>> data = np.arange(100, dtype=np.uint8) - >>> a = zarr.v2.array(data, chunks=10) - >>> a[:] - array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, - 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, - 96, 97, 98, 99], dtype=uint8) - >>> v = a.astype(np.float32) - >>> v.is_view - True - >>> v[:] - array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., - 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., - 20., 21., 22., 23., 24., 25., 26., 27., 28., 29., - 30., 31., 32., 33., 34., 35., 36., 37., 38., 39., - 40., 41., 42., 43., 44., 45., 46., 47., 48., 49., - 50., 51., 52., 53., 54., 55., 56., 57., 58., 59., - 60., 61., 62., 63., 64., 65., 66., 67., 68., 69., - 70., 71., 72., 73., 74., 75., 76., 77., 78., 79., - 80., 81., 82., 83., 84., 85., 86., 87., 88., 89., - 90., 91., 92., 93., 94., 95., 96., 97., 98., 99.], - dtype=float32) - """ - - dtype = np.dtype(dtype) - - filters = [] - if self._filters: - filters.extend(self._filters) - filters.insert(0, AsType(encode_dtype=self._dtype, decode_dtype=dtype)) - - return self.view(filters=filters, dtype=dtype, read_only=True) diff --git a/src/zarr/v2/creation.py b/src/zarr/v2/creation.py deleted file mode 100644 index d0ba00603d..0000000000 --- a/src/zarr/v2/creation.py +++ /dev/null @@ -1,707 +0,0 @@ -from typing import Optional -from warnings import warn - -import numpy as np -from numcodecs.registry import codec_registry - -from zarr.v2.core import Array -from zarr.v2.errors import ( - ArrayNotFoundError, - ContainsArrayError, - ContainsGroupError, -) -from zarr.v2.storage import ( - contains_array, - contains_group, - default_compressor, - init_array, - normalize_storage_path, - normalize_store_arg, -) -from zarr.v2.util import normalize_dimension_separator - - -def create( - shape, - chunks=True, - dtype=None, - compressor="default", - fill_value: Optional[int] = 0, - order="C", - store=None, - synchronizer=None, - overwrite=False, - path=None, - chunk_store=None, - filters=None, - cache_metadata=True, - cache_attrs=True, - read_only=False, - object_codec=None, - dimension_separator=None, - write_empty_chunks=True, - *, - meta_array=None, - **kwargs, -): - """Create an array. - - Parameters - ---------- - shape : int or tuple of ints - Array shape. - chunks : int or tuple of ints, optional - Chunk shape. If True, will be guessed from `shape` and `dtype`. If - False, will be set to `shape`, i.e., single chunk for the whole array. - If an int, the chunk size in each dimension will be given by the value - of `chunks`. Default is True. - dtype : string or dtype, optional - NumPy dtype. - compressor : Codec, optional - Primary compressor. - fill_value : object - Default value to use for uninitialized portions of the array. - order : {'C', 'F'}, optional - Memory layout to be used within each chunk. - store : MutableMapping or string - Store or path to directory in file system or name of zip file. - synchronizer : object, optional - Array synchronizer. - overwrite : bool, optional - If True, delete all pre-existing data in `store` at `path` before - creating the array. - path : string, optional - Path under which array is stored. - chunk_store : MutableMapping, optional - Separate storage for chunks. If not provided, `store` will be used - for storage of both chunks and metadata. - filters : sequence of Codecs, optional - Sequence of filters to use to encode chunk data prior to compression. - cache_metadata : bool, optional - If True, array configuration metadata will be cached for the - lifetime of the object. If False, array metadata will be reloaded - prior to all data access and modification operations (may incur - overhead depending on storage and data access pattern). - cache_attrs : bool, optional - If True (default), user attributes will be cached for attribute read - operations. If False, user attributes are reloaded from the store prior - to all attribute read operations. - read_only : bool, optional - True if array should be protected against modification. - object_codec : Codec, optional - A codec to encode object arrays, only needed if dtype=object. - dimension_separator : {'.', '/'}, optional - Separator placed between the dimensions of a chunk. - - .. versionadded:: 2.8 - - write_empty_chunks : bool, optional - If True (default), all chunks will be stored regardless of their - contents. If False, each chunk is compared to the array's fill value - prior to storing. If a chunk is uniformly equal to the fill value, then - that chunk is not be stored, and the store entry for that chunk's key - is deleted. This setting enables sparser storage, as only chunks with - non-fill-value data are stored, at the expense of overhead associated - with checking the data of each chunk. - - .. versionadded:: 2.11 - - meta_array : array-like, optional - An array instance to use for determining arrays to create and return - to users. Use `numpy.empty(())` by default. - - .. versionadded:: 2.13 - - Returns - ------- - z : zarr.v2.core.Array - - Examples - -------- - - Create an array with default settings:: - - >>> import zarr - >>> z = zarr.v2.create((10000, 10000), chunks=(1000, 1000)) - >>> z - - - Create an array with different some different configuration options:: - - >>> from numcodecs import Blosc - >>> compressor = Blosc(cname='zstd', clevel=1, shuffle=Blosc.BITSHUFFLE) - >>> z = zarr.v2.create((10000, 10000), chunks=(1000, 1000), dtype='i1', order='F', - ... compressor=compressor) - >>> z - - - To create an array with object dtype requires a filter that can handle Python object - encoding, e.g., `MsgPack` or `Pickle` from `numcodecs`:: - - >>> from numcodecs import MsgPack - >>> z = zarr.v2.create((10000, 10000), chunks=(1000, 1000), dtype=object, - ... object_codec=MsgPack()) - >>> z - - - Example with some filters, and also storing chunks separately from metadata:: - - >>> from numcodecs import Quantize, Adler32 - >>> store, chunk_store = dict(), dict() - >>> z = zarr.v2.create((10000, 10000), chunks=(1000, 1000), dtype='f8', - ... filters=[Quantize(digits=2, dtype='f8'), Adler32()], - ... store=store, chunk_store=chunk_store) - >>> z - - - """ - - # handle polymorphic store arg - store = normalize_store_arg(store, mode="w") - - # API compatibility with h5py - compressor, fill_value = _kwargs_compat(compressor, fill_value, kwargs) - - # optional array metadata - if dimension_separator is None: - dimension_separator = getattr(store, "_dimension_separator", None) - else: - store_separator = getattr(store, "_dimension_separator", None) - if store_separator not in (None, dimension_separator): - raise ValueError( - f"Specified dimension_separator: {dimension_separator}" - f"conflicts with store's separator: " - f"{store_separator}" - ) - dimension_separator = normalize_dimension_separator(dimension_separator) - - # initialize array metadata - init_array( - store, - shape=shape, - chunks=chunks, - dtype=dtype, - compressor=compressor, - fill_value=fill_value, - order=order, - overwrite=overwrite, - path=path, - chunk_store=chunk_store, - filters=filters, - object_codec=object_codec, - dimension_separator=dimension_separator, - ) - - # instantiate array - z = Array( - store, - path=path, - chunk_store=chunk_store, - synchronizer=synchronizer, - cache_metadata=cache_metadata, - cache_attrs=cache_attrs, - read_only=read_only, - write_empty_chunks=write_empty_chunks, - meta_array=meta_array, - ) - - return z - - -def _kwargs_compat(compressor, fill_value, kwargs): - # to be compatible with h5py, as well as backwards-compatible with Zarr - # 1.x, accept 'compression' and 'compression_opts' keyword arguments - - if compressor != "default": - # 'compressor' overrides 'compression' - if "compression" in kwargs: - warn( - "'compression' keyword argument overridden by 'compressor'", - stacklevel=3, - ) - del kwargs["compression"] - if "compression_opts" in kwargs: - warn( - "'compression_opts' keyword argument overridden by 'compressor'", - stacklevel=3, - ) - del kwargs["compression_opts"] - - elif "compression" in kwargs: - compression = kwargs.pop("compression") - compression_opts = kwargs.pop("compression_opts", None) - - if compression is None or compression == "none": - compressor = None - - elif compression == "default": - compressor = default_compressor - - elif isinstance(compression, str): - codec_cls = codec_registry[compression] - - # handle compression_opts - if isinstance(compression_opts, dict): - compressor = codec_cls(**compression_opts) - elif isinstance(compression_opts, (list, tuple)): - compressor = codec_cls(*compression_opts) - elif compression_opts is None: - compressor = codec_cls() - else: - # assume single argument, e.g., int - compressor = codec_cls(compression_opts) - - # be lenient here if user gives compressor as 'compression' - elif hasattr(compression, "get_config"): - compressor = compression - - else: - raise ValueError("bad value for compression: %r" % compression) - - # handle 'fillvalue' - if "fillvalue" in kwargs: - # to be compatible with h5py, accept 'fillvalue' instead of - # 'fill_value' - fill_value = kwargs.pop("fillvalue") - - # ignore other keyword arguments - for k in kwargs: - warn("ignoring keyword argument %r" % k) - - return compressor, fill_value - - -def empty(shape, **kwargs): - """Create an empty array. - - For parameter definitions see :func:`zarr.v2.creation.create`. - - Notes - ----- - The contents of an empty Zarr array are not defined. On attempting to - retrieve data from an empty Zarr array, any values may be returned, - and these are not guaranteed to be stable from one access to the next. - - """ - return create(shape=shape, fill_value=None, **kwargs) - - -def zeros(shape, **kwargs): - """Create an array, with zero being used as the default value for - uninitialized portions of the array. - - For parameter definitions see :func:`zarr.v2.creation.create`. - - Examples - -------- - >>> import zarr - >>> z = zarr.v2.zeros((10000, 10000), chunks=(1000, 1000)) - >>> z - - >>> z[:2, :2] - array([[0., 0.], - [0., 0.]]) - - """ - - return create(shape=shape, fill_value=0, **kwargs) - - -def ones(shape, **kwargs): - """Create an array, with one being used as the default value for - uninitialized portions of the array. - - For parameter definitions see :func:`zarr.v2.creation.create`. - - Examples - -------- - >>> import zarr - >>> z = zarr.v2.ones((10000, 10000), chunks=(1000, 1000)) - >>> z - - >>> z[:2, :2] - array([[1., 1.], - [1., 1.]]) - - """ - - return create(shape=shape, fill_value=1, **kwargs) - - -def full(shape, fill_value, **kwargs): - """Create an array, with `fill_value` being used as the default value for - uninitialized portions of the array. - - For parameter definitions see :func:`zarr.v2.creation.create`. - - Examples - -------- - >>> import zarr - >>> z = zarr.v2.full((10000, 10000), chunks=(1000, 1000), fill_value=42) - >>> z - - >>> z[:2, :2] - array([[42., 42.], - [42., 42.]]) - - """ - - return create(shape=shape, fill_value=fill_value, **kwargs) - - -def _get_shape_chunks(a): - shape = None - chunks = None - - if hasattr(a, "shape") and isinstance(a.shape, tuple): - shape = a.shape - - if hasattr(a, "chunks") and isinstance(a.chunks, tuple) and (len(a.chunks) == len(a.shape)): - chunks = a.chunks - - elif hasattr(a, "chunklen"): - # bcolz carray - chunks = (a.chunklen,) + a.shape[1:] - - return shape, chunks - - -def array(data, **kwargs): - """Create an array filled with `data`. - - The `data` argument should be a NumPy array or array-like object. For - other parameter definitions see :func:`zarr.v2.creation.create`. - - Examples - -------- - >>> import numpy as np - >>> import zarr - >>> a = np.arange(100000000).reshape(10000, 10000) - >>> z = zarr.v2.array(a, chunks=(1000, 1000)) - >>> z - - - """ - - # ensure data is array-like - if not hasattr(data, "shape") or not hasattr(data, "dtype"): - data = np.asanyarray(data) - - # setup dtype - kw_dtype = kwargs.get("dtype") - if kw_dtype is None: - kwargs["dtype"] = data.dtype - else: - kwargs["dtype"] = kw_dtype - - # setup shape and chunks - data_shape, data_chunks = _get_shape_chunks(data) - kwargs["shape"] = data_shape - kw_chunks = kwargs.get("chunks") - if kw_chunks is None: - kwargs["chunks"] = data_chunks - else: - kwargs["chunks"] = kw_chunks - - # pop read-only to apply after storing the data - read_only = kwargs.pop("read_only", False) - - # instantiate array - z = create(**kwargs) - - # fill with data - z[...] = data - - # set read_only property afterwards - z.read_only = read_only - - return z - - -def open_array( - store=None, - mode="a", - shape=None, - chunks=True, - dtype=None, - compressor="default", - fill_value=0, - order="C", - synchronizer=None, - filters=None, - cache_metadata=True, - cache_attrs=True, - path=None, - object_codec=None, - chunk_store=None, - storage_options=None, - partial_decompress=False, - write_empty_chunks=True, - *, - dimension_separator=None, - meta_array=None, - **kwargs, -): - """Open an array using file-mode-like semantics. - - Parameters - ---------- - store : MutableMapping or string, optional - Store or path to directory in file system or name of zip file. - mode : {'r', 'r+', 'a', 'w', 'w-'}, optional - Persistence mode: 'r' means read only (must exist); 'r+' means - read/write (must exist); 'a' means read/write (create if doesn't - exist); 'w' means create (overwrite if exists); 'w-' means create - (fail if exists). - shape : int or tuple of ints, optional - Array shape. - chunks : int or tuple of ints, optional - Chunk shape. If True, will be guessed from `shape` and `dtype`. If - False, will be set to `shape`, i.e., single chunk for the whole array. - If an int, the chunk size in each dimension will be given by the value - of `chunks`. Default is True. - dtype : string or dtype, optional - NumPy dtype. - compressor : Codec, optional - Primary compressor. - fill_value : object, optional - Default value to use for uninitialized portions of the array. - order : {'C', 'F'}, optional - Memory layout to be used within each chunk. - synchronizer : object, optional - Array synchronizer. - filters : sequence, optional - Sequence of filters to use to encode chunk data prior to compression. - cache_metadata : bool, optional - If True, array configuration metadata will be cached for the - lifetime of the object. If False, array metadata will be reloaded - prior to all data access and modification operations (may incur - overhead depending on storage and data access pattern). - cache_attrs : bool, optional - If True (default), user attributes will be cached for attribute read - operations. If False, user attributes are reloaded from the store prior - to all attribute read operations. - path : string, optional - Array path within store. - object_codec : Codec, optional - A codec to encode object arrays, only needed if dtype=object. - chunk_store : MutableMapping or string, optional - Store or path to directory in file system or name of zip file. - storage_options : dict - If using an fsspec URL to create the store, these will be passed to - the backend implementation. Ignored otherwise. - partial_decompress : bool, optional - If True and while the chunk_store is a FSStore and the compression used - is Blosc, when getting data from the array chunks will be partially - read and decompressed when possible. - write_empty_chunks : bool, optional - If True (default), all chunks will be stored regardless of their - contents. If False, each chunk is compared to the array's fill value - prior to storing. If a chunk is uniformly equal to the fill value, then - that chunk is not be stored, and the store entry for that chunk's key - is deleted. This setting enables sparser storage, as only chunks with - non-fill-value data are stored, at the expense of overhead associated - with checking the data of each chunk. - - .. versionadded:: 2.11 - - dimension_separator : {None, '.', '/'}, optional - Can be used to specify whether the array is in a flat ('.') or nested - ('/') format. If None, the appropriate value will be read from `store` - when present. Otherwise, defaults to '.'. - meta_array : array-like, optional - An array instance to use for determining arrays to create and return - to users. Use `numpy.empty(())` by default. - - .. versionadded:: 2.15 - - Returns - ------- - z : zarr.v2.core.Array - - Examples - -------- - >>> import numpy as np - >>> import zarr - >>> z1 = zarr.v2.open_array('data/example.zarr', mode='w', shape=(10000, 10000), - ... chunks=(1000, 1000), fill_value=0) - >>> z1[:] = np.arange(100000000).reshape(10000, 10000) - >>> z1 - - >>> z2 = zarr.v2.open_array('data/example.zarr', mode='r') - >>> z2 - - >>> np.all(z1[:] == z2[:]) - True - - Notes - ----- - There is no need to close an array. Data are automatically flushed to the - file system. - - """ - - # use same mode semantics as h5py - # r : read only, must exist - # r+ : read/write, must exist - # w : create, delete if exists - # w- or x : create, fail if exists - # a : read/write if exists, create otherwise (default) - - # handle polymorphic store arg - store = normalize_store_arg(store, storage_options=storage_options, mode=mode) - - if chunk_store is not None: - chunk_store = normalize_store_arg(chunk_store, storage_options=storage_options, mode=mode) - - # respect the dimension separator specified in a store, if present - if dimension_separator is None: - if hasattr(store, "_dimension_separator"): - dimension_separator = store._dimension_separator - else: - dimension_separator = "." - - path = normalize_storage_path(path) - - # API compatibility with h5py - compressor, fill_value = _kwargs_compat(compressor, fill_value, kwargs) - - # ensure fill_value of correct type - if fill_value is not None: - fill_value = np.array(fill_value, dtype=dtype)[()] - - # ensure store is initialized - - if mode in ["r", "r+"]: - if not contains_array(store, path=path): - if contains_group(store, path=path): - raise ContainsGroupError(path) - raise ArrayNotFoundError(path) - - elif mode == "w": - init_array( - store, - shape=shape, - chunks=chunks, - dtype=dtype, - compressor=compressor, - fill_value=fill_value, - order=order, - filters=filters, - overwrite=True, - path=path, - object_codec=object_codec, - chunk_store=chunk_store, - dimension_separator=dimension_separator, - ) - - elif mode == "a": - if not contains_array(store, path=path): - if contains_group(store, path=path): - raise ContainsGroupError(path) - init_array( - store, - shape=shape, - chunks=chunks, - dtype=dtype, - compressor=compressor, - fill_value=fill_value, - order=order, - filters=filters, - path=path, - object_codec=object_codec, - chunk_store=chunk_store, - dimension_separator=dimension_separator, - ) - - elif mode in ["w-", "x"]: - if contains_group(store, path=path): - raise ContainsGroupError(path) - elif contains_array(store, path=path): - raise ContainsArrayError(path) - else: - init_array( - store, - shape=shape, - chunks=chunks, - dtype=dtype, - compressor=compressor, - fill_value=fill_value, - order=order, - filters=filters, - path=path, - object_codec=object_codec, - chunk_store=chunk_store, - dimension_separator=dimension_separator, - ) - - # determine read only status - read_only = mode == "r" - - # instantiate array - z = Array( - store, - read_only=read_only, - synchronizer=synchronizer, - cache_metadata=cache_metadata, - cache_attrs=cache_attrs, - path=path, - chunk_store=chunk_store, - write_empty_chunks=write_empty_chunks, - meta_array=meta_array, - ) - - return z - - -def _like_args(a, kwargs): - shape, chunks = _get_shape_chunks(a) - if shape is not None: - kwargs.setdefault("shape", shape) - if chunks is not None: - kwargs.setdefault("chunks", chunks) - - if hasattr(a, "dtype"): - kwargs.setdefault("dtype", a.dtype) - - if isinstance(a, Array): - kwargs.setdefault("compressor", a.compressor) - kwargs.setdefault("order", a.order) - kwargs.setdefault("filters", a.filters) - else: - kwargs.setdefault("compressor", "default") - kwargs.setdefault("order", "C") - - -def empty_like(a, **kwargs): - """Create an empty array like `a`.""" - _like_args(a, kwargs) - return empty(**kwargs) - - -def zeros_like(a, **kwargs): - """Create an array of zeros like `a`.""" - _like_args(a, kwargs) - return zeros(**kwargs) - - -def ones_like(a, **kwargs): - """Create an array of ones like `a`.""" - _like_args(a, kwargs) - return ones(**kwargs) - - -def full_like(a, **kwargs): - """Create a filled array like `a`.""" - _like_args(a, kwargs) - if isinstance(a, Array): - kwargs.setdefault("fill_value", a.fill_value) - return full(**kwargs) - - -def open_like(a, path, **kwargs): - """Open a persistent array like `a`.""" - _like_args(a, kwargs) - if isinstance(a, Array): - kwargs.setdefault("fill_value", a.fill_value) - return open_array(path, **kwargs) diff --git a/src/zarr/v2/errors.py b/src/zarr/v2/errors.py deleted file mode 100644 index 30c9b13d39..0000000000 --- a/src/zarr/v2/errors.py +++ /dev/null @@ -1,80 +0,0 @@ -class MetadataError(Exception): - pass - - -class CopyError(RuntimeError): - pass - - -class _BaseZarrError(ValueError): - _msg = "" - - def __init__(self, *args): - super().__init__(self._msg.format(*args)) - - -class ArrayIndexError(IndexError): - pass - - -class _BaseZarrIndexError(IndexError): - _msg = "" - - def __init__(self, *args): - super().__init__(self._msg.format(*args)) - - -class ContainsGroupError(_BaseZarrError): - _msg = "path {0!r} contains a group" - - -class ContainsArrayError(_BaseZarrError): - _msg = "path {0!r} contains an array" - - -class ArrayNotFoundError(_BaseZarrError): - _msg = "array not found at path %r' {0!r}" - - -class GroupNotFoundError(_BaseZarrError): - _msg = "group not found at path {0!r}" - - -class PathNotFoundError(_BaseZarrError): - _msg = "nothing found at path {0!r}" - - -class BadCompressorError(_BaseZarrError): - _msg = "bad compressor; expected Codec object, found {0!r}" - - -class FSPathExistNotDir(GroupNotFoundError): - _msg = "path exists but is not a directory: %r" - - -class ReadOnlyError(PermissionError): - def __init__(self): - super().__init__("object is read-only") - - -class BoundsCheckError(_BaseZarrIndexError): - _msg = "index out of bounds for dimension with length {0}" - - -class NegativeStepError(IndexError): - def __init__(self): - super().__init__("only slices with step >= 1 are supported") - - -def err_too_many_indices(selection, shape): - raise IndexError( - "too many indices for array; expected {}, got {}".format(len(shape), len(selection)) - ) - - -class VindexInvalidSelectionError(_BaseZarrIndexError): - _msg = ( - "unsupported selection type for vectorized indexing; only " - "coordinate selection (tuple of integer arrays) and mask selection " - "(single Boolean array) are supported; got {0!r}" - ) diff --git a/src/zarr/v2/hierarchy.py b/src/zarr/v2/hierarchy.py deleted file mode 100644 index 25e47311b6..0000000000 --- a/src/zarr/v2/hierarchy.py +++ /dev/null @@ -1,1401 +0,0 @@ -from collections.abc import MutableMapping -from itertools import islice -from typing import Any - -import numpy as np - -from zarr.v2.attrs import Attributes -from zarr.v2.core import Array -from zarr.v2.creation import ( - array, - create, - empty, - empty_like, - full, - full_like, - ones, - ones_like, - zeros, - zeros_like, -) -from zarr.v2.errors import ( - ContainsArrayError, - ContainsGroupError, - GroupNotFoundError, - ReadOnlyError, -) -from zarr.v2.storage import ( - _prefix_to_group_key, - BaseStore, - MemoryStore, - group_meta_key, - attrs_key, - contains_array, - contains_group, - init_group, - listdir, - normalize_store_arg, - rename, - rmdir, -) - -from zarr.v2.util import ( - InfoReporter, - TreeViewer, - is_valid_python_name, - nolock, - normalize_shape, - normalize_storage_path, -) - - -class Group(MutableMapping[str, Any]): - """Instantiate a group from an initialized store. - - Parameters - ---------- - store : MutableMapping - Group store, already initialized. - If the Group is used in a context manager, and the store has a ``close`` method, - it will be called on exit. - path : string, optional - Group path. - read_only : bool, optional - True if group should be protected against modification. - chunk_store : MutableMapping, optional - Separate storage for chunks. If not provided, `store` will be used - for storage of both chunks and metadata. - cache_attrs : bool, optional - If True (default), user attributes will be cached for attribute read - operations. If False, user attributes are reloaded from the store prior - to all attribute read operations. - synchronizer : object, optional - Array synchronizer. - - meta_array : array-like, optional - An array instance to use for determining arrays to create and return - to users. Use `numpy.empty(())` by default. - - .. versionadded:: 2.13 - - Attributes - ---------- - store - path - name - read_only - chunk_store - synchronizer - attrs - info - meta_array - - Methods - ------- - __len__ - __iter__ - __contains__ - __getitem__ - __enter__ - __exit__ - group_keys - groups - array_keys - arrays - visit - visitkeys - visitvalues - visititems - tree - create_group - require_group - create_groups - require_groups - create_dataset - require_dataset - create - empty - zeros - ones - full - array - empty_like - zeros_like - ones_like - full_like - info - move - - """ - - def __init__( - self, - store, - path=None, - read_only=False, - chunk_store=None, - cache_attrs=True, - synchronizer=None, - *, - meta_array=None, - ): - store: BaseStore = _normalize_store_arg(store) - if chunk_store is not None: - chunk_store: BaseStore = _normalize_store_arg(chunk_store) - self._store = store - self._chunk_store = chunk_store - self._path = normalize_storage_path(path) - if self._path: - self._key_prefix = self._path + "/" - else: - self._key_prefix = "" - self._read_only = read_only - self._synchronizer = synchronizer - if meta_array is not None: - self._meta_array = np.empty_like(meta_array, shape=()) - else: - self._meta_array = np.empty(()) - - # guard conditions - if contains_array(store, path=self._path): - raise ContainsArrayError(path) - - # initialize metadata - mkey = None - try: - mkey = _prefix_to_group_key(self._store, self._key_prefix) - assert not mkey.endswith("root/.group") - meta_bytes = store[mkey] - except KeyError: - raise GroupNotFoundError(path) - else: - self._meta = self._store._metadata_class.decode_group_metadata(meta_bytes) - - # setup attributes - akey = self._key_prefix + attrs_key - - self._attrs = Attributes( - store, key=akey, read_only=read_only, cache=cache_attrs, synchronizer=synchronizer - ) - - # setup info - self._info = InfoReporter(self) - - @property - def store(self): - """A MutableMapping providing the underlying storage for the group.""" - return self._store - - @property - def path(self): - """Storage path.""" - return self._path - - @property - def name(self): - """Group name following h5py convention.""" - if self._path: - # follow h5py convention: add leading slash - name = self._path - if name[0] != "/": - name = "/" + name - return name - return "/" - - @property - def basename(self): - """Final component of name.""" - return self.name.split("/")[-1] - - @property - def read_only(self): - """A boolean, True if modification operations are not permitted.""" - return self._read_only - - @property - def chunk_store(self): - """A MutableMapping providing the underlying storage for array chunks.""" - if self._chunk_store is None: - return self._store - else: - return self._chunk_store - - @property - def synchronizer(self): - """Object used to synchronize write access to groups and arrays.""" - return self._synchronizer - - @property - def attrs(self): - """A MutableMapping containing user-defined attributes. Note that - attribute values must be JSON serializable.""" - return self._attrs - - @property - def info(self): - """Return diagnostic information about the group.""" - return self._info - - @property - def meta_array(self): - """An array-like instance to use for determining arrays to create and return - to users. - """ - return self._meta_array - - def __eq__(self, other): - return ( - isinstance(other, Group) - and self._store == other.store - and self._read_only == other.read_only - and self._path == other.path - # N.B., no need to compare attributes, should be covered by - # store comparison - ) - - def __iter__(self): - """Return an iterator over group member names. - - Examples - -------- - >>> import zarr - >>> g1 = zarr.v2.group() - >>> g2 = g1.create_group('foo') - >>> g3 = g1.create_group('bar') - >>> d1 = g1.create_dataset('baz', shape=100, chunks=10) - >>> d2 = g1.create_dataset('quux', shape=200, chunks=20) - >>> for name in g1: - ... print(name) - bar - baz - foo - quux - - """ - - for key in sorted(listdir(self._store, self._path)): - path = self._key_prefix + key - if contains_array(self._store, path) or contains_group(self._store, path): - yield key - - def __len__(self): - """Number of members.""" - return sum(1 for _ in self) - - def __repr__(self): - t = type(self) - r = "<{}.{}".format(t.__module__, t.__name__) - if self.name: - r += " %r" % self.name - if self._read_only: - r += " read-only" - r += ">" - return r - - def __enter__(self): - """Return the Group for use as a context manager.""" - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - """Call the close method of the underlying Store.""" - self.store.close() - - def info_items(self): - def typestr(o): - return "{}.{}".format(type(o).__module__, type(o).__name__) - - items = [] - - # basic info - if self.name is not None: - items += [("Name", self.name)] - items += [ - ("Type", typestr(self)), - ("Read-only", str(self.read_only)), - ] - - # synchronizer - if self._synchronizer is not None: - items += [("Synchronizer type", typestr(self._synchronizer))] - - # storage info - items += [("Store type", typestr(self._store))] - if self._chunk_store is not None: - items += [("Chunk store type", typestr(self._chunk_store))] - - # members - items += [("No. members", len(self))] - array_keys = sorted(self.array_keys()) - group_keys = sorted(self.group_keys()) - items += [("No. arrays", len(array_keys))] - items += [("No. groups", len(group_keys))] - if array_keys: - items += [("Arrays", ", ".join(array_keys))] - if group_keys: - items += [("Groups", ", ".join(group_keys))] - - return items - - def __getstate__(self): - return { - "store": self._store, - "path": self._path, - "read_only": self._read_only, - "chunk_store": self._chunk_store, - "cache_attrs": self._attrs.cache, - "synchronizer": self._synchronizer, - "meta_array": self._meta_array, - } - - def __setstate__(self, state): - self.__init__(**state) - - def _item_path(self, item): - absolute = isinstance(item, str) and item and item[0] == "/" - path = normalize_storage_path(item) - if not absolute and self._path: - path = self._key_prefix + path - return path - - def __contains__(self, item): - """Test for group membership. - - Examples - -------- - >>> import zarr - >>> g1 = zarr.v2.group() - >>> g2 = g1.create_group('foo') - >>> d1 = g1.create_dataset('bar', shape=100, chunks=10) - >>> 'foo' in g1 - True - >>> 'bar' in g1 - True - >>> 'baz' in g1 - False - - """ - path = self._item_path(item) - return contains_array(self._store, path) or contains_group( - self._store, path, explicit_only=False - ) - - def __getitem__(self, item): - """Obtain a group member. - - Parameters - ---------- - item : string - Member name or path. - - Examples - -------- - >>> import zarr - >>> g1 = zarr.v2.group() - >>> d1 = g1.create_dataset('foo/bar/baz', shape=100, chunks=10) - >>> g1['foo'] - - >>> g1['foo/bar'] - - >>> g1['foo/bar/baz'] - - - """ - path = self._item_path(item) - if contains_array(self._store, path): - return Array( - self._store, - read_only=self._read_only, - path=path, - chunk_store=self._chunk_store, - synchronizer=self._synchronizer, - cache_attrs=self.attrs.cache, - meta_array=self._meta_array, - ) - elif contains_group(self._store, path, explicit_only=True): - return Group( - self._store, - read_only=self._read_only, - path=path, - chunk_store=self._chunk_store, - cache_attrs=self.attrs.cache, - synchronizer=self._synchronizer, - meta_array=self._meta_array, - ) - else: - raise KeyError(item) - - def __setitem__(self, item, value): - self.array(item, value, overwrite=True) - - def __delitem__(self, item): - return self._write_op(self._delitem_nosync, item) - - def _delitem_nosync(self, item): - path = self._item_path(item) - if contains_array(self._store, path) or contains_group( - self._store, path, explicit_only=False - ): - rmdir(self._store, path) - else: - raise KeyError(item) - - def __getattr__(self, item): - # allow access to group members via dot notation - try: - return self.__getitem__(item) - except KeyError: - raise AttributeError - - def __dir__(self): - # noinspection PyUnresolvedReferences - base = super().__dir__() - keys = sorted(set(base + list(self))) - keys = [k for k in keys if is_valid_python_name(k)] - return keys - - def _ipython_key_completions_(self): - return sorted(self) - - def group_keys(self): - """Return an iterator over member names for groups only. - - Examples - -------- - >>> import zarr - >>> g1 = zarr.v2.group() - >>> g2 = g1.create_group('foo') - >>> g3 = g1.create_group('bar') - >>> d1 = g1.create_dataset('baz', shape=100, chunks=10) - >>> d2 = g1.create_dataset('quux', shape=200, chunks=20) - >>> sorted(g1.group_keys()) - ['bar', 'foo'] - - """ - - for key in sorted(listdir(self._store, self._path)): - path = self._key_prefix + key - if contains_group(self._store, path): - yield key - - def groups(self): - """Return an iterator over (name, value) pairs for groups only. - - Examples - -------- - >>> import zarr - >>> g1 = zarr.v2.group() - >>> g2 = g1.create_group('foo') - >>> g3 = g1.create_group('bar') - >>> d1 = g1.create_dataset('baz', shape=100, chunks=10) - >>> d2 = g1.create_dataset('quux', shape=200, chunks=20) - >>> for n, v in g1.groups(): - ... print(n, type(v)) - bar - foo - - """ - - for key in sorted(listdir(self._store, self._path)): - path = self._key_prefix + key - if contains_group(self._store, path, explicit_only=False): - yield ( - key, - Group( - self._store, - path=path, - read_only=self._read_only, - chunk_store=self._chunk_store, - cache_attrs=self.attrs.cache, - synchronizer=self._synchronizer, - ), - ) - - def array_keys(self, recurse=False): - """Return an iterator over member names for arrays only. - - Parameters - ---------- - recurse : recurse, optional - Option to return member names for all arrays, even from groups - below the current one. If False, only member names for arrays in - the current group will be returned. Default value is False. - - Examples - -------- - >>> import zarr - >>> g1 = zarr.v2.group() - >>> g2 = g1.create_group('foo') - >>> g3 = g1.create_group('bar') - >>> d1 = g1.create_dataset('baz', shape=100, chunks=10) - >>> d2 = g1.create_dataset('quux', shape=200, chunks=20) - >>> sorted(g1.array_keys()) - ['baz', 'quux'] - - """ - return self._array_iter(keys_only=True, method="array_keys", recurse=recurse) - - def arrays(self, recurse=False): - """Return an iterator over (name, value) pairs for arrays only. - - Parameters - ---------- - recurse : recurse, optional - Option to return (name, value) pairs for all arrays, even from groups - below the current one. If False, only (name, value) pairs for arrays in - the current group will be returned. Default value is False. - - Examples - -------- - >>> import zarr - >>> g1 = zarr.v2.group() - >>> g2 = g1.create_group('foo') - >>> g3 = g1.create_group('bar') - >>> d1 = g1.create_dataset('baz', shape=100, chunks=10) - >>> d2 = g1.create_dataset('quux', shape=200, chunks=20) - >>> for n, v in g1.arrays(): - ... print(n, type(v)) - baz - quux - - """ - return self._array_iter(keys_only=False, method="arrays", recurse=recurse) - - def _array_iter(self, keys_only, method, recurse): - for key in sorted(listdir(self._store, self._path)): - path = self._key_prefix + key - if contains_array(self._store, path): - _key = key.rstrip("/") - yield _key if keys_only else (_key, self[key]) - elif recurse and contains_group(self._store, path): - group = self[key] - yield from getattr(group, method)(recurse=recurse) - - def visitvalues(self, func): - """Run ``func`` on each object. - - Note: If ``func`` returns ``None`` (or doesn't return), - iteration continues. However, if ``func`` returns - anything else, it ceases and returns that value. - - Examples - -------- - >>> import zarr - >>> g1 = zarr.v2.group() - >>> g2 = g1.create_group('foo') - >>> g3 = g1.create_group('bar') - >>> g4 = g3.create_group('baz') - >>> g5 = g3.create_group('quux') - >>> def print_visitor(obj): - ... print(obj) - >>> g1.visitvalues(print_visitor) - - - - - >>> g3.visitvalues(print_visitor) - - - - """ - - def _visit(obj): - yield obj - keys = sorted(getattr(obj, "keys", lambda: [])()) - for k in keys: - yield from _visit(obj[k]) - - for each_obj in islice(_visit(self), 1, None): - value = func(each_obj) - if value is not None: - return value - - def visit(self, func): - """Run ``func`` on each object's path. - - Note: If ``func`` returns ``None`` (or doesn't return), - iteration continues. However, if ``func`` returns - anything else, it ceases and returns that value. - - Examples - -------- - >>> import zarr - >>> g1 = zarr.v2.group() - >>> g2 = g1.create_group('foo') - >>> g3 = g1.create_group('bar') - >>> g4 = g3.create_group('baz') - >>> g5 = g3.create_group('quux') - >>> def print_visitor(name): - ... print(name) - >>> g1.visit(print_visitor) - bar - bar/baz - bar/quux - foo - >>> g3.visit(print_visitor) - baz - quux - - Search for members matching some name query can be implemented using - ``visit`` that is, ``find`` and ``findall``. Consider the following - tree:: - - / - β”œβ”€β”€ aaa - β”‚ └── bbb - β”‚ └── ccc - β”‚ └── aaa - β”œβ”€β”€ bar - └── foo - - It is created as follows: - - >>> root = zarr.v2.group() - >>> foo = root.create_group("foo") - >>> bar = root.create_group("bar") - >>> root.create_group("aaa").create_group("bbb").create_group("ccc").create_group("aaa") - - - For ``find``, the first path that matches a given pattern (for example - "aaa") is returned. Note that a non-None value is returned in the visit - function to stop further iteration. - - >>> import re - >>> pattern = re.compile("aaa") - >>> found = None - >>> def find(path): - ... global found - ... if pattern.search(path) is not None: - ... found = path - ... return True - ... - >>> root.visit(find) - True - >>> print(found) - aaa - - For ``findall``, all the results are gathered into a list - - >>> pattern = re.compile("aaa") - >>> found = [] - >>> def findall(path): - ... if pattern.search(path) is not None: - ... found.append(path) - ... - >>> root.visit(findall) - >>> print(found) - ['aaa', 'aaa/bbb', 'aaa/bbb/ccc', 'aaa/bbb/ccc/aaa'] - - To match only on the last part of the path, use a greedy regex to filter - out the prefix: - - >>> prefix_pattern = re.compile(r".*/") - >>> pattern = re.compile("aaa") - >>> found = [] - >>> def findall(path): - ... match = prefix_pattern.match(path) - ... if match is None: - ... name = path - ... else: - ... _, end = match.span() - ... name = path[end:] - ... if pattern.search(name) is not None: - ... found.append(path) - ... return None - ... - >>> root.visit(findall) - >>> print(found) - ['aaa', 'aaa/bbb/ccc/aaa'] - """ - - base_len = len(self.name) - return self.visitvalues(lambda o: func(o.name[base_len:].lstrip("/"))) - - def visitkeys(self, func): - """An alias for :py:meth:`~Group.visit`.""" - - return self.visit(func) - - def visititems(self, func): - """Run ``func`` on each object's path and the object itself. - - Note: If ``func`` returns ``None`` (or doesn't return), - iteration continues. However, if ``func`` returns - anything else, it ceases and returns that value. - - Examples - -------- - >>> import zarr - >>> g1 = zarr.v2.group() - >>> g2 = g1.create_group('foo') - >>> g3 = g1.create_group('bar') - >>> g4 = g3.create_group('baz') - >>> g5 = g3.create_group('quux') - >>> def print_visitor(name, obj): - ... print((name, obj)) - >>> g1.visititems(print_visitor) - ('bar', ) - ('bar/baz', ) - ('bar/quux', ) - ('foo', ) - >>> g3.visititems(print_visitor) - ('baz', ) - ('quux', ) - - """ - - base_len = len(self.name) - return self.visitvalues(lambda o: func(o.name[base_len:].lstrip("/"), o)) - - def tree(self, expand=False, level=None): - """Provide a ``print``-able display of the hierarchy. - - Parameters - ---------- - expand : bool, optional - Only relevant for HTML representation. If True, tree will be fully expanded. - level : int, optional - Maximum depth to descend into hierarchy. - - Examples - -------- - >>> import zarr - >>> g1 = zarr.v2.group() - >>> g2 = g1.create_group('foo') - >>> g3 = g1.create_group('bar') - >>> g4 = g3.create_group('baz') - >>> g5 = g3.create_group('quux') - >>> d1 = g5.create_dataset('baz', shape=100, chunks=10) - >>> g1.tree() - / - β”œβ”€β”€ bar - β”‚ β”œβ”€β”€ baz - β”‚ └── quux - β”‚ └── baz (100,) float64 - └── foo - >>> g1.tree(level=2) - / - β”œβ”€β”€ bar - β”‚ β”œβ”€β”€ baz - β”‚ └── quux - └── foo - >>> g3.tree() - bar - β”œβ”€β”€ baz - └── quux - └── baz (100,) float64 - - Notes - ----- - Please note that this is an experimental feature. The behaviour of this - function is still evolving and the default output and/or parameters may change - in future versions. - - """ - - return TreeViewer(self, expand=expand, level=level) - - def _write_op(self, f, *args, **kwargs): - # guard condition - if self._read_only: - raise ReadOnlyError - - if self._synchronizer is None: - # no synchronization - lock = nolock - else: - # synchronize on the root group - lock = self._synchronizer[group_meta_key] - - with lock: - return f(*args, **kwargs) - - def create_group(self, name, overwrite=False): - """Create a sub-group. - - Parameters - ---------- - name : string - Group name. - overwrite : bool, optional - If True, overwrite any existing array with the given name. - - Returns - ------- - g : zarr.v2.hierarchy.Group - - Examples - -------- - >>> import zarr - >>> g1 = zarr.v2.group() - >>> g2 = g1.create_group('foo') - >>> g3 = g1.create_group('bar') - >>> g4 = g1.create_group('baz/quux') - - """ - - return self._write_op(self._create_group_nosync, name, overwrite=overwrite) - - def _create_group_nosync(self, name, overwrite=False): - path = self._item_path(name) - - # create terminal group - init_group(self._store, path=path, chunk_store=self._chunk_store, overwrite=overwrite) - - return Group( - self._store, - path=path, - read_only=self._read_only, - chunk_store=self._chunk_store, - cache_attrs=self.attrs.cache, - synchronizer=self._synchronizer, - ) - - def create_groups(self, *names, **kwargs): - """Convenience method to create multiple groups in a single call.""" - return tuple(self.create_group(name, **kwargs) for name in names) - - def require_group(self, name, overwrite=False): - """Obtain a sub-group, creating one if it doesn't exist. - - Parameters - ---------- - name : string - Group name. - overwrite : bool, optional - Overwrite any existing array with given `name` if present. - - Returns - ------- - g : zarr.v2.hierarchy.Group - - Examples - -------- - >>> import zarr - >>> g1 = zarr.v2.group() - >>> g2 = g1.require_group('foo') - >>> g3 = g1.require_group('foo') - >>> g2 == g3 - True - - """ - - return self._write_op(self._require_group_nosync, name, overwrite=overwrite) - - def _require_group_nosync(self, name, overwrite=False): - path = self._item_path(name) - - # create terminal group if necessary - if not contains_group(self._store, path): - init_group( - store=self._store, path=path, chunk_store=self._chunk_store, overwrite=overwrite - ) - - return Group( - self._store, - path=path, - read_only=self._read_only, - chunk_store=self._chunk_store, - cache_attrs=self.attrs.cache, - synchronizer=self._synchronizer, - ) - - def require_groups(self, *names): - """Convenience method to require multiple groups in a single call.""" - return tuple(self.require_group(name) for name in names) - - # noinspection PyIncorrectDocstring - def create_dataset(self, name, **kwargs): - """Create an array. - - Arrays are known as "datasets" in HDF5 terminology. For compatibility - with h5py, Zarr groups also implement the require_dataset() method. - - Parameters - ---------- - name : string - Array name. - data : array-like, optional - Initial data. - shape : int or tuple of ints - Array shape. - chunks : int or tuple of ints, optional - Chunk shape. If not provided, will be guessed from `shape` and - `dtype`. - dtype : string or dtype, optional - NumPy dtype. - compressor : Codec, optional - Primary compressor. - fill_value : object - Default value to use for uninitialized portions of the array. - order : {'C', 'F'}, optional - Memory layout to be used within each chunk. - synchronizer : zarr.v2.sync.ArraySynchronizer, optional - Array synchronizer. - filters : sequence of Codecs, optional - Sequence of filters to use to encode chunk data prior to - compression. - overwrite : bool, optional - If True, replace any existing array or group with the given name. - cache_metadata : bool, optional - If True, array configuration metadata will be cached for the - lifetime of the object. If False, array metadata will be reloaded - prior to all data access and modification operations (may incur - overhead depending on storage and data access pattern). - dimension_separator : {'.', '/'}, optional - Separator placed between the dimensions of a chunk. - - Returns - ------- - a : zarr.v2.core.Array - - Examples - -------- - >>> import zarr - >>> g1 = zarr.v2.group() - >>> d1 = g1.create_dataset('foo', shape=(10000, 10000), - ... chunks=(1000, 1000)) - >>> d1 - - >>> d2 = g1.create_dataset('bar/baz/qux', shape=(100, 100, 100), - ... chunks=(100, 10, 10)) - >>> d2 - - - """ - assert "mode" not in kwargs - - return self._write_op(self._create_dataset_nosync, name, **kwargs) - - def _create_dataset_nosync(self, name, data=None, **kwargs): - assert "mode" not in kwargs - path = self._item_path(name) - - # determine synchronizer - kwargs.setdefault("synchronizer", self._synchronizer) - kwargs.setdefault("cache_attrs", self.attrs.cache) - - # create array - if data is None: - a = create(store=self._store, path=path, chunk_store=self._chunk_store, **kwargs) - - else: - a = array(data, store=self._store, path=path, chunk_store=self._chunk_store, **kwargs) - - return a - - def require_dataset(self, name, shape, dtype=None, exact=False, **kwargs): - """Obtain an array, creating if it doesn't exist. - - Arrays are known as "datasets" in HDF5 terminology. For compatibility - with h5py, Zarr groups also implement the create_dataset() method. - - Other `kwargs` are as per :func:`zarr.v2.hierarchy.Group.create_dataset`. - - Parameters - ---------- - name : string - Array name. - shape : int or tuple of ints - Array shape. - dtype : string or dtype, optional - NumPy dtype. - exact : bool, optional - If True, require `dtype` to match exactly. If false, require - `dtype` can be cast from array dtype. - - """ - - return self._write_op( - self._require_dataset_nosync, name, shape=shape, dtype=dtype, exact=exact, **kwargs - ) - - def _require_dataset_nosync(self, name, shape, dtype=None, exact=False, **kwargs): - path = self._item_path(name) - - if contains_array(self._store, path): - # array already exists at path, validate that it is the right shape and type - - synchronizer = kwargs.get("synchronizer", self._synchronizer) - cache_metadata = kwargs.get("cache_metadata", True) - cache_attrs = kwargs.get("cache_attrs", self.attrs.cache) - a = Array( - self._store, - path=path, - read_only=self._read_only, - chunk_store=self._chunk_store, - synchronizer=synchronizer, - cache_metadata=cache_metadata, - cache_attrs=cache_attrs, - meta_array=self._meta_array, - ) - shape = normalize_shape(shape) - if shape != a.shape: - raise TypeError( - "shape do not match existing array; expected {}, got {}".format(a.shape, shape) - ) - dtype = np.dtype(dtype) - if exact: - if dtype != a.dtype: - raise TypeError( - "dtypes do not match exactly; expected {}, got {}".format(a.dtype, dtype) - ) - else: - if not np.can_cast(dtype, a.dtype): - raise TypeError("dtypes ({}, {}) cannot be safely cast".format(dtype, a.dtype)) - return a - - else: - return self._create_dataset_nosync(name, shape=shape, dtype=dtype, **kwargs) - - def create(self, name, **kwargs): - """Create an array. Keyword arguments as per - :func:`zarr.v2.creation.create`.""" - return self._write_op(self._create_nosync, name, **kwargs) - - def _create_nosync(self, name, **kwargs): - path = self._item_path(name) - kwargs.setdefault("synchronizer", self._synchronizer) - kwargs.setdefault("cache_attrs", self.attrs.cache) - return create(store=self._store, path=path, chunk_store=self._chunk_store, **kwargs) - - def empty(self, name, **kwargs): - """Create an array. Keyword arguments as per - :func:`zarr.v2.creation.empty`.""" - return self._write_op(self._empty_nosync, name, **kwargs) - - def _empty_nosync(self, name, **kwargs): - path = self._item_path(name) - kwargs.setdefault("synchronizer", self._synchronizer) - kwargs.setdefault("cache_attrs", self.attrs.cache) - return empty(store=self._store, path=path, chunk_store=self._chunk_store, **kwargs) - - def zeros(self, name, **kwargs): - """Create an array. Keyword arguments as per - :func:`zarr.v2.creation.zeros`.""" - return self._write_op(self._zeros_nosync, name, **kwargs) - - def _zeros_nosync(self, name, **kwargs): - path = self._item_path(name) - kwargs.setdefault("synchronizer", self._synchronizer) - kwargs.setdefault("cache_attrs", self.attrs.cache) - return zeros(store=self._store, path=path, chunk_store=self._chunk_store, **kwargs) - - def ones(self, name, **kwargs): - """Create an array. Keyword arguments as per - :func:`zarr.v2.creation.ones`.""" - return self._write_op(self._ones_nosync, name, **kwargs) - - def _ones_nosync(self, name, **kwargs): - path = self._item_path(name) - kwargs.setdefault("synchronizer", self._synchronizer) - kwargs.setdefault("cache_attrs", self.attrs.cache) - return ones(store=self._store, path=path, chunk_store=self._chunk_store, **kwargs) - - def full(self, name, fill_value, **kwargs): - """Create an array. Keyword arguments as per - :func:`zarr.v2.creation.full`.""" - return self._write_op(self._full_nosync, name, fill_value, **kwargs) - - def _full_nosync(self, name, fill_value, **kwargs): - path = self._item_path(name) - kwargs.setdefault("synchronizer", self._synchronizer) - kwargs.setdefault("cache_attrs", self.attrs.cache) - return full( - store=self._store, - path=path, - chunk_store=self._chunk_store, - fill_value=fill_value, - **kwargs, - ) - - def array(self, name, data, **kwargs): - """Create an array. Keyword arguments as per - :func:`zarr.v2.creation.array`.""" - return self._write_op(self._array_nosync, name, data, **kwargs) - - def _array_nosync(self, name, data, **kwargs): - path = self._item_path(name) - kwargs.setdefault("synchronizer", self._synchronizer) - kwargs.setdefault("cache_attrs", self.attrs.cache) - return array(data, store=self._store, path=path, chunk_store=self._chunk_store, **kwargs) - - def empty_like(self, name, data, **kwargs): - """Create an array. Keyword arguments as per - :func:`zarr.v2.creation.empty_like`.""" - return self._write_op(self._empty_like_nosync, name, data, **kwargs) - - def _empty_like_nosync(self, name, data, **kwargs): - path = self._item_path(name) - kwargs.setdefault("synchronizer", self._synchronizer) - kwargs.setdefault("cache_attrs", self.attrs.cache) - return empty_like( - data, store=self._store, path=path, chunk_store=self._chunk_store, **kwargs - ) - - def zeros_like(self, name, data, **kwargs): - """Create an array. Keyword arguments as per - :func:`zarr.v2.creation.zeros_like`.""" - return self._write_op(self._zeros_like_nosync, name, data, **kwargs) - - def _zeros_like_nosync(self, name, data, **kwargs): - path = self._item_path(name) - kwargs.setdefault("synchronizer", self._synchronizer) - kwargs.setdefault("cache_attrs", self.attrs.cache) - return zeros_like( - data, store=self._store, path=path, chunk_store=self._chunk_store, **kwargs - ) - - def ones_like(self, name, data, **kwargs): - """Create an array. Keyword arguments as per - :func:`zarr.v2.creation.ones_like`.""" - return self._write_op(self._ones_like_nosync, name, data, **kwargs) - - def _ones_like_nosync(self, name, data, **kwargs): - path = self._item_path(name) - kwargs.setdefault("synchronizer", self._synchronizer) - kwargs.setdefault("cache_attrs", self.attrs.cache) - return ones_like( - data, store=self._store, path=path, chunk_store=self._chunk_store, **kwargs - ) - - def full_like(self, name, data, **kwargs): - """Create an array. Keyword arguments as per - :func:`zarr.v2.creation.full_like`.""" - return self._write_op(self._full_like_nosync, name, data, **kwargs) - - def _full_like_nosync(self, name, data, **kwargs): - path = self._item_path(name) - kwargs.setdefault("synchronizer", self._synchronizer) - kwargs.setdefault("cache_attrs", self.attrs.cache) - return full_like( - data, store=self._store, path=path, chunk_store=self._chunk_store, **kwargs - ) - - def _move_nosync(self, path, new_path): - rename(self._store, path, new_path) - if self._chunk_store is not None: - rename(self._chunk_store, path, new_path) - - def move(self, source, dest): - """Move contents from one path to another relative to the Group. - - Parameters - ---------- - source : string - Name or path to a Zarr object to move. - dest : string - New name or path of the Zarr object. - """ - - source = self._item_path(source) - dest = self._item_path(dest) - - # Check that source exists. - if not ( - contains_array(self._store, source) - or contains_group(self._store, source, explicit_only=False) - ): - raise ValueError(f'The source, "{source}", does not exist.') - if contains_array(self._store, dest) or contains_group( - self._store, dest, explicit_only=False - ): - raise ValueError(f'The dest, "{dest}", already exists.') - - # Ensure groups needed for `dest` exist. - if "/" in dest: - self.require_group("/" + dest.rsplit("/", 1)[0]) - - self._write_op(self._move_nosync, source, dest) - - -def _normalize_store_arg(store, *, storage_options=None, mode="r"): - if store is None: - return MemoryStore() - return normalize_store_arg(store, storage_options=storage_options, mode=mode) - - -def group( - store=None, - overwrite=False, - chunk_store=None, - cache_attrs=True, - synchronizer=None, - path=None, - *, - meta_array=None, -): - """Create a group. - - Parameters - ---------- - store : MutableMapping or string, optional - Store or path to directory in file system. - overwrite : bool, optional - If True, delete any pre-existing data in `store` at `path` before - creating the group. - chunk_store : MutableMapping, optional - Separate storage for chunks. If not provided, `store` will be used - for storage of both chunks and metadata. - cache_attrs : bool, optional - If True (default), user attributes will be cached for attribute read - operations. If False, user attributes are reloaded from the store prior - to all attribute read operations. - synchronizer : object, optional - Array synchronizer. - path : string, optional - Group path within store. - meta_array : array-like, optional - An array instance to use for determining arrays to create and return - to users. Use `numpy.empty(())` by default. - - .. versionadded:: 2.16.1 - - Returns - ------- - g : zarr.v2.hierarchy.Group - - Examples - -------- - Create a group in memory:: - - >>> import zarr - >>> g = zarr.v2.group() - >>> g - - - Create a group with a different store:: - - >>> store = zarr.v2.DirectoryStore('data/example.zarr') - >>> g = zarr.v2.group(store=store, overwrite=True) - >>> g - - - """ - - # handle polymorphic store arg - store = _normalize_store_arg(store, mode="w") - - path = normalize_storage_path(path) - - requires_init = overwrite or not contains_group(store) - - if requires_init: - init_group(store, overwrite=overwrite, chunk_store=chunk_store, path=path) - - return Group( - store, - read_only=False, - chunk_store=chunk_store, - cache_attrs=cache_attrs, - synchronizer=synchronizer, - path=path, - meta_array=meta_array, - ) - - -def open_group( - store=None, - mode="a", - cache_attrs=True, - synchronizer=None, - path=None, - chunk_store=None, - storage_options=None, - *, - meta_array=None, -): - """Open a group using file-mode-like semantics. - - Parameters - ---------- - store : MutableMapping or string, optional - Store or path to directory in file system or name of zip file. - mode : {'r', 'r+', 'a', 'w', 'w-'}, optional - Persistence mode: 'r' means read only (must exist); 'r+' means - read/write (must exist); 'a' means read/write (create if doesn't - exist); 'w' means create (overwrite if exists); 'w-' means create - (fail if exists). - cache_attrs : bool, optional - If True (default), user attributes will be cached for attribute read - operations. If False, user attributes are reloaded from the store prior - to all attribute read operations. - synchronizer : object, optional - Array synchronizer. - path : string, optional - Group path within store. - chunk_store : MutableMapping or string, optional - Store or path to directory in file system or name of zip file. - storage_options : dict - If using an fsspec URL to create the store, these will be passed to - the backend implementation. Ignored otherwise. - meta_array : array-like, optional - An array instance to use for determining arrays to create and return - to users. Use `numpy.empty(())` by default. - - .. versionadded:: 2.13 - - Returns - ------- - g : zarr.v2.hierarchy.Group - - Examples - -------- - >>> import zarr - >>> root = zarr.v2.open_group('data/example.zarr', mode='w') - >>> foo = root.create_group('foo') - >>> bar = root.create_group('bar') - >>> root - - >>> root2 = zarr.v2.open_group('data/example.zarr', mode='a') - >>> root2 - - >>> root == root2 - True - - """ - - # handle polymorphic store arg - store = _normalize_store_arg(store, storage_options=storage_options, mode=mode) - - if chunk_store is not None: - chunk_store = _normalize_store_arg(chunk_store, storage_options=storage_options, mode=mode) - - path = normalize_storage_path(path) - - # ensure store is initialized - - if mode in ["r", "r+"]: - if not contains_group(store, path=path): - if contains_array(store, path=path): - raise ContainsArrayError(path) - raise GroupNotFoundError(path) - - elif mode == "w": - init_group(store, overwrite=True, path=path, chunk_store=chunk_store) - - elif mode == "a": - if not contains_group(store, path=path): - if contains_array(store, path=path): - raise ContainsArrayError(path) - init_group(store, path=path, chunk_store=chunk_store) - - elif mode in ["w-", "x"]: - if contains_array(store, path=path): - raise ContainsArrayError(path) - elif contains_group(store, path=path): - raise ContainsGroupError(path) - else: - init_group(store, path=path, chunk_store=chunk_store) - - # determine read only status - read_only = mode == "r" - - return Group( - store, - read_only=read_only, - cache_attrs=cache_attrs, - synchronizer=synchronizer, - path=path, - chunk_store=chunk_store, - meta_array=meta_array, - ) diff --git a/src/zarr/v2/indexing.py b/src/zarr/v2/indexing.py deleted file mode 100644 index bb2d9f1adb..0000000000 --- a/src/zarr/v2/indexing.py +++ /dev/null @@ -1,1074 +0,0 @@ -import collections -import itertools -import math -import numbers - -import numpy as np - - -from zarr.v2.errors import ( - ArrayIndexError, - NegativeStepError, - err_too_many_indices, - VindexInvalidSelectionError, - BoundsCheckError, -) - - -def is_integer(x): - """True if x is an integer (both pure Python or NumPy). - - Note that Python's bool is considered an integer too. - """ - return isinstance(x, numbers.Integral) - - -def is_integer_list(x): - """True if x is a list of integers. - - This function assumes ie *does not check* that all elements of the list - have the same type. Mixed type lists will result in other errors that will - bubble up anyway. - """ - return isinstance(x, list) and len(x) > 0 and is_integer(x[0]) - - -def is_integer_array(x, ndim=None): - t = not np.isscalar(x) and hasattr(x, "shape") and hasattr(x, "dtype") and x.dtype.kind in "ui" - if ndim is not None: - t = t and len(x.shape) == ndim - return t - - -def is_bool_array(x, ndim=None): - t = hasattr(x, "shape") and hasattr(x, "dtype") and x.dtype == bool - if ndim is not None: - t = t and len(x.shape) == ndim - return t - - -def is_scalar(value, dtype): - if np.isscalar(value): - return True - if isinstance(value, tuple) and dtype.names and len(value) == len(dtype.names): - return True - return False - - -def is_pure_fancy_indexing(selection, ndim): - """Check whether a selection contains only scalars or integer array-likes. - - Parameters - ---------- - selection : tuple, slice, or scalar - A valid selection value for indexing into arrays. - - Returns - ------- - is_pure : bool - True if the selection is a pure fancy indexing expression (ie not mixed - with boolean or slices). - """ - if ndim == 1: - if is_integer_list(selection) or is_integer_array(selection): - return True - # if not, we go through the normal path below, because a 1-tuple - # of integers is also allowed. - no_slicing = ( - isinstance(selection, tuple) - and len(selection) == ndim - and not (any(isinstance(elem, slice) or elem is Ellipsis for elem in selection)) - ) - return ( - no_slicing - and all( - is_integer(elem) or is_integer_list(elem) or is_integer_array(elem) - for elem in selection - ) - and any(is_integer_list(elem) or is_integer_array(elem) for elem in selection) - ) - - -def is_pure_orthogonal_indexing(selection, ndim): - if not ndim: - return False - - # Case 1: Selection is a single iterable of integers - if is_integer_list(selection) or is_integer_array(selection, ndim=1): - return True - - # Case two: selection contains either zero or one integer iterables. - # All other selection elements are slices or integers - return ( - isinstance(selection, tuple) - and len(selection) == ndim - and sum(is_integer_list(elem) or is_integer_array(elem) for elem in selection) <= 1 - and all( - is_integer_list(elem) or is_integer_array(elem) or isinstance(elem, (int, slice)) - for elem in selection - ) - ) - - -def normalize_integer_selection(dim_sel, dim_len): - # normalize type to int - dim_sel = int(dim_sel) - - # handle wraparound - if dim_sel < 0: - dim_sel = dim_len + dim_sel - - # handle out of bounds - if dim_sel >= dim_len or dim_sel < 0: - raise BoundsCheckError(dim_len) - - return dim_sel - - -ChunkDimProjection = collections.namedtuple( - "ChunkDimProjection", ("dim_chunk_ix", "dim_chunk_sel", "dim_out_sel") -) -"""A mapping from chunk to output array for a single dimension. - -Parameters ----------- -dim_chunk_ix - Index of chunk. -dim_chunk_sel - Selection of items from chunk array. -dim_out_sel - Selection of items in target (output) array. - -""" - - -class IntDimIndexer: - def __init__(self, dim_sel, dim_len, dim_chunk_len): - # normalize - dim_sel = normalize_integer_selection(dim_sel, dim_len) - - # store attributes - self.dim_sel = dim_sel - self.dim_len = dim_len - self.dim_chunk_len = dim_chunk_len - self.nitems = 1 - - def __iter__(self): - dim_chunk_ix = self.dim_sel // self.dim_chunk_len - dim_offset = dim_chunk_ix * self.dim_chunk_len - dim_chunk_sel = self.dim_sel - dim_offset - dim_out_sel = None - yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel) - - -def ceildiv(a, b): - return math.ceil(a / b) - - -class SliceDimIndexer: - def __init__(self, dim_sel, dim_len, dim_chunk_len): - # normalize - self.start, self.stop, self.step = dim_sel.indices(dim_len) - if self.step < 1: - raise NegativeStepError - - # store attributes - self.dim_len = dim_len - self.dim_chunk_len = dim_chunk_len - self.nitems = max(0, ceildiv((self.stop - self.start), self.step)) - self.nchunks = ceildiv(self.dim_len, self.dim_chunk_len) - - def __iter__(self): - # figure out the range of chunks we need to visit - dim_chunk_ix_from = self.start // self.dim_chunk_len - dim_chunk_ix_to = ceildiv(self.stop, self.dim_chunk_len) - - # iterate over chunks in range - for dim_chunk_ix in range(dim_chunk_ix_from, dim_chunk_ix_to): - # compute offsets for chunk within overall array - dim_offset = dim_chunk_ix * self.dim_chunk_len - dim_limit = min(self.dim_len, (dim_chunk_ix + 1) * self.dim_chunk_len) - - # determine chunk length, accounting for trailing chunk - dim_chunk_len = dim_limit - dim_offset - - if self.start < dim_offset: - # selection starts before current chunk - dim_chunk_sel_start = 0 - remainder = (dim_offset - self.start) % self.step - if remainder: - dim_chunk_sel_start += self.step - remainder - # compute number of previous items, provides offset into output array - dim_out_offset = ceildiv((dim_offset - self.start), self.step) - - else: - # selection starts within current chunk - dim_chunk_sel_start = self.start - dim_offset - dim_out_offset = 0 - - if self.stop > dim_limit: - # selection ends after current chunk - dim_chunk_sel_stop = dim_chunk_len - - else: - # selection ends within current chunk - dim_chunk_sel_stop = self.stop - dim_offset - - dim_chunk_sel = slice(dim_chunk_sel_start, dim_chunk_sel_stop, self.step) - dim_chunk_nitems = ceildiv((dim_chunk_sel_stop - dim_chunk_sel_start), self.step) - - # If there are no elements on the selection within this chunk, then skip - if dim_chunk_nitems == 0: - continue - - dim_out_sel = slice(dim_out_offset, dim_out_offset + dim_chunk_nitems) - - yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel) - - -def check_selection_length(selection, shape): - if len(selection) > len(shape): - err_too_many_indices(selection, shape) - - -def replace_ellipsis(selection, shape): - selection = ensure_tuple(selection) - - # count number of ellipsis present - n_ellipsis = sum(1 for i in selection if i is Ellipsis) - - if n_ellipsis > 1: - # more than 1 is an error - raise IndexError("an index can only have a single ellipsis ('...')") - - elif n_ellipsis == 1: - # locate the ellipsis, count how many items to left and right - n_items_l = selection.index(Ellipsis) # items to left of ellipsis - n_items_r = len(selection) - (n_items_l + 1) # items to right of ellipsis - n_items = len(selection) - 1 # all non-ellipsis items - - if n_items >= len(shape): - # ellipsis does nothing, just remove it - selection = tuple(i for i in selection if i != Ellipsis) - - else: - # replace ellipsis with as many slices are needed for number of dims - new_item = selection[:n_items_l] + ((slice(None),) * (len(shape) - n_items)) - if n_items_r: - new_item += selection[-n_items_r:] - selection = new_item - - # fill out selection if not completely specified - if len(selection) < len(shape): - selection += (slice(None),) * (len(shape) - len(selection)) - - # check selection not too long - check_selection_length(selection, shape) - - return selection - - -def replace_lists(selection): - return tuple( - np.asarray(dim_sel) if isinstance(dim_sel, list) else dim_sel for dim_sel in selection - ) - - -def ensure_tuple(v): - if not isinstance(v, tuple): - v = (v,) - return v - - -ChunkProjection = collections.namedtuple( - "ChunkProjection", ("chunk_coords", "chunk_selection", "out_selection") -) -"""A mapping of items from chunk to output array. Can be used to extract items from the -chunk array for loading into an output array. Can also be used to extract items from a -value array for setting/updating in a chunk array. - -Parameters ----------- -chunk_coords - Indices of chunk. -chunk_selection - Selection of items from chunk array. -out_selection - Selection of items in target (output) array. - -""" - - -def is_slice(s): - return isinstance(s, slice) - - -def is_contiguous_slice(s): - return is_slice(s) and (s.step is None or s.step == 1) - - -def is_positive_slice(s): - return is_slice(s) and (s.step is None or s.step >= 1) - - -def is_contiguous_selection(selection): - selection = ensure_tuple(selection) - return all((is_integer_array(s) or is_contiguous_slice(s) or s == Ellipsis) for s in selection) - - -def is_basic_selection(selection): - selection = ensure_tuple(selection) - return all(is_integer(s) or is_positive_slice(s) for s in selection) - - -# noinspection PyProtectedMember -class BasicIndexer: - def __init__(self, selection, array): - # handle ellipsis - selection = replace_ellipsis(selection, array._shape) - - # setup per-dimension indexers - dim_indexers = [] - for dim_sel, dim_len, dim_chunk_len in zip(selection, array._shape, array._chunks): - if is_integer(dim_sel): - dim_indexer = IntDimIndexer(dim_sel, dim_len, dim_chunk_len) - - elif is_slice(dim_sel): - dim_indexer = SliceDimIndexer(dim_sel, dim_len, dim_chunk_len) - - else: - raise IndexError( - "unsupported selection item for basic indexing; " - "expected integer or slice, got {!r}".format(type(dim_sel)) - ) - - dim_indexers.append(dim_indexer) - - self.dim_indexers = dim_indexers - self.shape = tuple(s.nitems for s in self.dim_indexers if not isinstance(s, IntDimIndexer)) - self.drop_axes = () - - def __iter__(self): - for dim_projections in itertools.product(*self.dim_indexers): - chunk_coords = tuple(p.dim_chunk_ix for p in dim_projections) - chunk_selection = tuple(p.dim_chunk_sel for p in dim_projections) - out_selection = tuple( - p.dim_out_sel for p in dim_projections if p.dim_out_sel is not None - ) - - yield ChunkProjection(chunk_coords, chunk_selection, out_selection) - - -class BoolArrayDimIndexer: - def __init__(self, dim_sel, dim_len, dim_chunk_len): - # check number of dimensions - if not is_bool_array(dim_sel, 1): - raise IndexError("Boolean arrays in an orthogonal selection must be 1-dimensional only") - - # check shape - if dim_sel.shape[0] != dim_len: - raise IndexError( - "Boolean array has the wrong length for dimension; expected {}, got {}".format( - dim_len, dim_sel.shape[0] - ) - ) - - # store attributes - self.dim_sel = dim_sel - self.dim_len = dim_len - self.dim_chunk_len = dim_chunk_len - self.nchunks = ceildiv(self.dim_len, self.dim_chunk_len) - - # precompute number of selected items for each chunk - self.chunk_nitems = np.zeros(self.nchunks, dtype="i8") - for dim_chunk_ix in range(self.nchunks): - dim_offset = dim_chunk_ix * self.dim_chunk_len - self.chunk_nitems[dim_chunk_ix] = np.count_nonzero( - self.dim_sel[dim_offset : dim_offset + self.dim_chunk_len] - ) - self.chunk_nitems_cumsum = np.cumsum(self.chunk_nitems) - self.nitems = self.chunk_nitems_cumsum[-1] - self.dim_chunk_ixs = np.nonzero(self.chunk_nitems)[0] - - def __iter__(self): - # iterate over chunks with at least one item - for dim_chunk_ix in self.dim_chunk_ixs: - # find region in chunk - dim_offset = dim_chunk_ix * self.dim_chunk_len - dim_chunk_sel = self.dim_sel[dim_offset : dim_offset + self.dim_chunk_len] - - # pad out if final chunk - if dim_chunk_sel.shape[0] < self.dim_chunk_len: - tmp = np.zeros(self.dim_chunk_len, dtype=bool) - tmp[: dim_chunk_sel.shape[0]] = dim_chunk_sel - dim_chunk_sel = tmp - - # find region in output - if dim_chunk_ix == 0: - start = 0 - else: - start = self.chunk_nitems_cumsum[dim_chunk_ix - 1] - stop = self.chunk_nitems_cumsum[dim_chunk_ix] - dim_out_sel = slice(start, stop) - - yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel) - - -class Order: - UNKNOWN = 0 - INCREASING = 1 - DECREASING = 2 - UNORDERED = 3 - - @staticmethod - def check(a): - diff = np.diff(a) - diff_positive = diff >= 0 - n_diff_positive = np.count_nonzero(diff_positive) - all_increasing = n_diff_positive == len(diff_positive) - any_increasing = n_diff_positive > 0 - if all_increasing: - order = Order.INCREASING - elif any_increasing: - order = Order.UNORDERED - else: - order = Order.DECREASING - return order - - -def wraparound_indices(x, dim_len): - loc_neg = x < 0 - if np.any(loc_neg): - x[loc_neg] = x[loc_neg] + dim_len - - -def boundscheck_indices(x, dim_len): - if np.any(x < 0) or np.any(x >= dim_len): - raise BoundsCheckError(dim_len) - - -class IntArrayDimIndexer: - """Integer array selection against a single dimension.""" - - def __init__( - self, - dim_sel, - dim_len, - dim_chunk_len, - wraparound=True, - boundscheck=True, - order=Order.UNKNOWN, - ): - # ensure 1d array - dim_sel = np.asanyarray(dim_sel) - if not is_integer_array(dim_sel, 1): - raise IndexError("integer arrays in an orthogonal selection must be 1-dimensional only") - - # handle wraparound - if wraparound: - wraparound_indices(dim_sel, dim_len) - - # handle out of bounds - if boundscheck: - boundscheck_indices(dim_sel, dim_len) - - # store attributes - self.dim_len = dim_len - self.dim_chunk_len = dim_chunk_len - self.nchunks = ceildiv(self.dim_len, self.dim_chunk_len) - self.nitems = len(dim_sel) - - # determine which chunk is needed for each selection item - # note: for dense integer selections, the division operation here is the - # bottleneck - dim_sel_chunk = dim_sel // dim_chunk_len - - # determine order of indices - if order == Order.UNKNOWN: - order = Order.check(dim_sel) - self.order = order - - if self.order == Order.INCREASING: - self.dim_sel = dim_sel - self.dim_out_sel = None - elif self.order == Order.DECREASING: - self.dim_sel = dim_sel[::-1] - # TODO should be possible to do this without creating an arange - self.dim_out_sel = np.arange(self.nitems - 1, -1, -1) - else: - # sort indices to group by chunk - self.dim_out_sel = np.argsort(dim_sel_chunk) - self.dim_sel = np.take(dim_sel, self.dim_out_sel) - - # precompute number of selected items for each chunk - self.chunk_nitems = np.bincount(dim_sel_chunk, minlength=self.nchunks) - - # find chunks that we need to visit - self.dim_chunk_ixs = np.nonzero(self.chunk_nitems)[0] - - # compute offsets into the output array - self.chunk_nitems_cumsum = np.cumsum(self.chunk_nitems) - - def __iter__(self): - for dim_chunk_ix in self.dim_chunk_ixs: - # find region in output - if dim_chunk_ix == 0: - start = 0 - else: - start = self.chunk_nitems_cumsum[dim_chunk_ix - 1] - stop = self.chunk_nitems_cumsum[dim_chunk_ix] - if self.order == Order.INCREASING: - dim_out_sel = slice(start, stop) - else: - dim_out_sel = self.dim_out_sel[start:stop] - - # find region in chunk - dim_offset = dim_chunk_ix * self.dim_chunk_len - dim_chunk_sel = self.dim_sel[start:stop] - dim_offset - - yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel) - - -def slice_to_range(s: slice, l: int): # noqa: E741 - return range(*s.indices(l)) - - -def ix_(selection, shape): - """Convert an orthogonal selection to a numpy advanced (fancy) selection, like numpy.ix_ - but with support for slices and single ints.""" - - # normalisation - selection = replace_ellipsis(selection, shape) - - # replace slice and int as these are not supported by numpy.ix_ - selection = [ - slice_to_range(dim_sel, dim_len) - if isinstance(dim_sel, slice) - else [dim_sel] - if is_integer(dim_sel) - else dim_sel - for dim_sel, dim_len in zip(selection, shape) - ] - - # now get numpy to convert to a coordinate selection - selection = np.ix_(*selection) - - return selection - - -def oindex(a, selection): - """Implementation of orthogonal indexing with slices and ints.""" - selection = replace_ellipsis(selection, a.shape) - drop_axes = tuple(i for i, s in enumerate(selection) if is_integer(s)) - selection = ix_(selection, a.shape) - result = a[selection] - if drop_axes: - result = result.squeeze(axis=drop_axes) - return result - - -def oindex_set(a, selection, value): - selection = replace_ellipsis(selection, a.shape) - drop_axes = tuple(i for i, s in enumerate(selection) if is_integer(s)) - selection = ix_(selection, a.shape) - if not np.isscalar(value) and drop_axes: - value = np.asanyarray(value) - value_selection = [slice(None)] * len(a.shape) - for i in drop_axes: - value_selection[i] = np.newaxis - value_selection = tuple(value_selection) - value = value[value_selection] - a[selection] = value - - -# noinspection PyProtectedMember -class OrthogonalIndexer: - def __init__(self, selection, array): - # handle ellipsis - selection = replace_ellipsis(selection, array._shape) - - # normalize list to array - selection = replace_lists(selection) - - # setup per-dimension indexers - dim_indexers = [] - for dim_sel, dim_len, dim_chunk_len in zip(selection, array._shape, array._chunks): - if is_integer(dim_sel): - dim_indexer = IntDimIndexer(dim_sel, dim_len, dim_chunk_len) - - elif isinstance(dim_sel, slice): - dim_indexer = SliceDimIndexer(dim_sel, dim_len, dim_chunk_len) - - elif is_integer_array(dim_sel): - dim_indexer = IntArrayDimIndexer(dim_sel, dim_len, dim_chunk_len) - - elif is_bool_array(dim_sel): - dim_indexer = BoolArrayDimIndexer(dim_sel, dim_len, dim_chunk_len) - - else: - raise IndexError( - "unsupported selection item for orthogonal indexing; " - "expected integer, slice, integer array or Boolean " - "array, got {!r}".format(type(dim_sel)) - ) - - dim_indexers.append(dim_indexer) - - self.array = array - self.dim_indexers = dim_indexers - self.shape = tuple(s.nitems for s in self.dim_indexers if not isinstance(s, IntDimIndexer)) - self.is_advanced = not is_basic_selection(selection) - if self.is_advanced: - self.drop_axes = tuple( - i - for i, dim_indexer in enumerate(self.dim_indexers) - if isinstance(dim_indexer, IntDimIndexer) - ) - else: - self.drop_axes = () - - def __iter__(self): - for dim_projections in itertools.product(*self.dim_indexers): - chunk_coords = tuple(p.dim_chunk_ix for p in dim_projections) - chunk_selection = tuple(p.dim_chunk_sel for p in dim_projections) - out_selection = tuple( - p.dim_out_sel for p in dim_projections if p.dim_out_sel is not None - ) - - # handle advanced indexing arrays orthogonally - if self.is_advanced: - # N.B., numpy doesn't support orthogonal indexing directly as yet, - # so need to work around via np.ix_. Also np.ix_ does not support a - # mixture of arrays and slices or integers, so need to convert slices - # and integers into ranges. - chunk_selection = ix_(chunk_selection, self.array._chunks) - - # special case for non-monotonic indices - if not is_basic_selection(out_selection): - out_selection = ix_(out_selection, self.shape) - - yield ChunkProjection(chunk_coords, chunk_selection, out_selection) - - -class OIndex: - def __init__(self, array): - self.array = array - - def __getitem__(self, selection): - fields, selection = pop_fields(selection) - selection = ensure_tuple(selection) - selection = replace_lists(selection) - return self.array.get_orthogonal_selection(selection, fields=fields) - - def __setitem__(self, selection, value): - fields, selection = pop_fields(selection) - selection = ensure_tuple(selection) - selection = replace_lists(selection) - return self.array.set_orthogonal_selection(selection, value, fields=fields) - - -# noinspection PyProtectedMember -class BlockIndexer: - def __init__(self, selection, array): - # handle ellipsis - selection = replace_ellipsis(selection, array._shape) - - # normalize list to array - selection = replace_lists(selection) - - # setup per-dimension indexers - dim_indexers = [] - for dim_sel, dim_len, dim_chunk_size in zip(selection, array._shape, array._chunks): - dim_numchunks = int(np.ceil(dim_len / dim_chunk_size)) - - if is_integer(dim_sel): - if dim_sel < 0: - dim_sel = dim_numchunks + dim_sel - - start = dim_sel * dim_chunk_size - stop = start + dim_chunk_size - slice_ = slice(start, stop) - - elif is_slice(dim_sel): - start = dim_sel.start if dim_sel.start is not None else 0 - stop = dim_sel.stop if dim_sel.stop is not None else dim_numchunks - - if dim_sel.step not in {1, None}: - raise IndexError( - "unsupported selection item for block indexing; " - "expected integer or slice with step=1, got {!r}".format(type(dim_sel)) - ) - - # Can't reuse wraparound_indices because it expects a numpy array - # We have integers here. - if start < 0: - start = dim_numchunks + start - if stop < 0: - stop = dim_numchunks + stop - - start = start * dim_chunk_size - stop = stop * dim_chunk_size - slice_ = slice(start, stop) - - else: - raise IndexError( - "unsupported selection item for block indexing; " - "expected integer or slice, got {!r}".format(type(dim_sel)) - ) - - dim_indexer = SliceDimIndexer(slice_, dim_len, dim_chunk_size) - dim_indexers.append(dim_indexer) - - if start >= dim_len or start < 0: - raise BoundsCheckError(dim_len) - - self.dim_indexers = dim_indexers - self.shape = tuple(s.nitems for s in self.dim_indexers) - self.drop_axes = () - - def __iter__(self): - for dim_projections in itertools.product(*self.dim_indexers): - chunk_coords = tuple(p.dim_chunk_ix for p in dim_projections) - chunk_selection = tuple(p.dim_chunk_sel for p in dim_projections) - out_selection = tuple( - p.dim_out_sel for p in dim_projections if p.dim_out_sel is not None - ) - - yield ChunkProjection(chunk_coords, chunk_selection, out_selection) - - -class BlockIndex: - def __init__(self, array): - self.array = array - - def __getitem__(self, selection): - fields, selection = pop_fields(selection) - selection = ensure_tuple(selection) - selection = replace_lists(selection) - return self.array.get_block_selection(selection, fields=fields) - - def __setitem__(self, selection, value): - fields, selection = pop_fields(selection) - selection = ensure_tuple(selection) - selection = replace_lists(selection) - return self.array.set_block_selection(selection, value, fields=fields) - - -# noinspection PyProtectedMember -def is_coordinate_selection(selection, array): - return (len(selection) == len(array._shape)) and all( - is_integer(dim_sel) or is_integer_array(dim_sel) for dim_sel in selection - ) - - -# noinspection PyProtectedMember -def is_mask_selection(selection, array): - return ( - len(selection) == 1 and is_bool_array(selection[0]) and selection[0].shape == array._shape - ) - - -# noinspection PyProtectedMember -class CoordinateIndexer: - def __init__(self, selection, array): - # some initial normalization - selection = ensure_tuple(selection) - selection = tuple([i] if is_integer(i) else i for i in selection) - selection = replace_lists(selection) - - # validation - if not is_coordinate_selection(selection, array): - raise IndexError( - "invalid coordinate selection; expected one integer " - "(coordinate) array per dimension of the target array, " - "got {!r}".format(selection) - ) - - # handle wraparound, boundscheck - for dim_sel, dim_len in zip(selection, array.shape): - # handle wraparound - wraparound_indices(dim_sel, dim_len) - - # handle out of bounds - boundscheck_indices(dim_sel, dim_len) - - # compute chunk index for each point in the selection - chunks_multi_index = tuple( - dim_sel // dim_chunk_len for (dim_sel, dim_chunk_len) in zip(selection, array._chunks) - ) - - # broadcast selection - this will raise error if array dimensions don't match - selection = np.broadcast_arrays(*selection) - chunks_multi_index = np.broadcast_arrays(*chunks_multi_index) - - # remember shape of selection, because we will flatten indices for processing - self.sel_shape = selection[0].shape if selection[0].shape else (1,) - - # flatten selection - selection = [dim_sel.reshape(-1) for dim_sel in selection] - chunks_multi_index = [dim_chunks.reshape(-1) for dim_chunks in chunks_multi_index] - - # ravel chunk indices - chunks_raveled_indices = np.ravel_multi_index(chunks_multi_index, dims=array._cdata_shape) - - # group points by chunk - if np.any(np.diff(chunks_raveled_indices) < 0): - # optimisation, only sort if needed - sel_sort = np.argsort(chunks_raveled_indices) - selection = tuple(dim_sel[sel_sort] for dim_sel in selection) - else: - sel_sort = None - - # store attributes - self.selection = selection - self.sel_sort = sel_sort - self.shape = selection[0].shape if selection[0].shape else (1,) - self.drop_axes = () - self.array = array - - # precompute number of selected items for each chunk - self.chunk_nitems = np.bincount(chunks_raveled_indices, minlength=array.nchunks) - self.chunk_nitems_cumsum = np.cumsum(self.chunk_nitems) - # locate the chunks we need to process - self.chunk_rixs = np.nonzero(self.chunk_nitems)[0] - - # unravel chunk indices - self.chunk_mixs = np.unravel_index(self.chunk_rixs, array._cdata_shape) - - def __iter__(self): - # iterate over chunks - for i, chunk_rix in enumerate(self.chunk_rixs): - chunk_coords = tuple(m[i] for m in self.chunk_mixs) - if chunk_rix == 0: - start = 0 - else: - start = self.chunk_nitems_cumsum[chunk_rix - 1] - stop = self.chunk_nitems_cumsum[chunk_rix] - if self.sel_sort is None: - out_selection = slice(start, stop) - else: - out_selection = self.sel_sort[start:stop] - - chunk_offsets = tuple( - dim_chunk_ix * dim_chunk_len - for dim_chunk_ix, dim_chunk_len in zip(chunk_coords, self.array._chunks) - ) - chunk_selection = tuple( - dim_sel[start:stop] - dim_chunk_offset - for (dim_sel, dim_chunk_offset) in zip(self.selection, chunk_offsets) - ) - - yield ChunkProjection(chunk_coords, chunk_selection, out_selection) - - -# noinspection PyProtectedMember -class MaskIndexer(CoordinateIndexer): - def __init__(self, selection, array): - # some initial normalization - selection = ensure_tuple(selection) - selection = replace_lists(selection) - - # validation - if not is_mask_selection(selection, array): - raise IndexError( - "invalid mask selection; expected one Boolean (mask)" - "array with the same shape as the target array, got {!r}".format(selection) - ) - - # convert to indices - selection = np.nonzero(selection[0]) - - # delegate the rest to superclass - super().__init__(selection, array) - - -class VIndex: - def __init__(self, array): - self.array = array - - def __getitem__(self, selection): - fields, selection = pop_fields(selection) - selection = ensure_tuple(selection) - selection = replace_lists(selection) - if is_coordinate_selection(selection, self.array): - return self.array.get_coordinate_selection(selection, fields=fields) - elif is_mask_selection(selection, self.array): - return self.array.get_mask_selection(selection, fields=fields) - else: - raise VindexInvalidSelectionError(selection) - - def __setitem__(self, selection, value): - fields, selection = pop_fields(selection) - selection = ensure_tuple(selection) - selection = replace_lists(selection) - if is_coordinate_selection(selection, self.array): - self.array.set_coordinate_selection(selection, value, fields=fields) - elif is_mask_selection(selection, self.array): - self.array.set_mask_selection(selection, value, fields=fields) - else: - raise VindexInvalidSelectionError(selection) - - -def check_fields(fields, dtype): - # early out - if fields is None: - return dtype - # check type - if not isinstance(fields, (str, list, tuple)): - raise IndexError( - "'fields' argument must be a string or list of strings; found {!r}".format(type(fields)) - ) - if fields: - if dtype.names is None: - raise IndexError("invalid 'fields' argument, array does not have any fields") - try: - if isinstance(fields, str): - # single field selection - out_dtype = dtype[fields] - else: - # multiple field selection - out_dtype = np.dtype([(f, dtype[f]) for f in fields]) - except KeyError as e: - raise IndexError("invalid 'fields' argument, field not found: {!r}".format(e)) - else: - return out_dtype - else: - return dtype - - -def check_no_multi_fields(fields): - if isinstance(fields, list): - if len(fields) == 1: - return fields[0] - elif len(fields) > 1: - raise IndexError("multiple fields are not supported for this operation") - return fields - - -def pop_fields(selection): - if isinstance(selection, str): - # single field selection - fields = selection - selection = () - elif not isinstance(selection, tuple): - # single selection item, no fields - fields = None - # leave selection as-is - else: - # multiple items, split fields from selection items - fields = [f for f in selection if isinstance(f, str)] - fields = fields[0] if len(fields) == 1 else fields - selection = tuple(s for s in selection if not isinstance(s, str)) - selection = selection[0] if len(selection) == 1 else selection - return fields, selection - - -def make_slice_selection(selection): - ls = [] - for dim_selection in selection: - if is_integer(dim_selection): - ls.append(slice(int(dim_selection), int(dim_selection) + 1, 1)) - elif isinstance(dim_selection, np.ndarray): - if len(dim_selection) == 1: - ls.append(slice(int(dim_selection[0]), int(dim_selection[0]) + 1, 1)) - else: - raise ArrayIndexError - else: - ls.append(dim_selection) - return ls - - -class PartialChunkIterator: - """Iterator to retrieve the specific coordinates of requested data - from within a compressed chunk. - - Parameters - ---------- - selection : tuple - tuple of slice objects to take from the chunk - arr_shape : shape of chunk to select data from - - Attributes - ---------- - arr_shape - selection - - Returns - ------- - Tuple with 3 elements: - - start: int - elements offset in the chunk to read from - nitems: int - number of elements to read in the chunk from start - partial_out_selection: list of slices - indices of a temporary empty array of size `Array._chunks` to assign - the decompressed data to after the partial read. - - Notes - ----- - An array is flattened when compressed with blosc, so this iterator takes - the wanted selection of an array and determines the wanted coordinates - of the flattened, compressed data to be read and then decompressed. The - decompressed data is then placed in a temporary empty array of size - `Array._chunks` at the indices yielded as partial_out_selection. - Once all the slices yielded by this iterator have been read, decompressed - and written to the temporary array, the wanted slice of the chunk can be - indexed from the temporary array and written to the out_selection slice - of the out array. - - """ - - def __init__(self, selection, arr_shape): - selection = make_slice_selection(selection) - self.arr_shape = arr_shape - - # number of selection dimensions can't be greater than the number of chunk dimensions - if len(selection) > len(self.arr_shape): - raise ValueError( - "Selection has more dimensions then the array:\n" - f"selection dimensions = {len(selection)}\n" - f"array dimensions = {len(self.arr_shape)}" - ) - - # any selection can not be out of the range of the chunk - selection_shape = np.empty(self.arr_shape)[tuple(selection)].shape - if any( - selection_dim < 0 or selection_dim > arr_dim - for selection_dim, arr_dim in zip(selection_shape, self.arr_shape) - ): - raise IndexError( - "a selection index is out of range for the dimension" - ) # pragma: no cover - - for i, dim_size in enumerate(self.arr_shape[::-1]): - index = len(self.arr_shape) - (i + 1) - if index <= len(selection) - 1: - slice_size = selection_shape[index] - if slice_size == dim_size and index > 0: - selection.pop() - else: - break - - chunk_loc_slices = [] - last_dim_slice = None if selection[-1].step > 1 else selection.pop() - for arr_shape_i, sl in zip(arr_shape, selection): - dim_chunk_loc_slices = [] - assert isinstance(sl, slice) - for x in slice_to_range(sl, arr_shape_i): - dim_chunk_loc_slices.append(slice(x, x + 1, 1)) - chunk_loc_slices.append(dim_chunk_loc_slices) - if last_dim_slice: - chunk_loc_slices.append([last_dim_slice]) - self.chunk_loc_slices = list(itertools.product(*chunk_loc_slices)) - - def __iter__(self): - chunk1 = self.chunk_loc_slices[0] - nitems = (chunk1[-1].stop - chunk1[-1].start) * np.prod( - self.arr_shape[len(chunk1) :], dtype=int - ) - for partial_out_selection in self.chunk_loc_slices: - start = 0 - for i, sl in enumerate(partial_out_selection): - start += sl.start * np.prod(self.arr_shape[i + 1 :], dtype=int) - yield start, nitems, partial_out_selection diff --git a/src/zarr/v2/meta.py b/src/zarr/v2/meta.py deleted file mode 100644 index 418c0727cf..0000000000 --- a/src/zarr/v2/meta.py +++ /dev/null @@ -1,303 +0,0 @@ -import base64 -import itertools -from collections.abc import Mapping - -import numpy as np - -from zarr.v2.errors import MetadataError -from zarr.v2.util import json_dumps, json_loads - -from typing import cast, Union, Any, List, Mapping as MappingType, TYPE_CHECKING - -if TYPE_CHECKING: # pragma: no cover - pass - - -ZARR_FORMAT = 2 - -# FLOAT_FILLS = {"NaN": np.nan, "Infinity": np.PINF, "-Infinity": np.NINF} - -_v3_core_types = set("".join(d) for d in itertools.product("<>", ("u", "i", "f"), ("2", "4", "8"))) -_v3_core_types = {"bool", "i1", "u1"} | _v3_core_types - -# The set of complex types allowed ({"c8", ">c16"}) -_v3_complex_types = set(f"{end}c{_bytes}" for end, _bytes in itertools.product("<>", ("8", "16"))) - -# All dtype.str values corresponding to datetime64 and timedelta64 -# see: https://numpy.org/doc/stable/reference/arrays.datetime.html#datetime-units -_date_units = ["Y", "M", "W", "D"] -_time_units = ["h", "m", "s", "ms", "us", "ΞΌs", "ns", "ps", "fs", "as"] -_v3_datetime_types = set( - f"{end}{kind}8[{unit}]" - for end, unit, kind in itertools.product("<>", _date_units + _time_units, ("m", "M")) -) - - -def get_extended_dtype_info(dtype) -> dict: - if dtype.str in _v3_complex_types: - return dict( - extension="https://zarr-specs.readthedocs.io/en/core-protocol-v3.0-dev/protocol/extensions/complex-dtypes/v1.0.html", - type=dtype.str, - fallback=None, - ) - elif dtype.str == "|O": - return dict( - extension="TODO: object array protocol URL", - type=dtype.str, - fallback=None, - ) - elif dtype.str.startswith("|S"): - return dict( - extension="TODO: bytestring array protocol URL", - type=dtype.str, - fallback=None, - ) - elif dtype.str.startswith("U"): - return dict( - extension="TODO: unicode array protocol URL", - type=dtype.str, - fallback=None, - ) - elif dtype.str.startswith("|V"): - return dict( - extension="TODO: structured array protocol URL", - type=dtype.descr, - fallback=None, - ) - elif dtype.str in _v3_datetime_types: - return dict( - extension="https://zarr-specs.readthedocs.io/en/latest/extensions/data-types/datetime/v1.0.html", - type=dtype.str, - fallback=None, - ) - else: - raise ValueError(f"Unsupported dtype: {dtype}") - - -class Metadata2: - ZARR_FORMAT = ZARR_FORMAT - - @classmethod - def parse_metadata(cls, s: Union[MappingType, bytes, str]) -> MappingType[str, Any]: - # Here we allow that a store may return an already-parsed metadata object, - # or a string of JSON that we will parse here. We allow for an already-parsed - # object to accommodate a consolidated metadata store, where all the metadata for - # all groups and arrays will already have been parsed from JSON. - - if isinstance(s, Mapping): - # assume metadata has already been parsed into a mapping object - meta = s - - else: - # assume metadata needs to be parsed as JSON - meta = json_loads(s) - - return meta - - @classmethod - def decode_array_metadata(cls, s: Union[MappingType, bytes, str]) -> MappingType[str, Any]: - meta = cls.parse_metadata(s) - - # check metadata format - zarr_format = meta.get("zarr_format", None) - if zarr_format != cls.ZARR_FORMAT: - raise MetadataError("unsupported zarr format: %s" % zarr_format) - - # extract array metadata fields - try: - dtype = cls.decode_dtype(meta["dtype"]) - if dtype.hasobject: - import numcodecs - - object_codec = numcodecs.get_codec(meta["filters"][0]) - else: - object_codec = None - - dimension_separator = meta.get("dimension_separator", None) - fill_value = cls.decode_fill_value(meta["fill_value"], dtype, object_codec) - meta = dict( - zarr_format=meta["zarr_format"], - shape=tuple(meta["shape"]), - chunks=tuple(meta["chunks"]), - dtype=dtype, - compressor=meta["compressor"], - fill_value=fill_value, - order=meta["order"], - filters=meta["filters"], - ) - if dimension_separator: - meta["dimension_separator"] = dimension_separator - except Exception as e: - raise MetadataError("error decoding metadata") from e - else: - return meta - - @classmethod - def encode_array_metadata(cls, meta: MappingType[str, Any]) -> bytes: - dtype = meta["dtype"] - sdshape = () - if dtype.subdtype is not None: - dtype, sdshape = dtype.subdtype - - dimension_separator = meta.get("dimension_separator") - if dtype.hasobject: - import numcodecs - - object_codec = numcodecs.get_codec(meta["filters"][0]) - else: - object_codec = None - - meta = dict( - zarr_format=cls.ZARR_FORMAT, - shape=meta["shape"] + sdshape, - chunks=meta["chunks"], - dtype=cls.encode_dtype(dtype), - compressor=meta["compressor"], - fill_value=cls.encode_fill_value(meta["fill_value"], dtype, object_codec), - order=meta["order"], - filters=meta["filters"], - ) - if dimension_separator: - meta["dimension_separator"] = dimension_separator - - return json_dumps(meta) - - @classmethod - def encode_dtype(cls, d: np.dtype): - if d.fields is None: - return d.str - else: - return d.descr - - @classmethod - def _decode_dtype_descr(cls, d) -> List[Any]: - # need to convert list of lists to list of tuples - if isinstance(d, list): - # recurse to handle nested structures - d = [(k[0], cls._decode_dtype_descr(k[1])) + tuple(k[2:]) for k in d] - return d - - @classmethod - def decode_dtype(cls, d) -> np.dtype: - d = cls._decode_dtype_descr(d) - return np.dtype(d) - - @classmethod - def decode_group_metadata(cls, s: Union[MappingType, bytes, str]) -> MappingType[str, Any]: - meta = cls.parse_metadata(s) - - # check metadata format version - zarr_format = meta.get("zarr_format", None) - if zarr_format != cls.ZARR_FORMAT: - raise MetadataError("unsupported zarr format: %s" % zarr_format) - - meta = dict(zarr_format=zarr_format) - return meta - - # N.B., keep `meta` parameter as a placeholder for future - # noinspection PyUnusedLocal - @classmethod - def encode_group_metadata(cls, meta=None) -> bytes: - meta = dict(zarr_format=cls.ZARR_FORMAT) - return json_dumps(meta) - - @classmethod - def decode_fill_value(cls, v: Any, dtype: np.dtype, object_codec: Any = None) -> Any: - # early out - if v is None: - return v - if dtype.kind == "V" and dtype.hasobject: - if object_codec is None: - raise ValueError("missing object_codec for object array") - v = base64.standard_b64decode(v) - v = object_codec.decode(v) - v = np.array(v, dtype=dtype)[()] - return v - if dtype.kind == "f": - if v == "NaN": - return np.nan - elif v == "Infinity": - return np.inf - elif v == "-Infinity": - return -np.inf - else: - return np.array(v, dtype=dtype)[()] - elif dtype.kind == "c": - v = ( - cls.decode_fill_value(v[0], dtype.type().real.dtype), - cls.decode_fill_value(v[1], dtype.type().imag.dtype), - ) - v = v[0] + 1j * v[1] - return np.array(v, dtype=dtype)[()] - elif dtype.kind == "S": - # noinspection PyBroadException - try: - v = base64.standard_b64decode(v) - except Exception: - # be lenient, allow for other values that may have been used before base64 - # encoding and may work as fill values, e.g., the number 0 - pass - v = np.array(v, dtype=dtype)[()] - return v - elif dtype.kind == "V": - v = base64.standard_b64decode(v) - v = np.array(v, dtype=dtype.str).view(dtype)[()] - return v - elif dtype.kind == "U": - # leave as-is - return v - else: - return np.array(v, dtype=dtype)[()] - - @classmethod - def encode_fill_value(cls, v: Any, dtype: np.dtype, object_codec: Any = None) -> Any: - # early out - if v is None: - return v - if dtype.kind == "V" and dtype.hasobject: - if object_codec is None: - raise ValueError("missing object_codec for object array") - v = object_codec.encode(v) - v = str(base64.standard_b64encode(v), "ascii") - return v - if dtype.kind == "f": - if np.isnan(v): - return "NaN" - elif np.isposinf(v): - return "Infinity" - elif np.isneginf(v): - return "-Infinity" - else: - return float(v) - elif dtype.kind in ("u", "i"): - return int(v) - elif dtype.kind == "b": - return bool(v) - elif dtype.kind == "c": - c = cast(np.complex128, np.dtype(complex).type()) - v = ( - cls.encode_fill_value(v.real, c.real.dtype, object_codec), - cls.encode_fill_value(v.imag, c.imag.dtype, object_codec), - ) - return v - elif dtype.kind in ("S", "V"): - v = str(base64.standard_b64encode(v), "ascii") - return v - elif dtype.kind == "U": - return v - elif dtype.kind in ("m", "M"): - return int(v.view("i8")) - else: - return v - - -parse_metadata = Metadata2.parse_metadata -decode_array_metadata = Metadata2.decode_array_metadata -encode_array_metadata = Metadata2.encode_array_metadata -encode_dtype = Metadata2.encode_dtype -_decode_dtype_descr = Metadata2._decode_dtype_descr -decode_dtype = Metadata2.decode_dtype -decode_group_metadata = Metadata2.decode_group_metadata -encode_group_metadata = Metadata2.encode_group_metadata -decode_fill_value = Metadata2.decode_fill_value -encode_fill_value = Metadata2.encode_fill_value diff --git a/src/zarr/v2/meta_v1.py b/src/zarr/v2/meta_v1.py deleted file mode 100644 index 881b9191eb..0000000000 --- a/src/zarr/v2/meta_v1.py +++ /dev/null @@ -1,64 +0,0 @@ -import json - -import numpy as np - -from zarr.v2.errors import MetadataError - - -def decode_metadata(b): - s = str(b, "ascii") - meta = json.loads(s) - zarr_format = meta.get("zarr_format", None) - if zarr_format != 1: - raise MetadataError("unsupported zarr format: %s" % zarr_format) - try: - meta = dict( - zarr_format=meta["zarr_format"], - shape=tuple(meta["shape"]), - chunks=tuple(meta["chunks"]), - dtype=decode_dtype(meta["dtype"]), - compression=meta["compression"], - compression_opts=meta["compression_opts"], - fill_value=meta["fill_value"], - order=meta["order"], - ) - except Exception as e: - raise MetadataError("error decoding metadata: %s" % e) - else: - return meta - - -def encode_metadata(meta): - meta = dict( - zarr_format=1, - shape=meta["shape"], - chunks=meta["chunks"], - dtype=encode_dtype(meta["dtype"]), - compression=meta["compression"], - compression_opts=meta["compression_opts"], - fill_value=meta["fill_value"], - order=meta["order"], - ) - s = json.dumps(meta, indent=4, sort_keys=True, ensure_ascii=True) - b = s.encode("ascii") - return b - - -def encode_dtype(d): - if d.fields is None: - return d.str - else: - return d.descr - - -def _decode_dtype_descr(d): - # need to convert list of lists to list of tuples - if isinstance(d, list): - # recurse to handle nested structures - d = [(f, _decode_dtype_descr(v)) for f, v in d] - return d - - -def decode_dtype(d): - d = _decode_dtype_descr(d) - return np.dtype(d) diff --git a/src/zarr/v2/n5.py b/src/zarr/v2/n5.py deleted file mode 100644 index a6fd39f5b8..0000000000 --- a/src/zarr/v2/n5.py +++ /dev/null @@ -1,896 +0,0 @@ -"""This module contains a storage class and codec to support the N5 format.""" - -import os -import struct -import sys -from typing import Any, Dict, Optional, cast -import warnings - -import numpy as np -from numcodecs.abc import Codec -from numcodecs.compat import ndarray_copy -from numcodecs.registry import get_codec, register_codec - -from zarr.v2.meta import ZARR_FORMAT, json_dumps, json_loads -from zarr.v2.storage import FSStore -from zarr.v2.storage import NestedDirectoryStore, _prog_ckey, _prog_number, normalize_storage_path -from zarr.v2.storage import array_meta_key as zarr_array_meta_key -from zarr.v2.storage import attrs_key as zarr_attrs_key -from zarr.v2.storage import group_meta_key as zarr_group_meta_key - -N5_FORMAT = "2.0.0" - -zarr_to_n5_keys = [ - ("chunks", "blockSize"), - ("dtype", "dataType"), - ("compressor", "compression"), - ("shape", "dimensions"), -] -n5_attrs_key = "attributes.json" -n5_keywords = ["n5", "dataType", "dimensions", "blockSize", "compression"] - - -class N5Store(NestedDirectoryStore): - """Storage class using directories and files on a standard file system, - following the N5 format (https://github.com/saalfeldlab/n5). - - Parameters - ---------- - path : string - Location of directory to use as the root of the storage hierarchy. - normalize_keys : bool, optional - If True, all store keys will be normalized to use lower case characters - (e.g. 'foo' and 'FOO' will be treated as equivalent). This can be - useful to avoid potential discrepancies between case-sensitive and - case-insensitive file system. Default value is False. - - Examples - -------- - Store a single array:: - - >>> import zarr - >>> store = zarr.N5Store('data/array.n5') - >>> z = zarr.zeros((10, 10), chunks=(5, 5), store=store, overwrite=True) - >>> z[...] = 42 - - Store a group:: - - >>> store = zarr.N5Store('data/group.n5') - >>> root = zarr.group(store=store, overwrite=True) - >>> foo = root.create_group('foo') - >>> bar = foo.zeros('bar', shape=(10, 10), chunks=(5, 5)) - >>> bar[...] = 42 - - Notes - ----- - - This is an experimental feature. - - Safe to write in multiple threads or processes. - - """ - - def __getitem__(self, key: str) -> bytes: - if key.endswith(zarr_group_meta_key): - key_new = key.replace(zarr_group_meta_key, n5_attrs_key) - value = group_metadata_to_zarr(self._load_n5_attrs(key_new)) - - return json_dumps(value) - - elif key.endswith(zarr_array_meta_key): - key_new = key.replace(zarr_array_meta_key, n5_attrs_key) - top_level = key == zarr_array_meta_key - value = array_metadata_to_zarr(self._load_n5_attrs(key_new), top_level=top_level) - return json_dumps(value) - - elif key.endswith(zarr_attrs_key): - key_new = key.replace(zarr_attrs_key, n5_attrs_key) - value = attrs_to_zarr(self._load_n5_attrs(key_new)) - - if len(value) == 0: - raise KeyError(key_new) - else: - return json_dumps(value) - - elif is_chunk_key(key): - key_new = invert_chunk_coords(key) - - else: - key_new = key - - return super().__getitem__(key_new) - - def __setitem__(self, key: str, value: Any): - if key.endswith(zarr_group_meta_key): - key_new = key.replace(zarr_group_meta_key, n5_attrs_key) - - n5_attrs = self._load_n5_attrs(key_new) - n5_attrs.update(**group_metadata_to_n5(json_loads(value))) - - value = json_dumps(n5_attrs) - - elif key.endswith(zarr_array_meta_key): - key_new = key.replace(zarr_array_meta_key, n5_attrs_key) - top_level = key == zarr_array_meta_key - n5_attrs = self._load_n5_attrs(key_new) - n5_attrs.update(**array_metadata_to_n5(json_loads(value), top_level=top_level)) - value = json_dumps(n5_attrs) - - elif key.endswith(zarr_attrs_key): - key_new = key.replace(zarr_attrs_key, n5_attrs_key) - - n5_attrs = self._load_n5_attrs(key_new) - zarr_attrs = json_loads(value) - - for k in n5_keywords: - if k in zarr_attrs: - warnings.warn(f"Attribute {k} is a reserved N5 keyword", UserWarning) - - # remove previous user attributes - for k in list(n5_attrs.keys()): - if k not in n5_keywords: - del n5_attrs[k] - - # add new user attributes - n5_attrs.update(**zarr_attrs) - - value = json_dumps(n5_attrs) - - elif is_chunk_key(key): - key_new = invert_chunk_coords(key) - - else: - key_new = key - - super().__setitem__(key_new, value) - - def __delitem__(self, key: str): - if key.endswith(zarr_group_meta_key): - key_new = key.replace(zarr_group_meta_key, n5_attrs_key) - elif key.endswith(zarr_array_meta_key): - key_new = key.replace(zarr_array_meta_key, n5_attrs_key) - elif key.endswith(zarr_attrs_key): - key_new = key.replace(zarr_attrs_key, n5_attrs_key) - elif is_chunk_key(key): - key_new = invert_chunk_coords(key) - else: - key_new = key - - super().__delitem__(key_new) - - def __contains__(self, key): - if key.endswith(zarr_group_meta_key): - key_new = key.replace(zarr_group_meta_key, n5_attrs_key) - if key_new not in self: - return False - # group if not a dataset (attributes do not contain 'dimensions') - return "dimensions" not in self._load_n5_attrs(key_new) - - elif key.endswith(zarr_array_meta_key): - key_new = key.replace(zarr_array_meta_key, n5_attrs_key) - # array if attributes contain 'dimensions' - return "dimensions" in self._load_n5_attrs(key_new) - - elif key.endswith(zarr_attrs_key): - key_new = key.replace(zarr_attrs_key, n5_attrs_key) - return self._contains_attrs(key_new) - - elif is_chunk_key(key): - key_new = invert_chunk_coords(key) - else: - key_new = key - - return super().__contains__(key_new) - - def __eq__(self, other): - return isinstance(other, N5Store) and self.path == other.path - - def listdir(self, path: Optional[str] = None): - if path is not None: - path = invert_chunk_coords(path) - path = cast(str, path) - # We can't use NestedDirectoryStore's listdir, as it requires - # array_meta_key to be present in array directories, which this store - # doesn't provide. - children = super().listdir(path=path) - - if self._is_array(path): - # replace n5 attribute file with respective zarr attribute files - children.remove(n5_attrs_key) - children.append(zarr_array_meta_key) - if self._contains_attrs(path): - children.append(zarr_attrs_key) - - # special handling of directories containing an array to map - # inverted nested chunk keys back to standard chunk keys - new_children = [] - root_path = self.dir_path(path) - for entry in children: - entry_path = os.path.join(root_path, entry) - if _prog_number.match(entry) and os.path.isdir(entry_path): - for dir_path, _, file_names in os.walk(entry_path): - for file_name in file_names: - file_path = os.path.join(dir_path, file_name) - rel_path = file_path.split(root_path + os.path.sep)[1] - new_child = rel_path.replace(os.path.sep, ".") - new_children.append(invert_chunk_coords(new_child)) - else: - new_children.append(entry) - - return sorted(new_children) - - elif self._is_group(path): - # replace n5 attribute file with respective zarr attribute files - children.remove(n5_attrs_key) - children.append(zarr_group_meta_key) - if self._contains_attrs(path): - children.append(zarr_attrs_key) - - return sorted(children) - - else: - return children - - def _load_n5_attrs(self, path: str) -> Dict[str, Any]: - try: - s = super().__getitem__(path) - return json_loads(s) - except KeyError: - return {} - - def _is_group(self, path: str): - if path is None: - attrs_key = n5_attrs_key - else: - attrs_key = os.path.join(path, n5_attrs_key) - - n5_attrs = self._load_n5_attrs(attrs_key) - return len(n5_attrs) > 0 and "dimensions" not in n5_attrs - - def _is_array(self, path: str): - if path is None: - attrs_key = n5_attrs_key - else: - attrs_key = os.path.join(path, n5_attrs_key) - - return "dimensions" in self._load_n5_attrs(attrs_key) - - def _contains_attrs(self, path: str): - if path is None: - attrs_key = n5_attrs_key - else: - if not path.endswith(n5_attrs_key): - attrs_key = os.path.join(path, n5_attrs_key) - else: - attrs_key = path - - attrs = attrs_to_zarr(self._load_n5_attrs(attrs_key)) - return len(attrs) > 0 - - -class N5FSStore(FSStore): - """Implementation of the N5 format (https://github.com/saalfeldlab/n5) - using `fsspec`, which allows storage on a variety of filesystems. Based - on `zarr.N5Store`. - Parameters - ---------- - path : string - Location of directory to use as the root of the storage hierarchy. - normalize_keys : bool, optional - If True, all store keys will be normalized to use lower case characters - (e.g. 'foo' and 'FOO' will be treated as equivalent). This can be - useful to avoid potential discrepancies between case-sensitive and - case-insensitive file system. Default value is False. - - Examples - -------- - Store a single array:: - - >>> import zarr - >>> store = zarr.N5FSStore('data/array.n5', auto_mkdir=True) - >>> z = zarr.zeros((10, 10), chunks=(5, 5), store=store, overwrite=True) - >>> z[...] = 42 - - Store a group:: - - >>> store = zarr.N5FSStore('data/group.n5', auto_mkdir=True) - >>> root = zarr.group(store=store, overwrite=True) - >>> foo = root.create_group('foo') - >>> bar = foo.zeros('bar', shape=(10, 10), chunks=(5, 5)) - >>> bar[...] = 42 - - Notes - ----- - This is an experimental feature. - Safe to write in multiple threads or processes. - - Be advised that the `_dimension_separator` property of this store - (and arrays it creates) is ".", but chunks saved by this store will - in fact be "/" separated, as proscribed by the N5 format. - - This is counter-intuitive (to say the least), but not arbitrary. - Chunks in N5 format are stored with reversed dimension order - relative to Zarr chunks: a chunk of a 3D Zarr array would be stored - on a file system as `/0/1/2`, but in N5 the same chunk would be - stored as `/2/1/0`. Therefore, stores targeting N5 must intercept - chunk keys and flip the order of the dimensions before writing to - storage, and this procedure requires chunk keys with "." separated - dimensions, hence the Zarr arrays targeting N5 have the deceptive - "." dimension separator. - """ - - _array_meta_key = "attributes.json" - _group_meta_key = "attributes.json" - _attrs_key = "attributes.json" - - def __init__(self, *args, **kwargs): - if "dimension_separator" in kwargs: - warnings.warn("Keyword argument `dimension_separator` will be ignored") - kwargs["dimension_separator"] = "." - super().__init__(*args, **kwargs) - - @staticmethod - def _swap_separator(key: str): - segments = list(key.split("/")) - if segments: - last_segment = segments[-1] - if _prog_ckey.match(last_segment): - coords = list(last_segment.split(".")) - last_segment = "/".join(coords[::-1]) - segments = segments[:-1] + [last_segment] - key = "/".join(segments) - return key - - def _normalize_key(self, key: str): - if is_chunk_key(key): - key = invert_chunk_coords(key) - - key = normalize_storage_path(key).lstrip("/") - if key: - *bits, end = key.split("/") - - if end not in (self._array_meta_key, self._group_meta_key, self._attrs_key): - end = end.replace(".", "/") - key = "/".join(bits + [end]) - return key.lower() if self.normalize_keys else key - - def __getitem__(self, key: str) -> bytes: - if key.endswith(zarr_group_meta_key): - key_new = key.replace(zarr_group_meta_key, self._group_meta_key) - value = group_metadata_to_zarr(self._load_n5_attrs(key_new)) - - return json_dumps(value) - - elif key.endswith(zarr_array_meta_key): - key_new = key.replace(zarr_array_meta_key, self._array_meta_key) - top_level = key == zarr_array_meta_key - value = array_metadata_to_zarr(self._load_n5_attrs(key_new), top_level=top_level) - return json_dumps(value) - - elif key.endswith(zarr_attrs_key): - key_new = key.replace(zarr_attrs_key, self._attrs_key) - value = attrs_to_zarr(self._load_n5_attrs(key_new)) - - if len(value) == 0: - raise KeyError(key_new) - else: - return json_dumps(value) - - elif is_chunk_key(key): - key_new = self._swap_separator(key) - - else: - key_new = key - - return super().__getitem__(key_new) - - def __setitem__(self, key: str, value: Any): - if key.endswith(zarr_group_meta_key): - key_new = key.replace(zarr_group_meta_key, self._group_meta_key) - - n5_attrs = self._load_n5_attrs(key_new) - n5_attrs.update(**group_metadata_to_n5(json_loads(value))) - - value = json_dumps(n5_attrs) - - elif key.endswith(zarr_array_meta_key): - key_new = key.replace(zarr_array_meta_key, self._array_meta_key) - top_level = key == zarr_array_meta_key - n5_attrs = self._load_n5_attrs(key_new) - n5_attrs.update(**array_metadata_to_n5(json_loads(value), top_level=top_level)) - - value = json_dumps(n5_attrs) - - elif key.endswith(zarr_attrs_key): - key_new = key.replace(zarr_attrs_key, self._attrs_key) - - n5_attrs = self._load_n5_attrs(key_new) - zarr_attrs = json_loads(value) - - for k in n5_keywords: - if k in zarr_attrs.keys(): - warnings.warn(f"Attribute {k} is a reserved N5 keyword", UserWarning) - - # replace previous user attributes - for k in list(n5_attrs.keys()): - if k not in n5_keywords: - del n5_attrs[k] - - # add new user attributes - n5_attrs.update(**zarr_attrs) - - value = json_dumps(n5_attrs) - - elif is_chunk_key(key): - key_new = self._swap_separator(key) - - else: - key_new = key - - super().__setitem__(key_new, value) - - def __delitem__(self, key: str): - if key.endswith(zarr_group_meta_key): - key_new = key.replace(zarr_group_meta_key, self._group_meta_key) - elif key.endswith(zarr_array_meta_key): - key_new = key.replace(zarr_array_meta_key, self._array_meta_key) - elif key.endswith(zarr_attrs_key): - key_new = key.replace(zarr_attrs_key, self._attrs_key) - elif is_chunk_key(key): - key_new = self._swap_separator(key) - else: - key_new = key - super().__delitem__(key_new) - - def __contains__(self, key: Any): - if key.endswith(zarr_group_meta_key): - key_new = key.replace(zarr_group_meta_key, self._group_meta_key) - if key_new not in self: - return False - # group if not a dataset (attributes do not contain 'dimensions') - return "dimensions" not in self._load_n5_attrs(key_new) - - elif key.endswith(zarr_array_meta_key): - key_new = key.replace(zarr_array_meta_key, self._array_meta_key) - # array if attributes contain 'dimensions' - return "dimensions" in self._load_n5_attrs(key_new) - - elif key.endswith(zarr_attrs_key): - key_new = key.replace(zarr_attrs_key, self._attrs_key) - return self._contains_attrs(key_new) - - elif is_chunk_key(key): - key_new = self._swap_separator(key) - - else: - key_new = key - return super().__contains__(key_new) - - def __eq__(self, other: Any): - return isinstance(other, N5FSStore) and self.path == other.path - - def listdir(self, path: Optional[str] = None): - if path is not None: - path = invert_chunk_coords(path) - - # We can't use NestedDirectoryStore's listdir, as it requires - # array_meta_key to be present in array directories, which this store - # doesn't provide. - children = super().listdir(path=path) - if self._is_array(path): - # replace n5 attribute file with respective zarr attribute files - children.remove(self._array_meta_key) - children.append(zarr_array_meta_key) - if self._contains_attrs(path): - children.append(zarr_attrs_key) - - # special handling of directories containing an array to map - # inverted nested chunk keys back to standard chunk keys - new_children = [] - root_path = self.dir_path(path) - for entry in children: - entry_path = os.path.join(root_path, entry) - if _prog_number.match(entry) and self.fs.isdir(entry_path): - for file_name in self.fs.find(entry_path): - file_path = os.path.join(root_path, file_name) - rel_path = file_path.split(root_path)[1] - new_child = rel_path.lstrip("/").replace("/", ".") - new_children.append(invert_chunk_coords(new_child)) - else: - new_children.append(entry) - return sorted(new_children) - - elif self._is_group(path): - # replace n5 attribute file with respective zarr attribute files - children.remove(self._group_meta_key) - children.append(zarr_group_meta_key) - if self._contains_attrs(path): - children.append(zarr_attrs_key) - return sorted(children) - else: - return children - - def _load_n5_attrs(self, path: str): - try: - s = super().__getitem__(path) - return json_loads(s) - except KeyError: - return {} - - def _is_group(self, path: Optional[str]): - if path is None: - attrs_key = self._attrs_key - else: - attrs_key = os.path.join(path, self._attrs_key) - - n5_attrs = self._load_n5_attrs(attrs_key) - return len(n5_attrs) > 0 and "dimensions" not in n5_attrs - - def _is_array(self, path: Optional[str]): - if path is None: - attrs_key = self._attrs_key - else: - attrs_key = os.path.join(path, self._attrs_key) - - return "dimensions" in self._load_n5_attrs(attrs_key) - - def _contains_attrs(self, path: Optional[str]): - if path is None: - attrs_key = self._attrs_key - else: - if not path.endswith(self._attrs_key): - attrs_key = os.path.join(path, self._attrs_key) - else: - attrs_key = path - - attrs = attrs_to_zarr(self._load_n5_attrs(attrs_key)) - return len(attrs) > 0 - - -def is_chunk_key(key: str): - rv = False - segments = list(key.split("/")) - if segments: - last_segment = segments[-1] - rv = bool(_prog_ckey.match(last_segment)) - return rv - - -def invert_chunk_coords(key: str): - segments = list(key.split("/")) - if segments: - last_segment = segments[-1] - if _prog_ckey.match(last_segment): - coords = list(last_segment.split(".")) - last_segment = "/".join(coords[::-1]) - segments = segments[:-1] + [last_segment] - key = "/".join(segments) - return key - - -def group_metadata_to_n5(group_metadata: Dict[str, Any]) -> Dict[str, Any]: - """Convert group metadata from zarr to N5 format.""" - del group_metadata["zarr_format"] - # TODO: This should only exist at the top-level - group_metadata["n5"] = N5_FORMAT - return group_metadata - - -def group_metadata_to_zarr(group_metadata: Dict[str, Any]) -> Dict[str, Any]: - """Convert group metadata from N5 to zarr format.""" - # This only exists at the top level - group_metadata.pop("n5", None) - group_metadata["zarr_format"] = ZARR_FORMAT - return group_metadata - - -def array_metadata_to_n5(array_metadata: Dict[str, Any], top_level=False) -> Dict[str, Any]: - """Convert array metadata from zarr to N5 format. If the `top_level` keyword argument is True, - then the `N5` : N5_FORMAT key : value pair will be inserted into the metadata.""" - - for f, t in zarr_to_n5_keys: - array_metadata[t] = array_metadata.pop(f) - del array_metadata["zarr_format"] - if top_level: - array_metadata["n5"] = N5_FORMAT - try: - dtype = np.dtype(array_metadata["dataType"]) - except TypeError: - raise TypeError(f"Data type {array_metadata['dataType']} is not supported by N5") - - array_metadata["dataType"] = dtype.name - array_metadata["dimensions"] = array_metadata["dimensions"][::-1] - array_metadata["blockSize"] = array_metadata["blockSize"][::-1] - - if "fill_value" in array_metadata: - if array_metadata["fill_value"] != 0 and array_metadata["fill_value"] is not None: - raise ValueError( - f"""Received fill_value = {array_metadata['fill_value']}, - but N5 only supports fill_value = 0""" - ) - del array_metadata["fill_value"] - - if "order" in array_metadata: - if array_metadata["order"] != "C": - raise ValueError( - f"Received order = {array_metadata['order']}, but N5 only supports order = C" - ) - del array_metadata["order"] - - if "filters" in array_metadata: - if array_metadata["filters"] != [] and array_metadata["filters"] is not None: - raise ValueError("Received filters, but N5 storage does not support zarr filters") - del array_metadata["filters"] - - assert "compression" in array_metadata - compressor_config = array_metadata["compression"] - compressor_config = compressor_config_to_n5(compressor_config) - array_metadata["compression"] = compressor_config - - if "dimension_separator" in array_metadata: - del array_metadata["dimension_separator"] - - return array_metadata - - -def array_metadata_to_zarr( - array_metadata: Dict[str, Any], top_level: bool = False -) -> Dict[str, Any]: - """Convert array metadata from N5 to zarr format. - If the `top_level` keyword argument is True, then the `N5` key will be removed from metadata""" - for t, f in zarr_to_n5_keys: - array_metadata[t] = array_metadata.pop(f) - if top_level: - array_metadata.pop("n5") - array_metadata["zarr_format"] = ZARR_FORMAT - - array_metadata["shape"] = array_metadata["shape"][::-1] - array_metadata["chunks"] = array_metadata["chunks"][::-1] - array_metadata["fill_value"] = 0 # also if None was requested - array_metadata["order"] = "C" - array_metadata["filters"] = [] - array_metadata["dimension_separator"] = "." - array_metadata["dtype"] = np.dtype(array_metadata["dtype"]).str - - compressor_config = array_metadata["compressor"] - compressor_config = compressor_config_to_zarr(compressor_config) - array_metadata["compressor"] = { - "id": N5ChunkWrapper.codec_id, - "compressor_config": compressor_config, - "dtype": array_metadata["dtype"], - "chunk_shape": array_metadata["chunks"], - } - - return array_metadata - - -def attrs_to_zarr(attrs: Dict[str, Any]) -> Dict[str, Any]: - """Get all zarr attributes from an N5 attributes dictionary (i.e., - all non-keyword attributes).""" - - # remove all N5 keywords - for n5_key in n5_keywords: - if n5_key in attrs: - del attrs[n5_key] - - return attrs - - -def compressor_config_to_n5(compressor_config: Optional[Dict[str, Any]]) -> Dict[str, Any]: - if compressor_config is None: - return {"type": "raw"} - else: - _compressor_config = compressor_config - - # peel wrapper, if present - if _compressor_config["id"] == N5ChunkWrapper.codec_id: - _compressor_config = _compressor_config["compressor_config"] - - codec_id = _compressor_config["id"] - n5_config = {"type": codec_id} - - if codec_id == "bz2": - n5_config["type"] = "bzip2" - n5_config["blockSize"] = _compressor_config["level"] - - elif codec_id == "blosc": - n5_config["cname"] = _compressor_config["cname"] - n5_config["clevel"] = _compressor_config["clevel"] - n5_config["shuffle"] = _compressor_config["shuffle"] - n5_config["blocksize"] = _compressor_config["blocksize"] - - elif codec_id == "lzma": - # Switch to XZ for N5 if we are using the default XZ format. - # Note: 4 is the default, which is lzma.CHECK_CRC64. - if _compressor_config["format"] == 1 and _compressor_config["check"] in [-1, 4]: - n5_config["type"] = "xz" - else: - warnings.warn( - "Not all N5 implementations support lzma compression (yet). You " - "might not be able to open the dataset with another N5 library.", - RuntimeWarning, - ) - n5_config["format"] = _compressor_config["format"] - n5_config["check"] = _compressor_config["check"] - n5_config["filters"] = _compressor_config["filters"] - - # The default is lzma.PRESET_DEFAULT, which is 6. - if _compressor_config["preset"]: - n5_config["preset"] = _compressor_config["preset"] - else: - n5_config["preset"] = 6 - - elif codec_id == "zlib": - n5_config["type"] = "gzip" - n5_config["level"] = _compressor_config["level"] - n5_config["useZlib"] = True - - elif codec_id == "gzip": - n5_config["type"] = "gzip" - n5_config["level"] = _compressor_config["level"] - n5_config["useZlib"] = False - - else: - n5_config.update({k: v for k, v in _compressor_config.items() if k != "type"}) - - return n5_config - - -def compressor_config_to_zarr(compressor_config: Dict[str, Any]) -> Optional[Dict[str, Any]]: - codec_id = compressor_config["type"] - zarr_config = {"id": codec_id} - - if codec_id == "bzip2": - zarr_config["id"] = "bz2" - zarr_config["level"] = compressor_config["blockSize"] - - elif codec_id == "blosc": - zarr_config["cname"] = compressor_config["cname"] - zarr_config["clevel"] = compressor_config["clevel"] - zarr_config["shuffle"] = compressor_config["shuffle"] - zarr_config["blocksize"] = compressor_config["blocksize"] - - elif codec_id == "lzma": - zarr_config["format"] = compressor_config["format"] - zarr_config["check"] = compressor_config["check"] - zarr_config["preset"] = compressor_config["preset"] - zarr_config["filters"] = compressor_config["filters"] - - elif codec_id == "xz": - zarr_config["id"] = "lzma" - zarr_config["format"] = 1 # lzma.FORMAT_XZ - zarr_config["check"] = -1 - zarr_config["preset"] = compressor_config["preset"] - zarr_config["filters"] = None - - elif codec_id == "gzip": - if compressor_config.get("useZlib"): - zarr_config["id"] = "zlib" - zarr_config["level"] = compressor_config["level"] - else: - zarr_config["id"] = "gzip" - zarr_config["level"] = compressor_config["level"] - - elif codec_id == "raw": - return None - - else: - zarr_config.update({k: v for k, v in compressor_config.items() if k != "type"}) - - return zarr_config - - -class N5ChunkWrapper(Codec): # type: ignore[misc] - codec_id = "n5_wrapper" - - def __init__(self, dtype, chunk_shape, compressor_config=None, compressor=None): - self.dtype = np.dtype(dtype) - self.chunk_shape = tuple(chunk_shape) - # is the dtype a little endian format? - self._little_endian = self.dtype.byteorder == "<" or ( - self.dtype.byteorder == "=" and sys.byteorder == "little" - ) - - if compressor: - if compressor_config is not None: - raise ValueError("Only one of compressor_config or compressor should be given.") - compressor_config = compressor.get_config() - - if compressor_config is None and compressor is None or compressor_config["id"] == "raw": - self.compressor_config = None - self._compressor = None - else: - self._compressor = get_codec(compressor_config) - self.compressor_config = self._compressor.get_config() - - def get_config(self): - config = {"id": self.codec_id, "compressor_config": self.compressor_config} - return config - - def encode(self, chunk): - assert chunk.flags.c_contiguous - - header = self._create_header(chunk) - chunk = self._to_big_endian(chunk) - - if self._compressor: - return header + self._compressor.encode(chunk) - else: - return header + chunk.tobytes(order="A") - - def decode(self, chunk, out=None) -> bytes: - len_header, chunk_shape = self._read_header(chunk) - chunk = chunk[len_header:] - - if out is not None: - # out should only be used if we read a complete chunk - assert chunk_shape == self.chunk_shape, "Expected chunk of shape {}, found {}".format( - self.chunk_shape, chunk_shape - ) - - if self._compressor: - self._compressor.decode(chunk, out) - else: - ndarray_copy(chunk, out) - - # we can byteswap in-place - if self._little_endian: - out.byteswap(True) - - return out - - else: - if self._compressor: - chunk = self._compressor.decode(chunk) - - # more expensive byteswap - chunk = self._from_big_endian(chunk) - - # read partial chunk - if chunk_shape != self.chunk_shape: - chunk = np.frombuffer(chunk, dtype=self.dtype) - chunk = chunk.reshape(chunk_shape) - complete_chunk = np.zeros(self.chunk_shape, dtype=self.dtype) - target_slices = tuple(slice(0, s) for s in chunk_shape) - complete_chunk[target_slices] = chunk - chunk = complete_chunk - - return chunk - - @staticmethod - def _create_header(chunk): - mode = struct.pack(">H", 0) - num_dims = struct.pack(">H", len(chunk.shape)) - shape = b"".join(struct.pack(">I", d) for d in chunk.shape[::-1]) - - return mode + num_dims + shape - - @staticmethod - def _read_header(chunk): - num_dims = struct.unpack(">H", chunk[2:4])[0] - shape = tuple( - struct.unpack(">I", chunk[i : i + 4])[0] for i in range(4, num_dims * 4 + 4, 4) - )[::-1] - - len_header = 4 + num_dims * 4 - - return len_header, shape - - def _to_big_endian(self, data): - # assumes data is ndarray - - if self._little_endian: - return data.byteswap() - return data - - def _from_big_endian(self, data): - # assumes data is byte array in big endian - - if not self._little_endian: - return data - - a = np.frombuffer(data, self.dtype.newbyteorder(">")) - return a.astype(self.dtype) - - -register_codec(N5ChunkWrapper, N5ChunkWrapper.codec_id) diff --git a/src/zarr/v2/storage.py b/src/zarr/v2/storage.py deleted file mode 100644 index 67240e520d..0000000000 --- a/src/zarr/v2/storage.py +++ /dev/null @@ -1,2822 +0,0 @@ -"""This module contains storage classes for use with Zarr arrays and groups. - -Note that any object implementing the :class:`MutableMapping` interface from the -:mod:`collections` module in the Python standard library can be used as a Zarr -array store, as long as it accepts string (str) keys and bytes values. - -In addition to the :class:`MutableMapping` interface, store classes may also implement -optional methods `listdir` (list members of a "directory") and `rmdir` (remove all -members of a "directory"). These methods should be implemented if the store class is -aware of the hierarchical organisation of resources within the store and can provide -efficient implementations. If these methods are not available, Zarr will fall back to -slower implementations that work via the :class:`MutableMapping` interface. Store -classes may also optionally implement a `rename` method (rename all members under a given -path) and a `getsize` method (return the size in bytes of a given value). - -""" - -import atexit -import errno -import glob -import multiprocessing -import operator -import os -import re -import shutil -import sys -import tempfile -import warnings -import zipfile -from collections import OrderedDict -from collections.abc import MutableMapping -from os import scandir -from pickle import PicklingError -from threading import Lock, RLock -from typing import Sequence, Mapping, Optional, Union, List, Tuple, Dict, Any -import uuid -import time - -from numcodecs.compat import ensure_bytes, ensure_text, ensure_contiguous_ndarray_like -from numcodecs.registry import codec_registry -from zarr.v2.context import Context - -from zarr.v2.errors import ( - MetadataError, - BadCompressorError, - ContainsArrayError, - ContainsGroupError, - FSPathExistNotDir, - ReadOnlyError, -) -from zarr.v2.meta import encode_array_metadata, encode_group_metadata -from zarr.v2.util import ( - buffer_size, - json_loads, - nolock, - normalize_chunks, - normalize_dimension_separator, - normalize_dtype, - normalize_fill_value, - normalize_order, - normalize_shape, - normalize_storage_path, - retry_call, - ensure_contiguous_ndarray_or_bytes, -) - -from zarr.v2._storage.absstore import ABSStore # noqa: F401 -from zarr.v2._storage.store import ( # noqa: F401 - _listdir_from_keys, - _rename_from_keys, - _rmdir_from_keys, - _path_to_prefix, - _prefix_to_array_key, - _prefix_to_group_key, - array_meta_key, - attrs_key, - group_meta_key, - DEFAULT_ZARR_VERSION, - BaseStore, - Store, -) - -__doctest_requires__ = { - ("RedisStore", "RedisStore.*"): ["redis"], - ("MongoDBStore", "MongoDBStore.*"): ["pymongo"], - ("LRUStoreCache", "LRUStoreCache.*"): ["s3fs"], -} - - -try: - # noinspection PyUnresolvedReferences - from zarr.v2.codecs import Blosc - - default_compressor = Blosc() -except ImportError: # pragma: no cover - from zarr.v2.codecs import Zlib - - default_compressor = Zlib() - - -Path = Union[str, bytes, None] -# allow MutableMapping for backwards compatibility -StoreLike = Union[BaseStore, MutableMapping[str, Any]] - - -def contains_array(store: StoreLike, path: Path = None) -> bool: - """Return True if the store contains an array at the given logical path.""" - path = normalize_storage_path(path) - prefix = _path_to_prefix(path) - key = _prefix_to_array_key(store, prefix) - return key in store - - -def contains_group(store: StoreLike, path: Path = None, explicit_only=True) -> bool: - """Return True if the store contains a group at the given logical path.""" - path = normalize_storage_path(path) - prefix = _path_to_prefix(path) - key = _prefix_to_group_key(store, prefix) - return key in store - - -def normalize_store_arg(store: Any, storage_options=None, mode="r") -> BaseStore: - if store is None: - store = KVStore(dict()) - return store - if isinstance(store, os.PathLike): - store = os.fspath(store) - if FSStore._fsspec_installed(): - import fsspec - - if isinstance(store, fsspec.FSMap): - return FSStore( - store.root, - fs=store.fs, - mode=mode, - check=store.check, - create=store.create, - missing_exceptions=store.missing_exceptions, - **(storage_options or {}), - ) - if isinstance(store, str): - if "://" in store or "::" in store: - return FSStore(store, mode=mode, **(storage_options or {})) - elif storage_options: - raise ValueError("storage_options passed with non-fsspec path") - if store.endswith(".zip"): - return ZipStore(store, mode=mode) - elif store.endswith(".n5"): - from zarr.v2.n5 import N5Store - - return N5Store(store) - else: - return DirectoryStore(store) - else: - store = Store._ensure_store(store) - return store - - -def rmdir(store: StoreLike, path: Path = None): - """Remove all items under the given path. If `store` provides a `rmdir` method, - this will be called, otherwise will fall back to implementation via the - `Store` interface.""" - path = normalize_storage_path(path) - if hasattr(store, "rmdir") and store.is_erasable(): # type: ignore - # pass through - store.rmdir(path) - else: - # slow version, delete one key at a time - _rmdir_from_keys(store, path) - - -def rename(store: Store, src_path: Path, dst_path: Path): - """Rename all items under the given path. If `store` provides a `rename` method, - this will be called, otherwise will fall back to implementation via the - `Store` interface.""" - src_path = normalize_storage_path(src_path) - dst_path = normalize_storage_path(dst_path) - if hasattr(store, "rename"): - # pass through - store.rename(src_path, dst_path) - else: - # slow version, delete one key at a time - _rename_from_keys(store, src_path, dst_path) - - -def listdir(store: BaseStore, path: Path = None): - """Obtain a directory listing for the given path. If `store` provides a `listdir` - method, this will be called, otherwise will fall back to implementation via the - `MutableMapping` interface.""" - path = normalize_storage_path(path) - if hasattr(store, "listdir"): - # pass through - return store.listdir(path) - else: - # slow version, iterate through all keys - warnings.warn( - f"Store {store} has no `listdir` method. From zarr 2.9 onwards " - "may want to inherit from `Store`.", - stacklevel=2, - ) - return _listdir_from_keys(store, path) - - -def _getsize(store: BaseStore, path: Path = None) -> int: - # compute from size of values - if isinstance(path, str) and path in store: - v = store[path] - size = buffer_size(v) - else: - path = "" if path is None else normalize_storage_path(path) - size = 0 - - members = listdir(store, path) - prefix = _path_to_prefix(path) - members = [prefix + k for k in members] - for k in members: - try: - v = store[k] - except KeyError: - pass - else: - try: - size += buffer_size(v) - except TypeError: - return -1 - return size - - -def getsize(store: BaseStore, path: Path = None) -> int: - """Compute size of stored items for a given path. If `store` provides a `getsize` - method, this will be called, otherwise will return -1.""" - if hasattr(store, "getsize"): - # pass through - path = normalize_storage_path(path) - return store.getsize(path) - elif isinstance(store, MutableMapping): - return _getsize(store, path) - else: - return -1 - - -def _require_parent_group( - path: Optional[str], - store: StoreLike, - chunk_store: Optional[StoreLike], - overwrite: bool, -): - # assume path is normalized - if path: - segments = path.split("/") - for i in range(len(segments)): - p = "/".join(segments[:i]) - if contains_array(store, p): - _init_group_metadata(store, path=p, chunk_store=chunk_store, overwrite=overwrite) - elif not contains_group(store, p): - _init_group_metadata(store, path=p, chunk_store=chunk_store) - - -def init_array( - store: StoreLike, - shape: Union[int, Tuple[int, ...]], - chunks: Union[bool, int, Tuple[int, ...]] = True, - dtype=None, - compressor="default", - fill_value=None, - order: str = "C", - overwrite: bool = False, - path: Optional[Path] = None, - chunk_store: Optional[StoreLike] = None, - filters=None, - object_codec=None, - dimension_separator=None, - storage_transformers=(), -): - """Initialize an array store with the given configuration. Note that this is a low-level - function and there should be no need to call this directly from user code. - - Parameters - ---------- - store : Store - A mapping that supports string keys and bytes-like values. - shape : int or tuple of ints - Array shape. - chunks : bool, int or tuple of ints, optional - Chunk shape. If True, will be guessed from `shape` and `dtype`. If - False, will be set to `shape`, i.e., single chunk for the whole array. - dtype : string or dtype, optional - NumPy dtype. - compressor : Codec, optional - Primary compressor. - fill_value : object - Default value to use for uninitialized portions of the array. - order : {'C', 'F'}, optional - Memory layout to be used within each chunk. - overwrite : bool, optional - If True, erase all data in `store` prior to initialisation. - path : string, bytes, optional - Path under which array is stored. - chunk_store : Store, optional - Separate storage for chunks. If not provided, `store` will be used - for storage of both chunks and metadata. - filters : sequence, optional - Sequence of filters to use to encode chunk data prior to compression. - object_codec : Codec, optional - A codec to encode object arrays, only needed if dtype=object. - dimension_separator : {'.', '/'}, optional - Separator placed between the dimensions of a chunk. - - Examples - -------- - Initialize an array store:: - - >>> from zarr.v2.storage import init_array, KVStore - >>> store = KVStore(dict()) - >>> init_array(store, shape=(10000, 10000), chunks=(1000, 1000)) - >>> sorted(store.keys()) - ['.zarray'] - - Array metadata is stored as JSON:: - - >>> print(store['.zarray'].decode()) - { - "chunks": [ - 1000, - 1000 - ], - "compressor": { - "blocksize": 0, - "clevel": 5, - "cname": "lz4", - "id": "blosc", - "shuffle": 1 - }, - "dtype": ">> store = KVStore(dict()) - >>> init_array(store, shape=100000000, chunks=1000000, dtype='i1', path='foo') - >>> sorted(store.keys()) - ['.zgroup', 'foo/.zarray'] - >>> print(store['foo/.zarray'].decode()) - { - "chunks": [ - 1000000 - ], - "compressor": { - "blocksize": 0, - "clevel": 5, - "cname": "lz4", - "id": "blosc", - "shuffle": 1 - }, - "dtype": "|i1", - "fill_value": null, - "filters": null, - "order": "C", - "shape": [ - 100000000 - ], - "zarr_format": 2 - } - - Notes - ----- - The initialisation process involves normalising all array metadata, encoding - as JSON and storing under the '.zarray' key. - - """ - - # normalize path - path = normalize_storage_path(path) - - # ensure parent group initialized - - _require_parent_group(path, store=store, chunk_store=chunk_store, overwrite=overwrite) - - if not compressor: - # compatibility with legacy tests using compressor=[] - compressor = None - _init_array_metadata( - store, - shape=shape, - chunks=chunks, - dtype=dtype, - compressor=compressor, - fill_value=fill_value, - order=order, - overwrite=overwrite, - path=path, - chunk_store=chunk_store, - filters=filters, - object_codec=object_codec, - dimension_separator=dimension_separator, - storage_transformers=storage_transformers, - ) - - -def _init_array_metadata( - store: StoreLike, - shape, - chunks=None, - dtype=None, - compressor="default", - fill_value=None, - order="C", - overwrite=False, - path: Optional[str] = None, - chunk_store: Optional[StoreLike] = None, - filters=None, - object_codec=None, - dimension_separator=None, - storage_transformers=(), -): - path = normalize_storage_path(path) - - # guard conditions - if overwrite: - # attempt to delete any pre-existing array in store - rmdir(store, path) - if chunk_store is not None: - rmdir(chunk_store, path) - - if not overwrite: - if contains_array(store, path): - raise ContainsArrayError(path) - if contains_group(store, path, explicit_only=False): - raise ContainsGroupError(path) - - # normalize metadata - dtype, object_codec = normalize_dtype(dtype, object_codec) - shape = normalize_shape(shape) + dtype.shape - dtype = dtype.base - chunks = normalize_chunks(chunks, shape, dtype.itemsize) - order = normalize_order(order) - fill_value = normalize_fill_value(fill_value, dtype) - - # optional array metadata - if dimension_separator is None: - dimension_separator = getattr(store, "_dimension_separator", None) - dimension_separator = normalize_dimension_separator(dimension_separator) - - # compressor prep - if shape == (): - # no point in compressing a 0-dimensional array, only a single value - compressor = None - elif compressor == "none": - # compatibility - compressor = None - elif compressor == "default": - compressor = default_compressor - - # obtain compressor config - compressor_config = None - if compressor: - try: - compressor_config = compressor.get_config() - except AttributeError as e: - raise BadCompressorError(compressor) from e - - # obtain filters config - if filters: - # TODO: filters was removed from the metadata in v3 - # raise error here if store_version > 2? - filters_config = [f.get_config() for f in filters] - else: - filters_config = [] - - # deal with object encoding - if dtype.hasobject: - if object_codec is None: - if not filters: - # there are no filters so we can be sure there is no object codec - raise ValueError("missing object_codec for object array") - else: - # one of the filters may be an object codec, issue a warning rather - # than raise an error to maintain backwards-compatibility - warnings.warn( - "missing object_codec for object array; this will raise a " - "ValueError in version 3.0", - FutureWarning, - ) - else: - filters_config.insert(0, object_codec.get_config()) - elif object_codec is not None: - warnings.warn("an object_codec is only needed for object arrays") - - # use null to indicate no filters - if not filters_config: - filters_config = None # type: ignore - - # initialize metadata - _compressor = compressor_config - meta = dict( - shape=shape, - compressor=_compressor, - fill_value=fill_value, - dimension_separator=dimension_separator, - ) - - meta.update(dict(chunks=chunks, dtype=dtype, order=order, filters=filters_config)) - assert not storage_transformers - - key = _prefix_to_array_key(store, _path_to_prefix(path)) - if hasattr(store, "_metadata_class"): - store[key] = store._metadata_class.encode_array_metadata(meta) - else: - store[key] = encode_array_metadata(meta) - - -# backwards compatibility -init_store = init_array - - -def init_group( - store: StoreLike, - overwrite: bool = False, - path: Path = None, - chunk_store: Optional[StoreLike] = None, -): - """Initialize a group store. Note that this is a low-level function and there should be no - need to call this directly from user code. - - Parameters - ---------- - store : Store - A mapping that supports string keys and byte sequence values. - overwrite : bool, optional - If True, erase all data in `store` prior to initialisation. - path : string, optional - Path under which array is stored. - chunk_store : Store, optional - Separate storage for chunks. If not provided, `store` will be used - for storage of both chunks and metadata. - - """ - - # normalize path - path = normalize_storage_path(path) - - _require_parent_group(path, store=store, chunk_store=chunk_store, overwrite=overwrite) - - # initialise metadata - _init_group_metadata(store=store, overwrite=overwrite, path=path, chunk_store=chunk_store) - - -def _init_group_metadata( - store: StoreLike, - overwrite: Optional[bool] = False, - path: Optional[str] = None, - chunk_store: Optional[StoreLike] = None, -): - path = normalize_storage_path(path) - - # guard conditions - if overwrite: - # attempt to delete any pre-existing items in store - rmdir(store, path) - if chunk_store is not None: - rmdir(chunk_store, path) - - if not overwrite: - if contains_array(store, path): - raise ContainsArrayError(path) - elif contains_group(store, path): - raise ContainsGroupError(path) - - # initialize metadata - # N.B., currently no metadata properties are needed, however there may - # be in future - meta: dict[str, Any] = {} - key = _prefix_to_group_key(store, _path_to_prefix(path)) - if hasattr(store, "_metadata_class"): - store[key] = store._metadata_class.encode_group_metadata(meta) - else: - store[key] = encode_group_metadata(meta) - - -def _dict_store_keys(d: dict[str, Any], prefix="", cls=dict): - for k in d.keys(): - v = d[k] - if isinstance(v, cls): - yield from _dict_store_keys(v, prefix + k + "/", cls) - else: - yield prefix + k - - -class KVStore(Store): - """ - This provides a default implementation of a store interface around - a mutable mapping, to avoid having to test stores for presence of methods. - - This, for most methods should just be a pass-through to the underlying KV - store which is likely to expose a MuttableMapping interface, - """ - - def __init__(self, mutablemapping): - self._mutable_mapping = mutablemapping - - def __getitem__(self, key): - return self._mutable_mapping[key] - - def __setitem__(self, key, value): - self._mutable_mapping[key] = value - - def __delitem__(self, key): - del self._mutable_mapping[key] - - def __contains__(self, key): - return key in self._mutable_mapping - - def get(self, key, default=None): - return self._mutable_mapping.get(key, default) - - def values(self): - return self._mutable_mapping.values() - - def __iter__(self): - return iter(self._mutable_mapping) - - def __len__(self): - return len(self._mutable_mapping) - - def __repr__(self): - return f"<{self.__class__.__name__}: \n{self._mutable_mapping!r}\n at {hex(id(self))}>" - - def __eq__(self, other): - if isinstance(other, KVStore): - return self._mutable_mapping == other._mutable_mapping - else: - return NotImplemented - - -class MemoryStore(Store): - """Store class that uses a hierarchy of :class:`KVStore` objects, thus all data - will be held in main memory. - - Examples - -------- - This is the default class used when creating a group. E.g.:: - - >>> import zarr - >>> g = zarr.v2.group() - >>> type(g.store) - - - Note that the default class when creating an array is the built-in - :class:`KVStore` class, i.e.:: - - >>> z = zarr.v2.zeros(100) - >>> type(z.store) - - - Notes - ----- - Safe to write in multiple threads. - - """ - - def __init__(self, root=None, cls=dict, dimension_separator=None): - if root is None: - self.root = cls() - else: - self.root = root - self.cls = cls - self.write_mutex = Lock() - self._dimension_separator = dimension_separator - - def __getstate__(self): - return self.root, self.cls - - def __setstate__(self, state): - root, cls = state - self.__init__(root=root, cls=cls) - - def _get_parent(self, item: str): - parent = self.root - # split the item - segments = item.split("/") - # find the parent container - for k in segments[:-1]: - parent = parent[k] - if not isinstance(parent, self.cls): - raise KeyError(item) - return parent, segments[-1] - - def _require_parent(self, item): - parent = self.root - # split the item - segments = item.split("/") - # require the parent container - for k in segments[:-1]: - try: - parent = parent[k] - except KeyError: - parent[k] = self.cls() - parent = parent[k] - else: - if not isinstance(parent, self.cls): - raise KeyError(item) - return parent, segments[-1] - - def __getitem__(self, item: str): - parent, key = self._get_parent(item) - try: - value = parent[key] - except KeyError: - raise KeyError(item) - else: - if isinstance(value, self.cls): - raise KeyError(item) - else: - return value - - def __setitem__(self, item: str, value): - with self.write_mutex: - parent, key = self._require_parent(item) - value = ensure_bytes(value) - parent[key] = value - - def __delitem__(self, item: str): - with self.write_mutex: - parent, key = self._get_parent(item) - try: - del parent[key] - except KeyError: - raise KeyError(item) - - def __contains__(self, item: str): # type: ignore[override] - try: - parent, key = self._get_parent(item) - value = parent[key] - except KeyError: - return False - else: - return not isinstance(value, self.cls) - - def __eq__(self, other): - return isinstance(other, MemoryStore) and self.root == other.root and self.cls == other.cls - - def keys(self): - yield from _dict_store_keys(self.root, cls=self.cls) - - def __iter__(self): - return self.keys() - - def __len__(self) -> int: - return sum(1 for _ in self.keys()) - - def listdir(self, path: Path = None) -> List[str]: - path = normalize_storage_path(path) - if path: - try: - parent, key = self._get_parent(path) - value = parent[key] - except KeyError: - return [] - else: - value = self.root - if isinstance(value, self.cls): - return sorted(value.keys()) - else: - return [] - - def rename(self, src_path: Path, dst_path: Path): - src_path = normalize_storage_path(src_path) - dst_path = normalize_storage_path(dst_path) - - src_parent, src_key = self._get_parent(src_path) - dst_parent, dst_key = self._require_parent(dst_path) - - dst_parent[dst_key] = src_parent.pop(src_key) - - def rmdir(self, path: Path = None): - path = normalize_storage_path(path) - if path: - try: - parent, key = self._get_parent(path) - value = parent[key] - except KeyError: - return - else: - if isinstance(value, self.cls): - del parent[key] - else: - # clear out root - self.root = self.cls() - - def getsize(self, path: Path = None): - path = normalize_storage_path(path) - - # obtain value to return size of - value = None - if path: - try: - parent, key = self._get_parent(path) - value = parent[key] - except KeyError: - pass - else: - value = self.root - - # obtain size of value - if value is None: - return 0 - - elif isinstance(value, self.cls): - # total size for directory - size = 0 - for v in value.values(): - if not isinstance(v, self.cls): - size += buffer_size(v) - return size - - else: - return buffer_size(value) - - def clear(self): - with self.write_mutex: - self.root.clear() - - -class DictStore(MemoryStore): - def __init__(self, *args, **kwargs): - warnings.warn( - "DictStore has been renamed to MemoryStore in 2.4.0 and " - "will be removed in the future. Please use MemoryStore.", - DeprecationWarning, - stacklevel=2, - ) - super().__init__(*args, **kwargs) - - -class DirectoryStore(Store): - """Storage class using directories and files on a standard file system. - - Parameters - ---------- - path : string - Location of directory to use as the root of the storage hierarchy. - normalize_keys : bool, optional - If True, all store keys will be normalized to use lower case characters - (e.g. 'foo' and 'FOO' will be treated as equivalent). This can be - useful to avoid potential discrepancies between case-sensitive and - case-insensitive file system. Default value is False. - dimension_separator : {'.', '/'}, optional - Separator placed between the dimensions of a chunk. - - Examples - -------- - Store a single array:: - - >>> import zarr - >>> store = zarr.v2.DirectoryStore('data/array.zarr') - >>> z = zarr.v2.zeros((10, 10), chunks=(5, 5), store=store, overwrite=True) - >>> z[...] = 42 - - Each chunk of the array is stored as a separate file on the file system, - i.e.:: - - >>> import os - >>> sorted(os.listdir('data/array.zarr')) - ['.zarray', '0.0', '0.1', '1.0', '1.1'] - - Store a group:: - - >>> store = zarr.v2.DirectoryStore('data/group.zarr') - >>> root = zarr.v2.group(store=store, overwrite=True) - >>> foo = root.create_group('foo') - >>> bar = foo.zeros('bar', shape=(10, 10), chunks=(5, 5)) - >>> bar[...] = 42 - - When storing a group, levels in the group hierarchy will correspond to - directories on the file system, i.e.:: - - >>> sorted(os.listdir('data/group.zarr')) - ['.zgroup', 'foo'] - >>> sorted(os.listdir('data/group.zarr/foo')) - ['.zgroup', 'bar'] - >>> sorted(os.listdir('data/group.zarr/foo/bar')) - ['.zarray', '0.0', '0.1', '1.0', '1.1'] - - Notes - ----- - Atomic writes are used, which means that data are first written to a - temporary file, then moved into place when the write is successfully - completed. Files are only held open while they are being read or written and are - closed immediately afterwards, so there is no need to manually close any files. - - Safe to write in multiple threads or processes. - - """ - - def __init__(self, path, normalize_keys=False, dimension_separator=None): - # guard conditions - path = os.path.abspath(path) - if os.path.exists(path) and not os.path.isdir(path): - raise FSPathExistNotDir(path) - - self.path = path - self.normalize_keys = normalize_keys - self._dimension_separator = dimension_separator - - def _normalize_key(self, key): - return key.lower() if self.normalize_keys else key - - @staticmethod - def _fromfile(fn): - """Read data from a file - - Parameters - ---------- - fn : str - Filepath to open and read from. - - Notes - ----- - Subclasses should overload this method to specify any custom - file reading logic. - """ - with open(fn, "rb") as f: - return f.read() - - @staticmethod - def _tofile(a, fn): - """Write data to a file - - Parameters - ---------- - a : array-like - Data to write into the file. - fn : str - Filepath to open and write to. - - Notes - ----- - Subclasses should overload this method to specify any custom - file writing logic. - """ - with open(fn, mode="wb") as f: - f.write(a) - - def __getitem__(self, key): - key = self._normalize_key(key) - filepath = os.path.join(self.path, key) - if os.path.isfile(filepath): - return self._fromfile(filepath) - else: - raise KeyError(key) - - def __setitem__(self, key, value): - key = self._normalize_key(key) - - # coerce to flat, contiguous array (ideally without copying) - value = ensure_contiguous_ndarray_like(value) - - # destination path for key - file_path = os.path.join(self.path, key) - - # ensure there is no directory in the way - if os.path.isdir(file_path): - shutil.rmtree(file_path) - - # ensure containing directory exists - dir_path, file_name = os.path.split(file_path) - if os.path.isfile(dir_path): - raise KeyError(key) - if not os.path.exists(dir_path): - try: - os.makedirs(dir_path) - except OSError as e: - if e.errno != errno.EEXIST: - raise KeyError(key) - - # write to temporary file - # note we're not using tempfile.NamedTemporaryFile to avoid restrictive file permissions - temp_name = file_name + "." + uuid.uuid4().hex + ".partial" - temp_path = os.path.join(dir_path, temp_name) - try: - self._tofile(value, temp_path) - - # move temporary file into place; - # make several attempts at writing the temporary file to get past - # potential antivirus file locking issues - retry_call(os.replace, (temp_path, file_path), exceptions=(PermissionError,)) - - finally: - # clean up if temp file still exists for whatever reason - if os.path.exists(temp_path): # pragma: no cover - os.remove(temp_path) - - def __delitem__(self, key): - key = self._normalize_key(key) - path = os.path.join(self.path, key) - if os.path.isfile(path): - os.remove(path) - elif os.path.isdir(path): - # include support for deleting directories, even though strictly - # speaking these do not exist as keys in the store - shutil.rmtree(path) - else: - raise KeyError(key) - - def __contains__(self, key): - key = self._normalize_key(key) - file_path = os.path.join(self.path, key) - return os.path.isfile(file_path) - - def __eq__(self, other): - return isinstance(other, DirectoryStore) and self.path == other.path - - def keys(self): - if os.path.exists(self.path): - yield from self._keys_fast(self.path) - - @staticmethod - def _keys_fast(path, walker=os.walk): - for dirpath, _, filenames in walker(path): - dirpath = os.path.relpath(dirpath, path) - if dirpath == os.curdir: - for f in filenames: - yield f - else: - dirpath = dirpath.replace("\\", "/") - for f in filenames: - yield "/".join((dirpath, f)) - - def __iter__(self): - return self.keys() - - def __len__(self): - return sum(1 for _ in self.keys()) - - def dir_path(self, path=None): - store_path = normalize_storage_path(path) - dir_path = self.path - if store_path: - dir_path = os.path.join(dir_path, store_path) - return dir_path - - def listdir(self, path=None): - return ( - self._nested_listdir(path) - if self._dimension_separator == "/" - else self._flat_listdir(path) - ) - - def _flat_listdir(self, path=None): - dir_path = self.dir_path(path) - if os.path.isdir(dir_path): - return sorted(os.listdir(dir_path)) - else: - return [] - - def _nested_listdir(self, path=None): - children = self._flat_listdir(path=path) - if array_meta_key in children: - # special handling of directories containing an array to map nested chunk - # keys back to standard chunk keys - new_children = [] - root_path = self.dir_path(path) - for entry in children: - entry_path = os.path.join(root_path, entry) - if _prog_number.match(entry) and os.path.isdir(entry_path): - for dir_path, _, file_names in os.walk(entry_path): - for file_name in file_names: - file_path = os.path.join(dir_path, file_name) - rel_path = file_path.split(root_path + os.path.sep)[1] - new_children.append( - rel_path.replace(os.path.sep, self._dimension_separator or ".") - ) - else: - new_children.append(entry) - return sorted(new_children) - else: - return children - - def rename(self, src_path, dst_path): - store_src_path = normalize_storage_path(src_path) - store_dst_path = normalize_storage_path(dst_path) - - dir_path = self.path - - src_path = os.path.join(dir_path, store_src_path) - dst_path = os.path.join(dir_path, store_dst_path) - - os.renames(src_path, dst_path) - - def rmdir(self, path=None): - store_path = normalize_storage_path(path) - dir_path = self.path - if store_path: - dir_path = os.path.join(dir_path, store_path) - if os.path.isdir(dir_path): - shutil.rmtree(dir_path) - - def getsize(self, path=None): - store_path = normalize_storage_path(path) - fs_path = self.path - if store_path: - fs_path = os.path.join(fs_path, store_path) - if os.path.isfile(fs_path): - return os.path.getsize(fs_path) - elif os.path.isdir(fs_path): - size = 0 - for child in scandir(fs_path): - if child.is_file(): - size += child.stat().st_size - return size - else: - return 0 - - def clear(self): - shutil.rmtree(self.path) - - -def atexit_rmtree(path, isdir=os.path.isdir, rmtree=shutil.rmtree): # pragma: no cover - """Ensure directory removal at interpreter exit.""" - if isdir(path): - rmtree(path) - - -# noinspection PyShadowingNames -def atexit_rmglob( - path, - glob=glob.glob, - isdir=os.path.isdir, - isfile=os.path.isfile, - remove=os.remove, - rmtree=shutil.rmtree, -): # pragma: no cover - """Ensure removal of multiple files at interpreter exit.""" - for p in glob(path): - if isfile(p): - remove(p) - elif isdir(p): - rmtree(p) - - -class FSStore(Store): - """Wraps an fsspec.FSMap to give access to arbitrary filesystems - - Requires that ``fsspec`` is installed, as well as any additional - requirements for the protocol chosen. - - Parameters - ---------- - url : str - The destination to map. If no fs is provided, should include protocol - and path, like "s3://bucket/root". If an fs is provided, can be a path - within that filesystem, like "bucket/root" - normalize_keys : bool - key_separator : str - public API for accessing dimension_separator. Never `None` - See dimension_separator for more information. - mode : str - "w" for writable, "r" for read-only - exceptions : list of Exception subclasses - When accessing data, any of these exceptions will be treated - as a missing key - dimension_separator : {'.', '/'}, optional - Separator placed between the dimensions of a chunk. - fs : fsspec.spec.AbstractFileSystem, optional - An existing filesystem to use for the store. - check : bool, optional - If True, performs a touch at the root location, to check for write access. - Passed to `fsspec.mapping.FSMap` constructor. - create : bool, optional - If True, performs a mkdir at the rool location. - Passed to `fsspec.mapping.FSMap` constructor. - missing_exceptions : sequence of Exceptions, optional - Exceptions classes to associate with missing files. - Passed to `fsspec.mapping.FSMap` constructor. - storage_options : passed to the fsspec implementation. Cannot be used - together with fs. - """ - - _array_meta_key = array_meta_key - _group_meta_key = group_meta_key - _attrs_key = attrs_key - - def __init__( - self, - url, - normalize_keys=False, - key_separator=None, - mode="w", - exceptions=(KeyError, PermissionError, IOError), - dimension_separator=None, - fs=None, - check=False, - create=False, - missing_exceptions=None, - **storage_options, - ): - if not self._fsspec_installed(): # pragma: no cover - raise ImportError("`fsspec` is required to use zarr's FSStore") - import fsspec - - mapper_options = {"check": check, "create": create} - # https://github.com/zarr-developers/zarr-python/pull/911#discussion_r841926292 - # Some fsspec implementations don't accept missing_exceptions. - # This is a workaround to avoid passing it in the most common scenarios. - # Remove this and add missing_exceptions to mapper_options when fsspec is released. - if missing_exceptions is not None: - mapper_options["missing_exceptions"] = missing_exceptions # pragma: no cover - - if fs is None: - protocol, _ = fsspec.core.split_protocol(url) - # set auto_mkdir to True for local file system - if protocol in (None, "file") and not storage_options.get("auto_mkdir"): - storage_options["auto_mkdir"] = True - self.map = fsspec.get_mapper(url, **{**mapper_options, **storage_options}) - self.fs = self.map.fs # for direct operations - self.path = self.fs._strip_protocol(url) - else: - if storage_options: - raise ValueError("Cannot specify both fs and storage_options") - self.fs = fs - self.path = self.fs._strip_protocol(url) - self.map = self.fs.get_mapper(self.path, **mapper_options) - - self.normalize_keys = normalize_keys - self.mode = mode - self.exceptions = exceptions - # For backwards compatibility. Guaranteed to be non-None - if key_separator is not None: - dimension_separator = key_separator - - self.key_separator = dimension_separator - self._default_key_separator() - - # Pass attributes to array creation - self._dimension_separator = dimension_separator - - def _default_key_separator(self): - if self.key_separator is None: - self.key_separator = "." - - def _normalize_key(self, key): - key = normalize_storage_path(key).lstrip("/") - if key: - *bits, end = key.split("/") - - if end not in (self._array_meta_key, self._group_meta_key, self._attrs_key): - end = end.replace(".", self.key_separator) - key = "/".join(bits + [end]) - - return key.lower() if self.normalize_keys else key - - def getitems( - self, keys: Sequence[str], *, contexts: Mapping[str, Context] - ) -> Mapping[str, Any]: - keys_transformed = [self._normalize_key(key) for key in keys] - results = self.map.getitems(keys_transformed, on_error="omit") - # The function calling this method may not recognize the transformed keys - # So we send the values returned by self.map.getitems back into the original key space. - return {keys[keys_transformed.index(rk)]: rv for rk, rv in results.items()} - - def __getitem__(self, key): - key = self._normalize_key(key) - try: - return self.map[key] - except self.exceptions as e: - raise KeyError(key) from e - - def setitems(self, values): - if self.mode == "r": - raise ReadOnlyError - - # Normalize keys and make sure the values are bytes - values = { - self._normalize_key(key): ensure_contiguous_ndarray_or_bytes(val) - for key, val in values.items() - } - self.map.setitems(values) - - def __setitem__(self, key, value): - if self.mode == "r": - raise ReadOnlyError - key = self._normalize_key(key) - value = ensure_contiguous_ndarray_or_bytes(value) - path = self.dir_path(key) - try: - if self.fs.isdir(path): - self.fs.rm(path, recursive=True) - self.map[key] = value - self.fs.invalidate_cache(self.fs._parent(path)) - except self.exceptions as e: - raise KeyError(key) from e - - def __delitem__(self, key): - if self.mode == "r": - raise ReadOnlyError - key = self._normalize_key(key) - path = self.dir_path(key) - if self.fs.isdir(path): - self.fs.rm(path, recursive=True) - else: - del self.map[key] - - def delitems(self, keys): - if self.mode == "r": - raise ReadOnlyError - # only remove the keys that exist in the store - nkeys = [self._normalize_key(key) for key in keys if key in self] - # rm errors if you pass an empty collection - if len(nkeys) > 0: - self.map.delitems(nkeys) - - def __contains__(self, key): - key = self._normalize_key(key) - return key in self.map - - def __eq__(self, other): - return type(self) is type(other) and self.map == other.map and self.mode == other.mode - - def keys(self): - return iter(self.map) - - def __iter__(self): - return self.keys() - - def __len__(self): - return len(list(self.keys())) - - def dir_path(self, path=None): - store_path = normalize_storage_path(path) - return self.map._key_to_str(store_path) - - def listdir(self, path=None): - dir_path = self.dir_path(path) - try: - children = sorted( - p.rstrip("/").rsplit("/", 1)[-1] for p in self.fs.ls(dir_path, detail=False) - ) - if self.key_separator != "/": - return children - else: - if self._array_meta_key in children: - # special handling of directories containing an array to map nested chunk - # keys back to standard chunk keys - new_children = [] - root_path = self.dir_path(path) - for entry in children: - entry_path = os.path.join(root_path, entry) - if _prog_number.match(entry) and self.fs.isdir(entry_path): - for file_name in self.fs.find(entry_path): - file_path = os.path.join(dir_path, file_name) - rel_path = file_path.split(root_path)[1] - rel_path = rel_path.lstrip("/") - new_children.append(rel_path.replace("/", ".")) - else: - new_children.append(entry) - return sorted(new_children) - else: - return children - except OSError: - return [] - - def rmdir(self, path=None): - if self.mode == "r": - raise ReadOnlyError - store_path = self.dir_path(path) - if self.fs.isdir(store_path): - self.fs.rm(store_path, recursive=True) - - def getsize(self, path=None): - store_path = self.dir_path(path) - return self.fs.du(store_path, True, True) - - def clear(self): - if self.mode == "r": - raise ReadOnlyError - self.map.clear() - - @classmethod - def _fsspec_installed(cls): - """Returns true if fsspec is installed""" - import importlib.util - - return importlib.util.find_spec("fsspec") is not None - - -class TempStore(DirectoryStore): - """Directory store using a temporary directory for storage. - - Parameters - ---------- - suffix : string, optional - Suffix for the temporary directory name. - prefix : string, optional - Prefix for the temporary directory name. - dir : string, optional - Path to parent directory in which to create temporary directory. - normalize_keys : bool, optional - If True, all store keys will be normalized to use lower case characters - (e.g. 'foo' and 'FOO' will be treated as equivalent). This can be - useful to avoid potential discrepancies between case-sensitive and - case-insensitive file system. Default value is False. - dimension_separator : {'.', '/'}, optional - Separator placed between the dimensions of a chunk. - """ - - # noinspection PyShadowingBuiltins - def __init__( - self, suffix="", prefix="zarr", dir=None, normalize_keys=False, dimension_separator=None - ): - path = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir) - atexit.register(atexit_rmtree, path) - super().__init__(path, normalize_keys=normalize_keys) - - -_prog_ckey = re.compile(r"^(\d+)(\.\d+)+$") -_prog_number = re.compile(r"^\d+$") - - -class NestedDirectoryStore(DirectoryStore): - """Storage class using directories and files on a standard file system, with - special handling for chunk keys so that chunk files for multidimensional - arrays are stored in a nested directory tree. - - Parameters - ---------- - path : string - Location of directory to use as the root of the storage hierarchy. - normalize_keys : bool, optional - If True, all store keys will be normalized to use lower case characters - (e.g. 'foo' and 'FOO' will be treated as equivalent). This can be - useful to avoid potential discrepancies between case-sensitive and - case-insensitive file system. Default value is False. - dimension_separator : {'/'}, optional - Separator placed between the dimensions of a chunk. - Only supports "/" unlike other implementations. - - Examples - -------- - Store a single array:: - - >>> import zarr - >>> store = zarr.v2.NestedDirectoryStore('data/array.zarr') - >>> z = zarr.v2.zeros((10, 10), chunks=(5, 5), store=store, overwrite=True) - >>> z[...] = 42 - - Each chunk of the array is stored as a separate file on the file system, - note the multiple directory levels used for the chunk files:: - - >>> import os - >>> sorted(os.listdir('data/array.zarr')) - ['.zarray', '0', '1'] - >>> sorted(os.listdir('data/array.zarr/0')) - ['0', '1'] - >>> sorted(os.listdir('data/array.zarr/1')) - ['0', '1'] - - Store a group:: - - >>> store = zarr.v2.NestedDirectoryStore('data/group.zarr') - >>> root = zarr.v2.group(store=store, overwrite=True) - >>> foo = root.create_group('foo') - >>> bar = foo.zeros('bar', shape=(10, 10), chunks=(5, 5)) - >>> bar[...] = 42 - - When storing a group, levels in the group hierarchy will correspond to - directories on the file system, i.e.:: - - >>> sorted(os.listdir('data/group.zarr')) - ['.zgroup', 'foo'] - >>> sorted(os.listdir('data/group.zarr/foo')) - ['.zgroup', 'bar'] - >>> sorted(os.listdir('data/group.zarr/foo/bar')) - ['.zarray', '0', '1'] - >>> sorted(os.listdir('data/group.zarr/foo/bar/0')) - ['0', '1'] - >>> sorted(os.listdir('data/group.zarr/foo/bar/1')) - ['0', '1'] - - Notes - ----- - The :class:`DirectoryStore` class stores all chunk files for an array - together in a single directory. On some file systems, the potentially large - number of files in a single directory can cause performance issues. The - :class:`NestedDirectoryStore` class provides an alternative where chunk - files for multidimensional arrays will be organised into a directory - hierarchy, thus reducing the number of files in any one directory. - - Safe to write in multiple threads or processes. - - """ - - def __init__(self, path, normalize_keys=False, dimension_separator="/"): - super().__init__(path, normalize_keys=normalize_keys) - if dimension_separator is None: - dimension_separator = "/" - elif dimension_separator != "/": - raise ValueError("NestedDirectoryStore only supports '/' as dimension_separator") - self._dimension_separator = dimension_separator - - def __eq__(self, other): - return isinstance(other, NestedDirectoryStore) and self.path == other.path - - -# noinspection PyPep8Naming -class ZipStore(Store): - """Storage class using a Zip file. - - Parameters - ---------- - path : string - Location of file. - compression : integer, optional - Compression method to use when writing to the archive. - allowZip64 : bool, optional - If True (the default) will create ZIP files that use the ZIP64 - extensions when the zipfile is larger than 2 GiB. If False - will raise an exception when the ZIP file would require ZIP64 - extensions. - mode : string, optional - One of 'r' to read an existing file, 'w' to truncate and write a new - file, 'a' to append to an existing file, or 'x' to exclusively create - and write a new file. - dimension_separator : {'.', '/'}, optional - Separator placed between the dimensions of a chunk. - - Examples - -------- - Store a single array:: - - >>> import zarr - >>> store = zarr.v2.ZipStore('data/array.zip', mode='w') - >>> z = zarr.v2.zeros((10, 10), chunks=(5, 5), store=store) - >>> z[...] = 42 - >>> store.close() # don't forget to call this when you're done - - Store a group:: - - >>> store = zarr.v2.ZipStore('data/group.zip', mode='w') - >>> root = zarr.v2.group(store=store) - >>> foo = root.create_group('foo') - >>> bar = foo.zeros('bar', shape=(10, 10), chunks=(5, 5)) - >>> bar[...] = 42 - >>> store.close() # don't forget to call this when you're done - - After modifying a ZipStore, the ``close()`` method must be called, otherwise - essential data will not be written to the underlying Zip file. The ZipStore - class also supports the context manager protocol, which ensures the ``close()`` - method is called on leaving the context, e.g.:: - - >>> with zarr.v2.ZipStore('data/array.zip', mode='w') as store: - ... z = zarr.v2.zeros((10, 10), chunks=(5, 5), store=store) - ... z[...] = 42 - ... # no need to call store.close() - - Notes - ----- - Each chunk of an array is stored as a separate entry in the Zip file. Note - that Zip files do not provide any way to remove or replace existing entries. - If an attempt is made to replace an entry, then a warning is generated by - the Python standard library about a duplicate Zip file entry. This can be - triggered if you attempt to write data to a Zarr array more than once, - e.g.:: - - >>> store = zarr.v2.ZipStore('data/example.zip', mode='w') - >>> z = zarr.v2.zeros(100, chunks=10, store=store) - >>> # first write OK - ... z[...] = 42 - >>> # second write generates warnings - ... z[...] = 42 # doctest: +SKIP - >>> store.close() - - This can also happen in a more subtle situation, where data are written only - once to a Zarr array, but the write operations are not aligned with chunk - boundaries, e.g.:: - - >>> store = zarr.v2.ZipStore('data/example.zip', mode='w') - >>> z = zarr.v2.zeros(100, chunks=10, store=store) - >>> z[5:15] = 42 - >>> # write overlaps chunk previously written, generates warnings - ... z[15:25] = 42 # doctest: +SKIP - - To avoid creating duplicate entries, only write data once, and align writes - with chunk boundaries. This alignment is done automatically if you call - ``z[...] = ...`` or create an array from existing data via :func:`zarr.v2.array`. - - Alternatively, use a :class:`DirectoryStore` when writing the data, then - manually Zip the directory and use the Zip file for subsequent reads. - Take note that the files in the Zip file must be relative to the root of the - Zarr archive. You may find it easier to create such a Zip file with ``7z``, e.g.:: - - 7z a -tzip archive.zarr.v2.zip archive.zarr/. - - Safe to write in multiple threads but not in multiple processes. - - """ - - _erasable = False - - def __init__( - self, - path, - compression=zipfile.ZIP_STORED, - allowZip64=True, - mode="a", - dimension_separator=None, - ): - # store properties - path = os.path.abspath(path) - self.path = path - self.compression = compression - self.allowZip64 = allowZip64 - self.mode = mode - self._dimension_separator = dimension_separator - - # Current understanding is that zipfile module in stdlib is not thread-safe, - # and so locking is required for both read and write. However, this has not - # been investigated in detail, perhaps no lock is needed if mode='r'. - self.mutex = RLock() - - # open zip file - self.zf = zipfile.ZipFile(path, mode=mode, compression=compression, allowZip64=allowZip64) - - def __getstate__(self): - self.flush() - return self.path, self.compression, self.allowZip64, self.mode - - def __setstate__(self, state): - path, compression, allowZip64, mode = state - # if initially opened with mode 'w' or 'x', re-open in mode 'a' so file doesn't - # get clobbered - if mode in "wx": - mode = "a" - self.__init__(path=path, compression=compression, allowZip64=allowZip64, mode=mode) - - def close(self): - """Closes the underlying zip file, ensuring all records are written.""" - with self.mutex: - self.zf.close() - - def flush(self): - """Closes the underlying zip file, ensuring all records are written, - then re-opens the file for further modifications.""" - if self.mode != "r": - with self.mutex: - self.zf.close() - # N.B., re-open with mode 'a' regardless of initial mode so we don't wipe - # what's been written - self.zf = zipfile.ZipFile( - self.path, mode="a", compression=self.compression, allowZip64=self.allowZip64 - ) - - def __enter__(self): - return self - - def __exit__(self, *args): - self.close() - - def __getitem__(self, key): - with self.mutex: - with self.zf.open(key) as f: # will raise KeyError - return f.read() - - def __setitem__(self, key, value): - if self.mode == "r": - raise ReadOnlyError - value = ensure_contiguous_ndarray_like(value).view("u1") - with self.mutex: - # writestr(key, value) writes with default permissions from - # zipfile (600) that are too restrictive, build ZipInfo for - # the key to work around limitation - keyinfo = zipfile.ZipInfo(filename=key, date_time=time.localtime(time.time())[:6]) - keyinfo.compress_type = self.compression - if keyinfo.filename[-1] == os.sep: - keyinfo.external_attr = 0o40775 << 16 # drwxrwxr-x - keyinfo.external_attr |= 0x10 # MS-DOS directory flag - else: - keyinfo.external_attr = 0o644 << 16 # ?rw-r--r-- - - self.zf.writestr(keyinfo, value) - - def __delitem__(self, key): - raise NotImplementedError - - def __eq__(self, other): - return ( - isinstance(other, ZipStore) - and self.path == other.path - and self.compression == other.compression - and self.allowZip64 == other.allowZip64 - ) - - def keylist(self): - with self.mutex: - return sorted(self.zf.namelist()) - - def keys(self): - yield from self.keylist() - - def __iter__(self): - return self.keys() - - def __len__(self): - return sum(1 for _ in self.keys()) - - def __contains__(self, key): - try: - with self.mutex: - self.zf.getinfo(key) - except KeyError: - return False - else: - return True - - def listdir(self, path=None): - path = normalize_storage_path(path) - return _listdir_from_keys(self, path) - - def getsize(self, path=None): - path = normalize_storage_path(path) - with self.mutex: - children = self.listdir(path) - if children: - size = 0 - for child in children: - if path: - name = path + "/" + child - else: - name = child - try: - info = self.zf.getinfo(name) - except KeyError: - pass - else: - size += info.compress_size - return size - elif path: - try: - info = self.zf.getinfo(path) - return info.compress_size - except KeyError: - return 0 - else: - return 0 - - def clear(self): - if self.mode == "r": - raise ReadOnlyError - with self.mutex: - self.close() - os.remove(self.path) - self.zf = zipfile.ZipFile( - self.path, mode=self.mode, compression=self.compression, allowZip64=self.allowZip64 - ) - - -def migrate_1to2(store): - """Migrate array metadata in `store` from Zarr format version 1 to - version 2. - - Parameters - ---------- - store : Store - Store to be migrated. - - Notes - ----- - Version 1 did not support hierarchies, so this migration function will - look for a single array in `store` and migrate the array metadata to - version 2. - - """ - - # migrate metadata - from zarr.v2 import meta_v1 - - meta = meta_v1.decode_metadata(store["meta"]) - del store["meta"] - - # add empty filters - meta["filters"] = None - - # migration compression metadata - compression = meta["compression"] - if compression is None or compression == "none": - compressor_config = None - else: - compression_opts = meta["compression_opts"] - codec_cls = codec_registry[compression] - if isinstance(compression_opts, dict): - compressor = codec_cls(**compression_opts) - else: - compressor = codec_cls(compression_opts) - compressor_config = compressor.get_config() - meta["compressor"] = compressor_config - del meta["compression"] - del meta["compression_opts"] - - # store migrated metadata - if hasattr(store, "_metadata_class"): - store[array_meta_key] = store._metadata_class.encode_array_metadata(meta) - else: - store[array_meta_key] = encode_array_metadata(meta) - - # migrate user attributes - store[attrs_key] = store["attrs"] - del store["attrs"] - - -# noinspection PyShadowingBuiltins -class DBMStore(Store): - """Storage class using a DBM-style database. - - Parameters - ---------- - path : string - Location of database file. - flag : string, optional - Flags for opening the database file. - mode : int - File mode used if a new file is created. - open : function, optional - Function to open the database file. If not provided, :func:`dbm.open` will be - used on Python 3, and :func:`anydbm.open` will be used on Python 2. - write_lock: bool, optional - Use a lock to prevent concurrent writes from multiple threads (True by default). - dimension_separator : {'.', '/'}, optional - Separator placed between the dimensions of a chunk.e - **open_kwargs - Keyword arguments to pass the `open` function. - - Examples - -------- - Store a single array:: - - >>> import zarr - >>> store = zarr.v2.DBMStore('data/array.db') - >>> z = zarr.v2.zeros((10, 10), chunks=(5, 5), store=store, overwrite=True) - >>> z[...] = 42 - >>> store.close() # don't forget to call this when you're done - - Store a group:: - - >>> store = zarr.v2.DBMStore('data/group.db') - >>> root = zarr.v2.group(store=store, overwrite=True) - >>> foo = root.create_group('foo') - >>> bar = foo.zeros('bar', shape=(10, 10), chunks=(5, 5)) - >>> bar[...] = 42 - >>> store.close() # don't forget to call this when you're done - - After modifying a DBMStore, the ``close()`` method must be called, otherwise - essential data may not be written to the underlying database file. The - DBMStore class also supports the context manager protocol, which ensures the - ``close()`` method is called on leaving the context, e.g.:: - - >>> with zarr.v2.DBMStore('data/array.db') as store: - ... z = zarr.v2.zeros((10, 10), chunks=(5, 5), store=store, overwrite=True) - ... z[...] = 42 - ... # no need to call store.close() - - A different database library can be used by passing a different function to - the `open` parameter. For example, if the `bsddb3 - `_ package is installed, a - Berkeley DB database can be used:: - - >>> import bsddb3 - >>> store = zarr.v2.DBMStore('data/array.bdb', open=bsddb3.btopen) - >>> z = zarr.v2.zeros((10, 10), chunks=(5, 5), store=store, overwrite=True) - >>> z[...] = 42 - >>> store.close() - - Notes - ----- - Please note that, by default, this class will use the Python standard - library `dbm.open` function to open the database file (or `anydbm.open` on - Python 2). There are up to three different implementations of DBM-style - databases available in any Python installation, and which one is used may - vary from one system to another. Database file formats are not compatible - between these different implementations. Also, some implementations are - more efficient than others. In particular, the "dumb" implementation will be - the fall-back on many systems, and has very poor performance for some usage - scenarios. If you want to ensure a specific implementation is used, pass the - corresponding open function, e.g., `dbm.gnu.open` to use the GNU DBM - library. - - Safe to write in multiple threads. May be safe to write in multiple processes, - depending on which DBM implementation is being used, although this has not been - tested. - - """ - - def __init__( - self, - path, - flag="c", - mode=0o666, - open=None, - write_lock=True, - dimension_separator=None, - **open_kwargs, - ): - if open is None: - import dbm - - open = dbm.open - path = os.path.abspath(path) - # noinspection PyArgumentList - self.db = open(path, flag, mode, **open_kwargs) - self.path = path - self.flag = flag - self.mode = mode - self.open = open - self.write_lock = write_lock - if write_lock: - # This may not be required as some dbm implementations manage their own - # locks, but err on the side of caution. - self.write_mutex = Lock() - else: - self.write_mutex = nolock - self.open_kwargs = open_kwargs - self._dimension_separator = dimension_separator - - def __getstate__(self): - try: - self.flush() # needed for ndbm - except Exception: - # flush may fail if db has already been closed - pass - return (self.path, self.flag, self.mode, self.open, self.write_lock, self.open_kwargs) - - def __setstate__(self, state): - path, flag, mode, open, write_lock, open_kws = state - if flag[0] == "n": - flag = "c" + flag[1:] # don't clobber an existing database - self.__init__(path=path, flag=flag, mode=mode, open=open, write_lock=write_lock, **open_kws) - - def close(self): - """Closes the underlying database file.""" - if hasattr(self.db, "close"): - with self.write_mutex: - self.db.close() - - def flush(self): - """Synchronizes data to the underlying database file.""" - if self.flag[0] != "r": - with self.write_mutex: - if hasattr(self.db, "sync"): - self.db.sync() - else: # pragma: no cover - # we don't cover this branch anymore as ndbm (oracle) is not packaged - # by conda-forge on non-mac OS: - # https://github.com/conda-forge/staged-recipes/issues/4476 - # fall-back, close and re-open, needed for ndbm - flag = self.flag - if flag[0] == "n": - flag = "c" + flag[1:] # don't clobber an existing database - self.db.close() - # noinspection PyArgumentList - self.db = self.open(self.path, flag, self.mode, **self.open_kwargs) - - def __enter__(self): - return self - - def __exit__(self, *args): - self.close() - - def __getitem__(self, key): - if isinstance(key, str): - key = key.encode("ascii") - return self.db[key] - - def __setitem__(self, key, value): - if isinstance(key, str): - key = key.encode("ascii") - value = ensure_bytes(value) - with self.write_mutex: - self.db[key] = value - - def __delitem__(self, key): - if isinstance(key, str): - key = key.encode("ascii") - with self.write_mutex: - del self.db[key] - - def __eq__(self, other): - return ( - isinstance(other, DBMStore) - and self.path == other.path - and - # allow flag and mode to differ - self.open == other.open - and self.open_kwargs == other.open_kwargs - ) - - def keys(self): - return (ensure_text(k, "ascii") for k in iter(self.db.keys())) - - def __iter__(self): - return self.keys() - - def __len__(self): - return sum(1 for _ in self.keys()) - - def __contains__(self, key): - if isinstance(key, str): - key = key.encode("ascii") - return key in self.db - - def rmdir(self, path: str = "") -> None: - path = normalize_storage_path(path) - _rmdir_from_keys(self, path) - - -class LMDBStore(Store): - """Storage class using LMDB. Requires the `lmdb `_ - package to be installed. - - - Parameters - ---------- - path : string - Location of database file. - buffers : bool, optional - If True (default) use support for buffers, which should increase performance by - reducing memory copies. - dimension_separator : {'.', '/'}, optional - Separator placed between the dimensions of a chunk. - **kwargs - Keyword arguments passed through to the `lmdb.open` function. - - Examples - -------- - Store a single array:: - - >>> import zarr - >>> store = zarr.v2.LMDBStore('data/array.mdb') - >>> z = zarr.v2.zeros((10, 10), chunks=(5, 5), store=store, overwrite=True) - >>> z[...] = 42 - >>> store.close() # don't forget to call this when you're done - - Store a group:: - - >>> store = zarr.v2.LMDBStore('data/group.mdb') - >>> root = zarr.v2.group(store=store, overwrite=True) - >>> foo = root.create_group('foo') - >>> bar = foo.zeros('bar', shape=(10, 10), chunks=(5, 5)) - >>> bar[...] = 42 - >>> store.close() # don't forget to call this when you're done - - After modifying a DBMStore, the ``close()`` method must be called, otherwise - essential data may not be written to the underlying database file. The - DBMStore class also supports the context manager protocol, which ensures the - ``close()`` method is called on leaving the context, e.g.:: - - >>> with zarr.v2.LMDBStore('data/array.mdb') as store: - ... z = zarr.v2.zeros((10, 10), chunks=(5, 5), store=store, overwrite=True) - ... z[...] = 42 - ... # no need to call store.close() - - Notes - ----- - By default writes are not immediately flushed to disk to increase performance. You - can ensure data are flushed to disk by calling the ``flush()`` or ``close()`` methods. - - Should be safe to write in multiple threads or processes due to the synchronization - support within LMDB, although writing from multiple processes has not been tested. - - """ - - def __init__(self, path, buffers=True, dimension_separator=None, **kwargs): - import lmdb - - # set default memory map size to something larger than the lmdb default, which is - # very likely to be too small for any moderate array (logic copied from zict) - map_size = 2**40 if sys.maxsize >= 2**32 else 2**28 - kwargs.setdefault("map_size", map_size) - - # don't initialize buffers to zero by default, shouldn't be necessary - kwargs.setdefault("meminit", False) - - # decide whether to use the writemap option based on the operating system's - # support for sparse files - writemap requires sparse file support otherwise - # the whole# `map_size` may be reserved up front on disk (logic copied from zict) - writemap = sys.platform.startswith("linux") - kwargs.setdefault("writemap", writemap) - - # decide options for when data are flushed to disk - choose to delay syncing - # data to filesystem, otherwise pay a large performance penalty (zict also does - # this) - kwargs.setdefault("metasync", False) - kwargs.setdefault("sync", False) - kwargs.setdefault("map_async", False) - - # set default option for number of cached transactions - max_spare_txns = multiprocessing.cpu_count() - kwargs.setdefault("max_spare_txns", max_spare_txns) - - # normalize path - path = os.path.abspath(path) - - # open database - self.db = lmdb.open(path, **kwargs) - - # store properties - self.buffers = buffers - self.path = path - self.kwargs = kwargs - self._dimension_separator = dimension_separator - - def __getstate__(self): - try: - self.flush() # just in case - except Exception: - # flush may fail if db has already been closed - pass - return self.path, self.buffers, self.kwargs - - def __setstate__(self, state): - path, buffers, kwargs = state - self.__init__(path=path, buffers=buffers, **kwargs) - - def close(self): - """Closes the underlying database.""" - self.db.close() - - def flush(self): - """Synchronizes data to the file system.""" - self.db.sync() - - def __enter__(self): - return self - - def __exit__(self, *args): - self.close() - - def __getitem__(self, key): - if isinstance(key, str): - key = key.encode("ascii") - # use the buffers option, should avoid a memory copy - with self.db.begin(buffers=self.buffers) as txn: - value = txn.get(key) - if value is None: - raise KeyError(key) - return value - - def __setitem__(self, key, value): - if isinstance(key, str): - key = key.encode("ascii") - with self.db.begin(write=True, buffers=self.buffers) as txn: - txn.put(key, value) - - def __delitem__(self, key): - if isinstance(key, str): - key = key.encode("ascii") - with self.db.begin(write=True) as txn: - if not txn.delete(key): - raise KeyError(key) - - def __contains__(self, key): - if isinstance(key, str): - key = key.encode("ascii") - with self.db.begin(buffers=self.buffers) as txn: - with txn.cursor() as cursor: - return cursor.set_key(key) - - def items(self): - with self.db.begin(buffers=self.buffers) as txn: - with txn.cursor() as cursor: - for k, v in cursor.iternext(keys=True, values=True): - yield ensure_text(k, "ascii"), v - - def keys(self): - with self.db.begin(buffers=self.buffers) as txn: - with txn.cursor() as cursor: - for k in cursor.iternext(keys=True, values=False): - yield ensure_text(k, "ascii") - - def values(self): - with self.db.begin(buffers=self.buffers) as txn: - with txn.cursor() as cursor: - yield from cursor.iternext(keys=False, values=True) - - def __iter__(self): - return self.keys() - - def __len__(self): - return self.db.stat()["entries"] - - -class LRUStoreCache(Store): - """Storage class that implements a least-recently-used (LRU) cache layer over - some other store. Intended primarily for use with stores that can be slow to - access, e.g., remote stores that require network communication to store and - retrieve data. - - Parameters - ---------- - store : Store - The store containing the actual data to be cached. - max_size : int - The maximum size that the cache may grow to, in number of bytes. Provide `None` - if you would like the cache to have unlimited size. - - Examples - -------- - The example below wraps an S3 store with an LRU cache:: - - >>> import s3fs - >>> import zarr - >>> s3 = s3fs.S3FileSystem(anon=True, client_kwargs=dict(region_name='eu-west-2')) - >>> store = s3fs.S3Map(root='zarr-demo/store', s3=s3, check=False) - >>> cache = zarr.v2.LRUStoreCache(store, max_size=2**28) - >>> root = zarr.v2.group(store=cache) # doctest: +REMOTE_DATA - >>> z = root['foo/bar/baz'] # doctest: +REMOTE_DATA - >>> from timeit import timeit - >>> # first data access is relatively slow, retrieved from store - ... timeit('print(z[:].tobytes())', number=1, globals=globals()) # doctest: +SKIP - b'Hello from the cloud!' - 0.1081731989979744 - >>> # second data access is faster, uses cache - ... timeit('print(z[:].tobytes())', number=1, globals=globals()) # doctest: +SKIP - b'Hello from the cloud!' - 0.0009490990014455747 - - """ - - def __init__(self, store: StoreLike, max_size: int): - self._store: BaseStore = BaseStore._ensure_store(store) - self._max_size = max_size - self._current_size = 0 - self._keys_cache = None - self._contains_cache: Dict[Any, Any] = {} - self._listdir_cache: Dict[Path, Any] = dict() - self._values_cache: Dict[Path, Any] = OrderedDict() - self._mutex = Lock() - self.hits = self.misses = 0 - - def __getstate__(self): - return ( - self._store, - self._max_size, - self._current_size, - self._keys_cache, - self._contains_cache, - self._listdir_cache, - self._values_cache, - self.hits, - self.misses, - ) - - def __setstate__(self, state): - ( - self._store, - self._max_size, - self._current_size, - self._keys_cache, - self._contains_cache, - self._listdir_cache, - self._values_cache, - self.hits, - self.misses, - ) = state - self._mutex = Lock() - - def __len__(self): - return len(self._keys()) - - def __iter__(self): - return self.keys() - - def __contains__(self, key): - with self._mutex: - if key not in self._contains_cache: - self._contains_cache[key] = key in self._store - return self._contains_cache[key] - - def clear(self): - self._store.clear() - self.invalidate() - - def keys(self): - with self._mutex: - return iter(self._keys()) - - def _keys(self): - if self._keys_cache is None: - self._keys_cache = list(self._store.keys()) - return self._keys_cache - - def listdir(self, path: Path = None): - with self._mutex: - try: - return self._listdir_cache[path] - except KeyError: - listing = listdir(self._store, path) - self._listdir_cache[path] = listing - return listing - - def getsize(self, path=None) -> int: - return getsize(self._store, path=path) - - def _pop_value(self): - # remove the first value from the cache, as this will be the least recently - # used value - _, v = self._values_cache.popitem(last=False) - return v - - def _accommodate_value(self, value_size): - if self._max_size is None: - return - # ensure there is enough space in the cache for a new value - while self._current_size + value_size > self._max_size: - v = self._pop_value() - self._current_size -= buffer_size(v) - - def _cache_value(self, key: Path, value): - # cache a value - value_size = buffer_size(value) - # check size of the value against max size, as if the value itself exceeds max - # size then we are never going to cache it - if self._max_size is None or value_size <= self._max_size: - self._accommodate_value(value_size) - self._values_cache[key] = value - self._current_size += value_size - - def invalidate(self): - """Completely clear the cache.""" - with self._mutex: - self._values_cache.clear() - self._invalidate_keys() - self._current_size = 0 - - def invalidate_values(self): - """Clear the values cache.""" - with self._mutex: - self._values_cache.clear() - - def invalidate_keys(self): - """Clear the keys cache.""" - with self._mutex: - self._invalidate_keys() - - def _invalidate_keys(self): - self._keys_cache = None - self._contains_cache.clear() - self._listdir_cache.clear() - - def _invalidate_value(self, key): - if key in self._values_cache: - value = self._values_cache.pop(key) - self._current_size -= buffer_size(value) - - def __getitem__(self, key): - try: - # first try to obtain the value from the cache - with self._mutex: - value = self._values_cache[key] - # cache hit if no KeyError is raised - self.hits += 1 - # treat the end as most recently used - self._values_cache.move_to_end(key) - - except KeyError: - # cache miss, retrieve value from the store - value = self._store[key] - with self._mutex: - self.misses += 1 - # need to check if key is not in the cache, as it may have been cached - # while we were retrieving the value from the store - if key not in self._values_cache: - self._cache_value(key, value) - - return value - - def __setitem__(self, key, value): - self._store[key] = value - with self._mutex: - self._invalidate_keys() - self._invalidate_value(key) - self._cache_value(key, value) - - def __delitem__(self, key): - del self._store[key] - with self._mutex: - self._invalidate_keys() - self._invalidate_value(key) - - -class SQLiteStore(Store): - """Storage class using SQLite. - - Parameters - ---------- - path : string - Location of database file. - dimension_separator : {'.', '/'}, optional - Separator placed between the dimensions of a chunk. - **kwargs - Keyword arguments passed through to the `sqlite3.connect` function. - - Examples - -------- - Store a single array:: - - >>> import zarr - >>> store = zarr.v2.SQLiteStore('data/array.sqldb') - >>> z = zarr.v2.zeros((10, 10), chunks=(5, 5), store=store, overwrite=True) - >>> z[...] = 42 - >>> store.close() # don't forget to call this when you're done - - Store a group:: - - >>> store = zarr.v2.SQLiteStore('data/group.sqldb') - >>> root = zarr.v2.group(store=store, overwrite=True) - >>> foo = root.create_group('foo') - >>> bar = foo.zeros('bar', shape=(10, 10), chunks=(5, 5)) - >>> bar[...] = 42 - >>> store.close() # don't forget to call this when you're done - """ - - def __init__(self, path, dimension_separator=None, **kwargs): - import sqlite3 - - self._dimension_separator = dimension_separator - - # normalize path - if path != ":memory:": - path = os.path.abspath(path) - - # store properties - self.path = path - self.kwargs = kwargs - - # allow threading if SQLite connections are thread-safe - # - # ref: https://www.sqlite.org/releaselog/3_3_1.html - # ref: https://github.com/python/cpython/issues/71377 - check_same_thread = True - if sqlite3.sqlite_version_info >= (3, 3, 1): - check_same_thread = False - - # keep a lock for serializing mutable operations - self.lock = Lock() - - # open database - self.db = sqlite3.connect( - self.path, - detect_types=0, - isolation_level=None, - check_same_thread=check_same_thread, - **self.kwargs, - ) - - # handle keys as `str`s - self.db.text_factory = str - - # get a cursor to read/write to the database - self.cursor = self.db.cursor() - - # initialize database with our table if missing - with self.lock: - self.cursor.execute("CREATE TABLE IF NOT EXISTS zarr(k TEXT PRIMARY KEY, v BLOB)") - - def __getstate__(self): - if self.path == ":memory:": - raise PicklingError("Cannot pickle in-memory SQLite databases") - return self.path, self.kwargs - - def __setstate__(self, state): - path, kwargs = state - self.__init__(path=path, **kwargs) - - def close(self): - """Closes the underlying database.""" - - # close cursor and db objects - self.cursor.close() - self.db.close() - - def __getitem__(self, key): - value = self.cursor.execute("SELECT v FROM zarr WHERE (k = ?)", (key,)) - for (v,) in value: - return v - raise KeyError(key) - - def __setitem__(self, key, value): - self.update({key: value}) - - def __delitem__(self, key): - with self.lock: - self.cursor.execute("DELETE FROM zarr WHERE (k = ?)", (key,)) - if self.cursor.rowcount < 1: - raise KeyError(key) - - def __contains__(self, key): - cs = self.cursor.execute("SELECT COUNT(*) FROM zarr WHERE (k = ?)", (key,)) - for (has,) in cs: - has = bool(has) - return has - - def items(self): - kvs = self.cursor.execute("SELECT k, v FROM zarr") - yield from kvs - - def keys(self): - ks = self.cursor.execute("SELECT k FROM zarr") - for (k,) in ks: - yield k - - def values(self): - vs = self.cursor.execute("SELECT v FROM zarr") - for (v,) in vs: - yield v - - def __iter__(self): - return self.keys() - - def __len__(self): - cs = self.cursor.execute("SELECT COUNT(*) FROM zarr") - for (c,) in cs: - return c - - def update(self, *args, **kwargs): - args += (kwargs,) - - kv_list = [] - for dct in args: - for k, v in dct.items(): - v = ensure_contiguous_ndarray_like(v) - - # Accumulate key-value pairs for storage - kv_list.append((k, v)) - - with self.lock: - self.cursor.executemany("REPLACE INTO zarr VALUES (?, ?)", kv_list) - - def listdir(self, path=None): - path = normalize_storage_path(path) - sep = "_" if path == "" else "/" - keys = self.cursor.execute( - """ - SELECT DISTINCT SUBSTR(m, 0, INSTR(m, "/")) AS l FROM ( - SELECT LTRIM(SUBSTR(k, LENGTH(?) + 1), "/") || "/" AS m - FROM zarr WHERE k LIKE (? || "{sep}%") - ) ORDER BY l ASC - """.format(sep=sep), - (path, path), - ) - keys = list(map(operator.itemgetter(0), keys)) - return keys - - def getsize(self, path=None): - path = normalize_storage_path(path) - size = self.cursor.execute( - """ - SELECT COALESCE(SUM(LENGTH(v)), 0) FROM zarr - WHERE k LIKE (? || "%") AND - 0 == INSTR(LTRIM(SUBSTR(k, LENGTH(?) + 1), "/"), "/") - """, - (path, path), - ) - for (s,) in size: - return s - - def rmdir(self, path=None): - path = normalize_storage_path(path) - if path: - with self.lock: - self.cursor.execute('DELETE FROM zarr WHERE k LIKE (? || "/%")', (path,)) - else: - self.clear() - - def clear(self): - with self.lock: - self.cursor.executescript( - """ - BEGIN TRANSACTION; - DROP TABLE zarr; - CREATE TABLE zarr(k TEXT PRIMARY KEY, v BLOB); - COMMIT TRANSACTION; - """ - ) - - -class MongoDBStore(Store): - """Storage class using MongoDB. - - .. note:: This is an experimental feature. - - Requires the `pymongo `_ - package to be installed. - - Parameters - ---------- - database : string - Name of database - collection : string - Name of collection - dimension_separator : {'.', '/'}, optional - Separator placed between the dimensions of a chunk. - **kwargs - Keyword arguments passed through to the `pymongo.MongoClient` function. - - Notes - ----- - The maximum chunksize in MongoDB documents is 16 MB. - - """ - - _key = "key" - _value = "value" - - def __init__( - self, - database="mongodb_zarr", - collection="zarr_collection", - dimension_separator=None, - **kwargs, - ): - import pymongo - - self._database = database - self._collection = collection - self._dimension_separator = dimension_separator - self._kwargs = kwargs - - self.client = pymongo.MongoClient(**self._kwargs) - self.db = self.client.get_database(self._database) - self.collection = self.db.get_collection(self._collection) - - def __getitem__(self, key): - doc = self.collection.find_one({self._key: key}) - - if doc is None: - raise KeyError(key) - else: - return doc[self._value] - - def __setitem__(self, key, value): - value = ensure_bytes(value) - self.collection.replace_one( - {self._key: key}, {self._key: key, self._value: value}, upsert=True - ) - - def __delitem__(self, key): - result = self.collection.delete_many({self._key: key}) - if not result.deleted_count == 1: - raise KeyError(key) - - def __iter__(self): - for f in self.collection.find({}): - yield f[self._key] - - def __len__(self): - return self.collection.count_documents({}) - - def __getstate__(self): - return self._database, self._collection, self._kwargs - - def __setstate__(self, state): - database, collection, kwargs = state - self.__init__(database=database, collection=collection, **kwargs) - - def close(self): - """Cleanup client resources and disconnect from MongoDB.""" - self.client.close() - - def clear(self): - """Remove all items from store.""" - self.collection.delete_many({}) - - -class RedisStore(Store): - """Storage class using Redis. - - .. note:: This is an experimental feature. - - Requires the `redis `_ - package to be installed. - - Parameters - ---------- - prefix : string - Name of prefix for Redis keys - dimension_separator : {'.', '/'}, optional - Separator placed between the dimensions of a chunk. - **kwargs - Keyword arguments passed through to the `redis.Redis` function. - - """ - - def __init__(self, prefix="zarr", dimension_separator=None, **kwargs): - import redis - - self._prefix = prefix - self._kwargs = kwargs - self._dimension_separator = dimension_separator - - self.client = redis.Redis(**kwargs) - - def _key(self, key): - return "{prefix}:{key}".format(prefix=self._prefix, key=key) - - def __getitem__(self, key): - return self.client[self._key(key)] - - def __setitem__(self, key, value): - value = ensure_bytes(value) - self.client[self._key(key)] = value - - def __delitem__(self, key): - count = self.client.delete(self._key(key)) - if not count: - raise KeyError(key) - - def keylist(self): - offset = len(self._key("")) # length of prefix - return [key[offset:].decode("utf-8") for key in self.client.keys(self._key("*"))] - - def keys(self): - yield from self.keylist() - - def __iter__(self): - yield from self.keys() - - def __len__(self): - return len(self.keylist()) - - def __getstate__(self): - return self._prefix, self._kwargs - - def __setstate__(self, state): - prefix, kwargs = state - self.__init__(prefix=prefix, **kwargs) - - def clear(self): - for key in self.keys(): - del self[key] - - -class ConsolidatedMetadataStore(Store): - """A layer over other storage, where the metadata has been consolidated into - a single key. - - The purpose of this class, is to be able to get all of the metadata for - a given array in a single read operation from the underlying storage. - See :func:`zarr.v2.convenience.consolidate_metadata` for how to create this - single metadata key. - - This class loads from the one key, and stores the data in a dict, so that - accessing the keys no longer requires operations on the backend store. - - This class is read-only, and attempts to change the array metadata will - fail, but changing the data is possible. If the backend storage is changed - directly, then the metadata stored here could become obsolete, and - :func:`zarr.v2.convenience.consolidate_metadata` should be called again and the class - re-invoked. The use case is for write once, read many times. - - .. versionadded:: 2.3 - - .. note:: This is an experimental feature. - - Parameters - ---------- - store: Store - Containing the zarr array. - metadata_key: str - The target in the store where all of the metadata are stored. We - assume JSON encoding. - - See Also - -------- - zarr.v2.convenience.consolidate_metadata, zarr.v2.convenience.open_consolidated - - """ - - def __init__(self, store: StoreLike, metadata_key=".zmetadata"): - self.store = Store._ensure_store(store) - - # retrieve consolidated metadata - meta = json_loads(self.store[metadata_key]) - - # check format of consolidated metadata - consolidated_format = meta.get("zarr_consolidated_format", None) - if consolidated_format != 1: - raise MetadataError( - "unsupported zarr consolidated metadata format: %s" % consolidated_format - ) - - # decode metadata - self.meta_store: Store = KVStore(meta["metadata"]) - - def __getitem__(self, key): - return self.meta_store[key] - - def __contains__(self, item): - return item in self.meta_store - - def __iter__(self): - return iter(self.meta_store) - - def __len__(self): - return len(self.meta_store) - - def __delitem__(self, key): - raise ReadOnlyError - - def __setitem__(self, key, value): - raise ReadOnlyError - - def getsize(self, path): - return getsize(self.meta_store, path) - - def listdir(self, path): - return listdir(self.meta_store, path) diff --git a/src/zarr/v2/sync.py b/src/zarr/v2/sync.py deleted file mode 100644 index 49684a51ee..0000000000 --- a/src/zarr/v2/sync.py +++ /dev/null @@ -1,48 +0,0 @@ -import os -from collections import defaultdict -from threading import Lock - -import fasteners - - -class ThreadSynchronizer: - """Provides synchronization using thread locks.""" - - def __init__(self): - self.mutex = Lock() - self.locks = defaultdict(Lock) - - def __getitem__(self, item): - with self.mutex: - return self.locks[item] - - def __getstate__(self): - return True - - def __setstate__(self, *args): - # reinitialize from scratch - self.__init__() - - -class ProcessSynchronizer: - """Provides synchronization using file locks via the - `fasteners `_ - package. - - Parameters - ---------- - path : string - Path to a directory on a file system that is shared by all processes. - N.B., this should be a *different* path to where you store the array. - - """ - - def __init__(self, path): - self.path = path - - def __getitem__(self, item): - path = os.path.join(self.path, item) - lock = fasteners.InterProcessLock(path) - return lock - - # pickling and unpickling should be handled automatically diff --git a/src/zarr/v2/util.py b/src/zarr/v2/util.py deleted file mode 100644 index 7e3bd788ec..0000000000 --- a/src/zarr/v2/util.py +++ /dev/null @@ -1,788 +0,0 @@ -import inspect -import json -import math -import numbers -from textwrap import TextWrapper -import mmap -import time -from typing import ( - Any, - Callable, - Dict, - Iterator, - Mapping, - Optional, - Tuple, - TypeVar, - Union, - Iterable, - cast, -) - -import numpy as np -import numpy.typing as npt -from asciitree import BoxStyle, LeftAligned -from asciitree.traversal import Traversal -from numcodecs.compat import ( - ensure_text, - ensure_ndarray_like, - ensure_bytes, - ensure_contiguous_ndarray_like, -) -from numcodecs.ndarray_like import NDArrayLike -from numcodecs.registry import codec_registry -from numcodecs.blosc import cbuffer_sizes, cbuffer_metainfo - -KeyType = TypeVar("KeyType") -ValueType = TypeVar("ValueType") - - -def flatten(arg: Iterable[Any]) -> Iterable[Any]: - for element in arg: - if isinstance(element, Iterable) and not isinstance(element, (str, bytes)): - yield from flatten(element) - else: - yield element - - -# codecs to use for object dtype convenience API -object_codecs = { - str.__name__: "vlen-utf8", - bytes.__name__: "vlen-bytes", - "array": "vlen-array", -} - - -class NumberEncoder(json.JSONEncoder): - def default(self, o): - # See json.JSONEncoder.default docstring for explanation - # This is necessary to encode numpy dtype - if isinstance(o, numbers.Integral): - return int(o) - if isinstance(o, numbers.Real): - return float(o) - return json.JSONEncoder.default(self, o) - - -def json_dumps(o: Any) -> bytes: - """Write JSON in a consistent, human-readable way.""" - return json.dumps( - o, indent=4, sort_keys=True, ensure_ascii=True, separators=(",", ": "), cls=NumberEncoder - ).encode("ascii") - - -def json_loads(s: Union[bytes, str]) -> Dict[str, Any]: - """Read JSON in a consistent way.""" - return json.loads(ensure_text(s, "utf-8")) - - -def normalize_shape(shape: Union[int, Tuple[int, ...], None]) -> Tuple[int, ...]: - """Convenience function to normalize the `shape` argument.""" - - if shape is None: - raise TypeError("shape is None") - - # handle 1D convenience form - if isinstance(shape, numbers.Integral): - shape = (int(shape),) - - # normalize - shape = cast(Tuple[int, ...], shape) - shape = tuple(int(s) for s in shape) - return shape - - -# code to guess chunk shape, adapted from h5py - -CHUNK_BASE = 256 * 1024 # Multiplier by which chunks are adjusted -CHUNK_MIN = 128 * 1024 # Soft lower limit (128k) -CHUNK_MAX = 64 * 1024 * 1024 # Hard upper limit - - -def guess_chunks(shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]: - """ - Guess an appropriate chunk layout for an array, given its shape and - the size of each element in bytes. Will allocate chunks only as large - as MAX_SIZE. Chunks are generally close to some power-of-2 fraction of - each axis, slightly favoring bigger values for the last index. - Undocumented and subject to change without warning. - """ - - ndims = len(shape) - # require chunks to have non-zero length for all dimensions - chunks = np.maximum(np.array(shape, dtype="=f8"), 1) - - # Determine the optimal chunk size in bytes using a PyTables expression. - # This is kept as a float. - dset_size = np.prod(chunks) * typesize - target_size = CHUNK_BASE * (2 ** np.log10(dset_size / (1024.0 * 1024))) - - if target_size > CHUNK_MAX: - target_size = CHUNK_MAX - elif target_size < CHUNK_MIN: - target_size = CHUNK_MIN - - idx = 0 - while True: - # Repeatedly loop over the axes, dividing them by 2. Stop when: - # 1a. We're smaller than the target chunk size, OR - # 1b. We're within 50% of the target chunk size, AND - # 2. The chunk is smaller than the maximum chunk size - - chunk_bytes = np.prod(chunks) * typesize - - if ( - chunk_bytes < target_size or abs(chunk_bytes - target_size) / target_size < 0.5 - ) and chunk_bytes < CHUNK_MAX: - break - - if np.prod(chunks) == 1: - break # Element size larger than CHUNK_MAX - - chunks[idx % ndims] = math.ceil(chunks[idx % ndims] / 2.0) - idx += 1 - - return tuple(int(x) for x in chunks) - - -def normalize_chunks(chunks: Any, shape: Tuple[int, ...], typesize: int) -> Tuple[int, ...]: - """Convenience function to normalize the `chunks` argument for an array - with the given `shape`.""" - - # N.B., expect shape already normalized - - # handle auto-chunking - if chunks is None or chunks is True: - return guess_chunks(shape, typesize) - - # handle no chunking - if chunks is False: - return shape - - # handle 1D convenience form - if isinstance(chunks, numbers.Integral): - chunks = tuple(int(chunks) for _ in shape) - - # handle bad dimensionality - if len(chunks) > len(shape): - raise ValueError("too many dimensions in chunks") - - # handle underspecified chunks - if len(chunks) < len(shape): - # assume chunks across remaining dimensions - chunks += shape[len(chunks) :] - - # handle None or -1 in chunks - if -1 in chunks or None in chunks: - chunks = tuple(s if c == -1 or c is None else int(c) for s, c in zip(shape, chunks)) - - chunks = tuple(int(c) for c in chunks) - return chunks - - -def normalize_dtype(dtype: Union[str, npt.DTypeLike], object_codec) -> Tuple[np.dtype[Any], Any]: - # convenience API for object arrays - if inspect.isclass(dtype): - dtype = dtype.__name__ - if isinstance(dtype, str): - # allow ':' to delimit class from codec arguments - tokens = dtype.split(":") - key = tokens[0] - if key in object_codecs: - dtype = np.dtype(object) - if object_codec is None: - codec_id = object_codecs[key] - if len(tokens) > 1: - args = tokens[1].split(",") - else: - args = [] - try: - object_codec = codec_registry[codec_id](*args) - except KeyError: # pragma: no cover - raise ValueError( - "codec %r for object type %r is not " - "available; please provide an " - "object_codec manually" % (codec_id, key) - ) - return dtype, object_codec - - dtype = np.dtype(dtype) - - # don't allow generic datetime64 or timedelta64, require units to be specified - if dtype == np.dtype("M8") or dtype == np.dtype("m8"): - raise ValueError( - "datetime64 and timedelta64 dtypes with generic units " - 'are not supported, please specify units (e.g., "M8[ns]")' - ) - - return dtype, object_codec - - -# noinspection PyTypeChecker -def is_total_slice(item, shape: Tuple[int]) -> bool: - """Determine whether `item` specifies a complete slice of array with the - given `shape`. Used to optimize __setitem__ operations on the Chunk - class.""" - - # N.B., assume shape is normalized - - if item == Ellipsis: - return True - if item == slice(None): - return True - if isinstance(item, slice): - item = (item,) - if isinstance(item, tuple): - return all( - ( - isinstance(it, slice) - and ((it == slice(None)) or ((it.stop - it.start == sh) and (it.step in [1, None]))) - ) - for it, sh in zip(item, shape) - ) - else: - raise TypeError("expected slice or tuple of slices, found %r" % item) - - -def normalize_resize_args(old_shape, *args): - # normalize new shape argument - if len(args) == 1: - new_shape = args[0] - else: - new_shape = args - if isinstance(new_shape, int): - new_shape = (new_shape,) - else: - new_shape = tuple(new_shape) - if len(new_shape) != len(old_shape): - raise ValueError("new shape must have same number of dimensions") - - # handle None in new_shape - new_shape = tuple(s if n is None else int(n) for s, n in zip(old_shape, new_shape)) - - return new_shape - - -def human_readable_size(size) -> str: - if size < 2**10: - return "%s" % size - elif size < 2**20: - return "%.1fK" % (size / float(2**10)) - elif size < 2**30: - return "%.1fM" % (size / float(2**20)) - elif size < 2**40: - return "%.1fG" % (size / float(2**30)) - elif size < 2**50: - return "%.1fT" % (size / float(2**40)) - else: - return "%.1fP" % (size / float(2**50)) - - -def normalize_order(order: str) -> str: - order = str(order).upper() - if order not in ["C", "F"]: - raise ValueError("order must be either 'C' or 'F', found: %r" % order) - return order - - -def normalize_dimension_separator(sep: Optional[str]) -> Optional[str]: - if sep in (".", "/", None): - return sep - else: - raise ValueError("dimension_separator must be either '.' or '/', found: %r" % sep) - - -def normalize_fill_value(fill_value, dtype: np.dtype[Any]): - if fill_value is None or dtype.hasobject: - # no fill value - pass - elif not isinstance(fill_value, np.void) and fill_value == 0: - # this should be compatible across numpy versions for any array type, including - # structured arrays - fill_value = np.zeros((), dtype=dtype)[()] - - elif dtype.kind == "U": - # special case unicode because of encoding issues on Windows if passed through numpy - # https://github.com/alimanfoo/zarr/pull/172#issuecomment-343782713 - - if not isinstance(fill_value, str): - raise ValueError( - "fill_value {!r} is not valid for dtype {}; must be a unicode string".format( - fill_value, dtype - ) - ) - - else: - try: - if isinstance(fill_value, bytes) and dtype.kind == "V": - # special case for numpy 1.14 compatibility - fill_value = np.array(fill_value, dtype=dtype.str).view(dtype)[()] - else: - fill_value = np.array(fill_value, dtype=dtype)[()] - - except Exception as e: - # re-raise with our own error message to be helpful - raise ValueError( - "fill_value {!r} is not valid for dtype {}; nested exception: {}".format( - fill_value, dtype, e - ) - ) - - return fill_value - - -def normalize_storage_path(path: Union[str, bytes, None]) -> str: - # handle bytes - if isinstance(path, bytes): - path = str(path, "ascii") - - # ensure str - if path is not None and not isinstance(path, str): - path = str(path) - - if path: - # convert backslash to forward slash - path = path.replace("\\", "/") - - # ensure no leading slash - while len(path) > 0 and path[0] == "/": - path = path[1:] - - # ensure no trailing slash - while len(path) > 0 and path[-1] == "/": - path = path[:-1] - - # collapse any repeated slashes - previous_char = None - collapsed = "" - for char in path: - if char == "/" and previous_char == "/": - pass - else: - collapsed += char - previous_char = char - path = collapsed - - # don't allow path segments with just '.' or '..' - segments = path.split("/") - if any(s in {".", ".."} for s in segments): - raise ValueError("path containing '.' or '..' segment not allowed") - - else: - path = "" - - return path - - -def buffer_size(v) -> int: - return ensure_ndarray_like(v).nbytes - - -def info_text_report(items: Dict[Any, Any]) -> str: - keys = [k for k, v in items] - max_key_len = max(len(k) for k in keys) - report = "" - for k, v in items: - wrapper = TextWrapper( - width=80, - initial_indent=k.ljust(max_key_len) + " : ", - subsequent_indent=" " * max_key_len + " : ", - ) - text = wrapper.fill(str(v)) - report += text + "\n" - return report - - -def info_html_report(items) -> str: - report = '' - report += "" - for k, v in items: - report += ( - "" - '' - '' - "" % (k, v) - ) - report += "" - report += "
%s%s
" - return report - - -class InfoReporter: - def __init__(self, obj): - self.obj = obj - - def __repr__(self): - items = self.obj.info_items() - return info_text_report(items) - - def _repr_html_(self): - items = self.obj.info_items() - return info_html_report(items) - - -class TreeNode: - def __init__(self, obj, depth=0, level=None): - self.obj = obj - self.depth = depth - self.level = level - - def get_children(self): - if hasattr(self.obj, "values") and (self.level is None or self.depth < self.level): - depth = self.depth + 1 - return [TreeNode(o, depth=depth, level=self.level) for o in self.obj.values()] - return [] - - def get_text(self): - name = self.obj.name.split("/")[-1] or "/" - if hasattr(self.obj, "shape"): - name += " {} {}".format(self.obj.shape, self.obj.dtype) - return name - - def get_type(self): - return type(self.obj).__name__ - - -class TreeTraversal(Traversal): # type: ignore[misc] - def get_children(self, node): - return node.get_children() - - def get_root(self, tree): - return tree - - def get_text(self, node): - return node.get_text() - - -tree_group_icon = "folder" -tree_array_icon = "table" - - -def tree_get_icon(stype: str) -> str: - if stype == "Array": - return tree_array_icon - elif stype == "Group": - return tree_group_icon - else: - raise ValueError("Unknown type: %s" % stype) - - -def tree_widget_sublist(node, root=False, expand=False): - import ipytree - - result = ipytree.Node() - result.icon = tree_get_icon(node.get_type()) - if root or (expand is True) or (isinstance(expand, int) and node.depth < expand): - result.opened = True - else: - result.opened = False - result.name = node.get_text() - result.nodes = [tree_widget_sublist(c, expand=expand) for c in node.get_children()] - result.disabled = True - - return result - - -def tree_widget(group, expand, level): - try: - import ipytree - except ImportError as error: - raise ImportError( - "{}: Run `pip install zarr[jupyter]` or `conda install ipytree`" - "to get the required ipytree dependency for displaying the tree " - "widget. If using jupyterlab<3, you also need to run " - "`jupyter labextension install ipytree`".format(error) - ) - - result = ipytree.Tree() - root = TreeNode(group, level=level) - result.add_node(tree_widget_sublist(root, root=True, expand=expand)) - - return result - - -class TreeViewer: - def __init__(self, group, expand=False, level=None): - self.group = group - self.expand = expand - self.level = level - - self.text_kwargs = dict(horiz_len=2, label_space=1, indent=1) - - self.bytes_kwargs = dict( - UP_AND_RIGHT="+", HORIZONTAL="-", VERTICAL="|", VERTICAL_AND_RIGHT="+" - ) - - self.unicode_kwargs = dict( - UP_AND_RIGHT="\u2514", - HORIZONTAL="\u2500", - VERTICAL="\u2502", - VERTICAL_AND_RIGHT="\u251c", - ) - - def __bytes__(self): - drawer = LeftAligned( - traverse=TreeTraversal(), draw=BoxStyle(gfx=self.bytes_kwargs, **self.text_kwargs) - ) - root = TreeNode(self.group, level=self.level) - result = drawer(root) - - # Unicode characters slip in on Python 3. - # So we need to straighten that out first. - result = result.encode() - - return result - - def __unicode__(self): - drawer = LeftAligned( - traverse=TreeTraversal(), draw=BoxStyle(gfx=self.unicode_kwargs, **self.text_kwargs) - ) - root = TreeNode(self.group, level=self.level) - return drawer(root) - - def __repr__(self): - return self.__unicode__() - - def _repr_mimebundle_(self, **kwargs): - tree = tree_widget(self.group, expand=self.expand, level=self.level) - return tree._repr_mimebundle_(**kwargs) - - -def check_array_shape(param, array, shape): - if not hasattr(array, "shape"): - raise TypeError( - "parameter {!r}: expected an array-like object, got {!r}".format(param, type(array)) - ) - if array.shape != shape: - raise ValueError( - "parameter {!r}: expected array with shape {!r}, got {!r}".format( - param, shape, array.shape - ) - ) - - -def is_valid_python_name(name): - from keyword import iskeyword - - return name.isidentifier() and not iskeyword(name) - - -class NoLock: - """A lock that doesn't lock.""" - - def __enter__(self): - pass - - def __exit__(self, *args): - pass - - -nolock = NoLock() - - -class PartialReadBuffer: - def __init__(self, store_key, chunk_store): - self.chunk_store = chunk_store - # is it fsstore or an actual fsspec map object - assert hasattr(self.chunk_store, "map") - self.map = self.chunk_store.map - self.fs = self.chunk_store.fs - self.store_key = store_key - self.buff = None - self.nblocks = None - self.start_points = None - self.n_per_block = None - self.start_points_max = None - self.read_blocks = set() - - _key_path = self.map._key_to_str(store_key) - _key_path = _key_path.split("/") - _chunk_path = [self.chunk_store._normalize_key(_key_path[-1])] - _key_path = "/".join(_key_path[:-1] + _chunk_path) - self.key_path = _key_path - - def prepare_chunk(self): - assert self.buff is None - header = self.fs.read_block(self.key_path, 0, 16) - nbytes, self.cbytes, blocksize = cbuffer_sizes(header) - typesize, _shuffle, _memcpyd = cbuffer_metainfo(header) - self.buff = mmap.mmap(-1, self.cbytes) - self.buff[0:16] = header - self.nblocks = nbytes / blocksize - self.nblocks = ( - int(self.nblocks) if self.nblocks == int(self.nblocks) else int(self.nblocks + 1) - ) - if self.nblocks == 1: - self.buff = self.read_full() - return - start_points_buffer = self.fs.read_block(self.key_path, 16, int(self.nblocks * 4)) - self.start_points = np.frombuffer(start_points_buffer, count=self.nblocks, dtype=np.int32) - self.start_points_max = self.start_points.max() - self.buff[16 : (16 + (self.nblocks * 4))] = start_points_buffer - self.n_per_block = blocksize / typesize - - def read_part(self, start, nitems): - assert self.buff is not None - if self.nblocks == 1: - return - start_block = int(start / self.n_per_block) - wanted_decompressed = 0 - while wanted_decompressed < nitems: - if start_block not in self.read_blocks: - start_byte = self.start_points[start_block] - if start_byte == self.start_points_max: - stop_byte = self.cbytes - else: - stop_byte = self.start_points[self.start_points > start_byte].min() - length = stop_byte - start_byte - data_buff = self.fs.read_block(self.key_path, start_byte, length) - self.buff[start_byte:stop_byte] = data_buff - self.read_blocks.add(start_block) - if wanted_decompressed == 0: - wanted_decompressed += ((start_block + 1) * self.n_per_block) - start - else: - wanted_decompressed += self.n_per_block - start_block += 1 - - def read_full(self): - return self.chunk_store[self.store_key] - - -class UncompressedPartialReadBufferV3: - def __init__(self, store_key, chunk_store, itemsize): - assert chunk_store.supports_efficient_get_partial_values - self.chunk_store = chunk_store - self.store_key = store_key - self.itemsize = itemsize - - def prepare_chunk(self): - pass - - def read_part(self, start, nitems): - return self.chunk_store.get_partial_values( - [(self.store_key, (start * self.itemsize, nitems * self.itemsize))] - )[0] - - def read_full(self): - return self.chunk_store[self.store_key] - - -def retry_call( - callabl: Callable[..., Any], - args=None, - kwargs=None, - exceptions: Tuple[Any, ...] = (), - retries: int = 10, - wait: float = 0.1, -) -> Any: - """ - Make several attempts to invoke the callable. If one of the given exceptions - is raised, wait the given period of time and retry up to the given number of - retries. - """ - - if args is None: - args = () - if kwargs is None: - kwargs = {} - - for attempt in range(1, retries + 1): - try: - return callabl(*args, **kwargs) - except exceptions: - if attempt < retries: - time.sleep(wait) - else: - raise - - -def all_equal(value: Any, array: Any): - """ - Test if all the elements of an array are equivalent to a value. - If `value` is None, then this function does not do any comparison and - returns False. - """ - - if value is None: - return False - if not value: - # if `value` is falsey, then just 1 truthy value in `array` - # is sufficient to return False. We assume here that np.any is - # optimized to return on the first truthy value in `array`. - try: - return not np.any(array) - except (TypeError, ValueError): # pragma: no cover - pass - if np.issubdtype(array.dtype, np.object_): - # we have to flatten the result of np.equal to handle outputs like - # [np.array([True,True]), True, True] - return all(flatten(np.equal(value, array, dtype=array.dtype))) - else: - # Numpy errors if you call np.isnan on custom dtypes, so ensure - # we are working with floats before calling isnan - if np.issubdtype(array.dtype, np.floating) and np.isnan(value): - return np.all(np.isnan(array)) - else: - # using == raises warnings from numpy deprecated pattern, but - # using np.equal() raises type errors for structured dtypes... - return np.all(value == array) - - -def ensure_contiguous_ndarray_or_bytes(buf) -> Union[NDArrayLike, bytes]: - """Convenience function to coerce `buf` to ndarray-like array or bytes. - - First check if `buf` can be zero-copy converted to a contiguous array. - If not, `buf` will be copied to a newly allocated `bytes` object. - - Parameters - ---------- - buf : ndarray-like, array-like, or bytes-like - A numpy array like object such as numpy.ndarray, cupy.ndarray, or - any object exporting a buffer interface. - - Returns - ------- - arr : NDArrayLike or bytes - A ndarray-like or bytes object - """ - - try: - return ensure_contiguous_ndarray_like(buf) - except TypeError: - # An error is raised if `buf` couldn't be zero-copy converted - return ensure_bytes(buf) - - -class ConstantMap(Mapping[KeyType, ValueType]): - """A read-only map that maps all keys to the same constant value - - Useful if you want to call `getitems()` with the same context for all keys. - - Parameters - ---------- - keys - The keys of the map. Will be copied to a frozenset if it isn't already. - constant - The constant that all keys are mapping to. - """ - - def __init__(self, keys: Iterable[KeyType], constant: ValueType) -> None: - self._keys = keys if isinstance(keys, frozenset) else frozenset(keys) - self._constant = constant - - def __getitem__(self, key: KeyType) -> ValueType: - if key not in self._keys: - raise KeyError(repr(key)) - return self._constant - - def __iter__(self) -> Iterator[KeyType]: - return iter(self._keys) - - def __len__(self) -> int: - return len(self._keys) - - def __contains__(self, key: object) -> bool: - return key in self._keys - - def __repr__(self) -> str: - return repr(dict(self.items())) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/benchmarks/__init__.py b/tests/benchmarks/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/benchmarks/common.py b/tests/benchmarks/common.py new file mode 100644 index 0000000000..e8809156a6 --- /dev/null +++ b/tests/benchmarks/common.py @@ -0,0 +1,8 @@ +from dataclasses import dataclass + + +@dataclass(kw_only=True, frozen=True) +class Layout: + shape: tuple[int, ...] + chunks: tuple[int, ...] + shards: tuple[int, ...] | None diff --git a/tests/benchmarks/conftest.py b/tests/benchmarks/conftest.py new file mode 100644 index 0000000000..be069d162d --- /dev/null +++ b/tests/benchmarks/conftest.py @@ -0,0 +1,15 @@ +"""Pytest configuration for benchmark tests.""" + +import pytest + +# Filter CodSpeed instrumentation warnings that can occur intermittently +# when registering benchmark results. This is a known issue with the +# CodSpeed walltime instrumentation hooks. +# See: https://github.com/CodSpeedHQ/pytest-codspeed + + +def pytest_configure(config: pytest.Config) -> None: + config.addinivalue_line( + "filterwarnings", + "ignore:Failed to set executed benchmark:RuntimeWarning", + ) diff --git a/tests/benchmarks/test_e2e.py b/tests/benchmarks/test_e2e.py new file mode 100644 index 0000000000..9720778d8f --- /dev/null +++ b/tests/benchmarks/test_e2e.py @@ -0,0 +1,258 @@ +""" +Benchmarks for end-to-end read/write performance of Zarr +""" + +from __future__ import annotations + +import os +import platform +import subprocess +import warnings +from functools import lru_cache +from operator import getitem, setitem +from typing import TYPE_CHECKING, Any, Literal + +import numpy as np +import pytest + +import zarr +from tests.benchmarks.common import Layout +from zarr import create_array +from zarr.core.config import config as zarr_config +from zarr.testing.store import LatencyStore + + +def clear_cache() -> None: + """Drop the OS page cache between benchmark rounds. + + Requires passwordless sudo, so it is opt-in: set `ZARR_BENCHMARK_CLEAR_CACHE=1` + to enable it (as the benchmark CI jobs do). By default this is a no-op, so a + plain `pytest` run never prompts for a sudo password (see issue #4199). + `sudo -n` guarantees we fail instead of blocking on a password prompt even + when the variable is set. + """ + if os.environ.get("ZARR_BENCHMARK_CLEAR_CACHE", "") not in ("1", "true"): + return + if platform.system() == "Darwin": + subprocess.call(["sync"]) + subprocess.call(["sudo", "-n", "purge"]) + elif platform.system() == "Linux": + subprocess.call(["sudo", "-n", "sh", "-c", "sync; echo 3 > /proc/sys/vm/drop_caches"]) + else: + warnings.warn( + f"ZARR_BENCHMARK_CLEAR_CACHE is set but cache clearing is not supported on " + f"{platform.system()}; skipping.", + stacklevel=2, + ) + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + from types import EllipsisType + + from pytest_benchmark.fixture import BenchmarkFixture + + from zarr.abc.store import Store + from zarr.core.common import NamedConfig + + +@lru_cache +def _data(shape: tuple[int]) -> np.ndarray: + n = shape[0] + period = 256 + noise_level = 1 + pattern = (np.sin(np.linspace(0, 2 * np.pi, period)) * 50 + 128).round().astype(np.uint8) + data = np.tile(pattern, int(np.ceil(n / period)))[:n].astype(np.int16) + rng = np.random.default_rng(0) + data += rng.integers(-noise_level, noise_level + 1, size=n, dtype=np.int16) + return np.clip(data, 0, 255).astype(np.uint8) + + +CompressorName = Literal["zstd"] | None + +compressors: dict[CompressorName, NamedConfig[Any, Any] | None] = { + None: None, + # Default v3 + "zstd": {"name": "zstd", "configuration": {"level": 0, "checksum": False}}, +} + + +layouts: tuple[Layout, ...] = ( + # No shards, just 1000 chunks + Layout(shape=(100_000_000,), chunks=(100_000,), shards=None), + # 1:1 chunk:shard shape, should measure overhead of sharding + Layout(shape=(100_000_000,), chunks=(100_000,), shards=(100_000,)), + # One shard with all the chunks, should measure over/under-head of handling inner shard chunks + Layout(shape=(100_000_000,), chunks=(100_000,), shards=(100_000 * 1_000,)), + # Mixed layout balancing inner vs. outer concurrency (likely the most real-world case) + Layout(shape=(1_000_000_000,), chunks=(100_000,), shards=(100_000 * 100,)), +) + +_PIPELINE_SETTINGS = { + "batched": {"codec_pipeline.path": "zarr.core.codec_pipeline.BatchedCodecPipeline"}, + "fused_full_threaded": { + "codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline", + "codec_pipeline.max_workers": None, + }, + "fused_single_threaded": { + "codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline", + "codec_pipeline.max_workers": 1, + }, +} + +_LATENCY_VALUES = (0, 0.03) + + +@pytest.fixture(params=_LATENCY_VALUES, ids=lambda v: f"latency={v}") +def latency(request: pytest.FixtureRequest) -> float: + return request.param # type: ignore[no-any-return] + + +@pytest.fixture +def bench_store(store: Store, latency: float, request: pytest.FixtureRequest) -> Store: + """Wraps the underlying store in LatencyStore when latency > 0. + + Local-store cases skip nonzero latency β€” synthetic latency on top of + a real LocalStore is double-counting; latency simulation only applies + to the in-process memory store. + """ + callspec = getattr(request.node, "callspec", None) + store_kind = callspec.params.get("store", "memory") if callspec is not None else "memory" + if latency > 0: + if store_kind == "local": + pytest.skip("latency injection only applies to in-memory store") + return LatencyStore( + store, get_latency=(latency, latency * 1.2), set_latency=(latency, latency * 1.2) + ) + if store_kind == "memory": + pytest.skip("memory store doesn't offer much over local without latency") + return store + + +@pytest.fixture(params=["batched"]) # , "fused_full_threaded", "fused_single_threaded"]) +def pipeline(request: pytest.FixtureRequest) -> Iterator[str]: + """Set ``codec_pipeline.path`` for the duration of the benchmark. + + Yields the pipeline name so each parametrize cell has a distinct + benchmark id. + """ + name = request.param + with zarr_config.set(_PIPELINE_SETTINGS[name]): + yield name + + +@pytest.mark.parametrize( + "get_data", [lambda shape: 1, lambda shape: _data(shape)], ids=["repeated", "semi_random"] +) +@pytest.mark.parametrize("compression_name", ["zstd", None]) +@pytest.mark.parametrize("layout", layouts, ids=str) +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +def test_write_array( + bench_store: Store, + layout: Layout, + compression_name: CompressorName, + pipeline: str, + benchmark: BenchmarkFixture, + get_data: Callable[[tuple[int]], np.ndarray | int], +) -> None: + """ + Test the time required to fill an array with a single value + """ + arr = create_array( + bench_store, + dtype="uint8", + shape=layout.shape, + chunks=layout.chunks, + shards=layout.shards, + compressors=compressors[compression_name], # type: ignore[arg-type] + fill_value=0, + ) + + def setup() -> tuple[tuple[zarr.Array, EllipsisType, int | np.ndarray], dict]: # type: ignore[type-arg] + clear_cache() + return (arr, Ellipsis, get_data(layout.shape)), {} # type: ignore[arg-type] + + benchmark.pedantic(setitem, setup=setup, rounds=3) # type: ignore[no-untyped-call] + + +@pytest.mark.parametrize( + "get_data", [lambda shape: 1, lambda shape: _data(shape)], ids=["repeated", "semi_random"] +) +@pytest.mark.parametrize("compression_name", ["zstd", None]) +@pytest.mark.parametrize("layout", layouts, ids=str) +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +def test_read_array( + bench_store: Store, + layout: Layout, + compression_name: CompressorName, + pipeline: str, + benchmark: BenchmarkFixture, + get_data: Callable[[tuple[int]], np.ndarray | int], +) -> None: + """ + Test the time required to read the entirety of an array + """ + arr = create_array( + bench_store, + dtype="uint8", + shape=layout.shape, + chunks=layout.chunks, + shards=layout.shards, + compressors=compressors[compression_name], # type: ignore[arg-type] + fill_value=0, + ) + arr[:] = get_data(layout.shape) # type: ignore[arg-type] + + def setup() -> tuple[tuple[zarr.Array, EllipsisType], dict]: # type: ignore[type-arg] + clear_cache() + return (arr, Ellipsis), {} + + benchmark.pedantic(getitem, setup=setup, rounds=3) # type: ignore[no-untyped-call] + + +_CONCURRENT_READ_THREADS = 8 +_concurrent_layout = Layout(shape=(64_000_000,), chunks=(4_000_000,), shards=None) + + +@pytest.mark.parametrize("pipeline", ["batched", "fused_full_threaded"], indirect=True) +@pytest.mark.parametrize("compression_name", ["zstd", None]) +@pytest.mark.parametrize("store", ["local"], indirect=["store"]) +def test_read_array_concurrent( + bench_store: Store, + compression_name: CompressorName, + pipeline: str, + benchmark: BenchmarkFixture, +) -> None: + """Dask-style access: several user threads each reading one chunk per call. + + All sync-API calls are serviced by the one global event loop, so this + measures how much of each read's IO+compute the pipeline runs while + holding the loop: anything inline serializes the readers. + """ + from concurrent.futures import ThreadPoolExecutor + + layout = _concurrent_layout + arr = create_array( + bench_store, + dtype="uint8", + shape=layout.shape, + chunks=layout.chunks, + shards=layout.shards, + compressors=compressors[compression_name], # type: ignore[arg-type] + fill_value=0, + ) + arr[:] = _data(layout.shape) + selections = [ + slice(start, start + layout.chunks[0]) + for start in range(0, layout.shape[0], layout.chunks[0]) + ] + + def read_all_chunks_concurrently() -> None: + with ThreadPoolExecutor(max_workers=_CONCURRENT_READ_THREADS) as executor: + list(executor.map(lambda sel: arr[sel], selections)) + + def setup() -> tuple[tuple[()], dict]: # type: ignore[type-arg] + clear_cache() + return (), {} + + benchmark.pedantic(read_all_chunks_concurrently, setup=setup, rounds=3) # type: ignore[no-untyped-call] diff --git a/tests/benchmarks/test_indexing.py b/tests/benchmarks/test_indexing.py new file mode 100644 index 0000000000..c9b80f9ff6 --- /dev/null +++ b/tests/benchmarks/test_indexing.py @@ -0,0 +1,343 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from pytest_benchmark.fixture import BenchmarkFixture + + from zarr.abc.store import Store + +from operator import getitem + +import pytest + +from zarr import create_array + +indexers = ( + (0,) * 3, + (slice(None),) * 3, + (slice(0, None, 4),) * 3, + (slice(10),) * 3, + (slice(10, -10, 4),) * 3, + (slice(None), slice(0, 3, 2), slice(0, 10)), +) + +shards = ( + None, + (50,) * 3, +) + + +@pytest.mark.parametrize("store", ["memory", "memory_get_latency"], indirect=["store"]) +@pytest.mark.parametrize("indexer", indexers, ids=str) +@pytest.mark.parametrize("shards", shards, ids=str) +def test_slice_indexing( + store: Store, + indexer: tuple[int | slice], + shards: tuple[int, ...] | None, + benchmark: BenchmarkFixture, +) -> None: + data = create_array( + store=store, + shape=(105,) * 3, + dtype="uint8", + chunks=(10,) * 3, + shards=shards, + compressors=None, + filters=None, + fill_value=0, + ) + + data[:] = 1 + benchmark(getitem, data, indexer) + + +# Benchmark for Morton order optimization with power-of-2 shards +# Morton order is used internally by sharding codec for chunk iteration +morton_shards = ( + (16,) * 3, # With 2x2x2 chunks: 8x8x8 = 512 chunks per shard + (32,) * 3, # With 2x2x2 chunks: 16x16x16 = 4096 chunks per shard +) + + +@pytest.mark.parametrize("store", ["memory"], indirect=["store"]) +@pytest.mark.parametrize("shards", morton_shards, ids=str) +def test_sharded_morton_indexing( + store: Store, + shards: tuple[int, ...], + benchmark: BenchmarkFixture, +) -> None: + """Benchmark sharded array indexing with power-of-2 chunks per shard. + + This benchmark exercises the Morton order iteration path in the sharding + codec, which benefits from the hypercube and vectorization optimizations. + The Morton order cache is cleared before each iteration to measure the + full computation cost. + """ + from zarr.core.indexing import _morton_order, morton_order_coords + + # Create array where each shard contains many small chunks + # e.g., shards=(32,32,32) with chunks=(2,2,2) means 16x16x16 = 4096 chunks per shard + shape = tuple(s * 2 for s in shards) # 2 shards per dimension + chunks = (2,) * 3 # Small chunks to maximize chunks per shard + + data = create_array( + store=store, + shape=shape, + dtype="uint8", + chunks=chunks, + shards=shards, + compressors=None, + filters=None, + fill_value=0, + ) + + data[:] = 1 + # Read a sub-shard region to exercise Morton order iteration + indexer = (slice(shards[0]),) * 3 + + def read_with_cache_clear() -> None: + _morton_order.cache_clear() + morton_order_coords.cache_clear() + getitem(data, indexer) + + benchmark(read_with_cache_clear) + + +# Benchmark with larger chunks_per_shard to make Morton order impact more visible +large_morton_shards = ( + (32,) * 3, # With 1x1x1 chunks: 32x32x32 = 32768 chunks per shard (power-of-2) + (30,) * 3, # With 1x1x1 chunks: 30x30x30 = 27000 chunks per shard (non-power-of-2) + (33,) + * 3, # With 1x1x1 chunks: 33x33x33 = 35937 chunks per shard (near-miss: just above power-of-2) +) + + +@pytest.mark.parametrize("store", ["memory"], indirect=["store"]) +@pytest.mark.parametrize("shards", large_morton_shards, ids=str) +def test_sharded_morton_indexing_large( + store: Store, + shards: tuple[int, ...], + benchmark: BenchmarkFixture, +) -> None: + """Benchmark sharded array indexing with large chunks_per_shard. + + Uses 1x1x1 chunks to maximize chunks_per_shard (32^3 = 32768), making + the Morton order computation a more significant portion of total time. + The Morton order cache is cleared before each iteration. + """ + from zarr.core.indexing import _morton_order, morton_order_coords + + # 1x1x1 chunks means chunks_per_shard equals shard shape + shape = tuple(s * 2 for s in shards) # 2 shards per dimension + chunks = (1,) * 3 # 1x1x1 chunks: chunks_per_shard = shards + + data = create_array( + store=store, + shape=shape, + dtype="uint8", + chunks=chunks, + shards=shards, + compressors=None, + filters=None, + fill_value=0, + ) + + data[:] = 1 + # Read one full shard + indexer = (slice(shards[0]),) * 3 + + def read_with_cache_clear() -> None: + _morton_order.cache_clear() + morton_order_coords.cache_clear() + getitem(data, indexer) + + benchmark(read_with_cache_clear) + + +@pytest.mark.parametrize("store", ["memory"], indirect=["store"]) +@pytest.mark.parametrize("shards", large_morton_shards, ids=str) +def test_sharded_morton_single_chunk( + store: Store, + shards: tuple[int, ...], + benchmark: BenchmarkFixture, +) -> None: + """Benchmark reading a single chunk from a large shard. + + This isolates the Morton order computation overhead by minimizing I/O. + Reading one chunk from a shard with 32^3 = 32768 chunks still requires + computing the full Morton order, making the optimization impact clear. + The Morton order cache is cleared before each iteration. + """ + from zarr.core.indexing import _morton_order, morton_order_coords + + # 1x1x1 chunks means chunks_per_shard equals shard shape + shape = tuple(s * 2 for s in shards) # 2 shards per dimension + chunks = (1,) * 3 # 1x1x1 chunks: chunks_per_shard = shards + + data = create_array( + store=store, + shape=shape, + dtype="uint8", + chunks=chunks, + shards=shards, + compressors=None, + filters=None, + fill_value=0, + ) + + data[:] = 1 + # Read only a single chunk (1x1x1) from the shard + indexer = (slice(1),) * 3 + + def read_with_cache_clear() -> None: + _morton_order.cache_clear() + morton_order_coords.cache_clear() + getitem(data, indexer) + + benchmark(read_with_cache_clear) + + +# Benchmark for morton_order_coords directly (no I/O) +morton_iter_shapes = ( + (8, 8, 8), # 512 elements (power-of-2) + (10, 10, 10), # 1000 elements (non-power-of-2) + (16, 16, 16), # 4096 elements (power-of-2) + (20, 20, 20), # 8000 elements (non-power-of-2) + (32, 32, 32), # 32768 elements (power-of-2) + (30, 30, 30), # 27000 elements (non-power-of-2) + (33, 33, 33), # 35937 elements (near-miss: just above power-of-2, n_z=262144) +) + + +@pytest.mark.parametrize("shape", morton_iter_shapes, ids=str) +def test_morton_order( + shape: tuple[int, ...], + benchmark: BenchmarkFixture, +) -> None: + """Benchmark morton_order_coords directly without I/O. + + This isolates the Morton order computation to measure the + optimization impact without array read/write overhead. + The cache is cleared before each iteration. + """ + from zarr.core.indexing import _morton_order, morton_order_coords + + def compute_morton_order() -> None: + _morton_order.cache_clear() + morton_order_coords.cache_clear() + # Build the full sequence to force computation + list(morton_order_coords(shape)) + + benchmark(compute_morton_order) + + +@pytest.mark.parametrize("store", ["memory"], indirect=["store"]) +@pytest.mark.parametrize("shards", large_morton_shards, ids=str) +def test_sharded_morton_write_single_chunk( + store: Store, + shards: tuple[int, ...], + benchmark: BenchmarkFixture, +) -> None: + """Benchmark writing a single chunk to a large shard. + + This is the clearest end-to-end demonstration of Morton order optimization. + Writing a single chunk to a shard with 32^3 = 32768 chunks requires + computing the full Morton order, but minimizes I/O overhead. + + Expected improvement: ~160ms (matching Morton computation speedup of ~178ms). + The Morton order cache is cleared before each iteration. + """ + import numpy as np + + from zarr.core.indexing import ( + _lexicographic_order, + _morton_order, + lexicographic_order_coords, + morton_order_coords, + ) + + # 1x1x1 chunks means chunks_per_shard equals shard shape + shape = tuple(s * 2 for s in shards) # 2 shards per dimension + chunks = (1,) * 3 # 1x1x1 chunks: chunks_per_shard = shards + + data = create_array( + store=store, + shape=shape, + dtype="uint8", + chunks=chunks, + shards=shards, + compressors=None, + filters=None, + fill_value=0, + ) + + # Write data for a single chunk + write_data = np.ones((1, 1, 1), dtype="uint8") + indexer = (slice(1), slice(1), slice(1)) + + def write_with_cache_clear() -> None: + # Clear every coordinate cache the write path touches, not just morton: + # the sharded write also builds the lexicographic grid (dict.fromkeys / + # to_dict_vectorized), so a partial clear would leave that path warm and + # under-report the cold build cost. + _morton_order.cache_clear() + morton_order_coords.cache_clear() + _lexicographic_order.cache_clear() + lexicographic_order_coords.cache_clear() + data[indexer] = write_data + + benchmark(write_with_cache_clear) + + +@pytest.mark.parametrize("store", ["memory"], indirect=["store"]) +@pytest.mark.parametrize("shards", large_morton_shards, ids=str) +def test_sharded_morton_write_single_chunk_warm_cache( + store: Store, + shards: tuple[int, ...], + benchmark: BenchmarkFixture, +) -> None: + """Benchmark a single-chunk shard write with the chunk-order cache warm. + + Unlike ``test_sharded_morton_write_single_chunk``, this does NOT clear the + order cache between iterations: it warms the cache once, then repeatedly + writes the same single chunk. This isolates the amortized per-write cost the + cache exists to optimize β€” the regime where the coordinate grid was already + built (by an earlier write to this shard, or to any same-shaped shard) and is + reused rather than rebuilt. Repeated writes to one shard and writes spread + across many same-shaped shards exercise that cache reuse identically. + + This is the regime the cold benchmark cannot see. A regression that rebuilds + the per-shard coordinate tuples on every write (rather than reusing the + cached sequence) is invisible to the cold benchmark but shows up here. + """ + import numpy as np + + from zarr.core.indexing import _morton_order, morton_order_coords + + shape = tuple(s * 2 for s in shards) # 2 shards per dimension + chunks = (1,) * 3 # 1x1x1 chunks: chunks_per_shard = shards + + data = create_array( + store=store, + shape=shape, + dtype="uint8", + chunks=chunks, + shards=shards, + compressors=None, + filters=None, + fill_value=0, + ) + + write_data = np.ones((1, 1, 1), dtype="uint8") + indexer = (slice(1), slice(1), slice(1)) + + # Warm the cache once up front; the timed writes then hit the warm path. + _morton_order.cache_clear() + morton_order_coords.cache_clear() + data[indexer] = write_data + + def write_warm() -> None: + data[indexer] = write_data + + benchmark(write_warm) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000..7ccf9958e7 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,579 @@ +from __future__ import annotations + +import math +import os +import pathlib +import re +import sys +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, cast + +import numpy as np +import numpy.typing as npt +import pytest +from hypothesis import HealthCheck, Verbosity, settings + +import zarr.registry +from zarr import AsyncGroup, config +from zarr.abc.store import Store +from zarr.codecs.sharding import IndexLocation, ShardingCodec +from zarr.core.array import ( + _parse_chunk_encoding_v2, + _parse_chunk_encoding_v3, + _parse_chunk_key_encoding, +) +from zarr.core.chunk_grids import ( + SHARDED_INNER_CHUNK_MAX_BYTES, + as_regular_shape, + guess_chunks, + normalize_chunks_nd, + resolve_outer_and_inner_chunks, +) +from zarr.core.common import ( + JSON, + DimensionNamesLike, + MemoryOrder, + ShapeLike, + ZarrFormat, + parse_shapelike, +) +from zarr.core.config import config as zarr_config +from zarr.core.dtype import ( + get_data_type_from_native_dtype, +) +from zarr.core.dtype.common import HasItemSize +from zarr.core.metadata.v2 import ArrayV2Metadata +from zarr.core.metadata.v3 import ArrayV3Metadata, create_chunk_grid_metadata +from zarr.core.sync import sync +from zarr.storage import FsspecStore, LocalStore, MemoryStore, StorePath, ZipStore +from zarr.testing.store import LatencyStore + +if TYPE_CHECKING: + from collections.abc import Generator + from contextlib import AbstractContextManager + from typing import Any, Literal + + from zarr.abc.codec import Codec + from zarr.core.array import CompressorsLike, FiltersLike, SerializerLike, ShardsLike + from zarr.core.chunk_key_encodings import ( + ChunkKeyEncoding, + ChunkKeyEncodingLike, + V2ChunkKeyEncoding, + ) + from zarr.core.dtype.wrapper import ZDType + + +@dataclass(frozen=True) +class Expect[TIn, TOut]: + """A test case with explicit input, expected output, and a human-readable id.""" + + input: TIn + output: TOut + id: str + + +@dataclass(frozen=True) +class ExpectFail[TIn]: + """A test case that should raise an exception. + + `msg` is a regex matched against the exception text (pytest's native + `match=` semantics). Leave it `None` to assert only the exception type. Set + `escape=True` when `msg` is a literal that contains regex metacharacters + such as `(`, `[`, or `.`; `escape` has no effect when `msg` is `None`. + """ + + input: TIn + exception: type[Exception] + id: str + msg: str | None = None + escape: bool = False + + def raises(self) -> AbstractContextManager[pytest.ExceptionInfo[Exception]]: + if self.msg is None: + return pytest.raises(self.exception) + pattern = re.escape(self.msg) if self.escape else self.msg + return pytest.raises(self.exception, match=pattern) + + +async def parse_store( + store: Literal["local", "memory", "fsspec", "zip", "memory_get_latency"], path: str +) -> LocalStore | MemoryStore | FsspecStore | ZipStore | LatencyStore: + if store == "local": + return await LocalStore.open(path) + if store == "memory": + return await MemoryStore.open() + if store == "fsspec": + return await FsspecStore.open(url=path) + if store == "zip": + return await ZipStore.open(f"{path}/zarr.zip", mode="w") + if store == "memory_get_latency": + return LatencyStore(MemoryStore(), get_latency=0.0001, set_latency=0.0) + raise AssertionError + + +@pytest.fixture(params=[str, pathlib.Path]) +def path_type(request: pytest.FixtureRequest) -> Any: + return request.param + + +# todo: harmonize this with local_store fixture +@pytest.fixture +async def store_path(tmp_path: pathlib.Path) -> StorePath: + store = await LocalStore.open(str(tmp_path)) + return StorePath(store) + + +@pytest.fixture +async def local_store(tmp_path: pathlib.Path) -> LocalStore: + return await LocalStore.open(str(tmp_path)) + + +@pytest.fixture +async def remote_store(url: str) -> FsspecStore: + return await FsspecStore.open(url) + + +@pytest.fixture +async def memory_store() -> MemoryStore: + return await MemoryStore.open() + + +@pytest.fixture +async def zip_store(tmp_path: pathlib.Path) -> ZipStore: + return await ZipStore.open(str(tmp_path / "zarr.zip"), mode="w") + + +@pytest.fixture +async def store(request: pytest.FixtureRequest, tmp_path: pathlib.Path) -> Store: + param = request.param + return await parse_store(param, str(tmp_path)) + + +@pytest.fixture +async def store2(request: pytest.FixtureRequest, tmp_path: pathlib.Path) -> Store: + """Fixture to create a second store for testing copy operations between stores""" + param = request.param + store2_path = tmp_path / "store2" + store2_path.mkdir() + return await parse_store(param, str(store2_path)) + + +@pytest.fixture(params=["local", "memory", "zip"]) +def sync_store(request: pytest.FixtureRequest, tmp_path: pathlib.Path) -> Store: + result = sync(parse_store(request.param, str(tmp_path))) + if not isinstance(result, Store): + raise TypeError(f"Wrong store class returned by test fixture! got {result} instead") + return result + + +@dataclass +class AsyncGroupRequest: + zarr_format: ZarrFormat + store: Literal["local", "fsspec", "memory", "zip"] + attributes: dict[str, Any] = field(default_factory=dict) + + +@pytest.fixture +async def async_group(request: pytest.FixtureRequest, tmp_path: pathlib.Path) -> AsyncGroup: + param: AsyncGroupRequest = request.param + + store = await parse_store(param.store, str(tmp_path)) + return await AsyncGroup.from_store( + store, + attributes=param.attributes, + zarr_format=param.zarr_format, + overwrite=False, + ) + + +@pytest.fixture(params=["numpy", "cupy"]) +def xp(request: pytest.FixtureRequest) -> Any: + """Fixture to parametrize over numpy-like libraries""" + + if request.param == "cupy": + request.node.add_marker(pytest.mark.gpu) + + return pytest.importorskip(request.param) + + +@pytest.fixture(autouse=True) +def reset_config() -> Generator[None, None, None]: + config.reset() + yield + config.reset() + + +@dataclass +class ArrayRequest: + shape: tuple[int, ...] + dtype: str + order: MemoryOrder + + +@pytest.fixture +def array_fixture(request: pytest.FixtureRequest) -> npt.NDArray[Any]: + array_request: ArrayRequest = request.param + return ( + np.arange(np.prod(array_request.shape)) + .reshape(array_request.shape, order=array_request.order) + .astype(array_request.dtype) + ) + + +@pytest.fixture(params=(2, 3), ids=["zarr2", "zarr3"]) +def zarr_format(request: pytest.FixtureRequest) -> ZarrFormat: + if request.param == 2: + return 2 + elif request.param == 3: + return 3 + msg = f"Invalid zarr format requested. Got {request.param}, expected on of (2,3)." + raise ValueError(msg) + + +def _clear_registries() -> None: + registries = zarr.registry._collect_entrypoints() + for registry in registries: + registry.lazy_load_list.clear() + + +@pytest.fixture +def set_path() -> Generator[None, None, None]: + tests_dir = str(pathlib.Path(__file__).parent.absolute()) + sys.path.append(tests_dir) + _clear_registries() + zarr.registry._collect_entrypoints() + + yield + + sys.path.remove(tests_dir) + _clear_registries() + zarr.registry._collect_entrypoints() + config.reset() + + +def pytest_addoption(parser: Any) -> None: + parser.addoption( + "--run-slow-hypothesis", + action="store_true", + default=False, + help="run slow hypothesis tests", + ) + + +def pytest_collection_modifyitems(config: Any, items: Any) -> None: + if config.getoption("--run-slow-hypothesis"): + return + skip_slow_hyp = pytest.mark.skip(reason="need --run-slow-hypothesis option to run") + for item in items: + if "slow_hypothesis" in item.keywords: + item.add_marker(skip_slow_hyp) + + +settings.register_profile( + "default", + parent=settings.get_profile("default"), + max_examples=300, + suppress_health_check=[HealthCheck.filter_too_much, HealthCheck.too_slow], + deadline=None, + verbosity=Verbosity.verbose, +) +settings.register_profile( + "ci", + parent=settings.get_profile("ci"), + max_examples=300, + derandomize=True, # more like regression testing + deadline=None, + suppress_health_check=[HealthCheck.filter_too_much, HealthCheck.too_slow], +) +settings.register_profile( + "nightly", + max_examples=500, + parent=settings.get_profile("ci"), + derandomize=False, + stateful_step_count=100, +) + +settings.load_profile(os.getenv("HYPOTHESIS_PROFILE", "default")) + + +# TODO: uncomment these overrides when we can get mypy to accept them +""" +@overload +def create_array_metadata( + *, + shape: ShapeLike, + dtype: npt.DTypeLike, + chunks: tuple[int, ...] | Literal["auto"], + shards: None, + filters: FiltersLike, + compressors: CompressorsLike, + serializer: SerializerLike, + fill_value: Any | None, + order: MemoryOrder | None, + zarr_format: Literal[2], + attributes: dict[str, JSON] | None, + chunk_key_encoding: ChunkKeyEncoding | ChunkKeyEncodingLike | None, + dimension_names: None, +) -> ArrayV2Metadata: ... + + +@overload +def create_array_metadata( + *, + shape: ShapeLike, + dtype: npt.DTypeLike, + chunks: tuple[int, ...] | Literal["auto"], + shards: ShardsLike | None, + filters: FiltersLike, + compressors: CompressorsLike, + serializer: SerializerLike, + fill_value: Any | None, + order: None, + zarr_format: Literal[3], + attributes: dict[str, JSON] | None, + chunk_key_encoding: ChunkKeyEncoding | ChunkKeyEncodingLike | None, + dimension_names: Iterable[str] | None, +) -> ArrayV3Metadata: ... +""" + + +def create_array_metadata( + *, + shape: ShapeLike, + dtype: npt.DTypeLike, + chunks: tuple[int, ...] | Literal["auto"] = "auto", + shards: ShardsLike | None = None, + filters: FiltersLike = "auto", + compressors: CompressorsLike = "auto", + serializer: SerializerLike = "auto", + fill_value: Any = 0, + order: MemoryOrder | None = None, + zarr_format: ZarrFormat, + attributes: dict[str, JSON] | None = None, + chunk_key_encoding: ChunkKeyEncoding | ChunkKeyEncodingLike | None = None, + dimension_names: DimensionNamesLike = None, +) -> ArrayV2Metadata | ArrayV3Metadata: + """ + Create array metadata + """ + dtype_parsed = get_data_type_from_native_dtype(dtype) + shape_parsed = parse_shapelike(shape) + chunk_key_encoding_parsed = _parse_chunk_key_encoding( + chunk_key_encoding, zarr_format=zarr_format + ) + item_size = 1 + if isinstance(dtype_parsed, HasItemSize): + item_size = dtype_parsed.item_size + if chunks == "auto": + chunks_normalized = guess_chunks( + shape_parsed, + item_size, + max_bytes=SHARDED_INNER_CHUNK_MAX_BYTES if shards is not None else None, + ) + else: + chunks_normalized = normalize_chunks_nd(chunks, shape_parsed) + outer_chunks, inner = resolve_outer_and_inner_chunks( + array_shape=shape_parsed, + chunks=chunks_normalized, + shard_shape=shards, + item_size=item_size, + ) + + if order is None: + order_parsed = zarr_config.get("array.order") + else: + order_parsed = order + + if zarr_format == 2: + filters_parsed, compressor_parsed = _parse_chunk_encoding_v2( + compressor=compressors, filters=filters, dtype=dtype_parsed + ) + chunk_key_encoding_parsed = cast("V2ChunkKeyEncoding", chunk_key_encoding_parsed) + return ArrayV2Metadata( + shape=shape_parsed, + dtype=dtype_parsed, + chunks=as_regular_shape(outer_chunks), + order=order_parsed, + dimension_separator=chunk_key_encoding_parsed.separator, + fill_value=fill_value, + compressor=compressor_parsed, + filters=filters_parsed, + attributes=attributes, + ) + elif zarr_format == 3: + array_array, array_bytes, bytes_bytes = _parse_chunk_encoding_v3( + compressors=compressors, + filters=filters, + serializer=serializer, + dtype=dtype_parsed, + ) + + sub_codecs: tuple[Codec, ...] = (*array_array, array_bytes, *bytes_bytes) + codecs_out: tuple[Codec, ...] + if inner is not None: + inner_chunks_flat = as_regular_shape(inner.outer_chunks) + index_location: IndexLocation = "end" + if isinstance(shards, dict): + index_location = cast("IndexLocation", shards.get("index_location", "end")) + sharding_codec = ShardingCodec( + chunk_shape=inner_chunks_flat, + codecs=sub_codecs, + index_location=index_location, + ) + validation_grid = create_chunk_grid_metadata(outer_chunks) + sharding_codec.validate( + shape=inner_chunks_flat, + dtype=dtype_parsed, + chunk_grid=validation_grid, + ) + codecs_out = (sharding_codec,) + else: + codecs_out = sub_codecs + + return ArrayV3Metadata( + shape=shape_parsed, + data_type=dtype_parsed, + chunk_grid=create_chunk_grid_metadata(outer_chunks), + chunk_key_encoding=chunk_key_encoding_parsed, + fill_value=fill_value, + codecs=codecs_out, + attributes=attributes, + dimension_names=dimension_names, + ) + + raise ValueError(f"Invalid Zarr format: {zarr_format}") + + +# TODO: uncomment these overrides when we can get mypy to accept them +""" +@overload +def meta_from_array( + array: np.ndarray[Any, Any], + chunks: tuple[int, ...] | Literal["auto"], + shards: None, + filters: FiltersLike, + compressors: CompressorsLike, + serializer: SerializerLike, + fill_value: Any | None, + order: MemoryOrder | None, + zarr_format: Literal[2], + attributes: dict[str, JSON] | None, + chunk_key_encoding: ChunkKeyEncoding | ChunkKeyEncodingLike | None, + dimension_names: Iterable[str] | None, +) -> ArrayV2Metadata: ... + + +@overload +def meta_from_array( + array: np.ndarray[Any, Any], + chunks: tuple[int, ...] | Literal["auto"], + shards: ShardsLike | None, + filters: FiltersLike, + compressors: CompressorsLike, + serializer: SerializerLike, + fill_value: Any | None, + order: None, + zarr_format: Literal[3], + attributes: dict[str, JSON] | None, + chunk_key_encoding: ChunkKeyEncoding | ChunkKeyEncodingLike | None, + dimension_names: Iterable[str] | None, +) -> ArrayV3Metadata: ... + +""" + + +def meta_from_array( + array: np.ndarray[Any, Any], + *, + chunks: tuple[int, ...] | Literal["auto"] = "auto", + shards: ShardsLike | None = None, + filters: FiltersLike = "auto", + compressors: CompressorsLike = "auto", + serializer: SerializerLike = "auto", + fill_value: Any = 0, + order: MemoryOrder | None = None, + zarr_format: ZarrFormat = 3, + attributes: dict[str, JSON] | None = None, + chunk_key_encoding: ChunkKeyEncoding | ChunkKeyEncodingLike | None = None, + dimension_names: DimensionNamesLike = None, +) -> ArrayV3Metadata | ArrayV2Metadata: + """ + Create array metadata from an array + """ + return create_array_metadata( + shape=array.shape, + dtype=array.dtype, + chunks=chunks, + shards=shards, + filters=filters, + compressors=compressors, + serializer=serializer, + fill_value=fill_value, + order=order, + zarr_format=zarr_format, + attributes=attributes, + chunk_key_encoding=chunk_key_encoding, + dimension_names=dimension_names, + ) + + +def skip_object_dtype(dtype: ZDType[Any, Any]) -> None: + if dtype.dtype_cls is type(np.dtype("O")): + msg = ( + f"{dtype} uses the numpy object data type, which is not a valid target for data " + "type resolution" + ) + pytest.skip(msg) + + +def nan_equal(a: object, b: object) -> bool: + """ + Convenience function for equality comparison between two values ``a`` and ``b``, that might both + be NaN. Returns True if both ``a`` and ``b`` are NaN, otherwise returns a == b + """ + if math.isnan(a) and math.isnan(b): # type: ignore[arg-type] + return True + return a == b + + +def deep_nan_equal(a: object, b: object) -> bool: + if isinstance(a, Mapping) and isinstance(b, Mapping): + return all(deep_nan_equal(a[k], b[k]) for k in a) + if isinstance(a, Sequence) and isinstance(b, Sequence): + return all(deep_nan_equal(a[i], b[i]) for i in range(len(a))) + return nan_equal(a, b) + + +# Shared mock-S3 (moto) backend. A single server is reused across the whole test session by +# every test that needs S3 -- both the fsspec store tests and the documentation examples -- +# instead of each module standing up its own. Consumers create their own buckets and choose +# how the endpoint reaches the client (explicit storage_options vs. the AWS_ENDPOINT_URL +# env var) on top of this fixture. + + +@pytest.fixture(scope="session") +def moto_server() -> Generator[str, None, None]: + """Start a session-scoped moto S3 server and yield its endpoint URL. + + The server binds an ephemeral port (port=0), so the endpoint is only known at + runtime; consumers must take it from this fixture rather than a constant. A fixed + port deadlocks under pytest-xdist: session-scoped fixtures run once per *worker*, so + concurrent workers race to bind the same port, and the losers block forever inside + ThreadedMotoServer.start(), whose server thread dies on "Address already in use" + before ever setting the ready event that start() waits on. + + importorskip lives inside the fixture so moto is only required when a test actually + requests an S3 backend, not for the whole test session.""" + moto_server_mod = pytest.importorskip("moto.moto_server.threaded_moto_server") + + server = moto_server_mod.ThreadedMotoServer(ip_address="127.0.0.1", port=0) + server.start() + host, port = server.get_host_and_port() + # moto needs *some* credentials present; use throwaway values if the environment has none. + os.environ.setdefault("AWS_SECRET_ACCESS_KEY", "foo") + os.environ.setdefault("AWS_ACCESS_KEY_ID", "foo") + try: + yield f"http://{host}:{port}/" + finally: + server.stop() diff --git a/tests/v3/package_with_entrypoint-0.1.dist-info/entry_points.txt b/tests/package_with_entrypoint-0.1.dist-info/entry_points.txt similarity index 89% rename from tests/v3/package_with_entrypoint-0.1.dist-info/entry_points.txt rename to tests/package_with_entrypoint-0.1.dist-info/entry_points.txt index eee724c912..7eb0eb7c86 100644 --- a/tests/v3/package_with_entrypoint-0.1.dist-info/entry_points.txt +++ b/tests/package_with_entrypoint-0.1.dist-info/entry_points.txt @@ -12,3 +12,5 @@ another_buffer = package_with_entrypoint:TestEntrypointGroup.Buffer another_ndbuffer = package_with_entrypoint:TestEntrypointGroup.NDBuffer [zarr.codec_pipeline] another_pipeline = package_with_entrypoint:TestEntrypointGroup.Pipeline +[zarr.data_type] +new_data_type = package_with_entrypoint:TestDataType \ No newline at end of file diff --git a/tests/package_with_entrypoint/__init__.py b/tests/package_with_entrypoint/__init__.py new file mode 100644 index 0000000000..23afcf1dc2 --- /dev/null +++ b/tests/package_with_entrypoint/__init__.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np +import numpy.typing as npt + +import zarr.core.buffer +from zarr.abc.codec import ArrayBytesCodec, CodecInput, CodecPipeline +from zarr.codecs import BytesCodec +from zarr.core.buffer import Buffer, NDBuffer +from zarr.core.dtype.npy.bool import Bool +from zarr.errors import DataTypeValidationError + +if TYPE_CHECKING: + from collections.abc import Iterable + from typing import Any, ClassVar, Literal, Self + + from zarr.core.array_spec import ArraySpec + from zarr.core.common import ZarrFormat + from zarr.core.dtype.common import DTypeJSON, DTypeSpec_V2 + + +class TestEntrypointCodec(ArrayBytesCodec): + is_fixed_size = True + + async def encode( + self, + chunks_and_specs: Iterable[tuple[CodecInput | None, ArraySpec]], + ) -> Iterable[Buffer | None]: + return [None] + + async def decode( + self, + chunks_and_specs: Iterable[tuple[CodecInput | None, ArraySpec]], + ) -> npt.NDArray[Any]: + return np.array(1) + + def compute_encoded_size(self, input_byte_length: int, chunk_spec: ArraySpec) -> int: + return input_byte_length + + +class TestEntrypointCodecPipeline(CodecPipeline): + def __init__(self, batch_size: int = 1) -> None: + pass + + async def encode( + self, chunks_and_specs: Iterable[tuple[CodecInput | None, ArraySpec]] + ) -> Iterable[Buffer | None]: + return [None] + + async def decode( + self, chunks_and_specs: Iterable[tuple[CodecInput | None, ArraySpec]] + ) -> Iterable[NDBuffer | None]: + return np.array(1) + + +class TestEntrypointBuffer(Buffer): + pass + + +class TestEntrypointNDBuffer(NDBuffer): + pass + + +class TestEntrypointGroup: + class Codec(BytesCodec): + pass + + class Buffer(zarr.core.buffer.Buffer): + pass + + class NDBuffer(zarr.core.buffer.NDBuffer): + pass + + class Pipeline(CodecPipeline): + pass + + +class TestDataType(Bool): + """ + This is a "data type" that serializes to "test" + """ + + _zarr_v3_name: ClassVar[Literal["test"]] = "test" # type: ignore[assignment] + + @classmethod + def from_json(cls, data: DTypeJSON, *, zarr_format: ZarrFormat) -> Self: + if zarr_format == 2 and data == {"name": cls._zarr_v3_name, "object_codec_id": None}: + return cls() + if zarr_format == 3 and data == cls._zarr_v3_name: + return cls() + raise DataTypeValidationError( + f"Invalid JSON representation of {cls.__name__}. Got {data!r}" + ) + + def to_json(self, zarr_format: ZarrFormat) -> str | DTypeSpec_V2: # type: ignore[override] + if zarr_format == 2: + return {"name": self._zarr_v3_name, "object_codec_id": None} + if zarr_format == 3: + return self._zarr_v3_name + raise ValueError("zarr_format must be 2 or 3") diff --git a/tests/test_abc/__init__.py b/tests/test_abc/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_abc/test_codec.py b/tests/test_abc/test_codec.py new file mode 100644 index 0000000000..e0f9ddb7bb --- /dev/null +++ b/tests/test_abc/test_codec.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +from zarr.abc.codec import _check_codecjson_v2 + + +def test_check_codecjson_v2_valid() -> None: + """ + Test that the _check_codecjson_v2 function works + """ + assert _check_codecjson_v2({"id": "gzip"}) + assert not _check_codecjson_v2({"id": 10}) + assert not _check_codecjson_v2([10, 11]) diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 0000000000..45d0c0dee4 --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,1627 @@ +from __future__ import annotations + +import inspect +import re +from typing import TYPE_CHECKING, Any + +import zarr.codecs +import zarr.storage +from zarr.core.array import AsyncArray, init_array +from zarr.storage import LocalStore, ZipStore +from zarr.storage._common import StorePath + +if TYPE_CHECKING: + from collections.abc import Callable + from pathlib import Path + + from zarr.abc.store import Store + from zarr.core.common import JSON, MemoryOrder, ZarrFormat + from zarr.types import AnyArray + +import contextlib +from typing import Literal + +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +import zarr +import zarr.api.asynchronous +import zarr.api.synchronous +import zarr.core.group +from zarr import Array, Group +from zarr.api.synchronous import ( + create, + create_array, + create_group, + from_array, + group, + load, + open_group, + save, + save_array, + save_group, +) +from zarr.core.buffer import NDArrayLike +from zarr.errors import ( + ArrayNotFoundError, + MetadataValidationError, + ZarrDeprecationWarning, + ZarrUserWarning, +) +from zarr.storage import MemoryStore +from zarr.storage._utils import normalize_path +from zarr.testing.utils import gpu_test + + +def test_create(memory_store: Store) -> None: + store = memory_store + + # create array + z = create(shape=100, store=store) + assert isinstance(z, Array) + assert z.shape == (100,) + + # create array, overwrite, specify chunk shape + z = create(shape=200, chunk_shape=20, store=store, overwrite=True) + assert isinstance(z, Array) + assert z.shape == (200,) + assert z.chunks == (20,) + + # create array, overwrite, specify chunk shape via chunks param + z = create(shape=400, chunks=40, store=store, overwrite=True) + assert isinstance(z, Array) + assert z.shape == (400,) + assert z.chunks == (40,) + + # create array with float shape + with pytest.raises(TypeError, match="Expected an iterable of integers"): + z = create(shape=(400.5, 100), store=store, overwrite=True) # type: ignore[arg-type] + + # create array with float chunk shape + with pytest.raises(TypeError, match="Chunk specification must be an integer or an iterable"): + z = create(shape=(400, 100), chunks=(16, 16.5), store=store, overwrite=True) # type: ignore[arg-type] + + +@pytest.mark.parametrize( + "func", + [ + zarr.api.asynchronous.zeros_like, + zarr.api.asynchronous.ones_like, + zarr.api.asynchronous.empty_like, + zarr.api.asynchronous.full_like, + zarr.api.asynchronous.open_like, + ], +) +@pytest.mark.parametrize("out_shape", ["keep", (10, 10)]) +@pytest.mark.parametrize("out_chunks", ["keep", (10, 10)]) +@pytest.mark.parametrize("out_dtype", ["keep", "int8"]) +@pytest.mark.parametrize("out_fill", ["keep", 4]) +async def test_array_like_creation( + zarr_format: ZarrFormat, + func: Callable[[Any], Any], + out_shape: Literal["keep"] | tuple[int, ...], + out_chunks: Literal["keep"] | tuple[int, ...], + out_dtype: str, + out_fill: Literal["keep"] | int, +) -> None: + """ + Test zeros_like, ones_like, empty_like, full_like, ensuring that we can override the + shape, chunks, dtype and fill_value of the array-like object provided to these functions with + appropriate keyword arguments + """ + ref_fill = 100 + ref_arr = zarr.create_array( + store={}, + shape=(11, 12), + dtype="uint8", + chunks=(11, 12), + zarr_format=zarr_format, + fill_value=ref_fill, + ) + kwargs: dict[str, object] = {} + if func is zarr.api.asynchronous.full_like: + if out_fill == "keep": + expect_fill = ref_fill + else: + expect_fill = out_fill + kwargs["fill_value"] = expect_fill + elif func is zarr.api.asynchronous.zeros_like: + expect_fill = 0 + elif func is zarr.api.asynchronous.ones_like: + expect_fill = 1 + elif func is zarr.api.asynchronous.empty_like: + if out_fill == "keep": + expect_fill = ref_fill + else: + kwargs["fill_value"] = out_fill + expect_fill = out_fill + elif func is zarr.api.asynchronous.open_like: # type: ignore[comparison-overlap] + if out_fill == "keep": # type: ignore[unreachable] + expect_fill = ref_fill + else: + kwargs["fill_value"] = out_fill + expect_fill = out_fill + kwargs["mode"] = "w" + else: + raise AssertionError + if out_shape != "keep": + kwargs["shape"] = out_shape + expect_shape = out_shape + else: + expect_shape = ref_arr.shape + if out_chunks != "keep": + kwargs["chunks"] = out_chunks + expect_chunks = out_chunks + else: + expect_chunks = ref_arr.chunks + if out_dtype != "keep": + kwargs["dtype"] = out_dtype + expect_dtype = out_dtype + else: + expect_dtype = ref_arr.dtype # type: ignore[assignment] + + new_arr = await func(ref_arr, path="foo", zarr_format=zarr_format, **kwargs) + assert new_arr.shape == expect_shape + assert new_arr.chunks == expect_chunks + assert new_arr.dtype == expect_dtype + assert np.all(Array(new_arr)[:] == expect_fill) + + +@pytest.mark.parametrize("mode_kwargs", [{}, {"mode": None}]) +async def test_open_like_creates_array_by_default( + zarr_format: ZarrFormat, mode_kwargs: dict[str, None] +) -> None: + ref_arr = zarr.create_array( + store={}, + shape=(11, 12), + dtype="uint8", + chunks=(11, 12), + zarr_format=zarr_format, + fill_value=100, + ) + + new_arr = await zarr.api.asynchronous.open_like( + ref_arr, + path="foo", + store={}, + zarr_format=zarr_format, + **mode_kwargs, + ) + + assert new_arr.shape == ref_arr.shape + assert new_arr.chunks == ref_arr.chunks + assert new_arr.dtype == ref_arr.dtype + assert np.all(Array(new_arr)[:] == ref_arr.fill_value) + + +async def test_open_like_default_mode_rejects_read_only_store( + zarr_format: ZarrFormat, +) -> None: + ref_arr = zarr.create_array( + store={}, + shape=(11, 12), + dtype="uint8", + chunks=(11, 12), + zarr_format=zarr_format, + ) + + with pytest.raises(ValueError, match="Store is read-only but mode is 'a'"): + await zarr.api.asynchronous.open_like( + ref_arr, + path="foo", + store=MemoryStore(read_only=True), + zarr_format=zarr_format, + ) + + +# TODO: parametrize over everything this function takes +@pytest.mark.parametrize("store", ["memory"], indirect=True) +def test_create_array(store: Store, zarr_format: ZarrFormat) -> None: + attrs: dict[str, JSON] = {"foo": 100} # explicit type annotation to avoid mypy error + shape = (10, 10) + path = "foo" + data_val = 1 + array_w = create_array( + store, + name=path, + shape=shape, + attributes=attrs, + chunks=shape, + dtype="uint8", + zarr_format=zarr_format, + ) + array_w[:] = data_val + assert array_w.shape == shape + assert array_w.attrs == attrs + assert np.array_equal(array_w[:], np.zeros(shape, dtype=array_w.dtype) + data_val) # type: ignore[unreachable] + + +@pytest.mark.parametrize("write_empty_chunks", [True, False]) +def test_write_empty_chunks_warns(write_empty_chunks: bool, zarr_format: ZarrFormat) -> None: + """ + Test that using the `write_empty_chunks` kwarg on array access will raise a warning. + """ + match = "The `write_empty_chunks` keyword argument .*" + with pytest.warns(RuntimeWarning, match=match): + _ = zarr.array( + data=np.arange(10), + shape=(10,), + dtype="uint8", + write_empty_chunks=write_empty_chunks, + zarr_format=zarr_format, + ) + + with pytest.warns(RuntimeWarning, match=match): + _ = zarr.create( + shape=(10,), + dtype="uint8", + write_empty_chunks=write_empty_chunks, + zarr_format=zarr_format, + ) + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_open_array_respects_write_empty_chunks_config(zarr_format: ZarrFormat) -> None: + """Test that zarr.open() respects write_empty_chunks config.""" + store = MemoryStore() + + _ = zarr.create( + store=store, + path="test_array", + shape=(10,), + chunks=(5,), + dtype="f8", + fill_value=0.0, + zarr_format=zarr_format, + ) + + arr2 = zarr.open(store=store, path="test_array", config={"write_empty_chunks": True}) + assert isinstance(arr2, zarr.Array) + + assert arr2.async_array.config.write_empty_chunks is True + + arr2[0:5] = np.zeros(5) + assert arr2.nchunks_initialized == 1 + + +@pytest.mark.parametrize("path", ["foo", "/", "/foo", "///foo/bar"]) +@pytest.mark.parametrize("node_type", ["array", "group"]) +def test_open_normalized_path( + memory_store: MemoryStore, path: str, node_type: Literal["array", "group"] +) -> None: + node: Group | AnyArray + if node_type == "group": + node = group(store=memory_store, path=path) + elif node_type == "array": + node = create(store=memory_store, path=path, shape=(2,)) + + assert node.path == normalize_path(path) + + +async def test_open_array(memory_store: MemoryStore, zarr_format: ZarrFormat) -> None: + store = memory_store + + # open array, create if doesn't exist + z = zarr.api.synchronous.open(store=store, shape=100, zarr_format=zarr_format) + assert isinstance(z, Array) + assert z.shape == (100,) + + # open array, overwrite + # store._store_dict = {} + store = MemoryStore() + z = zarr.api.synchronous.open(store=store, shape=200, zarr_format=zarr_format) + assert isinstance(z, Array) + assert z.shape == (200,) + + # open array, read-only + store_cls = type(store) + ro_store = await store_cls.open(store_dict=store._store_dict, read_only=True) + z = zarr.api.synchronous.open(store=ro_store, mode="r") + assert isinstance(z, Array) + assert z.shape == (200,) + assert z.read_only + + # path not found + with pytest.raises(FileNotFoundError): + zarr.api.synchronous.open(store="doesnotexist", mode="r", zarr_format=zarr_format) + + +def test_open_array_rectilinear_chunks(tmp_path: Path) -> None: + """zarr.open with rectilinear (dask-style) chunks preserves the chunk grid.""" + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata + + chunks = ((3, 3, 4), (5, 5)) + with zarr.config.set({"array.rectilinear_chunks": True}): + z = zarr.open(store=tmp_path, shape=(10, 10), dtype="float64", chunks=chunks, mode="w") + assert isinstance(z, Array) + assert z.shape == (10, 10) + assert isinstance(z.metadata.chunk_grid, RectilinearChunkGridMetadata) + assert z.read_chunk_sizes == ((3, 3, 4), (5, 5)) + + +async def test_async_array_open_array_not_found() -> None: + """Test that AsyncArray.open raises ArrayNotFoundError when array doesn't exist""" + store = MemoryStore() + # Try to open an array that does not exist + with pytest.raises(ArrayNotFoundError): + await AsyncArray.open(store, zarr_format=2) + + +def test_array_open_array_not_found_sync() -> None: + """Test that Array.open raises ArrayNotFoundError when array doesn't exist""" + store = MemoryStore() + # Try to open an array that does not exist + with pytest.raises(ArrayNotFoundError): + Array.open(store) + + +@pytest.mark.parametrize("store", ["memory", "local", "zip"], indirect=True) +def test_v2_and_v3_exist_at_same_path(store: Store) -> None: + zarr.create_array(store, shape=(10,), dtype="uint8", zarr_format=3) + zarr.create_array(store, shape=(10,), dtype="uint8", zarr_format=2) + msg = f"Both zarr.json (Zarr format 3) and .zarray (Zarr format 2) metadata objects exist at {store}. Zarr v3 will be used." + with pytest.warns(ZarrUserWarning, match=re.escape(msg)): + zarr.open(store=store) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +async def test_create_group(store: Store, zarr_format: ZarrFormat) -> None: + attrs = {"foo": 100} + path = "node" + node = create_group(store, path=path, attributes=attrs, zarr_format=zarr_format) + assert isinstance(node, Group) + assert node.attrs == attrs + assert node.metadata.zarr_format == zarr_format # type: ignore[unreachable] + + +async def test_open_group(memory_store: MemoryStore) -> None: + store = memory_store + + # open group, create if doesn't exist + g = open_group(store=store) + g.create_group("foo") + assert isinstance(g, Group) + assert "foo" in g + + # open group, overwrite + g = open_group(store=store, mode="w") + assert isinstance(g, Group) + assert "foo" not in g + + # open group, read-only + store_cls = type(store) + ro_store = await store_cls.open(store_dict=store._store_dict, read_only=True) + g = open_group(store=ro_store, mode="r") + assert isinstance(g, Group) + assert g.read_only + + +@pytest.mark.parametrize("zarr_format", [None, 2, 3]) +async def test_open_group_unspecified_version(tmp_path: Path, zarr_format: ZarrFormat) -> None: + """Regression test for https://github.com/zarr-developers/zarr-python/issues/2175""" + + # create a group with specified zarr format (could be 2, 3, or None) + _ = await zarr.api.asynchronous.open_group( + store=str(tmp_path), mode="w", zarr_format=zarr_format, attributes={"foo": "bar"} + ) + + # now open that group without specifying the format + g2 = await zarr.api.asynchronous.open_group(store=str(tmp_path), mode="r") + + assert g2.attrs == {"foo": "bar"} + + if zarr_format is not None: + assert g2.metadata.zarr_format == zarr_format + + +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +@pytest.mark.parametrize("n_args", [10, 1, 0]) +@pytest.mark.parametrize("n_kwargs", [10, 1, 0]) +@pytest.mark.parametrize("path", [None, "some_path"]) +def test_save(store: Store, n_args: int, n_kwargs: int, path: str | None) -> None: + data = np.arange(10) + args = [np.arange(10) for _ in range(n_args)] + kwargs = {f"arg_{i}": data for i in range(n_kwargs)} + + if n_kwargs == 0 and n_args == 0: + with pytest.raises(ValueError, match="at least one array must be provided"): + save(store, path=path) + elif n_args == 1 and n_kwargs == 0: + save(store, *args, path=path) + array = zarr.api.synchronous.open(store, path=path) + assert isinstance(array, Array) + assert_array_equal(array[:], data) + else: + save(store, *args, path=path, **kwargs) # type: ignore[arg-type] + group = zarr.api.synchronous.open(store, path=path) + assert isinstance(group, Group) + for array in group.array_values(): + assert_array_equal(array[:], data) + for k in kwargs: + assert k in group + assert group.nmembers() == n_args + n_kwargs + + +@pytest.mark.parametrize( + "data", + [ + np.array(42, dtype=np.int64), + np.array("teststr", dtype=np.bytes_), + ], +) +@pytest.mark.filterwarnings("ignore::zarr.errors.UnstableSpecificationWarning") +def test_group_setitem_loads_scalar_arrays(sync_store: Store, data: np.ndarray) -> None: + root = zarr.open_group(store=sync_store) + root["test"] = data + + assert_array_equal(root["test"][...], data) + assert_array_equal(zarr.load(store=sync_store, path="test"), data) + + +def test_save_errors() -> None: + with pytest.raises(ValueError, match="at least one array must be provided"): + # no arrays provided + save_group("data/group.zarr") + with pytest.raises(TypeError, match="missing 1 required positional argument: 'arr'"): + # no array provided + save_array("data/group.zarr") # type: ignore[call-arg] + with pytest.raises(ValueError, match="at least one array must be provided"): + # no arrays provided + save("data/group.zarr") + a = np.arange(10) + with pytest.raises( + TypeError, match="Keyword argument 'mode' must be a numpy or other NDArrayLike array" + ): + # mode is no valid argument and would get handled as an array + zarr.save("data/example.zarr", a, mode="w") + + +def test_open_with_mode_r(tmp_path: Path) -> None: + # 'r' means read only (must exist) + with pytest.raises(FileNotFoundError): + zarr.open(store=tmp_path, mode="r") + z1 = zarr.ones(store=tmp_path, shape=(3, 3)) + assert z1.fill_value == 1 + z2 = zarr.open(store=tmp_path, mode="r") + assert isinstance(z2, Array) + assert z2.fill_value == 1 + result = z2[:] + assert isinstance(result, NDArrayLike) + assert (result == 1).all() + with pytest.raises(ValueError): + z2[:] = 3 + + +def test_open_with_mode_r_plus(tmp_path: Path) -> None: + # 'r+' means read/write (must exist) + new_store_path = tmp_path / "new_store.zarr" + assert not new_store_path.exists(), "Test should operate on non-existent directory" + with pytest.raises(FileNotFoundError): + zarr.open(store=new_store_path, mode="r+") + assert not new_store_path.exists(), "mode='r+' should not create directory" + + zarr.ones(store=tmp_path, shape=(3, 3)) + z2 = zarr.open(store=tmp_path, mode="r+") + assert isinstance(z2, Array) + result = z2[:] + assert isinstance(result, NDArrayLike) + assert (result == 1).all() + z2[:] = 3 + + +async def test_open_with_mode_a(tmp_path: Path) -> None: + # Open without shape argument should default to group + g = zarr.open(store=tmp_path, mode="a") + assert isinstance(g, Group) + await g.store_path.delete() + + # 'a' means read/write (create if doesn't exist) + arr = zarr.open(store=tmp_path, mode="a", shape=(3, 3)) + assert isinstance(arr, Array) + arr[...] = 1 + z2 = zarr.open(store=tmp_path, mode="a") + assert isinstance(z2, Array) + result = z2[:] + assert isinstance(result, NDArrayLike) + assert (result == 1).all() + z2[:] = 3 + + +def test_open_with_mode_w(tmp_path: Path) -> None: + # 'w' means create (overwrite if exists); + arr = zarr.open(store=tmp_path, mode="w", shape=(3, 3)) + assert isinstance(arr, Array) + + arr[...] = 3 + z2 = zarr.open(store=tmp_path, mode="w", shape=(3, 3)) + assert isinstance(z2, Array) + result = z2[:] + assert isinstance(result, NDArrayLike) + assert not (result == 3).all() + z2[:] = 3 + + +def test_open_with_mode_w_minus(tmp_path: Path) -> None: + # 'w-' means create (fail if exists) + arr = zarr.open(store=tmp_path, mode="w-", shape=(3, 3)) + assert isinstance(arr, Array) + arr[...] = 1 + with pytest.raises(FileExistsError): + zarr.open(store=tmp_path, mode="w-") + + +@pytest.mark.parametrize("order", ["C", "F", None]) +@pytest.mark.parametrize("config", [{"order": "C"}, {"order": "F"}, {}], ids=["C", "F", "None"]) +def test_array_order( + order: MemoryOrder | None, config: dict[str, MemoryOrder | None], zarr_format: ZarrFormat +) -> None: + """ + Check that: + - For v2, memory order is taken from the `order` keyword argument. + - For v3, memory order is taken from `config`, and when order is passed a warning is raised + - The numpy array returned has the expected order + - For v2, the order metadata is set correctly + """ + default_order = zarr.config.get("array.order") + ctx: contextlib.AbstractContextManager # type: ignore[type-arg] + + if zarr_format == 3: + if order is None: + ctx = contextlib.nullcontext() + else: + ctx = pytest.warns( + RuntimeWarning, + match="The `order` keyword argument has no effect for Zarr format 3 arrays", + ) + + expected_order = config.get("order", default_order) + + if zarr_format == 2: + ctx = contextlib.nullcontext() + expected_order = order or config.get("order", default_order) + + with ctx: + arr = zarr.ones(shape=(2, 2), order=order, zarr_format=zarr_format, config=config) + + assert arr.order == expected_order + vals = np.asarray(arr) + if expected_order == "C": + assert vals.flags.c_contiguous + elif expected_order == "F": + assert vals.flags.f_contiguous + else: + raise AssertionError + + if zarr_format == 2: + assert arr.metadata.zarr_format == 2 + assert arr.metadata.order == expected_order + + +async def test_init_order_warns() -> None: + with pytest.warns( + RuntimeWarning, match="The `order` keyword argument has no effect for Zarr format 3 arrays" + ): + await init_array( + store_path=StorePath(store=MemoryStore()), + shape=(1,), + dtype="uint8", + zarr_format=3, + order="F", + ) + + +# def test_lazy_loader(): +# foo = np.arange(100) +# bar = np.arange(100, 0, -1) +# store = "data/group.zarr" +# save(store, foo=foo, bar=bar) +# loader = load(store) +# assert "foo" in loader +# assert "bar" in loader +# assert "baz" not in loader +# assert len(loader) == 2 +# assert sorted(loader) == ["bar", "foo"] +# assert_array_equal(foo, loader["foo"]) +# assert_array_equal(bar, loader["bar"]) +# assert "LazyLoader: " in repr(loader) + + +def test_load_array(sync_store: Store) -> None: + store = sync_store + foo = np.arange(100) + bar = np.arange(100, 0, -1) + save(store, foo=foo, bar=bar) + + # can also load arrays directly into a numpy array + for array_name in ["foo", "bar"]: + array = load(store, path=array_name) + assert isinstance(array, np.ndarray) + if array_name == "foo": + assert_array_equal(foo, array) + else: + assert_array_equal(bar, array) + + +@pytest.mark.parametrize("path", ["data", None]) +@pytest.mark.parametrize("load_read_only", [True, False, None]) +def test_load_zip(tmp_path: Path, path: str | None, load_read_only: bool | None) -> None: + file = tmp_path / "test.zip" + data = np.arange(100).reshape(10, 10) + + with ZipStore(file, mode="w", read_only=False) as zs: + save(zs, data, path=path) + with ZipStore(file, mode="r", read_only=load_read_only) as zs: + result = zarr.load(store=zs, path=path) + assert isinstance(result, np.ndarray) + assert np.array_equal(result, data) + with ZipStore(file, read_only=load_read_only) as zs: + result = zarr.load(store=zs, path=path) + assert isinstance(result, np.ndarray) + assert np.array_equal(result, data) + + +@pytest.mark.parametrize("path", ["data", None]) +@pytest.mark.parametrize("load_read_only", [True, False]) +def test_load_local(tmp_path: Path, path: str | None, load_read_only: bool) -> None: + file = tmp_path / "test.zip" + data = np.arange(100).reshape(10, 10) + + with LocalStore(file, read_only=False) as zs: + save(zs, data, path=path) + with LocalStore(file, read_only=load_read_only) as zs: + result = zarr.load(store=zs, path=path) + assert isinstance(result, np.ndarray) + assert np.array_equal(result, data) + + +def test_tree() -> None: + g1 = zarr.group() + g1.create_group("foo") + g3 = g1.create_group("bar") + g3.create_group("baz") + g5 = g3.create_group("qux") + g5.create_array("baz", shape=(100,), chunks=(10,), dtype="float64") + with pytest.warns(ZarrDeprecationWarning, match=r"Group\.tree instead\."): # noqa: PT031 + assert repr(zarr.tree(g1)) == repr(g1.tree()) + assert str(zarr.tree(g1)) == str(g1.tree()) + + +# @pytest.mark.parametrize("stores_from_path", [False, True]) +# @pytest.mark.parametrize( +# "with_chunk_store,listable", +# [(False, True), (True, True), (False, False)], +# ids=["default-listable", "with_chunk_store-listable", "default-unlistable"], +# ) +# def test_consolidate_metadata(with_chunk_store, listable, monkeypatch, stores_from_path): +# # setup initial data +# if stores_from_path: +# store = tempfile.mkdtemp() +# atexit.register(atexit_rmtree, store) +# if with_chunk_store: +# chunk_store = tempfile.mkdtemp() +# atexit.register(atexit_rmtree, chunk_store) +# else: +# chunk_store = None +# else: +# store = MemoryStore() +# chunk_store = MemoryStore() if with_chunk_store else None +# path = None +# z = group(store, chunk_store=chunk_store, path=path) + +# # Reload the actual store implementation in case str +# store_to_copy = z.store + +# z.create_group("g1") +# g2 = z.create_group("g2") +# g2.attrs["hello"] = "world" +# arr = g2.create_array("arr", shape=(20, 20), chunks=(5, 5), dtype="f8") +# assert 16 == arr.nchunks +# assert 0 == arr.nchunks_initialized +# arr.attrs["data"] = 1 +# arr[:] = 1.0 +# assert 16 == arr.nchunks_initialized + +# if stores_from_path: +# # get the actual store class for use with consolidate_metadata +# store_class = z._store +# else: +# store_class = store + +# # perform consolidation +# out = consolidate_metadata(store_class, path=path) +# assert isinstance(out, Group) +# assert ["g1", "g2"] == list(out) +# if not stores_from_path: +# assert isinstance(out._store, ConsolidatedMetadataStore) +# assert ".zmetadata" in store +# meta_keys = [ +# ".zgroup", +# "g1/.zgroup", +# "g2/.zgroup", +# "g2/.zattrs", +# "g2/arr/.zarray", +# "g2/arr/.zattrs", +# ] + +# for key in meta_keys: +# del store[key] + +# # https://github.com/zarr-developers/zarr-python/issues/993 +# # Make sure we can still open consolidated on an unlistable store: +# if not listable: +# fs_memory = pytest.importorskip("fsspec.implementations.memory") +# monkeypatch.setattr(fs_memory.MemoryFileSystem, "isdir", lambda x, y: False) +# monkeypatch.delattr(fs_memory.MemoryFileSystem, "ls") +# fs = fs_memory.MemoryFileSystem() +# store_to_open = FSStore("", fs=fs) +# # copy original store to new unlistable store +# store_to_open.update(store_to_copy) + +# else: +# store_to_open = store + +# # open consolidated +# z2 = open_consolidated(store_to_open, chunk_store=chunk_store, path=path) +# assert ["g1", "g2"] == list(z2) +# assert "world" == z2.g2.attrs["hello"] +# assert 1 == z2.g2.arr.attrs["data"] +# assert (z2.g2.arr[:] == 1.0).all() +# assert 16 == z2.g2.arr.nchunks +# if listable: +# assert 16 == z2.g2.arr.nchunks_initialized +# else: +# with pytest.raises(NotImplementedError): +# _ = z2.g2.arr.nchunks_initialized + +# if stores_from_path: +# # path string is note a BaseStore subclass so cannot be used to +# # initialize a ConsolidatedMetadataStore. + +# with pytest.raises(ValueError): +# cmd = ConsolidatedMetadataStore(store) +# else: +# # tests del/write on the store + +# cmd = ConsolidatedMetadataStore(store) +# with pytest.raises(PermissionError): +# del cmd[".zgroup"] +# with pytest.raises(PermissionError): +# cmd[".zgroup"] = None + +# # test getsize on the store +# assert isinstance(getsize(cmd), Integral) + +# # test new metadata are not writeable +# with pytest.raises(PermissionError): +# z2.create_group("g3") +# with pytest.raises(PermissionError): +# z2.create_dataset("spam", shape=42, chunks=7, dtype="i4") +# with pytest.raises(PermissionError): +# del z2["g2"] + +# # test consolidated metadata are not writeable +# with pytest.raises(PermissionError): +# z2.g2.attrs["hello"] = "universe" +# with pytest.raises(PermissionError): +# z2.g2.arr.attrs["foo"] = "bar" + +# # test the data are writeable +# z2.g2.arr[:] = 2 +# assert (z2.g2.arr[:] == 2).all() + +# # test invalid modes +# with pytest.raises(ValueError): +# open_consolidated(store, chunk_store=chunk_store, mode="a", path=path) +# with pytest.raises(ValueError): +# open_consolidated(store, chunk_store=chunk_store, mode="w", path=path) +# with pytest.raises(ValueError): +# open_consolidated(store, chunk_store=chunk_store, mode="w-", path=path) + +# # make sure keyword arguments are passed through without error +# open_consolidated( +# store, +# chunk_store=chunk_store, +# path=path, +# cache_attrs=True, +# synchronizer=None, +# ) + + +# @pytest.mark.parametrize( +# "options", +# ( +# {"dimension_separator": "/"}, +# {"dimension_separator": "."}, +# {"dimension_separator": None}, +# ), +# ) +# def test_save_array_separator(tmpdir, options): +# data = np.arange(6).reshape((3, 2)) +# url = tmpdir.join("test.zarr") +# save_array(url, data, **options) + + +# class TestCopyStore(unittest.TestCase): +# _version = 2 + +# def setUp(self): +# source = dict() +# source["foo"] = b"xxx" +# source["bar/baz"] = b"yyy" +# source["bar/qux"] = b"zzz" +# self.source = source + +# def _get_dest_store(self): +# return dict() + +# def test_no_paths(self): +# source = self.source +# dest = self._get_dest_store() +# copy_store(source, dest) +# assert len(source) == len(dest) +# for key in source: +# assert source[key] == dest[key] + +# def test_source_path(self): +# source = self.source +# # paths should be normalized +# for source_path in "bar", "bar/", "/bar", "/bar/": +# dest = self._get_dest_store() +# copy_store(source, dest, source_path=source_path) +# assert 2 == len(dest) +# for key in source: +# if key.startswith("bar/"): +# dest_key = key.split("bar/")[1] +# assert source[key] == dest[dest_key] +# else: +# assert key not in dest + +# def test_dest_path(self): +# source = self.source +# # paths should be normalized +# for dest_path in "new", "new/", "/new", "/new/": +# dest = self._get_dest_store() +# copy_store(source, dest, dest_path=dest_path) +# assert len(source) == len(dest) +# for key in source: +# if self._version == 3: +# dest_key = f"{key[:10]}new/{key[10:]}" +# else: +# dest_key = f"new/{key}" +# assert source[key] == dest[dest_key] + +# def test_source_dest_path(self): +# source = self.source +# # paths should be normalized +# for source_path in "bar", "bar/", "/bar", "/bar/": +# for dest_path in "new", "new/", "/new", "/new/": +# dest = self._get_dest_store() +# copy_store(source, dest, source_path=source_path, dest_path=dest_path) +# assert 2 == len(dest) +# for key in source: +# if key.startswith("bar/"): +# dest_key = "new/" + key.split("bar/")[1] +# assert source[key] == dest[dest_key] +# else: +# assert key not in dest +# assert (f"new/{key}") not in dest + +# def test_excludes_includes(self): +# source = self.source + +# # single excludes +# dest = self._get_dest_store() +# excludes = "f.*" +# copy_store(source, dest, excludes=excludes) +# assert len(dest) == 2 + +# root = "" +# assert "f{root}foo" not in dest + +# # multiple excludes +# dest = self._get_dest_store() +# excludes = "b.z", ".*x" +# copy_store(source, dest, excludes=excludes) +# assert len(dest) == 1 +# assert f"{root}foo" in dest +# assert f"{root}bar/baz" not in dest +# assert f"{root}bar/qux" not in dest + +# # excludes and includes +# dest = self._get_dest_store() +# excludes = "b.*" +# includes = ".*x" +# copy_store(source, dest, excludes=excludes, includes=includes) +# assert len(dest) == 2 +# assert f"{root}foo" in dest +# assert f"{root}bar/baz" not in dest +# assert f"{root}bar/qux" in dest + +# def test_dry_run(self): +# source = self.source +# dest = self._get_dest_store() +# copy_store(source, dest, dry_run=True) +# assert 0 == len(dest) + +# def test_if_exists(self): +# source = self.source +# dest = self._get_dest_store() +# root = "" +# dest[f"{root}bar/baz"] = b"mmm" + +# # default ('raise') +# with pytest.raises(CopyError): +# copy_store(source, dest) + +# # explicit 'raise' +# with pytest.raises(CopyError): +# copy_store(source, dest, if_exists="raise") + +# # skip +# copy_store(source, dest, if_exists="skip") +# assert 3 == len(dest) +# assert dest[f"{root}foo"] == b"xxx" +# assert dest[f"{root}bar/baz"] == b"mmm" +# assert dest[f"{root}bar/qux"] == b"zzz" + +# # replace +# copy_store(source, dest, if_exists="replace") +# assert 3 == len(dest) +# assert dest[f"{root}foo"] == b"xxx" +# assert dest[f"{root}bar/baz"] == b"yyy" +# assert dest[f"{root}bar/qux"] == b"zzz" + +# # invalid option +# with pytest.raises(ValueError): +# copy_store(source, dest, if_exists="foobar") + + +# def check_copied_array(original, copied, without_attrs=False, expect_props=None): +# # setup +# source_h5py = original.__module__.startswith("h5py.") +# dest_h5py = copied.__module__.startswith("h5py.") +# zarr_to_zarr = not (source_h5py or dest_h5py) +# h5py_to_h5py = source_h5py and dest_h5py +# zarr_to_h5py = not source_h5py and dest_h5py +# h5py_to_zarr = source_h5py and not dest_h5py +# if expect_props is None: +# expect_props = dict() +# else: +# expect_props = expect_props.copy() + +# # common properties in zarr and h5py +# for p in "dtype", "shape", "chunks": +# expect_props.setdefault(p, getattr(original, p)) + +# # zarr-specific properties +# if zarr_to_zarr: +# for p in "compressor", "filters", "order", "fill_value": +# expect_props.setdefault(p, getattr(original, p)) + +# # h5py-specific properties +# if h5py_to_h5py: +# for p in ( +# "maxshape", +# "compression", +# "compression_opts", +# "shuffle", +# "scaleoffset", +# "fletcher32", +# "fillvalue", +# ): +# expect_props.setdefault(p, getattr(original, p)) + +# # common properties with some name differences +# if h5py_to_zarr: +# expect_props.setdefault("fill_value", original.fillvalue) +# if zarr_to_h5py: +# expect_props.setdefault("fillvalue", original.fill_value) + +# # compare properties +# for k, v in expect_props.items(): +# assert v == getattr(copied, k) + +# # compare data +# assert_array_equal(original[:], copied[:]) + +# # compare attrs +# if without_attrs: +# for k in original.attrs.keys(): +# assert k not in copied.attrs +# else: +# if dest_h5py and "filters" in original.attrs: +# # special case in v3 (storing filters metadata under attributes) +# # we explicitly do not copy this info over to HDF5 +# original_attrs = original.attrs.asdict().copy() +# original_attrs.pop("filters") +# else: +# original_attrs = original.attrs +# assert sorted(original_attrs.items()) == sorted(copied.attrs.items()) + + +# def check_copied_group(original, copied, without_attrs=False, expect_props=None, shallow=False): +# # setup +# if expect_props is None: +# expect_props = dict() +# else: +# expect_props = expect_props.copy() + +# # compare children +# for k, v in original.items(): +# if hasattr(v, "shape"): +# assert k in copied +# check_copied_array(v, copied[k], without_attrs=without_attrs, expect_props=expect_props) +# elif shallow: +# assert k not in copied +# else: +# assert k in copied +# check_copied_group( +# v, +# copied[k], +# without_attrs=without_attrs, +# shallow=shallow, +# expect_props=expect_props, +# ) + +# # compare attrs +# if without_attrs: +# for k in original.attrs.keys(): +# assert k not in copied.attrs +# else: +# assert sorted(original.attrs.items()) == sorted(copied.attrs.items()) + + +# def test_copy_all(): +# """ +# https://github.com/zarr-developers/zarr-python/issues/269 + +# copy_all used to not copy attributes as `.keys()` does not return hidden `.zattrs`. + +# """ +# original_group = zarr.group(store=MemoryStore(), overwrite=True) +# original_group.attrs["info"] = "group attrs" +# original_subgroup = original_group.create_group("subgroup") +# original_subgroup.attrs["info"] = "sub attrs" + +# destination_group = zarr.group(store=MemoryStore(), overwrite=True) + +# # copy from memory to directory store +# copy_all( +# original_group, +# destination_group, +# dry_run=False, +# ) + +# assert "subgroup" in destination_group +# assert destination_group.attrs["info"] == "group attrs" +# assert destination_group.subgroup.attrs["info"] == "sub attrs" + + +# class TestCopy: +# @pytest.fixture(params=[False, True], ids=["zarr", "hdf5"]) +# def source(self, request, tmpdir): +# def prep_source(source): +# foo = source.create_group("foo") +# foo.attrs["experiment"] = "weird science" +# baz = foo.create_dataset("bar/baz", data=np.arange(100), chunks=(50,)) +# baz.attrs["units"] = "metres" +# if request.param: +# extra_kws = dict( +# compression="gzip", +# compression_opts=3, +# fillvalue=84, +# shuffle=True, +# fletcher32=True, +# ) +# else: +# extra_kws = dict(compressor=Zlib(3), order="F", fill_value=42, filters=[Adler32()]) +# source.create_dataset( +# "spam", +# data=np.arange(100, 200).reshape(20, 5), +# chunks=(10, 2), +# dtype="i2", +# **extra_kws, +# ) +# return source + +# if request.param: +# h5py = pytest.importorskip("h5py") +# fn = tmpdir.join("source.h5") +# with h5py.File(str(fn), mode="w") as h5f: +# yield prep_source(h5f) +# else: +# yield prep_source(group()) + +# @pytest.fixture(params=[False, True], ids=["zarr", "hdf5"]) +# def dest(self, request, tmpdir): +# if request.param: +# h5py = pytest.importorskip("h5py") +# fn = tmpdir.join("dest.h5") +# with h5py.File(str(fn), mode="w") as h5f: +# yield h5f +# else: +# yield group() + +# def test_copy_array(self, source, dest): +# # copy array with default options +# copy(source["foo/bar/baz"], dest) +# check_copied_array(source["foo/bar/baz"], dest["baz"]) +# copy(source["spam"], dest) +# check_copied_array(source["spam"], dest["spam"]) + +# def test_copy_bad_dest(self, source, dest): +# # try to copy to an array, dest must be a group +# dest = dest.create_dataset("eggs", shape=(100,)) +# with pytest.raises(ValueError): +# copy(source["foo/bar/baz"], dest) + +# def test_copy_array_name(self, source, dest): +# # copy array with name +# copy(source["foo/bar/baz"], dest, name="qux") +# assert "baz" not in dest +# check_copied_array(source["foo/bar/baz"], dest["qux"]) + +# def test_copy_array_create_options(self, source, dest): +# dest_h5py = dest.__module__.startswith("h5py.") + +# # copy array, provide creation options +# compressor = Zlib(9) +# create_kws = dict(chunks=(10,)) +# if dest_h5py: +# create_kws.update( +# compression="gzip", compression_opts=9, shuffle=True, fletcher32=True, fillvalue=42 +# ) +# else: +# create_kws.update(compressor=compressor, fill_value=42, order="F", filters=[Adler32()]) +# copy(source["foo/bar/baz"], dest, without_attrs=True, **create_kws) +# check_copied_array( +# source["foo/bar/baz"], dest["baz"], without_attrs=True, expect_props=create_kws +# ) + +# def test_copy_array_exists_array(self, source, dest): +# # copy array, dest array in the way +# dest.create_dataset("baz", shape=(10,)) + +# # raise +# with pytest.raises(CopyError): +# # should raise by default +# copy(source["foo/bar/baz"], dest) +# assert (10,) == dest["baz"].shape +# with pytest.raises(CopyError): +# copy(source["foo/bar/baz"], dest, if_exists="raise") +# assert (10,) == dest["baz"].shape + +# # skip +# copy(source["foo/bar/baz"], dest, if_exists="skip") +# assert (10,) == dest["baz"].shape + +# # replace +# copy(source["foo/bar/baz"], dest, if_exists="replace") +# check_copied_array(source["foo/bar/baz"], dest["baz"]) + +# # invalid option +# with pytest.raises(ValueError): +# copy(source["foo/bar/baz"], dest, if_exists="foobar") + +# def test_copy_array_exists_group(self, source, dest): +# # copy array, dest group in the way +# dest.create_group("baz") + +# # raise +# with pytest.raises(CopyError): +# copy(source["foo/bar/baz"], dest) +# assert not hasattr(dest["baz"], "shape") +# with pytest.raises(CopyError): +# copy(source["foo/bar/baz"], dest, if_exists="raise") +# assert not hasattr(dest["baz"], "shape") + +# # skip +# copy(source["foo/bar/baz"], dest, if_exists="skip") +# assert not hasattr(dest["baz"], "shape") + +# # replace +# copy(source["foo/bar/baz"], dest, if_exists="replace") +# check_copied_array(source["foo/bar/baz"], dest["baz"]) + +# def test_copy_array_skip_initialized(self, source, dest): +# dest_h5py = dest.__module__.startswith("h5py.") + +# dest.create_dataset("baz", shape=(100,), chunks=(10,), dtype="i8") +# assert not np.all(source["foo/bar/baz"][:] == dest["baz"][:]) + +# if dest_h5py: +# with pytest.raises(ValueError): +# # not available with copy to h5py +# copy(source["foo/bar/baz"], dest, if_exists="skip_initialized") + +# else: +# # copy array, dest array exists but not yet initialized +# copy(source["foo/bar/baz"], dest, if_exists="skip_initialized") +# check_copied_array(source["foo/bar/baz"], dest["baz"]) + +# # copy array, dest array exists and initialized, will be skipped +# dest["baz"][:] = np.arange(100, 200) +# copy(source["foo/bar/baz"], dest, if_exists="skip_initialized") +# assert_array_equal(np.arange(100, 200), dest["baz"][:]) +# assert not np.all(source["foo/bar/baz"][:] == dest["baz"][:]) + +# def test_copy_group(self, source, dest): +# # copy group, default options +# copy(source["foo"], dest) +# check_copied_group(source["foo"], dest["foo"]) + +# def test_copy_group_no_name(self, source, dest): +# with pytest.raises(TypeError): +# # need a name if copy root +# copy(source, dest) + +# copy(source, dest, name="root") +# check_copied_group(source, dest["root"]) + +# def test_copy_group_options(self, source, dest): +# # copy group, non-default options +# copy(source["foo"], dest, name="qux", without_attrs=True) +# assert "foo" not in dest +# check_copied_group(source["foo"], dest["qux"], without_attrs=True) + +# def test_copy_group_shallow(self, source, dest): +# # copy group, shallow +# copy(source, dest, name="eggs", shallow=True) +# check_copied_group(source, dest["eggs"], shallow=True) + +# def test_copy_group_exists_group(self, source, dest): +# # copy group, dest groups exist +# dest.create_group("foo/bar") +# copy(source["foo"], dest) +# check_copied_group(source["foo"], dest["foo"]) + +# def test_copy_group_exists_array(self, source, dest): +# # copy group, dest array in the way +# dest.create_dataset("foo/bar", shape=(10,)) + +# # raise +# with pytest.raises(CopyError): +# copy(source["foo"], dest) +# assert dest["foo/bar"].shape == (10,) +# with pytest.raises(CopyError): +# copy(source["foo"], dest, if_exists="raise") +# assert dest["foo/bar"].shape == (10,) + +# # skip +# copy(source["foo"], dest, if_exists="skip") +# assert dest["foo/bar"].shape == (10,) + +# # replace +# copy(source["foo"], dest, if_exists="replace") +# check_copied_group(source["foo"], dest["foo"]) + +# def test_copy_group_dry_run(self, source, dest): +# # dry run, empty destination +# n_copied, n_skipped, n_bytes_copied = copy( +# source["foo"], dest, dry_run=True, return_stats=True +# ) +# assert 0 == len(dest) +# assert 3 == n_copied +# assert 0 == n_skipped +# assert 0 == n_bytes_copied + +# # dry run, array exists in destination +# baz = np.arange(100, 200) +# dest.create_dataset("foo/bar/baz", data=baz) +# assert not np.all(source["foo/bar/baz"][:] == dest["foo/bar/baz"][:]) +# assert 1 == len(dest) + +# # raise +# with pytest.raises(CopyError): +# copy(source["foo"], dest, dry_run=True) +# assert 1 == len(dest) + +# # skip +# n_copied, n_skipped, n_bytes_copied = copy( +# source["foo"], dest, dry_run=True, if_exists="skip", return_stats=True +# ) +# assert 1 == len(dest) +# assert 2 == n_copied +# assert 1 == n_skipped +# assert 0 == n_bytes_copied +# assert_array_equal(baz, dest["foo/bar/baz"]) + +# # replace +# n_copied, n_skipped, n_bytes_copied = copy( +# source["foo"], dest, dry_run=True, if_exists="replace", return_stats=True +# ) +# assert 1 == len(dest) +# assert 3 == n_copied +# assert 0 == n_skipped +# assert 0 == n_bytes_copied +# assert_array_equal(baz, dest["foo/bar/baz"]) + +# def test_logging(self, source, dest, tmpdir): +# # callable log +# copy(source["foo"], dest, dry_run=True, log=print) + +# # file name +# fn = str(tmpdir.join("log_name")) +# copy(source["foo"], dest, dry_run=True, log=fn) + +# # file +# with tmpdir.join("log_file").open(mode="w") as f: +# copy(source["foo"], dest, dry_run=True, log=f) + +# # bad option +# with pytest.raises(TypeError): +# copy(source["foo"], dest, dry_run=True, log=True) + + +def test_open_falls_back_to_open_group() -> None: + # https://github.com/zarr-developers/zarr-python/issues/2309 + store = MemoryStore() + zarr.open_group(store, attributes={"key": "value"}) + + group = zarr.open(store) + assert isinstance(group, Group) + assert group.attrs == {"key": "value"} + + +async def test_open_falls_back_to_open_group_async(zarr_format: ZarrFormat) -> None: + # https://github.com/zarr-developers/zarr-python/issues/2309 + store = MemoryStore() + await zarr.api.asynchronous.open_group( + store, attributes={"key": "value"}, zarr_format=zarr_format + ) + + group = await zarr.api.asynchronous.open(store=store) + assert isinstance(group, zarr.core.group.AsyncGroup) + assert group.metadata.zarr_format == zarr_format + assert group.attrs == {"key": "value"} + + +@pytest.mark.parametrize("mode", ["r", "r+", "w", "a"]) +def test_open_modes_creates_group(tmp_path: Path, mode: str) -> None: + # https://github.com/zarr-developers/zarr-python/issues/2490 + zarr_dir = tmp_path / f"mode-{mode}-test.zarr" + if mode in ["r", "r+"]: + # Expect FileNotFoundError to be raised if 'r' or 'r+' mode + with pytest.raises(FileNotFoundError): + zarr.open(store=zarr_dir, mode=mode) # type: ignore[arg-type] + else: + group = zarr.open(store=zarr_dir, mode=mode) # type: ignore[arg-type] + assert isinstance(group, Group) + + +async def test_metadata_validation_error() -> None: + with pytest.raises( + MetadataValidationError, + match="Invalid value for 'zarr_format'. Expected 2, 3, or None. Got '3.0'.", + ): + await zarr.api.asynchronous.open_group(zarr_format="3.0") # type: ignore[arg-type] + + with pytest.raises( + MetadataValidationError, + match="Invalid value for 'zarr_format'. Expected 2, 3, or None. Got '3.0'.", + ): + await zarr.api.asynchronous.open_array(shape=(1,), zarr_format="3.0") # type: ignore[arg-type] + + +@pytest.mark.parametrize( + "store", + ["local", "memory", "zip"], + indirect=True, +) +def test_open_array_with_mode_r_plus(store: Store, zarr_format: ZarrFormat) -> None: + # 'r+' means read/write (must exist) + with pytest.raises(ArrayNotFoundError): + zarr.open_array(store=store, mode="r+", zarr_format=zarr_format) + zarr.ones(store=store, shape=(3, 3), zarr_format=zarr_format) + z2 = zarr.open_array(store=store, mode="r+") + assert isinstance(z2, Array) + assert z2.metadata.zarr_format == zarr_format + result = z2[:] + assert isinstance(result, NDArrayLike) + assert (result == 1).all() + z2[:] = 3 + + +@pytest.mark.parametrize( + ("a_func", "b_func"), + [ + (zarr.api.asynchronous.create_array, zarr.api.synchronous.create_array), + (zarr.api.asynchronous.save, zarr.api.synchronous.save), + (zarr.api.asynchronous.save_array, zarr.api.synchronous.save_array), + (zarr.api.asynchronous.save_group, zarr.api.synchronous.save_group), + (zarr.api.asynchronous.open_group, zarr.api.synchronous.open_group), + (zarr.api.asynchronous.create, zarr.api.synchronous.create), + ], +) +def test_consistent_signatures( + a_func: Callable[[object], object], b_func: Callable[[object], object] +) -> None: + """ + Ensure that pairs of functions have the same signature + """ + base_sig = inspect.signature(a_func) + test_sig = inspect.signature(b_func) + wrong: dict[str, list[object]] = { + "missing_from_test": [], + "missing_from_base": [], + "wrong_type": [], + } + for key, value in base_sig.parameters.items(): + if key not in test_sig.parameters: + wrong["missing_from_test"].append((key, value)) + for key, value in test_sig.parameters.items(): + if key not in base_sig.parameters: + wrong["missing_from_base"].append((key, value)) + if base_sig.parameters[key] != value: + wrong["wrong_type"].append({key: {"test": value, "base": base_sig.parameters[key]}}) + assert wrong["missing_from_base"] == [] + assert wrong["missing_from_test"] == [] + assert wrong["wrong_type"] == [] + + +def test_api_exports() -> None: + """ + Test that the sync API and the async API export the same objects + """ + assert zarr.api.asynchronous.__all__ == zarr.api.synchronous.__all__ + + +@gpu_test +@pytest.mark.parametrize( + "store", + ["local", "memory", "zip"], + indirect=True, +) +@pytest.mark.parametrize("zarr_format", [None, 2, 3]) +def test_gpu_basic(store: Store, zarr_format: ZarrFormat | None) -> None: + import cupy as cp + + if zarr_format == 2: + # Without this, the zstd codec attempts to convert the cupy + # array to bytes. + compressors = None + else: + compressors = "auto" + + with zarr.config.enable_gpu(): + src = cp.random.uniform(size=(100, 100)) # allocate on the device + z = zarr.create_array( + store, + name="a", + shape=src.shape, + chunks=(10, 10), + dtype=src.dtype, + overwrite=True, + zarr_format=zarr_format, + compressors=compressors, # type: ignore[arg-type] + ) + z[:10, :10] = src[:10, :10] + + result = z[:10, :10] + # assert_array_equal doesn't check the type + assert isinstance(result, type(src)) + cp.testing.assert_array_equal(result, src[:10, :10]) + + +def test_v2_without_compressor() -> None: + # Make sure it's possible to set no compressor for v2 arrays + arr = zarr.create(store={}, shape=(1), dtype="uint8", zarr_format=2, compressor=None) + assert arr.compressors == () + + +def test_v2_with_v3_compressor() -> None: + # Check trying to create a v2 array with a v3 compressor fails + with pytest.raises( + ValueError, + match="Cannot use a BytesBytesCodec as a compressor for zarr v2 arrays. Use a numcodecs codec directly instead.", + ): + zarr.create( + store={}, shape=(1), dtype="uint8", zarr_format=2, compressor=zarr.codecs.BloscCodec() + ) + + +def add_empty_file(path: Path) -> Path: + fpath = path / "a.txt" + fpath.touch() + return fpath + + +@pytest.mark.parametrize("create_function", [create_array, from_array]) +@pytest.mark.parametrize("overwrite", [True, False]) +def test_no_overwrite_array(tmp_path: Path, create_function: Callable, overwrite: bool) -> None: # type:ignore[type-arg] + store = zarr.storage.LocalStore(tmp_path) + existing_fpath = add_empty_file(tmp_path) + + assert existing_fpath.exists() + create_function(store=store, data=np.ones(shape=(1,)), overwrite=overwrite) + if overwrite: + assert not existing_fpath.exists() + else: + assert existing_fpath.exists() + + +@pytest.mark.parametrize("create_function", [create_group, group]) +@pytest.mark.parametrize("overwrite", [True, False]) +def test_no_overwrite_group(tmp_path: Path, create_function: Callable, overwrite: bool) -> None: # type:ignore[type-arg] + store = zarr.storage.LocalStore(tmp_path) + existing_fpath = add_empty_file(tmp_path) + + assert existing_fpath.exists() + create_function(store=store, overwrite=overwrite) + if overwrite: + assert not existing_fpath.exists() + else: + assert existing_fpath.exists() + + +@pytest.mark.parametrize("open_func", [zarr.open, open_group]) +@pytest.mark.parametrize("mode", ["r", "r+", "a", "w", "w-"]) +def test_no_overwrite_open(tmp_path: Path, open_func: Callable, mode: str) -> None: # type:ignore[type-arg] + store = zarr.storage.LocalStore(tmp_path) + existing_fpath = add_empty_file(tmp_path) + + assert existing_fpath.exists() + with contextlib.suppress(FileExistsError, FileNotFoundError, ZarrUserWarning): + open_func(store=store, mode=mode) + if mode == "w": + assert not existing_fpath.exists() + else: + assert existing_fpath.exists() + + +def test_no_overwrite_load(tmp_path: Path) -> None: + store = zarr.storage.LocalStore(tmp_path) + existing_fpath = add_empty_file(tmp_path) + + assert existing_fpath.exists() + with contextlib.suppress(NotImplementedError): + zarr.load(store) + assert existing_fpath.exists() + + +@pytest.mark.parametrize( + "f", + [ + zarr.array, + zarr.create, + zarr.create_array, + zarr.ones, + zarr.ones_like, + zarr.empty, + zarr.empty_like, + zarr.full, + zarr.full_like, + zarr.zeros, + zarr.zeros_like, + ], +) +def test_auto_chunks(f: Callable[..., AnyArray]) -> None: + # Make sure chunks are set automatically across the public API + # TODO: test shards with this test too + shape = (1000, 1000) + dtype = np.uint8 + kwargs = {"shape": shape, "dtype": dtype} + array = np.zeros(shape, dtype=dtype) + store = zarr.storage.MemoryStore() + + # ruff: disable[FURB171] + if f in [zarr.full, zarr.full_like]: + kwargs["fill_value"] = 0 + if f in [zarr.array]: + kwargs["data"] = array + if f in [zarr.empty_like, zarr.full_like, zarr.empty_like, zarr.ones_like, zarr.zeros_like]: + kwargs["a"] = array + if f in [zarr.create_array]: + kwargs["store"] = store + # ruff: enable[FURB171] + + a = f(**kwargs) + assert a.chunks == (500, 500) + + +@pytest.mark.parametrize("kwarg_name", ["synchronizer", "chunk_store", "cache_attrs", "meta_array"]) +def test_unimplemented_kwarg_warnings(kwarg_name: str) -> None: + kwargs = {kwarg_name: 1} + with pytest.warns(RuntimeWarning, match=".* is not yet implemented"): + zarr.create(shape=(1,), **kwargs) # type: ignore[arg-type] diff --git a/tests/test_api/test_asynchronous.py b/tests/test_api/test_asynchronous.py new file mode 100644 index 0000000000..6ebec36bbd --- /dev/null +++ b/tests/test_api/test_asynchronous.py @@ -0,0 +1,127 @@ +from __future__ import annotations + +import json +from dataclasses import dataclass +from typing import TYPE_CHECKING + +import numpy as np +import pytest + +from zarr import create_array +from zarr.api.asynchronous import _get_shape_chunks, _like_args, group, open +from zarr.core.buffer.core import default_buffer_prototype +from zarr.core.group import AsyncGroup + +if TYPE_CHECKING: + from pathlib import Path + from typing import Any + + import numpy.typing as npt + + from zarr.core.array import AsyncArray + from zarr.core.metadata import ArrayV2Metadata, ArrayV3Metadata + from zarr.types import AnyArray + + +@dataclass +class WithShape: + shape: tuple[int, ...] + + +@dataclass +class WithChunks(WithShape): + chunks: tuple[int, ...] + + +@dataclass +class WithChunkLen(WithShape): + chunklen: int + + +@pytest.mark.parametrize( + ("observed", "expected"), + [ + ({}, (None, None)), + (WithShape(shape=(1, 2)), ((1, 2), None)), + (WithChunks(shape=(1, 2), chunks=(1, 2)), ((1, 2), (1, 2))), + (WithChunkLen(shape=(10, 10), chunklen=1), ((10, 10), (1, 10))), + ], +) +def test_get_shape_chunks( + observed: object, expected: tuple[tuple[int, ...] | None, tuple[int, ...] | None] +) -> None: + """ + Test the _get_shape_chunks function + """ + assert _get_shape_chunks(observed) == expected + + +@pytest.mark.parametrize( + ("observed", "expected"), + [ + (np.arange(10, dtype=np.dtype("int64")), {"shape": (10,), "dtype": np.dtype("int64")}), + (WithChunks(shape=(1, 2), chunks=(1, 2)), {"chunks": (1, 2), "shape": (1, 2)}), + ( + create_array( + {}, + chunks=(10,), + shape=(100,), + dtype="f8", + compressors=None, + filters=None, + zarr_format=2, + )._async_array, + { + "chunks": (10,), + "shape": (100,), + "dtype": np.dtype("f8"), + "fill_value": np.float64(0.0), + "compressor": None, + "filters": None, + "order": "C", + }, + ), + ], +) +def test_like_args( + observed: AsyncArray[ArrayV2Metadata] + | AsyncArray[ArrayV3Metadata] + | AnyArray + | npt.NDArray[Any], + expected: object, +) -> None: + """ + Test the like_args function + """ + assert _like_args(observed) == expected + + +async def test_open_no_array() -> None: + """ + Test that zarr.api.asynchronous.open attempts to open a group when no array is found, but shape was specified in kwargs. + This behavior makes no sense but we should still test it. + """ + store = { + "zarr.json": default_buffer_prototype().buffer.from_bytes( + json.dumps({"zarr_format": 3, "node_type": "group"}).encode("utf-8") + ) + } + with pytest.raises( + TypeError, match=r"open_group\(\) got an unexpected keyword argument 'shape'" + ): + await open(store=store, shape=(1,)) + + +async def test_open_group_new_path(tmp_path: Path) -> None: + """ + Test that zarr.api.asynchronous.group properly handles a string representation of a local file + path that does not yet exist. + See https://github.com/zarr-developers/zarr-python/issues/3406 + """ + # tmp_path exists, but tmp_path / "test.zarr" will not, which is important for this test + path = tmp_path / "test.zarr" + grp = await group(store=path, attributes={"a": 1}) + assert isinstance(grp, AsyncGroup) + # Calling group on an existing store should just open that store + grp = await group(store=path) + assert grp.attrs == {"a": 1} diff --git a/tests/test_api/test_synchronous.py b/tests/test_api/test_synchronous.py new file mode 100644 index 0000000000..9b15ec32f6 --- /dev/null +++ b/tests/test_api/test_synchronous.py @@ -0,0 +1,128 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Final + +import pytest +from numpydoc.docscrape import NumpyDocString + +import zarr +from zarr.api import asynchronous, synchronous + +if TYPE_CHECKING: + from collections.abc import Callable + +MATCHED_EXPORT_NAMES: Final[tuple[str, ...]] = tuple( + sorted(set(synchronous.__all__) | set(asynchronous.__all__)) +) +"""A sorted tuple of names that are exported by both the sync and async APIs.""" + +MATCHED_CALLABLE_NAMES: Final[tuple[str, ...]] = tuple( + x for x in MATCHED_EXPORT_NAMES if callable(getattr(synchronous, x)) +) +"""A sorted tuple of callable names that are exported by both the sync and async APIs.""" + + +@pytest.mark.parametrize("callable_name", MATCHED_CALLABLE_NAMES) +def test_docstrings_match(callable_name: str) -> None: + """ + Tests that the docstrings for the sync and async define identical parameters. + """ + callable_a = getattr(synchronous, callable_name) + callable_b = getattr(asynchronous, callable_name) + if callable_a.__doc__ is None: + assert callable_b.__doc__ is None + else: + params_a = NumpyDocString(callable_a.__doc__)["Parameters"] + params_b = NumpyDocString(callable_b.__doc__)["Parameters"] + mismatch = [] + for idx, (a, b) in enumerate(zip(params_a, params_b, strict=False)): + if a != b: + mismatch.append((idx, (a, b))) + assert mismatch == [] + + +@pytest.mark.parametrize( + ("parameter_name", "array_creation_routines"), + [ + pytest.param( + ("store", "path"), + ( + asynchronous.create_array, + synchronous.create_array, + asynchronous.create_group, + synchronous.create_group, + zarr.AsyncGroup.create_array, + zarr.Group.create_array, + ), + id="store-path-create_array_group", + ), + pytest.param( + ( + "store", + "path", + ), + ( + asynchronous.create, + synchronous.create, + zarr.Group.create, + ), + id="store-path-create", + ), + pytest.param( + ( + ( + "filters", + "codecs", + "compressors", + "compressor", + "chunks", + "shape", + "dtype", + "shardsfill_value", + ) + ), + ( + asynchronous.create, + synchronous.create, + asynchronous.create_array, + synchronous.create_array, + zarr.AsyncGroup.create_array, + zarr.Group.create_array, + ), + id="encoding-params-create_and_array", + ), + ], +) +def test_docstring_consistent_parameters( + parameter_name: str, array_creation_routines: tuple[Callable[[Any], Any], ...] +) -> None: + """ + Tests that array and group creation routines document the same parameters consistently. + This test inspects the docstrings of sets of callables and generates two dicts: + + - a dict where the keys are parameter descriptions and the values are the names of the routines with those + descriptions + - a dict where the keys are parameter types and the values are the names of the routines with those types + + If each dict has just 1 value, then the parameter description and type in the docstring must be + identical across different routines. But if these dicts have multiple values, then there must be + routines that use the same parameter but document it differently, which will trigger a test failure. + """ + descs: dict[tuple[str, ...], tuple[str, ...]] = {} + types: dict[str, tuple[str, ...]] = {} + for routine in array_creation_routines: + key = f"{routine.__module__}.{routine.__qualname__}" + docstring = NumpyDocString(routine.__doc__) + param_dict = {d.name: d for d in docstring["Parameters"]} + if parameter_name in param_dict: + val = param_dict[parameter_name] + if tuple(val.desc) in descs: + descs[tuple(val.desc)] = descs[tuple(val.desc)] + (key,) + else: + descs[tuple(val.desc)] = (key,) + if val.type in types: + types[val.type] = types[val.type] + (key,) + else: + types[val.type] = (key,) + assert len(descs) <= 1 + assert len(types) <= 1 diff --git a/tests/test_array.py b/tests/test_array.py new file mode 100644 index 0000000000..b1a7a3c0f2 --- /dev/null +++ b/tests/test_array.py @@ -0,0 +1,2388 @@ +import dataclasses +import inspect +import json +import math +import multiprocessing as mp +import pickle +import re +import sys +from itertools import accumulate, starmap +from typing import TYPE_CHECKING, Any, Literal +from unittest import mock + +import numcodecs +import numpy as np +import numpy.typing as npt +import pytest +from packaging.version import Version + +import zarr.api.asynchronous +import zarr.api.synchronous as sync_api +from tests.conftest import skip_object_dtype +from zarr import Array, Group +from zarr.abc.store import Store +from zarr.codecs import ( + BytesCodec, + GzipCodec, + TransposeCodec, + ZstdCodec, +) +from zarr.core._info import ArrayInfo +from zarr.core.array import ( + AsyncArray, + CompressorsLike, + FiltersLike, + _iter_chunk_coords, + _iter_chunk_regions, + _iter_shard_coords, + _iter_shard_keys, + _iter_shard_regions, + _parse_chunk_encoding_v2, + _parse_chunk_encoding_v3, + _shards_initialized, + create_array, + default_filters_v2, + default_serializer_v3, +) +from zarr.core.array_spec import ArrayConfig, ArrayConfigParams +from zarr.core.buffer import NDArrayLike, NDArrayLikeOrScalar, cpu, default_buffer_prototype +from zarr.core.chunk_grids import ( + SHARDED_INNER_CHUNK_MAX_BYTES, + guess_chunks, + normalize_chunks_nd, + resolve_outer_and_inner_chunks, +) +from zarr.core.chunk_key_encodings import ChunkKeyEncodingParams +from zarr.core.common import JSON, ZarrFormat, ceildiv +from zarr.core.dtype import ( + DateTime64, + Float32, + Float64, + Int16, + Structured, + TimeDelta64, + UInt8, + VariableLengthBytes, + VariableLengthUTF8, + ZDType, + parse_dtype, +) +from zarr.core.dtype.common import ENDIANNESS_STR, EndiannessStr +from zarr.core.dtype.npy.common import NUMPY_ENDIANNESS_STR, endianness_from_numpy_str +from zarr.core.group import AsyncGroup +from zarr.core.indexing import BasicIndexer, _iter_grid, _iter_regions +from zarr.core.metadata.v2 import ArrayV2Metadata +from zarr.core.sync import sync +from zarr.errors import ( + ContainsArrayError, + ContainsGroupError, + ZarrUserWarning, +) +from zarr.storage import LocalStore, MemoryStore, StorePath +from zarr.storage._logging import LoggingStore +from zarr.types import AnyArray, AnyAsyncArray + +from .test_dtype.conftest import zdtype_examples + +if TYPE_CHECKING: + from zarr.abc.codec import CodecJSON_V3 + + +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +@pytest.mark.parametrize("zarr_format", [2, 3]) +@pytest.mark.parametrize("overwrite", [True, False]) +@pytest.mark.parametrize("extant_node", ["array", "group"]) +def test_array_creation_existing_node( + store: LocalStore | MemoryStore, + zarr_format: ZarrFormat, + overwrite: bool, + extant_node: Literal["array", "group"], +) -> None: + """ + Check that an existing array or group is handled as expected during array creation. + """ + spath = StorePath(store) + group = Group.from_store(spath, zarr_format=zarr_format) + expected_exception: type[ContainsArrayError | ContainsGroupError] + if extant_node == "array": + expected_exception = ContainsArrayError + _ = group.create_array("extant", shape=(10,), dtype="uint8") + elif extant_node == "group": + expected_exception = ContainsGroupError + _ = group.create_group("extant") + else: + raise AssertionError + + new_shape = (2, 2) + new_dtype = "float32" + + if overwrite: + if not store.supports_deletes: + pytest.skip("store does not support deletes") + arr_new = zarr.create_array( + spath / "extant", + shape=new_shape, + dtype=new_dtype, + overwrite=overwrite, + zarr_format=zarr_format, + ) + assert arr_new.shape == new_shape + assert arr_new.dtype == new_dtype + else: + with pytest.raises(expected_exception): + arr_new = zarr.create_array( + spath / "extant", + shape=new_shape, + dtype=new_dtype, + overwrite=overwrite, + zarr_format=zarr_format, + ) + + +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +@pytest.mark.parametrize("zarr_format", [2, 3]) +async def test_create_creates_parents( + store: LocalStore | MemoryStore, zarr_format: ZarrFormat +) -> None: + # prepare a root node, with some data set + await zarr.api.asynchronous.open_group( + store=store, path="a", zarr_format=zarr_format, attributes={"key": "value"} + ) + + # create a child node with a couple intermediates + await zarr.api.asynchronous.create( + shape=(2, 2), store=store, path="a/b/c/d", zarr_format=zarr_format + ) + parts = ["a", "a/b", "a/b/c"] + + if zarr_format == 2: + files = [".zattrs", ".zgroup"] + else: + files = ["zarr.json"] + + expected = [f"{part}/{file}" for file in files for part in parts] + + if zarr_format == 2: + expected.extend([".zattrs", ".zgroup", "a/b/c/d/.zarray", "a/b/c/d/.zattrs"]) + else: + expected.extend(["zarr.json", "a/b/c/d/zarr.json"]) + + expected = sorted(expected) + + result = sorted([x async for x in store.list_prefix("")]) + + assert result == expected + + paths = ["a", "a/b", "a/b/c"] + for path in paths: + g = await zarr.api.asynchronous.open_group(store=store, path=path) + assert isinstance(g, AsyncGroup) + + +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_array_name_properties_no_group( + store: LocalStore | MemoryStore, zarr_format: ZarrFormat +) -> None: + arr = zarr.create_array( + store=store, shape=(100,), chunks=(10,), zarr_format=zarr_format, dtype=">i4" + ) + assert arr.path == "" + assert arr.name == "/" + assert arr.basename == "" + + +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_array_name_properties_with_group( + store: LocalStore | MemoryStore, zarr_format: ZarrFormat +) -> None: + root = Group.from_store(store=store, zarr_format=zarr_format) + foo = root.create_array("foo", shape=(100,), chunks=(10,), dtype="i4") + assert foo.path == "foo" + assert foo.name == "/foo" + assert foo.basename == "foo" + + bar = root.create_group("bar") + spam = bar.create_array("spam", shape=(100,), chunks=(10,), dtype="i4") + + assert spam.path == "bar/spam" + assert spam.name == "/bar/spam" + assert spam.basename == "spam" + + +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@pytest.mark.parametrize("store", ["memory"], indirect=True) +@pytest.mark.parametrize("specify_fill_value", [True, False]) +@pytest.mark.parametrize( + "zdtype", zdtype_examples, ids=tuple(str(type(v)) for v in zdtype_examples) +) +def test_array_fill_value_default( + store: MemoryStore, specify_fill_value: bool, zdtype: ZDType[Any, Any] +) -> None: + """ + Test that creating an array with the fill_value parameter set to None, or unspecified, + results in the expected fill_value attribute of the array, i.e. the default value of the dtype + """ + shape = (10,) + if specify_fill_value: + arr = zarr.create_array( + store=store, + shape=shape, + dtype=zdtype, + zarr_format=3, + chunks=shape, + fill_value=None, + ) + else: + arr = zarr.create_array(store=store, shape=shape, dtype=zdtype, zarr_format=3, chunks=shape) + expected_fill_value = zdtype.default_scalar() + if isinstance(expected_fill_value, np.datetime64 | np.timedelta64): + if np.isnat(expected_fill_value): + assert np.isnat(arr.fill_value) + elif isinstance(expected_fill_value, np.floating | np.complexfloating): + if np.isnan(expected_fill_value): + assert np.isnan(arr.fill_value) + else: + assert arr.fill_value == expected_fill_value + # A simpler check would be to ensure that arr.fill_value.dtype == arr.dtype + # But for some numpy data types (namely, U), scalars might not have length. An empty string + # scalar from a `>U4` array would have dtype `>U`, and arr.fill_value.dtype == arr.dtype will fail. + + assert type(arr.fill_value) is type(np.array([arr.fill_value], dtype=arr.dtype)[0]) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +@pytest.mark.parametrize( + ("dtype_str", "fill_value"), + [("bool", True), ("uint8", 99), ("float32", -99.9), ("complex64", 3 + 4j)], +) +def test_array_v3_fill_value(store: MemoryStore, fill_value: int, dtype_str: str) -> None: + shape = (10,) + arr = zarr.create_array( + store=store, + shape=shape, + dtype=dtype_str, + zarr_format=3, + chunks=shape, + fill_value=fill_value, + ) + + assert arr.fill_value == np.dtype(dtype_str).type(fill_value) + assert arr.fill_value.dtype == arr.dtype + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +async def test_array_v3_nan_fill_value(store: MemoryStore) -> None: + shape = (10,) + arr = zarr.create_array( + store=store, + shape=shape, + dtype=np.float64, + zarr_format=3, + chunks=shape, + fill_value=np.nan, + ) + arr[:] = np.nan + + assert np.isnan(arr.fill_value) + assert arr.fill_value.dtype == arr.dtype + # all fill value chunk is an empty chunk, and should not be written + assert len([a async for a in store.list_prefix("/")]) == 0 + + +@pytest.mark.parametrize("store", ["local"], indirect=["store"]) +@pytest.mark.parametrize("zarr_format", [2, 3]) +async def test_serializable_async_array( + store: LocalStore | MemoryStore, zarr_format: ZarrFormat +) -> None: + expected = await zarr.api.asynchronous.create_array( + store=store, shape=(100,), chunks=(10,), zarr_format=zarr_format, dtype="i4" + ) + # await expected.setitems(list(range(100))) + + p = pickle.dumps(expected) + actual = pickle.loads(p) + + assert actual == expected + # np.testing.assert_array_equal(await actual.getitem(slice(None)), await expected.getitem(slice(None))) + # TODO: uncomment the parts of this test that will be impacted by the config/prototype changes in flight + + +@pytest.mark.parametrize("store", ["local"], indirect=["store"]) +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_serializable_sync_array(store: LocalStore, zarr_format: ZarrFormat) -> None: + expected = zarr.create_array( + store=store, shape=(100,), chunks=(10,), zarr_format=zarr_format, dtype="i4" + ) + expected[:] = list(range(100)) + + p = pickle.dumps(expected) + actual = pickle.loads(p) + + assert actual == expected + np.testing.assert_array_equal(actual[:], expected[:]) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +@pytest.mark.parametrize("zarr_format", [2, 3, "invalid"]) +def test_storage_transformers(store: MemoryStore, zarr_format: ZarrFormat | str) -> None: + """ + Test that providing an actual storage transformer produces a warning and otherwise passes through + """ + metadata_dict: dict[str, JSON] + if zarr_format == 3: + metadata_dict = { + "zarr_format": 3, + "node_type": "array", + "shape": (10,), + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": (1,)}}, + "data_type": "uint8", + "chunk_key_encoding": {"name": "v2", "configuration": {"separator": "/"}}, + "codecs": (BytesCodec().to_dict(),), + "fill_value": 0, + "storage_transformers": ({"test": "should_raise"}), + } + else: + metadata_dict = { + "zarr_format": zarr_format, + "shape": (10,), + "chunks": (1,), + "dtype": "|u1", + "dimension_separator": ".", + "codecs": (BytesCodec().to_dict(),), + "fill_value": 0, + "order": "C", + "storage_transformers": ({"test": "should_raise"}), + } + if zarr_format == 3: + match = "Arrays with storage transformers are not supported in zarr-python at this time." + with pytest.raises(ValueError, match=match): + Array.from_dict(StorePath(store), data=metadata_dict) + elif zarr_format == 2: + # no warning + Array.from_dict(StorePath(store), data=metadata_dict) + else: + match = f"Invalid zarr_format: {zarr_format}. Expected 2 or 3" + with pytest.raises(ValueError, match=match): + Array.from_dict(StorePath(store), data=metadata_dict) + + +@pytest.mark.parametrize("test_cls", [AnyArray, AnyAsyncArray]) +@pytest.mark.parametrize("nchunks", [2, 5, 10]) +def test_nchunks(test_cls: type[AnyArray] | type[AnyAsyncArray], nchunks: int) -> None: + """ + Test that nchunks returns the number of chunks defined for the array. + """ + store = MemoryStore() + shape = 100 + arr = zarr.create_array(store, shape=(shape,), chunks=(ceildiv(shape, nchunks),), dtype="i4") + expected = nchunks + if test_cls == Array: + observed = arr.nchunks + else: + observed = arr.async_array.nchunks + assert observed == expected + + +@pytest.mark.parametrize("test_cls", [Array, AsyncArray]) +@pytest.mark.parametrize( + ("shape", "shard_shape", "chunk_shape"), + [((10,), None, (1,)), ((10,), (1,), (1,)), ((40,), (20,), (5,))], +) +async def test_nchunks_initialized( + test_cls: type[AnyArray] | type[AnyAsyncArray], + shape: tuple[int, ...], + shard_shape: tuple[int, ...] | None, + chunk_shape: tuple[int, ...], +) -> None: + """ + Test that nchunks_initialized accurately returns the number of stored partitions. + """ + store = MemoryStore() + if shard_shape is None: + chunks_per_shard = 1 + else: + chunks_per_shard = np.prod(np.array(shard_shape) // np.array(chunk_shape)) + + arr = zarr.create_array(store, shape=shape, shards=shard_shape, chunks=chunk_shape, dtype="i1") + + # write chunks one at a time + for idx, region in enumerate(arr._iter_shard_regions()): + arr[region] = 1 + expected = idx + 1 + if test_cls == Array: + observed = arr._nshards_initialized + assert observed == arr.nchunks_initialized // chunks_per_shard + else: + observed = await arr.async_array._nshards_initialized() + assert observed == await arr.async_array.nchunks_initialized() // chunks_per_shard + assert observed == expected + + # delete chunks + for idx, key in enumerate(arr._iter_shard_keys()): + sync(arr.store_path.store.delete(key)) + if test_cls == Array: + observed = arr._nshards_initialized + assert observed == arr.nchunks_initialized // chunks_per_shard + else: + observed = await arr.async_array._nshards_initialized() + assert observed == await arr.async_array.nchunks_initialized() // chunks_per_shard + expected = arr._nshards - idx - 1 + assert observed == expected + + +@pytest.mark.parametrize("path", ["", "foo"]) +@pytest.mark.parametrize( + ("shape", "shard_shape", "chunk_shape"), + [((10,), None, (1,)), ((10,), (1,), (1,)), ((40,), (20,), (5,))], +) +async def test_chunks_initialized( + path: str, shape: tuple[int, ...], shard_shape: tuple[int, ...], chunk_shape: tuple[int, ...] +) -> None: + """ + Test that chunks_initialized accurately returns the keys of stored chunks. + """ + store = MemoryStore() + arr = zarr.create_array( + store, name=path, shape=shape, shards=shard_shape, chunks=chunk_shape, dtype="i1" + ) + if path: + await store.set(path, cpu.Buffer.from_bytes(b"")) + + chunks_accumulated = tuple( + accumulate(tuple(tuple(v.split(" ")) for v in arr._iter_shard_keys())) + ) + for keys, region in zip(chunks_accumulated, arr._iter_shard_regions(), strict=False): + arr[region] = 1 + observed = sorted(await _shards_initialized(arr.async_array)) + expected = sorted(keys) + assert observed == expected + + +def test_nbytes_stored() -> None: + arr = zarr.create(shape=(100,), chunks=(10,), dtype="i4", codecs=[BytesCodec()]) + result = arr.nbytes_stored() + assert result == 502 # the size of the metadata document. This is a fragile test. + arr[:50] = 1 + result = arr.nbytes_stored() + assert result == 702 # the size with 5 chunks filled. + arr[50:] = 2 + result = arr.nbytes_stored() + assert result == 902 # the size with all chunks filled. + + +async def test_nbytes_stored_async() -> None: + arr = await zarr.api.asynchronous.create( + shape=(100,), chunks=(10,), dtype="i4", codecs=[BytesCodec()] + ) + result = await arr.nbytes_stored() + assert result == 502 # the size of the metadata document. This is a fragile test. + await arr.setitem(slice(50), 1) + result = await arr.nbytes_stored() + assert result == 702 # the size with 5 chunks filled. + await arr.setitem(slice(50, 100), 2) + result = await arr.nbytes_stored() + assert result == 902 # the size with all chunks filled. + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_update_attrs(zarr_format: ZarrFormat) -> None: + # regression test for https://github.com/zarr-developers/zarr-python/issues/2328 + store = MemoryStore() + arr = zarr.create_array( + store=store, shape=(5,), chunks=(5,), dtype="f8", zarr_format=zarr_format + ) + arr.attrs["foo"] = "bar" + assert arr.attrs["foo"] == "bar" + + arr2 = zarr.open_array(store=store, zarr_format=zarr_format) + assert arr2.attrs["foo"] == "bar" + + +@pytest.mark.parametrize(("chunks", "shards"), [((2, 2), None), ((2, 2), (4, 4))]) +class TestInfo: + def test_info_v2(self, chunks: tuple[int, int], shards: tuple[int, int] | None) -> None: + arr = zarr.create_array(store={}, shape=(8, 8), dtype="f8", chunks=chunks, zarr_format=2) + result = arr.info + expected = ArrayInfo( + _zarr_format=2, + _data_type=arr.async_array._zdtype, + _fill_value=arr.fill_value, + _shape=(8, 8), + _chunk_shape=chunks, + _shard_shape=None, + _order="C", + _read_only=False, + _store_type="MemoryStore", + _count_bytes=512, + _compressors=(numcodecs.Zstd(),), + ) + assert result == expected + + def test_info_v3(self, chunks: tuple[int, int], shards: tuple[int, int] | None) -> None: + arr = zarr.create_array(store={}, shape=(8, 8), dtype="f8", chunks=chunks, shards=shards) + result = arr.info + expected = ArrayInfo( + _zarr_format=3, + _data_type=arr.async_array._zdtype, + _fill_value=arr.fill_value, + _shape=(8, 8), + _chunk_shape=chunks, + _shard_shape=shards, + _order="C", + _read_only=False, + _store_type="MemoryStore", + _compressors=(ZstdCodec(),), + _serializer=BytesCodec(), + _count_bytes=512, + ) + assert result == expected + + def test_info_complete(self, chunks: tuple[int, int], shards: tuple[int, int] | None) -> None: + arr = zarr.create_array( + store={}, + shape=(8, 8), + dtype="f8", + chunks=chunks, + shards=shards, + compressors=(), + ) + result = arr.info_complete() + expected = ArrayInfo( + _zarr_format=3, + _data_type=arr.async_array._zdtype, + _fill_value=arr.fill_value, + _shape=(8, 8), + _chunk_shape=chunks, + _shard_shape=shards, + _order="C", + _read_only=False, + _store_type="MemoryStore", + _serializer=BytesCodec(), + _count_bytes=512, + _count_chunks_initialized=0, + _count_bytes_stored=521 if shards is None else 982, # the metadata? + ) + assert result == expected + + arr[:4, :4] = 10 + result = arr.info_complete() + if shards is None: + expected = dataclasses.replace( + expected, _count_chunks_initialized=4, _count_bytes_stored=649 + ) + else: + expected = dataclasses.replace( + expected, _count_chunks_initialized=1, _count_bytes_stored=1178 + ) + assert result == expected + + async def test_info_v2_async( + self, chunks: tuple[int, int], shards: tuple[int, int] | None + ) -> None: + arr = await zarr.api.asynchronous.create_array( + store={}, shape=(8, 8), dtype="f8", chunks=chunks, zarr_format=2 + ) + result = arr.info + expected = ArrayInfo( + _zarr_format=2, + _data_type=Float64(), + _fill_value=arr.metadata.fill_value, + _shape=(8, 8), + _chunk_shape=(2, 2), + _shard_shape=None, + _order="C", + _read_only=False, + _store_type="MemoryStore", + _count_bytes=512, + _compressors=(numcodecs.Zstd(),), + ) + assert result == expected + + async def test_info_v3_async( + self, chunks: tuple[int, int], shards: tuple[int, int] | None + ) -> None: + arr = await zarr.api.asynchronous.create_array( + store={}, + shape=(8, 8), + dtype="f8", + chunks=chunks, + shards=shards, + ) + result = arr.info + expected = ArrayInfo( + _zarr_format=3, + _data_type=arr._zdtype, + _fill_value=arr.metadata.fill_value, + _shape=(8, 8), + _chunk_shape=chunks, + _shard_shape=shards, + _order="C", + _read_only=False, + _store_type="MemoryStore", + _compressors=(ZstdCodec(),), + _serializer=BytesCodec(), + _count_bytes=512, + ) + assert result == expected + + async def test_info_complete_async( + self, chunks: tuple[int, int], shards: tuple[int, int] | None + ) -> None: + arr = await zarr.api.asynchronous.create_array( + store={}, + dtype="f8", + shape=(8, 8), + chunks=chunks, + shards=shards, + compressors=None, + ) + result = await arr.info_complete() + expected = ArrayInfo( + _zarr_format=3, + _data_type=arr._zdtype, + _fill_value=arr.metadata.fill_value, + _shape=(8, 8), + _chunk_shape=chunks, + _shard_shape=shards, + _order="C", + _read_only=False, + _store_type="MemoryStore", + _serializer=BytesCodec(), + _count_bytes=512, + _count_chunks_initialized=0, + _count_bytes_stored=521 if shards is None else 982, # the metadata? + ) + assert result == expected + + await arr.setitem((slice(4), slice(4)), 10) + result = await arr.info_complete() + if shards is None: + expected = dataclasses.replace( + expected, _count_chunks_initialized=4, _count_bytes_stored=553 + ) + else: + expected = dataclasses.replace( + expected, _count_chunks_initialized=1, _count_bytes_stored=1178 + ) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +def test_resize_1d(store: MemoryStore, zarr_format: ZarrFormat) -> None: + z = zarr.create( + shape=105, chunks=10, dtype="i4", fill_value=0, store=store, zarr_format=zarr_format + ) + a = np.arange(105, dtype="i4") + z[:] = a + result = z[:] + assert isinstance(result, NDArrayLike) + assert (105,) == z.shape + assert (105,) == result.shape + assert np.dtype("i4") == z.dtype + assert np.dtype("i4") == result.dtype + assert (10,) == z.chunks + np.testing.assert_array_equal(a, result) + + z.resize(205) + result = z[:] + assert isinstance(result, NDArrayLike) + assert (205,) == z.shape + assert (205,) == result.shape + assert np.dtype("i4") == z.dtype + assert np.dtype("i4") == result.dtype + assert (10,) == z.chunks + np.testing.assert_array_equal(a, z[:105]) + np.testing.assert_array_equal(np.zeros(100, dtype="i4"), z[105:]) + + z.resize(55) + result = z[:] + assert isinstance(result, NDArrayLike) + assert (55,) == z.shape + assert (55,) == result.shape + assert np.dtype("i4") == z.dtype + assert np.dtype("i4") == result.dtype + assert (10,) == z.chunks + np.testing.assert_array_equal(a[:55], result) + + # via shape setter + new_shape = (105,) + z.shape = new_shape + result = z[:] + assert isinstance(result, NDArrayLike) + assert new_shape == z.shape + assert new_shape == result.shape + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +def test_resize_2d(store: MemoryStore, zarr_format: ZarrFormat) -> None: + z = zarr.create( + shape=(105, 105), + chunks=(10, 10), + dtype="i4", + fill_value=0, + store=store, + zarr_format=zarr_format, + ) + a = np.arange(105 * 105, dtype="i4").reshape((105, 105)) + z[:] = a + result = z[:] + assert isinstance(result, NDArrayLike) + assert (105, 105) == z.shape + assert (105, 105) == result.shape + assert np.dtype("i4") == z.dtype + assert np.dtype("i4") == result.dtype + assert (10, 10) == z.chunks + np.testing.assert_array_equal(a, result) + + z.resize((205, 205)) + result = z[:] + assert isinstance(result, NDArrayLike) + assert (205, 205) == z.shape + assert (205, 205) == result.shape + assert np.dtype("i4") == z.dtype + assert np.dtype("i4") == result.dtype + assert (10, 10) == z.chunks + np.testing.assert_array_equal(a, z[:105, :105]) + np.testing.assert_array_equal(np.zeros((100, 205), dtype="i4"), z[105:, :]) + np.testing.assert_array_equal(np.zeros((205, 100), dtype="i4"), z[:, 105:]) + + z.resize((55, 55)) + result = z[:] + assert isinstance(result, NDArrayLike) + assert (55, 55) == z.shape + assert (55, 55) == result.shape + assert np.dtype("i4") == z.dtype + assert np.dtype("i4") == result.dtype + assert (10, 10) == z.chunks + np.testing.assert_array_equal(a[:55, :55], result) + + z.resize((55, 1)) + result = z[:] + assert isinstance(result, NDArrayLike) + assert (55, 1) == z.shape + assert (55, 1) == result.shape + assert np.dtype("i4") == z.dtype + assert np.dtype("i4") == result.dtype + assert (10, 10) == z.chunks + np.testing.assert_array_equal(a[:55, :1], result) + + z.resize((1, 55)) + result = z[:] + assert isinstance(result, NDArrayLike) + assert (1, 55) == z.shape + assert (1, 55) == result.shape + assert np.dtype("i4") == z.dtype + assert np.dtype("i4") == result.dtype + assert (10, 10) == z.chunks + np.testing.assert_array_equal(a[:1, :10], z[:, :10]) + np.testing.assert_array_equal(np.zeros((1, 55 - 10), dtype="i4"), z[:, 10:55]) + + # via shape setter + new_shape = (105, 105) + z.shape = new_shape + result = z[:] + assert isinstance(result, NDArrayLike) + assert new_shape == z.shape + assert new_shape == result.shape + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +def test_resize_growing_skips_chunk_enumeration( + store: MemoryStore, zarr_format: ZarrFormat +) -> None: + """Growing an array should not enumerate chunk coords for deletion (#3650 mitigation).""" + z = zarr.create( + shape=(10, 10), + chunks=(5, 5), + dtype="i4", + fill_value=0, + store=store, + zarr_format=zarr_format, + ) + z[:] = np.ones((10, 10), dtype="i4") + + grid_cls = type(z._chunk_grid) + + # growth only - ensure no chunk coords are enumerated + with mock.patch.object( + grid_cls, + "all_chunk_coords", + wraps=z._chunk_grid.all_chunk_coords, + ) as mock_coords: + z.resize((20, 20)) + mock_coords.assert_not_called() + + assert z.shape == (20, 20) + np.testing.assert_array_equal(np.ones((10, 10), dtype="i4"), z[:10, :10]) + np.testing.assert_array_equal(np.zeros((10, 10), dtype="i4"), z[10:, 10:]) + + # shrink - ensure no regression of behaviour + with mock.patch.object( + grid_cls, + "all_chunk_coords", + wraps=z._chunk_grid.all_chunk_coords, + ) as mock_coords: + z.resize((5, 5)) + assert mock_coords.call_count > 0 + + assert z.shape == (5, 5) + np.testing.assert_array_equal(np.ones((5, 5), dtype="i4"), z[:]) + + # mixed: grow dim 0, shrink dim 1 - ensure deletion path runs + z2 = zarr.create( + shape=(10, 10), + chunks=(5, 5), + dtype="i4", + fill_value=0, + store=store, + zarr_format=zarr_format, + overwrite=True, + ) + z2[:] = np.ones((10, 10), dtype="i4") + + with mock.patch.object( + grid_cls, + "all_chunk_coords", + wraps=z2._chunk_grid.all_chunk_coords, + ) as mock_coords: + z2.resize((20, 5)) + assert mock_coords.call_count > 0 + + assert z2.shape == (20, 5) + np.testing.assert_array_equal(np.ones((10, 5), dtype="i4"), z2[:10, :]) + np.testing.assert_array_equal(np.zeros((10, 5), dtype="i4"), z2[10:, :]) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +def test_append_1d(store: MemoryStore, zarr_format: ZarrFormat) -> None: + a = np.arange(105) + z = zarr.create(shape=a.shape, chunks=10, dtype=a.dtype, store=store, zarr_format=zarr_format) + z[:] = a + assert a.shape == z.shape + assert a.dtype == z.dtype + assert (10,) == z.chunks + np.testing.assert_array_equal(a, z[:]) + + b = np.arange(105, 205) + e = np.append(a, b) + assert z.shape == (105,) + z.append(b) + assert e.shape == z.shape + assert e.dtype == z.dtype + assert (10,) == z.chunks + np.testing.assert_array_equal(e, z[:]) + + # check append handles array-like + c = [1, 2, 3] + f = np.append(e, c) + z.append(c) + assert f.shape == z.shape + assert f.dtype == z.dtype + assert (10,) == z.chunks + np.testing.assert_array_equal(f, z[:]) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +def test_append_2d(store: MemoryStore, zarr_format: ZarrFormat) -> None: + a = np.arange(105 * 105, dtype="i4").reshape((105, 105)) + z = zarr.create( + shape=a.shape, chunks=(10, 10), dtype=a.dtype, store=store, zarr_format=zarr_format + ) + z[:] = a + assert a.shape == z.shape + assert a.dtype == z.dtype + assert (10, 10) == z.chunks + actual = z[:] + np.testing.assert_array_equal(a, actual) + + b = np.arange(105 * 105, 2 * 105 * 105, dtype="i4").reshape((105, 105)) + e = np.append(a, b, axis=0) + z.append(b) + assert e.shape == z.shape + assert e.dtype == z.dtype + assert (10, 10) == z.chunks + actual = z[:] + np.testing.assert_array_equal(e, actual) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +def test_append_2d_axis(store: MemoryStore, zarr_format: ZarrFormat) -> None: + a = np.arange(105 * 105, dtype="i4").reshape((105, 105)) + z = zarr.create( + shape=a.shape, chunks=(10, 10), dtype=a.dtype, store=store, zarr_format=zarr_format + ) + z[:] = a + assert a.shape == z.shape + assert a.dtype == z.dtype + assert (10, 10) == z.chunks + np.testing.assert_array_equal(a, z[:]) + + b = np.arange(105 * 105, 2 * 105 * 105, dtype="i4").reshape((105, 105)) + e = np.append(a, b, axis=1) + z.append(b, axis=1) + assert e.shape == z.shape + assert e.dtype == z.dtype + assert (10, 10) == z.chunks + np.testing.assert_array_equal(e, z[:]) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +def test_append_bad_shape(store: MemoryStore, zarr_format: ZarrFormat) -> None: + a = np.arange(100) + z = zarr.create(shape=a.shape, chunks=10, dtype=a.dtype, store=store, zarr_format=zarr_format) + z[:] = a + b = a.reshape(10, 10) + with pytest.raises(ValueError): + z.append(b) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +@pytest.mark.parametrize("write_empty_chunks", [True, False]) +@pytest.mark.parametrize("fill_value", [0, 5]) +def test_write_empty_chunks_behavior( + zarr_format: ZarrFormat, store: MemoryStore, write_empty_chunks: bool, fill_value: int +) -> None: + """ + Check that the write_empty_chunks value of the config is applied correctly. We expect that + when write_empty_chunks is True, writing chunks equal to the fill value will result in + those chunks appearing in the store. + + When write_empty_chunks is False, writing chunks that are equal to the fill value will result in + those chunks not being present in the store. In particular, they should be deleted if they were + already present. + """ + + arr = zarr.create_array( + store=store, + shape=(2,), + zarr_format=zarr_format, + dtype="i4", + fill_value=fill_value, + chunks=(1,), + config={"write_empty_chunks": write_empty_chunks}, + ) + + assert arr.async_array.config.write_empty_chunks == write_empty_chunks + + # initialize the store with some non-fill value chunks + arr[:] = fill_value + 1 + assert arr._nshards_initialized == arr._nshards + + arr[:] = fill_value + + if not write_empty_chunks: + assert arr._nshards_initialized == 0 + else: + assert arr._nshards_initialized == arr._nshards + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +@pytest.mark.parametrize("fill_value", [0.0, -0.0]) +@pytest.mark.parametrize("dtype", ["f4", "f2"]) +def test_write_empty_chunks_negative_zero( + zarr_format: ZarrFormat, store: MemoryStore, fill_value: float, dtype: str +) -> None: + # regression test for https://github.com/zarr-developers/zarr-python/issues/3144 + + arr = zarr.create_array( + store=store, + shape=(2,), + zarr_format=zarr_format, + dtype=dtype, + fill_value=fill_value, + chunks=(1,), + config={"write_empty_chunks": False}, + ) + assert arr.nchunks_initialized == 0 + + # initialize the with the negated fill value (-0.0 for +0.0, +0.0 for -0.0) + arr[:] = -fill_value + assert arr.nchunks_initialized == arr.nchunks + + +@pytest.mark.parametrize( + ("fill_value", "expected"), + [ + (np.nan * 1j, ["NaN", "NaN"]), + (np.nan, ["NaN", 0.0]), + (np.inf, ["Infinity", 0.0]), + (np.inf * 1j, ["NaN", "Infinity"]), + (-np.inf, ["-Infinity", 0.0]), + (math.inf, ["Infinity", 0.0]), + ], +) +async def test_special_complex_fill_values_roundtrip(fill_value: Any, expected: list[Any]) -> None: + store = MemoryStore() + zarr.create_array(store=store, shape=(1,), dtype=np.complex64, fill_value=fill_value) + content = await store.get("zarr.json", prototype=default_buffer_prototype()) + assert content is not None + actual = json.loads(content.to_bytes()) + assert actual["fill_value"] == expected + + +@pytest.mark.parametrize("shape", [(1,), (2, 3), (4, 5, 6)]) +@pytest.mark.parametrize("dtype", ["uint8", "float32"]) +@pytest.mark.parametrize("array_type", ["async", "sync"]) +async def test_nbytes( + shape: tuple[int, ...], dtype: str, array_type: Literal["async", "sync"] +) -> None: + """ + Test that the ``nbytes`` attribute of an Array or AsyncArray correctly reports the capacity of + the chunks of that array. + """ + store = MemoryStore() + arr = zarr.create_array(store=store, shape=shape, dtype=dtype, fill_value=0) + if array_type == "async": + assert arr.async_array.nbytes == np.prod(arr.shape) * arr.dtype.itemsize + else: + assert arr.nbytes == np.prod(arr.shape) * arr.dtype.itemsize + + +@pytest.mark.parametrize( + ("array_shape", "chunk_shape", "target_shard_size_bytes", "expected_shards"), + [ + pytest.param( + (256, 256), + (32, 32), + 129 * 129, + (128, 128), + id="2d_chunking_max_byes_does_not_evenly_divide", + ), + pytest.param( + (256, 256), (32, 32), 64 * 64, (64, 64), id="2d_chunking_max_byes_evenly_divides" + ), + pytest.param( + (256, 256), + (64, 32), + 128 * 128, + (128, 64), + id="2d_non_square_chunking_max_byes_evenly_divides", + ), + pytest.param((256,), (2,), 255, (254,), id="max_bytes_just_below_array_shape"), + pytest.param((256,), (2,), 256, (256,), id="max_bytes_equal_to_array_shape"), + pytest.param((256,), (2,), 16, (16,), id="max_bytes_normal_val"), + pytest.param((256,), (2,), 2, (2,), id="max_bytes_same_as_chunk"), + pytest.param((256,), (2,), 1, (2,), id="max_bytes_less_than_chunk"), + pytest.param((256,), (2,), None, (4,), id="use_default_auto_setting"), + pytest.param((4,), (2,), None, (2,), id="small_array_shape_does_not_shard"), + ], +) +def test_auto_partition_auto_shards( + array_shape: tuple[int, ...], + chunk_shape: tuple[int, ...], + target_shard_size_bytes: int | None, + expected_shards: tuple[int, ...], +) -> None: + """ + Test that automatically picking a shard size returns a tuple of 2 * the chunk shape for any axis + where there are 8 or more chunks. + """ + dtype = np.dtype("uint8") + chunks_normalized = normalize_chunks_nd(chunk_shape, array_shape) + with pytest.warns( + ZarrUserWarning, + match="Automatic shard shape inference is experimental and may change without notice.", + ): + with zarr.config.set({"array.target_shard_size_bytes": target_shard_size_bytes}): + outer_chunks, _ = resolve_outer_and_inner_chunks( + array_shape=array_shape, + chunks=chunks_normalized, + shard_shape="auto", + item_size=dtype.itemsize, + ) + auto_shards = tuple(dim[0] for dim in outer_chunks) + assert auto_shards == expected_shards + + +def test_auto_partition_auto_shards_with_auto_chunks_should_be_close_to_1MiB() -> None: + """ + Test that automatically picking chunk and shard sizes together produces + chunks close to 1 MiB and shards that are a multiple of the chunk size. + """ + array_shape = (10_000_000,) + item_size = 1 + # Auto-chunks with sharding use the default inner chunk size target + chunks_normalized = guess_chunks( + array_shape, item_size, max_bytes=SHARDED_INNER_CHUNK_MAX_BYTES + ) + chunk_shape = tuple(dim[0] for dim in chunks_normalized) + chunk_bytes = np.prod(chunk_shape) * item_size + assert chunk_bytes <= SHARDED_INNER_CHUNK_MAX_BYTES + assert chunk_bytes > SHARDED_INNER_CHUNK_MAX_BYTES // 4 # should be in the right ballpark + + with pytest.warns( + ZarrUserWarning, + match="Automatic shard shape inference is experimental and may change without notice.", + ): + with zarr.config.set({"array.target_shard_size_bytes": 10_000_000}): + outer_chunks, inner = resolve_outer_and_inner_chunks( + array_shape=array_shape, + chunks=chunks_normalized, + shard_shape="auto", + item_size=item_size, + ) + assert inner is not None + shard_shape = tuple(dim[0] for dim in outer_chunks) + # Shard dimensions must be multiples of chunk dimensions + assert all(s % c == 0 for s, c in zip(shard_shape, chunk_shape, strict=True)) + + +def test_chunks_and_shards() -> None: + store = StorePath(MemoryStore()) + shape = (100, 100) + chunks = (5, 5) + shards = (10, 10) + + arr_v3 = zarr.create_array(store=store / "v3", shape=shape, chunks=chunks, dtype="i4") + assert arr_v3.chunks == chunks + assert arr_v3.shards is None + + arr_v3_sharding = zarr.create_array( + store=store / "v3_sharding", + shape=shape, + chunks=chunks, + shards=shards, + dtype="i4", + ) + assert arr_v3_sharding.chunks == chunks + assert arr_v3_sharding.shards == shards + + arr_v2 = zarr.create_array( + store=store / "v2", shape=shape, chunks=chunks, zarr_format=2, dtype="i4" + ) + assert arr_v2.chunks == chunks + assert arr_v2.shards is None + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@pytest.mark.parametrize( + ("dtype", "fill_value_expected"), [(" None: + a = zarr.create_array(store, shape=(5,), chunks=(5,), dtype=dtype) + assert a.fill_value == fill_value_expected + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +class TestCreateArray: + @staticmethod + def test_chunks_and_shards(store: Store) -> None: + spath = StorePath(store) + shape = (100, 100) + chunks = (5, 5) + shards = (10, 10) + + arr_v3 = zarr.create_array(store=spath / "v3", shape=shape, chunks=chunks, dtype="i4") + assert arr_v3.chunks == chunks + assert arr_v3.shards is None + + arr_v3_sharding = zarr.create_array( + store=spath / "v3_sharding", + shape=shape, + chunks=chunks, + shards=shards, + dtype="i4", + ) + assert arr_v3_sharding.chunks == chunks + assert arr_v3_sharding.shards == shards + + arr_v2 = zarr.create_array( + store=spath / "v2", shape=shape, chunks=chunks, zarr_format=2, dtype="i4" + ) + assert arr_v2.chunks == chunks + assert arr_v2.shards is None + + @staticmethod + @pytest.mark.parametrize("dtype", zdtype_examples) + @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") + def test_default_fill_value(dtype: ZDType[Any, Any], store: Store) -> None: + """ + Test that the fill value of an array is set to the default value for the dtype object + """ + a = zarr.create_array(store, shape=(5,), chunks=(5,), dtype=dtype) + if isinstance(dtype, DateTime64 | TimeDelta64) and np.isnat(a.fill_value): + assert np.isnat(dtype.default_scalar()) + else: + assert a.fill_value == dtype.default_scalar() + + @staticmethod + # @pytest.mark.parametrize("zarr_format", [2, 3]) + @pytest.mark.parametrize("dtype", zdtype_examples) + @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") + def test_default_fill_value_None( + dtype: ZDType[Any, Any], store: Store, zarr_format: ZarrFormat + ) -> None: + """ + Test that the fill value of an array is set to the default value for an explicit None argument for + Zarr Format 3, and to null for Zarr Format 2 + """ + a = zarr.create_array( + store, shape=(5,), chunks=(5,), dtype=dtype, fill_value=None, zarr_format=zarr_format + ) + if zarr_format == 3: + if isinstance(dtype, DateTime64 | TimeDelta64) and np.isnat(a.fill_value): + assert np.isnat(dtype.default_scalar()) + else: + assert a.fill_value == dtype.default_scalar() + elif zarr_format == 2: + assert a.fill_value is None + + @staticmethod + @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") + @pytest.mark.parametrize("dtype", zdtype_examples) + def test_dtype_forms(dtype: ZDType[Any, Any], store: Store, zarr_format: ZarrFormat) -> None: + """ + Test that the same array is produced from a ZDType instance, a numpy dtype, or a numpy string + """ + skip_object_dtype(dtype) + a = zarr.create_array( + store, name="a", shape=(5,), chunks=(5,), dtype=dtype, zarr_format=zarr_format + ) + + b = zarr.create_array( + store, + name="b", + shape=(5,), + chunks=(5,), + dtype=dtype.to_native_dtype(), + zarr_format=zarr_format, + ) + assert a.dtype == b.dtype + + # Structured dtypes do not have a numpy string representation that uniquely identifies them + if not isinstance(dtype, Structured): + if isinstance(dtype, VariableLengthUTF8): + # in numpy 2.3, StringDType().str becomes the string 'StringDType()' which numpy + # does not accept as a string representation of the dtype. + c = zarr.create_array( + store, + name="c", + shape=(5,), + chunks=(5,), + dtype=dtype.to_native_dtype().char, + zarr_format=zarr_format, + ) + else: + c = zarr.create_array( + store, + name="c", + shape=(5,), + chunks=(5,), + dtype=dtype.to_native_dtype().str, + zarr_format=zarr_format, + ) + assert a.dtype == c.dtype + + @staticmethod + @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") + @pytest.mark.parametrize("dtype", zdtype_examples) + def test_dtype_roundtrip( + dtype: ZDType[Any, Any], store: Store, zarr_format: ZarrFormat + ) -> None: + """ + Test that creating an array, then opening it, gets the same array. + """ + skip_object_dtype(dtype) + a = zarr.create_array(store, shape=(5,), chunks=(5,), dtype=dtype, zarr_format=zarr_format) + b = zarr.open_array(store) + assert a.dtype == b.dtype + + @staticmethod + @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") + @pytest.mark.parametrize("dtype", ["uint8", "float32", "U3", "S4", "V1"]) + @pytest.mark.parametrize( + "compressors", + [ + "auto", + None, + (), + (ZstdCodec(level=3),), + (ZstdCodec(level=3), GzipCodec(level=0)), + ZstdCodec(level=3), + {"name": "zstd", "configuration": {"level": 3}}, + ({"name": "zstd", "configuration": {"level": 3}},), + ], + ) + @pytest.mark.parametrize( + "filters", + [ + "auto", + None, + (), + ( + TransposeCodec( + order=[ + 0, + ] + ), + ), + ( + TransposeCodec( + order=[ + 0, + ] + ), + TransposeCodec( + order=[ + 0, + ] + ), + ), + TransposeCodec( + order=[ + 0, + ] + ), + {"name": "transpose", "configuration": {"order": [0]}}, + ({"name": "transpose", "configuration": {"order": [0]}},), + ], + ) + @pytest.mark.parametrize(("chunks", "shards"), [((6,), None), ((3,), (6,))]) + async def test_v3_chunk_encoding( + store: MemoryStore, + compressors: CompressorsLike, + filters: FiltersLike, + dtype: str, + chunks: tuple[int, ...], + shards: tuple[int, ...] | None, + ) -> None: + """ + Test various possibilities for the compressors and filters parameter to create_array + """ + arr = await create_array( + store=store, + dtype=dtype, + shape=(12,), + chunks=chunks, + shards=shards, + zarr_format=3, + filters=filters, + compressors=compressors, + ) + filters_expected, _, compressors_expected = _parse_chunk_encoding_v3( + filters=filters, + compressors=compressors, + serializer="auto", + dtype=arr._zdtype, + ) + assert arr.filters == filters_expected + assert arr.compressors == compressors_expected + + @staticmethod + @pytest.mark.parametrize("name", ["v2", "default", "invalid"]) + @pytest.mark.parametrize("separator", [".", "/"]) + async def test_chunk_key_encoding( + name: str, separator: Literal[".", "/"], zarr_format: ZarrFormat, store: MemoryStore + ) -> None: + chunk_key_encoding = ChunkKeyEncodingParams(name=name, separator=separator) # type: ignore[typeddict-item] + error_msg = "" + if name == "invalid": + error_msg = r'Unknown chunk key encoding: "Chunk key encoding \'invalid\' not found in registered chunk key encodings: \[.*\]."' + if zarr_format == 2 and name == "default": + error_msg = "Invalid chunk key encoding. For Zarr format 2 arrays, the `name` field of the chunk key encoding must be 'v2'." + if error_msg: + with pytest.raises(ValueError, match=error_msg): + arr = await create_array( + store=store, + dtype="uint8", + shape=(10,), + chunks=(1,), + zarr_format=zarr_format, + chunk_key_encoding=chunk_key_encoding, + ) + else: + arr = await create_array( + store=store, + dtype="uint8", + shape=(10,), + chunks=(1,), + zarr_format=zarr_format, + chunk_key_encoding=chunk_key_encoding, + ) + if isinstance(arr.metadata, ArrayV2Metadata): + assert arr.metadata.dimension_separator == separator + + @staticmethod + @pytest.mark.parametrize( + ("kwargs", "error_msg"), + [ + ({"serializer": "bytes"}, "Zarr format 2 arrays do not support `serializer`."), + ({"dimension_names": ["test"]}, "Zarr format 2 arrays do not support dimension names."), + ], + ) + async def test_create_array_invalid_v2_arguments( + kwargs: dict[str, Any], error_msg: str, store: MemoryStore + ) -> None: + with pytest.raises(ValueError, match=re.escape(error_msg)): + await zarr.api.asynchronous.create_array( + store=store, dtype="uint8", shape=(10,), chunks=(1,), zarr_format=2, **kwargs + ) + + @staticmethod + @pytest.mark.parametrize( + ("kwargs", "error_msg"), + [ + ( + {"dimension_names": ["test"]}, + "dimension_names cannot be used for arrays with zarr_format 2.", + ), + ( + {"chunk_key_encoding": {"name": "default", "separator": "/"}}, + "chunk_key_encoding cannot be used for arrays with zarr_format 2. Use dimension_separator instead.", + ), + ( + {"codecs": "bytes"}, + "codecs cannot be used for arrays with zarr_format 2. Use filters and compressor instead.", + ), + ], + ) + async def test_create_invalid_v2_arguments( + kwargs: dict[str, Any], error_msg: str, store: MemoryStore + ) -> None: + with pytest.raises(ValueError, match=re.escape(error_msg)): + await zarr.api.asynchronous.create( + store=store, dtype="uint8", shape=(10,), chunks=(1,), zarr_format=2, **kwargs + ) + + @staticmethod + @pytest.mark.parametrize( + ("kwargs", "error_msg"), + [ + ( + {"chunk_shape": (1,), "chunks": (2,)}, + "Only one of chunk_shape or chunks can be provided.", + ), + ( + {"dimension_separator": "/"}, + "dimension_separator cannot be used for arrays with zarr_format 3. Use chunk_key_encoding instead.", + ), + ( + {"filters": []}, + "filters cannot be used for arrays with zarr_format 3. Use array-to-array codecs instead", + ), + ( + {"compressor": "blosc"}, + "compressor cannot be used for arrays with zarr_format 3. Use bytes-to-bytes codecs instead", + ), + ], + ) + async def test_invalid_v3_arguments( + kwargs: dict[str, Any], error_msg: str, store: MemoryStore + ) -> None: + kwargs.setdefault("chunks", (1,)) + with pytest.raises(ValueError, match=re.escape(error_msg)): + zarr.create(store=store, dtype="uint8", shape=(10,), zarr_format=3, **kwargs) + + @staticmethod + @pytest.mark.parametrize("dtype", ["uint8", "float32", "str", "U10", "S10", ">M8[10s]"]) + @pytest.mark.parametrize( + "compressors", + [ + "auto", + None, + numcodecs.Zstd(level=3), + (), + (numcodecs.Zstd(level=3),), + ], + ) + @pytest.mark.parametrize( + "filters", ["auto", None, numcodecs.GZip(level=1), (numcodecs.GZip(level=1),)] + ) + async def test_v2_chunk_encoding( + store: MemoryStore, compressors: CompressorsLike, filters: FiltersLike, dtype: str + ) -> None: + if dtype == "str" and filters != "auto": + pytest.skip("Only the auto filters are compatible with str dtype in this test.") + arr: AsyncArray[ArrayV2Metadata] = await create_array( + store=store, + dtype=dtype, + shape=(10,), + zarr_format=2, + compressors=compressors, + filters=filters, + ) + filters_expected, compressor_expected = _parse_chunk_encoding_v2( + filters=filters, compressor=compressors, dtype=parse_dtype(dtype, zarr_format=2) + ) + assert arr.metadata.zarr_format == 2 # guard for mypy + assert arr.metadata.compressor == compressor_expected + assert arr.metadata.filters == filters_expected + + # Normalize for property getters + arr_compressors_expected = () if compressor_expected is None else (compressor_expected,) + arr_filters_expected = () if filters_expected is None else filters_expected + + assert arr.compressors == arr_compressors_expected + assert arr.filters == arr_filters_expected + + @staticmethod + @pytest.mark.parametrize("dtype", [UInt8(), Float32(), VariableLengthUTF8()]) + @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") + async def test_default_filters_compressors( + store: MemoryStore, dtype: UInt8 | Float32 | VariableLengthUTF8, zarr_format: ZarrFormat + ) -> None: + """ + Test that the default ``filters`` and ``compressors`` are used when ``create_array`` is invoked with ``filters`` and ``compressors`` unspecified. + """ + + arr = await create_array( + store=store, + dtype=dtype, # type: ignore[arg-type] + shape=(10,), + zarr_format=zarr_format, + ) + + sig = inspect.signature(create_array) + + if zarr_format == 3: + expected_filters, expected_serializer, expected_compressors = _parse_chunk_encoding_v3( + compressors=sig.parameters["compressors"].default, + filters=sig.parameters["filters"].default, + serializer=sig.parameters["serializer"].default, + dtype=dtype, # type: ignore[arg-type] + ) + + elif zarr_format == 2: + default_filters, default_compressors = _parse_chunk_encoding_v2( + compressor=sig.parameters["compressors"].default, + filters=sig.parameters["filters"].default, + dtype=dtype, # type: ignore[arg-type] + ) + if default_filters is None: + expected_filters = () + else: + expected_filters = default_filters # type: ignore[assignment] + + if default_compressors is None: + expected_compressors = () + else: + expected_compressors = (default_compressors,) # type: ignore[assignment] + expected_serializer = None + else: + raise ValueError(f"Invalid zarr_format: {zarr_format}") + + assert arr.filters == expected_filters + assert arr.serializer == expected_serializer + assert arr.compressors == expected_compressors + + @staticmethod + async def test_v2_no_shards(store: Store) -> None: + """ + Test that creating a Zarr v2 array with ``shard_shape`` set to a non-None value raises an error. + """ + msg = re.escape( + "Zarr format 2 arrays can only be created with `shard_shape` set to `None`. Got `shard_shape=(5,)` instead." + ) + with pytest.raises(ValueError, match=msg): + _ = await create_array( + store=store, + dtype="uint8", + shape=(10,), + shards=(5,), + zarr_format=2, + ) + + @staticmethod + @pytest.mark.parametrize("impl", ["sync", "async"]) + async def test_with_data(impl: Literal["sync", "async"], store: Store) -> None: + """ + Test that we can invoke ``create_array`` with a ``data`` parameter. + """ + data = np.arange(10) + name = "foo" + arr: AnyAsyncArray | AnyArray + if impl == "sync": + arr = sync_api.create_array(store, name=name, data=data) + stored = arr[:] + elif impl == "async": + arr = await create_array(store, name=name, data=data, zarr_format=3) + stored = await arr._get_selection( + BasicIndexer(..., shape=arr.shape, chunk_grid=arr._chunk_grid), + prototype=default_buffer_prototype(), + ) + else: + raise ValueError(f"Invalid impl: {impl}") + + assert np.array_equal(stored, data) + + @staticmethod + async def test_with_data_invalid_params(store: Store) -> None: + """ + Test that failing to specify data AND shape / dtype results in a ValueError + """ + with pytest.raises(ValueError, match="shape was not specified"): + await create_array(store, data=None, shape=None, dtype=None) + + # we catch shape=None first, so specifying a dtype should raise the same exception as before + with pytest.raises(ValueError, match="shape was not specified"): + await create_array(store, data=None, shape=None, dtype="uint8") + + with pytest.raises(ValueError, match="dtype was not specified"): + await create_array(store, data=None, shape=(10, 10)) + + @staticmethod + async def test_data_ignored_params(store: Store) -> None: + """ + Test that specifying data AND shape AND dtype results in a ValueError + """ + data = np.arange(10) + with pytest.raises( + ValueError, match="The data parameter was used, but the shape parameter was also used." + ): + await create_array(store, data=data, shape=data.shape, dtype=None, overwrite=True) + + # we catch shape first, so specifying a dtype should raise the same warning as before + with pytest.raises( + ValueError, match="The data parameter was used, but the shape parameter was also used." + ): + await create_array(store, data=data, shape=data.shape, dtype=data.dtype, overwrite=True) + + with pytest.raises( + ValueError, match="The data parameter was used, but the dtype parameter was also used." + ): + await create_array(store, data=data, shape=None, dtype=data.dtype, overwrite=True) + + @staticmethod + @pytest.mark.parametrize("write_empty_chunks", [True, False]) + async def test_write_empty_chunks_config(write_empty_chunks: bool, store: Store) -> None: + """ + Test that the value of write_empty_chunks is sensitive to the global config when not set + explicitly + """ + with zarr.config.set({"array.write_empty_chunks": write_empty_chunks}): + arr = await create_array(store, shape=(2, 2), dtype="i4") + assert arr.config.write_empty_chunks == write_empty_chunks + + @staticmethod + @pytest.mark.parametrize("path", [None, "", "/", "/foo", "foo", "foo/bar"]) + async def test_name(store: Store, zarr_format: ZarrFormat, path: str | None) -> None: + arr = await create_array( + store, shape=(2, 2), dtype="i4", name=path, zarr_format=zarr_format + ) + if path is None: + expected_path = "" + elif path.startswith("/"): + expected_path = path.lstrip("/") + else: + expected_path = path + assert arr.path == expected_path + assert arr.name == f"/{expected_path}" + + # test that implicit groups were created + path_parts = expected_path.split("/") + if len(path_parts) > 1: + *parents, _ = ["", *accumulate(path_parts, lambda x, y: "/".join([x, y]))] # noqa: FLY002 + for parent_path in parents: + # this will raise if these groups were not created + _ = await zarr.api.asynchronous.open_group( + store=store, path=parent_path, zarr_format=zarr_format + ) + + @staticmethod + @pytest.mark.parametrize("endianness", ENDIANNESS_STR) + def test_default_endianness( + store: Store, zarr_format: ZarrFormat, endianness: EndiannessStr + ) -> None: + """ + Test that endianness is correctly set when creating an array when not specifying a serializer. + """ + dtype = Int16(endianness=endianness) + arr = zarr.create_array(store=store, shape=(1,), dtype=dtype, zarr_format=zarr_format) + byte_order: str = arr[:].dtype.byteorder # type: ignore[union-attr] + assert byte_order in NUMPY_ENDIANNESS_STR + assert endianness_from_numpy_str(byte_order) == endianness # type: ignore[arg-type] + + +# The explicit id for b"a" avoids colliding with the auto-generated id for "a". +@pytest.mark.parametrize("value", [1, 1.4, "a", pytest.param(b"a", id="a-bytes"), np.array(1)]) +@pytest.mark.parametrize("zarr_format", [2, 3]) +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +def test_scalar_array(value: Any, zarr_format: ZarrFormat) -> None: + arr = zarr.array(value, zarr_format=zarr_format) + assert arr[...] == value + assert arr.shape == () + assert arr.ndim == 0 + assert isinstance(arr[()], NDArrayLikeOrScalar) + + +@pytest.mark.parametrize("store", ["local"], indirect=True) +@pytest.mark.parametrize("store2", ["local"], indirect=["store2"]) +@pytest.mark.parametrize("src_format", [2, 3]) +@pytest.mark.parametrize("new_format", [2, 3, None]) +async def test_creation_from_other_zarr_format( + store: Store, + store2: Store, + src_format: ZarrFormat, + new_format: ZarrFormat | None, +) -> None: + if src_format == 2: + src = zarr.create( + (50, 50), chunks=(10, 10), store=store, zarr_format=src_format, dimension_separator="/" + ) + else: + src = zarr.create( + (50, 50), + chunks=(10, 10), + store=store, + zarr_format=src_format, + chunk_key_encoding=("default", "."), + ) + + src[:] = np.arange(50 * 50).reshape((50, 50)) + result = zarr.from_array( + store=store2, + data=src, + zarr_format=new_format, + ) + np.testing.assert_array_equal(result[:], src[:]) + assert result.fill_value == src.fill_value + assert result.dtype == src.dtype + assert result.chunks == src.chunks + expected_format = src_format if new_format is None else new_format + assert result.metadata.zarr_format == expected_format + if src_format == new_format: + assert result.metadata == src.metadata + + result2 = zarr.array( + data=src, + store=store2, + overwrite=True, + zarr_format=new_format, + ) + np.testing.assert_array_equal(result2[:], src[:]) + + +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=True) +@pytest.mark.parametrize("store2", ["local", "memory", "zip"], indirect=["store2"]) +@pytest.mark.parametrize("src_chunks", [(40, 10), (11, 50)]) +@pytest.mark.parametrize("new_chunks", [(40, 10), (11, 50)]) +async def test_from_array( + store: Store, + store2: Store, + src_chunks: tuple[int, int], + new_chunks: tuple[int, int], + zarr_format: ZarrFormat, +) -> None: + src_fill_value = 2 + src_dtype = np.dtype("uint8") + src_attributes = None + + src = zarr.create( + (100, 10), + chunks=src_chunks, + dtype=src_dtype, + store=store, + fill_value=src_fill_value, + attributes=src_attributes, + ) + src[:] = np.arange(1000).reshape((100, 10)) + + new_fill_value = 3 + new_attributes: dict[str, JSON] = {"foo": "bar"} + + result = zarr.from_array( + data=src, + store=store2, + chunks=new_chunks, + fill_value=new_fill_value, + attributes=new_attributes, + ) + + np.testing.assert_array_equal(result[:], src[:]) + assert result.fill_value == new_fill_value + assert result.dtype == src_dtype + assert result.attrs == new_attributes + assert result.chunks == new_chunks + + +@pytest.mark.parametrize("store", ["local"], indirect=True) +@pytest.mark.parametrize("chunks", ["keep", "auto"]) +@pytest.mark.parametrize("write_data", [True, False]) +@pytest.mark.parametrize( + "src", + [ + np.arange(1000).reshape(10, 10, 10), + zarr.ones((10, 10, 10)), + 5, + [1, 2, 3], + [[1, 2, 3], [4, 5, 6]], + ], +) # add other npt.ArrayLike? +async def test_from_array_arraylike( + store: Store, + chunks: Literal["auto", "keep"] | tuple[int, int], + write_data: bool, + src: AnyArray | npt.ArrayLike, +) -> None: + fill_value = 42 + result = zarr.from_array( + store, data=src, chunks=chunks, write_data=write_data, fill_value=fill_value + ) + if write_data: + np.testing.assert_array_equal(result[...], np.array(src)) + else: + np.testing.assert_array_equal(result[...], np.full_like(src, fill_value)) + + +def test_from_array_F_order() -> None: + arr = zarr.create_array(store={}, data=np.array([1]), order="F", zarr_format=2) + with pytest.warns( + ZarrUserWarning, + match="The existing order='F' of the source Zarr format 2 array will be ignored.", + ): + zarr.from_array(store={}, data=arr, zarr_format=3) + + +async def test_orthogonal_set_total_slice() -> None: + """Ensure that a whole chunk overwrite does not read chunks""" + store = MemoryStore() + array = zarr.create_array(store, shape=(20, 20), chunks=(1, 2), dtype=int, fill_value=-1) + with mock.patch("zarr.storage.MemoryStore.get", side_effect=RuntimeError): + array[0, slice(4, 10)] = np.arange(6) + + array = zarr.create_array( + store, shape=(20, 21), chunks=(1, 2), dtype=int, fill_value=-1, overwrite=True + ) + with mock.patch("zarr.storage.MemoryStore.get", side_effect=RuntimeError): + array[0, :] = np.arange(21) + + with mock.patch("zarr.storage.MemoryStore.get", side_effect=RuntimeError): + array[:] = 1 + + +@pytest.mark.skipif( + Version(numcodecs.__version__) < Version("0.15.1"), + reason="codec configuration is overwritten on older versions. GH2800", +) +def test_roundtrip_numcodecs() -> None: + store = MemoryStore() + + compressors = [ + {"name": "numcodecs.shuffle", "configuration": {"elementsize": 2}}, + {"name": "numcodecs.zlib", "configuration": {"level": 4}}, + ] + filters: list[CodecJSON_V3] = [ + { + "name": "numcodecs.fixedscaleoffset", + "configuration": { + "scale": 100.0, + "offset": 0.0, + "dtype": " Any: + return arr[index] + + +@pytest.mark.parametrize( + "method", + [ + pytest.param( + "fork", + marks=[ + pytest.mark.skipif( + sys.platform in ("win32", "darwin"), + reason="fork not supported on Windows or OSX", + ), + # Python 3.15 deprecates fork() in multi-threaded processes, and zarr's + # sync event-loop thread is always running here. Fork-safety despite + # those threads is exactly what this test pins down, so keep running it. + pytest.mark.filterwarnings( + r"ignore:This process \(pid=\d+\) is multi-threaded, use of fork\(\):DeprecationWarning" + ), + ], + ), + "spawn", + pytest.param( + "forkserver", + marks=pytest.mark.skipif( + sys.platform == "win32", reason="forkserver not supported on Windows" + ), + ), + ], +) +@pytest.mark.parametrize("store", ["local"], indirect=True) +@pytest.mark.parametrize("shards", [None, (20,)]) +def test_multiprocessing( + store: Store, method: Literal["fork", "spawn", "forkserver"], shards: tuple[int, ...] | None +) -> None: + """ + Test that arrays can be pickled and indexed in child processes + """ + data = np.arange(100) + chunks: Literal["auto"] | tuple[int, ...] + if shards is None: + chunks = "auto" + else: + chunks = (1,) + arr = zarr.create_array(store=store, data=data, shards=shards, chunks=chunks) + ctx = mp.get_context(method) + with ctx.Pool() as pool: + results = pool.starmap(_index_array, [(arr, slice(len(data)))]) + assert all(np.array_equal(r, data) for r in results) + + +def test_create_array_method_signature() -> None: + """ + Test that the signature of the ``AsyncGroup.create_array`` function has nearly the same signature + as the ``create_array`` function. ``AsyncGroup.create_array`` should take all of the same keyword + arguments as ``create_array`` except ``store``. + """ + + base_sig = inspect.signature(create_array) + meth_sig = inspect.signature(AsyncGroup.create_array) + # ignore keyword arguments that are either missing or have different semantics when + # create_array is invoked as a group method + ignore_kwargs = {"zarr_format", "store", "name"} + # TODO: make this test stronger. right now, it only checks that all the parameters in the + # function signature are used in the method signature. we can be more strict and check that + # the method signature uses no extra parameters. + base_params = dict(filter(lambda kv: kv[0] not in ignore_kwargs, base_sig.parameters.items())) + assert (set(base_params.items()) - set(meth_sig.parameters.items())) == set() + + +async def test_sharding_coordinate_selection() -> None: + store = MemoryStore() + g = zarr.open_group(store, mode="w") + arr = g.create_array( + name="a", + shape=(2, 3, 4), + chunks=(1, 2, 2), + overwrite=True, + dtype=np.float32, + shards=(2, 4, 4), + ) + arr[:] = np.arange(2 * 3 * 4).reshape((2, 3, 4)) + result = arr[1, [0, 1]] # type: ignore[index] + assert isinstance(result, NDArrayLike) + assert (result == np.array([[12, 13, 14, 15], [16, 17, 18, 19]])).all() + + +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_array_repr(store: Store) -> None: + shape = (2, 3, 4) + dtype = "uint8" + arr = zarr.create_array(store, shape=shape, dtype=dtype) + assert str(arr) == f"" + + +class UnknownObjectCodecDtype(VariableLengthUTF8): + """A data type that requires an object codec with an unknown id, used for error-path tests.""" + + object_codec_id = "unknown" # type: ignore[assignment] + + +@pytest.mark.parametrize( + "dtype", [VariableLengthUTF8(), VariableLengthBytes(), UnknownObjectCodecDtype()] +) +def test_chunk_encoding_no_object_codec_errors(dtype: ZDType[Any, Any]) -> None: + """ + Test that a valuerror is raised when checking the chunk encoding for a v2 array with a + data type that requires an object codec, but where no object codec is specified + """ + if isinstance(dtype, VariableLengthUTF8): + codec_name = "the numcodecs.VLenUTF8 codec" + elif isinstance(dtype, VariableLengthBytes): + codec_name = "the numcodecs.VLenBytes codec" + else: + codec_name = f"an unknown object codec with id {dtype.object_codec_id!r}" # type: ignore[attr-defined] + msg = ( + f"Data type {dtype} requires {codec_name}, " + "but no such codec was specified in the filters or compressor parameters for " + "this array. " + ) + with pytest.raises(ValueError, match=re.escape(msg)): + _parse_chunk_encoding_v2(filters=None, compressor=None, dtype=dtype) + + +def test_unknown_object_codec_default_serializer_v3() -> None: + """ + Test that we get a valueerrror when trying to create the default serializer for a data type + that requires an unknown object codec + """ + dtype = UnknownObjectCodecDtype() + msg = f"Data type {dtype} requires an unknown object codec: {dtype.object_codec_id!r}." + with pytest.raises(ValueError, match=re.escape(msg)): + default_serializer_v3(dtype) + + +def test_unknown_object_codec_default_filters_v2() -> None: + """ + Test that we get a valueerrror when trying to create the default serializer for a data type + that requires an unknown object codec + """ + dtype = UnknownObjectCodecDtype() + msg = f"Data type {dtype} requires an unknown object codec: {dtype.object_codec_id!r}." + with pytest.raises(ValueError, match=re.escape(msg)): + default_filters_v2(dtype) + + +@pytest.mark.parametrize( + ("array_shape", "shard_shape", "chunk_shape"), + [ + ((10,), None, (1,)), + ((10,), (1,), (1,)), + ((30, 10), None, (2, 5)), + ((30, 10), (4, 10), (2, 5)), + ], +) +def test_chunk_grid_shape( + array_shape: tuple[int, ...], + shard_shape: tuple[int, ...] | None, + chunk_shape: tuple[int, ...], + zarr_format: ZarrFormat, +) -> None: + """ + Test that the shape of the chunk grid and the shard grid are correctly indicated + """ + if zarr_format == 2 and shard_shape is not None: + with pytest.raises( + ValueError, + match="Zarr format 2 arrays can only be created with `shard_shape` set to `None`.", + ): + arr = zarr.create_array( + {}, + dtype="uint8", + shape=array_shape, + chunks=chunk_shape, + shards=shard_shape, + zarr_format=zarr_format, + ) + pytest.skip("Zarr format 2 arrays can only be created with `shard_shape` set to `None`.") + else: + arr = zarr.create_array( + {}, + dtype="uint8", + shape=array_shape, + chunks=chunk_shape, + shards=shard_shape, + zarr_format=zarr_format, + ) + + chunk_grid_shape = tuple(starmap(ceildiv, zip(array_shape, chunk_shape, strict=True))) + if shard_shape is None: + _shard_shape = chunk_shape + else: + _shard_shape = shard_shape + shard_grid_shape = tuple(starmap(ceildiv, zip(array_shape, _shard_shape, strict=True))) + assert arr._chunk_grid_shape == chunk_grid_shape + assert arr.cdata_shape == chunk_grid_shape + assert arr.async_array.cdata_shape == chunk_grid_shape + assert arr._shard_grid_shape == shard_grid_shape + assert arr._nshards == np.prod(shard_grid_shape) + + +@pytest.mark.parametrize( + ("array_shape", "shard_shape", "chunk_shape"), [((10,), None, (1,)), ((30, 10), None, (2, 5))] +) +def test_iter_chunk_coords( + array_shape: tuple[int, ...], + shard_shape: tuple[int, ...] | None, + chunk_shape: tuple[int, ...], + zarr_format: ZarrFormat, +) -> None: + """ + Test that we can use the various invocations of iter_chunk_coords to iterate over the coordinates + of the origin of each chunk. + """ + + arr = zarr.create_array( + {}, + dtype="uint8", + shape=array_shape, + chunks=chunk_shape, + shards=shard_shape, + zarr_format=zarr_format, + ) + expected = tuple(_iter_grid(arr._shard_grid_shape)) + observed = tuple(_iter_chunk_coords(arr)) + assert observed == expected + assert observed == tuple(arr._iter_chunk_coords()) + assert observed == tuple(arr.async_array._iter_chunk_coords()) + + +@pytest.mark.parametrize( + ("array_shape", "shard_shape", "chunk_shape"), + [((10,), (1,), (1,)), ((10,), None, (1,)), ((30, 10), (10, 5), (2, 5))], +) +def test_iter_shard_coords( + array_shape: tuple[int, ...], + shard_shape: tuple[int, ...] | None, + chunk_shape: tuple[int, ...], + zarr_format: ZarrFormat, +) -> None: + """ + Test that we can use the various invocations of iter_shard_coords to iterate over the coordinates + of the origin of each shard. + """ + + if zarr_format == 2 and shard_shape is not None: + pytest.skip("Zarr format 2 does not support shard shape.") + + arr = zarr.create_array( + {}, + dtype="uint8", + shape=array_shape, + chunks=chunk_shape, + shards=shard_shape, + zarr_format=zarr_format, + ) + expected = tuple(_iter_grid(arr._shard_grid_shape)) + observed = tuple(_iter_shard_coords(arr)) + assert observed == expected + assert observed == tuple(arr._iter_shard_coords()) + assert observed == tuple(arr.async_array._iter_shard_coords()) + + +@pytest.mark.parametrize( + ("array_shape", "shard_shape", "chunk_shape"), + [((10,), (1,), (1,)), ((10,), None, (1,)), ((30, 10), (10, 5), (2, 5))], +) +def test_iter_shard_keys( + array_shape: tuple[int, ...], + shard_shape: tuple[int, ...] | None, + chunk_shape: tuple[int, ...], + zarr_format: ZarrFormat, +) -> None: + """ + Test that we can use the various invocations of iter_shard_keys to iterate over the stored + keys of the shards of an array. + """ + + if zarr_format == 2 and shard_shape is not None: + pytest.skip("Zarr format 2 does not support shard shape.") + + arr = zarr.create_array( + {}, + dtype="uint8", + shape=array_shape, + chunks=chunk_shape, + shards=shard_shape, + zarr_format=zarr_format, + ) + expected = tuple( + arr.metadata.encode_chunk_key(key) for key in _iter_grid(arr._shard_grid_shape) + ) + observed = tuple(_iter_shard_keys(arr)) + assert observed == expected + assert observed == tuple(arr._iter_shard_keys()) + assert observed == tuple(arr.async_array._iter_shard_keys()) + + +@pytest.mark.parametrize( + ("array_shape", "shard_shape", "chunk_shape"), + [((10,), None, (1,)), ((10,), (1,), (1,)), ((30, 10), (10, 5), (2, 5))], +) +def test_iter_shard_regions( + array_shape: tuple[int, ...], + shard_shape: tuple[int, ...] | None, + chunk_shape: tuple[int, ...], + zarr_format: ZarrFormat, +) -> None: + """ + Test that we can use the various invocations of iter_shard_regions to iterate over the regions + spanned by the shards of an array. + """ + if zarr_format == 2 and shard_shape is not None: + pytest.skip("Zarr format 2 does not support shard shape.") + + arr = zarr.create_array( + {}, + dtype="uint8", + shape=array_shape, + chunks=chunk_shape, + shards=shard_shape, + zarr_format=zarr_format, + ) + if shard_shape is None: + _shard_shape = chunk_shape + else: + _shard_shape = shard_shape + expected = tuple(_iter_regions(arr.shape, _shard_shape)) + observed = tuple(_iter_shard_regions(arr)) + assert observed == expected + assert observed == tuple(arr._iter_shard_regions()) + assert observed == tuple(arr.async_array._iter_shard_regions()) + + +@pytest.mark.parametrize( + ("array_shape", "shard_shape", "chunk_shape"), [((10,), None, (1,)), ((30, 10), None, (2, 5))] +) +def test_iter_chunk_regions( + array_shape: tuple[int, ...], + shard_shape: tuple[int, ...] | None, + chunk_shape: tuple[int, ...], + zarr_format: ZarrFormat, +) -> None: + """ + Test that we can use the various invocations of iter_chunk_regions to iterate over the regions + spanned by the chunks of an array. + """ + arr = zarr.create_array( + {}, + dtype="uint8", + shape=array_shape, + chunks=chunk_shape, + shards=shard_shape, + zarr_format=zarr_format, + ) + + expected = tuple(_iter_regions(arr.shape, chunk_shape)) + observed = tuple(_iter_chunk_regions(arr)) + assert observed == expected + assert observed == tuple(arr._iter_chunk_regions()) + assert observed == tuple(arr.async_array._iter_chunk_regions()) + + +@pytest.mark.parametrize("num_shards", [1, 3]) +@pytest.mark.parametrize("array_type", ["numpy", "zarr"]) +def test_create_array_with_data_num_gets( + num_shards: int, array_type: Literal["numpy", "zarr"] +) -> None: + """ + Test that creating an array with data only invokes a single get request per stored object + """ + store = LoggingStore(store=MemoryStore()) + + chunk_shape = (1,) + shard_shape = (100,) + shape = (shard_shape[0] * num_shards,) + data: AnyArray | npt.NDArray[np.int64] + if array_type == "numpy": + data = np.zeros(shape[0], dtype="int64") + else: + data = zarr.zeros(shape, dtype="int64") + + zarr.create_array(store, data=data, chunks=chunk_shape, shards=shard_shape, fill_value=-1) # type: ignore[arg-type] + # One get for the metadata; full-shard writes should not read shard payloads. + assert store.counter["get"] == 1 + + +@pytest.mark.parametrize( + ("selection", "expected_gets"), + [(slice(None), 0), (slice(1, 9), 1)], +) +def test_shard_write_num_gets(selection: slice, expected_gets: int) -> None: + """ + Test that partial-shard writes read the existing data and full-shard writes don't. + """ + store = LoggingStore(store=MemoryStore()) + arr = zarr.create_array( + store, + shape=(10,), + chunks=(1,), + shards=(10,), + dtype="int64", + fill_value=-1, + ) + arr[:] = 0 + + store.counter.clear() + + arr[selection] = 1 + + assert store.counter["get"] == expected_gets + + +@pytest.mark.parametrize("config", [{}, {"write_empty_chunks": True}, {"order": "C"}]) +def test_with_config(config: ArrayConfigParams) -> None: + """ + Test that `AsyncArray.with_config` and `Array.with_config` create a copy of the source + array with a new runtime configuration. + """ + # the config we start with + source_config: ArrayConfigParams = {"write_empty_chunks": False, "order": "F"} + source_array = zarr.create_array({}, shape=(1,), dtype="uint8", config=source_config) + + new_async_array_config_dict = source_array._async_array.with_config(config).config.to_dict() + new_array_config_dict = source_array.with_config(config).config.to_dict() + + for key in source_config: + if key in config: + assert new_async_array_config_dict[key] == config[key] # type: ignore[literal-required] + assert new_array_config_dict[key] == config[key] # type: ignore[literal-required] + else: + assert new_async_array_config_dict[key] == source_config[key] # type: ignore[literal-required] + assert new_array_config_dict[key] == source_config[key] # type: ignore[literal-required] + + +def test_with_config_polymorphism() -> None: + """ + Test that `AsyncArray.with_config` and `Array.with_config` accept dicts and full array config + objects. + """ + source_config: ArrayConfig = ArrayConfig.from_dict({"write_empty_chunks": False, "order": "F"}) + source_config_dict = source_config.to_dict() + + arr = zarr.create_array({}, shape=(1,), dtype="uint8") + arr_source_config = arr.with_config(source_config) + arr_source_config_dict = arr.with_config(source_config_dict) + + assert arr_source_config.config == arr_source_config_dict.config + + +@pytest.mark.parametrize( + ("chunk_input", "expected"), + [ + (-1, ((10,),)), + ((-1,), ((10,),)), + ((10,), ((10,),)), + ((5,), ((5, 5),)), + ((3,), ((3, 3, 3, 1),)), + ], + ids=["scalar-neg1", "tuple-neg1", "exact", "half", "remainder"], +) +async def test_create_array_chunks_1d( + chunk_input: int | tuple[int, ...], + expected: tuple[tuple[int, ...], ...], +) -> None: + """Test that chunk normalization produces the expected chunk sizes for 1D arrays.""" + arr = await create_array(store={}, shape=(10,), chunks=chunk_input, dtype="uint8") + assert arr.write_chunk_sizes == expected + + +@pytest.mark.parametrize( + ("chunk_input", "expected"), + [ + (-1, ((10,), (12,), (15,))), + ((3, 4, 5), ((3, 3, 3, 1), (4, 4, 4), (5, 5, 5))), + ((-1, 4, -1), ((10,), (4, 4, 4), (15,))), + ((10, 12, 15), ((10,), (12,), (15,))), + ((7, 3, 2), ((7, 3), (3, 3, 3, 3), (2, 2, 2, 2, 2, 2, 2, 1))), + ], + ids=["all-neg1", "mixed", "neg1-middle", "exact", "remainder"], +) +async def test_create_array_chunks_3d( + chunk_input: int | tuple[int, ...], + expected: tuple[tuple[int, ...], ...], +) -> None: + """Test that chunk normalization produces the expected chunk sizes for 3D arrays.""" + shape = (10, 12, 15) + arr = await create_array(store={}, shape=shape, chunks=chunk_input, dtype="float64") + assert arr.write_chunk_sizes == expected diff --git a/tests/test_array_spec.py b/tests/test_array_spec.py new file mode 100644 index 0000000000..4fbc0b1205 --- /dev/null +++ b/tests/test_array_spec.py @@ -0,0 +1,179 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import BufferPrototype, default_buffer_prototype +from zarr.core.buffer.cpu import NDBuffer +from zarr.core.dtype import get_data_type_from_native_dtype + +if TYPE_CHECKING: + from collections.abc import Callable + + from zarr.core.common import MemoryOrder + + +def _make_spec( + *, + shape: tuple[int, ...] = (4, 4), + native_dtype: Any = "int16", + fill_value: Any = 0, + order: MemoryOrder = "C", + write_empty_chunks: bool = False, + prototype: BufferPrototype | None = None, +) -> ArraySpec: + """Creates an ArraySpec with common defaults""" + zdtype = get_data_type_from_native_dtype(np.dtype(native_dtype)) + fill_value = zdtype.cast_scalar(fill_value) # mirrors ArrayV3Metadata's fill_value + return ArraySpec( + shape=shape, + dtype=zdtype, + fill_value=fill_value, + config=ArrayConfig(order=order, write_empty_chunks=write_empty_chunks), + prototype=prototype if prototype is not None else default_buffer_prototype(), + ) + + +class _AltNDBuffer(NDBuffer): + """A distinct NDBuffer subclass""" + + +_ALT_PROTOTYPE = BufferPrototype( + buffer=default_buffer_prototype().buffer, + nd_buffer=_AltNDBuffer, +) # a distinct BufferPrototype with a different nd_buffer subclass + + +# Difficult / important cases: +# issue #3054: np.void is unhashable when writeable +# nan/NaT aren't self-equal yet must compare equal for a ArraySpec +SPECS = [ + pytest.param({"native_dtype": "int16", "fill_value": 7}, id="int16"), + pytest.param({"native_dtype": "float64", "fill_value": 1.5}, id="float64"), + pytest.param({"native_dtype": "float64", "fill_value": float("nan")}, id="float64-nan"), + pytest.param({"native_dtype": "float64", "fill_value": -0.0}, id="float64-negzero"), + pytest.param({"native_dtype": "complex128", "fill_value": 1 + 2j}, id="complex128"), + pytest.param( + {"native_dtype": "complex128", "fill_value": complex(-0.0, -0.0)}, + id="complex128-negzero", + ), + pytest.param({"native_dtype": "bool", "fill_value": True}, id="bool"), + pytest.param( + {"native_dtype": "datetime64[s]", "fill_value": np.datetime64("2020-01-01")}, + id="datetime64", + ), + pytest.param( + {"native_dtype": "datetime64[s]", "fill_value": np.datetime64("NaT", "s")}, + id="datetime64-NaT", + ), + pytest.param( + {"native_dtype": [("a", "f8"), ("b", "i8")], "fill_value": (1.0, 2)}, + id="structured-void", + ), + pytest.param({"native_dtype": "U5", "fill_value": "hello"}, id="fixed-string"), + pytest.param({"shape": ()}, id="scalar-shape"), + pytest.param({"shape": (0,)}, id="zero-size"), + pytest.param({"order": "F"}, id="order-F"), +] + + +# Mutations: each mutate kwargs to an unequal version +def _grow_shape(kw: dict[str, Any]) -> dict[str, Any]: + return {"shape": (*kw.get("shape", (4, 4)), 1)} + + +def _flip_order(kw: dict[str, Any]) -> dict[str, Any]: + return {"order": "F" if kw.get("order", "C") == "C" else "C"} + + +def _swap_prototype(_kw: dict[str, Any]) -> dict[str, Any]: + return {"prototype": _ALT_PROTOTYPE} + + +MUTATIONS = [ + pytest.param(_grow_shape, id="shape"), + pytest.param(_flip_order, id="order"), + pytest.param(_swap_prototype, id="prototype"), +] + + +@pytest.mark.parametrize("kwargs", SPECS) +def test_hashable(kwargs: dict[str, Any]) -> None: + """Every ArraySpec is hashable, including structured (np.void) fill values.""" + assert isinstance(hash(_make_spec(**kwargs)), int) + + +@pytest.mark.parametrize("kwargs", SPECS) +def test_equal_specs_hash_equal(kwargs: dict[str, Any]) -> None: + """Independently built specs with identical fields are equal and hash equal.""" + a = _make_spec(**kwargs) + b = _make_spec(**kwargs) + assert a == b + assert hash(a) == hash(b) + + +@pytest.mark.parametrize("kwargs", SPECS) +@pytest.mark.parametrize("mutate", MUTATIONS) +def test_distinct_specs_unequal( + mutate: Callable[[dict[str, Any]], dict[str, Any]], + kwargs: dict[str, Any], +) -> None: + """Changing one dtype-independent field makes a spec unequal to its base.""" + base = _make_spec(**kwargs) + variant = _make_spec(**{**kwargs, **mutate(kwargs)}) + assert base != variant + + +@pytest.mark.parametrize( + ("base", "variant"), + [ + pytest.param({"fill_value": 0}, {"fill_value": 1}, id="fill_value"), + pytest.param({"native_dtype": "int16"}, {"native_dtype": "int32"}, id="dtype"), + pytest.param( + {"native_dtype": "float32", "fill_value": 1.0}, + {"native_dtype": "float64", "fill_value": 1.0}, + id="dtype-float-promote", + ), + ], +) +def test_dtype_and_fill_value_matter(base: dict[str, Any], variant: dict[str, Any]) -> None: + """dtype and fill_value participate in equality; they can't join the cross + product because fill_value is coupled to dtype.""" + assert _make_spec(**base) != _make_spec(**variant) + + +@pytest.mark.parametrize( + ("native_dtype", "neg_fill", "pos_fill"), + [ + pytest.param("float16", -0.0, 0.0, id="float16"), + pytest.param("float32", -0.0, 0.0, id="float32"), + pytest.param("float64", -0.0, 0.0, id="float64"), + pytest.param("complex128", complex(-0.0, -0.0), 0j, id="complex128-both"), + pytest.param("complex128", complex(0.0, -0.0), 0j, id="complex128-imag"), + pytest.param("complex128", complex(-0.0, 0.0), 0j, id="complex128-real"), + pytest.param([("a", "f8")], (-0.0,), (0.0,), id="structured"), + ], +) +def test_signed_zero_fills_are_distinct(native_dtype: Any, neg_fill: Any, pos_fill: Any) -> None: + """A -0.0 fill writes different bytes than +0.0, so the specs are not equal.""" + neg = _make_spec(native_dtype=native_dtype, fill_value=neg_fill) + pos = _make_spec(native_dtype=native_dtype, fill_value=pos_fill) + assert neg != pos + + +@pytest.mark.parametrize( + ("obj"), + [ + pytest.param(None, id="None"), + pytest.param(42, id="int"), + pytest.param("hello", id="str"), + pytest.param([1, 2, 3], id="list"), + pytest.param({"a": 1}, id="dict"), + ], +) +def test_unequal_with_invalid_type(obj: Any) -> None: + assert (_make_spec() == obj) is False + assert _make_spec() != obj diff --git a/tests/test_attributes.py b/tests/test_attributes.py new file mode 100644 index 0000000000..269704d2a0 --- /dev/null +++ b/tests/test_attributes.py @@ -0,0 +1,95 @@ +import json +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +import zarr.core +import zarr.core.attributes +import zarr.storage +from tests.conftest import deep_nan_equal +from zarr.core.common import ZarrFormat + +if TYPE_CHECKING: + from zarr.types import AnyArray + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +@pytest.mark.parametrize( + "data", [{"inf": np.inf, "-inf": -np.inf, "nan": np.nan}, {"a": 3, "c": 4}] +) +def test_put(data: dict[str, Any], zarr_format: ZarrFormat) -> None: + store = zarr.storage.MemoryStore() + attrs = zarr.core.attributes.Attributes(zarr.Group.from_store(store, zarr_format=zarr_format)) + attrs.put(data) + expected = json.loads(json.dumps(data, allow_nan=True)) + assert deep_nan_equal(dict(attrs), expected) + + +def test_asdict() -> None: + store = zarr.storage.MemoryStore() + attrs = zarr.core.attributes.Attributes( + zarr.Group.from_store(store, attributes={"a": 1, "b": 2}) + ) + result = attrs.asdict() + assert result == {"a": 1, "b": 2} + + +def test_update_attributes_preserves_existing() -> None: + """ + Test that `update_attributes` only updates the specified attributes + and preserves existing ones. + """ + store = zarr.storage.MemoryStore() + z = zarr.create(10, store=store, overwrite=True) + z.attrs["a"] = [] + z.attrs["b"] = 3 + assert dict(z.attrs) == {"a": [], "b": 3} + + z.update_attributes({"a": [3, 4], "c": 4}) + assert dict(z.attrs) == {"a": [3, 4], "b": 3, "c": 4} + + +def test_update_empty_attributes() -> None: + """ + Ensure updating when initial attributes are empty works. + """ + store = zarr.storage.MemoryStore() + z = zarr.create(10, store=store, overwrite=True) + assert dict(z.attrs) == {} + z.update_attributes({"a": [3, 4], "c": 4}) + assert dict(z.attrs) == {"a": [3, 4], "c": 4} + + +def test_update_no_changes() -> None: + """ + Ensure updating when no new or modified attributes does not alter existing ones. + """ + store = zarr.storage.MemoryStore() + z = zarr.create(10, store=store, overwrite=True) + z.attrs["a"] = [] + z.attrs["b"] = 3 + + z.update_attributes({}) + assert dict(z.attrs) == {"a": [], "b": 3} + + +@pytest.mark.parametrize("group", [True, False]) +def test_del_works(group: bool) -> None: + store = zarr.storage.MemoryStore() + z: zarr.Group | AnyArray + if group: + z = zarr.create_group(store) + else: + z = zarr.create_array(store=store, shape=10, dtype=int) + assert dict(z.attrs) == {} + z.update_attributes({"a": [3, 4], "c": 4}) + del z.attrs["a"] + assert dict(z.attrs) == {"c": 4} + + z2: zarr.Group | AnyArray + if group: + z2 = zarr.open_group(store) + else: + z2 = zarr.open_array(store) + assert dict(z2.attrs) == {"c": 4} diff --git a/tests/test_buffer.py b/tests/test_buffer.py new file mode 100644 index 0000000000..b4a16ed1de --- /dev/null +++ b/tests/test_buffer.py @@ -0,0 +1,240 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Literal + +import numpy as np +import pytest + +import zarr +from zarr.abc.buffer import ArrayLike, BufferPrototype, NDArrayLike +from zarr.buffer import cpu, gpu +from zarr.codecs.blosc import BloscCodec +from zarr.codecs.crc32c_ import Crc32cCodec +from zarr.codecs.gzip import GzipCodec +from zarr.codecs.transpose import TransposeCodec +from zarr.codecs.zstd import ZstdCodec +from zarr.errors import ZarrUserWarning +from zarr.storage import MemoryStore, StorePath +from zarr.testing.buffer import ( + NDBufferUsingTestNDArrayLike, + StoreExpectingTestBuffer, + TestBuffer, + TestNDArrayLike, +) +from zarr.testing.utils import gpu_mark, gpu_test, skip_if_no_gpu + +if TYPE_CHECKING: + import types + +try: + import cupy as cp +except ImportError: + cp = None + + +import zarr.api.asynchronous + +if TYPE_CHECKING: + import types + + +def test_nd_array_like(xp: types.ModuleType) -> None: + ary = xp.arange(10) + assert isinstance(ary, ArrayLike) + assert isinstance(ary, NDArrayLike) + + +async def test_async_array_prototype() -> None: + """Test the use of a custom buffer prototype""" + + expect = np.zeros((9, 9), dtype="uint16", order="F") + a = await zarr.api.asynchronous.create_array( + StorePath(StoreExpectingTestBuffer()) / "test_async_array_prototype", + shape=expect.shape, + chunks=(5, 5), + dtype=expect.dtype, + fill_value=0, + ) + expect[1:4, 3:6] = np.ones((3, 3)) + + my_prototype = BufferPrototype(buffer=TestBuffer, nd_buffer=NDBufferUsingTestNDArrayLike) + + await a.setitem( + selection=(slice(1, 4), slice(3, 6)), + value=np.ones((3, 3)), + prototype=my_prototype, + ) + got = await a.getitem(selection=(slice(0, 9), slice(0, 9)), prototype=my_prototype) + # ignoring a mypy error here that TestNDArrayLike doesn't meet the NDArrayLike protocol + # The test passes, so it clearly does. + assert isinstance(got, TestNDArrayLike) + assert np.array_equal(expect, got) # type: ignore[unreachable] + + +@gpu_test +async def test_async_array_gpu_prototype() -> None: + """Test the use of the GPU buffer prototype""" + + expect = cp.zeros((9, 9), dtype="uint16", order="F") + a = await zarr.api.asynchronous.create_array( + StorePath(MemoryStore()) / "test_async_array_gpu_prototype", + shape=expect.shape, + chunks=(5, 5), + dtype=expect.dtype, + fill_value=0, + ) + expect[1:4, 3:6] = cp.ones((3, 3)) + + await a.setitem( + selection=(slice(1, 4), slice(3, 6)), + value=cp.ones((3, 3)), + prototype=gpu.buffer_prototype, + ) + got = await a.getitem(selection=(slice(0, 9), slice(0, 9)), prototype=gpu.buffer_prototype) + assert isinstance(got, cp.ndarray) + assert cp.array_equal(expect, got) + + +async def test_codecs_use_of_prototype() -> None: + expect = np.zeros((10, 10), dtype="uint16", order="F") + a = await zarr.api.asynchronous.create_array( + StorePath(StoreExpectingTestBuffer()) / "test_codecs_use_of_prototype", + shape=expect.shape, + chunks=(5, 5), + dtype=expect.dtype, + fill_value=0, + compressors=[BloscCodec(), Crc32cCodec(), GzipCodec(), ZstdCodec()], + filters=[TransposeCodec(order=(1, 0))], + ) + expect[:] = np.arange(100).reshape(10, 10) + + my_prototype = BufferPrototype(buffer=TestBuffer, nd_buffer=NDBufferUsingTestNDArrayLike) + + await a.setitem( + selection=(slice(0, 10), slice(0, 10)), + value=expect[:], + prototype=my_prototype, + ) + got = await a.getitem(selection=(slice(0, 10), slice(0, 10)), prototype=my_prototype) + # ignoring a mypy error here that TestNDArrayLike doesn't meet the NDArrayLike protocol + # The test passes, so it clearly does. + assert isinstance(got, TestNDArrayLike) + assert np.array_equal(expect, got) # type: ignore[unreachable] + + +@gpu_test +async def test_codecs_use_of_gpu_prototype() -> None: + expect = cp.zeros((10, 10), dtype="uint16", order="F") + a = await zarr.api.asynchronous.create_array( + StorePath(MemoryStore()) / "test_codecs_use_of_gpu_prototype", + shape=expect.shape, + chunks=(5, 5), + dtype=expect.dtype, + fill_value=0, + compressors=[BloscCodec(), Crc32cCodec(), GzipCodec(), ZstdCodec()], + filters=[TransposeCodec(order=(1, 0))], + ) + expect[:] = cp.arange(100).reshape(10, 10) + msg = "Creating a zarr.buffer.gpu.Buffer with an array that does not support the __cuda_array_interface__ for zero-copy transfers, falling back to slow copy based path" + with pytest.warns(ZarrUserWarning, match=msg): + await a.setitem( + selection=(slice(0, 10), slice(0, 10)), + value=expect[:], + prototype=gpu.buffer_prototype, + ) + with pytest.warns(ZarrUserWarning, match=msg): + got = await a.getitem( + selection=(slice(0, 10), slice(0, 10)), prototype=gpu.buffer_prototype + ) + assert isinstance(got, cp.ndarray) + assert cp.array_equal(expect, got) + + +@gpu_test +async def test_sharding_use_of_gpu_prototype() -> None: + with zarr.config.enable_gpu(): + expect = cp.zeros((10, 10), dtype="uint16", order="F") + + a = await zarr.api.asynchronous.create_array( + StorePath(MemoryStore()) / "test_codecs_use_of_gpu_prototype", + shape=expect.shape, + chunks=(5, 5), + shards=(10, 10), + dtype=expect.dtype, + fill_value=0, + ) + expect[:] = cp.arange(100).reshape(10, 10) + msg = "Creating a zarr.buffer.gpu.Buffer with an array that does not support the __cuda_array_interface__ for zero-copy transfers, falling back to slow copy based path" + with pytest.warns(ZarrUserWarning, match=msg): + await a.setitem( + selection=(slice(0, 10), slice(0, 10)), + value=expect[:], + prototype=gpu.buffer_prototype, + ) + with pytest.warns(ZarrUserWarning, match=msg): + got = await a.getitem( + selection=(slice(0, 10), slice(0, 10)), prototype=gpu.buffer_prototype + ) + assert isinstance(got, cp.ndarray) + assert cp.array_equal(expect, got) + + +def test_numpy_buffer_prototype() -> None: + buffer = cpu.buffer_prototype.buffer.create_zero_length() + ndbuffer = cpu.buffer_prototype.nd_buffer.create(shape=(1, 2), dtype=np.dtype("int64")) + assert isinstance(buffer.as_array_like(), np.ndarray) + assert isinstance(ndbuffer.as_ndarray_like(), np.ndarray) + with pytest.raises(ValueError, match="Buffer does not contain a single scalar value"): + ndbuffer.as_scalar() + + +@gpu_test +def test_gpu_buffer_prototype() -> None: + buffer = gpu.buffer_prototype.buffer.create_zero_length() + ndbuffer = gpu.buffer_prototype.nd_buffer.create(shape=(1, 2), dtype=cp.dtype("int64")) + assert isinstance(buffer.as_array_like(), cp.ndarray) + assert isinstance(ndbuffer.as_ndarray_like(), cp.ndarray) + with pytest.raises(ValueError, match="Buffer does not contain a single scalar value"): + ndbuffer.as_scalar() + + +# TODO: the same test for other buffer classes +def test_cpu_buffer_as_scalar() -> None: + buf = cpu.buffer_prototype.nd_buffer.create(shape=(), dtype="int64") + assert buf.as_scalar() == buf.as_ndarray_like()[()] # type: ignore[index] + + +@pytest.mark.parametrize( + "prototype", + [ + cpu.buffer_prototype, + pytest.param( + gpu.buffer_prototype, + marks=[gpu_mark, skip_if_no_gpu], + ), + BufferPrototype( + buffer=cpu.Buffer, + nd_buffer=NDBufferUsingTestNDArrayLike, + ), + ], +) +@pytest.mark.parametrize( + "shape", + [ + (1, 2), + (1, 2, 3), + ], +) +@pytest.mark.parametrize("dtype", ["int32", "float64"]) +@pytest.mark.parametrize("order", ["C", "F"]) +def test_empty( + prototype: BufferPrototype, shape: tuple[int, ...], dtype: str, order: Literal["C", "F"] +) -> None: + buf = prototype.nd_buffer.empty(shape=shape, dtype=dtype, order=order) + result = buf.as_ndarray_like() + assert result.shape == shape + assert result.dtype == dtype + if order == "C": + assert result.flags.c_contiguous # type: ignore[attr-defined] + else: + assert result.flags.f_contiguous # type: ignore[attr-defined] diff --git a/tests/test_chunk_grids.py b/tests/test_chunk_grids.py new file mode 100644 index 0000000000..4640c43d1c --- /dev/null +++ b/tests/test_chunk_grids.py @@ -0,0 +1,279 @@ +from typing import Any + +import numpy as np +import pytest + +from tests.conftest import Expect, ExpectFail +from zarr.core.chunk_grids import ( + ChunkLayout, + _guess_regular_chunks, + normalize_chunks_1d, + normalize_chunks_nd, + resolve_outer_and_inner_chunks, +) + + +def _assert_chunks_equal( + actual: tuple[Any, ...], + expected: tuple[tuple[int, ...], ...], +) -> None: + """Compare a ChunksTuple (tuple of np.int64 arrays) against a tuple of int tuples.""" + assert len(actual) == len(expected), f"axis count mismatch: {len(actual)} vs {len(expected)}" + for axis, (a, e) in enumerate(zip(actual, expected, strict=True)): + assert np.array_equal(a, np.asarray(e, dtype=np.int64)), ( + f"axis {axis}: {list(a)} != {list(e)}" + ) + + +@pytest.mark.parametrize( + "shape", [(0,), (0,) * 2, (1, 2, 0, 4, 5), (10, 0), (10,), (100,) * 3, (1000000,), (10000,) * 2] +) +@pytest.mark.parametrize("itemsize", [1, 2, 4]) +def test_guess_chunks(shape: tuple[int, ...], itemsize: int) -> None: + chunks = _guess_regular_chunks(shape, itemsize) + chunk_size = np.prod(chunks) * itemsize + assert isinstance(chunks, tuple) + assert len(chunks) == len(shape) + assert chunk_size < (64 * 1024 * 1024) + # doesn't make any sense to allow chunks to have zero length dimension + assert all(0 < c <= max(s, 1) for c, s in zip(chunks, shape, strict=False)) + + +@pytest.mark.parametrize( + ("chunks", "shape", "expected"), + [ + # 1D cases + ((10,), (100,), ((10,) * 10,)), + ([10], (100,), ((10,) * 10,)), + (10, (100,), ((10,) * 10,)), + # 2D cases + ((10, 10), (100, 10), ((10,) * 10, (10,))), + (10, (100, 10), ((10,) * 10, (10,))), + ((10, -1), (100, 10), ((10,) * 10, (10,))), + # 3D cases + (30, (100, 20, 10), ((30, 30, 30, 30), (30,), (30,))), + ((30, -1, -1), (100, 20, 10), ((30, 30, 30, 30), (20,), (10,))), + ((30, 20, -1), (100, 20, 10), ((30, 30, 30, 30), (20,), (10,))), + ((30, 20, 10), (100, 20, 10), ((30, 30, 30, 30), (20,), (10,))), + # dask-style chunks (explicit per-chunk sizes) + (((100, 100, 100), (50, 50)), (300, 100), ((100, 100, 100), (50, 50))), + (((100, 100, 50),), (250,), ((100, 100, 50),)), + (((100,),), (100,), ((100,),)), + # no chunking (False means each dimension is one chunk spanning the full extent) + (False, (100,), ((100,),)), + (False, (100, 50), ((100,), (50,))), + # sentinel values + (-1, (100,), ((100,),)), + # zero-length dimensions preserve the declared chunk size + (10, (0,), ((10,),)), + ((5, 10), (0, 100), ((5,), (10,) * 10)), + ((5, 10), (20, 0), ((5, 5, 5, 5), (10,))), + # numpy integers are accepted anywhere a python int is, whether as the scalar + # convenience form, as per-dimension entries, or as the `-1` sentinel. + (np.int64(10), (100,), ((10,) * 10,)), + ((np.int64(2), np.int64(2)), (4, 4), ((2, 2), (2, 2))), + ((1, 3, np.int64(16), np.int64(16)), (1, 3, 32, 32), ((1,), (3,), (16, 16), (16, 16))), + ((np.int32(30), np.int64(-1)), (100, 20), ((30, 30, 30, 30), (20,))), + (np.array([10, 10]), (100, 100), ((10,) * 10, (10,) * 10)), + # rectilinear chunks given as numpy arrays + ((np.array([60, 40]), np.array([50, 50])), (100, 100), ((60, 40), (50, 50))), + ], +) +def test_normalize_chunks( + chunks: Any, shape: tuple[int, ...], expected: tuple[tuple[int, ...], ...] +) -> None: + _assert_chunks_equal(normalize_chunks_nd(chunks, shape), expected) + + +@pytest.mark.parametrize( + ("array_shape", "chunks_input", "shard_shape", "expected_outer", "expected_inner_outer"), + [ + # no sharding: outer = chunks, inner = None + ((100,), (10,), None, ((10,) * 10,), None), + # explicit regular shards + ((100,), (10,), (50,), ((50, 50),), ((10,) * 10,)), + # rectilinear shards + ((100,), (10,), ((60, 40),), ((60, 40),), ((10,) * 10,)), + # dict-style shards + ((100, 100), (10, 10), {"shape": (50, 50)}, ((50, 50), (50, 50)), ((10,) * 10, (10,) * 10)), + ], +) +def test_resolve_outer_and_inner_chunks( + array_shape: tuple[int, ...], + chunks_input: tuple[int, ...], + shard_shape: Any, + expected_outer: tuple[tuple[int, ...], ...], + expected_inner_outer: tuple[tuple[int, ...], ...] | None, +) -> None: + chunks = normalize_chunks_nd(chunks_input, array_shape) + outer_chunks, inner = resolve_outer_and_inner_chunks( + array_shape=array_shape, chunks=chunks, shard_shape=shard_shape, item_size=1 + ) + _assert_chunks_equal(outer_chunks, expected_outer) + if expected_inner_outer is None: + assert inner is None + else: + assert inner is not None + _assert_chunks_equal(inner.outer_chunks, expected_inner_outer) + assert inner.inner is None + + +def test_chunk_layout_nested() -> None: + """Test that ChunkLayout supports recursive nesting for nested sharding.""" + leaf = normalize_chunks_nd((5, 5), (100, 100)) + mid = ChunkLayout( + outer_chunks=normalize_chunks_nd((25, 25), (100, 100)), + inner=ChunkLayout(outer_chunks=leaf), + ) + top = ChunkLayout(outer_chunks=normalize_chunks_nd((50, 50), (100, 100)), inner=mid) + + # Three levels: top -> mid -> leaf + _assert_chunks_equal(top.outer_chunks, ((50, 50), (50, 50))) + assert top.inner is not None + _assert_chunks_equal(top.inner.outer_chunks, ((25,) * 4, (25,) * 4)) + assert top.inner.inner is not None + _assert_chunks_equal(top.inner.inner.outer_chunks, ((5,) * 20, (5,) * 20)) + assert top.inner.inner.inner is None + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input=(0, 100), + exception=ValueError, + id="zero-uniform", + msg="Chunk size must be positive", + ), + ExpectFail( + input=(-2, 100), + exception=ValueError, + id="negative-uniform", + msg="Chunk size must be positive", + ), + ExpectFail( + input=(np.int64(0), 100), + exception=ValueError, + id="zero-uniform-numpy", + msg="Chunk size must be positive", + ), + ExpectFail(input=([], 100), exception=ValueError, id="empty-list", msg="must not be empty"), + # Scalars that are neither integers nor iterable name themselves in the error, + # rather than surfacing an opaque "object is not iterable" from `list(chunks)`. + ExpectFail( + input=(2.5, 100), + exception=TypeError, + id="non-iterable-scalar", + msg="must be an integer or an iterable of integers; got 2.5 of type float", + escape=True, + ), + ExpectFail( + input=([10, -1, 10], 100), + exception=ValueError, + id="negative-element", + msg="must be positive", + ), + ExpectFail( + input=([10, 0, 10], 20), exception=ValueError, id="zero-element", msg="must be positive" + ), + ExpectFail( + input=([10, 20], 100), exception=ValueError, id="wrong-sum", msg="do not sum to span" + ), + # Nested/RLE form for a single dim is rejected with offending indices. + ExpectFail( + input=([[3, 3], 1], 7), + exception=TypeError, + id="rle-single-dim", + msg="non-integer element(s) ([3, 3],) at indices (0,)", + escape=True, + ), + # Multiple non-int elements: all offending indices reported. + ExpectFail( + input=([1, [2, 2], 1, [3]], 9), + exception=TypeError, + id="multiple-non-ints", + msg="non-integer element(s) ([2, 2], [3]) at indices (1, 3)", + escape=True, + ), + # Strings are non-integers and should be reported the same way. + ExpectFail( + input=([2, "3", 5], 10), + exception=TypeError, + id="string-element", + msg="non-integer element(s) ('3',) at indices (1,)", + escape=True, + ), + ], + ids=lambda c: c.id, +) +def test_normalize_chunks_1d_errors(case: ExpectFail[tuple[Any, int]]) -> None: + """Invalid 1D chunk specifications are rejected with informative error messages.""" + chunks, span = case.input + with case.raises(): + normalize_chunks_1d(chunks, span=span) + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input=(None, (100,)), + exception=ValueError, + id="none", + msg="None is not a valid chunk input", + ), + # `True` is rejected explicitly because bool is a subclass of int β€” without + # this guard, `chunks=True` would silently produce size-1 chunks. + ExpectFail( + input=(True, (100,)), + exception=ValueError, + id="true", + msg="True is not a valid chunk input", + ), + ExpectFail(input=("foo", (100,)), exception=ValueError, id="string", msg="dimensions"), + ExpectFail( + input=((100, 10), (100,)), exception=ValueError, id="too-many-dims", msg="dimensions" + ), + ExpectFail( + input=((10,), (100, 100)), exception=ValueError, id="too-few-dims", msg="dimensions" + ), + # End-to-end: per-dim RLE surfaces through normalize_chunks_nd. + ExpectFail( + input=([[6, 4], [[3, 3], 1]], (10, 10)), + exception=TypeError, + id="rle-inner-dim", + msg="non-integer element(s) ([3, 3],) at indices (0,)", + escape=True, + ), + ], + ids=lambda c: c.id, +) +def test_normalize_chunks_nd_errors(case: ExpectFail[tuple[Any, tuple[int, ...]]]) -> None: + """Invalid N-D chunk specifications are rejected with informative error messages.""" + chunks, shape = case.input + with case.raises(): + normalize_chunks_nd(chunks, shape) + + +@pytest.mark.parametrize( + "case", + [ + # uniform-chunks branch: one int β†’ broadcast across span via np.full. + Expect(input=(1000, 100_000), output=[1000] * 100, id="uniform"), + # explicit-per-chunk branch. + Expect(input=([10, 20, 30, 40], 100), output=[10, 20, 30, 40], id="explicit-list"), + # -1 sentinel branch: one chunk covering the full span. + Expect(input=(-1, 100), output=[100], id="full-span-sentinel"), + ], + ids=lambda c: c.id, +) +def test_normalize_chunks_1d_returns_int64_array( + case: Expect[tuple[Any, int], list[int]], +) -> None: + """Every branch of normalize_chunks_1d must produce a 1D int64 array.""" + chunks, span = case.input + result = normalize_chunks_1d(chunks, span) + assert isinstance(result, np.ndarray) + assert result.dtype == np.int64 + assert result.ndim == 1 + assert result.tolist() == case.output diff --git a/tests/test_chunk_key_encodings.py b/tests/test_chunk_key_encodings.py new file mode 100644 index 0000000000..dcc93b9249 --- /dev/null +++ b/tests/test_chunk_key_encodings.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import pytest + +from zarr.core.chunk_key_encodings import DefaultChunkKeyEncoding, V2ChunkKeyEncoding + + +@pytest.mark.parametrize("separator", ["/", "."]) +@pytest.mark.parametrize( + "coords", + [(), (0,), (1, 2), (10, 0, 3)], +) +def test_default_encoding_round_trips(separator: str, coords: tuple[int, ...]) -> None: + """Encoding coordinates and decoding the result returns the coordinates.""" + encoding = DefaultChunkKeyEncoding(separator=separator) # type: ignore[arg-type] + + key = encoding.encode_chunk_key(coords) + assert encoding.decode_chunk_key(key) == coords + + +@pytest.mark.parametrize("separator", ["/", "."]) +@pytest.mark.parametrize("coords", [(0,), (1, 2), (10, 0, 3)]) +def test_v2_encoding_round_trips(separator: str, coords: tuple[int, ...]) -> None: + """The v2 encoding round-trips coordinates for either separator.""" + encoding = V2ChunkKeyEncoding(separator=separator) # type: ignore[arg-type] + + key = encoding.encode_chunk_key(coords) + assert encoding.decode_chunk_key(key) == coords + + +@pytest.mark.parametrize("separator", ["/", "."]) +def test_v2_zero_dimensional_key_is_ambiguous(separator: str) -> None: + """A 0-d v2 array stores its sole chunk under `"0"`, the same key a 1-d + array uses for chunk 0, so decoding cannot recover the empty tuple on its + own -- the array's dimensionality is what disambiguates it.""" + encoding = V2ChunkKeyEncoding(separator=separator) # type: ignore[arg-type] + + assert encoding.encode_chunk_key(()) == "0" + assert encoding.decode_chunk_key("0") == (0,) + + +@pytest.mark.parametrize( + "chunk_key", + [ + "0/1", # no "c" prefix at all + "c0/1", # "c" not followed by the separator + "x/0/1", # wrong prefix character + "", + ], +) +def test_default_encoding_rejects_key_without_prefix(chunk_key: str) -> None: + """A key that does not carry the `c` prefix is not a chunk key + for this encoding, and must be rejected rather than silently decoded.""" + encoding = DefaultChunkKeyEncoding(separator="/") + + with pytest.raises(ValueError, match="Invalid chunk key"): + encoding.decode_chunk_key(chunk_key) + + +def test_default_encoding_rejects_key_using_the_other_separator() -> None: + """A key encoded with `.` is not valid for a `/`-separated encoding.""" + encoding = DefaultChunkKeyEncoding(separator="/") + + with pytest.raises(ValueError, match="Invalid chunk key"): + encoding.decode_chunk_key("c.0.1") diff --git a/tests/test_chunk_transform.py b/tests/test_chunk_transform.py new file mode 100644 index 0000000000..d2a2b39c41 --- /dev/null +++ b/tests/test_chunk_transform.py @@ -0,0 +1,154 @@ +"""Unit tests for ChunkTransform -- the per-chunk synchronous codec chain. + +ChunkTransform is the data structure FusedCodecPipeline uses to encode/decode a +single chunk through a sequence of codecs synchronously. These tests exercise it +directly (no pipeline, no store): construction and its rejection of codecs that +lack a synchronous implementation, encode/decode roundtrips across codec chains, +compute_encoded_size, and None short-circuiting when an array->array codec +returns None. End-to-end pipeline behavior lives in the pipeline test modules. +""" + +from __future__ import annotations + +from typing import Any + +import numpy as np +import pytest + +from zarr.abc.codec import ArrayBytesCodec, Codec +from zarr.codecs.bytes import BytesCodec +from zarr.codecs.crc32c_ import Crc32cCodec +from zarr.codecs.gzip import GzipCodec +from zarr.codecs.transpose import TransposeCodec +from zarr.codecs.zstd import ZstdCodec +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import Buffer, NDBuffer, default_buffer_prototype +from zarr.core.chunk_utils import ChunkTransform +from zarr.core.dtype import get_data_type_from_native_dtype + + +class AsyncOnlyCodec(ArrayBytesCodec): + """A codec that only supports async, for testing rejection of non-sync codecs.""" + + is_fixed_size = True + + async def _decode_single(self, chunk_data: Buffer, chunk_spec: ArraySpec) -> NDBuffer: + raise NotImplementedError # pragma: no cover + + async def _encode_single(self, chunk_data: NDBuffer, chunk_spec: ArraySpec) -> Buffer | None: + raise NotImplementedError # pragma: no cover + + def compute_encoded_size(self, input_byte_length: int, chunk_spec: ArraySpec) -> int: + return input_byte_length # pragma: no cover + + +def _make_array_spec(shape: tuple[int, ...], dtype: np.dtype[np.generic]) -> ArraySpec: + zdtype = get_data_type_from_native_dtype(dtype) + return ArraySpec( + shape=shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + + +def _make_nd_buffer(arr: np.ndarray[Any, np.dtype[Any]]) -> NDBuffer: + return default_buffer_prototype().nd_buffer.from_numpy_array(arr) + + +@pytest.mark.parametrize( + ("shape", "codecs"), + [ + ((100,), (BytesCodec(),)), + ((100,), (BytesCodec(), GzipCodec())), + ((3, 4), (TransposeCodec(order=(1, 0)), BytesCodec(), ZstdCodec())), + ], + ids=["bytes-only", "with-compression", "full-chain"], +) +def test_construction(shape: tuple[int, ...], codecs: tuple[Codec, ...]) -> None: + """Construction succeeds when all codecs implement SupportsSyncCodec.""" + _ = _make_array_spec(shape, np.dtype("float64")) + ChunkTransform(codecs=codecs) + + +@pytest.mark.parametrize( + ("shape", "codecs"), + [ + ((100,), (AsyncOnlyCodec(),)), + ((3, 4), (TransposeCodec(order=(1, 0)), AsyncOnlyCodec())), + ], + ids=["async-only", "mixed-sync-and-async"], +) +def test_construction_rejects_non_sync(shape: tuple[int, ...], codecs: tuple[Codec, ...]) -> None: + """Construction raises TypeError when any codec lacks SupportsSyncCodec.""" + _ = _make_array_spec(shape, np.dtype("float64")) + with pytest.raises(TypeError, match="AsyncOnlyCodec"): + ChunkTransform(codecs=codecs) + + +@pytest.mark.parametrize( + ("arr", "codecs"), + [ + (np.arange(100, dtype="float64"), (BytesCodec(),)), + (np.arange(100, dtype="float64"), (BytesCodec(), GzipCodec(level=1))), + ( + np.arange(12, dtype="float64").reshape(3, 4), + (TransposeCodec(order=(1, 0)), BytesCodec(), ZstdCodec(level=1)), + ), + (np.arange(100, dtype="float64"), (BytesCodec(), Crc32cCodec())), + (np.arange(50, dtype="int32"), (BytesCodec(), ZstdCodec(level=1))), + ], + ids=["bytes-only", "gzip", "transpose+zstd", "crc32c", "int32"], +) +def test_encode_decode_roundtrip( + arr: np.ndarray[Any, np.dtype[Any]], codecs: tuple[Codec, ...] +) -> None: + """Data survives a full encode/decode cycle.""" + spec = _make_array_spec(arr.shape, arr.dtype) + chain = ChunkTransform(codecs=codecs) + nd_buf = _make_nd_buffer(arr) + + encoded = chain.encode_chunk(nd_buf, spec) + assert encoded is not None + decoded = chain.decode_chunk(encoded, spec) + np.testing.assert_array_equal(arr, decoded.as_numpy_array()) + + +@pytest.mark.parametrize( + ("shape", "codecs", "input_size", "expected_size"), + [ + ((100,), (BytesCodec(),), 800, 800), + ((100,), (BytesCodec(), Crc32cCodec()), 800, 804), + ((3, 4), (TransposeCodec(order=(1, 0)), BytesCodec()), 96, 96), + ], + ids=["bytes-only", "crc32c", "transpose"], +) +def test_compute_encoded_size( + shape: tuple[int, ...], + codecs: tuple[Codec, ...], + input_size: int, + expected_size: int, +) -> None: + """compute_encoded_size returns the correct byte length.""" + spec = _make_array_spec(shape, np.dtype("float64")) + chain = ChunkTransform(codecs=codecs) + assert chain.compute_encoded_size(input_size, spec) == expected_size + + +def test_encode_returns_none_propagation() -> None: + """When an AA codec returns None, encode short-circuits and returns None.""" + + class NoneReturningAACodec(TransposeCodec): + """An ArrayArrayCodec that always returns None from encode.""" + + def _encode_sync(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer | None: + return None + + spec = _make_array_spec((3, 4), np.dtype("float64")) + chain = ChunkTransform( + codecs=(NoneReturningAACodec(order=(1, 0)), BytesCodec()), + ) + arr = np.arange(12, dtype="float64").reshape(3, 4) + nd_buf = _make_nd_buffer(arr) + assert chain.encode_chunk(nd_buf, spec) is None diff --git a/tests/test_cli/conftest.py b/tests/test_cli/conftest.py new file mode 100644 index 0000000000..4f95f47b5e --- /dev/null +++ b/tests/test_cli/conftest.py @@ -0,0 +1,146 @@ +from pathlib import Path +from typing import Any, Literal + +import pytest + +import zarr +from zarr.abc.store import Store +from zarr.core.common import ZarrFormat + + +def create_nested_zarr( + store: Store, + attributes: dict[str, Any] | None = None, + separator: Literal[".", "/"] = ".", + zarr_format: ZarrFormat = 2, +) -> list[str]: + """Create a zarr with nested groups / arrays for testing, returning the paths to all.""" + + if attributes is None: + attributes = {"baz": 42, "qux": [1, 4, 7, 12]} + + # 3 levels of nested groups + group_0 = zarr.create_group(store=store, zarr_format=zarr_format, attributes=attributes) + group_1 = group_0.create_group(name="group_1", attributes=attributes) + group_2 = group_1.create_group(name="group_2", attributes=attributes) + paths = [group_0.path, group_1.path, group_2.path] + + # 1 array per group + for i, group in enumerate([group_0, group_1, group_2]): + array = group.create_array( + name=f"array_{i}", + shape=(10, 10), + chunks=(5, 5), + dtype="uint16", + attributes=attributes, + chunk_key_encoding={"name": "v2", "separator": separator}, + ) + array[:] = 1 + paths.append(array.path) + + return paths + + +@pytest.fixture +def expected_paths() -> list[Path]: + """Expected paths for create_nested_zarr, with no metadata files or chunks""" + return [ + Path("array_0"), + Path("group_1"), + Path("group_1/array_1"), + Path("group_1/group_2"), + Path("group_1/group_2/array_2"), + ] + + +@pytest.fixture +def expected_chunks() -> list[Path]: + """Expected chunks for create_nested_zarr""" + return [ + Path("array_0/0.0"), + Path("array_0/0.1"), + Path("array_0/1.0"), + Path("array_0/1.1"), + Path("group_1/array_1/0.0"), + Path("group_1/array_1/0.1"), + Path("group_1/array_1/1.0"), + Path("group_1/array_1/1.1"), + Path("group_1/group_2/array_2/0.0"), + Path("group_1/group_2/array_2/0.1"), + Path("group_1/group_2/array_2/1.0"), + Path("group_1/group_2/array_2/1.1"), + ] + + +@pytest.fixture +def expected_v3_metadata() -> list[Path]: + """Expected v3 metadata for create_nested_zarr""" + return sorted( + [ + Path("zarr.json"), + Path("array_0/zarr.json"), + Path("group_1/zarr.json"), + Path("group_1/array_1/zarr.json"), + Path("group_1/group_2/zarr.json"), + Path("group_1/group_2/array_2/zarr.json"), + ] + ) + + +@pytest.fixture +def expected_v2_metadata() -> list[Path]: + """Expected v2 metadata for create_nested_zarr""" + return sorted( + [ + Path(".zgroup"), + Path(".zattrs"), + Path("array_0/.zarray"), + Path("array_0/.zattrs"), + Path("group_1/.zgroup"), + Path("group_1/.zattrs"), + Path("group_1/array_1/.zarray"), + Path("group_1/array_1/.zattrs"), + Path("group_1/group_2/.zgroup"), + Path("group_1/group_2/.zattrs"), + Path("group_1/group_2/array_2/.zarray"), + Path("group_1/group_2/array_2/.zattrs"), + ] + ) + + +@pytest.fixture +def expected_paths_no_metadata( + expected_paths: list[Path], expected_chunks: list[Path] +) -> list[Path]: + return sorted(expected_paths + expected_chunks) + + +@pytest.fixture +def expected_paths_v3_metadata( + expected_paths: list[Path], expected_chunks: list[Path], expected_v3_metadata: list[Path] +) -> list[Path]: + return sorted(expected_paths + expected_chunks + expected_v3_metadata) + + +@pytest.fixture +def expected_paths_v3_metadata_no_chunks( + expected_paths: list[Path], expected_v3_metadata: list[Path] +) -> list[Path]: + return sorted(expected_paths + expected_v3_metadata) + + +@pytest.fixture +def expected_paths_v2_metadata( + expected_paths: list[Path], expected_chunks: list[Path], expected_v2_metadata: list[Path] +) -> list[Path]: + return sorted(expected_paths + expected_chunks + expected_v2_metadata) + + +@pytest.fixture +def expected_paths_v2_v3_metadata( + expected_paths: list[Path], + expected_chunks: list[Path], + expected_v2_metadata: list[Path], + expected_v3_metadata: list[Path], +) -> list[Path]: + return sorted(expected_paths + expected_chunks + expected_v2_metadata + expected_v3_metadata) diff --git a/tests/test_cli/test_migrate_v3.py b/tests/test_cli/test_migrate_v3.py new file mode 100644 index 0000000000..7213aada12 --- /dev/null +++ b/tests/test_cli/test_migrate_v3.py @@ -0,0 +1,659 @@ +import lzma +from pathlib import Path +from typing import Literal, cast + +import numcodecs +import numcodecs.abc +import numpy as np +import pytest + +import zarr +from tests.test_cli.conftest import create_nested_zarr +from zarr.abc.codec import Codec +from zarr.codecs.blosc import BloscCodec +from zarr.codecs.bytes import BytesCodec +from zarr.codecs.gzip import GzipCodec +from zarr.codecs.numcodecs import LZMA, Delta +from zarr.codecs.transpose import TransposeCodec +from zarr.codecs.zstd import ZstdCodec +from zarr.core.chunk_key_encodings import V2ChunkKeyEncoding +from zarr.core.common import JSON, ZarrFormat +from zarr.core.dtype.npy.int import UInt8, UInt16 +from zarr.core.group import Group, GroupMetadata +from zarr.core.metadata.v3 import ArrayV3Metadata +from zarr.storage._local import LocalStore +from zarr.types import AnyArray + +typer_testing = pytest.importorskip( + "typer.testing", reason="optional cli dependencies aren't installed" +) +cli = pytest.importorskip("zarr._cli.cli", reason="optional cli dependencies aren't installed") + +runner = typer_testing.CliRunner() + + +def test_migrate_array(local_store: LocalStore) -> None: + shape = (10, 10) + chunks = (10, 10) + dtype = "uint16" + compressors = numcodecs.Blosc(cname="zstd", clevel=3, shuffle=1) + fill_value = 2 + attributes = cast(dict[str, JSON], {"baz": 42, "qux": [1, 4, 7, 12]}) + + zarr.create_array( + store=local_store, + shape=shape, + chunks=chunks, + dtype=dtype, + compressors=compressors, + zarr_format=2, + fill_value=fill_value, + attributes=attributes, + ) + + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) + assert result.exit_code == 0 + assert (local_store.root / "zarr.json").exists() + + zarr_array = zarr.open(local_store.root, zarr_format=3) + + expected_metadata = ArrayV3Metadata( + shape=shape, + data_type=UInt16(endianness="little"), + chunk_grid={"name": "regular", "configuration": {"chunk_shape": chunks}}, + chunk_key_encoding=V2ChunkKeyEncoding(separator="."), + fill_value=fill_value, + codecs=( + BytesCodec(endian="little"), + BloscCodec(typesize=2, cname="zstd", clevel=3, shuffle="shuffle", blocksize=0), + ), + attributes=attributes, + dimension_names=None, + storage_transformers=None, + ) + assert zarr_array.metadata == expected_metadata + + +def test_migrate_group(local_store: LocalStore) -> None: + attributes = {"baz": 42, "qux": [1, 4, 7, 12]} + zarr.create_group(store=local_store, zarr_format=2, attributes=attributes) + + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) + assert result.exit_code == 0 + assert (local_store.root / "zarr.json").exists() + + zarr_array = zarr.open(local_store.root, zarr_format=3) + expected_metadata = GroupMetadata( + attributes=attributes, zarr_format=3, consolidated_metadata=None + ) + assert zarr_array.metadata == expected_metadata + + +@pytest.mark.parametrize("separator", [".", "/"]) +def test_migrate_nested_groups_and_arrays_in_place( + local_store: LocalStore, separator: str, expected_v3_metadata: list[Path] +) -> None: + """Test that zarr.json are made at the correct points in a hierarchy of groups and arrays + (including when there are additional dirs due to using a / separator)""" + + attributes = {"baz": 42, "qux": [1, 4, 7, 12]} + paths = create_nested_zarr(local_store, attributes=attributes, separator=separator) + + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) + assert result.exit_code == 0 + + zarr_json_paths = sorted(local_store.root.rglob("zarr.json")) + expected_zarr_json_paths = [local_store.root / p for p in expected_v3_metadata] + assert zarr_json_paths == expected_zarr_json_paths + + # Check converted zarr can be opened + metadata accessed at all levels + zarr_array = zarr.open(local_store.root, zarr_format=3) + for path in paths: + zarr_v3 = cast(AnyArray | Group, zarr_array[path]) + metadata = zarr_v3.metadata + assert metadata.zarr_format == 3 + assert metadata.attributes == attributes + + +@pytest.mark.parametrize("separator", [".", "/"]) +async def test_migrate_nested_groups_and_arrays_separate_location( + tmp_path: Path, + separator: str, + expected_v2_metadata: list[Path], + expected_v3_metadata: list[Path], +) -> None: + """Test that zarr.json are made at the correct paths, when saving to a separate output location.""" + + input_zarr_path = tmp_path / "input.zarr" + output_zarr_path = tmp_path / "output.zarr" + + local_store = await LocalStore.open(str(input_zarr_path)) + create_nested_zarr(local_store, separator=separator) + + result = runner.invoke(cli.app, ["migrate", "v3", str(input_zarr_path), str(output_zarr_path)]) + assert result.exit_code == 0 + + # Files in input zarr should be unchanged i.e. still v2 only + zarr_json_paths = sorted(input_zarr_path.rglob("zarr.json")) + assert len(zarr_json_paths) == 0 + + paths = [ + path + for path in input_zarr_path.rglob("*") + if path.stem in [".zarray", ".zgroup", ".zattrs"] + ] + expected_paths = [input_zarr_path / p for p in expected_v2_metadata] + assert sorted(paths) == expected_paths + + # Files in output zarr should only contain v3 metadata + zarr_json_paths = sorted(output_zarr_path.rglob("zarr.json")) + expected_zarr_json_paths = [output_zarr_path / p for p in expected_v3_metadata] + assert zarr_json_paths == expected_zarr_json_paths + + +def test_remove_v2_metadata_option_in_place( + local_store: LocalStore, expected_paths_v3_metadata: list[Path] +) -> None: + create_nested_zarr(local_store) + + # convert v2 metadata to v3, then remove v2 metadata + result = runner.invoke( + cli.app, ["migrate", "v3", str(local_store.root), "--remove-v2-metadata"] + ) + assert result.exit_code == 0 + + paths = sorted(local_store.root.rglob("*")) + expected_paths = [local_store.root / p for p in expected_paths_v3_metadata] + assert paths == expected_paths + + +async def test_remove_v2_metadata_option_separate_location( + tmp_path: Path, + expected_paths_v2_metadata: list[Path], + expected_paths_v3_metadata_no_chunks: list[Path], +) -> None: + """Check that when using --remove-v2-metadata with a separate output location, no v2 metadata is removed from + the input location.""" + + input_zarr_path = tmp_path / "input.zarr" + output_zarr_path = tmp_path / "output.zarr" + + local_store = await LocalStore.open(str(input_zarr_path)) + create_nested_zarr(local_store) + + result = runner.invoke( + cli.app, + ["migrate", "v3", str(input_zarr_path), str(output_zarr_path), "--remove-v2-metadata"], + ) + assert result.exit_code == 0 + + # input image should be unchanged + paths = sorted(input_zarr_path.rglob("*")) + expected_paths = [input_zarr_path / p for p in expected_paths_v2_metadata] + assert paths == expected_paths + + # output image should be only v3 metadata + paths = sorted(output_zarr_path.rglob("*")) + expected_paths = [output_zarr_path / p for p in expected_paths_v3_metadata_no_chunks] + assert paths == expected_paths + + +def test_overwrite_option_in_place( + local_store: LocalStore, expected_paths_v2_v3_metadata: list[Path] +) -> None: + create_nested_zarr(local_store) + + # add v3 metadata in place + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) + assert result.exit_code == 0 + + # check that v3 metadata can be overwritten with --overwrite + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root), "--overwrite"]) + assert result.exit_code == 0 + + paths = sorted(local_store.root.rglob("*")) + expected_paths = [local_store.root / p for p in expected_paths_v2_v3_metadata] + assert paths == expected_paths + + +async def test_overwrite_option_separate_location( + tmp_path: Path, + expected_paths_v2_metadata: list[Path], + expected_paths_v3_metadata_no_chunks: list[Path], +) -> None: + input_zarr_path = tmp_path / "input.zarr" + output_zarr_path = tmp_path / "output.zarr" + + local_store = await LocalStore.open(str(input_zarr_path)) + create_nested_zarr(local_store) + + # create v3 metadata at output_zarr_path + result = runner.invoke( + cli.app, + ["migrate", "v3", str(input_zarr_path), str(output_zarr_path)], + ) + assert result.exit_code == 0 + + # re-run with --overwrite option + result = runner.invoke( + cli.app, + ["migrate", "v3", str(input_zarr_path), str(output_zarr_path), "--overwrite", "--force"], + ) + assert result.exit_code == 0 + + # original image should be un-changed + paths = sorted(input_zarr_path.rglob("*")) + expected_paths = [input_zarr_path / p for p in expected_paths_v2_metadata] + assert paths == expected_paths + + # output image is only v3 metadata + paths = sorted(output_zarr_path.rglob("*")) + expected_paths = [output_zarr_path / p for p in expected_paths_v3_metadata_no_chunks] + assert paths == expected_paths + + +@pytest.mark.parametrize("separator", [".", "/"]) +def test_migrate_sub_group( + local_store: LocalStore, separator: str, expected_v3_metadata: list[Path] +) -> None: + """Test that only arrays/groups within group_1 are converted (+ no other files in store)""" + + create_nested_zarr(local_store, separator=separator) + group_path = local_store.root / "group_1" + + result = runner.invoke(cli.app, ["migrate", "v3", str(group_path)]) + assert result.exit_code == 0 + + zarr_json_paths = sorted(local_store.root.rglob("zarr.json")) + expected_zarr_json_paths = [ + local_store.root / p + for p in expected_v3_metadata + if group_path in (local_store.root / p).parents + ] + assert zarr_json_paths == expected_zarr_json_paths + + +@pytest.mark.parametrize( + ("compressor_v2", "compressor_v3"), + [ + ( + numcodecs.Blosc(cname="zstd", clevel=3, shuffle=1), + BloscCodec(typesize=2, cname="zstd", clevel=3, shuffle="shuffle", blocksize=0), + ), + (numcodecs.Zstd(level=3), ZstdCodec(level=3)), + (numcodecs.GZip(level=3), GzipCodec(level=3)), + ], + ids=["blosc", "zstd", "gzip"], +) +def test_migrate_compressor( + local_store: LocalStore, compressor_v2: numcodecs.abc.Codec, compressor_v3: Codec +) -> None: + zarr_array = zarr.create_array( + store=local_store, + shape=(10, 10), + chunks=(10, 10), + dtype="uint16", + compressors=compressor_v2, + zarr_format=2, + fill_value=0, + ) + zarr_array[:] = 1 + + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) + assert result.exit_code == 0 + assert (local_store.root / "zarr.json").exists() + + zarr_array = zarr.open_array(local_store.root, zarr_format=3) + metadata = zarr_array.metadata + assert metadata.zarr_format == 3 + assert metadata.codecs == ( + BytesCodec(endian="little"), + compressor_v3, + ) + assert np.all(zarr_array[:] == 1) + + +def test_migrate_numcodecs_compressor(local_store: LocalStore) -> None: + """Test migration of a numcodecs compressor without a zarr.codecs equivalent.""" + + lzma_settings = { + "format": lzma.FORMAT_RAW, + "check": -1, + "preset": None, + "filters": [ + {"id": lzma.FILTER_DELTA, "dist": 4}, + {"id": lzma.FILTER_LZMA2, "preset": 1}, + ], + } + + zarr_array = zarr.create_array( + store=local_store, + shape=(10, 10), + chunks=(10, 10), + dtype="uint16", + compressors=numcodecs.LZMA.from_config(lzma_settings), + zarr_format=2, + fill_value=0, + ) + zarr_array[:] = 1 + + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) + assert result.exit_code == 0 + assert (local_store.root / "zarr.json").exists() + + zarr_array = zarr.open_array(local_store.root, zarr_format=3) + metadata = zarr_array.metadata + assert metadata.zarr_format == 3 + assert metadata.codecs == ( + BytesCodec(endian="little"), + LZMA( + format=lzma_settings["format"], + check=lzma_settings["check"], + preset=lzma_settings["preset"], + filters=lzma_settings["filters"], + ), + ) + assert np.all(zarr_array[:] == 1) + + +def test_migrate_filter(local_store: LocalStore) -> None: + filter_v2 = numcodecs.Delta(dtype=" None: + zarr_array = zarr.create_array( + store=local_store, + shape=(10, 10), + chunks=(10, 10), + dtype="uint16", + compressors=None, + zarr_format=2, + fill_value=0, + order=order, + ) + zarr_array[:] = 1 + + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) + assert result.exit_code == 0 + assert (local_store.root / "zarr.json").exists() + + zarr_array = zarr.open_array(local_store.root, zarr_format=3) + metadata = zarr_array.metadata + assert metadata.zarr_format == 3 + assert metadata.codecs == expected_codecs + assert np.all(zarr_array[:] == 1) + + +@pytest.mark.parametrize( + ("dtype", "expected_data_type", "expected_codecs"), + [ + ("uint8", UInt8(), (BytesCodec(endian=None),)), + ("uint16", UInt16(), (BytesCodec(endian="little"),)), + ], + ids=["single_byte", "multi_byte"], +) +def test_migrate_endian( + local_store: LocalStore, + dtype: str, + expected_data_type: UInt8 | UInt16, + expected_codecs: tuple[Codec], +) -> None: + zarr_array = zarr.create_array( + store=local_store, + shape=(10, 10), + chunks=(10, 10), + dtype=dtype, + compressors=None, + zarr_format=2, + fill_value=0, + ) + zarr_array[:] = 1 + + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) + assert result.exit_code == 0 + assert (local_store.root / "zarr.json").exists() + + zarr_array = zarr.open_array(local_store.root, zarr_format=3) + metadata = zarr_array.metadata + assert metadata.zarr_format == 3 + assert metadata.data_type == expected_data_type + assert metadata.codecs == expected_codecs + assert np.all(zarr_array[:] == 1) + + +@pytest.mark.parametrize("node_type", ["array", "group"]) +def test_migrate_v3(local_store: LocalStore, node_type: str) -> None: + """Attempting to convert a v3 array/group should always fail""" + + if node_type == "array": + zarr.create_array( + store=local_store, shape=(10, 10), chunks=(10, 10), zarr_format=3, dtype="uint16" + ) + else: + zarr.create_group(store=local_store, zarr_format=3) + + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) + assert result.exit_code == 1 + assert isinstance(result.exception, TypeError) + assert str(result.exception) == "Only arrays / groups with zarr v2 metadata can be converted" + + +def test_migrate_consolidated_metadata(local_store: LocalStore) -> None: + """Attempting to convert a group with consolidated metadata should always fail""" + + group = zarr.create_group(store=local_store, zarr_format=2) + group.create_array(shape=(1,), name="a", dtype="uint8") + zarr.consolidate_metadata(local_store) + + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) + assert result.exit_code == 1 + assert isinstance(result.exception, NotImplementedError) + assert str(result.exception) == "Migration of consolidated metadata isn't supported." + + +def test_migrate_unknown_codec(local_store: LocalStore) -> None: + """Attempting to convert a codec without a v3 equivalent should always fail""" + + zarr.create_array( + store=local_store, + shape=(10, 10), + chunks=(10, 10), + dtype="uint16", + filters=[numcodecs.Categorize(labels=["a", "b"], dtype=object)], + zarr_format=2, + fill_value=0, + ) + + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) + assert result.exit_code == 1 + assert isinstance(result.exception, ValueError) + assert ( + str(result.exception) + == "Couldn't find corresponding zarr.codecs.numcodecs codec for categorize" + ) + + +def test_migrate_incorrect_filter(local_store: LocalStore) -> None: + """Attempting to convert a filter (which is the wrong type of codec) should always fail""" + + zarr.create_array( + store=local_store, + shape=(10, 10), + chunks=(10, 10), + dtype="uint16", + filters=[numcodecs.Zstd(level=3)], + zarr_format=2, + fill_value=0, + ) + + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) + + assert result.exit_code == 1 + assert isinstance(result.exception, TypeError) + assert ( + str(result.exception) + == "Filter is not an ArrayArrayCodec" + ) + + +def test_migrate_incorrect_compressor(local_store: LocalStore) -> None: + """Attempting to convert a compressor (which is the wrong type of codec) should always fail""" + + zarr.create_array( + store=local_store, + shape=(10, 10), + chunks=(10, 10), + dtype="uint16", + compressors=numcodecs.Delta(dtype=" is not a BytesBytesCodec" + ) + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_remove_metadata_fails_without_force( + local_store: LocalStore, zarr_format: ZarrFormat +) -> None: + """Test removing metadata (when no alternate metadata is present) fails without --force.""" + + create_nested_zarr(local_store, zarr_format=zarr_format) + + result = runner.invoke(cli.app, ["remove-metadata", f"v{zarr_format}", str(local_store.root)]) + assert result.exit_code == 1 + assert isinstance(result.exception, ValueError) + assert str(result.exception).startswith(f"Cannot remove v{zarr_format} metadata at file") + + +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_remove_metadata_succeeds_with_force( + local_store: LocalStore, zarr_format: ZarrFormat, expected_paths_no_metadata: list[Path] +) -> None: + """Test removing metadata (when no alternate metadata is present) succeeds with --force.""" + + create_nested_zarr(local_store, zarr_format=zarr_format) + + result = runner.invoke( + cli.app, ["remove-metadata", f"v{zarr_format}", str(local_store.root), "--force"] + ) + assert result.exit_code == 0 + + paths = sorted(local_store.root.rglob("*")) + expected_paths = [local_store.root / p for p in expected_paths_no_metadata] + assert paths == expected_paths + + +def test_remove_metadata_sub_group( + local_store: LocalStore, expected_paths_no_metadata: list[Path] +) -> None: + """Test only v2 metadata within group_1 is removed and rest remains un-changed.""" + + create_nested_zarr(local_store) + + result = runner.invoke( + cli.app, ["remove-metadata", "v2", str(local_store.root / "group_1"), "--force"] + ) + assert result.exit_code == 0 + + # check all metadata files inside group_1 are removed (.zattrs / .zgroup / .zarray should remain only inside the top + # group) + paths = sorted(local_store.root.rglob("*")) + + expected_paths = [local_store.root / p for p in expected_paths_no_metadata] + expected_paths.append(local_store.root / ".zattrs") + expected_paths.append(local_store.root / ".zgroup") + expected_paths.append(local_store.root / "array_0" / ".zarray") + expected_paths.append(local_store.root / "array_0" / ".zattrs") + assert paths == sorted(expected_paths) + + +@pytest.mark.parametrize( + ("zarr_format", "expected_output_paths"), + [("v2", "expected_paths_v3_metadata"), ("v3", "expected_paths_v2_metadata")], +) +def test_remove_metadata_after_conversion( + local_store: LocalStore, + request: pytest.FixtureRequest, + zarr_format: str, + expected_output_paths: str, +) -> None: + """Test all v2/v3 metadata can be removed after metadata conversion (all groups / arrays / + metadata of other versions should remain as-is)""" + + create_nested_zarr(local_store) + + # convert v2 metadata to v3 (so now both v2 and v3 metadata present!), then remove either the v2 or v3 metadata + result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)]) + assert result.exit_code == 0 + result = runner.invoke(cli.app, ["remove-metadata", zarr_format, str(local_store.root)]) + assert result.exit_code == 0 + + paths = sorted(local_store.root.rglob("*")) + expected_paths = request.getfixturevalue(expected_output_paths) + expected_paths = [local_store.root / p for p in expected_paths] + assert paths == expected_paths + + +@pytest.mark.parametrize("cli_command", ["migrate", "remove-metadata"]) +def test_dry_run( + local_store: LocalStore, cli_command: str, expected_paths_v2_metadata: list[Path] +) -> None: + """Test that all files are un-changed after a dry run""" + + create_nested_zarr(local_store) + + if cli_command == "migrate": + result = runner.invoke( + cli.app, ["migrate", "v3", str(local_store.root), "--overwrite", "--force", "--dry-run"] + ) + else: + result = runner.invoke( + cli.app, ["remove-metadata", "v2", str(local_store.root), "--force", "--dry-run"] + ) + + assert result.exit_code == 0 + + paths = sorted(local_store.root.rglob("*")) + expected_paths = [local_store.root / p for p in expected_paths_v2_metadata] + assert paths == expected_paths diff --git a/tests/test_coalesce.py b/tests/test_coalesce.py new file mode 100644 index 0000000000..cb8ff29ec7 --- /dev/null +++ b/tests/test_coalesce.py @@ -0,0 +1,674 @@ +# tests/test_coalesce.py +from __future__ import annotations + +import asyncio +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +import pytest + +from zarr.abc.store import ( + ByteRequest, + OffsetByteRequest, + RangeByteRequest, + SuffixByteRequest, +) +from zarr.core._coalesce import ( + coalesce_ranges, + coalesced_get, +) +from zarr.core.buffer import Buffer, default_buffer_prototype + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Callable, Mapping, Sequence + + +def _buf(data: bytes) -> Buffer: + return default_buffer_prototype().buffer.from_bytes(data) + + +@dataclass +class FakeFetch: + """Records every call and serves canned bytes from an in-memory blob.""" + + blob: bytes + key_exists: bool = True + raise_on: Callable[[ByteRequest | None], bool] | None = None + calls: list[ByteRequest | None] = field(default_factory=list) + + async def __call__(self, byte_range: ByteRequest | None) -> Buffer | None: + self.calls.append(byte_range) + if not self.key_exists: + return None + if self.raise_on is not None and self.raise_on(byte_range): + raise OSError("injected") + if byte_range is None: + return _buf(self.blob) + if isinstance(byte_range, RangeByteRequest): + return _buf(self.blob[byte_range.start : byte_range.end]) + if isinstance(byte_range, OffsetByteRequest): + return _buf(self.blob[byte_range.offset :]) + if isinstance(byte_range, SuffixByteRequest): + return _buf(self.blob[-byte_range.suffix :]) + raise AssertionError(f"unknown byte_range {byte_range!r}") + + +async def _collect( + agen: AsyncIterator[Sequence[tuple[int, Buffer | None]]], +) -> list[list[tuple[int, Buffer | None]]]: + """Drain an async generator of groups into a list of lists of tuples.""" + return [list(group) async for group in agen] + + +def _contents(groups: list[list[tuple[int, Buffer | None]]]) -> dict[int, bytes]: + """Flatten to {index: bytes}.""" + result: dict[int, bytes] = {} + for group in groups: + for idx, buf in group: + assert buf is not None + result[idx] = buf.to_bytes() + return result + + +# --------------------------------------------------------------------------- +# Shared coalescing-knob bundles. Each is a complete mapping of all three +# kwargs to splat into `coalesced_get`; `coalesce_ranges` ignores +# `max_concurrency`. The leaf functions in `_coalesce.py` require all knobs +# explicitly β€” `Store.get_ranges` is the public entry point and owns the +# canonical defaults. Tests pick their own values appropriate to the scenario. +# --------------------------------------------------------------------------- + +# Permissive default for tests that don't care about specific thresholds. Mirrors +# `Store.get_ranges`'s public defaults but the test file owns this independently +# of any production constants. +DEFAULT: Mapping[str, int] = { + "max_concurrency": 10, + "max_gap_bytes": 1 << 20, + "max_coalesced_bytes": 16 << 20, +} +"""Permissive defaults; mirrors `Store.get_ranges`'s baseline.""" + +MERGE_GAP_50: Mapping[str, int] = { + "max_concurrency": 10, + "max_gap_bytes": 50, + "max_coalesced_bytes": 1 << 20, +} +"""Merge ranges within 50 bytes of each other.""" + +NO_MERGE: Mapping[str, int] = { + "max_concurrency": 10, + "max_gap_bytes": -1, + "max_coalesced_bytes": 1 << 20, +} +"""No merging: any positive gap is > -1, so no pair ever coalesces.""" + +CAP_50: Mapping[str, int] = { + "max_concurrency": 10, + "max_gap_bytes": 1000, + "max_coalesced_bytes": 50, +} +"""Gap permissive but merged size capped at 50 bytes.""" + + +def _grouping(opts: Mapping[str, int]) -> dict[str, int]: + """Return only the grouping knobs from a full options bundle. + + `coalesce_ranges` rejects `max_concurrency`; this lets test bundles be + full kwargs maps (for `coalesced_get`) and still be passed to the pure + planner via splat. + """ + return {k: v for k, v in opts.items() if k != "max_concurrency"} + + +# A deterministic blob used for content-sensitive cases: byte i == (i % 256). +_INDEXED_BLOB = bytes(i % 256 for i in range(10_000)) + + +# --------------------------------------------------------------------------- +# Parametrized structural/content tests (cases without async timing or errors). +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class StructuralCase: + """One row of the parametrized structure-and-contents table.""" + + id: str + """pytest id for the case.""" + ranges: list[ByteRequest | None] + """Input to coalesced_get.""" + options: Mapping[str, int] + """Coalescing knobs to splat into `coalesced_get`.""" + expected_group_sizes: list[int] + """Sorted list of group tuple-counts (order-independent).""" + expected_contents: dict[int, bytes] | None = None + """{input_index: bytes} to verify bytes, or None to skip the content check.""" + expected_n_fetches: int | None = None + """Exact number of calls to the fetch callable, or None to skip the check.""" + + +_STRUCTURAL_CASES: list[StructuralCase] = [ + StructuralCase( + id="empty-input", + ranges=[], + options=DEFAULT, + expected_group_sizes=[], + expected_n_fetches=0, + ), + StructuralCase( + id="single-range", + ranges=[RangeByteRequest(2, 5)], + options=DEFAULT, + expected_group_sizes=[1], + expected_contents={0: _INDEXED_BLOB[2:5]}, + expected_n_fetches=1, + ), + StructuralCase( + id="disjoint-3-no-merge", + ranges=[ + RangeByteRequest(0, 10), + RangeByteRequest(200, 210), + RangeByteRequest(500, 510), + ], + options=MERGE_GAP_50, + expected_group_sizes=[1, 1, 1], + expected_contents={ + 0: _INDEXED_BLOB[0:10], + 1: _INDEXED_BLOB[200:210], + 2: _INDEXED_BLOB[500:510], + }, + expected_n_fetches=3, + ), + StructuralCase( + id="adjacent-3-one-merged-group", + ranges=[ + RangeByteRequest(0, 5), + RangeByteRequest(10, 15), + RangeByteRequest(20, 25), + ], + options=MERGE_GAP_50, + expected_group_sizes=[3], + expected_contents={ + 0: _INDEXED_BLOB[0:5], + 1: _INDEXED_BLOB[10:15], + 2: _INDEXED_BLOB[20:25], + }, + expected_n_fetches=1, + ), + StructuralCase( + id="two-clusters-one-singleton", + ranges=[ + RangeByteRequest(0, 10), + RangeByteRequest(20, 30), + RangeByteRequest(500, 510), + ], + options=MERGE_GAP_50, + expected_group_sizes=[1, 2], + expected_contents={ + 0: _INDEXED_BLOB[0:10], + 1: _INDEXED_BLOB[20:30], + 2: _INDEXED_BLOB[500:510], + }, + expected_n_fetches=2, + ), + StructuralCase( + id="uncoalescable-mixed-with-range", + ranges=[ + RangeByteRequest(0, 3), + OffsetByteRequest(5), + SuffixByteRequest(2), + None, + ], + options=DEFAULT, + expected_group_sizes=[1, 1, 1, 1], + expected_contents={ + 0: _INDEXED_BLOB[0:3], + 1: _INDEXED_BLOB[5:], + 2: _INDEXED_BLOB[-2:], + 3: _INDEXED_BLOB, + }, + expected_n_fetches=4, + ), + StructuralCase( + id="shuffled-input-indices-preserved", + ranges=[ + RangeByteRequest(500, 510), + RangeByteRequest(0, 10), + RangeByteRequest(200, 210), + RangeByteRequest(300, 310), + ], + options=MERGE_GAP_50, + expected_group_sizes=[1, 1, 1, 1], + expected_contents={ + 0: _INDEXED_BLOB[500:510], + 1: _INDEXED_BLOB[0:10], + 2: _INDEXED_BLOB[200:210], + 3: _INDEXED_BLOB[300:310], + }, + expected_n_fetches=4, + ), + StructuralCase( + id="cap-prevents-merge-of-close-ranges", + # 20 + 20 gap + 20 = 60-byte merged span > cap of 50. + ranges=[RangeByteRequest(0, 20), RangeByteRequest(40, 60)], + options=CAP_50, + expected_group_sizes=[1, 1], + expected_n_fetches=2, + ), + StructuralCase( + id="single-range-larger-than-cap-passes-through", + # Cap only applies to MERGE decisions; a lone oversized range still fetches. + ranges=[RangeByteRequest(0, 200)], + options=CAP_50, + expected_group_sizes=[1], + expected_contents={0: _INDEXED_BLOB[0:200]}, + expected_n_fetches=1, + ), +] + + +@pytest.mark.parametrize("case", _STRUCTURAL_CASES, ids=lambda c: c.id) +async def test_coalescing_structure_and_contents(case: StructuralCase) -> None: + """Group structure, byte contents, and fetch-call count for the deterministic cases.""" + fetch = FakeFetch(_INDEXED_BLOB) + groups = await _collect(coalesced_get(fetch, case.ranges, **case.options)) + + assert sorted(len(g) for g in groups) == sorted(case.expected_group_sizes) + + if case.expected_contents is not None: + assert _contents(groups) == case.expected_contents + + if case.expected_n_fetches is not None: + assert len(fetch.calls) == case.expected_n_fetches + + +# --------------------------------------------------------------------------- +# Focused non-parametrized tests for cases with distinctive assertion shapes. +# --------------------------------------------------------------------------- + + +async def test_within_group_ordering_is_start_offset() -> None: + """Within a merged group, tuples are ordered by start offset, not input order.""" + fetch = FakeFetch(_INDEXED_BLOB) + # Two ranges that merge; one has a later start but is listed first in input. + ranges: list[ByteRequest | None] = [RangeByteRequest(20, 25), RangeByteRequest(0, 5)] + groups = await _collect(coalesced_get(fetch, ranges, **MERGE_GAP_50)) + assert len(groups) == 1 + # Input index 1 (start=0) comes first, then 0 (start=20). + assert [idx for idx, _ in groups[0]] == [1, 0] + + +async def test_adjacent_ranges_fire_single_fetch_spanning_merged_region() -> None: + """Verify the merged fetch covers exactly the span from min-start to max-end.""" + fetch = FakeFetch(_INDEXED_BLOB) + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 5), + RangeByteRequest(10, 15), + RangeByteRequest(20, 25), + ] + await _collect(coalesced_get(fetch, ranges, **MERGE_GAP_50)) + assert len(fetch.calls) == 1 + call = fetch.calls[0] + assert isinstance(call, RangeByteRequest) + assert call.start == 0 + assert call.end == 25 + + +# --------------------------------------------------------------------------- +# Concurrency and cancellation. +# --------------------------------------------------------------------------- + + +async def test_max_concurrency_is_honored() -> None: + """With 10 non-mergeable ranges and max_concurrency=3, peak in-flight must not exceed 3.""" + in_flight = 0 + peak = 0 + lock = asyncio.Lock() + + async def fetch(byte_range: ByteRequest | None) -> Buffer | None: + nonlocal in_flight, peak + async with lock: + in_flight += 1 + peak = max(peak, in_flight) + # give the scheduler a chance to run other tasks + await asyncio.sleep(0.01) + async with lock: + in_flight -= 1 + return _buf(b"x") + + ranges: list[ByteRequest | None] = [RangeByteRequest(i * 1000, i * 1000 + 1) for i in range(10)] + opts: Mapping[str, int] = { + "max_gap_bytes": 0, # force no merging + "max_coalesced_bytes": 1 << 20, + "max_concurrency": 3, + } + async for _group in coalesced_get(fetch, ranges, **opts): + pass + assert peak <= 3 + assert peak >= 2 # must have been some real concurrency + + +async def test_consumer_break_cancels_pending_fetches() -> None: + """Breaking out of the async for should cancel pending fetches rather than let them complete.""" + completed_calls = 0 + cancelled_calls = 0 + + async def fetch(byte_range: ByteRequest | None) -> Buffer | None: + nonlocal completed_calls, cancelled_calls + assert isinstance(byte_range, RangeByteRequest) + start = byte_range.start + try: + # First fetch returns fast so the async-for body runs and can break. + # Later fetches sleep long enough that cancellation has room to land. + await asyncio.sleep(0.001 if start == 0 else 2.0) + except asyncio.CancelledError: + cancelled_calls += 1 + raise + completed_calls += 1 + return _buf(b"x") + + opts: Mapping[str, int] = { + "max_gap_bytes": -1, # no merging + "max_coalesced_bytes": 1 << 20, + "max_concurrency": 3, + } + ranges: list[ByteRequest | None] = [RangeByteRequest(i * 1000, i * 1000 + 1) for i in range(6)] + + agen = coalesced_get(fetch, ranges, **opts) + async for _group in agen: + break + # Explicitly close the generator so its finally block runs (cancelling + # in-flight tasks) before we make assertions. + await agen.aclose() + + # The fast task completes; the remaining tasks are either cancelled while + # sleeping (raising CancelledError into the user try block) or cancelled + # while still waiting on the semaphore (which doesn't enter the try at all). + # Either way, none of them should be allowed to complete. + assert completed_calls == 1 + assert cancelled_calls >= 1 + assert completed_calls + cancelled_calls <= len(ranges) + + +# --------------------------------------------------------------------------- +# Key-missing semantics. +# --------------------------------------------------------------------------- + + +async def test_key_missing_from_first_call_raises() -> None: + """If the very first fetch returns None, the iterator raises an ExceptionGroup containing FileNotFoundError.""" + fetch = FakeFetch(b"x" * 100, key_exists=False) + ranges: list[ByteRequest | None] = [RangeByteRequest(0, 10), RangeByteRequest(20, 30)] + with pytest.RaisesGroup(pytest.RaisesExc(FileNotFoundError)): + await _collect(coalesced_get(fetch, ranges, **DEFAULT)) + + +@pytest.mark.parametrize( + "byte_range", + [OffsetByteRequest(5), SuffixByteRequest(5), None], + ids=["offset", "suffix", "none"], +) +async def test_key_missing_on_uncoalescable_input_raises( + byte_range: ByteRequest | None, +) -> None: + """Uncoalescable inputs take a distinct path; key-missing must still raise (wrapped in a group).""" + fetch = FakeFetch(b"x" * 100, key_exists=False) + with pytest.RaisesGroup(pytest.RaisesExc(FileNotFoundError)): + await _collect(coalesced_get(fetch, [byte_range], **DEFAULT)) + + +async def test_key_missing_mid_stream_raises_after_earlier_groups() -> None: + """If a later fetch returns None, earlier-completed groups yield before the raise.""" + call_count = 0 + + async def fetch(byte_range: ByteRequest | None) -> Buffer | None: + nonlocal call_count + call_count += 1 + # Deterministic: first call serves, second returns None. + await asyncio.sleep(0.01 if call_count == 1 else 0.02) + if call_count >= 2: + return None + return _buf(b"ok") + + opts: Mapping[str, int] = { + "max_gap_bytes": -1, + "max_coalesced_bytes": 1 << 20, + "max_concurrency": 1, # serialize for determinism + } + ranges: list[ByteRequest | None] = [RangeByteRequest(0, 2), RangeByteRequest(100, 102)] + agen = coalesced_get(fetch, ranges, **opts) + first = await anext(agen) + assert len(first) == 1 + with pytest.RaisesGroup(pytest.RaisesExc(FileNotFoundError)): + await anext(agen) + + +async def test_key_missing_mid_stream_with_concurrency_cancels_late_arrivals() -> None: + """ + Under max_concurrency > 1, a mid-stream miss should raise FileNotFoundError + and cancel still-in-flight unrelated tasks rather than wait for them. + """ + late_gate = asyncio.Event() + miss_fired = asyncio.Event() + # Driven by the test body after the first successful yield, so the miss + # task can't race past the start=0 result. + fire_miss = asyncio.Event() + + async def fetch(byte_range: ByteRequest | None) -> Buffer | None: + assert isinstance(byte_range, RangeByteRequest) + start = byte_range.start + if start == 0: + return _buf(b"ok") + if start == 1000: + # Wait for the test to give the green light before returning None. + # This makes ordering deterministic regardless of scheduling. + await asyncio.wait_for(fire_miss.wait(), timeout=5.0) + miss_fired.set() + return None + # Late arrivals would block on this gate; they should be cancelled + # before they ever return. + await asyncio.wait_for(late_gate.wait(), timeout=5.0) + return _buf(b"ok") + + opts: Mapping[str, int] = { + "max_gap_bytes": -1, + "max_coalesced_bytes": 1 << 20, + "max_concurrency": 3, + } + ranges: list[ByteRequest | None] = [RangeByteRequest(i * 1000, i * 1000 + 1) for i in range(7)] + + agen = coalesced_get(fetch, ranges, **opts) + first = await anext(agen) + assert len(first) == 1 + idx, buf = first[0] + assert idx == 0 + assert buf is not None + # Now that #0 has yielded, signal the miss task to return None. + fire_miss.set() + with pytest.RaisesGroup(pytest.RaisesExc(FileNotFoundError)): + await anext(agen) + assert miss_fired.is_set() + # Sanity: late_gate was never set, so the cancellation path is what completed the test. + assert not late_gate.is_set() + + +# --------------------------------------------------------------------------- +# Error propagation. +# --------------------------------------------------------------------------- + + +async def test_fetch_raises_propagates() -> None: + """An exception raised by fetch propagates on the yield that produced the failing group.""" + fetch = FakeFetch( + _INDEXED_BLOB, + raise_on=lambda r: isinstance(r, RangeByteRequest) and r.start >= 100, + ) + opts: Mapping[str, int] = { + "max_gap_bytes": -1, + "max_coalesced_bytes": 1 << 20, + "max_concurrency": 1, + } + ranges: list[ByteRequest | None] = [RangeByteRequest(0, 10), RangeByteRequest(200, 210)] + with pytest.RaisesGroup(pytest.RaisesExc(OSError, match="injected")): + await _collect(coalesced_get(fetch, ranges, **opts)) + + +# --------------------------------------------------------------------------- +# Property-style coverage invariant. +# --------------------------------------------------------------------------- + + +async def test_coverage_invariant_random_inputs() -> None: + """For any random RangeByteRequest input, every input index appears exactly once.""" + import random + + rng = random.Random(42) + fetch = FakeFetch(_INDEXED_BLOB) + + ranges: list[ByteRequest | None] = [] + for _ in range(50): + start = rng.randint(0, 9000) + length = rng.randint(1, 500) + ranges.append(RangeByteRequest(start, start + length)) + + groups = await _collect(coalesced_get(fetch, ranges, **DEFAULT)) + seen: list[int] = [idx for group in groups for idx, _buf in group] + assert sorted(seen) == list(range(len(ranges))) + + flat = _contents(groups) + for i, r in enumerate(ranges): + assert isinstance(r, RangeByteRequest) + assert flat[i] == _INDEXED_BLOB[r.start : r.end] + + +# --------------------------------------------------------------------------- +# Pure-function tests for coalesce_ranges (no async, no fetch). +# --------------------------------------------------------------------------- + + +def test_coalesce_ranges_empty_input() -> None: + groups, uncoalescable = coalesce_ranges([], max_gap_bytes=1 << 20, max_coalesced_bytes=16 << 20) + assert groups == [] + assert uncoalescable == [] + + +def test_coalesce_ranges_separates_coalescable_from_uncoalescable() -> None: + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 10), + OffsetByteRequest(100), + SuffixByteRequest(5), + None, + RangeByteRequest(20, 30), + ] + groups, uncoalescable = coalesce_ranges(ranges, **_grouping(MERGE_GAP_50)) + + # Both range requests fall within MERGE_GAP_50's gap budget. + assert len(groups) == 1 + assert [idx for idx, _ in groups[0]] == [0, 4] + + # Non-RangeByteRequest entries preserve their original input indices. + assert [(idx, type(req).__name__ if req else None) for idx, req in uncoalescable] == [ + (1, "OffsetByteRequest"), + (2, "SuffixByteRequest"), + (3, None), + ] + + +def test_coalesce_ranges_no_merge_when_gap_exceeds_budget() -> None: + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 10), + RangeByteRequest(200, 210), + RangeByteRequest(500, 510), + ] + groups, uncoalescable = coalesce_ranges(ranges, **_grouping(MERGE_GAP_50)) + assert uncoalescable == [] + assert [len(g) for g in groups] == [1, 1, 1] + assert [idx for g in groups for idx, _ in g] == [0, 1, 2] + + +def test_coalesce_ranges_merges_within_gap_budget() -> None: + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 5), + RangeByteRequest(10, 15), + RangeByteRequest(20, 25), + ] + groups, _ = coalesce_ranges(ranges, **_grouping(MERGE_GAP_50)) + assert len(groups) == 1 + assert [idx for idx, _ in groups[0]] == [0, 1, 2] + + +def test_coalesce_ranges_respects_max_coalesced_bytes() -> None: + # Gap budget is permissive (1000), but the merged span would exceed CAP_50's + # 50-byte cap, so the second range starts a new group. + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 30), + RangeByteRequest(40, 80), + ] + groups, _ = coalesce_ranges(ranges, **_grouping(CAP_50)) + assert [len(g) for g in groups] == [1, 1] + + +def test_coalesce_ranges_groups_are_sorted_by_start() -> None: + """Input order is irrelevant; groups always emerge in start-offset order.""" + ranges: list[ByteRequest | None] = [ + RangeByteRequest(500, 510), + RangeByteRequest(0, 10), + RangeByteRequest(20, 30), + RangeByteRequest(200, 210), + ] + groups, _ = coalesce_ranges(ranges, **_grouping(MERGE_GAP_50)) + # First group is the {0-10, 20-30} cluster (from input indices 1, 2). + # Then the {200-210} singleton, then {500-510}. + flat = [idx for g in groups for idx, _ in g] + assert flat == [1, 2, 3, 0] + # Within each group, members are sorted by start. + for g in groups: + starts = [r.start for _, r in g] + assert starts == sorted(starts) + + +def test_coalesce_ranges_overlapping_ranges_merge() -> None: + """Nested/overlapping ranges have a non-positive 'gap' and always merge.""" + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 100), + RangeByteRequest(50, 60), # nested + RangeByteRequest(80, 120), # overlaps + ] + groups, _ = coalesce_ranges(ranges, **_grouping(MERGE_GAP_50)) + assert len(groups) == 1 + assert [idx for idx, _ in groups[0]] == [0, 1, 2] + + +def test_coalesce_ranges_running_end_handles_nesting() -> None: + """A subsequent range fully inside the running span must not extend group_end backwards.""" + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 1000), # group_end=1000 + RangeByteRequest(100, 200), # nested; group_end stays at 1000 + RangeByteRequest(990, 1010), # gap = -10 from running end, still merges + ] + groups, _ = coalesce_ranges(ranges, **_grouping(MERGE_GAP_50)) + assert len(groups) == 1 + assert {idx for idx, _ in groups[0]} == {0, 1, 2} + + +def test_coalesce_ranges_only_uncoalescable_inputs() -> None: + ranges: list[ByteRequest | None] = [None, OffsetByteRequest(10), SuffixByteRequest(5)] + groups, uncoalescable = coalesce_ranges( + ranges, max_gap_bytes=1 << 20, max_coalesced_bytes=16 << 20 + ) + assert groups == [] + assert [idx for idx, _ in uncoalescable] == [0, 1, 2] + + +def test_coalesce_ranges_total_index_coverage() -> None: + """Every input index appears exactly once across groups + uncoalescable.""" + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 10), + None, + RangeByteRequest(15, 25), + OffsetByteRequest(100), + RangeByteRequest(30, 40), + ] + groups, uncoalescable = coalesce_ranges(ranges, **_grouping(MERGE_GAP_50)) + seen = sorted([idx for g in groups for idx, _ in g] + [idx for idx, _ in uncoalescable]) + assert seen == list(range(len(ranges))) diff --git a/tests/test_codec_entrypoints.py b/tests/test_codec_entrypoints.py new file mode 100644 index 0000000000..69cd0a1577 --- /dev/null +++ b/tests/test_codec_entrypoints.py @@ -0,0 +1,32 @@ +import pytest + +import zarr.registry +from zarr import config + + +@pytest.mark.usefixtures("set_path") +@pytest.mark.parametrize("codec_name", ["TestEntrypointCodec", "TestEntrypointGroup.Codec"]) +def test_entrypoint_codec(codec_name: str) -> None: + config.set({"codecs.test": f"package_with_entrypoint.{codec_name}"}) + cls_test = zarr.registry.get_codec_class("test") + assert cls_test.__qualname__ == codec_name + + +@pytest.mark.usefixtures("set_path") +def test_entrypoint_pipeline() -> None: + config.set({"codec_pipeline.path": "package_with_entrypoint.TestEntrypointCodecPipeline"}) + cls = zarr.registry.get_pipeline_class() + assert cls.__name__ == "TestEntrypointCodecPipeline" + + +@pytest.mark.usefixtures("set_path") +@pytest.mark.parametrize("buffer_name", ["TestEntrypointBuffer", "TestEntrypointGroup.Buffer"]) +def test_entrypoint_buffer(buffer_name: str) -> None: + config.set( + { + "buffer": f"package_with_entrypoint.{buffer_name}", + "ndbuffer": "package_with_entrypoint.TestEntrypointNDBuffer", + } + ) + assert zarr.registry.get_buffer_class().__qualname__ == buffer_name + assert zarr.registry.get_ndbuffer_class().__name__ == "TestEntrypointNDBuffer" diff --git a/tests/test_codec_pipeline.py b/tests/test_codec_pipeline.py new file mode 100644 index 0000000000..b069792fd8 --- /dev/null +++ b/tests/test_codec_pipeline.py @@ -0,0 +1,323 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +pytest.importorskip("hypothesis") + +import hypothesis.strategies as st +from hypothesis import given + +import zarr +from zarr.codecs import BytesCodec, CastValue, GzipCodec, TransposeCodec +from zarr.core.array import _get_chunk_spec +from zarr.core.buffer.core import default_buffer_prototype +from zarr.core.codec_pipeline import codecs_from_list +from zarr.core.config import config as zarr_config +from zarr.core.indexing import BasicIndexer +from zarr.storage import MemoryStore + +if TYPE_CHECKING: + from collections.abc import Callable, Generator + + from zarr.abc.codec import Codec + + +@pytest.fixture(autouse=True) +def _enable_rectilinear_chunks() -> Generator[None]: + """Enable rectilinear chunks for all tests in this module.""" + with zarr_config.set({"array.rectilinear_chunks": True}): + yield + + +pipeline_paths = [ + "zarr.core.codec_pipeline.BatchedCodecPipeline", + "zarr.core.codec_pipeline.FusedCodecPipeline", +] + + +@pytest.fixture(params=pipeline_paths, ids=["batched", "sync"]) +def pipeline_class(request: pytest.FixtureRequest) -> Generator[str]: + """Temporarily set the codec pipeline class for the test.""" + path = request.param + with zarr_config.set({"codec_pipeline.path": path}): + yield path + + +# --------------------------------------------------------------------------- +# GetResult status tests (low-level pipeline API) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("write_slice", "read_slice", "expected_statuses"), + [ + (slice(None), slice(None), ("present", "present", "present")), + (slice(0, 2), slice(None), ("present", "missing", "missing")), + (None, slice(None), ("missing", "missing", "missing")), + ], +) +async def test_read_returns_get_results( + pipeline_class: str, + write_slice: slice | None, + read_slice: slice, + expected_statuses: tuple[str, ...], +) -> None: + """CodecPipeline.read returns GetResult with correct statuses.""" + store = MemoryStore() + arr = zarr.open_array(store, mode="w", shape=(6,), chunks=(2,), dtype="int64", fill_value=-1) + + if write_slice is not None: + arr[write_slice] = 0 + + async_arr = arr._async_array + pipeline = async_arr.codec_pipeline + metadata = async_arr.metadata + + prototype = default_buffer_prototype() + config = async_arr.config + indexer = BasicIndexer( + read_slice, + shape=metadata.shape, + chunk_grid=async_arr._chunk_grid, + ) + + out_buffer = prototype.nd_buffer.empty( + shape=indexer.shape, + dtype=metadata.dtype.to_native_dtype(), + order=config.order, + ) + + results = await pipeline.read( + [ + ( + async_arr.store_path / metadata.encode_chunk_key(chunk_coords), + _get_chunk_spec(metadata, async_arr._chunk_grid, chunk_coords, config, prototype), + chunk_selection, + out_selection, + is_complete_chunk, + ) + for chunk_coords, chunk_selection, out_selection, is_complete_chunk in indexer + ], + out_buffer, + drop_axes=indexer.drop_axes, + ) + + assert len(results) == len(expected_statuses) + for result, expected_status in zip(results, expected_statuses, strict=True): + assert result["status"] == expected_status + + +# --------------------------------------------------------------------------- +# write_empty_chunks / read_missing_chunks config tests +# --------------------------------------------------------------------------- + + +async def test_write_empty_chunks_false_no_store(pipeline_class: str) -> None: + """With write_empty_chunks=False, fill_value-only chunks should not be stored.""" + store: dict[str, Any] = {} + arr = zarr.create_array( + store=store, + shape=(20,), + dtype="float64", + chunks=(10,), + shards=None, + compressors=None, + fill_value=0.0, + config={"write_empty_chunks": False}, + ) + arr[:] = 0.0 # all fill_value + + # Chunks should NOT be persisted + assert "c/0" not in store + assert "c/1" not in store + + # But reading should still return fill values + np.testing.assert_array_equal(arr[:], np.zeros(20, dtype="float64")) + + +try: + import cast_value_rs # noqa: F401 + + _HAS_CAST_VALUE_RS = True +except ModuleNotFoundError: + _HAS_CAST_VALUE_RS = False + +requires_cast_value_rs = pytest.mark.skipif( + not _HAS_CAST_VALUE_RS, reason="cast-value-rs not installed" +) + + +@requires_cast_value_rs +@pytest.mark.parametrize( + ("source_dtype", "target_dtype"), + [ + # Source is single-byte (no endianness); target is multi-byte (has endianness). + # Without the fix, BytesCodec.evolve_from_array_spec sees the source dtype, + # strips its `endian` to None, and then chokes when the chunk_spec dtype + # gets transformed to the multi-byte target before bytes-decoding. + ("int8", "int16"), + ("uint8", "int32"), + ("int8", "float32"), + # Source is multi-byte; target is single-byte (the reverse direction also + # exercises the spec-threading logic). + ("int16", "int8"), + ], +) +def test_codec_pipeline_threads_dtype_through_evolve(source_dtype: str, target_dtype: str) -> None: + """Regression for #3937: each codec must be evolved against the spec it + will see at runtime, not the original array spec. cast_value transforms + the dtype between AA codecs and the array->bytes serializer.""" + arr = zarr.create_array( + store={}, + shape=(4,), + chunks=(4,), + dtype=source_dtype, + fill_value=0, + filters=[CastValue(data_type=target_dtype)], + serializer=BytesCodec(endian="little"), + compressors=[], + zarr_format=3, + overwrite=True, + ) + arr[:] = np.asarray([0, 1, 2, 3], dtype=source_dtype) + np.testing.assert_array_equal(arr[:], np.asarray([0, 1, 2, 3], dtype=source_dtype)) + + +def test_evolve_threads_spec_preserving_serializer_endian(pipeline_class: str) -> None: + """Regression for #3937, dependency-free variant. + + `evolve_from_array_spec` must thread the spec FORWARD through the codec chain: + each codec is evolved against the spec produced by the previous one, not the + original array spec. An array->array codec that widens the dtype from a + single-byte type (no endianness) to a multi-byte type means the BytesCodec + serializer must be evolved against the *widened* dtype β€” otherwise it sees + the single-byte source, strips its `endian` to None, and later fails to + decode the multi-byte data. + + The original regression test for this needs `cast_value_rs` (so it only runs + in the optional-deps CI job). This variant uses a minimal dtype-widening AA + codec stub, so it runs everywhere and on both pipelines via `pipeline_class`. + """ + from dataclasses import dataclass + + from zarr.abc.codec import ArrayArrayCodec + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.dtype import get_data_type_from_native_dtype + from zarr.registry import get_pipeline_class + + @dataclass(frozen=True) + class _WidenToInt16(ArrayArrayCodec): + """Test-only AA codec: reports the encoded dtype as int16 (no real encode).""" + + is_fixed_size = True + + def to_dict(self) -> dict[str, Any]: + return {"name": "_widen_to_int16"} + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> _WidenToInt16: + return cls() + + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + from dataclasses import replace + + return replace(chunk_spec, dtype=get_data_type_from_native_dtype(np.dtype("int16"))) + + def compute_encoded_size(self, input_byte_length: int, _spec: ArraySpec) -> int: + return input_byte_length + + async def _decode_single(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + return chunk_array # pragma: no cover + + async def _encode_single(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + return chunk_array # pragma: no cover + + zdtype = get_data_type_from_native_dtype(np.dtype("int8")) # single-byte source + spec = ArraySpec( + shape=(4,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=False), + prototype=default_buffer_prototype(), + ) + + from zarr.core.codec_pipeline import BatchedCodecPipeline, FusedCodecPipeline + + pipeline = get_pipeline_class().from_codecs((_WidenToInt16(), BytesCodec(endian="little"))) + evolved = pipeline.evolve_from_array_spec(spec) + # Both concrete pipelines expose `array_bytes_codec`; narrow off the ABC. + assert isinstance(evolved, (BatchedCodecPipeline, FusedCodecPipeline)) + serializer = evolved.array_bytes_codec + + # The serializer must keep its little-endian setting: it is evolved against + # the widened (int16) dtype, not the single-byte source. + assert isinstance(serializer, BytesCodec) + assert serializer.endian is not None, ( + "BytesCodec serializer lost its `endian` β€” evolve_from_array_spec did not " + "thread the dtype-widening AA codec's spec into the serializer" + ) + + +# Property-based check of codecs_from_list ordering validation. +# +# Valid codec orderings are exactly: (ArrayArrayCodec)* (ArrayBytesCodec) +# (BytesBytesCodec)*. codecs_from_list walks adjacent pairs and must raise +# TypeError the moment a codec appears in a structurally invalid position -- +# notably, a BytesBytesCodec immediately following an ArrayArrayCodec with no +# ArrayBytesCodec in between (which previously built an error message but never +# raised it, falling through to an unrelated ValueError instead). +_AA = "AA" # ArrayArrayCodec -> TransposeCodec +_AB = "AB" # ArrayBytesCodec -> BytesCodec +_BB = "BB" # BytesBytesCodec -> GzipCodec + +_CODEC_FACTORY: dict[str, Callable[[], Codec]] = { + _AA: lambda: TransposeCodec(order=(0, 1)), + _AB: BytesCodec, + _BB: GzipCodec, +} + + +def _expected_codec_order_outcome(labels: list[str]) -> str: + """Independently predict codecs_from_list's outcome: 'TypeError', + 'ValueError' or 'ok', mirroring its left-to-right scan and the order in + which it checks ordering violations (TypeError) vs. the ArrayBytes-count + constraints (ValueError).""" + prev = None + seen_array_bytes = False + for cur in labels: + if cur == _AA: + if prev in (_AB, _BB): + return "TypeError" + elif cur == _AB: + if prev == _BB: + return "TypeError" + if seen_array_bytes: + return "ValueError" # two ArrayBytesCodecs + seen_array_bytes = True + else: # _BB + if prev == _AA: + return "TypeError" + prev = cur + if not seen_array_bytes: + return "ValueError" # Required ArrayBytesCodec was not found + return "ok" + + +@given(labels=st.lists(st.sampled_from([_AA, _AB, _BB]), min_size=1, max_size=5)) +def test_codecs_from_list_outcome_matches_order_rules(labels: list[str]) -> None: + codecs = [_CODEC_FACTORY[label]() for label in labels] + expected = _expected_codec_order_outcome(labels) + if expected == "TypeError": + with pytest.raises(TypeError): + codecs_from_list(codecs) + elif expected == "ValueError": + with pytest.raises(ValueError): + codecs_from_list(codecs) + else: + # Valid ordering: must classify without raising. + aa, _ab, bb = codecs_from_list(codecs) + assert labels.count(_AA) == len(aa) + assert labels.count(_BB) == len(bb) diff --git a/tests/test_codec_pipeline_suite.py b/tests/test_codec_pipeline_suite.py new file mode 100644 index 0000000000..f0376d185a --- /dev/null +++ b/tests/test_codec_pipeline_suite.py @@ -0,0 +1,590 @@ +"""Shared codec-pipeline behavior suite, run against EVERY codec pipeline. + +The defining property of a codec pipeline is that the array semantics it +produces must be identical no matter which pipeline is configured. To make +"one pipeline diverges from the others" structurally hard to ship, every +pipeline-agnostic behavior test lives as a method on ``CodecPipelineTests`` and +is instantiated once per pipeline (``TestBatchedPipeline`` / ``TestFusedPipeline``). + +Each test also runs over a *store axis* that exercises both code paths the +synchronous pipelines branch on: + +* ``sync`` -> ``MemoryStore`` (full sync surface: fast path) +* ``async`` -> ``_NoSyncIOStore(MemoryStore())`` (NOT sync-capable: async fallback) + +The async axis is deliberate: a regression that only affects the async fallback +of the default pipeline (e.g. a codec-spec-evolution bug that surfaces only on +remote stores) is invisible if every test runs on MemoryStore. Running the same +battery over a non-sync store closes that gap. + +Pipeline-specific tests (construction, ``from_codecs``, the byte-range write +fast path, etc.) stay in their own modules; only behavior that ALL pipelines +must share belongs here. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +import numcodecs +import numpy as np +import pytest + +import zarr +from zarr.codecs import BytesCodec, GzipCodec, ShardingCodec, TransposeCodec +from zarr.core.config import config as zarr_config +from zarr.errors import ChunkNotFoundError +from zarr.storage import MemoryStore +from zarr.testing.store import LatencyStore + +if TYPE_CHECKING: + from collections.abc import Iterator + + from zarr.abc.store import Store + from zarr.codecs.sharding import SubchunkWriteOrder + + +# --- store axis: a sync store and a non-sync (async-fallback) store ---------- + +STORE_KINDS = ["sync", "async"] + + +class _NoSyncIOStore(LatencyStore): + """An in-memory store that advertises no sync IO capability, so a + synchronous pipeline must fall back to its async path. (A plain wrapper + won't do: `WrapperStore` forwards the wrapped store's sync capability.)""" + + @property + def _supports_sync_io(self) -> bool: + return False + + +def _make_store(kind: str) -> Store: + if kind == "sync": + # MemoryStore supports get_sync/set_sync -> synchronous fast path. + return MemoryStore() + if kind == "async": + return _NoSyncIOStore(MemoryStore(), get_latency=0.0, set_latency=0.0) + raise AssertionError(kind) + + +# --- scenario model ---------------------------------------------------------- +# +# Most pipeline behavior tests have one shape: +# create an array, apply some writes, (optionally) assert which chunk keys +# exist, then assert reads come back correct. A Scenario captures exactly those +# variables so one parametrized test covers them all. Correctness is checked +# against a numpy reference array that the scenario mutates in lock-step with +# the zarr array, so cases don't hand-maintain expected values. + + +@dataclass(frozen=True) +class Scenario: + id: str + array_kwargs: dict[str, Any] + # (selection, value) writes applied in order. value may be a scalar or array. + writes: tuple[tuple[Any, Any], ...] = () + # selections to read back and check against the reference. () means "read all". + reads: tuple[Any, ...] = (slice(None),) + # substrings of chunk keys that must be present / absent after the writes. + # Only checked on the sync store (key layout is identical across stores, but + # we keep it to one axis to avoid asserting store internals twice). + keys_present: tuple[str, ...] = () + keys_absent: tuple[str, ...] = () + + def reference(self) -> np.ndarray: + """The numpy array the scenario's writes should produce, starting from + the array's fill value.""" + kw = self.array_kwargs + shape = kw["shape"] + dtype = np.dtype(kw["dtype"]) + fill = kw.get("fill_value", 0) + ref = np.full(shape, fill, dtype=dtype) + for sel, value in self.writes: + ref[sel] = value + return ref + + +def _val(n: int, dtype: str, offset: int = 1) -> np.ndarray: + return np.arange(offset, offset + n, dtype=dtype) + + +# Common dtype/chunk presets reused below. +_F64 = {"dtype": "float64", "fill_value": 0.0} +_I32 = {"dtype": "int32", "fill_value": -1} + +SCENARIOS: tuple[Scenario, ...] = ( + # --- full-array roundtrips across layouts/codecs ------------------------ + Scenario( + "1d-unsharded-roundtrip", + {"shape": (100,), "chunks": (10,), "shards": None, "compressors": None, **_F64}, + writes=((slice(None), _val(100, "float64")),), + ), + Scenario( + "1d-sharded-roundtrip", + {"shape": (100,), "chunks": (10,), "shards": (100,), "compressors": None, **_F64}, + writes=((slice(None), _val(100, "float64")),), + ), + Scenario( + "1d-multi-chunk-shard-roundtrip", + {"shape": (100,), "chunks": (10,), "shards": (50,), "compressors": None, **_F64}, + writes=((slice(None), _val(100, "float64")),), + ), + Scenario( + "2d-unsharded-roundtrip", + {"shape": (10, 20), "chunks": (5, 10), "shards": None, "compressors": None, **_I32}, + writes=((slice(None), np.arange(200, dtype="int32").reshape(10, 20)),), + ), + Scenario( + "2d-sharded-roundtrip", + {"shape": (20, 20), "chunks": (5, 5), "shards": (10, 10), "compressors": None, **_I32}, + writes=((slice(None), np.arange(400, dtype="int32").reshape(20, 20)),), + ), + Scenario( + "1d-gzip-roundtrip", + { + "shape": (100,), + "chunks": (10,), + "shards": None, + "compressors": {"name": "gzip", "configuration": {"level": 1}}, + **_F64, + }, + writes=((slice(None), _val(100, "float64")),), + ), + Scenario( + "1d-zstd-roundtrip", + { + "shape": (100,), + "chunks": (10,), + "shards": None, + "compressors": {"name": "zstd", "configuration": {"level": 1}}, + **_F64, + }, + writes=((slice(None), _val(100, "float64")),), + ), + Scenario( + "1d-float32-roundtrip", + { + "shape": (50,), + "chunks": (10,), + "shards": None, + "compressors": None, + "dtype": "float32", + "fill_value": 0.0, + }, + writes=((slice(None), _val(50, "float32")),), + ), + # zarr v2 goes through the V2Codec wrapper (filters + compressor), a + # different codec path than the v3 AA/AB/BB chain β€” and a different sync + # implementation under FusedCodecPipeline. Without these scenarios, v2 was + # only exercised implicitly via whichever pipeline is the global default. + Scenario( + "v2-roundtrip", + { + "shape": (100,), + "chunks": (10,), + "shards": None, + "compressors": None, + "zarr_format": 2, + **_F64, + }, + writes=((slice(None), _val(100, "float64")),), + ), + Scenario( + "v2-gzip-roundtrip", + { + "shape": (100,), + "chunks": (10,), + "shards": None, + "compressors": numcodecs.GZip(level=1), + "zarr_format": 2, + **_F64, + }, + writes=((slice(None), _val(100, "float64")),), + ), + # v2 filters are the other half of the V2Codec wrapper (numcodecs + # array->array filters, a distinct branch from the compressor in + # _encode_sync/_decode_sync). + Scenario( + "v2-filter-gzip-roundtrip", + { + "shape": (100,), + "chunks": (10,), + "shards": None, + "filters": numcodecs.Delta(dtype="float64"), + "compressors": numcodecs.GZip(level=1), + "zarr_format": 2, + **_F64, + }, + writes=((slice(None), _val(100, "float64")),), + ), + # --- read unwritten chunks -> fill value -------------------------------- + Scenario( + "missing-chunks-fill", + { + "shape": (100,), + "chunks": (10,), + "shards": None, + "compressors": None, + "dtype": "float64", + "fill_value": -7.0, + }, + writes=(), + ), + Scenario( + "missing-chunks-fill-sharded", + { + "shape": (100,), + "chunks": (10,), + "shards": (100,), + "compressors": None, + "dtype": "float64", + "fill_value": -7.0, + }, + writes=(), + ), + # --- partial write, varied read selections ------------------------------ + Scenario( + "partial-write-full-read", + {"shape": (100,), "chunks": (10,), "shards": None, "compressors": None, **_F64}, + writes=((slice(5, 15), _val(10, "float64")),), + reads=(slice(None),), + ), + Scenario( + "full-write-strided-read", + {"shape": (100,), "chunks": (10,), "shards": None, "compressors": None, **_F64}, + writes=((slice(None), _val(100, "float64")),), + reads=(np.s_[::3], np.s_[10:20]), + ), + Scenario( + "partial-write-partial-read-sharded", + {"shape": (100,), "chunks": (10,), "shards": (100,), "compressors": None, **_F64}, + writes=((slice(20, 70), _val(50, "float64")),), + reads=(np.s_[30:60], slice(None)), + ), + # scalar single-element reads from a sharded array hit the sharding codec's + # partial-decode path (_decode_partial_single), distinct from slice reads. + Scenario( + "sharded-scalar-reads-1d", + {"shape": (100,), "chunks": (10,), "shards": (50,), "compressors": None, **_F64}, + writes=((slice(None), _val(100, "float64")),), + reads=(np.s_[0], np.s_[50], np.s_[99], np.s_[::3]), + ), + Scenario( + "sharded-scalar-reads-2d", + {"shape": (20, 20), "chunks": (5, 5), "shards": (10, 10), "compressors": None, **_I32}, + writes=((slice(None), np.arange(400, dtype="int32").reshape(20, 20)),), + reads=(np.s_[0, 0], np.s_[10, 10], np.s_[19, 19]), + ), + # --- spec-changing codec (transpose): the async-spec-evolution guard ---- + Scenario( + "transpose", + { + "shape": (8, 12), + "chunks": (2, 4), + "shards": None, + "filters": [TransposeCodec(order=(1, 0))], + "serializer": BytesCodec(), + **_I32, + }, + writes=((slice(None), np.arange(96, dtype="int32").reshape(8, 12)),), + reads=(slice(None), np.s_[1:7, 2:10]), + ), + Scenario( + "transpose-gzip", + { + "shape": (8, 12), + "chunks": (2, 4), + "shards": None, + "filters": [TransposeCodec(order=(1, 0))], + "serializer": BytesCodec(), + "compressors": GzipCodec(level=1), + **_I32, + }, + writes=((slice(None), np.arange(96, dtype="int32").reshape(8, 12)),), + reads=(slice(None), np.s_[1:7, 2:10]), + ), + # --- nested sharding ---------------------------------------------------- + Scenario( + "nested-sharding", + { + "shape": (20, 20), + "chunks": (10, 10), + "shards": None, + "compressors": None, + **_I32, + "fill_value": 0, + "serializer": ShardingCodec( + chunk_shape=(10, 10), codecs=[ShardingCodec(chunk_shape=(5, 5))] + ), + }, + writes=((slice(None), np.arange(400, dtype="int32").reshape(20, 20)),), + ), + # --- partial overwrite of an existing shard (merge) --------------------- + Scenario( + "partial-shard-overwrite", + { + "shape": (40,), + "chunks": (4,), + "shards": (40,), + "compressors": None, + **_I32, + "config": {"write_empty_chunks": True}, + }, + writes=( + (slice(None), np.arange(40, dtype="int32")), + (slice(7, 18), _val(11, "int32", 700)), + ), + ), + # --- write_empty_chunks: storage-key presence/absence ------------------- + Scenario( + "write-empty-false-omits-fill-chunk", + { + "shape": (20,), + "chunks": (10,), + "shards": None, + "compressors": None, + **_F64, + "config": {"write_empty_chunks": False}, + }, + writes=((slice(0, 10), _val(10, "float64")), (slice(10, 20), np.zeros(10, "float64"))), + keys_present=("c/0",), + keys_absent=("c/1",), + ), + Scenario( + "write-empty-true-persists-fill-chunk", + { + "shape": (20,), + "chunks": (10,), + "shards": None, + "compressors": None, + **_F64, + "config": {"write_empty_chunks": True}, + }, + writes=((slice(None), np.zeros(20, "float64")),), + keys_present=("c/0", "c/1"), + ), + # default config (no explicit write_empty_chunks) must still skip fill chunks + Scenario( + "default-config-omits-fill-chunk", + {"shape": (20,), "chunks": (10,), "shards": None, "compressors": None, **_F64}, + writes=((slice(10, 20), np.zeros(10, "float64")),), + keys_absent=("c/1",), + ), +) + + +class CodecPipelineTests: + """Behavior every codec pipeline must satisfy, on sync and async stores. + + Subclasses set ``pipeline_path`` to the fully-qualified pipeline class. + """ + + pipeline_path: str + + @pytest.fixture(autouse=True) + def _use_pipeline(self) -> Iterator[None]: + with zarr_config.set({"codec_pipeline.path": self.pipeline_path}): + yield + + @pytest.fixture(params=STORE_KINDS) + def store(self, request: pytest.FixtureRequest) -> Store: + return _make_store(request.param) + + @staticmethod + def _chunk_keys(store: Store) -> set[str]: + """All non-metadata keys currently in the store (v3 and v2 metadata).""" + import asyncio + + def _is_metadata(key: str) -> bool: + tail = key.rsplit("/", 1)[-1] + return tail in ("zarr.json", ".zarray", ".zattrs", ".zgroup", ".zmetadata") + + async def _list() -> set[str]: + return {k async for k in store.list() if not _is_metadata(k)} + + return asyncio.run(_list()) + + # -- the common shape: create -> write -> [assert keys] -> assert reads ---- + + @pytest.mark.parametrize("scenario", SCENARIOS, ids=lambda s: s.id) + def test_scenario(self, store: Store, scenario: Scenario) -> None: + """Create an array, apply the scenario's writes, optionally assert which + chunk keys exist, then assert each read selection matches a numpy + reference. Run against every pipeline (subclass) and store kind (fixture). + """ + arr = zarr.create_array(store=store, **scenario.array_kwargs) + for sel, value in scenario.writes: + arr[sel] = value + + ref = scenario.reference() + for sel in scenario.reads: + np.testing.assert_array_equal( + arr[sel], ref[sel], err_msg=f"{scenario.id}: read {sel!r} mismatch" + ) + + if scenario.keys_present or scenario.keys_absent: + keys = self._chunk_keys(store) + for present in scenario.keys_present: + assert any(present in k for k in keys), (present, keys) + for absent in scenario.keys_absent: + assert not any(absent in k for k in keys), (absent, keys) + + # -- outliers that don't fit the create/write/read scenario shape ---------- + + def test_read_missing_chunks_false_raises(self, store: Store) -> None: + """read_missing_chunks=False makes reading an unwritten chunk an error, + not a fill β€” a different assertion (raises) than the scenario shape.""" + arr = zarr.create_array( + store=store, + shape=(20,), + dtype="float64", + chunks=(10,), + shards=None, + compressors=None, + fill_value=0.0, + config={"read_missing_chunks": False}, + ) + with pytest.raises(ChunkNotFoundError): + arr[:] + + def test_read_missing_chunks_false_sharded_semantics(self, store: Store) -> None: + """read_missing_chunks=False is a STORE-KEY-level promise on sharded arrays. + + The config exists to help consumers distinguish a transport error from a + truly missing chunk. That distinction applies to store keys: a missing + SHARD key raises ChunkNotFoundError. It does not cleanly apply to inner + subchunks of a shard that was fetched successfully β€” there is no + transport ambiguity there, the shard index simply records the subchunk + as absent β€” so missing inner subchunks fill with the fill value rather + than raising. This pins that asymmetry as intentional. + """ + arr = zarr.create_array( + store=store, + shape=(100,), + dtype="float64", + chunks=(10,), + shards=(50,), + compressors=None, + fill_value=-1.0, + config={"read_missing_chunks": False}, + ) + # No shard key exists yet: reading is a missing-store-key error. + with pytest.raises(ChunkNotFoundError): + arr[:] + + # Write one inner chunk of the first shard. The shard key now exists, + # but most inner subchunks are absent from its index. + arr[20:30] = np.arange(10, dtype="float64") + + # Reading across written + absent inner subchunks of the EXISTING shard + # fills rather than raises. + out = arr[15:35] + expected = np.full(20, -1.0) + expected[5:15] = np.arange(10, dtype="float64") + np.testing.assert_array_equal(out, expected) + + # Both halves of the asymmetry in ONE read against the SAME partially + # written array: shard 0 exists (absent subchunks fill), shard 1 has no + # store key (raises) β€” pins that the raise still fires once some shard + # exists, and not only on a fully-empty array. + with pytest.raises(ChunkNotFoundError): + arr[:] + with pytest.raises(ChunkNotFoundError): + arr[45:55] # spans the existing and the missing shard + + @pytest.mark.parametrize("subchunk_write_order", ["morton", "lexicographic", "colexicographic"]) + def test_partial_write_after_reopen_is_correct( + self, store: Store, subchunk_write_order: SubchunkWriteOrder + ) -> None: + """Has an extra step the scenario shape lacks β€” a REOPEN between writes. + + Reopening a sharded array and partially overwriting it must read back + correctly regardless of the original subchunk_write_order. subchunk_write_ + order is intentionally NOT recoverable on reopen, so chunk locations on a + write to an existing shard must come from the STORED shard index, not the + (now-default) live order. A non-square inner grid makes the orders + physically distinct, so a wrong offset would corrupt data and fail here. + """ + shape, shard, inner = (6, 4), (6, 4), (2, 2) + arr = zarr.create_array( + store=store, + shape=shape, + dtype="int32", + chunks=shard, + fill_value=-1, + compressors=None, + config={"write_empty_chunks": True}, + serializer=ShardingCodec( + chunk_shape=inner, codecs=[BytesCodec()], subchunk_write_order=subchunk_write_order + ), + ) + ref = np.arange(24, dtype="int32").reshape(shape) + arr[:] = ref + + reopened = zarr.open_array(store=store, mode="r+") + reopened[1:5, 0:3] = 777 # partial overwrite into the existing shard + ref[1:5, 0:3] = 777 + np.testing.assert_array_equal(reopened[:], ref) + + def test_empty_shard_deleted_after_overwrite_to_fill(self, store: Store) -> None: + """A shard written with real data and then fully overwritten back to the + fill value must have its store key deleted, not left as a stale blob. + + This has a mid-sequence key assertion (present after write 1, absent + after write 2) that the create/write/read scenario shape can't express. + """ + arr = zarr.create_array( + store=store, + shape=(16,), + chunks=(4,), + shards=(8,), + dtype="float64", + compressors=None, + fill_value=0.0, + ) + arr[0:8] = np.arange(8, dtype="float64") + 1 + assert any("c/0" in k for k in self._chunk_keys(store)) + arr[0:8] = 0.0 + assert not any("c/0" in k for k in self._chunk_keys(store)), ( + "shard should be deleted when fully overwritten to fill value" + ) + + def test_read_write_methods_do_not_branch_on_sharding_codec_type(self) -> None: + """Pipeline read/write must dispatch on supports_partial_encode/decode, + not isinstance(ShardingCodec) β€” a static guard against type-branching. + + Scoped to this pipeline's own read/write methods (other helpers, e.g. + metadata validation, may legitimately isinstance-check ShardingCodec). + """ + import inspect + import re + + from zarr.registry import get_pipeline_class + + # The autouse _use_pipeline fixture has set codec_pipeline.path to this + # subclass's pipeline; resolve the class it points at and guard that. + # reload_config=False so the fixture's config override is honored + # (reload_config=True re-reads the base config, ignoring the override). + cls = get_pipeline_class(reload_config=False) + + pattern = re.compile(r"isinstance\s*\([^)]*ShardingCodec[^)]*\)") + for method_name in ("read", "write", "read_sync", "write_sync"): + method = getattr(cls, method_name, None) + if method is None: + continue + matches = pattern.findall(inspect.getsource(method)) + assert not matches, ( + f"{cls.__name__}.{method_name} contains an isinstance check on " + f"ShardingCodec; use supports_partial_encode/decode instead. " + f"Matches: {matches}" + ) + + +class TestBatchedPipeline(CodecPipelineTests): + pipeline_path = "zarr.core.codec_pipeline.BatchedCodecPipeline" + + +class TestFusedPipeline(CodecPipelineTests): + pipeline_path = "zarr.core.codec_pipeline.FusedCodecPipeline" diff --git a/tests/test_codecs/__init__.py b/tests/test_codecs/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_codecs/test_blosc.py b/tests/test_codecs/test_blosc.py new file mode 100644 index 0000000000..e342dba8bb --- /dev/null +++ b/tests/test_codecs/test_blosc.py @@ -0,0 +1,275 @@ +import enum +import json +import warnings +from typing import Any, cast + +import numcodecs +import numpy as np +import pytest +from packaging.version import Version + +import zarr +from zarr.abc.codec import SupportsSyncCodec +from zarr.codecs import BloscCodec +from zarr.codecs.blosc import ( + BLOSC_CNAME, + BLOSC_SHUFFLE, + BloscCname, + BloscCnameLiteral, + BloscShuffle, + BloscShuffleLiteral, +) +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import default_buffer_prototype +from zarr.core.dtype import UInt16, get_data_type_from_native_dtype +from zarr.storage import MemoryStore, StorePath + + +@pytest.mark.parametrize("dtype", ["uint8", "uint16"]) +async def test_blosc_evolve(dtype: str) -> None: + typesize = np.dtype(dtype).itemsize + path = "blosc_evolve" + store = MemoryStore() + spath = StorePath(store, path) + zarr.create_array( + spath, + shape=(16, 16), + chunks=(16, 16), + dtype=dtype, + fill_value=0, + compressors=BloscCodec(), + ) + buf = await store.get(f"{path}/zarr.json", prototype=default_buffer_prototype()) + assert buf is not None + zarr_json = json.loads(buf.to_bytes()) + blosc_configuration_json = zarr_json["codecs"][1]["configuration"] + assert blosc_configuration_json["typesize"] == typesize + if typesize == 1: + assert blosc_configuration_json["shuffle"] == "bitshuffle" + else: + assert blosc_configuration_json["shuffle"] == "shuffle" + + path2 = "blosc_evolve_sharding" + spath2 = StorePath(store, path2) + zarr.create_array( + spath2, + shape=(16, 16), + chunks=(16, 16), + shards=(16, 16), + dtype=dtype, + fill_value=0, + compressors=BloscCodec(), + ) + buf = await store.get(f"{path2}/zarr.json", prototype=default_buffer_prototype()) + assert buf is not None + zarr_json = json.loads(buf.to_bytes()) + blosc_configuration_json = zarr_json["codecs"][0]["configuration"]["codecs"][1]["configuration"] + assert blosc_configuration_json["typesize"] == typesize + if typesize == 1: + assert blosc_configuration_json["shuffle"] == "bitshuffle" + else: + assert blosc_configuration_json["shuffle"] == "shuffle" + + +@pytest.mark.parametrize("shuffle", [None, "bitshuffle", "legacy-enum"]) +@pytest.mark.parametrize("typesize", [None, 1, 2]) +def test_tunable_attrs_param( + shuffle: BloscShuffleLiteral | str | None, typesize: int | None +) -> None: + """ + Test that the tunable_attrs parameter is set as expected when creating a BloscCodec. + """ + # Materialize BloscShuffle.shuffle via the deprecation shim without + # contaminating the BloscCodec construction below with that warning. + if shuffle == "legacy-enum": + with pytest.warns(DeprecationWarning, match="BloscShuffle.shuffle"): + shuffle_arg: BloscShuffleLiteral | str | None = BloscShuffle.shuffle + else: + shuffle_arg = shuffle + + codec = BloscCodec(typesize=typesize, shuffle=cast(BloscShuffleLiteral | None, shuffle_arg)) + + if shuffle_arg is None: + assert codec.shuffle == "bitshuffle" # default shuffle + assert "shuffle" in codec._tunable_attrs + if typesize is None: + assert codec.typesize == 1 # default typesize + assert "typesize" in codec._tunable_attrs + + new_dtype = UInt16() + array_spec = ArraySpec( + shape=(1,), + dtype=new_dtype, + fill_value=1, + prototype=default_buffer_prototype(), + config=cast(ArrayConfig, {}), + ) + + evolved_codec = codec.evolve_from_array_spec(array_spec=array_spec) + if typesize is None: + assert evolved_codec.typesize == new_dtype.item_size + else: + assert evolved_codec.typesize == codec.typesize + if shuffle_arg is None: + assert evolved_codec.shuffle == "shuffle" + else: + assert evolved_codec.shuffle == codec.shuffle + + +async def test_typesize() -> None: + a = np.arange(1000000, dtype=np.uint64) + codecs = [zarr.codecs.BytesCodec(), zarr.codecs.BloscCodec()] + z = zarr.array(a, chunks=(10000), codecs=codecs) + data = await z.store.get("c/0", prototype=default_buffer_prototype()) + assert data is not None + bytes = data.to_bytes() + size = len(bytes) + msg = f"Blosc size mismatch. First 10 bytes: {bytes[:20]!r} and last 10 bytes: {bytes[-20:]!r}" + if Version(numcodecs.__version__) >= Version("0.16.0"): + expected_size = 402 + assert size == expected_size, msg + else: + expected_size = 10216 + assert size == expected_size, msg + + +def test_blosc_codec_supports_sync() -> None: + assert isinstance(BloscCodec(), SupportsSyncCodec) + + +def test_blosc_codec_sync_roundtrip() -> None: + codec = BloscCodec(typesize=8) + arr = np.arange(100, dtype="float64") + zdtype = get_data_type_from_native_dtype(arr.dtype) + spec = ArraySpec( + shape=arr.shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + buf = default_buffer_prototype().buffer.from_array_like(arr.view("B")) + + encoded = codec._encode_sync(buf, spec) + assert encoded is not None + decoded = codec._decode_sync(encoded, spec) + result = np.frombuffer(decoded.as_numpy_array(), dtype="float64") + np.testing.assert_array_equal(arr, result) + + +@pytest.mark.parametrize("cname", BLOSC_CNAME) +def test_blosc_codec_accepts_all_cnames(cname: BloscCnameLiteral) -> None: + """ + Every compressor name in BLOSC_CNAME is accepted by BloscCodec and round-trips + to the same value on the stored attribute. Adding a new value to the + BloscCnameLiteral type alias without also adding it to BLOSC_CNAME (or vice + versa) is caught here. + """ + codec = BloscCodec(cname=cname) + assert codec.cname == cname + + +@pytest.mark.parametrize("shuffle", BLOSC_SHUFFLE) +def test_blosc_codec_accepts_all_shuffles(shuffle: BloscShuffleLiteral) -> None: + """ + Every shuffle mode in BLOSC_SHUFFLE is accepted by BloscCodec and round-trips + to the same value on the stored attribute. Adding a new value to the + BloscShuffleLiteral type alias without also adding it to BLOSC_SHUFFLE (or + vice versa) is caught here. + """ + codec = BloscCodec(shuffle=shuffle) + assert codec.shuffle == shuffle + + +@pytest.mark.parametrize("shuffle", BLOSC_SHUFFLE) +@pytest.mark.parametrize("cname", BLOSC_CNAME) +def test_blosc_codec_json_roundtrip(cname: BloscCnameLiteral, shuffle: BloscShuffleLiteral) -> None: + """ + JSON serialization (to_dict / from_dict) preserves every (cname, shuffle) + pair drawn from BLOSC_CNAME x BLOSC_SHUFFLE. Guards against drift in the + codec's V3 JSON form for any combination of compressor and shuffle option. + + The non-varied fields are fully specified so the codec has no tunable + attributes; tunability is not part of the JSON form and would otherwise + cause spurious round-trip mismatches. + """ + codec = BloscCodec(typesize=1, cname=cname, clevel=5, shuffle=shuffle, blocksize=0) + restored = BloscCodec.from_dict(codec.to_dict()) + assert restored == codec + + +@pytest.mark.parametrize( + ("enum_cls", "member", "expected"), + [ + (BloscShuffle, "shuffle", "shuffle"), + (BloscCname, "zstd", "zstd"), + ], +) +def test_blosc_enum_member_access_warns(enum_cls: type, member: str, expected: str) -> None: + """ + Accessing a member on the deprecated BloscShuffle / BloscCname classes + emits a DeprecationWarning and resolves to the equivalent literal string. + """ + match = f"{enum_cls.__name__}.{member}" + with pytest.warns(DeprecationWarning, match=match): + value = getattr(enum_cls, member) + assert value == expected + + +def test_blosc_enum_classes_import_silently() -> None: + """ + Importing the deprecated enum classes by name must not emit a warning; + only member access does. This guards against the blosc module accidentally + triggering its own deprecation warnings when it (or zarr) is imported. + """ + with warnings.catch_warnings(): + warnings.simplefilter("error") + from zarr.codecs.blosc import BloscCname as _BloscCname # noqa: F401 + from zarr.codecs.blosc import BloscShuffle as _BloscShuffle # noqa: F401 + + +def test_blosc_codec_init_with_enum_instance_warns() -> None: + """ + Passing a real `enum.Enum` instance to BloscCodec.__init__ (e.g. an + instance materialized before the deprecation shim was introduced) must + trigger the init-level deprecation warning and still normalize the value + to the corresponding literal string. + """ + + class LegacyShuffle(enum.Enum): + bitshuffle = "bitshuffle" + + class LegacyCname(enum.Enum): + zstd = "zstd" + + with pytest.warns(DeprecationWarning, match="enum"): + codec = BloscCodec( + cname=cast(BloscCname, LegacyCname.zstd), + shuffle=cast(BloscShuffle, LegacyShuffle.bitshuffle), + ) + assert codec.cname == "zstd" + assert codec.shuffle == "bitshuffle" + + +@pytest.mark.parametrize("param", ["cname", "shuffle"]) +def test_blosc_codec_rejects_unknown(param: str) -> None: + """ + BloscCodec.__init__ raises ValueError when given a string outside the + allowed set for `cname` or `shuffle`, and the error message names the + offending parameter. + """ + kwargs: dict[str, Any] = {param: f"not-a-{param}"} + with pytest.raises(ValueError, match=f"{param} must be one of"): + BloscCodec(**kwargs) + + +@pytest.mark.parametrize("enum_cls", [BloscShuffle, BloscCname]) +def test_blosc_enum_attribute_error_for_unknown_member(enum_cls: type) -> None: + """ + Attribute access for a name that is not a known member of the deprecated + enum classes falls through to AttributeError, matching the behavior of a + regular class. + """ + unknown_name = "not_a_member" + with pytest.raises(AttributeError): + getattr(enum_cls, unknown_name) diff --git a/tests/test_codecs/test_bytes.py b/tests/test_codecs/test_bytes.py new file mode 100644 index 0000000000..ead778f526 --- /dev/null +++ b/tests/test_codecs/test_bytes.py @@ -0,0 +1,340 @@ +"""Tests for `BytesCodec` and the deprecation of the `Endian` enum.""" + +from __future__ import annotations + +import enum +import sys +import warnings +from typing import TYPE_CHECKING, Any, Literal, cast + +import numpy as np +import pytest + +import zarr +from tests.conftest import Expect, ExpectFail +from zarr.abc.codec import SupportsSyncCodec +from zarr.codecs.bytes import ( + ENDIAN, + BytesCodec, + Endian, + EndianLiteral, +) +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import NDBuffer, default_buffer_prototype +from zarr.core.dtype import get_data_type_from_native_dtype +from zarr.core.dtype.npy.int import Int8, Int32 +from zarr.core.dtype.npy.structured import Struct +from zarr.storage import StorePath + +from .test_codecs import _AsyncArrayProxy + +if TYPE_CHECKING: + from zarr.abc.store import Store + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +@pytest.mark.parametrize( + "input_dtype", + [ + ">u2", + "f4"), ("mask", ">i4")], + [("flux", " None: + """ + The `bytes` codec stores multi-byte data in the byte order configured on the + codec, regardless of the input array's byte order, and reads it back to the + original values. For structured dtypes this applies to every multi-byte + field, per the `struct` data type spec; the struct cases guard against the + endianness bugs from + https://github.com/zarr-developers/zarr-python/issues/4141, where the + encode path never byte-swapped struct fields (numpy reports byteorder '|' + for void dtypes) and the decode path ignored the codec's endian entirely. + The input-dtype/store-endian cross-product exercises the encode-side + byteswap (input byte order != store byte order) and the no-op case alike. + Compression is disabled so the stored chunk is the codec's raw output and + its byte layout can be asserted directly. + """ + dtype = np.dtype(input_dtype) + if dtype.fields is None: + data = np.arange(0, 256, dtype=dtype).reshape((16, 16)) + else: + data = np.zeros((16, 16), dtype=dtype) + data["flux"] = np.arange(0, 256).reshape((16, 16)) + data["mask"] = np.arange(256, 512).reshape((16, 16)) + path = "endian" + spath = StorePath(store, path) + a = await zarr.api.asynchronous.create_array( + spath, + shape=data.shape, + chunks=(16, 16), + dtype=dtype, + fill_value=0, + compressors=None, + serializer=BytesCodec(endian=store_endian), + ) + + await _AsyncArrayProxy(a)[:, :].set(data) + + # The stored chunk is laid out in the byte order configured on the codec. + stored = await store.get(f"{path}/c/0/0", prototype=default_buffer_prototype()) + assert stored is not None + assert stored.to_bytes() == data.astype(dtype.newbyteorder(store_endian)).tobytes() + + # ... and the data reads back to the original values. + readback_data = await _AsyncArrayProxy(a)[:, :].get() + assert np.array_equal(data, readback_data) + + +def test_bytes_codec_supports_sync() -> None: + assert isinstance(BytesCodec(), SupportsSyncCodec) + + +@pytest.mark.parametrize("endian", ENDIAN) +@pytest.mark.parametrize( + "native_dtype", + [np.dtype("float64"), np.dtype(">u2"), np.dtype([("a", ">f4"), ("b", " None: + """ + The synchronous encode/decode path round-trips data, and the two byte + orders involved are independent: the codec's `endian` configuration governs + only the stored byte layout (every multi-byte value, including struct + fields, is laid out in the codec's byte order regardless of the input + array's byte order), while the decoded buffer's byte order is governed by + the array's data type regardless of the codec's. The mixed-endian struct + case pins that per-field byte order of the in-memory dtype survives a + roundtrip through a single stored byte order. + """ + if native_dtype.fields is None: + arr = np.arange(100, dtype=native_dtype) + else: + arr = np.array([(1.5, 2), (3.5, 4), (5.5, 6), (7.5, 8)], dtype=native_dtype) + zdtype = get_data_type_from_native_dtype(arr.dtype) + spec = ArraySpec( + shape=arr.shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + nd_buf: NDBuffer = default_buffer_prototype().nd_buffer.from_numpy_array(arr) + + codec = BytesCodec(endian=endian).evolve_from_array_spec(spec) + + encoded = codec._encode_sync(nd_buf, spec) + assert encoded is not None + assert encoded.to_bytes() == arr.astype(native_dtype.newbyteorder(endian)).tobytes() + + decoded = codec._decode_sync(encoded, spec) + assert decoded.dtype == zdtype.to_native_dtype() + np.testing.assert_array_equal(arr, decoded.as_numpy_array()) + + +@pytest.mark.parametrize("endian", ENDIAN) +def test_bytes_codec_accepts_all_endians(endian: EndianLiteral) -> None: + """ + Every endian value in ENDIAN is accepted by BytesCodec and round-trips + to the same value on the stored attribute. Catches drift between the + EndianLiteral type alias and the runtime ENDIAN tuple. + """ + codec = BytesCodec(endian=endian) + assert codec.endian == endian + + +@pytest.mark.parametrize("endian", ENDIAN) +def test_bytes_codec_json_roundtrip(endian: EndianLiteral) -> None: + """ + BytesCodec.to_dict produces the spec-defined wire shape and the + round-trip through from_dict preserves equality. Asserting the literal + JSON shape catches drift between BytesCodec's runtime representation and + the codec's V3 on-disk form. + """ + codec = BytesCodec(endian=endian) + assert codec.to_dict() == {"name": "bytes", "configuration": {"endian": endian}} + restored = BytesCodec.from_dict(codec.to_dict()) + assert restored == codec + + +# to_dict and from_dict are inverses over this (endian setting, wire dict) mapping: +# to_dict turns the endian setting into the dict; from_dict recovers it. +_ENDIAN_DICT_CASES: list[Expect[EndianLiteral | None, dict[str, Any]]] = [ + Expect( + input="little", + output={"name": "bytes", "configuration": {"endian": "little"}}, + id="little", + ), + Expect( + input="big", + output={"name": "bytes", "configuration": {"endian": "big"}}, + id="big", + ), + Expect(input=None, output={"name": "bytes"}, id="missing"), +] + + +@pytest.mark.parametrize("case", _ENDIAN_DICT_CASES, ids=lambda c: c.id) +def test_to_dict(case: Expect[EndianLiteral | None, dict[str, Any]]) -> None: + assert BytesCodec(endian=case.input).to_dict() == case.output + + +@pytest.mark.parametrize("case", _ENDIAN_DICT_CASES, ids=lambda c: c.id) +def test_from_dict(case: Expect[EndianLiteral | None, dict[str, Any]]) -> None: + assert BytesCodec.from_dict(case.output).endian == case.input + + +@pytest.mark.parametrize("endian", ["little", "big", pytest.param(None, id="missing")]) +def test_roundtrip(endian: EndianLiteral | None) -> None: + codec = BytesCodec(endian=endian) + + encoded = codec.to_dict() + roundtripped = BytesCodec.from_dict(encoded) + + assert codec == roundtripped + + +@pytest.mark.parametrize( + ("member", "expected"), + [("little", "little"), ("big", "big")], +) +def test_endian_member_access_warns(member: str, expected: str) -> None: + """ + Accessing a member on the deprecated `Endian` class emits a + `DeprecationWarning` and resolves to the equivalent literal string. + """ + with pytest.warns(DeprecationWarning, match=rf"Endian\.{member}"): + value = getattr(Endian, member) + assert value == expected + + +def test_endian_class_imports_silently() -> None: + """ + Importing the deprecated `Endian` class by name must not emit a warning; + only member access does. Guards against `bytes.py` accidentally + triggering its own deprecation warnings at import time. + """ + with warnings.catch_warnings(): + warnings.simplefilter("error") + from zarr.codecs.bytes import Endian as _Endian # noqa: F401 + + +def test_bytes_codec_init_with_enum_instance_warns() -> None: + """ + Passing a foreign `enum.Enum` instance to `BytesCodec.__init__` triggers + the init-level deprecation warning (from `_coerce_enum_input`) and + normalizes the value to the corresponding literal string. Covers the + case where a downstream package defined its own enum-shaped class to + bridge between zarr's old API and its own. + """ + + class LegacyEndian(enum.Enum): + little = "little" + + with pytest.warns(DeprecationWarning, match=r"Passing an enum to BytesCodec"): + codec = BytesCodec(endian=cast(Endian, LegacyEndian.little)) + assert codec.endian == "little" + + +def test_bytes_codec_init_with_deprecated_class_member() -> None: + """ + The realistic legacy-upgrade idiom: `BytesCodec(endian=Endian.little)`. + Member access on `Endian` emits one `DeprecationWarning` (from the + metaclass) and resolves to the bare string, which `BytesCodec` then + accepts without further warning. No second warning from + `_coerce_enum_input` because the metaclass already produced a string. + + The `cast` is necessary because the metaclass `__getattr__` is typed + as returning `str`, which does not statically match the codec's + `EndianLiteral` parameter even though the runtime value does. + """ + with pytest.warns(DeprecationWarning, match=r"Endian\.little"): + codec = BytesCodec(endian=cast(EndianLiteral, Endian.little)) + assert codec.endian == "little" + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input="north", + exception=ValueError, + id="unknown-string", + msg="endian must be one of", + ), + ], + ids=lambda c: c.id, +) +def test_bytes_codec_rejects_unknown_endian(case: ExpectFail[Any]) -> None: + """ + `BytesCodec.__init__` raises `ValueError` when given a value outside + `ENDIAN`, and the error message names the offending parameter. + """ + with case.raises(): + BytesCodec(endian=case.input) + + +def test_endian_attribute_error_for_unknown_member() -> None: + """ + Attribute access for a name that is not a known member of the + deprecated `Endian` class falls through to `AttributeError`, matching + the behavior of a regular class. + """ + with pytest.raises(AttributeError): + getattr(Endian, "not_a_member") # noqa: B009 + + +def test_bytes_codec_default_endian_matches_system() -> None: + """ + Constructing `BytesCodec()` with no arguments yields a codec whose + `endian` matches `sys.byteorder`. This replaces the previous + `default_system_endian = Endian(sys.byteorder)` module-level binding. + """ + codec = BytesCodec() + assert codec.endian == sys.byteorder + + +def _make_array_spec(dtype: Any) -> ArraySpec: + """Build a minimal ArraySpec around the given dtype for codec.evolve testing.""" + return ArraySpec( + shape=(1,), + dtype=dtype, + fill_value=0, + config=cast(ArrayConfig, {}), + prototype=default_buffer_prototype(), + ) + + +def test_bytes_codec_evolve_structured_multi_byte_fields_warns_and_defaults() -> None: + """ + BytesCodec(endian=None).evolve_from_array_spec(spec) with a structured dtype + whose fields contain multi-byte members emits a UserWarning about the + missing endian and returns a codec with endian set to "little" for legacy + compatibility. + """ + codec = BytesCodec(endian=None) + dtype = Struct(fields=(("a", Int32()), ("b", Int32()))) + spec = _make_array_spec(dtype) + with pytest.warns(UserWarning, match=r"Missing 'endian' for structured dtype"): + evolved = codec.evolve_from_array_spec(spec) + assert evolved.endian == "little" + + +def test_bytes_codec_evolve_structured_single_byte_fields_clears_endian() -> None: + """ + For a structured dtype whose fields are all single-byte, BytesCodec drops + its endian on evolve (endian is meaningless for single-byte content). + """ + codec = BytesCodec(endian="little") + dtype = Struct(fields=(("a", Int8()), ("b", Int8()))) + spec = _make_array_spec(dtype) + evolved = codec.evolve_from_array_spec(spec) + assert evolved.endian is None diff --git a/tests/test_codecs/test_cast_value.py b/tests/test_codecs/test_cast_value.py new file mode 100644 index 0000000000..c2e78770d9 --- /dev/null +++ b/tests/test_codecs/test_cast_value.py @@ -0,0 +1,613 @@ +from __future__ import annotations + +from typing import Any + +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +import zarr +from tests.conftest import Expect, ExpectFail +from zarr.codecs import BytesCodec, TransposeCodec +from zarr.codecs.cast_value import CastValue +from zarr.storage import MemoryStore + +try: + import cast_value_rs # noqa: F401 + + _HAS_CAST_VALUE_RS = True +except ModuleNotFoundError: + _HAS_CAST_VALUE_RS = False + +requires_cast_value_rs = pytest.mark.skipif( + not _HAS_CAST_VALUE_RS, reason="cast-value-rs not installed" +) + + +# --------------------------------------------------------------------------- +# Serialization +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "case", + [ + Expect( + input=CastValue(data_type="uint8"), + output={"name": "cast_value", "configuration": {"data_type": "uint8"}}, + id="minimal", + ), + Expect( + input=CastValue( + data_type="uint8", + rounding="towards-zero", + out_of_range="clamp", + scalar_map={"encode": [("NaN", 0)]}, + ), + output={ + "name": "cast_value", + "configuration": { + "data_type": "uint8", + "rounding": "towards-zero", + "out_of_range": "clamp", + "scalar_map": {"encode": [("NaN", 0)]}, + }, + }, + id="full", + ), + ], + ids=lambda c: c.id, +) +def test_to_dict(case: Expect[CastValue, dict[str, Any]]) -> None: + """to_dict produces the expected JSON structure.""" + assert case.input.to_dict() == case.output + + +@pytest.mark.parametrize( + "case", + [ + Expect( + input={"name": "cast_value", "configuration": {"data_type": "float32"}}, + output=("float32", "nearest-even", None), + id="defaults", + ), + Expect( + input={ + "name": "cast_value", + "configuration": { + "data_type": "int16", + "rounding": "towards-zero", + "out_of_range": "clamp", + }, + }, + output=("int16", "towards-zero", "clamp"), + id="explicit", + ), + ], + ids=lambda c: c.id, +) +def test_from_dict(case: Expect[dict[str, Any], tuple[str, str, str | None]]) -> None: + """from_dict deserializes configuration with correct values and defaults.""" + codec = CastValue.from_dict(case.input) + dtype_name, rounding, out_of_range = case.output + assert codec.dtype.to_native_dtype() == np.dtype(dtype_name) + assert codec.rounding == rounding + assert codec.out_of_range == out_of_range + + +@pytest.mark.parametrize( + "codec", + [ + CastValue(data_type="int16", rounding="towards-zero", out_of_range="clamp"), + CastValue( + data_type="uint8", + out_of_range="clamp", + scalar_map={"encode": [("NaN", 0)], "decode": [(0, "NaN")]}, + ), + ], + ids=["no-scalar-map", "with-scalar-map"], +) +def test_serialization_roundtrip(codec: CastValue) -> None: + """to_dict followed by from_dict produces an equal codec.""" + restored = CastValue.from_dict(codec.to_dict()) + assert codec == restored + + +# --------------------------------------------------------------------------- +# Construction +# --------------------------------------------------------------------------- + + +def test_construction_accepts_zdtype_object() -> None: + """data_type can be a ZDType instance, not just a JSON string.""" + from zarr.core.dtype import UInt8 + + codec = CastValue(data_type=UInt8()) + assert codec.dtype.to_native_dtype() == np.dtype("uint8") + + +def test_construction_rejects_invalid_target_dtype() -> None: + """Construction rejects target dtypes not in PERMITTED_DATA_TYPE_NAMES.""" + with pytest.raises(ValueError, match="Invalid target data type"): + CastValue(data_type="complex64") + + +# --------------------------------------------------------------------------- +# Validation +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input={"dtype": "complex128", "target": "float64"}, + msg="only supports integer and floating-point", + exception=ValueError, + id="complex-source", + ), + ExpectFail( + input={"dtype": "int32", "target": "float64", "out_of_range": "wrap"}, + msg="only valid for integer", + exception=ValueError, + id="wrap-float-target", + ), + ], + ids=lambda c: c.id, +) +def test_validation_rejects_invalid(case: ExpectFail[dict[str, Any]]) -> None: + """Invalid dtype or out_of_range combinations are rejected at array creation.""" + with case.raises(): + zarr.create_array( + store={}, + shape=(10,), + dtype=case.input["dtype"], + chunks=(10,), + filters=[ + CastValue( + data_type=case.input["target"], + out_of_range=case.input.get("out_of_range"), + ) + ], + compressors=None, + fill_value=0, + ) + + +@requires_cast_value_rs +@pytest.mark.parametrize( + ("source_dtype", "target_dtype"), + [ + ("float16", "int8"), + ("float32", "int32"), + ("float64", "int64"), + ("int32", "uint8"), + ], +) +def test_validation_accepts_wrap_with_integer_target(source_dtype: str, target_dtype: str) -> None: + """Regression for #3936: `out_of_range="wrap"` is permitted when the + cast TARGET (not the source array dtype) is an integer type.""" + zarr.create_array( + store={}, + shape=(1,), + dtype=source_dtype, + chunks=(1,), + filters=[CastValue(data_type=target_dtype, out_of_range="wrap")], + compressors=None, + fill_value=0, + ) + + +def test_zero_itemsize_raises() -> None: + """Variable-length dtypes (itemsize=0) are rejected by compute_encoded_size.""" + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.dtype.npy.string import VariableLengthUTF8 + + codec = CastValue(data_type="uint8") + spec = ArraySpec( + shape=(10,), + dtype=VariableLengthUTF8(), # type: ignore[arg-type] + fill_value="", + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + with pytest.raises(ValueError, match="fixed-size integer and floating-point data types"): + codec.compute_encoded_size(100, spec) + + +# --------------------------------------------------------------------------- +# Encode / decode +# --------------------------------------------------------------------------- + + +@requires_cast_value_rs +@pytest.mark.parametrize( + "case", + [ + Expect(input=("float64", "float32"), output=np.arange(50, dtype="float64"), id="f64β†’f32"), + Expect(input=("float32", "float64"), output=np.arange(50, dtype="float32"), id="f32β†’f64"), + Expect(input=("int32", "int64"), output=np.arange(50, dtype="int32"), id="i32β†’i64"), + Expect(input=("int64", "int16"), output=np.arange(50, dtype="int64"), id="i64β†’i16"), + Expect(input=("float64", "int32"), output=np.arange(50, dtype="float64"), id="f64β†’i32"), + Expect(input=("int32", "float64"), output=np.arange(50, dtype="int32"), id="i32β†’f64"), + ], + ids=lambda c: c.id, +) +def test_encode_decode_roundtrip( + case: Expect[tuple[str, str], np.ndarray[Any, np.dtype[Any]]], +) -> None: + """Small integer data survives encode β†’ decode for each dtype pair.""" + import zarr + + source_dtype, target_dtype = case.input + arr = zarr.create_array( + store={}, + shape=(50,), + dtype=source_dtype, + chunks=(50,), + filters=[CastValue(data_type=target_dtype)], + compressors=None, + fill_value=0, + ) + arr[:] = case.output + np.testing.assert_array_equal(arr[:], case.output) + + +@requires_cast_value_rs +@pytest.mark.parametrize( + "case", + [ + Expect( + input=np.array([1.7, -1.7, 2.5, -2.5], dtype="float64"), + output=np.array([1, -1, 2, -2], dtype="float64"), + id="towards-zero", + ), + ], + ids=lambda c: c.id, +) +def test_float_to_int_rounding( + case: Expect[np.ndarray[Any, np.dtype[Any]], np.ndarray[Any, np.dtype[Any]]], +) -> None: + """Fractional float values are truncated towards zero when cast to int32.""" + import zarr + + arr = zarr.create_array( + store={}, + shape=case.input.shape, + dtype=case.input.dtype, + chunks=case.input.shape, + filters=[CastValue(data_type="int32", rounding="towards-zero", out_of_range="clamp")], + compressors=None, + fill_value=0, + ) + arr[:] = case.input + np.testing.assert_array_equal(arr[:], case.output) + + +@requires_cast_value_rs +@pytest.mark.parametrize( + "case", + [ + Expect( + input=np.array([0, 200, -200], dtype="int32"), + output=np.array([0, 127, -128], dtype="int32"), + id="int32β†’int8", + ), + ], + ids=lambda c: c.id, +) +def test_out_of_range_clamp( + case: Expect[np.ndarray[Any, np.dtype[Any]], np.ndarray[Any, np.dtype[Any]]], +) -> None: + """Values outside the int8 range are clamped to [-128, 127].""" + import zarr + + arr = zarr.create_array( + store={}, + shape=case.input.shape, + dtype=case.input.dtype, + chunks=case.input.shape, + filters=[CastValue(data_type="int8", out_of_range="clamp")], + compressors=None, + fill_value=0, + ) + arr[:] = case.input + np.testing.assert_array_equal(arr[:], case.output) + + +def test_compute_encoded_size() -> None: + """compute_encoded_size correctly scales byte length by itemsize ratio.""" + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.dtype import get_data_type_from_json + + codec = CastValue(data_type="int16") + spec = ArraySpec( + shape=(10,), + dtype=get_data_type_from_json("float64", zarr_format=3), + fill_value=0, + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + # 10 float64 elements = 80 bytes -> 10 int16 elements = 20 bytes + assert codec.compute_encoded_size(80, spec) == 20 + + +@requires_cast_value_rs +def test_scalar_map_encode_decode_roundtrip() -> None: + """Scalar map entries are applied during encode and decode.""" + import zarr + + data = np.array([1.0, float("nan"), 3.0], dtype="float64") + arr = zarr.create_array( + store={}, + shape=data.shape, + dtype="float64", + chunks=data.shape, + filters=[ + CastValue( + data_type="int32", + rounding="nearest-even", + out_of_range="clamp", + scalar_map={"encode": [("NaN", -999)], "decode": [(-999, "NaN")]}, + ), + ], + compressors=None, + fill_value=1, + ) + arr[:] = data + result = np.asarray(arr[:]) + np.testing.assert_equal(result[0], 1.0) + np.testing.assert_equal(result[2], 3.0) + assert np.isnan(result[1]) + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input={ + "dtype": "int32", + "target": "int8", + "scalar_map": {"encode": [("NaN", 0)]}, + }, + msg="not representable in dtype int32", + exception=ValueError, + id="nan-key-for-int-source", + ), + ExpectFail( + input={ + "dtype": "int32", + "target": "float64", + "scalar_map": {"decode": [(0, "NaN")]}, + }, + msg="not representable in dtype int32", + exception=ValueError, + id="nan-value-for-int-decode-target", + ), + ExpectFail( + input={ + "dtype": "float64", + "target": "int8", + "scalar_map": {"encode": [("NaN", 999)]}, + }, + msg="not representable in dtype int8", + exception=ValueError, + id="encode-value-out-of-range", + ), + ExpectFail( + input={ + "dtype": "float64", + "target": "int8", + "scalar_map": {"encode": [("NaN", 1.5)]}, + }, + msg="not representable in dtype int8", + exception=ValueError, + id="encode-value-not-integer", + ), + ], + ids=lambda c: c.id, +) +def test_scalar_map_validation_rejects_invalid(case: ExpectFail[dict[str, Any]]) -> None: + """Invalid scalar_map entries are rejected at array creation.""" + import zarr + + with case.raises(): + zarr.create_array( + store={}, + shape=(10,), + dtype=case.input["dtype"], + chunks=(10,), + filters=[ + CastValue( + data_type=case.input["target"], + out_of_range="clamp", + scalar_map=case.input["scalar_map"], + ) + ], + compressors=None, + fill_value=0, + ) + + +@requires_cast_value_rs +def test_combined_with_scale_offset() -> None: + """scale_offset followed by cast_value compresses float64 into int16 and round-trips.""" + import zarr + from zarr.codecs.scale_offset import ScaleOffset + + arr = zarr.create_array( + store={}, + shape=(100,), + dtype="float64", + chunks=(100,), + filters=[ + ScaleOffset(offset=0, scale=10), + CastValue(data_type="int16", rounding="nearest-even", out_of_range="clamp"), + ], + compressors=None, + fill_value=0, + ) + data = np.arange(100, dtype="float64") * 0.1 + arr[:] = data + result = arr[:] + np.testing.assert_array_almost_equal(result, data, decimal=1) # type: ignore[arg-type] + + +@pytest.mark.parametrize( + "case", + [ + Expect( + input={"encode": [("NaN", 0)]}, + output={"encode": {"NaN": 0}}, + id="encode-only", + ), + Expect( + input={"encode": [("NaN", 0)], "decode": [(0, "NaN")]}, + output={"encode": {"NaN": 0}, "decode": {0: "NaN"}}, + id="both-directions", + ), + Expect( + input={"encode": {"NaN": 0}}, + output={"encode": {"NaN": 0}}, + id="already-normalized", + ), + ], + ids=lambda c: c.id, +) +def test_parse_scalar_map(case: Expect[Any, Any]) -> None: + from zarr.codecs.cast_value import parse_scalar_map + + assert parse_scalar_map(case.input) == case.output + + +# --------------------------------------------------------------------------- +# Backend version guard +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "case", + [ + Expect(input="0.4.2", output=None, id="exactly-minimum"), + Expect(input="0.4.3", output=None, id="newer-patch"), + Expect(input="0.5.0", output=None, id="newer-minor"), + Expect(input="1.0.0", output=None, id="newer-major"), + Expect(input="0.4.2.post1", output=None, id="post-release"), + Expect(input="0.4.0", output="0.4.0", id="known-corrupting"), + Expect(input="0.4.1", output="0.4.1", id="one-patch-below"), + Expect(input="0.3.0", output="0.3.0", id="older-minor"), + Expect(input="0.4.2.dev1", output="0.4.2.dev1", id="pre-release-of-minimum"), + ], + ids=lambda c: c.id, +) +def test_check_backend_version( + case: Expect[str, str | None], monkeypatch: pytest.MonkeyPatch +) -> None: + """Versions at or above the minimum pass; older ones report the installed version.""" + from zarr.codecs import cast_value as mod + + monkeypatch.setattr(mod, "version", lambda _: case.input) + result = mod._check_backend_version() + + if case.output is None: + assert result is None + else: + assert result is not None + assert case.output in result + assert mod.CAST_VALUE_RS_MIN_VERSION in result + + +def test_check_backend_version_allows_missing_metadata(monkeypatch: pytest.MonkeyPatch) -> None: + """A backend without distribution metadata is allowed: there is no version to compare.""" + from importlib.metadata import PackageNotFoundError + + from zarr.codecs import cast_value as mod + + def raise_not_found(_: str) -> str: + raise PackageNotFoundError + + monkeypatch.setattr(mod, "version", raise_not_found) + assert mod._check_backend_version() is None + + +def test_encode_rejects_outdated_backend(monkeypatch: pytest.MonkeyPatch) -> None: + """Using the codec with an outdated backend raises instead of corrupting data.""" + from zarr.codecs import cast_value as mod + + monkeypatch.setattr(mod, "_BACKEND_ERROR", "outdated backend") + codec = CastValue(data_type="uint16") + + with pytest.raises(ImportError, match="outdated backend"): + codec._do_cast( + np.arange(4, dtype=np.float32), target_dtype=np.dtype("uint16"), scalar_map=None + ) + + +def test_min_version_matches_pyproject() -> None: + """The runtime floor and the packaging floor must not drift apart.""" + import re + import tomllib + from pathlib import Path + + from zarr.codecs.cast_value import CAST_VALUE_RS_MIN_VERSION + + pyproject = Path(__file__).parents[2] / "pyproject.toml" + if not pyproject.is_file(): + pytest.skip("pyproject.toml is not available in an installed checkout") + + with pyproject.open("rb") as f: + extras = tomllib.load(f)["project"]["optional-dependencies"] + + (requirement,) = extras["cast-value-rs"] + match = re.fullmatch(r"cast-value-rs>=(?P[\w.]+)", requirement) + assert match is not None, f"unexpected requirement form: {requirement!r}" + assert match.group("version") == CAST_VALUE_RS_MIN_VERSION + + +# --------------------------------------------------------------------------- +# Non-contiguous input (regression for #4237) +# --------------------------------------------------------------------------- + + +@requires_cast_value_rs +def test_enforce_contiguous_arrays() -> None: + """ + Transpose codec produces non-contiguous arrays. + Ensure cast_value makes them contiguous before processing. + """ + data = np.arange(20, dtype=np.float32).reshape(5, 2, 2) + + def make_array(filters: list[Any]) -> Any: + return zarr.create_array( + store=MemoryStore(), + shape=data.shape, + dtype=data.dtype, + chunks=data.shape, + filters=filters, + serializer=BytesCodec(endian="little"), + compressors=None, + zarr_format=3, + ) + + # Cast before transpose + array = make_array( + [ + CastValue(data_type="uint16"), + TransposeCodec(order=(1, 2, 0)), + ] + ) + array[:] = data + assert_array_equal(array[:], data) + + # Cast after transpose + array = make_array( + [ + TransposeCodec(order=(1, 2, 0)), + CastValue(data_type="uint16"), + ] + ) + + array[:] = data + assert_array_equal(array[:], data) diff --git a/tests/test_codecs/test_codecs.py b/tests/test_codecs/test_codecs.py new file mode 100644 index 0000000000..8b4585503c --- /dev/null +++ b/tests/test_codecs/test_codecs.py @@ -0,0 +1,486 @@ +from __future__ import annotations + +import json +import warnings +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +import zarr +import zarr.api +import zarr.api.asynchronous +from zarr import Array, AsyncArray, config +from zarr.codecs import ( + BytesCodec, + GzipCodec, + ShardingCodec, + TransposeCodec, +) +from zarr.core.buffer import default_buffer_prototype +from zarr.core.indexing import BasicSelection, decode_morton, morton_order_coords +from zarr.core.metadata.v3 import ArrayV3Metadata +from zarr.dtype import UInt8 +from zarr.errors import ZarrUserWarning +from zarr.storage import MemoryStore, StorePath + +if TYPE_CHECKING: + from zarr.abc.codec import Codec + from zarr.abc.store import Store + from zarr.core.buffer.core import NDArrayLikeOrScalar + from zarr.core.common import MemoryOrder + from zarr.types import AnyAsyncArray + + +@dataclass(frozen=True) +class _AsyncArrayProxy: + array: AnyAsyncArray + + def __getitem__(self, selection: BasicSelection) -> _AsyncArraySelectionProxy: + return _AsyncArraySelectionProxy(self.array, selection) + + +@dataclass(frozen=True) +class _AsyncArraySelectionProxy: + array: AnyAsyncArray + selection: BasicSelection + + async def get(self) -> NDArrayLikeOrScalar: + return await self.array.getitem(self.selection) + + async def set(self, value: np.ndarray[Any, Any]) -> None: + return await self.array.setitem(self.selection, value) + + +def order_from_dim(order: MemoryOrder, ndim: int) -> tuple[int, ...]: + if order == "F": + return tuple(ndim - x - 1 for x in range(ndim)) + else: + return tuple(range(ndim)) + + +def test_sharding_pickle() -> None: + """ + Test that sharding codecs can be pickled + """ + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +@pytest.mark.parametrize("input_order", ["F", "C"]) +@pytest.mark.parametrize("store_order", ["F", "C"]) +@pytest.mark.parametrize("runtime_write_order", ["F", "C"]) +@pytest.mark.parametrize("runtime_read_order", ["F", "C"]) +@pytest.mark.parametrize("with_sharding", [True, False]) +async def test_order( + store: Store, + input_order: MemoryOrder, + store_order: MemoryOrder, + runtime_write_order: MemoryOrder, + runtime_read_order: MemoryOrder, + with_sharding: bool, +) -> None: + data = np.arange(0, 256, dtype="uint16").reshape((32, 8), order=input_order) + path = "order" + spath = StorePath(store, path=path) + + a = await zarr.api.asynchronous.create_array( + spath, + shape=data.shape, + chunks=(16, 8) if with_sharding else (32, 8), + shards=(32, 8) if with_sharding else None, + dtype=data.dtype, + fill_value=0, + chunk_key_encoding={"name": "v2", "separator": "."}, + filters=[TransposeCodec(order=order_from_dim(store_order, data.ndim))], + config={"order": runtime_write_order}, + ) + + await _AsyncArrayProxy(a)[:, :].set(data) + read_data = await _AsyncArrayProxy(a)[:, :].get() + assert np.array_equal(data, read_data) + + with config.set({"array.order": runtime_read_order}): + a = await AsyncArray.open( + spath, + ) + read_data = await _AsyncArrayProxy(a)[:, :].get() + assert np.array_equal(data, read_data) + + assert isinstance(read_data, np.ndarray) + if runtime_read_order == "F": + assert read_data.flags["F_CONTIGUOUS"] + assert not read_data.flags["C_CONTIGUOUS"] + else: + assert not read_data.flags["F_CONTIGUOUS"] + assert read_data.flags["C_CONTIGUOUS"] + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +@pytest.mark.parametrize("input_order", ["F", "C"]) +@pytest.mark.parametrize("runtime_write_order", ["F", "C"]) +@pytest.mark.parametrize("runtime_read_order", ["F", "C"]) +@pytest.mark.parametrize("with_sharding", [True, False]) +def test_order_implicit( + store: Store, + input_order: MemoryOrder, + runtime_write_order: MemoryOrder, + runtime_read_order: MemoryOrder, + with_sharding: bool, +) -> None: + data = np.arange(0, 256, dtype="uint16").reshape((16, 16), order=input_order) + path = "order_implicit" + spath = StorePath(store, path) + + with config.set({"array.order": runtime_write_order}): + a = zarr.create_array( + spath, + shape=data.shape, + chunks=(8, 8) if with_sharding else (16, 16), + shards=(16, 16) if with_sharding else None, + dtype=data.dtype, + fill_value=0, + ) + + a[:, :] = data + + with config.set({"array.order": runtime_read_order}): + a = Array.open(spath) + read_data = a[:, :] + assert np.array_equal(data, read_data) + + assert isinstance(read_data, np.ndarray) + if runtime_read_order == "F": + assert read_data.flags["F_CONTIGUOUS"] + assert not read_data.flags["C_CONTIGUOUS"] + else: + assert not read_data.flags["F_CONTIGUOUS"] + assert read_data.flags["C_CONTIGUOUS"] + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +def test_open(store: Store) -> None: + spath = StorePath(store) + a = zarr.create_array( + spath, + shape=(16, 16), + chunks=(16, 16), + dtype="int32", + fill_value=0, + ) + b = Array.open(spath) + assert a.metadata == b.metadata + + +def test_morton_exact_order() -> None: + """Test exact morton ordering for power-of-2 shapes.""" + assert list(morton_order_coords((2, 2))) == [(0, 0), (1, 0), (0, 1), (1, 1)] + assert list(morton_order_coords((2, 2, 2))) == [ + (0, 0, 0), + (1, 0, 0), + (0, 1, 0), + (1, 1, 0), + (0, 0, 1), + (1, 0, 1), + (0, 1, 1), + (1, 1, 1), + ] + assert list(morton_order_coords((2, 2, 2, 2))) == [ + (0, 0, 0, 0), + (1, 0, 0, 0), + (0, 1, 0, 0), + (1, 1, 0, 0), + (0, 0, 1, 0), + (1, 0, 1, 0), + (0, 1, 1, 0), + (1, 1, 1, 0), + (0, 0, 0, 1), + (1, 0, 0, 1), + (0, 1, 0, 1), + (1, 1, 0, 1), + (0, 0, 1, 1), + (1, 0, 1, 1), + (0, 1, 1, 1), + (1, 1, 1, 1), + ] + + +@pytest.mark.parametrize( + "shape", + [ + (2, 2, 2), + (5, 2), + (2, 5), + (2, 9, 2), + (3, 2, 12), + (2, 5, 1), + (4, 3, 6, 2, 7), + (3, 2, 1, 6, 4, 5, 2), + (1,), + (1, 1), + (5, 1, 3), + (1, 4, 1, 2), + (5, 5, 5), # triggers argsort strategy (n_z/n_total > 4) + ], +) +def test_morton_is_permutation(shape: tuple[int, ...]) -> None: + """Test that morton_order_coords produces every valid coordinate exactly once.""" + import itertools + + from zarr.core.common import product + + order = list(morton_order_coords(shape)) + expected_len = product(shape) + # completeness: every valid coordinate is present + assert len(order) == expected_len + # no duplicates + assert len(set(order)) == expected_len + # all coordinates are within bounds + assert all(all(c < s for c, s in zip(coord, shape, strict=True)) for coord in order) + # the set of coordinates equals the full cartesian product + assert set(order) == set(itertools.product(*(range(s) for s in shape))) + + +@pytest.mark.parametrize( + "shape", + [ + (2, 2), + (4, 4), + (2, 2, 2), + (4, 4, 4), + (2, 2, 2, 2), + ], +) +def test_morton_ordering(shape: tuple[int, ...]) -> None: + """Test that the iteration order matches consecutive decode_morton outputs. + + For power-of-2 shapes, every decode_morton output is in-bounds, + so the ordering should be exactly decode_morton(0), decode_morton(1), ... + """ + + order = list(morton_order_coords(shape)) + for i, coord in enumerate(order): + assert coord == decode_morton(i, shape) + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +def test_write_partial_chunks(store: Store) -> None: + data = np.arange(0, 256, dtype="uint16").reshape((16, 16)) + spath = StorePath(store) + a = zarr.create_array( + spath, + shape=data.shape, + chunks=(20, 20), + dtype=data.dtype, + fill_value=1, + ) + a[0:16, 0:16] = data + assert np.array_equal(a[0:16, 0:16], data) + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +async def test_delete_empty_chunks(store: Store) -> None: + data = np.ones((16, 16)) + path = "delete_empty_chunks" + spath = StorePath(store, path) + a = await zarr.api.asynchronous.create_array( + spath, + shape=data.shape, + chunks=(32, 32), + dtype=data.dtype, + fill_value=1, + ) + await _AsyncArrayProxy(a)[:16, :16].set(np.zeros((16, 16))) + await _AsyncArrayProxy(a)[:16, :16].set(data) + assert np.array_equal(await _AsyncArrayProxy(a)[:16, :16].get(), data) + assert await store.get(f"{path}/c0/0", prototype=default_buffer_prototype()) is None + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +async def test_dimension_names(store: Store) -> None: + data = np.arange(0, 256, dtype="uint16").reshape((16, 16)) + path = "dimension_names" + spath = StorePath(store, path) + await zarr.api.asynchronous.create_array( + spath, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + dimension_names=("x", "y"), + ) + + assert isinstance( + meta := (await zarr.api.asynchronous.open_array(store=spath)).metadata, ArrayV3Metadata + ) + assert meta.dimension_names == ( + "x", + "y", + ) + path2 = "dimension_names2" + spath2 = StorePath(store, path2) + await zarr.api.asynchronous.create_array( + spath2, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + ) + + assert isinstance(meta := (await AsyncArray.open(spath2)).metadata, ArrayV3Metadata) + assert meta.dimension_names is None + zarr_json_buffer = await store.get(f"{path2}/zarr.json", prototype=default_buffer_prototype()) + assert zarr_json_buffer is not None + assert "dimension_names" not in json.loads(zarr_json_buffer.to_bytes()) + + +@pytest.mark.parametrize( + "codecs", + [ + (BytesCodec(), TransposeCodec(order=order_from_dim("F", 2))), + (TransposeCodec(order=order_from_dim("F", 2)),), + ], +) +def test_invalid_metadata(codecs: tuple[Codec, ...]) -> None: + shape = (16,) + chunks = (16,) + data_type = UInt8() + with pytest.raises(ValueError, match="The `order` tuple must have as many entries"): + ArrayV3Metadata( + shape=shape, + chunk_grid={"name": "regular", "configuration": {"chunk_shape": chunks}}, + chunk_key_encoding={"name": "default", "configuration": {"separator": "/"}}, + fill_value=0, + data_type=data_type, + codecs=codecs, + attributes={}, + dimension_names=None, + ) + + +def test_invalid_metadata_create_array() -> None: + with pytest.warns( + ZarrUserWarning, + match="codec disables partial reads and writes, which may lead to inefficient performance", + ): + zarr.create_array( + {}, + shape=(16, 16), + chunks=(16, 16), + dtype=np.dtype("uint8"), + fill_value=0, + serializer=ShardingCodec(chunk_shape=(8, 8)), + compressors=[ + GzipCodec(), + ], + ) + + +@pytest.mark.parametrize( + "pipeline_path", + [ + "zarr.core.codec_pipeline.BatchedCodecPipeline", + "zarr.core.codec_pipeline.FusedCodecPipeline", + ], +) +def test_sharding_warning_fires_once_per_open(pipeline_path: str) -> None: + """Construction-time codec warnings (e.g. sharding's partial-reads warning) + must fire exactly once per array open, not once per internal codec-chain + reconstruction. + + `create_codec_pipeline` builds a throwaway pipeline via `from_codecs` (which + warns) and then calls `evolve_from_array_spec` on it, which re-splits the + (already-warned-about) codec chain against the evolved spec. That re-split + goes through `codecs_from_list_unchecked` rather than `codecs_from_list`, so + it does not re-emit the warning. `FusedCodecPipeline` additionally builds a + `ChunkTransform` (and, on the async fallback path, an `AsyncChunkTransform` + per call) from the same evolved codec chain, which must use the same quiet + variant. + """ + with config.set({"codec_pipeline.path": pipeline_path}): + store = MemoryStore() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + zarr.create_array( + store, + shape=(16, 16), + chunks=(16, 16), + dtype=np.dtype("uint8"), + fill_value=0, + serializer=ShardingCodec(chunk_shape=(8, 8)), + compressors=[GzipCodec()], + ) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + zarr.open_array(store, mode="r") + + matches = [w for w in caught if "disables partial reads" in str(w.message)] + assert len(matches) == 1 + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +async def test_resize(store: Store) -> None: + data = np.zeros((16, 18), dtype="uint16") + path = "resize" + spath = StorePath(store, path) + a = await zarr.api.asynchronous.create_array( + spath, + shape=data.shape, + chunks=(10, 10), + dtype=data.dtype, + chunk_key_encoding={"name": "v2", "separator": "."}, + fill_value=1, + ) + + await _AsyncArrayProxy(a)[:16, :18].set(data) + assert await store.get(f"{path}/1.1", prototype=default_buffer_prototype()) is not None + assert await store.get(f"{path}/0.0", prototype=default_buffer_prototype()) is not None + assert await store.get(f"{path}/0.1", prototype=default_buffer_prototype()) is not None + assert await store.get(f"{path}/1.0", prototype=default_buffer_prototype()) is not None + + await a.resize((10, 12)) + assert a.metadata.shape == (10, 12) + assert a.shape == (10, 12) + assert await store.get(f"{path}/0.0", prototype=default_buffer_prototype()) is not None + assert await store.get(f"{path}/0.1", prototype=default_buffer_prototype()) is not None + assert await store.get(f"{path}/1.0", prototype=default_buffer_prototype()) is None + assert await store.get(f"{path}/1.1", prototype=default_buffer_prototype()) is None + + +def _resolve_metadata_codecs() -> list[Codec]: + from zarr.codecs.crc32c_ import Crc32cCodec + from zarr.codecs.zstd import ZstdCodec + + return [ + BytesCodec(), + GzipCodec(level=1), + TransposeCodec(order=(0,)), + Crc32cCodec(), + ZstdCodec(level=1), + ] + + +@pytest.mark.parametrize("codec", _resolve_metadata_codecs(), ids=lambda c: type(c).__name__) +def test_resolve_metadata_only_mutates_shape(codec: Codec) -> None: + """A codec's resolve_metadata may change a chunk's `shape` but must leave the + prototype, dtype, fill_value, and config untouched -- the pipeline relies on + those being stable across the codec chain. + """ + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.dtype import get_data_type_from_native_dtype + + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + spec_in = ArraySpec( + shape=(10,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0.0), + config=ArrayConfig(order="C", write_empty_chunks=False), + prototype=default_buffer_prototype(), + ) + spec_out = codec.resolve_metadata(spec_in) + name = type(codec).__name__ + assert spec_out.prototype is spec_in.prototype, f"{name} changed prototype" + assert spec_out.dtype == spec_in.dtype, f"{name} changed dtype" + assert spec_out.fill_value == spec_in.fill_value, f"{name} changed fill_value" + assert spec_out.config == spec_in.config, f"{name} changed config" diff --git a/tests/test_codecs/test_crc32c.py b/tests/test_codecs/test_crc32c.py new file mode 100644 index 0000000000..3ab1070f60 --- /dev/null +++ b/tests/test_codecs/test_crc32c.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +import numpy as np + +from zarr.abc.codec import SupportsSyncCodec +from zarr.codecs.crc32c_ import Crc32cCodec +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import default_buffer_prototype +from zarr.core.dtype import get_data_type_from_native_dtype + + +def test_crc32c_codec_supports_sync() -> None: + assert isinstance(Crc32cCodec(), SupportsSyncCodec) + + +def test_crc32c_codec_sync_roundtrip() -> None: + codec = Crc32cCodec() + arr = np.arange(100, dtype="float64") + zdtype = get_data_type_from_native_dtype(arr.dtype) + spec = ArraySpec( + shape=arr.shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + buf = default_buffer_prototype().buffer.from_array_like(arr.view("B")) + + encoded = codec._encode_sync(buf, spec) + assert encoded is not None + decoded = codec._decode_sync(encoded, spec) + result = np.frombuffer(decoded.as_numpy_array(), dtype="float64") + np.testing.assert_array_equal(arr, result) diff --git a/tests/test_codecs/test_gzip.py b/tests/test_codecs/test_gzip.py new file mode 100644 index 0000000000..8932ba5e59 --- /dev/null +++ b/tests/test_codecs/test_gzip.py @@ -0,0 +1,52 @@ +import numpy as np +import pytest + +import zarr +from zarr.abc.codec import SupportsSyncCodec +from zarr.abc.store import Store +from zarr.codecs import GzipCodec +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import default_buffer_prototype +from zarr.core.dtype import get_data_type_from_native_dtype +from zarr.storage import StorePath + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +def test_gzip(store: Store) -> None: + data = np.arange(0, 256, dtype="uint16").reshape((16, 16)) + + a = zarr.create_array( + StorePath(store), + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + compressors=GzipCodec(), + ) + + a[:, :] = data + assert np.array_equal(data, a[:, :]) + + +def test_gzip_codec_supports_sync() -> None: + assert isinstance(GzipCodec(), SupportsSyncCodec) + + +def test_gzip_codec_sync_roundtrip() -> None: + codec = GzipCodec(level=1) + arr = np.arange(100, dtype="float64") + zdtype = get_data_type_from_native_dtype(arr.dtype) + spec = ArraySpec( + shape=arr.shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + buf = default_buffer_prototype().buffer.from_array_like(arr.view("B")) + + encoded = codec._encode_sync(buf, spec) + assert encoded is not None + decoded = codec._decode_sync(encoded, spec) + result = np.frombuffer(decoded.as_numpy_array(), dtype="float64") + np.testing.assert_array_equal(arr, result) diff --git a/tests/test_codecs/test_numcodecs.py b/tests/test_codecs/test_numcodecs.py new file mode 100644 index 0000000000..99cd89492f --- /dev/null +++ b/tests/test_codecs/test_numcodecs.py @@ -0,0 +1,390 @@ +from __future__ import annotations + +import contextlib +import pickle +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest +from numcodecs import GZip + +try: + from numcodecs.errors import UnknownCodecError +except ImportError: + # Older versions of numcodecs don't have a separate errors module + UnknownCodecError = ValueError + +from zarr import config, create_array, open_array +from zarr.abc.numcodec import _is_numcodec, _is_numcodec_cls +from zarr.codecs import numcodecs as _numcodecs +from zarr.registry import get_codec_class, get_numcodec + +if TYPE_CHECKING: + from collections.abc import Iterator + + +@contextlib.contextmanager +def codec_conf() -> Iterator[Any]: + base_conf = config.get("codecs") + new_conf = { + "numcodecs.bz2": "zarr.codecs.numcodecs.BZ2", + "numcodecs.crc32": "zarr.codecs.numcodecs.CRC32", + "numcodecs.crc32c": "zarr.codecs.numcodecs.CRC32C", + "numcodecs.lz4": "zarr.codecs.numcodecs.LZ4", + "numcodecs.lzma": "zarr.codecs.numcodecs.LZMA", + "numcodecs.zfpy": "zarr.codecs.numcodecs.ZFPY", + "numcodecs.adler32": "zarr.codecs.numcodecs.Adler32", + "numcodecs.astype": "zarr.codecs.numcodecs.AsType", + "numcodecs.bitround": "zarr.codecs.numcodecs.BitRound", + "numcodecs.blosc": "zarr.codecs.numcodecs.Blosc", + "numcodecs.delta": "zarr.codecs.numcodecs.Delta", + "numcodecs.fixedscaleoffset": "zarr.codecs.numcodecs.FixedScaleOffset", + "numcodecs.fletcher32": "zarr.codecs.numcodecs.Fletcher32", + "numcodecs.gzip": "zarr.codecs.numcodecs.GZip", + "numcodecs.jenkinslookup3": "zarr.codecs.numcodecs.JenkinsLookup3", + "numcodecs.pcodec": "zarr.codecs.numcodecs.PCodec", + "numcodecs.packbits": "zarr.codecs.numcodecs.PackBits", + "numcodecs.shuffle": "zarr.codecs.numcodecs.Shuffle", + "numcodecs.quantize": "zarr.codecs.numcodecs.Quantize", + "numcodecs.zlib": "zarr.codecs.numcodecs.Zlib", + "numcodecs.zstd": "zarr.codecs.numcodecs.Zstd", + } + + yield config.set({"codecs": new_conf | base_conf}) + + +if TYPE_CHECKING: + from zarr.core.common import JSON + + +def test_get_numcodec() -> None: + assert get_numcodec({"id": "gzip", "level": 2}) == GZip(level=2) # type: ignore[typeddict-unknown-key] + + +def test_is_numcodec() -> None: + """ + Test the _is_numcodec function + """ + assert _is_numcodec(GZip()) + + +def test_is_numcodec_cls() -> None: + """ + Test the _is_numcodec_cls function + """ + assert _is_numcodec_cls(GZip) + + +ALL_CODECS = tuple( + filter( + lambda v: issubclass(v, _numcodecs._NumcodecsCodec) and hasattr(v, "codec_name"), + tuple(getattr(_numcodecs, cls_name) for cls_name in _numcodecs.__all__), + ) +) + + +@pytest.mark.parametrize("codec_cls", ALL_CODECS) +def test_get_codec_class(codec_cls: type[_numcodecs._NumcodecsCodec]) -> None: + assert get_codec_class(codec_cls.codec_name) == codec_cls # type: ignore[comparison-overlap,misc] + + +@pytest.mark.parametrize("codec_class", ALL_CODECS) +def test_docstring(codec_class: type[_numcodecs._NumcodecsCodec]) -> None: + """ + Test that the docstring for the zarr.numcodecs codecs references the wrapped numcodecs class. + """ + assert "See [numcodecs." in codec_class.__doc__ # type: ignore[operator] + + +@pytest.mark.parametrize( + "codec_class", + [ + _numcodecs.Blosc, + _numcodecs.LZ4, + _numcodecs.Zstd, + _numcodecs.Zlib, + _numcodecs.GZip, + _numcodecs.BZ2, + _numcodecs.LZMA, + _numcodecs.Shuffle, + ], +) +def test_generic_compressor(codec_class: type[_numcodecs._NumcodecsBytesBytesCodec]) -> None: + data = np.arange(0, 256, dtype="uint16").reshape((16, 16)) + + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + compressors=[codec_class()], + ) + + a[:, :] = data.copy() + np.testing.assert_array_equal(data, a[:, :]) + + +@pytest.mark.parametrize( + ("codec_class", "codec_config"), + [ + (_numcodecs.Delta, {"dtype": "float32"}), + (_numcodecs.FixedScaleOffset, {"offset": 0, "scale": 25.5}), + (_numcodecs.FixedScaleOffset, {"offset": 0, "scale": 51, "astype": "uint16"}), + (_numcodecs.AsType, {"encode_dtype": "float32", "decode_dtype": "float32"}), + ], + ids=[ + "delta", + "fixedscaleoffset", + "fixedscaleoffset2", + "astype", + ], +) +def test_generic_filter( + codec_class: type[_numcodecs._NumcodecsArrayArrayCodec], + codec_config: dict[str, JSON], +) -> None: + data = np.linspace(0, 10, 256, dtype="float32").reshape((16, 16)) + + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + filters=[ + codec_class(**codec_config), + ], + ) + + a[:, :] = data.copy() + with codec_conf(): + b = open_array(a.store, mode="r") + np.testing.assert_array_equal(data, b[:, :]) + + +@pytest.mark.parametrize( + ("codec_class", "codec_config", "dtype"), + [ + (_numcodecs.Delta, {"dtype": "int64"}, "int64"), + (_numcodecs.FixedScaleOffset, {"offset": 0, "scale": 1}, "int64"), + (_numcodecs.PackBits, {}, "bool"), + ], + ids=["delta", "fixedscaleoffset", "packbits"], +) +def test_generic_filter_f_contiguous( + codec_class: type[_numcodecs._NumcodecsArrayArrayCodec], + codec_config: dict[str, JSON], + dtype: str, +) -> None: + # gh-3558: F-contiguous chunks were handed to numcodecs filters as is, and + # numcodecs flattens in memory order, so the elements came back transposed + if dtype == "bool": + data = np.asfortranarray(np.tril(np.ones((16, 16), dtype=bool))) + else: + data = np.asfortranarray(np.arange(256, dtype=dtype).reshape(16, 16)) + + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + filters=[codec_class(**codec_config)], + ) + + a[:, :] = data + np.testing.assert_array_equal(data, a[:, :]) + + +def test_generic_filter_bitround() -> None: + data = np.linspace(0, 1, 256, dtype="float32").reshape((16, 16)) + + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + filters=[_numcodecs.BitRound(keepbits=3)], + ) + + a[:, :] = data.copy() + b = open_array(a.store, mode="r") + assert np.allclose(data, b[:, :], atol=0.1) + + +def test_generic_filter_quantize() -> None: + data = np.linspace(0, 10, 256, dtype="float32").reshape((16, 16)) + + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + filters=[_numcodecs.Quantize(digits=3)], + ) + + a[:, :] = data.copy() + b = open_array(a.store, mode="r") + assert np.allclose(data, b[:, :], atol=0.001) + + +def test_generic_filter_packbits() -> None: + data = np.zeros((16, 16), dtype="bool") + data[0:4, :] = True + + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + filters=[_numcodecs.PackBits()], + ) + + a[:, :] = data.copy() + b = open_array(a.store, mode="r") + np.testing.assert_array_equal(data, b[:, :]) + + with pytest.raises(ValueError, match=".*requires bool dtype.*"): + create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype="uint32", + fill_value=0, + filters=[_numcodecs.PackBits()], + ) + + +@pytest.mark.parametrize( + "codec_class", + [ + _numcodecs.CRC32, + _numcodecs.CRC32C, + _numcodecs.Adler32, + _numcodecs.Fletcher32, + _numcodecs.JenkinsLookup3, + ], +) +def test_generic_checksum(codec_class: type[_numcodecs._NumcodecsBytesBytesCodec]) -> None: + # Check if the codec is available in numcodecs + try: + codec_class()._codec # noqa: B018 + except UnknownCodecError as e: # pragma: no cover + pytest.skip(f"{codec_class.codec_name} is not available in numcodecs: {e}") # type: ignore[misc] + + data = np.linspace(0, 10, 256, dtype="float32").reshape((16, 16)) + + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + compressors=[codec_class()], + ) + + a[:, :] = data.copy() + with codec_conf(): + b = open_array(a.store, mode="r") + np.testing.assert_array_equal(data, b[:, :]) + + +@pytest.mark.parametrize("codec_class", [_numcodecs.PCodec, _numcodecs.ZFPY]) +def test_generic_bytes_codec(codec_class: type[_numcodecs._NumcodecsArrayBytesCodec]) -> None: + try: + codec_class()._codec # noqa: B018 + except ValueError as e: # pragma: no cover + if "codec not available" in str(e): + pytest.xfail(f"{codec_class.codec_name} is not available: {e}") # type: ignore[misc] + else: + raise + except ImportError as e: # pragma: no cover + pytest.xfail(f"{codec_class.codec_name} is not available: {e}") # type: ignore[misc] + + data = np.arange(0, 256, dtype="float32").reshape((16, 16)) + + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + serializer=codec_class(), + ) + + a[:, :] = data.copy() + np.testing.assert_array_equal(data, a[:, :]) + + +def test_delta_astype() -> None: + data = np.linspace(0, 10, 256, dtype="i8").reshape((16, 16)) + + a = create_array( + {}, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + filters=[ + _numcodecs.Delta(dtype="i8", astype="i2"), + ], + ) + + a[:, :] = data.copy() + with codec_conf(): + b = open_array(a.store, mode="r") + np.testing.assert_array_equal(data, b[:, :]) + + +def test_repr() -> None: + codec = _numcodecs.LZ4(level=5) + assert repr(codec) == "LZ4(codec_name='numcodecs.lz4', codec_config={'level': 5})" + + +def test_to_dict() -> None: + codec = _numcodecs.LZ4(level=5) + assert codec.to_dict() == {"name": "numcodecs.lz4", "configuration": {"level": 5}} + + +@pytest.mark.parametrize( + "codec_cls", + [ + _numcodecs.Blosc, + _numcodecs.LZ4, + _numcodecs.Zstd, + _numcodecs.Zlib, + _numcodecs.GZip, + _numcodecs.BZ2, + _numcodecs.LZMA, + _numcodecs.Shuffle, + _numcodecs.BitRound, + _numcodecs.Delta, + _numcodecs.FixedScaleOffset, + _numcodecs.Quantize, + _numcodecs.PackBits, + _numcodecs.AsType, + _numcodecs.CRC32, + _numcodecs.CRC32C, + _numcodecs.Adler32, + _numcodecs.Fletcher32, + _numcodecs.JenkinsLookup3, + _numcodecs.PCodec, + _numcodecs.ZFPY, + ], +) +def test_codecs_pickleable(codec_cls: type[_numcodecs._NumcodecsCodec]) -> None: + # Check if the codec is available in numcodecs + try: + codec = codec_cls() + except UnknownCodecError as e: # pragma: no cover + pytest.skip(f"{codec_cls.codec_name} is not available in numcodecs: {e}") # type: ignore[misc] + + expected = codec + + p = pickle.dumps(codec) + actual = pickle.loads(p) + assert actual == expected diff --git a/tests/test_codecs/test_scale_offset.py b/tests/test_codecs/test_scale_offset.py new file mode 100644 index 0000000000..0081bb1901 --- /dev/null +++ b/tests/test_codecs/test_scale_offset.py @@ -0,0 +1,483 @@ +from __future__ import annotations + +from typing import Any + +import numpy as np +import pytest + +import zarr +from tests.conftest import Expect, ExpectFail +from zarr.codecs.scale_offset import ( + ScaleOffset, + _decode, + _decode_fits_natively, + _encode, +) +from zarr.core.buffer.core import default_buffer_prototype +from zarr.storage._memory import MemoryStore + +# --------------------------------------------------------------------------- +# Serialization +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "case", + [ + Expect(input=ScaleOffset(), output={"name": "scale_offset"}, id="default"), + Expect( + input=ScaleOffset(offset=5), + output={"name": "scale_offset", "configuration": {"offset": 5}}, + id="offset-only", + ), + Expect( + input=ScaleOffset(scale=0.1), + output={"name": "scale_offset", "configuration": {"scale": 0.1}}, + id="scale-only", + ), + Expect( + input=ScaleOffset(offset=5, scale=0.1), + output={"name": "scale_offset", "configuration": {"offset": 5, "scale": 0.1}}, + id="both", + ), + ], + ids=lambda c: c.id, +) +def test_to_dict(case: Expect[ScaleOffset, dict[str, Any]]) -> None: + """to_dict produces the expected JSON structure.""" + assert case.input.to_dict() == case.output + + +@pytest.mark.parametrize( + "case", + [ + Expect(input={"name": "scale_offset"}, output=(0, 1), id="no-config"), + Expect( + input={"name": "scale_offset", "configuration": {"offset": 3, "scale": 2}}, + output=(3, 2), + id="with-config", + ), + ], + ids=lambda c: c.id, +) +def test_from_dict(case: Expect[dict[str, Any], tuple[int | float, int | float]]) -> None: + """from_dict deserializes configuration with correct values and defaults.""" + codec = ScaleOffset.from_dict(case.input) + expected_offset, expected_scale = case.output + assert codec.offset == expected_offset + assert codec.scale == expected_scale + + +def test_serialization_roundtrip() -> None: + """to_dict followed by from_dict produces an equal codec.""" + original = ScaleOffset(offset=7, scale=0.5) + restored = ScaleOffset.from_dict(original.to_dict()) + assert original == restored + + +# --------------------------------------------------------------------------- +# Construction +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input={"offset": [1, 2]}, + exception=TypeError, + id="list-offset", + msg="offset must be a number or string", + ), + ExpectFail( + input={"scale": [1, 2]}, + exception=TypeError, + id="list-scale", + msg="scale must be a number or string", + ), + ], + ids=lambda c: c.id, +) +def test_construction_rejects_non_numeric(case: ExpectFail[dict[str, Any]]) -> None: + """Non-numeric offset or scale is rejected at construction time.""" + with case.raises(): + ScaleOffset(**case.input) + + +@pytest.mark.parametrize( + "case", + [ + Expect(input={"offset": 5, "scale": 2}, output=(5, 2), id="int"), + Expect(input={"offset": 0.5, "scale": 0.1}, output=(0.5, 0.1), id="float"), + ], + ids=lambda c: c.id, +) +def test_construction_accepts_numeric( + case: Expect[dict[str, Any], tuple[int | float, int | float]], +) -> None: + """Integer and float values are accepted for both parameters.""" + codec = ScaleOffset(**case.input) + assert codec.offset == case.output[0] + assert codec.scale == case.output[1] + + +# --------------------------------------------------------------------------- +# Encode / decode +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("dtype", "offset", "scale"), + [ + ("float64", 10.0, 0.1), + ("float32", 5.0, 2.0), + ("int32", 0, 1), + ], + ids=["float64", "float32", "int32-identity"], +) +def test_encode_decode_roundtrip(dtype: str, offset: float, scale: float) -> None: + """Data survives encode β†’ decode.""" + + arr = zarr.create_array( + store={}, + shape=(100,), + dtype=dtype, + chunks=(100,), + filters=[ScaleOffset(offset=offset, scale=scale)], + compressors=None, + fill_value=0, + ) + data = np.arange(100, dtype=dtype) + arr[:] = data + np.testing.assert_array_almost_equal(arr[:], data) # type: ignore[arg-type] + + +def test_fill_value_transformed() -> None: + """Fill value is transformed through the encode formula and read back correctly.""" + arr = zarr.create_array( + store={}, + shape=(10,), + dtype="float64", + chunks=(10,), + filters=[ScaleOffset(offset=5, scale=2)], + compressors=None, + fill_value=10.0, + ) + # fill_value=10.0, encode: (10 - 5) * 2 = 10.0 stored + # Reading back without writing should return the original fill value + np.testing.assert_array_equal(arr[:], np.full(10, 10.0)) + + +def test_identity_is_noop() -> None: + """Default codec (offset=0, scale=1) is a no-op.""" + import zarr + + arr = zarr.create_array( + store={}, + shape=(50,), + dtype="float64", + chunks=(50,), + filters=[ScaleOffset()], + compressors=None, + fill_value=0, + ) + data = np.arange(50, dtype="float64") + arr[:] = data + np.testing.assert_array_equal(arr[:], data) + + +def test_rejects_complex_dtype() -> None: + """Complex dtypes are rejected at array creation time.""" + + with pytest.raises(ValueError, match="only supports integer and floating-point"): + zarr.create_array( + store={}, + shape=(10,), + dtype="complex128", + chunks=(10,), + filters=[ScaleOffset(offset=1, scale=2)], + compressors=None, + fill_value=0, + ) + + +def test_uint64_large_value_roundtrip() -> None: + """uint64 values above 2**63 must survive encode+decode (spec requires uint64 support).""" + + arr = zarr.create_array( + store={}, + shape=(3,), + dtype="uint64", + chunks=(3,), + filters=[ScaleOffset(offset=0, scale=1)], + compressors=None, + fill_value=0, + ) + # Value above int64.max (2**63 - 1) β€” would wrap if we used int64 as wide dtype. + data = np.array([0, 2**63, 2**64 - 1], dtype="uint64") + arr[:] = data + np.testing.assert_array_equal(arr[:], data) + + +def test_float_nan_inf_preserved() -> None: + """NaN and Inf are representable in float dtypes per IEEE 754 and must pass through.""" + + arr = np.array([1.0, np.nan, np.inf, -np.inf], dtype="float64") + encoded = _encode(arr, np.float64(0.0), np.float64(2.0)) + np.testing.assert_array_equal(encoded[[0]], np.array([2.0])) + assert np.isnan(encoded[1]) + assert encoded[2] == np.inf + assert encoded[3] == -np.inf + decoded = _decode(encoded, np.float64(0.0), np.float64(2.0), scale_repr=2.0) + np.testing.assert_array_equal(decoded[[0]], np.array([1.0])) + assert np.isnan(decoded[1]) + + +def test_uint64_encode_rejects_underflow() -> None: + """uint64 underflow during encode raises rather than silently wrapping.""" + + arr = zarr.create_array( + store={}, + shape=(3,), + dtype="uint64", + chunks=(3,), + filters=[ScaleOffset(offset=100, scale=1)], + compressors=None, + fill_value=100, + ) + with pytest.raises(ValueError, match="outside the range of dtype uint64"): + arr[:] = np.array([100, 50, 200], dtype="uint64") + + +@pytest.mark.parametrize( + ("dtype", "scale"), + [ + ("int32", 0), + ("int32", "0"), + ("float64", 0.0), + ("float64", "0.0"), + ("float64", "0x0000000000000000"), + ], + ids=["int-numeric", "int-string", "float-numeric", "float-string", "float-hex"], +) +def test_rejects_zero_scale(dtype: str, scale: object) -> None: + """scale=0 is rejected (destroys data and breaks decode division). + + A string ``scale`` is a documented input, so every spelling of zero has to be + rejected the same way as the numeric one. + """ + + with pytest.raises(ValueError, match="scale must be non-zero"): + zarr.create_array( + store={}, + shape=(10,), + dtype=dtype, + chunks=(10,), + filters=[ScaleOffset(offset=0, scale=scale)], + compressors=None, + fill_value=0, + ) + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input={"dtype": "int32", "offset": 1.5, "scale": 1}, + exception=ValueError, + id="float-offset-for-int", + msg="offset value 1.5 is not representable", + ), + ExpectFail( + input={"dtype": "int32", "offset": 0, "scale": 0.5}, + exception=ValueError, + id="float-scale-for-int", + msg="scale value 0.5 is not representable", + ), + ExpectFail( + input={"dtype": "int16", "offset": "NaN", "scale": 1}, + exception=ValueError, + id="nan-offset-for-int", + msg="offset value 'NaN' is not representable", + ), + ], + ids=lambda c: c.id, +) +def test_rejects_unrepresentable_scale_offset(case: ExpectFail[dict[str, Any]]) -> None: + """Scale/offset values that can't be represented in the array dtype are rejected.""" + + with case.raises(): + zarr.create_array( + store={}, + shape=(10,), + dtype=case.input["dtype"], + chunks=(10,), + filters=[ScaleOffset(offset=case.input["offset"], scale=case.input["scale"])], + compressors=None, + fill_value=0, + ) + + +def test_dtype_preservation() -> None: + """Integer scale/offset arithmetic preserves the array dtype when division is exact.""" + + arr = zarr.create_array( + store={}, + shape=(10,), + dtype="int8", + chunks=(10,), + filters=[ScaleOffset(offset=1, scale=2)], + compressors=None, + fill_value=0, + ) + data = np.arange(10, dtype="int8") + arr[:] = data + # encode=(x-1)*2 is always divisible by scale=2, so decode is exact + np.testing.assert_array_equal(arr[:], data) + + +async def test_integer_decode_rejects_non_exact_division() -> None: + """Decoding an integer array raises when the stored value isn't divisible by scale.""" + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(3,), + dtype="int8", + chunks=(3,), + filters=[ScaleOffset(offset=0, scale=2)], + compressors=None, + fill_value=0, + ) + # Write raw encoded bytes directly so we can inject a value that isn't divisible by scale. + # Array layout: int8 [2, 3, 4]; 3 % 2 != 0, so decode must fail. + + buf = default_buffer_prototype().buffer.from_bytes(np.array([2, 3, 4], dtype="int8").tobytes()) + await arr.store_path.store.set("c/0", buf) + with pytest.raises(ValueError, match="non-zero remainder"): + arr[:] + + +def test_encode_rejects_signed_integer_overflow() -> None: + """Encoding raises when (value - offset) * scale exceeds the target integer range.""" + arr = zarr.create_array( + store={}, + shape=(3,), + dtype="int8", + chunks=(3,), + filters=[ScaleOffset(offset=0, scale=100)], + compressors=None, + fill_value=0, + ) + # 2 * 100 = 200, outside int8 range [-128, 127] + with pytest.raises(ValueError, match="outside the range of dtype int8"): + arr[:] = np.array([0, 1, 2], dtype="int8") + + +def test_encode_rejects_unsigned_integer_underflow() -> None: + """Encoding raises when value - offset underflows an unsigned dtype.""" + arr = zarr.create_array( + store={}, + shape=(3,), + dtype="uint8", + chunks=(3,), + filters=[ScaleOffset(offset=10, scale=1)], + compressors=None, + fill_value=10, + ) + # 5 - 10 = -5, outside uint8 range [0, 255] + with pytest.raises(ValueError, match="outside the range of dtype uint8"): + arr[:] = np.array([10, 5, 20], dtype="uint8") + + +def test_float32_dtype_preserved() -> None: + """float32 arrays survive encode+decode without being promoted to float64.""" + arr = np.arange(100, dtype="float32") + offset = np.float32(5.0) + scale = np.float32(0.25) + encoded = _encode(arr, offset, scale) + assert encoded.dtype == np.dtype("float32") + decoded = _decode(encoded, offset, scale, scale_repr=0.25) + assert decoded.dtype == np.dtype("float32") + + +def test_float_encode_rejects_wider_scalar() -> None: + """A float64 scalar passed with a float32 array must not silently widen the result.""" + arr = np.arange(10, dtype="float32") + # A numpy float64 scalar (not a Python float β€” NEP 50 exempts those) mixed with a + # float32 ndarray promotes to float64. The codec must reject that. + with pytest.raises(ValueError, match="changed dtype from float32 to float64"): + _encode(arr, np.float64(5.0), np.float64(0.25)) + + +def test_float_decode_rejects_wider_scalar() -> None: + """A float64 scalar passed with a float32 array must not silently widen on decode.""" + arr = np.arange(10, dtype="float32") + with pytest.raises(ValueError, match="changed dtype from float32 to float64"): + _decode(arr, np.float64(5.0), np.float64(0.25), scale_repr=0.25) + + +async def test_decode_rejects_integer_overflow_on_offset_add() -> None: + """Decoding raises when quotient + offset overflows the target integer dtype.""" + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(3,), + dtype="int8", + chunks=(3,), + filters=[ScaleOffset(offset=100, scale=1)], + compressors=None, + fill_value=0, + ) + # encoded=100 β†’ decoded = 100/1 + 100 = 200, outside int8 range + buf = default_buffer_prototype().buffer.from_bytes( + np.array([0, 50, 100], dtype="int8").tobytes() + ) + await arr.store_path.store.set("c/0", buf) + with pytest.raises(ValueError, match="outside the range of dtype int8"): + arr[:] + + +def test_decode_fits_natively_negative_scale() -> None: + """_decode_fits_natively handles negative scale by swapping bounds.""" + # For a negative scale, x // scale flips the relationship between min/max. + # The function should use info.max // scale as the lower bound and info.min // scale + # as the upper bound. + dtype = np.dtype("int16") + # scale=-2 inverts; offset=0 means range is just q_lo..q_hi + assert _decode_fits_natively(dtype, offset=0, scale=-2) is True + # An offset that pushes the range out of bounds returns False + assert _decode_fits_natively(dtype, offset=100000, scale=-2) is False + + +async def test_decode_int_widened_path() -> None: + """When _decode_fits_natively returns False, decode falls through to the widened path.""" + # For uint32 with offset near max, q_hi + offset can exceed uint32 if computed in target dtype. + # The widened path uses int64 arithmetic and range-checks the result. + # We bypass encode by writing raw bytes directly to the store. + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(3,), + dtype="uint32", + chunks=(3,), + # offset large enough that _decode_fits_natively returns False + filters=[ScaleOffset(offset=2**31, scale=1)], + compressors=None, + # fill_value must be >= offset to avoid uint32 underflow during encode + fill_value=2**31, + ) + # Encoded values that, when added to offset, stay within uint32 + buf = default_buffer_prototype().buffer.from_bytes( + np.array([0, 100, 1000], dtype="uint32").tobytes() + ) + await arr.store_path.store.set("c/0", buf) + expected = np.array([2**31, 2**31 + 100, 2**31 + 1000], dtype="uint32") + np.testing.assert_array_equal(arr[:], expected) + + +def test_compute_encoded_size() -> None: + """compute_encoded_size returns the input byte length unchanged (codec is fixed-size).""" + codec = ScaleOffset(offset=0, scale=1) + # The chunk_spec argument is unused; pass any sentinel + assert codec.compute_encoded_size(input_byte_length=100, _chunk_spec=None) == 100 # type: ignore[arg-type] + assert codec.compute_encoded_size(input_byte_length=0, _chunk_spec=None) == 0 # type: ignore[arg-type] diff --git a/tests/test_codecs/test_sharding.py b/tests/test_codecs/test_sharding.py new file mode 100644 index 0000000000..de576dbef5 --- /dev/null +++ b/tests/test_codecs/test_sharding.py @@ -0,0 +1,1264 @@ +import enum +import pickle +import warnings +from typing import Any, cast, get_args +from unittest.mock import AsyncMock + +import numpy as np +import numpy.typing as npt +import pytest + +import zarr +import zarr.api +import zarr.api.asynchronous +from zarr import Array +from zarr.abc.store import Store +from zarr.codecs import ( + BloscCodec, + BytesCodec, + Crc32cCodec, + ShardingCodec, + TransposeCodec, +) +from zarr.codecs.sharding import ( + INDEX_LOCATION, + MAX_UINT_64, + IndexLocation, + ShardingCodecIndexLocation, + SubchunkWriteOrder, + _ShardIndex, + _ShardReader, +) +from zarr.core.buffer import NDArrayLike, default_buffer_prototype +from zarr.core.indexing import lexicographic_order_coords +from zarr.core.metadata.v3 import ArrayV3Metadata +from zarr.storage import MemoryStore, StorePath, ZipStore + +from ..conftest import ArrayRequest +from .test_codecs import _AsyncArrayProxy, order_from_dim + + +def _reads_are_sync(store_mock: AsyncMock) -> bool: + """True when the partial-shard read for this store+pipeline goes through the + synchronous methods (get_sync / get_ranges_sync). That requires BOTH the + configured pipeline to be the sync (Fused) one AND the store to support sync + reads β€” a Fused read against a non-sync store (e.g. ZipStore) falls back to + the async path. Lets the partial-shard-read tests assert the same intent + against whichever method family is actually exercised.""" + from zarr.abc.store import SupportsGetSync + from zarr.core.config import config + + pipeline_is_sync = "Fused" in config.get("codec_pipeline.path") + # store_mock wraps the real store; check the wrapped class for sync support. + wrapped = getattr(store_mock, "_mock_wraps", store_mock) + return pipeline_is_sync and isinstance(wrapped, SupportsGetSync) + + +def _index_read_count(store_mock: AsyncMock) -> int: + """Number of shard-index reads, regardless of sync/async pipeline.""" + method = store_mock.get_sync if _reads_are_sync(store_mock) else store_mock.get + return int(method.call_count) + + +def _range_read_count(store_mock: AsyncMock) -> int: + """Number of coalesced chunk-data reads, regardless of sync/async pipeline.""" + method = store_mock.get_ranges_sync if _reads_are_sync(store_mock) else store_mock.get_ranges + return int(method.call_count) + + +def _fail_index_read(store_mock: AsyncMock) -> None: + """Simulate the shard-index load returning nothing, for the active path.""" + if _reads_are_sync(store_mock): + store_mock.get_sync.return_value = None + else: + store_mock.get.return_value = None + + +def _fail_chunk_reads( + store_mock: AsyncMock, key_absent_exc: type[Exception] = FileNotFoundError +) -> None: + """Simulate chunk-data loads failing (key absent), for the active path. + + Async get_ranges raises a BaseExceptionGroup; the sync get_ranges_sync mirrors + that contract, so both inject a FileNotFoundError-bearing group.""" + if _reads_are_sync(store_mock): + + def fail_sync(key: str, byte_ranges: Any, **kwargs: Any) -> Any: + raise BaseExceptionGroup("chunk read failed", [key_absent_exc(key)]) + + store_mock.get_ranges_sync = fail_sync + else: + + async def fail_async(key: str, byte_ranges: Any, **kwargs: Any) -> Any: + raise BaseExceptionGroup("chunk read failed", [key_absent_exc(key)]) + yield # type: ignore[unreachable] # marks this as an async generator + + store_mock.get_ranges = fail_async + + +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize( + "array_fixture", + [ + ArrayRequest(shape=(128,) * 1, dtype="uint8", order="C"), + ArrayRequest(shape=(128,) * 2, dtype="uint8", order="C"), + ArrayRequest(shape=(128,) * 3, dtype="uint16", order="F"), + ], + indirect=["array_fixture"], +) +@pytest.mark.parametrize("offset", [0, 10]) +def test_sharding( + store: Store, + array_fixture: npt.NDArray[Any], + index_location: IndexLocation, + offset: int, +) -> None: + """ + Test that we can create an array with a sharding codec, write data to that array, and get + the same data out via indexing. + """ + data = array_fixture + spath = StorePath(store) + + arr = zarr.create_array( + spath, + shape=tuple(s + offset for s in data.shape), + chunks=(32,) * data.ndim, + shards={"shape": (64,) * data.ndim, "index_location": index_location}, + dtype=data.dtype, + fill_value=6, + filters=[TransposeCodec(order=order_from_dim("F", data.ndim))], + compressors=BloscCodec(cname="lz4"), + ) + write_region = tuple(slice(offset, None) for dim in range(data.ndim)) + arr[write_region] = data + + if offset > 0: + empty_region = tuple(slice(0, offset) for dim in range(data.ndim)) + assert np.all(arr[empty_region] == arr.metadata.fill_value) + + read_data = arr[write_region] + assert isinstance(read_data, NDArrayLike) + assert data.shape == read_data.shape + assert np.array_equal(data, read_data) + + +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("offset", [0, 10]) +def test_sharding_scalar( + store: Store, + index_location: IndexLocation, + offset: int, +) -> None: + """ + Test that we can create an array with a sharding codec, write data to that array, and get + the same data out via indexing. + """ + spath = StorePath(store) + + arr = zarr.create_array( + spath, + shape=(128, 128), + chunks=(32, 32), + shards={"shape": (64, 64), "index_location": index_location}, + dtype="uint8", + fill_value=6, + filters=[TransposeCodec(order=order_from_dim("F", 2))], + compressors=BloscCodec(cname="lz4"), + ) + arr[:16, :16] = 10 # intentionally write partial chunks + read_data = arr[:16, :16] + np.testing.assert_array_equal(read_data, 10) + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +@pytest.mark.parametrize( + "array_fixture", + [ + ArrayRequest(shape=(128,) * 3, dtype="uint16", order="F"), + ], + indirect=["array_fixture"], +) +def test_sharding_partial( + store: Store, array_fixture: npt.NDArray[Any], index_location: IndexLocation +) -> None: + data = array_fixture + spath = StorePath(store) + a = zarr.create_array( + spath, + shape=tuple(a + 10 for a in data.shape), + chunks=(32, 32, 32), + shards={"shape": (64, 64, 64), "index_location": index_location}, + compressors=BloscCodec(cname="lz4"), + filters=[TransposeCodec(order=order_from_dim("F", data.ndim))], + dtype=data.dtype, + fill_value=0, + ) + + a[10:, 10:, 10:] = data + + read_data = a[0:10, 0:10, 0:10] + assert np.all(read_data == 0) + + read_data = a[10:, 10:, 10:] + assert isinstance(read_data, NDArrayLike) + assert data.shape == read_data.shape + assert np.array_equal(data, read_data) + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +@pytest.mark.parametrize( + "array_fixture", + [ + ArrayRequest(shape=(128,) * 3, dtype="uint16", order="F"), + ], + indirect=["array_fixture"], +) +def test_sharding_partial_readwrite( + store: Store, array_fixture: npt.NDArray[Any], index_location: IndexLocation +) -> None: + data = array_fixture + spath = StorePath(store) + a = zarr.create_array( + spath, + shape=data.shape, + chunks=(1, data.shape[1], data.shape[2]), + shards={"shape": data.shape, "index_location": index_location}, + dtype=data.dtype, + fill_value=0, + filters=None, + compressors=None, + ) + + a[:] = data + + for x in range(data.shape[0]): + read_data = a[x, :, :] + assert np.array_equal(data[x], read_data) + + +@pytest.mark.parametrize( + "array_fixture", + [ + ArrayRequest(shape=(128,) * 3, dtype="uint16", order="F"), + ], + indirect=["array_fixture"], +) +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_partial_read( + store: Store, array_fixture: npt.NDArray[Any], index_location: IndexLocation +) -> None: + data = array_fixture + spath = StorePath(store) + a = zarr.create_array( + spath, + shape=tuple(a + 10 for a in data.shape), + chunks=(32, 32, 32), + shards={"shape": (64, 64, 64), "index_location": index_location}, + compressors=BloscCodec(cname="lz4"), + filters=[TransposeCodec(order=order_from_dim("F", data.ndim))], + dtype=data.dtype, + fill_value=1, + ) + + read_data = a[0:10, 0:10, 0:10] + assert np.all(read_data == 1) + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_multiple_chunks_partial_shard_read( + store: Store, + index_location: IndexLocation, +) -> None: + array_shape = (16, 64) + shard_shape = (8, 32) + chunk_shape = (2, 4) + data = np.arange(np.prod(array_shape), dtype="float32").reshape(array_shape) + + store_mock = AsyncMock(wraps=store, spec=store.__class__) + a = zarr.create_array( + StorePath(store_mock), + shape=data.shape, + chunks=chunk_shape, + shards={"shape": shard_shape, "index_location": index_location}, + compressors=BloscCodec(cname="lz4"), + dtype=data.dtype, + fill_value=1, + ) + a[:] = data + + store_mock.reset_mock() # ignore store calls during array creation + + # Reads 3 (2 full, 1 partial) chunks each from 2 shards (a subset of both shards) + # for a total of 6 chunks accessed + assert np.allclose(a[0, 22:42], np.arange(22, 42, dtype="float32")) + + # 2 shard index reads + 2 coalesced chunk-data reads (one per shard) + assert _index_read_count(store_mock) == 2 + assert _range_read_count(store_mock) == 2 + + store_mock.reset_mock() + + # Reads 4 chunks from both shards along dimension 0 for a total of 8 chunks accessed + assert np.allclose(a[:, 0], np.arange(0, data.size, array_shape[1], dtype="float32")) + + # 2 shard index reads + 2 coalesced chunk-data reads (one per shard) + assert _index_read_count(store_mock) == 2 + assert _range_read_count(store_mock) == 2 + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_duplicate_read_indexes( + store: Store, + index_location: IndexLocation, +) -> None: + """ + Check that duplicate index reads are handled correctly when + using get_ranges for chunk data. + """ + array_shape = (15,) + shard_shape = (8,) + chunk_shape = (2,) + data = np.arange(np.prod(array_shape), dtype="float32").reshape(array_shape) + + store_mock = AsyncMock(wraps=store, spec=store.__class__) + a = zarr.create_array( + StorePath(store_mock), + shape=data.shape, + chunks=chunk_shape, + shards={"shape": shard_shape, "index_location": index_location}, + compressors=BloscCodec(cname="lz4"), + dtype=data.dtype, + fill_value=-1, + ) + a[:] = data + + store_mock.reset_mock() # ignore store calls during array creation + + # Read the same index multiple times from two chunks + indexer = [8, 8, 12, 12] + assert np.array_equal(a[indexer], data[indexer]) + + # 1 shard index read + 1 coalesced chunk-data read + assert _index_read_count(store_mock) == 1 + assert _range_read_count(store_mock) == 1 + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_read_empty_chunks_within_non_empty_shard_write_empty_false( + store: Store, index_location: IndexLocation +) -> None: + """ + Case where + - some, but not all, chunks in the last shard are empty + - the last shard is not complete (array length is not a multiple of shard shape), + this takes us down the partial shard read path + - write_empty_chunks=False so the shard index will have fewer entries than chunks in the shard + """ + # array with mixed empty and non-empty chunks in second shard + data = np.array([ + # shard 0. full 8 elements, all chunks have some non-fill data + 0, 1, 2, 3, 4, 5, 6, 7, + # shard 1. 6 elements (< shard shape) + 2, 0, # chunk 0, written + -9, -9, # chunk 1, all fill, not written + 4, 5 # chunk 2, written + ], dtype="int32") # fmt: off + + spath = StorePath(store) + a = zarr.create_array( + spath, + shape=(14,), + chunks=(2,), + shards={"shape": (8,), "index_location": index_location}, + dtype="int32", + fill_value=-9, + filters=None, + compressors=None, + config={"write_empty_chunks": False}, + ) + a[:] = data + + assert np.array_equal(a[:], data) + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_read_empty_chunks_within_empty_shard_write_empty_false( + store: Store, index_location: IndexLocation +) -> None: + """ + Case where + - all chunks in last shard are empty + - the last shard is not complete (array length is not a multiple of shard shape), + this takes us down the partial shard read path + - write_empty_chunks=False so the shard index will have no entries + """ + fill_value = -99 + shard_size = 8 + data = np.arange(14, dtype="int32") + data[shard_size:] = fill_value # 2nd shard is all fill value + + spath = StorePath(store) + a = zarr.create_array( + spath, + shape=(14,), + chunks=(2,), + shards={"shape": (shard_size,), "index_location": index_location}, + dtype="int32", + fill_value=fill_value, + filters=None, + compressors=None, + config={"write_empty_chunks": False}, + ) + a[:] = data + + assert np.array_equal(a[:], data) + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_partial_shard_read__index_load_fails( + store: Store, index_location: IndexLocation +) -> None: + """Test fill value is returned when the call to the store to load the bytes of the shard's chunk index fails.""" + array_shape = (16,) + shard_shape = (16,) + chunk_shape = (8,) + data = np.arange(np.prod(array_shape), dtype="float32").reshape(array_shape) + fill_value = -999 + + store_mock = AsyncMock(wraps=store, spec=store.__class__) + + a = zarr.create_array( + StorePath(store_mock), + shape=data.shape, + chunks=chunk_shape, + shards={"shape": shard_shape, "index_location": index_location}, + compressors=BloscCodec(cname="lz4"), + dtype=data.dtype, + fill_value=fill_value, + ) + a[:] = data + + # Loading the index returns None -> simulate an index load failure, on + # whichever read method the active pipeline uses (get / get_sync). + _fail_index_read(store_mock) + + # Read from one of two chunks in a shard to test the partial shard read path + assert a[0] == fill_value + assert a[0] != data[0] + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_partial_shard_read__index_chunk_slice_fails( + store: Store, + index_location: IndexLocation, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Test fill value is returned when looking up a chunk's byte slice within a shard fails.""" + array_shape = (16,) + shard_shape = (16,) + chunk_shape = (8,) + data = np.arange(np.prod(array_shape), dtype="float32").reshape(array_shape) + fill_value = -999 + + monkeypatch.setattr( + "zarr.codecs.sharding._ShardIndex.get_chunk_slice", + lambda self, chunk_coords: None, + ) + + a = zarr.create_array( + StorePath(store), + shape=data.shape, + chunks=chunk_shape, + shards={"shape": shard_shape, "index_location": index_location}, + compressors=BloscCodec(cname="lz4"), + dtype=data.dtype, + fill_value=fill_value, + ) + a[:] = data + + # Read from one of two chunks in a shard to test the partial shard read path + assert a[0] == fill_value + assert a[0] != data[0] + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_partial_shard_read__chunk_load_fails( + store: Store, index_location: IndexLocation +) -> None: + """Test fill value is returned when the call to the store to load a chunk's bytes fails.""" + array_shape = (16,) + shard_shape = (16,) + chunk_shape = (8,) + data = np.arange(np.prod(array_shape), dtype="float32").reshape(array_shape) + fill_value = -999 + + store_mock = AsyncMock(wraps=store, spec=store.__class__) + + a = zarr.create_array( + StorePath(store_mock), + shape=data.shape, + chunks=chunk_shape, + shards={"shape": shard_shape, "index_location": index_location}, + compressors=BloscCodec(cname="lz4"), + dtype=data.dtype, + fill_value=fill_value, + ) + a[:] = data + + # Set up store mock after array creation to simulate chunk load failure. + # Index loads still succeed, but chunk-byte loads fail (the coalesced range + # read raises a BaseExceptionGroup containing FileNotFoundError β€” the same + # shape produced when a key is absent), on whichever read method the active + # pipeline uses (get_ranges / get_ranges_sync). + store_mock.reset_mock() + _fail_chunk_reads(store_mock) + + # Read from one of two chunks in a shard to test the partial shard read path + assert a[0] == fill_value + assert a[0] != data[0] + + +@pytest.mark.parametrize( + "array_fixture", + [ + ArrayRequest(shape=(128,) * 3, dtype="uint16", order="F"), + ], + indirect=["array_fixture"], +) +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_sharding_partial_overwrite( + store: Store, array_fixture: npt.NDArray[Any], index_location: IndexLocation +) -> None: + data = array_fixture[:10, :10, :10] + spath = StorePath(store) + a = zarr.create_array( + spath, + shape=tuple(a + 10 for a in data.shape), + chunks=(32, 32, 32), + shards={"shape": (64, 64, 64), "index_location": index_location}, + compressors=BloscCodec(cname="lz4"), + filters=[TransposeCodec(order=order_from_dim("F", data.ndim))], + dtype=data.dtype, + fill_value=1, + ) + + a[:10, :10, :10] = data + + read_data = a[0:10, 0:10, 0:10] + assert np.array_equal(data, read_data) + + data += 10 + if isinstance(store, ZipStore): + with pytest.warns(UserWarning, match="Duplicate name: "): + a[:10, :10, :10] = data + else: + a[:10, :10, :10] = data + read_data = a[0:10, 0:10, 0:10] + assert np.array_equal(data, read_data) + + +# Zip storage raises a warning about a duplicate name, which we ignore. +@pytest.mark.filterwarnings("ignore:Duplicate name.*:UserWarning") +@pytest.mark.parametrize( + "array_fixture", + [ + ArrayRequest(shape=(127, 128, 129), dtype="uint16", order="F"), + ], + indirect=True, +) +@pytest.mark.parametrize( + "outer_index_location", + ["start", "end"], +) +@pytest.mark.parametrize( + "inner_index_location", + ["start", "end"], +) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_nested_sharding( + store: Store, + array_fixture: npt.NDArray[Any], + outer_index_location: IndexLocation, + inner_index_location: IndexLocation, +) -> None: + data = array_fixture + spath = StorePath(store) + # compressors=None ensures no BytesBytesCodec is added, which keeps + # supports_partial_decode=True and exercises the partial decode path + a = zarr.create_array( + spath, + data=data, + chunks=(64,) * data.ndim, + compressors=None, + serializer=ShardingCodec( + chunk_shape=(32,) * data.ndim, + codecs=[ + ShardingCodec(chunk_shape=(16,) * data.ndim, index_location=inner_index_location) + ], + index_location=outer_index_location, + ), + ) + + a[:] = data + + read_data = a[0 : data.shape[0], 0 : data.shape[1], 0 : data.shape[2]] + assert isinstance(read_data, NDArrayLike) + assert data.shape == read_data.shape + assert np.array_equal(data, read_data) + + +@pytest.mark.parametrize( + "array_fixture", + [ + ArrayRequest(shape=(128,) * 3, dtype="uint16", order="F"), + ], + indirect=["array_fixture"], +) +@pytest.mark.parametrize( + "outer_index_location", + ["start", "end"], +) +@pytest.mark.parametrize( + "inner_index_location", + ["start", "end"], +) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_nested_sharding_create_array( + store: Store, + array_fixture: npt.NDArray[Any], + outer_index_location: IndexLocation, + inner_index_location: IndexLocation, +) -> None: + data = array_fixture + spath = StorePath(store) + a = zarr.create_array( + spath, + shape=data.shape, + chunks=(32, 32, 32), + dtype=data.dtype, + fill_value=0, + serializer=ShardingCodec( + chunk_shape=(32, 32, 32), + codecs=[ShardingCodec(chunk_shape=(16, 16, 16), index_location=inner_index_location)], + index_location=outer_index_location, + ), + filters=None, + compressors=None, + ) + + a[:] = data + + read_data = a[:] + assert np.array_equal(data, read_data) + + +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_open_sharding(store: Store) -> None: + path = "open_sharding" + spath = StorePath(store, path) + a = zarr.create_array( + spath, + shape=(16, 16), + chunks=(8, 8), + shards=(16, 16), + filters=[TransposeCodec(order=order_from_dim("F", 2))], + compressors=BloscCodec(), + dtype="int32", + fill_value=0, + ) + b = Array.open(spath) + assert a.metadata == b.metadata + + +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +def test_write_partial_sharded_chunks(store: Store) -> None: + data = np.arange(0, 16 * 16, dtype="uint16").reshape((16, 16)) + spath = StorePath(store) + a = zarr.create_array( + spath, + shape=(40, 40), + chunks=(10, 10), + shards=(20, 20), + dtype=data.dtype, + compressors=BloscCodec(), + fill_value=1, + ) + a[0:16, 0:16] = data + assert np.array_equal(a[0:16, 0:16], data) + + +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +async def test_delete_empty_shards(store: Store) -> None: + if not store.supports_deletes: + pytest.skip("store does not support deletes") + path = "delete_empty_shards" + spath = StorePath(store, path) + a = await zarr.api.asynchronous.create_array( + spath, + shape=(16, 16), + chunks=(8, 8), + shards=(8, 16), + dtype="uint16", + compressors=None, + fill_value=1, + ) + print(a.metadata.to_dict()) + await _AsyncArrayProxy(a)[:, :].set(np.zeros((16, 16))) + await _AsyncArrayProxy(a)[8:, :].set(np.ones((8, 16))) + await _AsyncArrayProxy(a)[:, 8:].set(np.ones((16, 8))) + # chunk (0, 0) is full + # chunks (0, 1), (1, 0), (1, 1) are empty + # shard (0, 0) is half-full + # shard (1, 0) is empty + + data = np.ones((16, 16), dtype="uint16") + data[:8, :8] = 0 + assert np.array_equal(data, await _AsyncArrayProxy(a)[:, :].get()) + assert await store.get(f"{path}/c/1/0", prototype=default_buffer_prototype()) is None + chunk_bytes = await store.get(f"{path}/c/0/0", prototype=default_buffer_prototype()) + assert chunk_bytes is not None + assert len(chunk_bytes) == 16 * 2 + 8 * 8 * 2 + 4 + + +def test_structured_dtype_fill_value() -> None: + """Sharded arrays with a structured dtype are writable and readable even though + the fill value is an (unhashable) ``np.void`` scalar: the sharding codec's + chunk-spec caches key on ``ArraySpec``, whose hash must handle void fills + (see https://github.com/zarr-developers/zarr-python/issues/3054).""" + dtype = np.dtype([("a", "i4"), ("b", "f4")]) + arr = zarr.create_array( + MemoryStore(), + shape=(8,), + chunks=(2,), + shards=(4,), + dtype=dtype, + fill_value=(1, 2.0), + ) + data = np.array([(i, i / 2) for i in range(8)], dtype=dtype) + arr[:4] = data[:4] + + expected = np.zeros(8, dtype=dtype) + expected[:4] = data[:4] + expected[4:] = (1, 2.0) # untouched shard reads back as the fill value + assert np.array_equal(arr[:], expected) + + +def test_pickle() -> None: + """ShardingCodec round-trips through pickle, including the non-serialized + ``subchunk_write_order`` (which ``to_dict`` omits and which must not silently + revert to the ``morton`` default).""" + codec = ShardingCodec(chunk_shape=(8, 8)) + assert pickle.loads(pickle.dumps(codec)) == codec + + ordered = ShardingCodec(chunk_shape=(8, 8), subchunk_write_order="lexicographic") + restored = pickle.loads(pickle.dumps(ordered)) + assert restored == ordered + assert restored.subchunk_write_order == "lexicographic" + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +@pytest.mark.parametrize("index_location", ["start", "end"]) +async def test_sharding_with_empty_inner_chunk(store: Store, index_location: IndexLocation) -> None: + data = np.arange(0, 16 * 16, dtype="uint32").reshape((16, 16)) + fill_value = 1 + + path = f"sharding_with_empty_inner_chunk_{index_location}" + spath = StorePath(store, path) + a = await zarr.api.asynchronous.create_array( + spath, + shape=(16, 16), + chunks=(4, 4), + shards={"shape": (8, 8), "index_location": index_location}, + dtype="uint32", + fill_value=fill_value, + ) + data[:4, :4] = fill_value + await a.setitem(..., data) + print("read data") + data_read = await a.getitem(...) + assert np.array_equal(data_read, data) + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize("chunks_per_shard", [(5, 2), (2, 5), (5, 5)]) +async def test_sharding_with_chunks_per_shard( + store: Store, index_location: IndexLocation, chunks_per_shard: tuple[int] +) -> None: + chunk_shape = (2, 1) + shape = tuple(x * y for x, y in zip(chunks_per_shard, chunk_shape, strict=False)) + data = np.ones(np.prod(shape), dtype="int32").reshape(shape) + fill_value = 42 + + path = f"test_sharding_with_chunks_per_shard_{index_location}" + spath = StorePath(store, path) + a = zarr.create_array( + spath, + shape=shape, + chunks=chunk_shape, + shards={"shape": shape, "index_location": index_location}, + dtype="int32", + fill_value=fill_value, + ) + a[...] = data + data_read = a[...] + assert np.array_equal(data_read, data) + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +def test_invalid_metadata(store: Store) -> None: + spath1 = StorePath(store, "invalid_inner_chunk_shape") + with pytest.raises(ValueError): + zarr.create_array( + spath1, + shape=(16, 16), + shards=(16, 16), + chunks=(8,), + dtype=np.dtype("uint8"), + fill_value=0, + ) + spath2 = StorePath(store, "invalid_inner_chunk_shape") + with pytest.raises(ValueError): + zarr.create_array( + spath2, + shape=(16, 16), + shards=(16, 16), + chunks=(8, 7), + dtype=np.dtype("uint8"), + fill_value=0, + ) + + +def test_invalid_shard_shape() -> None: + with pytest.raises( + ValueError, + match=( + f"Chunk edge length {16} in dimension {0} is not " + f"divisible by the shard's inner chunk size {9}\\." + ), + ): + zarr.create_array( + {}, + shape=(16, 16), + shards=(16, 16), + chunks=(9, 9), + dtype=np.dtype("uint8"), + fill_value=0, + ) + + +@pytest.mark.parametrize("store", ["local"], indirect=["store"]) +def test_sharding_mixed_integer_list_indexing(store: Store) -> None: + """Regression test for https://github.com/zarr-developers/zarr-python/issues/3691. + + Mixed integer/list indexing on sharded arrays should return the same + shape and data as on equivalent chunked arrays. + """ + import numpy as np + + data = np.arange(200 * 100 * 10, dtype=np.uint8).reshape(200, 100, 10) + + chunked = zarr.create_array( + store, + name="chunked", + shape=(200, 100, 10), + dtype=np.uint8, + chunks=(200, 100, 1), + overwrite=True, + ) + chunked[:, :, :] = data + + sharded = zarr.create_array( + store, + name="sharded", + shape=(200, 100, 10), + dtype=np.uint8, + chunks=(200, 100, 1), + shards=(200, 100, 10), + overwrite=True, + ) + sharded[:, :, :] = data + + # Mixed integer + list indexing + c = chunked[0:10, 0, [0, 1]] # type: ignore[index] + s = sharded[0:10, 0, [0, 1]] # type: ignore[index] + assert c.shape == s.shape == (10, 2), ( # type: ignore[union-attr] + f"Expected (10, 2), got chunked={c.shape}, sharded={s.shape}" # type: ignore[union-attr] + ) + np.testing.assert_array_equal(c, s) + + # Multiple integer axes + c2 = chunked[0, 0, [0, 1, 2]] # type: ignore[index] + s2 = sharded[0, 0, [0, 1, 2]] # type: ignore[index] + assert c2.shape == s2.shape == (3,) # type: ignore[union-attr] + np.testing.assert_array_equal(c2, s2) + + # Slice + integer + slice + c3 = chunked[0:5, 1, 0:3] + s3 = sharded[0:5, 1, 0:3] + assert c3.shape == s3.shape == (5, 3) # type: ignore[union-attr] + np.testing.assert_array_equal(c3, s3) + + +async def stored_data_and_get_order( + codec: ShardingCodec, chunks_per_shard: tuple[int, ...] +) -> list[tuple[int, ...]]: + shard_shape = tuple(c * s for c, s in zip(chunks_per_shard, codec.chunk_shape, strict=True)) + store = MemoryStore() + arr = zarr.create_array( + StorePath(store), + shape=shard_shape, + dtype="uint8", + chunks=shard_shape, + serializer=codec, + filters=None, + compressors=None, + fill_value=0, + ) + + arr[:] = np.arange(np.prod(shard_shape), dtype="uint8").reshape(shard_shape) + + shard_buf = await store.get("c/0/0", prototype=default_buffer_prototype()) + if shard_buf is None: + raise RuntimeError("data write failed") + index = (await _ShardReader.from_bytes(shard_buf, codec, chunks_per_shard)).index + offset_to_coord: dict[int, tuple[int, ...]] = dict( + zip( + index.get_chunk_slices_vectorized(np.array(list(np.ndindex(chunks_per_shard))))[ + 0 + ], # start + list(np.ndindex(chunks_per_shard)), # coord + strict=True, + ) + ) + + # The physical write order is recovered by sorting coordinates by start offset. + return [coord for _, coord in sorted(offset_to_coord.items())] + + +@pytest.mark.parametrize( + "subchunk_write_order", + get_args(SubchunkWriteOrder), +) +async def test_encoded_subchunk_write_order(subchunk_write_order: SubchunkWriteOrder) -> None: + """Subchunks must be physically laid out in the shard in the order specified by + ``subchunk_write_order``. We verify this by decoding the shard index and sorting + the chunk coordinates by their byte offset. ``unordered`` makes no stable-order + promise, but is deterministic in this implementation, so it is checked the same way.""" + # Use a non-square chunks_per_shard so all orderings are distinguishable. + chunks_per_shard = (3, 2) + chunk_shape = (4, 4) + codec = ShardingCodec( + chunk_shape=chunk_shape, + codecs=[BytesCodec()], + index_codecs=[BytesCodec(), Crc32cCodec()], + index_location="end", + subchunk_write_order=subchunk_write_order, + ) + + actual_order = await stored_data_and_get_order(codec, chunks_per_shard) + expected_order = list(codec._subchunk_order_iter(chunks_per_shard, subchunk_write_order)) + assert actual_order == expected_order + + +@pytest.mark.parametrize( + "subchunk_write_order", + get_args(SubchunkWriteOrder), +) +@pytest.mark.parametrize("do_partial", [True, False], ids=["partial", "complete"]) +def test_subchunk_write_order_roundtrip( + subchunk_write_order: SubchunkWriteOrder, do_partial: bool +) -> None: + """Data written with any ``subchunk_write_order`` must round-trip correctly.""" + chunks_per_shard = (3, 2) + chunk_shape = (4, 4) + shard_shape = tuple(c * s for c, s in zip(chunks_per_shard, chunk_shape, strict=True)) + data = np.arange(np.prod(shard_shape), dtype="uint16").reshape(shard_shape) + arr = zarr.create_array( + StorePath(MemoryStore()), + shape=shard_shape, + dtype=data.dtype, + chunks=shard_shape, + serializer=ShardingCodec( + chunk_shape=chunk_shape, + codecs=[BytesCodec()], + subchunk_write_order=subchunk_write_order, + ), + filters=None, + compressors=None, + fill_value=0, + ) + if do_partial: + sub_data = data[: (shard_shape[0] // 2)] + arr[: (shard_shape[0] // 2)] = data[: (shard_shape[0] // 2)] + data = np.vstack([sub_data, np.zeros_like(sub_data)]) + else: + arr[:] = data + np.testing.assert_array_equal(arr[:], data) + + +# --- Tests for ShardingCodecIndexLocation deprecation --- + + +@pytest.mark.parametrize("location", INDEX_LOCATION) +def test_sharding_codec_accepts_all_index_locations(location: IndexLocation) -> None: + """ + Every value in INDEX_LOCATION is accepted by ShardingCodec and round-trips + to the same value on the stored attribute. Catches drift between the + IndexLocation type alias and the runtime INDEX_LOCATION tuple. + """ + codec = ShardingCodec(chunk_shape=(1,), index_location=location) + assert codec.index_location == location + + +@pytest.mark.parametrize("location", INDEX_LOCATION) +def test_sharding_codec_json_roundtrip_index_location( + location: IndexLocation, +) -> None: + """ + ShardingCodec.to_dict writes index_location as the bare literal string, + and the round-trip through from_dict preserves equality. Asserting the + on-disk index_location value (not just the round-trip) catches drift + between ShardingCodec's runtime representation and the V3 wire form. + """ + codec = ShardingCodec(chunk_shape=(1,), index_location=location) + serialized = codec.to_dict() + assert serialized["configuration"]["index_location"] == location # type: ignore[index, call-overload] + restored = ShardingCodec.from_dict(serialized) + assert restored == codec + + +@pytest.mark.parametrize( + ("member", "expected"), + [("start", "start"), ("end", "end")], +) +def test_sharding_index_location_member_access_warns(member: str, expected: str) -> None: + """ + Accessing a member on the deprecated ShardingCodecIndexLocation class + emits a DeprecationWarning and resolves to the equivalent literal string. + """ + with pytest.warns(DeprecationWarning, match=rf"ShardingCodecIndexLocation\.{member}"): + value = getattr(ShardingCodecIndexLocation, member) + assert value == expected + + +def test_sharding_index_location_class_imports_silently() -> None: + """ + Importing the deprecated ShardingCodecIndexLocation class by name must not + emit a warning; only member access does. + """ + with warnings.catch_warnings(): + warnings.simplefilter("error") + from zarr.codecs.sharding import ( # noqa: F401 + ShardingCodecIndexLocation as _SCIL, + ) + + +def test_sharding_codec_init_with_enum_instance_warns() -> None: + """ + Passing a foreign enum.Enum instance to ShardingCodec.__init__ triggers + the init-level deprecation warning (from _coerce_enum_input) and + normalizes the value to the corresponding literal string. Covers the + case where a downstream package defined its own enum-shaped class to + bridge between zarr's old API and its own. + """ + + class LegacyIndexLocation(enum.Enum): + end = "end" + + with pytest.warns(DeprecationWarning, match=r"Passing an enum to ShardingCodec"): + codec = ShardingCodec( + chunk_shape=(1,), + index_location=cast(ShardingCodecIndexLocation, LegacyIndexLocation.end), + ) + assert codec.index_location == "end" + + +def test_sharding_codec_init_with_deprecated_class_member() -> None: + """ + The realistic legacy-upgrade idiom: ShardingCodec(index_location=ShardingCodecIndexLocation.end). + Member access on ShardingCodecIndexLocation emits one DeprecationWarning + (from the metaclass) and resolves to the bare string, which ShardingCodec + then accepts without further warning. No second warning from + _coerce_enum_input because the metaclass already produced a string. + + The cast is necessary because the metaclass __getattr__ is typed as + returning str, which does not statically match the codec's + IndexLocation parameter even though the runtime value does. + """ + with pytest.warns(DeprecationWarning, match=r"ShardingCodecIndexLocation\.end"): + codec = ShardingCodec( + chunk_shape=(1,), + index_location=cast(IndexLocation, ShardingCodecIndexLocation.end), + ) + assert codec.index_location == "end" + + +def test_sharding_codec_rejects_unknown_index_location() -> None: + """ + ShardingCodec.__init__ raises ValueError when index_location is outside + INDEX_LOCATION, and the error message names the offending parameter. + """ + kwargs: dict[str, Any] = {"chunk_shape": (1,), "index_location": "middle"} + with pytest.raises(ValueError, match="index_location must be one of"): + ShardingCodec(**kwargs) + + +def test_sharding_index_location_attribute_error_for_unknown_member() -> None: + """ + Attribute access for a name that is not a known member of the deprecated + ShardingCodecIndexLocation class falls through to AttributeError. + """ + with pytest.raises(AttributeError): + getattr(ShardingCodecIndexLocation, "not_a_member") # noqa: B009 + + +@pytest.mark.parametrize("index_location", INDEX_LOCATION) +def test_create_array_with_dict_shards_index_location( + index_location: IndexLocation, +) -> None: + """ + zarr.create_array accepts a `ShardsConfigParam`-shaped dict for `shards` + with an explicit `index_location`, and the resulting sharding codec + stores that value. Covers the `isinstance(shards, dict)` branch in + init_array that the tuple-shaped `shards` form doesn't reach. + """ + arr = zarr.create_array( + store={}, + shape=(8,), + chunks=(2,), + shards={"shape": (4,), "index_location": index_location}, + dtype="uint8", + ) + assert isinstance(arr.metadata, ArrayV3Metadata) # needed for mypy + sharding = arr.metadata.codecs[0] + assert isinstance(sharding, ShardingCodec) + assert sharding.index_location == index_location + + +def test_sharding_zero_dimensional() -> None: + """Regression test for https://github.com/zarr-developers/zarr-python/issues/3751""" + arr = zarr.create_array({}, shape=(), dtype="f4", chunks=(), shards=()) + arr[()] = 42.0 + assert arr[()] == pytest.approx(42.0) + # Overwriting should also work + arr[()] = 43.0 + assert arr[()] == pytest.approx(43.0) + + +def test_shard_index_stores_chunks_per_shard_explicitly() -> None: + """_ShardIndex stores the chunk grid shape as an explicit field.""" + index = _ShardIndex.create_empty((2, 3)) + assert index.chunks_per_shard == (2, 3) + + # 0-D: chunks_per_shard is the empty tuple, distinct from the array's rank + index_0d = _ShardIndex.create_empty(()) + assert index_0d.chunks_per_shard == () + + +@pytest.mark.parametrize("chunks_per_shard", [(), (3,), (2, 3)]) +def test_shard_index_get_chunk_slices_vectorized(chunks_per_shard: tuple[int, ...]) -> None: + """get_chunk_slices_vectorized works uniformly across chunk grid ranks, including 0-D.""" + index = _ShardIndex.create_empty(chunks_per_shard) + # Write the first chunk; leave the rest (if any) empty. + all_coords = list(lexicographic_order_coords(chunks_per_shard)) + index.set_chunk_slice(all_coords[0], slice(10, 14)) + + coords_array = np.array(all_coords, dtype=np.uint64).reshape( + len(all_coords), len(chunks_per_shard) + ) + starts, ends, valid = index.get_chunk_slices_vectorized(coords_array) + + expected_valid = np.zeros(len(all_coords), dtype=bool) + expected_valid[0] = True + np.testing.assert_array_equal(valid, expected_valid) + assert starts[0] == 10 + assert ends[0] == 14 + np.testing.assert_array_equal(starts[~expected_valid], MAX_UINT_64) + + +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@pytest.mark.parametrize( + "pipeline_path", + [ + "zarr.core.codec_pipeline.FusedCodecPipeline", + "zarr.core.codec_pipeline.BatchedCodecPipeline", + ], +) +def test_sharding_vlen_inner_codec_roundtrip(pipeline_path: str) -> None: + """A sharded array whose inner codec chain is a variable-length codec + (VLenUTF8) must round-trip under either pipeline. + + Regression: the Fused pipeline's bulk-decode gate calls `c.is_fixed_size` + on every inner codec. `is_fixed_size` is declared on the Codec ABC but had + no default, so codecs that don't set it (VLenUTF8/VLenBytes, numcodecs + wrappers) raised AttributeError on read β€” crashing every sharded read whose + inner chain included such a codec. + """ + # The variable-length StringDType resolves to a VLenUTF8Codec inner chain + # (a fixed-width None: + """to_dict_vectorized derives its own coords and maps present chunks to buffers, empty to None. + + The reader is given the full per-shard chunk grid implicitly (it reads + ``chunks_per_shard`` off its own index), so the result must contain every + lexicographic coordinate as a key, with the stored bytes for present chunks + and ``None`` for empty ones. + """ + all_coords = list(lexicographic_order_coords(chunks_per_shard)) + # Lay two chunks back-to-back in the buffer; leave the rest (if any) empty. + payload = b"abcdXY" + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice(all_coords[0], slice(0, 4)) + present = {all_coords[0]: payload[0:4]} + if len(all_coords) > 1: + index.set_chunk_slice(all_coords[1], slice(4, 6)) + present[all_coords[1]] = payload[4:6] + + reader = _ShardReader() + reader.index = index + reader.buf = default_buffer_prototype().buffer.from_bytes(payload) + + result = reader.to_dict_vectorized() + + # Every lexicographic coordinate is present as a key, in order. + assert list(result.keys()) == all_coords + for coords in all_coords: + buf = result[coords] + if coords in present: + assert buf is not None + assert buf.to_bytes() == present[coords] + else: + assert buf is None diff --git a/tests/test_codecs/test_sharding_unit.py b/tests/test_codecs/test_sharding_unit.py new file mode 100644 index 0000000000..d8b8242a28 --- /dev/null +++ b/tests/test_codecs/test_sharding_unit.py @@ -0,0 +1,1144 @@ +from __future__ import annotations + +import asyncio +from dataclasses import dataclass, replace +from typing import TYPE_CHECKING, Any, Literal, cast +from unittest.mock import AsyncMock + +import numpy as np +import numpy.typing as npt +import pytest + +import zarr +from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec +from zarr.codecs.bytes import BytesCodec +from zarr.codecs.crc32c_ import Crc32cCodec +from zarr.codecs.gzip import GzipCodec +from zarr.codecs.sharding import ( + MAX_UINT_64, + ShardingCodec, + _ShardIndex, + _ShardingByteGetter, + _ShardReader, +) +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import Buffer as ABCBuffer +from zarr.core.buffer import NDBuffer, default_buffer_prototype +from zarr.core.buffer.cpu import Buffer +from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer +from zarr.core.chunk_grids import ChunkGrid +from zarr.core.config import config +from zarr.core.dtype import get_data_type_from_native_dtype +from zarr.core.indexing import BasicIndexer +from zarr.storage._common import StorePath +from zarr.storage._memory import MemoryStore + +if TYPE_CHECKING: + from zarr.core.array import ShardsConfigParam + from zarr.core.array_spec import ArrayConfigParams + +# ============================================================================ +# _ShardIndex tests +# ============================================================================ + + +def test_shard_index_create_empty() -> None: + """Test that create_empty creates an index filled with MAX_UINT_64.""" + chunks_per_shard = (2, 3) + index = _ShardIndex.create_empty(chunks_per_shard) + + assert index.chunks_per_shard == chunks_per_shard + assert index.offsets_and_lengths.shape == (2, 3, 2) + assert index.offsets_and_lengths.dtype == np.dtype(" None: + """Test create_empty with 1D chunks_per_shard.""" + chunks_per_shard = (4,) + index = _ShardIndex.create_empty(chunks_per_shard) + + assert index.chunks_per_shard == chunks_per_shard + assert index.offsets_and_lengths.shape == (4, 2) + + +def test_shard_index_is_all_empty_true() -> None: + """Test is_all_empty returns True for a freshly created empty index.""" + index = _ShardIndex.create_empty((2, 2)) + assert index.is_all_empty() is True + + +def test_shard_index_is_all_empty_false() -> None: + """Test is_all_empty returns False when at least one chunk is set.""" + index = _ShardIndex.create_empty((2, 2)) + index.set_chunk_slice((0, 0), slice(0, 100)) + assert index.is_all_empty() is False + + +def test_shard_index_get_chunk_slice_empty() -> None: + """Test get_chunk_slice returns None for empty chunks.""" + index = _ShardIndex.create_empty((2, 2)) + assert index.get_chunk_slice((0, 0)) is None + assert index.get_chunk_slice((1, 1)) is None + + +def test_shard_index_get_chunk_slice_set() -> None: + """Test get_chunk_slice returns correct (start, end) tuple after setting.""" + index = _ShardIndex.create_empty((2, 2)) + index.set_chunk_slice((0, 1), slice(100, 200)) + + result = index.get_chunk_slice((0, 1)) + assert result == (100, 200) + + +def test_shard_index_set_chunk_slice() -> None: + """Test set_chunk_slice correctly sets offset and length.""" + index = _ShardIndex.create_empty((3, 3)) + + # Set a chunk slice + index.set_chunk_slice((1, 2), slice(50, 150)) + + # Verify the underlying array + assert index.offsets_and_lengths[1, 2, 0] == 50 # offset + assert index.offsets_and_lengths[1, 2, 1] == 100 # length (150 - 50) + + +def test_shard_index_set_chunk_slice_none() -> None: + """Test set_chunk_slice with None marks chunk as empty.""" + index = _ShardIndex.create_empty((2, 2)) + + # First set a value + index.set_chunk_slice((0, 0), slice(0, 100)) + assert index.get_chunk_slice((0, 0)) == (0, 100) + + # Then clear it + index.set_chunk_slice((0, 0), None) + assert index.get_chunk_slice((0, 0)) is None + assert index.offsets_and_lengths[0, 0, 0] == MAX_UINT_64 + assert index.offsets_and_lengths[0, 0, 1] == MAX_UINT_64 + + +def test_shard_index_get_full_chunk_map() -> None: + """Test get_full_chunk_map returns correct boolean array.""" + index = _ShardIndex.create_empty((2, 3)) + + # Set some chunks + index.set_chunk_slice((0, 0), slice(0, 10)) + index.set_chunk_slice((1, 2), slice(10, 20)) + + chunk_map = index.get_full_chunk_map() + + assert chunk_map.shape == (2, 3) + assert chunk_map.dtype == np.bool_ + assert chunk_map[0, 0] is np.True_ + assert chunk_map[0, 1] is np.False_ + assert chunk_map[0, 2] is np.False_ + assert chunk_map[1, 0] is np.False_ + assert chunk_map[1, 1] is np.False_ + assert chunk_map[1, 2] is np.True_ + + +def test_shard_index_localize_chunk() -> None: + """Test _localize_chunk maps global coords to local shard coords via modulo.""" + index = _ShardIndex.create_empty((2, 3)) + + # Within bounds - should return same coords + assert index._localize_chunk((0, 0)) == (0, 0) + assert index._localize_chunk((1, 2)) == (1, 2) + + # Out of bounds - should wrap via modulo + assert index._localize_chunk((2, 0)) == (0, 0) # 2 % 2 = 0 + assert index._localize_chunk((3, 5)) == (1, 2) # 3 % 2 = 1, 5 % 3 = 2 + assert index._localize_chunk((4, 6)) == (0, 0) # 4 % 2 = 0, 6 % 3 = 0 + + +# ============================================================================ +# _load_partial_shard_maybe tests +# +# These exercise the partial-shard read path against a real MemoryStore wrapped +# in a StorePath (the external-store branch in `_load_partial_shard_maybe`), +# plus one test against a real `_ShardingByteGetter` (the in-memory branch used +# by nested sharding). +# ============================================================================ + + +async def _store_path_with_blob(key: str, blob: bytes) -> StorePath: + """Build a `StorePath` over a fresh `MemoryStore` containing `blob` at `key`.""" + store = MemoryStore() + await store.set(key, Buffer.from_bytes(blob)) + return StorePath(store, key) + + +async def test_load_partial_shard_maybe_index_load_fails() -> None: + """Returns None when the shard key is absent (index load fails).""" + codec = ShardingCodec(chunk_shape=(8,)) + byte_getter = StorePath(MemoryStore(), "missing") + + result = await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=(2,), + all_chunk_coords={(0,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + assert result is None + + +async def test_load_partial_shard_maybe_with_empty_chunks( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Chunks whose index entry is empty are silently skipped.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + + # Index where chunk (1,) is empty; the others point into the stored blob. + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 100)) + index.set_chunk_slice((2,), slice(100, 200)) + index.set_chunk_slice((3,), slice(200, 300)) + + async def mock_load_index( + self: ShardingCodec, byte_getter: StorePath, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + byte_getter = await _store_path_with_blob("shard", b"x" * 300) + + result = await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,), (1,), (2,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + assert result is not None + assert (0,) in result + assert (1,) not in result # empty in index + assert (2,) in result + + +async def test_load_partial_shard_maybe_all_chunks_empty( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Returns an empty dict when all requested chunks are empty (no I/O issued).""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + + # Fully-empty index β€” `get_chunk_slice` returns None for every coord. + index = _ShardIndex.create_empty(chunks_per_shard) + + async def mock_load_index( + self: ShardingCodec, byte_getter: StorePath, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + # Empty store is fine β€” we never reach the chunk-read path when all are empty. + byte_getter = StorePath(MemoryStore(), "shard") + + result = await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,), (1,), (2,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + assert result == {} + + +async def test_load_partial_shard_returns_chunk_contents( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Returns the correct bytes for each requested chunk.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 100)) + index.set_chunk_slice((1,), slice(100, 200)) + + async def mock_load_index( + self: ShardingCodec, byte_getter: StorePath, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + blob = b"A" * 100 + b"B" * 100 + byte_getter = await _store_path_with_blob("shard", blob) + + result = await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,), (1,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + assert result is not None + buf_0, buf_1 = result[(0,)], result[(1,)] + assert buf_0 is not None + assert buf_1 is not None + assert buf_0.to_bytes() == b"A" * 100 + assert buf_1.to_bytes() == b"B" * 100 + + +async def test_load_partial_shard_shard_disappears_returns_none( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """If the shard key is missing when chunk reads run, returns None. + + This models a race: the index loaded successfully, but the shard was deleted + before the chunk-byte fetches landed. `Store.get_ranges` surfaces this as a + `BaseExceptionGroup` containing `FileNotFoundError`, which the codec catches + and converts to None to match the index-missing branch's behavior. + """ + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 100)) + + async def mock_load_index( + self: ShardingCodec, byte_getter: StorePath, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + # Store has no value for "shard" β€” `get_ranges` will raise FileNotFoundError. + byte_getter = StorePath(MemoryStore(), "shard") + + result = await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + assert result is None + + +async def test_load_partial_shard_non_fnf_error_propagates( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Non-FileNotFoundError errors from get_ranges are re-raised, not swallowed. + + Our `BaseExceptionGroup.split(FileNotFoundError)` keeps the "shard gone" + behavior for FNF only; anything else (e.g. an OSError from the underlying + fetch) must bubble up. + """ + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 100)) + + async def mock_load_index( + self: ShardingCodec, byte_getter: StorePath, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + # Make the underlying store.get raise OSError. The default Store.get_ranges + # impl routes through self.get; coalesced_get wraps the failure in a + # BaseExceptionGroup, which our code re-raises (minus FNF leaves, of which + # there are none here). + async def boom(*args: object, **kwargs: object) -> Buffer | None: + raise OSError("injected disk error") + + store = MemoryStore() + monkeypatch.setattr(store, "get", boom) + byte_getter = StorePath(store, "shard") + + with pytest.RaisesGroup(pytest.RaisesExc(OSError, match="injected disk error")): + await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + +async def test_load_partial_shard_nested_sharding_path( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Nested sharding: byte_getter is a `_ShardingByteGetter` over an in-memory dict.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 100)) + index.set_chunk_slice((1,), slice(100, 200)) + + async def mock_load_index( + self: ShardingCodec, byte_getter: _ShardingByteGetter, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + # The "store" for an inner shard is a dict keyed by outer-chunk coords; the + # byte_getter reads ranges out of one entry of that dict. + blob = b"A" * 100 + b"B" * 100 + shard_dict: dict[tuple[int, ...], Buffer | None] = {(0,): Buffer.from_bytes(blob)} + byte_getter = _ShardingByteGetter(shard_dict, (0,)) + + result = await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,), (1,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + assert result is not None + buf_0, buf_1 = result[(0,)], result[(1,)] + assert buf_0 is not None + assert buf_1 is not None + assert buf_0.to_bytes() == b"A" * 100 + assert buf_1.to_bytes() == b"B" * 100 + + +async def test_load_partial_shard_nested_sharding_missing_outer_chunk( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Nested sharding: outer chunk absent β†’ `_ShardingByteGetter.get` returns None + β†’ chunks are silently skipped, yielding an empty shard_dict.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 100)) + + async def mock_load_index( + self: ShardingCodec, byte_getter: _ShardingByteGetter, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + # Empty outer dict β€” _ShardingByteGetter.get(...) returns None for any range. + shard_dict: dict[tuple[int, ...], Buffer | None] = {} + byte_getter = _ShardingByteGetter(shard_dict, (0,)) + + result = await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,)}, + max_gap_bytes=1 << 20, + max_coalesced_bytes=16 << 20, + ) + + assert result == {} + + +# ============================================================================ +# Supporting class tests (_ShardReader, _is_total_shard) +# ============================================================================ + + +def test_shard_reader_create_empty() -> None: + """Test _ShardReader.create_empty creates reader with empty index.""" + chunks_per_shard = (2, 3) + reader = _ShardReader.create_empty(chunks_per_shard) + + assert reader.index.is_all_empty() + assert len(reader.buf) == 0 + assert len(reader) == 2 * 3 + + +def test_shard_reader_iteration() -> None: + """Test _ShardReader iteration yields all chunk coordinates.""" + chunks_per_shard = (2, 2) + reader = _ShardReader.create_empty(chunks_per_shard) + + coords = list(reader) + + assert len(coords) == 4 + assert (0, 0) in coords + assert (0, 1) in coords + assert (1, 0) in coords + assert (1, 1) in coords + + +def test_shard_reader_getitem_raises_for_empty() -> None: + """Test _ShardReader.__getitem__ raises KeyError for empty chunks.""" + chunks_per_shard = (2,) + reader = _ShardReader.create_empty(chunks_per_shard) + + with pytest.raises(KeyError): + _ = reader[(0,)] + + +def test_is_total_shard_full() -> None: + """Test _is_total_shard returns True when all chunk coords are present.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (2, 2) + all_chunk_coords: set[tuple[int, ...]] = {(0, 0), (0, 1), (1, 0), (1, 1)} + + assert codec._is_total_shard(all_chunk_coords, chunks_per_shard) is True + + +def test_is_total_shard_partial() -> None: + """Test _is_total_shard returns False for partial chunk coords.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (2, 2) + all_chunk_coords: set[tuple[int, ...]] = {(0, 0), (1, 1)} # Missing (0, 1) and (1, 0) + + assert codec._is_total_shard(all_chunk_coords, chunks_per_shard) is False + + +def test_is_total_shard_empty() -> None: + """Test _is_total_shard returns False for empty chunk coords.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (2, 2) + all_chunk_coords: set[tuple[int, ...]] = set() + + assert codec._is_total_shard(all_chunk_coords, chunks_per_shard) is False + + +def test_is_total_shard_1d() -> None: + """Test _is_total_shard works with 1D shards.""" + codec = ShardingCodec(chunk_shape=(8,)) + chunks_per_shard = (4,) + all_chunk_coords: set[tuple[int, ...]] = {(0,), (1,), (2,), (3,)} + + assert codec._is_total_shard(all_chunk_coords, chunks_per_shard) is True + + # Partial + partial_coords: set[tuple[int, ...]] = {(0,), (2,)} + assert codec._is_total_shard(partial_coords, chunks_per_shard) is False + + +# ============================================================================ +# _inner_codecs_fixed_size tests +# ============================================================================ + + +def test_inner_codecs_fixed_size_no_compression() -> None: + """Inner codecs without compression should be fixed-size.""" + codec = ShardingCodec(chunk_shape=(10,), codecs=[BytesCodec()]) + assert codec._inner_codecs_fixed_size is True + + +def test_inner_codecs_fixed_size_with_compression() -> None: + """Inner codecs with compression should NOT be fixed-size.""" + codec = ShardingCodec(chunk_shape=(10,), codecs=[BytesCodec(), GzipCodec()]) + assert codec._inner_codecs_fixed_size is False + + +# ============================================================================ +# inner-chain spec threading +# ============================================================================ + + +@dataclass(frozen=True) +class _WidenToInt16(ArrayArrayCodec): + """Test-only sync-capable AA codec that reports its output dtype as int16.""" + + is_fixed_size = True + + def to_dict(self) -> dict[str, Any]: + return {"name": "_widen_to_int16"} + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> _WidenToInt16: + return cls() + + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + return replace(chunk_spec, dtype=get_data_type_from_native_dtype(np.dtype("int16"))) + + def compute_encoded_size(self, input_byte_length: int, _spec: ArraySpec) -> int: + return input_byte_length + + def _encode_sync(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + return chunk_array # pragma: no cover + + def _decode_sync(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + return chunk_array # pragma: no cover + + async def _encode_single(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + return chunk_array # pragma: no cover + + async def _decode_single(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + return chunk_array # pragma: no cover + + +def _int8_spec(shape: tuple[int, ...]) -> ArraySpec: + zdtype = get_data_type_from_native_dtype(np.dtype("int8")) # single-byte source + return ArraySpec( + shape=shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=False), + prototype=default_buffer_prototype(), + ) + + +def test_inner_chunk_transform_threads_spec() -> None: + """The inner codec chain must be evolved with the spec threaded forward. + + A dtype-widening inner array->array codec means the BytesCodec serializer + is evolved against the WIDENED dtype, not the single-byte source β€” + otherwise it strips its `endian` to None and fails to decode multi-byte + inner chunks. Same contract as the pipeline-level `evolve_codecs` + regression test, applied to `_get_inner_chunk_transform`. + """ + codec = ShardingCodec(chunk_shape=(4,), codecs=[_WidenToInt16(), BytesCodec(endian="little")]) + shard_spec = _int8_spec((8,)) + + transform = codec._get_inner_chunk_transform(shard_spec) + serializer = transform._ab_codec + assert isinstance(serializer, BytesCodec) + assert serializer.endian is not None, ( + "inner BytesCodec lost its `endian` β€” _get_inner_chunk_transform did not " + "thread the dtype-widening codec's spec into the serializer" + ) + + +def test_evolve_from_array_spec_threads_spec() -> None: + """`ShardingCodec.evolve_from_array_spec` must thread the spec through the + inner chain, like `_get_inner_chunk_transform` does. + + This method runs EARLIER, on the real array-creation path (the outer + pipeline evolves the sharding codec itself), so an unthreaded evolve here + bakes an endian-stripped BytesCodec into the evolved instance's `codecs` + before the transform builders ever run β€” and the later threaded evolve then + raises instead of recovering. Calling `_get_inner_chunk_transform` on the + EVOLVED instance pins the full real path. + """ + codec = ShardingCodec(chunk_shape=(4,), codecs=[_WidenToInt16(), BytesCodec(endian="little")]) + # the array spec the OUTER pipeline evolves the sharding codec against + array_spec = _int8_spec((8,)) + + evolved = codec.evolve_from_array_spec(array_spec) + inner_serializer = next(c for c in evolved.codecs if isinstance(c, BytesCodec)) + assert inner_serializer.endian is not None, ( + "evolve_from_array_spec evolved the inner BytesCodec against the " + "un-widened spec, stripping its `endian`" + ) + + # and the evolved instance must still build a working inner transform + transform = evolved._get_inner_chunk_transform(array_spec) + serializer = transform._ab_codec + assert isinstance(serializer, BytesCodec) + assert serializer.endian is not None + + +# ============================================================================ +# async whole-shard codec methods +# +# `ShardingCodec` advertises partial decode/encode, so the codec pipeline +# always routes sharded reads/writes through `_decode_partial_single` / +# `_encode_partial_single`. The whole-shard async methods `_decode_single` / +# `_encode_single` are reached only via the direct `ArrayBytesCodec` API (e.g. +# a consumer that calls the codec outside a pipeline), so they get no coverage +# from end-to-end array tests. Pin them with a direct round-trip. +# ============================================================================ + + +@pytest.mark.parametrize("write_empty_chunks", [True, False]) +def test_decode_single_encode_single_roundtrip(write_empty_chunks: bool) -> None: + """`ShardingCodec._encode_single` then `_decode_single` round-trips a whole + shard. Covers the async whole-shard path the pipeline bypasses in favor of + the partial methods.""" + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + spec = ArraySpec( + shape=(50,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=write_empty_chunks), + prototype=default_buffer_prototype(), + ) + codec = ShardingCodec(chunk_shape=(10,), codecs=[BytesCodec()]) + data = np.arange(50, dtype="float64") + value = CPUNDBuffer.from_numpy_array(data) + + encoded = asyncio.run(codec._encode_single(value, spec)) + assert encoded is not None # data is non-empty -> a shard is always produced + decoded = asyncio.run(codec._decode_single(encoded, spec)) + np.testing.assert_array_equal(decoded.as_numpy_array(), data) + + +def test_encode_single_all_empty_returns_none() -> None: + """`_encode_single` of an all-fill shard under write_empty_chunks=False + elides every inner chunk and returns None (the all-empty branch).""" + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + spec = ArraySpec( + shape=(50,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=False), + prototype=default_buffer_prototype(), + ) + codec = ShardingCodec(chunk_shape=(10,), codecs=[BytesCodec()]) + fill = CPUNDBuffer.from_numpy_array(np.zeros(50, dtype="float64")) + + assert asyncio.run(codec._encode_single(fill, spec)) is None + + +def test_decode_single_all_empty_fills() -> None: + """`_decode_single` of a shard whose index is all-empty fills the output + with the fill value (the is_all_empty fast path).""" + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + spec = ArraySpec( + shape=(50,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(-1.0), + config=ArrayConfig(order="C", write_empty_chunks=False), + prototype=default_buffer_prototype(), + ) + codec = ShardingCodec(chunk_shape=(10,), codecs=[BytesCodec()]) + # an empty shard is just the encoded empty index + empty_index = asyncio.run(codec._encode_shard_index(_ShardIndex.create_empty((5,)))) + decoded = asyncio.run(codec._decode_single(empty_index, spec)) + np.testing.assert_array_equal(decoded.as_numpy_array(), np.full(50, -1.0)) + + +# ============================================================================ +# async-only index codec fallback (#269) +# +# `_decode_shard_index` / `_encode_shard_index` delegate to their sync twins +# when every index codec is sync-capable, and otherwise fall back to the async +# pipeline. The default index chain (bytes + crc32c) is sync-capable, so the +# fallback is exercised only by an async-only index codec. +# ============================================================================ + + +class _AsyncOnlyBytesCodec(ArrayBytesCodec): + """An array<->bytes codec that implements ONLY the async per-chunk methods. + + Wraps a real `BytesCodec` for the actual conversion but deliberately omits + `_encode_sync`/`_decode_sync`, so it is NOT a `SupportsSyncCodec`. Used as + an index codec to force the async-pipeline fallback in + `_decode_shard_index`/`_encode_shard_index`. + """ + + _inner = BytesCodec() + + def to_dict(self) -> dict[str, Any]: + return {"name": "_async_only_bytes"} + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> _AsyncOnlyBytesCodec: + return cls() + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> _AsyncOnlyBytesCodec: + return self + + def compute_encoded_size(self, input_byte_length: int, _spec: ArraySpec) -> int: + return input_byte_length + + async def _decode_single(self, chunk_bytes: ABCBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return await self._inner._decode_single(chunk_bytes, chunk_spec) + + async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> ABCBuffer: + result = await self._inner._encode_single(chunk_array, chunk_spec) + assert result is not None + return result + + +def test_shard_index_async_fallback_for_async_only_index_codec() -> None: + """An async-only index codec is not sync-capable, so `_encode_shard_index` + and `_decode_shard_index` must take the async-pipeline fallback (#269) + instead of the sync twins β€” and still round-trip.""" + from zarr.abc.codec import SupportsSyncCodec + + codec = ShardingCodec( + chunk_shape=(10,), + codecs=[BytesCodec()], + index_codecs=[_AsyncOnlyBytesCodec(), Crc32cCodec()], + ) + assert not codec._index_codecs_sync_capable() + assert not isinstance(_AsyncOnlyBytesCodec(), SupportsSyncCodec) + + chunks_per_shard = (5,) + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 42)) + + encoded = asyncio.run(codec._encode_shard_index(index)) + decoded = asyncio.run(codec._decode_shard_index(encoded, chunks_per_shard)) + np.testing.assert_array_equal(decoded.offsets_and_lengths, index.offsets_and_lengths) + + +# ============================================================================ +# Coalescing config option tests +# +# Assert that the `array.sharding_coalesce_max_gap_bytes` and +# `array.sharding_coalesce_max_bytes` global config keys flow through +# `ArrayConfig` to `Store.get_ranges` as `max_gap_bytes` / +# `max_coalesced_bytes` kwargs, and that per-array `config={...}` overrides +# the global default. +# ============================================================================ + + +def _trigger_partial_shard_read(array_config: ArrayConfigParams | None = None) -> AsyncMock: + """Build a sharded array on a mocked `MemoryStore`, trigger a partial-shard + read via the public read path, and return the `get_ranges` mock. + """ + import zarr + + chunk_shape = (2,) + shard_shape = (8,) + data = np.arange(8, dtype="int32") + + store = MemoryStore() + store_mock = AsyncMock(wraps=store, spec=store.__class__) + + shards: ShardsConfigParam = { + "shape": shard_shape, + "index_location": "end", + } + a = zarr.create_array( + StorePath(store_mock), + shape=(8,), + chunks=chunk_shape, + shards=shards, + dtype=data.dtype, + fill_value=-1, + config=array_config, + ) + a[:] = data + + store_mock.reset_mock() + + # Read a strict subset of chunks to take the partial-shard read path. + _ = a[0:4] + + return cast(AsyncMock, store_mock.get_ranges) + + +def test_load_partial_shard_forwards_global_config_to_get_ranges() -> None: + """Global `array.sharding_coalesce_*` values flow into ArrayConfig at + array-creation time and are forwarded to `Store.get_ranges`.""" + with config.set( + { + "array.sharding_coalesce_max_gap_bytes": 4242, + "array.sharding_coalesce_max_bytes": 424242, + } + ): + get_ranges_mock = _trigger_partial_shard_read() + + assert get_ranges_mock.call_count >= 1 + for call in get_ranges_mock.call_args_list: + kwargs = call.kwargs + assert kwargs["max_gap_bytes"] == 4242 + assert kwargs["max_coalesced_bytes"] == 424242 + + +def test_load_partial_shard_per_array_config_overrides_global() -> None: + """Per-array `config={...}` passed to `create_array` takes precedence over + the global config and is forwarded to `Store.get_ranges`.""" + with config.set( + { + "array.sharding_coalesce_max_gap_bytes": 4242, + "array.sharding_coalesce_max_bytes": 424242, + } + ): + get_ranges_mock = _trigger_partial_shard_read( + array_config={ + "sharding_coalesce_max_gap_bytes": 99, + "sharding_coalesce_max_bytes": 9999, + }, + ) + + assert get_ranges_mock.call_count >= 1 + for call in get_ranges_mock.call_args_list: + kwargs = call.kwargs + assert kwargs["max_gap_bytes"] == 99 + assert kwargs["max_coalesced_bytes"] == 9999 + + +def test_load_partial_shard_uses_config_defaults() -> None: + """Without explicit config, defaults from `zarr.config` are forwarded.""" + get_ranges_mock = _trigger_partial_shard_read() + + assert get_ranges_mock.call_count >= 1 + for call in get_ranges_mock.call_args_list: + kwargs = call.kwargs + assert kwargs["max_gap_bytes"] == config.get("array.sharding_coalesce_max_gap_bytes") + assert kwargs["max_coalesced_bytes"] == config.get("array.sharding_coalesce_max_bytes") + + +async def test_load_partial_shard_explicit_kwargs_passthrough( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """`_load_partial_shard_maybe` forwards its explicit kwargs to `get_ranges`.""" + codec = ShardingCodec(chunk_shape=(2,)) + chunks_per_shard = (4,) + + index = _ShardIndex.create_empty(chunks_per_shard) + index.set_chunk_slice((0,), slice(0, 100)) + index.set_chunk_slice((2,), slice(200, 300)) + + store = MemoryStore() + await store.set("shard", Buffer.from_bytes(b"x" * 300)) + store_mock = AsyncMock(wraps=store, spec=store.__class__) + byte_getter = StorePath(store_mock, "shard") + + async def mock_load_index( + self: ShardingCodec, byte_getter: StorePath, cps: tuple[int, ...] + ) -> _ShardIndex: + return index + + monkeypatch.setattr(ShardingCodec, "_load_shard_index_maybe", mock_load_index) + + await codec._load_partial_shard_maybe( + byte_getter=byte_getter, + prototype=default_buffer_prototype(), + chunks_per_shard=chunks_per_shard, + all_chunk_coords={(0,), (2,)}, + max_gap_bytes=12345, + max_coalesced_bytes=67890, + ) + + store_mock.get_ranges.assert_called_once() + kwargs = store_mock.get_ranges.call_args.kwargs + assert kwargs["max_gap_bytes"] == 12345 + assert kwargs["max_coalesced_bytes"] == 67890 + + +# ============================================================================ +# Bulk full-shard decode: identity-read gating and dtype gating +# ============================================================================ + +_FUSED_PIPELINE = "zarr.core.codec_pipeline.FusedCodecPipeline" + + +def _fused_uncompressed_array( + index_location: Literal["start", "end"], +) -> tuple[Any, npt.NDArray[np.int32]]: + """Sharded `(8, 8)` array whose inner chain is a bare BytesCodec (no crc), + one shard covering the whole array, filled with `arange` data. Callers must + be inside a config context selecting the fused pipeline.""" + shards: ShardsConfigParam = {"shape": (8, 8), "index_location": index_location} + arr = zarr.create_array( + store=MemoryStore(), + shape=(8, 8), + chunks=(2, 2), + shards=shards, + dtype="int32", + compressors=None, + filters=None, + fill_value=0, + config={"write_empty_chunks": True}, + ) + ref = np.arange(64, dtype="int32").reshape(8, 8) + arr[:] = ref + return arr, ref + + +def _spy_on_bulk_decode(monkeypatch: pytest.MonkeyPatch) -> list[bool]: + """Record, per call, whether `_decode_full_shard_bulk_if_uncompressed` + engaged (returned non-None).""" + engaged: list[bool] = [] + orig = ShardingCodec._decode_full_shard_bulk_if_uncompressed + + def spy(self: ShardingCodec, shard_bytes: Any, shard_spec: Any, indexer: Any) -> Any: + result = orig(self, shard_bytes, shard_spec, indexer) + engaged.append(result is not None) + return result + + monkeypatch.setattr(ShardingCodec, "_decode_full_shard_bulk_if_uncompressed", spy) + return engaged + + +_PERM_8 = np.array([7, 2, 5, 0, 3, 6, 1, 4]) +_DUP_8 = np.array([0, 0, 1, 2, 3, 4, 5, 6]) + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +@pytest.mark.parametrize( + ("read", "expected", "expect_bulk"), + [ + pytest.param(lambda a: a[:], lambda r: r, True, id="full-slice"), + pytest.param(lambda a: a[...], lambda r: r, True, id="ellipsis"), + pytest.param( + lambda a: a[_PERM_8, :], lambda r: r[_PERM_8, :], False, id="fancy-permutation" + ), + pytest.param(lambda a: a[_DUP_8, :], lambda r: r[_DUP_8, :], False, id="fancy-duplicates"), + pytest.param( + lambda a: a.oindex[_PERM_8, :], + lambda r: r[_PERM_8, :], + False, + id="oindex-permutation", + ), + pytest.param( + lambda a: a.oindex[_DUP_8, :], lambda r: r[_DUP_8, :], False, id="oindex-duplicates" + ), + pytest.param(lambda a: a[1:7, :], lambda r: r[1:7, :], False, id="subset-slice"), + ], +) +def test_bulk_decode_engagement_and_correctness( + monkeypatch: pytest.MonkeyPatch, + index_location: Literal["start", "end"], + read: Any, + expected: Any, + expect_bulk: bool, +) -> None: + """Under the fused pipeline on an uncompressed crc-free shard, the bulk + whole-shard decode fires exactly for identity full reads β€” and every read + returns what numpy returns. The engagement assertions keep the correctness + half non-vacuous: a gate that simply disabled the fast path would pass the + value checks but fail here.""" + engaged = _spy_on_bulk_decode(monkeypatch) + with config.set({"codec_pipeline.path": _FUSED_PIPELINE}): + arr, ref = _fused_uncompressed_array(index_location) + engaged.clear() + np.testing.assert_array_equal(read(arr), expected(ref)) + if expect_bulk: + assert len(engaged) > 0, "bulk fast path was never reached for a full read" + assert all(engaged), "bulk fast path did not engage for a full read" + else: + assert not any(engaged), "bulk fast path engaged for a non-identity selection" + + +@pytest.mark.parametrize("index_location", ["start", "end"]) +def test_multi_shard_permutation_read(index_location: Literal["start", "end"]) -> None: + """A row permutation crossing shard boundaries must return permuted data + under the fused pipeline (each shard sees a gather selection whose shape + coincides with the shard shape).""" + shards: ShardsConfigParam = {"shape": (8, 8), "index_location": index_location} + with config.set({"codec_pipeline.path": _FUSED_PIPELINE}): + arr = zarr.create_array( + store=MemoryStore(), + shape=(16, 16), + chunks=(2, 2), + shards=shards, + dtype="int32", + compressors=None, + filters=None, + fill_value=0, + config={"write_empty_chunks": True}, + ) + ref = np.arange(256, dtype="int32").reshape(16, 16) + arr[:] = ref + perm = np.array([9, 3, 12, 0, 15, 6, 10, 1, 14, 5, 8, 2, 13, 7, 11, 4]) + np.testing.assert_array_equal(arr[perm, :8], ref[perm, :8]) + np.testing.assert_array_equal(arr.oindex[perm, :8], ref[perm, :8]) + + +def _dense_shard_blob( + codec: ShardingCodec, data: np.ndarray[Any, np.dtype[Any]], chunk_len: int +) -> Buffer: + """Hand-assemble a dense `index_location="end"` shard blob for 1-D `data`: + natural-order chunk payloads followed by the encoded index.""" + n_chunks = data.shape[0] // chunk_len + chunk_nbytes = chunk_len * data.dtype.itemsize + index = _ShardIndex.create_empty((n_chunks,)) + for i in range(n_chunks): + index.set_chunk_slice((i,), slice(i * chunk_nbytes, (i + 1) * chunk_nbytes)) + index_bytes = codec._encode_shard_index_sync(index) + return Buffer.from_bytes(data.tobytes() + index_bytes.to_bytes()) + + +def _identity_indexer(shape: tuple[int, ...], chunk_shape: tuple[int, ...]) -> BasicIndexer: + return BasicIndexer( + tuple(slice(0, s) for s in shape), + shape=shape, + chunk_grid=ChunkGrid.from_sizes(shape, chunk_shape), + ) + + +def _spec_for(data: np.ndarray[Any, np.dtype[Any]]) -> ArraySpec: + zdt = get_data_type_from_native_dtype(data.dtype) + return ArraySpec( + shape=data.shape, + dtype=zdt, + fill_value=zdt.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + + +def test_bulk_decode_declines_structured_dtype() -> None: + """The bulk path has no structured-dtype byte-order handling (the `Struct` + branch of `BytesCodec._decode_sync`), so it must decline structured specs. + The plain-dtype control on an identically constructed blob proves the + decline comes from the dtype gate, not from a malformed blob.""" + codec = ShardingCodec(chunk_shape=(2,), codecs=[BytesCodec(endian="little")]) + + # control: same construction with a plain dtype engages the bulk path + plain = np.arange(4, dtype=" None: + """`is_dense` accepts every layout whose fixed-size payloads exactly tile + the data section, wherever that section starts and in whatever order the + chunks were laid out.""" + chunk_len = 24 + n = int(np.prod(chunks_per_shard)) + slots = np.arange(n) + if layout_order == "reversed": + slots = slots[::-1] + offsets = data_section_start + slots * chunk_len + index = _ShardIndex.create_empty(chunks_per_shard) + for coord, off in zip(np.ndindex(chunks_per_shard), offsets, strict=True): + index.set_chunk_slice(tuple(coord), slice(int(off), int(off) + chunk_len)) + assert index.is_dense(chunk_len, data_section_start=data_section_start) is True + + +def test_shard_index_is_dense_rejects_overlapping_offsets() -> None: + """Unique but overlapping offsets (second payload starts inside the first) + are not dense.""" + chunk_len = 24 + index = _ShardIndex.create_empty((2,)) + index.set_chunk_slice((0,), slice(0, chunk_len)) + index.set_chunk_slice((1,), slice(12, 12 + chunk_len)) + assert index.is_dense(chunk_len, data_section_start=0) is False + + +def test_shard_index_is_dense_rejects_out_of_range_offsets() -> None: + """An offset outside the data section (here: chunk 0 pointing into an + `index_location="start"` index region) is not dense, even though offsets + are unique and non-overlapping.""" + chunk_len = 24 + data_section_start = 16 + index = _ShardIndex.create_empty((2,)) + index.set_chunk_slice((0,), slice(0, chunk_len)) + index.set_chunk_slice( + (1,), slice(data_section_start + chunk_len, data_section_start + 2 * chunk_len) + ) + assert index.is_dense(chunk_len, data_section_start=data_section_start) is False diff --git a/tests/test_codecs/test_transpose.py b/tests/test_codecs/test_transpose.py new file mode 100644 index 0000000000..949bb72a62 --- /dev/null +++ b/tests/test_codecs/test_transpose.py @@ -0,0 +1,123 @@ +import numpy as np +import pytest + +import zarr +from zarr import AsyncArray, config +from zarr.abc.codec import SupportsSyncCodec +from zarr.abc.store import Store +from zarr.codecs import TransposeCodec +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import NDBuffer, default_buffer_prototype +from zarr.core.common import MemoryOrder +from zarr.core.dtype import get_data_type_from_native_dtype +from zarr.storage import StorePath + +from .test_codecs import _AsyncArrayProxy + + +@pytest.mark.parametrize("input_order", ["F", "C"]) +@pytest.mark.parametrize("runtime_write_order", ["F", "C"]) +@pytest.mark.parametrize("runtime_read_order", ["F", "C"]) +@pytest.mark.parametrize("with_sharding", [True, False]) +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +async def test_transpose( + store: Store, + input_order: MemoryOrder, + runtime_write_order: MemoryOrder, + runtime_read_order: MemoryOrder, + with_sharding: bool, +) -> None: + data = np.arange(0, 256, dtype="uint16").reshape((1, 32, 8), order=input_order) + spath = StorePath(store, path="transpose") + with config.set({"array.order": runtime_write_order}): + a = await zarr.api.asynchronous.create_array( + spath, + shape=data.shape, + chunks=(1, 16, 8) if with_sharding else (1, 32, 8), + shards=(1, 32, 8) if with_sharding else None, + dtype=data.dtype, + fill_value=0, + chunk_key_encoding={"name": "v2", "separator": "."}, + filters=[TransposeCodec(order=(2, 1, 0))], + ) + + await _AsyncArrayProxy(a)[:, :].set(data) + read_data = await _AsyncArrayProxy(a)[:, :].get() + assert np.array_equal(data, read_data) + + with config.set({"array.order": runtime_read_order}): + a = await AsyncArray.open( + spath, + ) + read_data = await _AsyncArrayProxy(a)[:, :].get() + assert np.array_equal(data, read_data) + + assert isinstance(read_data, np.ndarray) + if runtime_read_order == "F": + assert read_data.flags["F_CONTIGUOUS"] + assert not read_data.flags["C_CONTIGUOUS"] + else: + assert not read_data.flags["F_CONTIGUOUS"] + assert read_data.flags["C_CONTIGUOUS"] + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +@pytest.mark.parametrize("order", [[1, 2, 0], [1, 2, 3, 0], [3, 2, 4, 0, 1]]) +def test_transpose_non_self_inverse(store: Store, order: list[int]) -> None: + shape = [i + 3 for i in range(len(order))] + data = np.arange(0, np.prod(shape), dtype="uint16").reshape(shape) + spath = StorePath(store, "transpose_non_self_inverse") + a = zarr.create_array( + spath, + shape=data.shape, + chunks=data.shape, + dtype=data.dtype, + fill_value=0, + filters=[TransposeCodec(order=order)], + ) + a[:, :] = data + read_data = a[:, :] + assert np.array_equal(data, read_data) + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +def test_transpose_invalid( + store: Store, +) -> None: + data = np.arange(0, 256, dtype="uint16").reshape((1, 32, 8)) + spath = StorePath(store, "transpose_invalid") + for order in [(1, 0), (3, 2, 1), (3, 3, 1), "F", "C"]: + with pytest.raises((ValueError, TypeError)): + zarr.create_array( + spath, + shape=data.shape, + chunks=(1, 32, 8), + dtype=data.dtype, + fill_value=0, + chunk_key_encoding={"name": "v2", "separator": "."}, + filters=[TransposeCodec(order=order)], # type: ignore[arg-type] + ) + + +def test_transpose_codec_supports_sync() -> None: + assert isinstance(TransposeCodec(order=(0, 1)), SupportsSyncCodec) + + +def test_transpose_codec_sync_roundtrip() -> None: + codec = TransposeCodec(order=(1, 0)) + arr = np.arange(12, dtype="float64").reshape(3, 4) + zdtype = get_data_type_from_native_dtype(arr.dtype) + spec = ArraySpec( + shape=arr.shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + nd_buf: NDBuffer = default_buffer_prototype().nd_buffer.from_numpy_array(arr) + + encoded = codec._encode_sync(nd_buf, spec) + assert encoded is not None + resolved_spec = codec.resolve_metadata(spec) + decoded = codec._decode_sync(encoded, resolved_spec) + np.testing.assert_array_equal(arr, decoded.as_numpy_array()) diff --git a/tests/test_codecs/test_vlen.py b/tests/test_codecs/test_vlen.py new file mode 100644 index 0000000000..b90ad88ddc --- /dev/null +++ b/tests/test_codecs/test_vlen.py @@ -0,0 +1,105 @@ +from typing import Any + +import numpy as np +import pytest + +import zarr +from zarr import Array +from zarr.abc.codec import Codec, SupportsSyncCodec +from zarr.abc.store import Store +from zarr.codecs import ZstdCodec +from zarr.codecs.vlen_utf8 import VLenBytesCodec, VLenUTF8Codec +from zarr.core.dtype import get_data_type_from_native_dtype +from zarr.core.metadata.v3 import ArrayV3Metadata +from zarr.storage import StorePath + +# The explicit id for the "str" literal avoids colliding with the auto-generated id for +# the `str` builtin. +numpy_str_dtypes: list[Any] = [ + None, + str, + pytest.param("str", id="str-literal"), + np.dtypes.StrDType, + "S", + "U", + np.dtypes.StringDType, +] +expected_array_string_dtype: np.dtype[Any] = np.dtypes.StringDType() + + +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@pytest.mark.parametrize("store", ["memory", "local"], indirect=["store"]) +@pytest.mark.parametrize("dtype", numpy_str_dtypes) +@pytest.mark.parametrize("as_object_array", [False, True]) +@pytest.mark.parametrize("compressor", [None, ZstdCodec()]) +def test_vlen_string( + store: Store, dtype: np.dtype[Any] | None, as_object_array: bool, compressor: Codec | None +) -> None: + strings = ["hello", "world", "this", "is", "a", "test"] + data = np.array(strings, dtype=dtype).reshape((2, 3)) + + sp = StorePath(store, path="string") + a = zarr.create_array( + sp, + shape=data.shape, + chunks=data.shape, + dtype=data.dtype, + fill_value="", + compressors=compressor, # type: ignore[arg-type] + ) + assert isinstance(a.metadata, ArrayV3Metadata) # needed for mypy + + # should also work if input array is an object array, provided we explicitly specified + # a stringlike dtype when creating the Array + if as_object_array: + data_obj = data.astype("O") + + a[:, :] = data_obj + else: + a[:, :] = data + assert np.array_equal(data, a[:, :]) + assert a.metadata.data_type == get_data_type_from_native_dtype(data.dtype) + assert a.dtype == data.dtype + + # test round trip + b = Array.open(sp) + assert isinstance(b.metadata, ArrayV3Metadata) # needed for mypy + assert np.array_equal(data, b[:, :]) + assert b.metadata.data_type == get_data_type_from_native_dtype(data.dtype) + assert a.dtype == data.dtype + + +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@pytest.mark.parametrize("store", ["memory"], indirect=["store"]) +@pytest.mark.parametrize( + ("dtype", "fill_value", "elements"), + [ + pytest.param("string", "", [f"S{i:05}" for i in range(9)], id="string"), + pytest.param("variable_length_bytes", b"", [b"%05d" % i for i in range(9)], id="bytes"), + ], +) +def test_vlen_f_contiguous( + store: Store, dtype: str, fill_value: str | bytes, elements: list[str] | list[bytes] +) -> None: + """An F-contiguous chunk written through a vlen codec round-trips in the original + element order rather than the transposed memory order (gh-3558).""" + # reshape(order="F") gives an F-contiguous view directly, so the whole-array write + # below hands an F-contiguous chunk to the codec; assert it to guard the precondition. + data = np.array(elements, dtype=object).reshape((3, 3), order="F") + assert data.flags.f_contiguous + sp = StorePath(store, path="vlen-f-contiguous") + # chunks == shape so the write is a single complete chunk, which the codec pipeline + # forwards to the codec untouched; a partial-chunk layout would be recopied to C order. + a = zarr.create_array( + sp, shape=data.shape, chunks=data.shape, dtype=dtype, fill_value=fill_value + ) + a[:, :] = data + assert np.array_equal(data, np.asarray(a[:, :], dtype=object)) + + +def test_vlen_utf8_codec_supports_sync() -> None: + assert isinstance(VLenUTF8Codec(), SupportsSyncCodec) + + +def test_vlen_bytes_codec_supports_sync() -> None: + assert isinstance(VLenBytesCodec(), SupportsSyncCodec) diff --git a/tests/test_codecs/test_zstd.py b/tests/test_codecs/test_zstd.py new file mode 100644 index 0000000000..3f3f15a41a --- /dev/null +++ b/tests/test_codecs/test_zstd.py @@ -0,0 +1,53 @@ +import numpy as np +import pytest + +import zarr +from zarr.abc.codec import SupportsSyncCodec +from zarr.abc.store import Store +from zarr.codecs import ZstdCodec +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import default_buffer_prototype +from zarr.core.dtype import get_data_type_from_native_dtype +from zarr.storage import StorePath + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +@pytest.mark.parametrize("checksum", [True, False]) +def test_zstd(store: Store, checksum: bool) -> None: + data = np.arange(0, 256, dtype="uint16").reshape((16, 16)) + + a = zarr.create_array( + StorePath(store, path="zstd"), + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + compressors=ZstdCodec(level=0, checksum=checksum), + ) + + a[:, :] = data + assert np.array_equal(data, a[:, :]) + + +def test_zstd_codec_supports_sync() -> None: + assert isinstance(ZstdCodec(), SupportsSyncCodec) + + +def test_zstd_codec_sync_roundtrip() -> None: + codec = ZstdCodec(level=1) + arr = np.arange(100, dtype="float64") + zdtype = get_data_type_from_native_dtype(arr.dtype) + spec = ArraySpec( + shape=arr.shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + buf = default_buffer_prototype().buffer.from_array_like(arr.view("B")) + + encoded = codec._encode_sync(buf, spec) + assert encoded is not None + decoded = codec._decode_sync(encoded, spec) + result = np.frombuffer(decoded.as_numpy_array(), dtype="float64") + np.testing.assert_array_equal(arr, result) diff --git a/tests/test_common.py b/tests/test_common.py new file mode 100644 index 0000000000..846dcbbad9 --- /dev/null +++ b/tests/test_common.py @@ -0,0 +1,198 @@ +from __future__ import annotations + +import asyncio +from collections.abc import Iterable +from typing import TYPE_CHECKING, get_args + +import numpy as np +import pytest + +from zarr.core.common import ( + ANY_ACCESS_MODE, + AccessModeLiteral, + concurrent_iter, + parse_bool, + parse_int, + parse_name, + parse_order, + parse_shapelike, + product, +) +from zarr.core.config import parse_indexing_order + +if TYPE_CHECKING: + from typing import Any, Literal + + +@pytest.mark.parametrize("data", [(0, 0, 0, 0), (1, 3, 4, 5, 6), (2, 4)]) +def test_product(data: tuple[int, ...]) -> None: + assert product(data) == np.prod(data) + + +def test_access_modes() -> None: + """ + Test that the access modes type and variable for run-time checking are equivalent. + """ + assert set(ANY_ACCESS_MODE) == set(get_args(AccessModeLiteral)) + + +async def test_concurrent_iter_schedules_eagerly() -> None: + """`concurrent_iter` must return already-scheduled tasks, not a lazy generator. + + Its docstring promises `func(*item)` is launched concurrently for every + item up front; a caller that awaits the returned tasks one at a time + (rather than via `gather`/`as_completed`, which force iteration) relies + on that eager scheduling to get any overlap at all. + """ + started = [False, False, False] + + async def mark(i: int) -> int: + started[i] = True + return i + + tasks = concurrent_iter([(0,), (1,), (2,)], mark) + + # Give the event loop one chance to run before awaiting anything + # individually. If `concurrent_iter` were lazy, nothing would have been + # scheduled yet and `started` would still be all-False here. + await asyncio.sleep(0) + assert started == [True, True, True] + + results = [await t for t in tasks] + assert results == [0, 1, 2] + + +# todo: test +def test_concurrent_map() -> None: ... + + +# todo: test +def test_to_thread() -> None: ... + + +# todo: test +def test_enum_names() -> None: ... + + +# todo: test +def test_parse_enum() -> None: ... + + +@pytest.mark.parametrize("data", [("foo", "bar"), (10, 11)]) +def test_parse_name_invalid(data: tuple[Any, Any]) -> None: + observed, expected = data + if isinstance(observed, str): + with pytest.raises(ValueError, match=f"Expected '{expected}'. Got {observed} instead."): + parse_name(observed, expected) + else: + with pytest.raises( + TypeError, match=f"Expected a string, got an instance of {type(observed)}." + ): + parse_name(observed, expected) + + +@pytest.mark.parametrize("data", [("foo", "foo"), ("10", "10")]) +def test_parse_name_valid(data: tuple[Any, Any]) -> None: + observed, expected = data + assert parse_name(observed, expected) == observed + + +@pytest.mark.parametrize("data", [0, 1, "hello", "f"]) +def test_parse_indexing_order_invalid(data: Any) -> None: + with pytest.raises(ValueError, match="Failed to parse input for 'order'"): + parse_indexing_order(data) + + +@pytest.mark.parametrize("data", [0, 1, "hello", "f"]) +def test_parse_order_invalid(data: Any) -> None: + with pytest.raises(ValueError, match="Failed to parse input for 'order'"): + parse_order(data) + + +@pytest.mark.parametrize("data", [0, 1, "true", None, [True]]) +def test_parse_bool_invalid(data: Any) -> None: + """Non-bool values are rejected with a ValueError.""" + with pytest.raises(ValueError, match="Expected instance of bool"): + parse_bool(data) + + +@pytest.mark.parametrize("data", [True, False]) +def test_parse_bool_valid(data: bool) -> None: + assert parse_bool(data) is data + + +@pytest.mark.parametrize("data", ["1", 1.0, True, False, None, [1], (1,)]) +def test_parse_int_invalid(data: Any) -> None: + """Non-int values (including bools, which are int subclasses) are rejected.""" + with pytest.raises(ValueError, match="Expected int"): + parse_int(data) + + +@pytest.mark.parametrize("data", [0, 1, -1, 2**63]) +def test_parse_int_valid(data: int) -> None: + assert parse_int(data) == data + + +@pytest.mark.parametrize("data", ["C", "F"]) +def parse_indexing_order_valid(data: Literal["C", "F"]) -> None: + assert parse_indexing_order(data) == data + + +@pytest.mark.parametrize("data", [lambda v: v, slice(None)]) +def test_parse_shapelike_invalid_single_type(data: Any) -> None: + """ + Test that we get the expected error message when passing in a value that is not an integer + or an iterable of integers. + """ + with pytest.raises(TypeError, match="Expected an integer or an iterable of integers."): + parse_shapelike(data) + + +def test_parse_shapelike_invalid_single_value() -> None: + """ + Test that we get the expected error message when passing in a negative integer. + """ + with pytest.raises(ValueError, match="Expected a non-negative integer."): + parse_shapelike(-1) + + +@pytest.mark.parametrize("data", ["shape", ("0", 1, 2, 3), {"0": "0"}, ((1, 2), (2, 2)), (4.0, 2)]) +def test_parse_shapelike_invalid_iterable_types(data: Any) -> None: + """ + Test that we get the expected error message when passing in an iterable containing + non-integer elements + """ + with pytest.raises(TypeError, match="Expected an iterable of integers"): + parse_shapelike(data) + + +@pytest.mark.parametrize("data", [(1, 2, 3, -1), (-10,)]) +def test_parse_shapelike_invalid_iterable_values(data: Any) -> None: + """ + Test that we get the expected error message when passing in an iterable containing negative + integers + """ + with pytest.raises(ValueError, match="Expected all values to be non-negative."): + parse_shapelike(data) + + +@pytest.mark.parametrize( + "data", [range(10), [0, 1, 2, np.uint64(3)], (3, 4, 5), (), 1, np.uint8(1)] +) +def test_parse_shapelike_valid(data: Iterable[int] | int) -> None: + if isinstance(data, Iterable): + expected = tuple(data) + else: + expected = (data,) + assert parse_shapelike(data) == expected + + +# todo: more dtypes +@pytest.mark.parametrize("data", [("uint8", np.uint8), ("float64", np.float64)]) +def parse_dtype(data: tuple[str, np.dtype[Any]]) -> None: + unparsed, parsed = data + assert parse_dtype(unparsed) == parsed + + +# todo: figure out what it means to test this +def test_parse_fill_value() -> None: ... diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000000..47f71a798e --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,485 @@ +import inspect +import os +from collections.abc import Iterable +from typing import Any +from unittest import mock +from unittest.mock import Mock + +import numpy as np +import pytest + +import zarr +from zarr import zeros +from zarr.abc.codec import CodecPipeline +from zarr.abc.store import ByteSetter, Store +from zarr.codecs import ( + BloscCodec, + BytesCodec, + Crc32cCodec, + ShardingCodec, +) +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import NDBuffer +from zarr.core.buffer.core import Buffer +from zarr.core.codec_pipeline import BatchedCodecPipeline +from zarr.core.config import BadConfigError, config +from zarr.core.indexing import SelectorTuple +from zarr.errors import ChunkNotFoundError, ZarrUserWarning +from zarr.registry import ( + fully_qualified_name, + get_buffer_class, + get_codec_class, + get_ndbuffer_class, + get_pipeline_class, + register_buffer, + register_codec, + register_ndbuffer, + register_pipeline, +) +from zarr.testing.buffer import ( + NDBufferUsingTestNDArrayLike, + StoreExpectingTestBuffer, + TestBuffer, + TestNDArrayLike, +) + + +def test_config_defaults_set() -> None: + # regression test for available defaults + assert ( + config.defaults + == [ + { + "default_zarr_format": 3, + "array": { + "order": "C", + "write_empty_chunks": False, + "read_missing_chunks": True, + "target_shard_size_bytes": None, + "rectilinear_chunks": False, + "sharding_coalesce_max_gap_bytes": 1 << 20, + "sharding_coalesce_max_bytes": 16 << 20, + }, + "async": {"concurrency": 10, "timeout": None}, + "threading": {"max_workers": None}, + "json_indent": 2, + "codec_pipeline": { + "path": "zarr.core.codec_pipeline.BatchedCodecPipeline", + "batch_size": 1, + "max_workers": None, + }, + "codecs": { + "blosc": "zarr.codecs.blosc.BloscCodec", + "gzip": "zarr.codecs.gzip.GzipCodec", + "zstd": "zarr.codecs.zstd.ZstdCodec", + "bytes": "zarr.codecs.bytes.BytesCodec", + "endian": "zarr.codecs.bytes.BytesCodec", # compatibility with earlier versions of ZEP1 + "crc32c": "zarr.codecs.crc32c_.Crc32cCodec", + "sharding_indexed": "zarr.codecs.sharding.ShardingCodec", + "transpose": "zarr.codecs.transpose.TransposeCodec", + "vlen-utf8": "zarr.codecs.vlen_utf8.VLenUTF8Codec", + "vlen-bytes": "zarr.codecs.vlen_utf8.VLenBytesCodec", + "numcodecs.bz2": "zarr.codecs.numcodecs.BZ2", + "numcodecs.crc32": "zarr.codecs.numcodecs.CRC32", + "numcodecs.crc32c": "zarr.codecs.numcodecs.CRC32C", + "numcodecs.lz4": "zarr.codecs.numcodecs.LZ4", + "numcodecs.lzma": "zarr.codecs.numcodecs.LZMA", + "numcodecs.zfpy": "zarr.codecs.numcodecs.ZFPY", + "numcodecs.adler32": "zarr.codecs.numcodecs.Adler32", + "numcodecs.astype": "zarr.codecs.numcodecs.AsType", + "numcodecs.bitround": "zarr.codecs.numcodecs.BitRound", + "numcodecs.blosc": "zarr.codecs.numcodecs.Blosc", + "numcodecs.delta": "zarr.codecs.numcodecs.Delta", + "numcodecs.fixedscaleoffset": "zarr.codecs.numcodecs.FixedScaleOffset", + "numcodecs.fletcher32": "zarr.codecs.numcodecs.Fletcher32", + "numcodecs.gzip": "zarr.codecs.numcodecs.GZip", + "numcodecs.jenkins_lookup3": "zarr.codecs.numcodecs.JenkinsLookup3", + "numcodecs.pcodec": "zarr.codecs.numcodecs.PCodec", + "numcodecs.packbits": "zarr.codecs.numcodecs.PackBits", + "numcodecs.shuffle": "zarr.codecs.numcodecs.Shuffle", + "numcodecs.quantize": "zarr.codecs.numcodecs.Quantize", + "numcodecs.zlib": "zarr.codecs.numcodecs.Zlib", + "numcodecs.zstd": "zarr.codecs.numcodecs.Zstd", + }, + "buffer": "zarr.buffer.cpu.Buffer", + "ndbuffer": "zarr.buffer.cpu.NDBuffer", + } + ] + ) + assert config.get("array.order") == "C" + assert config.get("async.concurrency") == 10 + assert config.get("async.timeout") is None + assert config.get("codec_pipeline.batch_size") == 1 + assert config.get("json_indent") == 2 + + +def test_array_config_init_defaults_match_global_config() -> None: + """Each `ArrayConfig.__init__` parameter that has a default must match the + value of `array.` in the global config. Catches drift between + the two sources of truth.""" + params = inspect.signature(ArrayConfig.__init__).parameters + has_defaults = { + name: p.default + for name, p in params.items() + if name != "self" and p.default is not inspect.Parameter.empty + } + assert has_defaults, "expected at least one default to check" + for name, default in has_defaults.items(): + assert default == config.get(f"array.{name}"), ( + f"ArrayConfig.__init__ default for {name!r} ({default!r}) does not " + f"match global config value for 'array.{name}' " + f"({config.get(f'array.{name}')!r})" + ) + + +@pytest.mark.parametrize( + ("key", "old_val", "new_val"), + [("array.order", "C", "F"), ("async.concurrency", 10, 128), ("json_indent", 2, 0)], +) +def test_config_defaults_can_be_overridden(key: str, old_val: Any, new_val: Any) -> None: + assert config.get(key) == old_val + with config.set({key: new_val}): + assert config.get(key) == new_val + + +def test_fully_qualified_name() -> None: + class MockClass: + pass + + assert ( + fully_qualified_name(MockClass) + == "tests.test_config.test_fully_qualified_name..MockClass" + ) + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +def test_config_codec_pipeline_class(store: Store) -> None: + # has default value + assert get_pipeline_class().__name__ != "" + + config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.BatchedCodecPipeline"}) + assert get_pipeline_class() == zarr.core.codec_pipeline.BatchedCodecPipeline + + _mock = Mock() + + class MockCodecPipeline(BatchedCodecPipeline): + async def write( + self, + batch_info: Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple, bool]], + value: NDBuffer, + drop_axes: tuple[int, ...] = (), + ) -> None: + _mock.call() + + register_pipeline(MockCodecPipeline) + config.set({"codec_pipeline.path": fully_qualified_name(MockCodecPipeline)}) + + assert get_pipeline_class() == MockCodecPipeline + + # test if codec is used + arr = zarr.create_array( + store=store, + shape=(100,), + chunks=(10,), + zarr_format=3, + dtype="i4", + ) + arr[:] = range(100) + + _mock.call.assert_called() + + config.set({"codec_pipeline.path": "wrong_name"}) + with pytest.raises(BadConfigError): + get_pipeline_class() + + class MockEnvCodecPipeline(CodecPipeline): + pass + + register_pipeline(MockEnvCodecPipeline) # type: ignore[type-abstract] + + with mock.patch.dict( + os.environ, {"ZARR_CODEC_PIPELINE__PATH": fully_qualified_name(MockEnvCodecPipeline)} + ): + assert get_pipeline_class(reload_config=True) == MockEnvCodecPipeline + + +@pytest.mark.filterwarnings("error") +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +def test_config_codec_implementation(store: Store) -> None: + # has default value + assert fully_qualified_name(get_codec_class("blosc")) == config.defaults[0]["codecs"]["blosc"] + + _mock = Mock() + + class MockBloscCodec(BloscCodec): + # Record a call from whichever encode entry point the active codec + # pipeline uses: the async `_encode_single` (BatchedCodecPipeline, the + # default) or the synchronous `_encode_sync` (FusedCodecPipeline). + # Overriding both keeps this test ("the configured codec is actually + # used") independent of which pipeline is the default. + async def _encode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer | None: + _mock.call() + return None + + def _encode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer | None: + _mock.call() + return None + + register_codec("blosc", MockBloscCodec) + with config.set({"codecs.blosc": fully_qualified_name(MockBloscCodec)}): + assert get_codec_class("blosc") == MockBloscCodec + + # test if codec is used + arr = zarr.create_array( + store=store, + shape=(100,), + chunks=(10,), + zarr_format=3, + dtype="i4", + compressors=[{"name": "blosc", "configuration": {}}], + ) + arr[:] = range(100) + _mock.call.assert_called() + + # test set codec with environment variable + class NewBloscCodec(BloscCodec): + pass + + register_codec("blosc", NewBloscCodec) + with mock.patch.dict(os.environ, {"ZARR_CODECS__BLOSC": fully_qualified_name(NewBloscCodec)}): + assert get_codec_class("blosc", reload_config=True) == NewBloscCodec + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +def test_config_ndbuffer_implementation(store: Store) -> None: + # set custom ndbuffer with TestNDArrayLike implementation + register_ndbuffer(NDBufferUsingTestNDArrayLike) + with config.set({"ndbuffer": fully_qualified_name(NDBufferUsingTestNDArrayLike)}): + assert get_ndbuffer_class() == NDBufferUsingTestNDArrayLike + arr = zarr.create_array( + store=store, + shape=(100,), + chunks=(10,), + zarr_format=3, + dtype="i4", + ) + got = arr[:] + assert isinstance(got, TestNDArrayLike) + + +def test_config_buffer_implementation() -> None: + # has default value + assert config.defaults[0]["buffer"] == "zarr.buffer.cpu.Buffer" + + arr = zeros(shape=(100,), store=StoreExpectingTestBuffer()) + + # AssertionError of StoreExpectingTestBuffer when not using my buffer + with pytest.raises(AssertionError): + arr[:] = np.arange(100) + + register_buffer(TestBuffer) + with config.set({"buffer": fully_qualified_name(TestBuffer)}): + assert get_buffer_class() == TestBuffer + + # no error using TestBuffer + data = np.arange(100) + arr[:] = np.arange(100) + assert np.array_equal(arr[:], data) + + data2d = np.arange(1000).reshape(100, 10) + arr_sharding = zeros( + shape=(100, 10), + store=StoreExpectingTestBuffer(), + codecs=[ShardingCodec(chunk_shape=(10, 10))], + ) + arr_sharding[:] = data2d + assert np.array_equal(arr_sharding[:], data2d) + + arr_Crc32c = zeros( + shape=(100, 10), + store=StoreExpectingTestBuffer(), + codecs=[BytesCodec(), Crc32cCodec()], + ) + arr_Crc32c[:] = data2d + assert np.array_equal(arr_Crc32c[:], data2d) + + +def test_config_buffer_backwards_compatibility() -> None: + # This should warn once zarr.core is private + # https://github.com/zarr-developers/zarr-python/issues/2621 + with zarr.config.set( + {"buffer": "zarr.core.buffer.cpu.Buffer", "ndbuffer": "zarr.core.buffer.cpu.NDBuffer"} + ): + get_buffer_class() + get_ndbuffer_class() + + +@pytest.mark.gpu +def test_config_buffer_backwards_compatibility_gpu() -> None: + # This should warn once zarr.core is private + # https://github.com/zarr-developers/zarr-python/issues/2621 + with zarr.config.set( + {"buffer": "zarr.core.buffer.gpu.Buffer", "ndbuffer": "zarr.core.buffer.gpu.NDBuffer"} + ): + get_buffer_class() + get_ndbuffer_class() + + +@pytest.mark.filterwarnings("error") +def test_warning_on_missing_codec_config() -> None: + class NewCodec(BytesCodec): + pass + + class NewCodec2(BytesCodec): + pass + + # error if codec is not registered + with pytest.raises(KeyError): + get_codec_class("missing_codec") + + # no warning if only one implementation is available + register_codec("new_codec", NewCodec) + get_codec_class("new_codec") + + # warning because multiple implementations are available but none is selected in the config + register_codec("new_codec", NewCodec2) + with pytest.warns( + ZarrUserWarning, match="not configured in config. Selecting any implementation" + ): + get_codec_class("new_codec") + + # no warning if multiple implementations are available and one is selected in the config + with config.set({"codecs.new_codec": fully_qualified_name(NewCodec)}): + get_codec_class("new_codec") + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +@pytest.mark.parametrize( + "kwargs", + [ + {"shards": (4, 4)}, + {"compressors": None}, + ], + ids=["partial_decode", "full_decode"], +) +def test_config_read_missing_chunks(store: Store, kwargs: dict[str, Any]) -> None: + arr = zarr.create_array( + store=store, + shape=(4, 4), + chunks=(2, 2), + dtype="int32", + fill_value=42, + **kwargs, + ) + + # default behavior: missing chunks are filled with the fill value + result = zarr.open_array(store)[:] + assert np.array_equal(result, np.full((4, 4), 42, dtype="int32")) + + # with read_missing_chunks=False, reading missing chunks raises an error + with config.set({"array.read_missing_chunks": False}): + with pytest.raises(ChunkNotFoundError): + zarr.open_array(store)[:] + + # after writing data, all chunks exist and no error is raised + arr[:] = np.arange(16, dtype="int32").reshape(4, 4) + with config.set({"array.read_missing_chunks": False}): + result = zarr.open_array(store)[:] + assert np.array_equal(result, np.arange(16, dtype="int32").reshape(4, 4)) + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +def test_config_read_missing_chunks_sharded_inner(store: Store) -> None: + """Because the shard index and inner chunks should be stored + together in a single storage object (read: a file or blob), + we delegate to the shard index the responsibility of determining + what chunks should be present. + + Thus, `read_missing_chunks` raises an error only if the entire *shard* + is missing. Missing inner chunks are filled with the array's fill value + and do not raise an error, even if `read_missing_chunks=False` at the + array level. + """ + arr = zarr.create_array( + store=store, + shape=(8, 4), + chunks=(2, 2), + shards=(4, 4), + dtype="int32", + fill_value=42, + ) + + # write only one inner chunk in the first shard, leaving the second shard empty + arr[0:2, 0:2] = np.ones((2, 2), dtype="int32") + + with config.set({"array.read_missing_chunks": False}): + a = zarr.open_array(store) + + # first shard exists: missing inner chunks are filled, no error + result = a[:4] + expected = np.full((4, 4), 42, dtype="int32") + expected[0:2, 0:2] = 1 + assert np.array_equal(result, expected) + + # second shard is entirely missing: raises an error + with pytest.raises(ChunkNotFoundError): + a[4:] + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +def test_config_read_missing_chunks_write_empty_chunks(store: Store) -> None: + """write_empty_chunks=False drops chunks equal to fill_value, which then + appear missing to read_missing_chunks=False.""" + arr = zarr.create_array( + store=store, + shape=(4,), + chunks=(2,), + dtype="int32", + fill_value=0, + config={"write_empty_chunks": False, "read_missing_chunks": False}, + ) + + # write non-fill-value data: chunks are stored + arr[:] = [1, 2, 3, 4] + assert np.array_equal(arr[:], [1, 2, 3, 4]) + + # overwrite with fill_value: chunks are dropped by write_empty_chunks=False + arr[:] = 0 + with pytest.raises(ChunkNotFoundError): + arr[:] + + # with write_empty_chunks=True, chunks are kept and no error is raised + with config.set({"array.write_empty_chunks": True}): + arr = zarr.open_array(store) + arr[:] = 0 + assert np.array_equal(arr[:], [0, 0, 0, 0]) + + +@pytest.mark.parametrize( + "key", + [ + "array.v2_default_compressor.numeric", + "array.v2_default_compressor.string", + "array.v2_default_compressor.bytes", + "array.v2_default_filters.string", + "array.v2_default_filters.bytes", + "array.v3_default_filters.numeric", + "array.v3_default_filters.raw", + "array.v3_default_filters.bytes", + "array.v3_default_serializer.numeric", + "array.v3_default_serializer.string", + "array.v3_default_serializer.bytes", + "array.v3_default_compressors.string", + "array.v3_default_compressors.bytes", + "array.v3_default_compressors", + ], +) +def test_deprecated_config(key: str) -> None: + """ + Test that a valuerror is raised when setting the default chunk encoding for a given + data type category + """ + + with pytest.raises(ValueError): + with zarr.config.set({key: "foo"}): + pass diff --git a/tests/test_docs.py b/tests/test_docs.py new file mode 100644 index 0000000000..0ed429f173 --- /dev/null +++ b/tests/test_docs.py @@ -0,0 +1,262 @@ +""" +Tests for executable code blocks in markdown documentation. + +This module uses pytest-examples to validate Python code examples in the docs. A block is +validated if it renders output at build (exec="true") or is explicitly marked for testing +(test="true"). The two flags are separate on purpose: exec= drives markdown-exec's +build-time rendering, while test= lets a block be validated without being run at build +(e.g. gpu/s3 examples the build environment cannot run). The test_no_unvalidated_blocks +guard ensures every python block declares one of those, or an explicit exec="false" opt-out +with a reason, so a block can never silently skip validation. +""" + +from __future__ import annotations + +from collections import defaultdict +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import pytest + +pytest.importorskip("pytest_examples") +from pytest_examples import CodeExample, EvalExample, find_examples + +if TYPE_CHECKING: + from collections.abc import Generator + +DOCS_ROOT = Path(__file__).parent.parent / "docs" +SOURCES_ROOT = Path(__file__).parent.parent / "src" / "zarr" + + +def name_example(path: str, session: str) -> str: + """Generate a readable name for a test case from file path and session.""" + file = Path(path) + try: + file = file.relative_to(DOCS_ROOT) + except ValueError: + # Path is outside DOCS_ROOT (e.g. a tmp_path fixture in unit tests); use the + # bare file name rather than an absolute path for a stable, readable id. + file = Path(file.name) + return f"{file}:{session}" + + +def _marker_names(settings: dict[str, str]) -> list[str]: + """Parse a block's markers="a b" attribute into a list of marker names.""" + return [name for name in settings.get("markers", "").split() if name] + + +def _is_tested(settings: dict[str, str]) -> bool: + """A block is validated by our pytest harness if it is run at build to render output + (exec="true") OR explicitly marked for testing (test="true"). The two flags are + separate on purpose: exec= drives markdown-exec's build-time rendering, while test= + lets a block be validated without being run at build (e.g. gpu/s3 blocks, which the + build environment cannot run).""" + return settings.get("exec") == "true" or settings.get("test") == "true" + + +def _session_params(root: Path) -> list[Any]: + """Group tested examples (exec="true" or test="true") by (file, session) and emit one + pytest.param per session, carrying the union of markers declared by that session's + blocks.""" + sessions: defaultdict[tuple[str, str], list[CodeExample]] = defaultdict(list) + marks_by_session: defaultdict[tuple[str, str], set[str]] = defaultdict(set) + + for example in find_examples(str(root)): + settings = example.prefix_settings() + if not _is_tested(settings): + continue + session_name = settings.get("session", "_default") + key = (str(example.path), session_name) + sessions[key].append(example) + marks_by_session[key].update(_marker_names(settings)) + + params = [] + for key in sorted(sessions.keys(), key=lambda x: (x[0], x[1])): + marks = tuple(getattr(pytest.mark, name) for name in sorted(marks_by_session[key])) + params.append(pytest.param(key, marks=marks, id=name_example(key[0], key[1]))) + return params + + +S3_BUCKET = "example-bucket" + + +@pytest.fixture +def docs_s3_backend( + moto_server: str, monkeypatch: pytest.MonkeyPatch +) -> Generator[None, None, None]: + """Point docs S3 examples at the shared moto server (tests/conftest.py) via a + process-wide AWS_ENDPOINT_URL, so a block can use a bare s3:// URL with no + storage_options (see spike in the design notes). The server lifecycle belongs to the + session-scoped `moto_server` fixture; this fixture only adds the docs-specific + endpoint env var and a fresh bucket, and restores both on teardown.""" + s3fs = pytest.importorskip("s3fs") + botocore = pytest.importorskip("botocore") + requests = pytest.importorskip("requests") + + monkeypatch.setenv("AWS_ENDPOINT_URL", moto_server) + + session = botocore.session.Session() + client = session.create_client("s3", endpoint_url=moto_server, region_name="us-east-1") + client.create_bucket(Bucket=S3_BUCKET) + client.close() + s3fs.S3FileSystem.clear_instance_cache() + try: + yield + finally: + # Reset moto state; AWS_ENDPOINT_URL is restored automatically by monkeypatch. + # The shared server keeps running (the moto_server fixture stops it at session end). + requests.post(f"{moto_server}moto-api/reset") + + +def test_markers_attribute_is_parsed(tmp_path: Path) -> None: + """A test="true" block tagged markers="s3" must surface that marker on its + parametrized case, so pytest can gate/bind it (e.g. attach the moto fixture). + Uses test="true" (not exec="true") because marker-bound blocks are validated by the + harness without being run at build time.""" + md = tmp_path / "ex.md" + md.write_text( + '```python test="true" session="demo" markers="s3"\nimport zarr\n```\n', + encoding="utf-8", + ) + params = _session_params(md.parent) + assert len(params) == 1 + marks = params[0].marks + assert any(m.name == "s3" for m in marks) + + +def test_no_unvalidated_blocks() -> None: + """Every python code block in docs/ must declare its validation state: exec="true" + (run at build to render output), test="true" (validated by this harness without being + run at build), or exec="false" with a reason (explicit, documented opt-out). A bare or + mistyped fence (e.g. exec="on") fails here, so a block can never silently opt out of + validation -- the gap that hid the invalid create_array(mode="w") example in #4016. + + A separate placement constraint is enforced by test_test_only_blocks_come_last.""" + offenders: list[str] = [] + for example in find_examples(str(DOCS_ROOT)): + rel = Path(example.path).relative_to(DOCS_ROOT) + settings = example.prefix_settings() + exec_val = settings.get("exec") + loc = f"{rel}:{example.start_line}" + # Validated either by build-render (exec="true") or by the test harness + # (test="true"). + if _is_tested(settings): + continue + # Explicit, documented opt-out from execution. + if exec_val == "false" and settings.get("reason", "").strip(): + continue + offenders.append( + f"{loc} (exec={exec_val!r}, test={settings.get('test')!r}, " + f"reason={settings.get('reason')!r})" + ) + + assert not offenders, ( + 'Docs python blocks must be exec="true", test="true", or exec="false" with a ' + "reason:\n" + "\n".join(offenders) + ) + + +def test_test_only_blocks_come_last() -> None: + """A conservative placement convention: a test="true"-only block must come after every + exec="true" block in the same file. + + Mechanism (established by experiment + markdown-exec's SuperFences integration): a + python fence that markdown-exec does not execute -- i.e. one lacking exec="true", + whether test="true" or exec="false" -- placed before an exec="true" block disrupts + markdown-exec's build-time execution of a *later, state-dependent* block. Observed: a + non-exec python fence inserted before the quickstart ZipStore write/read pair made the + read block fail with FileNotFoundError (the write never took effect), aborting + `mkdocs build --strict`. The effect needs a cross-block dependency to surface, so it + does not affect the standalone exec="true" blocks in e.g. data_types.md/performance.md + that already have exec="false" opt-out blocks above them. + + Because we cannot statically tell which later blocks are state-dependent, this guard + enforces the simple, safe convention only for the blocks we author this way + (test="true" marker-bound examples like s3/gpu). It is NOT a complete build-hazard + check -- the authoritative check is `mkdocs build --strict` (the docs:check CI job), + which catches the exec="false" case too. This guard just turns the common test-only + case into a fast, local failure.""" + # Collect, per published-docs file, the start lines of test-only and exec blocks. + test_only: defaultdict[str, list[int]] = defaultdict(list) + exec_lines: defaultdict[str, list[int]] = defaultdict(list) + for example in find_examples(str(DOCS_ROOT)): + settings = example.prefix_settings() + path = str(example.path) + if settings.get("exec") == "true": + exec_lines[path].append(example.start_line) + elif settings.get("test") == "true": + test_only[path].append(example.start_line) + + offenders: list[str] = [] + for path, only_lines in test_only.items(): + rel = Path(path).relative_to(DOCS_ROOT) + last_exec = max(exec_lines.get(path, [0])) + offenders.extend( + f'{rel}:{line} (test="true" block precedes an exec="true" block at line {last_exec})' + for line in only_lines + if line < last_exec + ) + + assert not offenders, ( + 'A test="true"-only block must come after every exec="true" block in the same ' + 'file: a non-executed python fence before an exec="true" block can disrupt ' + "markdown-exec's build-time execution of a later state-dependent block (see this " + "test's docstring):\n" + "\n".join(offenders) + ) + + +# Get all example sessions +@pytest.mark.parametrize("session_key", _session_params(DOCS_ROOT)) +def test_documentation_examples( + session_key: tuple[str, str], + eval_example: EvalExample, + request: pytest.FixtureRequest, +) -> None: + """ + Test that all validated code examples (exec="true" or test="true") in documentation + execute successfully. + + This test groups examples by session (file + session name) and runs them + sequentially in the same execution context, allowing code to build on + previous examples. + + This test uses pytest-examples to: + - Find all code examples marked exec="true" or test="true" in markdown files + - Group them by session + - Execute them in order within the same context + - Verify no exceptions are raised + """ + if request.node.get_closest_marker("gpu") is not None: + pytest.importorskip("cupy") + + if request.node.get_closest_marker("s3") is not None: + request.getfixturevalue("docs_s3_backend") + + file_path, session_name = session_key + + # Get examples for this session + all_examples = list(find_examples(DOCS_ROOT)) + examples = [] + for example in all_examples: + settings = example.prefix_settings() + if not _is_tested(settings): + continue + if str(example.path) == file_path and settings.get("session", "_default") == session_name: + examples.append(example) + + # Run all examples in this session sequentially, preserving state + module_globals: dict[str, object] = {} + for example in examples: + # TODO: uncomment this line when we are ready to fix output checks + # result = eval_example.run_print_check(example, module_globals=module_globals) + result = eval_example.run(example, module_globals=module_globals) + # Update globals with the results from this execution + module_globals.update(result) + + +@pytest.mark.parametrize("example", list(find_examples(str(SOURCES_ROOT))), ids=str) +def test_docstrings(example: CodeExample, eval_example: EvalExample) -> None: + """Test our docstring examples.""" + if example.path.name == "config.py" and "your.module" in example.source: + pytest.skip("Skip testing docstring example that assumes nonexistent module.") + eval_example.run_print_check(example) diff --git a/tests/test_dtype/__init__.py b/tests/test_dtype/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_dtype/conftest.py b/tests/test_dtype/conftest.py new file mode 100644 index 0000000000..100b9df226 --- /dev/null +++ b/tests/test_dtype/conftest.py @@ -0,0 +1,83 @@ +# Generate a collection of zdtype instances for use in testing. +import warnings +from collections import Counter +from typing import Any + +import numpy as np + +from zarr.core.dtype import data_type_registry +from zarr.core.dtype.common import HasLength +from zarr.core.dtype.npy.structured import Struct +from zarr.core.dtype.npy.time import DateTime64, TimeDelta64 +from zarr.core.dtype.wrapper import ZDType + +zdtype_examples: tuple[ZDType[Any, Any], ...] = () +for wrapper_cls in data_type_registry.contents.values(): + if wrapper_cls is Struct: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + zdtype_examples += ( + wrapper_cls.from_native_dtype(np.dtype([("a", np.float64), ("b", np.int8)])), + ) + elif issubclass(wrapper_cls, HasLength): + zdtype_examples += (wrapper_cls(length=1),) + elif issubclass(wrapper_cls, DateTime64 | TimeDelta64): + zdtype_examples += (wrapper_cls(unit="s", scale_factor=10),) + else: + zdtype_examples += (wrapper_cls(),) + + +def pytest_generate_tests(metafunc: Any) -> None: + """ + This is a pytest hook to parametrize class-scoped fixtures. + + This hook allows us to define class-scoped fixtures as class attributes and then + generate the parametrize calls for pytest. This allows the fixtures to be + reused across multiple tests within the same class. + + For example, if you had a regular pytest class like this: + + class TestClass: + @pytest.mark.parametrize("param_a", [1, 2, 3]) + def test_method(self, param_a): + ... + + Child classes inheriting from ``TestClass`` would not be able to override the ``param_a`` fixture + + this implementation of ``pytest_generate_tests`` allows you to define class-scoped fixtures as + class attributes, which allows the following to work: + + class TestExample: + param_a = [1, 2, 3] + + def test_example(self, param_a): + ... + + # this class will have its test_example method parametrized with the values of TestB.param_a + class TestB(TestExample): + param_a = [1, 2, 100, 10] + + """ + # Iterate over all the fixtures defined in the class + # and parametrize them with the values defined in the class + # This allows us to define class-scoped fixtures as class attributes + # and then generate the parametrize calls for pytest + for fixture_name in metafunc.fixturenames: + if hasattr(metafunc.cls, fixture_name): + params = getattr(metafunc.cls, fixture_name) + metafunc.parametrize( + fixture_name, params, scope="class", ids=_unique_ids([str(p) for p in params]) + ) + + +def _unique_ids(ids: list[str]) -> list[str]: + """Suffix repeated ids with their positional index so every id is unique. + + Distinct parameters can stringify identically: for example `np.dtype("i")` and + `np.dtype(" 1 else id_ for idx, id_ in enumerate(ids)] diff --git a/tests/test_dtype/test_npy/test_bool.py b/tests/test_dtype/test_npy/test_bool.py new file mode 100644 index 0000000000..da30214b3b --- /dev/null +++ b/tests/test_dtype/test_npy/test_bool.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +import numpy as np + +from tests.test_dtype.test_wrapper import BaseTestZDType +from zarr.core.dtype.npy.bool import Bool + + +class TestBool(BaseTestZDType): + test_cls = Bool + + valid_dtype = (np.dtype(np.bool_),) + invalid_dtype = ( + np.dtype(np.int8), + np.dtype(np.float64), + np.dtype(np.uint16), + ) + valid_json_v2 = ({"name": "|b1", "object_codec_id": None},) + valid_json_v3 = ("bool",) + invalid_json_v2 = ( + "|b1", + "bool", + "|f8", + ) + invalid_json_v3 = ( + "|b1", + "|f8", + {"name": "bool", "configuration": {"endianness": "little"}}, + ) + + scalar_v2_params = ((Bool(), True), (Bool(), False)) + scalar_v3_params = ((Bool(), True), (Bool(), False)) + + cast_value_params = ( + (Bool(), "true", np.True_), + (Bool(), True, np.True_), + (Bool(), False, np.False_), + (Bool(), np.True_, np.True_), + (Bool(), np.False_, np.False_), + ) + invalid_scalar_params = (None,) + item_size_params = (Bool(),) diff --git a/tests/test_dtype/test_npy/test_bytes.py b/tests/test_dtype/test_npy/test_bytes.py new file mode 100644 index 0000000000..6a4bcc4691 --- /dev/null +++ b/tests/test_dtype/test_npy/test_bytes.py @@ -0,0 +1,172 @@ +import numpy as np +import pytest + +from tests.test_dtype.test_wrapper import BaseTestZDType +from zarr.core.dtype.npy.bytes import NullTerminatedBytes, RawBytes, VariableLengthBytes +from zarr.errors import UnstableSpecificationWarning + + +class TestNullTerminatedBytes(BaseTestZDType): + test_cls = NullTerminatedBytes + valid_dtype = (np.dtype("|S10"), np.dtype("|S4")) + invalid_dtype = ( + np.dtype(np.int8), + np.dtype(np.float64), + np.dtype("|U10"), + ) + valid_json_v2 = ( + {"name": "|S1", "object_codec_id": None}, + {"name": "|S2", "object_codec_id": None}, + {"name": "|S4", "object_codec_id": None}, + ) + valid_json_v3 = ({"name": "null_terminated_bytes", "configuration": {"length_bytes": 10}},) + invalid_json_v2 = ( + "|S", + "|U10", + "|f8", + {"name": "|S4", "object_codec_id": "vlen-bytes"}, + ) + invalid_json_v3 = ( + {"name": "fixed_length_ascii", "configuration": {"length_bits": 0}}, + {"name": "numpy.fixed_length_ascii", "configuration": {"length_bits": "invalid"}}, + ) + + scalar_v2_params = ( + (NullTerminatedBytes(length=1), "MA=="), + (NullTerminatedBytes(length=2), "YWI="), + (NullTerminatedBytes(length=4), "YWJjZA=="), + ) + scalar_v3_params = ( + (NullTerminatedBytes(length=1), "MA=="), + (NullTerminatedBytes(length=2), "YWI="), + (NullTerminatedBytes(length=4), "YWJjZA=="), + ) + cast_value_params = ( + (NullTerminatedBytes(length=1), "", np.bytes_("")), + (NullTerminatedBytes(length=2), "ab", np.bytes_("ab")), + (NullTerminatedBytes(length=4), "abcdefg", np.bytes_("abcd")), + ) + invalid_scalar_params = ((NullTerminatedBytes(length=1), 1.0),) + item_size_params = ( + NullTerminatedBytes(length=1), + NullTerminatedBytes(length=4), + NullTerminatedBytes(length=10), + ) + + +class TestRawBytes(BaseTestZDType): + test_cls = RawBytes + valid_dtype = (np.dtype("|V10"),) + invalid_dtype = ( + np.dtype(np.int8), + np.dtype(np.float64), + np.dtype("|S10"), + ) + valid_json_v2 = ({"name": "|V10", "object_codec_id": None},) + valid_json_v3 = ( + {"name": "raw_bytes", "configuration": {"length_bytes": 1}}, + {"name": "raw_bytes", "configuration": {"length_bytes": 8}}, + ) + + invalid_json_v2 = ( + "|V", + "|S10", + "|f8", + ) + invalid_json_v3 = ( + {"name": "r10"}, + {"name": "r-80"}, + ) + + scalar_v2_params = ( + (RawBytes(length=1), "AA=="), + (RawBytes(length=2), "YWI="), + (RawBytes(length=4), "YWJjZA=="), + ) + scalar_v3_params = ( + (RawBytes(length=1), "AA=="), + (RawBytes(length=2), "YWI="), + (RawBytes(length=4), "YWJjZA=="), + ) + cast_value_params = ( + (RawBytes(length=1), b"\x00", np.void(b"\x00")), + (RawBytes(length=2), b"ab", np.void(b"ab")), + (RawBytes(length=4), b"abcd", np.void(b"abcd")), + ) + invalid_scalar_params = ((RawBytes(length=1), 1.0),) + item_size_params = ( + RawBytes(length=1), + RawBytes(length=4), + RawBytes(length=10), + ) + + +class TestVariableLengthBytes(BaseTestZDType): + test_cls = VariableLengthBytes + valid_dtype = (np.dtype("|O"),) + invalid_dtype = ( + np.dtype(np.int8), + np.dtype(np.float64), + np.dtype("|U10"), + ) + valid_json_v2 = ({"name": "|O", "object_codec_id": "vlen-bytes"},) + valid_json_v3 = ("variable_length_bytes",) + invalid_json_v2 = ( + "|S", + "|U10", + "|f8", + ) + invalid_json_v3 = ( + {"name": "fixed_length_ascii", "configuration": {"length_bits": 0}}, + {"name": "numpy.fixed_length_ascii", "configuration": {"length_bits": "invalid"}}, + ) + + scalar_v2_params = ( + (VariableLengthBytes(), ""), + (VariableLengthBytes(), "YWI="), + (VariableLengthBytes(), "YWJjZA=="), + ) + scalar_v3_params = ( + (VariableLengthBytes(), ""), + (VariableLengthBytes(), "YWI="), + (VariableLengthBytes(), "YWJjZA=="), + ) + cast_value_params = ( + (VariableLengthBytes(), "", b""), + (VariableLengthBytes(), "ab", b"ab"), + (VariableLengthBytes(), "abcdefg", b"abcdefg"), + ) + invalid_scalar_params = ((VariableLengthBytes(), 1.0),) + item_size_params = (VariableLengthBytes(),) + + +def test_vlen_bytes_alias() -> None: + """Test that "bytes" is an accepted alias for "variable_length_bytes" in JSON metadata""" + a = VariableLengthBytes.from_json("bytes", zarr_format=3) + b = VariableLengthBytes.from_json("variable_length_bytes", zarr_format=3) + assert a == b + + +@pytest.mark.parametrize( + "zdtype", [NullTerminatedBytes(length=10), RawBytes(length=10), VariableLengthBytes()] +) +def test_unstable_dtype_warning( + zdtype: NullTerminatedBytes | RawBytes | VariableLengthBytes, +) -> None: + """ + Test that we get a warning when serializing a dtype without a zarr v3 spec to json + when zarr_format is 3 + """ + with pytest.warns(UnstableSpecificationWarning): + zdtype.to_json(zarr_format=3) + + +@pytest.mark.parametrize("zdtype_cls", [NullTerminatedBytes, RawBytes]) +def test_invalid_size(zdtype_cls: type[NullTerminatedBytes] | type[RawBytes]) -> None: + """ + Test that it's impossible to create a data type that has no length + """ + length = 0 + msg = f"length must be >= 1, got {length}." + with pytest.raises(ValueError, match=msg): + zdtype_cls(length=length) diff --git a/tests/test_dtype/test_npy/test_common.py b/tests/test_dtype/test_npy/test_common.py new file mode 100644 index 0000000000..b7e4e875ad --- /dev/null +++ b/tests/test_dtype/test_npy/test_common.py @@ -0,0 +1,343 @@ +from __future__ import annotations + +import base64 +import re +import sys +from typing import TYPE_CHECKING, Any, get_args + +import numpy as np +import pytest + +from tests.conftest import nan_equal +from zarr.core.dtype.common import ENDIANNESS_STR, JSONFloatV2, SpecialFloatStrings +from zarr.core.dtype.npy.common import ( + NumpyEndiannessStr, + bytes_from_json, + bytes_to_json, + check_json_bool, + check_json_complex_float_v2, + check_json_complex_float_v3, + check_json_float_v2, + check_json_float_v3, + check_json_int, + check_json_intish_float, + check_json_str, + complex_float_to_json_v2, + complex_float_to_json_v3, + endianness_from_numpy_str, + endianness_to_numpy_str, + float_from_json_v2, + float_from_json_v3, + float_to_json_v2, + float_to_json_v3, +) + +if TYPE_CHECKING: + from zarr.core.common import JSON, ZarrFormat + + +# Each special value is tested as both a Python float and a numpy scalar. The explicit +# ids are load-bearing: np.float64("inf") stringifies identically to float("inf"), so +# without them these parameter sets would produce duplicate test ids. +json_float_v2_roundtrip_cases: tuple[Any, ...] = ( + pytest.param("Infinity", float("inf"), id="Infinity-float"), + pytest.param("Infinity", np.float64("inf"), id="Infinity-float64"), + pytest.param("-Infinity", float("-inf"), id="-Infinity-float"), + pytest.param("-Infinity", np.float64("-inf"), id="-Infinity-float64"), + pytest.param("NaN", float("nan"), id="NaN-float"), + pytest.param("NaN", np.float64("nan"), id="NaN-float64"), + pytest.param(1.0, 1.0, id="1.0-1.0"), +) + +json_float_v3_cases = json_float_v2_roundtrip_cases + + +@pytest.mark.parametrize( + ("data", "expected"), + [(">", "big"), ("<", "little"), ("=", sys.byteorder), ("|", None), ("err", "")], +) +def test_endianness_from_numpy_str(data: str, expected: str | None) -> None: + """ + Test that endianness_from_numpy_str correctly converts a numpy str literal to a human-readable literal value. + This test also checks that an invalid string input raises a ``ValueError`` + """ + if data in get_args(NumpyEndiannessStr): + assert endianness_from_numpy_str(data) == expected # type: ignore[arg-type] + else: + msg = f"Invalid endianness: {data!r}. Expected one of {get_args(NumpyEndiannessStr)}" + with pytest.raises(ValueError, match=re.escape(msg)): + endianness_from_numpy_str(data) # type: ignore[arg-type] + + +@pytest.mark.parametrize( + ("data", "expected"), + [("big", ">"), ("little", "<"), (None, "|"), ("err", "")], +) +def test_endianness_to_numpy_str(data: str | None, expected: str) -> None: + """ + Test that endianness_to_numpy_str correctly converts a human-readable literal value to a numpy str literal. + This test also checks that an invalid string input raises a ``ValueError`` + """ + if data in ENDIANNESS_STR: + assert endianness_to_numpy_str(data) == expected # type: ignore[arg-type] + else: + msg = f"Invalid endianness: {data!r}. Expected one of {ENDIANNESS_STR}" + with pytest.raises(ValueError, match=re.escape(msg)): + endianness_to_numpy_str(data) # type: ignore[arg-type] + + +@pytest.mark.parametrize( + ("data", "expected"), json_float_v2_roundtrip_cases + (("SHOULD_ERR", ""),) +) +def test_float_from_json_v2(data: JSONFloatV2 | str, expected: float | str) -> None: + """ + Test that float_from_json_v2 correctly converts a JSON string representation of a float to a float. + This test also checks that an invalid string input raises a ``ValueError`` + """ + if data != "SHOULD_ERR": + assert nan_equal(float_from_json_v2(data), expected) # type: ignore[arg-type] + else: + msg = f"could not convert string to float: {data!r}" + with pytest.raises(ValueError, match=msg): + float_from_json_v2(data) # type: ignore[arg-type] + + +@pytest.mark.parametrize( + ("data", "expected"), json_float_v3_cases + (("SHOULD_ERR", ""), ("0x", "")) +) +def test_float_from_json_v3(data: JSONFloatV2 | str, expected: float | str) -> None: + """ + Test that float_from_json_v3 correctly converts a JSON string representation of a float to a float. + This test also checks that an invalid string input raises a ``ValueError`` + """ + if data == "SHOULD_ERR": + msg = ( + f"Invalid float value: {data!r}. Expected a string starting with the hex prefix" + " '0x', or one of 'NaN', 'Infinity', or '-Infinity'." + ) + with pytest.raises(ValueError, match=msg): + float_from_json_v3(data) + elif data == "0x": + msg = ( + f"Invalid hexadecimal float value: {data!r}. " + "Expected the '0x' prefix to be followed by 4, 8, or 16 numeral characters" + ) + + with pytest.raises(ValueError, match=msg): + float_from_json_v3(data) + else: + assert nan_equal(float_from_json_v3(data), expected) + + +# note the order of parameters relative to the order of the parametrized variable. +@pytest.mark.parametrize(("expected", "data"), json_float_v2_roundtrip_cases) +def test_float_to_json_v2(data: float | np.floating[Any], expected: JSONFloatV2) -> None: + """ + Test that floats are JSON-encoded properly for zarr v2 + """ + observed = float_to_json_v2(data) + assert observed == expected + + +# note the order of parameters relative to the order of the parametrized variable. +@pytest.mark.parametrize(("expected", "data"), json_float_v3_cases) +def test_float_to_json_v3(data: float | np.floating[Any], expected: JSONFloatV2) -> None: + """ + Test that floats are JSON-encoded properly for zarr v3 + """ + observed = float_to_json_v3(data) + assert observed == expected + + +def test_bytes_from_json(zarr_format: ZarrFormat) -> None: + """ + Test that a string is interpreted as base64-encoded bytes using the ascii alphabet. + This test takes zarr_format as a parameter but doesn't actually do anything with it, because at + present there is no zarr-format-specific logic in the code being tested, but such logic may + exist in the future. + """ + data = "\00" + assert bytes_from_json(data, zarr_format=zarr_format) == base64.b64decode(data.encode("ascii")) + + +def test_bytes_to_json(zarr_format: ZarrFormat) -> None: + """ + Test that bytes are encoded with base64 using the ascii alphabet. + + This test takes zarr_format as a parameter but doesn't actually do anything with it, because at + present there is no zarr-format-specific logic in the code being tested, but such logic may + exist in the future. + """ + + data = b"asdas" + assert bytes_to_json(data, zarr_format=zarr_format) == base64.b64encode(data).decode("ascii") + + +# note the order of parameters relative to the order of the parametrized variable. +@pytest.mark.parametrize(("json_expected", "float_data"), json_float_v2_roundtrip_cases) +def test_complex_to_json_v2( + float_data: float | np.floating[Any], json_expected: JSONFloatV2 +) -> None: + """ + Test that complex numbers are correctly converted to JSON in v2 format. + + This use the same test input as the float tests, but the conversion is tested + for complex numbers with real and imaginary parts equal to the float + values provided in the test cases. + """ + cplx = complex(float_data, float_data) + cplx_npy = np.complex128(cplx) + assert complex_float_to_json_v2(cplx) == (json_expected, json_expected) + assert complex_float_to_json_v2(cplx_npy) == (json_expected, json_expected) + + +# note the order of parameters relative to the order of the parametrized variable. +@pytest.mark.parametrize(("json_expected", "float_data"), json_float_v3_cases) +def test_complex_to_json_v3( + float_data: float | np.floating[Any], json_expected: JSONFloatV2 +) -> None: + """ + Test that complex numbers are correctly converted to JSON in v3 format. + + This use the same test input as the float tests, but the conversion is tested + for complex numbers with real and imaginary parts equal to the float + values provided in the test cases. + """ + cplx = complex(float_data, float_data) + cplx_npy = np.complex128(cplx) + assert complex_float_to_json_v3(cplx) == (json_expected, json_expected) + assert complex_float_to_json_v3(cplx_npy) == (json_expected, json_expected) + + +@pytest.mark.parametrize(("json_expected", "float_data"), json_float_v3_cases) +def test_complex_float_to_json( + float_data: float | np.floating[Any], json_expected: JSONFloatV2, zarr_format: ZarrFormat +) -> None: + """ + Test that complex numbers are correctly converted to JSON in v2 or v3 formats, depending + on the ``zarr_format`` keyword argument. + + This use the same test input as the float tests, but the conversion is tested + for complex numbers with real and imaginary parts equal to the float + values provided in the test cases. + """ + + cplx = complex(float_data, float_data) + cplx_npy = np.complex128(cplx) + if zarr_format == 2: + assert complex_float_to_json_v2(cplx) == (json_expected, json_expected) + assert complex_float_to_json_v2(cplx_npy) == ( + json_expected, + json_expected, + ) + elif zarr_format == 3: + assert complex_float_to_json_v3(cplx) == (json_expected, json_expected) + assert complex_float_to_json_v3(cplx_npy) == ( + json_expected, + json_expected, + ) + else: + raise ValueError("zarr_format must be 2 or 3") # pragma: no cover + + +check_json_float_cases = get_args(SpecialFloatStrings) + (1.0, 2) + + +@pytest.mark.parametrize("data", check_json_float_cases) +def test_check_json_float_v2_valid(data: JSONFloatV2 | int) -> None: + assert check_json_float_v2(data) + + +def test_check_json_float_v2_invalid() -> None: + assert not check_json_float_v2("invalid") + + +@pytest.mark.parametrize("data", check_json_float_cases) +def test_check_json_float_v3_valid(data: JSONFloatV2 | int) -> None: + assert check_json_float_v3(data) + + +def test_check_json_float_v3_invalid() -> None: + assert not check_json_float_v3("invalid") + + +check_json_complex_float_true_cases: tuple[list[JSONFloatV2], ...] = ( + [0.0, 1.0], + [0.0, 1.0], + [-1.0, "NaN"], + ["Infinity", 1.0], + ["Infinity", "NaN"], +) + +check_json_complex_float_false_cases: tuple[object, ...] = ( + 0.0, + "foo", + [0.0], + [1.0, 2.0, 3.0], + [1.0, "_infinity_"], + {"hello": 1.0}, +) + + +@pytest.mark.parametrize("data", check_json_complex_float_true_cases) +def test_check_json_complex_float_v2_true(data: JSON) -> None: + assert check_json_complex_float_v2(data) + + +@pytest.mark.parametrize("data", check_json_complex_float_false_cases) +def test_check_json_complex_float_v2_false(data: JSON) -> None: + assert not check_json_complex_float_v2(data) + + +@pytest.mark.parametrize("data", check_json_complex_float_true_cases) +def test_check_json_complex_float_v3_true(data: JSON) -> None: + assert check_json_complex_float_v3(data) + + +@pytest.mark.parametrize("data", check_json_complex_float_false_cases) +def test_check_json_complex_float_v3_false(data: JSON) -> None: + assert not check_json_complex_float_v3(data) + + +@pytest.mark.parametrize("data", check_json_complex_float_true_cases) +def test_check_json_complex_float_true(data: JSON, zarr_format: ZarrFormat) -> None: + if zarr_format == 2: + assert check_json_complex_float_v2(data) + elif zarr_format == 3: + assert check_json_complex_float_v3(data) + else: + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + +@pytest.mark.parametrize("data", check_json_complex_float_false_cases) +def test_check_json_complex_float_false(data: JSON, zarr_format: ZarrFormat) -> None: + if zarr_format == 2: + assert not check_json_complex_float_v2(data) + elif zarr_format == 3: + assert not check_json_complex_float_v3(data) + else: + raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover + + +def test_check_json_int() -> None: + assert check_json_int(0) + assert not check_json_int(1.0) + + +def test_check_json_intish_float() -> None: + assert check_json_intish_float(0.0) + assert check_json_intish_float(1.0) + assert not check_json_intish_float("0") + assert not check_json_intish_float(1.1) + + +def test_check_json_str() -> None: + assert check_json_str("0") + assert not check_json_str(1.0) + + +def test_check_json_bool() -> None: + assert check_json_bool(True) + assert check_json_bool(False) + assert not check_json_bool(1.0) + assert not check_json_bool("True") diff --git a/tests/test_dtype/test_npy/test_complex.py b/tests/test_dtype/test_npy/test_complex.py new file mode 100644 index 0000000000..b4ce42be58 --- /dev/null +++ b/tests/test_dtype/test_npy/test_complex.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import math + +import numpy as np + +from tests.test_dtype.test_wrapper import BaseTestZDType +from zarr.core.dtype.npy.complex import Complex64, Complex128 + + +class _BaseTestFloat(BaseTestZDType): + def scalar_equals(self, scalar1: object, scalar2: object) -> bool: + if np.isnan(scalar1) and np.isnan(scalar2): # type: ignore[call-overload] + return True + return super().scalar_equals(scalar1, scalar2) + + +class TestComplex64(_BaseTestFloat): + test_cls = Complex64 + valid_dtype = (np.dtype(">c8"), np.dtype("c8", "object_codec_id": None}, + {"name": "c16"), np.dtype("c16", "object_codec_id": None}, + {"name": " bool: + if np.isnan(scalar1) and np.isnan(scalar2): # type: ignore[call-overload] + return True + return super().scalar_equals(scalar1, scalar2) + + hex_string_params: tuple[tuple[str, float], ...] = () + + def test_hex_encoding(self, hex_string_params: tuple[str, float]) -> None: + """ + Test that hexadecimal strings can be read as NaN values + """ + hex_string, expected = hex_string_params + zdtype = self.test_cls() + observed = zdtype.from_json_scalar(hex_string, zarr_format=3) + assert self.scalar_equals(observed, expected) + + +class TestFloat16(_BaseTestFloat): + test_cls = Float16 + valid_dtype = (np.dtype(">f2"), np.dtype("f2", "object_codec_id": None}, + {"name": "f4"), np.dtype("f4", "object_codec_id": None}, + {"name": "f8"), np.dtype("f8", "object_codec_id": None}, + {"name": " None: + """Test the check_json_floatish_str function.""" + from zarr.core.dtype.npy.common import check_json_floatish_str + + # Test valid string floats + assert check_json_floatish_str("3.14") + assert check_json_floatish_str("0.0") + assert check_json_floatish_str("-2.5") + assert check_json_floatish_str("1.0") + + # Test invalid cases + assert not check_json_floatish_str("not_a_number") + assert not check_json_floatish_str("") + assert not check_json_floatish_str(3.14) # actual float, not string + assert not check_json_floatish_str(42) # int + assert not check_json_floatish_str(None) + + # Test that special cases still work via float() conversion + # (these will be handled by existing functions first in practice) + assert check_json_floatish_str("NaN") + assert check_json_floatish_str("Infinity") + assert check_json_floatish_str("-Infinity") + + +def test_string_float_from_json_scalar() -> None: + """Test that string representations of floats can be parsed by from_json_scalar.""" + # Test with Float32 + dtype_instance = Float32() + result = dtype_instance.from_json_scalar("3.14", zarr_format=3) + assert abs(result - np.float32(3.14)) < 1e-6 + assert isinstance(result, np.float32) + + # Test other cases + result = dtype_instance.from_json_scalar("0.0", zarr_format=3) + assert result == np.float32(0.0) + + result = dtype_instance.from_json_scalar("-2.5", zarr_format=3) + assert result == np.float32(-2.5) + + # Test that it works for v2 format too + result = dtype_instance.from_json_scalar("1.5", zarr_format=2) + assert result == np.float32(1.5) diff --git a/tests/test_dtype/test_npy/test_int.py b/tests/test_dtype/test_npy/test_int.py new file mode 100644 index 0000000000..9eab053080 --- /dev/null +++ b/tests/test_dtype/test_npy/test_int.py @@ -0,0 +1,331 @@ +from __future__ import annotations + +import numpy as np + +from tests.test_dtype.test_wrapper import BaseTestZDType +from zarr.core.dtype.npy.int import Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64 + + +class TestInt8(BaseTestZDType): + test_cls = Int8 + scalar_type = np.int8 + valid_dtype = (np.dtype(np.int8),) + invalid_dtype = ( + np.dtype(np.int16), + np.dtype(np.uint16), + np.dtype(np.float64), + ) + valid_json_v2 = ({"name": "|i1", "object_codec_id": None},) + valid_json_v3 = ("int8",) + invalid_json_v2 = ( + ">i1", + "int8", + "|f8", + ) + invalid_json_v3 = ( + "|i1", + "|f8", + {"name": "int8", "configuration": {"endianness": "little"}}, + ) + + scalar_v2_params = ((Int8(), 1), (Int8(), -1), (Int8(), 1.0)) + scalar_v3_params = ((Int8(), 1), (Int8(), -1)) + cast_value_params = ( + (Int8(), 1, np.int8(1)), + (Int8(), -1, np.int8(-1)), + ) + invalid_scalar_params = ((Int8(), {"set!"}), (Int8(), ("tuple",))) + item_size_params = (Int8(),) + + +class TestInt16(BaseTestZDType): + test_cls = Int16 + scalar_type = np.int16 + valid_dtype = (np.dtype(">i2"), np.dtype("i2", "object_codec_id": None}, + {"name": "i4"), np.dtype("i4", "object_codec_id": None}, + {"name": "i8"), np.dtype("i8", "object_codec_id": None}, + {"name": "u2"), np.dtype("u2", "object_codec_id": None}, + {"name": "u4"), np.dtype("u4", "object_codec_id": None}, + {"name": "u8"), np.dtype("u8", "object_codec_id": None}, + {"name": " None: + """Test the check_json_intish_str function.""" + from zarr.core.dtype.npy.common import check_json_intish_str + + # Test valid string integers + assert check_json_intish_str("0") + assert check_json_intish_str("42") + assert check_json_intish_str("-5") + assert check_json_intish_str("123") + + # Test invalid cases + assert not check_json_intish_str("3.14") + assert not check_json_intish_str("not_a_number") + assert not check_json_intish_str("") + assert not check_json_intish_str(42) # actual int, not string + assert not check_json_intish_str(3.14) # float + assert not check_json_intish_str(None) + + +def test_string_integer_from_json_scalar() -> None: + """Test that string representations of integers can be parsed by from_json_scalar.""" + # Test the specific reproducer case + dtype_instance = Int32() + result = dtype_instance.from_json_scalar("0", zarr_format=3) + assert result == np.int32(0) + assert isinstance(result, np.int32) + + # Test other cases + result = dtype_instance.from_json_scalar("42", zarr_format=3) + assert result == np.int32(42) + + result = dtype_instance.from_json_scalar("-5", zarr_format=3) + assert result == np.int32(-5) + + # Test that it works for v2 format too + result = dtype_instance.from_json_scalar("123", zarr_format=2) + assert result == np.int32(123) diff --git a/tests/test_dtype/test_npy/test_string.py b/tests/test_dtype/test_npy/test_string.py new file mode 100644 index 0000000000..c3b292e5fc --- /dev/null +++ b/tests/test_dtype/test_npy/test_string.py @@ -0,0 +1,97 @@ +from __future__ import annotations + +import numpy as np +import pytest + +from tests.test_dtype.test_wrapper import BaseTestZDType +from zarr.core.dtype import FixedLengthUTF32 +from zarr.core.dtype.npy.string import VariableLengthUTF8 + + +class TestVariableLengthString(BaseTestZDType): + test_cls = VariableLengthUTF8 # type: ignore[assignment] + valid_dtype = (np.dtypes.StringDType(),) # type: ignore[assignment] + invalid_dtype = ( + np.dtype(np.int8), + np.dtype(np.float64), + np.dtype("|S10"), + ) + valid_json_v2 = ({"name": "|O", "object_codec_id": "vlen-utf8"},) + valid_json_v3 = ("string",) + invalid_json_v2 = ( + "|S10", + "|f8", + "invalid", + ) + invalid_json_v3 = ( + {"name": "variable_length_utf8", "configuration": {"invalid_key": "value"}}, + {"name": "invalid_name"}, + ) + + scalar_v2_params = ((VariableLengthUTF8(), ""), (VariableLengthUTF8(), "hi")) + scalar_v3_params = ( + (VariableLengthUTF8(), ""), + (VariableLengthUTF8(), "hi"), + ) + + cast_value_params = ( + (VariableLengthUTF8(), "", np.str_("")), + (VariableLengthUTF8(), "hi", np.str_("hi")), + ) + # anything can become a string + invalid_scalar_params = (None,) + item_size_params = (VariableLengthUTF8(),) + + +class TestFixedLengthUTF32(BaseTestZDType): + test_cls = FixedLengthUTF32 + valid_dtype = (np.dtype(">U10"), np.dtype("U10", "object_codec_id": None}, + {"name": " None: + """ + Test that it's impossible to create a data type that has no length + """ + length = 0 + msg = f"length must be >= 1, got {length}." + with pytest.raises(ValueError, match=msg): + FixedLengthUTF32(length=length) diff --git a/tests/test_dtype/test_npy/test_structured.py b/tests/test_dtype/test_npy/test_structured.py new file mode 100644 index 0000000000..554c3b4e41 --- /dev/null +++ b/tests/test_dtype/test_npy/test_structured.py @@ -0,0 +1,262 @@ +from __future__ import annotations + +from typing import Any + +import numpy as np +import pytest + +from tests.test_dtype.test_wrapper import BaseTestZDType +from zarr.core.dtype import ( + Float16, + Float64, + Int32, + Int64, + Struct, + Structured, + UInt8, +) + + +class TestStruct(BaseTestZDType): + """Test the canonical 'struct' dtype format.""" + + test_cls = Struct + valid_dtype = ( + np.dtype([("field1", np.int32), ("field2", np.float64)]), + np.dtype([("field1", np.int64), ("field2", np.int32)]), + ) + invalid_dtype = ( + np.dtype(np.int8), + np.dtype(np.float64), + np.dtype("|S10"), + ) + valid_json_v2 = ( + {"name": [["field1", ">i4"], ["field2", ">f8"]], "object_codec_id": None}, + {"name": [["field1", ">i8"], ["field2", ">i4"]], "object_codec_id": None}, + ) + valid_json_v3 = ( + { + "name": "struct", + "configuration": { + "fields": [ + {"name": "field1", "data_type": "int32"}, + {"name": "field2", "data_type": "float64"}, + ] + }, + }, + { + "name": "struct", + "configuration": { + "fields": [ + { + "name": "field1", + "data_type": { + "name": "numpy.datetime64", + "configuration": {"unit": "s", "scale_factor": 1}, + }, + }, + { + "name": "field2", + "data_type": { + "name": "fixed_length_utf32", + "configuration": {"length_bytes": 32}, + }, + }, + ] + }, + }, + ) + invalid_json_v2 = ( + [("field1", "|i1"), ("field2", "|f8")], + [("field1", "|S10"), ("field2", "|f8")], + ) + invalid_json_v3 = ( + { + "name": "struct", + "configuration": { + "fields": [ + ("field1", {"name": "int32", "configuration": {"endianness": "invalid"}}), + ("field2", {"name": "float64", "configuration": {"endianness": "big"}}), + ] + }, + }, + {"name": "invalid_name"}, + ) + + scalar_v2_params = ( + (Struct(fields=(("field1", Int32()), ("field2", Float64()))), "AQAAAAAAAAAAAPA/"), + (Struct(fields=(("field1", Float16()), ("field2", Int32()))), "AQAAAAAA"), + ) + scalar_v3_params = ( + ( + Struct(fields=(("field1", Int32()), ("field2", Float64()))), + {"field1": 1, "field2": 1.0}, + ), + (Struct(fields=(("field1", Int64()), ("field2", Int32()))), {"field1": 1, "field2": 1}), + ) + + cast_value_params = ( + ( + Struct(fields=(("field1", Int32()), ("field2", Float64()))), + (1, 2.0), + np.array((1, 2.0), dtype=[("field1", np.int32), ("field2", np.float64)]), + ), + ( + Struct(fields=(("field1", Int64()), ("field2", Int32()))), + (3, 4.5), + np.array((3, 4.5), dtype=[("field1", np.int64), ("field2", np.int32)]), + ), + ) + + item_size_params = ( + Struct(fields=(("field1", Int32()), ("field2", Float64()))), + Struct(fields=(("field1", Int64()), ("field2", Int32()))), + ) + + invalid_scalar_params = ( + (Struct(fields=(("field1", Int32()), ("field2", Float64()))), "i am a string"), + (Struct(fields=(("field1", Int32()), ("field2", Float64()))), {"type": "dict"}), + ) + + def scalar_equals(self, scalar1: Any, scalar2: Any) -> bool: + if hasattr(scalar1, "shape") and hasattr(scalar2, "shape"): + return np.array_equal(scalar1, scalar2) + return super().scalar_equals(scalar1, scalar2) + + +class TestStructured: + """Test the legacy 'structured' dtype format.""" + + def test_invalid_size(self) -> None: + """Test that it's impossible to create a data type that has no fields.""" + fields = () + msg = f"must have at least one field. Got {fields!r}" + with pytest.raises(ValueError, match=msg): + Structured(fields=fields) + + def test_structured_legacy_name_with_tuple_format(self) -> None: + """Test that the legacy 'structured' name with tuple field format is accepted.""" + json_v3 = { + "name": "structured", + "configuration": { + "fields": [ + ["field1", "int32"], + ["field2", "float64"], + ] + }, + } + dtype = Structured.from_json(json_v3, zarr_format=3) + assert dtype.fields[0][0] == "field1" + assert dtype.fields[1][0] == "field2" + + @pytest.mark.filterwarnings("ignore::zarr.errors.UnstableSpecificationWarning") + def test_structured_writes_tuple_format(self) -> None: + """Test that 'structured' writes the tuple field format.""" + dtype = Structured(fields=(("field1", Int32()), ("field2", Float64()))) + json_v3 = dtype.to_json(zarr_format=3) + assert json_v3["name"] == "structured" + assert json_v3["configuration"]["fields"][0] == ["field1", "int32"] + + +def test_invalid_size() -> None: + """Test that it's impossible to create a data type that has no fields.""" + fields = () + msg = f"must have at least one field. Got {fields!r}" + with pytest.raises(ValueError, match=msg): + Struct(fields=fields) + + +@pytest.mark.filterwarnings("ignore::zarr.errors.UnstableSpecificationWarning") +def test_struct_name_is_primary() -> None: + """Test that 'struct' is the primary name written to JSON.""" + dtype = Struct(fields=(("field1", Int32()), ("field2", Float64()))) + json_v3 = dtype.to_json(zarr_format=3) + assert json_v3["name"] == "struct" + + +def test_struct_reads_legacy_tuple_format() -> None: + """Test that 'struct' dtype reads the legacy tuple field format.""" + json_v3 = { + "name": "struct", + "configuration": { + "fields": [ + ["field1", "int32"], + ["field2", "float64"], + ] + }, + } + dtype = Struct.from_json(json_v3, zarr_format=3) + assert isinstance(dtype, Struct) + assert dtype.fields[0][0] == "field1" + assert dtype.fields[1][0] == "field2" + + +def test_struct_reads_canonical_object_format() -> None: + """Test that 'struct' dtype reads the new object field format.""" + json_v3 = { + "name": "struct", + "configuration": { + "fields": [ + {"name": "field1", "data_type": "int32"}, + {"name": "field2", "data_type": "float64"}, + ] + }, + } + dtype = Struct.from_json(json_v3, zarr_format=3) + assert isinstance(dtype, Struct) + assert dtype.fields[0][0] == "field1" + assert dtype.fields[1][0] == "field2" + + +def test_fill_value_dict_form() -> None: + """Test that dict form fill values are properly parsed.""" + dtype = Struct(fields=(("x", Int32()), ("y", Float64()))) + fill_value = dtype.from_json_scalar({"x": 42, "y": 3.14}, zarr_format=3) + assert fill_value["x"] == 42 + assert fill_value["y"] == 3.14 + + +def test_fill_value_dict_form_missing_fields() -> None: + """Test that missing fields in dict form fill values use defaults.""" + dtype = Struct(fields=(("x", Int32()), ("y", Float64()))) + fill_value = dtype.from_json_scalar({"x": 42}, zarr_format=3) + assert fill_value["x"] == 42 + assert fill_value["y"] == 0.0 + + +def test_fill_value_legacy_base64() -> None: + """Test that legacy base64-encoded fill values are still readable.""" + dtype = Struct(fields=(("field1", Int32()), ("field2", Float64()))) + fill_value = dtype.from_json_scalar("AQAAAAAAAAAAAPA/", zarr_format=3) + assert fill_value["field1"] == 1 + assert fill_value["field2"] == 1.0 + + +def test_fill_value_to_json_dict_form() -> None: + """Test that fill values are serialized as dict form.""" + dtype = Struct(fields=(("x", Int32()), ("y", Float64()))) + scalar = np.array((42, 3.14), dtype=[("x", np.int32), ("y", np.float64)])[()] + json_val = dtype.to_json_scalar(scalar, zarr_format=3) + assert isinstance(json_val, dict) + assert json_val["x"] == 42 + assert json_val["y"] == 3.14 + + +def test_has_multi_byte_fields_true() -> None: + """Test that has_multi_byte_fields returns True for dtypes with multi-byte fields.""" + dtype = Struct(fields=(("field1", Int32()), ("field2", Float64()))) + assert dtype.has_multi_byte_fields() is True + + +def test_has_multi_byte_fields_false() -> None: + """Test that has_multi_byte_fields returns False for dtypes with only single-byte fields.""" + dtype = Struct(fields=(("field1", UInt8()), ("field2", UInt8()))) + assert dtype.has_multi_byte_fields() is False + + +def test_struct_from_native_dtype() -> None: + """Test that Struct can be created from native numpy dtype.""" + dtype = np.dtype([("field1", np.int32), ("field2", np.float64)]) + struct = Struct.from_native_dtype(dtype) + assert struct.fields[0][0] == "field1" + assert struct.fields[1][0] == "field2" diff --git a/tests/test_dtype/test_npy/test_time.py b/tests/test_dtype/test_npy/test_time.py new file mode 100644 index 0000000000..67ba3bd130 --- /dev/null +++ b/tests/test_dtype/test_npy/test_time.py @@ -0,0 +1,177 @@ +from __future__ import annotations + +import re +from typing import get_args + +import numpy as np +import pytest + +from tests.test_dtype.test_wrapper import BaseTestZDType +from zarr.core.dtype.npy.common import DateTimeUnit +from zarr.core.dtype.npy.time import DateTime64, TimeDelta64, datetime_from_int + + +class _TestTimeBase(BaseTestZDType): + def json_scalar_equals(self, scalar1: object, scalar2: object) -> bool: + # This method gets overridden here to support the equivalency between NaT and + # -9223372036854775808 fill values + nat_scalars = (-9223372036854775808, "NaT") + if scalar1 in nat_scalars and scalar2 in nat_scalars: + return True + return scalar1 == scalar2 + + def scalar_equals(self, scalar1: object, scalar2: object) -> bool: + if np.isnan(scalar1) and np.isnan(scalar2): # type: ignore[call-overload] + return True + return super().scalar_equals(scalar1, scalar2) + + +class TestDateTime64(_TestTimeBase): + test_cls = DateTime64 + valid_dtype = (np.dtype("datetime64[10ns]"), np.dtype("datetime64[us]"), np.dtype("datetime64")) + invalid_dtype = ( + np.dtype(np.int8), + np.dtype(np.float64), + np.dtype("timedelta64[ns]"), + ) + valid_json_v2 = ( + {"name": ">M8", "object_codec_id": None}, + {"name": ">M8[s]", "object_codec_id": None}, + {"name": "m8", "object_codec_id": None}, + {"name": ">m8[s]", "object_codec_id": None}, + {"name": " None: + """ + Test that an invalid unit raises a ValueError. + """ + unit = "invalid" + msg = f"unit must be one of ('Y', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us', 'ΞΌs', 'ns', 'ps', 'fs', 'as', 'generic'), got {unit!r}." + with pytest.raises(ValueError, match=re.escape(msg)): + DateTime64(unit=unit) # type: ignore[arg-type] + with pytest.raises(ValueError, match=re.escape(msg)): + TimeDelta64(unit=unit) # type: ignore[arg-type] + + +def test_time_scale_factor_too_low() -> None: + """ + Test that an invalid unit raises a ValueError. + """ + scale_factor = 0 + msg = f"scale_factor must be > 0, got {scale_factor}." + with pytest.raises(ValueError, match=msg): + DateTime64(scale_factor=scale_factor) + with pytest.raises(ValueError, match=msg): + TimeDelta64(scale_factor=scale_factor) + + +def test_default_is_NaT() -> None: + np.testing.assert_equal( + TimeDelta64(unit="ns", scale_factor=1).default_scalar(), np.timedelta64("NaT", "ns") + ) + + +def test_time_scale_factor_too_high() -> None: + """ + Test that an invalid unit raises a ValueError. + """ + scale_factor = 2**31 + msg = f"scale_factor must be < 2147483648, got {scale_factor}." + with pytest.raises(ValueError, match=msg): + DateTime64(scale_factor=scale_factor) + with pytest.raises(ValueError, match=msg): + TimeDelta64(scale_factor=scale_factor) + + +@pytest.mark.parametrize("unit", get_args(DateTimeUnit)) +@pytest.mark.parametrize("scale_factor", [1, 10]) +@pytest.mark.parametrize("value", [0, 1, 10]) +def test_datetime_from_int(unit: DateTimeUnit, scale_factor: int, value: int) -> None: + """ + Test datetime_from_int. + """ + expected = np.int64(value).view(f"datetime64[{scale_factor}{unit}]") + assert datetime_from_int(value, unit=unit, scale_factor=scale_factor) == expected diff --git a/tests/test_dtype/test_wrapper.py b/tests/test_dtype/test_wrapper.py new file mode 100644 index 0000000000..cc365e86d4 --- /dev/null +++ b/tests/test_dtype/test_wrapper.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +import re +from typing import TYPE_CHECKING, Any, ClassVar + +import pytest + +from zarr.core.dtype.common import DTypeSpec_V2, DTypeSpec_V3, HasItemSize + +if TYPE_CHECKING: + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType + + +""" +class _TestZDTypeSchema: + # subclasses define the URL for the schema, if available + schema_url: ClassVar[str] = "" + + @pytest.fixture(scope="class") + def get_schema(self) -> object: + response = requests.get(self.schema_url) + response.raise_for_status() + return json_schema.loads(response.text) + + def test_schema(self, schema: json_schema.Schema) -> None: + assert schema.is_valid(self.test_cls.to_json(zarr_format=2)) +""" + + +class BaseTestZDType: + """ + A base class for testing ZDType subclasses. This class works in conjunction with the custom + pytest collection function ``pytest_generate_tests`` defined in conftest.py, which applies the + following procedure when generating tests: + + At test generation time, for each test fixture referenced by a method on this class + pytest will look for an attribute with the same name as that fixture. Pytest will assume that + this class attribute is a tuple of values to be used for generating a parametrized test fixture. + + This means that child classes can, by using different values for these class attributes, have + customized test parametrization. + + Attributes + ---------- + test_cls : type[ZDType[TBaseDType, TBaseScalar]] + The ZDType subclass being tested. + scalar_type : ClassVar[type[TBaseScalar]] + The expected scalar type for the ZDType. + valid_dtype : ClassVar[tuple[TBaseDType, ...]] + A tuple of valid numpy dtypes for the ZDType. + invalid_dtype : ClassVar[tuple[TBaseDType, ...]] + A tuple of invalid numpy dtypes for the ZDType. + valid_json_v2 : ClassVar[tuple[str | dict[str, object] | list[object], ...]] + A tuple of valid JSON representations for Zarr format version 2. + invalid_json_v2 : ClassVar[tuple[str | dict[str, object] | list[object], ...]] + A tuple of invalid JSON representations for Zarr format version 2. + valid_json_v3 : ClassVar[tuple[str | dict[str, object], ...]] + A tuple of valid JSON representations for Zarr format version 3. + invalid_json_v3 : ClassVar[tuple[str | dict[str, object], ...]] + A tuple of invalid JSON representations for Zarr format version 3. + cast_value_params : ClassVar[tuple[tuple[Any, Any, Any], ...]] + A tuple of (dtype, value, expected) tuples for testing ZDType.cast_value. + scalar_v2_params : ClassVar[tuple[Any, ...]] + A tuple of (dtype, scalar json) tuples for testing + ZDType.from_json_scalar / ZDType.to_json_scalar for zarr v2 + scalar_v3_params : ClassVar[tuple[Any, ...]] + A tuple of (dtype, scalar json) tuples for testing + ZDType.from_json_scalar / ZDType.to_json_scalar for zarr v3 + invalid_scalar_params : ClassVar[tuple[Any, ...]] + A tuple of (dtype, value) tuples, where each value is expected to fail ZDType.cast_value. + item_size_params : ClassVar[tuple[Any, ...]] + A tuple of (dtype, expected) tuples for testing ZDType.item_size + """ + + test_cls: type[ZDType[TBaseDType, TBaseScalar]] + scalar_type: ClassVar[type[TBaseScalar]] + valid_dtype: ClassVar[tuple[TBaseDType, ...]] = () + invalid_dtype: ClassVar[tuple[TBaseDType, ...]] = () + + valid_json_v2: ClassVar[tuple[DTypeSpec_V2, ...]] = () + invalid_json_v2: ClassVar[tuple[str | dict[str, object] | list[object], ...]] = () + + valid_json_v3: ClassVar[tuple[DTypeSpec_V3, ...]] = () + invalid_json_v3: ClassVar[tuple[str | dict[str, object], ...]] = () + + # for testing scalar round-trip serialization, we need a tuple of (data type json, scalar json) + # pairs. the first element of the pair is used to create a dtype instance, and the second + # element is the json serialization of the scalar that we want to round-trip. + + scalar_v2_params: ClassVar[tuple[tuple[ZDType[Any, Any], Any], ...]] = () + scalar_v3_params: ClassVar[tuple[tuple[Any, Any], ...]] = () + cast_value_params: ClassVar[tuple[tuple[ZDType[Any, Any], Any, Any], ...]] = () + # Some data types, like bool and string, can consume any python object as a scalar. + # So we allow passing None in to this test to indicate that it should be skipped. + invalid_scalar_params: ClassVar[tuple[tuple[ZDType[Any, Any], Any], ...] | tuple[None]] = () + item_size_params: ClassVar[tuple[ZDType[Any, Any], ...]] = () + + def json_scalar_equals(self, scalar1: object, scalar2: object) -> bool: + # An equality check for json-encoded scalars. This defaults to regular equality, + # but some classes may need to override this for special cases + return scalar1 == scalar2 + + def scalar_equals(self, scalar1: object, scalar2: object) -> bool: + # An equality check for scalars. This defaults to regular equality, + # but some classes may need to override this for special cases + return scalar1 == scalar2 + + def test_check_dtype_valid(self, valid_dtype: TBaseDType) -> None: + assert self.test_cls._check_native_dtype(valid_dtype) + + def test_check_dtype_invalid(self, invalid_dtype: object) -> None: + assert not self.test_cls._check_native_dtype(invalid_dtype) # type: ignore[arg-type] + + def test_from_dtype_roundtrip(self, valid_dtype: Any) -> None: + zdtype = self.test_cls.from_native_dtype(valid_dtype) + assert zdtype.to_native_dtype() == valid_dtype + + def test_from_json_roundtrip_v2(self, valid_json_v2: DTypeSpec_V2) -> None: + zdtype = self.test_cls.from_json(valid_json_v2, zarr_format=2) + assert zdtype.to_json(zarr_format=2) == valid_json_v2 + + @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") + def test_from_json_roundtrip_v3(self, valid_json_v3: DTypeSpec_V3) -> None: + zdtype = self.test_cls.from_json(valid_json_v3, zarr_format=3) + assert zdtype.to_json(zarr_format=3) == valid_json_v3 + + def test_scalar_roundtrip_v2(self, scalar_v2_params: tuple[ZDType[Any, Any], Any]) -> None: + zdtype, scalar_json = scalar_v2_params + scalar = zdtype.from_json_scalar(scalar_json, zarr_format=2) + assert self.json_scalar_equals(scalar_json, zdtype.to_json_scalar(scalar, zarr_format=2)) + + def test_scalar_roundtrip_v3(self, scalar_v3_params: tuple[ZDType[Any, Any], Any]) -> None: + zdtype, scalar_json = scalar_v3_params + scalar = zdtype.from_json_scalar(scalar_json, zarr_format=3) + assert self.json_scalar_equals(scalar_json, zdtype.to_json_scalar(scalar, zarr_format=3)) + + def test_cast_value(self, cast_value_params: tuple[ZDType[Any, Any], Any, Any]) -> None: + zdtype, value, expected = cast_value_params + observed = zdtype.cast_scalar(value) + assert self.scalar_equals(expected, observed) + # check that casting is idempotent + assert self.scalar_equals(zdtype.cast_scalar(observed), observed) + + def test_invalid_scalar( + self, invalid_scalar_params: tuple[ZDType[Any, Any], Any] | None + ) -> None: + if invalid_scalar_params is None: + pytest.skip(f"No test data provided for {self}.{__name__}") + zdtype, data = invalid_scalar_params + msg = ( + f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the " + f"data type {zdtype}." + ) + with pytest.raises(TypeError, match=re.escape(msg)): + zdtype.cast_scalar(data) + + def test_item_size(self, item_size_params: ZDType[Any, Any]) -> None: + """ + Test that the item_size attribute matches the numpy dtype itemsize attribute, for dtypes + with a fixed scalar size. + """ + if isinstance(item_size_params, HasItemSize): + assert item_size_params.item_size == item_size_params.to_native_dtype().itemsize + else: + pytest.skip(f"Data type {item_size_params} does not implement HasItemSize") diff --git a/tests/test_dtype_registry.py b/tests/test_dtype_registry.py new file mode 100644 index 0000000000..40239c1132 --- /dev/null +++ b/tests/test_dtype_registry.py @@ -0,0 +1,217 @@ +from __future__ import annotations + +import re +from typing import TYPE_CHECKING, Any, Literal, get_args + +import numpy as np +import pytest + +from tests.conftest import skip_object_dtype +from zarr.core.dtype import ( + AnyDType, + DataTypeRegistry, + TBaseDType, + TBaseScalar, + get_data_type_from_json, +) +from zarr.core.dtype.common import unpack_dtype_json +from zarr.dtype import ( # type: ignore[attr-defined] + Bool, + FixedLengthUTF32, + VariableLengthUTF8, + ZDType, + data_type_registry, + parse_data_type, + parse_dtype, +) + +if TYPE_CHECKING: + from zarr.core.common import ZarrFormat + +from .test_dtype.conftest import zdtype_examples + + +@pytest.fixture +def data_type_registry_fixture() -> DataTypeRegistry: + return DataTypeRegistry() + + +class TestRegistry: + @staticmethod + def test_register(data_type_registry_fixture: DataTypeRegistry) -> None: + """ + Test that registering a dtype in a data type registry works. + """ + data_type_registry_fixture.register(Bool._zarr_v3_name, Bool) + assert data_type_registry_fixture.get(Bool._zarr_v3_name) == Bool + assert isinstance(data_type_registry_fixture.match_dtype(np.dtype("bool")), Bool) + + @staticmethod + def test_override(data_type_registry_fixture: DataTypeRegistry) -> None: + """ + Test that registering a new dtype with the same name works (overriding the previous one). + """ + data_type_registry_fixture.register(Bool._zarr_v3_name, Bool) + + class NewBool(Bool): + def default_scalar(self) -> np.bool_: + return np.True_ + + data_type_registry_fixture.register(NewBool._zarr_v3_name, NewBool) + assert isinstance(data_type_registry_fixture.match_dtype(np.dtype("bool")), NewBool) + + @staticmethod + @pytest.mark.parametrize( + ("wrapper_cls", "dtype_str"), [(Bool, "bool"), (FixedLengthUTF32, "|U4")] + ) + def test_match_dtype( + data_type_registry_fixture: DataTypeRegistry, + wrapper_cls: type[ZDType[TBaseDType, TBaseScalar]], + dtype_str: str, + ) -> None: + """ + Test that match_dtype resolves a numpy dtype into an instance of the correspond wrapper for that dtype. + """ + data_type_registry_fixture.register(wrapper_cls._zarr_v3_name, wrapper_cls) + assert isinstance(data_type_registry_fixture.match_dtype(np.dtype(dtype_str)), wrapper_cls) + + @staticmethod + def test_match_dtype_string_na_object_error( + data_type_registry_fixture: DataTypeRegistry, + ) -> None: + data_type_registry_fixture.register(VariableLengthUTF8._zarr_v3_name, VariableLengthUTF8) # type: ignore[arg-type] + dtype: np.dtype[Any] = np.dtypes.StringDType(na_object=None) + with pytest.raises(ValueError, match=r"Zarr data type resolution from StringDType.*failed"): + data_type_registry_fixture.match_dtype(dtype) + + @staticmethod + def test_unregistered_dtype(data_type_registry_fixture: DataTypeRegistry) -> None: + """ + Test that match_dtype raises an error if the dtype is not registered. + """ + outside_dtype_name = "int8" + outside_dtype = np.dtype(outside_dtype_name) + msg = f"No Zarr data type found that matches dtype '{outside_dtype!r}'" + with pytest.raises(ValueError, match=re.escape(msg)): + data_type_registry_fixture.match_dtype(outside_dtype) + + with pytest.raises(KeyError): + data_type_registry_fixture.get(outside_dtype_name) + + @staticmethod + @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") + @pytest.mark.parametrize("zdtype", zdtype_examples) + def test_registered_dtypes_match_dtype(zdtype: ZDType[TBaseDType, TBaseScalar]) -> None: + """ + Test that the registered dtypes can be retrieved from the registry. + """ + skip_object_dtype(zdtype) + assert data_type_registry.match_dtype(zdtype.to_native_dtype()) == zdtype + + @staticmethod + @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") + @pytest.mark.parametrize("zdtype", zdtype_examples) + def test_registered_dtypes_match_json( + zdtype: ZDType[TBaseDType, TBaseScalar], zarr_format: ZarrFormat + ) -> None: + assert ( + data_type_registry.match_json( + zdtype.to_json(zarr_format=zarr_format), zarr_format=zarr_format + ) + == zdtype + ) + + @staticmethod + @pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") + @pytest.mark.parametrize("zdtype", zdtype_examples) + def test_match_dtype_unique( + zdtype: ZDType[Any, Any], + data_type_registry_fixture: DataTypeRegistry, + zarr_format: ZarrFormat, + ) -> None: + """ + Test that the match_dtype method uniquely specifies a registered data type. We create a local registry + that excludes the data type class being tested, and ensure that an instance of the wrapped data type + fails to match anything in the registry + """ + skip_object_dtype(zdtype) + for _cls in get_args(AnyDType): + if _cls is not type(zdtype): + data_type_registry_fixture.register(_cls._zarr_v3_name, _cls) + + dtype_instance = zdtype.to_native_dtype() + + msg = f"No Zarr data type found that matches dtype '{dtype_instance!r}'" + with pytest.raises(ValueError, match=re.escape(msg)): + data_type_registry_fixture.match_dtype(dtype_instance) + + instance_dict = zdtype.to_json(zarr_format=zarr_format) + msg = f"No Zarr data type found that matches {instance_dict!r}" + with pytest.raises(ValueError, match=re.escape(msg)): + data_type_registry_fixture.match_json(instance_dict, zarr_format=zarr_format) + + +@pytest.mark.usefixtures("set_path") +def test_entrypoint_dtype(zarr_format: ZarrFormat) -> None: + from package_with_entrypoint import TestDataType + + data_type_registry._lazy_load() + instance = TestDataType() + dtype_json = instance.to_json(zarr_format=zarr_format) + assert get_data_type_from_json(dtype_json, zarr_format=zarr_format) == instance + data_type_registry.unregister(TestDataType._zarr_v3_name) + + +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@pytest.mark.parametrize("data_type", zdtype_examples, ids=str) +@pytest.mark.parametrize("json_style", [(2, "internal"), (2, "metadata"), (3, None)], ids=str) +@pytest.mark.parametrize( + "dtype_parser_func", [parse_dtype, parse_data_type], ids=["parse_dtype", "parse_data_type"] +) +def test_parse_data_type( + data_type: ZDType[Any, Any], + json_style: tuple[ZarrFormat, Literal["internal", "metadata"] | None], + dtype_parser_func: Any, +) -> None: + """ + Test the parsing of data types into ZDType instances. + + This function tests the ability of `dtype_parser_func` to correctly + interpret and parse data type specifications into `ZDType` instances + according to the specified Zarr format and JSON style. + + Parameters + ---------- + data_type : ZDType[Any, Any] + The data type to be tested for parsing. + json_style : tuple[ZarrFormat, None or Literal["internal", "metadata"]] + A tuple specifying the Zarr format version and the JSON style + for Zarr V2 2. For Zarr V2 there are 2 JSON styles: "internal", and + "metadata". The internal style takes the form {"name": , "object_codec_id": }, + while the metadata style is just . + dtype_parser_func : Any + The function to be tested for parsing the data type. This is necessary for compatibility + reasons, as we support multiple functions that perform the same data type parsing operation. + """ + zarr_format, style = json_style + dtype_spec: Any + + if zarr_format == 2: + dtype_spec = data_type.to_json(zarr_format=zarr_format) + if style == "internal": + pass + elif style == "metadata": + dtype_spec = unpack_dtype_json(dtype_spec) + else: + raise ValueError(f"Invalid zarr v2 json style: {style}") + else: + dtype_spec = data_type.to_json(zarr_format=zarr_format) + + if dtype_spec == "|O": + # The object data type on its own is ambiguous and should fail to resolve. + msg = "Zarr data type resolution from object failed." + with pytest.raises(ValueError, match=msg): + dtype_parser_func(dtype_spec, zarr_format=zarr_format) + else: + observed = dtype_parser_func(dtype_spec, zarr_format=zarr_format) + assert observed == data_type diff --git a/tests/test_errors.py b/tests/test_errors.py new file mode 100644 index 0000000000..17dbada9f4 --- /dev/null +++ b/tests/test_errors.py @@ -0,0 +1,101 @@ +"""Test errors""" + +import pytest + +from zarr.errors import ( + ArrayNotFoundError, + ContainsArrayAndGroupError, + ContainsArrayError, + ContainsGroupError, + DataTypeValidationError, + GroupNotFoundError, + MetadataValidationError, + NodeTypeValidationError, + ZarrDeprecationWarning, +) + + +def test_group_not_found_error() -> None: + """ + Test that calling GroupNotFoundError with multiple arguments returns a formatted string. + This is deprecated behavior. + """ + err = GroupNotFoundError("store", "path") + assert str(err) == "No group found in store 'store' at path 'path'" + + +def test_array_not_found_error() -> None: + """ + Test that calling ArrayNotFoundError with multiple arguments returns a formatted string. + This is deprecated behavior. + """ + err = ArrayNotFoundError("store", "path") + assert str(err) == "No array found in store 'store' at path 'path'" + + +def test_metadata_validation_error() -> None: + """ + Test that calling MetadataValidationError with multiple arguments returns a formatted string. + This is deprecated behavior. + """ + err = MetadataValidationError("a", "b", "c") + assert str(err) == "Invalid value for 'a'. Expected 'b'. Got 'c'." + + +def test_contains_group_error() -> None: + """ + Test that calling ContainsGroupError with multiple arguments returns a formatted string. + This is deprecated behavior. + """ + err = ContainsGroupError("store", "path") + assert str(err) == "A group exists in store 'store' at path 'path'." + + +def test_contains_array_error() -> None: + """ + Test that calling ContainsArrayError with multiple arguments returns a formatted string. + This is deprecated behavior. + """ + err = ContainsArrayError("store", "path") + assert str(err) == "An array exists in store 'store' at path 'path'." + + +def test_contains_array_and_group_error() -> None: + """ + Test that calling ContainsArrayAndGroupError with multiple arguments returns a formatted string. + This is deprecated behavior. + """ + err = ContainsArrayAndGroupError("store", "path") + assert str(err) == ( + "Array and group metadata documents (.zarray and .zgroup) were both found in store 'store' " + "at path 'path'. Only one of these files may be present in a given directory / prefix. " + "Remove the .zarray file, or the .zgroup file, or both." + ) + + +def test_node_type_validation_error() -> None: + """ + Test that calling NodeTypeValidationError with multiple arguments returns a formatted string. + This is deprecated behavior. + """ + err = NodeTypeValidationError("a", "b", "c") + assert str(err) == "Invalid value for 'a'. Expected 'b'. Got 'c'." + + +@pytest.mark.parametrize( + "module_name", + [ + "zarr.core.dtype.common", + "zarr.core.dtype", + "zarr.dtype", + ], +) +def test_data_type_validation_error_deprecated_import(module_name: str) -> None: + import importlib + + module = importlib.import_module(module_name) + + with pytest.warns(ZarrDeprecationWarning, match=f"{module_name}"): + cls = module.DataTypeValidationError + + assert cls is DataTypeValidationError diff --git a/tests/test_examples.py b/tests/test_examples.py new file mode 100644 index 0000000000..a6634e8cc6 --- /dev/null +++ b/tests/test_examples.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +import re +import subprocess +import sys +from pathlib import Path +from typing import Final + +import pytest +import tomlkit +from packaging.requirements import Requirement + +examples_dir = "examples" +script_paths = tuple(Path(examples_dir).rglob("*.py")) + +PEP_723_REGEX: Final = r"(?m)^# /// (?P[a-zA-Z0-9-]+)$\s(?P(^#(| .*)$\s)+)^# ///$" + +# This is the absolute path to the local Zarr installation. Moving this test to a different directory will break it. +ZARR_PROJECT_PATH = Path(".").absolute() + + +def set_dep(script: str, dependency: str) -> str: + """ + Set a dependency in a PEP-723 script header. + If the package is already in the list, it will be replaced. + If the package is not already in the list, it will be added. + + Source code modified from + https://packaging.python.org/en/latest/specifications/inline-script-metadata/#reference-implementation + """ + match = re.search(PEP_723_REGEX, script) + + if match is None: + raise ValueError(f"PEP-723 header not found in {script}") + + content = "".join( + line[2:] if line.startswith("# ") else line[1:] + for line in match.group("content").splitlines(keepends=True) + ) + + config = tomlkit.parse(content) + for idx, dep in enumerate(tuple(config["dependencies"])): + if Requirement(dep).name == Requirement(dependency).name: + config["dependencies"][idx] = dependency + + new_content = "".join( + f"# {line}" if line.strip() else f"#{line}" + for line in tomlkit.dumps(config).splitlines(keepends=True) + ) + + start, end = match.span("content") + return script[:start] + new_content + script[end:] + + +def resave_script(source_path: Path, dest_path: Path) -> None: + """ + Read a script from source_path and save it to dest_path after inserting the absolute path to the + local Zarr project directory in the PEP-723 header. + """ + source_text = source_path.read_text() + dest_text = set_dep(source_text, f"zarr @ file:///{ZARR_PROJECT_PATH}") + dest_path.write_text(dest_text) + + +def test_script_paths() -> None: + """ + Test that our test fixture is working properly and collecting script paths. + """ + assert len(script_paths) > 0 + + +@pytest.mark.skipif( + sys.platform == "win32", reason="This test fails for unknown reasons on Windows in CI." +) +@pytest.mark.parametrize("script_path", script_paths) +def test_scripts_can_run(script_path: Path, tmp_path: Path) -> None: + dest_path = tmp_path / script_path.name + # We resave the script after inserting the absolute path to the local Zarr project directory, + # and then test its behavior. + # This allows the example to be useful to users who don't have Zarr installed, but also testable. + resave_script(script_path, dest_path) + result = subprocess.run( + ["uv", "run", "--refresh", str(dest_path)], capture_output=True, text=True, check=False + ) + assert result.returncode == 0, ( + f"Script at {script_path} failed to run. Output: {result.stdout} Error: {result.stderr}" + ) diff --git a/tests/test_experimental/test_cache_store.py b/tests/test_experimental/test_cache_store.py new file mode 100644 index 0000000000..f688a6ca02 --- /dev/null +++ b/tests/test_experimental/test_cache_store.py @@ -0,0 +1,1075 @@ +""" +Tests for the dual-store cache implementation. +""" + +import asyncio +import time + +import pytest + +from zarr.abc.store import RangeByteRequest, Store, SuffixByteRequest +from zarr.core.buffer.core import default_buffer_prototype +from zarr.core.buffer.cpu import Buffer as CPUBuffer +from zarr.experimental.cache_store import CacheStore +from zarr.storage import MemoryStore + + +class TestCacheStore: + """Test the dual-store cache implementation.""" + + @pytest.fixture + def source_store(self) -> MemoryStore: + """Create a source store with some test data.""" + return MemoryStore() + + @pytest.fixture + def cache_store(self) -> MemoryStore: + """Create an empty cache store.""" + return MemoryStore() + + @pytest.fixture + def cached_store(self, source_store: Store, cache_store: Store) -> CacheStore: + """Create a cached store instance.""" + return CacheStore(source_store, cache_store=cache_store) + + async def test_with_read_only_round_trip(self) -> None: + """ + Ensure that CacheStore.with_read_only returns another CacheStore with + the requested read_only state, shares cache state, and does not change + the original store's read_only flag. + """ + source = MemoryStore() + cache = MemoryStore() + + # Start from a read-only underlying store + source_ro = source.with_read_only(read_only=True) + cached_ro = CacheStore(store=source_ro, cache_store=cache) + assert cached_ro.read_only + + buf = CPUBuffer.from_bytes(b"0123") + + # Cannot write through the read-only cache store + with pytest.raises( + ValueError, match="store was opened in read-only mode and does not support writing" + ): + await cached_ro.set("foo", buf) + + # Create a writable cache store from the read-only one + writer = cached_ro.with_read_only(read_only=False) + assert isinstance(writer, CacheStore) + assert not writer.read_only + + # Cache configuration and state are shared + assert writer._cache is cached_ro._cache + assert writer._state is cached_ro._state + assert writer._state.key_insert_times is cached_ro._state.key_insert_times + + # Writes via the writable cache store succeed and are cached + await writer.set("foo", buf) + out = await writer.get("foo", default_buffer_prototype()) + assert out is not None + assert out.to_bytes() == buf.to_bytes() + + # The original cache store remains read-only + assert cached_ro.read_only + with pytest.raises( + ValueError, match="store was opened in read-only mode and does not support writing" + ): + await cached_ro.set("bar", buf) + + # Creating a read-only copy from the writable cache store works and is enforced + reader = writer.with_read_only(read_only=True) + assert isinstance(reader, CacheStore) + assert reader.read_only + with pytest.raises( + ValueError, match="store was opened in read-only mode and does not support writing" + ): + await reader.set("baz", buf) + + async def test_basic_caching(self, cached_store: CacheStore, source_store: Store) -> None: + """Test basic cache functionality.""" + # Store some data + test_data = CPUBuffer.from_bytes(b"test data") + await cached_store.set("test_key", test_data) + + # Verify it's in both stores + assert await source_store.exists("test_key") + assert await cached_store._cache.exists("test_key") + + # Retrieve and verify caching works + result = await cached_store.get("test_key", default_buffer_prototype()) + assert result is not None + assert result.to_bytes() == b"test data" + + async def test_cache_miss_and_population( + self, cached_store: CacheStore, source_store: Store + ) -> None: + """Test cache miss and subsequent population.""" + # Put data directly in source store (bypassing cache) + test_data = CPUBuffer.from_bytes(b"source data") + await source_store.set("source_key", test_data) + + # First access should miss cache but populate it + result = await cached_store.get("source_key", default_buffer_prototype()) + assert result is not None + assert result.to_bytes() == b"source data" + + # Verify data is now in cache + assert await cached_store._cache.exists("source_key") + + async def test_cache_expiration(self) -> None: + """Test cache expiration based on max_age_seconds.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore( + source_store, + cache_store=cache_store, + max_age_seconds=1, # 1 second expiration + ) + + # Store data + test_data = CPUBuffer.from_bytes(b"expiring data") + await cached_store.set("expire_key", test_data) + + # Should be fresh initially + assert cached_store._is_key_fresh("expire_key") + + # Wait for expiration + await asyncio.sleep(1.1) + + # Should now be stale + assert not cached_store._is_key_fresh("expire_key") + + async def test_cache_set_data_false(self, source_store: Store, cache_store: Store) -> None: + """Test behavior when cache_set_data=False.""" + cached_store = CacheStore(source_store, cache_store=cache_store, cache_set_data=False) + + test_data = CPUBuffer.from_bytes(b"no cache data") + await cached_store.set("no_cache_key", test_data) + + # Data should be in source but not cache + assert await source_store.exists("no_cache_key") + assert not await cache_store.exists("no_cache_key") + + async def test_delete_removes_from_both_stores(self, cached_store: CacheStore) -> None: + """Test that delete removes from both source and cache.""" + test_data = CPUBuffer.from_bytes(b"delete me") + await cached_store.set("delete_key", test_data) + + # Verify in both stores + assert await cached_store._store.exists("delete_key") + assert await cached_store._cache.exists("delete_key") + + # Delete + await cached_store.delete("delete_key") + + # Verify removed from both + assert not await cached_store._store.exists("delete_key") + assert not await cached_store._cache.exists("delete_key") + + async def test_exists_checks_source_store( + self, cached_store: CacheStore, source_store: Store + ) -> None: + """Test that exists() checks the source store (source of truth).""" + # Put data directly in source + test_data = CPUBuffer.from_bytes(b"exists test") + await source_store.set("exists_key", test_data) + + # Should exist even though not in cache + assert await cached_store.exists("exists_key") + + async def test_list_operations(self, cached_store: CacheStore, source_store: Store) -> None: + """Test listing operations delegate to source store.""" + # Add some test data + test_data = CPUBuffer.from_bytes(b"list test") + await cached_store.set("list/item1", test_data) + await cached_store.set("list/item2", test_data) + await cached_store.set("other/item3", test_data) + + # Test list_dir + list_items = [key async for key in cached_store.list_dir("list/")] + assert len(list_items) >= 2 # Should include our items + + # Test list_prefix + prefix_items = [key async for key in cached_store.list_prefix("list/")] + assert len(prefix_items) >= 2 + + async def test_stale_cache_refresh(self) -> None: + """Test that stale cache entries are refreshed from source.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(source_store, cache_store=cache_store, max_age_seconds=1) + + # Store initial data + old_data = CPUBuffer.from_bytes(b"old data") + await cached_store.set("refresh_key", old_data) + + # Wait for expiration + await asyncio.sleep(1.1) + + # Update source store directly (simulating external update) + new_data = CPUBuffer.from_bytes(b"new data") + await source_store.set("refresh_key", new_data) + + # Access should refresh from source when cache is stale + result = await cached_store.get("refresh_key", default_buffer_prototype()) + assert result is not None + assert result.to_bytes() == b"new data" + + async def test_infinity_max_age(self, cached_store: CacheStore) -> None: + """Test that 'infinity' max_age means cache never expires.""" + test_data = CPUBuffer.from_bytes(b"eternal data") + await cached_store.set("eternal_key", test_data) + + # Should always be fresh + assert cached_store._is_key_fresh("eternal_key") + + # Even after time passes + await asyncio.sleep(0.1) + assert cached_store._is_key_fresh("eternal_key") + + async def test_cache_returns_cached_data_for_performance( + self, cached_store: CacheStore, source_store: Store + ) -> None: + """Test that cache returns cached data for performance, even if not in source.""" + # Put data in cache but not source (simulates orphaned cache entry) + test_data = CPUBuffer.from_bytes(b"orphaned data") + await cached_store._cache.set("orphan_key", test_data) + cached_store._state.key_insert_times["orphan_key"] = time.monotonic() + + # Cache should return data for performance (no source verification) + result = await cached_store.get("orphan_key", default_buffer_prototype()) + assert result is not None + assert result.to_bytes() == b"orphaned data" + + # Cache entry should remain (performance optimization) + assert await cached_store._cache.exists("orphan_key") + assert "orphan_key" in cached_store._state.key_insert_times + + async def test_cache_coherency_through_expiration(self) -> None: + """Test that cache coherency is managed through cache expiration, not source verification.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore( + source_store, + cache_store=cache_store, + max_age_seconds=1, # Short expiration for coherency + ) + + # Add data to both stores + test_data = CPUBuffer.from_bytes(b"original data") + await cached_store.set("coherency_key", test_data) + + # Remove from source (simulating external deletion) + await source_store.delete("coherency_key") + + # Cache should still return cached data (performance optimization) + result = await cached_store.get("coherency_key", default_buffer_prototype()) + assert result is not None + assert result.to_bytes() == b"original data" + + # Wait for cache expiration + await asyncio.sleep(1.1) + + # Now stale cache should be refreshed from source + result = await cached_store.get("coherency_key", default_buffer_prototype()) + assert result is None # Key no longer exists in source + + async def test_cache_info(self, cached_store: CacheStore) -> None: + """Test cache_info method returns correct information.""" + # Test initial state + info = cached_store.cache_info() + + # Check all expected keys are present + expected_keys = { + "cache_store_type", + "max_age_seconds", + "max_size", + "current_size", + "cache_set_data", + "tracked_keys", + "cached_keys", + } + assert set(info.keys()) == expected_keys + + # Check initial values + assert info["cache_store_type"] == "MemoryStore" + assert info["max_age_seconds"] == "infinity" + assert info["max_size"] is None # Default unlimited + assert info["current_size"] == 0 + assert info["cache_set_data"] is True + assert info["tracked_keys"] == 0 + assert info["cached_keys"] == 0 + + # Add some data and verify tracking + test_data = CPUBuffer.from_bytes(b"test data for cache info") + await cached_store.set("info_test_key", test_data) + + # Check updated info + updated_info = cached_store.cache_info() + assert updated_info["tracked_keys"] == 1 + assert updated_info["cached_keys"] == 1 + assert updated_info["current_size"] > 0 # Should have some size now + + async def test_cache_info_with_max_size(self) -> None: + """Test cache_info with max_size configuration.""" + source_store = MemoryStore() + cache_store = MemoryStore() + + # Create cache with specific max_size and max_age + cached_store = CacheStore( + source_store, + cache_store=cache_store, + max_size=1024, + max_age_seconds=300, + ) + + info = cached_store.cache_info() + assert info["max_size"] == 1024 + assert info["max_age_seconds"] == 300 + assert info["current_size"] == 0 + + async def test_clear_cache(self, cached_store: CacheStore) -> None: + """Test clear_cache method clears all cache data and tracking.""" + # Add some test data + test_data1 = CPUBuffer.from_bytes(b"test data 1") + test_data2 = CPUBuffer.from_bytes(b"test data 2") + + await cached_store.set("clear_test_1", test_data1) + await cached_store.set("clear_test_2", test_data2) + + # Verify data is cached + info_before = cached_store.cache_info() + assert info_before["tracked_keys"] == 2 + assert info_before["cached_keys"] == 2 + assert info_before["current_size"] > 0 + + # Verify data exists in cache + assert await cached_store._cache.exists("clear_test_1") + assert await cached_store._cache.exists("clear_test_2") + + # Clear the cache + await cached_store.clear_cache() + + # Verify cache is cleared + info_after = cached_store.cache_info() + assert info_after["tracked_keys"] == 0 + assert info_after["cached_keys"] == 0 + assert info_after["current_size"] == 0 + + # Verify data is removed from cache store (if it supports clear) + if hasattr(cached_store._cache, "clear"): + # If cache store supports clear, all data should be gone + assert not await cached_store._cache.exists("clear_test_1") + assert not await cached_store._cache.exists("clear_test_2") + + # Verify data still exists in source store + assert await cached_store._store.exists("clear_test_1") + assert await cached_store._store.exists("clear_test_2") + + async def test_max_age_infinity(self) -> None: + """Test cache with infinite max age.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(source_store, cache_store=cache_store, max_age_seconds="infinity") + + # Add data and verify it never expires + test_data = CPUBuffer.from_bytes(b"test data") + await cached_store.set("test_key", test_data) + + # Even after time passes, key should be fresh + assert cached_store._is_key_fresh("test_key") + + async def test_max_age_numeric(self) -> None: + """Test cache with numeric max age.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore( + source_store, + cache_store=cache_store, + max_age_seconds=1, # 1 second + ) + + # Add data + test_data = CPUBuffer.from_bytes(b"test data") + await cached_store.set("test_key", test_data) + + # Key should be fresh initially + assert cached_store._is_key_fresh("test_key") + + # Manually set old timestamp to test expiration + cached_store._state.key_insert_times["test_key"] = time.monotonic() - 2 # 2 seconds ago + + # Key should now be stale + assert not cached_store._is_key_fresh("test_key") + + async def test_cache_set_data_disabled(self) -> None: + """Test cache behavior when cache_set_data is False.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(source_store, cache_store=cache_store, cache_set_data=False) + + # Set data + test_data = CPUBuffer.from_bytes(b"test data") + await cached_store.set("test_key", test_data) + + # Data should be in source but not in cache + assert await source_store.exists("test_key") + assert not await cache_store.exists("test_key") + + # Cache info should show no cached data + info = cached_store.cache_info() + assert info["cache_set_data"] is False + assert info["cached_keys"] == 0 + + async def test_eviction_with_max_size(self) -> None: + """Test LRU eviction when max_size is exceeded.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore( + source_store, + cache_store=cache_store, + max_size=100, # Small cache size + ) + + # Add data that exceeds cache size + small_data = CPUBuffer.from_bytes(b"a" * 40) # 40 bytes + medium_data = CPUBuffer.from_bytes(b"b" * 40) # 40 bytes + large_data = CPUBuffer.from_bytes(b"c" * 40) # 40 bytes (would exceed 100 byte limit) + + # Set first two items + await cached_store.set("key1", small_data) + await cached_store.set("key2", medium_data) + + # Cache should have 2 items + info = cached_store.cache_info() + assert info["cached_keys"] == 2 + assert info["current_size"] == 80 + + # Add third item - should trigger eviction of first item + await cached_store.set("key3", large_data) + + # Cache should still have items but first one may be evicted + info = cached_store.cache_info() + assert info["current_size"] <= 100 + + async def test_value_exceeds_max_size(self) -> None: + """Test behavior when a single value exceeds max_size.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore( + source_store, + cache_store=cache_store, + max_size=50, # Small cache size + ) + + # Try to cache data larger than max_size + large_data = CPUBuffer.from_bytes(b"x" * 100) # 100 bytes > 50 byte limit + await cached_store.set("large_key", large_data) + + # Data should be in source but not cached + assert await source_store.exists("large_key") + info = cached_store.cache_info() + assert info["cached_keys"] == 0 + assert info["current_size"] == 0 + + async def test_get_nonexistent_key(self) -> None: + """Test getting a key that doesn't exist in either store.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(source_store, cache_store=cache_store) + + # Try to get nonexistent key + result = await cached_store.get("nonexistent", default_buffer_prototype()) + assert result is None + + # Should not create any cache entries + info = cached_store.cache_info() + assert info["cached_keys"] == 0 + + async def test_delete_both_stores(self) -> None: + """Test that delete removes from both source and cache stores.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(source_store, cache_store=cache_store) + + # Add data + test_data = CPUBuffer.from_bytes(b"test data") + await cached_store.set("test_key", test_data) + + # Verify it's in both stores + assert await source_store.exists("test_key") + assert await cache_store.exists("test_key") + + # Delete + await cached_store.delete("test_key") + + # Verify it's removed from both + assert not await source_store.exists("test_key") + assert not await cache_store.exists("test_key") + + # Verify tracking is updated + info = cached_store.cache_info() + assert info["cached_keys"] == 0 + + async def test_invalid_max_age_seconds(self) -> None: + """Test that invalid max_age_seconds values raise ValueError.""" + source_store = MemoryStore() + cache_store = MemoryStore() + + with pytest.raises(ValueError, match="max_age_seconds string value must be 'infinity'"): + CacheStore(source_store, cache_store=cache_store, max_age_seconds="invalid") + + async def test_unlimited_cache_size(self) -> None: + """Test behavior when max_size is None (unlimited).""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore( + source_store, + cache_store=cache_store, + max_size=None, # Unlimited cache + ) + + # Add large amounts of data + for i in range(10): + large_data = CPUBuffer.from_bytes(b"x" * 1000) # 1KB each + await cached_store.set(f"large_key_{i}", large_data) + + # All should be cached since there's no size limit + info = cached_store.cache_info() + assert info["cached_keys"] == 10 + assert info["current_size"] == 10000 # 10 * 1000 bytes + + async def test_evict_key_exception_handling(self) -> None: + """Test exception handling in _evict_key method.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(source_store, cache_store=cache_store, max_size=100) + + # Add some data + test_data = CPUBuffer.from_bytes(b"test data") + await cached_store.set("test_key", test_data) + + # Manually corrupt the tracking to trigger exception + # Remove from one structure but not others to create inconsistency + del cached_store._state.cache_order["test_key"] + + # Try to evict - should handle the KeyError gracefully + await cached_store._evict_key("test_key") + + # Should still work and not crash + info = cached_store.cache_info() + assert isinstance(info, dict) + + async def test_get_no_cache_delete_tracking(self) -> None: + """Test _get_no_cache when key doesn't exist and needs cleanup.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(source_store, cache_store=cache_store) + + # First, add key to cache tracking but not to source + test_data = CPUBuffer.from_bytes(b"test data") + await cache_store.set("phantom_key", test_data) + await cached_store._track_entry("phantom_key", test_data) + + # Verify it's in tracking + assert "phantom_key" in cached_store._state.cache_order + assert "phantom_key" in cached_store._state.key_insert_times + + # Now try to get it - since it's not in source, should clean up tracking + result = await cached_store._get_no_cache("phantom_key", default_buffer_prototype()) + assert result is None + + # Should have cleaned up tracking + assert "phantom_key" not in cached_store._state.cache_order + assert "phantom_key" not in cached_store._state.key_insert_times + + async def test_accommodate_value_no_max_size(self) -> None: + """Test _accommodate_value early return when max_size is None.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore( + source_store, + cache_store=cache_store, + max_size=None, # No size limit + ) + + # This should return early without doing anything + await cached_store._accommodate_value(1000000) # Large value + + # Should not affect anything since max_size is None + info = cached_store.cache_info() + assert info["current_size"] == 0 + + async def test_concurrent_set_operations(self) -> None: + """Test that concurrent set operations don't corrupt cache size tracking.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(source_store, cache_store=cache_store, max_size=1000) + + # Create 10 concurrent set operations + async def set_data(key: str) -> None: + data = CPUBuffer.from_bytes(b"x" * 50) + await cached_store.set(key, data) + + # Run concurrently + await asyncio.gather(*[set_data(f"key_{i}") for i in range(10)]) + + info = cached_store.cache_info() + # Expected: 10 keys * 50 bytes = 500 bytes + assert info["cached_keys"] == 10 + assert info["current_size"] == 500 # WOULD FAIL due to race condition + + async def test_concurrent_eviction_race(self) -> None: + """Test concurrent evictions don't corrupt size tracking.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(source_store, cache_store=cache_store, max_size=200) + + # Fill cache to near capacity + data = CPUBuffer.from_bytes(b"x" * 80) + await cached_store.set("key1", data) + await cached_store.set("key2", data) + + # Now trigger two concurrent sets that both need to evict + async def set_large(key: str) -> None: + large_data = CPUBuffer.from_bytes(b"y" * 100) + await cached_store.set(key, large_data) + + await asyncio.gather(set_large("key3"), set_large("key4")) + + info = cached_store.cache_info() + # Size should be consistent with tracked keys + assert info["current_size"] <= 200 # Might pass + # But verify actual cache store size matches tracking + total_size = sum( + cached_store._state.key_sizes.get(k, 0) for k in cached_store._state.cache_order + ) + assert total_size == info["current_size"] # WOULD FAIL + + async def test_concurrent_get_and_evict(self) -> None: + """Test get operations during eviction don't cause corruption.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(source_store, cache_store=cache_store, max_size=100) + + # Setup + data = CPUBuffer.from_bytes(b"x" * 40) + await cached_store.set("key1", data) + await cached_store.set("key2", data) + + # Concurrent: read key1 while adding key3 (triggers eviction) + async def read_key() -> None: + for _ in range(100): + await cached_store.get("key1", default_buffer_prototype()) + + async def write_key() -> None: + for i in range(10): + new_data = CPUBuffer.from_bytes(b"y" * 40) + await cached_store.set(f"new_{i}", new_data) + + await asyncio.gather(read_key(), write_key()) + + # Verify consistency + info = cached_store.cache_info() + assert info["current_size"] <= 100 + assert len(cached_store._state.cache_order) == len(cached_store._state.key_sizes) + + async def test_eviction_actually_deletes_from_cache_store(self) -> None: + """Test that eviction removes keys from cache_store, not just tracking.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(source_store, cache_store=cache_store, max_size=100) + + # Add data that will be evicted + data1 = CPUBuffer.from_bytes(b"x" * 60) + data2 = CPUBuffer.from_bytes(b"y" * 60) + + await cached_store.set("key1", data1) + + # Verify key1 is in cache_store + assert await cache_store.exists("key1") + + # Add key2, which should evict key1 + await cached_store.set("key2", data2) + + # Check tracking - key1 should be removed + assert "key1" not in cached_store._state.cache_order + assert "key1" not in cached_store._state.key_sizes + + # CRITICAL: key1 should also be removed from cache_store + assert not await cache_store.exists("key1"), ( + "Evicted key still exists in cache_store! _evict_key doesn't actually delete." + ) + + # But key1 should still exist in source store + assert await source_store.exists("key1") + + async def test_eviction_no_orphaned_keys(self) -> None: + """Test that eviction doesn't leave orphaned keys in cache_store.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(source_store, cache_store=cache_store, max_size=150) + + # Add multiple keys that will cause evictions + for i in range(10): + data = CPUBuffer.from_bytes(b"x" * 60) + await cached_store.set(f"key_{i}", data) + + # Check tracking + info = cached_store.cache_info() + tracked_keys = info["cached_keys"] + + # Count actual keys in cache_store + actual_keys = 0 + async for _ in cache_store.list(): + actual_keys += 1 + + # Cache store should have same number of keys as tracking + assert actual_keys == tracked_keys, ( + f"Cache store has {actual_keys} keys but tracking shows {tracked_keys}. " + f"Eviction doesn't delete from cache_store!" + ) + + async def test_size_accounting_with_key_updates(self) -> None: + """Test that updating the same key replaces size instead of accumulating.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(source_store, cache_store=cache_store, max_size=500) + + # Set initial value + data1 = CPUBuffer.from_bytes(b"x" * 100) + await cached_store.set("same_key", data1) + + info1 = cached_store.cache_info() + assert info1["current_size"] == 100 + + # Update with different size + data2 = CPUBuffer.from_bytes(b"y" * 200) + await cached_store.set("same_key", data2) + + info2 = cached_store.cache_info() + + # Should be 200, not 300 (update replaces, doesn't accumulate) + assert info2["current_size"] == 200, ( + f"Expected size 200 but got {info2['current_size']}. " + "Updating same key should replace, not accumulate." + ) + + async def test_all_tracked_keys_exist_in_cache_store(self) -> None: + """Test invariant: all keys in tracking should exist in cache_store.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(source_store, cache_store=cache_store, max_size=500) + + # Add some data + for i in range(5): + data = CPUBuffer.from_bytes(b"x" * 50) + await cached_store.set(f"key_{i}", data) + + # Every str key in tracking should exist in cache_store + # (tuple keys are byte-range entries stored in-memory, not in the Store) + for entry_key in cached_store._state.cache_order: + if isinstance(entry_key, str): + assert await cache_store.exists(entry_key), ( + f"Key '{entry_key}' is tracked but doesn't exist in cache_store" + ) + + # Every str key in _key_sizes should exist in cache_store + for entry_key in cached_store._state.key_sizes: + if isinstance(entry_key, str): + assert await cache_store.exists(entry_key), ( + f"Key '{entry_key}' has size tracked but doesn't exist in cache_store" + ) + + # Additional coverage tests for 100% coverage + + async def test_cache_store_requires_delete_support(self) -> None: + """Test that CacheStore validates cache_store supports deletes.""" + from unittest.mock import MagicMock + + # Create a mock store that doesn't support deletes + source_store = MemoryStore() + cache_store = MagicMock() + cache_store.supports_deletes = False + + with pytest.raises(ValueError, match="does not support deletes"): + CacheStore(store=source_store, cache_store=cache_store) + + async def test_evict_key_exception_handling_with_real_error( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Test _evict_key exception handling when deletion fails.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(store=source_store, cache_store=cache_store, max_size=100) + + # Set up a key in tracking + buffer = CPUBuffer.from_bytes(b"test data") + await cached_store.set("test_key", buffer) + + # Mock the cache delete to raise an exception + async def failing_delete(key: str) -> None: + raise RuntimeError("Simulated cache deletion failure") + + monkeypatch.setattr(cache_store, "delete", failing_delete) + + # Attempt to evict should raise the exception + with pytest.raises(RuntimeError, match="Simulated cache deletion failure"): + async with cached_store._state.lock: + await cached_store._evict_key("test_key") + + async def test_cache_stats_method(self) -> None: + """Test cache_stats method returns correct statistics.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(store=source_store, cache_store=cache_store, max_size=1000) + + # Initially, stats should be zero + stats = cached_store.cache_stats() + assert stats["hits"] == 0 + assert stats["misses"] == 0 + assert stats["evictions"] == 0 + assert stats["total_requests"] == 0 + assert stats["hit_rate"] == 0.0 + + # Perform some operations + buffer = CPUBuffer.from_bytes(b"x" * 100) + + # Write to source store directly to avoid affecting stats + await source_store.set("key1", buffer) + + # First get is a miss (not in cache yet) + result1 = await cached_store.get("key1", default_buffer_prototype()) + assert result1 is not None + + # Second get is a hit (now in cache) + result2 = await cached_store.get("key1", default_buffer_prototype()) + assert result2 is not None + + stats = cached_store.cache_stats() + assert stats["hits"] == 1 + assert stats["misses"] == 1 + assert stats["total_requests"] == 2 + assert stats["hit_rate"] == 0.5 + + async def test_cache_stats_with_evictions(self) -> None: + """Test cache_stats tracks evictions correctly.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore( + store=source_store, + cache_store=cache_store, + max_size=150, # Small size to force eviction + ) + + # Add items that will trigger eviction + buffer1 = CPUBuffer.from_bytes(b"x" * 100) + buffer2 = CPUBuffer.from_bytes(b"y" * 100) + + await cached_store.set("key1", buffer1) + await cached_store.set("key2", buffer2) # Should evict key1 + + stats = cached_store.cache_stats() + assert stats["evictions"] == 1 + + def test_repr_method(self) -> None: + """Test __repr__ returns useful string representation.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore( + store=source_store, cache_store=cache_store, max_age_seconds=60, max_size=1024 + ) + + repr_str = repr(cached_store) + + # Check that repr contains key information + assert "CacheStore" in repr_str + assert "max_age_seconds=60" in repr_str + assert "max_size=1024" in repr_str + assert "current_size=0" in repr_str + assert "cached_keys=0" in repr_str + + async def test_cache_stats_zero_division_protection(self) -> None: + """Test cache_stats handles zero requests correctly.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(store=source_store, cache_store=cache_store) + + # With no requests, hit_rate should be 0.0 (not NaN or error) + stats = cached_store.cache_stats() + assert stats["hit_rate"] == 0.0 + assert stats["total_requests"] == 0 + + async def test_byte_range_does_not_corrupt_cache(self) -> None: + """Test that fetching a byte range does not store partial data under the full key. + + Reproduces https://github.com/zarr-developers/zarr-python/issues/3690: + when a byte-range read populates the cache, subsequent reads of different + ranges (or the full key) return wrong data. + """ + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(store=source_store, cache_store=cache_store) + + full_data = b"bar baz" + await source_store.set("foo", CPUBuffer.from_bytes(full_data)) + + proto = default_buffer_prototype() + + # First read: byte range [0, 3) -> b"bar" + bar = await cached_store.get("foo", proto, byte_range=RangeByteRequest(0, 3)) + assert bar is not None + assert bar.to_bytes() == b"bar" + + # Second read: different byte range [4, 7) -> b"baz" + baz = await cached_store.get("foo", proto, byte_range=RangeByteRequest(4, 7)) + assert baz is not None + assert baz.to_bytes() == b"baz" + + # Third read: full key -> full data + full = await cached_store.get("foo", proto) + assert full is not None + assert full.to_bytes() == full_data + + async def test_full_read_then_byte_range(self) -> None: + """Test that a cached full read correctly serves subsequent byte-range requests.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(store=source_store, cache_store=cache_store) + + full_data = b"hello world" + await source_store.set("key", CPUBuffer.from_bytes(full_data)) + + proto = default_buffer_prototype() + + # Full read populates cache + full = await cached_store.get("key", proto) + assert full is not None + assert full.to_bytes() == full_data + + # Byte-range reads should return the correct slices + part = await cached_store.get("key", proto, byte_range=RangeByteRequest(0, 5)) + assert part is not None + assert part.to_bytes() == b"hello" + + part2 = await cached_store.get("key", proto, byte_range=RangeByteRequest(6, 11)) + assert part2 is not None + assert part2.to_bytes() == b"world" + + suffix = await cached_store.get("key", proto, byte_range=SuffixByteRequest(5)) + assert suffix is not None + assert suffix.to_bytes() == b"world" + + async def test_byte_range_set_then_read(self) -> None: + """Test that data written via set() can be read back with byte ranges.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(store=source_store, cache_store=cache_store) + + full_data = b"abcdefghij" + await cached_store.set("key", CPUBuffer.from_bytes(full_data)) + + proto = default_buffer_prototype() + + # Byte-range reads from the cached data + mid = await cached_store.get("key", proto, byte_range=RangeByteRequest(3, 7)) + assert mid is not None + assert mid.to_bytes() == b"defg" + + # Full read should still work + full = await cached_store.get("key", proto) + assert full is not None + assert full.to_bytes() == full_data + + async def test_set_invalidates_cached_byte_ranges(self) -> None: + """Test that set() invalidates previously cached byte-range entries.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(store=source_store, cache_store=cache_store) + + proto = default_buffer_prototype() + + # Populate source and cache some byte ranges + await source_store.set("key", CPUBuffer.from_bytes(b"old data!!")) + r1 = await cached_store.get("key", proto, byte_range=RangeByteRequest(0, 3)) + assert r1 is not None + assert r1.to_bytes() == b"old" + + # Byte-range entry should be in range_cache + assert ("key", RangeByteRequest(0, 3)) in cached_store._state.cache_order + + # Overwrite via set() β€” range entries must be invalidated + await cached_store.set("key", CPUBuffer.from_bytes(b"NEW DATA!!")) + + # The old range entry should be gone from tracking and range_cache + assert ("key", RangeByteRequest(0, 3)) not in cached_store._state.cache_order + assert "key" not in cached_store._state.range_cache + + # A fresh byte-range read should return the new data + r2 = await cached_store.get("key", proto, byte_range=RangeByteRequest(0, 3)) + assert r2 is not None + assert r2.to_bytes() == b"NEW" + + async def test_delete_invalidates_cached_byte_ranges(self) -> None: + """Test that delete() removes previously cached byte-range entries.""" + source_store = MemoryStore() + cache_store = MemoryStore() + cached_store = CacheStore(store=source_store, cache_store=cache_store) + + proto = default_buffer_prototype() + + # Populate and cache a byte range + await source_store.set("key", CPUBuffer.from_bytes(b"hello world")) + r = await cached_store.get("key", proto, byte_range=RangeByteRequest(0, 5)) + assert r is not None + assert r.to_bytes() == b"hello" + + assert ("key", RangeByteRequest(0, 5)) in cached_store._state.cache_order + + # Delete the key β€” range entries must be cleaned up + await cached_store.delete("key") + + assert ("key", RangeByteRequest(0, 5)) not in cached_store._state.cache_order + assert "key" not in cached_store._state.range_cache + + # Key is gone from source + result = await cached_store.get("key", proto) + assert result is None + + +def test_cache_store_opts_out_of_sync_io() -> None: + """`CacheStore` must not advertise sync IO capability. + + Its caching logic lives only in the async `get`/`set`/`delete` overrides, + while the inherited `WrapperStore` sync methods delegate straight to the + source store. If the fused codec pipeline took the sync fast path, writes + and deletes would bypass the cache and later async reads would serve stale + entries. The opt-out forces sync-capable consumers onto the async path, + which keeps the cache coherent. + """ + from zarr.abc.store import _store_supports_sync_io + from zarr.storage import MemoryStore + + cached = CacheStore(MemoryStore(), cache_store=MemoryStore()) + assert _store_supports_sync_io(cached) is False + + +async def test_cache_coherent_after_fused_pipeline_write() -> None: + """Writing through the fused pipeline must not leave stale cache entries.""" + import numpy as np + + import zarr + from zarr.core.config import config as zarr_config + from zarr.storage import MemoryStore + + source = MemoryStore() + cached = CacheStore(source, cache_store=MemoryStore()) + with zarr_config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"}): + arr = zarr.create_array(cached, shape=(8,), chunks=(8,), dtype="int32", fill_value=0) + arr[:] = np.arange(8, dtype="int32") + np.testing.assert_array_equal(arr[:], np.arange(8)) + # Overwrite, then read back through the same cached handle: the read + # must observe the overwrite, not a cached copy of the first write. + arr[:] = np.arange(100, 108, dtype="int32") + np.testing.assert_array_equal(arr[:], np.arange(100, 108)) diff --git a/tests/test_fastpath_equivalence.py b/tests/test_fastpath_equivalence.py new file mode 100644 index 0000000000..9a2f782d13 --- /dev/null +++ b/tests/test_fastpath_equivalence.py @@ -0,0 +1,402 @@ +"""Property tests: every fast path must equal the general path. + +The codec pipelines contain fast paths that skip work whose result is known β€” +the complete-chunk merge view, the vectorized whole-shard bulk decode, the +scalar-broadcast write memoization, byte-range coalescing. Each is only safe if +it produces results identical to the general path it bypasses. These tests pin +that equivalence on randomized inputs, so a fast path that silently diverges +(the bug class behind the bulk-decode endianness fix) fails here instead of +corrupting data downstream. + +Convention for new fast paths: a fast path is "skip work whose result is +known", never "a different algorithm" β€” and it ships with a property test in +this module asserting equality with the general path. +""" + +from __future__ import annotations + +from typing import Any + +import hypothesis.extra.numpy as npst +import hypothesis.strategies as st +import numpy as np +from hypothesis import given, settings + +import zarr +from zarr.abc.store import OffsetByteRequest, RangeByteRequest, SuffixByteRequest +from zarr.codecs.bytes import BytesCodec +from zarr.codecs.sharding import ShardingCodec +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import default_buffer_prototype +from zarr.core.buffer.cpu import Buffer as CPUBuffer +from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer +from zarr.core.chunk_grids import ChunkGrid +from zarr.core.chunk_utils import _merge_chunk_array +from zarr.core.dtype import get_data_type_from_native_dtype +from zarr.core.indexing import BasicIndexer +from zarr.storage import MemoryStore + +_DTYPES = st.sampled_from(["uint8", "int16", "float32"]) + + +def _spec(shape: tuple[int, ...], dtype: str, *, write_empty_chunks: bool = True) -> ArraySpec: + zdtype = get_data_type_from_native_dtype(np.dtype(dtype)) + return ArraySpec( + shape=shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=write_empty_chunks), + prototype=default_buffer_prototype(), + ) + + +# --------------------------------------------------------------------------- +# _merge_chunk_array: the complete-chunk early return (a view of +# value[out_selection]) must equal the general create/copy + setitem path. +# --------------------------------------------------------------------------- + + +@st.composite +def _merge_cases(draw: st.DrawFn) -> tuple[np.ndarray, tuple[int, ...], tuple[slice, ...]]: + ndim = draw(st.integers(1, 3)) + chunk_shape = tuple(draw(st.integers(1, 5)) for _ in range(ndim)) + n_blocks = draw(st.integers(1, 3)) + dtype = draw(_DTYPES) + # value spans n_blocks chunk-sized blocks along axis 0; out_selection picks one + value_shape = (chunk_shape[0] * n_blocks, *chunk_shape[1:]) + value = draw(npst.arrays(dtype=np.dtype(dtype), shape=value_shape)) + block = draw(st.integers(0, n_blocks - 1)) + out_selection = ( + slice(block * chunk_shape[0], (block + 1) * chunk_shape[0]), + *(slice(0, s) for s in chunk_shape[1:]), + ) + return value, chunk_shape, out_selection + + +@settings(max_examples=200, deadline=None) +@given(case=_merge_cases(), with_existing=st.booleans()) +def test_merge_complete_chunk_equals_general_path( + case: tuple[np.ndarray, tuple[int, ...], tuple[slice, ...]], with_existing: bool +) -> None: + """The is_complete_chunk fast path (return a view of value[out_selection]) + must produce exactly what the general merge path produces β€” and a complete + write must be independent of any existing chunk content.""" + value_np, chunk_shape, out_selection = case + spec = _spec(chunk_shape, str(value_np.dtype)) + value = CPUNDBuffer.from_numpy_array(value_np) + chunk_selection = tuple(slice(0, s) for s in chunk_shape) + + existing = None + if with_existing: + existing = CPUNDBuffer.from_numpy_array(np.full(chunk_shape, 7, dtype=value_np.dtype)) + + fast = _merge_chunk_array(existing, value, out_selection, spec, chunk_selection, True, ()) + general = _merge_chunk_array(existing, value, out_selection, spec, chunk_selection, False, ()) + np.testing.assert_array_equal(fast.as_numpy_array(), general.as_numpy_array()) + np.testing.assert_array_equal(fast.as_numpy_array(), value_np[out_selection]) + + +# --------------------------------------------------------------------------- +# _decode_full_shard_bulk_if_uncompressed: the vectorized dense-shard decode must equal the +# general per-chunk decode (_decode_sync), across dtypes, endianness, write +# orders, and index locations. This is the bug class of the historical +# bulk-decode endianness fix. +# --------------------------------------------------------------------------- + + +@st.composite +def _shard_cases(draw: st.DrawFn) -> dict[str, Any]: + ndim = draw(st.integers(1, 2)) + chunk_shape = tuple(draw(st.integers(1, 4)) for _ in range(ndim)) + grid = tuple(draw(st.integers(1, 3)) for _ in range(ndim)) + shard_shape = tuple(c * g for c, g in zip(chunk_shape, grid, strict=True)) + dtype = draw(_DTYPES) + data = draw(npst.arrays(dtype=np.dtype(dtype), shape=shard_shape)) + return { + "chunk_shape": chunk_shape, + "shard_shape": shard_shape, + "data": data, + "endian": draw(st.sampled_from(["little", "big"])), + "index_location": draw(st.sampled_from(["start", "end"])), + "subchunk_write_order": draw( + st.sampled_from(["morton", "lexicographic", "colexicographic", "unordered"]) + ), + } + + +@settings(max_examples=100, deadline=None) +@given(case=_shard_cases()) +def test_bulk_shard_decode_equals_general_decode(case: dict[str, Any]) -> None: + """For dense fixed-size uncompressed shards, the vectorized bulk decode must + reproduce the general per-chunk decode exactly, whatever the endianness, + subchunk write order, or index location.""" + codec = ShardingCodec( + chunk_shape=case["chunk_shape"], + codecs=[BytesCodec(endian=case["endian"])], + index_location=case["index_location"], + subchunk_write_order=case["subchunk_write_order"], + ) + spec = _spec(case["shard_shape"], str(case["data"].dtype), write_empty_chunks=True) + blob = codec._encode_sync(CPUNDBuffer.from_numpy_array(case["data"]), spec) + assert blob is not None # write_empty_chunks=True -> dense, never elided + + general = codec._decode_sync(blob, spec) + indexer = BasicIndexer( + tuple(slice(0, s) for s in case["shard_shape"]), + shape=case["shard_shape"], + chunk_grid=ChunkGrid.from_sizes(case["shard_shape"], case["chunk_shape"]), + ) + bulk = codec._decode_full_shard_bulk_if_uncompressed(blob, spec, indexer) + # the fast path must APPLY for this dense uncompressed configuration β€” + # a vacuous None would silently stop testing the equivalence + assert bulk is not None + np.testing.assert_array_equal(bulk.as_numpy_array(), general.as_numpy_array()) + np.testing.assert_array_equal(general.as_numpy_array(), case["data"]) + + +def test_merge_complete_chunk_returns_view_and_write_does_not_mutate_source() -> None: + """The complete-chunk merge fast path returns a VIEW of the caller's value + (no copy β€” that is the perf win), and a multi-chunk write through either + pipeline leaves the user's source array untouched. + + Pins both halves of the aliasing contract: a future "defensive copy" + refactor that silently reintroduces the per-chunk create/fill/copy breaks + the first assertion, and an in-place-mutating codec that corrupts the + user's array through the shared view breaks the second. + """ + # the fast path must return a view aliasing `value`, not a copy + value_np = np.arange(30, dtype="uint16") + spec = _spec((10,), "uint16") + value = CPUNDBuffer.from_numpy_array(value_np) + merged = _merge_chunk_array(None, value, (slice(10, 20),), spec, (slice(0, 10),), True, ()) + assert np.shares_memory(merged.as_numpy_array(), value_np), ( + "complete-chunk merge no longer returns a view of the caller's value" + ) + + # end-to-end: the source array is byte-identical after a multi-chunk write + for pipeline_path in ( + "zarr.core.codec_pipeline.FusedCodecPipeline", + "zarr.core.codec_pipeline.BatchedCodecPipeline", + ): + with zarr.config.set({"codec_pipeline.path": pipeline_path}): + arr = zarr.create_array( + store=MemoryStore(), + shape=(30,), + chunks=(10,), + dtype="uint16", + compressors=None, + fill_value=0, + ) + source = np.arange(30, dtype="uint16") + snapshot = source.copy() + arr[:] = source + np.testing.assert_array_equal(source, snapshot, err_msg=pipeline_path) + np.testing.assert_array_equal(arr[:], snapshot, err_msg=pipeline_path) + + +# --------------------------------------------------------------------------- +# Whole-shard bulk decode under arbitrary indexing: the bulk decode only fires +# for an *identity full-shard* read (every dimension a whole-dim step-1 slice), +# but it is reached through the partial-read path (`_decode_partial_sync`) for +# any indexer. A reordering or duplicating coordinate/orthogonal selection can +# have an output shape equal to the shard shape β€” trivially in 1-D (any +# selection of `shard_len` points), and in >=2-D whenever an axis-0 index array +# has exactly `shard_shape[0]` entries β€” and must NOT be served by the bulk +# path in natural order; it must honor the selection. This pins the END-TO-END +# read, which `test_bulk_shard_decode_equals_general_decode` (identity +# BasicIndexer only) cannot reach. See the vindex- and +# oindex-on-uncompressed-shard corruption bugs. +# --------------------------------------------------------------------------- + + +@st.composite +def _uncompressed_shard_index_cases(draw: st.DrawFn) -> dict[str, Any]: + ndim = draw(st.integers(1, 2)) + chunk_shape = tuple(draw(st.integers(1, 4)) for _ in range(ndim)) + grid = tuple(draw(st.integers(1, 4)) for _ in range(ndim)) + shard_shape = tuple(c * g for c, g in zip(chunk_shape, grid, strict=True)) + dtype = draw(_DTYPES) + data = draw(npst.arrays(dtype=np.dtype(dtype), shape=shard_shape)) + dim0 = shard_shape[0] + # axis-0 index array sized to the dimension: either a permutation + # (reordering, no duplicates) or an arbitrary list (duplicates likely) β€” + # both keep the output shape equal to the shard shape. + if draw(st.booleans()): + idx = np.array(draw(st.permutations(list(range(dim0)))), dtype=np.intp) + else: + idx = np.array( + draw(st.lists(st.integers(0, dim0 - 1), min_size=dim0, max_size=dim0)), + dtype=np.intp, + ) + return { + "chunk_shape": chunk_shape, + "shard_shape": shard_shape, + "data": data, + "idx": idx, + "endian": draw(st.sampled_from(["little", "big"])), + "index_location": draw(st.sampled_from(["start", "end"])), + "subchunk_write_order": draw( + st.sampled_from(["morton", "lexicographic", "colexicographic", "unordered"]) + ), + } + + +@settings(max_examples=200, deadline=None) +@given(case=_uncompressed_shard_index_cases()) +def test_reordering_read_on_uncompressed_shard_honors_selection(case: dict[str, Any]) -> None: + """A reordering or duplicating fancy/vindex/oindex read over a full + uncompressed shard must return the selected data, not the shard in natural + order β€” under the Fused pipeline (where the bulk-decode fast path engages) + exactly as under numpy.""" + idx = case["idx"] + data = case["data"] + ndim = data.ndim + serializer = BytesCodec(endian=case["endian"]) + + with zarr.config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"}): + arr = zarr.create_array( + store=MemoryStore(), + shape=case["shard_shape"], + chunks=case["chunk_shape"], + shards={"shape": case["shard_shape"], "index_location": case["index_location"]}, + dtype=data.dtype, + serializer=serializer, + compressors=None, + filters=None, + fill_value=0, + ) + arr[...] = data + + # axis-0 index array (rest full slices): an OrthogonalIndexer whose + # output shape equals the shard shape but which reorders/duplicates rows. + rest = (slice(None),) * (ndim - 1) + np.testing.assert_array_equal(arr[(idx, *rest)], data[idx]) + np.testing.assert_array_equal(arr.oindex[(idx, *rest)], data[idx]) + if ndim == 1: + # coordinate selection: flattened point count == shard shape. + np.testing.assert_array_equal(arr.vindex[idx], data[idx]) + else: + # 2-D broadcast index arrays: full-coverage coordinate selection + # whose shape equals the shard shape. + cols = np.arange(case["shard_shape"][1]) + np.testing.assert_array_equal( + arr.vindex[idx[:, None], cols[None, :]], data[idx[:, None], cols[None, :]] + ) + + +# --------------------------------------------------------------------------- +# Scalar-broadcast write memoization: writing a scalar must produce the same +# STORED BYTES as writing the equivalent broadcast array. +# --------------------------------------------------------------------------- + + +@st.composite +def _scalar_cases(draw: st.DrawFn) -> dict[str, Any]: + n_chunks = draw(st.integers(2, 6)) + chunk = draw(st.integers(2, 6)) + shape = n_chunks * chunk + start = draw(st.integers(0, shape - 1)) + stop = draw(st.integers(start + 1, shape)) + return { + "shape": shape, + "chunk": chunk, + "sel": slice(start, stop), + "scalar": draw(st.integers(0, 255)), + "write_empty_chunks": draw(st.booleans()), + "sharded": draw(st.booleans()), + } + + +@settings(max_examples=100, deadline=None) +@given(case=_scalar_cases()) +def test_scalar_write_equals_broadcast_write(case: dict[str, Any]) -> None: + """arr[sel] = scalar and arr[sel] = full(sel_shape, scalar) must leave the + store byte-identical (pins the scalar-broadcast memoization in the sharded + partial-write path, incl. its empty-chunk normalization).""" + + def build() -> tuple[MemoryStore, zarr.Array[Any]]: + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(case["shape"],), + chunks=(case["chunk"],), + shards=(case["shape"],) if case["sharded"] else None, + dtype="uint8", + compressors=None, + fill_value=0, + config={"write_empty_chunks": case["write_empty_chunks"]}, + ) + return store, arr + + # The scalar-broadcast memoization lives in the Fused sync write path; pin it + # explicitly since Fused is no longer the default pipeline. + with zarr.config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"}): + store_a, arr_a = build() + arr_a[case["sel"]] = case["scalar"] + + store_b, arr_b = build() + n = case["sel"].stop - case["sel"].start + arr_b[case["sel"]] = np.full(n, case["scalar"], dtype="uint8") + + keys_a = {k: bytes(v.to_bytes()) for k, v in store_a._store_dict.items()} + keys_b = {k: bytes(v.to_bytes()) for k, v in store_b._store_dict.items()} + assert keys_a == keys_b + + +# --------------------------------------------------------------------------- +# get_ranges_sync coalescing: merged fetches must return exactly what +# individual per-range gets return, for any gap/coalesce limits. +# --------------------------------------------------------------------------- + + +@st.composite +def _range_cases(draw: st.DrawFn) -> dict[str, Any]: + blob_len = draw(st.integers(1, 200)) + n = draw(st.integers(1, 8)) + ranges: list[RangeByteRequest | OffsetByteRequest | SuffixByteRequest | None] = [] + for _ in range(n): + kind = draw(st.sampled_from(["range", "offset", "suffix", "none"])) + if kind == "range": + start = draw(st.integers(0, blob_len - 1)) + end = draw(st.integers(start + 1, blob_len)) + ranges.append(RangeByteRequest(start, end)) + elif kind == "offset": + ranges.append(OffsetByteRequest(draw(st.integers(0, blob_len - 1)))) + elif kind == "suffix": + ranges.append(SuffixByteRequest(draw(st.integers(1, blob_len)))) + else: + ranges.append(None) + return { + "blob": draw(st.binary(min_size=blob_len, max_size=blob_len)), + "ranges": ranges, + "max_gap": draw(st.integers(0, 64)), + "max_coalesced": draw(st.integers(1, 512)), + } + + +@settings(max_examples=200, deadline=None) +@given(case=_range_cases()) +def test_get_ranges_sync_equals_individual_gets(case: dict[str, Any]) -> None: + """Coalesced byte-range reads must return exactly what one get_sync per + range returns β€” for any gap/coalesce limits (the offset re-slicing math is + where a coalescing bug would corrupt data).""" + store = MemoryStore() + store._is_open = True + proto = default_buffer_prototype() + store._store_dict["k"] = CPUBuffer.from_bytes(case["blob"]) + + expected = [store.get_sync("k", prototype=proto, byte_range=r) for r in case["ranges"]] + + got: dict[int, bytes | None] = {} + for idx, buf in store.get_ranges_sync( + "k", + case["ranges"], + prototype=proto, + max_gap_bytes=case["max_gap"], + max_coalesced_bytes=case["max_coalesced"], + ): + got[idx] = None if buf is None else bytes(buf.to_bytes()) + + for i, exp in enumerate(expected): + exp_bytes = None if exp is None else bytes(exp.to_bytes()) + assert got.get(i) == exp_bytes, f"range {i} ({case['ranges'][i]!r}) mismatch" diff --git a/tests/test_fused_pipeline.py b/tests/test_fused_pipeline.py new file mode 100644 index 0000000000..5c712fa97a --- /dev/null +++ b/tests/test_fused_pipeline.py @@ -0,0 +1,1235 @@ +"""Tests for FusedCodecPipeline -- the per-chunk-fused codec pipeline.""" + +from __future__ import annotations + +import asyncio +from dataclasses import dataclass, field, replace +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +import zarr +from zarr.abc.codec import ( + ArrayBytesCodec, + ArrayBytesCodecPartialDecodeMixin, + ArrayBytesCodecPartialEncodeMixin, + BytesBytesCodec, +) +from zarr.abc.store import Store, _store_supports_sync_io +from zarr.codecs.bytes import BytesCodec +from zarr.codecs.gzip import GzipCodec +from zarr.codecs.transpose import TransposeCodec +from zarr.codecs.zstd import ZstdCodec +from zarr.core.codec_pipeline import FusedCodecPipeline +from zarr.core.config import config as zarr_config +from zarr.registry import register_codec +from zarr.storage import MemoryStore, StorePath, WrapperStore +from zarr.storage._utils import _normalize_byte_range_index +from zarr.testing.store import LatencyStore + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Callable, Iterable + + from zarr.abc.store import ByteRequest + from zarr.core.array_spec import ArraySpec + from zarr.core.buffer import Buffer, BufferPrototype, NDBuffer + + +@pytest.mark.parametrize( + "codecs", + [ + (BytesCodec(),), + (BytesCodec(), GzipCodec(level=1)), + (BytesCodec(), ZstdCodec(level=1)), + (TransposeCodec(order=(1, 0)), BytesCodec()), + (TransposeCodec(order=(1, 0)), BytesCodec(), ZstdCodec(level=1)), + ], + ids=["bytes-only", "gzip", "zstd", "transpose", "transpose+zstd"], +) +def test_construction(codecs: tuple[Any, ...]) -> None: + """FusedCodecPipeline can be constructed from valid codec combinations.""" + pipeline = FusedCodecPipeline.from_codecs(codecs) + assert pipeline.codecs == codecs + + +def test_sync_api_compute_off_event_loop(monkeypatch: pytest.MonkeyPatch) -> None: + """Codec compute must never run on the thread driving the event loop. + + Every sync-API call, from every user thread, is serviced by the one global + `zarr_io` event loop. Running decode/encode inline on that loop's thread + turns it into a mutex around codec compute: concurrent readers serialize, + and the penalty grows with codec cost (observed as "fused pipeline is + slower for zstd data" under dask-style multi-threaded single-chunk reads). + """ + import asyncio + + from zarr.core.chunk_utils import ChunkTransform + + compute_on_loop = {"decode": False, "encode": False} + calls = {"decode": 0, "encode": 0} + real_decode = ChunkTransform.decode_chunk + real_encode = ChunkTransform.encode_chunk + + def _running_loop() -> bool: + try: + asyncio.get_running_loop() + except RuntimeError: + return False + return True + + def traced_decode(self: ChunkTransform, chunk_bytes: Any, chunk_spec: Any) -> Any: + calls["decode"] += 1 + compute_on_loop["decode"] = compute_on_loop["decode"] or _running_loop() + return real_decode(self, chunk_bytes, chunk_spec) + + def traced_encode(self: ChunkTransform, chunk_array: Any, chunk_spec: Any) -> Any: + calls["encode"] += 1 + compute_on_loop["encode"] = compute_on_loop["encode"] or _running_loop() + return real_encode(self, chunk_array, chunk_spec) + + monkeypatch.setattr(ChunkTransform, "decode_chunk", traced_decode) + monkeypatch.setattr(ChunkTransform, "encode_chunk", traced_encode) + + with zarr_config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"}): + arr = zarr.create_array( + MemoryStore(), + shape=(8, 8), + chunks=(4, 4), + dtype="float64", + compressors=ZstdCodec(level=1), + ) + data = np.arange(64, dtype="float64").reshape(8, 8) + arr[:4, :4] = data[:4, :4] # single-chunk write (batch of 1) + arr[:] = data # multi-chunk write + # Guard against vacuity: if the sync fast path stops triggering, the + # traced ChunkTransform methods are never called (the async fallback + # uses AsyncChunkTransform) and the on-loop flags stay trivially False. + assert calls["encode"] > 0 + assert compute_on_loop["encode"] is False + + np.testing.assert_array_equal(arr[:4, :4], data[:4, :4]) # single-chunk read + np.testing.assert_array_equal(arr[:], data) # multi-chunk read + assert calls["decode"] > 0 + assert compute_on_loop["decode"] is False + + +def test_evolve_from_array_spec() -> None: + """evolve_from_array_spec creates a sync transform.""" + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.dtype import get_data_type_from_native_dtype + + pipeline = FusedCodecPipeline.from_codecs((BytesCodec(),)) + assert pipeline.sync_transform is None + + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + spec = ArraySpec( + shape=(100,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + evolved = pipeline.evolve_from_array_spec(spec) + assert evolved.sync_transform is not None + + +# --------------------------------------------------------------------------- +# Sync path tests +# +# These exercise FusedCodecPipeline's synchronous API (write_sync / read_sync / +# sync_transform), which has no equivalent on BatchedCodecPipeline -- so they +# cannot live in the pipeline-agnostic CodecPipelineTests suite. The async +# roundtrip / fill-value behaviour is covered there (test_scenario) across both +# pipelines and sync/async stores. +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("dtype", "shape"), + [ + ("float64", (100,)), + ("float32", (50,)), + ("int32", (200,)), + ("float64", (10, 10)), + ], + ids=["f64-1d", "f32-1d", "i32-1d", "f64-2d"], +) +def test_read_write_sync_roundtrip(dtype: str, shape: tuple[int, ...]) -> None: + """Data written via write_sync can be read back via read_sync.""" + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer + from zarr.core.dtype import get_data_type_from_native_dtype + + store = MemoryStore() + zdtype = get_data_type_from_native_dtype(np.dtype(dtype)) + spec = ArraySpec( + shape=shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + + pipeline = FusedCodecPipeline.from_codecs((BytesCodec(),)) + pipeline = pipeline.evolve_from_array_spec(spec) + + data = np.arange(int(np.prod(shape)), dtype=dtype).reshape(shape) + value = CPUNDBuffer.from_numpy_array(data) + chunk_selection = tuple(slice(0, s) for s in shape) + out_selection = chunk_selection + store_path = StorePath(store, "c/0") + + # Write sync + pipeline.write_sync( + [(store_path, spec, chunk_selection, out_selection, True)], + value, + ) + + # Read sync + out = CPUNDBuffer.from_numpy_array(np.zeros(shape, dtype=dtype)) + pipeline.read_sync( + [(store_path, spec, chunk_selection, out_selection, True)], + out, + ) + + np.testing.assert_array_equal(data, out.as_numpy_array()) + + +def test_read_sync_missing_chunk_fills() -> None: + """Sync read of a missing chunk fills with the fill value.""" + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer + from zarr.core.dtype import get_data_type_from_native_dtype + + store = MemoryStore() + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + spec = ArraySpec( + shape=(10,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(42.0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + + pipeline = FusedCodecPipeline.from_codecs((BytesCodec(),)) + pipeline = pipeline.evolve_from_array_spec(spec) + + out = CPUNDBuffer.from_numpy_array(np.zeros(10, dtype="float64")) + store_path = StorePath(store, "c/0") + chunk_sel = (slice(0, 10),) + + pipeline.read_sync( + [(store_path, spec, chunk_sel, chunk_sel, True)], + out, + ) + + np.testing.assert_array_equal(out.as_numpy_array(), np.full(10, 42.0)) + + +def test_sync_write_async_read_roundtrip() -> None: + """Data written via write_sync can be read back via async read.""" + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer + from zarr.core.dtype import get_data_type_from_native_dtype + from zarr.core.sync import sync + + store = MemoryStore() + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + spec = ArraySpec( + shape=(100,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + + pipeline = FusedCodecPipeline.from_codecs((BytesCodec(),)) + pipeline = pipeline.evolve_from_array_spec(spec) + + data = np.arange(100, dtype="float64") + value = CPUNDBuffer.from_numpy_array(data) + chunk_sel = (slice(0, 100),) + store_path = StorePath(store, "c/0") + + # Write sync + pipeline.write_sync( + [(store_path, spec, chunk_sel, chunk_sel, True)], + value, + ) + + # Read async + out = CPUNDBuffer.from_numpy_array(np.zeros(100, dtype="float64")) + sync( + pipeline.read( + [(store_path, spec, chunk_sel, chunk_sel, True)], + out, + ) + ) + + +def test_chunk_transform_uses_runtime_prototype() -> None: + """ChunkTransform must pass each codec the prototype from the runtime chunk_spec, + not one captured at evolve time. Constructs ChunkTransform directly (a + Fused-internal data structure with no BatchedCodecPipeline equivalent). + """ + from zarr.abc.codec import BytesBytesCodec + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import BufferPrototype, default_buffer_prototype + from zarr.core.chunk_utils import ChunkTransform + from zarr.core.dtype import get_data_type_from_native_dtype + + class _PrototypeRecordingCodec(BytesBytesCodec): # type: ignore[misc,unused-ignore] + """A no-op BB codec that records the prototype it was called with.""" + + is_fixed_size = True + seen_prototypes: list[object] + + def __init__(self) -> None: + object.__setattr__(self, "seen_prototypes", []) + + def to_dict(self) -> dict[str, Any]: + return {"name": "_prototype_recording", "configuration": {}} + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> _PrototypeRecordingCodec: + return cls() + + def compute_encoded_size(self, input_byte_length: int, _spec: ArraySpec) -> int: + return input_byte_length + + def _encode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer | None: + self.seen_prototypes.append(chunk_spec.prototype) + return chunk_bytes + + def _decode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + self.seen_prototypes.append(chunk_spec.prototype) + return chunk_bytes + + async def _encode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer | None: + return self._encode_sync(chunk_bytes, chunk_spec) + + async def _decode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return self._decode_sync(chunk_bytes, chunk_spec) + + recording = _PrototypeRecordingCodec() + transform = ChunkTransform(codecs=(BytesCodec(), recording)) + + zdtype = get_data_type_from_native_dtype(np.dtype("float64")) + + def _spec(prototype: BufferPrototype) -> ArraySpec: + return ArraySpec( + shape=(10,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0.0), + config=ArrayConfig(order="C", write_empty_chunks=False), + prototype=prototype, + ) + + proto_default = default_buffer_prototype() + # A distinct BufferPrototype instance with the same buffer/nd_buffer types -- + # fails an identity check but works at runtime. + proto_other = BufferPrototype(buffer=proto_default.buffer, nd_buffer=proto_default.nd_buffer) + assert proto_other is not proto_default + + arr = proto_default.nd_buffer.from_numpy_array(np.arange(10, dtype="float64")) + transform.encode_chunk(arr, _spec(proto_default)) + transform.encode_chunk(arr, _spec(proto_other)) + + assert recording.seen_prototypes[0] is proto_default + assert recording.seen_prototypes[1] is proto_other, ( + "ChunkTransform did not pass the runtime prototype to the codec" + ) + + +# --------------------------------------------------------------------------- +# Thread-pool (max_workers > 1) tests +# +# The pool dispatch in read_sync/write_sync is Fused-only and off by default +# (codec_pipeline.max_workers defaults to 1 == sequential). These tests opt in +# and exercise the pool path end-to-end, exception propagation from workers, +# and concurrent decode through the shared ChunkTransform. +# --------------------------------------------------------------------------- + +_FUSED_POOL_CONFIG = { + "codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline", + "codec_pipeline.max_workers": 4, +} + + +def test_read_write_with_thread_pool() -> None: + """With max_workers > 1, multi-chunk reads and writes dispatch through the + thread pool (pool.map in read_sync/write_sync) and produce the same results + as sequential execution. + + The `_get_pool` spy pins that the pool branch actually fires: without it, + a config-resolution regression (renamed key, `_resolve_max_workers` + returning 1) would silently degrade all the pool tests into re-testing the + sequential branch while staying green. + """ + from unittest.mock import patch + + import zarr.core.codec_pipeline as cp_mod + + with zarr_config.set(_FUSED_POOL_CONFIG): + assert cp_mod._resolve_max_workers() == 4, ( + "codec_pipeline.max_workers config did not reach _resolve_max_workers" + ) + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(100,), + chunks=(10,), + dtype="float64", + compressors=None, + fill_value=0.0, + ) + assert isinstance(arr._async_array.codec_pipeline, FusedCodecPipeline) + data = np.arange(100, dtype="float64") + with patch.object(cp_mod, "_get_pool", wraps=cp_mod._get_pool) as pool_spy: + arr[:] = data # 10 chunks -> pool dispatch in write_sync + assert pool_spy.call_count >= 1, "multi-chunk write did not take the pool branch" + writes = pool_spy.call_count + np.testing.assert_array_equal(arr[:], data) # pool dispatch in read_sync + assert pool_spy.call_count > writes, "multi-chunk read did not take the pool branch" + arr[5:25] = 7.0 # partial write: merge path through the pool + data[5:25] = 7.0 + np.testing.assert_array_equal(arr[:], data) + + +def test_thread_pool_write_worker_exception_propagates() -> None: + """A store error raised inside a pool worker during write_sync surfaces to + the caller (write_sync consumes pool.map, so worker exceptions re-raise).""" + from unittest.mock import patch + + with zarr_config.set(_FUSED_POOL_CONFIG): + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(100,), + chunks=(10,), + dtype="float64", + compressors=None, + fill_value=0.0, + ) + with ( + patch.object(store, "set_sync", side_effect=RuntimeError("simulated store error")), + pytest.raises(RuntimeError, match="simulated store error"), + ): + arr[:] = np.arange(100, dtype="float64") + + +def test_thread_pool_read_worker_exception_propagates() -> None: + """A store error raised inside a pool worker during read_sync surfaces to + the caller (read_sync consumes pool.map into a tuple).""" + from unittest.mock import patch + + with zarr_config.set(_FUSED_POOL_CONFIG): + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(100,), + chunks=(10,), + dtype="float64", + compressors=None, + fill_value=0.0, + ) + arr[:] = np.arange(100, dtype="float64") + with ( + patch.object(store, "get_sync", side_effect=RuntimeError("simulated store error")), + pytest.raises(RuntimeError, match="simulated store error"), + ): + arr[:] + + +def test_resolve_max_workers_warns_and_falls_back_on_invalid_config() -> None: + """`codec_pipeline.max_workers` arrives via the config/env layer (e.g. + `ZARR_CODEC_PIPELINE__MAX_WORKERS`), so garbage input should warn and fall + back to the default rather than raising mid-read. + """ + import os + + import zarr.core.codec_pipeline as cp_mod + from zarr.errors import ZarrUserWarning + + default = os.cpu_count() or 1 + with zarr_config.set({"codec_pipeline.max_workers": "fast"}): + with pytest.warns(ZarrUserWarning, match="max_workers"): + result = cp_mod._resolve_max_workers() + assert result == default + + +async def test_encode_and_write_as_completed_cancels_stray_writes_on_failure() -> None: + """A failing write must not leave sibling writes running in the background. + + `_encode_and_write_as_completed` fires one write task per chunk as soon as + its encode completes, then `gather`s them. Plain `gather` (without + `return_exceptions=True`) re-raises the first exception without cancelling + the other in-flight tasks, so a still-running write would keep going after + the caller has already seen the exception -- and its eventual outcome is + never retrieved (an unraisable "Task exception was never retrieved" + warning if it later fails). + """ + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer + from zarr.core.chunk_utils import ChunkTransform + from zarr.core.codec_pipeline import _encode_and_write_as_completed + from zarr.core.dtype import get_data_type_from_native_dtype + + write_started = asyncio.Event() + write_finished = False + + class _SlowByteSetter: + async def get( + self, prototype: BufferPrototype, byte_range: ByteRequest | None = None + ) -> Buffer | None: + return None + + async def set(self, value: Buffer) -> None: + nonlocal write_finished + write_started.set() + await asyncio.sleep(0.2) + write_finished = True + + async def delete(self) -> None: + pass + + async def set_if_not_exists(self, default: Buffer) -> None: + pass + + class _FailingByteSetter: + async def get( + self, prototype: BufferPrototype, byte_range: ByteRequest | None = None + ) -> Buffer | None: + return None + + async def set(self, value: Buffer) -> None: + raise RuntimeError("simulated write failure") + + async def delete(self) -> None: + pass + + async def set_if_not_exists(self, default: Buffer) -> None: + pass + + zdtype = get_data_type_from_native_dtype(np.dtype("uint8")) + chunk_spec = ArraySpec( + shape=(1,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + chunk_array = CPUNDBuffer.from_numpy_array(np.zeros(1, dtype="uint8")) + transform = ChunkTransform(codecs=(BytesCodec(),)) + + batch = [ + (_SlowByteSetter(), chunk_array, chunk_spec), + (_FailingByteSetter(), chunk_array, chunk_spec), + ] + + with pytest.raises(RuntimeError, match="simulated write failure"): + await _encode_and_write_as_completed(batch, transform) # type: ignore[arg-type] + + assert write_started.is_set() + # Give the slow write's sleep long enough to finish if it were left + # running unattended in the background instead of being cancelled. + await asyncio.sleep(0.3) + assert not write_finished, "the slow write should have been cancelled, not left running" + + +def test_concurrent_reads_shared_transform_with_pool() -> None: + """Concurrent decode through the shared ChunkTransform produces correct data. + + The transform's `_resolve_specs` cache is shared mutable state. With no + array->array codecs the cache is bypassed entirely, so this uses a transpose + filter to force cache traffic, max_workers=4 so pool workers decode chunks + concurrently, and an outer thread pool so multiple reads are in flight at + once. Each round RE-OPENS the array so the shared transform starts with a + cold spec cache and the concurrent readers race the non-atomic first fill β€” + reading through a single pre-warmed handle would only ever exercise cache + hits. This pins correctness under concurrency (it cannot prove the absence + of a race, but a torn cache would corrupt results here). + """ + from concurrent.futures import ThreadPoolExecutor + + with zarr_config.set(_FUSED_POOL_CONFIG): + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(40, 40), + chunks=(5, 5), + dtype="int32", + filters=[TransposeCodec(order=(1, 0))], + serializer=BytesCodec(), + compressors=None, + fill_value=-1, + ) + data = np.arange(1600, dtype="int32").reshape(40, 40) + arr[:] = data + + for _ in range(5): # several rounds, each racing a cold cache + fresh = zarr.open_array(store=store, mode="r") + + def read_row_block(i: int, handle: zarr.Array[Any] = fresh) -> np.ndarray: + return np.asarray(handle[i * 4 : (i + 1) * 4, :]) + + with ThreadPoolExecutor(max_workers=8) as ex: + futures = {ex.submit(read_row_block, i): i for i in range(10)} + for fut, i in futures.items(): + np.testing.assert_array_equal(fut.result(), data[i * 4 : (i + 1) * 4, :]) + + +def test_shared_transform_decode_alternating_specs() -> None: + """A single ChunkTransform must decode chunks of DIFFERENT specs correctly + when calls alternate, exercising eviction/refill of its single-entry + `_resolve_specs` cache. + + The two specs differ in shape, so each call evicts the other's cached entry. + A transpose filter forces the cache to be used (with no AA codec the cache is + bypassed). The cache entry is stored as one atomic tuple precisely so a + concurrent reader can never observe a key paired with another spec's resolved + chain; this test pins the sequential eviction/refill correctness that + underpins that guarantee. (The concurrent counterpart is + `test_concurrent_reads_shared_transform_with_pool`.) + """ + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer + from zarr.core.chunk_utils import ChunkTransform + from zarr.core.dtype import get_data_type_from_native_dtype + + def _spec(shape: tuple[int, ...]) -> ArraySpec: + zdtype = get_data_type_from_native_dtype(np.dtype("int32")) + return ArraySpec( + shape=shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + + transform = ChunkTransform(codecs=(TransposeCodec(order=(1, 0)), BytesCodec())) + + # two distinct specs (different shapes) sharing the one transform + cache slot + cases = [] + for shape in [(5, 7), (3, 11)]: + spec = _spec(shape) + arr = np.arange(int(np.prod(shape)), dtype="int32").reshape(shape) + encoded = transform.encode_chunk(CPUNDBuffer.from_numpy_array(arr), spec) + assert encoded is not None + cases.append((spec, encoded, arr)) + + # Alternate specs so every call evicts and refills the single cache slot. + for i in range(20): + spec, encoded, expected = cases[i % len(cases)] + got = transform.decode_chunk(encoded, spec).as_numpy_array() + np.testing.assert_array_equal(got, expected) + + +def test_sharded_fallback_inner_chunks_avoid_async_transform() -> None: + """Inner chunks of a shard on a NON-sync store decode through the sync + ChunkTransform, not per-chunk AsyncChunkTransform coroutines. + + The sharding byte getters are in-memory dict wrappers; they implement + SyncByteGetter/SyncByteSetter, and the nested inner pipeline is evolved + (so its sync transform exists), letting the nested read/write take the + sync fast path. Without this, every inner chunk pays a coroutine for a + dict lookup plus an async per-chunk transform β€” measured at 1.5x (raw) to + 3.6x (gzip) of sharded fallback read time. + """ + from unittest.mock import patch + + from zarr.core.codec_pipeline import AsyncChunkTransform + from zarr.testing.store import LatencyStore + + calls = {"decode": 0, "encode": 0} + orig_decode = AsyncChunkTransform.decode_chunk + orig_encode = AsyncChunkTransform.encode_chunk + + async def spy_decode(self: Any, *args: Any, **kwargs: Any) -> Any: + calls["decode"] += 1 + return await orig_decode(self, *args, **kwargs) + + async def spy_encode(self: Any, *args: Any, **kwargs: Any) -> Any: + calls["encode"] += 1 + return await orig_encode(self, *args, **kwargs) + + # LatencyStore is not sync-capable -> the OUTER pipeline takes the async + # fallback; the INNER chunks go over the sharding byte getters. + store = LatencyStore(MemoryStore(), get_latency=0.0, set_latency=0.0) + arr = zarr.create_array( + store=store, + shape=(100,), + chunks=(10,), + shards=(50,), + dtype="uint8", + compressors=None, + fill_value=0, + ) + if not isinstance(arr._async_array.codec_pipeline, FusedCodecPipeline): + pytest.skip("sync fast path for inner chunks is specific to FusedCodecPipeline") + + data = np.arange(100, dtype="uint8") + sync_calls = {"read_sync": 0} + orig_read_sync = FusedCodecPipeline.read_sync + + def spy_read_sync(self: Any, *args: Any, **kwargs: Any) -> Any: + sync_calls["read_sync"] += 1 + return orig_read_sync(self, *args, **kwargs) + + with ( + patch.object(AsyncChunkTransform, "decode_chunk", spy_decode), + patch.object(AsyncChunkTransform, "encode_chunk", spy_encode), + patch.object(FusedCodecPipeline, "read_sync", spy_read_sync), + ): + arr[:] = data + out = np.asarray(arr[:]) + + np.testing.assert_array_equal(out, data) + assert calls == {"decode": 0, "encode": 0}, ( + f"inner chunks went through per-chunk AsyncChunkTransform coroutines: {calls}" + ) + # The outer store is not sync-capable, so any read_sync calls are the + # NESTED pipeline taking the sync fast path over the sharding byte getters + # (the SyncByteGetter gate). Without the gate, inner chunks go through + # concurrent_map with one coroutine per chunk. (Writes don't appear here: + # the fallback write encodes whole shards through the outer sync transform + # -> ShardingCodec._encode_sync, never touching the nested byte setters.) + assert sync_calls["read_sync"] >= 1, "nested read did not take the sync fast path" + + +def test_write_over_sync_byte_setter_takes_sync_path() -> None: + """`FusedCodecPipeline.write` routes a non-StorePath `SyncByteSetter` (the + sharding codec's `_ShardingByteSetter`) through `write_sync`. + + This is the write-side twin of the SyncByteGetter gate: the read test + above cannot guard it because fallback whole-array writes encode shards + via `_encode_sync` and never touch the nested byte setters. The nested + `write` over `_ShardingByteSetter` is reached from the async shard encode + paths (`_encode_single`/`_encode_partial_single`), so pin the gate + directly: without it, this write degrades to the async fallback (one + coroutine per inner chunk for an in-memory dict store). + """ + import asyncio + from unittest.mock import patch + + from zarr.codecs.sharding import _ShardingByteSetter + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.dtype import get_data_type_from_native_dtype + + zdtype = get_data_type_from_native_dtype(np.dtype("uint8")) + spec = ArraySpec( + shape=(10,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + pipeline = FusedCodecPipeline.from_codecs([BytesCodec()]).evolve_from_array_spec(spec) + assert pipeline.sync_transform is not None + + shard_dict: dict[tuple[int, ...], Any] = {} + setter = _ShardingByteSetter(shard_dict, (0,)) + value = default_buffer_prototype().nd_buffer.from_numpy_array(np.arange(10, dtype="uint8")) + + sync_calls = {"write_sync": 0} + orig_write_sync = FusedCodecPipeline.write_sync + + def spy_write_sync(self: Any, *args: Any, **kwargs: Any) -> Any: + sync_calls["write_sync"] += 1 + return orig_write_sync(self, *args, **kwargs) + + sel = (slice(0, 10),) + with patch.object(FusedCodecPipeline, "write_sync", spy_write_sync): + asyncio.run(pipeline.write([(setter, spec, sel, sel, True)], value)) + + assert sync_calls["write_sync"] >= 1, ( + "write over a SyncByteSetter did not take the sync fast path" + ) + written = shard_dict[(0,)] + np.testing.assert_array_equal( + np.frombuffer(written.to_bytes(), dtype="uint8"), np.arange(10, dtype="uint8") + ) + + +# --------------------------------------------------------------------------- +# Async-only codecs inside a shard's inner codec chain +# --------------------------------------------------------------------------- + + +class _AsyncOnlyNoopCodec(BytesBytesCodec): # type: ignore[misc,unused-ignore] + """A no-op BB codec implementing ONLY the async codec interface. + + Deliberately does NOT satisfy `SupportsSyncCodec` (no `_decode_sync` / + `_encode_sync`), modelling a third-party codec that predates the sync + protocol. Class-level counters prove the codec actually ran. + """ + + is_fixed_size = True + encode_calls = 0 + decode_calls = 0 + + def to_dict(self) -> dict[str, Any]: + return {"name": "test-async-only-noop", "configuration": {}} + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> _AsyncOnlyNoopCodec: + return cls() + + def compute_encoded_size(self, input_byte_length: int, _spec: Any) -> int: + return input_byte_length + + async def _encode_single(self, chunk_bytes: Any, chunk_spec: Any) -> Any: + type(self).encode_calls += 1 + return chunk_bytes + + async def _decode_single(self, chunk_bytes: Any, chunk_spec: Any) -> Any: + type(self).decode_calls += 1 + return chunk_bytes + + +def test_sharded_roundtrip_with_async_only_inner_codec() -> None: + """A sharded array whose INNER codec chain contains an async-only codec + round-trips under FusedCodecPipeline (full write, partial write, full read, + partial read). + + Regression: the pipeline's top-level guard (evolve_from_array_spec -> + sync_transform=None) only inspected the top-level chain. ShardingCodec + structurally satisfies SupportsSyncCodec, so a sync transform was built and + the sync fast path dove into ShardingCodec's sync shard paths, which raised + TypeError from the inner ChunkTransform. The pipeline must instead decline + the sync fast path and fall back to the async inner pipeline, like + BatchedCodecPipeline. + """ + _AsyncOnlyNoopCodec.encode_calls = 0 + _AsyncOnlyNoopCodec.decode_calls = 0 + + with zarr_config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"}): + store = MemoryStore() + arr = zarr.create_array( + store=store, + shape=(16, 16), + shards=(8, 8), + chunks=(4, 4), + dtype="int32", + compressors=[_AsyncOnlyNoopCodec()], + fill_value=-1, + ) + assert isinstance(arr._async_array.codec_pipeline, FusedCodecPipeline) + + data = np.arange(256, dtype="int32").reshape(16, 16) + arr[:] = data # full write + np.testing.assert_array_equal(arr[:], data) # full read + np.testing.assert_array_equal(arr[2:11, 3:14], data[2:11, 3:14]) # partial read + + arr[5:7, 5:13] = 0 # partial write (read-merge-write of existing shards) + data[5:7, 5:13] = 0 + np.testing.assert_array_equal(arr[:], data) + + assert _AsyncOnlyNoopCodec.encode_calls > 0, "async-only inner codec never encoded" + assert _AsyncOnlyNoopCodec.decode_calls > 0, "async-only inner codec never decoded" + + # The stored bytes are valid for the default pipeline too: read them back + # under BatchedCodecPipeline (default codec_pipeline.path). Opening from + # metadata needs the codec name in the registry. + from zarr.registry import register_codec + + register_codec("test-async-only-noop", _AsyncOnlyNoopCodec) + reread = zarr.open_array(store=store, mode="r") + np.testing.assert_array_equal(reread[:], data) + + +# --------------------------------------------------------------------------- +# AsyncChunkTransform: the async per-chunk codec chain used on the async +# fallback path. It is the async mirror of ChunkTransform, so it must produce +# identical bytes/arrays. The default (Fused, sync-store) path never uses it; +# these tests drive it directly over multi-codec chains so the aa/bb loops and +# the all-fill drop branch are exercised. +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "codecs", + [ + (BytesCodec(),), + (BytesCodec(), GzipCodec(level=1)), + (TransposeCodec(order=(1, 0)), BytesCodec()), + (TransposeCodec(order=(1, 0)), BytesCodec(), ZstdCodec(level=1)), + ], + ids=["bytes-only", "bb", "aa", "aa+ab+bb"], +) +def test_async_chunk_transform_matches_sync(codecs: tuple[Any, ...]) -> None: + """`AsyncChunkTransform.decode_chunk`/`encode_chunk` must round-trip and + produce exactly what the synchronous `ChunkTransform` produces, across + array->array, array->bytes, and bytes->bytes codec combinations. + + This is the async mirror of the codecs the default pipeline runs + synchronously; a divergence here corrupts data only on the async fallback + path (remote stores), which no end-to-end test of the default pipeline + touches. + """ + import asyncio + + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer + from zarr.core.chunk_utils import ChunkTransform, evolve_codecs + from zarr.core.codec_pipeline import AsyncChunkTransform + from zarr.core.dtype import get_data_type_from_native_dtype + + shape = (4, 4) + zdtype = get_data_type_from_native_dtype(np.dtype("int32")) + spec = ArraySpec( + shape=shape, + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + evolved = evolve_codecs(codecs, spec) + sync_t = ChunkTransform(codecs=evolved) + async_t = AsyncChunkTransform(codecs=evolved) + + data = np.arange(16, dtype="int32").reshape(shape) + value = CPUNDBuffer.from_numpy_array(data) + + sync_bytes = sync_t.encode_chunk(value, spec) + async_bytes = asyncio.run(async_t.encode_chunk(value, spec)) + assert sync_bytes is not None + assert async_bytes is not None + np.testing.assert_array_equal(async_bytes.to_bytes(), sync_bytes.to_bytes()) + + sync_arr = sync_t.decode_chunk(async_bytes, spec) + async_arr = asyncio.run(async_t.decode_chunk(async_bytes, spec)) + np.testing.assert_array_equal(async_arr.as_numpy_array(), sync_arr.as_numpy_array()) + np.testing.assert_array_equal(async_arr.as_numpy_array(), data) + + +def test_async_decode_encode_passes_through_none_chunks() -> None: + """`FusedCodecPipeline.decode`/`encode` (the async batch entry points used + on the fallback path) map a None chunk to None and leave real chunks + untouched β€” pins the None-passthrough branch the default sync path skips.""" + import asyncio + + from zarr.core.array_spec import ArrayConfig, ArraySpec + from zarr.core.buffer import default_buffer_prototype + from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer + from zarr.core.dtype import get_data_type_from_native_dtype + + zdtype = get_data_type_from_native_dtype(np.dtype("int32")) + spec = ArraySpec( + shape=(4,), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig(order="C", write_empty_chunks=True), + prototype=default_buffer_prototype(), + ) + pipeline = FusedCodecPipeline.from_codecs([BytesCodec()]).evolve_from_array_spec(spec) + + data = np.arange(4, dtype="int32") + value = CPUNDBuffer.from_numpy_array(data) + + # encode a real chunk and a None chunk together + encoded = list(asyncio.run(pipeline.encode([(value, spec), (None, spec)]))) + assert encoded[1] is None + assert encoded[0] is not None + + # decode the real chunk and a None chunk together + decoded = list(asyncio.run(pipeline.decode([(encoded[0], spec), (None, spec)]))) + assert decoded[1] is None + assert decoded[0] is not None + np.testing.assert_array_equal(decoded[0].as_numpy_array(), data) + + +# --------------------------------------------------------------------------- +# Graceful fallback for partial-mixin codecs without private sync-partial hooks +# +# The public partial-decode/encode contract (`ArrayBytesCodecPartialDecodeMixin` +# / `ArrayBytesCodecPartialEncodeMixin`) only requires the async +# `_decode_partial_single` / `_encode_partial_single`. The fused pipeline must +# route such codecs through its full-chunk sync path instead of asserting on +# the private `_decode_partial_sync` / `_encode_partial_sync` hooks. The double +# below is a minimal conforming implementer of that contract; it guards the +# public extension API, so it must not grow the private sync-partial methods. +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class PartialMixinCodec( + ArrayBytesCodec, ArrayBytesCodecPartialDecodeMixin, ArrayBytesCodecPartialEncodeMixin +): + """Serializer with sync whole-chunk methods plus ONLY async partial methods. + + This is the pre-fused public contract for partial-capable codecs: the + mixins' `_decode_partial_single` / `_encode_partial_single`. It must not + implement `_decode_partial_sync` / `_encode_partial_sync`. + """ + + inner: BytesCodec = field(default_factory=BytesCodec) + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> PartialMixinCodec: + return cls() + + def to_dict(self) -> dict[str, Any]: + return {"name": "test-partial-mixin"} + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> PartialMixinCodec: + return replace(self, inner=self.inner.evolve_from_array_spec(array_spec)) + + def compute_encoded_size(self, input_byte_length: int, chunk_spec: ArraySpec) -> int: + return self.inner.compute_encoded_size(input_byte_length, chunk_spec) + + def _decode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> NDBuffer: + return self.inner._decode_sync(chunk_bytes, chunk_spec) + + def _encode_sync(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer | None: + return self.inner._encode_sync(chunk_array, chunk_spec) + + async def _decode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> NDBuffer: + return self._decode_sync(chunk_bytes, chunk_spec) + + async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer | None: + return self._encode_sync(chunk_array, chunk_spec) + + async def _decode_partial_single( + self, byte_getter: Any, selection: Any, chunk_spec: ArraySpec + ) -> NDBuffer | None: + chunk_bytes = await byte_getter.get(prototype=chunk_spec.prototype) + if chunk_bytes is None: + return None + return self._decode_sync(chunk_bytes, chunk_spec)[selection] + + async def _encode_partial_single( + self, byte_setter: Any, chunk_array: NDBuffer, selection: Any, chunk_spec: ArraySpec + ) -> None: + existing = await byte_setter.get(prototype=chunk_spec.prototype) + if existing is None: + full = chunk_spec.prototype.nd_buffer.create( + shape=chunk_spec.shape, + dtype=chunk_spec.dtype.to_native_dtype(), + fill_value=chunk_spec.fill_value, + ) + else: + full = self._decode_sync(existing, chunk_spec) + full[selection] = chunk_array + encoded = self._encode_sync(full, chunk_spec) + assert encoded is not None + await byte_setter.set(encoded) + + +register_codec("test-partial-mixin", PartialMixinCodec) + +_FUSED = {"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"} +_BATCHED = {"codec_pipeline.path": "zarr.core.codec_pipeline.BatchedCodecPipeline"} + + +@pytest.mark.filterwarnings("ignore::zarr.errors.UnstableSpecificationWarning") +@pytest.mark.parametrize("dtype", ["uint8", "float64"]) +def test_partial_mixin_codec_async_partial_only_round_trip(dtype: str) -> None: + """A serializer advertising the partial mixins with only async partial + methods must round-trip under the fused pipeline: full write, full read, + partial read, partial write, plus cross-pipeline parity with + BatchedCodecPipeline.""" + data = np.arange(64, dtype=dtype).reshape(8, 8) + + with zarr_config.set(_FUSED): + store = MemoryStore() + arr = zarr.create_array( + store, + shape=(8, 8), + chunks=(4, 4), + dtype=dtype, + serializer=PartialMixinCodec(), + compressors=None, + filters=None, + fill_value=0, + ) + + pipeline = arr._async_array.codec_pipeline + assert isinstance(pipeline, FusedCodecPipeline) + assert pipeline.supports_partial_decode + assert pipeline.supports_partial_encode + assert pipeline.sync_transform is not None + + arr[:] = data + np.testing.assert_array_equal(arr[:], data) + np.testing.assert_array_equal(arr[1:5, 2:7], data[1:5, 2:7]) + + expected = data.copy() + expected[2:6, 1:3] = 7 + arr[2:6, 1:3] = expected[2:6, 1:3] + np.testing.assert_array_equal(arr[:], expected) + + with zarr_config.set(_BATCHED): + np.testing.assert_array_equal(zarr.open_array(store, mode="r")[:], expected) + + +# Sync-IO capability gating (`zarr.abc.store._store_supports_sync_io`) +# +# The fused read/write fast paths must engage iff the store advertises the +# FULL synchronous IO surface (get_sync + set_sync + delete_sync): write_sync +# needs get_sync for partial-chunk read-modify-write and delete_sync for +# all-fill chunk cleanup, so gating on any single protocol can crash +# mid-batch. Wrappers must forward the capability of the wrapped store. +# --------------------------------------------------------------------------- + + +class AsyncOnlyStore(Store): + """Dict-backed store implementing only the async `Store` surface (no `*_sync`).""" + + def __init__(self) -> None: + super().__init__(read_only=False) + self._data: dict[str, Buffer] = {} + + def __eq__(self, other: object) -> bool: + return other is self + + @property + def supports_writes(self) -> bool: + return True + + @property + def supports_deletes(self) -> bool: + return True + + @property + def supports_listing(self) -> bool: + return True + + async def get( + self, key: str, prototype: BufferPrototype, byte_range: ByteRequest | None = None + ) -> Buffer | None: + try: + value = self._data[key] + except KeyError: + return None + start, stop = _normalize_byte_range_index(value, byte_range) + return prototype.buffer.from_buffer(value[start:stop]) + + async def get_partial_values( + self, + prototype: BufferPrototype, + key_ranges: Iterable[tuple[str, ByteRequest | None]], + ) -> list[Buffer | None]: + return [await self.get(key, prototype, byte_range) for key, byte_range in key_ranges] + + async def exists(self, key: str) -> bool: + return key in self._data + + async def set(self, key: str, value: Buffer) -> None: + self._check_writable() + self._data[key] = value + + async def delete(self, key: str) -> None: + self._check_writable() + self._data.pop(key, None) + + async def list(self) -> AsyncIterator[str]: + for key in list(self._data): + yield key + + async def list_prefix(self, prefix: str) -> AsyncIterator[str]: + for key in list(self._data): + if key.startswith(prefix): + yield key + + async def list_dir(self, prefix: str) -> AsyncIterator[str]: + if prefix and not prefix.endswith("/"): + prefix += "/" + seen: set[str] = set() + for key in list(self._data): + if key.startswith(prefix): + head = key.removeprefix(prefix).split("/")[0] + if head not in seen: + seen.add(head) + yield head + + +class SetOnlySyncStore(AsyncOnlyStore): + """Implements `set_sync` but not `get_sync`/`delete_sync` (partial sync surface).""" + + def set_sync(self, key: str, value: Buffer) -> None: + self._check_writable() + self._data[key] = value + + +@pytest.mark.parametrize( + ("store_factory", "expect_sync_path"), + [ + (MemoryStore, True), + (lambda: WrapperStore(MemoryStore()), True), + (lambda: LatencyStore(MemoryStore()), True), + (SetOnlySyncStore, False), + (lambda: WrapperStore(AsyncOnlyStore()), False), + ], + ids=[ + "full-sync", + "wrapper-of-sync", + "latency-wrapper-of-sync", + "set-sync-only", + "wrapper-of-async-only", + ], +) +def test_sync_io_capability_gates_fused_paths( + store_factory: Callable[[], Store], expect_sync_path: bool +) -> None: + """The fused pipeline takes the sync fast path iff the store satisfies + `_store_supports_sync_io`, + and every store round-trips correctly through full writes, partial + (read-modify-write) writes, and all-fill (delete) writes β€” a store with a + partial sync surface must get a clean async fallback, never a mid-batch + error.""" + from unittest.mock import patch + + store = store_factory() + assert _store_supports_sync_io(store) is expect_sync_path + + calls = {"read_sync": 0, "write_sync": 0} + orig_read_sync = FusedCodecPipeline.read_sync + orig_write_sync = FusedCodecPipeline.write_sync + + def spy_read_sync(self: FusedCodecPipeline, *args: Any, **kwargs: Any) -> Any: + calls["read_sync"] += 1 + return orig_read_sync(self, *args, **kwargs) + + def spy_write_sync(self: FusedCodecPipeline, *args: Any, **kwargs: Any) -> Any: + calls["write_sync"] += 1 + return orig_write_sync(self, *args, **kwargs) + + with zarr_config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"}): + arr = zarr.create_array( + store=store, + shape=(8,), + chunks=(4,), + dtype="uint8", + compressors=None, + fill_value=0, + ) + assert isinstance(arr._async_array.codec_pipeline, FusedCodecPipeline) + with ( + patch.object(FusedCodecPipeline, "read_sync", spy_read_sync), + patch.object(FusedCodecPipeline, "write_sync", spy_write_sync), + ): + data = np.arange(8, dtype="uint8") + arr[:] = data # complete-chunk writes + arr[:3] = 7 # partial write -> read-modify-write needs get + data[:3] = 7 + np.testing.assert_array_equal(arr[:], data) + arr[4:8] = 0 # all-fill chunk -> delete needed + data[4:8] = 0 + np.testing.assert_array_equal(arr[:], data) + + if expect_sync_path: + assert calls["write_sync"] > 0, "sync-capable store did not take the sync write path" + assert calls["read_sync"] > 0, "sync-capable store did not take the sync read path" + else: + assert calls["write_sync"] == 0, "non-sync store took the sync write path" + assert calls["read_sync"] == 0, "non-sync store took the sync read path" diff --git a/tests/test_group.py b/tests/test_group.py new file mode 100644 index 0000000000..f7f2333ef5 --- /dev/null +++ b/tests/test_group.py @@ -0,0 +1,2363 @@ +from __future__ import annotations + +import contextlib +import inspect +import json +import operator +import pickle +import re +import time +import warnings +from typing import TYPE_CHECKING, Any, Literal, get_args + +import numpy as np +import pytest +from numcodecs import Blosc + +import zarr +import zarr.api.asynchronous +import zarr.api.synchronous +import zarr.storage +from zarr import Array, AsyncArray, AsyncGroup, Group +from zarr.abc.store import Store +from zarr.core import sync_group +from zarr.core._info import GroupInfo +from zarr.core.buffer import default_buffer_prototype +from zarr.core.config import config as zarr_config +from zarr.core.dtype import Float64, Int32 +from zarr.core.dtype.common import unpack_dtype_json +from zarr.core.dtype.npy.int import UInt8 +from zarr.core.group import ( + ConsolidatedMetadata, + GroupMetadata, + ImplicitGroupMarker, + _build_metadata_v3, + _get_roots, + _parse_hierarchy_dict, + create_hierarchy, + create_nodes, + create_rooted_hierarchy, + get_node, +) +from zarr.core.metadata.v3 import ArrayV3Metadata +from zarr.core.sync import _collect_aiterator, sync +from zarr.errors import ( + ArrayNotFoundError, + ContainsArrayError, + ContainsGroupError, + GroupNotFoundError, + MetadataValidationError, + ZarrUserWarning, +) +from zarr.storage import LocalStore, MemoryStore, StorePath, ZipStore +from zarr.storage._common import make_store_path +from zarr.storage._utils import _join_paths, normalize_path +from zarr.testing.store import LatencyStore + +from .conftest import meta_from_array, parse_store + +if TYPE_CHECKING: + import pathlib + from collections.abc import Callable + + from zarr.core.buffer.core import Buffer + from zarr.core.common import JSON, ZarrFormat + from zarr.core.dtype import ZDType, ZDTypeLike + + +@pytest.fixture(params=["local", "memory", "zip"]) +async def store(request: pytest.FixtureRequest, tmp_path: pathlib.Path) -> Store: + result = await parse_store(request.param, str(tmp_path)) + if not isinstance(result, Store): + raise TypeError(f"Wrong store class returned by test fixture! got {result} instead") + return result + + +@pytest.fixture(params=[True, False]) +def overwrite(request: pytest.FixtureRequest) -> bool: + result = request.param + if not isinstance(result, bool): + raise TypeError("Wrong type returned by test fixture.") + return result + + +def test_group_init(store: Store, zarr_format: ZarrFormat) -> None: + """ + Test that initializing a group from an asyncgroup works. + """ + agroup = sync(AsyncGroup.from_store(store=store, zarr_format=zarr_format)) + group = Group(agroup) + assert group._async_group == agroup + + +async def test_create_creates_parents(store: Store, zarr_format: ZarrFormat) -> None: + # prepare a root node, with some data set + await zarr.api.asynchronous.open_group( + store=store, path="a", zarr_format=zarr_format, attributes={"key": "value"} + ) + objs = {x async for x in store.list()} + if zarr_format == 2: + assert objs == {".zgroup", ".zattrs", "a/.zgroup", "a/.zattrs"} + else: + assert objs == {"zarr.json", "a/zarr.json"} + + # test that root group node was created + root = await zarr.api.asynchronous.open_group( + store=store, + ) + agroup = await root.get_group("a") + assert agroup.attrs == {"key": "value"} + + # create a child node with a couple intermediates + await zarr.api.asynchronous.open_group(store=store, path="a/b/c/d", zarr_format=zarr_format) + parts = ["a", "a/b", "a/b/c"] + + if zarr_format == 2: + files = [".zattrs", ".zgroup"] + else: + files = ["zarr.json"] + + expected = [f"{part}/{file}" for file in files for part in parts] + + if zarr_format == 2: + expected.extend([".zgroup", ".zattrs", "a/b/c/d/.zgroup", "a/b/c/d/.zattrs"]) + else: + expected.extend(["zarr.json", "a/b/c/d/zarr.json"]) + + expected = sorted(expected) + + result = sorted([x async for x in store.list_prefix("")]) + + assert result == expected + + paths = ["a", "a/b", "a/b/c"] + for path in paths: + g = await zarr.api.asynchronous.open_group(store=store, path=path) + assert isinstance(g, AsyncGroup) + + if path == "a": + # ensure we didn't overwrite the root attributes + assert g.attrs == {"key": "value"} + else: + assert g.attrs == {} + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +@pytest.mark.parametrize("root_name", ["", "/", "a", "/a"]) +@pytest.mark.parametrize("branch_name", ["foo", "/foo", "foo/bar", "/foo/bar"]) +def test_group_name_properties( + store: Store, zarr_format: ZarrFormat, root_name: str, branch_name: str +) -> None: + """ + Test that the path, name, and basename attributes of a group and its subgroups are consistent + """ + root = Group.from_store(store=StorePath(store=store, path=root_name), zarr_format=zarr_format) + assert root.path == normalize_path(root_name) + assert root.name == f"/{root.path}" + assert root.basename == root.path + + branch = root.create_group(branch_name) + if root.path == "": + assert branch.path == normalize_path(branch_name) + else: + assert branch.path == "/".join([root.path, normalize_path(branch_name)]) + assert branch.name == f"/{branch.path}" + assert branch.basename == branch_name.split("/")[-1] + + +@pytest.mark.parametrize("consolidated_metadata", [True, False]) +def test_group_members(store: Store, zarr_format: ZarrFormat, consolidated_metadata: bool) -> None: + """ + Test that `Group.members` returns correct values, i.e. the arrays and groups + (explicit and implicit) contained in that group. + """ + # group/ + # subgroup/ + # subsubgroup/ + # subsubsubgroup + # subarray + + path = "group" + group = Group.from_store( + store=store, + zarr_format=zarr_format, + ) + members_expected: dict[str, Array | Group] = {} + + members_expected["subgroup"] = group.create_group("subgroup") + # make a sub-sub-subgroup, to ensure that the children calculation doesn't go + # too deep in the hierarchy + subsubgroup = members_expected["subgroup"].create_group("subsubgroup") + subsubsubgroup = subsubgroup.create_group("subsubsubgroup") + + members_expected["subarray"] = group.create_array( + "subarray", shape=(100,), dtype="uint8", chunks=(10,), overwrite=True + ) + # add an extra object to the domain of the group. + # the list of children should ignore this object. + sync( + store.set( + f"{path}/extra_object-1", + default_buffer_prototype().buffer.from_bytes(b"000000"), + ) + ) + # add an extra object under a directory-like prefix in the domain of the group. + # this creates a directory with a random key in it + # this should not show up as a member + sync( + store.set( + f"{path}/extra_directory/extra_object-2", + default_buffer_prototype().buffer.from_bytes(b"000000"), + ) + ) + + # this warning shows up when extra objects show up in the hierarchy + warn_context = pytest.warns( + ZarrUserWarning, + match=r"(?:Object at .* is not recognized as a component of a Zarr hierarchy.)|(?:Consolidated metadata is currently not part in the Zarr format 3 specification.)", + ) + if consolidated_metadata: + if isinstance(store, ZipStore): + with warn_context: + with pytest.warns(UserWarning, match="Duplicate name: "): + zarr.consolidate_metadata(store=store, zarr_format=zarr_format) + else: + with warn_context: + zarr.consolidate_metadata(store=store, zarr_format=zarr_format) + # now that we've consolidated the store, we shouldn't get the warnings from the unrecognized objects anymore + # we use a nullcontext to handle these cases + warn_context = contextlib.nullcontext() + group = zarr.open_consolidated(store=store, zarr_format=zarr_format) + + with warn_context: + members_observed = group.members() + # members are not guaranteed to be ordered, so sort before comparing + assert sorted(dict(members_observed)) == sorted(members_expected) + + # partial + with warn_context: + members_observed = group.members(max_depth=1) + members_expected["subgroup/subsubgroup"] = subsubgroup + # members are not guaranteed to be ordered, so sort before comparing + assert sorted(dict(members_observed)) == sorted(members_expected) + + # total + with warn_context: + members_observed = group.members(max_depth=None) + members_expected["subgroup/subsubgroup/subsubsubgroup"] = subsubsubgroup + # members are not guaranteed to be ordered, so sort before comparing + assert sorted(dict(members_observed)) == sorted(members_expected) + + with pytest.raises(ValueError, match="max_depth"): + members_observed = group.members(max_depth=-1) + + +def test_group(store: Store, zarr_format: ZarrFormat) -> None: + """ + Test basic Group routines. + """ + store_path = StorePath(store) + agroup = AsyncGroup(metadata=GroupMetadata(zarr_format=zarr_format), store_path=store_path) + group = Group(agroup) + assert agroup.metadata is group.metadata + assert agroup.store_path == group.store_path == store_path + + # create two groups + foo = group.create_group("foo") + bar = foo.create_group("bar", attributes={"baz": "qux"}) + + # create an array from the "bar" group + data = np.arange(0, 4 * 4, dtype="uint16").reshape((4, 4)) + arr = bar.create_array("baz", shape=data.shape, dtype=data.dtype, chunks=(2, 2), overwrite=True) + arr[:] = data + + # check the array + assert arr == bar["baz"] + assert arr.shape == data.shape + assert arr.dtype == data.dtype + + # TODO: update this once the array api settles down + assert arr.chunks == (2, 2) + + bar2 = foo["bar"] + assert dict(bar2.attrs) == {"baz": "qux"} + + # update a group's attributes + if isinstance(store, ZipStore): + with pytest.warns(UserWarning, match="Duplicate name: "): + bar2.attrs.update({"name": "bar"}) + else: + bar2.attrs.update({"name": "bar"}) + # bar.attrs was modified in-place + assert dict(bar2.attrs) == {"baz": "qux", "name": "bar"} + + # and the attrs were modified in the store + bar3 = foo["bar"] + assert dict(bar3.attrs) == {"baz": "qux", "name": "bar"} + + +def test_group_create(store: Store, overwrite: bool, zarr_format: ZarrFormat) -> None: + """ + Test that `Group.from_store` works as expected. + """ + attributes = {"foo": 100} + group = Group.from_store( + store, attributes=attributes, zarr_format=zarr_format, overwrite=overwrite + ) + + assert group.attrs == attributes + + if not overwrite: + with pytest.raises(ContainsGroupError): + _ = Group.from_store(store, overwrite=overwrite, zarr_format=zarr_format) + + +def test_group_open(store: Store, zarr_format: ZarrFormat, overwrite: bool) -> None: + """ + Test the `Group.open` method. + """ + spath = StorePath(store) + # attempt to open a group that does not exist + with pytest.raises(FileNotFoundError): + Group.open(store) + + # create the group + attrs = {"path": "foo"} + group_created = Group.from_store( + store, attributes=attrs, zarr_format=zarr_format, overwrite=overwrite + ) + assert group_created.attrs == attrs + assert group_created.metadata.zarr_format == zarr_format + assert group_created.store_path == spath + + # attempt to create a new group in place, to test overwrite + new_attrs = {"path": "bar"} + if not overwrite: + with pytest.raises(ContainsGroupError): + Group.from_store(store, attributes=attrs, zarr_format=zarr_format, overwrite=overwrite) + else: + if not store.supports_deletes: + pytest.skip( + "Store does not support deletes but `overwrite` is True, requiring deletes to override a group" + ) + group_created_again = Group.from_store( + store, attributes=new_attrs, zarr_format=zarr_format, overwrite=overwrite + ) + assert group_created_again.attrs == new_attrs + assert group_created_again.metadata.zarr_format == zarr_format + assert group_created_again.store_path == spath + + +@pytest.mark.parametrize("consolidated", [True, False]) +def test_group_getitem(store: Store, zarr_format: ZarrFormat, consolidated: bool) -> None: + """ + Test the `Group.__getitem__` method. + """ + + group = Group.from_store(store, zarr_format=zarr_format) + subgroup = group.create_group(name="subgroup") + subarray = group.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="uint8") + subsubarray = subgroup.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="uint8") + + if consolidated: + if zarr_format == 3: + with pytest.warns( # noqa: PT031 + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + if isinstance(store, ZipStore): + with pytest.warns(UserWarning, match="Duplicate name: "): + group = zarr.api.synchronous.consolidate_metadata( + store=store, zarr_format=zarr_format + ) + else: + group = zarr.api.synchronous.consolidate_metadata( + store=store, zarr_format=zarr_format + ) + else: + if isinstance(store, ZipStore): + with pytest.warns(UserWarning, match="Duplicate name: "): + group = zarr.api.synchronous.consolidate_metadata( + store=store, zarr_format=zarr_format + ) + else: + group = zarr.api.synchronous.consolidate_metadata( + store=store, zarr_format=zarr_format + ) + # we're going to assume that `group.metadata` is correct, and reuse that to focus + # on indexing in this test. Other tests verify the correctness of group.metadata + object.__setattr__( + subgroup.metadata, + "consolidated_metadata", + ConsolidatedMetadata( + metadata={"subarray": group.metadata.consolidated_metadata.metadata["subarray"]} + ), + ) + + assert group["subgroup"] == subgroup + assert group["subarray"] == subarray + assert group["subgroup"]["subarray"] == subsubarray + assert group["subgroup/subarray"] == subsubarray + + with pytest.raises(KeyError, match="nope"): + group["nope"] + + with pytest.raises(KeyError, match="subarray/subsubarray"): + group["subarray/subsubarray"] + + # Now test the mixed case + if consolidated: + object.__setattr__( + group.metadata.consolidated_metadata.metadata["subgroup"], + "consolidated_metadata", + None, + ) + + # test the implementation directly + with pytest.raises(KeyError): + group._async_group._getitem_consolidated( + group.store_path, "subgroup/subarray", prefix="/" + ) + + with pytest.raises(KeyError): + # We've chosen to trust the consolidated metadata, which doesn't + # contain this array + group["subgroup/subarray"] + + with pytest.raises(KeyError, match="subarray/subsubarray"): + group["subarray/subsubarray"] + + +def test_group_get_with_default(store: Store, zarr_format: ZarrFormat) -> None: + group = Group.from_store(store, zarr_format=zarr_format) + + # default behavior + result = group.get("subgroup") + assert result is None + + # custom default + result = group.get("subgroup", 8) + assert result == 8 + + # now with a group + subgroup = group.require_group("subgroup") + if isinstance(store, ZipStore): + with pytest.warns(UserWarning, match="Duplicate name: "): + subgroup.attrs["foo"] = "bar" + else: + subgroup.attrs["foo"] = "bar" + result = group.get("subgroup", 8) + assert result.attrs["foo"] == "bar" + + +def test_group_get_array(store: Store, zarr_format: ZarrFormat) -> None: + """ + `Group.get_array` returns the array at the given path, for both direct child names + and nested paths, and the result is statically typed as an Array. + """ + group = Group.from_store(store, zarr_format=zarr_format) + subgroup = group.create_group(name="subgroup") + subarray = group.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="uint8") + subsubarray = subgroup.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="uint8") + + observed = group.get_array("subarray") + assert isinstance(observed, Array) + assert observed == subarray + assert group.get_array("subgroup/subarray") == subsubarray + + +def test_group_get_array_missing(store: Store, zarr_format: ZarrFormat) -> None: + """ + `Group.get_array` raises `ArrayNotFoundError` when no node exists at the given path. + """ + group = Group.from_store(store, zarr_format=zarr_format) + with pytest.raises(ArrayNotFoundError, match="No array found in store"): + group.get_array("missing") + + +def test_group_get_array_wrong_node_type(store: Store, zarr_format: ZarrFormat) -> None: + """ + `Group.get_array` raises `ContainsGroupError` when the node at the given path is a + group rather than an array. + """ + group = Group.from_store(store, zarr_format=zarr_format) + group.create_group(name="subgroup") + with pytest.raises(ContainsGroupError, match="A group exists in store"): + group.get_array("subgroup") + + +def test_group_get_group(store: Store, zarr_format: ZarrFormat) -> None: + """ + `Group.get_group` returns the group at the given path, for both direct child names + and nested paths, and the result is statically typed as a Group. + """ + group = Group.from_store(store, zarr_format=zarr_format) + subgroup = group.create_group(name="subgroup") + subsubgroup = subgroup.create_group(name="subsubgroup") + + observed = group.get_group("subgroup") + assert isinstance(observed, Group) + assert observed == subgroup + assert group.get_group("subgroup/subsubgroup") == subsubgroup + + +def test_group_get_group_missing(store: Store, zarr_format: ZarrFormat) -> None: + """ + `Group.get_group` raises `GroupNotFoundError` when no node exists at the given path. + """ + group = Group.from_store(store, zarr_format=zarr_format) + with pytest.raises(GroupNotFoundError, match="No group found in store"): + group.get_group("missing") + + +def test_group_get_group_wrong_node_type(store: Store, zarr_format: ZarrFormat) -> None: + """ + `Group.get_group` raises `ContainsArrayError` when the node at the given path is an + array rather than a group. + """ + group = Group.from_store(store, zarr_format=zarr_format) + group.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="uint8") + with pytest.raises(ContainsArrayError, match="An array exists in store"): + group.get_group("subarray") + + +@pytest.mark.parametrize("consolidated", [True, False]) +def test_group_delitem(store: Store, zarr_format: ZarrFormat, consolidated: bool) -> None: + """ + Test the `Group.__delitem__` method. + """ + if not store.supports_deletes: + pytest.skip("store does not support deletes") + + group = Group.from_store(store, zarr_format=zarr_format) + subgroup = group.create_group(name="subgroup") + subarray = group.create_array(name="subarray", shape=(10,), chunks=(10,), dtype="uint8") + + if consolidated: + if zarr_format == 3: + with pytest.warns( # noqa: PT031 + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + if isinstance(store, ZipStore): + with pytest.warns(UserWarning, match="Duplicate name: "): + group = zarr.api.synchronous.consolidate_metadata( + store=store, zarr_format=zarr_format + ) + else: + group = zarr.api.synchronous.consolidate_metadata( + store=store, zarr_format=zarr_format + ) + else: + group = zarr.api.synchronous.consolidate_metadata(store=store, zarr_format=zarr_format) + object.__setattr__( + subgroup.metadata, "consolidated_metadata", ConsolidatedMetadata(metadata={}) + ) + + assert group["subgroup"] == subgroup + assert group["subarray"] == subarray + + del group["subgroup"] + with pytest.raises(KeyError, match="subgroup"): + group["subgroup"] + + del group["subarray"] + with pytest.raises(KeyError, match="subarray"): + group["subarray"] + + +def test_group_iter(store: Store, zarr_format: ZarrFormat) -> None: + """ + Test the `Group.__iter__` method. + """ + + group = Group.from_store(store, zarr_format=zarr_format) + assert list(group) == [] + + +def test_group_len(store: Store, zarr_format: ZarrFormat) -> None: + """ + Test the `Group.__len__` method. + """ + + group = Group.from_store(store, zarr_format=zarr_format) + assert len(group) == 0 + + +def test_group_setitem(store: Store, zarr_format: ZarrFormat) -> None: + """ + Test the `Group.__setitem__` method. + """ + group = Group.from_store(store, zarr_format=zarr_format) + arr = np.ones((2, 4)) + group["key"] = arr + assert list(group.array_keys()) == ["key"] + assert group["key"].shape == (2, 4) + np.testing.assert_array_equal(group["key"][:], arr) + + if store.supports_deletes: + key = "key" + else: + # overwriting with another array requires deletes + # for stores that don't support this, we just use a new key + key = "key2" + + # overwrite with another array + arr = np.zeros((3, 5)) + group[key] = arr + assert key in list(group.array_keys()) + assert group[key].shape == (3, 5) + np.testing.assert_array_equal(group[key], arr) + + +def test_group_contains(store: Store, zarr_format: ZarrFormat) -> None: + """ + Test the `Group.__contains__` method + """ + group = Group.from_store(store, zarr_format=zarr_format) + assert "foo" not in group + _ = group.create_group(name="foo") + assert "foo" in group + + +@pytest.mark.parametrize("consolidate", [True, False]) +def test_group_child_iterators(store: Store, zarr_format: ZarrFormat, consolidate: bool): + group = Group.from_store(store, zarr_format=zarr_format) + expected_group_keys = ["g0", "g1"] + expected_group_values = [group.create_group(name=name) for name in expected_group_keys] + expected_groups = list(zip(expected_group_keys, expected_group_values, strict=False)) + + fill_value = 3 + dtype = UInt8() + + expected_group_values[0].create_group("subgroup") + expected_group_values[0].create_array( + "subarray", shape=(1,), dtype=dtype, fill_value=fill_value + ) + + expected_array_keys = ["a0", "a1"] + + expected_array_values = [ + group.create_array(name=name, shape=(1,), dtype=dtype, fill_value=fill_value) + for name in expected_array_keys + ] + expected_arrays = list(zip(expected_array_keys, expected_array_values, strict=False)) + + if consolidate: + if zarr_format == 3: + with pytest.warns( # noqa: PT031 + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + if isinstance(store, ZipStore): + with pytest.warns(UserWarning, match="Duplicate name: "): + group = zarr.consolidate_metadata(store) + else: + group = zarr.consolidate_metadata(store) + else: + if isinstance(store, ZipStore): + with pytest.warns(UserWarning, match="Duplicate name: "): + group = zarr.consolidate_metadata(store) + else: + group = zarr.consolidate_metadata(store) + if zarr_format == 2: + metadata = { + "subarray": { + "attributes": {}, + "dtype": unpack_dtype_json(dtype.to_json(zarr_format=zarr_format)), + "fill_value": fill_value, + "shape": (1,), + "chunks": (1,), + "order": "C", + "filters": None, + "compressor": Blosc(), + "zarr_format": zarr_format, + }, + "subgroup": { + "attributes": {}, + "consolidated_metadata": { + "metadata": {}, + "kind": "inline", + "must_understand": False, + }, + "node_type": "group", + "zarr_format": zarr_format, + }, + } + else: + metadata = { + "subarray": { + "attributes": {}, + "chunk_grid": { + "configuration": {"chunk_shape": (1,)}, + "name": "regular", + }, + "chunk_key_encoding": { + "configuration": {"separator": "/"}, + "name": "default", + }, + "codecs": ( + {"configuration": {"endian": "little"}, "name": "bytes"}, + {"configuration": {}, "name": "zstd"}, + ), + "data_type": unpack_dtype_json(dtype.to_json(zarr_format=zarr_format)), + "fill_value": fill_value, + "node_type": "array", + "shape": (1,), + "zarr_format": zarr_format, + }, + "subgroup": { + "attributes": {}, + "consolidated_metadata": { + "metadata": {}, + "kind": "inline", + "must_understand": False, + }, + "node_type": "group", + "zarr_format": zarr_format, + }, + } + + object.__setattr__( + expected_group_values[0].metadata, + "consolidated_metadata", + ConsolidatedMetadata.from_dict( + { + "kind": "inline", + "metadata": metadata, + "must_understand": False, + } + ), + ) + object.__setattr__( + expected_group_values[1].metadata, + "consolidated_metadata", + ConsolidatedMetadata(metadata={}), + ) + + result = sorted(group.groups(), key=operator.itemgetter(0)) + assert result == expected_groups + + assert sorted(group.groups(), key=operator.itemgetter(0)) == expected_groups + assert sorted(group.group_keys()) == expected_group_keys + assert sorted(group.group_values(), key=lambda x: x.name) == expected_group_values + + assert sorted(group.arrays(), key=operator.itemgetter(0)) == expected_arrays + assert sorted(group.array_keys()) == expected_array_keys + assert sorted(group.array_values(), key=lambda x: x.name) == expected_array_values + + +def test_group_update_attributes(store: Store, zarr_format: ZarrFormat) -> None: + """ + Test the behavior of `Group.update_attributes` + """ + attrs = {"foo": 100} + group = Group.from_store(store, zarr_format=zarr_format, attributes=attrs) + assert group.attrs == attrs + new_attrs = {"bar": 100} + if isinstance(store, ZipStore): + with pytest.warns(UserWarning, match="Duplicate name: "): + new_group = group.update_attributes(new_attrs) + else: + new_group = group.update_attributes(new_attrs) + + updated_attrs = attrs.copy() + updated_attrs.update(new_attrs) + assert new_group.attrs == updated_attrs + + +async def test_group_update_attributes_async(store: Store, zarr_format: ZarrFormat) -> None: + """ + Test the behavior of `Group.update_attributes_async` + """ + attrs = {"foo": 100} + group = Group.from_store(store, zarr_format=zarr_format, attributes=attrs) + assert group.attrs == attrs + new_attrs = {"bar": 100} + if isinstance(store, ZipStore): + with pytest.warns(UserWarning, match="Duplicate name: "): + new_group = await group.update_attributes_async(new_attrs) + else: + new_group = await group.update_attributes_async(new_attrs) + assert new_group.attrs == new_attrs + + +@pytest.mark.parametrize("name", ["a", "/a"]) +def test_group_create_array( + store: Store, + zarr_format: ZarrFormat, + overwrite: bool, + name: str, +) -> None: + """ + Test `Group.from_store` + """ + group = Group.from_store(store, zarr_format=zarr_format) + shape = (10, 10) + dtype = "uint8" + data = np.arange(np.prod(shape)).reshape(shape).astype(dtype) + + array = group.create_array(name=name, shape=shape, dtype=dtype) + array[:] = data + + if not overwrite: + with pytest.raises(ContainsArrayError): # noqa: PT012 + a = group.create_array(name=name, shape=shape, dtype=dtype) + a[:] = data + + assert array.path == normalize_path(name) + assert array.name == f"/{array.path}" + assert array.shape == shape + assert array.dtype == np.dtype(dtype) + assert np.array_equal(array[:], data) + + +@pytest.mark.parametrize("method", ["create_array", "create_group"]) +def test_create_with_parent_array(store: Store, zarr_format: ZarrFormat, method: str): + """Test that groups/arrays cannot be created under a parent array.""" + + # create a group with a child array + group = Group.from_store(store, zarr_format=zarr_format) + group.create_array(name="arr_1", shape=(10, 10), dtype="uint8") + + error_msg = r"A parent of .* is an array - only groups may have child nodes." + if method == "create_array": + with pytest.raises(ValueError, match=error_msg): + group.create_array("arr_1/group_1/group_2/arr_2", shape=(10, 10), dtype="uint8") + + else: + with pytest.raises(ValueError, match=error_msg): + group.create_group("arr_1/group_1/group_2/group_3") + + +LikeMethodName = Literal["zeros_like", "ones_like", "empty_like", "full_like"] + + +@pytest.mark.parametrize("method_name", get_args(LikeMethodName)) +@pytest.mark.parametrize("out_shape", ["keep", (10, 10)]) +@pytest.mark.parametrize("out_chunks", ["keep", (10, 10)]) +@pytest.mark.parametrize("out_dtype", ["keep", "int8"]) +def test_group_array_like_creation( + zarr_format: ZarrFormat, + method_name: LikeMethodName, + out_shape: Literal["keep"] | tuple[int, ...], + out_chunks: Literal["keep"] | tuple[int, ...], + out_dtype: str, +) -> None: + """ + Test Group.{zeros_like, ones_like, empty_like, full_like}, ensuring that we can override the + shape, chunks, and dtype of the array-like object provided to these functions with + appropriate keyword arguments + """ + ref_arr = zarr.ones(store={}, shape=(11, 12), dtype="uint8", chunks=(11, 12)) + group = Group.from_store({}, zarr_format=zarr_format) + kwargs = {} + if method_name == "full_like": + expect_fill = 4 + kwargs["fill_value"] = expect_fill + meth = group.full_like + elif method_name == "zeros_like": + expect_fill = 0 + meth = group.zeros_like + elif method_name == "ones_like": + expect_fill = 1 + meth = group.ones_like + elif method_name == "empty_like": + expect_fill = ref_arr.fill_value + meth = group.empty_like + else: + raise AssertionError + if out_shape != "keep": + kwargs["shape"] = out_shape + expect_shape = out_shape + else: + expect_shape = ref_arr.shape + if out_chunks != "keep": + kwargs["chunks"] = out_chunks + expect_chunks = out_chunks + else: + expect_chunks = ref_arr.chunks + if out_dtype != "keep": + kwargs["dtype"] = out_dtype + expect_dtype = out_dtype + else: + expect_dtype = ref_arr.dtype + + new_arr = meth(name="foo", data=ref_arr, **kwargs) + assert new_arr.shape == expect_shape + assert new_arr.chunks == expect_chunks + assert new_arr.dtype == expect_dtype + assert np.all(new_arr[:] == expect_fill) + + +def test_group_array_creation( + store: Store, + zarr_format: ZarrFormat, +): + group = Group.from_store(store, zarr_format=zarr_format) + shape = (10, 10) + empty_array = group.empty(name="empty", shape=shape) + assert isinstance(empty_array, Array) + assert empty_array.fill_value == 0 + assert empty_array.shape == shape + assert empty_array.store_path.store == store + assert empty_array.store_path.path == "empty" + + empty_like_array = group.empty_like(name="empty_like", data=empty_array) + assert isinstance(empty_like_array, Array) + assert empty_like_array.fill_value == 0 + assert empty_like_array.shape == shape + assert empty_like_array.store_path.store == store + + empty_array_bool = group.empty(name="empty_bool", shape=shape, dtype=np.dtype("bool")) + assert isinstance(empty_array_bool, Array) + assert not empty_array_bool.fill_value + assert empty_array_bool.shape == shape + assert empty_array_bool.store_path.store == store + + empty_like_array_bool = group.empty_like(name="empty_like_bool", data=empty_array_bool) + assert isinstance(empty_like_array_bool, Array) + assert not empty_like_array_bool.fill_value + assert empty_like_array_bool.shape == shape + assert empty_like_array_bool.store_path.store == store + + zeros_array = group.zeros(name="zeros", shape=shape) + assert isinstance(zeros_array, Array) + assert zeros_array.fill_value == 0 + assert zeros_array.shape == shape + assert zeros_array.store_path.store == store + + zeros_like_array = group.zeros_like(name="zeros_like", data=zeros_array) + assert isinstance(zeros_like_array, Array) + assert zeros_like_array.fill_value == 0 + assert zeros_like_array.shape == shape + assert zeros_like_array.store_path.store == store + + ones_array = group.ones(name="ones", shape=shape) + assert isinstance(ones_array, Array) + assert ones_array.fill_value == 1 + assert ones_array.shape == shape + assert ones_array.store_path.store == store + + ones_like_array = group.ones_like(name="ones_like", data=ones_array) + assert isinstance(ones_like_array, Array) + assert ones_like_array.fill_value == 1 + assert ones_like_array.shape == shape + assert ones_like_array.store_path.store == store + + full_array = group.full(name="full", shape=shape, fill_value=42) + assert isinstance(full_array, Array) + assert full_array.fill_value == 42 + assert full_array.shape == shape + assert full_array.store_path.store == store + + full_like_array = group.full_like(name="full_like", data=full_array, fill_value=43) + assert isinstance(full_like_array, Array) + assert full_like_array.fill_value == 43 + assert full_like_array.shape == shape + assert full_like_array.store_path.store == store + + +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +@pytest.mark.parametrize("zarr_format", [2, 3]) +@pytest.mark.parametrize("overwrite", [True, False]) +@pytest.mark.parametrize("extant_node", ["array", "group"]) +def test_group_creation_existing_node( + store: Store, + zarr_format: ZarrFormat, + overwrite: bool, + extant_node: Literal["array", "group"], +) -> None: + """ + Check that an existing array or group is handled as expected during group creation. + """ + spath = StorePath(store) + group = Group.from_store(spath, zarr_format=zarr_format) + expected_exception: type[ContainsArrayError | ContainsGroupError] + attributes: dict[str, JSON] = {"old": True} + + if extant_node == "array": + expected_exception = ContainsArrayError + _ = group.create_array("extant", shape=(10,), dtype="uint8", attributes=attributes) + elif extant_node == "group": + expected_exception = ContainsGroupError + _ = group.create_group("extant", attributes=attributes) + else: + raise AssertionError + + new_attributes = {"new": True} + + if overwrite: + if not store.supports_deletes: + pytest.skip("store does not support deletes but overwrite is True") + node_new = Group.from_store( + spath / "extant", + attributes=new_attributes, + zarr_format=zarr_format, + overwrite=overwrite, + ) + assert node_new.attrs == new_attributes + else: + with pytest.raises(expected_exception): + node_new = Group.from_store( + spath / "extant", + attributes=new_attributes, + zarr_format=zarr_format, + overwrite=overwrite, + ) + + +async def test_asyncgroup_create( + store: Store, + overwrite: bool, + zarr_format: ZarrFormat, +) -> None: + """ + Test that `AsyncGroup.from_store` works as expected. + """ + spath = StorePath(store=store) + attributes = {"foo": 100} + agroup = await AsyncGroup.from_store( + store, + attributes=attributes, + overwrite=overwrite, + zarr_format=zarr_format, + ) + + assert agroup.metadata == GroupMetadata(zarr_format=zarr_format, attributes=attributes) + assert agroup.store_path == await make_store_path(store) + + if not overwrite: + with pytest.raises(ContainsGroupError): + agroup = await AsyncGroup.from_store( + spath, + attributes=attributes, + overwrite=overwrite, + zarr_format=zarr_format, + ) + # create an array at our target path + collision_name = "foo" + _ = await zarr.api.asynchronous.create_array( + spath / collision_name, shape=(10,), dtype="uint8", zarr_format=zarr_format + ) + with pytest.raises(ContainsArrayError): + _ = await AsyncGroup.from_store( + StorePath(store=store) / collision_name, + attributes=attributes, + overwrite=overwrite, + zarr_format=zarr_format, + ) + + +async def test_asyncgroup_attrs(store: Store, zarr_format: ZarrFormat) -> None: + attributes = {"foo": 100} + agroup = await AsyncGroup.from_store(store, zarr_format=zarr_format, attributes=attributes) + + assert agroup.attrs == agroup.metadata.attributes == attributes + + +async def test_asyncgroup_open( + store: Store, + zarr_format: ZarrFormat, +) -> None: + """ + Create an `AsyncGroup`, then ensure that we can open it using `AsyncGroup.open` + """ + attributes = {"foo": 100} + group_w = await AsyncGroup.from_store( + store=store, + attributes=attributes, + overwrite=False, + zarr_format=zarr_format, + ) + + group_r = await AsyncGroup.open(store=store, zarr_format=zarr_format) + + assert group_w.attrs == group_w.attrs == attributes + assert group_w == group_r + + +async def test_asyncgroup_open_wrong_format( + store: Store, + zarr_format: ZarrFormat, +) -> None: + _ = await AsyncGroup.from_store(store=store, overwrite=False, zarr_format=zarr_format) + zarr_format_wrong: ZarrFormat + # try opening with the wrong zarr format + if zarr_format == 3: + zarr_format_wrong = 2 + elif zarr_format == 2: + zarr_format_wrong = 3 + else: + raise AssertionError + + with pytest.raises(FileNotFoundError): + await AsyncGroup.open(store=store, zarr_format=zarr_format_wrong) + + +# todo: replace the dict[str, Any] type with something a bit more specific +# should this be async? +@pytest.mark.parametrize( + "data", + [ + {"zarr_format": 3, "node_type": "group", "attributes": {"foo": 100}}, + {"zarr_format": 2, "attributes": {"foo": 100}}, + ], +) +def test_asyncgroup_from_dict(store: Store, data: dict[str, Any]) -> None: + """ + Test that we can create an AsyncGroup from a dict + """ + path = "test" + store_path = StorePath(store=store, path=path) + group = AsyncGroup.from_dict(store_path, data=data) + + assert group.metadata.zarr_format == data["zarr_format"] + assert group.metadata.attributes == data["attributes"] + + +# todo: replace this with a declarative API where we model a full hierarchy + + +async def test_asyncgroup_getitem(store: Store, zarr_format: ZarrFormat) -> None: + """ + Create an `AsyncGroup`, then create members of that group, and ensure that we can access those + members via the `AsyncGroup.getitem` method. + """ + agroup = await AsyncGroup.from_store(store=store, zarr_format=zarr_format) + + array_name = "sub_array" + sub_array = await agroup.create_array(name=array_name, shape=(10,), dtype="uint8", chunks=(2,)) + assert await agroup.getitem(array_name) == sub_array + + sub_group_path = "sub_group" + sub_group = await agroup.create_group(sub_group_path, attributes={"foo": 100}) + assert await agroup.getitem(sub_group_path) == sub_group + + # check that asking for a nonexistent key raises KeyError + with pytest.raises(KeyError, match="foo"): + await agroup.getitem("foo") + + +async def test_asyncgroup_delitem(store: Store, zarr_format: ZarrFormat) -> None: + if not store.supports_deletes: + pytest.skip("store does not support deletes") + + agroup = await AsyncGroup.from_store(store=store, zarr_format=zarr_format) + array_name = "sub_array" + _ = await agroup.create_array( + name=array_name, + shape=(10,), + dtype="uint8", + chunks=(2,), + attributes={"foo": 100}, + ) + await agroup.delitem(array_name) + + # todo: clean up the code duplication here + if zarr_format == 2: + assert not await agroup.store_path.store.exists(f"{array_name}/.zarray") + assert not await agroup.store_path.store.exists(f"{array_name}/.zattrs") + elif zarr_format == 3: + assert not await agroup.store_path.store.exists(f"{array_name}/zarr.json") + else: + raise AssertionError + + sub_group_path = "sub_group" + _ = await agroup.create_group(sub_group_path, attributes={"foo": 100}) + await agroup.delitem(sub_group_path) + if zarr_format == 2: + assert not await agroup.store_path.store.exists(f"{array_name}/.zgroup") + assert not await agroup.store_path.store.exists(f"{array_name}/.zattrs") + elif zarr_format == 3: + assert not await agroup.store_path.store.exists(f"{array_name}/zarr.json") + else: + raise AssertionError + + +@pytest.mark.parametrize("name", ["a", "/a"]) +async def test_asyncgroup_create_group( + store: Store, + name: str, + zarr_format: ZarrFormat, +) -> None: + agroup = await AsyncGroup.from_store(store=store, zarr_format=zarr_format) + attributes = {"foo": 999} + subgroup = await agroup.create_group(name=name, attributes=attributes) + + assert isinstance(subgroup, AsyncGroup) + assert subgroup.path == normalize_path(name) + assert subgroup.name == f"/{subgroup.path}" + assert subgroup.attrs == attributes + assert subgroup.store_path.path == subgroup.path + assert subgroup.store_path.store == store + assert subgroup.metadata.zarr_format == zarr_format + + +async def test_asyncgroup_create_array( + store: Store, zarr_format: ZarrFormat, overwrite: bool +) -> None: + """ + Test that the AsyncGroup.create_array method works correctly. We ensure that array properties + specified in create_array are present on the resulting array. + """ + + agroup = await AsyncGroup.from_store(store=store, zarr_format=zarr_format) + + if not overwrite: + with pytest.raises(ContainsGroupError): + agroup = await AsyncGroup.from_store(store=store, zarr_format=zarr_format) + + shape = (10,) + dtype = "uint8" + chunk_shape = (4,) + attributes: dict[str, JSON] = {"foo": 100} + + sub_node_path = "sub_array" + subnode = await agroup.create_array( + name=sub_node_path, + shape=shape, + dtype=dtype, + chunks=chunk_shape, + attributes=attributes, + ) + assert isinstance(subnode, AsyncArray) + assert subnode.attrs == attributes + assert subnode.store_path.path == sub_node_path + assert subnode.store_path.store == store + assert subnode.shape == shape + assert subnode.dtype == dtype + assert subnode._chunk_grid.chunk_shape == chunk_shape + assert subnode.metadata.zarr_format == zarr_format + + +async def test_asyncgroup_update_attributes(store: Store, zarr_format: ZarrFormat) -> None: + """ + Test that the AsyncGroup.update_attributes method works correctly. + """ + attributes_old = {"foo": 10} + attributes_new = {"baz": "new"} + agroup = await AsyncGroup.from_store( + store=store, zarr_format=zarr_format, attributes=attributes_old + ) + + if isinstance(store, ZipStore): + with pytest.warns(UserWarning, match="Duplicate name"): + agroup_new_attributes = await agroup.update_attributes(attributes_new) + else: + agroup_new_attributes = await agroup.update_attributes(attributes_new) + attributes_updated = attributes_old.copy() + attributes_updated.update(attributes_new) + assert agroup_new_attributes.attrs == attributes_updated + + +@pytest.mark.parametrize("store", ["local"], indirect=["store"]) +@pytest.mark.parametrize("zarr_format", [2, 3]) +async def test_serializable_async_group(store: LocalStore, zarr_format: ZarrFormat) -> None: + expected = await AsyncGroup.from_store( + store=store, attributes={"foo": 999}, zarr_format=zarr_format + ) + p = pickle.dumps(expected) + actual = pickle.loads(p) + assert actual == expected + + +@pytest.mark.parametrize("store", ["local"], indirect=["store"]) +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_serializable_sync_group(store: LocalStore, zarr_format: ZarrFormat) -> None: + expected = Group.from_store(store=store, attributes={"foo": 999}, zarr_format=zarr_format) + p = pickle.dumps(expected) + actual = pickle.loads(p) + assert actual == expected + + +@pytest.mark.parametrize("consolidated_metadata", [True, False]) +async def test_group_members_async(store: Store, consolidated_metadata: bool) -> None: + group = await AsyncGroup.from_store( + store=store, + ) + a0 = await group.create_array("a0", shape=(1,), dtype="uint8") + g0 = await group.create_group("g0") + a1 = await g0.create_array("a1", shape=(1,), dtype="uint8") + g1 = await g0.create_group("g1") + a2 = await g1.create_array("a2", shape=(1,), dtype="uint8") + g2 = await g1.create_group("g2") + + # immediate children + children = sorted([x async for x in group.members()], key=operator.itemgetter(0)) + assert children == [ + ("a0", a0), + ("g0", g0), + ] + + nmembers = await group.nmembers() + assert nmembers == 2 + + # partial + children = sorted([x async for x in group.members(max_depth=1)], key=operator.itemgetter(0)) + expected = [ + ("a0", a0), + ("g0", g0), + ("g0/a1", a1), + ("g0/g1", g1), + ] + assert children == expected + nmembers = await group.nmembers(max_depth=1) + assert nmembers == 4 + + # all children + all_children = sorted( + [x async for x in group.members(max_depth=None)], key=operator.itemgetter(0) + ) + expected = [ + ("a0", a0), + ("g0", g0), + ("g0/a1", a1), + ("g0/g1", g1), + ("g0/g1/a2", a2), + ("g0/g1/g2", g2), + ] + assert all_children == expected + + if consolidated_metadata: + with pytest.warns( # noqa: PT031 + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + if isinstance(store, ZipStore): + with pytest.warns(UserWarning, match="Duplicate name"): + await zarr.api.asynchronous.consolidate_metadata(store=store) + else: + await zarr.api.asynchronous.consolidate_metadata(store=store) + group = await zarr.api.asynchronous.open_group(store=store) + + nmembers = await group.nmembers(max_depth=None) + assert nmembers == 6 + + with pytest.raises(ValueError, match="max_depth"): + [x async for x in group.members(max_depth=-1)] + + if consolidated_metadata: + # test for mixed known and unknown metadata. + # For now, we trust the consolidated metadata. + object.__setattr__( + group.metadata.consolidated_metadata.metadata["g0"].consolidated_metadata.metadata[ + "g1" + ], + "consolidated_metadata", + None, + ) + # test depth=0 + nmembers = await group.nmembers(max_depth=0) + assert nmembers == 2 + # test depth=1 + nmembers = await group.nmembers(max_depth=1) + assert nmembers == 4 + # test depth=None + all_children = sorted( + [x async for x in group.members(max_depth=None)], key=operator.itemgetter(0) + ) + assert len(all_children) == 4 + nmembers = await group.nmembers(max_depth=None) + assert nmembers == 4 + # test depth<0 + with pytest.raises(ValueError, match="max_depth"): + await group.nmembers(max_depth=-1) + + +async def test_require_group(store: LocalStore | MemoryStore, zarr_format: ZarrFormat) -> None: + root = await AsyncGroup.from_store(store=store, zarr_format=zarr_format) + + # create foo group + _ = await root.create_group("foo", attributes={"foo": 100}) + + # test that we can get the group using require_group + foo_group = await root.require_group("foo") + assert foo_group.attrs == {"foo": 100} + + # test that we can get the group using require_group and overwrite=True + if store.supports_deletes: + foo_group = await root.require_group("foo", overwrite=True) + assert foo_group.attrs == {} + + _ = await foo_group.create_array( + "bar", shape=(10,), dtype="uint8", chunks=(2,), attributes={"foo": 100} + ) + + # test that overwriting a group w/ children fails + # TODO: figure out why ensure_no_existing_node is not catching the foo.bar array + # + # with pytest.raises(ContainsArrayError): + # await root.require_group("foo", overwrite=True) + + # test that requiring a group where an array is fails + with pytest.raises(TypeError, match="Incompatible object"): + await foo_group.require_group("bar") + + +async def test_require_groups(store: LocalStore | MemoryStore, zarr_format: ZarrFormat) -> None: + root = await AsyncGroup.from_store(store=store, zarr_format=zarr_format) + # create foo group + _ = await root.create_group("foo", attributes={"foo": 100}) + # create bar group + _ = await root.create_group("bar", attributes={"bar": 200}) + + foo_group, bar_group = await root.require_groups("foo", "bar") + assert foo_group.attrs == {"foo": 100} + assert bar_group.attrs == {"bar": 200} + + # get a mix of existing and new groups + foo_group, spam_group = await root.require_groups("foo", "spam") + assert foo_group.attrs == {"foo": 100} + assert spam_group.attrs == {} + + # no names + no_group = await root.require_groups() + assert no_group == () + + +async def test_require_array(store: Store, zarr_format: ZarrFormat) -> None: + root = await AsyncGroup.from_store(store=store, zarr_format=zarr_format) + foo1 = await root.require_array("foo", shape=(10,), dtype="i8", attributes={"foo": 101}) + assert foo1.attrs == {"foo": 101} + foo2 = await root.require_array("foo", shape=(10,), dtype="i8") + assert foo2.attrs == {"foo": 101} + + # exact = False + _ = await root.require_array("foo", shape=10, dtype="f8") + + # errors w/ exact True + with pytest.raises(TypeError, match="Incompatible dtype"): + await root.require_array("foo", shape=(10,), dtype="f8", exact=True) + + with pytest.raises(TypeError, match="Incompatible shape"): + await root.require_array("foo", shape=(100, 100), dtype="i8") + + with pytest.raises(TypeError, match="Incompatible dtype"): + await root.require_array("foo", shape=(10,), dtype="f4") + + _ = await root.create_group("bar") + with pytest.raises(TypeError, match="Incompatible object"): + await root.require_array("bar", shape=(10,), dtype="int8") + + +@pytest.mark.parametrize( + ("dtype", "expected"), + [ + (Int32(), Int32()), + (np.dtype("int32"), Int32()), + ("int32", Int32()), + (None, Float64()), + ], + ids=["zdtype", "numpy", "str", "none"], +) +async def test_require_array_zdtype( + store: Store, zarr_format: ZarrFormat, dtype: ZDTypeLike | None, expected: ZDType[Any, Any] +) -> None: + """An existing array can be required with a ZDType, as well as a string, a NumPy dtype, + or None. See https://github.com/zarr-developers/zarr-python/issues/3377 + """ + root = await AsyncGroup.from_store(store=store, zarr_format=zarr_format) + await root.create_array("foo", shape=(10,), dtype=expected) + + foo = await root.require_array("foo", shape=(10,), dtype=dtype, exact=True) + assert foo._zdtype == expected + + +@pytest.mark.parametrize("consolidate", [True, False]) +async def test_members_name(store: Store, consolidate: bool, zarr_format: ZarrFormat): + group = Group.from_store(store=store, zarr_format=zarr_format) + a = group.create_group(name="a") + a.create_array("array", shape=(1,), dtype="uint8") + b = a.create_group(name="b") + b.create_array("array", shape=(1,), dtype="uint8") + + if consolidate: + if isinstance(store, ZipStore): + with pytest.warns(UserWarning, match="Duplicate name"): # noqa: PT031 + if zarr_format == 3: + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + group = zarr.api.synchronous.consolidate_metadata(store) + else: + group = zarr.api.synchronous.consolidate_metadata(store) + else: + if zarr_format == 3: + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + group = zarr.api.synchronous.consolidate_metadata(store) + else: + group = zarr.api.synchronous.consolidate_metadata(store) + result = group["a"]["b"] + assert result.name == "/a/b" + + paths = sorted(x.name for _, x in group.members(max_depth=None)) + expected = ["/a", "/a/array", "/a/b", "/a/b/array"] + assert paths == expected + + # regression test for https://github.com/zarr-developers/zarr-python/pull/2356 + g = zarr.open_group(store, use_consolidated=False) + with warnings.catch_warnings(): + warnings.simplefilter("error") + assert list(g) + + +async def test_open_mutable_mapping(): + group = await zarr.api.asynchronous.open_group( + store={}, + ) + assert isinstance(group.store_path.store, MemoryStore) + + +def test_open_mutable_mapping_sync(): + group = zarr.open_group( + store={}, + ) + assert isinstance(group.store_path.store, MemoryStore) + + +async def test_open_ambiguous_node(): + zarr_json_bytes = default_buffer_prototype().buffer.from_bytes( + json.dumps({"zarr_format": 3, "node_type": "group"}).encode("utf-8") + ) + zgroup_bytes = default_buffer_prototype().buffer.from_bytes( + json.dumps({"zarr_format": 2}).encode("utf-8") + ) + store: dict[str, Buffer] = {"zarr.json": zarr_json_bytes, ".zgroup": zgroup_bytes} + with pytest.warns( + ZarrUserWarning, + match=r"Both zarr\.json \(Zarr format 3\) and \.zgroup \(Zarr format 2\) metadata objects exist at", + ): + await AsyncGroup.open(store, zarr_format=None) + + +class TestConsolidated: + async def test_group_getitem_consolidated(self, store: Store) -> None: + root = await AsyncGroup.from_store(store=store) + # Set up the test structure with + # / + # g0/ # group /g0 + # g1/ # group /g0/g1 + # g2/ # group /g0/g1/g2 + # x1/ # group /x0 + # x2/ # group /x0/x1 + # x3/ # group /x0/x1/x2 + + g0 = await root.create_group("g0") + g1 = await g0.create_group("g1") + await g1.create_group("g2") + + x0 = await root.create_group("x0") + x1 = await x0.create_group("x1") + await x1.create_group("x2") + + with pytest.warns( # noqa: PT031 + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + if isinstance(store, ZipStore): + with pytest.warns(UserWarning, match="Duplicate name"): + await zarr.api.asynchronous.consolidate_metadata(store) + else: + await zarr.api.asynchronous.consolidate_metadata(store) + + # On disk, we've consolidated all the metadata in the root zarr.json + group = await zarr.api.asynchronous.open(store=store) + rg0 = await group.get_group("g0") + + expected = ConsolidatedMetadata( + metadata={ + "g1": GroupMetadata( + attributes={}, + zarr_format=3, + consolidated_metadata=ConsolidatedMetadata( + metadata={ + "g2": GroupMetadata( + attributes={}, + zarr_format=3, + consolidated_metadata=ConsolidatedMetadata(metadata={}), + ) + } + ), + ), + } + ) + assert rg0.metadata.consolidated_metadata == expected + + rg1 = await rg0.get_group("g1") + assert rg1.metadata.consolidated_metadata == expected.metadata["g1"].consolidated_metadata + + rg2 = await rg1.get_group("g2") + assert rg2.metadata.consolidated_metadata == ConsolidatedMetadata(metadata={}) + + async def test_group_delitem_consolidated(self, store: Store) -> None: + if isinstance(store, ZipStore): + raise pytest.skip("Not implemented") + + root = await AsyncGroup.from_store(store=store) + # Set up the test structure with + # / + # g0/ # group /g0 + # g1/ # group /g0/g1 + # g2/ # group /g0/g1/g2 + # data # array + # x1/ # group /x0 + # x2/ # group /x0/x1 + # x3/ # group /x0/x1/x2 + # data # array + + g0 = await root.create_group("g0") + g1 = await g0.create_group("g1") + g2 = await g1.create_group("g2") + await g2.create_array("data", shape=(1,), dtype="uint8") + + x0 = await root.create_group("x0") + x1 = await x0.create_group("x1") + x2 = await x1.create_group("x2") + await x2.create_array("data", shape=(1,), dtype="uint8") + + with pytest.warns( # noqa: PT031 + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + if isinstance(store, ZipStore): + with pytest.warns(UserWarning, match="Duplicate name"): + await zarr.api.asynchronous.consolidate_metadata(store) + else: + await zarr.api.asynchronous.consolidate_metadata(store) + + group = await zarr.api.asynchronous.open_consolidated(store=store) + assert len(group.metadata.consolidated_metadata.metadata) == 2 + assert "g0" in group.metadata.consolidated_metadata.metadata + + await group.delitem("g0") + assert len(group.metadata.consolidated_metadata.metadata) == 1 + assert "g0" not in group.metadata.consolidated_metadata.metadata + + def test_open_consolidated_raises(self, store: Store) -> None: + if isinstance(store, ZipStore): + raise pytest.skip("Not implemented") + + root = Group.from_store(store=store) + + # fine to be missing by default + zarr.open_group(store=store) + + with pytest.raises(ValueError, match="Consolidated metadata requested."): + zarr.open_group(store=store, use_consolidated=True) + + # Now create consolidated metadata... + root.create_group("g0") + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + zarr.consolidate_metadata(store) + + # and explicitly ignore it. + group = zarr.open_group(store=store, use_consolidated=False) + assert group.metadata.consolidated_metadata is None + + async def test_open_consolidated_raises_async(self, store: Store) -> None: + if isinstance(store, ZipStore): + raise pytest.skip("Not implemented") + + root = await AsyncGroup.from_store(store=store) + + # fine to be missing by default + await zarr.api.asynchronous.open_group(store=store) + + with pytest.raises(ValueError, match="Consolidated metadata requested."): + await zarr.api.asynchronous.open_group(store=store, use_consolidated=True) + + # Now create consolidated metadata... + await root.create_group("g0") + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + await zarr.api.asynchronous.consolidate_metadata(store) + + # and explicitly ignore it. + group = await zarr.api.asynchronous.open_group(store=store, use_consolidated=False) + assert group.metadata.consolidated_metadata is None + + +class TestGroupMetadata: + def test_from_dict_extra_fields(self): + data = { + "attributes": {"key": "value"}, + "_nczarr_superblock": {"version": "2.0.0"}, + "zarr_format": 2, + } + result = GroupMetadata.from_dict(data) + expected = GroupMetadata(attributes={"key": "value"}, zarr_format=2) + assert result == expected + + +class TestInfo: + def test_info(self): + store = zarr.storage.MemoryStore() + A = zarr.group(store=store, path="A") + B = A.create_group(name="B") + + B.create_array(name="x", shape=(1,), dtype="uint8") + B.create_array(name="y", shape=(2,), dtype="uint8") + + result = A.info + expected = GroupInfo( + _name="A", + _read_only=False, + _store_type="MemoryStore", + _zarr_format=3, + ) + assert result == expected + + result = A.info_complete() + expected = GroupInfo( + _name="A", + _read_only=False, + _store_type="MemoryStore", + _zarr_format=3, + _count_members=3, + _count_arrays=2, + _count_groups=1, + ) + assert result == expected + + +def test_update_attrs() -> None: + # regression test for https://github.com/zarr-developers/zarr-python/issues/2328 + root = Group.from_store( + MemoryStore(), + ) + root.attrs["foo"] = "bar" + assert root.attrs["foo"] == "bar" + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +def test_delitem_removes_children(store: Store, zarr_format: ZarrFormat) -> None: + # https://github.com/zarr-developers/zarr-python/issues/2191 + g1 = zarr.group(store=store, zarr_format=zarr_format) + g1.create_group("0") + g1.create_group("0/0") + arr = g1.create_array("0/0/0", shape=(1,), dtype="uint8") + arr[:] = 1 + del g1["0"] + with pytest.raises(KeyError, match="0/0"): + g1["0/0"] + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +@pytest.mark.parametrize("impl", ["async", "sync"]) +async def test_create_nodes( + impl: Literal["async", "sync"], store: Store, zarr_format: ZarrFormat +) -> None: + """ + Ensure that ``create_nodes`` can create a zarr hierarchy from a model of that + hierarchy in dict form. Note that this creates an incomplete Zarr hierarchy. + """ + node_spec = { + "group": GroupMetadata(attributes={"foo": 10}), + "group/array_0": meta_from_array(np.arange(3), zarr_format=zarr_format), + "group/array_1": meta_from_array(np.arange(4), zarr_format=zarr_format), + "group/subgroup/array_0": meta_from_array(np.arange(4), zarr_format=zarr_format), + "group/subgroup/array_1": meta_from_array(np.arange(5), zarr_format=zarr_format), + } + if impl == "sync": + observed_nodes = dict(sync_group.create_nodes(store=store, nodes=node_spec)) + elif impl == "async": + observed_nodes = dict(await _collect_aiterator(create_nodes(store=store, nodes=node_spec))) + else: + raise ValueError(f"Invalid impl: {impl}") + + assert node_spec == {k: v.metadata for k, v in observed_nodes.items()} + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +def test_create_nodes_concurrency_limit(store: MemoryStore) -> None: + """ + Test that the execution time of create_nodes can be constrained by the async concurrency + configuration setting. + """ + set_latency = 0.02 + num_groups = 10 + groups = {str(idx): GroupMetadata() for idx in range(num_groups)} + + latency_store = LatencyStore(store, set_latency=set_latency) + + # check how long it takes to iterate over the groups + # if create_nodes is sensitive to IO latency, + # this should take (num_groups * get_latency) seconds + # otherwise, it should take only marginally more than get_latency seconds + with zarr_config.set({"async.concurrency": 1}): + start = time.time() + _ = tuple(sync_group.create_nodes(store=latency_store, nodes=groups)) + elapsed = time.time() - start + assert elapsed > num_groups * set_latency + + +@pytest.mark.parametrize( + ("a_func", "b_func"), + [ + (zarr.core.group.AsyncGroup.create_array, zarr.core.group.Group.create_array), + (zarr.core.group.AsyncGroup.create_hierarchy, zarr.core.group.Group.create_hierarchy), + (zarr.core.group.create_hierarchy, zarr.core.sync_group.create_hierarchy), + (zarr.core.group.create_nodes, zarr.core.sync_group.create_nodes), + (zarr.core.group.create_rooted_hierarchy, zarr.core.sync_group.create_rooted_hierarchy), + (zarr.core.group.get_node, zarr.core.sync_group.get_node), + ], + # The default ids (from __name__) collide: the method pair and the module-level pair + # for create_hierarchy would both be id'd "create_hierarchy-create_hierarchy". + ids=lambda func: f"{func.__module__.rsplit('.', maxsplit=1)[-1]}.{func.__qualname__}", +) +def test_consistent_signatures( + a_func: Callable[[object], object], b_func: Callable[[object], object] +) -> None: + """ + Ensure that pairs of functions have consistent signatures + """ + base_sig = inspect.signature(a_func) + test_sig = inspect.signature(b_func) + wrong: dict[str, list[object]] = { + "missing_from_test": [], + "missing_from_base": [], + "wrong_type": [], + } + for key, value in base_sig.parameters.items(): + if key not in test_sig.parameters: + wrong["missing_from_test"].append((key, value)) + for key, value in test_sig.parameters.items(): + if key not in base_sig.parameters: + wrong["missing_from_base"].append((key, value)) + if base_sig.parameters[key] != value: + wrong["wrong_type"].append({key: {"test": value, "base": base_sig.parameters[key]}}) + assert wrong["missing_from_base"] == [] + assert wrong["missing_from_test"] == [] + assert wrong["wrong_type"] == [] + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +@pytest.mark.parametrize("overwrite", [True, False]) +@pytest.mark.parametrize("impl", ["async", "sync"]) +async def test_create_hierarchy( + impl: Literal["async", "sync"], store: Store, overwrite: bool, zarr_format: ZarrFormat +) -> None: + """ + Test that ``create_hierarchy`` can create a complete Zarr hierarchy, even if the input describes + an incomplete one. + """ + + hierarchy_spec = { + "group": GroupMetadata(attributes={"path": "group"}, zarr_format=zarr_format), + "group/array_0": meta_from_array( + np.arange(3), attributes={"path": "group/array_0"}, zarr_format=zarr_format + ), + "group/subgroup/array_0": meta_from_array( + np.arange(4), attributes={"path": "group/subgroup/array_0"}, zarr_format=zarr_format + ), + } + pre_existing_nodes = { + "group/extra": GroupMetadata(zarr_format=zarr_format, attributes={"path": "group/extra"}), + "": GroupMetadata(zarr_format=zarr_format, attributes={"name": "root"}), + } + # we expect create_hierarchy to insert a group that was missing from the hierarchy spec + expected_meta = hierarchy_spec | {"group/subgroup": GroupMetadata(zarr_format=zarr_format)} + + # initialize the group with some nodes + _ = dict(sync_group.create_nodes(store=store, nodes=pre_existing_nodes)) + + if impl == "sync": + created = dict( + sync_group.create_hierarchy(store=store, nodes=hierarchy_spec, overwrite=overwrite) + ) + elif impl == "async": + created = { + k: v + async for k, v in create_hierarchy( + store=store, nodes=hierarchy_spec, overwrite=overwrite + ) + } + else: + raise ValueError(f"Invalid impl: {impl}") + if not overwrite: + extra_group = sync_group.get_node(store=store, path="group/extra", zarr_format=zarr_format) + assert extra_group.metadata.attributes == {"path": "group/extra"} + else: + with pytest.raises(FileNotFoundError): + await get_node(store=store, path="group/extra", zarr_format=zarr_format) + assert expected_meta == {k: v.metadata for k, v in created.items()} + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +@pytest.mark.parametrize("extant_node", ["array", "group"]) +@pytest.mark.parametrize("impl", ["async", "sync"]) +async def test_create_hierarchy_existing_nodes( + impl: Literal["async", "sync"], + store: Store, + extant_node: Literal["array", "group"], + zarr_format: ZarrFormat, +) -> None: + """ + Test that create_hierarchy with overwrite = False will not overwrite an existing array or group, + and raises an exception instead. + """ + extant_node_path = "node" + + if extant_node == "array": + extant_metadata = meta_from_array( + np.zeros(4), zarr_format=zarr_format, attributes={"extant": True} + ) + new_metadata = meta_from_array(np.zeros(4), zarr_format=zarr_format) + err_cls = ContainsArrayError + else: + extant_metadata = GroupMetadata(zarr_format=zarr_format, attributes={"extant": True}) + new_metadata = GroupMetadata(zarr_format=zarr_format) + err_cls = ContainsGroupError + + # write the extant metadata + tuple(sync_group.create_nodes(store=store, nodes={extant_node_path: extant_metadata})) + + msg = f"{extant_node} exists in store {store!r} at path {extant_node_path!r}." + # ensure that we cannot invoke create_hierarchy with overwrite=False here + if impl == "sync": + with pytest.raises(err_cls, match=re.escape(msg)): + tuple( + sync_group.create_hierarchy( + store=store, nodes={"node": new_metadata}, overwrite=False + ) + ) + elif impl == "async": + with pytest.raises(err_cls, match=re.escape(msg)): + tuple( + [ + x + async for x in create_hierarchy( + store=store, nodes={"node": new_metadata}, overwrite=False + ) + ] + ) + else: + raise ValueError(f"Invalid impl: {impl}") + + # ensure that the extant metadata was not overwritten + assert ( + await get_node(store=store, path=extant_node_path, zarr_format=zarr_format) + ).metadata.attributes == {"extant": True} + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +@pytest.mark.parametrize("overwrite", [True, False]) +@pytest.mark.parametrize("group_path", ["", "foo"]) +@pytest.mark.parametrize("impl", ["async", "sync"]) +async def test_group_create_hierarchy( + store: Store, + zarr_format: ZarrFormat, + overwrite: bool, + group_path: str, + impl: Literal["async", "sync"], +) -> None: + """ + Test that the Group.create_hierarchy method creates specified nodes and returns them in a dict. + Also test that off-target nodes are not deleted, and that the root group is not deleted + """ + root_attrs = {"root": True} + g = sync_group.create_rooted_hierarchy( + store=store, + nodes={group_path: GroupMetadata(zarr_format=zarr_format, attributes=root_attrs)}, + ) + node_spec = { + "a": GroupMetadata(zarr_format=zarr_format, attributes={"name": "a"}), + "a/b": GroupMetadata(zarr_format=zarr_format, attributes={"name": "a/b"}), + "a/b/c": meta_from_array( + np.zeros(5), zarr_format=zarr_format, attributes={"name": "a/b/c"} + ), + } + # This node should be kept if overwrite is True + extant_spec = {"b": GroupMetadata(zarr_format=zarr_format, attributes={"name": "b"})} + if impl == "async": + extant_created = dict( + await _collect_aiterator(g._async_group.create_hierarchy(extant_spec, overwrite=False)) + ) + nodes_created = dict( + await _collect_aiterator( + g._async_group.create_hierarchy(node_spec, overwrite=overwrite) + ) + ) + elif impl == "sync": + extant_created = dict(g.create_hierarchy(extant_spec, overwrite=False)) + nodes_created = dict(g.create_hierarchy(node_spec, overwrite=overwrite)) + + all_members = dict(g.members(max_depth=None)) + for k, v in node_spec.items(): + assert all_members[k].metadata == v == nodes_created[k].metadata + + # if overwrite is True, the extant nodes should be erased + for k, v in extant_spec.items(): + if overwrite: + assert k in all_members + else: + assert all_members[k].metadata == v == extant_created[k].metadata + # ensure that we left the root group as-is + assert ( + sync_group.get_node(store=store, path=group_path, zarr_format=zarr_format).attrs.asdict() + == root_attrs + ) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +@pytest.mark.parametrize("overwrite", [True, False]) +def test_group_create_hierarchy_no_root( + store: Store, zarr_format: ZarrFormat, overwrite: bool +) -> None: + """ + Test that the Group.create_hierarchy method will error if the dict provided contains a root. + """ + g = Group.from_store(store, zarr_format=zarr_format) + tree = { + "": GroupMetadata(zarr_format=zarr_format, attributes={"name": "a"}), + } + with pytest.raises( + ValueError, match="It is an error to use this method to create a root node. " + ): + _ = dict(g.create_hierarchy(tree, overwrite=overwrite)) + + +class TestParseHierarchyDict: + """ + Tests for the function that parses dicts of str : Metadata pairs, ensuring that the output models a + valid Zarr hierarchy + """ + + @staticmethod + def test_normed_keys() -> None: + """ + Test that keys get normalized properly + """ + + nodes = { + "a": GroupMetadata(), + "/b": GroupMetadata(), + "": GroupMetadata(), + "/a//c////": GroupMetadata(), + } + observed = _parse_hierarchy_dict(data=nodes) + expected = {normalize_path(k): v for k, v in nodes.items()} + assert observed == expected + + @staticmethod + def test_empty() -> None: + """ + Test that an empty dict passes through + """ + assert _parse_hierarchy_dict(data={}) == {} + + @staticmethod + def test_implicit_groups() -> None: + """ + Test that implicit groups were added as needed. + """ + requested = {"a/b/c": GroupMetadata()} + expected = requested | { + "": ImplicitGroupMarker(), + "a": ImplicitGroupMarker(), + "a/b": ImplicitGroupMarker(), + } + observed = _parse_hierarchy_dict(data=requested) + assert observed == expected + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +def test_group_create_hierarchy_invalid_mixed_zarr_format( + store: Store, zarr_format: ZarrFormat +) -> None: + """ + Test that ``Group.create_hierarchy`` will raise an error if the zarr_format of the nodes is + different from the parent group. + """ + other_format = 2 if zarr_format == 3 else 3 + g = Group.from_store(store, zarr_format=other_format) + tree = { + "a": GroupMetadata(zarr_format=zarr_format, attributes={"name": "a"}), + "a/b": meta_from_array(np.zeros(5), zarr_format=zarr_format, attributes={"name": "a/c"}), + } + + msg = "The zarr_format of the nodes must be the same as the parent group." + with pytest.raises(ValueError, match=msg): + _ = tuple(g.create_hierarchy(tree)) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +@pytest.mark.parametrize("defect", ["array/array", "array/group"]) +@pytest.mark.parametrize("impl", ["async", "sync"]) +async def test_create_hierarchy_invalid_nested( + impl: Literal["async", "sync"], store: Store, defect: tuple[str, str], zarr_format: ZarrFormat +) -> None: + """ + Test that create_hierarchy will not create a Zarr array that contains a Zarr group + or Zarr array. + """ + if defect == "array/array": + hierarchy_spec = { + "array_0": meta_from_array(np.arange(3), zarr_format=zarr_format), + "array_0/subarray": meta_from_array(np.arange(4), zarr_format=zarr_format), + } + elif defect == "array/group": + hierarchy_spec = { + "array_0": meta_from_array(np.arange(3), zarr_format=zarr_format), + "array_0/subgroup": GroupMetadata(attributes={"foo": 10}, zarr_format=zarr_format), + } + + msg = "Only Zarr groups can contain other nodes." + if impl == "sync": + with pytest.raises(ValueError, match=msg): + tuple(sync_group.create_hierarchy(store=store, nodes=hierarchy_spec)) + elif impl == "async": + with pytest.raises(ValueError, match=msg): + await _collect_aiterator(create_hierarchy(store=store, nodes=hierarchy_spec)) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +@pytest.mark.parametrize("impl", ["async", "sync"]) +async def test_create_hierarchy_invalid_mixed_format( + impl: Literal["async", "sync"], store: Store +) -> None: + """ + Test that create_hierarchy will not create a Zarr group that contains a both Zarr v2 and + Zarr v3 nodes. + """ + msg = ( + "Got data with both Zarr v2 and Zarr v3 nodes, which is invalid. " + "The following keys map to Zarr v2 nodes: ['v2']. " + "The following keys map to Zarr v3 nodes: ['v3']." + "Ensure that all nodes have the same Zarr format." + ) + nodes = { + "v2": GroupMetadata(zarr_format=2), + "v3": GroupMetadata(zarr_format=3), + } + if impl == "sync": + with pytest.raises(ValueError, match=re.escape(msg)): + tuple( + sync_group.create_hierarchy( + store=store, + nodes=nodes, + ) + ) + elif impl == "async": + with pytest.raises(ValueError, match=re.escape(msg)): + await _collect_aiterator( + create_hierarchy( + store=store, + nodes=nodes, + ) + ) + else: + raise ValueError(f"Invalid impl: {impl}") + + +@pytest.mark.parametrize("store", ["memory", "local"], indirect=True) +@pytest.mark.parametrize("zarr_format", [2, 3]) +@pytest.mark.parametrize("root_key", ["", "root"]) +@pytest.mark.parametrize("impl", ["async", "sync"]) +async def test_create_rooted_hierarchy_group( + impl: Literal["async", "sync"], store: Store, zarr_format, root_key: str +) -> None: + """ + Test that the _create_rooted_hierarchy can create a group. + """ + root_meta = {root_key: GroupMetadata(zarr_format=zarr_format, attributes={"path": root_key})} + group_names = ["a", "a/b"] + array_names = ["a/b/c", "a/b/d"] + + # just to ensure that we don't use the same name twice in tests + assert set(group_names) & set(array_names) == set() + + groups_expected_meta = { + _join_paths([root_key, node_name]): GroupMetadata( + zarr_format=zarr_format, attributes={"path": node_name} + ) + for node_name in group_names + } + + arrays_expected_meta = { + _join_paths([root_key, node_name]): meta_from_array(np.zeros(4), zarr_format=zarr_format) + for node_name in array_names + } + + nodes_create = root_meta | groups_expected_meta | arrays_expected_meta + if impl == "sync": + g = sync_group.create_rooted_hierarchy(store=store, nodes=nodes_create) + assert isinstance(g, Group) + members = g.members(max_depth=None) + elif impl == "async": + g = await create_rooted_hierarchy(store=store, nodes=nodes_create) + assert isinstance(g, AsyncGroup) + members = await _collect_aiterator(g.members(max_depth=None)) + else: + raise ValueError(f"Unknown implementation: {impl}") + + assert g.metadata.attributes == {"path": root_key} + + members_observed_meta = {k: v.metadata for k, v in members} + members_expected_meta_relative = { + k.removeprefix(root_key).lstrip("/"): v + for k, v in (groups_expected_meta | arrays_expected_meta).items() + } + assert members_observed_meta == members_expected_meta_relative + + +@pytest.mark.parametrize("store", ["memory", "local"], indirect=True) +@pytest.mark.parametrize("zarr_format", [2, 3]) +@pytest.mark.parametrize("root_key", ["", "root"]) +@pytest.mark.parametrize("impl", ["async", "sync"]) +async def test_create_rooted_hierarchy_array( + impl: Literal["async", "sync"], store: Store, zarr_format, root_key: str +) -> None: + """ + Test that _create_rooted_hierarchy can create an array. + """ + + root_meta = { + root_key: meta_from_array( + np.arange(3), zarr_format=zarr_format, attributes={"path": root_key} + ) + } + nodes_create = root_meta + + if impl == "sync": + a = sync_group.create_rooted_hierarchy(store=store, nodes=nodes_create, overwrite=True) + assert isinstance(a, Array) + elif impl == "async": + a = await create_rooted_hierarchy(store=store, nodes=nodes_create, overwrite=True) + assert isinstance(a, AsyncArray) + else: + raise ValueError(f"Invalid impl: {impl}") + assert a.metadata.attributes == {"path": root_key} + + +@pytest.mark.parametrize("impl", ["async", "sync"]) +async def test_create_rooted_hierarchy_invalid(impl: Literal["async", "sync"]) -> None: + """ + Ensure _create_rooted_hierarchy will raise a ValueError if the input does not contain + a root node. + """ + zarr_format = 3 + nodes = { + "a": GroupMetadata(zarr_format=zarr_format), + "b": GroupMetadata(zarr_format=zarr_format), + } + msg = "The input does not specify a root node. " + if impl == "sync": + with pytest.raises(ValueError, match=msg): + sync_group.create_rooted_hierarchy(store=store, nodes=nodes) + elif impl == "async": + with pytest.raises(ValueError, match=msg): + await create_rooted_hierarchy(store=store, nodes=nodes) + else: + raise ValueError(f"Invalid impl: {impl}") + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +def test_group_members_performance(store: Store) -> None: + """ + Test that the execution time of Group.members is less than the number of members times the + latency for accessing each member. + """ + get_latency = 0.1 + + # use the input store to create some groups + group_create = zarr.group(store=store) + num_groups = 10 + + # Create some groups + for i in range(num_groups): + group_create.create_group(f"group{i}") + + latency_store = LatencyStore(store, get_latency=get_latency) + # create a group with some latency on get operations + group_read = zarr.group(store=latency_store) + + # check how long it takes to iterate over the groups + # if .members is sensitive to IO latency, + # this should take (num_groups * get_latency) seconds + # otherwise, it should take only marginally more than get_latency seconds + start = time.time() + _ = group_read.members() + elapsed = time.time() - start + + assert elapsed < (num_groups * get_latency) + + +@pytest.mark.parametrize("store", ["memory"], indirect=True) +def test_group_members_concurrency_limit(store: MemoryStore) -> None: + """ + Test that the execution time of Group.members can be constrained by the async concurrency + configuration setting. + """ + get_latency = 0.02 + + # use the input store to create some groups + group_create = zarr.group(store=store) + num_groups = 10 + + # Create some groups + for i in range(num_groups): + group_create.create_group(f"group{i}") + + latency_store = LatencyStore(store, get_latency=get_latency) + # create a group with some latency on get operations + group_read = zarr.group(store=latency_store) + + # check how long it takes to iterate over the groups + # if .members is sensitive to IO latency, + # this should take (num_groups * get_latency) seconds + # otherwise, it should take only marginally more than get_latency seconds + with zarr_config.set({"async.concurrency": 1}): + start = time.time() + _ = group_read.members() + elapsed = time.time() - start + + assert elapsed > num_groups * get_latency + + +@pytest.mark.parametrize("option", ["array", "group", "invalid"]) +def test_build_metadata_v3(option: Literal["array", "group", "invalid"]) -> None: + """ + Test that _build_metadata_v3 returns the correct metadata for a v3 array or group + """ + match option: + case "array": + metadata_dict = meta_from_array(np.arange(10), zarr_format=3).to_dict() + assert _build_metadata_v3(metadata_dict) == ArrayV3Metadata.from_dict(metadata_dict) + case "group": + metadata_dict = GroupMetadata(attributes={"foo": 10}, zarr_format=3).to_dict() + assert _build_metadata_v3(metadata_dict) == GroupMetadata.from_dict(metadata_dict) + case "invalid": + metadata_dict = GroupMetadata(zarr_format=3).to_dict() + metadata_dict.pop("node_type") + # TODO: fix the error message + msg = "Required key 'node_type' is missing from the provided metadata document." + with pytest.raises(MetadataValidationError, match=msg): + _build_metadata_v3(metadata_dict) + + +@pytest.mark.parametrize("roots", [("",), ("a", "b")]) +def test_get_roots(roots: tuple[str, ...]): + root_nodes = {k: GroupMetadata(attributes={"name": k}) for k in roots} + child_nodes = { + _join_paths([k, "foo"]): GroupMetadata(attributes={"name": _join_paths([k, "foo"])}) + for k in roots + } + data = root_nodes | child_nodes + assert set(_get_roots(data)) == set(roots) + + +def test_open_array_as_group(): + z = zarr.create_array(shape=(40, 50), chunks=(10, 10), dtype="f8", store={}) + with pytest.raises(ContainsArrayError): + zarr.open_group(z.store) diff --git a/tests/test_indexing.py b/tests/test_indexing.py new file mode 100644 index 0000000000..04fbdad8c6 --- /dev/null +++ b/tests/test_indexing.py @@ -0,0 +1,2305 @@ +from __future__ import annotations + +import itertools +from collections import Counter +from typing import TYPE_CHECKING, Any +from uuid import uuid4 + +import numpy as np +import numpy.typing as npt +import pytest +from numpy.testing import assert_array_equal + +import zarr +from tests.conftest import Expect, ExpectFail +from zarr import Array +from zarr.core.buffer import default_buffer_prototype +from zarr.core.chunk_grids import ChunkGrid +from zarr.core.indexing import ( + BasicSelection, + CoordinateIndexer, + CoordinateSelection, + OrthogonalSelection, + Selection, + _ArrayIndexingOrder, + _iter_grid, + _iter_regions, + ceildiv, + make_slice_selection, + normalize_integer_selection, + oindex, + oindex_set, + replace_ellipsis, +) +from zarr.registry import get_ndbuffer_class +from zarr.storage import MemoryStore, StorePath + +if TYPE_CHECKING: + from collections.abc import AsyncGenerator + + from zarr.abc.store import ByteRequest + from zarr.core.buffer import BufferPrototype + from zarr.core.buffer.core import Buffer + + +@pytest.fixture +async def store() -> AsyncGenerator[StorePath]: + return StorePath(await MemoryStore.open()) + + +def zarr_array_from_numpy_array( + store: StorePath, + a: npt.NDArray[Any], + chunk_shape: tuple[int, ...] | None = None, +) -> zarr.Array: + z = zarr.create_array( + store=store / str(uuid4()), + shape=a.shape, + dtype=a.dtype, + chunks=chunk_shape or a.shape, + chunk_key_encoding={"name": "v2", "separator": "."}, + ) + z[()] = a + return z + + +class CountingDict(MemoryStore): + counter: Counter[tuple[str, str]] + + @classmethod + async def open(cls) -> CountingDict: + store = await super().open() + store.counter = Counter() + return store + + async def get( + self, + key: str, + prototype: BufferPrototype, + byte_range: tuple[int | None, int | None] | None = None, + ) -> Buffer | None: + key_suffix = "/".join(key.split("/")[1:]) + self.counter["__getitem__", key_suffix] += 1 + return await super().get(key, prototype, byte_range) + + async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: + key_suffix = "/".join(key.split("/")[1:]) + self.counter["__setitem__", key_suffix] += 1 + return await super().set(key, value, byte_range) + + def get_sync( + self, + key: str, + *, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + key_suffix = "/".join(key.split("/")[1:]) + self.counter["__getitem__", key_suffix] += 1 + return super().get_sync(key, prototype=prototype, byte_range=byte_range) + + def set_sync(self, key: str, value: Buffer) -> None: + key_suffix = "/".join(key.split("/")[1:]) + self.counter["__setitem__", key_suffix] += 1 + return super().set_sync(key, value) + + +def test_normalize_integer_selection() -> None: + """normalize_integer_selection handles positive/negative indices and raises IndexError for out-of-bounds values.""" + assert 1 == normalize_integer_selection(1, 100) + assert 99 == normalize_integer_selection(-1, 100) + with pytest.raises(IndexError): + normalize_integer_selection(100, 100) + with pytest.raises(IndexError): + normalize_integer_selection(1000, 100) + with pytest.raises(IndexError): + normalize_integer_selection(-1000, 100) + + +def test_replace_ellipsis() -> None: + """replace_ellipsis expands Ellipsis to full slice(None) selections for 1D and 2D shapes.""" + # 1D, single item + assert (0,) == replace_ellipsis(0, (100,)) + + # 1D + assert (slice(None),) == replace_ellipsis(Ellipsis, (100,)) + assert (slice(None),) == replace_ellipsis(slice(None), (100,)) + assert (slice(None, 100),) == replace_ellipsis(slice(None, 100), (100,)) + assert (slice(0, None),) == replace_ellipsis(slice(0, None), (100,)) + assert (slice(None),) == replace_ellipsis((slice(None), Ellipsis), (100,)) + assert (slice(None),) == replace_ellipsis((Ellipsis, slice(None)), (100,)) + + # 2D, single item + assert (0, 0) == replace_ellipsis((0, 0), (100, 100)) + assert (-1, 1) == replace_ellipsis((-1, 1), (100, 100)) + + # 2D, single col/row + assert (0, slice(None)) == replace_ellipsis((0, slice(None)), (100, 100)) + assert (0, slice(None)) == replace_ellipsis((0,), (100, 100)) + assert (slice(None), 0) == replace_ellipsis((slice(None), 0), (100, 100)) + + # 2D slice + assert (slice(None), slice(None)) == replace_ellipsis(Ellipsis, (100, 100)) + assert (slice(None), slice(None)) == replace_ellipsis(slice(None), (100, 100)) + assert (slice(None), slice(None)) == replace_ellipsis((slice(None), slice(None)), (100, 100)) + assert (slice(None), slice(None)) == replace_ellipsis((Ellipsis, slice(None)), (100, 100)) + assert (slice(None), slice(None)) == replace_ellipsis((slice(None), Ellipsis), (100, 100)) + assert (slice(None), slice(None)) == replace_ellipsis( + (slice(None), Ellipsis, slice(None)), (100, 100) + ) + assert (slice(None), slice(None)) == replace_ellipsis( + (Ellipsis, slice(None), slice(None)), (100, 100) + ) + assert (slice(None), slice(None)) == replace_ellipsis( + (slice(None), slice(None), Ellipsis), (100, 100) + ) + + +@pytest.mark.parametrize( + ("value", "dtype"), + [ + (42, "uint8"), + pytest.param( + (b"aaa", 1, 4.2), + [("foo", "S3"), ("bar", "i4"), ("baz", "f8")], + marks=pytest.mark.filterwarnings("ignore::zarr.errors.UnstableSpecificationWarning"), + ), + ], +) +@pytest.mark.parametrize("use_out", [True, False]) +def test_get_basic_selection_0d(store: StorePath, use_out: bool, value: Any, dtype: Any) -> None: + """get_basic_selection on a 0-dimensional array returns the scalar value via Ellipsis and (), including the `out` buffer path.""" + # setup + arr_np = np.array(value, dtype=dtype) + arr_z = zarr_array_from_numpy_array(store, arr_np) + + assert_array_equal(arr_np, arr_z.get_basic_selection(Ellipsis)) + assert_array_equal(arr_np, arr_z[...]) + assert arr_np[()] == arr_z.get_basic_selection(()) + assert arr_np[()] == arr_z[()] + + if use_out: + # test out param + b = default_buffer_prototype().nd_buffer.from_numpy_array(np.zeros_like(arr_np)) + arr_z.get_basic_selection(Ellipsis, out=b) + assert_array_equal(arr_np, b.as_ndarray_like()) + + # todo: uncomment the structured array tests when we can make them pass, + # or delete them if we formally decide not to support structured dtypes. + + # test structured array + # value = (b"aaa", 1, 4.2) + # a = np.array(value, dtype=[("foo", "S3"), ("bar", "i4"), ("baz", "f8")]) + # z = zarr_array_from_numpy_array(store, a) + # z[()] = value + # assert_array_equal(a, z.get_basic_selection(Ellipsis)) + # assert_array_equal(a, z[...]) + # assert a[()] == z.get_basic_selection(()) + # assert a[()] == z[()] + # assert b"aaa" == z.get_basic_selection((), fields="foo") + # assert b"aaa" == z["foo"] + # assert a[["foo", "bar"]] == z.get_basic_selection((), fields=["foo", "bar"]) + # assert a[["foo", "bar"]] == z["foo", "bar"] + # # test out param + # b = NDBuffer.from_numpy_array(np.zeros_like(a)) + # z.get_basic_selection(Ellipsis, out=b) + # assert_array_equal(a, b) + # c = NDBuffer.from_numpy_array(np.zeros_like(a[["foo", "bar"]])) + # z.get_basic_selection(Ellipsis, out=c, fields=["foo", "bar"]) + # assert_array_equal(a[["foo", "bar"]], c) + + +_BASIC_1D_CASES: list[Expect[BasicSelection, None]] = [ + Expect(input=5, output=None, id="single-positive"), + Expect(input=-1, output=None, id="single-negative"), + Expect(input=slice(3, 18), output=None, id="bounded-slice"), + Expect(input=slice(0, 100), output=None, id="over-bounds-slice"), + Expect(input=slice(-18, -3), output=None, id="negative-slice"), + Expect(input=slice(0, 0), output=None, id="empty-slice"), + Expect(input=slice(-1, 0), output=None, id="empty-negative-slice"), + Expect(input=slice(None), output=None, id="full-slice"), + Expect(input=Ellipsis, output=None, id="ellipsis"), + Expect(input=(), output=None, id="empty-tuple"), + Expect(input=(Ellipsis, slice(None)), output=None, id="ellipsis-slice"), + Expect(input=slice(None, None, 3), output=None, id="stride-3"), + Expect(input=slice(3, 27, 5), output=None, id="bounded-stride"), +] + +_BASIC_1D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail( + input=slice(None, None, -1), + exception=IndexError, + id="negative-step", + msg="only slices with step >= 1 are supported", + ), + ExpectFail( + input=2.3, + exception=IndexError, + id="float", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), + # get_basic_selection and z[...] word their errors differently for a string + # selection, so this case asserts only the exception type (msg=None). + ExpectFail( + input="foo", + exception=IndexError, + id="string", + msg=None, + ), + ExpectFail( + input=b"xxx", + exception=IndexError, + id="bytes", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), + ExpectFail( + input=None, + exception=IndexError, + id="none", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), + ExpectFail( + input=(0, 0), + exception=IndexError, + id="tuple-too-many", + msg="too many indices for array; expected 1, got 2", + ), + ExpectFail( + input=(slice(None), slice(None)), + exception=IndexError, + id="two-slices", + msg="too many indices for array; expected 1, got 2", + ), +] + + +def _test_get_basic_selection( + a: npt.NDArray[Any] | Array, z: Array, selection: BasicSelection +) -> None: + expect = a[selection] + actual = z.get_basic_selection(selection) + assert_array_equal(expect, actual) + actual = z[selection] + assert_array_equal(expect, actual) + + # test out param + b = default_buffer_prototype().nd_buffer.from_numpy_array( + np.empty(shape=expect.shape, dtype=expect.dtype) + ) + z.get_basic_selection(selection, out=b) + assert_array_equal(expect, b.as_numpy_array()) + + +@pytest.mark.parametrize("case", _BASIC_1D_CASES, ids=lambda c: c.id) +def test_get_basic_selection_1d(store: StorePath, case: Expect[BasicSelection, None]) -> None: + """Basic getitem on a 1D array matches numpy for ints, slices, strides, and full selections.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_get_basic_selection(a, z, case.input) + + +@pytest.mark.parametrize("case", _BASIC_1D_BAD_CASES, ids=lambda c: c.id) +def test_get_basic_selection_1d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """Basic getitem on a 1D array rejects negative steps and invalid index types with IndexError.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.get_basic_selection(case.input) + with case.raises(): + z[case.input] + + +_BASIC_2D_CASES: list[Expect[BasicSelection, None]] = [ + Expect(input=5, output=None, id="single-row"), + Expect(input=-1, output=None, id="single-row-neg"), + Expect(input=(5, slice(None)), output=None, id="row-and-full-col"), + Expect(input=(slice(None), 3), output=None, id="single-col"), + Expect(input=(slice(None), -1), output=None, id="single-col-neg"), + Expect(input=slice(None), output=None, id="full"), + Expect(input=slice(2, 9), output=None, id="row-slice"), + Expect(input=slice(0, 0), output=None, id="empty-row-slice"), + Expect(input=(slice(2, 9), slice(1, 4)), output=None, id="2d-slice"), + Expect(input=(slice(0, 12, 3), slice(0, 5, 2)), output=None, id="strided-2d-slice"), + Expect(input=Ellipsis, output=None, id="ellipsis"), + Expect(input=(), output=None, id="empty-tuple"), +] + +_BASIC_2D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail( + input=2.3, + exception=IndexError, + id="float", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), + ExpectFail( + input="foo", + exception=IndexError, + id="string", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), + ExpectFail( + input=None, + exception=IndexError, + id="none", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), + ExpectFail( + input=(2.3, slice(None)), + exception=IndexError, + id="float-in-tuple", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), + ExpectFail( + input=slice(None, None, -1), + exception=IndexError, + id="negative-step", + msg="only slices with step >= 1 are supported", + ), + ExpectFail( + input=(slice(None), slice(None), slice(None)), + exception=IndexError, + id="too-many-dims", + msg="too many indices for array; expected 2, got 3", + ), + ExpectFail( + input=[0, 1], + exception=IndexError, + id="integer-list", + msg="unsupported selection item for basic indexing; expected integer or slice, got ", + escape=True, + ), +] + + +@pytest.mark.parametrize("case", _BASIC_2D_CASES, ids=lambda c: c.id) +def test_get_basic_selection_2d(store: StorePath, case: Expect[BasicSelection, None]) -> None: + """Basic getitem on a 2D array matches numpy for rows, cols, slices, and strides.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_get_basic_selection(a, z, case.input) + + +@pytest.mark.parametrize("case", _BASIC_2D_BAD_CASES, ids=lambda c: c.id) +def test_get_basic_selection_2d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """Basic getitem on a 2D array rejects malformed selections with IndexError.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + with case.raises(): + z.get_basic_selection(case.input) + + +def test_basic_2d_fancy_fallback(store: StorePath) -> None: + """Indexing a 2D array with paired integer lists falls back to fancy (vectorized) indexing.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + np.testing.assert_array_equal(z[([0, 1], [0, 1])], a[([0, 1], [0, 1])]) + + +def test_get_basic_selection_1d_rejects_integer_list(store: StorePath) -> None: + """get_basic_selection on a 1D array rejects an integer list (basic indexing is int/slice only).""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with pytest.raises(IndexError, match="unsupported selection item for basic indexing"): + z.get_basic_selection([1, 0]) + + +def test_get_basic_selection_2d_rejects_list_in_tuple(store: StorePath) -> None: + """get_basic_selection on a 2D array rejects a list nested in an index tuple.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + with pytest.raises(IndexError, match="unsupported selection item for basic indexing"): + z.get_basic_selection((slice(None), [0, 1])) + + +def test_fancy_indexing_fallback_on_get_setitem(store: StorePath) -> None: + """Paired integer-list indexing falls back to vectorized (fancy) get and set via `__getitem__`/`__setitem__`.""" + z = zarr_array_from_numpy_array(store, np.zeros((20, 20))) + z[[1, 2, 3], [1, 2, 3]] = 1 + np.testing.assert_array_equal( + z[:4, :4], + [ + [0, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1], + ], + ) + np.testing.assert_array_equal(z[[1, 2, 3], [1, 2, 3]], 1) + # test broadcasting + np.testing.assert_array_equal(z[1, [1, 2, 3]], [1, 0, 0]) + # test 1D fancy indexing + z2 = zarr_array_from_numpy_array(store, np.zeros(5)) + z2[[1, 2, 3]] = 1 + np.testing.assert_array_equal(z2[:], [0, 1, 1, 1, 0]) + + +@pytest.mark.parametrize( + ("index", "expected_result"), + [ + # Single iterable of integers + ([0, 1], [[0, 1, 2], [3, 4, 5]]), + # List first, then slice + (([0, 1], slice(None)), [[0, 1, 2], [3, 4, 5]]), + # List first, then slice + (([0, 1], slice(1, None)), [[1, 2], [4, 5]]), + # Slice first, then list + ((slice(0, 2), [0, 2]), [[0, 2], [3, 5]]), + # Slices only + ((slice(0, 2), slice(0, 2)), [[0, 1], [3, 4]]), + # List with repeated index + (([1, 0, 1], slice(1, None)), [[4, 5], [1, 2], [4, 5]]), + # 1D indexing + (([1, 0, 1]), [[3, 4, 5], [0, 1, 2], [3, 4, 5]]), + ], +) +def test_orthogonal_indexing_fallback_on_getitem_2d( + store: StorePath, index: Selection, expected_result: npt.ArrayLike +) -> None: + """ + Tests the orthogonal indexing fallback on __getitem__ for a 2D matrix. + + In addition to checking expected behavior, all indexing + is also checked against numpy. + """ + # [0, 1, 2], + # [3, 4, 5], + # [6, 7, 8] + a = np.arange(9).reshape(3, 3) + z = zarr_array_from_numpy_array(store, a) + + np.testing.assert_array_equal(z[index], a[index], err_msg="Indexing disagrees with numpy") + np.testing.assert_array_equal(z[index], expected_result) + + +def test_setitem_zarr_array_as_value() -> None: + """Assigning a zarr array as a value in `__setitem__` does not raise a SyncError (regression for GH3611).""" + # Regression test for https://github.com/zarr-developers/zarr-python/issues/3611 + # Assigning a zarr Array as the value used to raise + # SyncError("Calling sync() from within a running loop") because the codec + # pipeline tried to index the zarr array inside an already-running async loop. + src = zarr.array(np.arange(10), chunks=(5,)) + dst = zarr.zeros(10, chunks=(5,), dtype=src.dtype) + + # Full assignment + dst[:] = src + assert_array_equal(dst[:], np.arange(10)) + + # Slice assignment + dst2 = zarr.zeros(10, chunks=(5,), dtype=src.dtype) + dst2[2:7] = src[2:7] + assert_array_equal(dst2[2:7], np.arange(2, 7)) + + +@pytest.mark.skip(reason="fails on ubuntu, windows; numpy=2.2; in CI") +def test_setitem_repeated_index(): + """oindex assignment with repeated indices writes the last value for each duplicated index position.""" + array = zarr.array(data=np.zeros((4,)), chunks=(1,)) + indexer = np.array([-1, -1, 0, 0]) + array.oindex[(indexer,)] = [0, 1, 2, 3] + np.testing.assert_array_equal(array[:], np.array([3, 0, 0, 1])) + + indexer = np.array([-1, 0, 0, -1]) + array.oindex[(indexer,)] = [0, 1, 2, 3] + np.testing.assert_array_equal(array[:], np.array([2, 0, 0, 3])) + + +Index = list[int] | tuple[slice | int | list[int], ...] + + +@pytest.mark.parametrize( + ("index", "expected_result"), + [ + # Single iterable of integers + ([0, 1], [[[0, 1, 2], [3, 4, 5], [6, 7, 8]], [[9, 10, 11], [12, 13, 14], [15, 16, 17]]]), + # One slice, two integers + ((slice(0, 2), 1, 1), [4, 13]), + # One integer, two slices + ((slice(0, 2), 1, slice(0, 2)), [[3, 4], [12, 13]]), + # Two slices and a list + ((slice(0, 2), [1, 2], slice(0, 2)), [[[3, 4], [6, 7]], [[12, 13], [15, 16]]]), + ], +) +def test_orthogonal_indexing_fallback_on_getitem_3d( + store: StorePath, index: Selection, expected_result: npt.ArrayLike +) -> None: + """ + Tests the orthogonal indexing fallback on __getitem__ for a 3D matrix. + + In addition to checking expected behavior, all indexing + is also checked against numpy. + """ + # [[[ 0, 1, 2], + # [ 3, 4, 5], + # [ 6, 7, 8]], + + # [[ 9, 10, 11], + # [12, 13, 14], + # [15, 16, 17]], + + # [[18, 19, 20], + # [21, 22, 23], + # [24, 25, 26]]] + a = np.arange(27).reshape(3, 3, 3) + z = zarr_array_from_numpy_array(store, a) + + np.testing.assert_array_equal(z[index], a[index], err_msg="Indexing disagrees with numpy") + np.testing.assert_array_equal(z[index], expected_result) + + +@pytest.mark.parametrize( + ("index", "expected_result"), + [ + # Single iterable of integers + ([0, 1], [[1, 1, 1], [1, 1, 1], [0, 0, 0]]), + # List and slice combined + (([0, 1], slice(1, 3)), [[0, 1, 1], [0, 1, 1], [0, 0, 0]]), + # Index repetition is ignored on setitem + (([0, 1, 1, 1, 1, 1, 1], slice(1, 3)), [[0, 1, 1], [0, 1, 1], [0, 0, 0]]), + # Slice with step + (([0, 2], slice(None, None, 2)), [[1, 0, 1], [0, 0, 0], [1, 0, 1]]), + ], +) +def test_orthogonal_indexing_fallback_on_setitem_2d( + store: StorePath, index: Selection, expected_result: npt.ArrayLike +) -> None: + """ + Tests the orthogonal indexing fallback on __setitem__ for a 3D matrix. + + In addition to checking expected behavior, all indexing + is also checked against numpy. + """ + # Slice + fancy index + a = np.zeros((3, 3)) + z = zarr_array_from_numpy_array(store, a) + z[index] = 1 + a[index] = 1 + np.testing.assert_array_equal(z[:], expected_result) + np.testing.assert_array_equal(z[:], a, err_msg="Indexing disagrees with numpy") + + +def test_fancy_indexing_doesnt_mix_with_implicit_slicing(store: StorePath) -> None: + """Fancy indexing that would require implicit slicing over an unspecified axis raises IndexError on a 3D array.""" + z2 = zarr_array_from_numpy_array(store, np.zeros((5, 5, 5))) + with pytest.raises(IndexError): + z2[[1, 2, 3], [1, 2, 3]] = 2 + with pytest.raises(IndexError): + np.testing.assert_array_equal(z2[[1, 2, 3], [1, 2, 3]], 0) + with pytest.raises(IndexError): + z2[..., [1, 2, 3]] = 2 # type: ignore[index] + with pytest.raises(IndexError): + np.testing.assert_array_equal(z2[..., [1, 2, 3]], 0) # type: ignore[index] + + +@pytest.mark.parametrize( + ("value", "dtype"), + [ + (42, "uint8"), + pytest.param( + (b"aaa", 1, 4.2), + [("foo", "S3"), ("bar", "i4"), ("baz", "f8")], + marks=pytest.mark.filterwarnings("ignore::zarr.errors.UnstableSpecificationWarning"), + ), + ], +) +def test_set_basic_selection_0d( + store: StorePath, value: Any, dtype: str | list[tuple[str, str]] +) -> None: + """set_basic_selection and `__setitem__` write scalar values correctly to a 0-dimensional array.""" + arr_np = np.array(value, dtype=dtype) + arr_np_zeros = np.zeros_like(arr_np, dtype=dtype) + arr_z = zarr_array_from_numpy_array(store, arr_np_zeros) + assert_array_equal(arr_np_zeros, arr_z) + + arr_z.set_basic_selection(Ellipsis, value) + assert_array_equal(arr_np, arr_z) + arr_z[...] = arr_np_zeros[()] + assert_array_equal(arr_np_zeros, arr_z) + arr_z[...] = value + assert_array_equal(arr_np, arr_z) + + # todo: uncomment the structured array tests when we can make them pass, + # or delete them if we formally decide not to support structured dtypes. + + # arr_z.set_basic_selection(Ellipsis, v["foo"], fields="foo") + # assert v["foo"] == arr_z["foo"] + # assert arr_np_zeros["bar"] == arr_z["bar"] + # assert arr_np_zeros["baz"] == arr_z["baz"] + # arr_z["bar"] = v["bar"] + # assert v["foo"] == arr_z["foo"] + # assert v["bar"] == arr_z["bar"] + # assert arr_np_zeros["baz"] == arr_z["baz"] + # # multiple field assignment not supported + # with pytest.raises(IndexError): + # arr_z.set_basic_selection(Ellipsis, v[["foo", "bar"]], fields=["foo", "bar"]) + # with pytest.raises(IndexError): + # arr_z[..., "foo", "bar"] = v[["foo", "bar"]] + + +def _test_get_orthogonal_selection( + a: npt.NDArray[Any], z: Array, selection: OrthogonalSelection +) -> None: + expect = oindex(a, selection) + actual = z.get_orthogonal_selection(selection) + assert_array_equal(expect, actual) + actual = z.oindex[selection] + assert_array_equal(expect, actual) + + +_ORTHO_1D_BOOL_CASES: list[Expect[OrthogonalSelection, None]] = [ + Expect(input=np.zeros(30, dtype=bool), output=None, id="empty-mask"), + Expect(input=np.ones(30, dtype=bool), output=None, id="full-mask"), + Expect(input=np.arange(30) % 2 == 0, output=None, id="alternating-mask"), + Expect(input=np.arange(30) == 7, output=None, id="single-true"), + Expect( + input=np.isin(np.arange(30), [0, 1, 8, 15, 29]), + output=None, + id="sparse-cross-chunk", + ), +] + +_ORTHO_1D_BOOL_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail( + input=np.zeros(5, dtype=bool), + exception=IndexError, + id="mask-too-short", + msg="wrong length for dimension; expected 30, got 5", + ), + ExpectFail( + input=np.zeros(50, dtype=bool), + exception=IndexError, + id="mask-too-long", + msg="wrong length for dimension; expected 30, got 50", + ), + ExpectFail( + input=[[True, False], [False, True]], + exception=IndexError, + id="mask-too-many-dims", + msg="must be 1-dimensional only", + ), +] + + +@pytest.mark.parametrize("case", _ORTHO_1D_BOOL_CASES, ids=lambda c: c.id) +def test_get_orthogonal_selection_1d_bool( + store: StorePath, case: Expect[OrthogonalSelection, None] +) -> None: + """oindex with a 1D boolean mask matches numpy across chunk boundaries.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_get_orthogonal_selection(a, z, case.input) + + +@pytest.mark.parametrize("case", _ORTHO_1D_BOOL_BAD_CASES, ids=lambda c: c.id) +def test_get_orthogonal_selection_1d_bool_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """oindex rejects masks of the wrong length or dimensionality with IndexError.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.oindex[case.input] + + +_ORTHO_1D_INT_CASES: list[Expect[OrthogonalSelection, None]] = [ + Expect(input=[0, 8, 15, 29], output=None, id="sorted"), + Expect(input=[3, 29, 1, 16], output=None, id="unsorted"), + Expect(input=[2, 2, 8, 8], output=None, id="duplicates"), + Expect(input=[0, 3, 10, -23, -12, -1], output=None, id="wraparound"), + Expect(input=[15], output=None, id="single"), +] + +_ORTHO_1D_INT_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail( + input=[31], + exception=IndexError, + id="out-of-bounds-high", + msg="index out of bounds for dimension with length 30", + ), + ExpectFail( + input=[-31], + exception=IndexError, + id="out-of-bounds-low", + msg="index out of bounds for dimension with length 30", + ), + ExpectFail( + input=[[2, 4], [6, 8]], + exception=IndexError, + id="too-many-dims", + msg="integer arrays in an orthogonal selection must be 1-dimensional only", + ), +] + + +@pytest.mark.parametrize("case", _ORTHO_1D_INT_CASES, ids=lambda c: c.id) +def test_get_orthogonal_selection_1d_int( + store: StorePath, case: Expect[OrthogonalSelection, None] +) -> None: + """oindex with a 1D integer array matches numpy, including wraparound and duplicates.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_get_orthogonal_selection(a, z, case.input) + + +@pytest.mark.parametrize("case", _ORTHO_1D_INT_BAD_CASES, ids=lambda c: c.id) +def test_get_orthogonal_selection_1d_int_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """oindex rejects out-of-bounds or multi-dimensional integer selections with IndexError.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.get_orthogonal_selection(case.input) + with case.raises(): + z.oindex[case.input] + + +_ORTHO_2D_IX0_BOOL = np.isin(np.arange(12), [0, 5, 11]) # rows 0, 5, 11 +_ORTHO_2D_IX1_BOOL = np.array([True, False, True, False, True]) # cols 0, 2, 4 +_ORTHO_2D_IX0_INT = np.array([0, 5, 11]) +_ORTHO_2D_IX1_INT = np.array([0, 2, 4]) + +_ORTHO_2D_CASES: list[Expect[OrthogonalSelection, None]] = [ + Expect(input=(_ORTHO_2D_IX0_BOOL, _ORTHO_2D_IX1_BOOL), output=None, id="both-bool"), + Expect(input=(_ORTHO_2D_IX0_BOOL, slice(1, 4)), output=None, id="bool-slice"), + Expect(input=(_ORTHO_2D_IX0_BOOL, slice(0, 5, 2)), output=None, id="bool-strided-slice"), + Expect(input=(slice(2, 9), _ORTHO_2D_IX1_BOOL), output=None, id="slice-bool"), + Expect(input=(slice(0, 12, 4), _ORTHO_2D_IX1_BOOL), output=None, id="strided-slice-bool"), + Expect(input=(_ORTHO_2D_IX0_BOOL, 3), output=None, id="bool-int"), + Expect(input=(7, _ORTHO_2D_IX1_BOOL), output=None, id="int-bool"), + Expect(input=(_ORTHO_2D_IX0_INT, _ORTHO_2D_IX1_INT), output=None, id="both-int"), + Expect(input=(_ORTHO_2D_IX0_INT, _ORTHO_2D_IX1_BOOL), output=None, id="int-array-bool-array"), + Expect(input=(_ORTHO_2D_IX0_BOOL, _ORTHO_2D_IX1_INT), output=None, id="bool-array-int-array"), + Expect(input=7, output=None, id="single-row"), + Expect(input=(slice(None), 3), output=None, id="single-col"), + Expect(input=(slice(None), slice(None)), output=None, id="full"), + Expect(input=slice(2, 9), output=None, id="row-slice"), +] + +_ORTHO_2D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail( + input=2.3, + exception=IndexError, + id="float-index", + msg="unsupported selection item for orthogonal indexing", + ), + # get_orthogonal_selection and oindex raise different messages for a string + # selection, so assert only the exception type. + ExpectFail( + input="foo", + exception=IndexError, + id="string-index", + msg=None, + ), + ExpectFail( + input=None, + exception=IndexError, + id="none-index", + msg="unsupported selection item for orthogonal indexing", + ), + ExpectFail( + input=slice(None, None, -1), + exception=IndexError, + id="negative-step", + msg="only slices with step >= 1 are supported", + ), + ExpectFail( + input=(0, 0, 0), + exception=IndexError, + id="too-many-dims", + msg="too many indices for array", + ), +] + + +@pytest.mark.parametrize("case", _ORTHO_2D_CASES, ids=lambda c: c.id) +def test_get_orthogonal_selection_2d( + store: StorePath, case: Expect[OrthogonalSelection, None] +) -> None: + """oindex on a 2D array matches numpy for array/slice/int combinations per axis.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_get_orthogonal_selection(a, z, case.input) + + +@pytest.mark.parametrize("case", _ORTHO_2D_BAD_CASES, ids=lambda c: c.id) +def test_get_orthogonal_selection_2d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """oindex on a 2D array rejects malformed selections with IndexError.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + with case.raises(): + z.get_orthogonal_selection(case.input) + with case.raises(): + z.oindex[case.input] + + +_ORTHO_3D_IX0_BOOL = np.isin(np.arange(7), [0, 3, 6]) # axis 0 +_ORTHO_3D_IX1_BOOL = np.isin(np.arange(6), [0, 2, 5]) # axis 1 +_ORTHO_3D_IX2_BOOL = np.isin(np.arange(10), [0, 4, 9]) # axis 2 +_ORTHO_3D_IX0_INT = np.array([0, 3, 6]) +_ORTHO_3D_IX1_INT = np.array([0, 2, 5]) +_ORTHO_3D_IX2_INT = np.array([0, 4, 9]) + +_ORTHO_3D_CASES: list[Expect[OrthogonalSelection, None]] = [ + # single value + Expect(input=(5, 3, 8), output=None, id="single-value"), + Expect(input=(-1, -1, -1), output=None, id="all-negative"), + # index all axes with arrays + Expect( + input=(_ORTHO_3D_IX0_BOOL, _ORTHO_3D_IX1_BOOL, _ORTHO_3D_IX2_BOOL), + output=None, + id="three-bool-arrays", + ), + Expect( + input=(_ORTHO_3D_IX0_INT, _ORTHO_3D_IX1_INT, _ORTHO_3D_IX2_INT), + output=None, + id="three-int-arrays", + ), + # mixed indexing with single array / slices + Expect( + input=(_ORTHO_3D_IX0_BOOL, slice(1, 5), slice(2, 9)), output=None, id="array-slice-slice" + ), + Expect( + input=(slice(1, 6), _ORTHO_3D_IX1_BOOL, slice(2, 9)), output=None, id="slice-array-slice" + ), + Expect( + input=(slice(1, 6), slice(1, 5), _ORTHO_3D_IX2_BOOL), output=None, id="slice-slice-array" + ), + Expect( + input=(_ORTHO_3D_IX0_BOOL, slice(0, 6, 2), slice(0, 10, 3)), + output=None, + id="array-strided-strided", + ), + Expect( + input=(slice(0, 7, 2), _ORTHO_3D_IX1_BOOL, slice(0, 10, 3)), + output=None, + id="strided-array-strided", + ), + Expect( + input=(slice(0, 7, 2), slice(0, 6, 2), _ORTHO_3D_IX2_BOOL), + output=None, + id="strided-strided-array", + ), + # mixed indexing with single array / ints + Expect(input=(_ORTHO_3D_IX0_BOOL, 3, 8), output=None, id="array-int-int"), + Expect(input=(5, _ORTHO_3D_IX1_BOOL, 8), output=None, id="int-array-int"), + Expect(input=(5, 3, _ORTHO_3D_IX2_BOOL), output=None, id="int-int-array"), + # mixed indexing with single array / slice / int + Expect(input=(_ORTHO_3D_IX0_BOOL, slice(1, 5), 8), output=None, id="array-slice-int"), + Expect(input=(5, _ORTHO_3D_IX1_BOOL, slice(2, 9)), output=None, id="int-array-slice"), + Expect(input=(slice(1, 6), 3, _ORTHO_3D_IX2_BOOL), output=None, id="slice-int-array"), + # mixed indexing with two arrays / slice + Expect( + input=(_ORTHO_3D_IX0_BOOL, _ORTHO_3D_IX1_BOOL, slice(2, 9)), + output=None, + id="two-arrays-slice", + ), + Expect( + input=(slice(1, 6), _ORTHO_3D_IX1_BOOL, _ORTHO_3D_IX2_BOOL), + output=None, + id="slice-two-arrays", + ), + Expect( + input=(_ORTHO_3D_IX0_BOOL, slice(1, 5), _ORTHO_3D_IX2_BOOL), + output=None, + id="array-slice-array", + ), + # mixed indexing with two arrays / integer + Expect(input=(_ORTHO_3D_IX0_BOOL, _ORTHO_3D_IX1_BOOL, 8), output=None, id="two-arrays-int"), + Expect(input=(5, _ORTHO_3D_IX1_BOOL, _ORTHO_3D_IX2_BOOL), output=None, id="int-two-arrays"), + Expect(input=(_ORTHO_3D_IX0_BOOL, 3, _ORTHO_3D_IX2_BOOL), output=None, id="array-int-array"), +] + + +@pytest.mark.parametrize("case", _ORTHO_3D_CASES, ids=lambda c: c.id) +def test_get_orthogonal_selection_3d( + store: StorePath, case: Expect[OrthogonalSelection, None] +) -> None: + """oindex on a 3D array matches numpy for array/slice/int combinations per axis.""" + a = np.arange(420, dtype=int).reshape(7, 6, 10) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(3, 2, 4)) + _test_get_orthogonal_selection(a, z, case.input) + + +def test_orthogonal_indexing_edge_cases(store: StorePath) -> None: + """oindex on a shape-(1, 2, 3) array correctly handles mixing integer, slice, int-list, and bool-list indexers per axis.""" + a = np.arange(6).reshape(1, 2, 3) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(1, 2, 3)) + + expect = oindex(a, (0, slice(None), [0, 1, 2])) + actual = z.oindex[0, :, [0, 1, 2]] + assert_array_equal(expect, actual) + + expect = oindex(a, (0, slice(None), [True, True, True])) + actual = z.oindex[0, :, [True, True, True]] + assert_array_equal(expect, actual) + + +def _test_set_orthogonal_selection( + v: npt.NDArray[np.int_], a: npt.NDArray[Any], z: Array, selection: OrthogonalSelection +) -> None: + for value in 42, oindex(v, selection), oindex(v, selection).tolist(): + if isinstance(value, list) and value == []: + # skip these cases as cannot preserve all dimensions + continue + # setup expectation + a[:] = 0 + oindex_set(a, selection, value) + # long-form API + z[:] = 0 + z.set_orthogonal_selection(selection, value) + assert_array_equal(a, z[:]) + # short-form API + z[:] = 0 + z.oindex[selection] = value + assert_array_equal(a, z[:]) + + +@pytest.mark.parametrize("case", _ORTHO_1D_BOOL_CASES + _ORTHO_1D_INT_CASES, ids=lambda c: c.id) +def test_set_orthogonal_selection_1d( + store: StorePath, case: Expect[OrthogonalSelection, None] +) -> None: + """set_orthogonal_selection on a 1D array round-trips through numpy for masks and int arrays.""" + v = np.arange(30, dtype=int) + a = np.empty_like(v) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_set_orthogonal_selection(v, a, z, case.input) + + +def test_set_item_1d_last_two_chunks(store: StorePath): + """Regression for GH2849: `__setitem__` correctly writes to the last two chunks of a 1D array and to 0-dimensional scalar arrays.""" + # regression test for GH2849 + g = zarr.open_group(store=store, zarr_format=3, mode="w") + a = g.create_array("bar", shape=(10,), chunks=(3,), dtype=int) + data = np.array([7, 8, 9]) + a[slice(7, 10)] = data + np.testing.assert_array_equal(a[slice(7, 10)], data) + + z = zarr.open_group(store=store, mode="w") + z.create_array("zoo", dtype=float, shape=()) + z["zoo"][...] = np.array(1) # why doesn't [:] work? + np.testing.assert_equal(z["zoo"][()], np.array(1)) + + z = zarr.open_group(store=store, mode="w") + z.create_array("zoo", dtype=float, shape=()) + z["zoo"][...] = 1 # why doesn't [:] work? + np.testing.assert_equal(z["zoo"][()], np.array(1)) + + +@pytest.mark.parametrize("case", _ORTHO_2D_CASES, ids=lambda c: c.id) +def test_set_orthogonal_selection_2d( + store: StorePath, case: Expect[OrthogonalSelection, None] +) -> None: + """set_orthogonal_selection on a 2D array round-trips through numpy.""" + v = np.arange(60, dtype=int).reshape(12, 5) + a = np.empty_like(v) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_set_orthogonal_selection(v, a, z, case.input) + + +@pytest.mark.parametrize("case", _ORTHO_3D_CASES, ids=lambda c: c.id) +def test_set_orthogonal_selection_3d( + store: StorePath, case: Expect[OrthogonalSelection, None] +) -> None: + """set_orthogonal_selection on a 3D array round-trips through numpy.""" + v = np.arange(420, dtype=int).reshape(7, 6, 10) + a = np.empty_like(v) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(3, 2, 4)) + _test_set_orthogonal_selection(v, a, z, case.input) + + +def test_orthogonal_indexing_fallback_on_get_setitem(store: StorePath) -> None: + """Paired integer-list indexing on a 2D array falls back to orthogonal get and set via `__getitem__`/`__setitem__`.""" + z = zarr_array_from_numpy_array(store, np.zeros((20, 20))) + z[[1, 2, 3], [1, 2, 3]] = 1 + np.testing.assert_array_equal( + z[:4, :4], + [ + [0, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1], + ], + ) + np.testing.assert_array_equal(z[[1, 2, 3], [1, 2, 3]], 1) + # test broadcasting + np.testing.assert_array_equal(z[1, [1, 2, 3]], [1, 0, 0]) + # test 1D fancy indexing + z2 = zarr_array_from_numpy_array(store, np.zeros(5)) + z2[[1, 2, 3]] = 1 + np.testing.assert_array_equal(z2[:], [0, 1, 1, 1, 0]) + + +def _test_get_coordinate_selection( + a: npt.NDArray, z: Array, selection: CoordinateSelection +) -> None: + expect = a[selection] + actual = z.get_coordinate_selection(selection) + assert_array_equal(expect, actual) + actual = z.vindex[selection] + assert_array_equal(expect, actual) + + +_COORD_1D_CASES: list[Expect[CoordinateSelection, None]] = [ + Expect(input=5, output=None, id="single"), + Expect(input=-1, output=None, id="single-negative"), + Expect(input=[0, 3, 10, -23, -12, -1], output=None, id="wraparound"), + Expect(input=[3, 25, 8, 17], output=None, id="out-of-order"), + Expect(input=[1, 8, 15, 29], output=None, id="sorted"), + Expect(input=[29, 15, 8, 1], output=None, id="reversed"), + Expect(input=np.array([29, 15, 8, 1], dtype=np.uint32), output=None, id="reversed-uint"), + Expect(input=[2, 2, 8, 8], output=None, id="duplicates"), + Expect(input=np.array([[2, 4], [6, 8]]), output=None, id="multi-dim"), + # sorted-1D fast path (chunk_shape=(7,)): boundaries, contiguous runs, single chunk, full + Expect(input=[0, 6, 7, 13, 14, 28, 29], output=None, id="sorted-chunk-boundaries"), + Expect(input=[0, 1, 2, 8, 9, 10, 21, 22, 23], output=None, id="sorted-contiguous-runs"), + Expect(input=[1, 2, 3, 4, 5, 6], output=None, id="sorted-single-chunk"), + Expect(input=list(range(30)), output=None, id="sorted-full"), + Expect(input=[0, 0, 7, 7, 7, 29], output=None, id="sorted-duplicates-boundaries"), +] + +# get_coordinate_selection and vindex word their errors differently for these +# invalid-type inputs, so these cases assert only the exception type (msg=None). +_COORD_1D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail(input=slice(5, 15), exception=IndexError, id="slice", msg=None), + ExpectFail(input=slice(None), exception=IndexError, id="full-slice", msg=None), + ExpectFail(input=Ellipsis, exception=IndexError, id="ellipsis", msg=None), + ExpectFail(input=2.3, exception=IndexError, id="float", msg=None), + ExpectFail(input="foo", exception=IndexError, id="string", msg=None), + ExpectFail(input=b"xxx", exception=IndexError, id="bytes", msg=None), + ExpectFail(input=None, exception=IndexError, id="none", msg=None), + ExpectFail(input=(0, 0), exception=IndexError, id="tuple-pair", msg=None), + ExpectFail(input=(slice(None), slice(None)), exception=IndexError, id="two-slices", msg=None), + ExpectFail( + input=[31], + exception=IndexError, + id="out-of-bounds-high", + msg="index out of bounds for dimension with length 30", + ), + ExpectFail( + input=[-31], + exception=IndexError, + id="out-of-bounds-low", + msg="index out of bounds for dimension with length 30", + ), +] + +_COORD_2D_IX0 = np.array([0, 5, 11, 2, 8]) +_COORD_2D_IX1 = np.array([1, 3, 4, 0, 2]) + +_COORD_2D_CASES: list[Expect[CoordinateSelection, None]] = [ + Expect(input=(5, 4), output=None, id="single"), + Expect(input=(-1, -1), output=None, id="single-negative"), + Expect(input=(_COORD_2D_IX0, _COORD_2D_IX1), output=None, id="both-arrays"), + # scalar broadcasts in coordinate indexing (numpy and zarr agree) + Expect(input=(np.array([0, 5, 11]), 4), output=None, id="array-int"), + Expect(input=(7, np.array([0, 2, 4])), output=None, id="int-array"), + Expect(input=([3, 3, 4, 2, 5], [1, 3, 4, 0, 2]), output=None, id="not-monotonic-first"), + Expect(input=([1, 1, 2, 2, 5], [1, 3, 2, 1, 0]), output=None, id="not-monotonic-second"), + Expect( + input=(np.array([[1, 1, 2], [2, 2, 5]]), np.array([[1, 3, 2], [1, 0, 0]])), + output=None, + id="multi-dim", + ), +] + +_COORD_2D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail( + input=(slice(5, 15), [1, 2, 3]), + exception=IndexError, + id="slice-with-array", + msg=None, + ), + ExpectFail( + input=([1, 2, 3], slice(5, 15)), + exception=IndexError, + id="array-with-slice", + msg=None, + ), + ExpectFail( + input=(Ellipsis, [1, 2, 3]), + exception=IndexError, + id="ellipsis-with-array", + msg=None, + ), + ExpectFail(input=Ellipsis, exception=IndexError, id="ellipsis", msg=None), + ExpectFail( + input=(np.array([12]), np.array([0])), + exception=IndexError, + id="out-of-bounds-axis0", + msg="index out of bounds for dimension with length 12", + ), + ExpectFail( + input=(np.array([0]), np.array([5])), + exception=IndexError, + id="out-of-bounds-axis1", + msg="index out of bounds for dimension with length 5", + ), +] + + +@pytest.mark.parametrize("case", _COORD_1D_CASES, ids=lambda c: c.id) +def test_get_coordinate_selection_1d( + store: StorePath, case: Expect[CoordinateSelection, None] +) -> None: + """vindex and get_coordinate_selection on a 1D array match numpy for int, list, and multi-dim selections.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_get_coordinate_selection(a, z, case.input) + + +@pytest.mark.parametrize( + ("chunks", "shards"), + [((7,), None), ((7,), (21,))], + ids=["chunked", "sharded"], +) +def test_get_coordinate_selection_1d_fast_path( + store: StorePath, chunks: tuple[int, ...], shards: tuple[int, ...] | None +) -> None: + """The sorted-1D-runs fast path in CoordinateIndexer matches numpy on chunked and sharded arrays. + + Exercises the boundary/run/single-chunk/full-array cases that the fast path optimizes, plus + the sharded case where the top-level (shard) grid drives chunk assignment. + """ + a = np.arange(210, dtype=int) + z = zarr.create_array( + store=store / str(uuid4()), + shape=a.shape, + dtype=a.dtype, + chunks=chunks, + shards=shards, + ) + z[:] = a + rng = np.random.default_rng(0) + selections = [ + np.sort(rng.choice(210, 60, replace=False)), # scattered sorted + np.array([0, 6, 7, 20, 21, 209]), # chunk/shard boundaries + np.concatenate([np.arange(s, s + 5) for s in (0, 33, 100, 180)]), # contiguous runs + np.array([0, 0, 7, 7, 209]), # sorted with duplicates + np.arange(210), # whole array + np.array([5]), # single element + ] + for sel in selections: + assert_array_equal(a[sel], z.get_coordinate_selection(sel)) + assert_array_equal(a[sel], z.vindex[sel]) + + +def test_coordinate_indexer_1d_last_chunk_boundary_does_not_overflow() -> None: + max_intp = np.iinfo(np.intp).max + chunk_size = max_intp // 2 + 1 + coords = np.arange(max_intp - 4, max_intp, dtype=np.intp) + chunk_grid = ChunkGrid.from_sizes((max_intp,), (chunk_size,)) + + (projection,) = tuple(CoordinateIndexer((coords,), (max_intp,), chunk_grid)) + + assert projection.chunk_coords == (1,) + assert_array_equal(projection.chunk_selection[0], coords - chunk_size) + assert projection.out_selection == slice(0, 4) + + +@pytest.mark.parametrize("coord_dtype", [np.int8, np.uint8, np.uint32]) +def test_coordinate_selection_1d_narrow_dtype_large_chunk( + store: StorePath, coord_dtype: type[np.integer[Any]] +) -> None: + source = np.arange(1_000) + coords = np.arange(10, dtype=coord_dtype) + z = zarr_array_from_numpy_array(store, source, chunk_shape=(1_000,)) + + assert_array_equal(z.get_coordinate_selection(coords), source[coords]) + assert_array_equal(z.vindex[coords], source[coords]) + assert_array_equal(z[coords], source[coords]) + + expected = source.copy() + expected[coords] = -1 + z.set_coordinate_selection(coords, -1) + assert_array_equal(z[:], expected) + z[:] = source + z.vindex[coords] = -1 + assert_array_equal(z[:], expected) + + +def test_coordinate_indexer_1d_sparse_selection_uses_general_path( + monkeypatch: pytest.MonkeyPatch, +) -> None: + coords = np.array([0, 99]) + chunk_grid = ChunkGrid.from_sizes((100,), (1,)) + + def unexpected_searchsorted(*args: Any, **kwargs: Any) -> None: + pytest.fail("sparse coordinate selection should not call searchsorted") + + monkeypatch.setattr(np, "searchsorted", unexpected_searchsorted) + projections = tuple(CoordinateIndexer((coords,), (100,), chunk_grid)) + + assert tuple(projection.chunk_coords for projection in projections) == ((0,), (99,)) + + +def test_get_coordinate_selection_1d_irregular_grid(store: StorePath) -> None: + """Coordinate selections on an irregular (rectilinear) chunk grid bypass the sorted-1D fast + path (which requires a regular grid) and still match numpy via the general path.""" + a = np.arange(30, dtype=int) + with zarr.config.set({"array.rectilinear_chunks": True}): + z = zarr.create_array( + store=store / str(uuid4()), + shape=a.shape, + dtype=a.dtype, + chunks=((3, 3, 4, 5, 5, 5, 5),), + ) + z[:] = a + for sel in (np.array([1, 8, 15, 29]), np.array([0, 3, 3, 29]), np.arange(30)): + assert_array_equal(a[sel], z.get_coordinate_selection(sel)) + + +@pytest.mark.parametrize("case", _COORD_1D_BAD_CASES, ids=lambda c: c.id) +def test_get_coordinate_selection_1d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """get_coordinate_selection and vindex both raise IndexError for invalid 1D selections.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.get_coordinate_selection(case.input) # type: ignore[arg-type] + with case.raises(): + z.vindex[case.input] # type: ignore[index] + + +@pytest.mark.parametrize("case", _COORD_2D_CASES, ids=lambda c: c.id) +def test_get_coordinate_selection_2d( + store: StorePath, case: Expect[CoordinateSelection, None] +) -> None: + """vindex and get_coordinate_selection on a 2D array match numpy for coordinate selections.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_get_coordinate_selection(a, z, case.input) + + +@pytest.mark.parametrize("case", _COORD_2D_BAD_CASES, ids=lambda c: c.id) +def test_get_coordinate_selection_2d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """get_coordinate_selection raises IndexError when slices or Ellipsis appear in a 2D coordinate selection.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + with case.raises(): + z.get_coordinate_selection(case.input) # type: ignore[arg-type] + + +def _test_set_coordinate_selection( + v: npt.NDArray, a: npt.NDArray, z: Array, selection: CoordinateSelection +) -> None: + for value in 42, v[selection], v[selection].tolist(): + # setup expectation + a[:] = 0 + a[selection] = value + # test long-form API + z[:] = 0 + z.set_coordinate_selection(selection, value) + assert_array_equal(a, z[:]) + # test short-form API + z[:] = 0 + z.vindex[selection] = value + assert_array_equal(a, z[:]) + + +@pytest.mark.parametrize("case", _COORD_1D_CASES, ids=lambda c: c.id) +def test_set_coordinate_selection_1d( + store: StorePath, case: Expect[CoordinateSelection, None] +) -> None: + """set_coordinate_selection and vindex assignment on a 1D array round-trip through numpy.""" + v = np.arange(30, dtype=int) + a = np.empty_like(v) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_set_coordinate_selection(v, a, z, case.input) + + +@pytest.mark.parametrize("case", _COORD_2D_CASES, ids=lambda c: c.id) +def test_set_coordinate_selection_2d( + store: StorePath, case: Expect[CoordinateSelection, None] +) -> None: + """set_coordinate_selection and vindex assignment on a 2D array round-trip through numpy.""" + v = np.arange(60, dtype=int).reshape(12, 5) + a = np.empty_like(v) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_set_coordinate_selection(v, a, z, case.input) + + +def _test_get_block_selection( + a: npt.NDArray[Any], + z: Array, + selection: BasicSelection, + expected_idx: slice | tuple[slice, ...], +) -> None: + expect = a[expected_idx] + actual = z.get_block_selection(selection) + assert_array_equal(expect, actual) + actual = z.blocks[selection] + assert_array_equal(expect, actual) + + +_BLOCK_1D_CASES: list[Expect[BasicSelection, slice]] = [ + Expect(input=0, output=slice(0, 7), id="block-0"), + Expect(input=2, output=slice(14, 21), id="block-mid"), + Expect(input=4, output=slice(28, 30), id="block-last"), + Expect(input=-1, output=slice(28, 30), id="block-neg-1"), + Expect(input=-2, output=slice(21, 28), id="block-neg-2"), + Expect(input=slice(3), output=slice(0, 21), id="slice-to-3"), + Expect(input=slice(None, 2), output=slice(0, 14), id="slice-none-2"), + Expect(input=slice(1, 2), output=slice(7, 14), id="slice-1-2"), + Expect(input=slice(-2, -1), output=slice(21, 28), id="slice-neg"), + Expect(input=slice(None), output=slice(0, 30), id="full"), +] + +_BLOCK_1D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail(input=slice(3, 8, 2), exception=IndexError, id="strided-slice"), + ExpectFail(input=2.3, exception=IndexError, id="float"), + ExpectFail(input=b"xxx", exception=IndexError, id="bytes"), + ExpectFail(input=None, exception=IndexError, id="none"), + ExpectFail(input=(0, 0), exception=IndexError, id="tuple-pair"), + ExpectFail(input=(slice(None), slice(None)), exception=IndexError, id="two-slices"), + ExpectFail(input=[0, 5, 3], exception=IndexError, id="int-list"), + ExpectFail(input=5, exception=IndexError, id="out-of-bounds-high"), + ExpectFail(input=-6, exception=IndexError, id="out-of-bounds-low"), +] + +_BLOCK_2D_CASES: list[Expect[BasicSelection, tuple[slice, slice]]] = [ + Expect(input=(0, 0), output=(slice(0, 5), slice(0, 2)), id="single-00"), + Expect(input=(1, 1), output=(slice(5, 10), slice(2, 4)), id="single-mid"), + Expect(input=(-1, -1), output=(slice(10, 12), slice(4, 5)), id="neg"), + Expect(input=(slice(0, 2), 0), output=(slice(0, 10), slice(0, 2)), id="slice-rows"), + Expect(input=(2, slice(1, 3)), output=(slice(10, 12), slice(2, 5)), id="slice-cols"), + Expect(input=(slice(0, 2), slice(0, 2)), output=(slice(0, 10), slice(0, 4)), id="both-slices"), + Expect(input=(slice(None), slice(None)), output=(slice(0, 12), slice(0, 5)), id="full"), +] + +_BLOCK_2D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail(input=(slice(5, 15), [1, 2, 3]), exception=IndexError, id="slice-with-array"), + ExpectFail(input=(Ellipsis, [1, 2, 3]), exception=IndexError, id="ellipsis-with-array"), + ExpectFail(input=(slice(15, 20), slice(None)), exception=IndexError, id="out-of-bounds"), +] + + +@pytest.mark.parametrize("case", _BLOCK_1D_CASES, ids=lambda c: c.id) +def test_get_block_selection_1d(store: StorePath, case: Expect[BasicSelection, slice]) -> None: + """get_block_selection / .blocks on a 1D array selects whole chunks matching the array slice.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_get_block_selection(a, z, case.input, case.output) + + +@pytest.mark.parametrize("case", _BLOCK_1D_BAD_CASES, ids=lambda c: c.id) +def test_get_block_selection_1d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """get_block_selection / .blocks on a 1D array rejects invalid block selections with IndexError.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.get_block_selection(case.input) + with case.raises(): + z.blocks[case.input] + + +@pytest.mark.parametrize("case", _BLOCK_2D_CASES, ids=lambda c: c.id) +def test_get_block_selection_2d( + store: StorePath, case: Expect[BasicSelection, tuple[slice, slice]] +) -> None: + """get_block_selection / .blocks on a 2D array selects whole chunk regions matching the array slices.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_get_block_selection(a, z, case.input, case.output) + + +@pytest.mark.parametrize("case", _BLOCK_2D_BAD_CASES, ids=lambda c: c.id) +def test_get_block_selection_2d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """get_block_selection on a 2D array rejects invalid or out-of-bounds block selections with IndexError.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + with case.raises(): + z.get_block_selection(case.input) + + +def _test_set_block_selection( + v: npt.NDArray[Any], + a: npt.NDArray[Any], + z: zarr.Array, + selection: BasicSelection, + expected_idx: slice | tuple[slice, ...], +) -> None: + for value in 42, v[expected_idx], v[expected_idx].tolist(): + # setup expectation + a[:] = 0 + a[expected_idx] = value + # test long-form API + z[:] = 0 + z.set_block_selection(selection, value) + assert_array_equal(a, z[:]) + # test short-form API + z[:] = 0 + z.blocks[selection] = value + assert_array_equal(a, z[:]) + + +@pytest.mark.parametrize("case", _BLOCK_1D_CASES, ids=lambda c: c.id) +def test_set_block_selection_1d(store: StorePath, case: Expect[BasicSelection, slice]) -> None: + """set_block_selection / .blocks assignment on a 1D array round-trips through numpy for each block selection.""" + v = np.arange(30, dtype=int) + a = np.empty_like(v) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_set_block_selection(v, a, z, case.input, case.output) + + +@pytest.mark.parametrize("case", _BLOCK_1D_BAD_CASES, ids=lambda c: c.id) +def test_set_block_selection_1d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """set_block_selection / .blocks assignment on a 1D array rejects invalid block selections with IndexError.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.set_block_selection(case.input, 42) + with case.raises(): + z.blocks[case.input] = 42 + + +@pytest.mark.parametrize("case", _BLOCK_2D_CASES, ids=lambda c: c.id) +def test_set_block_selection_2d( + store: StorePath, case: Expect[BasicSelection, tuple[slice, slice]] +) -> None: + """set_block_selection / .blocks assignment on a 2D array round-trips through numpy for each block selection.""" + v = np.arange(60, dtype=int).reshape(12, 5) + a = np.empty_like(v) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_set_block_selection(v, a, z, case.input, case.output) + + +@pytest.mark.parametrize("case", _BLOCK_2D_BAD_CASES, ids=lambda c: c.id) +def test_set_block_selection_2d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """set_block_selection on a 2D array rejects invalid or out-of-bounds block selections with IndexError.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + with case.raises(): + z.set_block_selection(case.input, 42) + + +def _test_get_mask_selection(a: npt.NDArray[Any], z: Array, selection: npt.NDArray) -> None: + expect = a[selection] + actual = z.get_mask_selection(selection) + assert_array_equal(expect, actual) + actual = z.vindex[selection] + assert_array_equal(expect, actual) + actual = z[selection] + assert_array_equal(expect, actual) + + +_MASK_1D_CASES: list[Expect[Any, None]] = [ + Expect(input=np.zeros(30, dtype=bool), output=None, id="all-false"), + Expect(input=np.ones(30, dtype=bool), output=None, id="all-true"), + Expect(input=np.arange(30) % 2 == 0, output=None, id="alternating"), + Expect( + input=np.isin(np.arange(30), [0, 7, 14, 29]), + output=None, + id="sparse-cross-chunk", + ), +] + +# msg=None for all 1d bad cases: get_mask_selection and vindex raise different +# messages for the same input, so no single substring satisfies both assertions. +_MASK_1D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail(input=slice(5, 15), exception=IndexError, id="slice"), + ExpectFail(input=slice(None), exception=IndexError, id="full-slice"), + ExpectFail(input=Ellipsis, exception=IndexError, id="ellipsis"), + ExpectFail(input=2.3, exception=IndexError, id="float"), + ExpectFail(input="foo", exception=IndexError, id="string"), + ExpectFail(input=b"xxx", exception=IndexError, id="bytes"), + ExpectFail(input=None, exception=IndexError, id="none"), + ExpectFail(input=(0, 0), exception=IndexError, id="tuple-pair"), + ExpectFail(input=(slice(None), slice(None)), exception=IndexError, id="two-slices"), + ExpectFail(input=np.zeros(5, dtype=bool), exception=IndexError, id="mask-too-short"), + ExpectFail(input=np.zeros(50, dtype=bool), exception=IndexError, id="mask-too-long"), + ExpectFail(input=[[True, False], [False, True]], exception=IndexError, id="too-many-dims"), +] + + +def _make_sparse_2d_mask() -> npt.NDArray[np.bool_]: + """Build a deterministic sparse (12, 5) boolean mask with Trues at (0,0), (5,2), (11,4), (2,3).""" + mask = np.zeros((12, 5), dtype=bool) + for r, c in [(0, 0), (5, 2), (11, 4), (2, 3)]: + mask[r, c] = True + return mask + + +_MASK_2D_CASES: list[Expect[Any, None]] = [ + Expect(input=np.zeros((12, 5), dtype=bool), output=None, id="all-false"), + Expect(input=np.ones((12, 5), dtype=bool), output=None, id="all-true"), + Expect( + input=(np.add.outer(np.arange(12), np.arange(5)) % 2).astype(bool), + output=None, + id="checkerboard", + ), + Expect( + input=_make_sparse_2d_mask(), + output=None, + id="sparse", + ), +] + +_MASK_2D_BAD_CASES: list[ExpectFail[Any]] = [ + ExpectFail(input=np.zeros((12, 3), dtype=bool), exception=IndexError, id="too-few-cols"), + ExpectFail(input=np.zeros((20, 5), dtype=bool), exception=IndexError, id="too-many-rows"), + ExpectFail(input=[True, False], exception=IndexError, id="wrong-ndim"), +] + + +@pytest.mark.parametrize("case", _MASK_1D_CASES, ids=lambda c: c.id) +def test_get_mask_selection_1d(store: StorePath, case: Expect[Any, None]) -> None: + """get_mask_selection / vindex / getitem on a 1D array match numpy for boolean masks.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_get_mask_selection(a, z, case.input) + + +@pytest.mark.parametrize("case", _MASK_1D_BAD_CASES, ids=lambda c: c.id) +def test_get_mask_selection_1d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """get_mask_selection / vindex on a 1D array reject non-boolean-mask and mis-shaped selections.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.get_mask_selection(case.input) # type: ignore[arg-type] + with case.raises(): + z.vindex[case.input] # type: ignore[index] + + +@pytest.mark.parametrize("case", _MASK_2D_CASES, ids=lambda c: c.id) +def test_get_mask_selection_2d(store: StorePath, case: Expect[Any, None]) -> None: + """get_mask_selection / vindex / getitem on a 2D array match numpy for boolean masks.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_get_mask_selection(a, z, case.input) + + +@pytest.mark.parametrize("case", _MASK_2D_BAD_CASES, ids=lambda c: c.id) +def test_get_mask_selection_2d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """vindex on a 2D array rejects masks of the wrong shape or dimensionality.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + with case.raises(): + z.vindex[case.input] # type: ignore[index] + + +def _test_set_mask_selection( + v: npt.NDArray, a: npt.NDArray, z: Array, selection: npt.NDArray +) -> None: + a[:] = 0 + z[:] = 0 + a[selection] = v[selection] + z.set_mask_selection(selection, v[selection]) + assert_array_equal(a, z[:]) + z[:] = 0 + z.vindex[selection] = v[selection] + assert_array_equal(a, z[:]) + z[:] = 0 + z[selection] = v[selection] + assert_array_equal(a, z[:]) + + +@pytest.mark.parametrize("case", _MASK_1D_CASES, ids=lambda c: c.id) +def test_set_mask_selection_1d(store: StorePath, case: Expect[Any, None]) -> None: + """set_mask_selection / vindex / setitem on a 1D array match numpy for boolean masks.""" + v = np.arange(30, dtype=int) + a = np.empty_like(v) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + _test_set_mask_selection(v, a, z, case.input) + + +@pytest.mark.parametrize("case", _MASK_1D_BAD_CASES, ids=lambda c: c.id) +def test_set_mask_selection_1d_raises(store: StorePath, case: ExpectFail[Any]) -> None: + """set_mask_selection / vindex on a 1D array reject non-boolean-mask and mis-shaped selections.""" + a = np.arange(30, dtype=int) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + with case.raises(): + z.set_mask_selection(case.input, 42) # type: ignore[arg-type] + with case.raises(): + z.vindex[case.input] = 42 # type: ignore[index] + + +@pytest.mark.parametrize("case", _MASK_2D_CASES, ids=lambda c: c.id) +def test_set_mask_selection_2d(store: StorePath, case: Expect[Any, None]) -> None: + """set_mask_selection / vindex / setitem on a 2D array match numpy for boolean masks.""" + v = np.arange(60, dtype=int).reshape(12, 5) + a = np.empty_like(v) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + _test_set_mask_selection(v, a, z, case.input) + + +def test_get_selection_out(store: StorePath) -> None: + """get_*_selection writes results into a provided out buffer, matching numpy.""" + # basic selections + a = np.arange(30) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(7,)) + + selections = [ + slice(5, 15), + slice(0, 30), + slice(1, 2), + ] + for selection in selections: + expect = a[selection] + out = get_ndbuffer_class().from_numpy_array(np.empty(expect.shape)) + z.get_basic_selection(selection, out=out) + assert_array_equal(expect, out.as_numpy_array()[:]) + + with pytest.raises(TypeError): + z.get_basic_selection(Ellipsis, out=[]) # type: ignore[arg-type] + + # orthogonal selections + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + selections = [ + # index both axes with bool array + (_ORTHO_2D_IX0_BOOL, _ORTHO_2D_IX1_BOOL), + # mixed indexing with bool array / slice + (_ORTHO_2D_IX0_BOOL, slice(1, 4)), + (slice(2, 9), _ORTHO_2D_IX1_BOOL), + # mixed indexing with bool array / int + (_ORTHO_2D_IX0_BOOL, 3), + (7, _ORTHO_2D_IX1_BOOL), + # mixed int array / bool array + (_ORTHO_2D_IX0_BOOL, _ORTHO_2D_IX1_INT), + (_ORTHO_2D_IX0_INT, _ORTHO_2D_IX1_BOOL), + ] + for selection in selections: + expect = oindex(a, selection) + out = get_ndbuffer_class().from_numpy_array(np.zeros(expect.shape, dtype=expect.dtype)) + z.get_orthogonal_selection(selection, out=out) + assert_array_equal(expect, out.as_numpy_array()[:]) + + # coordinate selections + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + selections = [ + # index both axes with array + (np.array([0, 5, 11]), np.array([0, 2, 4])), + # mixed indexing with array / int + (np.array([0, 5, 11]), 3), + (7, np.array([0, 2, 4])), + ] + for selection in selections: + expect = a[selection] + out = get_ndbuffer_class().from_numpy_array(np.zeros(expect.shape, dtype=expect.dtype)) + z.get_coordinate_selection(selection, out=out) + assert_array_equal(expect, out.as_numpy_array()[:]) + + +@pytest.mark.xfail(reason="fields are not supported in v3") +def test_get_selections_with_fields(store: StorePath) -> None: + """Would verify that basic, orthogonal, coordinate, and mask selections with structured-array `fields` arguments return the correct sub-fields (xfail: fields unsupported in v3).""" + a = np.array( + [("aaa", 1, 4.2), ("bbb", 2, 8.4), ("ccc", 3, 12.6)], + dtype=[("foo", "S3"), ("bar", "i4"), ("baz", "f8")], + ) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(2,)) + + fields_fixture: list[str | list[str]] = [ + "foo", + ["foo"], + ["foo", "bar"], + ["foo", "baz"], + ["bar", "baz"], + ["foo", "bar", "baz"], + ["bar", "foo"], + ["baz", "bar", "foo"], + ] + + for fields in fields_fixture: + # total selection + expect = a[fields] + actual = z.get_basic_selection(Ellipsis, fields=fields) + assert_array_equal(expect, actual) + # alternative API + if isinstance(fields, str): + actual = z[fields] + assert_array_equal(expect, actual) + elif len(fields) == 2: + actual = z[fields[0], fields[1]] + assert_array_equal(expect, actual) + if isinstance(fields, str): + actual = z[..., fields] + assert_array_equal(expect, actual) + elif len(fields) == 2: + actual = z[..., fields[0], fields[1]] + assert_array_equal(expect, actual) + + # basic selection with slice + expect = a[fields][0:2] + actual = z.get_basic_selection(slice(0, 2), fields=fields) + assert_array_equal(expect, actual) + # alternative API + if isinstance(fields, str): + actual = z[0:2, fields] + assert_array_equal(expect, actual) + elif len(fields) == 2: + actual = z[0:2, fields[0], fields[1]] + assert_array_equal(expect, actual) + + # basic selection with single item + expect = a[fields][1] + actual = z.get_basic_selection(1, fields=fields) + assert_array_equal(expect, actual) + # alternative API + if isinstance(fields, str): + actual = z[1, fields] + assert_array_equal(expect, actual) + elif len(fields) == 2: + actual = z[1, fields[0], fields[1]] + assert_array_equal(expect, actual) + + # orthogonal selection + ix = [0, 2] + expect = a[fields][ix] + actual = z.get_orthogonal_selection(ix, fields=fields) + assert_array_equal(expect, actual) + # alternative API + if isinstance(fields, str): + actual = z.oindex[ix, fields] + assert_array_equal(expect, actual) + elif len(fields) == 2: + actual = z.oindex[ix, fields[0], fields[1]] + assert_array_equal(expect, actual) + + # coordinate selection + ix = [0, 2] + expect = a[fields][ix] + actual = z.get_coordinate_selection(ix, fields=fields) + assert_array_equal(expect, actual) + # alternative API + if isinstance(fields, str): + actual = z.vindex[ix, fields] + assert_array_equal(expect, actual) + elif len(fields) == 2: + actual = z.vindex[ix, fields[0], fields[1]] + assert_array_equal(expect, actual) + + # mask selection + ix = [True, False, True] + expect = a[fields][ix] + actual = z.get_mask_selection(ix, fields=fields) + assert_array_equal(expect, actual) + # alternative API + if isinstance(fields, str): + actual = z.vindex[ix, fields] + assert_array_equal(expect, actual) + elif len(fields) == 2: + actual = z.vindex[ix, fields[0], fields[1]] + assert_array_equal(expect, actual) + + # missing/bad fields + with pytest.raises(IndexError): + z.get_basic_selection(Ellipsis, fields=["notafield"]) + with pytest.raises(IndexError): + z.get_basic_selection(Ellipsis, fields=slice(None)) # type: ignore[arg-type] + + +@pytest.mark.xfail(reason="fields are not supported in v3") +def test_set_selections_with_fields(store: StorePath) -> None: + """Would verify that basic, orthogonal, coordinate, and mask set-selections with structured-array `fields` correctly write individual fields and reject multi-field assignment (xfail: fields unsupported in v3).""" + v = np.array( + [("aaa", 1, 4.2), ("bbb", 2, 8.4), ("ccc", 3, 12.6)], + dtype=[("foo", "S3"), ("bar", "i4"), ("baz", "f8")], + ) + a = np.empty_like(v) + z = zarr_array_from_numpy_array(store, v, chunk_shape=(2,)) + + fields_fixture: list[str | list[str]] = [ + "foo", + [], + ["foo"], + ["foo", "bar"], + ["foo", "baz"], + ["bar", "baz"], + ["foo", "bar", "baz"], + ["bar", "foo"], + ["baz", "bar", "foo"], + ] + + for fields in fields_fixture: + # currently multi-field assignment is not supported in numpy, so we won't support + # it either + if isinstance(fields, list) and len(fields) > 1: + with pytest.raises(IndexError): + z.set_basic_selection(Ellipsis, v, fields=fields) + with pytest.raises(IndexError): + z.set_orthogonal_selection([0, 2], v, fields=fields) # type: ignore[arg-type] + with pytest.raises(IndexError): + z.set_coordinate_selection([0, 2], v, fields=fields) + with pytest.raises(IndexError): + z.set_mask_selection([True, False, True], v, fields=fields) # type: ignore[arg-type] + + else: + if isinstance(fields, list) and len(fields) == 1: + # work around numpy does not support multi-field assignment even if there + # is only one field + key = fields[0] + elif isinstance(fields, list) and len(fields) == 0: + # work around numpy ambiguity about what is a field selection + key = Ellipsis + else: + key = fields + + # setup expectation + a[:] = ("", 0, 0) + z[:] = ("", 0, 0) + assert_array_equal(a, z[:]) + a[key] = v[key] + # total selection + z.set_basic_selection(Ellipsis, v[key], fields=fields) + assert_array_equal(a, z[:]) + + # basic selection with slice + a[:] = ("", 0, 0) + z[:] = ("", 0, 0) + a[key][0:2] = v[key][0:2] + z.set_basic_selection(slice(0, 2), v[key][0:2], fields=fields) + assert_array_equal(a, z[:]) + + # orthogonal selection + a[:] = ("", 0, 0) + z[:] = ("", 0, 0) + ix = [0, 2] + a[key][ix] = v[key][ix] + z.set_orthogonal_selection(ix, v[key][ix], fields=fields) + assert_array_equal(a, z[:]) + + # coordinate selection + a[:] = ("", 0, 0) + z[:] = ("", 0, 0) + ix = [0, 2] + a[key][ix] = v[key][ix] + z.set_coordinate_selection(ix, v[key][ix], fields=fields) + assert_array_equal(a, z[:]) + + # mask selection + a[:] = ("", 0, 0) + z[:] = ("", 0, 0) + ix = [True, False, True] + a[key][ix] = v[key][ix] + z.set_mask_selection(ix, v[key][ix], fields=fields) + assert_array_equal(a, z[:]) + + +def test_slice_selection_uints() -> None: + """make_slice_selection accepts unsigned integer indices without error and produces correct shape.""" + arr = np.arange(24).reshape((4, 6)) + idx = np.uint64(3) + slice_sel = make_slice_selection((idx,)) + assert arr[tuple(slice_sel)].shape == (1, 6) + + +def test_numpy_int_indexing(store: StorePath) -> None: + """Indexing with a plain Python int and with `np.int64` both return the correct scalar element.""" + a = np.arange(1050) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) + assert a[42] == z[42] + assert a[np.int64(42)] == z[np.int64(42)] + + +@pytest.mark.parametrize( + ("shape", "chunks", "ops"), + [ + # 1D test cases + ((1070,), (50,), [("__getitem__", (slice(200, 400),))]), + ((1070,), (50,), [("__getitem__", (slice(200, 400, 100),))]), + ( + (1070,), + (50,), + [ + ("__getitem__", (slice(200, 400),)), + ("__setitem__", (slice(200, 400, 100),)), + ], + ), + # 2D test cases + ( + (40, 50), + (5, 8), + [ + ("__getitem__", (slice(6, 37, 13), (slice(4, 10)))), + ("__setitem__", (slice(None), (slice(None)))), + ], + ), + ], +) +async def test_accessed_chunks( + shape: tuple[int, ...], chunks: tuple[int, ...], ops: list[tuple[str, tuple[slice, ...]]] +) -> None: + """Only the chunks intersected by a slice selection are read or written, verified via a `CountingDict` store.""" + # Test that only the required chunks are accessed during basic selection operations + # shape: array shape + # chunks: chunk size + # ops: list of tuples with (optype, tuple of slices) + # optype = "__getitem__" or "__setitem__", tuple length must match number of dims + + # Use a counting dict as the backing store so we can track the items access + store = await CountingDict.open() + z = zarr_array_from_numpy_array(StorePath(store), np.zeros(shape), chunk_shape=chunks) + + for ii, (optype, slices) in enumerate(ops): + # Resolve the slices into the accessed chunks for each dimension + chunks_per_dim = [] + for N, C, sl in zip(shape, chunks, slices, strict=True): + chunk_ind = np.arange(N, dtype=int)[sl] // C + chunks_per_dim.append(np.unique(chunk_ind)) + + # Combine and generate the cartesian product to determine the chunks keys that + # will be accessed + chunks_accessed = [".".join(map(str, comb)) for comb in itertools.product(*chunks_per_dim)] + + counts_before = store.counter.copy() + + # Perform the operation + if optype == "__getitem__": + z[slices] + else: + z[slices] = ii + + # Get the change in counts + delta_counts = store.counter - counts_before + + # Check that the access counts for the operation have increased by one for all + # the chunks we expect to be included + for ci in chunks_accessed: + assert delta_counts.pop((optype, ci)) == 1 + + # If the chunk was partially written to it will also have been read once. We + # don't determine if the chunk was actually partial here, just that the + # counts are consistent that this might have happened + if optype == "__setitem__": + assert ("__getitem__", ci) not in delta_counts or delta_counts.pop( + ("__getitem__", ci) + ) == 1 + # Check that no other chunks were accessed + assert len(delta_counts) == 0 + + +@pytest.mark.parametrize( + "selection", + [ + # basic selection + [...], + [1, ...], + [slice(None)], + [1, 3], + [[1, 2, 3], 4], + [np.arange(12)], + [slice(2, 9)], + [slice(1, 3), 3], + [[1, 3]], + # mask selection + [np.tile([True, False, True, False, True], (12, 1))], + [np.full((12, 5), False)], + # coordinate selection + [[1, 2, 3, 4], [0, 1, 2, 3]], + [[10, 11, 5], [4, 0, 2]], + ], +) +def test_indexing_equals_numpy(store: StorePath, selection: Selection) -> None: + """Indexing a zarr array with assorted basic/mask/coordinate selections matches numpy.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + # note: in python 3.10 a[*selection] is not valid unpacking syntax + expected = a[*selection,] + actual = z[*selection,] + assert_array_equal(expected, actual, err_msg=f"selection: {selection}") + + +@pytest.mark.parametrize( + "selection", + [ + [np.tile([True, False], 6), np.tile([True, False, True, False, True], 1)], + [np.full(12, False), np.array([True, False, True, False, True])], + [np.full(12, True), np.full(5, True)], + [np.full(12, True), [True, False, True, False, True]], + ], +) +def test_orthogonal_bool_indexing_like_numpy_ix( + store: StorePath, selection: list[npt.ArrayLike] +) -> None: + """Orthogonal boolean indexing on each axis matches numpy's np.ix_ semantics.""" + a = np.arange(60, dtype=int).reshape(12, 5) + z = zarr_array_from_numpy_array(store, a, chunk_shape=(5, 2)) + expected = a[np.ix_(*selection)] + # note: in python 3.10 z[*selection] is not valid unpacking syntax + actual = z[*selection,] + assert_array_equal(expected, actual, err_msg=f"{selection=}") + + +@pytest.mark.parametrize("ndim", [1, 2, 3]) +@pytest.mark.parametrize("origin_0d", [None, (0,), (1,)]) +@pytest.mark.parametrize("selection_shape_0d", [None, (2,), (3,)]) +def test_iter_grid( + ndim: int, origin_0d: tuple[int] | None, selection_shape_0d: tuple[int] | None +) -> None: + """ + Test that iter_grid works as expected for 1, 2, and 3 dimensions. + """ + grid_shape = (10, 5, 7)[:ndim] + + if origin_0d is not None: + origin_kwarg = origin_0d * ndim + origin = origin_kwarg + else: + origin_kwarg = None + origin = (0,) * ndim + + if selection_shape_0d is not None: + selection_shape_kwarg = selection_shape_0d * ndim + selection_shape = selection_shape_kwarg + else: + selection_shape_kwarg = None + selection_shape = tuple(gs - o for gs, o in zip(grid_shape, origin, strict=False)) + + observed = tuple( + _iter_grid(grid_shape, origin=origin_kwarg, selection_shape=selection_shape_kwarg) + ) + + # generate a numpy array of indices, and index it + coord_array = np.array(list(itertools.product(*[range(s) for s in grid_shape]))).reshape( + (*grid_shape, ndim) + ) + coord_array_indexed = coord_array[ + tuple(slice(o, o + s, 1) for o, s in zip(origin, selection_shape, strict=False)) + + (range(ndim),) + ] + + expected = tuple(map(tuple, coord_array_indexed.reshape(-1, ndim).tolist())) + assert observed == expected + + +def test_iter_grid_invalid() -> None: + """ + Ensure that a selection_shape that exceeds the grid_shape + origin produces an indexing error. + """ + with pytest.raises(IndexError): + list(_iter_grid((5,), origin=(0,), selection_shape=(10,))) + + +def test_indexing_with_zarr_array(store: StorePath) -> None: + """Regression for GH2133: indexing a zarr array with another zarr array (boolean or integer) as the indexer produces the same result as indexing with the equivalent numpy array.""" + # regression test for https://github.com/zarr-developers/zarr-python/issues/2133 + a = np.arange(10) + za = zarr.array(a, chunks=2, store=store, path="a") + ix = [False, True, False, True, False, True, False, True, False, True] + ii = [0, 2, 4, 5] + + zix = zarr.array(ix, chunks=2, store=store, dtype="bool", path="ix") + zii = zarr.array(ii, chunks=2, store=store, dtype="i4", path="ii") + assert_array_equal(a[ix], za[zix]) + assert_array_equal(a[ix], za.oindex[zix]) + assert_array_equal(a[ix], za.vindex[zix]) + + assert_array_equal(a[ii], za[zii]) + assert_array_equal(a[ii], za.oindex[zii]) + + +@pytest.mark.parametrize("store", ["local", "memory"], indirect=["store"]) +@pytest.mark.parametrize("shape", [(0, 2, 3), (0,), (3, 0)]) +def test_zero_sized_chunks(store: StorePath, shape: list[int]) -> None: + """Arrays with zero-extent dimensions can be created and indexed without error; reading back returns the fill value.""" + # Chunk sizes must be >= 1 per spec; use 1 for zero-extent dimensions. + chunks = tuple(max(1, s) for s in shape) + z = zarr.create_array(store=store, shape=shape, chunks=chunks, zarr_format=3, dtype="f8") + z[...] = 42 + assert_array_equal(z[...], np.zeros(shape, dtype="f8")) + + +@pytest.mark.parametrize("store", ["memory"], indirect=["store"]) +def test_vectorized_indexing_incompatible_shape(store) -> None: + """Regression for GH2469: vectorized set-indexing raises ValueError when the value shape is incompatible with the indexer shape.""" + # GH2469 + shape = (4, 4) + chunks = (2, 2) + fill_value = 32767 + arr = zarr.create( + shape, + store=store, + chunks=chunks, + dtype=np.int16, + fill_value=fill_value, + codecs=[zarr.codecs.BytesCodec(), zarr.codecs.BloscCodec()], + ) + with pytest.raises(ValueError, match="Attempting to set"): + arr[np.array([1, 2]), np.array([1, 2])] = np.array([[-1, -2], [-3, -4]]) + + +def test_iter_chunk_regions(): + """_iter_chunk_regions yields slices that exactly cover each chunk, and reading/writing each region round-trips correctly.""" + chunks = (2, 3) + a = zarr.create((10, 10), chunks=chunks) + a[:] = 1 + for region in a._iter_chunk_regions(): + assert_array_equal(a[region], np.ones_like(a[region])) + a[region] = 0 + assert_array_equal(a[region], np.zeros_like(a[region])) + + +@pytest.mark.parametrize( + ("domain_shape", "region_shape", "origin", "selection_shape"), + [ + ((9,), (1,), None, (9,)), + ((9,), (1,), (0,), (9,)), + ((3,), (2,), (0,), (1,)), + ((9,), (2,), (2,), (2,)), + ((9, 9), (2, 1), None, None), + ((9, 9), (4, 1), None, None), + ], +) +@pytest.mark.parametrize("order", ["lexicographic"]) +@pytest.mark.parametrize("trim_excess", [True, False]) +def test_iter_regions( + domain_shape: tuple[int, ...], + region_shape: tuple[int, ...], + origin: tuple[int, ...] | None, + selection_shape: tuple[int, ...] | None, + order: _ArrayIndexingOrder, + trim_excess: bool, +) -> None: + """ + Test that iter_regions properly iterates over contiguous regions of a gridded domain. + """ + expected_slices_by_dim: list[list[slice]] = [] + origin_parsed: tuple[int, ...] + selection_shape_parsed: tuple[int, ...] + if origin is None: + origin_parsed = (0,) * len(domain_shape) + else: + origin_parsed = origin + if selection_shape is None: + selection_shape_parsed = tuple( + ceildiv(ds, rs) - o + for ds, o, rs in zip(domain_shape, origin_parsed, region_shape, strict=True) + ) + else: + selection_shape_parsed = selection_shape + for d_s, r_s, o, ss in zip( + domain_shape, region_shape, origin_parsed, selection_shape_parsed, strict=True + ): + _expected_slices: list[slice] = [] + start = o * r_s + for incr in range(start, start + ss * r_s, r_s): + if trim_excess: + term = min(incr + r_s, d_s) + else: + term = incr + r_s + _expected_slices.append(slice(incr, term, 1)) + expected_slices_by_dim.append(_expected_slices) + + expected = tuple(itertools.product(*expected_slices_by_dim)) + observed = tuple( + _iter_regions( + domain_shape, + region_shape, + origin=origin, + selection_shape=selection_shape, + order=order, + trim_excess=trim_excess, + ) + ) + assert observed == expected + + +class TestAsync: + @pytest.mark.parametrize( + ("indexer", "expected"), + [ + # int + ((0,), np.array([1, 2])), + ((1,), np.array([3, 4])), + ((0, 1), np.array(2)), + # slice + ((slice(None),), np.array([[1, 2], [3, 4]])), + ((slice(0, 1),), np.array([[1, 2]])), + ((slice(1, 2),), np.array([[3, 4]])), + ((slice(0, 2),), np.array([[1, 2], [3, 4]])), + ((slice(0, 0),), np.empty(shape=(0, 2), dtype="i8")), + # ellipsis + ((...,), np.array([[1, 2], [3, 4]])), + ((0, ...), np.array([1, 2])), + ((..., 0), np.array([1, 3])), + ((0, 1, ...), np.array(2)), + # combined + ((0, slice(None)), np.array([1, 2])), + ((slice(None), 0), np.array([1, 3])), + ((slice(None), slice(None)), np.array([[1, 2], [3, 4]])), + # array of ints + (([0]), np.array([[1, 2]])), + (([1]), np.array([[3, 4]])), + (([0], [1]), np.array(2)), + (([0, 1], [0]), np.array([[1], [3]])), + (([0, 1], [0, 1]), np.array([[1, 2], [3, 4]])), + # boolean array + (np.array([True, True]), np.array([[1, 2], [3, 4]])), + (np.array([True, False]), np.array([[1, 2]])), + (np.array([False, True]), np.array([[3, 4]])), + (np.array([False, False]), np.empty(shape=(0, 2), dtype="i8")), + ], + ) + async def test_async_oindex(self, store, indexer, expected): + """The async `oindex.getitem` interface returns the correct orthogonally-indexed result for int, slice, ellipsis, array, and boolean indexers.""" + z = zarr.create_array(store=store, shape=(2, 2), chunks=(1, 1), zarr_format=3, dtype="i8") + z[...] = np.array([[1, 2], [3, 4]]) + async_zarr = z._async_array + + result = await async_zarr.oindex.getitem(indexer) + assert_array_equal(result, expected) + + async def test_async_oindex_with_zarr_array(self, store): + """The async `oindex.getitem` interface accepts a zarr boolean array as the indexer and returns the correct rows.""" + group = zarr.create_group(store=store, zarr_format=3) + + z1 = group.create_array(name="z1", shape=(2, 2), chunks=(1, 1), dtype="i8") + z1[...] = np.array([[1, 2], [3, 4]]) + async_zarr = z1._async_array + + # create boolean zarr array to index with + z2 = group.create_array(name="z2", shape=(2,), chunks=(1,), dtype="?") + z2[...] = np.array([True, False]) + + result = await async_zarr.oindex.getitem(z2) + expected = np.array([[1, 2]]) + assert_array_equal(result, expected) + + @pytest.mark.parametrize( + ("indexer", "expected"), + [ + (([0], [0]), np.array(1)), + (([0, 1], [0, 1]), np.array([1, 4])), + (np.array([[False, True], [False, True]]), np.array([2, 4])), + ], + ) + async def test_async_vindex(self, store, indexer, expected): + """The async `vindex.getitem` interface returns the correct vectorized-indexed result for coordinate and boolean indexers.""" + z = zarr.create_array(store=store, shape=(2, 2), chunks=(1, 1), zarr_format=3, dtype="i8") + z[...] = np.array([[1, 2], [3, 4]]) + async_zarr = z._async_array + + result = await async_zarr.vindex.getitem(indexer) + assert_array_equal(result, expected) + + async def test_async_vindex_with_zarr_array(self, store): + """The async `vindex.getitem` interface accepts a zarr 2D boolean array as the indexer and returns the correct elements.""" + group = zarr.create_group(store=store, zarr_format=3) + + z1 = group.create_array(name="z1", shape=(2, 2), chunks=(1, 1), dtype="i8") + z1[...] = np.array([[1, 2], [3, 4]]) + async_zarr = z1._async_array + + # create boolean zarr array to index with + z2 = group.create_array(name="z2", shape=(2, 2), chunks=(1, 1), dtype="?") + z2[...] = np.array([[False, True], [False, True]]) + + result = await async_zarr.vindex.getitem(z2) + expected = np.array([2, 4]) + assert_array_equal(result, expected) + + async def test_async_invalid_indexer(self, store): + """The async `vindex.getitem` and `oindex.getitem` interfaces raise IndexError when given an unsupported indexer type.""" + z = zarr.create_array(store=store, shape=(2, 2), chunks=(1, 1), zarr_format=3, dtype="i8") + z[...] = np.array([[1, 2], [3, 4]]) + async_zarr = z._async_array + + with pytest.raises(IndexError): + await async_zarr.vindex.getitem("invalid_indexer") + + with pytest.raises(IndexError): + await async_zarr.oindex.getitem("invalid_indexer") diff --git a/tests/test_info.py b/tests/test_info.py new file mode 100644 index 0000000000..08f2318dc2 --- /dev/null +++ b/tests/test_info.py @@ -0,0 +1,141 @@ +import textwrap + +import pytest + +from zarr.codecs.bytes import BytesCodec +from zarr.core._info import ArrayInfo, GroupInfo, human_readable_size +from zarr.core.common import ZarrFormat +from zarr.core.dtype.npy.int import Int32 + +ZARR_FORMATS = [2, 3] + + +@pytest.mark.parametrize("zarr_format", ZARR_FORMATS) +def test_group_info_repr(zarr_format: ZarrFormat) -> None: + info = GroupInfo( + _name="a", _store_type="MemoryStore", _read_only=False, _zarr_format=zarr_format + ) + result = repr(info) + expected = textwrap.dedent(f"""\ + Name : a + Type : Group + Zarr format : {zarr_format} + Read-only : False + Store type : MemoryStore""") + assert result == expected + + +@pytest.mark.parametrize("zarr_format", ZARR_FORMATS) +def test_group_info_complete(zarr_format: ZarrFormat) -> None: + info = GroupInfo( + _name="a", + _store_type="MemoryStore", + _zarr_format=zarr_format, + _read_only=False, + _count_arrays=10, + _count_groups=4, + _count_members=14, + ) + result = repr(info) + expected = textwrap.dedent(f"""\ + Name : a + Type : Group + Zarr format : {zarr_format} + Read-only : False + Store type : MemoryStore + No. members : 14 + No. arrays : 10 + No. groups : 4""") + assert result == expected + + +@pytest.mark.parametrize("zarr_format", ZARR_FORMATS) +def test_array_info(zarr_format: ZarrFormat) -> None: + info = ArrayInfo( + _zarr_format=zarr_format, + _data_type=Int32(), + _fill_value=0, + _shape=(100, 100), + _chunk_shape=(10, 100), + _order="C", + _read_only=True, + _store_type="MemoryStore", + _serializer=BytesCodec(), + ) + result = repr(info) + assert result == textwrap.dedent(f"""\ + Type : Array + Zarr format : {zarr_format} + Data type : Int32(endianness='little') + Fill value : 0 + Shape : (100, 100) + Chunk shape : (10, 100) + Order : C + Read-only : True + Store type : MemoryStore + Filters : () + Serializer : BytesCodec(endian='little') + Compressors : ()""") + + +@pytest.mark.parametrize("zarr_format", ZARR_FORMATS) +@pytest.mark.parametrize("bytes_things", [(1_000_000, "976.6K", 500_000, "488.3K", "2.0", 5)]) +def test_array_info_complete( + zarr_format: ZarrFormat, bytes_things: tuple[int, str, int, str, str, int] +) -> None: + ( + count_bytes, + count_bytes_formatted, + count_bytes_stored, + count_bytes_stored_formatted, + storage_ratio_formatted, + count_chunks_initialized, + ) = bytes_things + info = ArrayInfo( + _zarr_format=zarr_format, + _data_type=Int32(), + _fill_value=0, + _shape=(100, 100), + _chunk_shape=(10, 100), + _order="C", + _read_only=True, + _store_type="MemoryStore", + _serializer=BytesCodec(), + _count_bytes=count_bytes, + _count_bytes_stored=count_bytes_stored, + _count_chunks_initialized=count_chunks_initialized, + ) + result = repr(info) + assert result == textwrap.dedent(f"""\ + Type : Array + Zarr format : {zarr_format} + Data type : Int32(endianness='little') + Fill value : 0 + Shape : (100, 100) + Chunk shape : (10, 100) + Order : C + Read-only : True + Store type : MemoryStore + Filters : () + Serializer : BytesCodec(endian='little') + Compressors : () + No. bytes : {count_bytes} ({count_bytes_formatted}) + No. bytes stored : {count_bytes_stored} ({count_bytes_stored_formatted}) + Storage ratio : {storage_ratio_formatted} + Chunks Initialized : 5""") + + +@pytest.mark.parametrize( + ("size", "expected"), + [ + (1, "1"), + (2**10, "1.0K"), + (2**20, "1.0M"), + (2**30, "1.0G"), + (2**40, "1.0T"), + (2**50, "1.0P"), + ], +) +def test_human_readable_size(size: int, expected: str) -> None: + result = human_readable_size(size) + assert result == expected diff --git a/tests/test_json.py b/tests/test_json.py new file mode 100644 index 0000000000..17a8c631d5 --- /dev/null +++ b/tests/test_json.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +import math +from typing import TYPE_CHECKING + +import pytest + +from zarr.core._json import ( + buffer_to_json, + buffer_to_json_object, + get_json, + json_to_buffer, + set_json, +) +from zarr.core.buffer import cpu, default_buffer_prototype +from zarr.storage import MemoryStore +from zarr.storage._common import StorePath + +if TYPE_CHECKING: + from zarr.core.common import JSON + + +def test_json_to_buffer_round_trips() -> None: + """`buffer_to_json` inverts `json_to_buffer` for an arbitrary JSON value.""" + obj: JSON = {"zarr_format": 3, "node_type": "group", "attributes": {"a": [1, 2, 3]}} + buffer = json_to_buffer(obj) + assert buffer_to_json(buffer) == obj + + +def test_json_to_buffer_uses_given_prototype() -> None: + """`json_to_buffer` constructs the buffer from the supplied prototype.""" + prototype = default_buffer_prototype() + buffer = json_to_buffer({"x": 1}, prototype=prototype) + assert isinstance(buffer, prototype.buffer) + + +def test_json_to_buffer_allows_nan_by_default() -> None: + """`json_to_buffer` permits NaN by default (writes it as `NaN`).""" + buffer = json_to_buffer({"fill_value": math.nan}) + decoded = buffer_to_json(buffer) + assert isinstance(decoded, dict) + assert math.isnan(decoded["fill_value"]) + + +def test_json_to_buffer_allow_nan_false_rejects_nan() -> None: + """`json_to_buffer(allow_nan=False)` raises on a non-finite value.""" + with pytest.raises(ValueError, match="Out of range float"): + json_to_buffer({"fill_value": math.nan}, allow_nan=False) + + +def test_json_to_buffer_indent_controls_formatting() -> None: + """`json_to_buffer(indent=...)` controls whitespace in the serialized bytes.""" + obj: JSON = {"a": 1, "b": 2} + compact = json_to_buffer(obj).to_bytes() + indented = json_to_buffer(obj, indent=2).to_bytes() + assert b"\n" not in compact + assert b"\n" in indented + # both still round-trip to the same value + assert buffer_to_json(json_to_buffer(obj, indent=2)) == obj + + +async def test_get_json_reads_existing_key() -> None: + """`get_json` returns the parsed document stored at an existing key.""" + store = MemoryStore() + obj: JSON = {"zarr_format": 3, "node_type": "array"} + await set_json(store, "zarr.json", obj) + assert await get_json(store, "zarr.json") == obj + + +async def test_get_json_returns_none_for_missing_key() -> None: + """`get_json` returns None (rather than raising) when the key is absent.""" + store = MemoryStore() + assert await get_json(store, "does-not-exist") is None + + +async def test_set_json_then_get_json_round_trips() -> None: + """`set_json` followed by `get_json` returns the original value.""" + store = MemoryStore() + obj: JSON = {"a": 1, "b": [2, 3], "c": {"d": None}} + await set_json(store, "doc.json", obj) + assert await get_json(store, "doc.json") == obj + + +async def test_storepath_get_json_reads_existing_key() -> None: + """`StorePath.get_json` reads and parses the document at its own path.""" + store = MemoryStore() + obj: JSON = {"zarr_format": 2} + await set_json(store, "group/.zgroup", obj) + sp = StorePath(store, "group/.zgroup") + assert await sp.get_json() == obj + + +async def test_storepath_get_json_returns_none_for_missing() -> None: + """`StorePath.get_json` returns None when its path is absent.""" + store = MemoryStore() + sp = StorePath(store, "missing") + assert await sp.get_json() is None + + +def test_buffer_to_json_on_cpu_buffer() -> None: + """`buffer_to_json` works on a plain CPU buffer built from raw bytes.""" + buffer = cpu.Buffer.from_bytes(b'{"hello": "world"}') + assert buffer_to_json(buffer) == {"hello": "world"} + + +def test_buffer_to_json_object_returns_dict() -> None: + """`buffer_to_json_object` returns the parsed object as a dict.""" + buffer = cpu.Buffer.from_bytes(b'{"node_type": "group"}') + assert buffer_to_json_object(buffer) == {"node_type": "group"} + + +def test_buffer_to_json_object_rejects_non_object() -> None: + """`buffer_to_json_object` raises TypeError when the document is not an object.""" + buffer = cpu.Buffer.from_bytes(b"[1, 2, 3]") + with pytest.raises(TypeError, match="Expected a JSON object"): + buffer_to_json_object(buffer) diff --git a/tests/test_json_parse.py b/tests/test_json_parse.py new file mode 100644 index 0000000000..da723119aa --- /dev/null +++ b/tests/test_json_parse.py @@ -0,0 +1,122 @@ +"""Tests for :mod:`zarr.core.json_parse`. + +``convert`` delegates JSON type coercion to :func:`msgspec.convert` (translating +``msgspec.ValidationError`` into ``TypeError``); ``validate_json_value`` is the +hand-written fallback for the recursive ``JSON`` alias msgspec cannot build, +including a nesting-depth limit. The final group is a regression test for the +``parse_storage_transformers`` fix that motivated the depth limit work. +""" + +from __future__ import annotations + +from typing import Literal + +import pytest + +from zarr.core.json_parse import MAX_JSON_DEPTH, convert, parse_field, validate_json_value +from zarr.core.metadata.v3 import parse_storage_transformers + + +class TestConvert: + def test_literal(self) -> None: + assert convert(3, Literal[3]) == 3 + assert convert("array", Literal["array", "group"]) == "array" + + def test_literal_rejects_non_member(self) -> None: + with pytest.raises(ValueError, match="Expected instance of"): + convert(4, Literal[3]) + with pytest.raises(ValueError, match="Expected instance of"): + convert("Q", Literal["C", "F"]) + + def test_sequence_coerced_to_tuple(self) -> None: + assert convert([1, 2, 3], tuple[int, ...]) == (1, 2, 3) + assert convert([1, 2], tuple[int, int]) == (1, 2) + + def test_int(self) -> None: + assert convert(5, int) == 5 + + def test_bool_int_strictness(self) -> None: + # bool is an int subclass, but the two must not be interchangeable. + with pytest.raises(ValueError): + convert(True, int) + with pytest.raises(ValueError): + convert(1, bool) + # ... and True must not satisfy Literal[1]. + with pytest.raises(ValueError): + convert(True, Literal[1]) + + +class TestParseField: + def test_valid_passthrough(self) -> None: + assert parse_field(3, Literal[3], "zarr_format") == 3 + + def test_wraps_with_field_context(self) -> None: + with pytest.raises(ValueError, match="Failed to parse input for 'zarr_format'"): + parse_field(4, Literal[3], "zarr_format") + + def test_custom_error_type_and_chaining(self) -> None: + class MyError(ValueError): + pass + + with pytest.raises(MyError, match="Failed to parse input for 'node_type'") as exc_info: + parse_field(5, Literal["array"], "node_type", error=MyError) + # the generic type error is chained as the cause + assert isinstance(exc_info.value.__cause__, ValueError) + + +class TestValidateJsonValue: + @pytest.mark.parametrize("value", [None, True, 1, 1.5, "s"]) + def test_primitives(self, value: object) -> None: + assert validate_json_value(value) is value + + def test_nested(self) -> None: + value = {"a": [1, 2.0, "x", True, None], "b": {"c": [{}]}} + assert validate_json_value(value) is value + + def test_rejects_non_str_keys(self) -> None: + with pytest.raises(TypeError, match="keys must be str"): + validate_json_value({1: "x"}) + + def test_rejects_non_json_leaf(self) -> None: + with pytest.raises(TypeError, match="not a valid JSON value"): + validate_json_value(object()) + with pytest.raises(TypeError, match="not a valid JSON value"): + validate_json_value({"a": object()}) + + def test_depth_limit(self) -> None: + def nest(depth: int) -> object: + v: object = "leaf" + for _ in range(depth): + v = {"k": v} + return v + + # At the limit it passes; one level deeper it is rejected. This bound is + # new behavior the previous per-field parsers never had. + assert validate_json_value(nest(MAX_JSON_DEPTH)) is not None + with pytest.raises(ValueError, match="maximum depth"): + validate_json_value(nest(MAX_JSON_DEPTH + 1)) + + +class TestStorageTransformersRegression: + """`parse_storage_transformers` used to call `len(tuple(data))` and then + return `data` itself, exhausting a one-shot iterable and returning a value + typed as a tuple but not actually a tuple.""" + + def test_none(self) -> None: + assert parse_storage_transformers(None) == () + + def test_empty(self) -> None: + assert parse_storage_transformers([]) == () + + def test_list_returns_tuple(self) -> None: + result = parse_storage_transformers([{"a": 1}]) + assert result == ({"a": 1},) + assert isinstance(result, tuple) + + def test_generator_not_exhausted(self) -> None: + result = parse_storage_transformers(iter([{"a": 1}, {"b": 2}])) + assert result == ({"a": 1}, {"b": 2}) + + def test_non_iterable_rejected(self) -> None: + with pytest.raises(TypeError, match="Expected an iterable"): + parse_storage_transformers(5) diff --git a/tests/test_metadata/__init__.py b/tests/test_metadata/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_metadata/conftest.py b/tests/test_metadata/conftest.py new file mode 100644 index 0000000000..24f2417fce --- /dev/null +++ b/tests/test_metadata/conftest.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from zarr.codecs.bytes import BytesCodec + +if TYPE_CHECKING: + from zarr.core.metadata.v3 import ArrayMetadataJSON_V3 + + +def minimal_metadata_dict_v3( + extra_fields: dict[str, Any] | None = None, **overrides: Any +) -> ArrayMetadataJSON_V3: + """Build a minimal valid V3 array metadata JSON dict. + + The output matches the shape of ``ArrayV3Metadata.to_dict()`` β€” all + fields that ``to_dict`` always emits are included. + + Parameters + ---------- + extra_fields : dict, optional + Extra keys to inject into the dict (e.g. extension fields). + **overrides + Override any of the standard metadata fields. + """ + d: ArrayMetadataJSON_V3 = { + "zarr_format": 3, + "node_type": "array", + "shape": (4, 4), + "data_type": "uint8", + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": (4, 4)}}, + "chunk_key_encoding": {"name": "default", "configuration": {"separator": "/"}}, + "fill_value": 0, + "codecs": (BytesCodec().to_dict(),), # type: ignore[typeddict-item] + "attributes": {}, + "storage_transformers": (), + } + d.update(overrides) # type: ignore[typeddict-item] + if extra_fields is not None: + d.update(extra_fields) # type: ignore[typeddict-item] + return d diff --git a/tests/test_metadata/test_consolidated.py b/tests/test_metadata/test_consolidated.py new file mode 100644 index 0000000000..cd0fd92d74 --- /dev/null +++ b/tests/test_metadata/test_consolidated.py @@ -0,0 +1,903 @@ +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest +from numcodecs import Blosc + +import zarr.api.asynchronous +import zarr.api.synchronous +import zarr.storage +from zarr import AsyncGroup +from zarr.api.asynchronous import ( + consolidate_metadata, + group, + open, + open_consolidated, +) +from zarr.core.buffer import cpu, default_buffer_prototype +from zarr.core.dtype import parse_dtype +from zarr.core.group import ConsolidatedMetadata, GroupMetadata +from zarr.core.metadata import ArrayV3Metadata +from zarr.core.metadata.v2 import ArrayV2Metadata +from zarr.errors import ZarrUserWarning +from zarr.storage import StorePath + +if TYPE_CHECKING: + from zarr.abc.store import Store + from zarr.core.common import JSON, ZarrFormat + + +@pytest.fixture +async def memory_store_with_hierarchy(memory_store: Store) -> Store: + g = await group(store=memory_store, attributes={"foo": "bar"}) + dtype = "uint8" + await g.create_array(name="air", shape=(1, 2, 3), dtype=dtype) + await g.create_array(name="lat", shape=(1,), dtype=dtype) + await g.create_array(name="lon", shape=(2,), dtype=dtype) + await g.create_array(name="time", shape=(3,), dtype=dtype) + + child = await g.create_group("child", attributes={"key": "child"}) + await child.create_array("array", shape=(4, 4), attributes={"key": "child"}, dtype=dtype) + + grandchild = await child.create_group("grandchild", attributes={"key": "grandchild"}) + await grandchild.create_array( + "array", shape=(4, 4), attributes={"key": "grandchild"}, dtype=dtype + ) + await grandchild.create_group("empty_group", attributes={"key": "empty"}) + return memory_store + + +class TestConsolidated: + @pytest.mark.filterwarnings("ignore:Consolidated metadata") + async def test_getitem_consolidated_empty_leaf_group( + self, memory_store: zarr.storage.MemoryStore, zarr_format: ZarrFormat + ) -> None: + # This test writes the bytes directly, rather than using the zarr API, to mimic + # how older versions of zarr-python wrote the consolidated metadata. + # Notably, zarr-python 2.x does not include a + # + # "consolidated_metadata": {"metadata": {}} + # + # field on the leaf group nodes. + if zarr_format == 2: + zmetadata: dict[str, JSON] = { + "metadata": { + ".zattrs": {}, + ".zgroup": {"zarr_format": 2}, + "raw/.zattrs": {}, + "raw/.zgroup": {"zarr_format": 2}, + "raw/varm/.zattrs": {}, + "raw/varm/.zgroup": {"zarr_format": 2}, + }, + "zarr_consolidated_format": 1, + } + await memory_store.set( + ".zgroup", cpu.Buffer.from_bytes(json.dumps({"zarr_format": 2}).encode()) + ) + await memory_store.set(".zattrs", cpu.Buffer.from_bytes(json.dumps({}).encode())) + await memory_store.set( + ".zmetadata", cpu.Buffer.from_bytes(json.dumps(zmetadata).encode()) + ) + + else: + zmetadata = { + "attributes": {}, + "zarr_format": 3, + "consolidated_metadata": { + "kind": "inline", + "must_understand": False, + "metadata": { + "raw": { + "attributes": {}, + "zarr_format": 3, + "node_type": "group", + }, + "raw/varm": { + "attributes": {}, + "zarr_format": 3, + "node_type": "group", + }, + }, + }, + "node_type": "group", + } + await memory_store.set( + "zarr.json", cpu.Buffer.from_bytes(json.dumps(zmetadata).encode()) + ) + + group = await zarr.api.asynchronous.open_consolidated( + store=memory_store, zarr_format=zarr_format + ) + raw = await group.get_group("raw") + assert raw.metadata.consolidated_metadata is not None + + varm = await raw.get_group("varm") + assert varm.metadata.consolidated_metadata == ConsolidatedMetadata(metadata={}) + + async def test_open_consolidated_false_raises(self) -> None: + store = zarr.storage.MemoryStore() + with pytest.raises(TypeError, match="use_consolidated"): + await zarr.api.asynchronous.open_consolidated(store, use_consolidated=False) # type: ignore[arg-type] + + def test_open_consolidated_false_raises_sync(self) -> None: + store = zarr.storage.MemoryStore() + with pytest.raises(TypeError, match="use_consolidated"): + zarr.open_consolidated(store, use_consolidated=False) # type: ignore[arg-type] + + async def test_consolidated(self, memory_store_with_hierarchy: Store) -> None: + # TODO: Figure out desired keys in + # TODO: variety in the hierarchies + # More nesting + # arrays under arrays + # single array + # etc. + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + await consolidate_metadata(memory_store_with_hierarchy) + group2 = await AsyncGroup.open(memory_store_with_hierarchy) + + array_metadata: dict[str, JSON] = { + "attributes": {}, + "chunk_key_encoding": { + "configuration": {"separator": "/"}, + "name": "default", + }, + "codecs": ( + {"configuration": {"endian": "little"}, "name": "bytes"}, + {"configuration": {"level": 0, "checksum": False}, "name": "zstd"}, + ), + "data_type": "uint8", + "fill_value": 0, + "node_type": "array", + # "shape": (1, 2, 3), + "zarr_format": 3, + } + + expected = GroupMetadata( + attributes={"foo": "bar"}, + consolidated_metadata=ConsolidatedMetadata( + kind="inline", + must_understand=False, + metadata={ + "air": ArrayV3Metadata.from_dict( + { + "shape": (1, 2, 3), + "chunk_grid": { + "configuration": {"chunk_shape": (1, 2, 3)}, + "name": "regular", + }, + **array_metadata, + } + ), + "lat": ArrayV3Metadata.from_dict( + { + "shape": (1,), + "chunk_grid": { + "configuration": {"chunk_shape": (1,)}, + "name": "regular", + }, + **array_metadata, + } + ), + "lon": ArrayV3Metadata.from_dict( + { + "shape": (2,), + "chunk_grid": { + "configuration": {"chunk_shape": (2,)}, + "name": "regular", + }, + **array_metadata, + } + ), + "time": ArrayV3Metadata.from_dict( + { + "shape": (3,), + "chunk_grid": { + "configuration": {"chunk_shape": (3,)}, + "name": "regular", + }, + **array_metadata, + } + ), + "child": GroupMetadata( + attributes={"key": "child"}, + consolidated_metadata=ConsolidatedMetadata( + metadata={ + "array": ArrayV3Metadata.from_dict( + { + **array_metadata, + "attributes": {"key": "child"}, + "shape": (4, 4), + "chunk_grid": { + "configuration": {"chunk_shape": (4, 4)}, + "name": "regular", + }, + } + ), + "grandchild": GroupMetadata( + attributes={"key": "grandchild"}, + consolidated_metadata=ConsolidatedMetadata( + metadata={ + # known to be empty child group + "empty_group": GroupMetadata( + consolidated_metadata=ConsolidatedMetadata( + metadata={} + ), + attributes={"key": "empty"}, + ), + "array": ArrayV3Metadata.from_dict( + { + **array_metadata, + "attributes": {"key": "grandchild"}, + "shape": (4, 4), + "chunk_grid": { + "configuration": {"chunk_shape": (4, 4)}, + "name": "regular", + }, + } + ), + } + ), + ), + }, + ), + ), + }, + ), + ) + + assert group2.metadata == expected + group3 = await open(store=memory_store_with_hierarchy) + assert group3.metadata == expected + + group4 = await open_consolidated(store=memory_store_with_hierarchy) + assert group4.metadata == expected + + buf = await memory_store_with_hierarchy.get( + "zarr.json", prototype=default_buffer_prototype() + ) + assert buf is not None + + result_raw = json.loads(buf.to_bytes())["consolidated_metadata"] + assert result_raw["kind"] == "inline" + assert sorted(result_raw["metadata"]) == [ + "air", + "child", + "child/array", + "child/grandchild", + "child/grandchild/array", + "child/grandchild/empty_group", + "lat", + "lon", + "time", + ] + + def test_consolidated_sync(self, memory_store: Store) -> None: + g = zarr.api.synchronous.group(store=memory_store, attributes={"foo": "bar"}) + dtype = "uint8" + g.create_array(name="air", shape=(1, 2, 3), dtype=dtype) + g.create_array(name="lat", shape=(1,), dtype=dtype) + g.create_array(name="lon", shape=(2,), dtype=dtype) + g.create_array(name="time", shape=(3,), dtype=dtype) + + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + zarr.api.synchronous.consolidate_metadata(memory_store) + group2 = zarr.Group.open(memory_store) + + array_metadata: dict[str, JSON] = { + "attributes": {}, + "chunk_key_encoding": { + "configuration": {"separator": "/"}, + "name": "default", + }, + "codecs": ( + {"configuration": {"endian": "little"}, "name": "bytes"}, + {"configuration": {"level": 0, "checksum": False}, "name": "zstd"}, + ), + "data_type": dtype, + "fill_value": 0, + "node_type": "array", + # "shape": (1, 2, 3), + "zarr_format": 3, + } + + expected = GroupMetadata( + attributes={"foo": "bar"}, + consolidated_metadata=ConsolidatedMetadata( + kind="inline", + must_understand=False, + metadata={ + "air": ArrayV3Metadata.from_dict( + { + "shape": (1, 2, 3), + "chunk_grid": { + "configuration": {"chunk_shape": (1, 2, 3)}, + "name": "regular", + }, + **array_metadata, + } + ), + "lat": ArrayV3Metadata.from_dict( + { + "shape": (1,), + "chunk_grid": { + "configuration": {"chunk_shape": (1,)}, + "name": "regular", + }, + **array_metadata, + } + ), + "lon": ArrayV3Metadata.from_dict( + { + "shape": (2,), + "chunk_grid": { + "configuration": {"chunk_shape": (2,)}, + "name": "regular", + }, + **array_metadata, + } + ), + "time": ArrayV3Metadata.from_dict( + { + "shape": (3,), + "chunk_grid": { + "configuration": {"chunk_shape": (3,)}, + "name": "regular", + }, + **array_metadata, + } + ), + }, + ), + ) + assert group2.metadata == expected + group3 = zarr.api.synchronous.open(store=memory_store) + assert group3.metadata == expected + + group4 = zarr.api.synchronous.open_consolidated(store=memory_store) + assert group4.metadata == expected + + async def test_not_writable_raises(self, memory_store: zarr.storage.MemoryStore) -> None: + await group(store=memory_store, attributes={"foo": "bar"}) + read_store = zarr.storage.MemoryStore(store_dict=memory_store._store_dict, read_only=True) + with pytest.raises(ValueError, match="does not support writing"): + await consolidate_metadata(read_store) + + async def test_non_root_node(self, memory_store_with_hierarchy: Store) -> None: + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + await consolidate_metadata(memory_store_with_hierarchy, path="child") + root = await AsyncGroup.open(memory_store_with_hierarchy) + child = await AsyncGroup.open(StorePath(memory_store_with_hierarchy) / "child") + + assert root.metadata.consolidated_metadata is None + assert child.metadata.consolidated_metadata is not None + assert "air" not in child.metadata.consolidated_metadata.metadata + assert "grandchild" in child.metadata.consolidated_metadata.metadata + + def test_consolidated_metadata_from_dict(self) -> None: + data: dict[str, JSON] = {"must_understand": False} + + # missing kind + with pytest.raises(ValueError, match="kind='None'"): + ConsolidatedMetadata.from_dict(data) + + # invalid kind + data["kind"] = "invalid" + with pytest.raises(ValueError, match="kind='invalid'"): + ConsolidatedMetadata.from_dict(data) + + # missing metadata + data["kind"] = "inline" + + with pytest.raises(TypeError, match="Unexpected type for 'metadata'"): + ConsolidatedMetadata.from_dict(data) + + data["kind"] = "inline" + # empty is fine + data["metadata"] = {} + ConsolidatedMetadata.from_dict(data) + + def test_flatten(self) -> None: + array_metadata: dict[str, Any] = { + "attributes": {}, + "chunk_key_encoding": { + "configuration": {"separator": "/"}, + "name": "default", + }, + "codecs": ({"configuration": {"endian": "little"}, "name": "bytes"},), + "data_type": "float64", + "fill_value": np.float64(0.0), + "node_type": "array", + # "shape": (1, 2, 3), + "zarr_format": 3, + } + + metadata = ConsolidatedMetadata( + kind="inline", + must_understand=False, + metadata={ + "air": ArrayV3Metadata.from_dict( + { + "shape": (1, 2, 3), + "chunk_grid": { + "configuration": {"chunk_shape": (1, 2, 3)}, + "name": "regular", + }, + **array_metadata, + } + ), + "lat": ArrayV3Metadata.from_dict( + { + "shape": (1,), + "chunk_grid": { + "configuration": {"chunk_shape": (1,)}, + "name": "regular", + }, + **array_metadata, + } + ), + "child": GroupMetadata( + attributes={"key": "child"}, + consolidated_metadata=ConsolidatedMetadata( + metadata={ + "array": ArrayV3Metadata.from_dict( + { + **array_metadata, + "attributes": {"key": "child"}, + "shape": (4, 4), + "chunk_grid": { + "configuration": {"chunk_shape": (4, 4)}, + "name": "regular", + }, + } + ), + "grandchild": GroupMetadata( + attributes={"key": "grandchild"}, + consolidated_metadata=ConsolidatedMetadata( + metadata={ + "array": ArrayV3Metadata.from_dict( + { + **array_metadata, + "attributes": {"key": "grandchild"}, + "shape": (4, 4), + "chunk_grid": { + "configuration": {"chunk_shape": (4, 4)}, + "name": "regular", + }, + } + ) + } + ), + ), + }, + ), + ), + }, + ) + result = metadata.flattened_metadata + + expected = { + "air": metadata.metadata["air"], + "lat": metadata.metadata["lat"], + "child": GroupMetadata( + attributes={"key": "child"}, consolidated_metadata=ConsolidatedMetadata(metadata={}) + ), + "child/array": metadata.metadata["child"].consolidated_metadata.metadata["array"], # type: ignore[union-attr] + "child/grandchild": GroupMetadata( + attributes={"key": "grandchild"}, + consolidated_metadata=ConsolidatedMetadata(metadata={}), + ), + "child/grandchild/array": ( + metadata.metadata["child"] + .consolidated_metadata.metadata["grandchild"] # type: ignore[union-attr] + .consolidated_metadata.metadata["array"] + ), + } + assert result == expected + + def test_invalid_metadata_raises(self) -> None: + payload: dict[str, JSON] = { + "kind": "inline", + "must_understand": False, + "metadata": { + "foo": [1, 2, 3] # invalid + }, + } + + with pytest.raises(TypeError, match="key='foo', type='list'"): + ConsolidatedMetadata.from_dict(payload) + + def test_to_dict_empty(self) -> None: + meta = ConsolidatedMetadata( + metadata={ + "empty": GroupMetadata( + attributes={"key": "empty"}, + consolidated_metadata=ConsolidatedMetadata(metadata={}), + ) + } + ) + result = meta.to_dict() + expected = { + "kind": "inline", + "must_understand": False, + "metadata": { + "empty": { + "attributes": {"key": "empty"}, + "consolidated_metadata": { + "kind": "inline", + "must_understand": False, + "metadata": {}, + }, + "node_type": "group", + "zarr_format": 3, + } + }, + } + assert result == expected + + @pytest.mark.parametrize("zarr_format", [2, 3]) + async def test_to_dict_order( + self, memory_store: zarr.storage.MemoryStore, zarr_format: ZarrFormat + ) -> None: + with zarr.config.set(default_zarr_format=zarr_format): + g = await group(store=memory_store) + + # Create groups in non-lexicographix order + dtype = "float32" + await g.create_array(name="b", shape=(1,), dtype=dtype) + child = await g.create_group("c", attributes={"key": "child"}) + await g.create_array(name="a", shape=(1,), dtype=dtype) + + await child.create_array("e", shape=(1,), dtype=dtype) + await child.create_array("d", shape=(1,), dtype=dtype) + + # Consolidate metadata and re-open store + if zarr_format == 3: + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + await zarr.api.asynchronous.consolidate_metadata(memory_store) + else: + await zarr.api.asynchronous.consolidate_metadata(memory_store) + g2 = await zarr.api.asynchronous.open_group(store=memory_store) + + assert g2.metadata.consolidated_metadata is not None + assert list(g2.metadata.consolidated_metadata.metadata) == ["a", "b", "c"] + assert list(g2.metadata.consolidated_metadata.flattened_metadata) == [ + "a", + "b", + "c", + "c/d", + "c/e", + ] + + @pytest.mark.parametrize("zarr_format", [2, 3]) + async def test_open_consolidated_raises_async(self, zarr_format: ZarrFormat) -> None: + store = zarr.storage.MemoryStore() + await AsyncGroup.from_store(store, zarr_format=zarr_format) + with pytest.raises(ValueError): + await zarr.api.asynchronous.open_consolidated(store, zarr_format=zarr_format) + + with pytest.raises(ValueError): + await zarr.api.asynchronous.open_consolidated(store, zarr_format=None) + + @pytest.fixture + async def v2_consolidated_metadata_empty_dataset( + self, memory_store: zarr.storage.MemoryStore + ) -> AsyncGroup: + zgroup_bytes = cpu.Buffer.from_bytes(json.dumps({"zarr_format": 2}).encode()) + zmetadata_bytes = cpu.Buffer.from_bytes( + b'{"metadata":{".zgroup":{"zarr_format":2}},"zarr_consolidated_format":1}' + ) + return AsyncGroup._from_bytes_v2( + StorePath(memory_store, path=""), + zgroup_bytes, + zattrs_bytes=None, + consolidated_metadata_bytes=zmetadata_bytes, + ) + + async def test_consolidated_metadata_backwards_compatibility( + self, v2_consolidated_metadata_empty_dataset: AsyncGroup + ) -> None: + """ + Test that consolidated metadata handles a missing .zattrs key. This is necessary for backwards compatibility with zarr-python 2.x. See https://github.com/zarr-developers/zarr-python/issues/2694 + """ + store = zarr.storage.MemoryStore() + await zarr.api.asynchronous.open(store=store, zarr_format=2) + await zarr.api.asynchronous.consolidate_metadata(store) + result = await zarr.api.asynchronous.open_consolidated(store, zarr_format=2) + assert result.metadata == v2_consolidated_metadata_empty_dataset.metadata + + async def test_consolidated_metadata_v2(self) -> None: + store = zarr.storage.MemoryStore() + g = await AsyncGroup.from_store(store, attributes={"key": "root"}, zarr_format=2) + dtype = parse_dtype("uint8", zarr_format=2) + await g.create_array(name="a", shape=(1,), attributes={"key": "a"}, dtype=dtype) + g1 = await g.create_group(name="g1", attributes={"key": "g1"}) + await g1.create_group(name="g2", attributes={"key": "g2"}) + + await zarr.api.asynchronous.consolidate_metadata(store) + result = await zarr.api.asynchronous.open_consolidated(store, zarr_format=2) + + expected = GroupMetadata( + attributes={"key": "root"}, + zarr_format=2, + consolidated_metadata=ConsolidatedMetadata( + metadata={ + "a": ArrayV2Metadata( + shape=(1,), + dtype=dtype, + attributes={"key": "a"}, + chunks=(1,), + fill_value=0, + compressor=Blosc(), + order="C", + ), + "g1": GroupMetadata( + attributes={"key": "g1"}, + zarr_format=2, + consolidated_metadata=ConsolidatedMetadata( + metadata={ + "g2": GroupMetadata( + attributes={"key": "g2"}, + zarr_format=2, + consolidated_metadata=ConsolidatedMetadata(metadata={}), + ) + } + ), + ), + } + ), + ) + assert result.metadata == expected + + @pytest.mark.parametrize("zarr_format", [2, 3]) + async def test_use_consolidated_false( + self, memory_store: zarr.storage.MemoryStore, zarr_format: ZarrFormat + ) -> None: + with zarr.config.set(default_zarr_format=zarr_format): + g = await group(store=memory_store, attributes={"foo": "bar"}) + await g.create_group(name="a") + + # test a stale read + if zarr_format == 3: + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + await zarr.api.asynchronous.consolidate_metadata(memory_store) + else: + await zarr.api.asynchronous.consolidate_metadata(memory_store) + await g.create_group(name="b") + + stale = await zarr.api.asynchronous.open_group(store=memory_store) + assert len([x async for x in stale.members()]) == 1 + assert stale.metadata.consolidated_metadata + assert list(stale.metadata.consolidated_metadata.metadata) == ["a"] + + # bypass stale data + good = await zarr.api.asynchronous.open_group( + store=memory_store, use_consolidated=False + ) + assert len([x async for x in good.members()]) == 2 + + # reconsolidate + if zarr_format == 3: + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + await zarr.api.asynchronous.consolidate_metadata(memory_store) + else: + await zarr.api.asynchronous.consolidate_metadata(memory_store) + + good = await zarr.api.asynchronous.open_group(store=memory_store) + assert len([x async for x in good.members()]) == 2 + assert good.metadata.consolidated_metadata + assert sorted(good.metadata.consolidated_metadata.metadata) == ["a", "b"] + + async def test_stale_child_metadata_ignored( + self, memory_store: zarr.storage.MemoryStore + ) -> None: + # https://github.com/zarr-developers/zarr-python/issues/2921 + # When consolidating metadata, we should ignore any (possibly stale) metadata + # from previous consolidations, *including at child nodes*. + root = await zarr.api.asynchronous.group(store=memory_store, zarr_format=3) + await root.create_group("foo") + await zarr.api.asynchronous.consolidate_metadata(memory_store, path="foo") + await root.create_group("foo/bar/spam") + + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + await zarr.api.asynchronous.consolidate_metadata(memory_store) + + reopened = await zarr.api.asynchronous.open_consolidated(store=memory_store, zarr_format=3) + result = [x[0] async for x in reopened.members(max_depth=None)] + expected = ["foo", "foo/bar", "foo/bar/spam"] + assert result == expected + + async def test_use_consolidated_for_children_members( + self, memory_store: zarr.storage.MemoryStore + ) -> None: + # A test that has *unconsolidated* metadata at the root group, but discovers + # a child group with consolidated metadata. + + root = await zarr.api.asynchronous.create_group(store=memory_store) + await root.create_group("a/b") + # Consolidate metadata at "a/b" + await zarr.api.asynchronous.consolidate_metadata(memory_store, path="a/b") + + # Add a new group a/b/c, that's not present in the CM at "a/b" + await root.create_group("a/b/c") + + # Now according to the consolidated metadata, "a" has children ["b"] + # but according to the unconsolidated metadata, "a" has children ["b", "c"] + group = await zarr.api.asynchronous.open_group(store=memory_store, path="a") + with pytest.warns(ZarrUserWarning, match="Object at 'c' not found"): + result = sorted([x[0] async for x in group.members(max_depth=None)]) + expected = ["b"] + assert result == expected + + result = sorted( + [x[0] async for x in group.members(max_depth=None, use_consolidated_for_children=False)] + ) + expected = ["b", "b/c"] + assert result == expected + + async def test_absolute_path_for_subgroup(self, memory_store: zarr.storage.MemoryStore) -> None: + root = await zarr.api.asynchronous.create_group(store=memory_store) + await root.create_group("a/b") + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + await zarr.api.asynchronous.consolidate_metadata(memory_store) + + group = await zarr.api.asynchronous.open_group(store=memory_store) + subgroup = await group.get_group("/a") + members = [x async for x in subgroup.keys()] # noqa: SIM118 + assert members == ["b"] + + +@pytest.mark.parametrize("fill_value", [np.nan, np.inf, -np.inf]) +async def test_consolidated_metadata_encodes_special_chars( + memory_store: Store, zarr_format: ZarrFormat, fill_value: float +) -> None: + root = await group(store=memory_store, zarr_format=zarr_format) + _time = await root.create_array("time", shape=(12,), dtype=np.float64, fill_value=fill_value) + if zarr_format == 3: + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + await zarr.api.asynchronous.consolidate_metadata(memory_store) + else: + await zarr.api.asynchronous.consolidate_metadata(memory_store) + + root = await group(store=memory_store, zarr_format=zarr_format) + root_buffer = root.metadata.to_buffer_dict(default_buffer_prototype()) + + if zarr_format == 2: + root_metadata = json.loads(root_buffer[".zmetadata"].to_bytes().decode("utf-8"))["metadata"] + elif zarr_format == 3: + root_metadata = json.loads(root_buffer["zarr.json"].to_bytes().decode("utf-8"))[ + "consolidated_metadata" + ]["metadata"] + + expected_fill_value = _time._zdtype.to_json_scalar(fill_value, zarr_format=2) + + if zarr_format == 2: + assert root_metadata["time/.zarray"]["fill_value"] == expected_fill_value + elif zarr_format == 3: + assert root_metadata["time"]["fill_value"] == expected_fill_value + + +class NonConsolidatedStore(zarr.storage.MemoryStore): + """A store that doesn't support consolidated metadata""" + + @property + def supports_consolidated_metadata(self) -> bool: + return False + + +async def test_consolidate_metadata_raises_for_self_consolidating_stores() -> None: + """Verify calling consolidate_metadata on a non supporting stores raises an error.""" + + memory_store = NonConsolidatedStore() + root = await zarr.api.asynchronous.create_group(store=memory_store) + await root.create_group("a/b") + + with pytest.raises(TypeError, match="doesn't support consolidated metadata"): + await zarr.api.asynchronous.consolidate_metadata(memory_store) + + +async def test_open_group_in_non_consolidating_stores() -> None: + memory_store = NonConsolidatedStore() + root = await zarr.api.asynchronous.create_group(store=memory_store) + await root.create_group("a/b") + + # Opening a group without consolidatedion works as expected + await AsyncGroup.open(memory_store, use_consolidated=False) + + # let the Store opt out of consolidation + await AsyncGroup.open(memory_store, use_consolidated=None) + + # Opening a group with use_consolidated=True should fail + with pytest.raises(ValueError, match="doesn't support consolidated metadata"): + await AsyncGroup.open(memory_store, use_consolidated=True) + + +@pytest.mark.parametrize( + "order", + [ + # keys grouped by parent, the order zarr-python used to write before it + # started sorting the persisted keys + ["a", "b", "a/x", "a/y", "b/x", "b/y"], + # sibling subtrees interleaved, which is what the (depth, casefold) sort + # produces for names differing only by case + ["a", "b", "a/x", "b/x", "a/y", "b/y"], + # reversed, to cover a parent appearing after its children in the mapping + ["b/y", "b/x", "a/y", "a/x", "b", "a"], + ], +) +def test_flat_to_nested_is_order_independent(order: list[str]) -> None: + """The persisted key order is arbitrary, so nesting must not depend on it.""" + group_metadata: dict[str, JSON] = {"zarr_format": 3, "node_type": "group", "attributes": {}} + consolidated = ConsolidatedMetadata.from_dict( + { + "kind": "inline", + "must_understand": False, + "metadata": dict.fromkeys(order, group_metadata), + } + ) + + assert sorted(consolidated.metadata) == ["a", "b"] + for name in ("a", "b"): + child = consolidated.metadata[name] + assert isinstance(child, GroupMetadata) + assert child.consolidated_metadata is not None + assert sorted(child.consolidated_metadata.metadata) == ["x", "y"] + + +async def test_consolidated_metadata_case_differing_siblings(memory_store: Store) -> None: + """Sibling nodes whose names differ only by case each keep their own children. + + Regression test for https://github.com/zarr-developers/zarr-python/issues/4226 + """ + root = await zarr.api.asynchronous.create_group(store=memory_store) + for name in ("Study", "study"): + child = await root.create_group(f"obs/{name}") + await child.create_array(name="categories", shape=(2,), dtype="uint8") + await child.create_array(name="codes", shape=(2,), dtype="uint8") + + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + await consolidate_metadata(memory_store) + + consolidated = await open_consolidated(store=memory_store) + result = sorted([key async for key, _ in consolidated.members(max_depth=None)]) + assert result == [ + "obs", + "obs/Study", + "obs/Study/categories", + "obs/Study/codes", + "obs/study", + "obs/study/categories", + "obs/study/codes", + ] diff --git a/tests/test_metadata/test_v2.py b/tests/test_metadata/test_v2.py new file mode 100644 index 0000000000..1358f458d6 --- /dev/null +++ b/tests/test_metadata/test_v2.py @@ -0,0 +1,401 @@ +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Literal + +import numpy as np +import pytest + +import zarr.api.asynchronous +import zarr.storage +from zarr.core.buffer import cpu +from zarr.core.buffer.core import default_buffer_prototype +from zarr.core.dtype.npy.float import Float32, Float64 +from zarr.core.dtype.npy.int import Int16 +from zarr.core.group import ConsolidatedMetadata, GroupMetadata +from zarr.core.metadata import ArrayV2Metadata +from zarr.core.metadata.v2 import parse_zarr_format +from zarr.errors import ZarrUserWarning + +if TYPE_CHECKING: + from pathlib import Path + from typing import Any + + from zarr.abc.codec import Codec + from zarr.core.common import JSON + + +def test_parse_zarr_format_valid() -> None: + assert parse_zarr_format(2) == 2 + + +# The explicit id for "3" avoids colliding with the auto-generated id for the int 3. +@pytest.mark.parametrize("data", [None, 1, 3, 4, 5, pytest.param("3", id="3-str")]) +def test_parse_zarr_format_invalid(data: Any) -> None: + with pytest.raises(ValueError, match="Failed to parse input for 'zarr_format'"): + parse_zarr_format(data) + + +@pytest.mark.parametrize("attributes", [None, {"foo": "bar"}]) +@pytest.mark.parametrize("filters", [None, [{"id": "gzip", "level": 1}]]) +@pytest.mark.parametrize("compressor", [None, {"id": "gzip", "level": 1}]) +@pytest.mark.parametrize("fill_value", [None, 0, 1]) +@pytest.mark.parametrize("order", ["C", "F"]) +@pytest.mark.parametrize("dimension_separator", [".", "/", None]) +def test_metadata_to_dict( + compressor: Codec | None, + filters: tuple[Codec] | None, + fill_value: Any, + order: Literal["C", "F"], + dimension_separator: Literal[".", "/"] | None, + attributes: dict[str, Any] | None, +) -> None: + shape = (1, 2, 3) + chunks = (1,) * len(shape) + data_type = "|u1" + metadata_dict = { + "zarr_format": 2, + "shape": shape, + "chunks": chunks, + "dtype": data_type, + "order": order, + "compressor": compressor, + "filters": filters, + "fill_value": fill_value, + } + + if attributes is not None: + metadata_dict["attributes"] = attributes + if dimension_separator is not None: + metadata_dict["dimension_separator"] = dimension_separator + + metadata = ArrayV2Metadata.from_dict(metadata_dict) + observed = metadata.to_dict() + expected = metadata_dict.copy() + + if attributes is None: + assert observed["attributes"] == {} + observed.pop("attributes") + + if dimension_separator is None: + expected_dimension_sep = "." + assert observed["dimension_separator"] == expected_dimension_sep + observed.pop("dimension_separator") + + assert observed == expected + + +def test_filters_empty_tuple_warns() -> None: + metadata_dict = { + "zarr_format": 2, + "shape": (1,), + "chunks": (1,), + "dtype": "|u1", + "order": "C", + "compressor": None, + "filters": (), + "fill_value": 0, + } + with pytest.warns( + ZarrUserWarning, match="Found an empty list of filters in the array metadata document." + ): + meta = ArrayV2Metadata.from_dict(metadata_dict) + assert meta.filters is None + + +class TestConsolidated: + @pytest.fixture + async def v2_consolidated_metadata( + self, memory_store: zarr.storage.MemoryStore + ) -> zarr.storage.MemoryStore: + zmetadata: dict[str, JSON] = { + "metadata": { + ".zattrs": { + "Conventions": "COARDS", + }, + ".zgroup": {"zarr_format": 2}, + "air/.zarray": { + "chunks": [730], + "compressor": None, + "dtype": " None: + # .zgroup, .zattrs, .metadata + store = v2_consolidated_metadata + group = zarr.open_consolidated(store=store, zarr_format=2) + assert group.metadata.consolidated_metadata is not None + expected = ConsolidatedMetadata( + metadata={ + "air": ArrayV2Metadata( + shape=(730,), + fill_value=0, + chunks=(730,), + attributes={"_ARRAY_DIMENSIONS": ["time"], "dataset": "NMC Reanalysis"}, + dtype=Int16(), + order="C", + filters=None, + dimension_separator=".", + compressor=None, + ), + "time": ArrayV2Metadata( + shape=(730,), + fill_value=0.0, + chunks=(730,), + attributes={ + "_ARRAY_DIMENSIONS": ["time"], + "calendar": "standard", + "long_name": "Time", + "standard_name": "time", + "units": "hours since 1800-01-01", + }, + dtype=Float32(), + order="C", + filters=None, + dimension_separator=".", + compressor=None, + ), + "nested": GroupMetadata( + attributes={"key": "value"}, + zarr_format=2, + consolidated_metadata=ConsolidatedMetadata( + metadata={ + "array": ArrayV2Metadata( + shape=(730,), + fill_value=0.0, + chunks=(730,), + attributes={ + "calendar": "standard", + }, + dtype=Float32(), + order="C", + filters=None, + dimension_separator=".", + compressor=None, + ) + } + ), + ), + }, + kind="inline", + must_understand=False, + ) + result = group.metadata.consolidated_metadata + assert result == expected + + async def test_getitem_consolidated( + self, v2_consolidated_metadata: zarr.storage.MemoryStore + ) -> None: + store = v2_consolidated_metadata + group = await zarr.api.asynchronous.open_consolidated(store=store, zarr_format=2) + air = await group.getitem("air") + assert isinstance(air, zarr.AsyncArray) + assert air.metadata.shape == (730,) + + +def test_from_dict_extra_fields() -> None: + data = { + "_nczarr_array": {"dimrefs": ["/dim1", "/dim2"], "storage": "chunked"}, + "attributes": {"key": "value"}, + "chunks": [8], + "compressor": None, + "dtype": " None: + """Two metadata objects with an identical NaN fill_value compare equal. + + NaN is not equal to itself under IEEE 754, so the default dataclass __eq__ + reports two otherwise-identical metadata objects as unequal. Metadata + equality must treat matching NaN fill values as equal (see issue #2929). + """ + a = ArrayV2Metadata( + shape=(8,), dtype=Float64(), chunks=(8,), fill_value=np.float64("nan"), order="C" + ) + b = ArrayV2Metadata( + shape=(8,), dtype=Float64(), chunks=(8,), fill_value=np.float64("nan"), order="C" + ) + assert a == b + + +def test_eq_distinct_fill_value() -> None: + """Metadata objects that differ only in fill_value do not compare equal.""" + a = ArrayV2Metadata(shape=(8,), dtype=Float64(), chunks=(8,), fill_value=0.0, order="C") + b = ArrayV2Metadata(shape=(8,), dtype=Float64(), chunks=(8,), fill_value=1.0, order="C") + assert a != b + + +@pytest.mark.parametrize("fill_value", [np.float64("inf"), np.float64("-inf")]) +def test_eq_inf_fill_value(fill_value: np.float64) -> None: + """Two metadata objects with an identical infinite fill_value compare equal.""" + a = ArrayV2Metadata(shape=(8,), dtype=Float64(), chunks=(8,), fill_value=fill_value, order="C") + b = ArrayV2Metadata(shape=(8,), dtype=Float64(), chunks=(8,), fill_value=fill_value, order="C") + assert a == b + + +def test_hash_consistent_with_eq_nan_fill_value() -> None: + """Equal metadata objects with a NaN fill_value hash equal. + + NaN hashes by identity, so a field-based hash would break the + ``a == b implies hash(a) == hash(b)`` invariant for objects that compare + equal under the to_dict-based __eq__. + """ + a = ArrayV2Metadata( + shape=(8,), dtype=Float64(), chunks=(8,), fill_value=np.float64("nan"), order="C" + ) + b = ArrayV2Metadata( + shape=(8,), dtype=Float64(), chunks=(8,), fill_value=np.float64("nan"), order="C" + ) + assert a == b + assert hash(a) == hash(b) + + +def test_eq_non_metadata() -> None: + """Comparison against a non-metadata object returns False rather than erroring.""" + a = ArrayV2Metadata(shape=(8,), dtype=Float64(), chunks=(8,), fill_value=0.0, order="C") + assert a != object() + + +def test_zstd_checksum() -> None: + compressor_config: dict[str, JSON] = {"id": "zstd", "level": 5, "checksum": False} + arr = zarr.create_array( + {}, + shape=(10,), + chunks=(10,), + dtype="int32", + compressors=compressor_config, + zarr_format=2, + ) + metadata = json.loads( + arr.metadata.to_buffer_dict(default_buffer_prototype())[".zarray"].to_bytes() + ) + assert "checksum" not in metadata["compressor"] + + +@pytest.mark.parametrize("fill_value", [np.void((0, 0), np.dtype([("foo", "i4"), ("bar", "i4")]))]) +def test_structured_dtype_fill_value_serialization( + tmp_path: Path, fill_value: np.void | np.dtype[Any] +) -> None: + zarr_format: Literal[2] = 2 + group_path = tmp_path / "test.zarr" + root_group = zarr.open_group(group_path, mode="w", zarr_format=zarr_format) + dtype = np.dtype([("foo", "i4"), ("bar", "i4")]) + root_group.create_array( + name="structured_dtype", + shape=(100, 100), + chunks=(100, 100), + dtype=dtype, + fill_value=fill_value, + ) + + zarr.consolidate_metadata(root_group.store, zarr_format=zarr_format) + root_group = zarr.open_group(group_path, mode="r") + observed = root_group.metadata.consolidated_metadata.metadata["structured_dtype"].fill_value # type: ignore[union-attr] + assert observed == fill_value diff --git a/tests/test_metadata/test_v3.py b/tests/test_metadata/test_v3.py new file mode 100644 index 0000000000..d1e156e500 --- /dev/null +++ b/tests/test_metadata/test_v3.py @@ -0,0 +1,471 @@ +"""Tests for zarr v3 metadata classes and parsing helpers.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING + +import numpy as np +import pytest + +from tests.conftest import Expect, ExpectFail +from tests.test_metadata.conftest import minimal_metadata_dict_v3 +from zarr.core.buffer import default_buffer_prototype +from zarr.core.chunk_grids import is_regular_1d, is_regular_nd +from zarr.core.config import config +from zarr.core.dtype import Float64, UInt8 +from zarr.core.group import GroupMetadata, parse_node_type +from zarr.core.metadata.v2 import ArrayV2Metadata +from zarr.core.metadata.v3 import ( + ARRAY_METADATA_KEYS, + ArrayMetadataJSON_V3, + ArrayV3Metadata, + parse_codecs, + parse_dimension_names, + parse_node_type_array, + parse_zarr_format, +) +from zarr.errors import ( + MetadataValidationError, + NodeTypeValidationError, + UnknownCodecError, +) + +if TYPE_CHECKING: + from typing import Any + + +# --------------------------------------------------------------------------- +# Parsing helpers +# --------------------------------------------------------------------------- + + +def test_parse_zarr_format_valid() -> None: + """The integer 3 is the only valid zarr_format for v3.""" + assert parse_zarr_format(3) == 3 + + +@pytest.mark.parametrize("data", [None, 1, 2, 4, 5, "3"]) +def test_parse_zarr_format_invalid(data: Any) -> None: + """Non-3 values are rejected.""" + with pytest.raises(MetadataValidationError): + parse_zarr_format(data) + + +def test_parse_node_type_valid() -> None: + """'array' and 'group' are the only valid node types.""" + assert parse_node_type("array") == "array" + assert parse_node_type("group") == "group" + + +@pytest.mark.parametrize("data", [None, 2, "other"]) +def test_parse_node_type_invalid(data: Any) -> None: + """Non-string and unrecognized values are rejected.""" + with pytest.raises(MetadataValidationError): + parse_node_type(data) + + +def test_parse_node_type_array_valid() -> None: + """parse_node_type_array accepts only 'array'.""" + assert parse_node_type_array("array") == "array" + + +@pytest.mark.parametrize("data", [None, "group"]) +def test_parse_node_type_array_invalid(data: Any) -> None: + """parse_node_type_array rejects 'group' and non-string values.""" + with pytest.raises(NodeTypeValidationError): + parse_node_type_array(data) + + +@pytest.mark.parametrize("data", [None, ("a", "b", "c"), ["a", "a", "a"], ()]) +def test_parse_dimension_names_valid(data: Any) -> None: + """None, tuples of strings, lists of strings, and empty tuples are accepted.""" + result = parse_dimension_names(data) + if data is None: + assert result is None + else: + assert result == tuple(data) + + +@pytest.mark.parametrize("data", [[1, 2, "a"], [None, 3]]) +def test_parse_dimension_names_invalid(data: Any) -> None: + """Iterables containing non-string elements are rejected.""" + with pytest.raises(TypeError, match="Expected either None or"): + parse_dimension_names(data) + + +def test_parse_codecs_unknown_raises(monkeypatch: pytest.MonkeyPatch) -> None: + """An unregistered codec name raises UnknownCodecError.""" + from collections import defaultdict + + import zarr.registry + from zarr.registry import Registry + + monkeypatch.setattr(zarr.registry, "_codec_registries", defaultdict(Registry)) + with pytest.raises(UnknownCodecError): + parse_codecs([{"name": "unknown"}]) + + +# --------------------------------------------------------------------------- +# Chunk-grid regularity helpers +# --------------------------------------------------------------------------- + +# Cases used for both list/tuple (Python-sequence path) and ndarray (vectorized +# path) of `is_regular_1d`. Parametrizing the input form ensures both branches +# are exercised by the same suite of edge cases. +_REGULAR_1D_CASES: list[Expect[list[int], bool]] = [ + Expect(input=[], output=True, id="empty"), + Expect(input=[10], output=True, id="single-chunk"), + Expect(input=[10, 10, 10], output=True, id="all-equal"), + Expect(input=[10, 10, 10, 7], output=True, id="smaller-boundary"), + Expect(input=[10, 10, 10, 10], output=True, id="exact-multiple"), + Expect(input=[10, 5, 10], output=False, id="middle-mismatch"), + Expect(input=[10, 10, 10, 12], output=False, id="last-larger"), + # The first chunk anchors the size; later mismatches in the middle fail + # before the boundary check. + Expect(input=[5, 10, 5], output=False, id="middle-larger"), +] + + +@pytest.mark.parametrize("case", _REGULAR_1D_CASES, ids=lambda c: c.id) +def test_is_regular_1d_sequence(case: Expect[list[int], bool]) -> None: + """`is_regular_1d` accepts plain Python sequences and uses the iterative path.""" + # list and tuple both go through the non-ndarray branch. + assert is_regular_1d(case.input) is case.output + assert is_regular_1d(tuple(case.input)) is case.output + + +@pytest.mark.parametrize("case", _REGULAR_1D_CASES, ids=lambda c: c.id) +def test_is_regular_1d_ndarray(case: Expect[list[int], bool]) -> None: + """`is_regular_1d` accepts int64 ndarrays and uses the vectorized path.""" + arr = np.asarray(case.input, dtype=np.int64) + assert is_regular_1d(arr) is case.output + + +@pytest.mark.parametrize( + "case", + [ + Expect(input=[[10, 10, 10], [5, 5]], output=True, id="all-regular"), + Expect(input=[[10, 10, 7], [5, 5, 5, 3]], output=True, id="all-regular-with-boundary"), + Expect(input=[[10, 10, 10], [5, 8, 5]], output=False, id="second-dim-irregular"), + Expect(input=[[10, 5, 10], [5, 5]], output=False, id="first-dim-irregular"), + Expect(input=[], output=True, id="zero-dims"), + ], + ids=lambda c: c.id, +) +def test_is_regular_nd_sequence(case: Expect[list[list[int]], bool]) -> None: + """`is_regular_nd` returns True iff every per-dim spec is regular.""" + assert is_regular_nd(case.input) is case.output + # Same result via ndarray inputs. + assert is_regular_nd([np.asarray(d, dtype=np.int64) for d in case.input]) is case.output + + +# --------------------------------------------------------------------------- +# Types +# --------------------------------------------------------------------------- + + +def test_array_metadata_keys_matches_typeddict() -> None: + """ + Test that the variable modelling the set of keys for array v3 metadata matches + the keys of the typeddict model for the metadata. + """ + assert ARRAY_METADATA_KEYS == set(ArrayMetadataJSON_V3.__annotations__.keys()) + + +# --------------------------------------------------------------------------- +# ArrayV3Metadata: round-trip +# --------------------------------------------------------------------------- + +# Codecs after evolution for single-byte (uint8) and multi-byte (float64) types. +_UINT8_CODECS = ({"name": "bytes"},) +_FLOAT64_CODECS = ({"name": "bytes", "configuration": {"endian": "little"}},) + + +@pytest.mark.parametrize( + "case", + [ + Expect( + input={}, + output=minimal_metadata_dict_v3(codecs=_UINT8_CODECS), + id="minimal", + ), + Expect( + input={"attributes": {"key": "value"}}, + output=minimal_metadata_dict_v3(attributes={"key": "value"}, codecs=_UINT8_CODECS), + id="with_attributes", + ), + Expect( + input={"dimension_names": ("x", "y")}, + output=minimal_metadata_dict_v3(dimension_names=("x", "y"), codecs=_UINT8_CODECS), + id="with_dimension_names", + ), + Expect( + input={"storage_transformers": ()}, + output=minimal_metadata_dict_v3(storage_transformers=(), codecs=_UINT8_CODECS), + id="with_storage_transformers", + ), + Expect( + input={"data_type": "float64", "fill_value": 0.0}, + output=minimal_metadata_dict_v3( + data_type="float64", fill_value=0.0, codecs=_FLOAT64_CODECS + ), + id="float64", + ), + Expect( + input={"chunk_key_encoding": {"name": "v2", "configuration": {"separator": "."}}}, + output=minimal_metadata_dict_v3( + chunk_key_encoding={"name": "v2", "configuration": {"separator": "."}}, + codecs=_UINT8_CODECS, + ), + id="v2_chunk_key_encoding", + ), + Expect( + input={"data_type": "float64", "fill_value": "NaN"}, + output=minimal_metadata_dict_v3( + data_type="float64", fill_value="NaN", codecs=_FLOAT64_CODECS + ), + id="nan_fill_value", + ), + Expect( + input={"data_type": "float64", "fill_value": "Infinity"}, + output=minimal_metadata_dict_v3( + data_type="float64", fill_value="Infinity", codecs=_FLOAT64_CODECS + ), + id="inf_fill_value", + ), + Expect( + input={"data_type": "float64", "fill_value": "-Infinity"}, + output=minimal_metadata_dict_v3( + data_type="float64", fill_value="-Infinity", codecs=_FLOAT64_CODECS + ), + id="neg_inf_fill_value", + ), + Expect( + input={ + "attributes": {}, + "storage_transformers": (), + "extra_fields": {"my_ext": {"must_understand": False, "data": [1, 2, 3]}}, + }, + output=minimal_metadata_dict_v3( + attributes={}, + storage_transformers=(), + codecs=_UINT8_CODECS, + extra_fields={"my_ext": {"must_understand": False, "data": [1, 2, 3]}}, + ), + id="extra_fields", + ), + ], + ids=lambda case: case.id, +) +def test_array_metadata_roundtrip(case: Expect[dict[str, Any], dict[str, Any]]) -> None: + """from_dict(d).to_dict() produces the expected output, including codec evolution.""" + d = minimal_metadata_dict_v3(**case.input) + m = ArrayV3Metadata.from_dict(d) # type: ignore[arg-type] + assert m.to_dict() == case.output + + +# --------------------------------------------------------------------------- +# ArrayV3Metadata: failure modes +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input={"dimension_names": ("x", "y", "z")}, + exception=ValueError, + msg="dimension_names.*shape", + id="dimension_names_length_mismatch", + ), + ExpectFail( + input={"data_type": "uint8", "fill_value": {}}, + exception=TypeError, + id="invalid_fill_value_type", + ), + ], + ids=lambda case: case.id, +) +def test_array_metadata_from_dict_fails(case: ExpectFail[dict[str, Any]]) -> None: + """from_dict rejects invalid metadata documents.""" + d = minimal_metadata_dict_v3(**case.input) + with case.raises(): + ArrayV3Metadata.from_dict(d) # type: ignore[arg-type] + + +@pytest.mark.parametrize( + "case", + [ + ExpectFail( + input=minimal_metadata_dict_v3(extra_fields={"my_ext": {"must_understand": True}}), + exception=MetadataValidationError, + msg="disallowed extra fields", + id="must_understand_true", + ), + ExpectFail( + input=minimal_metadata_dict_v3(extra_fields={"my_ext": 42}), + exception=MetadataValidationError, + msg="disallowed extra fields", + id="non_dict_extra_field", + ), + ], + ids=lambda case: case.id, +) +def test_array_metadata_extra_fields_rejected(case: ExpectFail[dict[str, Any]]) -> None: + """from_dict rejects extra fields that don't conform to the spec.""" + with case.raises(): + ArrayV3Metadata.from_dict(case.input) + + +def test_init_extra_fields_collision() -> None: + """Extra field keys that collide with reserved metadata field names are rejected.""" + extra_fields: dict[str, object] = {"shape": (10,), "data_type": "uint8"} + with pytest.raises(ValueError, match="collide with keys reserved"): + ArrayV3Metadata( + shape=(10,), + data_type=UInt8(), + chunk_grid={"name": "regular", "configuration": {"chunk_shape": (10,)}}, + chunk_key_encoding={"name": "default", "configuration": {"separator": "/"}}, + fill_value=0, + codecs=({"name": "bytes", "configuration": {"endian": "little"}},), + attributes={}, + dimension_names=None, + extra_fields=extra_fields, # type: ignore[arg-type] + ) + + +# --------------------------------------------------------------------------- +# Equality +# --------------------------------------------------------------------------- + + +def test_eq_nan_fill_value() -> None: + """Two metadata objects with an identical NaN fill_value compare equal. + + NaN is not equal to itself under IEEE 754, so the default dataclass __eq__ + reports two otherwise-identical metadata objects as unequal. Metadata + equality must treat matching NaN fill values as equal (see issue #2929). + """ + a = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value="NaN")) # type: ignore[arg-type] + b = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value="NaN")) # type: ignore[arg-type] + assert a == b + + +def test_eq_distinct_fill_value() -> None: + """Metadata objects that differ only in fill_value do not compare equal.""" + a = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value=0.0)) # type: ignore[arg-type] + b = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value=1.0)) # type: ignore[arg-type] + assert a != b + + +@pytest.mark.parametrize("fill_value", ["Infinity", "-Infinity"]) +def test_eq_inf_fill_value(fill_value: str) -> None: + """Two metadata objects with an identical infinite fill_value compare equal.""" + a = ArrayV3Metadata.from_dict( + minimal_metadata_dict_v3(data_type="float64", fill_value=fill_value) # type: ignore[arg-type] + ) + b = ArrayV3Metadata.from_dict( + minimal_metadata_dict_v3(data_type="float64", fill_value=fill_value) # type: ignore[arg-type] + ) + assert a == b + + +def test_hash_consistent_with_eq_nan_fill_value() -> None: + """Equal metadata objects with a NaN fill_value hash equal. + + NaN hashes by identity, so a field-based hash would break the + ``a == b implies hash(a) == hash(b)`` invariant for objects that compare + equal under the to_dict-based __eq__. + """ + a = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value="NaN")) # type: ignore[arg-type] + b = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value="NaN")) # type: ignore[arg-type] + assert a == b + assert hash(a) == hash(b) + + +def test_eq_non_metadata() -> None: + """Comparison against a non-metadata object returns False rather than erroring.""" + a = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value=0.0)) # type: ignore[arg-type] + assert a != object() + + +def test_eq_across_zarr_formats() -> None: + """A v2 and v3 metadata describing the same array do not compare equal. + + Each __eq__ guards on its own concrete type and returns NotImplemented + otherwise, so the two versions are never equal even when they describe the + same array. + """ + v3 = ArrayV3Metadata.from_dict(minimal_metadata_dict_v3(data_type="float64", fill_value=0.0)) # type: ignore[arg-type] + v2 = ArrayV2Metadata(shape=(4, 4), dtype=Float64(), chunks=(4, 4), fill_value=0.0, order="C") + assert v2 != v3 + assert v3 != v2 + + +# --------------------------------------------------------------------------- +# JSON indent +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("indent", [2, 4, None]) +def test_json_indent(indent: int | None) -> None: + """The json_indent config setting controls indentation in to_buffer_dict output.""" + with config.set({"json_indent": indent}): + m = GroupMetadata() + d = m.to_buffer_dict(default_buffer_prototype())["zarr.json"].to_bytes() + assert d == json.dumps(json.loads(d), indent=indent).encode() + + +# --------------------------------------------------------------------------- +# GroupMetadata.to_dict +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("attributes", [None, {"foo": "bar"}]) +def test_group_metadata_to_dict(attributes: dict[str, Any] | None) -> None: + """GroupMetadata.to_dict produces the expected v3 JSON structure.""" + meta = GroupMetadata(attributes=attributes) + assert meta.to_dict() == { + "zarr_format": 3, + "node_type": "group", + "attributes": attributes or {}, + } + + +@pytest.mark.parametrize("attributes", [None, {"foo": "bar"}]) +def test_group_metadata_to_dict_consolidated(attributes: dict[str, Any] | None) -> None: + """GroupMetadata.to_dict includes consolidated_metadata when present.""" + from zarr import consolidate_metadata, create_group + from zarr.errors import ZarrUserWarning + + store: dict[str, object] = {} + group = create_group(store, attributes=attributes, zarr_format=3) + group.create_group("foo") + with pytest.warns( + ZarrUserWarning, + match="Consolidated metadata is currently not part in the Zarr format 3 specification.", + ): + group = consolidate_metadata(store) + + assert group.metadata.to_dict() == { + "zarr_format": 3, + "node_type": "group", + "attributes": attributes or {}, + "consolidated_metadata": { + "kind": "inline", + "must_understand": False, + "metadata": { + "foo": { + "attributes": {}, + "zarr_format": 3, + "node_type": "group", + "consolidated_metadata": { + "kind": "inline", + "metadata": {}, + "must_understand": False, + }, + } + }, + }, + } diff --git a/tests/test_pipeline_parity.py b/tests/test_pipeline_parity.py new file mode 100644 index 0000000000..94d95c4c24 --- /dev/null +++ b/tests/test_pipeline_parity.py @@ -0,0 +1,523 @@ +"""Pipeline parity test β€” exhaustive matrix of read/write scenarios. + +For every cell of the matrix (codec config x layout x operation +sequence x runtime config), assert that ``FusedCodecPipeline`` and +``BatchedCodecPipeline`` produce semantically identical results: + + * Same returned array contents on read. + * Same set of store keys after writes (catches divergent empty-shard + handling: one pipeline deletes, the other writes an empty blob). + * Reading each pipeline's store contents through the *other* pipeline + yields the same array (catches "wrote a layout that only one + pipeline can read" bugs). + +Pipeline-divergence bugs (e.g. one pipeline writes a dense shard +layout while the other writes a compact layout) fail this test +loudly with a clear diff, instead of waiting for a downstream +test to trip over the symptom. + +Byte-for-byte equality of store contents is intentionally NOT +checked: codecs like gzip embed the wall-clock timestamp in their +output, so two compressions of the same data done at different +seconds produce different bytes despite being semantically +identical. + +The matrix axes are: + + * codec chain β€” bytes-only, gzip, with/without sharding + * layout β€” chunk_shape, shard_shape (None for no sharding) + * write sequence β€” full overwrite, partial in middle, scalar to one + cell, multiple overlapping writes, sequence ending in fill values + * runtime config β€” write_empty_chunks True/False +""" + +from __future__ import annotations + +import warnings +from contextlib import contextmanager +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +import zarr +from zarr.codecs.bytes import BytesCodec +from zarr.codecs.crc32c_ import Crc32cCodec +from zarr.codecs.gzip import GzipCodec +from zarr.codecs.sharding import ( + SUBCHUNK_WRITE_ORDER, + IndexLocation, + ShardingCodec, + SubchunkWriteOrder, +) +from zarr.codecs.transpose import TransposeCodec +from zarr.core.config import config as zarr_config +from zarr.errors import ZarrUserWarning +from zarr.storage import MemoryStore + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + +# --------------------------------------------------------------------------- +# Reference helpers +# --------------------------------------------------------------------------- + + +def _store_snapshot(store: MemoryStore) -> dict[str, bytes]: + """Return {key: bytes} for every entry in the store.""" + return {k: bytes(v.to_bytes()) for k, v in store._store_dict.items()} + + +# --------------------------------------------------------------------------- +# Matrix definitions +# --------------------------------------------------------------------------- + + +# Each codec config is (filters, serializer, compressors). We only vary the +# pieces that actually affect the pipeline. compressors=None means a +# fixed-size chain (the byte-range fast path is eligible when sharded). +CodecConfig = dict[str, Any] + +CODEC_CONFIGS: list[tuple[str, CodecConfig]] = [ + ("bytes-only", {"compressors": None}), + ("gzip", {"compressors": GzipCodec(level=1)}), + # Big-endian serializer: the on-disk byte order is carried by the BytesCodec, + # not the dtype. Guards the bulk whole-shard decode against ignoring endian + # (it would otherwise reinterpret big-endian bytes as native β€” silent + # corruption). dtype is int32 so endianness is observable. + ( + "bytes-big-endian", + {"compressors": None, "serializer": BytesCodec(endian="big"), "dtype": "int32"}, + ), + # crc32c as a bytes->bytes codec after the serializer: the bulk fast path + # must NOT silently drop checksum verification (it falls through to the + # per-chunk path). Parity still requires identical bytes + contents across + # pipelines. (crc32c is a BytesBytesCodec, so it goes in `compressors`.) + ( + "bytes-crc32c", + {"compressors": [Crc32cCodec()], "serializer": BytesCodec(), "dtype": "int32"}, + ), +] + + +# (id, kwargs) β€” chunks/shards layout. kwargs are passed to create_array. +LayoutConfig = dict[str, Any] + +LAYOUT_CONFIGS: list[tuple[str, LayoutConfig]] = [ + ("1d-unsharded", {"shape": (100,), "chunks": (10,), "shards": None}), + ("1d-1chunk-per-shard", {"shape": (100,), "chunks": (10,), "shards": (10,)}), + ("1d-multi-chunk-per-shard", {"shape": (100,), "chunks": (10,), "shards": (50,)}), + ("2d-unsharded", {"shape": (20, 20), "chunks": (5, 5), "shards": None}), + ("2d-sharded", {"shape": (20, 20), "chunks": (5, 5), "shards": (10, 10)}), + # Nested sharding: outer chunk (10,10) sharded into inner chunks (5,5). + # Restricted to the codec configs that don't set their own `serializer` + # (bytes-only, gzip): this layout supplies an explicit nested-ShardingCodec + # `serializer`, and a codec config that also sets `serializer` (e.g. + # bytes-big-endian) would silently clobber it via dict merge, dropping + # sharding from the test entirely rather than exercising it. The gzip + # config applies as an outer bytes-bytes codec around the outer + # ShardingCodec -- this is the regression coverage for the fused pipeline + # applying outer AA/BB codecs around sharding (see + # `pipeline_supports_partial_decode`/`pipeline_supports_partial_encode`). + ( + "2d-nested-sharded", + { + "shape": (20, 20), + "chunks": (10, 10), + "shards": None, + "serializer": ShardingCodec( + chunk_shape=(10, 10), + codecs=[ShardingCodec(chunk_shape=(5, 5))], + ), + "_codec_ids": {"bytes-only", "gzip"}, + }, + ), +] + + +WriteOp = tuple[Any, Any] # (selection, value) +WriteSequence = tuple[str, list[WriteOp]] + + +def _full_overwrite(shape: tuple[int, ...]) -> list[WriteOp]: + return [((slice(None),) * len(shape), np.arange(int(np.prod(shape))).reshape(shape) + 1)] + + +def _partial_middle(shape: tuple[int, ...]) -> list[WriteOp]: + if len(shape) == 1: + n = shape[0] + return [((slice(n // 4, 3 * n // 4),), 7)] + # 2D: write a centered block + rs = slice(shape[0] // 4, 3 * shape[0] // 4) + cs = slice(shape[1] // 4, 3 * shape[1] // 4) + return [((rs, cs), 7)] + + +def _scalar_one_cell(shape: tuple[int, ...]) -> list[WriteOp]: + if len(shape) == 1: + return [((shape[0] // 2,), 99)] + return [((shape[0] // 2, shape[1] // 2), 99)] + + +def _overlapping(shape: tuple[int, ...]) -> list[WriteOp]: + if len(shape) == 1: + n = shape[0] + return [ + ((slice(0, n // 2),), 1), + ((slice(n // 4, 3 * n // 4),), 2), + ((slice(n // 2, n),), 3), + ] + rs1, cs1 = slice(0, shape[0] // 2), slice(0, shape[1] // 2) + rs2, cs2 = slice(shape[0] // 4, 3 * shape[0] // 4), slice(shape[1] // 4, 3 * shape[1] // 4) + return [((rs1, cs1), 1), ((rs2, cs2), 2)] + + +def _ends_in_fill(shape: tuple[int, ...]) -> list[WriteOp]: + """Write something then overwrite it with fill β€” exercises empty-chunk handling.""" + full = (slice(None),) * len(shape) + return [(full, 5), (full, 0)] + + +def _ends_in_partial_fill(shape: tuple[int, ...]) -> list[WriteOp]: + """Write data, then overwrite half with fill β€” some chunks become empty.""" + full: tuple[slice, ...] + half: tuple[slice, ...] + if len(shape) == 1: + full = (slice(None),) + half = (slice(0, shape[0] // 2),) + else: + full = (slice(None), slice(None)) + half = (slice(0, shape[0] // 2), slice(None)) + return [(full, 5), (half, 0)] + + +SEQUENCES: list[tuple[str, Callable[[tuple[int, ...]], list[WriteOp]]]] = [ + ("full-overwrite", _full_overwrite), + ("partial-middle", _partial_middle), + ("scalar-one-cell", _scalar_one_cell), + ("overlapping", _overlapping), + ("ends-in-fill", _ends_in_fill), + ("ends-in-partial-fill", _ends_in_partial_fill), +] + + +WRITE_EMPTY_CHUNKS = [False, True] + + +# --------------------------------------------------------------------------- +# Matrix iteration (pruned) +# --------------------------------------------------------------------------- + + +def _matrix() -> Iterator[Any]: + for codec_id, codec_kwargs in CODEC_CONFIGS: + for layout_id, layout in LAYOUT_CONFIGS: + allowed = layout.get("_codec_ids") + if allowed is not None and codec_id not in allowed: + continue + for seq_id, seq_fn in SEQUENCES: + for wec in WRITE_EMPTY_CHUNKS: + yield pytest.param( + codec_kwargs, + layout, + seq_fn, + wec, + id=f"{layout_id}-{codec_id}-{seq_id}-wec{wec}", + ) + + +# --------------------------------------------------------------------------- +# The parity test +# --------------------------------------------------------------------------- + + +@contextmanager +def _ignore_sharding_combo_warning() -> Iterator[None]: + """Suppress the "combining sharding_indexed disables partial reads" warning. + + Only the nested-sharded-plus-outer-codec matrix cell emits this; scoping the + ignore filter to just its message/category (rather than blanket-disabling + warnings) keeps every other warning in the run promoted to an error as usual. + """ + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message=r"Combining a `sharding_indexed` codec.*", + category=ZarrUserWarning, + ) + yield + + +def _write_under_pipeline( + pipeline_path: str, + codec_kwargs: CodecConfig, + layout: LayoutConfig, + sequence: list[WriteOp], + write_empty_chunks: bool, +) -> tuple[MemoryStore, Any]: + """Apply a sequence of writes via the chosen pipeline. + + Returns (store with the written data, final array contents read back). + """ + # Strip private metadata keys (e.g. "_codec_ids") before passing to create_array. + array_layout = {k: v for k, v in layout.items() if not k.startswith("_")} + # dtype defaults to float64 but a codec config may override it (e.g. an + # endian-sensitive int dtype). Merge so the override wins without a dup kwarg. + create_kwargs = {"dtype": "float64", **array_layout, **codec_kwargs} + store = MemoryStore() + with zarr_config.set({"codec_pipeline.path": pipeline_path}): + with _ignore_sharding_combo_warning(): + arr = zarr.create_array( + store=store, + fill_value=0, + config={"write_empty_chunks": write_empty_chunks}, + **create_kwargs, + ) + for sel, val in sequence: + arr[sel] = val + contents = arr[...] + return store, contents + + +def _read_under_pipeline(pipeline_path: str, store: MemoryStore) -> Any: + """Re-open an existing store under the chosen pipeline and read it whole.""" + with zarr_config.set({"codec_pipeline.path": pipeline_path}): + with _ignore_sharding_combo_warning(): + arr = zarr.open_array(store=store, mode="r") + return arr[...] + + +_BATCHED = "zarr.core.codec_pipeline.BatchedCodecPipeline" +_FUSED = "zarr.core.codec_pipeline.FusedCodecPipeline" + + +@pytest.mark.parametrize( + ("codec_kwargs", "layout", "sequence_fn", "write_empty_chunks"), + list(_matrix()), +) +def test_pipeline_parity( + codec_kwargs: CodecConfig, + layout: LayoutConfig, + sequence_fn: Callable[[tuple[int, ...]], list[WriteOp]], + write_empty_chunks: bool, +) -> None: + """FusedCodecPipeline must be semantically identical to BatchedCodecPipeline. + + Three checks, in order of decreasing diagnostic value: + + 1. Both pipelines return the same array contents after the same + write sequence (catches semantic correctness bugs). + 2. Both pipelines produce the same set of store keys (catches + empty-shard divergence: one deletes, the other doesn't). + 3. Each pipeline can correctly read the *other* pipeline's + output (catches layout-divergence bugs that would prevent + interop, e.g. dense vs compact shard layouts). + + Byte-for-byte store equality is intentionally not checked: codecs + like gzip embed wall-clock timestamps that vary between runs. + """ + sequence = sequence_fn(layout["shape"]) + + batched_store, batched_arr = _write_under_pipeline( + _BATCHED, codec_kwargs, layout, sequence, write_empty_chunks + ) + sync_store, sync_arr = _write_under_pipeline( + _FUSED, codec_kwargs, layout, sequence, write_empty_chunks + ) + + # 1. Array contents must agree. + np.testing.assert_array_equal( + sync_arr, + batched_arr, + err_msg="FusedCodecPipeline returned different array contents than BatchedCodecPipeline", + ) + + # 2. Store key sets must agree. + batched_keys = set(batched_store._store_dict) - {"zarr.json"} + sync_keys = set(sync_store._store_dict) - {"zarr.json"} + assert sync_keys == batched_keys, ( + f"Pipelines disagree on which store keys exist.\n" + f" only in batched: {sorted(batched_keys - sync_keys)}\n" + f" only in sync: {sorted(sync_keys - batched_keys)}" + ) + + # 3. Cross-read: each pipeline must correctly read the other's output. + sync_reads_batched = _read_under_pipeline(_FUSED, batched_store) + batched_reads_sync = _read_under_pipeline(_BATCHED, sync_store) + np.testing.assert_array_equal( + sync_reads_batched, + batched_arr, + err_msg="FusedCodecPipeline could not correctly read BatchedCodecPipeline's output", + ) + np.testing.assert_array_equal( + batched_reads_sync, + sync_arr, + err_msg="BatchedCodecPipeline could not correctly read FusedCodecPipeline's output", + ) + + +# --------------------------------------------------------------------------- +# Partial-read parity across subchunk write orders +# --------------------------------------------------------------------------- +# +# Note: general partial-read coverage (scalar single-element and strided reads +# from sharded arrays, which hit the sharding codec's partial-decode path) lives +# in tests/test_codec_pipeline_suite.py as Scenarios. Those run each pipeline +# against a numpy reference -- strictly stronger than checking the two pipelines +# only against each other, and they cover both the sync (_decode_partial_sync) +# and async (_decode_partial_single) partial-decode variants. What remains here +# is the cross-pipeline byte-identical-layout check, which the per-pipeline +# suite structurally cannot express. + + +@pytest.mark.parametrize("subchunk_write_order", SUBCHUNK_WRITE_ORDER) +@pytest.mark.parametrize("index_location", ["start", "end"]) +def test_pipeline_parity_subchunk_write_order( + subchunk_write_order: SubchunkWriteOrder, index_location: IndexLocation +) -> None: + """Both pipelines must agree across every subchunk_write_order, including a + PARTIAL write into an already-dense fixed-size shard. + + This is the regression net for the byte-range write fast path, which derives + each chunk's physical slot from its rank in subchunk_write_order. A wrong + (e.g. hardcoded morton) assumption corrupts non-default orders silently, so + we assert both identical contents AND identical stored bytes across pipelines. + write_empty_chunks=True keeps every slot present, making the shard dense and + the byte-range write path eligible. + """ + # 2D, fixed-size (no compression). The shard (array `chunks`) must hold + # MULTIPLE inner chunks, and be non-square, so morton / lexicographic / + # colexicographic produce physically DIFFERENT layouts β€” with one inner + # chunk per shard all orders coincide and a wrong-order bug is invisible. + # inner chunk = (2, 2); shard = (6, 4) -> a 3x2 grid of inner chunks. + shape, shard_shape, inner_chunk = (12, 8), (6, 4), (2, 2) + serializer = ShardingCodec( + chunk_shape=inner_chunk, + codecs=[BytesCodec()], + index_location=index_location, + subchunk_write_order=subchunk_write_order, + ) + ref = np.arange(int(np.prod(shape)), dtype="int32").reshape(shape) + + def run(pipeline_path: str) -> tuple[dict[str, bytes], Any]: + store = MemoryStore() + with zarr_config.set({"codec_pipeline.path": pipeline_path}): + arr = zarr.create_array( + store=store, + shape=shape, + chunks=shard_shape, # array "chunks" == shard size for a ShardingCodec serializer + dtype="int32", + fill_value=-1, + serializer=serializer, + compressors=None, + config={"write_empty_chunks": True}, + ) + arr[:] = ref # dense full write + arr[3:9, 1:6] = 777 # partial write INTO the dense shard + contents = arr[...] + return _store_snapshot(store), contents + + batched_bytes, batched_contents = run(_BATCHED) + sync_bytes, sync_contents = run(_FUSED) + + # Contents must always match across pipelines and equal the reference β€” + # this catches a wrong-order byte-range write (it corrupts the data). + expected = ref.copy() + expected[3:9, 1:6] = 777 + np.testing.assert_array_equal(batched_contents, expected) + np.testing.assert_array_equal( + sync_contents, + batched_contents, + err_msg=f"pipeline contents diverged for subchunk_write_order={subchunk_write_order!r}", + ) + # The two pipelines must also produce byte-identical shards β€” a stronger + # check that they agree on physical layout. This holds for EVERY order + # (without special-casing any by name): both pipelines lay chunks out via + # the same `_subchunk_order_iter`, so for a given codec instance they must + # land on the same bytes whatever that order resolves to. We make no + # assumption here about what any particular order "means" β€” only that the + # two implementations agree. + assert sync_bytes == batched_bytes, ( + f"pipelines wrote different bytes for subchunk_write_order={subchunk_write_order!r} " + f"(index_location={index_location!r}) β€” byte-range write fast path likely assumed " + f"the wrong physical chunk order" + ) + + +# --------------------------------------------------------------------------- +# Outer array-array / bytes-bytes codecs around a sharding serializer +# --------------------------------------------------------------------------- +# +# Regression coverage for FusedCodecPipeline.supports_partial_decode/encode: +# it used to allow AA/BB codecs outside the sharding codec, so its partial +# branches called ShardingCodec._decode_partial_sync/_encode_partial_sync +# directly on the raw stored value, skipping any outer filter/compressor. +# That corrupted on-disk bytes for an outer bytes-bytes codec (unreadable by +# the other pipeline) and silently produced wrong data for an outer +# array-array codec. Both configs below force the partial branches: a +# region write and a region read are included alongside the full ones. + +_OUTER_AA_BB_CONFIGS: list[tuple[str, CodecConfig]] = [ + ( + "outer-gzip-around-sharding", + { + "serializer": ShardingCodec(chunk_shape=(2, 2)), + "compressors": [GzipCodec(level=1)], + }, + ), + ( + "outer-transpose-around-sharding", + { + "filters": [TransposeCodec(order=(1, 0))], + "serializer": ShardingCodec(chunk_shape=(2, 2)), + "compressors": None, + }, + ), +] + + +@pytest.mark.parametrize(("config_id", "codec_kwargs"), _OUTER_AA_BB_CONFIGS) +@pytest.mark.parametrize( + ("writer", "reader"), + [(_BATCHED, _FUSED), (_FUSED, _BATCHED)], + ids=["batched-write-fused-read", "fused-write-batched-read"], +) +def test_pipeline_parity_outer_aa_bb_codecs( + config_id: str, + codec_kwargs: CodecConfig, + writer: str, + reader: str, +) -> None: + """Data written under one pipeline with outer AA/BB codecs must read back + correctly under the other, including through a partial write and a + partial read. + """ + shape = (8, 8) + data = (np.arange(int(np.prod(shape))).reshape(shape) + 1).astype("uint16") + store = MemoryStore() + + with zarr_config.set({"codec_pipeline.path": writer}): + with _ignore_sharding_combo_warning(): + arr = zarr.create_array( + store=store, + shape=shape, + chunks=(4, 4), + dtype=data.dtype, + fill_value=0, + **codec_kwargs, + ) + arr[...] = data + arr[2:5, 1:3] = 99 # region write -- exercises the partial-encode branch + + expected = data.copy() + expected[2:5, 1:3] = 99 + + with zarr_config.set({"codec_pipeline.path": reader}): + with _ignore_sharding_combo_warning(): + arr2 = zarr.open_array(store=store, mode="r") + full = arr2[...] + partial = arr2[1:3, 2:7] # region read -- exercises the partial-decode branch + + np.testing.assert_array_equal(full, expected) + np.testing.assert_array_equal(partial, expected[1:3, 2:7]) diff --git a/tests/test_properties.py b/tests/test_properties.py new file mode 100644 index 0000000000..33888bfd4e --- /dev/null +++ b/tests/test_properties.py @@ -0,0 +1,450 @@ +import itertools +import json +import numbers +from collections.abc import Generator +from typing import Any + +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +import zarr +from zarr.core.buffer import default_buffer_prototype + +pytest.importorskip("hypothesis") + +import hypothesis.extra.numpy as npst +import hypothesis.strategies as st +from hypothesis import assume, given, settings + +from zarr.abc.store import Store +from zarr.core.common import ZARR_JSON, ZARRAY_JSON, ZATTRS_JSON +from zarr.core.metadata import ArrayV2Metadata, ArrayV3Metadata +from zarr.core.sync import sync +from zarr.testing.strategies import ( + array_metadata, + arrays, + basic_indices, + block_indices, + block_test_arrays, + complex_rectilinear_arrays, + numpy_arrays, + orthogonal_indices, + rectilinear_arrays, + simple_arrays, + stores, + zarr_formats, +) + + +@pytest.fixture(autouse=True) +def _enable_rectilinear_chunks() -> Generator[None, None, None]: + """Enable rectilinear chunks for all property tests since strategies may generate them.""" + with zarr.config.set({"array.rectilinear_chunks": True}): + yield + + +def deep_equal(a: Any, b: Any) -> bool: + """Deep equality check with handling of special cases for array metadata classes""" + if isinstance(a, (complex, np.complexfloating)) and isinstance( + b, (complex, np.complexfloating) + ): + a_real, a_imag = float(a.real), float(a.imag) + b_real, b_imag = float(b.real), float(b.imag) + if np.isnan(a_real) and np.isnan(b_real): + real_eq = True + else: + real_eq = a_real == b_real + if np.isnan(a_imag) and np.isnan(b_imag): + imag_eq = True + else: + imag_eq = a_imag == b_imag + return real_eq and imag_eq + + if isinstance(a, (float, np.floating)) and isinstance(b, (float, np.floating)): + if np.isnan(a) and np.isnan(b): + return True + return a == b + + if isinstance(a, np.datetime64) and isinstance(b, np.datetime64): + if np.isnat(a) and np.isnat(b): + return True + return a == b + + if isinstance(a, np.ndarray) and isinstance(b, np.ndarray): + if a.shape != b.shape: + return False + return all(itertools.starmap(deep_equal, zip(a.flat, b.flat, strict=False))) + + if isinstance(a, dict) and isinstance(b, dict): + if set(a.keys()) != set(b.keys()): + return False + return all(deep_equal(a[k], b[k]) for k in a) + + if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)): + if len(a) != len(b): + return False + return all(itertools.starmap(deep_equal, zip(a, b, strict=False))) + + return a == b + + +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@given(data=st.data()) +def test_array_roundtrip(data: st.DataObject) -> None: + nparray = data.draw(numpy_arrays()) + zarray = data.draw(arrays(arrays=st.just(nparray))) + assert_array_equal(nparray, zarray[:]) + + +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@given(array=arrays()) +def test_array_creates_implicit_groups(array): + path = array.path + ancestry = path.split("/")[:-1] + for i in range(len(ancestry)): + parent = "/".join(ancestry[: i + 1]) + if array.metadata.zarr_format == 2: + assert ( + sync(array.store.get(f"{parent}/.zgroup", prototype=default_buffer_prototype())) + is not None + ) + elif array.metadata.zarr_format == 3: + assert ( + sync(array.store.get(f"{parent}/zarr.json", prototype=default_buffer_prototype())) + is not None + ) + + +# this decorator removes timeout; not ideal but it should avoid intermittent CI failures + + +@settings(deadline=None) +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@given(data=st.data()) +async def test_basic_indexing(data: st.DataObject) -> None: + zarray = data.draw(st.one_of(simple_arrays(), rectilinear_arrays())) + nparray = zarray[:] + indexer = data.draw(basic_indices(shape=nparray.shape)) + + # sync get + actual = zarray[indexer] + assert_array_equal(nparray[indexer], actual) + + # async get + async_zarray = zarray._async_array + actual = await async_zarray.getitem(indexer) + assert_array_equal(nparray[indexer], actual) + + # sync set + new_data = data.draw(numpy_arrays(shapes=st.just(actual.shape), dtype=nparray.dtype)) + zarray[indexer] = new_data + nparray[indexer] = new_data + assert_array_equal(nparray, zarray[:]) + + # TODO test async setitem? + + +@settings(deadline=None) +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@given(data=st.data()) +async def test_basic_indexing_complex_rectilinear(data: st.DataObject) -> None: + nparray, zarray = data.draw(complex_rectilinear_arrays()) + indexer = data.draw(basic_indices(shape=nparray.shape)) + assert_array_equal(nparray[indexer], zarray[indexer]) + + +@given(data=st.data()) +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +async def test_oindex(data: st.DataObject) -> None: + # integer_array_indices can't handle 0-size dimensions. + zarray = data.draw( + st.one_of( + simple_arrays(shapes=npst.array_shapes(max_dims=4, min_side=1)), + rectilinear_arrays(shapes=npst.array_shapes(max_dims=4, min_side=1, max_side=20)), + ) + ) + nparray = zarray[:] + zindexer, npindexer = data.draw(orthogonal_indices(shape=nparray.shape)) + + # sync get + actual = zarray.oindex[zindexer] + assert_array_equal(nparray[npindexer], actual) + + # async get + async_zarray = zarray._async_array + actual = await async_zarray.oindex.getitem(zindexer) + assert_array_equal(nparray[npindexer], actual) + + # sync get + assume(zarray.shards is None) # GH2834 + for idxr in npindexer: + if isinstance(idxr, np.ndarray) and idxr.size != np.unique(idxr).size: + # behaviour of setitem with repeated indices is not guaranteed in practice + assume(False) + new_data = data.draw(numpy_arrays(shapes=st.just(actual.shape), dtype=nparray.dtype)) + nparray[npindexer] = new_data + zarray.oindex[zindexer] = new_data + assert_array_equal(nparray, zarray[:]) + + # note: async oindex setitem not yet implemented + + +@given(data=st.data()) +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +async def test_vindex(data: st.DataObject) -> None: + # integer_array_indices can't handle 0-size dimensions. + zarray = data.draw( + st.one_of( + simple_arrays(shapes=npst.array_shapes(max_dims=4, min_side=1)), + rectilinear_arrays(shapes=npst.array_shapes(max_dims=3, min_side=1, max_side=20)), + ) + ) + nparray = zarray[:] + indexer = data.draw( + npst.integer_array_indices( + shape=nparray.shape, result_shape=npst.array_shapes(min_side=1, max_dims=None) + ) + ) + + # sync get + actual = zarray.vindex[indexer] + assert_array_equal(nparray[indexer], actual) + + # async get + async_zarray = zarray._async_array + actual = await async_zarray.vindex.getitem(indexer) + assert_array_equal(nparray[indexer], actual) + + # sync set + # FIXME! + # when the indexer is such that a value gets overwritten multiple times, + # I think the output depends on chunking. + # new_data = data.draw(npst.arrays(shape=st.just(actual.shape), dtype=nparray.dtype)) + # nparray[indexer] = new_data + # zarray.vindex[indexer] = new_data + # assert_array_equal(nparray, zarray[:]) + + # note: async vindex setitem not yet implemented + + +@settings(deadline=None) +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@given(data=st.data()) +def test_mask_indexing(data: st.DataObject) -> None: + zarray = data.draw(st.one_of(simple_arrays(), rectilinear_arrays())) + nparray = zarray[:] + mask = data.draw(npst.arrays(dtype=np.bool_, shape=st.just(nparray.shape))) + + expected = nparray[mask] + + # sync get, via both the dedicated method and the vindex interface + assert_array_equal(expected, zarray.get_mask_selection(mask)) + assert_array_equal(expected, zarray.vindex[mask]) + + # sync set, via both interfaces + assume(zarray.shards is None) # GH2834 + new_data = data.draw(numpy_arrays(shapes=st.just(expected.shape), dtype=nparray.dtype)) + nparray[mask] = new_data + zarray.set_mask_selection(mask, new_data) + assert_array_equal(nparray, zarray[:]) + + zarray.vindex[mask] = new_data + assert_array_equal(nparray, zarray[:]) + + +@settings(deadline=None) +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@given(data=st.data()) +def test_block_indexing(data: st.DataObject) -> None: + # Block indexing addresses whole inner chunks. block_indices() builds its + # array-space oracle from cumulative chunk offsets, so it works for regular + # (uniform), rectilinear, and sharded grids alike; block_test_arrays draws + # across that matrix (rectilinear + sharded is unsupported and not drawn). + zarray, nparray = data.draw(block_test_arrays()) + + block_indexer, array_indexer = data.draw(block_indices(chunk_sizes=zarray.write_chunk_sizes)) + expected = nparray[array_indexer] + + # sync get, via both the .blocks interface and the dedicated method + assert_array_equal(expected, zarray.blocks[block_indexer]) + assert_array_equal(expected, zarray.get_block_selection(block_indexer)) + + # sync set, via both interfaces; sharded set is broken upstream (GH2834) + assume(zarray.shards is None) + new_data = data.draw(numpy_arrays(shapes=st.just(expected.shape), dtype=nparray.dtype)) + nparray[array_indexer] = new_data + zarray.blocks[block_indexer] = new_data + assert_array_equal(nparray, zarray[:]) + + zarray.set_block_selection(block_indexer, new_data) + assert_array_equal(nparray, zarray[:]) + + +@given(store=stores, meta=array_metadata()) # type: ignore[misc] +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +async def test_roundtrip_array_metadata_from_store( + store: Store, meta: ArrayV2Metadata | ArrayV3Metadata +) -> None: + """ + Verify that the I/O for metadata in a store are lossless. + + This test serializes an ArrayV2Metadata or ArrayV3Metadata object to a dict + of buffers via `to_buffer_dict`, writes each buffer to a store under keys + prefixed with "0/", and then reads them back. The test asserts that each + retrieved buffer exactly matches the original buffer. + """ + asdict = meta.to_buffer_dict(prototype=default_buffer_prototype()) + for key, expected in asdict.items(): + await store.set(f"0/{key}", expected) + actual = await store.get(f"0/{key}", prototype=default_buffer_prototype()) + assert actual == expected + + +@given(data=st.data(), zarr_format=zarr_formats) +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +def test_roundtrip_array_metadata_from_json(data: st.DataObject, zarr_format: int) -> None: + """ + Verify that JSON serialization and deserialization of metadata is lossless. + + For Zarr v2: + - The metadata is split into two JSON documents (one for array data and one + for attributes). The test merges the attributes back before deserialization. + For Zarr v3: + - All metadata is stored in a single JSON document. No manual merger is necessary. + + The test then converts both the original and round-tripped metadata objects + into dictionaries using `dataclasses.asdict` and uses a deep equality check + to verify that the roundtrip has preserved all fields (including special + cases like NaN, Infinity, complex numbers, and datetime values). + """ + metadata = data.draw(array_metadata(zarr_formats=st.just(zarr_format))) + buffer_dict = metadata.to_buffer_dict(prototype=default_buffer_prototype()) + + if zarr_format == 2: + zarray_dict = json.loads(buffer_dict[ZARRAY_JSON].to_bytes().decode()) + zattrs_dict = json.loads(buffer_dict[ZATTRS_JSON].to_bytes().decode()) + # zattrs and zarray are separate in v2, we have to add attributes back prior to `from_dict` + zarray_dict["attributes"] = zattrs_dict + metadata_roundtripped = ArrayV2Metadata.from_dict(zarray_dict) + else: + zarray_dict = json.loads(buffer_dict[ZARR_JSON].to_bytes().decode()) + metadata_roundtripped = ArrayV3Metadata.from_dict(zarray_dict) + + orig = metadata.to_dict() + rt = metadata_roundtripped.to_dict() + + assert deep_equal(orig, rt), f"Roundtrip mismatch:\nOriginal: {orig}\nRoundtripped: {rt}" + + +# @st.composite +# def advanced_indices(draw, *, shape): +# basic_idxr = draw( +# basic_indices( +# shape=shape, min_dims=len(shape), max_dims=len(shape), allow_ellipsis=False +# ).filter(lambda x: isinstance(x, tuple)) +# ) + +# int_idxr = draw( +# npst.integer_array_indices(shape=shape, result_shape=npst.array_shapes(max_dims=1)) +# ) +# args = tuple( +# st.sampled_from((l, r)) for l, r in zip_longest(basic_idxr, int_idxr, fillvalue=slice(None)) +# ) +# return draw(st.tuples(*args)) + + +# @given(st.data()) +# def test_roundtrip_object_array(data): +# nparray = data.draw(np_arrays) +# zarray = data.draw(arrays(arrays=st.just(nparray))) +# assert_array_equal(nparray, zarray[:]) + + +def serialized_complex_float_is_valid( + serialized: tuple[numbers.Real | str, numbers.Real | str], +) -> bool: + """ + Validate that the serialized representation of a complex float conforms to the spec. + + The specification requires that a serialized complex float must be either: + - A JSON number, or + - One of the strings "NaN", "Infinity", or "-Infinity". + + Args: + serialized: The value produced by JSON serialization for a complex floating point number. + + Returns: + bool: True if the serialized value is valid according to the spec, False otherwise. + """ + return ( + isinstance(serialized, tuple) + and len(serialized) == 2 + and all(serialized_float_is_valid(x) for x in serialized) + ) + + +def serialized_float_is_valid(serialized: numbers.Real | str) -> bool: + """ + Validate that the serialized representation of a float conforms to the spec. + + The specification requires that a serialized float must be either: + - A JSON number, or + - One of the strings "NaN", "Infinity", or "-Infinity". + + Args: + serialized: The value produced by JSON serialization for a floating point number. + + Returns: + bool: True if the serialized value is valid according to the spec, False otherwise. + """ + if isinstance(serialized, numbers.Real): + return True + return serialized in ("NaN", "Infinity", "-Infinity") + + +@given(meta=array_metadata()) # type: ignore[misc] +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +def test_array_metadata_meets_spec(meta: ArrayV2Metadata | ArrayV3Metadata) -> None: + """ + Validate that the array metadata produced by the library conforms to the relevant spec (V2 vs V3). + + For ArrayV2Metadata: + - Ensures that 'zarr_format' is 2. + - Verifies that 'filters' is either None or a tuple (and not an empty tuple). + For ArrayV3Metadata: + - Ensures that 'zarr_format' is 3. + + For both versions: + - If the dtype is a floating point of some kind, verifies of fill values: + * NaN is serialized as the string "NaN" + * Positive Infinity is serialized as the string "Infinity" + * Negative Infinity is serialized as the string "-Infinity" + * Other fill values are preserved as-is. + - If the dtype is a complex number of some kind, verifies that each component of the fill + value (real and imaginary) satisfies the serialization rules for floating point numbers. + - If the dtype is a datetime of some kind, verifies that `NaT` values are serialized as "NaT". + + Note: + This test validates spec-compliance for array metadata serialization. + It is a work-in-progress and should be expanded as further edge cases are identified. + """ + asdict_dict = meta.to_dict() + + # version-specific validations + if isinstance(meta, ArrayV2Metadata): + assert asdict_dict["filters"] != () + assert asdict_dict["filters"] is None or isinstance(asdict_dict["filters"], tuple) + assert asdict_dict["zarr_format"] == 2 + else: + assert asdict_dict["zarr_format"] == 3 + + # version-agnostic validations + dtype_native = meta.dtype.to_native_dtype() + if dtype_native.kind == "f": + assert serialized_float_is_valid(asdict_dict["fill_value"]) + elif dtype_native.kind == "c": + # fill_value should be a two-element array [real, imag]. + assert serialized_complex_float_is_valid(asdict_dict["fill_value"]) + elif dtype_native.kind in ("M", "m") and np.isnat(meta.fill_value): + assert asdict_dict["fill_value"] == -9223372036854775808 diff --git a/tests/test_regression/__init__.py b/tests/test_regression/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_regression/scripts/__init__.py b/tests/test_regression/scripts/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_regression/scripts/v2.18.py b/tests/test_regression/scripts/v2.18.py new file mode 100644 index 0000000000..4c730b9c79 --- /dev/null +++ b/tests/test_regression/scripts/v2.18.py @@ -0,0 +1,81 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "zarr==2.18", +# "numcodecs==0.15" +# ] +# /// + +import argparse + +import zarr +from zarr._storage.store import BaseStore + + +def copy_group( + *, node: zarr.hierarchy.Group, store: zarr.storage.BaseStore, path: str, overwrite: bool +) -> zarr.hierarchy.Group: + result = zarr.group(store=store, path=path, overwrite=overwrite) + result.attrs.put(node.attrs.asdict()) + for key, child in node.items(): + child_path = f"{path}/{key}" + if isinstance(child, zarr.hierarchy.Group): + copy_group(node=child, store=store, path=child_path, overwrite=overwrite) + elif isinstance(child, zarr.core.Array): + copy_array(node=child, store=store, overwrite=overwrite, path=child_path) + return result + + +def copy_array( + *, node: zarr.core.Array, store: BaseStore, path: str, overwrite: bool +) -> zarr.core.Array: + result = zarr.create( + shape=node.shape, + dtype=node.dtype, + fill_value=node.fill_value, + chunks=node.chunks, + compressor=node.compressor, + filters=node.filters, + order=node.order, + dimension_separator=node._dimension_separator, + store=store, + path=path, + overwrite=overwrite, + ) + result.attrs.put(node.attrs.asdict()) + result[:] = node[:] + return result + + +def copy_node( + node: zarr.hierarchy.Group | zarr.core.Array, store: BaseStore, path: str, overwrite: bool +) -> zarr.hierarchy.Group | zarr.core.Array: + if isinstance(node, zarr.hierarchy.Group): + return copy_group(node=node, store=store, path=path, overwrite=overwrite) + elif isinstance(node, zarr.core.Array): + return copy_array(node=node, store=store, path=path, overwrite=overwrite) + else: + raise TypeError(f"Unexpected node type: {type(node)}") # pragma: no cover + + +def cli() -> None: + parser = argparse.ArgumentParser( + description="Copy a zarr hierarchy from one location to another" + ) + parser.add_argument("source", type=str, help="Path to the source zarr hierarchy") + parser.add_argument("destination", type=str, help="Path to the destination zarr hierarchy") + args = parser.parse_args() + + src, dst = args.source, args.destination + root_src = zarr.open(src, mode="r") + result = copy_node(node=root_src, store=zarr.NestedDirectoryStore(dst), path="", overwrite=True) + + print(f"successfully created {result} at {dst}") + + +def main() -> None: + cli() + + +if __name__ == "__main__": + main() diff --git a/tests/test_regression/scripts/v3.0.8.py b/tests/test_regression/scripts/v3.0.8.py new file mode 100644 index 0000000000..5a055665e8 --- /dev/null +++ b/tests/test_regression/scripts/v3.0.8.py @@ -0,0 +1,69 @@ +# /// script +# requires-python = "==3.12" +# dependencies = [ +# "zarr==3.0.8", +# "numcodecs==0.16.3" +# ] +# /// + + +import argparse + +import zarr +from zarr.abc.store import Store + +def copy_group( + *, node: zarr.Group, store: Store, path: str, overwrite: bool +) -> zarr.Group: + result = zarr.create_group( + store=store, + path=path, + overwrite=overwrite, + attributes=node.attrs.asdict(), + zarr_format=node.metadata.zarr_format) + for key, child in node.members(): + child_path = f"{path}/{key}" + if isinstance(child, zarr.Group): + copy_group(node=child, store=store, path=child_path, overwrite=overwrite) + else: + copy_array(node=child, store=store, overwrite=overwrite, path=child_path) + return result + + +def copy_array( + *, node: zarr.Array, store: Store, path: str, overwrite: bool +) -> zarr.Array: + result = zarr.from_array(store, name=path, data=node, write_data=True) + return result + + +def copy_node( + node: zarr.Group | zarr.Array, store: Store, path: str, overwrite: bool +) -> zarr.Group | zarr.Array: + if isinstance(node, zarr.Group): + return copy_group(node=node, store=store, path=path, overwrite=overwrite) + else: + return copy_array(node=node, store=store, path=path, overwrite=overwrite) + + +def cli() -> None: + parser = argparse.ArgumentParser( + description="Copy a zarr hierarchy from one location to another" + ) + parser.add_argument("source", type=str, help="Path to the source zarr hierarchy") + parser.add_argument("destination", type=str, help="Path to the destination zarr hierarchy") + args = parser.parse_args() + + src, dst = args.source, args.destination + root_src = zarr.open(src, mode="r") + result = copy_node(node=root_src, store=dst, path="", overwrite=True) + + print(f"successfully created {result} at {dst}") + + +def main() -> None: + cli() + + +if __name__ == "__main__": + main() diff --git a/tests/test_regression/test_v2_dtype_regression.py b/tests/test_regression/test_v2_dtype_regression.py new file mode 100644 index 0000000000..faba087e32 --- /dev/null +++ b/tests/test_regression/test_v2_dtype_regression.py @@ -0,0 +1,249 @@ +import subprocess +import sys +from dataclasses import dataclass +from itertools import product +from pathlib import Path +from typing import TYPE_CHECKING, Literal + +import numpy as np +import pytest +from numcodecs import LZ4, LZMA, Blosc, GZip, VLenBytes, VLenUTF8, Zstd + +import zarr +import zarr.abc +import zarr.abc.codec +import zarr.codecs as zarrcodecs +from zarr.abc.numcodec import Numcodec +from zarr.core.chunk_key_encodings import V2ChunkKeyEncoding +from zarr.core.dtype.npy.bytes import VariableLengthBytes +from zarr.core.dtype.npy.string import VariableLengthUTF8 +from zarr.storage import LocalStore +from zarr.types import ArrayV2, ArrayV3 + +if TYPE_CHECKING: + from zarr.core.dtype import ZDTypeLike + +ZarrPythonVersion = Literal["2.18", "3.0.8"] + + +def runner_installed() -> bool: + """ + Check if a PEP-723 compliant python script runner is installed. + """ + try: + subprocess.check_output(["uv", "--version"]) + return True # noqa: TRY300 + except FileNotFoundError: + return False + + +@dataclass(kw_only=True) +class ArrayParams: + values: np.ndarray[tuple[int], np.dtype[np.generic]] + fill_value: np.generic | str | int | bytes + filters: tuple[Numcodec, ...] = () + serializer: str | None = None + compressor: Numcodec + + +basic_codecs: tuple[Numcodec, ...] = GZip(), Blosc(), LZ4(), LZMA(), Zstd() +basic_dtypes = "|b", ">i2", ">i4", ">f4", ">f8", "c8", "c16", "M8[10us]", "m8[4ps]" +string_dtypes = "U4" +bytes_dtypes = ">S1", "V10", " ArrayV2: + """ + Writes a zarr array to a temporary directory based on the provided ArrayParams. The array is + returned. + """ + dest = tmp_path / "in" + store = LocalStore(dest) + array_params: ArrayParams = request.param + compressor = array_params.compressor + chunk_key_encoding = V2ChunkKeyEncoding(separator="/") + dtype: ZDTypeLike + if array_params.values.dtype == np.dtype("|O") and array_params.serializer == "vlen-utf8": + dtype = VariableLengthUTF8() # type: ignore[assignment] + filters = array_params.filters + (VLenUTF8(),) + elif array_params.values.dtype == np.dtype("|O") and array_params.serializer == "vlen-bytes": + dtype = VariableLengthBytes() + filters = array_params.filters + (VLenBytes(),) + else: + dtype = array_params.values.dtype + filters = array_params.filters + z = zarr.create_array( + store, + shape=array_params.values.shape, + dtype=dtype, + chunks=array_params.values.shape, + compressors=compressor, + filters=filters, + fill_value=array_params.fill_value, + order="C", + chunk_key_encoding=chunk_key_encoding, + write_data=True, + zarr_format=2, + ) + z[:] = array_params.values + return z + + +@pytest.fixture +def source_array_v3(tmp_path: Path, request: pytest.FixtureRequest) -> ArrayV3: + """ + Writes a zarr array to a temporary directory based on the provided ArrayParams. The array is + returned. + """ + dest = tmp_path / "in" + store = LocalStore(dest) + array_params: ArrayParams = request.param + chunk_key_encoding = V2ChunkKeyEncoding(separator="/") + dtype: ZDTypeLike + serializer: Literal["auto"] | zarr.abc.codec.Codec + if array_params.values.dtype == np.dtype("|O") and array_params.serializer == "vlen-utf8": + dtype = VariableLengthUTF8() # type: ignore[assignment] + serializer = zarrcodecs.VLenUTF8Codec() + elif array_params.values.dtype == np.dtype("|O") and array_params.serializer == "vlen-bytes": + dtype = VariableLengthBytes() + serializer = zarrcodecs.VLenBytesCodec() + else: + dtype = array_params.values.dtype + serializer = "auto" + if array_params.compressor == GZip(): + compressor = zarrcodecs.GzipCodec() + else: + msg = ( + "This test is only compatible with gzip compression at the moment, because the author" + "did not want to implement a complete abstraction layer for v2 and v3 codecs in this test." + ) + raise ValueError(msg) + z = zarr.create_array( + store, + shape=array_params.values.shape, + dtype=dtype, + chunks=array_params.values.shape, + compressors=compressor, + filters=array_params.filters, + serializer=serializer, + fill_value=array_params.fill_value, + chunk_key_encoding=chunk_key_encoding, + write_data=True, + zarr_format=3, + ) + z[:] = array_params.values + return z + + +# TODO: make this dynamic based on the installed scripts +script_paths = [Path(__file__).resolve().parent / "scripts" / "v2.18.py"] + + +@pytest.mark.skipif( + sys.platform == "darwin" and sys.version_info >= (3, 14), + reason="Numcodecs pinned to 0.15 does not build on newer macos installations with newer python versions: see discussion https://github.com/zarr-developers/zarr-python/pull/3564#issuecomment-4081145034", +) +@pytest.mark.skipif(not runner_installed(), reason="no python script runner installed") +@pytest.mark.parametrize( + "source_array_v2", array_cases_v2_18, indirect=True, ids=tuple(map(str, array_cases_v2_18)) +) +@pytest.mark.parametrize("script_path", script_paths) +def test_roundtrip_v2(source_array_v2: ArrayV2, tmp_path: Path, script_path: Path) -> None: + out_path = tmp_path / "out" + copy_op = subprocess.run( + [ + "uv", + "run", + str(script_path), + str(source_array_v2.store).removeprefix("file://"), + str(out_path), + ], + capture_output=True, + text=True, + check=False, + ) + assert copy_op.returncode == 0, f"stdout {copy_op.stdout}\n stderr{copy_op.stderr}" + out_array = zarr.open_array(store=out_path, mode="r", zarr_format=2) + assert source_array_v2.metadata.to_dict() == out_array.metadata.to_dict() + assert np.array_equal(source_array_v2[:], out_array[:]) + + +@pytest.mark.skipif(not runner_installed(), reason="no python script runner installed") +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +@pytest.mark.parametrize( + "source_array_v3", array_cases_v3_08, indirect=True, ids=tuple(map(str, array_cases_v3_08)) +) +def test_roundtrip_v3(source_array_v3: ArrayV3, tmp_path: Path) -> None: + script_path = Path(__file__).resolve().parent / "scripts" / "v3.0.8.py" + out_path = tmp_path / "out" + copy_op = subprocess.run( + [ + "uv", + "run", + str(script_path), + str(source_array_v3.store).removeprefix("file://"), + str(out_path), + ], + capture_output=True, + text=True, + check=False, + ) + assert copy_op.returncode == 0 + out_array = zarr.open_array(store=out_path, mode="r", zarr_format=3) + assert source_array_v3.metadata.to_dict() == out_array.metadata.to_dict() + assert np.array_equal(source_array_v3[:], out_array[:]) diff --git a/tests/test_store/__init__.py b/tests/test_store/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/test_store/test_core.py b/tests/test_store/test_core.py new file mode 100644 index 0000000000..7ba4344810 --- /dev/null +++ b/tests/test_store/test_core.py @@ -0,0 +1,417 @@ +import tempfile +from collections.abc import Awaitable, Callable, Generator +from pathlib import Path +from typing import Any, Literal + +import pytest +from packaging.version import parse as parse_version + +import zarr +from zarr import Group +from zarr.abc.store import Store +from zarr.core.buffer import cpu +from zarr.core.common import ZARR_JSON, AccessModeLiteral, ZarrFormat +from zarr.storage import FsspecStore, LocalStore, MemoryStore, StoreLike, StorePath, ZipStore +from zarr.storage._common import ( + _contains_node_v3, + contains_array, + contains_group, + make_store, + make_store_path, +) +from zarr.storage._utils import ( + _join_paths, + _normalize_path_keys, + _normalize_paths, + _relativize_path, + normalize_path, +) + +# contains_array and contains_group share this signature. +_ContainsFunc = Callable[[StorePath, ZarrFormat], Awaitable[bool]] + + +@pytest.fixture( + params=["none", "temp_dir_str", "temp_dir_path", "store_path", "memory_store", "dict"] +) +def store_like( + request: pytest.FixtureRequest, +) -> Generator[str | Path | StorePath | MemoryStore | dict[Any, Any] | None, None, None]: + if request.param == "none": + yield None + elif request.param == "temp_dir_str": + with tempfile.TemporaryDirectory() as temp_dir: + yield temp_dir + elif request.param == "temp_dir_path": + with tempfile.TemporaryDirectory() as temp_dir: + yield Path(temp_dir) + elif request.param == "store_path": + yield StorePath(store=MemoryStore(store_dict={}), path="/") + elif request.param == "memory_store": + yield MemoryStore(store_dict={}) + elif request.param == "dict": + yield {} + + +@pytest.mark.parametrize("path", ["foo", "foo/bar"]) +@pytest.mark.parametrize("write_group", [True, False]) +@pytest.mark.parametrize("zarr_format", [2, 3]) +async def test_contains_group( + local_store: LocalStore, path: str, write_group: bool, zarr_format: ZarrFormat +) -> None: + """ + Test that the contains_group method correctly reports the existence of a group. + """ + root = Group.from_store(store=local_store, zarr_format=zarr_format) + if write_group: + root.create_group(path) + store_path = StorePath(local_store, path=path) + assert await contains_group(store_path, zarr_format=zarr_format) == write_group + + +@pytest.mark.parametrize("path", ["foo", "foo/bar"]) +@pytest.mark.parametrize("write_array", [True, False]) +@pytest.mark.parametrize("zarr_format", [2, 3]) +async def test_contains_array( + local_store: LocalStore, path: str, write_array: bool, zarr_format: ZarrFormat +) -> None: + """ + Test that the contains array method correctly reports the existence of an array. + """ + root = Group.from_store(store=local_store, zarr_format=zarr_format) + if write_array: + root.create_array(path, shape=(100,), chunks=(10,), dtype="i4") + store_path = StorePath(local_store, path=path) + assert await contains_array(store_path, zarr_format=zarr_format) == write_array + + +@pytest.mark.parametrize("func", [contains_array, contains_group]) +async def test_contains_invalid_format_raises(local_store: LocalStore, func: _ContainsFunc) -> None: + """ + Test contains_group and contains_array raise errors for invalid zarr_formats + """ + store_path = StorePath(local_store) + with pytest.raises(ValueError, match="Invalid zarr_format provided. Got 3.0, expected 2 or 3"): + assert await func(store_path, "3.0") # type: ignore[arg-type] + + +async def _write_zarr_json(store_path: StorePath, data: bytes) -> None: + """Write raw bytes to the v3 metadata key under `store_path`.""" + await (store_path / ZARR_JSON).set(cpu.Buffer.from_bytes(data)) + + +@pytest.mark.parametrize("func", [contains_array, contains_group]) +async def test_contains_malformed_json_returns_false( + local_store: LocalStore, func: _ContainsFunc +) -> None: + """A v3 metadata document that is not valid JSON reads as 'not present'.""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b"{not valid json") + assert await func(store_path, 3) is False + + +@pytest.mark.parametrize("func", [contains_array, contains_group]) +async def test_contains_non_object_json_returns_false( + local_store: LocalStore, func: _ContainsFunc +) -> None: + """A v3 metadata document that is valid JSON but not an object reads as 'not present'.""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b"[1, 2, 3]") + assert await func(store_path, 3) is False + + +@pytest.mark.parametrize("func", [contains_array, contains_group]) +async def test_contains_missing_node_type_returns_false( + local_store: LocalStore, func: _ContainsFunc +) -> None: + """A v3 metadata document with no 'node_type' key reads as 'not present'.""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b'{"zarr_format": 3}') + assert await func(store_path, 3) is False + + +@pytest.mark.parametrize("func", [contains_array, contains_group]) +async def test_contains_non_utf8_bytes_returns_false( + local_store: LocalStore, func: _ContainsFunc +) -> None: + """A v3 metadata document that is not valid UTF-8 reads as 'not present' (not an error).""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b"\x80\x81\x82\x83") + assert await func(store_path, 3) is False + + +async def test_contains_node_v3_malformed_json_returns_nothing(local_store: LocalStore) -> None: + """`_contains_node_v3` returns 'nothing' when the document is not valid JSON.""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b"{not valid json") + assert await _contains_node_v3(store_path) == "nothing" + + +async def test_contains_node_v3_non_object_json_returns_nothing(local_store: LocalStore) -> None: + """`_contains_node_v3` returns 'nothing' when the document is not a JSON object.""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b"[1, 2, 3]") + assert await _contains_node_v3(store_path) == "nothing" + + +async def test_contains_node_v3_missing_node_type_returns_nothing(local_store: LocalStore) -> None: + """`_contains_node_v3` returns 'nothing' when the document lacks a 'node_type' key.""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b'{"zarr_format": 3}') + assert await _contains_node_v3(store_path) == "nothing" + + +async def test_contains_node_v3_non_utf8_bytes_returns_nothing(local_store: LocalStore) -> None: + """`_contains_node_v3` returns 'nothing' when the document is not valid UTF-8.""" + store_path = StorePath(local_store, path="foo") + await _write_zarr_json(store_path, b"\x80\x81\x82\x83") + assert await _contains_node_v3(store_path) == "nothing" + + +@pytest.mark.parametrize("path", [None, "", "bar"]) +async def test_make_store_path_none(path: str) -> None: + """ + Test that creating a store_path with None creates a memorystore + """ + store_path = await make_store_path(None, path=path) + assert isinstance(store_path.store, MemoryStore) + assert store_path.path == normalize_path(path) + + +@pytest.mark.parametrize("path", [None, "", "bar"]) +@pytest.mark.parametrize("store_type", [str, Path]) +@pytest.mark.parametrize("mode", ["r", "w"]) +async def test_make_store_path_local( + tmp_path: Path, + store_type: type[str] | type[Path] | type[LocalStore], + path: str, + mode: AccessModeLiteral, +) -> None: + """ + Test the various ways of invoking make_store_path that create a LocalStore + """ + store_like = store_type(str(tmp_path)) + store_path = await make_store_path(store_like, path=path, mode=mode) + assert isinstance(store_path.store, LocalStore) + assert Path(store_path.store.root) == Path(tmp_path) + assert store_path.path == normalize_path(path) + assert store_path.read_only == (mode == "r") + + +@pytest.mark.parametrize("path", [None, "", "bar"]) +@pytest.mark.parametrize("mode", ["r", "w"]) +async def test_make_store_path_store_path( + tmp_path: Path, path: str, mode: AccessModeLiteral +) -> None: + """ + Test invoking make_store_path when the input is another store_path. In particular we want to ensure + that a new path is handled correctly. + """ + ro = mode == "r" + store_like = await StorePath.open( + LocalStore(str(tmp_path), read_only=ro), path="root", mode=mode + ) + store_path = await make_store_path(store_like, path=path, mode=mode) + assert isinstance(store_path.store, LocalStore) + assert Path(store_path.store.root) == tmp_path + path_normalized = normalize_path(path) + assert store_path.path == (store_like / path_normalized).path + assert store_path.read_only == ro + + +@pytest.mark.parametrize("modes", [(True, "w"), (False, "x")]) +async def test_store_path_invalid_mode_raises( + tmp_path: Path, modes: tuple[bool, Literal["w", "x"]] +) -> None: + """ + Test that ValueErrors are raise for invalid mode. + """ + with pytest.raises(ValueError): + await StorePath.open(LocalStore(str(tmp_path), read_only=modes[0]), path="", mode=modes[1]) # type: ignore[arg-type] + + +async def test_make_store_path_invalid() -> None: + """ + Test that invalid types raise TypeError + """ + with pytest.raises(TypeError, match="Unsupported type for store_like: 'int'"): + await make_store_path(1) + + +async def test_make_store_path_fsspec() -> None: + pytest.importorskip("fsspec") + pytest.importorskip("requests") + pytest.importorskip("aiohttp") + store_path = await make_store_path("http://foo.com/bar") + assert isinstance(store_path.store, FsspecStore) + + +async def test_make_store_path_storage_options_raises(store_like: StoreLike) -> None: + with pytest.raises(TypeError, match="storage_options"): + await make_store_path(store_like, storage_options={"foo": "bar"}) + + +# universal-pathlib 0.2.x emits this from its own subclass registry when a local UPath is built. +@pytest.mark.filterwarnings( + "ignore:Detected a customized `__new__` method in subclass:DeprecationWarning" +) +@pytest.mark.parametrize( + ("url", "expected"), + [ + ("memory://bucket/foo.zarr", FsspecStore), + ("s3://bucket/foo.zarr", FsspecStore), + ("file://{tmp}/foo.zarr", LocalStore), + ("{tmp}/foo.zarr", LocalStore), + ], +) +async def test_make_store_upath(url: str, expected: type[Store], tmp_path: Path) -> None: + """ + A remote UPath becomes an FsspecStore, and a local one becomes a LocalStore, so that + UPath("/data") and Path("/data") agree. See https://github.com/zarr-developers/zarr-python/issues/4244. + """ + upath = pytest.importorskip("upath") + fsspec = pytest.importorskip("fsspec") + if url.startswith("s3://"): + pytest.importorskip("s3fs") + if url.startswith("memory://") and parse_version(fsspec.__version__) < parse_version( + "2024.12.0" + ): + # MemoryFileSystem is synchronous, so it can only be used once fsspec is new enough to + # supply AsyncFileSystemWrapper. + pytest.skip("No AsyncFileSystemWrapper") + store = await make_store(upath.UPath(url.format(tmp=tmp_path))) + assert isinstance(store, expected) + if isinstance(store, LocalStore): + # The local branch rebuilds the root from the UPath, so a mangled path would still + # produce a LocalStore. Pin the root down too, since "file://{tmp}" has no leading + # slash on Windows. + assert store.root == tmp_path / "foo.zarr" + + +async def test_make_store_upath_storage_options_raises() -> None: + """A UPath carries its own storage options, so a separate mapping is ambiguous.""" + upath = pytest.importorskip("upath") + with pytest.raises(TypeError, match="storage_options"): + await make_store(upath.UPath("memory://bucket/foo.zarr"), storage_options={"foo": "bar"}) + + +async def test_unsupported() -> None: + with pytest.raises(TypeError, match="Unsupported type for store_like: 'int'"): + await make_store_path(1) + + +@pytest.mark.parametrize( + "path", + [ + "/foo/bar", + "//foo/bar", + "foo///bar", + "foo/bar///", + Path("foo/bar"), + b"foo/bar", + ], +) +def test_normalize_path_valid(path: str | bytes | Path) -> None: + assert normalize_path(path) == "foo/bar" + + +def test_normalize_path_upath() -> None: + upath = pytest.importorskip("upath") + assert normalize_path(upath.UPath("foo/bar", protocol="memory")) == "memory:/foo/bar" + + +def test_normalize_path_none() -> None: + assert normalize_path(None) == "" + + +@pytest.mark.parametrize("path", [".", ".."]) +def test_normalize_path_invalid(path: str) -> None: + with pytest.raises(ValueError, match="is invalid because its string representation contains"): + normalize_path(path) + + +@pytest.mark.parametrize("paths", [("", "foo"), ("foo", "bar")]) +def test_join_paths(paths: tuple[str, str]) -> None: + """ + Test that _join_paths joins paths in a way that is robust to an empty string + """ + observed = _join_paths(paths) + if paths[0] == "": + assert observed == paths[1] + else: + assert observed == "/".join(paths) + + +class TestNormalizePaths: + @staticmethod + def test_valid() -> None: + """ + Test that path normalization works as expected + """ + paths = ["a", "b", "c", "d", "", "//a///b//"] + assert _normalize_paths(paths) == tuple(normalize_path(p) for p in paths) + + @staticmethod + @pytest.mark.parametrize("paths", [("", "/"), ("///a", "a")]) + def test_invalid(paths: tuple[str, str]) -> None: + """ + Test that name collisions after normalization raise a ``ValueError`` + """ + msg = ( + f"After normalization, the value '{paths[1]}' collides with '{paths[0]}'. " + f"Both '{paths[1]}' and '{paths[0]}' normalize to the same value: '{normalize_path(paths[0])}'. " + f"You should use either '{paths[1]}' or '{paths[0]}', but not both." + ) + with pytest.raises(ValueError, match=msg): + _normalize_paths(paths) + + +def test_normalize_path_keys() -> None: + """ + Test that ``_normalize_path_keys`` just applies the normalize_path function to each key of its + input + """ + data = {"a": 10, "//b": 10} + assert _normalize_path_keys(data) == {normalize_path(k): v for k, v in data.items()} + + +@pytest.mark.parametrize( + ("path", "prefix", "expected"), + [ + ("a", "", "a"), + ("a/b/c", "a/b", "c"), + ("a/b/c", "a", "b/c"), + ], +) +def test_relativize_path_valid(path: str, prefix: str, expected: str) -> None: + """ + Test the normal behavior of the _relativize_path function. Prefixes should be removed from the + path argument. + """ + assert _relativize_path(path=path, prefix=prefix) == expected + + +def test_relativize_path_invalid() -> None: + path = "a/b/c" + prefix = "b" + msg = f"The first component of {path} does not start with {prefix}." + with pytest.raises(ValueError, match=msg): + _relativize_path(path="a/b/c", prefix="b") + + +def test_different_open_mode(tmp_path: Path) -> None: + # Test with a store that implements .with_read_only() + store = MemoryStore() + zarr.create((100,), store=store, zarr_format=2, path="a") + arr = zarr.open_array(store=store, path="a", zarr_format=2, mode="r") + assert arr.store.read_only + + # Test with a store that doesn't implement .with_read_only() + zarr_path = tmp_path / "foo.zarr" + zip_store = ZipStore(zarr_path, mode="w") + zarr.create((100,), store=zip_store, zarr_format=2, path="a") + with pytest.raises( + ValueError, + match="Store is not read-only but mode is 'r'. Unable to create a read-only copy of the store. Please use a read-only store or a storage class that implements .with_read_only().", + ): + zarr.open_array(store=zip_store, path="a", zarr_format=2, mode="r") diff --git a/tests/test_store/test_fsspec.py b/tests/test_store/test_fsspec.py new file mode 100644 index 0000000000..bb03970d5b --- /dev/null +++ b/tests/test_store/test_fsspec.py @@ -0,0 +1,703 @@ +from __future__ import annotations + +import json +import re +import warnings +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest +from packaging.version import parse as parse_version + +import zarr.api.asynchronous +from zarr import Array +from zarr.abc.store import OffsetByteRequest +from zarr.core.buffer import Buffer, cpu, default_buffer_prototype +from zarr.core.sync import _collect_aiterator, sync +from zarr.errors import ZarrUserWarning +from zarr.storage import FsspecStore +from zarr.storage._common import make_store +from zarr.storage._fsspec import _make_async +from zarr.testing.store import StoreTests + +if TYPE_CHECKING: + import pathlib + from collections.abc import Generator + from pathlib import Path + + import botocore.client + import s3fs + + from zarr.core.common import JSON + + +# Warning filter due to https://github.com/boto/boto3/issues/3889 +pytestmark = [ + pytest.mark.filterwarnings( + re.escape("ignore:datetime.datetime.utcnow() is deprecated:DeprecationWarning") + ), + # FsspecStore.from_url() and from_mapper() now close the aiohttp session on store.close(). + # This filter covers stores that are GC'd without an explicit close() call, and any + # residual sessions from aiobotocore's ClientCreatorContext (a separate upstream issue). + pytest.mark.filterwarnings("ignore:Unclosed client session:ResourceWarning"), + pytest.mark.filterwarnings( + "ignore:coroutine 'ClientCreatorContext.__aexit__' was never awaited:RuntimeWarning" + ), + # s3fs finalizers can fail when sessions are garbage collected without being entered + pytest.mark.filterwarnings( + "ignore:Exception ignored in.*finalize object.*:pytest.PytestUnraisableExceptionWarning" + ), +] + +fsspec = pytest.importorskip("fsspec") +s3fs = pytest.importorskip("s3fs") +requests = pytest.importorskip("requests") +# Skip this module entirely when moto is absent; the server itself comes from the shared +# `moto_server` fixture in tests/conftest.py. +pytest.importorskip("moto") +botocore = pytest.importorskip("botocore") + +# ### amended from s3fs ### # +test_bucket_name = "test" +secure_bucket_name = "test-secure" + + +@pytest.fixture +def endpoint_url(moto_server: str) -> str: + """Endpoint of the shared session-scoped moto server (see tests/conftest.py). + + A fixture rather than a module-level constant because the server binds an ephemeral + port, so the endpoint is only known once the server is running.""" + return moto_server + + +def get_boto3_client(endpoint_url: str) -> botocore.client.BaseClient: + # NB: we use the sync botocore client for setup + session = botocore.session.Session() + + # Prevent IllegalLocationConstraintException by explicitly setting region to + # "us-east-1", which does not require configuring LocationConstraint during + # bucket creation. (It is, in fact, forbidden for that region.) Necessary + # in the face of "ambient" AWS configuration in a development environment + # where the default region might be configured differently. + return session.create_client("s3", endpoint_url=endpoint_url, region_name="us-east-1") + + +@pytest.fixture(autouse=True) +def s3(endpoint_url: str) -> Generator[s3fs.S3FileSystem, None, None]: + """ + Quoting Martin Durant: + pytest-asyncio creates a new event loop for each async test. + When an async-mode s3fs instance is made from async, it will be assigned to the loop from + which it is made. That means that if you use s3fs again from a subsequent test, + you will have the same identical instance, but be running on a different loop - which fails. + + For the rest: it's very convenient to clean up the state of the store between tests, + make sure we start off blank each time. + + https://github.com/zarr-developers/zarr-python/pull/1785#discussion_r1634856207 + """ + client = get_boto3_client(endpoint_url) + client.create_bucket(Bucket=test_bucket_name, ACL="public-read") + s3fs.S3FileSystem.clear_instance_cache() + s3 = s3fs.S3FileSystem( + anon=False, + client_kwargs={"endpoint_url": endpoint_url}, + # Prevent "AssertionError: Session was never entered" from aiobotocore + # at end of test execution. Using clear_instance_cache is insufficient, + # although still necessary. + skip_instance_cache=True, + ) + session = sync(s3.set_session()) + s3.invalidate_cache() + yield s3 + requests.post(f"{endpoint_url}/moto-api/reset") + client.close() + sync(session.close()) + + +# ### end from s3fs ### # + + +async def test_basic(endpoint_url: str) -> None: + store = FsspecStore.from_url( + f"s3://{test_bucket_name}/foo/spam/", + storage_options={"endpoint_url": endpoint_url, "anon": False}, + ) + assert store.fs.asynchronous + assert store.path == f"{test_bucket_name}/foo/spam" + assert await _collect_aiterator(store.list()) == () + assert not await store.exists("foo") + data = b"hello" + await store.set("foo", cpu.Buffer.from_bytes(data)) + assert await store.exists("foo") + buf = await store.get("foo", prototype=default_buffer_prototype()) + assert buf is not None + assert buf.to_bytes() == data + out = await store.get_partial_values( + prototype=default_buffer_prototype(), key_ranges=[("foo", OffsetByteRequest(1))] + ) + assert out[0] is not None + assert out[0].to_bytes() == data[1:] + + +class TestFsspecStoreS3(StoreTests[FsspecStore, cpu.Buffer]): + store_cls = FsspecStore + buffer_cls = cpu.Buffer + + @pytest.fixture + def store_kwargs(self, endpoint_url: str) -> dict[str, str | bool]: + try: + from fsspec import url_to_fs + except ImportError: + # before fsspec==2024.3.1 + from fsspec.core import url_to_fs + fs, path = url_to_fs( + f"s3://{test_bucket_name}", endpoint_url=endpoint_url, anon=False, asynchronous=True + ) + return {"fs": fs, "path": path} + + @pytest.fixture + async def store(self, store_kwargs: dict[str, Any]) -> FsspecStore: + return self.store_cls(**store_kwargs) + + async def get(self, store: FsspecStore, key: str) -> Buffer: + # make a new, synchronous instance of the filesystem because this test is run in sync code + new_fs = fsspec.filesystem( + "s3", endpoint_url=store.fs.endpoint_url, anon=store.fs.anon, asynchronous=False + ) + return self.buffer_cls.from_bytes(new_fs.cat(f"{store.path}/{key}")) + + async def set(self, store: FsspecStore, key: str, value: Buffer) -> None: + # make a new, synchronous instance of the filesystem because this test is run in sync code + new_fs = fsspec.filesystem( + "s3", endpoint_url=store.fs.endpoint_url, anon=store.fs.anon, asynchronous=False + ) + new_fs.write_bytes(f"{store.path}/{key}", value.to_bytes()) + + def test_store_repr(self, store: FsspecStore) -> None: + assert str(store) == "" + + def test_store_supports_writes(self, store: FsspecStore) -> None: + assert store.supports_writes + + def test_store_supports_listing(self, store: FsspecStore) -> None: + assert store.supports_listing + + async def test_fsspec_store_from_uri(self, store: FsspecStore, endpoint_url: str) -> None: + storage_options = { + "endpoint_url": endpoint_url, + "anon": False, + } + + meta: dict[str, JSON] = { + "attributes": {"key": "value"}, + "zarr_format": 3, + "node_type": "group", + } + + await store.set( + "zarr.json", + self.buffer_cls.from_bytes(json.dumps(meta).encode()), + ) + group = await zarr.api.asynchronous.open_group( + store=f"s3://{test_bucket_name}", storage_options=storage_options + ) + assert dict(group.attrs) == {"key": "value"} + + meta = { + "attributes": {"key": "value-2"}, + "zarr_format": 3, + "node_type": "group", + } + await store.set( + "directory-2/zarr.json", + self.buffer_cls.from_bytes(json.dumps(meta).encode()), + ) + group = await zarr.api.asynchronous.open_group( + store=f"s3://{test_bucket_name}/directory-2", storage_options=storage_options + ) + assert dict(group.attrs) == {"key": "value-2"} + + meta = { + "attributes": {"key": "value-3"}, + "zarr_format": 3, + "node_type": "group", + } + await store.set( + "directory-3/zarr.json", + self.buffer_cls.from_bytes(json.dumps(meta).encode()), + ) + group = await zarr.api.asynchronous.open_group( + store=f"s3://{test_bucket_name}", path="directory-3", storage_options=storage_options + ) + assert dict(group.attrs) == {"key": "value-3"} + + @pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.03.01"), + reason="Prior bug in from_upath", + ) + def test_from_upath(self, endpoint_url: str) -> None: + upath = pytest.importorskip("upath") + path = upath.UPath( + f"s3://{test_bucket_name}/foo/bar/", + endpoint_url=endpoint_url, + anon=False, + asynchronous=True, + ) + result = FsspecStore.from_upath(path) + assert result.fs.endpoint_url == endpoint_url + assert result.fs.asynchronous + assert result.path == f"{test_bucket_name}/foo/bar" + + @pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.03.01"), + reason="Prior bug in from_upath", + ) + def test_from_upath_sync_filesystem(self, endpoint_url: str) -> None: + """ + A UPath built without ``asynchronous=True`` -- the common case -- yields an async-mode + filesystem that keeps the original storage options. + """ + upath = pytest.importorskip("upath") + path = upath.UPath( + f"s3://{test_bucket_name}/foo/bar/", + endpoint_url=endpoint_url, + anon=False, + ) + assert not path.fs.asynchronous + with warnings.catch_warnings(): + warnings.simplefilter("error", ZarrUserWarning) + result = FsspecStore.from_upath(path) + assert result.fs.asynchronous + assert result.fs.endpoint_url == endpoint_url + assert result.path == f"{test_bucket_name}/foo/bar" + + async def test_open_group_from_upath(self, endpoint_url: str) -> None: + """ + Passing a remote UPath to the top-level API works. + + Regression test for https://github.com/zarr-developers/zarr-python/issues/4244. + """ + upath = pytest.importorskip("upath") + path = upath.UPath( + f"s3://{test_bucket_name}/upath-group", + endpoint_url=endpoint_url, + anon=False, + ) + group = await zarr.api.asynchronous.open_group(path, mode="w", attributes={"key": "value"}) + assert isinstance(group.store_path.store, FsspecStore) + + reopened = await zarr.api.asynchronous.open_group(path, mode="r") + assert dict(reopened.attrs) == {"key": "value"} + + def test_init_warns_if_fs_asynchronous_is_false(self, endpoint_url: str) -> None: + try: + from fsspec import url_to_fs + except ImportError: + # before fsspec==2024.3.1 + from fsspec.core import url_to_fs + fs, path = url_to_fs( + f"s3://{test_bucket_name}", endpoint_url=endpoint_url, anon=False, asynchronous=False + ) + store_kwargs = {"fs": fs, "path": path} + with pytest.warns(ZarrUserWarning, match=r".* was not created with `asynchronous=True`.*"): + self.store_cls(**store_kwargs) + + async def test_empty_nonexistent_path(self, store_kwargs: dict[str, Any]) -> None: + # regression test for https://github.com/zarr-developers/zarr-python/pull/2343 + store_kwargs["path"] += "/abc" + store = await self.store_cls.open(**store_kwargs) + assert await store.is_empty("") + + async def test_delete_dir_unsupported_deletes(self, store: FsspecStore) -> None: + store.supports_deletes = False + with pytest.raises( + NotImplementedError, + match="This method is only available for stores that support deletes.", + ): + await store.delete_dir("test_prefix") + + # ── Filesystem lifecycle ────────────────────────────────────────────────── + + async def test_close_marks_store_closed(self, endpoint_url: str) -> None: + """close() must succeed and mark the store not-open.""" + store = FsspecStore.from_url( + f"s3://{test_bucket_name}/lifecycle/", + storage_options={"endpoint_url": endpoint_url, "anon": False}, + ) + await store.set("probe", cpu.Buffer.from_bytes(b"x")) + + store.close() + + assert not store._is_open + + +def array_roundtrip(store: FsspecStore) -> None: + """ + Round trip an array using a Zarr store + + Args: + store: FsspecStore + """ + data = np.ones((3, 3)) + arr = zarr.create_array(store=store, overwrite=True, data=data) + assert isinstance(arr, Array) + # Read set values + arr2 = zarr.open_array(store=store) + assert isinstance(arr2, Array) + np.testing.assert_array_equal(arr[:], data) + + +@pytest.mark.parametrize( + ("root", "key", "expected"), + [ + # `"/"` as root collapses so that bare-key backends (notably + # ReferenceFileSystem) get the right key. Regression test for + # https://github.com/zarr-developers/zarr-python/issues/3922 . + ("/", "zarr.json", "zarr.json"), + ("", "zarr.json", "zarr.json"), + # Trailing slashes on the root are stripped before joining. + ("foo/", "zarr.json", "foo/zarr.json"), + ("foo", "zarr.json", "foo/zarr.json"), + # Leading slashes on the root are preserved -- absolute filesystem + # paths must stay absolute. Regression test for the titiler-xarray + # breakage that #3924 introduced when `normalize_path` was applied to + # `FsspecStore.path`. + ("/home/runner/data.zarr", "zarr.json", "/home/runner/data.zarr/zarr.json"), + ("/home/runner/data.zarr/", "zarr.json", "/home/runner/data.zarr/zarr.json"), + # Multi-segment keys. + ("/home/foo", "a/b/zarr.json", "/home/foo/a/b/zarr.json"), + ("", "a/b/zarr.json", "a/b/zarr.json"), + # Trailing slash on the result is stripped (relevant when key is ""). + ("/home/foo", "", "/home/foo"), + ], +) +def test_dereference_path(root: str, key: str, expected: str) -> None: + """Verify the contract `_dereference_path` provides for `FsspecStore`. + + `FsspecStore.path` is stored verbatim; the join with a key must collapse a + sentinel `"/"` root, strip trailing slashes, and preserve leading + slashes on absolute paths. + """ + from zarr.storage._utils import _dereference_path + + assert _dereference_path(root, key) == expected + + +async def test_fsspec_store_open_group_via_reference_filesystem() -> None: + """End-to-end regression test for + https://github.com/zarr-developers/zarr-python/issues/3922 . + + ``ReferenceFileSystem`` keys its refs by bare strings like ``"zarr.json"``. + The bug was that ``FsspecStore(fs=ref_fs, path="/")`` produced + ``"//zarr.json"`` at the join site and failed to find the entry, raising + ``GroupNotFoundError``. This test pins ``path="/"`` explicitly to keep + coverage even if the default value changes later. + """ + import json + + from fsspec.implementations.reference import ReferenceFileSystem + + group_json = json.dumps({"zarr_format": 3, "node_type": "group", "attributes": {}}) + fs = ReferenceFileSystem( + fo={"version": 1, "refs": {"zarr.json": group_json}}, + asynchronous=True, + ) + store = FsspecStore(fs=fs, path="/", read_only=True) + group = await zarr.api.asynchronous.open_group(store, mode="r") + assert group.metadata.zarr_format == 3 + + +async def test_fsspec_store_read_array_chunk_via_reference_filesystem() -> None: + """End-to-end regression test that exercises the byte-range read path + against ``ReferenceFileSystem``. + + Beyond opening a group (covered by + ``test_fsspec_store_open_group_via_reference_filesystem``), this test + constructs a small zarr v3 array whose chunk lives in the refs dict and + reads it through the store. Path-handling bugs on the byte-range + fetch path (used by kerchunk-style virtualization) would surface here + rather than at metadata-open time. + """ + import json + + import numpy as np + from fsspec.implementations.reference import ReferenceFileSystem + + # Construct a minimal v3 zarr: a single 1-D uint8 array of length 4 with + # one chunk of size 4. The chunk bytes are little-endian uint8s 1..4. + array_meta = json.dumps( + { + "zarr_format": 3, + "node_type": "array", + "shape": [4], + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": [4]}}, + "data_type": "uint8", + "chunk_key_encoding": {"name": "default", "configuration": {"separator": "/"}}, + "fill_value": 0, + "codecs": [{"name": "bytes", "configuration": {"endian": "little"}}], + "attributes": {}, + } + ) + chunk_bytes = bytes([1, 2, 3, 4]) + + refs: dict[str, str] = { + "zarr.json": array_meta, + # ReferenceFileSystem accepts raw bytes via base64 encoding or + # latin-1-decoded strings; latin-1 round-trips bytes 1:1. + "c/0": chunk_bytes.decode("latin-1"), + } + + fs = ReferenceFileSystem( + fo={"version": 1, "refs": refs}, + asynchronous=True, + ) + store = FsspecStore(fs=fs, path="/", read_only=True) + array = await zarr.api.asynchronous.open_array(store=store, mode="r") + data = await array.getitem(slice(None)) + np.testing.assert_array_equal(data, np.array([1, 2, 3, 4], dtype="uint8")) + + +@pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.12.0"), + reason="No AsyncFileSystemWrapper", +) +def test_wrap_sync_filesystem(tmp_path: pathlib.Path) -> None: + """The local fs is not async so we should expect it to be wrapped automatically""" + from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper + + store = FsspecStore.from_url(f"file://{tmp_path}", storage_options={"auto_mkdir": True}) + assert isinstance(store.fs, AsyncFileSystemWrapper) + assert store.fs.async_impl + array_roundtrip(store) + + +@pytest.mark.skipif( + parse_version(fsspec.__version__) >= parse_version("2024.12.0"), + reason="No AsyncFileSystemWrapper", +) +def test_wrap_sync_filesystem_raises(tmp_path: pathlib.Path) -> None: + """The local fs is not async so we should expect it to be wrapped automatically""" + with pytest.raises(ImportError, match="The filesystem .*"): + FsspecStore.from_url(f"file://{tmp_path}", storage_options={"auto_mkdir": True}) + + +@pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.12.0"), + reason="No AsyncFileSystemWrapper", +) +def test_no_wrap_async_filesystem(endpoint_url: str) -> None: + """An async fs should not be wrapped automatically; fsspec's s3 filesystem is such an fs""" + from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper + + store = FsspecStore.from_url( + f"s3://{test_bucket_name}/foo/spam/", + storage_options={"endpoint_url": endpoint_url, "anon": False, "asynchronous": True}, + read_only=False, + ) + assert not isinstance(store.fs, AsyncFileSystemWrapper) + assert store.fs.async_impl + array_roundtrip(store) + + +@pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.12.0"), + reason="No AsyncFileSystemWrapper", +) +def test_open_fsmap_file(tmp_path: pathlib.Path) -> None: + min_fsspec_with_async_wrapper = parse_version("2024.12.0") + current_version = parse_version(fsspec.__version__) + + fs = fsspec.filesystem("file", auto_mkdir=True) + mapper = fs.get_mapper(tmp_path) + + if current_version < min_fsspec_with_async_wrapper: + # Expect ImportError for older versions + with pytest.raises( + ImportError, + match=r"The filesystem .* is synchronous, and the required AsyncFileSystemWrapper is not available.*", + ): + array_roundtrip(mapper) + else: + # Newer versions should work + array_roundtrip(mapper) + + +@pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.12.0"), + reason="No AsyncFileSystemWrapper", +) +def test_open_fsmap_file_raises(tmp_path: pathlib.Path) -> None: + fsspec = pytest.importorskip("fsspec.implementations.local") + fs = fsspec.LocalFileSystem(auto_mkdir=False) + mapper = fs.get_mapper(tmp_path) + with pytest.raises(FileNotFoundError, match="No such file or directory: .*"): + array_roundtrip(mapper) + + +@pytest.mark.parametrize("asynchronous", [True, False]) +def test_open_fsmap_s3(asynchronous: bool, endpoint_url: str) -> None: + s3_filesystem = s3fs.S3FileSystem( + asynchronous=asynchronous, endpoint_url=endpoint_url, anon=False + ) + mapper = s3_filesystem.get_mapper(f"s3://{test_bucket_name}/map/foo/") + array_roundtrip(mapper) + + +def test_open_s3map_raises(endpoint_url: str) -> None: + with pytest.raises(TypeError, match="Unsupported type for store_like:.*"): + zarr.open(store=0, mode="w", shape=(3, 3)) + s3_filesystem = s3fs.S3FileSystem(asynchronous=True, endpoint_url=endpoint_url, anon=False) + mapper = s3_filesystem.get_mapper(f"s3://{test_bucket_name}/map/foo/") + with pytest.raises( + ValueError, match="'path' was provided but is not used for FSMap store_like objects" + ): + zarr.open(store=mapper, path="bar", mode="w", shape=(3, 3)) + with pytest.raises( + TypeError, + match="'storage_options' is only used when the store is passed as an FSSpec URI string.", + ): + zarr.open(store=mapper, storage_options={"anon": True}, mode="w", shape=(3, 3)) + + +async def test_close_does_not_close_filesystem_session() -> None: + """close() must not touch the filesystem's session. + + fsspec caches and shares filesystem instances across callers, so the + session is not the store's to close. HTTP is used because its aiohttp + session is observably closed for good; s3fs transparently reconnects, which + would hide a regression. No request is issued β€” set_session() only + constructs the session. + """ + pytest.importorskip("aiohttp") + store = FsspecStore.from_url("http://example.com/a") + session = await store.fs.set_session() + + store.close() + + assert not session.closed + + +async def test_close_does_not_break_a_sibling_store() -> None: + """Closing one store must not close a session another store is using. + + Two stores from different URLs on one host are handed the same cached + filesystem; a store that closed it on close() would take the sibling's + session down too. This is the regression guard for that bug. + """ + pytest.importorskip("aiohttp") + s1 = FsspecStore.from_url("http://example.com/a") + s2 = FsspecStore.from_url("http://example.com/b") + session = await s2.fs.set_session() + + s1.close() + + assert not session.closed + + +@pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.12.0"), + reason="No AsyncFileSystemWrapper", +) +def test_from_mapper_wraps_sync_filesystem(tmp_path: pathlib.Path) -> None: + """from_mapper() with a sync fs wraps it in an AsyncFileSystemWrapper.""" + import fsspec as _fsspec + from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper + + fs = _fsspec.filesystem("file", auto_mkdir=True) + mapper = fs.get_mapper(str(tmp_path)) + store = FsspecStore.from_mapper(mapper) + assert isinstance(store.fs, AsyncFileSystemWrapper) + + +@pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.12.0"), + reason="No AsyncFileSystemWrapper", +) +def test_with_read_only_shares_filesystem(tmp_path: pathlib.Path) -> None: + """with_read_only() returns a store sharing the source's filesystem.""" + source = FsspecStore.from_url(f"file://{tmp_path}", storage_options={"auto_mkdir": False}) + + derived = source.with_read_only(read_only=True) + + assert derived.fs is source.fs + assert derived.read_only + assert not source.read_only + + +def test_make_async_preserves_unserializable_storage_options() -> None: + """A sync instance of an async filesystem whose storage options hold objects that + cannot round-trip through JSON (e.g. an Azure credential) must still convert. + + See https://github.com/zarr-developers/zarr-python/issues/4220 + """ + pytest.importorskip("aiohttp") + credential = object() # stand-in for e.g. azure.identity.DefaultAzureCredential + sync_fs = fsspec.filesystem("http", client_kwargs={"auth": credential}) + assert sync_fs.async_impl + assert not sync_fs.asynchronous + + async_fs = _make_async(sync_fs) + + assert async_fs.asynchronous + assert async_fs.client_kwargs["auth"] is credential + + +@pytest.mark.parametrize("asynchronous", [True, False]) +def test_make_async(asynchronous: bool, endpoint_url: str) -> None: + s3_filesystem = s3fs.S3FileSystem( + asynchronous=asynchronous, endpoint_url=endpoint_url, anon=False + ) + fs = _make_async(s3_filesystem) + assert fs.asynchronous + + +@pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.12.0"), + reason="No AsyncFileSystemWrapper", +) +async def test_delete_dir_wrapped_filesystem(tmp_path: Path) -> None: + from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper + from fsspec.implementations.local import LocalFileSystem + + wrapped_fs = AsyncFileSystemWrapper(LocalFileSystem(auto_mkdir=True)) + store = FsspecStore(wrapped_fs, read_only=False, path=f"{tmp_path}/test/path") + + assert isinstance(store.fs, AsyncFileSystemWrapper) + assert store.fs.asynchronous + + await store.set("zarr.json", cpu.Buffer.from_bytes(b"root")) + await store.set("foo-bar/zarr.json", cpu.Buffer.from_bytes(b"root")) + await store.set("foo/zarr.json", cpu.Buffer.from_bytes(b"bar")) + await store.set("foo/c/0", cpu.Buffer.from_bytes(b"chunk")) + await store.delete_dir("foo") + assert await store.exists("zarr.json") + assert await store.exists("foo-bar/zarr.json") + assert not await store.exists("foo/zarr.json") + assert not await store.exists("foo/c/0") + + +@pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.12.0"), + reason="No AsyncFileSystemWrapper", +) +async def test_with_read_only_auto_mkdir(tmp_path: Path) -> None: + """ + Test that creating a read-only copy of a store backed by the local file system does not error + if auto_mkdir is False. + """ + + store_w = FsspecStore.from_url(f"file://{tmp_path}", storage_options={"auto_mkdir": False}) + _ = store_w.with_read_only() + + +@pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.12.0"), + reason="No AsyncFileSystemWrapper", +) +async def test_memory_scheme() -> None: + """Test that the "memory" scheme creates a `MemoryFileSystem`-backed store""" + store = await make_store("memory://test") + assert isinstance(store, FsspecStore) + assert store.fs.protocol == "memory" diff --git a/tests/test_store/test_fsspec_get_ranges.py b/tests/test_store/test_fsspec_get_ranges.py new file mode 100644 index 0000000000..61d834d22f --- /dev/null +++ b/tests/test_store/test_fsspec_get_ranges.py @@ -0,0 +1,124 @@ +# tests/test_store/test_fsspec_get_ranges.py +"""Lightweight integration tests for FsspecStore.get_ranges using MemoryFileSystem. + +These don't need moto/s3 β€” they exercise the new method against an in-process +fsspec MemoryFileSystem wrapped in the async wrapper. +""" + +from __future__ import annotations + +import pytest +from packaging.version import parse as parse_version + +from zarr.abc.store import RangeByteRequest +from zarr.core.buffer import Buffer, default_buffer_prototype +from zarr.storage import FsspecStore +from zarr.storage._fsspec import _make_async + +fsspec = pytest.importorskip("fsspec") + +# AsyncFileSystemWrapper (needed to wrap a sync MemoryFileSystem) landed in fsspec 2024.12.0. +# Older versions are pinned by the min-deps CI job, so skip the whole file there. +pytestmark = pytest.mark.skipif( + parse_version(fsspec.__version__) < parse_version("2024.12.0"), + reason="No AsyncFileSystemWrapper", +) + + +@pytest.fixture +def memory_store() -> FsspecStore: + """An FsspecStore backed by fsspec MemoryFileSystem (wrapped async).""" + from fsspec.implementations.memory import MemoryFileSystem + + # Each test gets a clean filesystem; MemoryFileSystem is a singleton per target_options, + # so clear state explicitly. + fs: MemoryFileSystem = MemoryFileSystem() + fs.store.clear() + fs.pseudo_dirs.clear() + async_fs = _make_async(fs) + return FsspecStore(fs=async_fs, path="/root") + + +async def _write(store: FsspecStore, key: str, data: bytes) -> None: + buf = default_buffer_prototype().buffer.from_bytes(data) + await store.set(key, buf) + + +async def test_get_ranges_happy_path(memory_store: FsspecStore) -> None: + blob = bytes(i % 256 for i in range(1024)) + await _write(memory_store, "blob", blob) + proto = default_buffer_prototype() + + ranges = [ + RangeByteRequest(0, 10), + RangeByteRequest(100, 110), + RangeByteRequest(500, 520), + ] + groups: list[list[tuple[int, Buffer | None]]] = [ + list(group) async for group in memory_store.get_ranges("blob", ranges, prototype=proto) + ] + + flat: dict[int, bytes] = {} + for group in groups: + for idx, buf in group: + assert buf is not None + flat[idx] = buf.to_bytes() + + assert flat[0] == blob[0:10] + assert flat[1] == blob[100:110] + assert flat[2] == blob[500:520] + + +async def test_get_ranges_missing_key_raises(memory_store: FsspecStore) -> None: + """A request against a missing key raises BaseExceptionGroup containing FileNotFoundError.""" + proto = default_buffer_prototype() + agen = memory_store.get_ranges("does-not-exist", [RangeByteRequest(0, 10)], prototype=proto) + with pytest.RaisesGroup(pytest.RaisesExc(FileNotFoundError)): + await anext(agen) + + +async def test_get_ranges_forwards_coalescing_kwargs(memory_store: FsspecStore) -> None: + """`max_gap_bytes=-1` forces no merging; we should see three groups for three ranges.""" + blob = bytes(i % 256 for i in range(1024)) + await _write(memory_store, "blob", blob) + proto = default_buffer_prototype() + + ranges = [ + RangeByteRequest(0, 10), + RangeByteRequest(11, 20), # adjacent: would merge under defaults + RangeByteRequest(21, 30), + ] + groups: list[list[tuple[int, Buffer | None]]] = [ + list(group) + async for group in memory_store.get_ranges( + "blob", ranges, prototype=proto, max_gap_bytes=-1 + ) + ] + # With merging disabled, every range becomes its own one-tuple group. + assert sorted(len(g) for g in groups) == [1, 1, 1] + + +async def test_get_ranges_mixed_range_types(memory_store: FsspecStore) -> None: + """Covers RangeByteRequest, OffsetByteRequest, SuffixByteRequest, and None in one call.""" + from zarr.abc.store import ByteRequest, OffsetByteRequest, SuffixByteRequest + + blob = bytes(i % 256 for i in range(512)) + await _write(memory_store, "mixed", blob) + proto = default_buffer_prototype() + + ranges: list[ByteRequest | None] = [ + RangeByteRequest(0, 10), + OffsetByteRequest(500), + SuffixByteRequest(12), + None, + ] + flat: dict[int, bytes] = {} + async for group in memory_store.get_ranges("mixed", ranges, prototype=proto): + for idx, buf in group: + assert buf is not None + flat[idx] = buf.to_bytes() + + assert flat[0] == blob[0:10] + assert flat[1] == blob[500:] + assert flat[2] == blob[-12:] + assert flat[3] == blob diff --git a/tests/test_store/test_get_ranges.py b/tests/test_store/test_get_ranges.py new file mode 100644 index 0000000000..522d6565aa --- /dev/null +++ b/tests/test_store/test_get_ranges.py @@ -0,0 +1,183 @@ +# tests/test_store/test_get_ranges.py +"""Tests for `Store.get_ranges` β€” the ABC default implementation and wrapper delegation. + +`Store.get_ranges` is defined on the ABC with a default implementation built +on `coalesced_get(self.get, ...)`, so every store inherits a working version. +These tests cover that inherited path and the explicit delegation in +`WrapperStore` (which ensures wrapped stores' optimized overrides are honored). +Store-specific overrides (e.g. `FsspecStore`) have their own test modules. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest + +from zarr.abc.store import RangeByteRequest +from zarr.core.buffer import default_buffer_prototype +from zarr.storage import MemoryStore, ZipStore +from zarr.storage._wrapper import WrapperStore + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Sequence + from pathlib import Path + + from zarr.abc.store import ByteRequest + from zarr.core.buffer import Buffer, BufferPrototype + + +async def _write(store: MemoryStore, key: str, data: bytes) -> None: + buf = default_buffer_prototype().buffer.from_bytes(data) + await store.set(key, buf) + + +async def test_memory_store_inherits_get_ranges_from_abc() -> None: + """MemoryStore doesn't override `get_ranges`; the ABC default must work end-to-end.""" + store = MemoryStore() + blob = bytes(i % 256 for i in range(512)) + await _write(store, "blob", blob) + + ranges = [RangeByteRequest(0, 10), RangeByteRequest(100, 110)] + proto = default_buffer_prototype() + flat: dict[int, bytes] = {} + async for group in store.get_ranges("blob", ranges, prototype=proto): + for idx, buf in group: + assert buf is not None + flat[idx] = buf.to_bytes() + + assert flat[0] == blob[0:10] + assert flat[1] == blob[100:110] + + +async def test_memory_store_get_ranges_missing_key_raises() -> None: + """A missing key on a default-impl store raises BaseExceptionGroup containing FileNotFoundError.""" + store = MemoryStore() + proto = default_buffer_prototype() + agen = store.get_ranges("does-not-exist", [RangeByteRequest(0, 10)], prototype=proto) + with pytest.RaisesGroup(pytest.RaisesExc(FileNotFoundError)): + await anext(agen) + + +def test_get_ranges_sync_reads_multiple_ranges() -> None: + """The synchronous `get_ranges_sync` on a sync-capable store returns each + requested range, mirroring the async `get_ranges` happy path.""" + import asyncio + + store = MemoryStore() + blob = bytes(i % 256 for i in range(512)) + asyncio.run(_write(store, "blob", blob)) + + ranges = [RangeByteRequest(0, 10), RangeByteRequest(100, 110)] + proto = default_buffer_prototype() + flat: dict[int, bytes] = {} + for idx, buf in store.get_ranges_sync("blob", ranges, prototype=proto): + assert buf is not None + flat[idx] = buf.to_bytes() + + assert flat[0] == blob[0:10] + assert flat[1] == blob[100:110] + + +def test_get_ranges_sync_missing_key_raises() -> None: + """A missing key makes `get_ranges_sync` raise a BaseExceptionGroup + containing FileNotFoundError β€” the same contract as async `get_ranges`, so + callers handle a deleted shard uniformly across sync and async paths.""" + store = MemoryStore() + proto = default_buffer_prototype() + with pytest.RaisesGroup(pytest.RaisesExc(FileNotFoundError)): + store.get_ranges_sync("does-not-exist", [RangeByteRequest(0, 10)], prototype=proto) + + +def test_get_ranges_sync_on_non_sync_store_raises_type_error(tmp_path: Path) -> None: + """`get_ranges_sync` requires the store to support synchronous reads + (`SupportsGetSync`); a non-sync store raises TypeError rather than silently + falling back.""" + store = ZipStore(tmp_path / "store.zip", mode="w") + proto = default_buffer_prototype() + with pytest.raises(TypeError, match="does not support synchronous reads"): + store.get_ranges_sync("k", [RangeByteRequest(0, 10)], prototype=proto) + + +async def test_wrapper_store_delegates_get_ranges() -> None: + """WrapperStore.get_ranges must delegate to the wrapped store, not fall back to the default.""" + + class CountingMemoryStore(MemoryStore): + """Tallies get_ranges invocations so we can assert delegation.""" + + get_ranges_calls: int = 0 + + async def get_ranges( + self, + key: str, + byte_ranges: Sequence[ByteRequest | None], + *, + prototype: BufferPrototype, + max_concurrency: int = 10, + max_gap_bytes: int = 1 << 20, + max_coalesced_bytes: int = 16 << 20, + ) -> AsyncIterator[Sequence[tuple[int, Buffer | None]]]: + type(self).get_ranges_calls += 1 + async for group in super().get_ranges( + key, + byte_ranges, + prototype=prototype, + max_concurrency=max_concurrency, + max_gap_bytes=max_gap_bytes, + max_coalesced_bytes=max_coalesced_bytes, + ): + yield group + + inner = CountingMemoryStore() + blob = b"x" * 100 + await _write(inner, "k", blob) + wrapped = WrapperStore(inner) + + proto = default_buffer_prototype() + groups: list[list[tuple[int, Buffer | None]]] = [ + list(group) + async for group in wrapped.get_ranges("k", [RangeByteRequest(0, 5)], prototype=proto) + ] + + assert CountingMemoryStore.get_ranges_calls == 1 + assert len(groups) == 1 + assert groups[0][0][0] == 0 + + +async def test_wrapper_store_forwards_coalescing_kwargs() -> None: + """Coalescing kwargs flow through WrapperStore to the wrapped store's get_ranges.""" + + class SpyMemoryStore(MemoryStore): + last_max_gap_bytes: int | None = None + + async def get_ranges( + self, + key: str, + byte_ranges: Sequence[ByteRequest | None], + *, + prototype: BufferPrototype, + max_concurrency: int = 10, + max_gap_bytes: int = 1 << 20, + max_coalesced_bytes: int = 16 << 20, + ) -> AsyncIterator[Sequence[tuple[int, Buffer | None]]]: + type(self).last_max_gap_bytes = max_gap_bytes + async for group in super().get_ranges( + key, + byte_ranges, + prototype=prototype, + max_concurrency=max_concurrency, + max_gap_bytes=max_gap_bytes, + max_coalesced_bytes=max_coalesced_bytes, + ): + yield group + + inner = SpyMemoryStore() + await _write(inner, "k", b"y" * 100) + wrapped = WrapperStore(inner) + proto = default_buffer_prototype() + async for _ in wrapped.get_ranges( + "k", [RangeByteRequest(0, 5)], prototype=proto, max_gap_bytes=-1 + ): + pass + + assert SpyMemoryStore.last_max_gap_bytes == -1 diff --git a/tests/test_store/test_latency.py b/tests/test_store/test_latency.py new file mode 100644 index 0000000000..9cb71fd6a0 --- /dev/null +++ b/tests/test_store/test_latency.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +import time +from unittest.mock import patch + +import numpy as np +import pytest + +import zarr +from zarr.abc.store import RangeByteRequest +from zarr.core.buffer import default_buffer_prototype +from zarr.core.codec_pipeline import FusedCodecPipeline +from zarr.core.config import config as zarr_config +from zarr.storage import MemoryStore +from zarr.testing.store import LatencyStore + + +async def test_latency_store_with_read_only_round_trip() -> None: + """ + Ensure that LatencyStore.with_read_only returns another LatencyStore with + the requested read_only state, preserves latency configuration, and does + not change the original wrapper. + """ + base = await MemoryStore.open() + # Start from a read-only underlying store + ro_base = base.with_read_only(read_only=True) + latency_ro = LatencyStore(ro_base, get_latency=0.01, set_latency=0.02) + + assert latency_ro.read_only + assert latency_ro.get_latency == pytest.approx(0.01) + assert latency_ro.set_latency == pytest.approx(0.02) + + buf = default_buffer_prototype().buffer.from_bytes(b"abcd") + + # Cannot write through the read-only wrapper + with pytest.raises( + ValueError, match="store was opened in read-only mode and does not support writing" + ): + await latency_ro.set("key", buf) + + # Create a writable wrapper from the read-only one + writer = latency_ro.with_read_only(read_only=False) + assert isinstance(writer, LatencyStore) + assert not writer.read_only + # Latency configuration is preserved + assert writer.get_latency == latency_ro.get_latency + assert writer.set_latency == latency_ro.set_latency + + # Writes via the writable wrapper succeed + await writer.set("key", buf) + out = await writer.get("key", prototype=default_buffer_prototype()) + assert out is not None + assert out.to_bytes() == buf.to_bytes() + + # Creating a read-only copy from the writable wrapper works and is enforced + reader = writer.with_read_only(read_only=True) + assert isinstance(reader, LatencyStore) + assert reader.read_only + with pytest.raises( + ValueError, match="store was opened in read-only mode and does not support writing" + ): + await reader.set("other", buf) + + # The original read-only wrapper remains read-only + assert latency_ro.read_only + + +@pytest.mark.parametrize( + ("get_latency", "set_latency"), + [ + (0.01, 0.02), + ((0.1, 0.05), (0.2, 0.01)), + ], + ids=["scalar", "distribution"], +) +def test_with_store_preserves_latency_config( + get_latency: float | tuple[float, float], set_latency: float | tuple[float, float] +) -> None: + """Derived stores (e.g. via `with_read_only`) keep the raw latency config β€” + a `(loc, scale)` distribution must not collapse to one sampled float.""" + store = LatencyStore(MemoryStore(), get_latency=get_latency, set_latency=set_latency) + derived = store.with_read_only(True) + assert derived._get_latency == store._get_latency + assert derived._set_latency == store._set_latency + + +def test_sync_methods_inject_latency(monkeypatch: pytest.MonkeyPatch) -> None: + """`get_sync`/`set_sync` sleep the configured latency on the calling thread + before delegating to the wrapped store.""" + sleeps: list[float] = [] + monkeypatch.setattr(time, "sleep", sleeps.append) + + store = LatencyStore(MemoryStore(), get_latency=0.123, set_latency=0.456) + buf = default_buffer_prototype().buffer.from_bytes(b"abcd") + store.set_sync("key", buf) + assert sleeps == [pytest.approx(0.456)] + out = store.get_sync("key", prototype=default_buffer_prototype()) + assert out is not None + assert out.to_bytes() == b"abcd" + assert sleeps == [pytest.approx(0.456), pytest.approx(0.123)] + + +async def test_get_ranges_pays_latency_per_fetch() -> None: + """`get_ranges` routes through the coalescing default built on `self.get`, + so each merged fetch pays the configured latency instead of bypassing it + via WrapperStore delegation. Two ranges further apart than `max_gap_bytes` + cannot coalesce -> exactly two `get` calls.""" + proto = default_buffer_prototype() + inner = MemoryStore() + await inner.set("blob", proto.buffer.from_bytes(bytes(4 << 20))) + store = LatencyStore(inner, get_latency=0.0) + + requests = [RangeByteRequest(0, 10), RangeByteRequest(2 << 20, (2 << 20) + 10)] + results: list[tuple[int, object]] = [] + with patch.object(store, "get", wraps=store.get) as get_spy: + async for group in store.get_ranges("blob", requests, prototype=proto): + results.extend(group) + assert get_spy.await_count == 2 + assert sorted(idx for idx, _ in results) == [0, 1] + for _, buf in results: + assert buf is not None + assert len(buf) == 10 # type: ignore[arg-type] + + +async def test_get_partial_values_routes_through_get() -> None: + """`get_partial_values` issues one `self.get` per key-range so each fetch + pays the configured latency instead of bypassing it via WrapperStore + delegation.""" + proto = default_buffer_prototype() + inner = MemoryStore() + await inner.set("blob", proto.buffer.from_bytes(b"0123456789")) + store = LatencyStore(inner, get_latency=0.0) + + with patch.object(store, "get", wraps=store.get) as get_spy: + results = await store.get_partial_values( + proto, [("blob", RangeByteRequest(0, 4)), ("blob", None)] + ) + assert get_spy.await_count == 2 + assert results[0] is not None + assert results[0].to_bytes() == b"0123" + assert results[1] is not None + assert results[1].to_bytes() == b"0123456789" + + +def test_latency_store_engages_fused_sync_path() -> None: + """A LatencyStore wrapping a sync-capable store must take the fused sync + fast path: reads go through the inner store's `get_sync`, not the async + fallback.""" + inner = MemoryStore() + store = LatencyStore(inner, get_latency=0.0, set_latency=0.0) + with zarr_config.set({"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"}): + arr = zarr.create_array( + store=store, + shape=(8,), + chunks=(4,), + dtype="uint8", + compressors=None, + fill_value=0, + ) + assert isinstance(arr._async_array.codec_pipeline, FusedCodecPipeline) + data = np.arange(8, dtype="uint8") + arr[:] = data + with patch.object(inner, "get_sync", wraps=inner.get_sync) as get_sync_spy: + np.testing.assert_array_equal(arr[:], data) + assert get_sync_spy.call_count == 2 # one per chunk diff --git a/tests/test_store/test_local.py b/tests/test_store/test_local.py new file mode 100644 index 0000000000..90d214ee2c --- /dev/null +++ b/tests/test_store/test_local.py @@ -0,0 +1,166 @@ +from __future__ import annotations + +import pathlib +import re + +import numpy as np +import pytest + +import zarr +from zarr import create_array +from zarr.core.buffer import Buffer, cpu +from zarr.storage import LocalStore +from zarr.storage._local import _atomic_write +from zarr.testing.store import StoreTests +from zarr.testing.utils import assert_bytes_equal + + +class TestLocalStore(StoreTests[LocalStore, cpu.Buffer]): + store_cls = LocalStore + buffer_cls = cpu.Buffer + + async def get(self, store: LocalStore, key: str) -> Buffer: + return self.buffer_cls.from_bytes((store.root / key).read_bytes()) + + async def set(self, store: LocalStore, key: str, value: Buffer) -> None: + parent = (store.root / key).parent + if not parent.exists(): + parent.mkdir(parents=True) + (store.root / key).write_bytes(value.to_bytes()) + + @pytest.fixture + def store_kwargs(self, tmp_path: pathlib.Path) -> dict[str, str]: + return {"root": str(tmp_path)} + + def test_store_repr(self, store: LocalStore) -> None: + assert str(store) == f"file://{store.root.as_posix()}" + + def test_store_supports_writes(self, store: LocalStore) -> None: + assert store.supports_writes + + def test_store_supports_listing(self, store: LocalStore) -> None: + assert store.supports_listing + + async def test_empty_with_empty_subdir(self, store: LocalStore) -> None: + assert await store.is_empty("") + (store.root / "foo/bar").mkdir(parents=True) + assert await store.is_empty("") + + def test_delete_sync_directory(self, store: LocalStore) -> None: + """`delete_sync` on a key that is a directory must remove the whole tree. + + Mirrors the async `delete_dir` behavior: deleting `"foo"` where + `"foo"` is a directory containing further nested paths should remove + everything under it, not just fail or delete a single file. + """ + (store.root / "foo" / "bar").mkdir(parents=True) + (store.root / "foo" / "bar" / "baz").write_bytes(b"data") + + store.delete_sync("foo") + + assert not (store.root / "foo").exists() + + def test_creates_new_directory(self, tmp_path: pathlib.Path) -> None: + target = tmp_path.joinpath("a", "b", "c") + assert not target.exists() + + store = self.store_cls(root=target) + zarr.group(store=store) + + def test_invalid_root_raises(self) -> None: + """ + Test that a TypeError is raised when a non-str/Path type is used for the `root` argument + """ + with pytest.raises( + TypeError, + match=r"'root' must be a string or Path instance. Got an instance of instead.", + ): + LocalStore(root=0) # type: ignore[arg-type] + + async def test_get_with_prototype_default(self, store: LocalStore) -> None: + """ + Ensure that data can be read via ``store.get`` if the prototype keyword argument is unspecified, i.e. set to ``None``. + """ + data_buf = self.buffer_cls.from_bytes(b"\x01\x02\x03\x04") + key = "c/0" + await self.set(store, key, data_buf) + observed = await store.get(key, prototype=None) + assert_bytes_equal(observed, data_buf) + + @pytest.mark.parametrize("ndim", [0, 1, 3]) + @pytest.mark.parametrize( + "destination", ["destination", "foo/bar/destintion", pathlib.Path("foo/bar/destintion")] + ) + async def test_move( + self, tmp_path: pathlib.Path, ndim: int, destination: pathlib.Path | str + ) -> None: + origin = tmp_path / "origin" + if isinstance(destination, str): + destination = str(tmp_path / destination) + else: + destination = tmp_path / destination + + print(type(destination)) + store = await LocalStore.open(root=origin) + shape = (4,) * ndim + chunks = (2,) * ndim + data = np.arange(4**ndim) + if ndim > 0: + data = data.reshape(*shape) + array = create_array(store, data=data, chunks=chunks or "auto") + + await store.move(destination) + + assert store.root == pathlib.Path(destination) + assert pathlib.Path(destination).exists() + assert not origin.exists() + assert np.array_equal(array[...], data) + + store2 = await LocalStore.open(root=origin) + with pytest.raises( + FileExistsError, match=re.escape(f"Destination root {destination} already exists") + ): + await store2.move(destination) + + +@pytest.mark.parametrize("exclusive", [True, False]) +def test_atomic_write_successful(tmp_path: pathlib.Path, exclusive: bool) -> None: + path = tmp_path / "data" + with _atomic_write(path, "wb", exclusive=exclusive) as f: + f.write(b"abc") + assert path.read_bytes() == b"abc" + assert list(path.parent.iterdir()) == [path] # no temp files + + +@pytest.mark.parametrize("exclusive", [True, False]) +def test_atomic_write_incomplete(tmp_path: pathlib.Path, exclusive: bool) -> None: + path = tmp_path / "data" + with pytest.raises(RuntimeError): # noqa: PT012 + with _atomic_write(path, "wb", exclusive=exclusive) as f: + f.write(b"a") + raise RuntimeError + assert not path.exists() + assert list(path.parent.iterdir()) == [] # no temp files + + +def test_atomic_write_non_exclusive_preexisting(tmp_path: pathlib.Path) -> None: + path = tmp_path / "data" + with path.open("wb") as f: + f.write(b"xyz") + assert path.read_bytes() == b"xyz" + with _atomic_write(path, "wb", exclusive=False) as f: + f.write(b"abc") + assert path.read_bytes() == b"abc" + assert list(path.parent.iterdir()) == [path] # no temp files + + +def test_atomic_write_exclusive_preexisting(tmp_path: pathlib.Path) -> None: + path = tmp_path / "data" + with path.open("wb") as f: + f.write(b"xyz") + assert path.read_bytes() == b"xyz" + with pytest.raises(FileExistsError): + with _atomic_write(path, "wb", exclusive=True) as f: + f.write(b"abc") + assert path.read_bytes() == b"xyz" + assert list(path.parent.iterdir()) == [path] # no temp files diff --git a/tests/test_store/test_logging.py b/tests/test_store/test_logging.py new file mode 100644 index 0000000000..96cd184938 --- /dev/null +++ b/tests/test_store/test_logging.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING, TypedDict + +import pytest + +import zarr +from zarr.core.buffer import Buffer, cpu, default_buffer_prototype +from zarr.storage import LocalStore, LoggingStore +from zarr.testing.store import StoreTests + +if TYPE_CHECKING: + from pathlib import Path + + from zarr.abc.store import Store + + +class StoreKwargs(TypedDict): + store: LocalStore + log_level: str + + +class TestLoggingStore(StoreTests[LoggingStore[LocalStore], cpu.Buffer]): + # store_cls is needed to do an isinstance check, so can't be a subscripted generic + store_cls = LoggingStore # type: ignore[assignment] + buffer_cls = cpu.Buffer + + async def get(self, store: LoggingStore[LocalStore], key: str) -> Buffer: + return self.buffer_cls.from_bytes((store._store.root / key).read_bytes()) + + async def set(self, store: LoggingStore[LocalStore], key: str, value: Buffer) -> None: + parent = (store._store.root / key).parent + if not parent.exists(): + parent.mkdir(parents=True) + (store._store.root / key).write_bytes(value.to_bytes()) + + @pytest.fixture + def store_kwargs(self, tmp_path: Path) -> StoreKwargs: + return {"store": LocalStore(str(tmp_path)), "log_level": "DEBUG"} + + @pytest.fixture + def open_kwargs(self, tmp_path: Path) -> dict[str, type[LocalStore] | str]: + return {"store_cls": LocalStore, "root": str(tmp_path), "log_level": "DEBUG"} + + @pytest.fixture + def store(self, store_kwargs: StoreKwargs) -> LoggingStore[LocalStore]: + return self.store_cls(**store_kwargs) + + def test_store_supports_writes(self, store: LoggingStore[LocalStore]) -> None: + assert store.supports_writes + + def test_store_supports_listing(self, store: LoggingStore[LocalStore]) -> None: + assert store.supports_listing + + def test_store_repr(self, store: LoggingStore[LocalStore]) -> None: + assert f"{store!r}" == f"LoggingStore(LocalStore, 'file://{store._store.root.as_posix()}')" + + def test_store_str(self, store: LoggingStore[LocalStore]) -> None: + assert str(store) == f"logging-file://{store._store.root.as_posix()}" + + async def test_default_handler( + self, local_store: LocalStore, capsys: pytest.CaptureFixture[str] + ) -> None: + # Store and then remove existing handlers to enter default handler code path + handlers = logging.getLogger().handlers[:] + for h in handlers: + logging.getLogger().removeHandler(h) + # Test logs are sent to stdout + wrapped = LoggingStore(store=local_store) + buffer = default_buffer_prototype().buffer + res = await wrapped.set("foo/bar/c/0", buffer.from_bytes(b"\x01\x02\x03\x04")) # type: ignore[func-returns-value] + assert res is None + captured = capsys.readouterr() + assert len(captured) == 2 + assert "Calling LocalStore.set" in captured.out + assert "Finished LocalStore.set" in captured.out + # Restore handlers + for h in handlers: + logging.getLogger().addHandler(h) + + def test_is_open_setter_raises(self, store: LoggingStore[LocalStore]) -> None: + "Test that a user cannot change `_is_open` without opening the underlying store." + with pytest.raises( + NotImplementedError, match="LoggingStore must be opened via the `_open` method" + ): + store._is_open = True + + async def test_with_read_only_round_trip(self, local_store: LocalStore) -> None: + """ + Ensure that LoggingStore.with_read_only returns another LoggingStore with + the requested read_only state, preserves logging configuration, and does + not change the original store. + """ + # Start from a read-only underlying store + ro_store = local_store.with_read_only(read_only=True) + wrapped_ro = LoggingStore(store=ro_store, log_level="INFO") + assert wrapped_ro.read_only + + buf = default_buffer_prototype().buffer.from_bytes(b"0123") + + # Cannot write through the read-only wrapper + with pytest.raises( + ValueError, match="store was opened in read-only mode and does not support writing" + ): + await wrapped_ro.set("foo", buf) + + # Create a writable wrapper + writer = wrapped_ro.with_read_only(read_only=False) + assert isinstance(writer, LoggingStore) + assert not writer.read_only + # logging configuration is preserved + assert writer.log_level == wrapped_ro.log_level + assert writer.log_handler == wrapped_ro.log_handler + + # Writes via the writable wrapper succeed + await writer.set("foo", buf) + out = await writer.get("foo", prototype=default_buffer_prototype()) + assert out is not None + assert out.to_bytes() == buf.to_bytes() + + # The original wrapper remains read-only + assert wrapped_ro.read_only + with pytest.raises( + ValueError, match="store was opened in read-only mode and does not support writing" + ): + await wrapped_ro.set("bar", buf) + + +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +async def test_logging_store(store: Store, caplog: pytest.LogCaptureFixture) -> None: + wrapped = LoggingStore(store=store, log_level="DEBUG") + buffer = default_buffer_prototype().buffer + + caplog.clear() + res = await wrapped.set("foo/bar/c/0", buffer.from_bytes(b"\x01\x02\x03\x04")) # type: ignore[func-returns-value] + assert res is None + assert len(caplog.record_tuples) == 2 + for tup in caplog.record_tuples: + assert str(store) in tup[0] + assert f"Calling {type(store).__name__}.set" in caplog.record_tuples[0][2] + assert f"Finished {type(store).__name__}.set" in caplog.record_tuples[1][2] + + caplog.clear() + keys = [k async for k in wrapped.list()] + assert keys == ["foo/bar/c/0"] + assert len(caplog.record_tuples) == 2 + for tup in caplog.record_tuples: + assert str(store) in tup[0] + assert f"Calling {type(store).__name__}.list" in caplog.record_tuples[0][2] + assert f"Finished {type(store).__name__}.list" in caplog.record_tuples[1][2] + + +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"]) +async def test_logging_store_counter(store: Store) -> None: + wrapped = LoggingStore(store=store, log_level="DEBUG") + + arr = zarr.create(shape=(10,), store=wrapped, overwrite=True) + arr[:] = 1 + + assert wrapped.counter["set"] == 2 + assert wrapped.counter["list"] == 0 + assert wrapped.counter["list_dir"] == 0 + assert wrapped.counter["list_prefix"] == 0 + if store.supports_deletes: + assert wrapped.counter["get"] == 0 # 1 if overwrite=False + assert wrapped.counter["delete_dir"] == 1 + else: + assert wrapped.counter["get"] == 1 + assert wrapped.counter["delete_dir"] == 0 diff --git a/tests/test_store/test_memory.py b/tests/test_store/test_memory.py new file mode 100644 index 0000000000..013dae7044 --- /dev/null +++ b/tests/test_store/test_memory.py @@ -0,0 +1,527 @@ +from __future__ import annotations + +import re +from typing import TYPE_CHECKING, Any + +import numpy as np +import numpy.typing as npt +import pytest + +import zarr +from zarr.core.buffer import Buffer, cpu, default_buffer_prototype, gpu +from zarr.errors import ZarrUserWarning +from zarr.storage import GpuMemoryStore, ManagedMemoryStore, MemoryStore +from zarr.storage._utils import _join_paths +from zarr.testing.store import StoreTests +from zarr.testing.utils import gpu_test + +if TYPE_CHECKING: + from zarr.core.common import ZarrFormat + + +# TODO: work out where this warning is coming from and fix it +@pytest.mark.filterwarnings( + re.escape("ignore:coroutine 'ClientCreatorContext.__aexit__' was never awaited") +) +class TestMemoryStore(StoreTests[MemoryStore, cpu.Buffer]): + store_cls = MemoryStore + buffer_cls = cpu.Buffer + + async def set(self, store: MemoryStore, key: str, value: Buffer) -> None: + store._store_dict[key] = value + + async def get(self, store: MemoryStore, key: str) -> Buffer: + return store._store_dict[key] + + @pytest.fixture(params=[None, True]) + def store_kwargs(self, request: pytest.FixtureRequest) -> dict[str, Any]: + kwargs: dict[str, Any] + if request.param is True: + kwargs = {"store_dict": {}} + else: + kwargs = {"store_dict": None} + return kwargs + + @pytest.fixture + async def store(self, store_kwargs: dict[str, Any]) -> MemoryStore: + return self.store_cls(**store_kwargs) + + def test_store_repr(self, store: MemoryStore) -> None: + assert str(store) == f"memory://{id(store._store_dict)}" + + def test_store_supports_writes(self, store: MemoryStore) -> None: + assert store.supports_writes + + def test_store_supports_listing(self, store: MemoryStore) -> None: + assert store.supports_listing + + async def test_list_prefix(self, store: MemoryStore) -> None: + assert True + + @pytest.mark.parametrize("dtype", ["uint8", "float32", "int64"]) + @pytest.mark.parametrize("zarr_format", [2, 3]) + async def test_deterministic_size( + self, store: MemoryStore, dtype: npt.DTypeLike, zarr_format: ZarrFormat + ) -> None: + a = zarr.empty( + store=store, + shape=(3,), + chunks=(1000,), + dtype=dtype, + zarr_format=zarr_format, + overwrite=True, + ) + a[...] = 1 + a.resize((1000,)) + + np.testing.assert_array_equal(a[:3], 1) + np.testing.assert_array_equal(a[3:], 0) + + @pytest.mark.parametrize("method", ["set", "set_sync", "set_if_not_exists"]) + async def test_set_does_not_retain_caller_buffer(self, store: MemoryStore, method: str) -> None: + """Writing a buffer must not alias the caller's memory. + + MemoryStore keeps whatever it is handed alive in a dict, so retaining + the caller's buffer lets a later mutation of that buffer rewrite data + already committed to the store. + """ + source = np.frombuffer(bytearray(b"\x01\x02\x03\x04"), dtype="B") + value = cpu.Buffer.from_array_like(source) + + if method == "set_sync": + store.set_sync("k", value) + else: + await getattr(store, method)("k", value) + + source[:] = 0xF # mutate the caller's memory after the write + stored = await store.get("k", prototype=default_buffer_prototype()) + assert stored is not None + assert stored.to_bytes() == b"\x01\x02\x03\x04" + + @pytest.mark.parametrize( + "pipeline", + [ + "zarr.core.codec_pipeline.BatchedCodecPipeline", + "zarr.core.codec_pipeline.FusedCodecPipeline", + ], + ) + @pytest.mark.parametrize(("shape", "chunks"), [((30,), (10,)), ((8,), (4,)), ((4,), (4,))]) + def test_write_does_not_alias_source_array( + self, pipeline: str, shape: tuple[int], chunks: tuple[int] + ) -> None: + """Mutating the source array after a write must not corrupt stored chunks. + + Without compression the encoded buffer is a zero-copy view of the + caller's array all the way down to the store, so this covers both the + single-chunk and multi-chunk write paths. + """ + with zarr.config.set({"codec_pipeline.path": pipeline}): + array = zarr.create_array( + store=MemoryStore(), shape=shape, chunks=chunks, dtype="i4", compressors=None + ) + source = np.arange(shape[0], dtype="i4") + expected = source.copy() + array[:] = source + source[:] = -1 + + np.testing.assert_array_equal(array[:], expected) + + +# TODO: fix this warning +@pytest.mark.filterwarnings("ignore:Unclosed client session:ResourceWarning") +@gpu_test +class TestGpuMemoryStore(StoreTests[GpuMemoryStore, gpu.Buffer]): + store_cls = GpuMemoryStore + buffer_cls = gpu.Buffer + + async def set(self, store: GpuMemoryStore, key: str, value: gpu.Buffer) -> None: # type: ignore[override] + store._store_dict[key] = value + + async def get(self, store: MemoryStore, key: str) -> Buffer: + return store._store_dict[key] + + @pytest.fixture(params=[None, True]) + def store_kwargs(self, request: pytest.FixtureRequest) -> dict[str, Any]: + kwargs: dict[str, Any] + if request.param is True: + kwargs = {"store_dict": {}} + else: + kwargs = {"store_dict": None} + return kwargs + + @pytest.fixture + async def store(self, store_kwargs: dict[str, Any]) -> GpuMemoryStore: + return self.store_cls(**store_kwargs) + + def test_store_repr(self, store: GpuMemoryStore) -> None: + assert str(store) == f"gpumemory://{id(store._store_dict)}" + + def test_store_supports_writes(self, store: GpuMemoryStore) -> None: + assert store.supports_writes + + def test_store_supports_listing(self, store: GpuMemoryStore) -> None: + assert store.supports_listing + + async def test_list_prefix(self, store: GpuMemoryStore) -> None: + assert True + + def test_dict_reference(self, store: GpuMemoryStore) -> None: + store_dict: dict[str, Any] = {} + result = GpuMemoryStore(store_dict=store_dict) + assert result._store_dict is store_dict + + def test_from_dict(self) -> None: + d = { + "a": gpu.Buffer.from_bytes(b"aaaa"), + "b": cpu.Buffer.from_bytes(b"bbbb"), + } + msg = "Creating a zarr.buffer.gpu.Buffer with an array that does not support the __cuda_array_interface__ for zero-copy transfers, falling back to slow copy based path" + with pytest.warns(ZarrUserWarning, match=msg): + result = GpuMemoryStore.from_dict(d) + for v in result._store_dict.values(): + assert type(v) is gpu.Buffer + + def test_set_sync_converts_to_gpu_buffer(self, store: GpuMemoryStore) -> None: + """`set_sync` must convert its value to a `gpu.Buffer`, mirroring `set`. + + `GpuMemoryStore`'s invariant is that every stored value is a + `gpu.Buffer`. Without this override, the inherited `MemoryStore.set_sync` + would store the CPU buffer it was given as-is, breaking that invariant + for whichever code path (e.g. the fused pipeline) uses the sync API. + """ + cpu_value = cpu.Buffer.from_bytes(b"aaaa") + msg = "Creating a zarr.buffer.gpu.Buffer with an array that does not support the __cuda_array_interface__ for zero-copy transfers, falling back to slow copy based path" + with pytest.warns(ZarrUserWarning, match=msg): + store.set_sync("k", cpu_value) + assert type(store._store_dict["k"]) is gpu.Buffer + + +class TestManagedMemoryStore(StoreTests[ManagedMemoryStore, cpu.Buffer]): + store_cls = ManagedMemoryStore + buffer_cls = cpu.Buffer + + async def set(self, store: ManagedMemoryStore, key: str, value: Buffer) -> None: + store._store_dict[_join_paths([store.path, key])] = value + + async def get(self, store: ManagedMemoryStore, key: str) -> Buffer: + return store._store_dict[_join_paths([store.path, key])] + + @pytest.fixture + def store_kwargs(self, request: pytest.FixtureRequest) -> dict[str, Any]: + # Use a unique name per test to avoid sharing state between tests + # but ensure the name is deterministic for equality tests + # Replace '/' with '-' since store names cannot contain '/' + # A non-empty path exercises prefix handling; a store with an + # unprefixed key in its backing dict would pass these tests + # vacuously with path="". + sanitized_name = request.node.name.replace("/", "-") + return {"name": f"test-{sanitized_name}", "path": "prefix"} + + @pytest.fixture + async def store(self, store_kwargs: dict[str, Any]) -> ManagedMemoryStore: + return self.store_cls(**store_kwargs) + + def test_store_repr(self, store: ManagedMemoryStore) -> None: + assert str(store) == _join_paths([f"memory://{store.name}", store.path]) + + async def test_serializable_store(self, store: ManagedMemoryStore) -> None: + """ + Test pickling semantics for ManagedMemoryStore. + + When pickled and unpickled within the same process (where the original + store still exists in the registry), the unpickled store reconnects to + the same backing dict. + """ + import pickle + + # Add some data to the store + await store.set("test-key", self.buffer_cls.from_bytes(b"test-value")) + + # Pickle and unpickle the store + pickled = pickle.dumps(store) + store2 = pickle.loads(pickled) + + # The unpickled store should reconnect to the same backing dict + assert store2._store_dict is store._store_dict + assert store2.name == store.name + assert store2.path == store.path + assert store2.read_only == store.read_only + + # The data should be accessible + result = await store2.get("test-key") + assert result is not None + assert result.to_bytes() == b"test-value" + + async def test_pickle_with_path(self) -> None: + """Test that path is preserved through pickle round-trip.""" + import pickle + + store = ManagedMemoryStore(name="pickle-path-test", path="some/path") + await store.set("key", self.buffer_cls.from_bytes(b"value")) + + pickled = pickle.dumps(store) + store2 = pickle.loads(pickled) + + assert store2.path == "some/path" + assert store2._store_dict is store._store_dict + + # Check that operations use the path correctly + result = await store2.get("key") + assert result is not None + assert result.to_bytes() == b"value" + + def test_pickle_after_gc(self) -> None: + """ + Test that unpickling after the original store is garbage collected + creates a new empty store with the same name (in the same process). + """ + import gc + import pickle + + # Create a store with a unique name and pickle it + store = ManagedMemoryStore(name="gc-pickle-test") + store._store_dict["key"] = self.buffer_cls.from_bytes(b"value") + pickled = pickle.dumps(store) + + # Delete the store and garbage collect + del store + gc.collect() + + # Unpickling should create a new store with an empty dict + store2 = pickle.loads(pickled) + assert store2.name == "gc-pickle-test" + # The dict is empty because the original was garbage collected + assert len(store2._store_dict) == 0 + + async def test_cross_process_detection(self) -> None: + """ + Test that unpickling a ManagedMemoryStore in a different process raises an error. + + This prevents silent data loss when a store is pickled and unpickled + in a different process (e.g., with multiprocessing). + """ + import os + + store = ManagedMemoryStore(name="cross-process-test") + await store.set("key", self.buffer_cls.from_bytes(b"value")) + + # Get the reduce tuple and modify the state to simulate a different process + cls, args, state = store.__reduce__() + state["created_pid"] = os.getpid() + 1 # Fake a different process ID + + # Manually reconstruct what pickle.loads would do + # This simulates unpickling data that was pickled in a different process + reconstructed = cls(*args) + with pytest.raises(RuntimeError, match="was created in process"): + reconstructed.__setstate__(state) + + def test_store_supports_writes(self, store: ManagedMemoryStore) -> None: + assert store.supports_writes + + def test_store_supports_listing(self, store: ManagedMemoryStore) -> None: + assert store.supports_listing + + @pytest.mark.parametrize("dtype", ["uint8", "float32", "int64"]) + @pytest.mark.parametrize("zarr_format", [2, 3]) + async def test_deterministic_size( + self, store: MemoryStore, dtype: npt.DTypeLike, zarr_format: ZarrFormat + ) -> None: + a = zarr.empty( + store=store, + shape=(3,), + chunks=(1000,), + dtype=dtype, + zarr_format=zarr_format, + overwrite=True, + ) + a[...] = 1 + a.resize((1000,)) + + np.testing.assert_array_equal(a[:3], 1) + np.testing.assert_array_equal(a[3:], 0) + + def test_from_url(self, store: ManagedMemoryStore) -> None: + """Test that from_url creates a store sharing the same dict.""" + url = str(store) + store2 = ManagedMemoryStore.from_url(url) + assert store2._store_dict is store._store_dict + + def test_from_url_with_path(self, store: ManagedMemoryStore) -> None: + """Test that from_url extracts path component from URL.""" + # Reconnect to the fixture's dict via its name, but with an empty + # path, so appending "/some/path" below yields exactly that path. + base = ManagedMemoryStore(name=store.name) + url = f"{base}/some/path" + store2 = ManagedMemoryStore.from_url(url) + assert store2._store_dict is store._store_dict + assert store2.path == "some/path" + assert str(store2) == url + + def test_from_url_invalid(self) -> None: + """Test that from_url raises ValueError for non-existent store.""" + with pytest.raises(ValueError, match="Memory store not found"): + ManagedMemoryStore.from_url("memory://nonexistent-store") + + def test_from_url_not_memory_scheme(self) -> None: + """Test that from_url raises ValueError for non-memory URLs.""" + with pytest.raises(ValueError, match="Expected a 'memory://' URL"): + ManagedMemoryStore.from_url("file:///tmp/test") + + def test_named_store(self) -> None: + """Test that stores can be created with explicit names.""" + store = ManagedMemoryStore(name="my-test-store") + assert store.name == "my-test-store" + assert str(store) == "memory://my-test-store" + + def test_named_store_shares_dict(self) -> None: + """Test that creating a store with the same name shares the dict.""" + store1 = ManagedMemoryStore(name="shared-store") + store2 = ManagedMemoryStore(name="shared-store") + assert store1._store_dict is store2._store_dict + assert store1.name == store2.name + + def test_auto_generated_name(self) -> None: + """Test that stores get auto-generated names when none provided.""" + store = ManagedMemoryStore() + assert store.name is not None + assert str(store) == f"memory://{store.name}" + + def test_with_read_only_shares_dict(self, store: ManagedMemoryStore) -> None: + """Test that with_read_only creates a store sharing the same dict.""" + store2 = store.with_read_only(True) + assert store2._store_dict is store._store_dict + assert store2.read_only is True + assert store.read_only is False + + def test_with_read_only_preserves_path(self) -> None: + """Test that with_read_only preserves the path.""" + store = ManagedMemoryStore(name="path-test", path="some/path") + store2 = store.with_read_only(True) + assert store2.path == "some/path" + assert store2._store_dict is store._store_dict + + async def test_path_prefix_operations(self) -> None: + """Test that store operations use the path prefix correctly.""" + store = ManagedMemoryStore(name="prefix-test") + store_with_path = ManagedMemoryStore.from_url("memory://prefix-test/subdir") + + # Write via store_with_path + await store_with_path.set("key", self.buffer_cls.from_bytes(b"value")) + + # The key should be stored with the prefix in the underlying dict + assert "subdir/key" in store._store_dict + assert "key" not in store._store_dict + + # Read via store_with_path should work + result = await store_with_path.get("key") + assert result is not None + assert result.to_bytes() == b"value" + + # Read via store without path should use full key + result2 = await store.get("subdir/key") + assert result2 is not None + assert result2.to_bytes() == b"value" + + async def test_path_list_operations(self) -> None: + """Test that list operations filter by path prefix.""" + store = ManagedMemoryStore(name="list-test") + + # Set up some keys at different paths + await store.set("a/key1", self.buffer_cls.from_bytes(b"v1")) + await store.set("a/key2", self.buffer_cls.from_bytes(b"v2")) + await store.set("b/key3", self.buffer_cls.from_bytes(b"v3")) + + # Create a store with path "a" + store_a = ManagedMemoryStore.from_url("memory://list-test/a") + + # list() should only return keys under "a", without the "a/" prefix + keys = [k async for k in store_a.list()] + assert sorted(keys) == ["key1", "key2"] + + async def test_path_exists(self) -> None: + """Test that exists() uses the path prefix.""" + store = ManagedMemoryStore(name="exists-test") + await store.set("prefix/key", self.buffer_cls.from_bytes(b"value")) + + store_with_path = ManagedMemoryStore.from_url("memory://exists-test/prefix") + assert await store_with_path.exists("key") + assert not await store_with_path.exists("prefix/key") + + def test_path_normalization(self) -> None: + """Test that paths are normalized.""" + store1 = ManagedMemoryStore(name="norm-test", path="a/b/") + store2 = ManagedMemoryStore(name="norm-test", path="/a/b") + store3 = ManagedMemoryStore(name="norm-test", path="a//b") + assert store1.path == "a/b" + assert store2.path == "a/b" + assert store3.path == "a/b" + + def test_name_cannot_contain_slash(self) -> None: + """Test that store names cannot contain '/'.""" + with pytest.raises(ValueError, match="cannot contain '/'"): + ManagedMemoryStore(name="foo/bar") + + def test_garbage_collection(self) -> None: + """Test that the dict is garbage collected when no stores reference it.""" + import gc + + store = ManagedMemoryStore() + url = str(store) + + # URL should resolve while store exists + store2 = ManagedMemoryStore.from_url(url) + assert store2._store_dict is store._store_dict + + # Delete both stores + del store + del store2 + gc.collect() + + # URL should no longer resolve + with pytest.raises(ValueError, match="garbage collected"): + ManagedMemoryStore.from_url(url) + + def test_sync_methods_respect_path_prefix(self) -> None: + """`get_sync`/`set_sync`/`delete_sync` must prefix keys with `self.path`, + exactly like the async `get`/`set`/`delete` methods. + + `ManagedMemoryStore` used to inherit these from `MemoryStore`, which + writes/reads the raw key. Two stores sharing a dict with different + `path` values would then cross-talk through the sync API. + """ + store = ManagedMemoryStore(name="sync-prefix-test", path="subdir") + data_buf = self.buffer_cls.from_bytes(b"value") + + store.set_sync("key", data_buf) + assert "subdir/key" in store._store_dict + assert "key" not in store._store_dict + + result = store.get_sync("key") + assert result is not None + assert result.to_bytes() == b"value" + + store.delete_sync("key") + assert "subdir/key" not in store._store_dict + + def test_fused_pipeline_respects_path_prefix(self) -> None: + """End-to-end regression: the fused pipeline's sync store fast path must + write chunks under the store's path prefix. + + `FusedCodecPipeline` uses `set_sync`/`get_sync` when a store implements + the sync protocols. If those methods skip the prefix that the async + methods apply, chunk data lands outside `self.path` and a fresh handle + re-reading through the prefix silently sees fill values instead. + """ + with zarr.config.set( + {"codec_pipeline.path": "zarr.core.codec_pipeline.FusedCodecPipeline"} + ): + store = ManagedMemoryStore(name="fused-prefix-test", path="subdir") + arr = zarr.create_array(store, shape=(4,), chunks=(4,), dtype="uint8", zarr_format=3) + arr[:] = np.arange(4, dtype="uint8") + + bad_keys = [k for k in store._store_dict if not k.startswith("subdir/")] + assert bad_keys == [], f"keys written outside the store's path prefix: {bad_keys}" + + store2 = ManagedMemoryStore.from_url("memory://fused-prefix-test/subdir") + arr2 = zarr.open_array(store2, mode="r") + np.testing.assert_array_equal(arr2[:], np.arange(4, dtype="uint8")) diff --git a/tests/test_store/test_object.py b/tests/test_store/test_object.py new file mode 100644 index 0000000000..1ea148b3c3 --- /dev/null +++ b/tests/test_store/test_object.py @@ -0,0 +1,141 @@ +import re +from pathlib import Path +from typing import TypedDict + +import pytest + +obstore = pytest.importorskip("obstore") + +from hypothesis.stateful import ( + run_state_machine_as_test, +) +from obstore.store import LocalStore, MemoryStore, S3Store + +from zarr.core.buffer import Buffer, cpu +from zarr.core.sync import _collect_aiterator +from zarr.storage import ObjectStore +from zarr.testing.stateful import ZarrHierarchyStateMachine +from zarr.testing.store import StoreTests + + +class StoreKwargs(TypedDict): + store: LocalStore + read_only: bool + + +class TestObjectStore(StoreTests[ObjectStore[LocalStore], cpu.Buffer]): + # store_cls is needed to do an isinstance check, so can't be a subscripted generic + store_cls = ObjectStore # type: ignore[assignment] + buffer_cls = cpu.Buffer + + @pytest.fixture + def store_kwargs(self, tmp_path: Path) -> StoreKwargs: + store = LocalStore(prefix=tmp_path) + return {"store": store, "read_only": False} + + @pytest.fixture + def store(self, store_kwargs: StoreKwargs) -> ObjectStore[LocalStore]: + return self.store_cls(**store_kwargs) + + async def get(self, store: ObjectStore[LocalStore], key: str) -> Buffer: + assert isinstance(store.store, LocalStore) + new_local_store = LocalStore(prefix=store.store.prefix) + return self.buffer_cls.from_bytes(obstore.get(new_local_store, key).bytes()) + + async def set(self, store: ObjectStore[LocalStore], key: str, value: Buffer) -> None: + assert isinstance(store.store, LocalStore) + new_local_store = LocalStore(prefix=store.store.prefix) + obstore.put(new_local_store, key, value.to_bytes()) + + def test_store_repr(self, store: ObjectStore[LocalStore]) -> None: + from fnmatch import fnmatch + + pattern = "ObjectStore(object_store://LocalStore(*))" + assert fnmatch(f"{store!r}", pattern) + + def test_store_supports_writes(self, store: ObjectStore[LocalStore]) -> None: + assert store.supports_writes + + def test_store_supports_partial_writes(self, store: ObjectStore[LocalStore]) -> None: + assert not store.supports_partial_writes + + def test_store_supports_listing(self, store: ObjectStore[LocalStore]) -> None: + assert store.supports_listing + + def test_store_equal(self, store: ObjectStore[LocalStore]) -> None: + """Test store equality""" + # Test equality against a different instance type + assert store != 0 + # Test equality against a different store type + new_memory_store = ObjectStore(MemoryStore()) + assert store != new_memory_store + # Test equality against a read only store + assert isinstance(store.store, LocalStore) + new_local_store = ObjectStore(LocalStore(prefix=store.store.prefix), read_only=True) + assert store != new_local_store + # Test two memory stores cannot be equal + second_memory_store = ObjectStore(MemoryStore()) + assert new_memory_store != second_memory_store + + def test_store_init_raises(self) -> None: + """Test __init__ raises appropriate error for improper store type""" + with pytest.raises(TypeError): + ObjectStore("path/to/store") # type: ignore[type-var] + + async def test_store_getsize(self, store: ObjectStore[LocalStore]) -> None: + buf = cpu.Buffer.from_bytes(b"\x01\x02\x03\x04") + await self.set(store, "key", buf) + size = await store.getsize("key") + assert size == len(buf) + + async def test_store_getsize_prefix(self, store: ObjectStore[LocalStore]) -> None: + buf = cpu.Buffer.from_bytes(b"\x01\x02\x03\x04") + await self.set(store, "c/key1/0", buf) + await self.set(store, "c/key2/0", buf) + size = await store.getsize_prefix("c/key1") + assert size == len(buf) + total_size = await store.getsize_prefix("c") + assert total_size == len(buf) * 2 + + +@pytest.mark.filterwarnings( + re.escape("ignore:datetime.datetime.utcnow() is deprecated:DeprecationWarning") +) +async def test_list_dir_ignores_s3_prefix_marker(moto_server: str) -> None: + """Ensure obstore's exact-prefix S3 directory marker is not listed as a child.""" + boto3 = pytest.importorskip("boto3") + bucket = "object-store-prefix-marker" + client = boto3.client( + "s3", + endpoint_url=moto_server, + region_name="us-east-1", + aws_access_key_id="x", + aws_secret_access_key="x", + ) + client.create_bucket(Bucket=bucket) + client.put_object(Bucket=bucket, Key="g/", Body=b"") + + store = ObjectStore( + S3Store( + bucket=bucket, + endpoint=moto_server, + region="us-east-1", + access_key_id="x", + secret_access_key="x", + client_options={"allow_http": True}, + virtual_hosted_style_request=False, + ) + ) + + assert await _collect_aiterator(store.list_dir("g")) == () + assert await _collect_aiterator(store.list_dir("g/")) == () + + +@pytest.mark.slow_hypothesis +def test_zarr_hierarchy() -> None: + sync_store = ObjectStore(MemoryStore()) + + def mk_test_instance_sync() -> ZarrHierarchyStateMachine: + return ZarrHierarchyStateMachine(sync_store) + + run_state_machine_as_test(mk_test_instance_sync) # type: ignore[no-untyped-call] diff --git a/tests/test_store/test_stateful.py b/tests/test_store/test_stateful.py new file mode 100644 index 0000000000..82b482d0ff --- /dev/null +++ b/tests/test_store/test_stateful.py @@ -0,0 +1,51 @@ +# Stateful tests for arbitrary Zarr stores. +from collections.abc import Generator + +import pytest +from hypothesis.stateful import ( + run_state_machine_as_test, +) + +import zarr +from zarr.abc.store import Store +from zarr.storage import LocalStore, ZipStore +from zarr.testing.stateful import ZarrHierarchyStateMachine, ZarrStoreStateMachine + +pytestmark = [ + pytest.mark.slow_hypothesis, + # TODO: work out where this warning is coming from and fix + pytest.mark.filterwarnings("ignore:Unclosed client session:ResourceWarning"), +] + + +@pytest.fixture(autouse=True) +def _enable_rectilinear_chunks() -> Generator[None, None, None]: + """Enable rectilinear chunks since strategies may generate them.""" + with zarr.config.set({"array.rectilinear_chunks": True}): + yield + + +@pytest.mark.filterwarnings("ignore::zarr.core.dtype.common.UnstableSpecificationWarning") +def test_zarr_hierarchy(sync_store: Store) -> None: + def mk_test_instance_sync() -> ZarrHierarchyStateMachine: + return ZarrHierarchyStateMachine(sync_store) + + if isinstance(sync_store, ZipStore): + pytest.skip(reason="ZipStore does not support delete") + + run_state_machine_as_test(mk_test_instance_sync) # type: ignore[no-untyped-call] + + +def test_zarr_store(sync_store: Store) -> None: + def mk_test_instance_sync() -> ZarrStoreStateMachine: + return ZarrStoreStateMachine(sync_store) + + if isinstance(sync_store, ZipStore): + pytest.skip(reason="ZipStore does not support delete") + + if isinstance(sync_store, LocalStore): + # This test uses arbitrary keys, which are passed to `set` and `delete`. + # It assumes that `set` and `delete` are the only two operations that modify state. + # But LocalStore, directories can hang around even after a key is delete-d. + pytest.skip(reason="Test isn't suitable for LocalStore.") + run_state_machine_as_test(mk_test_instance_sync) # type: ignore[no-untyped-call] diff --git a/tests/test_store/test_utils.py b/tests/test_store/test_utils.py new file mode 100644 index 0000000000..291526fab8 --- /dev/null +++ b/tests/test_store/test_utils.py @@ -0,0 +1,128 @@ +from __future__ import annotations + +import sys +from unittest.mock import patch + +import pytest + +from zarr.abc.store import SuffixByteRequest +from zarr.core.buffer.core import default_buffer_prototype +from zarr.storage._utils import ParsedStoreUrl, _normalize_byte_range_index, parse_store_url + + +class TestParseStoreUrl: + """Tests for parse_store_url.""" + + def test_memory_url(self) -> None: + result = parse_store_url("memory://mystore") + assert result == ParsedStoreUrl( + scheme="memory", name="mystore", path="", raw="memory://mystore" + ) + + def test_memory_url_with_path(self) -> None: + result = parse_store_url("memory://mystore/path/to/data") + assert result == ParsedStoreUrl( + scheme="memory", + name="mystore", + path="path/to/data", + raw="memory://mystore/path/to/data", + ) + + def test_memory_url_no_name(self) -> None: + result = parse_store_url("memory://") + assert result.scheme == "memory" + assert result.name is None + + def test_s3_url(self) -> None: + result = parse_store_url("s3://bucket/key") + assert result == ParsedStoreUrl( + scheme="s3", name="bucket", path="key", raw="s3://bucket/key" + ) + + def test_file_url(self) -> None: + result = parse_store_url("file:///tmp/test") + assert result.scheme == "file" + + def test_local_absolute_path(self) -> None: + result = parse_store_url("/local/path") + assert result == ParsedStoreUrl(scheme="", name=None, path="/local/path", raw="/local/path") + + def test_local_relative_path(self) -> None: + result = parse_store_url("relative/path") + assert result == ParsedStoreUrl( + scheme="", name=None, path="relative/path", raw="relative/path" + ) + + @pytest.mark.parametrize( + "url", + [ + "C:\\Users\\foo", + "C:/Users/foo", + "D:/data/zarr", + "c:/test", + ], + ) + def test_windows_drive_letter(self, url: str) -> None: + """On Windows, bare drive-letter paths must be treated as local paths.""" + with patch.object(sys, "platform", "win32"): + result = parse_store_url(url) + assert result.scheme == "" + assert result.name is None + assert result.path == url + assert result.raw == url + + @pytest.mark.parametrize( + "url", + [ + "file:///C:/Users/foo", + "file://C:/Users/foo", + ], + ) + def test_file_url_with_drive_letter_on_windows(self, url: str) -> None: + """file:// URLs with drive letters are not treated as bare paths.""" + with patch.object(sys, "platform", "win32"): + result = parse_store_url(url) + assert result.scheme == "file" + + @pytest.mark.parametrize( + "url", + [ + "C:\\Users\\foo", + "C:/Users/foo", + ], + ) + def test_drive_letter_not_special_on_non_windows(self, url: str) -> None: + """On non-Windows platforms, drive-letter paths go through urlparse.""" + with patch.object(sys, "platform", "linux"): + result = parse_store_url(url) + # urlparse interprets the drive letter as a scheme + assert result.scheme == "c" + + +class TestNormalizeByteRangeIndex: + """Tests for _normalize_byte_range_index.""" + + def test_suffix_larger_than_data_returns_all_bytes(self) -> None: + """Regression: SuffixByteRequest with suffix > len(data) must not produce a + negative start index that causes numpy to return fewer bytes than available.""" + prototype = default_buffer_prototype() + data = prototype.buffer.from_bytes(b"hello") # 5 bytes + byte_range = SuffixByteRequest(suffix=7) + start, stop = _normalize_byte_range_index(data, byte_range) + assert start == 0, f"start should be 0 (clamped), got {start}" + result = data[start:stop] + assert len(result) == 5, f"expected all 5 bytes, got {len(result)}" + + def test_suffix_exact_length(self) -> None: + """SuffixByteRequest with suffix == len(data) returns all bytes.""" + prototype = default_buffer_prototype() + data = prototype.buffer.from_bytes(b"hello") + start, _stop = _normalize_byte_range_index(data, SuffixByteRequest(suffix=5)) + assert start == 0 + + def test_suffix_shorter_than_data(self) -> None: + """SuffixByteRequest with suffix < len(data) returns the last n bytes.""" + prototype = default_buffer_prototype() + data = prototype.buffer.from_bytes(b"hello") + start, _stop = _normalize_byte_range_index(data, SuffixByteRequest(suffix=3)) + assert start == 2 diff --git a/tests/test_store/test_wrapper.py b/tests/test_store/test_wrapper.py new file mode 100644 index 0000000000..e556a108c5 --- /dev/null +++ b/tests/test_store/test_wrapper.py @@ -0,0 +1,169 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, TypedDict + +import pytest + +from zarr.abc.store import ByteRequest, Store, _store_supports_sync_io +from zarr.core.buffer import Buffer +from zarr.core.buffer.cpu import Buffer as CPUBuffer +from zarr.core.buffer.cpu import buffer_prototype +from zarr.storage import LocalStore, MemoryStore, WrapperStore, ZipStore +from zarr.testing.store import LatencyStore, StoreTests + +if TYPE_CHECKING: + from pathlib import Path + + from zarr.core.buffer.core import BufferPrototype + + +class StoreKwargs(TypedDict): + store: LocalStore + + +class OpenKwargs(TypedDict): + store_cls: type[LocalStore] + root: str + + +# TODO: fix this warning +@pytest.mark.filterwarnings( + "ignore:coroutine 'ClientCreatorContext.__aexit__' was never awaited:RuntimeWarning" +) +class TestWrapperStore(StoreTests[WrapperStore[Any], Buffer]): + store_cls = WrapperStore + buffer_cls = CPUBuffer + + async def get(self, store: WrapperStore[LocalStore], key: str) -> Buffer: + return self.buffer_cls.from_bytes((store._store.root / key).read_bytes()) + + async def set(self, store: WrapperStore[LocalStore], key: str, value: Buffer) -> None: + parent = (store._store.root / key).parent + if not parent.exists(): + parent.mkdir(parents=True) + (store._store.root / key).write_bytes(value.to_bytes()) + + @pytest.fixture + def store_kwargs(self, tmp_path: Path) -> StoreKwargs: + return {"store": LocalStore(str(tmp_path))} + + @pytest.fixture + def open_kwargs(self, tmp_path: Path) -> OpenKwargs: + return {"store_cls": LocalStore, "root": str(tmp_path)} + + def test_store_supports_writes(self, store: WrapperStore[LocalStore]) -> None: + assert store.supports_writes + + def test_store_supports_listing(self, store: WrapperStore[LocalStore]) -> None: + assert store.supports_listing + + def test_store_repr(self, store: WrapperStore[LocalStore]) -> None: + assert f"{store!r}" == f"WrapperStore(LocalStore, 'file://{store._store.root.as_posix()}')" + + def test_store_str(self, store: WrapperStore[LocalStore]) -> None: + assert str(store) == f"wrapping-file://{store._store.root.as_posix()}" + + def test_check_writeable(self, store: WrapperStore[LocalStore]) -> None: + """ + Test _check_writeable() runs without errors. + """ + store._check_writable() + + def test_close(self, store: WrapperStore[LocalStore]) -> None: + "Test store can be closed" + store.close() + assert not store._is_open + + def test_is_open_setter_raises(self, store: WrapperStore[LocalStore]) -> None: + """ + Test that a user cannot change `_is_open` without opening the underlying store. + """ + with pytest.raises( + NotImplementedError, match="WrapperStore must be opened via the `_open` method" + ): + store._is_open = True + + +# TODO: work out where warning is coming from and fix +@pytest.mark.filterwarnings( + "ignore:coroutine 'ClientCreatorContext.__aexit__' was never awaited:RuntimeWarning" +) +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=True) +async def test_wrapped_set(store: Store, capsys: pytest.CaptureFixture[str]) -> None: + # define a class that prints when it sets + class NoisySetter(WrapperStore[Store]): + async def set(self, key: str, value: Buffer) -> None: + print(f"setting {key}") + await super().set(key, value) + + key = "foo" + value = CPUBuffer.from_bytes(b"bar") + store_wrapped = NoisySetter(store) + await store_wrapped.set(key, value) + captured = capsys.readouterr() + assert f"setting {key}" in captured.out + assert await store_wrapped.get(key, buffer_prototype) == value + + +@pytest.mark.filterwarnings("ignore:Unclosed client session:ResourceWarning") +@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=True) +async def test_wrapped_get(store: Store, capsys: pytest.CaptureFixture[str]) -> None: + # define a class that prints when it sets + class NoisyGetter(WrapperStore[Any]): + async def get( + self, key: str, prototype: BufferPrototype, byte_range: ByteRequest | None = None + ) -> None: + print(f"getting {key}") + await super().get(key, prototype=prototype, byte_range=byte_range) + + key = "foo" + value = CPUBuffer.from_bytes(b"bar") + store_wrapped = NoisyGetter(store) + await store_wrapped.set(key, value) + await store_wrapped.get(key, buffer_prototype) + captured = capsys.readouterr() + assert f"getting {key}" in captured.out + + +@pytest.mark.parametrize( + ("store_factory", "expected"), + [ + (lambda tmp: MemoryStore(), True), + (lambda tmp: LocalStore(str(tmp)), True), + (lambda tmp: WrapperStore(MemoryStore()), True), + (lambda tmp: LatencyStore(MemoryStore()), True), + (lambda tmp: ZipStore(tmp / "store.zip", mode="w"), False), + (lambda tmp: WrapperStore(ZipStore(tmp / "store.zip", mode="w")), False), + ], + ids=[ + "memory", + "local", + "wrapper-of-memory", + "latency-wrapper-of-memory", + "zip", + "wrapper-of-zip", + ], +) +def test_supports_sync_io(store_factory: Any, expected: bool, tmp_path: Path | Any) -> None: + """`_store_supports_sync_io` is True only for stores implementing the full + sync surface (get_sync + set_sync + delete_sync); wrappers forward the + wrapped store's capability via `_supports_sync_io`.""" + assert _store_supports_sync_io(store_factory(tmp_path)) is expected + + +def test_wrapper_get_sync_without_inner_sync_raises(tmp_path: Any) -> None: + store = WrapperStore(ZipStore(tmp_path / "store.zip", mode="w")) + with pytest.raises(TypeError, match="does not support synchronous get"): + store.get_sync("key") + + +def test_wrapper_set_sync_without_inner_sync_raises(tmp_path: Any) -> None: + store = WrapperStore(ZipStore(tmp_path / "store.zip", mode="w")) + with pytest.raises(TypeError, match="does not support synchronous set"): + store.set_sync("key", CPUBuffer.from_bytes(b"data")) + + +def test_wrapper_delete_sync_without_inner_sync_raises(tmp_path: Any) -> None: + store = WrapperStore(ZipStore(tmp_path / "store.zip", mode="w")) + with pytest.raises(TypeError, match="does not support synchronous delete"): + store.delete_sync("key") diff --git a/tests/test_store/test_zip.py b/tests/test_store/test_zip.py new file mode 100644 index 0000000000..32b18c5273 --- /dev/null +++ b/tests/test_store/test_zip.py @@ -0,0 +1,409 @@ +from __future__ import annotations + +import io +import os +import pickle +import shutil +import tempfile +import zipfile +from typing import TYPE_CHECKING + +import numpy as np +import pytest +from hypothesis import settings +from hypothesis.stateful import ( + RuleBasedStateMachine, + initialize, + precondition, + rule, + run_state_machine_as_test, +) + +import zarr +from zarr import create_array +from zarr.core.buffer import Buffer, cpu, default_buffer_prototype +from zarr.core.sync import sync +from zarr.storage import ZipStore +from zarr.testing.store import StoreTests + +if TYPE_CHECKING: + from pathlib import Path + from typing import Any + + +# TODO: work out where this is coming from and fix +pytestmark = [ + pytest.mark.filterwarnings( + "ignore:coroutine method 'aclose' of 'ZipStore.list' was never awaited:RuntimeWarning" + ) +] + + +class TestZipStore(StoreTests[ZipStore, cpu.Buffer]): + store_cls = ZipStore + buffer_cls = cpu.Buffer + + @pytest.fixture + def store_kwargs(self) -> dict[str, str | bool]: + fd, temp_path = tempfile.mkstemp() + os.close(fd) + os.unlink(temp_path) + + return {"path": temp_path, "mode": "w", "read_only": False} + + async def get(self, store: ZipStore, key: str) -> Buffer: + buf = store._get(key, prototype=default_buffer_prototype()) + assert buf is not None + return buf + + async def set(self, store: ZipStore, key: str, value: Buffer) -> None: + return store._set(key, value) + + def test_store_read_only(self, store: ZipStore) -> None: + assert not store.read_only + + async def test_read_only_store_raises(self, store_kwargs: dict[str, Any]) -> None: + # we need to create the zipfile in write mode before switching to read mode + store = await self.store_cls.open(**store_kwargs) + store.close() + + kwargs = {**store_kwargs, "mode": "a", "read_only": True} + store = await self.store_cls.open(**kwargs) + assert store._zmode == "a" + assert store.read_only + + # set + with pytest.raises(ValueError): + await store.set("foo", cpu.Buffer.from_bytes(b"bar")) + + def test_store_repr(self, store: ZipStore) -> None: + assert str(store) == f"zip://{store.path}" + + def test_store_supports_writes(self, store: ZipStore) -> None: + assert store.supports_writes + + def test_store_supports_listing(self, store: ZipStore) -> None: + assert store.supports_listing + + # TODO: fix this warning + @pytest.mark.filterwarnings("ignore:Unclosed client session:ResourceWarning") + def test_api_integration(self, store: ZipStore) -> None: + root = zarr.open_group(store=store, mode="a") + + data = np.arange(10000, dtype=np.uint16).reshape(100, 100) + z = root.create_array( + shape=data.shape, chunks=(10, 10), name="foo", dtype=np.uint16, fill_value=99 + ) + z[:] = data + + assert np.array_equal(data, z[:]) + + # you can overwrite existing chunks but zipfile will issue a warning + with pytest.warns(UserWarning, match="Duplicate name: 'foo/c/0/0'"): + z[0, 0] = 100 + + # TODO: assigning an entire chunk to fill value ends up deleting the chunk which is not supported + # a work around will be needed here. + with pytest.raises(NotImplementedError): + z[0:10, 0:10] = 99 + + bar = root.create_group("bar", attributes={"hello": "world"}) + assert "hello" in dict(bar.attrs) + + # keys cannot be deleted + with pytest.raises(NotImplementedError): + del root["bar"] + + store.close() + + @pytest.mark.parametrize("read_only", [True, False]) + async def test_store_open_read_only( + self, store_kwargs: dict[str, Any], read_only: bool + ) -> None: + if read_only: + # create an empty zipfile + with zipfile.ZipFile(store_kwargs["path"], mode="w"): + pass + + await super().test_store_open_read_only(store_kwargs, read_only) + + @pytest.mark.parametrize(("zip_mode", "read_only"), [("w", False), ("a", False), ("x", False)]) + async def test_zip_open_mode_translation( + self, store_kwargs: dict[str, Any], zip_mode: str, read_only: bool + ) -> None: + kws = {**store_kwargs, "mode": zip_mode} + store = await self.store_cls.open(**kws) + assert store.read_only == read_only + + def test_externally_zipped_store(self, tmp_path: Path) -> None: + # See: https://github.com/zarr-developers/zarr-python/issues/2757 + zarr_path = tmp_path / "foo.zarr" + root = zarr.open_group(store=zarr_path, mode="w") + root.require_group("foo") + foo = root.get_group("foo") + foo["bar"] = np.array([1]) + shutil.make_archive(str(zarr_path), "zip", zarr_path) + zip_path = tmp_path / "foo.zarr.zip" + zipped = zarr.open_group(ZipStore(zip_path, mode="r"), mode="r") + assert list(zipped.keys()) == list(root.keys()) + group = zipped.get_group("foo") + assert list(group.keys()) == list(group.keys()) + + async def test_list_without_explicit_open(self, tmp_path: Path) -> None: + # ZipStore.list(), list_dir(), and exists() should auto-open + # the zip file just like _get() and _set() do. + zip_path = tmp_path / "data.zip" + zarr_path = tmp_path / "foo.zarr" + root = zarr.open_group(store=zarr_path, mode="w") + root["x"] = np.array([1, 2, 3]) + shutil.make_archive(str(zarr_path), "zip", zarr_path) + shutil.move(f"{zarr_path}.zip", zip_path) + + store = ZipStore(zip_path, mode="r") + assert not store._is_open + + keys = [k async for k in store.list()] + assert len(keys) > 0 + + store2 = ZipStore(zip_path, mode="r") + assert not store2._is_open + assert await store2.exists(keys[0]) + + store3 = ZipStore(zip_path, mode="r") + assert not store3._is_open + dir_keys = [k async for k in store3.list_dir("")] + assert len(dir_keys) > 0 + + async def test_move(self, tmp_path: Path) -> None: + origin = tmp_path / "origin.zip" + destination = tmp_path / "some_folder" / "destination.zip" + + store = await ZipStore.open(path=origin, mode="a") + array = create_array(store, data=np.arange(10)) + + await store.move(str(destination)) + + assert store.path == destination + assert destination.exists() + assert not origin.exists() + assert np.array_equal(array[...], np.arange(10)) + + +class TestZipStoreFileObj: + """ZipStore backed by an open binary file-like object instead of a path.""" + + @pytest.fixture + def zip_bytes(self, tmp_path: Path) -> bytes: + path = tmp_path / "data.zip" + store = ZipStore(path, mode="w") + zarr.create_array(store, data=np.arange(10), chunks=(5,)) + store.close() + return path.read_bytes() + + def test_read_from_fileobj(self, zip_bytes: bytes) -> None: + # an existing archive can be read through any seekable binary reader + store = ZipStore(io.BytesIO(zip_bytes), mode="r") + array = zarr.open_array(store, mode="r") + assert np.array_equal(array[...], np.arange(10)) + assert store.path is None + + def test_write_to_fileobj(self) -> None: + # a writable file object receives the archive; the bytes it holds + # after close() are a complete, reopenable zip + buffer = io.BytesIO() + store = ZipStore(buffer, mode="w", read_only=False) + zarr.create_array(store, data=np.arange(4)) + store.close() + + roundtrip = ZipStore(io.BytesIO(buffer.getvalue()), mode="r") + array = zarr.open_array(roundtrip, mode="r") + assert np.array_equal(array[...], np.arange(4)) + + async def test_clear_unsupported(self, zip_bytes: bytes) -> None: + # clear() requires a filesystem location, so it raises a clear error + # for file-object-backed stores + store = ZipStore(io.BytesIO(zip_bytes), mode="a", read_only=False) + store._sync_open() + with pytest.raises(NotImplementedError, match="clear.*file-like"): + await store.clear() + + async def test_move_unsupported(self, zip_bytes: bytes) -> None: + # move() requires a filesystem location, so it raises a clear error + # for file-object-backed stores + store = ZipStore(io.BytesIO(zip_bytes), mode="a", read_only=False) + store._sync_open() + with pytest.raises(NotImplementedError, match="move.*file-like"): + await store.move("elsewhere.zip") + + def test_invalid_file_object_rejected(self) -> None: + # objects without read/seek/tell are rejected at construction, not + # deep inside zipfile + with pytest.raises(TypeError, match="read/seek/tell"): + ZipStore(42, mode="r") # type: ignore[arg-type] + + @pytest.mark.parametrize("mode", ["w", "a", "x"]) + def test_non_iobase_reader_write_modes_rejected(self, zip_bytes: bytes, mode: str) -> None: + # readers that are not io.IOBase instances are adapted for reading + # only; write modes are rejected at construction with a clear error + class MinimalReader: + def __init__(self, data: bytes) -> None: + self._buffer = io.BytesIO(data) + + def read(self, size: int, /) -> bytes: + return self._buffer.read(size) + + def seek(self, pos: int, whence: int = 0, /) -> int: + return self._buffer.seek(pos, whence) + + def tell(self) -> int: + return self._buffer.tell() + + with pytest.raises(TypeError, match="opened for reading"): + ZipStore(MinimalReader(zip_bytes), mode=mode, read_only=False) # type: ignore[arg-type] + + def test_fsspec_file(self, tmp_path: Path, zip_bytes: bytes) -> None: + # a file opened through fsspec (already an io.IOBase) is used directly; + # fsspec's local filesystem stands in for a remote one + fsspec = pytest.importorskip("fsspec") + + path = tmp_path / "fsspec.zip" + path.write_bytes(zip_bytes) + with fsspec.open(f"local://{path}", "rb") as fileobj: + store = ZipStore(fileobj, mode="r") + array = zarr.open_array(store, mode="r") + assert np.array_equal(array[...], np.arange(10)) + assert store.path is None + + def test_obstore_reader(self, tmp_path: Path, zip_bytes: bytes) -> None: + # obstore's ReadableFile is not an io.IOBase and its read() returns a + # buffer-protocol object; ZipStore adapts it via _RawReaderAdapter + obstore = pytest.importorskip("obstore") + from obstore.store import LocalStore as ObstoreLocalStore + + (tmp_path / "obstore.zip").write_bytes(zip_bytes) + reader = obstore.open_reader(ObstoreLocalStore(str(tmp_path)), "obstore.zip") + store = ZipStore(reader, mode="r") + array = zarr.open_array(store, mode="r") + assert np.array_equal(array[...], np.arange(10)) + + def test_raw_reader_adapter_eof(self) -> None: + from zarr.storage._zip import _RawReaderAdapter + + class MinimalReader: + """Non-io.IOBase reader exposing only read/seek/tell, like obstore.""" + + def __init__(self, data: bytes) -> None: + self._buffer = io.BytesIO(data) + + def read(self, size: int, /) -> bytes: + return self._buffer.read(size) + + def seek(self, pos: int, whence: int = 0, /) -> int: + return self._buffer.seek(pos, whence) + + def tell(self) -> int: + return self._buffer.tell() + + # the adapter must clamp reads to EOF: some readers (obstore < 0.6) + # raise on short reads instead of returning fewer bytes + data = b"0123456789" + adapter = _RawReaderAdapter(MinimalReader(data)) # type: ignore[arg-type] + + # A read straddling EOF returns only the remaining bytes. + adapter.seek(len(data) - 3) + buf = bytearray(8) + assert adapter.readinto(buf) == 3 + assert bytes(buf[:3]) == data[-3:] + + # A read at EOF returns 0. + assert adapter.tell() == len(data) + assert adapter.readinto(bytearray(8)) == 0 + + def test_pickle_fileobj_raises(self, zip_bytes: bytes) -> None: + # an open file object cannot be reliably serialized, so pickling a + # file-object-backed store raises with a pointer at the alternative + store = ZipStore(io.BytesIO(zip_bytes), mode="r") + with pytest.raises(TypeError, match="cannot pickle a ZipStore backed by a file-like"): + pickle.dumps(store) + + def test_pickle_path_backed_roundtrip(self, tmp_path: Path, zip_bytes: bytes) -> None: + # path-backed stores remain picklable: the path is serialized and the + # archive is reopened on unpickling + path = tmp_path / "pickled.zip" + path.write_bytes(zip_bytes) + store = ZipStore(path, mode="r") + unpickled = pickle.loads(pickle.dumps(store)) + array = zarr.open_array(unpickled, mode="r") + assert np.array_equal(array[...], np.arange(10)) + + def test_str_and_eq(self, zip_bytes: bytes) -> None: + # file-object-backed stores stringify with the object repr and + # compare equal only when backed by the very same file object + fileobj = io.BytesIO(zip_bytes) + store = ZipStore(fileobj, mode="r") + assert str(store).startswith("zip://<") + assert store == ZipStore(fileobj, mode="r") + assert store != ZipStore(io.BytesIO(zip_bytes), mode="r") + + +class ZipStoreLifecycleMachine(RuleBasedStateMachine): + """Drive a ZipStore through construct / open / write / close transitions. + + Invariant under test: a constructed ZipStore can always be closed without + raising, regardless of whether it was ever opened or did any I/O. This is a + property-based generalization of the former example-based regression tests + for ZipStore.close() being called on a never-opened store (which raised + AttributeError because ``_lock`` is created lazily in ``_sync_open``). + """ + + def __init__(self, tmp_path: Path) -> None: + super().__init__() + self._tmp_path = tmp_path + self._counter = 0 + self.store: ZipStore | None = None + self._opened = False + + @initialize() + def start(self) -> None: + self.store = None + self._opened = False + + @precondition(lambda self: self.store is None) + @rule() + def construct(self) -> None: + # Fresh path each time so mode="w" never clobbers a closed archive. + self._counter += 1 + self.store = ZipStore(self._tmp_path / f"s{self._counter}.zip", mode="w") + self._opened = False + + @precondition(lambda self: self.store is not None and not self._opened) + @rule() + def open(self) -> None: + assert self.store is not None + self.store._sync_open() + self._opened = True + + @precondition(lambda self: self.store is not None and not self._opened) + @rule() + def write(self) -> None: + assert self.store is not None + # store.set auto-opens the store. + sync(self.store.set("a", cpu.Buffer.from_bytes(b"hi"))) + self._opened = True + + @precondition(lambda self: self.store is not None) + @rule() + def close(self) -> None: + assert self.store is not None + # The property under test: close() must never raise, even with no + # prior open or I/O. + self.store.close() + self.store = None + self._opened = False + + +def test_zipstore_close_lifecycle(tmp_path: Path) -> None: + run_state_machine_as_test( # type: ignore[no-untyped-call] + lambda: ZipStoreLifecycleMachine(tmp_path), + settings=settings(max_examples=50, deadline=None), + ) diff --git a/tests/test_sync.py b/tests/test_sync.py new file mode 100644 index 0000000000..c5eadb0f4f --- /dev/null +++ b/tests/test_sync.py @@ -0,0 +1,165 @@ +import asyncio +from collections.abc import AsyncGenerator +from unittest.mock import AsyncMock, patch + +import pytest + +import zarr +from zarr.core.sync import ( + SyncError, + SyncMixin, + _get_executor, + _get_lock, + _get_loop, + cleanup_resources, + loop, + sync, +) + + +@pytest.fixture(params=[True, False]) +def sync_loop(request: pytest.FixtureRequest) -> asyncio.AbstractEventLoop | None: + if request.param is True: + return _get_loop() + else: + return None + + +@pytest.fixture +def clean_state(): + # use this fixture to make sure no existing threads/loops exist in zarr.core.sync + cleanup_resources() + yield + cleanup_resources() + + +def test_get_loop() -> None: + # test that calling _get_loop() twice returns the same loop + loop = _get_loop() + loop2 = _get_loop() + assert loop is loop2 + + +def test_get_lock() -> None: + # test that calling _get_lock() twice returns the same lock + lock = _get_lock() + lock2 = _get_lock() + assert lock is lock2 + + +def test_sync(sync_loop: asyncio.AbstractEventLoop | None) -> None: + foo = AsyncMock(return_value="foo") + assert sync(foo(), loop=sync_loop) == "foo" + foo.assert_awaited_once() + + +def test_sync_raises(sync_loop: asyncio.AbstractEventLoop | None) -> None: + foo = AsyncMock(side_effect=ValueError("foo-bar")) + with pytest.raises(ValueError, match="foo-bar"): + sync(foo(), loop=sync_loop) + foo.assert_awaited_once() + + +def test_sync_timeout() -> None: + duration = 0.02 + + async def foo() -> None: + await asyncio.sleep(duration) + + with pytest.raises(asyncio.TimeoutError): + sync(foo(), timeout=duration / 10) + + +def test_sync_raises_if_no_coroutine(sync_loop: asyncio.AbstractEventLoop | None) -> None: + def foo() -> str: + return "foo" + + with pytest.raises(TypeError): + sync(foo(), loop=sync_loop) # type: ignore[arg-type] + + +@pytest.mark.filterwarnings("ignore:coroutine.*was never awaited") +def test_sync_raises_if_loop_is_closed() -> None: + loop = _get_loop() + + foo = AsyncMock(return_value="foo") + with patch.object(loop, "is_closed", return_value=True): + with pytest.raises(RuntimeError): + sync(foo(), loop=loop) + foo.assert_not_awaited() + + +@pytest.mark.filterwarnings("ignore:Unclosed client session:ResourceWarning") +@pytest.mark.filterwarnings("ignore:coroutine.*was never awaited") +def test_sync_raises_if_calling_sync_from_within_a_running_loop( + sync_loop: asyncio.AbstractEventLoop | None, +) -> None: + def foo() -> str: + # technically, this should be an async function but doing that + # yields a warning because it is never awaited by the inner function + return "foo" + + async def bar() -> str: + return sync(foo(), loop=sync_loop) # type: ignore[arg-type] + + with pytest.raises(SyncError): + sync(bar(), loop=sync_loop) + + +@pytest.mark.filterwarnings("ignore:coroutine.*was never awaited") +def test_sync_raises_if_loop_is_invalid_type() -> None: + foo = AsyncMock(return_value="foo") + with pytest.raises(TypeError): + sync(foo(), loop=1) # type: ignore[arg-type] + foo.assert_not_awaited() + + +def test_sync_mixin(sync_loop) -> None: + class AsyncFoo: + def __init__(self) -> None: + pass + + async def foo(self) -> str: + return "foo" + + async def bar(self) -> AsyncGenerator: + for i in range(10): + yield i + + class SyncFoo(SyncMixin): + def __init__(self, async_foo: AsyncFoo) -> None: + self._async_foo = async_foo + + def foo(self) -> str: + return self._sync(self._async_foo.foo()) + + def bar(self) -> list[int]: + return self._sync_iter(self._async_foo.bar()) + + async_foo = AsyncFoo() + foo = SyncFoo(async_foo) + assert foo.foo() == "foo" + assert foo.bar() == list(range(10)) + + +@pytest.mark.parametrize("workers", [None, 1, 2]) +def test_threadpool_executor(clean_state, workers: int | None) -> None: + with zarr.config.set({"threading.max_workers": workers}): + _ = zarr.zeros(shape=(1,)) # trigger executor creation + assert loop != [None] # confirm loop was created + if workers is None: + # confirm no executor was created if no workers were specified + # (this is the default behavior) + assert loop[0]._default_executor is None + else: + # confirm executor was created and attached to loop as the default executor + # note: python doesn't have a direct way to get the default executor so we + # use the private attribute + assert _get_executor() is loop[0]._default_executor + assert _get_executor()._max_workers == workers + + +def test_cleanup_resources_idempotent() -> None: + _get_executor() # trigger resource creation (iothread, loop, thread-pool) + cleanup_resources() + cleanup_resources() diff --git a/tests/test_tree.py b/tests/test_tree.py new file mode 100644 index 0000000000..78ea121f4d --- /dev/null +++ b/tests/test_tree.py @@ -0,0 +1,104 @@ +import textwrap +from typing import Any + +import pytest + +import zarr + + +@pytest.mark.parametrize("root_name", [None, "root"]) +@pytest.mark.parametrize("atty", [True, False]) +@pytest.mark.parametrize("plain", [True, False]) +def test_tree(root_name: Any, atty: bool, plain: bool, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("sys.stdout.isatty", lambda: atty) + + if atty and not plain: + BOPEN = "\x1b[1m" + BCLOSE = "\x1b[0m" + else: + BOPEN = "" + BCLOSE = "" + + g = zarr.group(path=root_name) + A = g.create_group("A") + B = g.create_group("B") + C = B.create_group("C") + D = C.create_group("C") + + A.create_array(name="x", shape=(2), dtype="float64") + A.create_array(name="y", shape=(0,), dtype="int8") + B.create_array(name="x", shape=(0,), dtype="float64") + C.create_array(name="x", shape=(0,), dtype="float64") + D.create_array(name="x", shape=(0,), dtype="float64") + + result = repr(g.tree(plain=plain)) + root = root_name or "" + + expected = textwrap.dedent(f"""\ + {BOPEN}/{root}{BCLOSE} + β”œβ”€β”€ {BOPEN}A{BCLOSE} + β”‚ β”œβ”€β”€ {BOPEN}x{BCLOSE} (2,) float64 + β”‚ └── {BOPEN}y{BCLOSE} (0,) int8 + └── {BOPEN}B{BCLOSE} + β”œβ”€β”€ {BOPEN}C{BCLOSE} + β”‚ β”œβ”€β”€ {BOPEN}C{BCLOSE} + β”‚ β”‚ └── {BOPEN}x{BCLOSE} (0,) float64 + β”‚ └── {BOPEN}x{BCLOSE} (0,) float64 + └── {BOPEN}x{BCLOSE} (0,) float64 + """) + + assert result == expected + + result = repr(g.tree(level=0, plain=plain)) + expected = textwrap.dedent(f"""\ + {BOPEN}/{root}{BCLOSE} + β”œβ”€β”€ {BOPEN}A{BCLOSE} + └── {BOPEN}B{BCLOSE} + """) + assert result == expected + + if not plain: + tree = g.tree(plain=False) + bundle = tree._repr_mimebundle_() + assert "text/plain" in bundle + assert "text/html" in bundle + assert "A" in bundle["text/html"] + assert "x" in bundle["text/html"] + assert " None: + g = zarr.group() + g.create_group("a") + g.create_group("b") + g.create_group("c") + g.create_group("d") + g.create_group("e") + + result = repr(g.tree(max_nodes=3, plain=True)) + assert "Truncated at max_nodes=3" in result + # Should show exactly 3 nodes (lines with ── connectors). + lines = result.strip().split("\n") + node_lines = [line for line in lines if "──" in line] + assert len(node_lines) == 3 + + # Full tree should not show truncation message. + full = repr(g.tree(max_nodes=500, plain=True)) + assert "truncated" not in full + + +def test_tree_html_escaping() -> None: + g = zarr.group() + g.create_group("") + + tree = g.tree() + bundle = tree._repr_mimebundle_() + assert "<img" in bundle["text/html"] + assert "" in bundle["text/plain"] + + +def test_expand_not_implemented() -> None: + g = zarr.group() + with pytest.raises(NotImplementedError): + g.tree(expand=True) diff --git a/tests/test_unified_chunk_grid.py b/tests/test_unified_chunk_grid.py new file mode 100644 index 0000000000..f0b54519ab --- /dev/null +++ b/tests/test_unified_chunk_grid.py @@ -0,0 +1,2855 @@ +""" +Tests for the unified ChunkGrid design (POC). + +Tests the core ChunkGrid with FixedDimension/VaryingDimension internals, +ChunkSpec, serialization round-trips, indexing with rectilinear grids, +and end-to-end array creation + read/write. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import numpy as np +import pytest + +import zarr +from zarr.core.chunk_grids import ( + ChunkGrid, + ChunkSpec, + FixedDimension, + VaryingDimension, + _is_rectilinear_chunks, +) +from zarr.core.common import compress_rle, expand_rle +from zarr.core.metadata.v3 import ( + RectilinearChunkGridMetadata, + RectilinearChunkGridMetadataJSON, + RegularChunkGridMetadata, + parse_chunk_grid, +) +from zarr.errors import BoundsCheckError +from zarr.storage import MemoryStore + +if TYPE_CHECKING: + from collections.abc import Generator + from pathlib import Path + + +@pytest.fixture(autouse=True) +def _enable_rectilinear_chunks() -> Generator[None, None, None]: + """Enable rectilinear chunks for all tests in this module.""" + with zarr.config.set({"array.rectilinear_chunks": True}): + yield + + +def _edges(grid: ChunkGrid, dim: int) -> tuple[int, ...]: + """Extract the per-chunk edge lengths for *dim* from a ChunkGrid.""" + d = grid._dimensions[dim] + if isinstance(d, FixedDimension): + return tuple(d.size for _ in range(d.nchunks)) + if isinstance(d, VaryingDimension): + return tuple(d.edges) + raise TypeError(f"Unexpected dimension type: {type(d)}") + + +# --------------------------------------------------------------------------- +# Dimension index_to_chunk bounds tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("dim", "index", "match"), + [ + (VaryingDimension([10, 20, 30], extent=60), 60, "out of bounds"), + (VaryingDimension([10, 20, 30], extent=60), 100, "out of bounds"), + (FixedDimension(size=10, extent=95), 95, "out of bounds"), + (FixedDimension(size=10, extent=95), -1, "Negative"), + ], + ids=[ + "varying-at-extent", + "varying-past-extent", + "fixed-at-extent", + "fixed-negative", + ], +) +def test_dimension_index_to_chunk_bounds( + dim: FixedDimension | VaryingDimension, index: int, match: str +) -> None: + """Out-of-bounds or negative indices raise IndexError for both dimension types""" + with pytest.raises(IndexError, match=match): + dim.index_to_chunk(index) + + +@pytest.mark.parametrize( + ("dim", "index", "expected"), + [ + (VaryingDimension([10, 20, 30], extent=60), 59, 2), + (FixedDimension(size=10, extent=95), 94, 9), + ], + ids=["varying-last-valid", "fixed-last-valid"], +) +def test_dimension_index_to_chunk_last_valid( + dim: FixedDimension | VaryingDimension, index: int, expected: int +) -> None: + """Last valid index maps to the correct chunk for both dimension types""" + assert dim.index_to_chunk(index) == expected + + +# --------------------------------------------------------------------------- +# Rectilinear feature flag tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "action", + [ + lambda: RectilinearChunkGridMetadata(chunk_shapes=((10, 20), (25, 25))), + lambda: RectilinearChunkGridMetadata.from_dict( + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[10, 20, 30], [50, 50]]}, + } + ), + lambda: zarr.create_array(MemoryStore(), shape=(30,), chunks=[[10, 20]], dtype="int32"), + ], + ids=["constructor", "from_dict", "create_array"], +) +def test_rectilinear_feature_flag_blocked(action: Any) -> None: + """Rectilinear chunk operations raise ValueError when the feature flag is disabled""" + with zarr.config.set({"array.rectilinear_chunks": False}): + with pytest.raises(ValueError, match="experimental and disabled by default"): + action() + + +def test_rectilinear_feature_flag_enabled() -> None: + """Rectilinear chunk grid construction succeeds when the feature flag is enabled""" + with zarr.config.set({"array.rectilinear_chunks": True}): + grid = RectilinearChunkGridMetadata(chunk_shapes=((10, 20), (25, 25))) + assert grid.ndim == 2 + + +# --------------------------------------------------------------------------- +# FixedDimension tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ( + "size", + "extent", + "chunk_ix", + "expected_nchunks", + "expected_chunk_size", + "expected_data_size", + "expected_offset", + ), + [ + (10, 100, 0, 10, 10, 10, 0), + (10, 100, 1, 10, 10, 10, 10), + (10, 100, 9, 10, 10, 10, 90), + (10, 95, 9, 10, 10, 5, 90), # boundary chunk + (0, 0, None, 0, None, None, None), # zero-size + ], + ids=["start", "middle", "end", "boundary", "zero-size"], +) +def test_fixed_dimension( + size: int, + extent: int, + chunk_ix: int | None, + expected_nchunks: int, + expected_chunk_size: int | None, + expected_data_size: int | None, + expected_offset: int | None, +) -> None: + """FixedDimension properties match expected values for various chunk/extent combinations""" + d = FixedDimension(size=size, extent=extent) + assert d.nchunks == expected_nchunks + if chunk_ix is not None: + assert d.chunk_size(chunk_ix) == expected_chunk_size + assert d.data_size(chunk_ix) == expected_data_size + assert d.chunk_offset(chunk_ix) == expected_offset + + +@pytest.mark.parametrize( + ("idx", "expected"), + [(0, 0), (9, 0), (10, 1), (25, 2)], +) +def test_fixed_dimension_index_to_chunk(idx: int, expected: int) -> None: + """FixedDimension.index_to_chunk maps element indices to correct chunk indices""" + d = FixedDimension(size=10, extent=100) + assert d.index_to_chunk(idx) == expected + + +def test_fixed_dimension_indices_to_chunks() -> None: + """FixedDimension.indices_to_chunks vectorizes index-to-chunk mapping over an array""" + d = FixedDimension(size=10, extent=100) + indices = np.array([0, 5, 10, 15, 99]) + np.testing.assert_array_equal(d.indices_to_chunks(indices), [0, 0, 1, 1, 9]) + + +@pytest.mark.parametrize( + ("size", "extent", "match"), + [(-1, 100, "must be >= 0"), (10, -1, "must be >= 0")], + ids=["negative-size", "negative-extent"], +) +def test_fixed_dimension_rejects_negative(size: int, extent: int, match: str) -> None: + """FixedDimension raises ValueError for negative size or extent""" + with pytest.raises(ValueError, match=match): + FixedDimension(size=size, extent=extent) + + +# --------------------------------------------------------------------------- +# VaryingDimension tests +# --------------------------------------------------------------------------- + + +def test_varying_dimension_construction() -> None: + """VaryingDimension stores edges, cumulative sums, nchunks, and extent correctly""" + d = VaryingDimension([10, 20, 30], extent=60) + assert d.edges == (10, 20, 30) + assert d.cumulative == (10, 30, 60) + assert d.nchunks == 3 + assert d.extent == 60 + + +@pytest.mark.parametrize( + ( + "chunk_idx", + "expected_offset", + "expected_size", + "expected_data", + "expected_chunk_for_first_idx", + ), + [ + (0, 0, 10, 10, 0), + (1, 10, 20, 20, 1), + (2, 30, 30, 30, 2), + ], +) +def test_varying_dimension( + chunk_idx: int, + expected_offset: int, + expected_size: int, + expected_data: int, + expected_chunk_for_first_idx: int, +) -> None: + """VaryingDimension chunk_offset, chunk_size, data_size, and index_to_chunk return correct values""" + d = VaryingDimension([10, 20, 30], extent=60) + assert d.chunk_offset(chunk_idx) == expected_offset + assert d.chunk_size(chunk_idx) == expected_size + assert d.data_size(chunk_idx) == expected_data + assert d.index_to_chunk(expected_offset) == expected_chunk_for_first_idx + + +def test_varying_dimension_indices_to_chunks() -> None: + """VaryingDimension.indices_to_chunks vectorizes index-to-chunk mapping over an array""" + d = VaryingDimension([10, 20, 30], extent=60) + indices = np.array([0, 9, 10, 29, 30, 59]) + np.testing.assert_array_equal(d.indices_to_chunks(indices), [0, 0, 1, 1, 2, 2]) + + +@pytest.mark.parametrize( + ("edges", "extent", "match"), + [ + ([], 0, "must not be empty"), + ([10, 0, 5], 15, "must be > 0"), + ], + ids=["empty", "zero-edge"], +) +def test_varying_dimension_rejects_invalid(edges: list[int], extent: int, match: str) -> None: + """VaryingDimension raises ValueError for empty edges or zero-length edges""" + with pytest.raises(ValueError, match=match): + VaryingDimension(edges, extent=extent) + + +# --------------------------------------------------------------------------- +# ChunkSpec tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("slices", "codec_shape", "expected_shape", "expected_boundary"), + [ + ((slice(0, 10), slice(0, 20)), (10, 20), (10, 20), False), + ((slice(90, 95), slice(0, 20)), (10, 20), (5, 20), True), + ((slice(10, 10),), (0,), (0,), False), + ((slice(0, 10), slice(0, 5)), (10, 10), (10, 5), True), + ], + ids=["basic", "boundary", "empty-slices", "multidim-boundary"], +) +def test_chunk_spec( + slices: tuple[slice, ...], + codec_shape: tuple[int, ...], + expected_shape: tuple[int, ...], + expected_boundary: bool, +) -> None: + """ChunkSpec reports correct shape and boundary status from slices and codec_shape""" + spec = ChunkSpec(slices=slices, codec_shape=codec_shape) + assert spec.shape == expected_shape + assert spec.is_boundary == expected_boundary + + +# --------------------------------------------------------------------------- +# ChunkGrid construction tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("array_shape", "chunk_sizes", "expected_regular", "expected_ndim", "expected_chunk_shape"), + [ + ((100, 200), (10, 20), True, 2, (10, 20)), + ((), (), True, 0, ()), + ((60, 100), [[10, 20, 30], [25, 25, 25, 25]], False, 2, None), + ((30, 50), [[10, 10, 10], [25, 25]], True, 2, (10, 25)), # uniform edges β†’ regular + ], + ids=["regular", "zero-dim", "rectilinear", "uniform-becomes-regular"], +) +def test_chunk_grid_construction( + array_shape: tuple[int, ...], + chunk_sizes: Any, + expected_regular: bool, + expected_ndim: int, + expected_chunk_shape: tuple[int, ...] | None, +) -> None: + """ChunkGrid.from_sizes produces grids with correct regularity, ndim, and chunk_shape""" + g = ChunkGrid.from_sizes(array_shape, chunk_sizes) + assert g.is_regular == expected_regular + assert g.ndim == expected_ndim + if expected_chunk_shape is not None: + assert g.chunk_shape == expected_chunk_shape + else: + with pytest.raises(ValueError, match="only available for regular"): + _ = g.chunk_shape + + +def test_chunk_grid_rectilinear_uniform_dim_is_fixed() -> None: + """A rectilinear grid with all-same sizes in one dim stores it as Fixed.""" + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [25, 25, 25, 25]]) + assert isinstance(g._dimensions[0], VaryingDimension) + assert isinstance(g._dimensions[1], FixedDimension) + + +# --------------------------------------------------------------------------- +# ChunkGrid query tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("shape", "chunks", "expected_grid_shape"), + [ + ((100, 200), (10, 20), (10, 10)), + ((95, 200), (10, 20), (10, 10)), + ((60, 100), [[10, 20, 30], [25, 25, 25, 25]], (3, 4)), + ], + ids=["regular", "regular-boundary", "rectilinear"], +) +def test_chunk_grid_shape( + shape: tuple[int, ...], + chunks: Any, + expected_grid_shape: tuple[int, ...], +) -> None: + """ChunkGrid.grid_shape returns the expected number of chunks per dimension""" + g = ChunkGrid.from_sizes(shape, chunks) + assert g.grid_shape == expected_grid_shape + + +@pytest.mark.parametrize( + ( + "array_shape", + "chunk_sizes", + "coords", + "expected_shape", + "expected_codec_shape", + "expected_boundary", + ), + [ + # regular interior + ((100, 200), (10, 20), (0, 0), (10, 20), (10, 20), False), + # regular boundary + ((95, 200), (10, 20), (9, 0), (5, 20), (10, 20), True), + # rectilinear + ((60, 100), [[10, 20, 30], [25, 25, 25, 25]], (0, 0), (10, 25), (10, 25), False), + ((60, 100), [[10, 20, 30], [25, 25, 25, 25]], (1, 0), (20, 25), (20, 25), False), + ((60, 100), [[10, 20, 30], [25, 25, 25, 25]], (2, 3), (30, 25), (30, 25), False), + ], + ids=["regular", "regular-boundary", "rectilinear-0,0", "rectilinear-1,0", "rectilinear-2,3"], +) +def test_chunk_grid_getitem( + array_shape: tuple[int, ...], + chunk_sizes: Any, + coords: tuple[int, ...], + expected_shape: tuple[int, ...], + expected_codec_shape: tuple[int, ...], + expected_boundary: bool, +) -> None: + """ChunkGrid.__getitem__ returns a ChunkSpec with correct shape, codec_shape, and boundary flag""" + g = ChunkGrid.from_sizes(array_shape, chunk_sizes) + spec = g[coords] + assert spec is not None + assert spec.shape == expected_shape + assert spec.codec_shape == expected_codec_shape + assert spec.is_boundary == expected_boundary + + +@pytest.mark.parametrize( + ("array_shape", "chunk_sizes", "coords"), + [ + ((100, 200), (10, 20), (99, 0)), + ((60, 100), [[10, 20, 30], [25, 25, 25, 25]], (3, 0)), + ], + ids=["regular-oob", "rectilinear-oob"], +) +def test_chunk_grid_getitem_oob( + array_shape: tuple[int, ...], chunk_sizes: Any, coords: tuple[int, ...] +) -> None: + """Out-of-bounds chunk coordinates return None""" + g = ChunkGrid.from_sizes(array_shape, chunk_sizes) + assert g[coords] is None + + +def test_chunk_grid_getitem_slices() -> None: + """ChunkSpec.slices reflect the correct start/stop for a rectilinear chunk""" + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [25, 25, 25, 25]]) + spec = g[(1, 2)] + assert spec is not None + assert spec.slices == (slice(10, 30, 1), slice(50, 75, 1)) + + +# -- all_chunk_coords tests -- + + +@pytest.mark.parametrize( + ("array_shape", "chunk_sizes", "origin", "selection_shape", "expected_coords"), + [ + # rectilinear grid + ( + (60, 100), + [[10, 20, 30], [50, 50]], + None, + None, + [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)], + ), + ((60, 100), [[10, 20, 30], [50, 50]], (1, 0), None, [(1, 0), (1, 1), (2, 0), (2, 1)]), + ((60, 100), [[10, 20, 30], [50, 50]], None, (2, 1), [(0, 0), (1, 0)]), + ((60, 100), [[10, 20, 30], [50, 50]], (1, 1), (2, 1), [(1, 1), (2, 1)]), + # regular grid + ((30, 40), (10, 20), (2, 1), None, [(2, 1)]), + ((30, 40), (10, 20), None, (0, 0), []), + ((60, 80), (20, 20), (0, 2), (3, 1), [(0, 2), (1, 2), (2, 2)]), + ], + ids=[ + "all", + "with-origin", + "with-sel-shape", + "origin+sel", + "last-chunk", + "zero-sel", + "single-dim", + ], +) +def test_all_chunk_coords( + array_shape: tuple[int, ...], + chunk_sizes: Any, + origin: tuple[int, ...] | None, + selection_shape: tuple[int, ...] | None, + expected_coords: list[tuple[int, ...]], +) -> None: + """all_chunk_coords yields the expected coordinates with optional origin and selection_shape""" + g = ChunkGrid.from_sizes(array_shape, chunk_sizes) + kwargs: dict[str, Any] = {} + if origin is not None: + kwargs["origin"] = origin + if selection_shape is not None: + kwargs["selection_shape"] = selection_shape + assert list(g.all_chunk_coords(**kwargs)) == expected_coords + + +def test_chunk_grid_get_nchunks() -> None: + """get_nchunks returns the total number of chunks across all dimensions""" + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + assert g.get_nchunks() == 6 + + +def test_chunk_grid_iter() -> None: + """Iterating a ChunkGrid yields the correct number of ChunkSpec objects""" + g = ChunkGrid.from_sizes((30, 40), (10, 20)) + specs = list(g) + assert len(specs) == 6 + assert all(isinstance(s, ChunkSpec) for s in specs) + + +# --------------------------------------------------------------------------- +# RLE tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("compressed", "expected"), + [ + ([[10, 3]], [10, 10, 10]), + ([[10, 2], [20, 1]], [10, 10, 20]), + ], +) +def test_rle_expand(compressed: list[Any], expected: list[int]) -> None: + """RLE-encoded edges expand correctly""" + assert expand_rle(compressed) == expected + + +@pytest.mark.parametrize( + ("original", "expected"), + [ + ([10, 10, 10], [[10, 3]]), + ([10, 10, 20], [[10, 2], 20]), + ([5], [5]), + ([10, 20, 30], [10, 20, 30]), + ], +) +def test_rle_compress(original: list[int], expected: list[Any]) -> None: + """compress_rle produces the expected RLE encoding for various input sequences""" + assert compress_rle(original) == expected + + +def test_rle_roundtrip() -> None: + """compress_rle followed by expand_rle recovers the original sequence""" + original = [10, 10, 10, 20, 20, 30] + compressed = compress_rle(original) + assert expand_rle(compressed) == original + + +@pytest.mark.parametrize( + ("rle_input", "match"), + [ + ([0], "Chunk edge length must be >= 1"), + ([-5], "Chunk edge length must be >= 1"), + ([[0, 3]], "Chunk edge length must be >= 1"), + ([[-10, 2]], "Chunk edge length must be >= 1"), + ([[5, 0]], "RLE repeat count must be >= 1"), + ([[5, -1]], "RLE repeat count must be >= 1"), + ], + ids=[ + "zero-edge", + "negative-edge", + "zero-rle-size", + "negative-rle-size", + "zero-rle-count", + "negative-rle-count", + ], +) +def test_rle_expand_rejects_invalid(rle_input: list[Any], match: str) -> None: + """expand_rle raises ValueError for zero/negative edge lengths or repeat counts""" + with pytest.raises(ValueError, match=match): + expand_rle(rle_input) + + +# -- expand_rle handles JSON floats -- + + +def test_expand_rle_bare_integer_floats_accepted() -> None: + """JSON parsers may emit 10.0 for the integer 10; expand_rle should handle it.""" + result = expand_rle([10.0, 20.0]) # type: ignore[list-item] + assert result == [10, 20] + + +def test_expand_rle_pair_with_float_count() -> None: + """expand_rle accepts float repeat counts that are integer-valued""" + result = expand_rle([[10, 3.0]]) # type: ignore[list-item] + assert result == [10, 10, 10] + + +# --------------------------------------------------------------------------- +# _is_rectilinear_chunks tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ([[10, 20], [5, 5]], True), + (((10, 20), (5, 5)), True), + ((10, 20), False), + ([10, 20], False), + (10, False), + ("auto", False), + ([], False), + ([[]], True), + (ChunkGrid.from_sizes((10,), (5,)), False), + (None, False), + (3.14, False), + ], + ids=[ + "nested-lists", + "nested-tuples", + "flat-tuple", + "flat-list", + "single-int", + "string", + "empty-list", + "empty-nested-list", + "chunk-grid-instance", + "none", + "float", + ], +) +def test_is_rectilinear_chunks(value: Any, expected: bool) -> None: + """_is_rectilinear_chunks correctly identifies nested sequences as rectilinear""" + assert _is_rectilinear_chunks(value) is expected + + +def test_is_rectilinear_chunks_handles_broken_iterable() -> None: + """_is_rectilinear_chunks returns False for objects that raise on iteration.""" + + class BrokenIter: + def __iter__(self) -> Any: + raise TypeError("cannot iterate") + + assert _is_rectilinear_chunks(BrokenIter()) is False + + +# --------------------------------------------------------------------------- +# Serialization tests +# --------------------------------------------------------------------------- + + +def test_serialization_error_non_regular_chunk_shape() -> None: + """Accessing chunk_shape on a non-regular grid raises ValueError.""" + grid = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [25, 25, 25, 25]]) + with pytest.raises(ValueError, match="only available for regular"): + grid.chunk_shape # noqa: B018 + + +def test_serialization_error_zero_extent_rectilinear() -> None: + """RectilinearChunkGridMetadata rejects empty edge tuples.""" + with pytest.raises(ValueError, match="has no chunk edges"): + RectilinearChunkGridMetadata(chunk_shapes=((),)) + + +def test_serialization_unknown_name_parse() -> None: + """Parsing metadata with an unknown chunk grid name raises ValueError""" + with pytest.raises(ValueError, match="Unknown chunk grid"): + parse_chunk_grid({"name": "hexagonal", "configuration": {}}) + + +def test_from_metadata_unknown_chunk_grid_type() -> None: + """ChunkGrid.from_metadata raises TypeError for unrecognised chunk grid metadata.""" + from unittest.mock import MagicMock + + from zarr.core.metadata.v3 import ArrayV3Metadata + + mock_meta = MagicMock(spec=ArrayV3Metadata) + mock_meta.chunk_grid = MagicMock() # not Regular or Rectilinear + with pytest.raises(TypeError, match="Unknown chunk grid metadata type"): + ChunkGrid.from_metadata(mock_meta) + + +def test_from_sizes_rejects_empty_edge_list() -> None: + """ChunkGrid.from_sizes raises ValueError when a dimension has an empty edge list.""" + with pytest.raises(ValueError, match="at least one chunk"): + ChunkGrid.from_sizes((10,), ([],)) + + +# --------------------------------------------------------------------------- +# Spec compliance tests +# --------------------------------------------------------------------------- + + +def test_spec_kind_inline_required_on_deserialize() -> None: + """Deserialization requires kind: 'inline'.""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"chunk_shapes": [[10, 20], [15, 15]]}, + } + with pytest.raises(ValueError, match="requires a 'kind' field"): + parse_chunk_grid(data) + + +def test_spec_kind_unknown_rejected() -> None: + """Unsupported rectilinear chunk grid kind raises ValueError on parse""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "reference", "chunk_shapes": [[10, 20], [15, 15]]}, + } + with pytest.raises(ValueError, match="Unsupported rectilinear chunk grid kind"): + parse_chunk_grid(data) + + +def test_spec_integer_shorthand_per_dimension() -> None: + """A bare integer in chunk_shapes means repeat until >= extent.""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [4, [1, 2, 3]]}, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + g = ChunkGrid.from_sizes((6, 6), meta.chunk_shapes) + assert _edges(g, 0) == (4, 4) + assert _edges(g, 1) == (1, 2, 3) + + +def test_spec_mixed_rle_and_bare_integers() -> None: + """An array can mix bare integers and [value, count] RLE pairs.""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[[1, 3], 3]]}, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + g = ChunkGrid.from_sizes((6,), meta.chunk_shapes) + assert _edges(g, 0) == (1, 1, 1, 3) + + +def test_spec_overflow_chunks_allowed() -> None: + """Edge sum >= extent is valid (overflow chunks permitted).""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[4, 4, 4]]}, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + g = ChunkGrid.from_sizes((6,), meta.chunk_shapes) + assert _edges(g, 0) == (4, 4, 4) + + +def test_spec_example() -> None: + """The full example from the spec README.""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": { + "kind": "inline", + "chunk_shapes": [ + 4, + [1, 2, 3], + [[4, 2]], + [[1, 3], 3], + [4, 4, 4], + ], + }, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + g = ChunkGrid.from_sizes((6, 6, 6, 6, 6), meta.chunk_shapes) + assert _edges(g, 0) == (4, 4) + assert _edges(g, 1) == (1, 2, 3) + assert _edges(g, 2) == (4, 4) + assert _edges(g, 3) == (1, 1, 1, 3) + assert _edges(g, 4) == (4, 4, 4) + + +# --------------------------------------------------------------------------- +# parse_chunk_grid validation tests +# --------------------------------------------------------------------------- + + +def test_parse_chunk_grid_varying_extent_mismatch_raises() -> None: + """Reconstructing a ChunkGrid with mismatched extents raises ValueError""" + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + with pytest.raises(ValueError, match="extent"): + ChunkGrid( + dimensions=tuple( + dim.with_extent(ext) for dim, ext in zip(g._dimensions, (100, 100), strict=True) + ) + ) + + +def test_parse_chunk_grid_varying_extent_match_ok() -> None: + """Reconstructing a ChunkGrid with matching extents succeeds""" + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + g2 = ChunkGrid( + dimensions=tuple( + dim.with_extent(ext) for dim, ext in zip(g._dimensions, (60, 100), strict=True) + ) + ) + assert g2._dimensions[0].extent == 60 + + +@pytest.mark.parametrize( + ("chunk_shapes", "array_shape", "match"), + [ + ([[10, 20, 30], [25, 25]], (100, 50), "extent 100 exceeds sum of edges 60"), + ([[50, 50], [10, 20]], (100, 50), "extent 50 exceeds sum of edges 30"), + ], + ids=["first-dim-mismatch", "second-dim-mismatch"], +) +def test_parse_chunk_grid_rectilinear_extent_mismatch_raises( + chunk_shapes: list[list[int]], array_shape: tuple[int, ...], match: str +) -> None: + """Rectilinear grid raises ValueError when array extent exceeds sum of edges""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": chunk_shapes}, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + with pytest.raises(ValueError, match=match): + ChunkGrid.from_sizes(array_shape, meta.chunk_shapes) + + +def test_parse_chunk_grid_rectilinear_extent_match_passes() -> None: + """Rectilinear grid with matching extents parses and builds successfully""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[10, 20, 30], [25, 25]]}, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + g = ChunkGrid.from_sizes((60, 50), meta.chunk_shapes) + assert g.grid_shape == (3, 2) + + +def test_parse_chunk_grid_rectilinear_ndim_mismatch_raises() -> None: + """Mismatched ndim between array shape and chunk_sizes raises ValueError""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[10, 20], [25, 25]]}, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + with pytest.raises(ValueError, match="3 dimensions but chunk_sizes has 2"): + ChunkGrid.from_sizes((30, 50, 100), meta.chunk_shapes) + + +def test_parse_chunk_grid_rectilinear_rle_extent_validated() -> None: + """RLE-encoded edges are expanded before validation.""" + data: dict[str, Any] = { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[[10, 5]], [[25, 2]]]}, + } + meta = parse_chunk_grid(data) + assert isinstance(meta, RectilinearChunkGridMetadata) + g = ChunkGrid.from_sizes((50, 50), meta.chunk_shapes) + assert g.grid_shape == (5, 2) + with pytest.raises(ValueError, match="extent 100 exceeds sum of edges 50"): + ChunkGrid.from_sizes((100, 50), meta.chunk_shapes) + + +def test_parse_chunk_grid_varying_dimension_extent_mismatch_on_chunkgrid_input() -> None: + """ChunkGrid constructor rejects VaryingDimension with extent exceeding sum of edges""" + g = ChunkGrid.from_sizes((60, 50), [[10, 20, 30], [25, 25]]) + with pytest.raises(ValueError, match="less than"): + ChunkGrid( + dimensions=tuple( + dim.with_extent(ext) for dim, ext in zip(g._dimensions, (100, 50), strict=True) + ) + ) + + +# --------------------------------------------------------------------------- +# Rectilinear indexing tests +# --------------------------------------------------------------------------- + + +def test_basic_indexer_rectilinear() -> None: + """BasicIndexer produces correct projections for a full-slice rectilinear selection""" + from zarr.core.indexing import BasicIndexer + + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + indexer = BasicIndexer( + selection=(slice(None), slice(None)), + shape=(60, 100), + chunk_grid=g, + ) + projections = list(indexer) + assert len(projections) == 6 + + p0 = projections[0] + assert p0.chunk_coords == (0, 0) + assert p0.chunk_selection == (slice(0, 10, 1), slice(0, 50, 1)) + + p1 = projections[2] + assert p1.chunk_coords == (1, 0) + assert p1.chunk_selection == (slice(0, 20, 1), slice(0, 50, 1)) + + +def test_basic_indexer_int_selection() -> None: + """BasicIndexer with integer selection maps to the correct chunk and local offset""" + from zarr.core.indexing import BasicIndexer + + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + indexer = BasicIndexer( + selection=(15, slice(None)), + shape=(60, 100), + chunk_grid=g, + ) + projections = list(indexer) + assert len(projections) == 2 + assert projections[0].chunk_coords == (1, 0) + assert projections[0].chunk_selection == (5, slice(0, 50, 1)) + + +def test_basic_indexer_slice_subset() -> None: + """BasicIndexer with partial slices spans the expected chunk dimensions""" + from zarr.core.indexing import BasicIndexer + + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + indexer = BasicIndexer( + selection=(slice(5, 35), slice(0, 50)), + shape=(60, 100), + chunk_grid=g, + ) + projections = list(indexer) + chunk_coords_dim0 = sorted({p.chunk_coords[0] for p in projections}) + assert chunk_coords_dim0 == [0, 1, 2] + + +def test_orthogonal_indexer_rectilinear() -> None: + """OrthogonalIndexer produces the expected number of projections for a rectilinear grid""" + from zarr.core.indexing import OrthogonalIndexer + + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + indexer = OrthogonalIndexer( + selection=(slice(None), slice(None)), + shape=(60, 100), + chunk_grid=g, + ) + projections = list(indexer) + assert len(projections) == 6 + + +def test_oob_block_raises_bounds_check_error() -> None: + """Out-of-bounds block index should raise BoundsCheckError, not IndexError.""" + store = MemoryStore() + a = zarr.create_array(store, shape=(30,), chunks=[[10, 20]], dtype="int32") + with pytest.raises(BoundsCheckError): + a.get_block_selection((2,)) + + +# --------------------------------------------------------------------------- +# End-to-end tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("shape", "chunks", "expected_regular"), + [ + ((100, 200), (10, 20), True), + ((60, 100), [[10, 20, 30], [50, 50]], False), + ], + ids=["regular", "rectilinear"], +) +def test_e2e_create_array( + tmp_path: Path, shape: tuple[int, ...], chunks: Any, expected_regular: bool +) -> None: + """End-to-end array creation sets correct regularity and ndim on chunk_grid""" + arr = zarr.create_array( + store=tmp_path / "arr.zarr", + shape=shape, + chunks=chunks, + dtype="float32", + ) + assert ChunkGrid.from_metadata(arr.metadata).is_regular == expected_regular + assert ChunkGrid.from_metadata(arr.metadata).ndim == len(shape) + + +@pytest.mark.parametrize( + ("shape", "chunks", "grid_type_name", "grid_name"), + [ + ((100, 200), (10, 20), "RegularChunkGridMetadata", "regular"), + ((60, 100), [[10, 20, 30], [50, 50]], "RectilinearChunkGridMetadata", "rectilinear"), + ], + ids=["regular", "rectilinear"], +) +def test_e2e_chunk_grid_serializes( + tmp_path: Path, shape: tuple[int, ...], chunks: Any, grid_type_name: str, grid_name: str +) -> None: + """Array metadata serializes chunk_grid with the correct type and name""" + from zarr.core.metadata.v3 import ( + ArrayV3Metadata, + RectilinearChunkGridMetadata, + RegularChunkGridMetadata, + ) + + grid_type = ( + RegularChunkGridMetadata + if grid_type_name == "RegularChunkGridMetadata" + else RectilinearChunkGridMetadata + ) + arr = zarr.create_array( + store=tmp_path / "arr.zarr", + shape=shape, + chunks=chunks, + dtype="float32", + ) + assert isinstance(arr.metadata, ArrayV3Metadata) + assert isinstance(arr.metadata.chunk_grid, grid_type) + d = arr.metadata.to_dict() + chunk_grid_dict = d["chunk_grid"] + assert isinstance(chunk_grid_dict, dict) + assert chunk_grid_dict["name"] == grid_name + + +def test_e2e_chunk_grid_name_roundtrip_preserves_rectilinear(tmp_path: Path) -> None: + """A rectilinear grid with uniform edges stays 'rectilinear' through to_dict/from_dict.""" + from zarr.core.metadata.v3 import ArrayV3Metadata, RectilinearChunkGridMetadata + + meta_dict: dict[str, Any] = { + "zarr_format": 3, + "node_type": "array", + "shape": [100, 100], + "chunk_grid": { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[[50, 2]], [[25, 4]]]}, + }, + "chunk_key_encoding": {"name": "default"}, + "data_type": "float32", + "fill_value": 0.0, + "codecs": [{"name": "bytes", "configuration": {"endian": "little"}}], + } + meta = ArrayV3Metadata.from_dict(meta_dict) + assert isinstance(meta.chunk_grid, RectilinearChunkGridMetadata) + d = meta.to_dict() + chunk_grid_dict = d["chunk_grid"] + assert isinstance(chunk_grid_dict, dict) + assert chunk_grid_dict["name"] == "rectilinear" + + +def test_e2e_chunk_grid_name_regular_from_dict(tmp_path: Path) -> None: + """A 'regular' chunk grid name is preserved through from_dict.""" + from zarr.core.metadata.v3 import ArrayV3Metadata, RegularChunkGridMetadata + + meta_dict: dict[str, Any] = { + "zarr_format": 3, + "node_type": "array", + "shape": [100, 100], + "chunk_grid": { + "name": "regular", + "configuration": {"chunk_shape": [50, 25]}, + }, + "chunk_key_encoding": {"name": "default"}, + "data_type": "float32", + "fill_value": 0.0, + "codecs": [{"name": "bytes", "configuration": {"endian": "little"}}], + } + meta = ArrayV3Metadata.from_dict(meta_dict) + assert isinstance(meta.chunk_grid, RegularChunkGridMetadata) + d = meta.to_dict() + chunk_grid_dict = d["chunk_grid"] + assert isinstance(chunk_grid_dict, dict) + assert chunk_grid_dict["name"] == "regular" + + +# --------------------------------------------------------------------------- +# Sharding compatibility tests +# --------------------------------------------------------------------------- + + +def test_sharding_accepts_rectilinear_outer_grid() -> None: + """ShardingCodec.validate should not reject rectilinear outer grids.""" + from zarr.codecs.sharding import ShardingCodec + from zarr.core.dtype import Float32 + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata + + codec = ShardingCodec(chunk_shape=(5, 5)) + grid_meta = RectilinearChunkGridMetadata(chunk_shapes=((10, 20, 30), (50, 50))) + + codec.validate( + shape=(60, 100), + dtype=Float32(), + chunk_grid=grid_meta, + ) + + +def test_sharding_rejects_non_divisible_rectilinear() -> None: + """Rectilinear shard sizes not divisible by inner chunk_shape should raise.""" + from zarr.codecs.sharding import ShardingCodec + from zarr.core.dtype import Float32 + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata + + codec = ShardingCodec(chunk_shape=(5, 5)) + grid_meta = RectilinearChunkGridMetadata(chunk_shapes=((10, 20, 17), (50, 50))) + + with pytest.raises(ValueError, match="divisible"): + codec.validate( + shape=(47, 100), + dtype=Float32(), + chunk_grid=grid_meta, + ) + + +def test_sharding_accepts_divisible_rectilinear() -> None: + """Rectilinear shard sizes all divisible by inner chunk_shape should pass.""" + from zarr.codecs.sharding import ShardingCodec + from zarr.core.dtype import Float32 + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata + + codec = ShardingCodec(chunk_shape=(5, 5)) + grid_meta = RectilinearChunkGridMetadata(chunk_shapes=((10, 20, 30), (50, 50))) + + codec.validate( + shape=(60, 100), + dtype=Float32(), + chunk_grid=grid_meta, + ) + + +def test_sharding_rejects_non_divisible_among_repeated_edges() -> None: + """Shard validation catches a non-divisible edge even among many repeated valid ones.""" + from zarr.codecs.sharding import ShardingCodec + from zarr.core.dtype import Float32 + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata + + # edges (10, 10, 7) β€” 7 is not divisible by 5 + codec = ShardingCodec(chunk_shape=(5,)) + grid_meta = RectilinearChunkGridMetadata(chunk_shapes=((10, 10, 7),)) + with pytest.raises(ValueError, match="divisible"): + codec.validate(shape=(27,), dtype=Float32(), chunk_grid=grid_meta) + + +def test_sharding_accepts_all_repeated_divisible_edges() -> None: + """Shard validation passes when all distinct edges are divisible by inner chunk size.""" + from zarr.codecs.sharding import ShardingCodec + from zarr.core.dtype import Float32 + from zarr.core.metadata.v3 import RectilinearChunkGridMetadata + + # edges (10, 10, 20, 10) β€” unique values {10, 20}, both divisible by 5 + codec = ShardingCodec(chunk_shape=(5,)) + grid_meta = RectilinearChunkGridMetadata(chunk_shapes=((10, 10, 20, 10),)) + codec.validate(shape=(50,), dtype=Float32(), chunk_grid=grid_meta) + + +# --------------------------------------------------------------------------- +# Edge cases +# --------------------------------------------------------------------------- + + +def test_edge_case_chunk_grid_boundary_getitem() -> None: + """ChunkGrid with boundary FixedDimension via direct construction.""" + g = ChunkGrid(dimensions=(FixedDimension(10, 95), FixedDimension(20, 40))) + spec = g[(9, 1)] + assert spec is not None + assert spec.shape == (5, 20) + assert spec.codec_shape == (10, 20) + assert spec.is_boundary + + +def test_edge_case_chunk_grid_boundary_iter() -> None: + """Iterating a boundary grid yields correct boundary ChunkSpecs.""" + g = ChunkGrid(dimensions=(FixedDimension(10, 25),)) + specs = list(g) + assert len(specs) == 3 + assert specs[0].shape == (10,) + assert specs[1].shape == (10,) + assert specs[2].shape == (5,) + assert specs[2].is_boundary + assert not specs[0].is_boundary + + +def test_edge_case_chunk_grid_boundary_shape() -> None: + """shape property with boundary extent.""" + g = ChunkGrid(dimensions=(FixedDimension(10, 95),)) + assert g.grid_shape == (10,) + + +# -- Zero-size and zero-extent -- + + +@pytest.mark.parametrize( + ("size", "extent"), + [(0, 0), (0, 5), (10, 0)], + ids=["zero-size-zero-extent", "zero-size-nonzero-extent", "zero-extent-nonzero-size"], +) +def test_edge_case_zero_size_or_extent(size: int, extent: int) -> None: + """FixedDimension with zero size or extent has zero chunks and getitem returns None""" + d = FixedDimension(size=size, extent=extent) + assert d.nchunks == 0 + g = ChunkGrid(dimensions=(d,)) + assert g[0] is None + + +def test_edge_case_zero_size_data_and_indices() -> None: + """FixedDimension(size=0) handles data_size, index_to_chunk, and indices_to_chunks safely.""" + d = FixedDimension(size=0, extent=0) + # Zero-sized chunks have zero data + assert d.data_size(0) == 0 + # Vectorized lookup maps every index to chunk 0 (avoids division by zero) + indices = np.array([0, 0, 0], dtype=np.intp) + np.testing.assert_array_equal(d.indices_to_chunks(indices), np.zeros(3, dtype=np.intp)) + + +def test_edge_case_zero_size_nonzero_extent_index() -> None: + """FixedDimension(size=0, extent>0) maps valid indices to chunk 0 without dividing by zero.""" + d = FixedDimension(size=0, extent=5) + assert d.nchunks == 0 + # index_to_chunk avoids division by zero and returns 0 + assert d.index_to_chunk(0) == 0 + assert d.index_to_chunk(4) == 0 + + +def test_edge_case_zero_size_data_and_index() -> None: + """FixedDimension(size=0) returns zero for data_size and maps indices to chunk 0.""" + d = FixedDimension(size=0, extent=0) + # data_size returns 0 for a zero-sized chunk + assert d.data_size(0) == 0 + # vectorized indices_to_chunks returns zeros + indices = np.array([0, 0, 0], dtype=np.intp) + np.testing.assert_array_equal(d.indices_to_chunks(indices), np.zeros(3, dtype=np.intp)) + + +# -- 0-d grid -- + + +def test_0d_grid_getitem() -> None: + """0-d grid has exactly one chunk at coords ().""" + g = ChunkGrid.from_sizes((), ()) + spec = g[()] + assert spec is not None + assert spec.shape == () + assert spec.codec_shape == () + assert not spec.is_boundary + + +def test_0d_grid_iter() -> None: + """0-d grid iteration yields a single ChunkSpec.""" + g = ChunkGrid.from_sizes((), ()) + specs = list(g) + assert len(specs) == 1 + + +def test_0d_grid_all_chunk_coords() -> None: + """0-d grid has one chunk coord: the empty tuple.""" + g = ChunkGrid.from_sizes((), ()) + coords = list(g.all_chunk_coords()) + assert coords == [()] + + +def test_0d_grid_nchunks() -> None: + """0-d grid reports exactly one chunk""" + g = ChunkGrid.from_sizes((), ()) + assert g.get_nchunks() == 1 + + +# -- parse_chunk_grid edge cases -- + + +def test_parse_chunk_grid_preserves_varying_extent() -> None: + """parse_chunk_grid does not overwrite VaryingDimension extent.""" + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + assert isinstance(g._dimensions[0], VaryingDimension) + assert g._dimensions[0].extent == 60 + + g2 = ChunkGrid( + dimensions=tuple( + dim.with_extent(ext) for dim, ext in zip(g._dimensions, (60, 100), strict=True) + ) + ) + assert isinstance(g2._dimensions[0], VaryingDimension) + assert g2._dimensions[0].extent == 60 + + +def test_parse_chunk_grid_rebinds_fixed_extent() -> None: + """parse_chunk_grid updates FixedDimension extent from array shape.""" + g = ChunkGrid.from_sizes((100, 200), (10, 20)) + assert g._dimensions[0].extent == 100 + + g2 = ChunkGrid( + dimensions=tuple( + dim.with_extent(ext) for dim, ext in zip(g._dimensions, (50, 100), strict=True) + ) + ) + assert isinstance(g2._dimensions[0], FixedDimension) + assert g2._dimensions[0].extent == 50 + assert g2.grid_shape == (5, 5) + + +# -- ChunkGrid.__getitem__ validation -- + + +def test_getitem_int_1d_regular() -> None: + """Integer indexing works for 1-d regular grids.""" + g = ChunkGrid.from_sizes((100,), (10,)) + spec = g[0] + assert spec is not None + assert spec.shape == (10,) + assert spec.slices == (slice(0, 10, 1),) + spec = g[9] + assert spec is not None + assert spec.shape == (10,) + + +def test_getitem_int_1d_rectilinear() -> None: + """Integer indexing works for 1-d rectilinear grids.""" + g = ChunkGrid.from_sizes((100,), [[20, 30, 50]]) + spec = g[0] + assert spec is not None + assert spec.shape == (20,) + spec = g[1] + assert spec is not None + assert spec.shape == (30,) + spec = g[2] + assert spec is not None + assert spec.shape == (50,) + + +@pytest.mark.parametrize( + ("shape", "chunks", "match"), + [ + ((), (), "Expected 0 coordinate.*got 1"), + ((100, 200), (10, 20), "Expected 2 coordinate.*got 1"), + ], + ids=["0d", "2d"], +) +def test_getitem_int_ndim_mismatch_raises( + shape: tuple[int, ...], chunks: tuple[int, ...], match: str +) -> None: + """Integer indexing on a multi-dim or 0-d grid raises ValueError for ndim mismatch""" + g = ChunkGrid.from_sizes(shape, chunks) + with pytest.raises(ValueError, match=match): + g[0] + + +@pytest.mark.parametrize( + "index", + [(10,), (99,), (-1,)], + ids=["oob-10", "oob-99", "negative"], +) +def test_getitem_oob_returns_none(index: tuple[int, ...]) -> None: + """Out-of-bounds or negative chunk indices return None""" + g = ChunkGrid.from_sizes((100,), (10,)) + assert g[index] is None + + +# -- Rectilinear with zero-nchunks FixedDimension -- + + +def test_zero_nchunks_fixed_dim_in_rectilinear() -> None: + """A rectilinear grid with a 0-extent FixedDimension still has valid size.""" + g = ChunkGrid( + dimensions=( + VaryingDimension([10, 20], extent=30), + FixedDimension(size=10, extent=0), + ) + ) + assert g.grid_shape == (2, 0) + + +# -- VaryingDimension data_size -- + + +def test_varying_dim_data_size_equals_chunk_size() -> None: + """For VaryingDimension, data_size == chunk_size (no padding).""" + d = VaryingDimension([10, 20, 5], extent=35) + for i in range(3): + assert d.data_size(i) == d.chunk_size(i) + + +# --------------------------------------------------------------------------- +# OrthogonalIndexer rectilinear tests +# --------------------------------------------------------------------------- + + +def test_orthogonal_int_array_selection_rectilinear() -> None: + """Integer array selection with rectilinear grid must produce correct + chunk-local selections.""" + from zarr.core.indexing import OrthogonalIndexer + + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + indexer = OrthogonalIndexer( + selection=(np.array([5, 15, 35]), slice(None)), + shape=(60, 100), + chunk_grid=g, + ) + projections = list(indexer) + chunk_coords = [p.chunk_coords for p in projections] + assert chunk_coords == [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)] + + +def test_orthogonal_bool_array_selection_rectilinear() -> None: + """Boolean array selection with rectilinear grid produces correct chunk projections.""" + from zarr.core.indexing import OrthogonalIndexer + + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + mask = np.zeros(60, dtype=bool) + mask[5] = True + mask[15] = True + mask[35] = True + indexer = OrthogonalIndexer( + selection=(mask, slice(None)), + shape=(60, 100), + chunk_grid=g, + ) + projections = list(indexer) + assert len(projections) == 6 + chunk_coords = [p.chunk_coords for p in projections] + assert (0, 0) in chunk_coords + assert (1, 0) in chunk_coords + assert (2, 0) in chunk_coords + assert (0, 1) in chunk_coords + assert (1, 1) in chunk_coords + assert (2, 1) in chunk_coords + + +def test_orthogonal_advanced_indexing_produces_correct_projections() -> None: + """Verify OrthogonalIndexer produces correct chunk projections + for advanced indexing with VaryingDimension.""" + from zarr.core.indexing import OrthogonalIndexer + + g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]]) + indexer = OrthogonalIndexer( + selection=(np.array([5, 15]), slice(None)), + shape=(60, 100), + chunk_grid=g, + ) + projections = list(indexer) + assert len(projections) == 4 + coords = [p.chunk_coords for p in projections] + assert (0, 0) in coords + assert (0, 1) in coords + assert (1, 0) in coords + assert (1, 1) in coords + + +# --------------------------------------------------------------------------- +# Full pipeline rectilinear tests (helpers) +# --------------------------------------------------------------------------- + + +def _make_1d(tmp_path: Path) -> tuple[zarr.Array[Any], np.ndarray[Any, Any]]: + a = np.arange(30, dtype="int32") + z = zarr.create_array( + store=tmp_path / "arr1d.zarr", + shape=(30,), + chunks=[[5, 10, 15]], + dtype="int32", + ) + z[:] = a + return z, a + + +def _make_2d(tmp_path: Path) -> tuple[zarr.Array[Any], np.ndarray[Any, Any]]: + a = np.arange(6000, dtype="int32").reshape(60, 100) + z = zarr.create_array( + store=tmp_path / "arr2d.zarr", + shape=(60, 100), + chunks=[[10, 20, 30], [25, 25, 25, 25]], + dtype="int32", + ) + z[:] = a + return z, a + + +# --- Basic selection --- + + +def test_pipeline_basic_selection_1d(tmp_path: Path) -> None: + """1D rectilinear basic selections match numpy for ints, slices, and full-array reads""" + z, a = _make_1d(tmp_path) + sels: list[Any] = [0, 4, 5, 14, 15, 29, -1, slice(None), slice(3, 18), slice(0, 0)] + for sel in sels: + np.testing.assert_array_equal(z[sel], a[sel], err_msg=f"sel={sel}") + + +def test_pipeline_basic_selection_1d_strided(tmp_path: Path) -> None: + """1D rectilinear strided slice selections match numpy""" + z, a = _make_1d(tmp_path) + for sel in [slice(None, None, 2), slice(1, 25, 3), slice(0, 30, 7)]: + np.testing.assert_array_equal(z[sel], a[sel], err_msg=f"sel={sel}") + + +def test_pipeline_basic_selection_2d(tmp_path: Path) -> None: + """2D rectilinear basic selections match numpy across chunk boundaries""" + z, a = _make_2d(tmp_path) + selections: list[Any] = [ + 42, + -1, + (9, 24), + (10, 25), + (30, 50), + (59, 99), + slice(None), + (slice(5, 35), slice(20, 80)), + (slice(0, 10), slice(0, 25)), + (slice(10, 10), slice(None)), + (slice(None, None, 3), slice(None, None, 7)), + ] + for sel in selections: + np.testing.assert_array_equal(z[sel], a[sel], err_msg=f"sel={sel}") + + +# --- Orthogonal selection --- + + +def test_pipeline_orthogonal_selection_1d_bool(tmp_path: Path) -> None: + """1D boolean orthogonal indexing on rectilinear arrays matches numpy""" + z, a = _make_1d(tmp_path) + ix = np.zeros(30, dtype=bool) + ix[[0, 4, 5, 14, 15, 29]] = True + np.testing.assert_array_equal(z.oindex[ix], a[ix]) + + +def test_pipeline_orthogonal_selection_1d_int(tmp_path: Path) -> None: + """1D integer and negative-index orthogonal selection on rectilinear arrays matches numpy""" + z, a = _make_1d(tmp_path) + ix = np.array([0, 4, 5, 14, 15, 29]) + np.testing.assert_array_equal(z.oindex[ix], a[ix]) + ix_neg = np.array([0, -1, -15, -25]) + np.testing.assert_array_equal(z.oindex[ix_neg], a[ix_neg]) + + +def test_pipeline_orthogonal_selection_2d_bool(tmp_path: Path) -> None: + """2D boolean orthogonal selection on rectilinear arrays matches numpy""" + z, a = _make_2d(tmp_path) + ix0 = np.zeros(60, dtype=bool) + ix0[[0, 9, 10, 29, 30, 59]] = True + ix1 = np.zeros(100, dtype=bool) + ix1[[0, 24, 25, 49, 50, 99]] = True + np.testing.assert_array_equal(z.oindex[ix0, ix1], a[np.ix_(ix0, ix1)]) + + +def test_pipeline_orthogonal_selection_2d_int(tmp_path: Path) -> None: + """2D integer orthogonal selection on rectilinear arrays matches numpy""" + z, a = _make_2d(tmp_path) + ix0 = np.array([0, 9, 10, 29, 30, 59]) + ix1 = np.array([0, 24, 25, 49, 50, 99]) + np.testing.assert_array_equal(z.oindex[ix0, ix1], a[np.ix_(ix0, ix1)]) + + +def test_pipeline_orthogonal_selection_2d_mixed(tmp_path: Path) -> None: + """2D mixed int-array and slice orthogonal selection on rectilinear arrays matches numpy""" + z, a = _make_2d(tmp_path) + ix = np.array([0, 9, 10, 29, 30, 59]) + np.testing.assert_array_equal(z.oindex[ix, slice(25, 75)], a[np.ix_(ix, np.arange(25, 75))]) + np.testing.assert_array_equal( + z.oindex[slice(10, 30), ix[:4]], a[np.ix_(np.arange(10, 30), ix[:4])] + ) + + +# --- Coordinate (vindex) selection --- + + +def test_pipeline_coordinate_selection_1d(tmp_path: Path) -> None: + """1D coordinate (vindex) selection on rectilinear arrays matches numpy""" + z, a = _make_1d(tmp_path) + ix = np.array([0, 4, 5, 14, 15, 29]) + np.testing.assert_array_equal(z.vindex[ix], a[ix]) + + +def test_pipeline_coordinate_selection_2d(tmp_path: Path) -> None: + """2D coordinate (vindex) selection on rectilinear arrays matches numpy""" + z, a = _make_2d(tmp_path) + r = np.array([0, 9, 10, 29, 30, 59]) + c = np.array([0, 24, 25, 49, 50, 99]) + np.testing.assert_array_equal(z.vindex[r, c], a[r, c]) + + +def test_pipeline_coordinate_selection_2d_bool_mask(tmp_path: Path) -> None: + """2D boolean mask vindex selection on rectilinear arrays matches numpy""" + z, a = _make_2d(tmp_path) + mask = a > 3000 + np.testing.assert_array_equal(z.vindex[mask], a[mask]) + + +# --- Block selection --- + + +def test_pipeline_block_selection_1d(tmp_path: Path) -> None: + """1D block selection on rectilinear arrays returns correct chunk data""" + z, a = _make_1d(tmp_path) + np.testing.assert_array_equal(z.blocks[0], a[0:5]) + np.testing.assert_array_equal(z.blocks[1], a[5:15]) + np.testing.assert_array_equal(z.blocks[2], a[15:30]) + np.testing.assert_array_equal(z.blocks[-1], a[15:30]) + np.testing.assert_array_equal(z.blocks[0:2], a[0:15]) + np.testing.assert_array_equal(z.blocks[1:3], a[5:30]) + np.testing.assert_array_equal(z.blocks[:], a[:]) + + +def test_pipeline_block_selection_2d(tmp_path: Path) -> None: + """2D block selection on rectilinear arrays returns correct chunk data""" + z, a = _make_2d(tmp_path) + np.testing.assert_array_equal(z.blocks[0, 0], a[0:10, 0:25]) + np.testing.assert_array_equal(z.blocks[1, 2], a[10:30, 50:75]) + np.testing.assert_array_equal(z.blocks[2, 3], a[30:60, 75:100]) + np.testing.assert_array_equal(z.blocks[-1, -1], a[30:60, 75:100]) + np.testing.assert_array_equal(z.blocks[0:2, 1:3], a[0:30, 25:75]) + np.testing.assert_array_equal(z.blocks[:, :], a[:, :]) + + +def test_pipeline_set_block_selection_1d(tmp_path: Path) -> None: + """Writing via 1D block selection on rectilinear arrays persists correctly""" + z, a = _make_1d(tmp_path) + val = np.full(10, -1, dtype="int32") + z.blocks[1] = val + a[5:15] = val + np.testing.assert_array_equal(z[:], a) + + +def test_pipeline_set_block_selection_2d(tmp_path: Path) -> None: + """Writing via 2D block selection on rectilinear arrays persists correctly""" + z, a = _make_2d(tmp_path) + val = np.full((30, 50), -99, dtype="int32") + z.blocks[0:2, 1:3] = val + a[0:30, 25:75] = val + np.testing.assert_array_equal(z[:], a) + + +def test_pipeline_block_selection_slice_stop_at_nchunks(tmp_path: Path) -> None: + """Block slice with stop == nchunks exercises the dim_len fallback.""" + z, a = _make_1d(tmp_path) + np.testing.assert_array_equal(z.blocks[1:3], a[5:30]) + np.testing.assert_array_equal(z.blocks[0:10], a[:]) + + +def test_pipeline_block_selection_slice_stop_at_nchunks_2d(tmp_path: Path) -> None: + """Same fallback test for 2D rectilinear arrays.""" + z, a = _make_2d(tmp_path) + np.testing.assert_array_equal(z.blocks[2:3, 3:4], a[30:60, 75:100]) + np.testing.assert_array_equal(z.blocks[0:99, 0:99], a[:, :]) + + +# --- Set coordinate selection --- + + +def test_pipeline_set_coordinate_selection_1d(tmp_path: Path) -> None: + """Writing via 1D coordinate selection on rectilinear arrays persists correctly""" + z, a = _make_1d(tmp_path) + ix = np.array([0, 4, 5, 14, 15, 29]) + val = np.full(len(ix), -7, dtype="int32") + z.vindex[ix] = val + a[ix] = val + np.testing.assert_array_equal(z[:], a) + + +def test_pipeline_set_coordinate_selection_2d(tmp_path: Path) -> None: + """Writing via 2D coordinate selection on rectilinear arrays persists correctly""" + z, a = _make_2d(tmp_path) + r = np.array([0, 9, 10, 29, 30, 59]) + c = np.array([0, 24, 25, 49, 50, 99]) + val = np.full(len(r), -42, dtype="int32") + z.vindex[r, c] = val + a[r, c] = val + np.testing.assert_array_equal(z[:], a) + + +# --- Set selection --- + + +def test_pipeline_set_basic_selection(tmp_path: Path) -> None: + """Writing via basic slice selection on rectilinear arrays persists correctly""" + z, a = _make_2d(tmp_path) + new_data = np.full((20, 50), -1, dtype="int32") + z[5:25, 10:60] = new_data + a[5:25, 10:60] = new_data + np.testing.assert_array_equal(z[:], a) + + +def test_pipeline_set_orthogonal_selection(tmp_path: Path) -> None: + """Writing via orthogonal selection on rectilinear arrays persists correctly""" + z, a = _make_2d(tmp_path) + rows = np.array([0, 10, 30]) + cols = np.array([0, 25, 50, 75]) + val = np.full((3, 4), -99, dtype="int32") + z.oindex[rows, cols] = val + a[np.ix_(rows, cols)] = val + np.testing.assert_array_equal(z[:], a) + + +# --- Higher dimensions --- + + +def test_pipeline_3d_array(tmp_path: Path) -> None: + """3D rectilinear array write and read-back match numpy""" + shape = (12, 20, 15) + chunk_shapes = [[4, 8], [5, 5, 10], [5, 10]] + a = np.arange(int(np.prod(shape)), dtype="int32").reshape(shape) + z = zarr.create_array( + store=tmp_path / "arr3d.zarr", + shape=shape, + chunks=chunk_shapes, + dtype="int32", + ) + z[:] = a + np.testing.assert_array_equal(z[:], a) + np.testing.assert_array_equal(z[2:10, 3:18, 4:14], a[2:10, 3:18, 4:14]) + + +def test_pipeline_1d_single_chunk(tmp_path: Path) -> None: + """Single-chunk rectilinear array write and read-back match numpy""" + a = np.arange(20, dtype="int32") + z = zarr.create_array( + store=tmp_path / "arr1c.zarr", + shape=(20,), + chunks=[[20]], + dtype="int32", + ) + z[:] = a + np.testing.assert_array_equal(z[:], a) + + +# --- Persistence roundtrip --- + + +def test_pipeline_persistence_roundtrip(tmp_path: Path) -> None: + """Rectilinear array survives close and reopen with correct data""" + _, a = _make_2d(tmp_path) + z2 = zarr.open_array(store=tmp_path / "arr2d.zarr", mode="r") + assert not ChunkGrid.from_metadata(z2.metadata).is_regular + np.testing.assert_array_equal(z2[:], a) + + +# --- Highly irregular chunks --- + + +def test_pipeline_highly_irregular_chunks(tmp_path: Path) -> None: + """Highly irregular chunk sizes produce correct write and partial-read results""" + shape = (100, 100) + chunk_shapes = [[5, 10, 15, 20, 50], [100]] + a = np.arange(10000, dtype="int32").reshape(shape) + z = zarr.create_array( + store=tmp_path / "irreg.zarr", + shape=shape, + chunks=chunk_shapes, + dtype="int32", + ) + z[:] = a + np.testing.assert_array_equal(z[:], a) + np.testing.assert_array_equal(z[3:97, 10:90], a[3:97, 10:90]) + + +# --- API validation --- + + +def test_pipeline_v2_rejects_rectilinear(tmp_path: Path) -> None: + """Creating a rectilinear array with zarr_format=2 raises ValueError""" + with pytest.raises(ValueError, match="Zarr format 2"): + zarr.create_array( + store=tmp_path / "v2.zarr", + shape=(30,), + chunks=[[10, 20]], + dtype="int32", + zarr_format=2, + ) + + +def test_pipeline_sharding_rejects_rectilinear_chunks_with_shards(tmp_path: Path) -> None: + """Rectilinear chunks (inner) with sharding is not supported.""" + with pytest.raises(ValueError, match="Rectilinear chunks with sharding"): + zarr.create_array( + store=tmp_path / "shard.zarr", + shape=(60, 100), + chunks=[[10, 20, 30], [25, 25, 25, 25]], + shards=(30, 50), + dtype="int32", + ) + + +def test_pipeline_rectilinear_shards_roundtrip(tmp_path: Path) -> None: + """Rectilinear shards with uniform inner chunks: full write/read roundtrip.""" + data = np.arange(120 * 100, dtype="int32").reshape(120, 100) + arr = zarr.create_array( + store=tmp_path / "rect_shards.zarr", + shape=(120, 100), + chunks=(10, 10), + shards=[[60, 40, 20], [50, 50]], + dtype="int32", + ) + arr[:] = data + result = arr[:] + np.testing.assert_array_equal(result, data) + + +def test_pipeline_rectilinear_shards_partial_read(tmp_path: Path) -> None: + """Partial reads across rectilinear shard boundaries.""" + data = np.arange(120 * 100, dtype="float64").reshape(120, 100) + arr = zarr.create_array( + store=tmp_path / "rect_shards.zarr", + shape=(120, 100), + chunks=(10, 10), + shards=[[60, 40, 20], [50, 50]], + dtype="float64", + ) + arr[:] = data + result = arr[50:70, 40:60] + np.testing.assert_array_equal(result, data[50:70, 40:60]) + + +def test_pipeline_rectilinear_shards_validates_divisibility(tmp_path: Path) -> None: + """Inner chunk_shape must divide every shard's dimensions.""" + with pytest.raises(ValueError, match="divisible"): + zarr.create_array( + store=tmp_path / "bad.zarr", + shape=(120, 100), + chunks=(10, 10), + shards=[[60, 45, 15], [50, 50]], + dtype="int32", + ) + + +def test_pipeline_nchunks(tmp_path: Path) -> None: + """Rectilinear array reports the correct total number of chunks""" + z, _ = _make_2d(tmp_path) + assert ChunkGrid.from_metadata(z.metadata).get_nchunks() == 12 + + +def test_pipeline_parse_chunk_grid_regular_from_dict() -> None: + """parse_chunk_grid constructs a regular grid from a metadata dict.""" + d: dict[str, Any] = {"name": "regular", "configuration": {"chunk_shape": [10, 20]}} + meta = parse_chunk_grid(d) + assert isinstance(meta, RegularChunkGridMetadata) + g = ChunkGrid.from_sizes((100, 200), tuple(meta.chunk_shape)) + assert g.is_regular + assert g.chunk_shape == (10, 20) + assert g.grid_shape == (10, 10) + assert g.get_nchunks() == 100 + + +# --------------------------------------------------------------------------- +# VaryingDimension boundary tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("edges", "extent", "chunk_idx", "expected_data_size"), + [ + ([10, 20, 30], 50, 0, 10), + ([10, 20, 30], 50, 1, 20), + ([10, 20, 30], 50, 2, 20), + ([10, 20, 30], 60, 2, 30), + ([10, 20, 30], 31, 0, 10), + ([10, 20, 30], 31, 1, 20), + ([10, 20, 30], 31, 2, 1), + ], + ids=[ + "interior-0", + "interior-1", + "boundary-clipped", + "exact-no-clip", + "single-element-boundary-0", + "single-element-boundary-1", + "single-element-boundary-2", + ], +) +def test_varying_dimension_boundary_data_size( + edges: list[int], extent: int, chunk_idx: int, expected_data_size: int +) -> None: + """VaryingDimension.data_size clips correctly at boundary chunks""" + d = VaryingDimension(edges, extent=extent) + assert d.data_size(chunk_idx) == expected_data_size + + +def test_varying_dimension_boundary_extent_parameter() -> None: + """VaryingDimension preserves extent and full chunk_size even when extent < sum of edges""" + d = VaryingDimension([10, 20, 30], extent=50) + assert d.extent == 50 + assert d.chunk_size(2) == 30 + + +def test_varying_dimension_extent_exceeds_sum_rejected() -> None: + """VaryingDimension rejects extent greater than sum of edges""" + with pytest.raises(ValueError, match="exceeds sum of edges"): + VaryingDimension([10, 20], extent=50) + + +def test_varying_dimension_negative_extent_rejected() -> None: + """VaryingDimension rejects negative extent""" + with pytest.raises(ValueError, match="must be >= 0"): + VaryingDimension([10, 20], extent=-1) + + +def test_varying_dimension_zero_extent() -> None: + """VaryingDimension with extent=0 has zero active chunks but retains all grid cells.""" + d = VaryingDimension([10, 20], extent=0) + assert d.nchunks == 0 + assert d.ngridcells == 2 + # No chunks overlap [0, 0), so the grid is structurally non-empty but logically empty + g = ChunkGrid(dimensions=(d,)) + assert g.grid_shape == (0,) + assert list(g) == [] + + +def test_varying_dimension_boundary_chunk_spec() -> None: + """ChunkGrid with a boundary VaryingDimension produces correct ChunkSpec.""" + g = ChunkGrid(dimensions=(VaryingDimension([10, 20, 30], extent=50),)) + spec = g[(2,)] + assert spec is not None + assert spec.codec_shape == (30,) + assert spec.shape == (20,) + assert spec.is_boundary is True + + +def test_varying_dimension_interior_chunk_spec() -> None: + """Interior VaryingDimension chunk has matching codec_shape and shape with no boundary""" + g = ChunkGrid(dimensions=(VaryingDimension([10, 20, 30], extent=50),)) + spec = g[(0,)] + assert spec is not None + assert spec.codec_shape == (10,) + assert spec.shape == (10,) + assert spec.is_boundary is False + + +# --------------------------------------------------------------------------- +# Multiple overflow chunks tests +# --------------------------------------------------------------------------- + + +def test_overflow_multiple_chunks_past_extent() -> None: + """Edges past extent are structural; nchunks counts active only.""" + g = ChunkGrid.from_sizes((50,), [[10, 20, 30, 40]]) + d = g._dimensions[0] + assert d.ngridcells == 4 + assert d.nchunks == 3 + assert d.data_size(0) == 10 + assert d.data_size(1) == 20 + assert d.data_size(2) == 20 + assert d.chunk_size(2) == 30 + + +def test_overflow_chunk_spec_past_extent_is_oob() -> None: + """Chunk entirely past the extent is out of bounds (not active).""" + g = ChunkGrid.from_sizes((50,), [[10, 20, 30, 40]]) + spec = g[(3,)] + assert spec is None + + +def test_overflow_chunk_spec_partial() -> None: + """ChunkSpec for a partially-overflowing chunk clips correctly.""" + g = ChunkGrid.from_sizes((50,), [[10, 20, 30, 40]]) + spec = g[(2,)] + assert spec is not None + assert spec.shape == (20,) + assert spec.codec_shape == (30,) + assert spec.is_boundary is True + assert spec.slices == (slice(30, 50, 1),) + + +def test_overflow_chunk_sizes() -> None: + """chunk_sizes only includes active chunks.""" + g = ChunkGrid.from_sizes((50,), [[10, 20, 30, 40]]) + assert g.chunk_sizes == ((10, 20, 20),) + + +def test_overflow_multidim() -> None: + """Overflow in multiple dimensions simultaneously.""" + g = ChunkGrid.from_sizes((45, 100), [[10, 20, 30], [40, 40, 40]]) + assert g.chunk_sizes == ((10, 20, 15), (40, 40, 20)) + spec = g[(2, 2)] + assert spec is not None + assert spec.shape == (15, 20) + assert spec.codec_shape == (30, 40) + + +def test_overflow_uniform_edges_collapses_to_fixed() -> None: + """Uniform edges where len == ceildiv(extent, edge) collapse to FixedDimension.""" + g = ChunkGrid.from_sizes((35,), [[10, 10, 10, 10]]) + assert isinstance(g._dimensions[0], FixedDimension) + assert g.is_regular + assert g.chunk_sizes == ((10, 10, 10, 5),) + assert g._dimensions[0].nchunks == 4 + + +def test_overflow_index_to_chunk_near_extent() -> None: + """Index lookup near and at the extent boundary.""" + d = VaryingDimension([10, 20, 30, 40], extent=50) + assert d.index_to_chunk(29) == 1 + assert d.index_to_chunk(30) == 2 + assert d.index_to_chunk(49) == 2 + + +# --------------------------------------------------------------------------- +# Boundary indexing tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ( + "dim", + "mask", + "dim_len", + "expected_chunk_ix", + "expected_sel_len", + "expected_first_two", + "expected_third", + ), + [ + ( + FixedDimension(size=5, extent=7), + np.array([False, False, False, False, False, True, True]), + 7, + 1, + 5, + (np.True_, np.True_), + np.False_, + ), + ( + VaryingDimension([5, 10], extent=7), + np.array([False, False, False, False, False, True, True]), + 7, + 1, + 10, + (np.True_, np.True_), + np.False_, + ), + ], + ids=["fixed-boundary", "varying-boundary"], +) +def test_bool_indexer_boundary( + dim: FixedDimension | VaryingDimension, + mask: np.ndarray[Any, Any], + dim_len: int, + expected_chunk_ix: int, + expected_sel_len: int, + expected_first_two: tuple[Any, Any], + expected_third: Any, +) -> None: + """BoolArrayDimIndexer pads to codec size for boundary chunks.""" + from zarr.core.indexing import BoolArrayDimIndexer + + indexer = BoolArrayDimIndexer(mask, dim_len, dim) + projections = list(indexer) + assert len(projections) == 1 + p = projections[0] + assert p.dim_chunk_ix == expected_chunk_ix + sel = p.dim_chunk_sel + assert isinstance(sel, np.ndarray) + assert sel.shape[0] == expected_sel_len + assert sel[0] is expected_first_two[0] + assert sel[1] is expected_first_two[1] + assert sel[2] is expected_third + + +def test_bool_indexer_no_padding_interior() -> None: + """No padding needed for interior chunks.""" + from zarr.core.indexing import BoolArrayDimIndexer + + dim = FixedDimension(size=5, extent=10) + mask = np.array([True, False, False, False, False, False, False, False, False, False]) + indexer = BoolArrayDimIndexer(mask, 10, dim) + projections = list(indexer) + assert len(projections) == 1 + p = projections[0] + assert p.dim_chunk_ix == 0 + sel = p.dim_chunk_sel + assert isinstance(sel, np.ndarray) + assert sel.shape[0] == 5 + + +def test_slice_indexer_varying_boundary() -> None: + """SliceDimIndexer clips to data_size at boundary for VaryingDimension.""" + from zarr.core.indexing import SliceDimIndexer + + dim = VaryingDimension([5, 10], extent=7) + indexer = SliceDimIndexer(slice(None), 7, dim) + projections = list(indexer) + assert len(projections) == 2 + assert projections[0].dim_chunk_sel == slice(0, 5, 1) + assert projections[1].dim_chunk_sel == slice(0, 2, 1) + + +def test_int_array_indexer_varying_boundary() -> None: + """IntArrayDimIndexer handles indices near boundary correctly.""" + from zarr.core.indexing import IntArrayDimIndexer + + dim = VaryingDimension([5, 10], extent=7) + indices = np.array([6]) + indexer = IntArrayDimIndexer(indices, 7, dim) + projections = list(indexer) + assert len(projections) == 1 + assert projections[0].dim_chunk_ix == 1 + sel = projections[0].dim_chunk_sel + assert isinstance(sel, np.ndarray) + np.testing.assert_array_equal(sel, [1]) + + +@pytest.mark.parametrize( + "dim", + [FixedDimension(size=2, extent=10), VaryingDimension([5, 5], extent=10)], + ids=["fixed", "varying"], +) +def test_slice_indexer_empty_slice_at_boundary(dim: FixedDimension | VaryingDimension) -> None: + """SliceDimIndexer yields no projections for an empty slice at the dimension boundary.""" + from zarr.core.indexing import SliceDimIndexer + + indexer = SliceDimIndexer(slice(10, 10), 10, dim) + projections = list(indexer) + assert len(projections) == 0 + + +def test_orthogonal_indexer_varying_boundary_advanced() -> None: + """OrthogonalIndexer with advanced indexing uses per-chunk chunk_size.""" + from zarr.core.indexing import OrthogonalIndexer + + g = ChunkGrid( + dimensions=( + VaryingDimension([5, 10], extent=7), + FixedDimension(size=4, extent=8), + ) + ) + indexer = OrthogonalIndexer( + selection=(np.array([0, 6]), slice(None)), + shape=(7, 8), + chunk_grid=g, + ) + projections = list(indexer) + assert len(projections) == 4 + coords = {p.chunk_coords for p in projections} + assert coords == {(0, 0), (0, 1), (1, 0), (1, 1)} + + +# --------------------------------------------------------------------------- +# update_shape tests +# --------------------------------------------------------------------------- + + +def test_update_shape_no_change() -> None: + """update_shape with the same shape preserves edges unchanged""" + grid = ChunkGrid.from_sizes((60, 50), [[10, 20, 30], [25, 25]]) + new_grid = grid.update_shape((60, 50)) + assert _edges(new_grid, 0) == (10, 20, 30) + assert _edges(new_grid, 1) == (25, 25) + + +def test_update_shape_grow_single_dim() -> None: + """Growing a single dimension appends a new edge chunk""" + grid = ChunkGrid.from_sizes((60, 50), [[10, 20, 30], [25, 25]]) + new_grid = grid.update_shape((80, 50)) + assert _edges(new_grid, 0) == (10, 20, 30, 20) + assert _edges(new_grid, 1) == (25, 25) + + +def test_update_shape_grow_multiple_dims() -> None: + """Growing multiple dimensions appends correctly sized edge chunks""" + grid = ChunkGrid.from_sizes((30, 50), [[10, 20], [20, 30]]) + new_grid = grid.update_shape((45, 65)) + assert _edges(new_grid, 0) == (10, 20, 15) + assert _edges(new_grid, 1) == (20, 30, 15) + + +def test_update_shape_shrink_single_dim() -> None: + """Shrinking a single dimension reduces nchunks while preserving edges""" + grid = ChunkGrid.from_sizes((100, 50), [[10, 20, 30, 40], [25, 25]]) + new_grid = grid.update_shape((35, 50)) + assert _edges(new_grid, 0) == (10, 20, 30, 40) + assert new_grid._dimensions[0].nchunks == 3 + assert _edges(new_grid, 1) == (25, 25) + + +def test_update_shape_shrink_to_single_chunk() -> None: + """Shrinking to fit within the first chunk reduces nchunks to 1""" + grid = ChunkGrid.from_sizes((60, 50), [[10, 20, 30], [25, 25]]) + new_grid = grid.update_shape((5, 50)) + assert _edges(new_grid, 0) == (10, 20, 30) + assert new_grid._dimensions[0].nchunks == 1 + assert _edges(new_grid, 1) == (25, 25) + + +def test_update_shape_shrink_multiple_dims() -> None: + """Shrinking multiple dimensions reduces nchunks in each dimension""" + grid = ChunkGrid.from_sizes((40, 60), [[10, 10, 15, 5], [20, 25, 15]]) + new_grid = grid.update_shape((25, 35)) + assert _edges(new_grid, 0) == (10, 10, 15, 5) + assert new_grid._dimensions[0].nchunks == 3 + assert _edges(new_grid, 1) == (20, 25, 15) + assert new_grid._dimensions[1].nchunks == 2 + + +def test_update_shape_dimension_mismatch_error() -> None: + """update_shape raises ValueError when new shape has different ndim""" + grid = ChunkGrid.from_sizes((30, 70), [[10, 20], [30, 40]]) + with pytest.raises(ValueError, match="dimensions"): + grid.update_shape((30, 70, 100)) + + +def test_update_shape_boundary_cases() -> None: + """update_shape handles grow-one-dim and shrink-both-dims edge cases correctly""" + grid = ChunkGrid.from_sizes((60, 40), [[10, 20, 30], [15, 25]]) + new_grid = grid.update_shape((60, 65)) + assert _edges(new_grid, 0) == (10, 20, 30) + assert _edges(new_grid, 1) == (15, 25, 25) + + grid2 = ChunkGrid.from_sizes((60, 50), [[10, 20, 30], [15, 25, 10]]) + new_grid2 = grid2.update_shape((30, 40)) + assert _edges(new_grid2, 0) == (10, 20, 30) + assert new_grid2._dimensions[0].nchunks == 2 + assert _edges(new_grid2, 1) == (15, 25, 10) + assert new_grid2._dimensions[1].nchunks == 2 + + +def test_update_shape_regular_preserves_extents(tmp_path: Path) -> None: + """Resize a regular array -- chunk_grid extents must match new shape.""" + z = zarr.create_array( + store=tmp_path / "regular.zarr", + shape=(100,), + chunks=(10,), + dtype="int32", + ) + z[:] = np.arange(100, dtype="int32") + z.resize(50) + assert z.shape == (50,) + assert ChunkGrid.from_metadata(z.metadata)._dimensions[0].extent == 50 + + +# --------------------------------------------------------------------------- +# update_shape boundary tests +# --------------------------------------------------------------------------- + + +def test_update_shape_shrink_creates_boundary() -> None: + """Shrinking extent into a chunk creates a boundary with clipped data_size""" + grid = ChunkGrid.from_sizes((60,), [[10, 20, 30]]) + new_grid = grid.update_shape((45,)) + dim = new_grid._dimensions[0] + assert isinstance(dim, VaryingDimension) + assert dim.edges == (10, 20, 30) + assert dim.extent == 45 + assert dim.chunk_size(2) == 30 + assert dim.data_size(2) == 15 + + +def test_update_shape_shrink_to_exact_boundary() -> None: + """Shrinking to an exact chunk boundary reduces nchunks without partial data""" + grid = ChunkGrid.from_sizes((60,), [[10, 20, 30]]) + new_grid = grid.update_shape((30,)) + dim = new_grid._dimensions[0] + assert isinstance(dim, VaryingDimension) + assert dim.edges == (10, 20, 30) + assert dim.nchunks == 2 + assert dim.ngridcells == 3 + assert dim.extent == 30 + assert dim.data_size(1) == 20 + + +def test_update_shape_shrink_chunk_spec() -> None: + """After shrink, ChunkSpec reflects boundary correctly.""" + grid = ChunkGrid.from_sizes((60,), [[10, 20, 30]]) + new_grid = grid.update_shape((45,)) + spec = new_grid[(2,)] + assert spec is not None + assert spec.codec_shape == (30,) + assert spec.shape == (15,) + assert spec.is_boundary is True + + +def test_update_shape_parse_chunk_grid_rebinds_extent() -> None: + """parse_chunk_grid re-binds VaryingDimension extent to array shape.""" + g = ChunkGrid.from_sizes((60,), [[10, 20, 30]]) + g2 = ChunkGrid( + dimensions=tuple( + dim.with_extent(ext) for dim, ext in zip(g._dimensions, (50,), strict=True) + ) + ) + dim = g2._dimensions[0] + assert isinstance(dim, VaryingDimension) + assert dim.extent == 50 + assert dim.data_size(2) == 20 + + +# --------------------------------------------------------------------------- +# Resize rectilinear tests +# --------------------------------------------------------------------------- + + +async def test_async_resize_grow() -> None: + """Async resize grow appends new edge chunks and preserves existing data""" + store = zarr.storage.MemoryStore() + arr = await zarr.api.asynchronous.create_array( + store=store, + shape=(30, 40), + chunks=[[10, 20], [20, 20]], + dtype="i4", + zarr_format=3, + ) + data = np.arange(30 * 40, dtype="i4").reshape(30, 40) + await arr.setitem(slice(None), data) + + await arr.resize((50, 60)) + assert arr.shape == (50, 60) + assert _edges(ChunkGrid.from_metadata(arr.metadata), 0) == (10, 20, 20) + assert _edges(ChunkGrid.from_metadata(arr.metadata), 1) == (20, 20, 20) + result = await arr.getitem((slice(0, 30), slice(0, 40))) + np.testing.assert_array_equal(result, data) + + +async def test_async_resize_shrink() -> None: + """Async resize shrink truncates data to the new shape""" + store = zarr.storage.MemoryStore() + arr = await zarr.api.asynchronous.create_array( + store=store, + shape=(60, 50), + chunks=[[10, 20, 30], [25, 25]], + dtype="f4", + zarr_format=3, + ) + data = np.arange(60 * 50, dtype="f4").reshape(60, 50) + await arr.setitem(slice(None), data) + + await arr.resize((25, 30)) + assert arr.shape == (25, 30) + result = await arr.getitem(slice(None)) + np.testing.assert_array_equal(result, data[:25, :30]) + + +def test_sync_resize_grow() -> None: + """Sync resize grow expands the array and preserves existing data""" + store = zarr.storage.MemoryStore() + arr = zarr.create_array( + store=store, + shape=(20, 30), + chunks=[[8, 12], [10, 20]], + dtype="u1", + zarr_format=3, + ) + data = np.arange(20 * 30, dtype="u1").reshape(20, 30) + arr[:] = data + arr.resize((35, 45)) + assert arr.shape == (35, 45) + np.testing.assert_array_equal(arr[:20, :30], data) + + +def test_sync_resize_shrink() -> None: + """Sync resize shrink truncates the array and returns correct data""" + store = zarr.storage.MemoryStore() + arr = zarr.create_array( + store=store, + shape=(40, 50), + chunks=[[10, 15, 15], [20, 30]], + dtype="i2", + zarr_format=3, + ) + data = np.arange(40 * 50, dtype="i2").reshape(40, 50) + arr[:] = data + arr.resize((15, 30)) + assert arr.shape == (15, 30) + np.testing.assert_array_equal(arr[:], data[:15, :30]) + + +# --------------------------------------------------------------------------- +# Append rectilinear tests +# --------------------------------------------------------------------------- + + +async def test_append_first_axis() -> None: + """Appending along axis 0 grows the array and concatenates data correctly""" + store = zarr.storage.MemoryStore() + arr = await zarr.api.asynchronous.create_array( + store=store, + shape=(30, 20), + chunks=[[10, 20], [10, 10]], + dtype="i4", + zarr_format=3, + ) + initial = np.arange(30 * 20, dtype="i4").reshape(30, 20) + await arr.setitem(slice(None), initial) + + append_data = np.arange(30 * 20, 45 * 20, dtype="i4").reshape(15, 20) + await arr.append(append_data, axis=0) + assert arr.shape == (45, 20) + + result = await arr.getitem(slice(None)) + np.testing.assert_array_equal(result, np.vstack([initial, append_data])) + + +async def test_append_second_axis() -> None: + """Appending along axis 1 grows the array and concatenates data correctly""" + store = zarr.storage.MemoryStore() + arr = await zarr.api.asynchronous.create_array( + store=store, + shape=(20, 30), + chunks=[[10, 10], [10, 20]], + dtype="f4", + zarr_format=3, + ) + initial = np.arange(20 * 30, dtype="f4").reshape(20, 30) + await arr.setitem(slice(None), initial) + + append_data = np.arange(20 * 30, 20 * 45, dtype="f4").reshape(20, 15) + await arr.append(append_data, axis=1) + assert arr.shape == (20, 45) + + result = await arr.getitem(slice(None)) + np.testing.assert_array_equal(result, np.hstack([initial, append_data])) + + +def test_sync_append() -> None: + """Sync append grows the array and preserves both initial and appended data""" + store = zarr.storage.MemoryStore() + arr = zarr.create_array( + store=store, + shape=(20, 20), + chunks=[[8, 12], [7, 13]], + dtype="u2", + zarr_format=3, + ) + initial = np.arange(20 * 20, dtype="u2").reshape(20, 20) + arr[:] = initial + + append_data = np.arange(20 * 20, 25 * 20, dtype="u2").reshape(5, 20) + arr.append(append_data, axis=0) + assert arr.shape == (25, 20) + np.testing.assert_array_equal(arr[:20, :], initial) + np.testing.assert_array_equal(arr[20:, :], append_data) + + +async def test_multiple_appends() -> None: + """Multiple sequential appends accumulate data correctly""" + store = zarr.storage.MemoryStore() + arr = await zarr.api.asynchronous.create_array( + store=store, + shape=(10, 10), + chunks=[[3, 7], [4, 6]], + dtype="i4", + zarr_format=3, + ) + initial = np.arange(10 * 10, dtype="i4").reshape(10, 10) + await arr.setitem(slice(None), initial) + + all_data = [initial] + for i in range(3): + chunk = np.full((5, 10), i + 100, dtype="i4") + await arr.append(chunk, axis=0) + all_data.append(chunk) + + assert arr.shape == (25, 10) + result = await arr.getitem(slice(None)) + np.testing.assert_array_equal(result, np.vstack(all_data)) + + +async def test_append_with_partial_edge_chunks() -> None: + """Appending data that creates partial edge chunks preserves all data""" + store = zarr.storage.MemoryStore() + arr = await zarr.api.asynchronous.create_array( + store=store, + shape=(25, 30), + chunks=[[10, 15], [12, 18]], + dtype="f8", + zarr_format=3, + ) + initial = np.random.default_rng(42).random((25, 30)) + await arr.setitem(slice(None), initial) + + append_data = np.random.default_rng(43).random((10, 30)) + await arr.append(append_data, axis=0) + assert arr.shape == (35, 30) + + result = np.asarray(await arr.getitem(slice(None))) + np.testing.assert_array_almost_equal(result, np.vstack([initial, append_data])) + + +async def test_append_small_data() -> None: + """Appending a small amount of data smaller than a chunk works correctly""" + store = zarr.storage.MemoryStore() + arr = await zarr.api.asynchronous.create_array( + store=store, + shape=(20, 20), + chunks=[[8, 12], [7, 13]], + dtype="i4", + zarr_format=3, + ) + data = np.arange(20 * 20, dtype="i4").reshape(20, 20) + await arr.setitem(slice(None), data) + + small = np.full((3, 20), 999, dtype="i4") + await arr.append(small, axis=0) + assert arr.shape == (23, 20) + result = await arr.getitem((slice(20, 23), slice(None))) + np.testing.assert_array_equal(result, small) + + +# --------------------------------------------------------------------------- +# V2 regression tests +# --------------------------------------------------------------------------- + + +def test_v2_create_and_readback(tmp_path: Path) -> None: + """Basic V2 array: create, write, read back.""" + data = np.arange(60, dtype="float64").reshape(6, 10) + a = zarr.create_array( + store=tmp_path / "v2.zarr", + shape=data.shape, + chunks=(3, 5), + dtype=data.dtype, + zarr_format=2, + ) + a[:] = data + np.testing.assert_array_equal(a[:], data) + + +def test_v2_chunk_grid_is_regular(tmp_path: Path) -> None: + """V2 chunk_grid produces a regular ChunkGrid with FixedDimensions.""" + a = zarr.create_array( + store=tmp_path / "v2.zarr", + shape=(20, 30), + chunks=(10, 15), + dtype="int32", + zarr_format=2, + ) + grid = ChunkGrid.from_metadata(a.metadata) + assert grid.is_regular + assert grid.chunk_shape == (10, 15) + assert grid.grid_shape == (2, 2) + assert all(isinstance(d, FixedDimension) for d in grid._dimensions) + + +def test_v2_boundary_chunks(tmp_path: Path) -> None: + """V2 boundary chunks: codec buffer size stays full, data is clipped.""" + a = zarr.create_array( + store=tmp_path / "v2.zarr", + shape=(25,), + chunks=(10,), + dtype="int32", + zarr_format=2, + ) + grid = ChunkGrid.from_metadata(a.metadata) + assert grid._dimensions[0].nchunks == 3 + assert grid._dimensions[0].chunk_size(2) == 10 + assert grid._dimensions[0].data_size(2) == 5 + + +def test_v2_slicing_with_boundary(tmp_path: Path) -> None: + """V2 array slicing across boundary chunks returns correct data.""" + data = np.arange(25, dtype="int32") + a = zarr.create_array( + store=tmp_path / "v2.zarr", + shape=(25,), + chunks=(10,), + dtype="int32", + zarr_format=2, + ) + a[:] = data + np.testing.assert_array_equal(a[18:25], data[18:25]) + np.testing.assert_array_equal(a[:], data) + + +def test_v2_metadata_roundtrip(tmp_path: Path) -> None: + """V2 metadata survives store close and reopen.""" + store_path = tmp_path / "v2.zarr" + data = np.arange(12, dtype="float32").reshape(3, 4) + a = zarr.create_array( + store=store_path, + shape=data.shape, + chunks=(2, 2), + dtype=data.dtype, + zarr_format=2, + ) + a[:] = data + + b = zarr.open_array(store=store_path, mode="r") + assert b.metadata.zarr_format == 2 + assert b.chunks == (2, 2) + assert ChunkGrid.from_metadata(b.metadata).chunk_shape == (2, 2) + np.testing.assert_array_equal(b[:], data) + + +def test_v2_chunk_spec_via_grid(tmp_path: Path) -> None: + """ChunkSpec from V2 grid has correct slices and codec_shape.""" + a = zarr.create_array( + store=tmp_path / "v2.zarr", + shape=(15, 20), + chunks=(10, 10), + dtype="int32", + zarr_format=2, + ) + grid = ChunkGrid.from_metadata(a.metadata) + spec = grid[(0, 0)] + assert spec is not None + assert spec.shape == (10, 10) + assert spec.codec_shape == (10, 10) + spec = grid[(1, 1)] + assert spec is not None + assert spec.shape == (5, 10) + assert spec.codec_shape == (10, 10) + + +# --------------------------------------------------------------------------- +# ChunkSizes tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("shape", "chunks", "expected"), + [ + ((100, 80), (30, 40), ((30, 30, 30, 10), (40, 40))), + ((90, 80), (30, 40), ((30, 30, 30), (40, 40))), + ((60, 100), [[10, 20, 30], [50, 50]], ((10, 20, 30), (50, 50))), + ((10,), (10,), ((10,),)), + ], + ids=["regular", "regular-exact", "rectilinear", "single-chunk"], +) +def test_chunk_sizes( + shape: tuple[int, ...], chunks: Any, expected: tuple[tuple[int, ...], ...] +) -> None: + """chunk_sizes returns the per-dimension tuple of actual data sizes""" + grid = ChunkGrid.from_sizes(shape, chunks) + assert grid.chunk_sizes == expected + + +def test_array_read_chunk_sizes_regular() -> None: + """Regular array exposes correct read_chunk_sizes and write_chunk_sizes""" + store = zarr.storage.MemoryStore() + arr = zarr.create_array( + store=store, shape=(100, 80), chunks=(30, 40), dtype="i4", zarr_format=3 + ) + assert arr.read_chunk_sizes == ((30, 30, 30, 10), (40, 40)) + assert arr.write_chunk_sizes == ((30, 30, 30, 10), (40, 40)) + + +def test_array_read_chunk_sizes_rectilinear() -> None: + """Rectilinear array exposes correct read_chunk_sizes and write_chunk_sizes""" + store = zarr.storage.MemoryStore() + arr = zarr.create_array( + store=store, shape=(60, 100), chunks=[[10, 20, 30], [50, 50]], dtype="i4", zarr_format=3 + ) + assert arr.read_chunk_sizes == ((10, 20, 30), (50, 50)) + assert arr.write_chunk_sizes == ((10, 20, 30), (50, 50)) + + +def test_array_sharded_chunk_sizes() -> None: + """Sharded array read_chunk_sizes reflects inner chunks and write_chunk_sizes reflects shards""" + store = zarr.storage.MemoryStore() + arr = zarr.create_array( + store=store, + shape=(120, 80), + chunks=(60, 40), + shards=(120, 80), + dtype="i4", + zarr_format=3, + ) + assert arr.read_chunk_sizes == ((60, 60), (40, 40)) + assert arr.write_chunk_sizes == ((120,), (80,)) + + +# --------------------------------------------------------------------------- +# Info display test +# --------------------------------------------------------------------------- + + +def test_chunk_grid_repr_regular() -> None: + """ChunkGrid repr shows uniform chunk sizes and array shape for regular grids.""" + grid = ChunkGrid.from_sizes((100, 200), (10, 20)) + r = repr(grid) + assert r == "ChunkGrid(chunk_sizes=(10, 20), array_shape=(100, 200))" + + +def test_chunk_grid_repr_rectilinear() -> None: + """ChunkGrid repr shows per-chunk edge tuples for rectilinear dimensions.""" + grid = ChunkGrid.from_sizes((30,), ([10, 20],)) + r = repr(grid) + assert "(10, 20)" in r + assert "(30,)" in r + + +def test_info_display_rectilinear() -> None: + """Array.info should not crash for rectilinear grids.""" + store = zarr.storage.MemoryStore() + arr = zarr.create_array( + store=store, + shape=(30,), + chunks=[[10, 20]], + dtype="i4", + zarr_format=3, + ) + info = arr.info + text = repr(info) + assert "" in text + assert "Array" in text + + +# --------------------------------------------------------------------------- +# nchunks tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("shape", "chunks", "expected"), + [ + ((30,), [[10, 20]], 2), + ((30, 40), [[10, 20], [15, 25]], 4), + ], + ids=["1d", "2d"], +) +def test_nchunks_rectilinear( + shape: tuple[int, ...], chunks: list[list[int]], expected: int +) -> None: + """Array.nchunks reports correct total chunk count for rectilinear arrays""" + store = MemoryStore() + a = zarr.create_array(store, shape=shape, chunks=chunks, dtype="int32") + assert a.nchunks == expected + + +# --------------------------------------------------------------------------- +# iter_chunk_regions test +# --------------------------------------------------------------------------- + + +def test_iter_chunk_regions_rectilinear() -> None: + """_iter_chunk_regions should work for rectilinear arrays.""" + from zarr.core.array import _iter_chunk_regions + + store = MemoryStore() + a = zarr.create_array(store, shape=(30,), chunks=[[10, 20]], dtype="int32") + regions = list(_iter_chunk_regions(a)) + assert len(regions) == 2 + assert regions[0] == (slice(0, 10, 1),) + assert regions[1] == (slice(10, 30, 1),) + + +# --------------------------------------------------------------------------- +# RectilinearChunkGridMetadata metadata object tests (already parametrized) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("json_input", "expected_chunk_shapes"), + [ + ( + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [4, 8]}, + }, + (4, 8), + ), + ( + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[1, 2, 3], [10, 20]]}, + }, + ((1, 2, 3), (10, 20)), + ), + ( + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[[4, 3]], [10, 20]]}, + }, + ((4, 4, 4), (10, 20)), + ), + ( + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[[1, 3], 3], [5]]}, + }, + ((1, 1, 1, 3), (5,)), + ), + ( + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [4, [10, 20]]}, + }, + (4, (10, 20)), + ), + ], +) +def test_rectilinear_from_dict( + json_input: RectilinearChunkGridMetadataJSON, + expected_chunk_shapes: tuple[int | tuple[int, ...], ...], +) -> None: + """RectilinearChunkGridMetadata.from_dict correctly parses all spec forms.""" + grid = RectilinearChunkGridMetadata.from_dict(json_input) + assert grid.chunk_shapes == expected_chunk_shapes + + +@pytest.mark.parametrize( + ("chunk_shapes", "expected_json_shapes"), + [ + ((4, 8), [4, 8]), + (((4,), (8,)), [[4], [8]]), + (((10, 20), (5, 5)), [[10, 20], [[5, 2]]]), + (((4, 4, 4), (10, 20)), [[[4, 3]], [10, 20]]), + ((4, (10, 20)), [4, [10, 20]]), + ], +) +def test_rectilinear_to_dict( + chunk_shapes: tuple[int | tuple[int, ...], ...], + expected_json_shapes: list[Any], +) -> None: + """RectilinearChunkGridMetadata.to_dict serializes back to spec-compliant JSON.""" + grid = RectilinearChunkGridMetadata(chunk_shapes=chunk_shapes) + result = grid.to_dict() + assert result["name"] == "rectilinear" + assert result["configuration"]["kind"] == "inline" + assert list(result["configuration"]["chunk_shapes"]) == expected_json_shapes + + +@pytest.mark.parametrize( + "json_input", + [ + {"name": "rectilinear", "configuration": {"kind": "inline", "chunk_shapes": [4, 8]}}, + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[1, 2, 3], [10, 20]]}, + }, + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[[4, 3]], [[5, 2]]]}, + }, + ], +) +def test_rectilinear_roundtrip(json_input: RectilinearChunkGridMetadataJSON) -> None: + """from_dict -> to_dict -> from_dict produces the same grid.""" + grid1 = RectilinearChunkGridMetadata.from_dict(json_input) + grid2 = RectilinearChunkGridMetadata.from_dict(grid1.to_dict()) + assert grid1.chunk_shapes == grid2.chunk_shapes + + +# --------------------------------------------------------------------------- +# Hypothesis property tests +# --------------------------------------------------------------------------- + + +pytest.importorskip("hypothesis") + +import hypothesis.strategies as st +from hypothesis import event, given, settings + + +@st.composite +def rectilinear_chunks_st(draw: st.DrawFn, *, shape: tuple[int, ...]) -> list[list[int]]: + """Generate valid rectilinear chunk shapes for a given array shape.""" + chunk_shapes: list[list[int]] = [] + for size in shape: + assert size > 0 + max_chunks = min(size, 10) + nchunks = draw(st.integers(min_value=1, max_value=max_chunks)) + if nchunks == 1: + chunk_shapes.append([size]) + else: + dividers = sorted( + draw( + st.lists( + st.integers(min_value=1, max_value=size - 1), + min_size=nchunks - 1, + max_size=nchunks - 1, + unique=True, + ) + ) + ) + chunk_shapes.append( + [a - b for a, b in zip(dividers + [size], [0] + dividers, strict=False)] + ) + return chunk_shapes + + +@st.composite +def rectilinear_arrays_st(draw: st.DrawFn) -> tuple[zarr.Array[Any], np.ndarray[Any, Any]]: + """Generate a rectilinear zarr array with random data, shape, and chunks.""" + from zarr.storage import MemoryStore + + ndim = draw(st.integers(min_value=1, max_value=3)) + shape = draw(st.tuples(*[st.integers(min_value=2, max_value=20) for _ in range(ndim)])) + chunk_shapes = draw(rectilinear_chunks_st(shape=shape)) + event(f"ndim={ndim}, shape={shape}") + + a = np.arange(int(np.prod(shape)), dtype="int32").reshape(shape) + store = MemoryStore() + z = zarr.create_array(store=store, shape=shape, chunks=chunk_shapes, dtype="int32") + z[:] = a + return z, a + + +@settings(deadline=None, max_examples=50) +@given(data=st.data()) +def test_property_block_indexing_rectilinear(data: st.DataObject) -> None: + """Property test: block indexing on rectilinear arrays matches numpy.""" + z, a = data.draw(rectilinear_arrays_st()) + grid = ChunkGrid.from_metadata(z.metadata) + + for dim in range(a.ndim): + dim_grid = grid._dimensions[dim] + block_ix = data.draw(st.integers(min_value=0, max_value=dim_grid.nchunks - 1)) + sel = [slice(None)] * a.ndim + start = dim_grid.chunk_offset(block_ix) + stop = start + dim_grid.data_size(block_ix) + sel[dim] = slice(start, stop) + block_sel: list[slice | int] = [slice(None)] * a.ndim + block_sel[dim] = block_ix + np.testing.assert_array_equal( + z.blocks[tuple(block_sel)], + a[tuple(sel)], + err_msg=f"dim={dim}, block={block_ix}", + ) diff --git a/tests/test_v2.py b/tests/test_v2.py new file mode 100644 index 0000000000..798687438b --- /dev/null +++ b/tests/test_v2.py @@ -0,0 +1,312 @@ +import json +from pathlib import Path +from typing import Any, Literal + +import numpy as np +import pytest +from numcodecs import Delta, Zlib +from numcodecs.blosc import Blosc +from numcodecs.zstd import Zstd + +import zarr +import zarr.core.buffer +import zarr.storage +from zarr import config +from zarr.abc.store import Store +from zarr.core.buffer.core import default_buffer_prototype +from zarr.core.dtype import FixedLengthUTF32, VariableLengthUTF8 +from zarr.core.dtype.npy.bytes import NullTerminatedBytes +from zarr.core.dtype.npy.structured import Struct +from zarr.core.dtype.wrapper import ZDType +from zarr.core.group import Group +from zarr.core.sync import sync +from zarr.errors import ZarrDeprecationWarning +from zarr.storage import MemoryStore, StorePath + + +@pytest.fixture +async def store() -> StorePath: + return StorePath(await MemoryStore.open()) + + +def test_simple(store: StorePath) -> None: + data = np.arange(0, 256, dtype="uint16").reshape((16, 16)) + + a = zarr.create_array( + store / "simple_v2", + zarr_format=2, + shape=data.shape, + chunks=(16, 16), + dtype=data.dtype, + fill_value=0, + ) + + a[:, :] = data + assert np.array_equal(data, a[:, :]) + + +def test_codec_pipeline() -> None: + # https://github.com/zarr-developers/zarr-python/issues/2243 + store = MemoryStore() + array = zarr.create( + store=store, + shape=(1,), + dtype="i4", + zarr_format=2, + filters=[Delta(dtype="i4").get_config()], + compressor=Blosc().get_config(), + ) + array[:] = 1 + result = array[:] + expected = np.ones(1) + np.testing.assert_array_equal(result, expected) + + +@pytest.mark.parametrize( + ("dtype", "expected_dtype", "fill_value", "fill_value_json"), + [ + ("|S1", "|S1", b"X", "WA=="), + ("|V1", "|V1", b"X", "WA=="), + ("|V10", "|V10", b"X", "WAAAAAAAAAAAAA=="), + ], +) +async def test_v2_encode_decode( + dtype: str, expected_dtype: str, fill_value: bytes, fill_value_json: str +) -> None: + store = zarr.storage.MemoryStore() + g = zarr.group(store=store, zarr_format=2) + g.create_array( + name="foo", shape=(3,), chunks=(3,), dtype=dtype, fill_value=fill_value, compressor=None + ) + + result = await store.get("foo/.zarray", zarr.core.buffer.default_buffer_prototype()) + assert result is not None + + serialized = json.loads(result.to_bytes()) + expected = { + "chunks": [3], + "compressor": None, + "dtype": expected_dtype, + "fill_value": fill_value_json, + "filters": None, + "order": "C", + "shape": [3], + "zarr_format": 2, + "dimension_separator": ".", + } + assert serialized == expected + + data = zarr.open_array(store=store, path="foo")[:] + np.testing.assert_equal(data, np.full((3,), b"X", dtype=dtype)) + + data = zarr.open_array(store=store, path="foo")[:] + np.testing.assert_equal(data, np.full((3,), b"X", dtype=dtype)) + + +@pytest.mark.parametrize( + ("dtype", "value"), + [ + (NullTerminatedBytes(length=1), b"Y"), + (FixedLengthUTF32(length=1), "Y"), + (VariableLengthUTF8(), "Y"), + ], +) +def test_v2_encode_decode_with_data(dtype: ZDType[Any, Any], value: str) -> None: + expected = np.full((3,), value, dtype=dtype.to_native_dtype()) + a = zarr.create( + shape=(3,), + zarr_format=2, + dtype=dtype, + ) + a[:] = expected + data = a[:] + np.testing.assert_equal(data, expected) + + +@pytest.mark.parametrize("filters", [[], [Delta(dtype=" None: + array_fixture = [42] + with config.set({"array.order": order}): + arr = zarr.create(shape=1, dtype=" None: + """ + Test that passing compressor=None results in no compressor. Also test that the default value of the compressor + parameter does produce a compressor. + """ + g = zarr.open(store, mode="w", zarr_format=2) + assert isinstance(g, Group) + arr = g.create_array("one", dtype="i8", shape=(1,), chunks=(1,), compressor=None) + assert arr.async_array.compressor is None + assert not (arr.filters) + arr = g.create_array("two", dtype="i8", shape=(1,), chunks=(1,)) + assert arr.async_array.compressor is not None + assert not (arr.filters) + arr = g.create_array("three", dtype="i8", shape=(1,), chunks=(1,), compressor=Zstd()) + assert arr.async_array.compressor is not None + assert not (arr.filters) + with pytest.raises(ValueError): + g.create_array( + "four", dtype="i8", shape=(1,), chunks=(1,), compressor=None, compressors=None + ) + + +@pytest.mark.parametrize("numpy_order", ["C", "F"]) +@pytest.mark.parametrize("zarr_order", ["C", "F"]) +def test_v2_non_contiguous(numpy_order: Literal["C", "F"], zarr_order: Literal["C", "F"]) -> None: + """ + Make sure zarr v2 arrays save data using the memory order given to the zarr array, + not the memory order of the original numpy array. + """ + store = MemoryStore() + arr = zarr.create_array( + store, + shape=(10, 8), + chunks=(3, 3), + fill_value=np.nan, + dtype="float64", + zarr_format=2, + filters=None, + compressors=None, + overwrite=True, + order=zarr_order, + ) + + # Non-contiguous write, using numpy memory order + a = np.arange(arr.shape[0] * arr.shape[1]).reshape(arr.shape, order=numpy_order) + arr[6:9, 3:6] = a[6:9, 3:6] # The slice on the RHS is important + np.testing.assert_array_equal(arr[6:9, 3:6], a[6:9, 3:6]) + + buf = sync(store.get("2.1", default_buffer_prototype())) + assert buf is not None + np.testing.assert_array_equal( + a[6:9, 3:6], + np.frombuffer(buf.to_bytes(), dtype="float64").reshape((3, 3), order=zarr_order), + ) + # After writing and reading from zarr array, order should be same as zarr order + sub_arr = arr[6:9, 3:6] + assert isinstance(sub_arr, np.ndarray) + if zarr_order == "F": + assert (sub_arr).flags.f_contiguous + else: + assert (sub_arr).flags.c_contiguous + + # Contiguous write + store = MemoryStore() + arr = zarr.create_array( + store, + shape=(10, 8), + chunks=(3, 3), + fill_value=np.nan, + dtype="float64", + zarr_format=2, + compressors=None, + filters=None, + overwrite=True, + order=zarr_order, + ) + + a = np.arange(9).reshape((3, 3), order=numpy_order) + arr[6:9, 3:6] = a + np.testing.assert_array_equal(arr[6:9, 3:6], a) + # After writing and reading from zarr array, order should be same as zarr order + sub_arr = arr[6:9, 3:6] + assert isinstance(sub_arr, np.ndarray) + if zarr_order == "F": + assert (sub_arr).flags.f_contiguous + else: + assert (sub_arr).flags.c_contiguous + + +def test_default_compressor_deprecation_warning() -> None: + with pytest.warns(ZarrDeprecationWarning, match="default_compressor is deprecated"): + zarr.storage.default_compressor = "zarr.codecs.zstd.ZstdCodec()" # type: ignore[attr-defined] + + +@pytest.mark.parametrize("fill_value", [None, (b"", 0, 0.0)], ids=["no_fill", "fill"]) +def test_structured_dtype_roundtrip(fill_value: float | bytes, tmp_path: Path) -> None: + a = np.array( + [(b"aaa", 1, 4.2), (b"bbb", 2, 8.4), (b"ccc", 3, 12.6)], + dtype=[("foo", "S3"), ("bar", "i4"), ("baz", "f8")], + ) + array_path = tmp_path / "data.zarr" + za = zarr.create( + shape=(3,), + store=array_path, + chunks=(2,), + fill_value=fill_value, + zarr_format=2, + dtype=a.dtype, + ) + if fill_value is not None: + assert (np.array([fill_value] * a.shape[0], dtype=a.dtype) == za[:]).all() + za[...] = a + za = zarr.open_array(store=array_path) + assert (a == za[:]).all() + + +@pytest.mark.parametrize( + ( + "fill_value", + "dtype", + "expected_result", + ), + [ + ( + ("Alice", 30), + np.dtype([("name", "U10"), ("age", "i4")]), + np.array([("Alice", 30)], dtype=[("name", "U10"), ("age", "i4")])[0], + ), + ( + ["Bob", 25], + np.dtype([("name", "U10"), ("age", "i4")]), + np.array([("Bob", 25)], dtype=[("name", "U10"), ("age", "i4")])[0], + ), + ( + b"\x01\x00\x00\x00\x02\x00\x00\x00", + np.dtype([("x", "i4"), ("y", "i4")]), + np.array([(1, 2)], dtype=[("x", "i4"), ("y", "i4")])[0], + ), + ], + ids=[ + "tuple_input", + "list_input", + "bytes_input", + ], +) +def test_parse_structured_fill_value_valid( + fill_value: Any, dtype: np.dtype[Any], expected_result: Any +) -> None: + zdtype = Struct.from_native_dtype(dtype) + result = zdtype.cast_scalar(fill_value) + assert result.dtype == expected_result.dtype + assert result == expected_result + if isinstance(expected_result, np.void): + for name in expected_result.dtype.names or []: + assert result[name] == expected_result[name] + + +@pytest.mark.parametrize("fill_value", [None, b"x"], ids=["no_fill", "fill"]) +def test_other_dtype_roundtrip(fill_value: bytes | None, tmp_path: Path) -> None: + a = np.array([b"a\0\0", b"bb", b"ccc"], dtype="V7") + array_path = tmp_path / "data.zarr" + za = zarr.create( + shape=(3,), + store=array_path, + chunks=(2,), + fill_value=fill_value, + zarr_format=2, + dtype=a.dtype, + ) + if fill_value is not None: + assert (np.array([fill_value] * a.shape[0], dtype=a.dtype) == za[:]).all() + za[...] = a + za = zarr.open_array(store=array_path) + assert (a == za[:]).all() diff --git a/tests/test_version_derivation.py b/tests/test_version_derivation.py new file mode 100644 index 0000000000..b9e3e90551 --- /dev/null +++ b/tests/test_version_derivation.py @@ -0,0 +1,34 @@ +"""Sanity check that ``zarr.__version__`` looks like a v3-or-newer release. + +Background: zarr-python derives its version from ``git describe`` via +hatch-vcs. The repo also publishes a separate ``zarr-metadata`` subpackage +that uses ``zarr_metadata-v*`` tags. Without the ``--match v*`` filter in +``[tool.hatch] version.raw-options.git_describe_command``, ``git describe`` +walks back to those subpackage tags and reports a version like ``0.2.0`` for +a from-source build of zarr-python itself β€” see +https://github.com/zarr-developers/zarr-python/pull/3994. + +This test catches that class of regression: anything that makes zarr-python +report a version lower than the v3 release line. When 4.0 is released, +bump the floor; that's a deliberate, one-line edit at a planned boundary. +""" + +from __future__ import annotations + +from packaging.version import Version + +import zarr + + +def test_version_is_v3_or_newer() -> None: + # Use packaging.Version so we transparently handle hatch-vcs dev suffixes + # like "3.2.2.dev30+gdc5e1825" that appear on any source build past the + # latest v* tag β€” Version.major returns 3 for that string. + parsed = Version(zarr.__version__) + assert parsed.major >= 3, ( + f"zarr.__version__={zarr.__version__!r} is not on the v3 (or newer) " + f"release line. If this fires on a from-source build, check that " + f"[tool.hatch] version.raw-options.git_describe_command in " + f"pyproject.toml still includes ``--match v*`` so the " + f"``zarr_metadata-v*`` subpackage tags are excluded. See PR #3994." + ) diff --git a/tests/test_zarr.py b/tests/test_zarr.py new file mode 100644 index 0000000000..f49873132e --- /dev/null +++ b/tests/test_zarr.py @@ -0,0 +1,29 @@ +import pytest + +import zarr + + +def test_exports() -> None: + """ + Ensure that everything in __all__ can be imported. + """ + from zarr import __all__ + + for export in __all__: + getattr(zarr, export) + + +def test_print_debug_info(capsys: pytest.CaptureFixture[str]) -> None: + """ + Ensure that print_debug_info does not raise an error + """ + from importlib.metadata import version + + from zarr import __version__, print_debug_info + + print_debug_info() + captured = capsys.readouterr() + # test that at least some of what we expect is + # printed out + assert f"zarr: {__version__}" in captured.out + assert f"numpy: {version('numpy')}" in captured.out diff --git a/tests/v2/conftest.py b/tests/v2/conftest.py deleted file mode 100644 index 6680e4066b..0000000000 --- a/tests/v2/conftest.py +++ /dev/null @@ -1,7 +0,0 @@ -import pytest -import pathlib - - -@pytest.fixture(params=[str, pathlib.Path]) -def path_type(request): - return request.param diff --git a/tests/v2/fixture/.zgroup b/tests/v2/fixture/.zgroup deleted file mode 100644 index 3b7daf227c..0000000000 --- a/tests/v2/fixture/.zgroup +++ /dev/null @@ -1,3 +0,0 @@ -{ - "zarr_format": 2 -} \ No newline at end of file diff --git a/tests/v2/fixture/dimension_separator/flat/.zarray b/tests/v2/fixture/dimension_separator/flat/.zarray deleted file mode 100644 index f265bb0674..0000000000 --- a/tests/v2/fixture/dimension_separator/flat/.zarray +++ /dev/null @@ -1,23 +0,0 @@ -{ - "chunks": [ - 2, - 2 - ], - "compressor": { - "blocksize": 0, - "clevel": 5, - "cname": "lz4", - "id": "blosc", - "shuffle": 1 - }, - "dimension_separator": ".", - "dtype": "=φ^Ξοϋήr}εΉΟΌόνQχ>ΚΧ/›/λ·O·ϊκλ{”/χώτΨκυ­½κζΙωΫ―.η―?^χkς_yι«?ύΣόk―ω±{δφ,ϊϊήιέΗk―ύ±~ϋ.φή=Ÿή―}ε§_ωωϋ>‹Ÿζωή«_ΏμύΪΧώΛoΎyΧύ[ύςΫΏφ=ύώφΙφ-^}ωΣ―½—ΊΏτςϋύ―½+ειΛν[{WΏΏ§ύέ—―_ώΤίΎ+Ο}·§ό§ά{Νο>]vΏχκέ_ϋžφ­όξέSWήΪ«_―{χθW—―YΏ}q{žϊΫΫ½\^ϊbϋdο?ΥΧΎ•§?Ύό~χ/^ωζ­~ΏoyήΧTΫwε›'»W½ό§ο}z_ž~ωΪ§ήήΎw\ίς§ηοώνžξΛ[}εηνS—υΛφΛϊΛoΏμ½|ε©{__ίγbσς·ε§κoίΚO_ϋ–Κoy²χζ_μ½\Ÿί³=ζ/ΊΏϊΤεϊΪΧwνS—νS―oυ{/›§ΎςλΣ/{υ]Ίyφ]μύSξχΜ–Χχ*/=.ίο!ηοήχ§—§~±χq}qω‹υ/φ}rωέ»ωΧΎ§ώϊκ/Ο{χθ—υΏΝΣ_~{Υε˟ή{?εφxοΏG~ογε_{ν+SΥ―~ρ΅'½χϋYΏύoύζΕλϋΩ'{οως«Η}―‹W_χξ—ΝΏtύ±ίsυ_{Ν[{V_χυ_lώ·ϋΜ“ΫΣώΥ—ρυή+oέ_ϋ|ŸώKχ=ϊΣΫχΣωφΙφΉη)χύΝΏξ—Ώ<χ]|ε©›wνU_χkΏύεεϋ!V_ύε―ώφΩ/wΏόλ{<υΫgΏό6Ώχϊύzϊ•Φοώ‹Ν—έgž~uοσ―ο‘ώνχσ^ί}ξ—Ϋ·ξΥeσμ—ίήλ{Ϋ~χx_~ί#οΊWοώΣΌλήύφ«—Χ{bχΕζ½εςλσώιΎuoώΫ<ύ²ωqί'nŸχw_ž~Ώ—|έšΧ{̏—nŸά}οΛ»ή—ίϋψκS·O―}ίή›'›Ÿ~½―}ϊ}ΟΚχ^^ύζΛξ‘ίϊΧώφ•οώ‹»_{ΊΏϊ½—ΫWŸ|ελ_ωνΝ/{VχεεΣWώυΛkOύϊeχΕέ›/ηo₯η/?ξ^vοΚ7/φήό8β΅ος?έkώΪγ{Μ—υΛξΏξσ―½ήη_οI7/^{ΣνΣ―.λ_{άΏϊ―όKΏφxνήξ{ίΚΏτυ=|\χ‹λWΏς>Υλσ{ΘWΎ{ίή?υ·Χ>Ω½Wώ₯—Ώϊ½Χνy{ε«ΏeχvοΏ}ΛοϋδςΛ»tύqϋϋ₯_χιφ-ξ=λϋ€―=ιεΗζ­ϋ΅wωWώΥχ6οςϋ^ύξΙο{{Ο₯_yφ—WΎΊlΎϊΫΌΛoŸ~υ΅§ο©_ΎξνΛΧχLΟoŸ{τΗε/SέΌkϊ[Ύϊ<ο―χλ—½ΏϊυΛε―ί7½ίGΆΚχ>?~Ϊ·όζΕξ½ξ}χκεΥ§ών½yrύ~Ώ΅'έ{ρΪSΎχυ·W]ΎόφΛ+―}εΗΛί^σ/6OΏΊμΎΈ=Ϋ—ΏχΚW[ύiοΉςίξΝΏςν{ΛWΎϊΕφλT_Ώ·ωώ^r~σϊΎι‹?Ν³/φ{\ωOύkΏχΎW]Φο^ύκςεW·[vΟΕυυϋΙk―ώυϋ”—nή[φ=Χ}ύνυ>½}q~σΣυ_\žύ²ωφλ—υ—WΏόΤίϋμ3/Ξ-»Ο~YΏΌφτ}ΜΛιΎwωWώΊ―Wίzώςε§}λήΌΨ=λ{δ/ί=²ώΕOϋΛΧ/·―Ύ·οyλ_ύνmΟbϋΜ»τς{οβOϋέ#Χ·ς/ΏΊο-ΏχιO―έ§λ—Ν7O½ϋk_Ίy²ωr}Ύ§ό₯ηΏϊήκϊεφ΄ο­Ύή_žϊΕξ‰ϋ>qωρΧ{ς_zωφΙ+Οχ–—_vΟu―.—ί^σΣמ•—―>οεOχυήξεφ_ϋ.ύΪλ½άΎφ,^ϋυ»gυ•§ίΌuν]ΊyWΏ{βφΛζ§―=κήΛϊεΛο{eοΥλσύΎO}ρΚ7/vŸ{Vήκο~ε―Όόέ›Ώτ§yή?eσύ^κν7ίχΘωΝ7Ο>ύςε7q{―<ϋeσΝSΏξΥε·yω{oάο«Λω}Ÿ\^~ΩχΘϊΝΧ/λΏς{―yΫ'—ίχ0/½ώ8Κϋ)}ε­Ύ΅ΗχΘζ«―ΎφtΏϊΥί²ύΧ>uϋ.=zίΊΧ/―οsεωώφ•χ–―ΎKwάžχϋWΎύΧ>υ‹ΧχΉ~χΖφ΅ίΌόιrώ•—ιέ—/wŸ.η7_~ϊύVΎύζ«Ϋ§_½ϋή·Η{uστ_zyφΛν1OΆε—§n^ϊς§·Χ~yε―{σγ§{VŸχ±{ν3oω{χqϊΊ_{.ωλήύ—?½½‹λK—»wΕΧ^υ·lΪί{Μ_ώυ^ύ«ΊOΏφ|ͺ—ο^σά/λ/―|uοσχύeοΥ―<ο/^y½Η~σσ«ΛφΙW^ϊϊ~KoίΥ·τΥχΤυ—οχς=?­»_ΎϊΪΧϋή²ωφΛζ«›§_]ΞτχΘίϋΝsίεzΏφ=½_{ΫWΎΌή“ί~οΥ?Ν[ϋ―ό·Ί~Ωύ—ήχhΏχ—ίΎξϋ=δεoΟΛ{Ϊiž{ί²ϋΦ}ϋεή{ιφΙλ~υ]ίΏΌφΩη½|έ§·ΟόK·oέ·Κ[χOχΉΗ>YΏύ²ώς~κ}ευήΕυ=έ“ί<ο}ο§ώϊΜ//]ΦοžK/οϊ~κξYϊ΅Η}ν1±ωryξ‹WΊyoΩ|ΩΌφϊήφxωΥW_ωϊν»Έϋςμ“υΛϊνW—Λλ{zŸΎφ^ώξΛ—½_ϋκΧo^œ_^ωk_χκζ§Ί―ϋ·}λ=kŸώ΅wέ·/έ<υ•ί{Υ―Ός»—½—σ·?.oωΣσwvΏ~σV}ωΫ³όιω»κχ>^ϋΣλ“λOΚ«οι}}νyš—ίουν½yξ“W_ϋςχ=V~Ί~Ωϋ‹»_{žξο~ωΫ―ξΎφδΛΧ/λΏϊΦ½ύr{μ“―~ύq}k_ύκ—ν}ϋΜσ½ιω―}ήΛWήεWΏφ\z{ϊžOΉο‘?vŸ|ωΥcχΥ—Ϋ'λχϋ\~υ·χW[]Ώϋδ§{ϋήϊλ{ͺΫ/—Χο—§_{ΎυwoΏάί#——νOΧΧoώ[.ΟΎ§ωέηΝ[όν^οΧχlŸΊl^οYχιλ}Oυς—_ύ)ϋžλ½—ώtίΣοαΎ§ω½ιήόεǟφϋΎςάSίςΫqyυΕεΫ/ηχώβςέW^ϊβςמξ—ή½ωξ‘/S½~σεςςΛϊ}―ά}ίΗ{υΈώε_ϊOωΫλί'―ώςήκζ»'^ωWŸχ«oελ—ΛοχzΚυ­Ό₯_ο]ykί·y«―ύ~ϋδόήΗφ½½Χož¬[^ολχ1?Ίϋϋ>ρς{/―ώςŸϊλoOχ±zΌϊΣ»_yή_{ΥΛ―Oέ|Ή{χΕζΙλΎ=—nžμ^Ή|ϋδή£ίΎ‹ίφλΏΨ~χΖΎGφύρΫ~ύυ—·φ^{.}εΫwν{»χΚ³Κ_yOίφ~ωϋžξΥ/ϋ^ωΚKχ½rϋΜw|ωλ/ί{Ω<ΉΌ§ϋ½—ν/Ώ½²~Ωόξέ+Ϋ—nž}ε{/ωήλ—σ{»χς―ό΅ί|οΥWωι±yκζΛωϋ+/=ύρν3_~›—Σ=έ·ί½κkoύήΛε=υ{o₯Ϋwέ›'{_~ίoqοM_l_ώ·ωϊλ»ςΥeχ¬οQŸώ•—ίζε/?^ί'=Ϊγ}¬ίο£.λwO\ŸΌξσ/½χ.½ϋŸκ+Οχ—ίž8ΕΧώKw\ϋV^zώ΅ΚΏξWΏ}ν±OΎϊԟφ·gωΫ§ξ>uΉ}ε-~ΊΗώςΦύς»§{ύΎGύκφήόΈύΧύ‹{zlΎόSολ=υΛν±OvίΚ+ς_ϊ·ωήϋυΈοχΩ<ΩχΙεΥχφή<οε«OΏμ}ΌΎϋ.zίcρκ˟ΎϊΝΟΏή»tσΧ}}ϊεkΏώΥΧήςꏗnž}YW,ά \ No newline at end of file diff --git a/tests/v2/fixture/test_format_compatibility/array_15/compressor_1/1 b/tests/v2/fixture/test_format_compatibility/array_15/compressor_1/1 deleted file mode 100644 index ab66664703..0000000000 Binary files a/tests/v2/fixture/test_format_compatibility/array_15/compressor_1/1 and /dev/null differ diff --git a/tests/v2/fixture/test_format_compatibility/array_15/compressor_2/.zarray b/tests/v2/fixture/test_format_compatibility/array_15/compressor_2/.zarray deleted file mode 100644 index 26ab07b3ec..0000000000 --- a/tests/v2/fixture/test_format_compatibility/array_15/compressor_2/.zarray +++ /dev/null @@ -1,17 +0,0 @@ -{ - "chunks": [ - 3000 - ], - "compressor": { - "id": "bz2", - "level": 1 - }, - "dtype": "ύϊ—ηΓΛ…ς <ˆη—ΗΏΊευۏύωΓΏώόΡΊŸ?6Ο>πζΓC9ίσΎΎδΆξλK½(n_ήιη§Ή‹r`ϋs?ζπΣαωΥϊψƒyξ6‡/‡A:55κ«‘<υϊυίs•ηgυrVoώςόέήί­ΟCϋάΞ±ϋ¬ώVΫgsΥφΩξΗ>?Ομ娝Γδϋ”g―E9Ÿζ™ΓσΙΡ‡όϊο΅Χ-ο3Ί»η•‹‡;/Wζ_ύΦφj”žχ§9tζQβ·ζ[½Zί^PŽΎzQΞα³ος|ςυεC9ϊ|x:}yt·>ž^-wQ>ΎkΣςœΙ£ƒΛ«ν!_βϊτρj~όζβWO·ύΥmίΌ£σsΏ/σ=$’Ώs£Ώρ›#^.~ux¨Ώχ‘–·Ψσςϋ5ΎύωώΥ7·λά£ύ ΌΥoχμ:{˜εΘ7―ΦΗΛWλoξκnύφη>ψνa”§―ήΎόΦ=笓ΟΉΠήό°ϋy~δΠ­ŸΞžτϊ‹τΛ«ΧOΏΌyϊ·Z>δΣίϊθςz˜{~nΠΑ#ΆξόΝνΌμ7sΆO·ω|Π^«“G§ρŸό·ό-Oί9voήφ.οuηϋ}οώωfμ9RaΎΟιν©ξω™‹§7š@·―Φ—§ήœχ½ς{Ψφε@yζ›«¦ΗCύvξQεg^ΏO~σγ=’7g}tΛ«‘œ­w>ϋhύσsJŸή>κΞw?ω|‘ߜέCύŽΟηφ–»ΌΊχέχMή·«³ώϝγy›#ο}Ώ£ώϊΚϋ‚ή|ŠΕ[ήϊΥ‹φΌεθσ©ιΥσΊ©{Oζτ~9ΟχώηλNνaΞ;Re?ϋΈΗφΡΓΌWΗ/O―ξώύό|oQί†[Σ»'}ό­Ά―Ύϊ6G>]ϋrΞυ―Ο^«λΌ}¨σ~Ϊ\Jό’yψ۞tϊκš{Π~ΟΟyοσ“B‡Q›oΞςϊ‹tςτν‘ΦotžΌ_[^^Ο‹_ξϊŸΧ__Ξ{΄ψθω)³=€λš^7ί£ζΠΓ£δΛύHpΘ§†ςωδ6Ÿ|<κρζmO·yxΘΟŸ{’—Gυε©‘<}9jΊOΈzσ‘9ς—ηΧίyΫη§—O·}:|λŸχyΣ΅/οΌ½Νƒφο|Οsφΰ[ΏΎΉt‹Ϋη‡φ‚Νsϊώ§ΛχΦξ'oΟεoσροώΜ—·z><‡ϊΦ—GooΘ―孟^β‘Hεͺω Ύ=‘ΎΛƒέ·MžLc>7ΝΣWΓΓG―¦ί=Τ­ΛϋΠΎtjσΤπ¦3Ώρω>ν=Zύ’3Ϊkφγ[>^^η<οE^λσzβεΛλ:χ oωpσ6gkyx(nξΞοZj>Ÿ0tςΰφιΰφOϋVwή>ηΟΟ{ωΞ½~sεoMΏ~Ή|ϊjύEyί{δ\τ;‡oϋ[wnž»Ϋόυw½oΘλA'ΧΎ°ωηsδ<φUC~5Ήζ4fίυ©εΎη˜’sO {~ξ[]ΟΛλΝo/5|η₯ηύcΞ"?δTΣ«{Ϝ‡ΆNjτzω‡NΞκθρ·<:9πΖo_nc>ί—·œξo•ηhυ»Ÿϊ$<οgύφΈιυωδ«o>:θD[―ί<:hžΎZzuχσ~ᧇ|ζπ«ιψιιιψ <ˆη_Ÿϊ}ήσύΫyyρζΚΓ«σyxx?σ\v^ξYΞζ«ωœςΑOΊw_φήyrω žΎωηΉτνΗΏ(οπ~ζuϋ€—o^λsN<έϋܜcsιωε̜ξλ>suZŸηqσΥφβ·—>ΔCzσšίϋ¦†>/ƒrΜ£„›Oo}Ό5έΦx¨Οo>ΌυΧOg―Eω«SΛγΓσ-5Ÿη€ύωύωΥpχ9:?σω„|§Ξs_€[ή7€Χ7ί½4Ÿ=VGoΦs›ϋ5ŸŸκŸ„ψ%6κΓξώώξfrsΰΡE·Χζ4Ÿs-Ά?Ÿ[7~σννkŽ>¨Ώυϊεo_Mg~λΞΡuOpω<'φέyr!€ƒyŸρΣύY”ε@9[ΣΫO}ΠϜŸŸξέGϋžΚsm”·sΤού<Ÿt{^Ύoώž‹Oύj:σε@<έζΙΑ7ΊΟΉ‹Η—ϋΤ—#‘Οάυισ©εͺ»Ÿοw<€ηΏρG—{ρλΏc>§ψvή'ήϋρσαακι짆τπ–Γo>}#•χUξ­uy~ρ½OήxsΥ‹&Σ94‡nQΎ}yΛ§λ:Ο½ώAχ‘ηAώ wyψž«kΞ}_~{™―†›OΗ―6yυοΊμG;oορωΌ¬~χΠ‡ζΌοŝύψV―–ηΎ$θ«ι6^κC9rω–οΪyr|‹|PΏχyΎ/oϋΙ±/\^ {žύ3wsψ }θΊ–μyqu~ŸΛΌΟδπ-κΫΗύJΖ―ίϊΌžτέίϋΚήτ=W•άΫ\sφ<τ!^_ο‘Χƒ/Κ•ιψρζσι«υ[ίέTΉΟΞqŽ(ν#ή|ϊφi”ϋόα3Ο‰WΣΫ.ίΎΜΗσΙέΉΫο:yίΟ•ώΌgΈσΥςΥτψSg΅ώϊΆv.<”εΪΟ}αƒς1ο9ω½«η‡?ώΜλܜŸίh>l欞«ρΠϋΰ‘<}5€sξΥαα»/η’'G͏‡‡ΟΟΝWGρϋΏςœo>=l_φΤ·‡5€ΣWλCόmήαν σ=)Η9ϋτ­~sΤ°σLΙχ’Ύ\HΉ9ίλν›χ{ΰSΛ‡ζBsυΥPΞκυρPNΧφΝ}ΘmάώσΉ’o>ΌΝλό|ώτ=I}Ξ—)»~Ύ;Χ~°ύ™«o?H―/_½}>:}θΫ—wCώΝ§Χ‡xσπζ6ζVίΎ<ςΏχηυrώ­εΰνAo}zΌšώ{]φ⣇ζoώ{-zνΕ/Ώωϋ}Kζ‡νΟο―ΞωΝ…rΤ«WοœυιΛYάώΝOgΌΪyδΐξηώozΉ7ζ}ͺΝ‘{CΊFϋζ{Υ=μ~ŸrwOz|ηfž>\ή>·ύ—ίœžοάy~wύςο{˜ž< ½ΉΫWΣΩ{ΎχVΏ>ωψ›^ΩKξΉθ‘>δΣ_άΎ}ψoHgOΉτjH―^>^mΏ#nύϊςΥPŽ>ΏΉj}ϊνwΚ~Ψ9ϋύεύ#G χϋ>~ΉζH€φ‘SλΓίΉy_jΊ³ΌΪΔχΌά+½θΥ|tjΈυm/ύΥ«ωΜο:ί+Λ_#ε \ No newline at end of file diff --git a/tests/v2/fixture/test_format_compatibility/array_16/compressor_1/1 b/tests/v2/fixture/test_format_compatibility/array_16/compressor_1/1 deleted file mode 100644 index 41b2124f0d..0000000000 Binary files a/tests/v2/fixture/test_format_compatibility/array_16/compressor_1/1 and /dev/null differ diff --git a/tests/v2/fixture/test_format_compatibility/array_16/compressor_2/.zarray b/tests/v2/fixture/test_format_compatibility/array_16/compressor_2/.zarray deleted file mode 100644 index 59f8cc2b9c..0000000000 --- a/tests/v2/fixture/test_format_compatibility/array_16/compressor_2/.zarray +++ /dev/null @@ -1,17 +0,0 @@ -{ - "chunks": [ - 3000 - ], - "compressor": { - "id": "bz2", - "level": 1 - }, - "dtype": "ηάηϋόžοφΌJό_ω’ΕrβΕr {ϊ­…Εφ^₯Šε†bQ0ςΐβτ…ί.ΟzώVδΈ^όΧ‘‡Κ7Iώώ₯‹v°Ο†;WžΚpΗΰΥn©ϊΑM€Ϋ­ξ―πƒΩW’§±ίHž -£ΌΫδ+MŸηπ¬(Ο΅μwγρ¬|OΑ†{ά!ςξ¦—!/ΑCXΑxΩΗΏ…¬! σCϊh­ώΉς΄Eω*ςΟgΔ>Nώ#ψ›²wSoυμ‡ι―-9ύOβίןύpφ"ψ‹ΤίΖ>n·Ύ2N΅ΰ·~άΌϊΡ#VΚχ3ϊ Ό–6ζ/Εώ’όYj©[)n)^Δmc?ΗΈί!οBuOgΑΎZQμΥεΚήA½}π—ΚσΊkΥ»ώ \ήƒ_Ψ?€ϋ‡Ό/«ΧΎ=½oxβQ!Ύ#}—<Νΰ—°W•o4Y…ΌLΏ¨s%|φJςΝ&―‘χPϊDυ;‹Ϋ(ο8zΦ£+ΰnε_ Ο`ςIυΛ‘«ΰ*«σ>ά\yώχά…Ζ³9ω‹ϊύψϋΐίΙΎ/υδΝϋ™ύΒuϋΚ7 n‘ΈσΟ ως~¬W…̼ؐ> Ύ――R±Έ‘όMθα·Ζψ}ŠΧ&υ?¦7’§¬)Ύ <ϊl²%ϋσdKόžφΌ²―;μΟi4ύΈό~Ϊ±“o;ζΏ:ϊͺ¦NyϊψΗΨˆ»¬χ/Ό―ƒ―¬^)γ2.}‰›+1άΥp;α–ΑeΤVήΰΊΐΘΣ Ώ6Ζw{iΈœc&ΐ­%GΑGωK«·™=ϋΧ!βΦΙۏΌώ5ϊ‹τvϊθ.ξ{ω:¨“ηyΊͺψωδΧπWβy6ωŒ|Γω³οϊBήΪκfέΚ{ΆΔψ !,~ ΎύΔίHώΏΊΊWΑνRφWα.ΰΏ…ήUυΰποΐο φkΰN–·Άϊ5δ9‚=λKquΰ²Ν>γωkθ³zΖKύWι™WΎQ?λί0y/e˜ρW“d.˜­N7φr-Ε7ΣΗJυ˟sAΞU‹ωΏ“/σQζ‹<›δΟΌ½ώ υ -Υ›ΐήV½Μmΰ2ί~Ν?Oύβσ;›§―ό[Γ?ΚΎΜσΘΌ˜σΥ4ώς͐Ώ5=η،ϋ·π“α²n^©dφK™'οΟβGʟυ.Ώ‹x.Ε8zγω&ΉLύΜ‹-ΰή&Vo„<ΩΟΥQ·7ž«θ9ΏδwXΟ’βΣ_φΗ“ΔέA–€oGΞ"sή~―λρ:δεψd½Ξϊ:?ϊn$O}yjί%sκΔΏ^ή πΜΌ“}ΐVy'θ³’Έρδ²™{Ÿ -x=ΟήUόής;κ ξ\Έ>⚫»ﻌWy^!snlwωΊ|―Λ3~ΩJ?™_²Ώ¬39ΏηTςuς;ιˆ_Φ“ΌχΉΚ}Τ‰x-’²Έ™ψP –γ9ξlŽFp―ρg1†ž{¬χo²Ώ’ξ£β§Σsου-ϋVφΘΖc™Χ³ε\ΦΠΈ4…">χσροE.β__ξίρμχΑυΧέΈηή!ηδ)ψgߝυθe|rΞl‘Ÿšψ–’/χ#“Τ}Zέβ_%Ώβ―ƒΟ™β³ίh@ο―ΞHΌvΡ«¨ϋ$\ζΟ»ψ—uτIφœ―³οΝΎ5ϋ₯œ;s.8RέUβ{ΰϋ₯μ Θ¬πϋQΩ_u‡ϋXίίΙs\ώ¦Ζg&ΉƒΏΆϊΓυ]€Nwφ«ΩsΊ[\φΧΈ{ξ—ΧMpΉ?iό&ρΏ₯Nφο{θ?ΐύWή5Ζk=λκ;ψ}ΐήZΏωξ³@μ³ΏΛΉπAρy§‹?ούx4WΏ™|½ΰ抿œύrψ¬/Ÿθηώά{εΉ\ˆwΦ‘ΖκdήΟϊPŸάεΌ°XόρκΎ§^OψœΒ·όΔ=ίΏzμιλTφάe=Νώθ=ώ¬ƒΛΤyBžΌΏΉί[€^<΁ΎϋtόsŽιΙ^¨Οcπλ!~;ξέ²N=˜ώΘάƒœ_I|Φ+jAΦ½Ψ‡§žCδ»_―πΒ;λVφ‘xΟ_U|Ζk)=ίΓ*Β„η‰ϊΝΌŽΊƒψK‘SΤιLΟώ―=χ%Εηόώ9_d^Λ~―¦ώΞΗλ -ϊέϊν¬ξαόΉŸΟωi{φΗEβΏbΟΎσzψgŸ|‘ό9mΦOή‹EςέFώSϋΔ₯κτμ―‡׍ϊΘ|Χσ O}ΌŽ…λMξKφΊμΉ―h€ή(uvΐεά»Ώ,ΦοΡϊ« Ÿ}qΎTβί ώρϊΞό“ϋ‡ŠβO€["ξφƒΙΟΨW’™ΞΟρSΥιi\ŸοΠ97η;~ξ«λŠ―ίVϊ=J|ΞEyςτmώδFό -Ε―₯—αοƒožή“<άμ†kΟ@zή—.ς―f―MΆ"_Tw+άχκg]ng|ςwGo€Λό[Mύ5Ζ'χ"Χΐ)ξΕ³x@\Ξ+sΰξ$ͺχ˜<“=Ώ|‡Λw†FμωN}ΠP|²Nι{ŽΊΛυŸο:ΩΗeήΜ½XζΝ+πxFήδίΥΟωp5ή Ψgͺ3Jέ—πΨHί,Οcβςύώ<ϊΏασ>ηώ6λΫ<ρ97―‡+>χ™g:ι#uކΟwίCπ>B|Ζ)η“JžΟυβς)χΰΉίZ·ξaςdγq*ζ•πϊ‰?ϋΌ›ΰržΏ_¨!_Φ…¬»ί‰Ο=ΗopyΆ―Ζ!οIξmsŸρΚ½ΤηΖeΈηΦQ|ζ­{ρΜϊ‘Ώwh? ώ-ό²^$.ωΊ«ΣΖψΟχ΅>ŠπΚΏ‰=σɁςŸΔ€ϊ%ε©L^̞χnlόκoη―‡_ξ‘²θȟω~Ÿψόή2ΞeρΛΌŸϋ­ήϊ¨G>WWύΣδΛχηίu­S \ No newline at end of file diff --git a/tests/v2/fixture/test_format_compatibility/array_7/compressor_1/1 b/tests/v2/fixture/test_format_compatibility/array_7/compressor_1/1 deleted file mode 100644 index 2755ef8b40..0000000000 Binary files a/tests/v2/fixture/test_format_compatibility/array_7/compressor_1/1 and /dev/null differ diff --git a/tests/v2/fixture/test_format_compatibility/array_7/compressor_2/.zarray b/tests/v2/fixture/test_format_compatibility/array_7/compressor_2/.zarray deleted file mode 100644 index f534454b54..0000000000 --- a/tests/v2/fixture/test_format_compatibility/array_7/compressor_2/.zarray +++ /dev/null @@ -1,17 +0,0 @@ -{ - "chunks": [ - 1200 - ], - "compressor": { - "id": "bz2", - "level": 1 - }, - "dtype": " None: - g = group(store=DirectoryStore(str(tmpdir)), path='utf8attrs') - attrs = {"foo": "た"} - g.attrs.put(attrs) - assert g.attrs.asdict() == attrs - - def test_get_set_del_contains(self): - store = _init_store() - a = self.init_attributes(store) - assert "foo" not in a - a["foo"] = "bar" - a["baz"] = 42 - assert "foo" in a - assert "baz" in a - assert "bar" == a["foo"] - assert 42 == a["baz"] - del a["foo"] - assert "foo" not in a - with pytest.raises(KeyError): - # noinspection PyStatementEffect - a["foo"] - - def test_update_put(self): - store = _init_store() - a = self.init_attributes(store) - assert "foo" not in a - assert "bar" not in a - assert "baz" not in a - - a.update(foo="spam", bar=42, baz=4.2) - assert a["foo"] == "spam" - assert a["bar"] == 42 - assert a["baz"] == 4.2 - - a.put(dict(foo="eggs", bar=84)) - assert a["foo"] == "eggs" - assert a["bar"] == 84 - assert "baz" not in a - - def test_iterators(self): - store = _init_store() - a = self.init_attributes(store) - assert 0 == len(a) - assert set() == set(a) - assert set() == set(a.keys()) - assert set() == set(a.values()) - assert set() == set(a.items()) - - a["foo"] = "bar" - a["baz"] = 42 - - assert 2 == len(a) - assert {"foo", "baz"} == set(a) - assert {"foo", "baz"} == set(a.keys()) - assert {"bar", 42} == set(a.values()) - assert {("foo", "bar"), ("baz", 42)} == set(a.items()) - - def test_read_only(self): - store = _init_store() - a = self.init_attributes(store, read_only=True) - store[".zattrs"] = json.dumps(dict(foo="bar", baz=42)).encode("ascii") - assert a["foo"] == "bar" - assert a["baz"] == 42 - with pytest.raises(PermissionError): - a["foo"] = "quux" - with pytest.raises(PermissionError): - del a["foo"] - with pytest.raises(PermissionError): - a.update(foo="quux") - - def test_key_completions(self): - store = _init_store() - a = self.init_attributes(store) - d = a._ipython_key_completions_() - assert "foo" not in d - assert "123" not in d - assert "baz" not in d - assert "asdf;" not in d - a["foo"] = 42 - a["123"] = 4.2 - a["asdf;"] = "ghjkl;" - d = a._ipython_key_completions_() - assert "foo" in d - assert "123" in d - assert "asdf;" in d - assert "baz" not in d - - def test_caching_on(self): - # caching is turned on by default - - # setup store - store = CountingDict() - attrs_key = ".zattrs" - assert 0 == store.counter["__getitem__", attrs_key] - assert 0 == store.counter["__setitem__", attrs_key] - store[attrs_key] = json.dumps(dict(foo="xxx", bar=42)).encode("ascii") - assert 0 == store.counter["__getitem__", attrs_key] - assert 1 == store.counter["__setitem__", attrs_key] - - # setup attributes - a = self.init_attributes(store) - - # test __getitem__ causes all attributes to be cached - assert a["foo"] == "xxx" - assert 1 == store.counter["__getitem__", attrs_key] - assert a["bar"] == 42 - assert 1 == store.counter["__getitem__", attrs_key] - assert a["foo"] == "xxx" - assert 1 == store.counter["__getitem__", attrs_key] - - # test __setitem__ updates the cache - a["foo"] = "yyy" - get_cnt = 2 - assert get_cnt == store.counter["__getitem__", attrs_key] - assert 2 == store.counter["__setitem__", attrs_key] - assert a["foo"] == "yyy" - assert get_cnt == store.counter["__getitem__", attrs_key] - assert 2 == store.counter["__setitem__", attrs_key] - - # test update() updates the cache - a.update(foo="zzz", bar=84) - get_cnt = 3 - assert get_cnt == store.counter["__getitem__", attrs_key] - assert 3 == store.counter["__setitem__", attrs_key] - assert a["foo"] == "zzz" - assert a["bar"] == 84 - assert get_cnt == store.counter["__getitem__", attrs_key] - assert 3 == store.counter["__setitem__", attrs_key] - - # test __contains__ uses the cache - assert "foo" in a - assert get_cnt == store.counter["__getitem__", attrs_key] - assert 3 == store.counter["__setitem__", attrs_key] - assert "spam" not in a - assert get_cnt == store.counter["__getitem__", attrs_key] - assert 3 == store.counter["__setitem__", attrs_key] - - # test __delitem__ updates the cache - del a["bar"] - get_cnt = 4 - assert get_cnt == store.counter["__getitem__", attrs_key] - assert 4 == store.counter["__setitem__", attrs_key] - assert "bar" not in a - assert get_cnt == store.counter["__getitem__", attrs_key] - assert 4 == store.counter["__setitem__", attrs_key] - - # test refresh() - store[attrs_key] = json.dumps(dict(foo="xxx", bar=42)).encode("ascii") - assert get_cnt == store.counter["__getitem__", attrs_key] - a.refresh() - get_cnt = 5 - assert get_cnt == store.counter["__getitem__", attrs_key] - assert a["foo"] == "xxx" - assert get_cnt == store.counter["__getitem__", attrs_key] - assert a["bar"] == 42 - assert get_cnt == store.counter["__getitem__", attrs_key] - - def test_caching_off(self): - # setup store - store = CountingDict() - attrs_key = ".zattrs" - assert 0 == store.counter["__getitem__", attrs_key] - assert 0 == store.counter["__setitem__", attrs_key] - store[attrs_key] = json.dumps(dict(foo="xxx", bar=42)).encode("ascii") - assert 0 == store.counter["__getitem__", attrs_key] - assert 1 == store.counter["__setitem__", attrs_key] - - # setup attributes - a = self.init_attributes(store, cache=False) - - # test __getitem__ - assert a["foo"] == "xxx" - assert 1 == store.counter["__getitem__", attrs_key] - assert a["bar"] == 42 - assert 2 == store.counter["__getitem__", attrs_key] - assert a["foo"] == "xxx" - assert 3 == store.counter["__getitem__", attrs_key] - - # test __setitem__ - a["foo"] = "yyy" - get_cnt = 4 - assert get_cnt == store.counter["__getitem__", attrs_key] - assert 2 == store.counter["__setitem__", attrs_key] - assert a["foo"] == "yyy" - get_cnt = 5 - assert get_cnt == store.counter["__getitem__", attrs_key] - assert 2 == store.counter["__setitem__", attrs_key] - - # test update() - a.update(foo="zzz", bar=84) - get_cnt = 6 - assert get_cnt == store.counter["__getitem__", attrs_key] - assert 3 == store.counter["__setitem__", attrs_key] - assert a["foo"] == "zzz" - assert a["bar"] == 84 - get_cnt = 8 - assert get_cnt == store.counter["__getitem__", attrs_key] - assert 3 == store.counter["__setitem__", attrs_key] - - # test __contains__ - assert "foo" in a - get_cnt = 9 - assert get_cnt == store.counter["__getitem__", attrs_key] - assert 3 == store.counter["__setitem__", attrs_key] - assert "spam" not in a - get_cnt = 10 - assert get_cnt == store.counter["__getitem__", attrs_key] - assert 3 == store.counter["__setitem__", attrs_key] - - def test_wrong_keys(self): - store = _init_store() - a = self.init_attributes(store) - - warning_msg = "only attribute keys of type 'string' will be allowed in the future" - - with pytest.warns(DeprecationWarning, match=warning_msg): - a[1] = "foo" - - with pytest.warns(DeprecationWarning, match=warning_msg): - a.put({1: "foo"}) - - with pytest.warns(DeprecationWarning, match=warning_msg): - a.update({1: "foo"}) diff --git a/tests/v2/test_convenience.py b/tests/v2/test_convenience.py deleted file mode 100644 index f558a8800f..0000000000 --- a/tests/v2/test_convenience.py +++ /dev/null @@ -1,804 +0,0 @@ -import atexit -import tempfile -import unittest -from numbers import Integral - -import numpy as np -import pytest -from numcodecs import Adler32, Zlib -from numpy.testing import assert_array_equal - -import zarr.v2 as zarr -from zarr.v2.convenience import ( - consolidate_metadata, - copy, - copy_store, - load, - open, - open_consolidated, - save, - save_group, - save_array, - copy_all, -) -from zarr.v2.core import Array -from zarr.v2.errors import CopyError -from zarr.v2.hierarchy import Group, group -from zarr.v2.storage import ( - ConsolidatedMetadataStore, - FSStore, - MemoryStore, - atexit_rmtree, - getsize, -) - - -def test_open_array(path_type): - store = tempfile.mkdtemp() - atexit.register(atexit_rmtree, store) - store = path_type(store) - - # open array, create if doesn't exist - z = open(store, mode="a", shape=100) - assert isinstance(z, Array) - assert z.shape == (100,) - - # open array, overwrite - z = open(store, mode="w", shape=200) - assert isinstance(z, Array) - assert z.shape == (200,) - - # open array, read-only - z = open(store, mode="r") - assert isinstance(z, Array) - assert z.shape == (200,) - assert z.read_only - - # path not found - with pytest.raises(ValueError): - open("doesnotexist", mode="r") - - -def test_open_group(path_type): - store = tempfile.mkdtemp() - atexit.register(atexit_rmtree, store) - store = path_type(store) - - # open group, create if doesn't exist - g = open(store, mode="a") - g.create_group("foo") - assert isinstance(g, Group) - assert "foo" in g - - # open group, overwrite - g = open(store, mode="w") - assert isinstance(g, Group) - assert "foo" not in g - - # open group, read-only - g = open(store, mode="r") - assert isinstance(g, Group) - assert g.read_only - - -def test_save_errors(): - with pytest.raises(ValueError): - # no arrays provided - save_group("data/group.zarr") - with pytest.raises(TypeError): - # no array provided - save_array("data/group.zarr") - with pytest.raises(ValueError): - # no arrays provided - save("data/group.zarr") - - -def test_lazy_loader(): - foo = np.arange(100) - bar = np.arange(100, 0, -1) - store = "data/group.zarr" - save(store, foo=foo, bar=bar) - loader = load(store) - assert "foo" in loader - assert "bar" in loader - assert "baz" not in loader - assert len(loader) == 2 - assert sorted(loader) == ["bar", "foo"] - assert_array_equal(foo, loader["foo"]) - assert_array_equal(bar, loader["bar"]) - assert "LazyLoader: " in repr(loader) - - -def test_load_array(): - foo = np.arange(100) - bar = np.arange(100, 0, -1) - store = "data/group.zarr" - save(store, foo=foo, bar=bar) - - # can also load arrays directly into a numpy array - for array_name in ["foo", "bar"]: - array_path = array_name - array = load(store, path=array_path) - assert isinstance(array, np.ndarray) - if array_name == "foo": - assert_array_equal(foo, array) - else: - assert_array_equal(bar, array) - - -def test_tree(): - g1 = zarr.group() - g1.create_group("foo") - g3 = g1.create_group("bar") - g3.create_group("baz") - g5 = g3.create_group("qux") - g5.create_dataset("baz", shape=100, chunks=10) - assert repr(zarr.tree(g1)) == repr(g1.tree()) - assert str(zarr.tree(g1)) == str(g1.tree()) - - -@pytest.mark.parametrize("stores_from_path", [False, True]) -@pytest.mark.parametrize( - "with_chunk_store,listable", - [(False, True), (True, True), (False, False)], - ids=["default-listable", "with_chunk_store-listable", "default-unlistable"], -) -def test_consolidate_metadata(with_chunk_store, listable, monkeypatch, stores_from_path): - # setup initial data - if stores_from_path: - store = tempfile.mkdtemp() - atexit.register(atexit_rmtree, store) - if with_chunk_store: - chunk_store = tempfile.mkdtemp() - atexit.register(atexit_rmtree, chunk_store) - else: - chunk_store = None - else: - store = MemoryStore() - chunk_store = MemoryStore() if with_chunk_store else None - path = None - z = group(store, chunk_store=chunk_store, path=path) - - # Reload the actual store implementation in case str - store_to_copy = z.store - - z.create_group("g1") - g2 = z.create_group("g2") - g2.attrs["hello"] = "world" - arr = g2.create_dataset("arr", shape=(20, 20), chunks=(5, 5), dtype="f8") - assert 16 == arr.nchunks - assert 0 == arr.nchunks_initialized - arr.attrs["data"] = 1 - arr[:] = 1.0 - assert 16 == arr.nchunks_initialized - - if stores_from_path: - # get the actual store class for use with consolidate_metadata - store_class = z._store - else: - store_class = store - - # perform consolidation - out = consolidate_metadata(store_class, path=path) - assert isinstance(out, Group) - assert ["g1", "g2"] == list(out) - if not stores_from_path: - assert isinstance(out._store, ConsolidatedMetadataStore) - assert ".zmetadata" in store - meta_keys = [ - ".zgroup", - "g1/.zgroup", - "g2/.zgroup", - "g2/.zattrs", - "g2/arr/.zarray", - "g2/arr/.zattrs", - ] - - for key in meta_keys: - del store[key] - - # https://github.com/zarr-developers/zarr-python/issues/993 - # Make sure we can still open consolidated on an unlistable store: - if not listable: - fs_memory = pytest.importorskip("fsspec.implementations.memory") - monkeypatch.setattr(fs_memory.MemoryFileSystem, "isdir", lambda x, y: False) - monkeypatch.delattr(fs_memory.MemoryFileSystem, "ls") - fs = fs_memory.MemoryFileSystem() - store_to_open = FSStore("", fs=fs) - # copy original store to new unlistable store - store_to_open.update(store_to_copy) - - else: - store_to_open = store - - # open consolidated - z2 = open_consolidated(store_to_open, chunk_store=chunk_store, path=path) - assert ["g1", "g2"] == list(z2) - assert "world" == z2.g2.attrs["hello"] - assert 1 == z2.g2.arr.attrs["data"] - assert (z2.g2.arr[:] == 1.0).all() - assert 16 == z2.g2.arr.nchunks - if listable: - assert 16 == z2.g2.arr.nchunks_initialized - else: - with pytest.raises(NotImplementedError): - _ = z2.g2.arr.nchunks_initialized - - if stores_from_path: - # path string is note a BaseStore subclass so cannot be used to - # initialize a ConsolidatedMetadataStore. - - with pytest.raises(ValueError): - cmd = ConsolidatedMetadataStore(store) - else: - # tests del/write on the store - - cmd = ConsolidatedMetadataStore(store) - with pytest.raises(PermissionError): - del cmd[".zgroup"] - with pytest.raises(PermissionError): - cmd[".zgroup"] = None - - # test getsize on the store - assert isinstance(getsize(cmd), Integral) - - # test new metadata are not writeable - with pytest.raises(PermissionError): - z2.create_group("g3") - with pytest.raises(PermissionError): - z2.create_dataset("spam", shape=42, chunks=7, dtype="i4") - with pytest.raises(PermissionError): - del z2["g2"] - - # test consolidated metadata are not writeable - with pytest.raises(PermissionError): - z2.g2.attrs["hello"] = "universe" - with pytest.raises(PermissionError): - z2.g2.arr.attrs["foo"] = "bar" - - # test the data are writeable - z2.g2.arr[:] = 2 - assert (z2.g2.arr[:] == 2).all() - - # test invalid modes - with pytest.raises(ValueError): - open_consolidated(store, chunk_store=chunk_store, mode="a", path=path) - with pytest.raises(ValueError): - open_consolidated(store, chunk_store=chunk_store, mode="w", path=path) - with pytest.raises(ValueError): - open_consolidated(store, chunk_store=chunk_store, mode="w-", path=path) - - # make sure keyword arguments are passed through without error - open_consolidated( - store, - chunk_store=chunk_store, - path=path, - cache_attrs=True, - synchronizer=None, - ) - - -@pytest.mark.parametrize( - "options", - ( - {"dimension_separator": "/"}, - {"dimension_separator": "."}, - {"dimension_separator": None}, - ), -) -def test_save_array_separator(tmpdir, options): - data = np.arange(6).reshape((3, 2)) - url = tmpdir.join("test.zarr") - save_array(url, data, **options) - - -class TestCopyStore(unittest.TestCase): - _version = 2 - - def setUp(self): - source = dict() - source["foo"] = b"xxx" - source["bar/baz"] = b"yyy" - source["bar/qux"] = b"zzz" - self.source = source - - def _get_dest_store(self): - return dict() - - def test_no_paths(self): - source = self.source - dest = self._get_dest_store() - copy_store(source, dest) - assert len(source) == len(dest) - for key in source: - assert source[key] == dest[key] - - def test_source_path(self): - source = self.source - # paths should be normalized - for source_path in "bar", "bar/", "/bar", "/bar/": - dest = self._get_dest_store() - copy_store(source, dest, source_path=source_path) - assert 2 == len(dest) - for key in source: - if key.startswith("bar/"): - dest_key = key.split("bar/")[1] - assert source[key] == dest[dest_key] - else: - assert key not in dest - - def test_dest_path(self): - source = self.source - # paths should be normalized - for dest_path in "new", "new/", "/new", "/new/": - dest = self._get_dest_store() - copy_store(source, dest, dest_path=dest_path) - assert len(source) == len(dest) - for key in source: - if self._version == 3: - dest_key = key[:10] + "new/" + key[10:] - else: - dest_key = "new/" + key - assert source[key] == dest[dest_key] - - def test_source_dest_path(self): - source = self.source - # paths should be normalized - for source_path in "bar", "bar/", "/bar", "/bar/": - for dest_path in "new", "new/", "/new", "/new/": - dest = self._get_dest_store() - copy_store(source, dest, source_path=source_path, dest_path=dest_path) - assert 2 == len(dest) - for key in source: - if key.startswith("bar/"): - dest_key = "new/" + key.split("bar/")[1] - assert source[key] == dest[dest_key] - else: - assert key not in dest - assert ("new/" + key) not in dest - - def test_excludes_includes(self): - source = self.source - - # single excludes - dest = self._get_dest_store() - excludes = "f.*" - copy_store(source, dest, excludes=excludes) - assert len(dest) == 2 - - root = "" - assert root + "foo" not in dest - - # multiple excludes - dest = self._get_dest_store() - excludes = "b.z", ".*x" - copy_store(source, dest, excludes=excludes) - assert len(dest) == 1 - assert root + "foo" in dest - assert root + "bar/baz" not in dest - assert root + "bar/qux" not in dest - - # excludes and includes - dest = self._get_dest_store() - excludes = "b.*" - includes = ".*x" - copy_store(source, dest, excludes=excludes, includes=includes) - assert len(dest) == 2 - assert root + "foo" in dest - assert root + "bar/baz" not in dest - assert root + "bar/qux" in dest - - def test_dry_run(self): - source = self.source - dest = self._get_dest_store() - copy_store(source, dest, dry_run=True) - assert 0 == len(dest) - - def test_if_exists(self): - source = self.source - dest = self._get_dest_store() - root = "" - dest[root + "bar/baz"] = b"mmm" - - # default ('raise') - with pytest.raises(CopyError): - copy_store(source, dest) - - # explicit 'raise' - with pytest.raises(CopyError): - copy_store(source, dest, if_exists="raise") - - # skip - copy_store(source, dest, if_exists="skip") - assert 3 == len(dest) - assert dest[root + "foo"] == b"xxx" - assert dest[root + "bar/baz"] == b"mmm" - assert dest[root + "bar/qux"] == b"zzz" - - # replace - copy_store(source, dest, if_exists="replace") - assert 3 == len(dest) - assert dest[root + "foo"] == b"xxx" - assert dest[root + "bar/baz"] == b"yyy" - assert dest[root + "bar/qux"] == b"zzz" - - # invalid option - with pytest.raises(ValueError): - copy_store(source, dest, if_exists="foobar") - - -def check_copied_array(original, copied, without_attrs=False, expect_props=None): - # setup - source_h5py = original.__module__.startswith("h5py.") - dest_h5py = copied.__module__.startswith("h5py.") - zarr_to_zarr = not (source_h5py or dest_h5py) - h5py_to_h5py = source_h5py and dest_h5py - zarr_to_h5py = not source_h5py and dest_h5py - h5py_to_zarr = source_h5py and not dest_h5py - if expect_props is None: - expect_props = dict() - else: - expect_props = expect_props.copy() - - # common properties in zarr and h5py - for p in "dtype", "shape", "chunks": - expect_props.setdefault(p, getattr(original, p)) - - # zarr-specific properties - if zarr_to_zarr: - for p in "compressor", "filters", "order", "fill_value": - expect_props.setdefault(p, getattr(original, p)) - - # h5py-specific properties - if h5py_to_h5py: - for p in ( - "maxshape", - "compression", - "compression_opts", - "shuffle", - "scaleoffset", - "fletcher32", - "fillvalue", - ): - expect_props.setdefault(p, getattr(original, p)) - - # common properties with some name differences - if h5py_to_zarr: - expect_props.setdefault("fill_value", original.fillvalue) - if zarr_to_h5py: - expect_props.setdefault("fillvalue", original.fill_value) - - # compare properties - for k, v in expect_props.items(): - assert v == getattr(copied, k) - - # compare data - assert_array_equal(original[:], copied[:]) - - # compare attrs - if without_attrs: - for k in original.attrs.keys(): - assert k not in copied.attrs - else: - if dest_h5py and "filters" in original.attrs: - # special case in v3 (storing filters metadata under attributes) - # we explicitly do not copy this info over to HDF5 - original_attrs = original.attrs.asdict().copy() - original_attrs.pop("filters") - else: - original_attrs = original.attrs - assert sorted(original_attrs.items()) == sorted(copied.attrs.items()) - - -def check_copied_group(original, copied, without_attrs=False, expect_props=None, shallow=False): - # setup - if expect_props is None: - expect_props = dict() - else: - expect_props = expect_props.copy() - - # compare children - for k, v in original.items(): - if hasattr(v, "shape"): - assert k in copied - check_copied_array(v, copied[k], without_attrs=without_attrs, expect_props=expect_props) - elif shallow: - assert k not in copied - else: - assert k in copied - check_copied_group( - v, - copied[k], - without_attrs=without_attrs, - shallow=shallow, - expect_props=expect_props, - ) - - # compare attrs - if without_attrs: - for k in original.attrs.keys(): - assert k not in copied.attrs - else: - assert sorted(original.attrs.items()) == sorted(copied.attrs.items()) - - -def test_copy_all(): - """ - https://github.com/zarr-developers/zarr-python/issues/269 - - copy_all used to not copy attributes as `.keys()` does not return hidden `.zattrs`. - - """ - original_group = zarr.group(store=MemoryStore(), overwrite=True) - original_group.attrs["info"] = "group attrs" - original_subgroup = original_group.create_group("subgroup") - original_subgroup.attrs["info"] = "sub attrs" - - destination_group = zarr.group(store=MemoryStore(), overwrite=True) - - # copy from memory to directory store - copy_all( - original_group, - destination_group, - dry_run=False, - ) - - assert "subgroup" in destination_group - assert destination_group.attrs["info"] == "group attrs" - assert destination_group.subgroup.attrs["info"] == "sub attrs" - - -class TestCopy: - @pytest.fixture(params=[False, True], ids=["zarr", "hdf5"]) - def source(self, request, tmpdir): - def prep_source(source): - foo = source.create_group("foo") - foo.attrs["experiment"] = "weird science" - baz = foo.create_dataset("bar/baz", data=np.arange(100), chunks=(50,)) - baz.attrs["units"] = "metres" - if request.param: - extra_kws = dict( - compression="gzip", - compression_opts=3, - fillvalue=84, - shuffle=True, - fletcher32=True, - ) - else: - extra_kws = dict(compressor=Zlib(3), order="F", fill_value=42, filters=[Adler32()]) - source.create_dataset( - "spam", - data=np.arange(100, 200).reshape(20, 5), - chunks=(10, 2), - dtype="i2", - **extra_kws, - ) - return source - - if request.param: - h5py = pytest.importorskip("h5py") - fn = tmpdir.join("source.h5") - with h5py.File(str(fn), mode="w") as h5f: - yield prep_source(h5f) - else: - yield prep_source(group()) - - @pytest.fixture(params=[False, True], ids=["zarr", "hdf5"]) - def dest(self, request, tmpdir): - if request.param: - h5py = pytest.importorskip("h5py") - fn = tmpdir.join("dest.h5") - with h5py.File(str(fn), mode="w") as h5f: - yield h5f - else: - yield group() - - def test_copy_array(self, source, dest): - # copy array with default options - copy(source["foo/bar/baz"], dest) - check_copied_array(source["foo/bar/baz"], dest["baz"]) - copy(source["spam"], dest) - check_copied_array(source["spam"], dest["spam"]) - - def test_copy_bad_dest(self, source, dest): - # try to copy to an array, dest must be a group - dest = dest.create_dataset("eggs", shape=(100,)) - with pytest.raises(ValueError): - copy(source["foo/bar/baz"], dest) - - def test_copy_array_name(self, source, dest): - # copy array with name - copy(source["foo/bar/baz"], dest, name="qux") - assert "baz" not in dest - check_copied_array(source["foo/bar/baz"], dest["qux"]) - - def test_copy_array_create_options(self, source, dest): - dest_h5py = dest.__module__.startswith("h5py.") - - # copy array, provide creation options - compressor = Zlib(9) - create_kws = dict(chunks=(10,)) - if dest_h5py: - create_kws.update( - compression="gzip", compression_opts=9, shuffle=True, fletcher32=True, fillvalue=42 - ) - else: - create_kws.update(compressor=compressor, fill_value=42, order="F", filters=[Adler32()]) - copy(source["foo/bar/baz"], dest, without_attrs=True, **create_kws) - check_copied_array( - source["foo/bar/baz"], dest["baz"], without_attrs=True, expect_props=create_kws - ) - - def test_copy_array_exists_array(self, source, dest): - # copy array, dest array in the way - dest.create_dataset("baz", shape=(10,)) - - # raise - with pytest.raises(CopyError): - # should raise by default - copy(source["foo/bar/baz"], dest) - assert (10,) == dest["baz"].shape - with pytest.raises(CopyError): - copy(source["foo/bar/baz"], dest, if_exists="raise") - assert (10,) == dest["baz"].shape - - # skip - copy(source["foo/bar/baz"], dest, if_exists="skip") - assert (10,) == dest["baz"].shape - - # replace - copy(source["foo/bar/baz"], dest, if_exists="replace") - check_copied_array(source["foo/bar/baz"], dest["baz"]) - - # invalid option - with pytest.raises(ValueError): - copy(source["foo/bar/baz"], dest, if_exists="foobar") - - def test_copy_array_exists_group(self, source, dest): - # copy array, dest group in the way - dest.create_group("baz") - - # raise - with pytest.raises(CopyError): - copy(source["foo/bar/baz"], dest) - assert not hasattr(dest["baz"], "shape") - with pytest.raises(CopyError): - copy(source["foo/bar/baz"], dest, if_exists="raise") - assert not hasattr(dest["baz"], "shape") - - # skip - copy(source["foo/bar/baz"], dest, if_exists="skip") - assert not hasattr(dest["baz"], "shape") - - # replace - copy(source["foo/bar/baz"], dest, if_exists="replace") - check_copied_array(source["foo/bar/baz"], dest["baz"]) - - def test_copy_array_skip_initialized(self, source, dest): - dest_h5py = dest.__module__.startswith("h5py.") - - dest.create_dataset("baz", shape=(100,), chunks=(10,), dtype="i8") - assert not np.all(source["foo/bar/baz"][:] == dest["baz"][:]) - - if dest_h5py: - with pytest.raises(ValueError): - # not available with copy to h5py - copy(source["foo/bar/baz"], dest, if_exists="skip_initialized") - - else: - # copy array, dest array exists but not yet initialized - copy(source["foo/bar/baz"], dest, if_exists="skip_initialized") - check_copied_array(source["foo/bar/baz"], dest["baz"]) - - # copy array, dest array exists and initialized, will be skipped - dest["baz"][:] = np.arange(100, 200) - copy(source["foo/bar/baz"], dest, if_exists="skip_initialized") - assert_array_equal(np.arange(100, 200), dest["baz"][:]) - assert not np.all(source["foo/bar/baz"][:] == dest["baz"][:]) - - def test_copy_group(self, source, dest): - # copy group, default options - copy(source["foo"], dest) - check_copied_group(source["foo"], dest["foo"]) - - def test_copy_group_no_name(self, source, dest): - with pytest.raises(TypeError): - # need a name if copy root - copy(source, dest) - - copy(source, dest, name="root") - check_copied_group(source, dest["root"]) - - def test_copy_group_options(self, source, dest): - # copy group, non-default options - copy(source["foo"], dest, name="qux", without_attrs=True) - assert "foo" not in dest - check_copied_group(source["foo"], dest["qux"], without_attrs=True) - - def test_copy_group_shallow(self, source, dest): - # copy group, shallow - copy(source, dest, name="eggs", shallow=True) - check_copied_group(source, dest["eggs"], shallow=True) - - def test_copy_group_exists_group(self, source, dest): - # copy group, dest groups exist - dest.create_group("foo/bar") - copy(source["foo"], dest) - check_copied_group(source["foo"], dest["foo"]) - - def test_copy_group_exists_array(self, source, dest): - # copy group, dest array in the way - dest.create_dataset("foo/bar", shape=(10,)) - - # raise - with pytest.raises(CopyError): - copy(source["foo"], dest) - assert dest["foo/bar"].shape == (10,) - with pytest.raises(CopyError): - copy(source["foo"], dest, if_exists="raise") - assert dest["foo/bar"].shape == (10,) - - # skip - copy(source["foo"], dest, if_exists="skip") - assert dest["foo/bar"].shape == (10,) - - # replace - copy(source["foo"], dest, if_exists="replace") - check_copied_group(source["foo"], dest["foo"]) - - def test_copy_group_dry_run(self, source, dest): - # dry run, empty destination - n_copied, n_skipped, n_bytes_copied = copy( - source["foo"], dest, dry_run=True, return_stats=True - ) - assert 0 == len(dest) - assert 3 == n_copied - assert 0 == n_skipped - assert 0 == n_bytes_copied - - # dry run, array exists in destination - baz = np.arange(100, 200) - dest.create_dataset("foo/bar/baz", data=baz) - assert not np.all(source["foo/bar/baz"][:] == dest["foo/bar/baz"][:]) - assert 1 == len(dest) - - # raise - with pytest.raises(CopyError): - copy(source["foo"], dest, dry_run=True) - assert 1 == len(dest) - - # skip - n_copied, n_skipped, n_bytes_copied = copy( - source["foo"], dest, dry_run=True, if_exists="skip", return_stats=True - ) - assert 1 == len(dest) - assert 2 == n_copied - assert 1 == n_skipped - assert 0 == n_bytes_copied - assert_array_equal(baz, dest["foo/bar/baz"]) - - # replace - n_copied, n_skipped, n_bytes_copied = copy( - source["foo"], dest, dry_run=True, if_exists="replace", return_stats=True - ) - assert 1 == len(dest) - assert 3 == n_copied - assert 0 == n_skipped - assert 0 == n_bytes_copied - assert_array_equal(baz, dest["foo/bar/baz"]) - - def test_logging(self, source, dest, tmpdir): - # callable log - copy(source["foo"], dest, dry_run=True, log=print) - - # file name - fn = str(tmpdir.join("log_name")) - copy(source["foo"], dest, dry_run=True, log=fn) - - # file - with tmpdir.join("log_file").open(mode="w") as f: - copy(source["foo"], dest, dry_run=True, log=f) - - # bad option - with pytest.raises(TypeError): - copy(source["foo"], dest, dry_run=True, log=True) diff --git a/tests/v2/test_core.py b/tests/v2/test_core.py deleted file mode 100644 index f053725b95..0000000000 --- a/tests/v2/test_core.py +++ /dev/null @@ -1,2510 +0,0 @@ -import atexit -import os -import sys -import pickle -import shutil -from typing import Any, Literal, Optional, Tuple, Union -import unittest -from itertools import zip_longest -from tempfile import mkdtemp -import numpy as np -import packaging.version -import pytest -from numcodecs import ( - BZ2, - JSON, - LZ4, - Blosc, - Categorize, - Delta, - FixedScaleOffset, - GZip, - MsgPack, - Pickle, - VLenArray, - VLenBytes, - VLenUTF8, - Zlib, -) -from numcodecs.compat import ensure_bytes, ensure_ndarray -from numcodecs.tests.common import greetings -from numpy.testing import assert_array_almost_equal, assert_array_equal - -import zarr.v2 -from zarr.v2._storage.store import ( - BaseStore, -) - -from zarr.v2.core import Array -from zarr.v2.meta import json_loads -from zarr.v2.n5 import N5Store, N5FSStore, n5_keywords -from zarr.v2.storage import ( - ABSStore, - DBMStore, - DirectoryStore, - FSStore, - KVStore, - LMDBStore, - LRUStoreCache, - NestedDirectoryStore, - SQLiteStore, - atexit_rmglob, - atexit_rmtree, - init_array, - init_group, - normalize_store_arg, -) - -from zarr.v2.util import buffer_size -from .util import abs_container, skip_test_env_var, have_fsspec, mktemp - -# noinspection PyMethodMayBeStatic - - -class TestArray: - root = "" - path = "" - compressor = Zlib(level=1) - filters = None - dimension_separator: Literal["/", ".", None] = None - cache_metadata = True - cache_attrs = True - partial_decompress: bool = False - write_empty_chunks = True - read_only = False - storage_transformers: Tuple[Any, ...] = () - - def create_store(self) -> BaseStore: - return KVStore(dict()) - - # used by child classes - def create_chunk_store(self) -> Optional[BaseStore]: - return None - - def create_storage_transformers(self, shape: Union[int, Tuple[int, ...]]) -> Tuple[Any, ...]: - return () - - def create_filters(self, dtype: Optional[str]) -> Tuple[Any, ...]: - return () - - def create_array(self, shape: Union[int, Tuple[int, ...]], **kwargs): - store = self.create_store() - chunk_store = self.create_chunk_store() - # keyword arguments for array initialization - init_array_kwargs = { - "path": kwargs.pop("path", self.path), - "compressor": kwargs.pop("compressor", self.compressor), - "chunk_store": chunk_store, - "storage_transformers": self.create_storage_transformers(shape), - "filters": kwargs.pop("filters", self.create_filters(kwargs.get("dtype", None))), - } - - # keyword arguments for array instantiation - access_array_kwargs = { - "path": init_array_kwargs["path"], - "read_only": kwargs.pop("read_only", self.read_only), - "chunk_store": chunk_store, - "cache_metadata": kwargs.pop("cache_metadata", self.cache_metadata), - "cache_attrs": kwargs.pop("cache_attrs", self.cache_attrs), - "partial_decompress": kwargs.pop("partial_decompress", self.partial_decompress), - "write_empty_chunks": kwargs.pop("write_empty_chunks", self.write_empty_chunks), - } - - init_array(store, shape, **{**init_array_kwargs, **kwargs}) - - return Array(store, **access_array_kwargs) - - def test_array_init(self): - # normal initialization - store = self.create_store() - init_array(store, shape=100, chunks=10, dtype=" end - assert [] == list(z.islice(6, 5)) - - z.store.close() - - def test_iter(self): - params = ( - ((1,), (1,)), - ((2,), (1,)), - ((1,), (2,)), - ((3,), (3,)), - ((1000,), (100,)), - ((100,), (1000,)), - ((1, 100), (1, 1)), - ((1, 0), (1, 1)), - ((0, 1), (1, 1)), - ((0, 1), (2, 1)), - ((100, 1), (3, 1)), - ((100, 100), (10, 10)), - ((10, 10, 10), (3, 3, 3)), - ) - for shape, chunks in params: - z = self.create_array(shape=shape, chunks=chunks, dtype=int) - a = np.arange(np.prod(shape)).reshape(shape) - z[:] = a - for expect, actual in zip_longest(a, z): - assert_array_equal(expect, actual) - z.store.close() - - def test_islice(self): - params = ( - ((1,), (1,), 0, 1), - ((2,), (1,), 0, 1), - ((1,), (2,), 0, 1), - ((3,), (3,), 1, 2), - ((1000,), (100,), 150, 1050), - ((100,), (1000,), 25, 75), - ((1, 100), (1, 1), 0, 1), - ((100, 1), (3, 1), 56, 100), - ((100, 100), (10, 10), 13, 99), - ((10, 10, 10), (3, 3, 3), 2, 4), - ) - for shape, chunks, start, end in params: - z = self.create_array(shape=shape, chunks=chunks, dtype=int) - a = np.arange(np.prod(shape)).reshape(shape) - z[:] = a - end_array = min(end, a.shape[0]) - for expect, actual in zip_longest(a[start:end_array], z.islice(start, end)): - assert_array_equal(expect, actual) - if hasattr(z.store, "close"): - z.store.close() - - def test_compressors(self): - compressors = [None, BZ2(), Blosc(), LZ4(), Zlib(), GZip()] - if LZMA: - compressors.append(LZMA()) - for compressor in compressors: - a = self.create_array(shape=1000, chunks=100, compressor=compressor) - a[0:100] = 1 - assert np.all(a[0:100] == 1) - a[:] = 1 - assert np.all(a[:] == 1) - a.store.close() - - def test_endian(self): - dtype = np.dtype("float32") - a1 = self.create_array(shape=1000, chunks=100, dtype=dtype.newbyteorder("<")) - a1[:] = 1 - x1 = a1[:] - a2 = self.create_array(shape=1000, chunks=100, dtype=dtype.newbyteorder(">")) - a2[:] = 1 - x2 = a2[:] - assert_array_equal(x1, x2) - a1.store.close() - a2.store.close() - - def test_attributes(self): - a = self.create_array(shape=10, chunks=10, dtype="i8") - a.attrs["foo"] = "bar" - assert a.attrs.key in a.store - attrs = json_loads(a.store[a.attrs.key]) - assert "foo" in attrs and attrs["foo"] == "bar" - - a.attrs["bar"] = "foo" - assert a.attrs.key in a.store - attrs = json_loads(a.store[a.attrs.key]) - assert "foo" in attrs and attrs["foo"] == "bar" - assert "bar" in attrs and attrs["bar"] == "foo" - a.store.close() - - def test_structured_with_object(self): - a = self.create_array( - fill_value=(0.0, None), - shape=10, - chunks=10, - dtype=[("x", float), ("y", object)], - object_codec=Pickle(), - ) - assert tuple(a[0]) == (0.0, None) - - -class TestArrayWithPath(TestArray): - path = "foo/bar" - compressor = Blosc() - - def test_nchunks_initialized(self): - pass - - def expected(self): - return [ - "f710da18d45d38d4aaf2afd7fb822fdd73d02957", - "1437428e69754b1e1a38bd7fc9e43669577620db", - "6c530b6b9d73e108cc5ee7b6be3d552cc994bdbe", - "4c0a76fb1222498e09dcd92f7f9221d6cea8b40e", - "05b0663ffe1785f38d3a459dec17e57a18f254af", - ] - - def test_nbytes_stored(self): - # MemoryStore as store - z = self.create_array(shape=1000, chunks=100) - expect_nbytes_stored = sum( - buffer_size(v) for k, v in z.store.items() if k.startswith("foo/bar/") - ) - assert expect_nbytes_stored == z.nbytes_stored - z[:] = 42 - expect_nbytes_stored = sum( - buffer_size(v) for k, v in z.store.items() if k.startswith("foo/bar/") - ) - assert expect_nbytes_stored == z.nbytes_stored - - # mess with store - z.store[z._key_prefix + "foo"] = list(range(10)) - assert -1 == z.nbytes_stored - - -class TestArrayWithChunkStore(TestArray): - compressor = Blosc() - - def create_chunk_store(self): - return KVStore(dict()) - - def expected(self): - return [ - "f710da18d45d38d4aaf2afd7fb822fdd73d02957", - "1437428e69754b1e1a38bd7fc9e43669577620db", - "6c530b6b9d73e108cc5ee7b6be3d552cc994bdbe", - "4c0a76fb1222498e09dcd92f7f9221d6cea8b40e", - "05b0663ffe1785f38d3a459dec17e57a18f254af", - ] - - def test_nbytes_stored(self): - z = self.create_array(shape=1000, chunks=100) - expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values()) - expect_nbytes_stored += sum(buffer_size(v) for v in z.chunk_store.values()) - assert expect_nbytes_stored == z.nbytes_stored - z[:] = 42 - expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values()) - expect_nbytes_stored += sum(buffer_size(v) for v in z.chunk_store.values()) - assert expect_nbytes_stored == z.nbytes_stored - - # mess with store - z.chunk_store[z._key_prefix + "foo"] = list(range(10)) - assert -1 == z.nbytes_stored - - -class TestArrayWithDirectoryStore(TestArray): - def create_store(self): - path = mkdtemp() - atexit.register(shutil.rmtree, path) - store = DirectoryStore(path) - return store - - def test_nbytes_stored(self): - # dict as store - z = self.create_array(shape=1000, chunks=100) - expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values()) - assert expect_nbytes_stored == z.nbytes_stored - z[:] = 42 - expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values()) - assert expect_nbytes_stored == z.nbytes_stored - - -def test_array_init_from_dict(): - # initialization via non-Store MutableMapping - store = dict() - init_array(store, shape=100, chunks=10, dtype=" Tuple[Any, ...]: - return ( - Delta(dtype=dtype), - FixedScaleOffset(dtype=dtype, scale=1, offset=0), - ) - - def expected(self): - return [ - "b80367c5599d47110d42bd8886240c2f46620dba", - "95a7b2471225e73199c9716d21e8d3dd6e5f6f2a", - "7300f1eb130cff5891630038fd99c28ef23d3a01", - "c649ad229bc5720258b934ea958570c2f354c2eb", - "62fc9236d78af18a5ec26c12eea1d33bce52501e", - ] - - def test_astype_no_filters(self): - shape = (100,) - dtype = np.dtype(np.int8) - astype = np.dtype(np.float32) - - store = KVStore(dict()) - init_array(store, shape=shape, chunks=10, dtype=dtype) - - data = np.arange(np.prod(shape), dtype=dtype).reshape(shape) - - z1 = Array(store) - z1[...] = data - z2 = z1.astype(astype) - - expected = data.astype(astype) - assert_array_equal(expected, z2) - assert z2.read_only - - def test_astype(self): - shape = (100,) - chunks = (10,) - - dtype = np.dtype(np.int8) - astype = np.dtype(np.float32) - - data = np.arange(np.prod(shape), dtype=dtype).reshape(shape) - - z1 = self.create_array(shape=shape, chunks=chunks, dtype=dtype) - z1[...] = data - z2 = z1.astype(astype) - - expected = data.astype(astype) - assert_array_equal(expected, z2) - - def test_array_dtype_shape(self): - # skip this one, cannot do delta on unstructured array - pass - - def test_structured_array(self): - # skip this one, cannot do delta on structured array - pass - - def test_structured_array_subshapes(self): - # skip this one, cannot do delta on structured array - pass - - def test_structured_array_nested(self): - # skip this one, cannot do delta on structured array - pass - - def test_dtypes(self): - # skip this one, delta messes up floats - pass - - def test_object_arrays(self): - # skip this one, cannot use delta with objects - pass - - def test_object_arrays_vlen_text(self): - # skip this one, cannot use delta with objects - pass - - def test_object_arrays_vlen_bytes(self): - # skip this one, cannot use delta with objects - pass - - def test_object_arrays_vlen_array(self): - # skip this one, cannot use delta with objects - pass - - def test_object_arrays_danger(self): - # skip this one, cannot use delta with objects - pass - - def test_structured_array_contain_object(self): - # skip this one, cannot use delta on structured array - pass - - -# custom store, does not support getsize() -class CustomMapping: - def __init__(self): - self.inner = KVStore(dict()) - - def __iter__(self): - return iter(self.keys()) - - def keys(self): - return self.inner.keys() - - def values(self): - return self.inner.values() - - def get(self, item, default=None): - try: - return self.inner[item] - except KeyError: - return default - - def __getitem__(self, item): - return self.inner[item] - - def __setitem__(self, item, value): - self.inner[item] = ensure_bytes(value) - - def __delitem__(self, key): - del self.inner[key] - - def __contains__(self, item): - return item in self.inner - - def close(self): - return self.inner.close() - - -class TestArrayWithCustomMapping(TestArray): - def create_store(self): - return CustomMapping() - - def test_nbytes_stored(self): - z = self.create_array(shape=1000, chunks=100) - assert 245 == z.nbytes_stored - z[:] = 42 - assert 515 == z.nbytes_stored - - -class TestArrayNoCache(TestArray): - def test_cache_metadata(self): - a1 = self.create_array(shape=100, chunks=10, dtype="i1", cache_metadata=False) - path = None - a2 = Array(a1.store, path=path, cache_metadata=True) - assert a1.shape == a2.shape - assert a1.size == a2.size - assert a1.nbytes == a2.nbytes - assert a1.nchunks == a2.nchunks - - # a1 is not caching so *will* see updates made via other objects - a2.resize(200) - assert (200,) == a2.shape - assert 200 == a2.size - assert 200 == a2.nbytes - assert 20 == a2.nchunks - assert a1.shape == a2.shape - assert a1.size == a2.size - assert a1.nbytes == a2.nbytes - assert a1.nchunks == a2.nchunks - - a2.append(np.zeros(100)) - assert (300,) == a2.shape - assert 300 == a2.size - assert 300 == a2.nbytes - assert 30 == a2.nchunks - assert a1.shape == a2.shape - assert a1.size == a2.size - assert a1.nbytes == a2.nbytes - assert a1.nchunks == a2.nchunks - - # a2 is caching so *will not* see updates made via other objects - a1.resize(400) - assert (400,) == a1.shape - assert 400 == a1.size - assert 400 == a1.nbytes - assert 40 == a1.nchunks - assert (300,) == a2.shape - assert 300 == a2.size - assert 300 == a2.nbytes - assert 30 == a2.nchunks - - def test_cache_attrs(self): - a1 = self.create_array(shape=100, chunks=10, dtype="i1", cache_attrs=False) - path = None - a2 = Array(a1.store, path=path, cache_attrs=True) - assert a1.attrs.asdict() == a2.attrs.asdict() - - # a1 is not caching so *will* see updates made via other objects - a2.attrs["foo"] = "xxx" - a2.attrs["bar"] = 42 - assert a1.attrs.asdict() == a2.attrs.asdict() - - # a2 is caching so *will not* see updates made via other objects - a1.attrs["foo"] = "yyy" - assert "yyy" == a1.attrs["foo"] - assert "xxx" == a2.attrs["foo"] - - def test_object_arrays_danger(self): - # skip this one as it only works if metadata are cached - pass - - -class TestArrayWithStoreCache(TestArray): - def create_store(self): - return LRUStoreCache(dict(), max_size=None) - - def test_store_has_bytes_values(self): - # skip as the cache has no control over how the store provides values - pass - - -@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") -class TestArrayWithFSStore(TestArray): - compressor = Blosc() - dimension_separator: Literal[".", "/"] = "." - - def create_store(self): - path = mkdtemp() - atexit.register(shutil.rmtree, path) - key_separator = self.dimension_separator - store = FSStore( - path, - key_separator=key_separator, - auto_mkdir=True, - check=True, - create=True, - missing_exceptions=None, - ) - return store - - def expected(self): - return [ - "ab753fc81df0878589535ca9bad2816ba88d91bc", - "c16261446f9436b1e9f962e57ce3e8f6074abe8a", - "c2ef3b2fb2bc9dcace99cd6dad1a7b66cc1ea058", - "6e52f95ac15b164a8e96843a230fcee0e610729b", - "091fa99bc60706095c9ce30b56ce2503e0223f56", - ] - - -@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") -class TestArrayWithFSStoreFromFilesystem(TestArray): - compressor = Blosc() - dimension_separator = "." - - def create_store(self): - from fsspec.implementations.local import LocalFileSystem - - fs = LocalFileSystem(auto_mkdir=True) - path = mkdtemp() - atexit.register(shutil.rmtree, path) - key_separator = self.dimension_separator - store = FSStore( - path, - fs=fs, - key_separator=key_separator, - check=True, - create=True, - missing_exceptions=None, - ) - return store - - def expected(self): - return [ - "ab753fc81df0878589535ca9bad2816ba88d91bc", - "c16261446f9436b1e9f962e57ce3e8f6074abe8a", - "c2ef3b2fb2bc9dcace99cd6dad1a7b66cc1ea058", - "6e52f95ac15b164a8e96843a230fcee0e610729b", - "091fa99bc60706095c9ce30b56ce2503e0223f56", - ] - - -@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") -class TestArrayWithFSStorePartialRead(TestArray): - compressor = Blosc(blocksize=256) - partial_decompress = True - - def create_store(self): - path = mkdtemp() - atexit.register(shutil.rmtree, path) - store = FSStore(path) - return store - - def expected(self): - return [ - "dd7577d645c38767cf6f6d1ef8fd64002883a014", - "aa0de9892cf1ed3cda529efbf3233720b84489b7", - "e6191c44cf958576c29c41cef0f55b028a4dbdff", - "88adeeabb819feecccadf50152293dbb42f9107e", - "1426e084427f9920e29c9ec81b663d1005849455", - ] - - def test_non_cont(self): - z = self.create_array(shape=(500, 500, 500), chunks=(50, 50, 50), dtype="""" - - data = np.arange(25).reshape((5, 5)) - ds = zarr.v2.create( - shape=data.shape, - chunks=(5, 5), - dtype=data.dtype, - compressor=(None), - store=FSStore(url=str(tmpdir), mode="a"), - order="F", - ) - - ds[:] = data - - ds_reopened = zarr.v2.open_array(store=FSStore(url=str(tmpdir), mode="r")) - - written_data = ds_reopened[:] - assert_array_equal(data, written_data) diff --git a/tests/v2/test_creation.py b/tests/v2/test_creation.py deleted file mode 100644 index 08073a8ac3..0000000000 --- a/tests/v2/test_creation.py +++ /dev/null @@ -1,691 +0,0 @@ -import atexit -import os.path -import shutil -import warnings - -import numpy as np -import pytest -from numpy.testing import assert_array_equal - -from zarr.v2.codecs import Zlib -from zarr.v2.core import Array -from zarr.v2.creation import ( - array, - create, - empty, - empty_like, - full, - full_like, - ones, - ones_like, - open_array, - open_like, - zeros, - zeros_like, -) -from zarr.v2.hierarchy import open_group -from zarr.v2.n5 import N5Store -from zarr.v2.storage import DirectoryStore, KVStore -from zarr.v2.sync import ThreadSynchronizer -from .util import mktemp, have_fsspec - - -_VERSIONS = (None, 2) -_VERSIONS2 = (2,) - - -# something bcolz-like -class MockBcolzArray: - def __init__(self, data, chunklen): - self.data = data - self.chunklen = chunklen - - def __getattr__(self, item): - return getattr(self.data, item) - - def __getitem__(self, item): - return self.data[item] - - -# something h5py-like -class MockH5pyDataset: - def __init__(self, data, chunks): - self.data = data - self.chunks = chunks - - def __getattr__(self, item): - return getattr(self.data, item) - - def __getitem__(self, item): - return self.data[item] - - -def _init_creation_kwargs(at_root=True): - kwargs = {} - if not at_root: - kwargs["path"] = "array" - return kwargs - - -@pytest.mark.parametrize("at_root", [False, True]) -def test_array(at_root): - kwargs = _init_creation_kwargs(at_root) - - # with numpy array - a = np.arange(100) - z = array(a, chunks=10, **kwargs) - assert a.shape == z.shape - assert a.dtype == z.dtype - assert_array_equal(a, z[:]) - - # with array-like - a = list(range(100)) - z = array(a, chunks=10, **kwargs) - assert (100,) == z.shape - assert np.asarray(a).dtype == z.dtype - assert_array_equal(np.asarray(a), z[:]) - - # with another zarr array - z2 = array(z, **kwargs) - assert z.shape == z2.shape - assert z.chunks == z2.chunks - assert z.dtype == z2.dtype - assert_array_equal(z[:], z2[:]) - - # with chunky array-likes - - b = np.arange(1000).reshape(100, 10) - c = MockBcolzArray(b, 10) - z3 = array(c, **kwargs) - assert c.shape == z3.shape - assert (10, 10) == z3.chunks - - b = np.arange(1000).reshape(100, 10) - c = MockH5pyDataset(b, chunks=(10, 2)) - z4 = array(c, **kwargs) - assert c.shape == z4.shape - assert (10, 2) == z4.chunks - - c = MockH5pyDataset(b, chunks=None) - z5 = array(c, **kwargs) - assert c.shape == z5.shape - assert isinstance(z5.chunks, tuple) - - # with dtype=None - a = np.arange(100, dtype="i4") - z = array(a, dtype=None, **kwargs) - assert_array_equal(a[:], z[:]) - assert a.dtype == z.dtype - - # with dtype=something else - a = np.arange(100, dtype="i4") - z = array(a, dtype="i8", **kwargs) - assert_array_equal(a[:], z[:]) - assert np.dtype("i8") == z.dtype - - -@pytest.mark.parametrize("at_root", [False, True]) -def test_empty(at_root): - kwargs = _init_creation_kwargs(at_root) - z = empty(100, chunks=10, **kwargs) - assert (100,) == z.shape - assert (10,) == z.chunks - - -@pytest.mark.parametrize("at_root", [False, True]) -def test_zeros(at_root): - kwargs = _init_creation_kwargs(at_root) - z = zeros(100, chunks=10, **kwargs) - assert (100,) == z.shape - assert (10,) == z.chunks - assert_array_equal(np.zeros(100), z[:]) - - -@pytest.mark.parametrize("at_root", [False, True]) -def test_ones(at_root): - kwargs = _init_creation_kwargs(at_root) - z = ones(100, chunks=10, **kwargs) - assert (100,) == z.shape - assert (10,) == z.chunks - assert_array_equal(np.ones(100), z[:]) - - -@pytest.mark.parametrize("at_root", [False, True]) -def test_full(at_root): - kwargs = _init_creation_kwargs(at_root) - z = full(100, chunks=10, fill_value=42, dtype="i4", **kwargs) - assert (100,) == z.shape - assert (10,) == z.chunks - assert_array_equal(np.full(100, fill_value=42, dtype="i4"), z[:]) - - # nan - z = full(100, chunks=10, fill_value=np.nan, dtype="f8", **kwargs) - assert np.all(np.isnan(z[:])) - - -def test_full_additional_dtypes(): - """Test additional types that aren't part of the base v3 spec.""" - kwargs = _init_creation_kwargs() - # NaT - z = full(100, chunks=10, fill_value="NaT", dtype="M8[s]", **kwargs) - assert np.all(np.isnat(z[:])) - z = full(100, chunks=10, fill_value="NaT", dtype="m8[s]", **kwargs) - assert np.all(np.isnat(z[:])) - - # byte string dtype - v = b"xxx" - z = full(100, chunks=10, fill_value=v, dtype="S3", **kwargs) - assert v == z[0] - a = z[...] - assert z.dtype == a.dtype - assert v == a[0] - assert np.all(a == v) - - # unicode string dtype - v = "xxx" - z = full(100, chunks=10, fill_value=v, dtype="U3", **kwargs) - assert v == z[0] - a = z[...] - assert z.dtype == a.dtype - assert v == a[0] - assert np.all(a == v) - - # bytes fill value / unicode dtype - v = b"xxx" - with pytest.raises(ValueError): - full(100, chunks=10, fill_value=v, dtype="U3") - - -@pytest.mark.parametrize("dimension_separator", [".", "/", None]) -@pytest.mark.parametrize("at_root", [False, True]) -def test_open_array(at_root, dimension_separator): - store = "data/array.zarr" - kwargs = _init_creation_kwargs(at_root) - - # mode == 'w' - z = open_array( - store, mode="w", shape=100, chunks=10, dimension_separator=dimension_separator, **kwargs - ) - z[:] = 42 - assert isinstance(z, Array) - - assert isinstance(z.store, DirectoryStore) - assert (100,) == z.shape - assert (10,) == z.chunks - assert_array_equal(np.full(100, fill_value=42), z[:]) - - if dimension_separator is None: - assert z._dimension_separator == "." - else: - assert z._dimension_separator == dimension_separator - - # mode in 'r', 'r+' - group_kwargs = kwargs.copy() - open_group("data/group.zarr", mode="w", **group_kwargs) - for mode in "r", "r+": - with pytest.raises(ValueError): - open_array("doesnotexist", mode=mode) - with pytest.raises(ValueError): - open_array("data/group.zarr", mode=mode) - z = open_array(store, mode="r", **kwargs) - assert isinstance(z, Array) - assert isinstance(z.store, DirectoryStore) - assert (100,) == z.shape - assert (10,) == z.chunks - assert_array_equal(np.full(100, fill_value=42), z[:]) - with pytest.raises(PermissionError): - z[:] = 43 - z = open_array(store, mode="r+", **kwargs) - assert isinstance(z, Array) - assert isinstance(z.store, DirectoryStore) - assert (100,) == z.shape - assert (10,) == z.chunks - assert_array_equal(np.full(100, fill_value=42), z[:]) - z[:] = 43 - assert_array_equal(np.full(100, fill_value=43), z[:]) - - # mode == 'a' - shutil.rmtree(store) - z = open_array(store, mode="a", shape=100, chunks=10, **kwargs) - z[:] = 42 - assert isinstance(z, Array) - assert isinstance(z.store, DirectoryStore) - assert (100,) == z.shape - assert (10,) == z.chunks - assert_array_equal(np.full(100, fill_value=42), z[:]) - - with pytest.raises(ValueError): - open_array("data/group.zarr", mode="a", **kwargs) - - # mode in 'w-', 'x' - for mode in "w-", "x": - shutil.rmtree(store) - z = open_array(store, mode=mode, shape=100, chunks=10, **kwargs) - z[:] = 42 - assert isinstance(z, Array) - assert isinstance(z.store, DirectoryStore) - assert (100,) == z.shape - assert (10,) == z.chunks - assert_array_equal(np.full(100, fill_value=42), z[:]) - with pytest.raises(ValueError): - open_array(store, mode=mode, **kwargs) - - with pytest.raises(ValueError): - open_array("data/group.zarr", mode=mode, **kwargs) - - # with synchronizer - z = open_array(store, synchronizer=ThreadSynchronizer(), **kwargs) - assert isinstance(z, Array) - - # with path - kwargs_no_path = kwargs.copy() - kwargs_no_path.pop("path", None) - z = open_array(store, shape=100, path="foo/bar", mode="w", **kwargs_no_path) - assert isinstance(z, Array) - assert "foo/bar" == z.path - - # with chunk store - meta_store = "data/meta.zarr" - chunk_store = "data/chunks.zarr" - z = open_array(store=meta_store, chunk_store=chunk_store, shape=11, mode="w", **kwargs) - z[:] = 42 - assert os.path.abspath(meta_store) == z.store.path - assert os.path.abspath(chunk_store) == z.chunk_store.path - - -def test_open_array_none(): - # open with store = None - z = open_array(mode="w", shape=100, chunks=10) - assert isinstance(z, Array) - - -@pytest.mark.parametrize("dimension_separator", [".", "/", None]) -def test_open_array_infer_separator_from_store(dimension_separator): - StoreClass = DirectoryStore - path = None - store = StoreClass("data/array.zarr", dimension_separator=dimension_separator) - - # Note: no dimension_separator kwarg to open_array - # we are testing here that it gets inferred from store - z = open_array(store, path=path, mode="w", shape=100, chunks=10) - z[:] = 42 - assert isinstance(z, Array) - assert isinstance(z.store, DirectoryStore) - assert (100,) == z.shape - assert (10,) == z.chunks - assert_array_equal(np.full(100, fill_value=42), z[:]) - - if dimension_separator is None: - assert z._dimension_separator == "." - else: - assert z._dimension_separator == dimension_separator - - -def test_open_array_n5(): - store = "data/array.zarr" - kwargs = _init_creation_kwargs() - - # for N5 store - store = "data/array.n5" - z = open_array(store, mode="w", shape=100, chunks=10, **kwargs) - z[:] = 42 - assert isinstance(z, Array) - assert isinstance(z.store, N5Store) - assert (100,) == z.shape - assert (10,) == z.chunks - assert_array_equal(np.full(100, fill_value=42), z[:]) - - store = "data/group.n5" - group_kwargs = kwargs.copy() - z = open_group(store, mode="w", **group_kwargs) - i = z.create_group("inner") - a = i.zeros("array", shape=100, chunks=10) - a[:] = 42 - - # Edit inner/attributes.json to not include "n5" - with open("data/group.n5/inner/attributes.json", "w") as o: - o.write("{}") - - # Re-open - a = open_group(store, **group_kwargs)["inner"]["array"] - assert isinstance(a, Array) - assert isinstance(z.store, N5Store) - assert (100,) == a.shape - assert (10,) == a.chunks - assert_array_equal(np.full(100, fill_value=42), a[:]) - - -@pytest.mark.parametrize("at_root", [False, True]) -def test_open_array_dict_store(at_root): - # dict will become a KVStore - store = dict() - kwargs = _init_creation_kwargs(at_root) - expected_store_type = KVStore - - # mode == 'w' - z = open_array(store, mode="w", shape=100, chunks=10, **kwargs) - z[:] = 42 - assert isinstance(z, Array) - assert isinstance(z.store, expected_store_type) - assert (100,) == z.shape - assert (10,) == z.chunks - assert_array_equal(np.full(100, fill_value=42), z[:]) - - -@pytest.mark.parametrize("at_root", [False, True]) -def test_create_in_dict(at_root): - kwargs = _init_creation_kwargs(at_root) - expected_store_type = KVStore - - for func in [empty, zeros, ones]: - a = func(100, store=dict(), **kwargs) - assert isinstance(a.store, expected_store_type) - - a = full(100, 5, store=dict(), **kwargs) - assert isinstance(a.store, expected_store_type) - - -@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") -@pytest.mark.parametrize("at_root", [False, True]) -def test_create_writeable_mode(at_root, tmp_path): - # Regression test for https://github.com/zarr-developers/zarr-python/issues/1306 - import fsspec - - kwargs = _init_creation_kwargs(at_root) - store = fsspec.get_mapper(str(tmp_path)) - z = create(100, store=store, **kwargs) - assert z.store.map == store - - -@pytest.mark.parametrize("at_root", [False, True]) -def test_empty_like(at_root): - kwargs = _init_creation_kwargs(at_root) - - # zarr array - z = empty(100, chunks=10, dtype="f4", compressor=Zlib(5), order="F", **kwargs) - z2 = empty_like(z, path=kwargs.get("path")) - assert z.shape == z2.shape - assert z.chunks == z2.chunks - assert z.dtype == z2.dtype - assert z.compressor.get_config() == z2.compressor.get_config() - assert z.fill_value == z2.fill_value - assert z.order == z2.order - - # numpy array - a = np.empty(100, dtype="f4") - z3 = empty_like(a, **kwargs) - assert a.shape == z3.shape - assert (100,) == z3.chunks - assert a.dtype == z3.dtype - assert z3.fill_value is None - - # something slightly silly - a = [0] * 100 - z3 = empty_like(a, shape=200, **kwargs) - assert (200,) == z3.shape - - # other array-likes - b = np.arange(1000).reshape(100, 10) - c = MockBcolzArray(b, 10) - z = empty_like(c, **kwargs) - assert b.shape == z.shape - assert (10, 10) == z.chunks - c = MockH5pyDataset(b, chunks=(10, 2)) - z = empty_like(c, **kwargs) - assert b.shape == z.shape - assert (10, 2) == z.chunks - c = MockH5pyDataset(b, chunks=None) - z = empty_like(c, **kwargs) - assert b.shape == z.shape - assert isinstance(z.chunks, tuple) - - -@pytest.mark.parametrize("at_root", [False, True]) -def test_zeros_like(at_root): - kwargs = _init_creation_kwargs(at_root) - - # zarr array - z = zeros(100, chunks=10, dtype="f4", compressor=Zlib(5), order="F", **kwargs) - z2 = zeros_like(z, path=kwargs.get("path")) - assert z.shape == z2.shape - assert z.chunks == z2.chunks - assert z.dtype == z2.dtype - assert z.compressor.get_config() == z2.compressor.get_config() - assert z.fill_value == z2.fill_value - assert z.order == z2.order - - # numpy array - a = np.empty(100, dtype="f4") - z3 = zeros_like(a, chunks=10, **kwargs) - assert a.shape == z3.shape - assert (10,) == z3.chunks - assert a.dtype == z3.dtype - assert 0 == z3.fill_value - - -@pytest.mark.parametrize("at_root", [False, True]) -def test_ones_like(at_root): - kwargs = _init_creation_kwargs(at_root) - - # zarr array - z = ones(100, chunks=10, dtype="f4", compressor=Zlib(5), order="F", **kwargs) - z2 = ones_like(z, path=kwargs.get("path")) - assert z.shape == z2.shape - assert z.chunks == z2.chunks - assert z.dtype == z2.dtype - assert z.compressor.get_config() == z2.compressor.get_config() - assert z.fill_value == z2.fill_value - assert z.order == z2.order - - # numpy array - a = np.empty(100, dtype="f4") - z3 = ones_like(a, chunks=10, **kwargs) - assert a.shape == z3.shape - assert (10,) == z3.chunks - assert a.dtype == z3.dtype - assert 1 == z3.fill_value - - -@pytest.mark.parametrize("at_root", [False, True]) -def test_full_like(at_root): - kwargs = _init_creation_kwargs(at_root) - - z = full(100, chunks=10, dtype="f4", compressor=Zlib(5), fill_value=42, order="F", **kwargs) - z2 = full_like(z, path=kwargs.get("path")) - assert z.shape == z2.shape - assert z.chunks == z2.chunks - assert z.dtype == z2.dtype - assert z.compressor.get_config() == z2.compressor.get_config() - assert z.fill_value == z2.fill_value - assert z.order == z2.order - - # numpy array - a = np.empty(100, dtype="f4") - z3 = full_like(a, chunks=10, fill_value=42, **kwargs) - assert a.shape == z3.shape - assert (10,) == z3.chunks - assert a.dtype == z3.dtype - assert 42 == z3.fill_value - - with pytest.raises(TypeError): - # fill_value missing - full_like(a, chunks=10, **kwargs) - - -@pytest.mark.parametrize("at_root", [False, True]) -def test_open_like(at_root): - kwargs = _init_creation_kwargs(at_root) - - # zarr array - path = mktemp() - atexit.register(shutil.rmtree, path) - z = full(100, chunks=10, dtype="f4", compressor=Zlib(5), fill_value=42, order="F", **kwargs) - z2 = open_like(z, path) - assert z.shape == z2.shape - assert z.chunks == z2.chunks - assert z.dtype == z2.dtype - assert z.compressor.get_config() == z2.compressor.get_config() - assert z.fill_value == z2.fill_value - assert z.order == z2.order - - # numpy array - path = mktemp() - atexit.register(shutil.rmtree, path) - a = np.empty(100, dtype="f4") - z3 = open_like(a, path, chunks=10) - assert a.shape == z3.shape - assert (10,) == z3.chunks - assert a.dtype == z3.dtype - assert 0 == z3.fill_value - - -@pytest.mark.parametrize("at_root", [False, True]) -def test_create(at_root): - kwargs = _init_creation_kwargs(at_root) - - # defaults - z = create(100, **kwargs) - assert isinstance(z, Array) - assert (100,) == z.shape - assert (100,) == z.chunks # auto-chunks - assert np.dtype(None) == z.dtype - assert "blosc" == z.compressor.codec_id - assert 0 == z.fill_value - - # all specified - z = create(100, chunks=10, dtype="i4", compressor=Zlib(1), fill_value=42, order="F", **kwargs) - assert isinstance(z, Array) - assert (100,) == z.shape - assert (10,) == z.chunks - assert np.dtype("i4") == z.dtype - assert "zlib" == z.compressor.codec_id - assert 1 == z.compressor.level - assert 42 == z.fill_value - assert "F" == z.order - - # with synchronizer - synchronizer = ThreadSynchronizer() - z = create(100, chunks=10, synchronizer=synchronizer, **kwargs) - assert isinstance(z, Array) - assert (100,) == z.shape - assert (10,) == z.chunks - assert synchronizer is z.synchronizer - - # don't allow string as compressor arg - with pytest.raises(ValueError): - create(100, chunks=10, compressor="zlib", **kwargs) - - # h5py compatibility - - z = create(100, compression="zlib", compression_opts=9, **kwargs) - assert "zlib" == z.compressor.codec_id - assert 9 == z.compressor.level - - z = create(100, compression="default", **kwargs) - assert "blosc" == z.compressor.codec_id - - # errors - with pytest.raises(ValueError): - # bad compression argument - create(100, compression=1, **kwargs) - with pytest.raises(ValueError): - # bad fill value - create(100, dtype="i4", fill_value="foo", **kwargs) - - # auto chunks - z = create(1000000000, chunks=True, **kwargs) - assert z.chunks[0] < z.shape[0] - z = create(1000000000, chunks=None, **kwargs) # backwards-compatibility - assert z.chunks[0] < z.shape[0] - # no chunks - z = create(1000000000, chunks=False, **kwargs) - assert z.chunks == z.shape - - -def test_compression_args(): - kwargs = _init_creation_kwargs() - - with warnings.catch_warnings(): - warnings.simplefilter("default") - z = create(100, compression="zlib", compression_opts=9, **kwargs) - assert isinstance(z, Array) - assert "zlib" == z.compressor.codec_id - assert 9 == z.compressor.level - - # 'compressor' overrides 'compression' - with pytest.warns(UserWarning): - z = create(100, compressor=Zlib(9), compression="bz2", compression_opts=1, **kwargs) - assert isinstance(z, Array) - assert "zlib" == z.compressor.codec_id - assert 9 == z.compressor.level - - # 'compressor' ignores 'compression_opts' - with pytest.warns(UserWarning): - z = create(100, compressor=Zlib(9), compression_opts=1, **kwargs) - assert isinstance(z, Array) - assert "zlib" == z.compressor.codec_id - assert 9 == z.compressor.level - - with pytest.warns(UserWarning): - # 'compressor' overrides 'compression' - create(100, compressor=Zlib(9), compression="bz2", compression_opts=1, **kwargs) - with pytest.warns(UserWarning): - # 'compressor' ignores 'compression_opts' - create(100, compressor=Zlib(9), compression_opts=1, **kwargs) - - -@pytest.mark.parametrize("at_root", [False, True]) -def test_create_read_only(at_root): - # https://github.com/alimanfoo/zarr/issues/151 - - kwargs = _init_creation_kwargs(at_root) - - # create an array initially read-only, then enable writing - z = create(100, read_only=True, **kwargs) - assert z.read_only - with pytest.raises(PermissionError): - z[:] = 42 - z.read_only = False - z[:] = 42 - assert np.all(z[...] == 42) - z.read_only = True - with pytest.raises(PermissionError): - z[:] = 0 - - # this is subtly different, but here we want to create an array with data, and then - # have it be read-only - a = np.arange(100) - z = array(a, read_only=True, **kwargs) - assert_array_equal(a, z[...]) - assert z.read_only - with pytest.raises(PermissionError): - z[:] = 42 - - -def test_json_dumps_chunks_numpy_dtype(): - z = zeros((10,), chunks=(np.int64(2),)) - assert np.all(z[...] == 0) - - -@pytest.mark.parametrize( - ("init_shape", "init_chunks", "shape", "chunks"), - ( - ((1,), (1,), (1,), (1,)), - ((1.0,), (1.0,), (1,), (1,)), - ((1.0,), False, (1,), (1,)), - ((1.0,), True, (1,), (1,)), - ((1.0,), None, (1,), (1,)), - ), -) -def test_shape_chunk_ints(init_shape, init_chunks, shape, chunks): - g = open_group() - array = g.create_dataset("ds", shape=init_shape, chunks=init_chunks, dtype=np.uint8) - - assert all( - isinstance(s, int) for s in array.shape - ), f"Expected shape to be all ints but found {array.shape=}." - assert all( - isinstance(c, int) for c in array.chunks - ), f"Expected chunks to be all ints but found {array.chunks=}." - assert array.shape == shape, f"Expected {shape=} but found {array.shape=}." - assert array.chunks == chunks, f"Expected {chunks=} but found {array.chunks=}." diff --git a/tests/v2/test_dim_separator.py b/tests/v2/test_dim_separator.py deleted file mode 100644 index 2cff527f89..0000000000 --- a/tests/v2/test_dim_separator.py +++ /dev/null @@ -1,136 +0,0 @@ -import pathlib - -import pytest -from numpy.testing import assert_array_equal -from functools import partial - -import zarr.v2 -from zarr.v2.core import Array -from zarr.v2.storage import DirectoryStore, NestedDirectoryStore, FSStore -from .util import have_fsspec - - -needs_fsspec = pytest.mark.skipif(not have_fsspec, reason="needs fsspec") - - -@pytest.fixture( - params=( - "static_flat", - "static_flat_legacy", - "static_nested", - "static_nested_legacy", - "directory_nested", - "directory_flat", - "directory_default", - "nesteddirectory_nested", - "nesteddirectory_default", - pytest.param("fs_nested", marks=needs_fsspec), - pytest.param("fs_flat", marks=needs_fsspec), - pytest.param("fs_default", marks=needs_fsspec), - ) -) -def dataset(tmpdir, request) -> None: - """ - Generate a variety of different Zarrs using - different store implementations as well as - different dimension_separator arguments. - """ - - loc = tmpdir.join("dim_sep_test.zarr") - which = request.param - kwargs = {} - - if which.startswith("static"): - test_root = pathlib.Path(__file__).parent - suffix = which[len("static_") :] - static = test_root / "fixture" / "dimension_separator" / suffix - - # this commented block will generate the static fixtures. - # if not static.exists(): # pragma: no cover - # if "nested" in which: - # # No way to reproduce the nested_legacy file via code - # generator = NestedDirectoryStore - # else: - # if "legacy" in suffix: - # # No dimension_separator metadata included - # generator = DirectoryStore - # else: - # # Explicit dimension_separator metadata included - # generator = partial(DirectoryStore, dimension_separator=".") - - # # store the data - should be one-time operation - # s = generator(str(static)) - # a = zarr.v2.open(store=s, mode="w", shape=(2, 2), dtype=" len(array_keys) - assert sorted(array_keys_recurse) == ["baz", "zab"] - - # test recursive arrays - arrays = list(g1["foo"].arrays(recurse=False)) - arrays_recurse = list(g1["foo"].arrays(recurse=True)) - assert len(arrays_recurse) > len(arrays) - assert "zab" == arrays_recurse[0][0] - assert g1["foo"]["bar"]["zab"] == arrays_recurse[0][1] - - g1.store.close() - - def test_getattr(self): - # setup - g1 = self.create_group() - g2 = g1.create_group("foo") - g2.create_dataset("bar", shape=100) - - # test - assert g1["foo"] == g1.foo - assert g2["bar"] == g2.bar - # test that hasattr returns False instead of an exception (issue #88) - assert not hasattr(g1, "unexistingattribute") - - g1.store.close() - - def test_setitem(self): - g = self.create_group() - try: - data = np.arange(100) - g["foo"] = data - assert_array_equal(data, g["foo"]) - data = np.arange(200) - g["foo"] = data - assert_array_equal(data, g["foo"]) - # 0d array - g["foo"] = 42 - assert () == g["foo"].shape - assert 42 == g["foo"][()] - except NotImplementedError: - pass - g.store.close() - - def test_delitem(self): - g = self.create_group() - g.create_group("foo") - g.create_dataset("bar/baz", shape=100, chunks=10) - assert "foo" in g - assert "bar" in g - assert "bar/baz" in g - try: - del g["bar"] - with pytest.raises(KeyError): - del g["xxx"] - except NotImplementedError: - pass - else: - assert "foo" in g - assert "bar" not in g - assert "bar/baz" not in g - g.store.close() - - def test_move(self): - g = self.create_group() - - data = np.arange(100) - g["boo"] = data - - data = np.arange(100) - g["foo"] = data - - g.move("foo", "bar") - assert "foo" not in g - assert "bar" in g - assert_array_equal(data, g["bar"]) - - g.move("bar", "foo/bar") - assert "bar" not in g - assert "foo" in g - assert "foo/bar" in g - assert isinstance(g["foo"], Group) - assert_array_equal(data, g["foo/bar"]) - - g.move("foo", "foo2") - assert "foo" not in g - assert "foo/bar" not in g - assert "foo2" in g - assert "foo2/bar" in g - assert isinstance(g["foo2"], Group) - assert_array_equal(data, g["foo2/bar"]) - - g2 = g["foo2"] - g2.move("bar", "/bar") - assert "foo2" in g - assert "foo2/bar" not in g - assert "bar" in g - assert isinstance(g["foo2"], Group) - - assert_array_equal(data, g["bar"]) - - with pytest.raises(ValueError): - g2.move("bar", "bar2") - - with pytest.raises(ValueError): - g.move("bar", "boo") - - g.store.close() - - def test_array_creation(self): - grp = self.create_group() - - a = grp.create("a", shape=100, chunks=10) - assert isinstance(a, Array) - b = grp.empty("b", shape=100, chunks=10) - assert isinstance(b, Array) - assert b.fill_value is None - c = grp.zeros("c", shape=100, chunks=10) - assert isinstance(c, Array) - assert 0 == c.fill_value - d = grp.ones("d", shape=100, chunks=10) - assert isinstance(d, Array) - assert 1 == d.fill_value - e = grp.full("e", shape=100, chunks=10, fill_value=42) - assert isinstance(e, Array) - assert 42 == e.fill_value - - f = grp.empty_like("f", a) - assert isinstance(f, Array) - assert f.fill_value is None - g = grp.zeros_like("g", a) - assert isinstance(g, Array) - assert 0 == g.fill_value - h = grp.ones_like("h", a) - assert isinstance(h, Array) - assert 1 == h.fill_value - i = grp.full_like("i", e) - assert isinstance(i, Array) - assert 42 == i.fill_value - - j = grp.array("j", data=np.arange(100), chunks=10) - assert isinstance(j, Array) - assert_array_equal(np.arange(100), j[:]) - - grp.store.close() - - grp = self.create_group(read_only=True) - with pytest.raises(PermissionError): - grp.create("aa", shape=100, chunks=10) - with pytest.raises(PermissionError): - grp.empty("aa", shape=100, chunks=10) - with pytest.raises(PermissionError): - grp.zeros("aa", shape=100, chunks=10) - with pytest.raises(PermissionError): - grp.ones("aa", shape=100, chunks=10) - with pytest.raises(PermissionError): - grp.full("aa", shape=100, chunks=10, fill_value=42) - with pytest.raises(PermissionError): - grp.array("aa", data=np.arange(100), chunks=10) - with pytest.raises(PermissionError): - grp.create("aa", shape=100, chunks=10) - with pytest.raises(PermissionError): - grp.empty_like("aa", a) - with pytest.raises(PermissionError): - grp.zeros_like("aa", a) - with pytest.raises(PermissionError): - grp.ones_like("aa", a) - with pytest.raises(PermissionError): - grp.full_like("aa", a) - - grp.store.close() - - def test_paths(self): - g1 = self.create_group() - g2 = g1.create_group("foo/bar") - - assert g1 == g1["/"] - assert g1 == g1["//"] - assert g1 == g1["///"] - assert g1 == g2["/"] - assert g1 == g2["//"] - assert g1 == g2["///"] - assert g2 == g1["foo/bar"] - assert g2 == g1["/foo/bar"] - assert g2 == g1["foo/bar/"] - assert g2 == g1["//foo/bar"] - assert g2 == g1["//foo//bar//"] - assert g2 == g1["///foo///bar///"] - assert g2 == g2["/foo/bar"] - - with pytest.raises(ValueError): - g1["."] - with pytest.raises(ValueError): - g1[".."] - with pytest.raises(ValueError): - g1["foo/."] - with pytest.raises(ValueError): - g1["foo/.."] - with pytest.raises(ValueError): - g1["foo/./bar"] - with pytest.raises(ValueError): - g1["foo/../bar"] - - g1.store.close() - - def test_pickle(self): - # setup group - g = self.create_group() - d = g.create_dataset("foo/bar", shape=100, chunks=10) - d[:] = np.arange(100) - path = g.path - name = g.name - n = len(g) - keys = list(g) - - # round-trip through pickle - dump = pickle.dumps(g) - # some stores cannot be opened twice at the same time, need to close - # store before can round-trip through pickle - g.store.close() - g2 = pickle.loads(dump) - - # verify - assert path == g2.path - assert name == g2.name - assert n == len(g2) - assert keys == list(g2) - assert isinstance(g2["foo"], Group) - assert isinstance(g2["foo/bar"], Array) - - g2.store.close() - - def test_context_manager(self): - with self.create_group() as g: - d = g.create_dataset("foo/bar", shape=100, chunks=10) - d[:] = np.arange(100) - - -@pytest.mark.parametrize("chunk_dict", [False, True]) -def test_group_init_from_dict(chunk_dict): - if chunk_dict: - store, chunk_store = dict(), dict() - else: - store, chunk_store = dict(), None - init_group(store, path=None, chunk_store=chunk_store) - g = Group(store, path=None, read_only=False, chunk_store=chunk_store) - assert store is not g.store - assert isinstance(g.store, KVStore) - if chunk_store is None: - assert g.store is g.chunk_store - else: - assert chunk_store is not g.chunk_store - - -class TestGroupWithMemoryStore(TestGroup): - @staticmethod - def create_store(): - return MemoryStore(), None - - -class TestGroupWithDirectoryStore(TestGroup): - @staticmethod - def create_store(): - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - store = DirectoryStore(path) - return store, None - - -@skip_test_env_var("ZARR_TEST_ABS") -class TestGroupWithABSStore(TestGroup): - @staticmethod - def create_store(): - container_client = abs_container() - store = ABSStore(client=container_client) - store.rmdir() - return store, None - - @pytest.mark.skipif(sys.version_info < (3, 7), reason="attr not serializable in py36") - def test_pickle(self): - # internal attribute on ContainerClient isn't serializable for py36 and earlier - super().test_pickle() - - -class TestGroupWithNestedDirectoryStore(TestGroup): - @staticmethod - def create_store(): - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - store = NestedDirectoryStore(path) - return store, None - - -@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") -class TestGroupWithFSStore(TestGroup): - @staticmethod - def create_store(): - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - store = FSStore(path) - return store, None - - def test_round_trip_nd(self): - data = np.arange(1000).reshape(10, 10, 10) - name = "raw" - - store, _ = self.create_store() - f = open_group(store, mode="w") - f.create_dataset(name, data=data, chunks=(5, 5, 5), compressor=None) - assert name in f - h = open_group(store, mode="r") - np.testing.assert_array_equal(h[name][:], data) - - -@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") -class TestGroupWithNestedFSStore(TestGroupWithFSStore): - @staticmethod - def create_store(): - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - store = FSStore(path, key_separator="/", auto_mkdir=True) - return store, None - - def test_inconsistent_dimension_separator(self): - data = np.arange(1000).reshape(10, 10, 10) - name = "raw" - - store, _ = self.create_store() - f = open_group(store, mode="w") - - # cannot specify dimension_separator that conflicts with the store - with pytest.raises(ValueError): - f.create_dataset( - name, data=data, chunks=(5, 5, 5), compressor=None, dimension_separator="." - ) - - -class TestGroupWithZipStore(TestGroup): - @staticmethod - def create_store(): - path = mktemp(suffix=".zip") - atexit.register(os.remove, path) - store = ZipStore(path) - return store, None - - def test_context_manager(self): - with self.create_group() as g: - store = g.store - d = g.create_dataset("foo/bar", shape=100, chunks=10) - d[:] = np.arange(100) - - # Check that exiting the context manager closes the store, - # and therefore the underlying ZipFile. - with pytest.raises(ValueError): - store.zf.extractall() - - def test_move(self): - # zip store is not erasable (can so far only append to a zip - # so we can't test for move. - pass - - -class TestGroupWithDBMStore(TestGroup): - @staticmethod - def create_store(): - path = mktemp(suffix=".anydbm") - atexit.register(atexit_rmglob, path + "*") - store = DBMStore(path, flag="n") - return store, None - - -class TestGroupWithDBMStoreBerkeleyDB(TestGroup): - @staticmethod - def create_store(): - bsddb3 = pytest.importorskip("bsddb3") - path = mktemp(suffix=".dbm") - atexit.register(os.remove, path) - store = DBMStore(path, flag="n", open=bsddb3.btopen) - return store, None - - -class TestGroupWithLMDBStore(TestGroup): - @staticmethod - def create_store(): - pytest.importorskip("lmdb") - path = mktemp(suffix=".lmdb") - atexit.register(atexit_rmtree, path) - store = LMDBStore(path) - return store, None - - -class TestGroupWithSQLiteStore(TestGroup): - def create_store(self): - pytest.importorskip("sqlite3") - path = mktemp(suffix=".db") - atexit.register(atexit_rmtree, path) - store = SQLiteStore(path) - return store, None - - -class TestGroupWithChunkStore(TestGroup): - @staticmethod - def create_store(): - return KVStore(dict()), KVStore(dict()) - - def test_chunk_store(self): - # setup - store, chunk_store = self.create_store() - g = self.create_group(store, chunk_store=chunk_store) - - # check attributes - assert store is g.store - assert chunk_store is g.chunk_store - - # create array - a = g.zeros("foo", shape=100, chunks=10) - assert store is a.store - assert chunk_store is a.chunk_store - a[:] = np.arange(100) - assert_array_equal(np.arange(100), a[:]) - - # check store keys - expect = sorted([group_meta_key, "foo/" + array_meta_key]) - actual = sorted(store.keys()) - assert expect == actual - expect = ["foo/" + str(i) for i in range(10)] - actual = sorted(chunk_store.keys()) - assert expect == actual - - -class TestGroupWithStoreCache(TestGroup): - @staticmethod - def create_store(): - store = LRUStoreCache(dict(), max_size=None) - return store, None - - -@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") -def test_group_writeable_mode(tmp_path): - # Regression test for https://github.com/zarr-developers/zarr-python/issues/1353 - import fsspec - - store = fsspec.get_mapper(str(tmp_path)) - zg = group(store=store) - assert zg.store.map == store - - -def test_open_group(): - # test the open_group() convenience function - - store = "data/group.zarr" - - expected_store_type = DirectoryStore - - # mode == 'w' - path = None - g = open_group(store, path=path, mode="w") - assert isinstance(g, Group) - assert isinstance(g.store, expected_store_type) - assert 0 == len(g) - g.create_groups("foo", "bar") - assert 2 == len(g) - - # mode in 'r', 'r+' - open_array("data/array.zarr", shape=100, chunks=10, mode="w") - for mode in "r", "r+": - with pytest.raises(ValueError): - open_group("doesnotexist", mode=mode) - with pytest.raises(ValueError): - open_group("data/array.zarr", mode=mode) - g = open_group(store, mode="r") - assert isinstance(g, Group) - assert 2 == len(g) - with pytest.raises(PermissionError): - g.create_group("baz") - g = open_group(store, mode="r+") - assert isinstance(g, Group) - assert 2 == len(g) - g.create_groups("baz", "quux") - assert 4 == len(g) - - # mode == 'a' - shutil.rmtree(store) - g = open_group(store, path=path, mode="a") - assert isinstance(g, Group) - assert isinstance(g.store, expected_store_type) - assert 0 == len(g) - g.create_groups("foo", "bar") - assert 2 == len(g) - - with pytest.raises(ValueError): - open_group("data/array.zarr", mode="a") - - # mode in 'w-', 'x' - for mode in "w-", "x": - shutil.rmtree(store) - g = open_group(store, path=path, mode=mode) - assert isinstance(g, Group) - assert isinstance(g.store, expected_store_type) - assert 0 == len(g) - g.create_groups("foo", "bar") - assert 2 == len(g) - with pytest.raises(ValueError): - open_group(store, path=path, mode=mode) - with pytest.raises(ValueError): - open_group("data/array.zarr", mode=mode) - - # open with path - g = open_group(store, path="foo/bar") - assert isinstance(g, Group) - assert "foo/bar" == g.path - - -def test_group_completions(): - path = None - g = group(path=path) - d = dir(g) - assert "foo" not in d - assert "bar" not in d - assert "baz" not in d - assert "qux" not in d - assert "xxx" not in d - assert "yyy" not in d - assert "zzz" not in d - assert "123" not in d - assert "456" not in d - g.create_groups("foo", "bar", "baz/qux", "123") - g.zeros("xxx", shape=100) - g.zeros("yyy", shape=100) - g.zeros("zzz", shape=100) - g.zeros("456", shape=100) - d = dir(g) - assert "foo" in d - assert "bar" in d - assert "baz" in d - assert "qux" not in d - assert "xxx" in d - assert "yyy" in d - assert "zzz" in d - assert "123" not in d # not valid identifier - assert "456" not in d # not valid identifier - - -def test_group_key_completions(): - path = None - g = group(path=path) - d = dir(g) - # noinspection PyProtectedMember - k = g._ipython_key_completions_() - - # none of these names should be an attribute - assert "foo" not in d - assert "bar" not in d - assert "baz" not in d - assert "qux" not in d - assert "xxx" not in d - assert "yyy" not in d - assert "zzz" not in d - assert "123" not in d - assert "456" not in d - assert "asdf;" not in d - - # none of these names should be an item - assert "foo" not in k - assert "bar" not in k - assert "baz" not in k - assert "qux" not in k - assert "xxx" not in k - assert "yyy" not in k - assert "zzz" not in k - assert "123" not in k - assert "456" not in k - assert "asdf;" not in k - - g.create_groups("foo", "bar", "baz/qux", "123") - g.zeros("xxx", shape=100) - g.zeros("yyy", shape=100) - g.zeros("zzz", shape=100) - g.zeros("456", shape=100) - g.zeros("asdf;", shape=100) - - d = dir(g) - # noinspection PyProtectedMember - k = g._ipython_key_completions_() - - assert "foo" in d - assert "bar" in d - assert "baz" in d - assert "qux" not in d - assert "xxx" in d - assert "yyy" in d - assert "zzz" in d - assert "123" not in d # not valid identifier - assert "456" not in d # not valid identifier - assert "asdf;" not in d # not valid identifier - - assert "foo" in k - assert "bar" in k - assert "baz" in k - assert "qux" not in k - assert "xxx" in k - assert "yyy" in k - assert "zzz" in k - assert "123" in k - assert "456" in k - assert "asdf;" in k - - -def _check_tree(g, expect_bytes, expect_text): - assert expect_bytes == bytes(g.tree()) - assert expect_text == str(g.tree()) - expect_repr = expect_text - assert expect_repr == repr(g.tree()) - if ipytree: - # noinspection PyProtectedMember - widget = g.tree()._repr_mimebundle_() - isinstance(widget, ipytree.Tree) - - -@pytest.mark.parametrize("at_root", [False, True]) -def test_tree(at_root): - # setup - path = None if at_root else "group1" - g1 = group(path=path) - g2 = g1.create_group("foo") - g3 = g1.create_group("bar") - g3.create_group("baz") - g5 = g3.create_group("quux") - g5.create_dataset("baz", shape=100, chunks=10) - - tree_path = "/" if at_root else path - # test root group - - expect_bytes = textwrap.dedent( - f"""\ - {tree_path} - +-- bar - | +-- baz - | +-- quux - | +-- baz (100,) float64 - +-- foo""" - ).encode() - expect_text = textwrap.dedent( - f"""\ - {tree_path} - β”œβ”€β”€ bar - β”‚ β”œβ”€β”€ baz - β”‚ └── quux - β”‚ └── baz (100,) float64 - └── foo""" - ) - _check_tree(g1, expect_bytes, expect_text) - - # test different group - expect_bytes = textwrap.dedent( - """\ - foo""" - ).encode() - expect_text = textwrap.dedent( - """\ - foo""" - ) - _check_tree(g2, expect_bytes, expect_text) - - # test different group - expect_bytes = textwrap.dedent( - """\ - bar - +-- baz - +-- quux - +-- baz (100,) float64""" - ).encode() - expect_text = textwrap.dedent( - """\ - bar - β”œβ”€β”€ baz - └── quux - └── baz (100,) float64""" - ) - _check_tree(g3, expect_bytes, expect_text) - - -def test_open_group_from_paths(): - """Verify zarr_version is applied to both the store and chunk_store.""" - store = tempfile.mkdtemp() - chunk_store = tempfile.mkdtemp() - atexit.register(atexit_rmtree, store) - atexit.register(atexit_rmtree, chunk_store) - path = "g1" - _ = open_group(store, path=path, chunk_store=chunk_store) diff --git a/tests/v2/test_indexing.py b/tests/v2/test_indexing.py deleted file mode 100644 index c1fd87572d..0000000000 --- a/tests/v2/test_indexing.py +++ /dev/null @@ -1,1758 +0,0 @@ -import numpy as np -import pytest -from numpy.testing import assert_array_equal - -import zarr.v2 -from zarr.v2.indexing import ( - make_slice_selection, - normalize_integer_selection, - oindex, - oindex_set, - replace_ellipsis, - PartialChunkIterator, -) - -from .util import CountingDict - - -def test_normalize_integer_selection(): - assert 1 == normalize_integer_selection(1, 100) - assert 99 == normalize_integer_selection(-1, 100) - with pytest.raises(IndexError): - normalize_integer_selection(100, 100) - with pytest.raises(IndexError): - normalize_integer_selection(1000, 100) - with pytest.raises(IndexError): - normalize_integer_selection(-1000, 100) - - -def test_replace_ellipsis(): - # 1D, single item - assert (0,) == replace_ellipsis(0, (100,)) - - # 1D - assert (slice(None),) == replace_ellipsis(Ellipsis, (100,)) - assert (slice(None),) == replace_ellipsis(slice(None), (100,)) - assert (slice(None, 100),) == replace_ellipsis(slice(None, 100), (100,)) - assert (slice(0, None),) == replace_ellipsis(slice(0, None), (100,)) - assert (slice(None),) == replace_ellipsis((slice(None), Ellipsis), (100,)) - assert (slice(None),) == replace_ellipsis((Ellipsis, slice(None)), (100,)) - - # 2D, single item - assert (0, 0) == replace_ellipsis((0, 0), (100, 100)) - assert (-1, 1) == replace_ellipsis((-1, 1), (100, 100)) - - # 2D, single col/row - assert (0, slice(None)) == replace_ellipsis((0, slice(None)), (100, 100)) - assert (0, slice(None)) == replace_ellipsis((0,), (100, 100)) - assert (slice(None), 0) == replace_ellipsis((slice(None), 0), (100, 100)) - - # 2D slice - assert (slice(None), slice(None)) == replace_ellipsis(Ellipsis, (100, 100)) - assert (slice(None), slice(None)) == replace_ellipsis(slice(None), (100, 100)) - assert (slice(None), slice(None)) == replace_ellipsis((slice(None), slice(None)), (100, 100)) - assert (slice(None), slice(None)) == replace_ellipsis((Ellipsis, slice(None)), (100, 100)) - assert (slice(None), slice(None)) == replace_ellipsis((slice(None), Ellipsis), (100, 100)) - assert (slice(None), slice(None)) == replace_ellipsis( - (slice(None), Ellipsis, slice(None)), (100, 100) - ) - assert (slice(None), slice(None)) == replace_ellipsis( - (Ellipsis, slice(None), slice(None)), (100, 100) - ) - assert (slice(None), slice(None)) == replace_ellipsis( - (slice(None), slice(None), Ellipsis), (100, 100) - ) - - -def test_get_basic_selection_0d(): - # setup - a = np.array(42) - z = zarr.v2.create(shape=a.shape, dtype=a.dtype, fill_value=None) - z[...] = a - - assert_array_equal(a, z.get_basic_selection(Ellipsis)) - assert_array_equal(a, z[...]) - assert 42 == z.get_basic_selection(()) - assert 42 == z[()] - - # test out param - b = np.zeros_like(a) - z.get_basic_selection(Ellipsis, out=b) - assert_array_equal(a, b) - - # test structured array - value = (b"aaa", 1, 4.2) - a = np.array(value, dtype=[("foo", "S3"), ("bar", "i4"), ("baz", "f8")]) - z = zarr.v2.create(shape=a.shape, dtype=a.dtype, fill_value=None) - z[()] = value - assert_array_equal(a, z.get_basic_selection(Ellipsis)) - assert_array_equal(a, z[...]) - assert a[()] == z.get_basic_selection(()) - assert a[()] == z[()] - assert b"aaa" == z.get_basic_selection((), fields="foo") - assert b"aaa" == z["foo"] - assert a[["foo", "bar"]] == z.get_basic_selection((), fields=["foo", "bar"]) - assert a[["foo", "bar"]] == z["foo", "bar"] - # test out param - b = np.zeros_like(a) - z.get_basic_selection(Ellipsis, out=b) - assert_array_equal(a, b) - c = np.zeros_like(a[["foo", "bar"]]) - z.get_basic_selection(Ellipsis, out=c, fields=["foo", "bar"]) - assert_array_equal(a[["foo", "bar"]], c) - - -basic_selections_1d = [ - # single value - 42, - -1, - # slices - slice(0, 1050), - slice(50, 150), - slice(0, 2000), - slice(-150, -50), - slice(-2000, 2000), - slice(0, 0), # empty result - slice(-1, 0), # empty result - # total selections - slice(None), - Ellipsis, - (), - (Ellipsis, slice(None)), - # slice with step - slice(None), - slice(None, None), - slice(None, None, 1), - slice(None, None, 10), - slice(None, None, 100), - slice(None, None, 1000), - slice(None, None, 10000), - slice(0, 1050), - slice(0, 1050, 1), - slice(0, 1050, 10), - slice(0, 1050, 100), - slice(0, 1050, 1000), - slice(0, 1050, 10000), - slice(1, 31, 3), - slice(1, 31, 30), - slice(1, 31, 300), - slice(81, 121, 3), - slice(81, 121, 30), - slice(81, 121, 300), - slice(50, 150), - slice(50, 150, 1), - slice(50, 150, 10), -] - - -basic_selections_1d_bad = [ - # only positive step supported - slice(None, None, -1), - slice(None, None, -10), - slice(None, None, -100), - slice(None, None, -1000), - slice(None, None, -10000), - slice(1050, -1, -1), - slice(1050, -1, -10), - slice(1050, -1, -100), - slice(1050, -1, -1000), - slice(1050, -1, -10000), - slice(1050, 0, -1), - slice(1050, 0, -10), - slice(1050, 0, -100), - slice(1050, 0, -1000), - slice(1050, 0, -10000), - slice(150, 50, -1), - slice(150, 50, -10), - slice(31, 1, -3), - slice(121, 81, -3), - slice(-1, 0, -1), - # bad stuff - 2.3, - "foo", - b"xxx", - None, - (0, 0), - (slice(None), slice(None)), -] - - -def _test_get_basic_selection(a, z, selection): - expect = a[selection] - actual = z.get_basic_selection(selection) - assert_array_equal(expect, actual) - actual = z[selection] - assert_array_equal(expect, actual) - - -# noinspection PyStatementEffect -def test_get_basic_selection_1d(): - # setup - a = np.arange(1050, dtype=int) - z = zarr.v2.create(shape=a.shape, chunks=100, dtype=a.dtype) - z[:] = a - - for selection in basic_selections_1d: - _test_get_basic_selection(a, z, selection) - - for selection in basic_selections_1d_bad: - with pytest.raises(IndexError): - z.get_basic_selection(selection) - with pytest.raises(IndexError): - z[selection] - - with pytest.raises(IndexError): - z.get_basic_selection([1, 0]) - - -basic_selections_2d = [ - # single row - 42, - -1, - (42, slice(None)), - (-1, slice(None)), - # single col - (slice(None), 4), - (slice(None), -1), - # row slices - slice(None), - slice(0, 1000), - slice(250, 350), - slice(0, 2000), - slice(-350, -250), - slice(0, 0), # empty result - slice(-1, 0), # empty result - slice(-2000, 0), - slice(-2000, 2000), - # 2D slices - (slice(None), slice(1, 5)), - (slice(250, 350), slice(None)), - (slice(250, 350), slice(1, 5)), - (slice(250, 350), slice(-5, -1)), - (slice(250, 350), slice(-50, 50)), - (slice(250, 350, 10), slice(1, 5)), - (slice(250, 350), slice(1, 5, 2)), - (slice(250, 350, 33), slice(1, 5, 3)), - # total selections - (slice(None), slice(None)), - Ellipsis, - (), - (Ellipsis, slice(None)), - (Ellipsis, slice(None), slice(None)), -] - - -basic_selections_2d_bad = [ - # bad stuff - 2.3, - "foo", - b"xxx", - None, - (2.3, slice(None)), - # only positive step supported - slice(None, None, -1), - (slice(None, None, -1), slice(None)), - (0, 0, 0), - (slice(None), slice(None), slice(None)), -] - - -# noinspection PyStatementEffect -def test_get_basic_selection_2d(): - # setup - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr.v2.create(shape=a.shape, chunks=(300, 3), dtype=a.dtype) - z[:] = a - - for selection in basic_selections_2d: - _test_get_basic_selection(a, z, selection) - - bad_selections = basic_selections_2d_bad + [ - # integer arrays - [0, 1], - (slice(None), [0, 1]), - ] - for selection in bad_selections: - with pytest.raises(IndexError): - z.get_basic_selection(selection) - # check fallback on fancy indexing - fancy_selection = ([0, 1], [0, 1]) - np.testing.assert_array_equal(z[fancy_selection], [0, 11]) - - -def test_fancy_indexing_fallback_on_get_setitem(): - z = zarr.v2.zeros((20, 20)) - z[[1, 2, 3], [1, 2, 3]] = 1 - np.testing.assert_array_equal( - z[:4, :4], - [ - [0, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 1, 0], - [0, 0, 0, 1], - ], - ) - np.testing.assert_array_equal(z[[1, 2, 3], [1, 2, 3]], 1) - # test broadcasting - np.testing.assert_array_equal(z[1, [1, 2, 3]], [1, 0, 0]) - # test 1D fancy indexing - z2 = zarr.v2.zeros(5) - z2[[1, 2, 3]] = 1 - np.testing.assert_array_equal(z2, [0, 1, 1, 1, 0]) - - -@pytest.mark.parametrize( - "index,expected_result", - [ - # Single iterable of integers - ([0, 1], [[0, 1, 2], [3, 4, 5]]), - # List first, then slice - (([0, 1], slice(None)), [[0, 1, 2], [3, 4, 5]]), - # List first, then slice - (([0, 1], slice(1, None)), [[1, 2], [4, 5]]), - # Slice first, then list - ((slice(0, 2), [0, 2]), [[0, 2], [3, 5]]), - # Slices only - ((slice(0, 2), slice(0, 2)), [[0, 1], [3, 4]]), - # List with repeated index - (([1, 0, 1], slice(1, None)), [[4, 5], [1, 2], [4, 5]]), - # 1D indexing - (([1, 0, 1]), [[3, 4, 5], [0, 1, 2], [3, 4, 5]]), - ], -) -def test_orthogonal_indexing_fallback_on_getitem_2d(index, expected_result): - """ - Tests the orthogonal indexing fallback on __getitem__ for a 2D matrix. - - In addition to checking expected behavior, all indexing - is also checked against numpy. - """ - # [0, 1, 2], - # [3, 4, 5], - # [6, 7, 8] - a = np.arange(9).reshape(3, 3) - z = zarr.v2.array(a) - - np.testing.assert_array_equal(z[index], a[index], err_msg="Indexing disagrees with numpy") - np.testing.assert_array_equal(z[index], expected_result) - - -@pytest.mark.parametrize( - "index,expected_result", - [ - # Single iterable of integers - ([0, 1], [[[0, 1, 2], [3, 4, 5], [6, 7, 8]], [[9, 10, 11], [12, 13, 14], [15, 16, 17]]]), - # One slice, two integers - ((slice(0, 2), 1, 1), [4, 13]), - # One integer, two slices - ((slice(0, 2), 1, slice(0, 2)), [[3, 4], [12, 13]]), - # Two slices and a list - ((slice(0, 2), [1, 2], slice(0, 2)), [[[3, 4], [6, 7]], [[12, 13], [15, 16]]]), - ], -) -def test_orthogonal_indexing_fallback_on_getitem_3d(index, expected_result): - """ - Tests the orthogonal indexing fallback on __getitem__ for a 3D matrix. - - In addition to checking expected behavior, all indexing - is also checked against numpy. - """ - # [[[ 0, 1, 2], - # [ 3, 4, 5], - # [ 6, 7, 8]], - - # [[ 9, 10, 11], - # [12, 13, 14], - # [15, 16, 17]], - - # [[18, 19, 20], - # [21, 22, 23], - # [24, 25, 26]]] - a = np.arange(27).reshape(3, 3, 3) - z = zarr.v2.array(a) - - np.testing.assert_array_equal(z[index], a[index], err_msg="Indexing disagrees with numpy") - np.testing.assert_array_equal(z[index], expected_result) - - -@pytest.mark.parametrize( - "index,expected_result", - [ - # Single iterable of integers - ([0, 1], [[1, 1, 1], [1, 1, 1], [0, 0, 0]]), - # List and slice combined - (([0, 1], slice(1, 3)), [[0, 1, 1], [0, 1, 1], [0, 0, 0]]), - # Index repetition is ignored on setitem - (([0, 1, 1, 1, 1, 1, 1], slice(1, 3)), [[0, 1, 1], [0, 1, 1], [0, 0, 0]]), - # Slice with step - (([0, 2], slice(None, None, 2)), [[1, 0, 1], [0, 0, 0], [1, 0, 1]]), - ], -) -def test_orthogonal_indexing_fallback_on_setitem_2d(index, expected_result): - """ - Tests the orthogonal indexing fallback on __setitem__ for a 3D matrix. - - In addition to checking expected behavior, all indexing - is also checked against numpy. - """ - # Slice + fancy index - a = np.zeros((3, 3)) - z = zarr.v2.array(a) - z[index] = 1 - a[index] = 1 - np.testing.assert_array_equal(z, expected_result) - np.testing.assert_array_equal(z, a, err_msg="Indexing disagrees with numpy") - - -def test_fancy_indexing_doesnt_mix_with_implicit_slicing(): - z2 = zarr.v2.zeros((5, 5, 5)) - with pytest.raises(IndexError): - z2[[1, 2, 3], [1, 2, 3]] = 2 - with pytest.raises(IndexError): - np.testing.assert_array_equal(z2[[1, 2, 3], [1, 2, 3]], 0) - with pytest.raises(IndexError): - z2[..., [1, 2, 3]] = 2 - with pytest.raises(IndexError): - np.testing.assert_array_equal(z2[..., [1, 2, 3]], 0) - - -def test_set_basic_selection_0d(): - # setup - v = np.array(42) - a = np.zeros_like(v) - z = zarr.v2.zeros_like(v) - assert_array_equal(a, z) - - # tests - z.set_basic_selection(Ellipsis, v) - assert_array_equal(v, z) - z[...] = 0 - assert_array_equal(a, z) - z[...] = v - assert_array_equal(v, z) - - # test structured array - value = (b"aaa", 1, 4.2) - v = np.array(value, dtype=[("foo", "S3"), ("bar", "i4"), ("baz", "f8")]) - a = np.zeros_like(v) - z = zarr.v2.create(shape=a.shape, dtype=a.dtype, fill_value=None) - - # tests - z.set_basic_selection(Ellipsis, v) - assert_array_equal(v, z) - z.set_basic_selection(Ellipsis, a) - assert_array_equal(a, z) - z[...] = v - assert_array_equal(v, z) - z[...] = a - assert_array_equal(a, z) - # with fields - z.set_basic_selection(Ellipsis, v["foo"], fields="foo") - assert v["foo"] == z["foo"] - assert a["bar"] == z["bar"] - assert a["baz"] == z["baz"] - z["bar"] = v["bar"] - assert v["foo"] == z["foo"] - assert v["bar"] == z["bar"] - assert a["baz"] == z["baz"] - # multiple field assignment not supported - with pytest.raises(IndexError): - z.set_basic_selection(Ellipsis, v[["foo", "bar"]], fields=["foo", "bar"]) - with pytest.raises(IndexError): - z[..., "foo", "bar"] = v[["foo", "bar"]] - - -def _test_get_orthogonal_selection(a, z, selection): - expect = oindex(a, selection) - actual = z.get_orthogonal_selection(selection) - assert_array_equal(expect, actual) - actual = z.oindex[selection] - assert_array_equal(expect, actual) - - -# noinspection PyStatementEffect -def test_get_orthogonal_selection_1d_bool(): - # setup - a = np.arange(1050, dtype=int) - z = zarr.v2.create(shape=a.shape, chunks=100, dtype=a.dtype) - z[:] = a - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - _test_get_orthogonal_selection(a, z, ix) - - # test errors - with pytest.raises(IndexError): - z.oindex[np.zeros(50, dtype=bool)] # too short - with pytest.raises(IndexError): - z.oindex[np.zeros(2000, dtype=bool)] # too long - with pytest.raises(IndexError): - z.oindex[[[True, False], [False, True]]] # too many dimensions - - -# noinspection PyStatementEffect -def test_get_orthogonal_selection_1d_int(): - # setup - a = np.arange(1050, dtype=int) - z = zarr.v2.create(shape=a.shape, chunks=100, dtype=a.dtype) - z[:] = a - - np.random.seed(42) - # test with different degrees of sparseness - for p in 2, 0.5, 0.1, 0.01: - # unordered - ix = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - _test_get_orthogonal_selection(a, z, ix) - # increasing - ix.sort() - _test_get_orthogonal_selection(a, z, ix) - # decreasing - ix = ix[::-1] - _test_get_orthogonal_selection(a, z, ix) - - selections = basic_selections_1d + [ - # test wraparound - [0, 3, 10, -23, -12, -1], - # explicit test not sorted - [3, 105, 23, 127], - ] - for selection in selections: - _test_get_orthogonal_selection(a, z, selection) - - bad_selections = basic_selections_1d_bad + [ - [a.shape[0] + 1], # out of bounds - [-(a.shape[0] + 1)], # out of bounds - [[2, 4], [6, 8]], # too many dimensions - ] - for selection in bad_selections: - with pytest.raises(IndexError): - z.get_orthogonal_selection(selection) - with pytest.raises(IndexError): - z.oindex[selection] - - -def _test_get_orthogonal_selection_2d(a, z, ix0, ix1): - selections = [ - # index both axes with array - (ix0, ix1), - # mixed indexing with array / slice - (ix0, slice(1, 5)), - (ix0, slice(1, 5, 2)), - (slice(250, 350), ix1), - (slice(250, 350, 10), ix1), - # mixed indexing with array / int - (ix0, 4), - (42, ix1), - ] - for selection in selections: - _test_get_orthogonal_selection(a, z, selection) - - -# noinspection PyStatementEffect -def test_get_orthogonal_selection_2d(): - # setup - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr.v2.create(shape=a.shape, chunks=(300, 3), dtype=a.dtype) - z[:] = a - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - # boolean arrays - ix0 = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - ix1 = np.random.binomial(1, 0.5, size=a.shape[1]).astype(bool) - _test_get_orthogonal_selection_2d(a, z, ix0, ix1) - - # mixed int array / bool array - selections = ( - (ix0, np.nonzero(ix1)[0]), - (np.nonzero(ix0)[0], ix1), - ) - for selection in selections: - _test_get_orthogonal_selection(a, z, selection) - - # integer arrays - ix0 = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - ix1 = np.random.choice(a.shape[1], size=int(a.shape[1] * 0.5), replace=True) - _test_get_orthogonal_selection_2d(a, z, ix0, ix1) - ix0.sort() - ix1.sort() - _test_get_orthogonal_selection_2d(a, z, ix0, ix1) - ix0 = ix0[::-1] - ix1 = ix1[::-1] - _test_get_orthogonal_selection_2d(a, z, ix0, ix1) - - for selection in basic_selections_2d: - _test_get_orthogonal_selection(a, z, selection) - - for selection in basic_selections_2d_bad: - with pytest.raises(IndexError): - z.get_orthogonal_selection(selection) - with pytest.raises(IndexError): - z.oindex[selection] - - -def _test_get_orthogonal_selection_3d(a, z, ix0, ix1, ix2): - selections = [ - # single value - (84, 42, 4), - (-1, -1, -1), - # index all axes with array - (ix0, ix1, ix2), - # mixed indexing with single array / slices - (ix0, slice(15, 25), slice(1, 5)), - (slice(50, 70), ix1, slice(1, 5)), - (slice(50, 70), slice(15, 25), ix2), - (ix0, slice(15, 25, 5), slice(1, 5, 2)), - (slice(50, 70, 3), ix1, slice(1, 5, 2)), - (slice(50, 70, 3), slice(15, 25, 5), ix2), - # mixed indexing with single array / ints - (ix0, 42, 4), - (84, ix1, 4), - (84, 42, ix2), - # mixed indexing with single array / slice / int - (ix0, slice(15, 25), 4), - (42, ix1, slice(1, 5)), - (slice(50, 70), 42, ix2), - # mixed indexing with two array / slice - (ix0, ix1, slice(1, 5)), - (slice(50, 70), ix1, ix2), - (ix0, slice(15, 25), ix2), - # mixed indexing with two array / integer - (ix0, ix1, 4), - (42, ix1, ix2), - (ix0, 42, ix2), - ] - for selection in selections: - _test_get_orthogonal_selection(a, z, selection) - - -def test_get_orthogonal_selection_3d(): - # setup - a = np.arange(100000, dtype=int).reshape(200, 50, 10) - z = zarr.v2.create(shape=a.shape, chunks=(60, 20, 3), dtype=a.dtype) - z[:] = a - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - # boolean arrays - ix0 = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - ix1 = np.random.binomial(1, 0.5, size=a.shape[1]).astype(bool) - ix2 = np.random.binomial(1, 0.5, size=a.shape[2]).astype(bool) - _test_get_orthogonal_selection_3d(a, z, ix0, ix1, ix2) - - # integer arrays - ix0 = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - ix1 = np.random.choice(a.shape[1], size=int(a.shape[1] * 0.5), replace=True) - ix2 = np.random.choice(a.shape[2], size=int(a.shape[2] * 0.5), replace=True) - _test_get_orthogonal_selection_3d(a, z, ix0, ix1, ix2) - ix0.sort() - ix1.sort() - ix2.sort() - _test_get_orthogonal_selection_3d(a, z, ix0, ix1, ix2) - ix0 = ix0[::-1] - ix1 = ix1[::-1] - ix2 = ix2[::-1] - _test_get_orthogonal_selection_3d(a, z, ix0, ix1, ix2) - - -def test_orthogonal_indexing_edge_cases(): - a = np.arange(6).reshape(1, 2, 3) - z = zarr.v2.create(shape=a.shape, chunks=(1, 2, 3), dtype=a.dtype) - z[:] = a - - expect = oindex(a, (0, slice(None), [0, 1, 2])) - actual = z.oindex[0, :, [0, 1, 2]] - assert_array_equal(expect, actual) - - expect = oindex(a, (0, slice(None), [True, True, True])) - actual = z.oindex[0, :, [True, True, True]] - assert_array_equal(expect, actual) - - -def _test_set_orthogonal_selection(v, a, z, selection): - for value in 42, oindex(v, selection), oindex(v, selection).tolist(): - if isinstance(value, list) and value == []: - # skip these cases as cannot preserve all dimensions - continue - # setup expectation - a[:] = 0 - oindex_set(a, selection, value) - # long-form API - z[:] = 0 - z.set_orthogonal_selection(selection, value) - assert_array_equal(a, z[:]) - # short-form API - z[:] = 0 - z.oindex[selection] = value - assert_array_equal(a, z[:]) - - -def test_set_orthogonal_selection_1d(): - # setup - v = np.arange(1050, dtype=int) - a = np.empty(v.shape, dtype=int) - z = zarr.v2.create(shape=a.shape, chunks=100, dtype=a.dtype) - - # test with different degrees of sparseness - np.random.seed(42) - for p in 0.5, 0.1, 0.01: - # boolean arrays - ix = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - _test_set_orthogonal_selection(v, a, z, ix) - - # integer arrays - ix = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - _test_set_orthogonal_selection(v, a, z, ix) - ix.sort() - _test_set_orthogonal_selection(v, a, z, ix) - ix = ix[::-1] - _test_set_orthogonal_selection(v, a, z, ix) - - # basic selections - for selection in basic_selections_1d: - _test_set_orthogonal_selection(v, a, z, selection) - - -def _test_set_orthogonal_selection_2d(v, a, z, ix0, ix1): - selections = [ - # index both axes with array - (ix0, ix1), - # mixed indexing with array / slice or int - (ix0, slice(1, 5)), - (slice(250, 350), ix1), - (ix0, 4), - (42, ix1), - ] - for selection in selections: - _test_set_orthogonal_selection(v, a, z, selection) - - -def test_set_orthogonal_selection_2d(): - # setup - v = np.arange(10000, dtype=int).reshape(1000, 10) - a = np.empty_like(v) - z = zarr.v2.create(shape=a.shape, chunks=(300, 3), dtype=a.dtype) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - # boolean arrays - ix0 = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - ix1 = np.random.binomial(1, 0.5, size=a.shape[1]).astype(bool) - _test_set_orthogonal_selection_2d(v, a, z, ix0, ix1) - - # integer arrays - ix0 = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - ix1 = np.random.choice(a.shape[1], size=int(a.shape[1] * 0.5), replace=True) - _test_set_orthogonal_selection_2d(v, a, z, ix0, ix1) - ix0.sort() - ix1.sort() - _test_set_orthogonal_selection_2d(v, a, z, ix0, ix1) - ix0 = ix0[::-1] - ix1 = ix1[::-1] - _test_set_orthogonal_selection_2d(v, a, z, ix0, ix1) - - for selection in basic_selections_2d: - _test_set_orthogonal_selection(v, a, z, selection) - - -def _test_set_orthogonal_selection_3d(v, a, z, ix0, ix1, ix2): - selections = ( - # single value - (84, 42, 4), - (-1, -1, -1), - # index all axes with bool array - (ix0, ix1, ix2), - # mixed indexing with single bool array / slice or int - (ix0, slice(15, 25), slice(1, 5)), - (slice(50, 70), ix1, slice(1, 5)), - (slice(50, 70), slice(15, 25), ix2), - (ix0, 42, 4), - (84, ix1, 4), - (84, 42, ix2), - (ix0, slice(15, 25), 4), - (slice(50, 70), ix1, 4), - (slice(50, 70), 42, ix2), - # indexing with two arrays / slice - (ix0, ix1, slice(1, 5)), - # indexing with two arrays / integer - (ix0, ix1, 4), - ) - for selection in selections: - _test_set_orthogonal_selection(v, a, z, selection) - - -def test_set_orthogonal_selection_3d(): - # setup - v = np.arange(100000, dtype=int).reshape(200, 50, 10) - a = np.empty_like(v) - z = zarr.v2.create(shape=a.shape, chunks=(60, 20, 3), dtype=a.dtype) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - # boolean arrays - ix0 = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - ix1 = np.random.binomial(1, 0.5, size=a.shape[1]).astype(bool) - ix2 = np.random.binomial(1, 0.5, size=a.shape[2]).astype(bool) - _test_set_orthogonal_selection_3d(v, a, z, ix0, ix1, ix2) - - # integer arrays - ix0 = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - ix1 = np.random.choice(a.shape[1], size=int(a.shape[1] * 0.5), replace=True) - ix2 = np.random.choice(a.shape[2], size=int(a.shape[2] * 0.5), replace=True) - _test_set_orthogonal_selection_3d(v, a, z, ix0, ix1, ix2) - - # sorted increasing - ix0.sort() - ix1.sort() - ix2.sort() - _test_set_orthogonal_selection_3d(v, a, z, ix0, ix1, ix2) - - # sorted decreasing - ix0 = ix0[::-1] - ix1 = ix1[::-1] - ix2 = ix2[::-1] - _test_set_orthogonal_selection_3d(v, a, z, ix0, ix1, ix2) - - -def test_orthogonal_indexing_fallback_on_get_setitem(): - z = zarr.v2.zeros((20, 20)) - z[[1, 2, 3], [1, 2, 3]] = 1 - np.testing.assert_array_equal( - z[:4, :4], - [ - [0, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 1, 0], - [0, 0, 0, 1], - ], - ) - np.testing.assert_array_equal(z[[1, 2, 3], [1, 2, 3]], 1) - # test broadcasting - np.testing.assert_array_equal(z[1, [1, 2, 3]], [1, 0, 0]) - # test 1D fancy indexing - z2 = zarr.v2.zeros(5) - z2[[1, 2, 3]] = 1 - np.testing.assert_array_equal(z2, [0, 1, 1, 1, 0]) - - -def _test_get_coordinate_selection(a, z, selection): - expect = a[selection] - actual = z.get_coordinate_selection(selection) - assert_array_equal(expect, actual) - actual = z.vindex[selection] - assert_array_equal(expect, actual) - - -coordinate_selections_1d_bad = [ - # slice not supported - slice(5, 15), - slice(None), - Ellipsis, - # bad stuff - 2.3, - "foo", - b"xxx", - None, - (0, 0), - (slice(None), slice(None)), -] - - -# noinspection PyStatementEffect -def test_get_coordinate_selection_1d(): - # setup - a = np.arange(1050, dtype=int) - z = zarr.v2.create(shape=a.shape, chunks=100, dtype=a.dtype) - z[:] = a - - np.random.seed(42) - # test with different degrees of sparseness - for p in 2, 0.5, 0.1, 0.01: - n = int(a.size * p) - ix = np.random.choice(a.shape[0], size=n, replace=True) - _test_get_coordinate_selection(a, z, ix) - ix.sort() - _test_get_coordinate_selection(a, z, ix) - ix = ix[::-1] - _test_get_coordinate_selection(a, z, ix) - - selections = [ - # test single item - 42, - -1, - # test wraparound - [0, 3, 10, -23, -12, -1], - # test out of order - [3, 105, 23, 127], # not monotonically increasing - # test multi-dimensional selection - np.array([[2, 4], [6, 8]]), - ] - for selection in selections: - _test_get_coordinate_selection(a, z, selection) - - # test errors - bad_selections = coordinate_selections_1d_bad + [ - [a.shape[0] + 1], # out of bounds - [-(a.shape[0] + 1)], # out of bounds - ] - for selection in bad_selections: - with pytest.raises(IndexError): - z.get_coordinate_selection(selection) - with pytest.raises(IndexError): - z.vindex[selection] - - -def test_get_coordinate_selection_2d(): - # setup - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr.v2.create(shape=a.shape, chunks=(300, 3), dtype=a.dtype) - z[:] = a - - np.random.seed(42) - # test with different degrees of sparseness - for p in 2, 0.5, 0.1, 0.01: - n = int(a.size * p) - ix0 = np.random.choice(a.shape[0], size=n, replace=True) - ix1 = np.random.choice(a.shape[1], size=n, replace=True) - selections = [ - # single value - (42, 4), - (-1, -1), - # index both axes with array - (ix0, ix1), - # mixed indexing with array / int - (ix0, 4), - (42, ix1), - (42, 4), - ] - for selection in selections: - _test_get_coordinate_selection(a, z, selection) - - # not monotonically increasing (first dim) - ix0 = [3, 3, 4, 2, 5] - ix1 = [1, 3, 5, 7, 9] - _test_get_coordinate_selection(a, z, (ix0, ix1)) - - # not monotonically increasing (second dim) - ix0 = [1, 1, 2, 2, 5] - ix1 = [1, 3, 2, 1, 0] - _test_get_coordinate_selection(a, z, (ix0, ix1)) - - # multi-dimensional selection - ix0 = np.array([[1, 1, 2], [2, 2, 5]]) - ix1 = np.array([[1, 3, 2], [1, 0, 0]]) - _test_get_coordinate_selection(a, z, (ix0, ix1)) - - with pytest.raises(IndexError): - selection = slice(5, 15), [1, 2, 3] - z.get_coordinate_selection(selection) - with pytest.raises(IndexError): - selection = [1, 2, 3], slice(5, 15) - z.get_coordinate_selection(selection) - with pytest.raises(IndexError): - selection = Ellipsis, [1, 2, 3] - z.get_coordinate_selection(selection) - with pytest.raises(IndexError): - selection = Ellipsis - z.get_coordinate_selection(selection) - - -def _test_set_coordinate_selection(v, a, z, selection): - for value in 42, v[selection], v[selection].tolist(): - # setup expectation - a[:] = 0 - a[selection] = value - # test long-form API - z[:] = 0 - z.set_coordinate_selection(selection, value) - assert_array_equal(a, z[:]) - # test short-form API - z[:] = 0 - z.vindex[selection] = value - assert_array_equal(a, z[:]) - - -def test_set_coordinate_selection_1d(): - # setup - v = np.arange(1050, dtype=int) - a = np.empty(v.shape, dtype=v.dtype) - z = zarr.v2.create(shape=a.shape, chunks=100, dtype=a.dtype) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 2, 0.5, 0.1, 0.01: - n = int(a.size * p) - ix = np.random.choice(a.shape[0], size=n, replace=True) - _test_set_coordinate_selection(v, a, z, ix) - - # multi-dimensional selection - ix = np.array([[2, 4], [6, 8]]) - _test_set_coordinate_selection(v, a, z, ix) - - for selection in coordinate_selections_1d_bad: - with pytest.raises(IndexError): - z.set_coordinate_selection(selection, 42) - with pytest.raises(IndexError): - z.vindex[selection] = 42 - - -def test_set_coordinate_selection_2d(): - # setup - v = np.arange(10000, dtype=int).reshape(1000, 10) - a = np.empty_like(v) - z = zarr.v2.create(shape=a.shape, chunks=(300, 3), dtype=a.dtype) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 2, 0.5, 0.1, 0.01: - n = int(a.size * p) - ix0 = np.random.choice(a.shape[0], size=n, replace=True) - ix1 = np.random.choice(a.shape[1], size=n, replace=True) - - selections = ( - (42, 4), - (-1, -1), - # index both axes with array - (ix0, ix1), - # mixed indexing with array / int - (ix0, 4), - (42, ix1), - ) - for selection in selections: - _test_set_coordinate_selection(v, a, z, selection) - - # multi-dimensional selection - ix0 = np.array([[1, 2, 3], [4, 5, 6]]) - ix1 = np.array([[1, 3, 2], [2, 0, 5]]) - _test_set_coordinate_selection(v, a, z, (ix0, ix1)) - - -def _test_get_block_selection(a, z, selection, expected_idx): - expect = a[expected_idx] - actual = z.get_block_selection(selection) - assert_array_equal(expect, actual) - actual = z.blocks[selection] - assert_array_equal(expect, actual) - - -block_selections_1d = [ - # test single item - 0, - 5, - # test wraparound - -1, - -4, - # test slice - slice(5), - slice(None, 3), - slice(5, 6), - slice(-3, -1), - slice(None), # Full slice -] - -block_selections_1d_array_projection = [ - # test single item - slice(100), - slice(500, 600), - # test wraparound - slice(1000, None), - slice(700, 800), - # test slice - slice(500), - slice(None, 300), - slice(500, 600), - slice(800, 1000), - slice(None), -] - -block_selections_1d_bad = [ - # slice not supported - slice(3, 8, 2), - # bad stuff - 2.3, - "foo", - b"xxx", - None, - (0, 0), - (slice(None), slice(None)), - [0, 5, 3], -] - - -def test_get_block_selection_1d(): - # setup - a = np.arange(1050, dtype=int) - z = zarr.v2.create(shape=a.shape, chunks=100, dtype=a.dtype) - z[:] = a - - for selection, expected_idx in zip(block_selections_1d, block_selections_1d_array_projection): - _test_get_block_selection(a, z, selection, expected_idx) - - bad_selections = block_selections_1d_bad + [ - z.nchunks + 1, # out of bounds - -(z.nchunks + 1), # out of bounds - ] - - for selection in bad_selections: - with pytest.raises(IndexError): - z.get_block_selection(selection) - with pytest.raises(IndexError): - z.blocks[selection] - - -block_selections_2d = [ - # test single item - (0, 0), - (1, 2), - # test wraparound - (-1, -1), - (-3, -2), - # test slice - (slice(1), slice(2)), - (slice(None, 2), slice(-2, -1)), - (slice(2, 3), slice(-2, None)), - (slice(-3, -1), slice(-3, -2)), - (slice(None), slice(None)), # Full slice -] - -block_selections_2d_array_projection = [ - # test single item - (slice(300), slice(3)), - (slice(300, 600), slice(6, 9)), - # test wraparound - (slice(900, None), slice(9, None)), - (slice(300, 600), slice(6, 9)), - # test slice - (slice(300), slice(6)), - (slice(None, 600), slice(6, 9)), - (slice(600, 900), slice(6, None)), - (slice(300, 900), slice(3, 6)), - (slice(None), slice(None)), # Full slice -] - - -def test_get_block_selection_2d(): - # setup - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr.v2.create(shape=a.shape, chunks=(300, 3), dtype=a.dtype) - z[:] = a - - for selection, expected_idx in zip(block_selections_2d, block_selections_2d_array_projection): - _test_get_block_selection(a, z, selection, expected_idx) - - with pytest.raises(IndexError): - selection = slice(5, 15), [1, 2, 3] - z.get_block_selection(selection) - with pytest.raises(IndexError): - selection = Ellipsis, [1, 2, 3] - z.get_block_selection(selection) - with pytest.raises(IndexError): # out of bounds - selection = slice(15, 20), slice(None) - z.get_block_selection(selection) - - -def _test_set_block_selection( - v: np.ndarray, a: np.ndarray, z: zarr.v2.Array, selection, expected_idx -): - for value in 42, v[expected_idx], v[expected_idx].tolist(): - # setup expectation - a[:] = 0 - a[expected_idx] = value - # test long-form API - z[:] = 0 - z.set_block_selection(selection, value) - assert_array_equal(a, z[:]) - # test short-form API - z[:] = 0 - z.blocks[selection] = value - assert_array_equal(a, z[:]) - - -def test_set_block_selection_1d(): - # setup - v = np.arange(1050, dtype=int) - a = np.empty(v.shape, dtype=v.dtype) - z = zarr.v2.create(shape=a.shape, chunks=100, dtype=a.dtype) - - for selection, expected_idx in zip(block_selections_1d, block_selections_1d_array_projection): - _test_set_block_selection(v, a, z, selection, expected_idx) - - for selection in block_selections_1d_bad: - with pytest.raises(IndexError): - z.set_block_selection(selection, 42) - with pytest.raises(IndexError): - z.blocks[selection] = 42 - - -def test_set_block_selection_2d(): - # setup - v = np.arange(10000, dtype=int).reshape(1000, 10) - a = np.empty(v.shape, dtype=v.dtype) - z = zarr.v2.create(shape=a.shape, chunks=(300, 3), dtype=a.dtype) - - for selection, expected_idx in zip(block_selections_2d, block_selections_2d_array_projection): - _test_set_block_selection(v, a, z, selection, expected_idx) - - with pytest.raises(IndexError): - selection = slice(5, 15), [1, 2, 3] - z.set_block_selection(selection, 42) - with pytest.raises(IndexError): - selection = Ellipsis, [1, 2, 3] - z.set_block_selection(selection, 42) - with pytest.raises(IndexError): # out of bounds - selection = slice(15, 20), slice(None) - z.set_block_selection(selection, 42) - - -def _test_get_mask_selection(a, z, selection): - expect = a[selection] - actual = z.get_mask_selection(selection) - assert_array_equal(expect, actual) - actual = z.vindex[selection] - assert_array_equal(expect, actual) - - -mask_selections_1d_bad = [ - # slice not supported - slice(5, 15), - slice(None), - Ellipsis, - # bad stuff - 2.3, - "foo", - b"xxx", - None, - (0, 0), - (slice(None), slice(None)), -] - - -# noinspection PyStatementEffect -def test_get_mask_selection_1d(): - # setup - a = np.arange(1050, dtype=int) - z = zarr.v2.create(shape=a.shape, chunks=100, dtype=a.dtype) - z[:] = a - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - _test_get_mask_selection(a, z, ix) - - # test errors - bad_selections = mask_selections_1d_bad + [ - np.zeros(50, dtype=bool), # too short - np.zeros(2000, dtype=bool), # too long - [[True, False], [False, True]], # too many dimensions - ] - for selection in bad_selections: - with pytest.raises(IndexError): - z.get_mask_selection(selection) - with pytest.raises(IndexError): - z.vindex[selection] - - -# noinspection PyStatementEffect -def test_get_mask_selection_2d(): - # setup - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr.v2.create(shape=a.shape, chunks=(300, 3), dtype=a.dtype) - z[:] = a - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix = np.random.binomial(1, p, size=a.size).astype(bool).reshape(a.shape) - _test_get_mask_selection(a, z, ix) - - # test errors - with pytest.raises(IndexError): - z.vindex[np.zeros((1000, 5), dtype=bool)] # too short - with pytest.raises(IndexError): - z.vindex[np.zeros((2000, 10), dtype=bool)] # too long - with pytest.raises(IndexError): - z.vindex[[True, False]] # wrong no. dimensions - - -def _test_set_mask_selection(v, a, z, selection): - a[:] = 0 - z[:] = 0 - a[selection] = v[selection] - z.set_mask_selection(selection, v[selection]) - assert_array_equal(a, z[:]) - z[:] = 0 - z.vindex[selection] = v[selection] - assert_array_equal(a, z[:]) - - -def test_set_mask_selection_1d(): - # setup - v = np.arange(1050, dtype=int) - a = np.empty_like(v) - z = zarr.v2.create(shape=a.shape, chunks=100, dtype=a.dtype) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - _test_set_mask_selection(v, a, z, ix) - - for selection in mask_selections_1d_bad: - with pytest.raises(IndexError): - z.set_mask_selection(selection, 42) - with pytest.raises(IndexError): - z.vindex[selection] = 42 - - -def test_set_mask_selection_2d(): - # setup - v = np.arange(10000, dtype=int).reshape(1000, 10) - a = np.empty_like(v) - z = zarr.v2.create(shape=a.shape, chunks=(300, 3), dtype=a.dtype) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix = np.random.binomial(1, p, size=a.size).astype(bool).reshape(a.shape) - _test_set_mask_selection(v, a, z, ix) - - -def test_get_selection_out(): - # basic selections - a = np.arange(1050) - z = zarr.v2.create(shape=1050, chunks=100, dtype=a.dtype) - z[:] = a - selections = [ - slice(50, 150), - slice(0, 1050), - slice(1, 2), - ] - for selection in selections: - expect = a[selection] - out = zarr.v2.create(shape=expect.shape, chunks=10, dtype=expect.dtype, fill_value=0) - z.get_basic_selection(selection, out=out) - assert_array_equal(expect, out[:]) - - with pytest.raises(TypeError): - z.get_basic_selection(Ellipsis, out=[]) - - # orthogonal selections - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr.v2.create(shape=a.shape, chunks=(300, 3), dtype=a.dtype) - z[:] = a - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix0 = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - ix1 = np.random.binomial(1, 0.5, size=a.shape[1]).astype(bool) - selections = [ - # index both axes with array - (ix0, ix1), - # mixed indexing with array / slice - (ix0, slice(1, 5)), - (slice(250, 350), ix1), - # mixed indexing with array / int - (ix0, 4), - (42, ix1), - # mixed int array / bool array - (ix0, np.nonzero(ix1)[0]), - (np.nonzero(ix0)[0], ix1), - ] - for selection in selections: - expect = oindex(a, selection) - # out = zarr.v2.create(shape=expect.shape, chunks=10, dtype=expect.dtype, - # fill_value=0) - out = np.zeros(expect.shape, dtype=expect.dtype) - z.get_orthogonal_selection(selection, out=out) - assert_array_equal(expect, out[:]) - - # coordinate selections - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr.v2.create(shape=a.shape, chunks=(300, 3), dtype=a.dtype) - z[:] = a - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - n = int(a.size * p) - ix0 = np.random.choice(a.shape[0], size=n, replace=True) - ix1 = np.random.choice(a.shape[1], size=n, replace=True) - selections = [ - # index both axes with array - (ix0, ix1), - # mixed indexing with array / int - (ix0, 4), - (42, ix1), - ] - for selection in selections: - expect = a[selection] - out = np.zeros(expect.shape, dtype=expect.dtype) - z.get_coordinate_selection(selection, out=out) - assert_array_equal(expect, out[:]) - - -def test_get_selections_with_fields(): - a = [("aaa", 1, 4.2), ("bbb", 2, 8.4), ("ccc", 3, 12.6)] - a = np.array(a, dtype=[("foo", "S3"), ("bar", "i4"), ("baz", "f8")]) - z = zarr.v2.create(shape=a.shape, chunks=2, dtype=a.dtype, fill_value=None) - z[:] = a - - fields_fixture = [ - "foo", - ["foo"], - ["foo", "bar"], - ["foo", "baz"], - ["bar", "baz"], - ["foo", "bar", "baz"], - ["bar", "foo"], - ["baz", "bar", "foo"], - ] - - for fields in fields_fixture: - # total selection - expect = a[fields] - actual = z.get_basic_selection(Ellipsis, fields=fields) - assert_array_equal(expect, actual) - # alternative API - if isinstance(fields, str): - actual = z[fields] - assert_array_equal(expect, actual) - elif len(fields) == 2: - actual = z[fields[0], fields[1]] - assert_array_equal(expect, actual) - if isinstance(fields, str): - actual = z[..., fields] - assert_array_equal(expect, actual) - elif len(fields) == 2: - actual = z[..., fields[0], fields[1]] - assert_array_equal(expect, actual) - - # basic selection with slice - expect = a[fields][0:2] - actual = z.get_basic_selection(slice(0, 2), fields=fields) - assert_array_equal(expect, actual) - # alternative API - if isinstance(fields, str): - actual = z[0:2, fields] - assert_array_equal(expect, actual) - elif len(fields) == 2: - actual = z[0:2, fields[0], fields[1]] - assert_array_equal(expect, actual) - - # basic selection with single item - expect = a[fields][1] - actual = z.get_basic_selection(1, fields=fields) - assert_array_equal(expect, actual) - # alternative API - if isinstance(fields, str): - actual = z[1, fields] - assert_array_equal(expect, actual) - elif len(fields) == 2: - actual = z[1, fields[0], fields[1]] - assert_array_equal(expect, actual) - - # orthogonal selection - ix = [0, 2] - expect = a[fields][ix] - actual = z.get_orthogonal_selection(ix, fields=fields) - assert_array_equal(expect, actual) - # alternative API - if isinstance(fields, str): - actual = z.oindex[ix, fields] - assert_array_equal(expect, actual) - elif len(fields) == 2: - actual = z.oindex[ix, fields[0], fields[1]] - assert_array_equal(expect, actual) - - # coordinate selection - ix = [0, 2] - expect = a[fields][ix] - actual = z.get_coordinate_selection(ix, fields=fields) - assert_array_equal(expect, actual) - # alternative API - if isinstance(fields, str): - actual = z.vindex[ix, fields] - assert_array_equal(expect, actual) - elif len(fields) == 2: - actual = z.vindex[ix, fields[0], fields[1]] - assert_array_equal(expect, actual) - - # mask selection - ix = [True, False, True] - expect = a[fields][ix] - actual = z.get_mask_selection(ix, fields=fields) - assert_array_equal(expect, actual) - # alternative API - if isinstance(fields, str): - actual = z.vindex[ix, fields] - assert_array_equal(expect, actual) - elif len(fields) == 2: - actual = z.vindex[ix, fields[0], fields[1]] - assert_array_equal(expect, actual) - - # missing/bad fields - with pytest.raises(IndexError): - z.get_basic_selection(Ellipsis, fields=["notafield"]) - with pytest.raises(IndexError): - z.get_basic_selection(Ellipsis, fields=slice(None)) - - -def test_set_selections_with_fields(): - v = [("aaa", 1, 4.2), ("bbb", 2, 8.4), ("ccc", 3, 12.6)] - v = np.array(v, dtype=[("foo", "S3"), ("bar", "i4"), ("baz", "f8")]) - a = np.empty_like(v) - z = zarr.v2.empty_like(v, chunks=2) - - fields_fixture = [ - "foo", - [], - ["foo"], - ["foo", "bar"], - ["foo", "baz"], - ["bar", "baz"], - ["foo", "bar", "baz"], - ["bar", "foo"], - ["baz", "bar", "foo"], - ] - - for fields in fields_fixture: - # currently multi-field assignment is not supported in numpy, so we won't support - # it either - if isinstance(fields, list) and len(fields) > 1: - with pytest.raises(IndexError): - z.set_basic_selection(Ellipsis, v, fields=fields) - with pytest.raises(IndexError): - z.set_orthogonal_selection([0, 2], v, fields=fields) - with pytest.raises(IndexError): - z.set_coordinate_selection([0, 2], v, fields=fields) - with pytest.raises(IndexError): - z.set_mask_selection([True, False, True], v, fields=fields) - - else: - if isinstance(fields, list) and len(fields) == 1: - # work around numpy does not support multi-field assignment even if there - # is only one field - key = fields[0] - elif isinstance(fields, list) and len(fields) == 0: - # work around numpy ambiguity about what is a field selection - key = Ellipsis - else: - key = fields - - # setup expectation - a[:] = ("", 0, 0) - z[:] = ("", 0, 0) - assert_array_equal(a, z[:]) - a[key] = v[key] - # total selection - z.set_basic_selection(Ellipsis, v[key], fields=fields) - assert_array_equal(a, z[:]) - - # basic selection with slice - a[:] = ("", 0, 0) - z[:] = ("", 0, 0) - a[key][0:2] = v[key][0:2] - z.set_basic_selection(slice(0, 2), v[key][0:2], fields=fields) - assert_array_equal(a, z[:]) - - # orthogonal selection - a[:] = ("", 0, 0) - z[:] = ("", 0, 0) - ix = [0, 2] - a[key][ix] = v[key][ix] - z.set_orthogonal_selection(ix, v[key][ix], fields=fields) - assert_array_equal(a, z[:]) - - # coordinate selection - a[:] = ("", 0, 0) - z[:] = ("", 0, 0) - ix = [0, 2] - a[key][ix] = v[key][ix] - z.set_coordinate_selection(ix, v[key][ix], fields=fields) - assert_array_equal(a, z[:]) - - # mask selection - a[:] = ("", 0, 0) - z[:] = ("", 0, 0) - ix = [True, False, True] - a[key][ix] = v[key][ix] - z.set_mask_selection(ix, v[key][ix], fields=fields) - assert_array_equal(a, z[:]) - - -@pytest.mark.parametrize( - "selection, arr, expected", - [ - ( - (slice(5, 8, 1), slice(2, 4, 1), slice(0, 100, 1)), - np.arange(2, 100_002).reshape((100, 10, 100)), - [ - (5200, 200, (slice(5, 6, 1), slice(2, 4, 1))), - (6200, 200, (slice(6, 7, 1), slice(2, 4, 1))), - (7200, 200, (slice(7, 8, 1), slice(2, 4, 1))), - ], - ), - ( - (slice(5, 8, 1), slice(2, 4, 1), slice(0, 5, 1)), - np.arange(2, 100_002).reshape((100, 10, 100)), - [ - (5200.0, 5.0, (slice(5, 6, 1), slice(2, 3, 1), slice(0, 5, 1))), - (5300.0, 5.0, (slice(5, 6, 1), slice(3, 4, 1), slice(0, 5, 1))), - (6200.0, 5.0, (slice(6, 7, 1), slice(2, 3, 1), slice(0, 5, 1))), - (6300.0, 5.0, (slice(6, 7, 1), slice(3, 4, 1), slice(0, 5, 1))), - (7200.0, 5.0, (slice(7, 8, 1), slice(2, 3, 1), slice(0, 5, 1))), - (7300.0, 5.0, (slice(7, 8, 1), slice(3, 4, 1), slice(0, 5, 1))), - ], - ), - ( - (slice(5, 8, 1), slice(2, 4, 1), slice(0, 5, 1)), - np.asfortranarray(np.arange(2, 100_002).reshape((100, 10, 100))), - [ - (5200.0, 5.0, (slice(5, 6, 1), slice(2, 3, 1), slice(0, 5, 1))), - (5300.0, 5.0, (slice(5, 6, 1), slice(3, 4, 1), slice(0, 5, 1))), - (6200.0, 5.0, (slice(6, 7, 1), slice(2, 3, 1), slice(0, 5, 1))), - (6300.0, 5.0, (slice(6, 7, 1), slice(3, 4, 1), slice(0, 5, 1))), - (7200.0, 5.0, (slice(7, 8, 1), slice(2, 3, 1), slice(0, 5, 1))), - (7300.0, 5.0, (slice(7, 8, 1), slice(3, 4, 1), slice(0, 5, 1))), - ], - ), - ( - (slice(5, 8, 1), slice(2, 4, 1)), - np.arange(2, 100_002).reshape((100, 10, 100)), - [ - (5200, 200, (slice(5, 6, 1), slice(2, 4, 1))), - (6200, 200, (slice(6, 7, 1), slice(2, 4, 1))), - (7200, 200, (slice(7, 8, 1), slice(2, 4, 1))), - ], - ), - ( - (slice(0, 10, 1),), - np.arange(0, 10).reshape((10)), - [(0, 10, (slice(0, 10, 1),))], - ), - ((0,), np.arange(0, 100).reshape((10, 10)), [(0, 10, (slice(0, 1, 1),))]), - ( - ( - 0, - 0, - ), - np.arange(0, 100).reshape((10, 10)), - [(0, 1, (slice(0, 1, 1), slice(0, 1, 1)))], - ), - ((0,), np.arange(0, 10).reshape((10)), [(0, 1, (slice(0, 1, 1),))]), - pytest.param( - (slice(5, 8, 1), slice(2, 4, 1), slice(0, 5, 1)), - np.arange(2, 100002).reshape((10, 1, 10000)), - None, - marks=[pytest.mark.xfail(reason="slice 2 is out of range")], - ), - pytest.param( - (slice(5, 8, 1), slice(2, 4, 1), slice(0, 5, 1)), - np.arange(2, 100_002).reshape((10, 10_000)), - None, - marks=[pytest.mark.xfail(reason="slice 2 is out of range")], - ), - ], -) -def test_PartialChunkIterator(selection, arr, expected): - PCI = PartialChunkIterator(selection, arr.shape) - results = list(PCI) - assert results == expected - - -def test_slice_selection_uints(): - arr = np.arange(24).reshape((4, 6)) - idx = np.uint64(3) - slice_sel = make_slice_selection((idx,)) - assert arr[tuple(slice_sel)].shape == (1, 6) - - -def test_numpy_int_indexing(): - a = np.arange(1050) - z = zarr.v2.create(shape=1050, chunks=100, dtype=a.dtype) - z[:] = a - assert a[42] == z[42] - assert a[np.int64(42)] == z[np.int64(42)] - - -@pytest.mark.parametrize( - "shape, chunks, ops", - [ - # 1D test cases - ((1070,), (50,), [("__getitem__", (slice(200, 400),))]), - ((1070,), (50,), [("__getitem__", (slice(200, 400, 100),))]), - ( - (1070,), - (50,), - [ - ("__getitem__", (slice(200, 400),)), - ("__setitem__", (slice(200, 400, 100),)), - ], - ), - # 2D test cases - ( - (40, 50), - (5, 8), - [ - ("__getitem__", (slice(6, 37, 13), (slice(4, 10)))), - ("__setitem__", (slice(None), (slice(None)))), - ], - ), - ], -) -def test_accessed_chunks(shape, chunks, ops): - # Test that only the required chunks are accessed during basic selection operations - # shape: array shape - # chunks: chunk size - # ops: list of tuples with (optype, tuple of slices) - # optype = "__getitem__" or "__setitem__", tuple length must match number of dims - import itertools - - # Use a counting dict as the backing store so we can track the items access - store = CountingDict() - z = zarr.v2.create(shape=shape, chunks=chunks, store=store) - - for ii, (optype, slices) in enumerate(ops): - # Resolve the slices into the accessed chunks for each dimension - chunks_per_dim = [] - for N, C, sl in zip(shape, chunks, slices): - chunk_ind = np.arange(N, dtype=int)[sl] // C - chunks_per_dim.append(np.unique(chunk_ind)) - - # Combine and generate the cartesian product to determine the chunks keys that - # will be accessed - chunks_accessed = [] - for comb in itertools.product(*chunks_per_dim): - chunks_accessed.append(".".join([str(ci) for ci in comb])) - - counts_before = store.counter.copy() - - # Perform the operation - if optype == "__getitem__": - z[slices] - else: - z[slices] = ii - - # Get the change in counts - delta_counts = store.counter - counts_before - - # Check that the access counts for the operation have increased by one for all - # the chunks we expect to be included - for ci in chunks_accessed: - assert delta_counts.pop((optype, ci)) == 1 - - # If the chunk was partially written to it will also have been read once. We - # don't determine if the chunk was actually partial here, just that the - # counts are consistent that this might have happened - if optype == "__setitem__": - assert ("__getitem__", ci) not in delta_counts or delta_counts.pop( - ("__getitem__", ci) - ) == 1 - # Check that no other chunks were accessed - assert len(delta_counts) == 0 diff --git a/tests/v2/test_info.py b/tests/v2/test_info.py deleted file mode 100644 index 9f68119295..0000000000 --- a/tests/v2/test_info.py +++ /dev/null @@ -1,66 +0,0 @@ -import numcodecs -import pytest - -import zarr.v2 -from zarr.v2.util import InfoReporter - - -@pytest.mark.parametrize("array_size", [10, 15000]) -def test_info(array_size): - # setup - g = zarr.v2.group(store=dict(), chunk_store=dict(), synchronizer=zarr.v2.ThreadSynchronizer()) - g.create_group("foo") - z = g.zeros("bar", shape=array_size, filters=[numcodecs.Adler32()]) - - # test group info - items = g.info_items() - keys = sorted([k for k, _ in items]) - expected_keys = sorted( - [ - "Type", - "Read-only", - "Synchronizer type", - "Store type", - "Chunk store type", - "No. members", - "No. arrays", - "No. groups", - "Arrays", - "Groups", - "Name", - ] - ) - assert expected_keys == keys - - # can also get a string representation of info via the info attribute - assert isinstance(g.info, InfoReporter) - assert "Type" in repr(g.info) - - # test array info - items = z.info_items() - keys = sorted([k for k, _ in items]) - expected_keys = sorted( - [ - "Type", - "Data type", - "Shape", - "Chunk shape", - "Order", - "Read-only", - "Filter [0]", - "Compressor", - "Synchronizer type", - "Store type", - "Chunk store type", - "No. bytes", - "No. bytes stored", - "Storage ratio", - "Chunks initialized", - "Name", - ] - ) - assert expected_keys == keys - - # can also get a string representation of info via the info attribute - assert isinstance(z.info, InfoReporter) - assert "Type" in repr(z.info) diff --git a/tests/v2/test_meta.py b/tests/v2/test_meta.py deleted file mode 100644 index b7c00ec64c..0000000000 --- a/tests/v2/test_meta.py +++ /dev/null @@ -1,527 +0,0 @@ -import base64 -import json - -import numpy as np -import pytest - -from zarr.v2.codecs import Blosc, Delta, Pickle, Zlib -from zarr.v2.errors import MetadataError -from zarr.v2.meta import ( - ZARR_FORMAT, - decode_array_metadata, - decode_dtype, - decode_group_metadata, - encode_array_metadata, - encode_dtype, - encode_fill_value, - decode_fill_value, -) -from zarr.v2.util import normalize_dtype, normalize_fill_value - - -def assert_json_equal(expect, actual): - if isinstance(actual, bytes): - actual = str(actual, "ascii") - ej = json.loads(expect) - aj = json.loads(actual) - assert ej == aj - - -def test_encode_decode_array_1(): - meta = dict( - shape=(100,), - chunks=(10,), - dtype=np.dtype(" CuPyCPUCompressor: - if compressor: - compressor = getattr(zarr.v2.codecs, compressor)() - return CuPyCPUCompressor(compressor) - - -def init_store(tmp_path, store_type) -> Optional[Store]: - if store_type is DirectoryStore: - return store_type(str(tmp_path / "store")) - if store_type is MemoryStore: - return MemoryStore() - return None - - -def ensure_module(module): - if isinstance(module, str): - return pytest.importorskip(module) - return module - - -param_module_and_compressor = [ - (MyArray, None), - ("cupy", init_compressor(None)), - ("cupy", init_compressor("Zlib")), - ("cupy", init_compressor("Blosc")), -] - - -@pytest.mark.parametrize("module, compressor", param_module_and_compressor) -@pytest.mark.parametrize("store_type", [None, DirectoryStore, MemoryStore, ZipStore]) -def test_array(tmp_path, module, compressor, store_type): - xp = ensure_module(module) - - store = init_store(tmp_path / "from_cupy_array", store_type) - a = xp.arange(100) - z = array(a, chunks=10, compressor=compressor, store=store, meta_array=xp.empty(())) - assert a.shape == z.shape - assert a.dtype == z.dtype - assert isinstance(a, type(z[:])) - assert isinstance(z.meta_array, type(xp.empty(()))) - xp.testing.assert_array_equal(a, z[:]) - - # with array-like - store = init_store(tmp_path / "from_list", store_type) - a = list(range(100)) - z = array(a, chunks=10, compressor=compressor, store=store, meta_array=xp.empty(())) - assert (100,) == z.shape - assert np.asarray(a).dtype == z.dtype - xp.testing.assert_array_equal(a, z[:]) - - # with another zarr array - store = init_store(tmp_path / "from_another_store", store_type) - z2 = array(z, compressor=compressor, store=store, meta_array=xp.empty(())) - assert z.shape == z2.shape - assert z.chunks == z2.chunks - assert z.dtype == z2.dtype - xp.testing.assert_array_equal(z[:], z2[:]) - - store = init_store(tmp_path / "open_array", store_type) - a = xp.arange(100) - z = open_array( - store, - shape=a.shape, - dtype=a.dtype, - chunks=10, - compressor=compressor, - meta_array=xp.empty(()), - ) - z[:] = a - assert a.shape == z.shape - assert a.dtype == z.dtype - assert isinstance(a, type(z[:])) - assert isinstance(z.meta_array, type(xp.empty(()))) - xp.testing.assert_array_equal(a, z[:]) - - -@pytest.mark.parametrize("module, compressor", param_module_and_compressor) -def test_empty(module, compressor): - xp = ensure_module(module) - z = empty( - 100, - chunks=10, - compressor=compressor, - meta_array=xp.empty(()), - ) - assert (100,) == z.shape - assert (10,) == z.chunks - - -@pytest.mark.parametrize("module, compressor", param_module_and_compressor) -def test_zeros(module, compressor): - xp = ensure_module(module) - z = zeros( - 100, - chunks=10, - compressor=compressor, - meta_array=xp.empty(()), - ) - assert (100,) == z.shape - assert (10,) == z.chunks - xp.testing.assert_array_equal(np.zeros(100), z[:]) - - -@pytest.mark.parametrize("module, compressor", param_module_and_compressor) -def test_ones(module, compressor): - xp = ensure_module(module) - z = ones( - 100, - chunks=10, - compressor=compressor, - meta_array=xp.empty(()), - ) - assert (100,) == z.shape - assert (10,) == z.chunks - xp.testing.assert_array_equal(np.ones(100), z[:]) - - -@pytest.mark.parametrize("module, compressor", param_module_and_compressor) -def test_full(module, compressor): - xp = ensure_module(module) - z = full( - 100, - chunks=10, - fill_value=42, - dtype="i4", - compressor=compressor, - meta_array=xp.empty(()), - ) - assert (100,) == z.shape - assert (10,) == z.chunks - xp.testing.assert_array_equal(np.full(100, fill_value=42, dtype="i4"), z[:]) - - # nan - z = full( - 100, - chunks=10, - fill_value=np.nan, - dtype="f8", - compressor=compressor, - meta_array=xp.empty(()), - ) - assert np.all(np.isnan(z[:])) - - -@pytest.mark.parametrize("group_create_function", [group, open_group]) -@pytest.mark.parametrize("module, compressor", param_module_and_compressor) -@pytest.mark.parametrize("store_type", [None, DirectoryStore, MemoryStore, ZipStore]) -def test_group(tmp_path, group_create_function, module, compressor, store_type): - xp = ensure_module(module) - store = init_store(tmp_path, store_type) - g = group_create_function(store, meta_array=xp.empty(())) - g.ones("data", shape=(10, 11), dtype=int, compressor=compressor) - a = g["data"] - assert a.shape == (10, 11) - assert a.dtype == int - assert isinstance(a, Array) - assert isinstance(a[:], type(xp.empty(()))) - assert (a[:] == 1).all() - assert isinstance(g.meta_array, type(xp.empty(()))) diff --git a/tests/v2/test_n5.py b/tests/v2/test_n5.py deleted file mode 100644 index 238e9b2c6e..0000000000 --- a/tests/v2/test_n5.py +++ /dev/null @@ -1,53 +0,0 @@ -import pytest - -from zarr.v2.n5 import N5ChunkWrapper, N5FSStore -from zarr.v2.creation import create -from zarr.v2.storage import atexit_rmtree -from numcodecs import GZip -import numpy as np -from typing import Tuple -import json -import atexit - -from .util import have_fsspec - - -def test_make_n5_chunk_wrapper(): - dtype = "uint8" - chunk_shape = (10,) - codec = GZip() - # ValueError when specifying both compressor and compressor_config - with pytest.raises(ValueError): - N5ChunkWrapper( - dtype, chunk_shape=chunk_shape, compressor_config=codec.get_config(), compressor=codec - ) - - wrapper_a = N5ChunkWrapper(dtype, chunk_shape=chunk_shape, compressor_config=codec.get_config()) - wrapper_b = N5ChunkWrapper(dtype, chunk_shape=chunk_shape, compressor=codec) - assert wrapper_a == wrapper_b - - -@pytest.mark.parametrize("chunk_shape", ((2,), (4, 4), (8, 8, 8))) -def test_partial_chunk_decode(chunk_shape: Tuple[int, ...]): - # Test that the N5Chunk wrapper can handle fractional chunks that - # may be generated by other N5 implementations - dtype = "uint8" - codec = GZip() - codec_wrapped = N5ChunkWrapper(dtype, chunk_shape=chunk_shape, compressor=codec) - subslices = tuple(slice(0, cs // 2) for cs in chunk_shape) - chunk = np.zeros(chunk_shape, dtype=dtype) - chunk[subslices] = 1 - subchunk = np.ascontiguousarray(chunk[subslices]) - assert np.array_equal(codec_wrapped.decode(codec_wrapped.encode(subchunk)), chunk) - - -@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") -def test_dtype_decode(): - path = "data/array.n5" - atexit_rmtree(path) - atexit.register(atexit_rmtree, path) - n5_store = N5FSStore(path) - create(100, store=n5_store) - dtype_n5 = json.loads(n5_store[".zarray"])["dtype"] - dtype_zarr = json.loads(create(100).store[".zarray"])["dtype"] - assert dtype_n5 == dtype_zarr diff --git a/tests/v2/test_storage.py b/tests/v2/test_storage.py deleted file mode 100644 index cce1e5cb3c..0000000000 --- a/tests/v2/test_storage.py +++ /dev/null @@ -1,2505 +0,0 @@ -import array -import atexit -import json -import os -import pathlib -import sys -import pickle -import shutil -import tempfile -from contextlib import contextmanager -from pickle import PicklingError -from zipfile import ZipFile - -import numpy as np -import pytest -from numpy.testing import assert_array_almost_equal, assert_array_equal - -from numcodecs.compat import ensure_bytes - -import zarr.v2 -from zarr.v2 import meta_v1 -from zarr.v2.codecs import BZ2, AsType, Blosc, Zlib -from zarr.v2.context import Context -from zarr.v2.convenience import consolidate_metadata -from zarr.v2.errors import ContainsArrayError, ContainsGroupError, MetadataError -from zarr.v2.hierarchy import group -from zarr.v2.meta import ZARR_FORMAT, decode_array_metadata -from zarr.v2.n5 import N5Store, N5FSStore, N5_FORMAT, n5_attrs_key -from zarr.v2.storage import ( - ABSStore, - ConsolidatedMetadataStore, - DBMStore, - DictStore, - DirectoryStore, - KVStore, - LMDBStore, - LRUStoreCache, - MemoryStore, - MongoDBStore, - NestedDirectoryStore, - RedisStore, - SQLiteStore, - Store, - TempStore, - ZipStore, - array_meta_key, - atexit_rmglob, - atexit_rmtree, - attrs_key, - default_compressor, - getsize, - group_meta_key, - init_array, - init_group, - migrate_1to2, - normalize_store_arg, -) -from zarr.v2.storage import FSStore, rename, listdir -from .util import CountingDict, have_fsspec, skip_test_env_var, abs_container, mktemp -from zarr.v2.util import ConstantMap, json_dumps - - -@contextmanager -def does_not_raise(): - yield - - -@pytest.fixture( - params=[ - (None, "."), - (".", "."), - ("/", "/"), - ] -) -def dimension_separator_fixture(request): - return request.param - - -def skip_if_nested_chunks(**kwargs): - if kwargs.get("dimension_separator") == "/": - pytest.skip("nested chunks are unsupported") - - -def test_kvstore_repr(): - repr(KVStore(dict())) - - -def test_ensure_store(): - class InvalidStore: - pass - - with pytest.raises(ValueError): - Store._ensure_store(InvalidStore()) - - # cannot initialize without a store - with pytest.raises(ValueError): - Store._ensure_store(None) - - -def test_capabilities(): - s = KVStore(dict()) - assert s.is_readable() - assert s.is_listable() - assert s.is_erasable() - assert s.is_writeable() - - -def test_getsize_non_implemented(): - assert getsize(object()) == -1 - - -def test_kvstore_eq(): - assert KVStore(dict()) != dict() - - -def test_coverage_rename(): - store = dict() - store["a"] = 1 - rename(store, "a", "b") - - -def test_deprecated_listdir_nosotre(): - store = dict() - with pytest.warns(UserWarning, match="has no `listdir`"): - listdir(store) - - -class StoreTests: - """Abstract store tests.""" - - version = 2 - root = "" - - def create_store(self, **kwargs): # pragma: no cover - # implement in sub-class - raise NotImplementedError - - def test_context_manager(self): - with self.create_store(): - pass - - def test_get_set_del_contains(self): - store = self.create_store() - - # test __contains__, __getitem__, __setitem__ - key = self.root + "foo" - assert key not in store - with pytest.raises(KeyError): - # noinspection PyStatementEffect - store[key] - store[key] = b"bar" - assert key in store - assert b"bar" == ensure_bytes(store[key]) - - # test __delitem__ (optional) - try: - del store[key] - except NotImplementedError: - pass - else: - assert key not in store - with pytest.raises(KeyError): - # noinspection PyStatementEffect - store[key] - with pytest.raises(KeyError): - # noinspection PyStatementEffect - del store[key] - - store.close() - - def test_set_invalid_content(self): - store = self.create_store() - - with pytest.raises(TypeError): - store[self.root + "baz"] = list(range(5)) - - store.close() - - def test_clear(self): - store = self.create_store() - store[self.root + "foo"] = b"bar" - store[self.root + "baz"] = b"qux" - assert len(store) == 2 - store.clear() - assert len(store) == 0 - assert self.root + "foo" not in store - assert self.root + "baz" not in store - - store.close() - - def test_pop(self): - store = self.create_store() - store[self.root + "foo"] = b"bar" - store[self.root + "baz"] = b"qux" - assert len(store) == 2 - v = store.pop(self.root + "foo") - assert ensure_bytes(v) == b"bar" - assert len(store) == 1 - v = store.pop(self.root + "baz") - assert ensure_bytes(v) == b"qux" - assert len(store) == 0 - with pytest.raises(KeyError): - store.pop(self.root + "xxx") - v = store.pop(self.root + "xxx", b"default") - assert v == b"default" - v = store.pop(self.root + "xxx", b"") - assert v == b"" - v = store.pop(self.root + "xxx", None) - assert v is None - - store.close() - - def test_popitem(self): - store = self.create_store() - store[self.root + "foo"] = b"bar" - k, v = store.popitem() - assert k == self.root + "foo" - assert ensure_bytes(v) == b"bar" - assert len(store) == 0 - with pytest.raises(KeyError): - store.popitem() - - store.close() - - def test_writeable_values(self): - store = self.create_store() - - # __setitem__ should accept any value that implements buffer interface - store[self.root + "foo1"] = b"bar" - store[self.root + "foo2"] = bytearray(b"bar") - store[self.root + "foo3"] = array.array("B", b"bar") - store[self.root + "foo4"] = np.frombuffer(b"bar", dtype="u1") - - store.close() - - def test_update(self): - store = self.create_store() - assert self.root + "foo" not in store - assert self.root + "baz" not in store - - if self.version == 2: - store.update(foo=b"bar", baz=b"quux") - else: - kv = {self.root + "foo": b"bar", self.root + "baz": b"quux"} - store.update(kv) - - assert b"bar" == ensure_bytes(store[self.root + "foo"]) - assert b"quux" == ensure_bytes(store[self.root + "baz"]) - - store.close() - - def test_iterators(self): - store = self.create_store() - - # test iterator methods on empty store - assert 0 == len(store) - assert set() == set(store) - assert set() == set(store.keys()) - assert set() == set(store.values()) - assert set() == set(store.items()) - - # setup some values - store[self.root + "a"] = b"aaa" - store[self.root + "b"] = b"bbb" - store[self.root + "c/d"] = b"ddd" - store[self.root + "c/e/f"] = b"fff" - - # test iterators on store with data - assert 4 == len(store) - expected = set(self.root + k for k in ["a", "b", "c/d", "c/e/f"]) - assert expected == set(store) - assert expected == set(store.keys()) - assert {b"aaa", b"bbb", b"ddd", b"fff"} == set(map(ensure_bytes, store.values())) - assert { - (self.root + "a", b"aaa"), - (self.root + "b", b"bbb"), - (self.root + "c/d", b"ddd"), - (self.root + "c/e/f", b"fff"), - } == set(map(lambda kv: (kv[0], ensure_bytes(kv[1])), store.items())) - - store.close() - - def test_pickle(self): - # setup store - store = self.create_store() - store[self.root + "foo"] = b"bar" - store[self.root + "baz"] = b"quux" - n = len(store) - keys = sorted(store.keys()) - - # round-trip through pickle - dump = pickle.dumps(store) - # some stores cannot be opened twice at the same time, need to close - # store before can round-trip through pickle - store.close() - # check can still pickle after close - assert dump == pickle.dumps(store) - store2 = pickle.loads(dump) - - # verify - assert n == len(store2) - assert keys == sorted(store2.keys()) - assert b"bar" == ensure_bytes(store2[self.root + "foo"]) - assert b"quux" == ensure_bytes(store2[self.root + "baz"]) - - store2.close() - - def test_getsize(self): - store = self.create_store() - if isinstance(store, dict) or hasattr(store, "getsize"): - assert 0 == getsize(store) - store["foo"] = b"x" - assert 1 == getsize(store) - assert 1 == getsize(store, "foo") - store["bar"] = b"yy" - assert 3 == getsize(store) - assert 2 == getsize(store, "bar") - store["baz"] = bytearray(b"zzz") - assert 6 == getsize(store) - assert 3 == getsize(store, "baz") - store["quux"] = array.array("B", b"zzzz") - assert 10 == getsize(store) - assert 4 == getsize(store, "quux") - store["spong"] = np.frombuffer(b"zzzzz", dtype="u1") - assert 15 == getsize(store) - assert 5 == getsize(store, "spong") - - store.close() - - # noinspection PyStatementEffect - def test_hierarchy(self): - # setup - store = self.create_store() - store[self.root + "a"] = b"aaa" - store[self.root + "b"] = b"bbb" - store[self.root + "c/d"] = b"ddd" - store[self.root + "c/e/f"] = b"fff" - store[self.root + "c/e/g"] = b"ggg" - - # check keys - assert self.root + "a" in store - assert self.root + "b" in store - assert self.root + "c/d" in store - assert self.root + "c/e/f" in store - assert self.root + "c/e/g" in store - assert self.root + "c" not in store - assert self.root + "c/" not in store - assert self.root + "c/e" not in store - assert self.root + "c/e/" not in store - assert self.root + "c/d/x" not in store - - # check __getitem__ - with pytest.raises(KeyError): - store[self.root + "c"] - with pytest.raises(KeyError): - store[self.root + "c/e"] - with pytest.raises(KeyError): - store[self.root + "c/d/x"] - - # test getsize (optional) - if hasattr(store, "getsize"): - # TODO: proper behavior of getsize? - # v3 returns size of all nested arrays, not just the - # size of the arrays in the current folder. - if self.version == 2: - assert 6 == store.getsize() - else: - assert 15 == store.getsize() - assert 3 == store.getsize("a") - assert 3 == store.getsize("b") - if self.version == 2: - assert 3 == store.getsize("c") - else: - assert 9 == store.getsize("c") - assert 3 == store.getsize("c/d") - assert 6 == store.getsize("c/e") - assert 3 == store.getsize("c/e/f") - assert 3 == store.getsize("c/e/g") - # non-existent paths - assert 0 == store.getsize("x") - assert 0 == store.getsize("a/x") - assert 0 == store.getsize("c/x") - assert 0 == store.getsize("c/x/y") - assert 0 == store.getsize("c/d/y") - assert 0 == store.getsize("c/d/y/z") - - # access item via full path - assert 3 == store.getsize(self.root + "a") - - # test listdir (optional) - if hasattr(store, "listdir"): - assert {"a", "b", "c"} == set(store.listdir(self.root)) - assert {"d", "e"} == set(store.listdir(self.root + "c")) - assert {"f", "g"} == set(store.listdir(self.root + "c/e")) - # no exception raised if path does not exist or is leaf - assert [] == store.listdir(self.root + "x") - assert [] == store.listdir(self.root + "a/x") - assert [] == store.listdir(self.root + "c/x") - assert [] == store.listdir(self.root + "c/x/y") - assert [] == store.listdir(self.root + "c/d/y") - assert [] == store.listdir(self.root + "c/d/y/z") - # the following is listdir(filepath), for which fsspec gives [filepath] - # as posix would, but an empty list was previously assumed - # assert [] == store.listdir(self.root + "c/e/f") - - # test rename (optional) - if store.is_erasable(): - store.rename("c/e", "c/e2") - assert self.root + "c/d" in store - assert self.root + "c/e" not in store - assert self.root + "c/e/f" not in store - assert self.root + "c/e/g" not in store - assert self.root + "c/e2" not in store - assert self.root + "c/e2/f" in store - assert self.root + "c/e2/g" in store - store.rename("c/e2", "c/e") - assert self.root + "c/d" in store - assert self.root + "c/e2" not in store - assert self.root + "c/e2/f" not in store - assert self.root + "c/e2/g" not in store - assert self.root + "c/e" not in store - assert self.root + "c/e/f" in store - assert self.root + "c/e/g" in store - store.rename("c", "c1/c2/c3") - assert self.root + "a" in store - assert self.root + "c" not in store - assert self.root + "c/d" not in store - assert self.root + "c/e" not in store - assert self.root + "c/e/f" not in store - assert self.root + "c/e/g" not in store - assert self.root + "c1" not in store - assert self.root + "c1/c2" not in store - assert self.root + "c1/c2/c3" not in store - assert self.root + "c1/c2/c3/d" in store - assert self.root + "c1/c2/c3/e" not in store - assert self.root + "c1/c2/c3/e/f" in store - assert self.root + "c1/c2/c3/e/g" in store - store.rename("c1/c2/c3", "c") - assert self.root + "c" not in store - assert self.root + "c/d" in store - assert self.root + "c/e" not in store - assert self.root + "c/e/f" in store - assert self.root + "c/e/g" in store - assert self.root + "c1" not in store - assert self.root + "c1/c2" not in store - assert self.root + "c1/c2/c3" not in store - assert self.root + "c1/c2/c3/d" not in store - assert self.root + "c1/c2/c3/e" not in store - assert self.root + "c1/c2/c3/e/f" not in store - assert self.root + "c1/c2/c3/e/g" not in store - - # test rmdir (optional) - store.rmdir("c/e") - assert self.root + "c/d" in store - assert self.root + "c/e/f" not in store - assert self.root + "c/e/g" not in store - store.rmdir("c") - assert self.root + "c/d" not in store - store.rmdir() - assert self.root + "a" not in store - assert self.root + "b" not in store - store[self.root + "a"] = b"aaa" - store[self.root + "c/d"] = b"ddd" - store[self.root + "c/e/f"] = b"fff" - # no exceptions raised if path does not exist or is leaf - store.rmdir("x") - store.rmdir("a/x") - store.rmdir("c/x") - store.rmdir("c/x/y") - store.rmdir("c/d/y") - store.rmdir("c/d/y/z") - store.rmdir("c/e/f") - assert self.root + "a" in store - assert self.root + "c/d" in store - assert self.root + "c/e/f" in store - - store.close() - - def test_init_array(self, dimension_separator_fixture): - pass_dim_sep, want_dim_sep = dimension_separator_fixture - - store = self.create_store(dimension_separator=pass_dim_sep) - init_array(store, shape=1000, chunks=100) - - # check metadata - assert array_meta_key in store - meta = store._metadata_class.decode_array_metadata(store[array_meta_key]) - assert ZARR_FORMAT == meta["zarr_format"] - assert (1000,) == meta["shape"] - assert (100,) == meta["chunks"] - assert np.dtype(None) == meta["dtype"] - assert default_compressor.get_config() == meta["compressor"] - assert meta["fill_value"] is None - # Missing MUST be assumed to be "." - assert meta.get("dimension_separator", ".") is want_dim_sep - - store.close() - - def test_init_array_overwrite(self): - self._test_init_array_overwrite("F") - - def test_init_array_overwrite_path(self): - self._test_init_array_overwrite_path("F") - - def test_init_array_overwrite_chunk_store(self): - self._test_init_array_overwrite_chunk_store("F") - - def test_init_group_overwrite(self): - self._test_init_group_overwrite("F") - - def test_init_group_overwrite_path(self): - self._test_init_group_overwrite_path("F") - - def test_init_group_overwrite_chunk_store(self): - self._test_init_group_overwrite_chunk_store("F") - - def _test_init_array_overwrite(self, order): - # setup - store = self.create_store() - path = None - mkey = array_meta_key - meta = dict( - shape=(2000,), - chunks=(200,), - dtype=np.dtype("u1"), - compressor=Zlib(1).get_config(), - fill_value=0, - order=order, - filters=None, - ) - - store[mkey] = store._metadata_class.encode_array_metadata(meta) - - # don't overwrite (default) - with pytest.raises(ContainsArrayError): - init_array(store, shape=1000, chunks=100, path=path) - - # do overwrite - try: - init_array(store, shape=1000, chunks=100, dtype="i4", overwrite=True, path=path) - except NotImplementedError: - pass - else: - assert mkey in store - meta = store._metadata_class.decode_array_metadata(store[mkey]) - if self.version == 2: - assert ZARR_FORMAT == meta["zarr_format"] - assert (100,) == meta["chunks"] - assert np.dtype("i4") == meta["dtype"] - else: - assert (100,) == meta["chunk_grid"]["chunk_shape"] - assert np.dtype("i4") == meta["data_type"] - assert (1000,) == meta["shape"] - - store.close() - - def test_init_array_path(self): - path = "foo/bar" - store = self.create_store() - init_array(store, shape=1000, chunks=100, path=path) - - # check metadata - mkey = path + "/" + array_meta_key - assert mkey in store - meta = store._metadata_class.decode_array_metadata(store[mkey]) - assert ZARR_FORMAT == meta["zarr_format"] - assert (100,) == meta["chunks"] - assert np.dtype(None) == meta["dtype"] - assert default_compressor.get_config() == meta["compressor"] - assert (1000,) == meta["shape"] - assert meta["fill_value"] is None - - store.close() - - def _test_init_array_overwrite_path(self, order): - # setup - path = "foo/bar" - store = self.create_store() - mkey = path + "/" + array_meta_key - meta = dict( - shape=(2000,), - chunks=(200,), - dtype=np.dtype("u1"), - compressor=Zlib(1).get_config(), - fill_value=0, - order=order, - filters=None, - ) - store[mkey] = store._metadata_class.encode_array_metadata(meta) - - # don't overwrite - with pytest.raises(ContainsArrayError): - init_array(store, shape=1000, chunks=100, path=path) - - # do overwrite - try: - init_array(store, shape=1000, chunks=100, dtype="i4", path=path, overwrite=True) - except NotImplementedError: - pass - else: - if self.version == 2: - assert group_meta_key in store - assert array_meta_key not in store - assert mkey in store - # should have been overwritten - meta = store._metadata_class.decode_array_metadata(store[mkey]) - if self.version == 2: - assert ZARR_FORMAT == meta["zarr_format"] - assert (100,) == meta["chunks"] - assert np.dtype("i4") == meta["dtype"] - else: - assert (100,) == meta["chunk_grid"]["chunk_shape"] - assert np.dtype("i4") == meta["data_type"] - assert (1000,) == meta["shape"] - - store.close() - - def test_init_array_overwrite_group(self): - # setup - path = "foo/bar" - store = self.create_store() - array_key = path + "/" + array_meta_key - group_key = path + "/" + group_meta_key - store[group_key] = store._metadata_class.encode_group_metadata() - - # don't overwrite - with pytest.raises(ContainsGroupError): - init_array(store, shape=1000, chunks=100, path=path) - - # do overwrite - try: - init_array(store, shape=1000, chunks=100, dtype="i4", path=path, overwrite=True) - except NotImplementedError: - pass - else: - assert group_key not in store - assert array_key in store - meta = store._metadata_class.decode_array_metadata(store[array_key]) - if self.version == 2: - assert ZARR_FORMAT == meta["zarr_format"] - assert (100,) == meta["chunks"] - assert np.dtype("i4") == meta["dtype"] - else: - assert (100,) == meta["chunk_grid"]["chunk_shape"] - assert np.dtype("i4") == meta["data_type"] - assert (1000,) == meta["shape"] - - store.close() - - def _test_init_array_overwrite_chunk_store(self, order): - # setup - store = self.create_store() - chunk_store = self.create_store() - - path = None - data_path = "" - mkey = array_meta_key - meta = dict( - shape=(2000,), - chunks=(200,), - dtype=np.dtype("u1"), - compressor=None, - fill_value=0, - filters=None, - order=order, - ) - - store[mkey] = store._metadata_class.encode_array_metadata(meta) - - chunk_store[data_path + "0"] = b"aaa" - chunk_store[data_path + "1"] = b"bbb" - - # don't overwrite (default) - with pytest.raises(ContainsArrayError): - init_array(store, path=path, shape=1000, chunks=100, chunk_store=chunk_store) - - # do overwrite - try: - init_array( - store, - path=path, - shape=1000, - chunks=100, - dtype="i4", - overwrite=True, - chunk_store=chunk_store, - ) - except NotImplementedError: - pass - else: - assert mkey in store - meta = store._metadata_class.decode_array_metadata(store[mkey]) - if self.version == 2: - assert ZARR_FORMAT == meta["zarr_format"] - assert (100,) == meta["chunks"] - assert np.dtype("i4") == meta["dtype"] - else: - assert (100,) == meta["chunk_grid"]["chunk_shape"] - assert np.dtype("i4") == meta["data_type"] - assert (1000,) == meta["shape"] - assert data_path + "0" not in chunk_store - assert data_path + "1" not in chunk_store - - store.close() - chunk_store.close() - - def test_init_array_compat(self): - store = self.create_store() - path = None - mkey = array_meta_key - init_array(store, path=path, shape=1000, chunks=100, compressor="none") - meta = store._metadata_class.decode_array_metadata(store[mkey]) - if self.version == 2: - assert meta["compressor"] is None - else: - assert "compressor" not in meta - store.close() - - def test_init_group(self): - store = self.create_store() - path = None - mkey = group_meta_key - init_group(store, path=path) - - # check metadata - assert mkey in store - meta = store._metadata_class.decode_group_metadata(store[mkey]) - if self.version == 2: - assert ZARR_FORMAT == meta["zarr_format"] - else: - assert meta == {"attributes": {}} - - store.close() - - def _test_init_group_overwrite(self, order): - # setup - store = self.create_store() - store[array_meta_key] = store._metadata_class.encode_array_metadata( - dict( - shape=(2000,), - chunks=(200,), - dtype=np.dtype("u1"), - compressor=None, - fill_value=0, - order=order, - filters=None, - ) - ) - - # don't overwrite array (default) - with pytest.raises(ContainsArrayError): - init_group(store) - - # do overwrite - try: - init_group(store, overwrite=True) - except NotImplementedError: - pass - else: - assert array_meta_key not in store - assert group_meta_key in store - meta = store._metadata_class.decode_group_metadata(store[group_meta_key]) - assert ZARR_FORMAT == meta["zarr_format"] - - # don't overwrite group - with pytest.raises(ValueError): - init_group(store) - - store.close() - - def _test_init_group_overwrite_path(self, order): - # setup - path = "foo/bar" - store = self.create_store() - meta = dict( - shape=(2000,), - chunks=(200,), - dtype=np.dtype("u1"), - compressor=None, - fill_value=0, - order=order, - filters=None, - ) - array_key = path + "/" + array_meta_key - group_key = path + "/" + group_meta_key - store[array_key] = store._metadata_class.encode_array_metadata(meta) - - # don't overwrite - with pytest.raises(ValueError): - init_group(store, path=path) - - # do overwrite - try: - init_group(store, overwrite=True, path=path) - except NotImplementedError: - pass - else: - if self.version == 2: - assert array_meta_key not in store - assert group_meta_key in store - assert array_key not in store - assert group_key in store - # should have been overwritten - meta = store._metadata_class.decode_group_metadata(store[group_key]) - if self.version == 2: - assert ZARR_FORMAT == meta["zarr_format"] - else: - assert meta == {"attributes": {}} - - store.close() - - def _test_init_group_overwrite_chunk_store(self, order): - # setup - store = self.create_store() - chunk_store = self.create_store() - store[array_meta_key] = store._metadata_class.encode_array_metadata( - dict( - shape=(2000,), - chunks=(200,), - dtype=np.dtype("u1"), - compressor=None, - fill_value=0, - filters=None, - order=order, - ) - ) - chunk_store["foo"] = b"bar" - chunk_store["baz"] = b"quux" - - # don't overwrite array (default) - with pytest.raises(ValueError): - init_group(store, chunk_store=chunk_store) - - # do overwrite - try: - init_group(store, overwrite=True, chunk_store=chunk_store) - except NotImplementedError: - pass - else: - assert array_meta_key not in store - assert group_meta_key in store - meta = store._metadata_class.decode_group_metadata(store[group_meta_key]) - assert ZARR_FORMAT == meta["zarr_format"] - assert "foo" not in chunk_store - assert "baz" not in chunk_store - - # don't overwrite group - with pytest.raises(ValueError): - init_group(store) - - store.close() - chunk_store.close() - - -class TestMappingStore(StoreTests): - def create_store(self, **kwargs): - skip_if_nested_chunks(**kwargs) - return KVStore(dict()) - - def test_set_invalid_content(self): - # Generic mappings support non-buffer types - pass - - -def setdel_hierarchy_checks(store, root=""): - # these tests are for stores that are aware of hierarchy levels; this - # behaviour is not strictly required by Zarr but these tests are included - # to define behaviour of MemoryStore and DirectoryStore classes - - # check __setitem__ and __delitem__ blocked by leaf - - store[root + "a/b"] = b"aaa" - with pytest.raises(KeyError): - store[root + "a/b/c"] = b"xxx" - with pytest.raises(KeyError): - del store[root + "a/b/c"] - - store[root + "d"] = b"ddd" - with pytest.raises(KeyError): - store[root + "d/e/f"] = b"xxx" - with pytest.raises(KeyError): - del store[root + "d/e/f"] - - # test __setitem__ overwrite level - store[root + "x/y/z"] = b"xxx" - store[root + "x/y"] = b"yyy" - assert b"yyy" == ensure_bytes(store[root + "x/y"]) - assert root + "x/y/z" not in store - store[root + "x"] = b"zzz" - assert b"zzz" == ensure_bytes(store[root + "x"]) - assert root + "x/y" not in store - - # test __delitem__ overwrite level - store[root + "r/s/t"] = b"xxx" - del store[root + "r/s"] - assert root + "r/s/t" not in store - store[root + "r/s"] = b"xxx" - del store[root + "r"] - assert root + "r/s" not in store - - -class TestMemoryStore(StoreTests): - def create_store(self, **kwargs): - skip_if_nested_chunks(**kwargs) - return MemoryStore(**kwargs) - - def test_store_contains_bytes(self): - store = self.create_store() - store[self.root + "foo"] = np.array([97, 98, 99, 100, 101], dtype=np.uint8) - assert store[self.root + "foo"] == b"abcde" - - def test_setdel(self): - store = self.create_store() - setdel_hierarchy_checks(store, self.root) - - -class TestDictStore(StoreTests): - def create_store(self, **kwargs): - skip_if_nested_chunks(**kwargs) - - with pytest.warns(DeprecationWarning): - return DictStore(**kwargs) - - def test_deprecated(self): - store = self.create_store() - assert isinstance(store, MemoryStore) - - def test_pickle(self): - with pytest.warns(DeprecationWarning): - # pickle.load() will also trigger deprecation warning - super().test_pickle() - - -class TestDirectoryStore(StoreTests): - def create_store(self, normalize_keys=False, dimension_separator=".", **kwargs): - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - store = DirectoryStore( - path, normalize_keys=normalize_keys, dimension_separator=dimension_separator, **kwargs - ) - return store - - def test_filesystem_path(self): - # test behaviour with path that does not exist - path = "data/store" - if os.path.exists(path): - shutil.rmtree(path) - store = DirectoryStore(path) - # should only be created on demand - assert not os.path.exists(path) - store["foo"] = b"bar" - assert os.path.isdir(path) - - # check correct permissions - # regression test for https://github.com/zarr-developers/zarr-python/issues/325 - stat = os.stat(path) - mode = stat.st_mode & 0o666 - umask = os.umask(0) - os.umask(umask) - assert mode == (0o666 & ~umask) - - # test behaviour with file path - with tempfile.NamedTemporaryFile() as f: - with pytest.raises(ValueError): - DirectoryStore(f.name) - - def test_init_pathlib(self): - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - DirectoryStore(pathlib.Path(path)) - - def test_pickle_ext(self): - store = self.create_store() - store2 = pickle.loads(pickle.dumps(store)) - - # check path is preserved - assert store.path == store2.path - - # check point to same underlying directory - assert self.root + "xxx" not in store - store2[self.root + "xxx"] = b"yyy" - assert b"yyy" == ensure_bytes(store[self.root + "xxx"]) - - def test_setdel(self): - store = self.create_store() - setdel_hierarchy_checks(store, self.root) - - def test_normalize_keys(self): - store = self.create_store(normalize_keys=True) - store[self.root + "FOO"] = b"bar" - assert self.root + "FOO" in store - assert self.root + "foo" in store - - def test_listing_keys_slash(self): - def mock_walker_slash(_path): - yield from [ - # trailing slash in first key - ("root_with_slash/", ["d1", "g1"], [".zgroup"]), - ("root_with_slash/d1", [], [".zarray"]), - ("root_with_slash/g1", [], [".zgroup"]), - ] - - res = set(DirectoryStore._keys_fast("root_with_slash/", walker=mock_walker_slash)) - assert res == {".zgroup", "g1/.zgroup", "d1/.zarray"} - - def test_listing_keys_no_slash(self): - def mock_walker_no_slash(_path): - yield from [ - # no trailing slash in first key - ("root_with_no_slash", ["d1", "g1"], [".zgroup"]), - ("root_with_no_slash/d1", [], [".zarray"]), - ("root_with_no_slash/g1", [], [".zgroup"]), - ] - - res = set(DirectoryStore._keys_fast("root_with_no_slash", mock_walker_no_slash)) - assert res == {".zgroup", "g1/.zgroup", "d1/.zarray"} - - -@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") -class TestFSStore(StoreTests): - def create_store(self, normalize_keys=False, dimension_separator=".", path=None, **kwargs): - if path is None: - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - - store = FSStore( - path, normalize_keys=normalize_keys, dimension_separator=dimension_separator, **kwargs - ) - return store - - def test_init_array(self): - store = self.create_store() - init_array(store, shape=1000, chunks=100) - - # check metadata - assert array_meta_key in store - meta = store._metadata_class.decode_array_metadata(store[array_meta_key]) - assert ZARR_FORMAT == meta["zarr_format"] - assert (1000,) == meta["shape"] - assert (100,) == meta["chunks"] - assert np.dtype(None) == meta["dtype"] - assert meta["dimension_separator"] == "." - - def test_dimension_separator(self): - for x in (".", "/"): - store = self.create_store(dimension_separator=x) - norm = store._normalize_key - assert ".zarray" == norm(".zarray") - assert ".zarray" == norm("/.zarray") - assert ".zgroup" == norm("/.zgroup") - assert "group/.zarray" == norm("group/.zarray") - assert "group/.zgroup" == norm("group/.zgroup") - assert "group/.zarray" == norm("/group/.zarray") - assert "group/.zgroup" == norm("/group/.zgroup") - - def test_complex(self): - path1 = tempfile.mkdtemp() - path2 = tempfile.mkdtemp() - store = self.create_store( - path="simplecache::file://" + path1, - simplecache={"same_names": True, "cache_storage": path2}, - ) - assert not store - assert not os.listdir(path1) - assert not os.listdir(path2) - store[self.root + "foo"] = b"hello" - assert "foo" in os.listdir(str(path1) + "/" + self.root) - assert self.root + "foo" in store - assert "foo" in os.listdir(str(path2)) - assert store[self.root + "foo"] == b"hello" - - def test_deep_ndim(self): - store = self.create_store() - path = None if self.version == 2 else "group1" - foo = zarr.v2.open_group(store=store, path=path) - bar = foo.create_group("bar") - baz = bar.create_dataset("baz", shape=(4, 4, 4), chunks=(2, 2, 2), dtype="i8") - baz[:] = 1 - if self.version == 2: - assert set(store.listdir()) == {".zgroup", "bar"} - else: - assert set(store.listdir()) == {"data", "meta", "zarr.v2.json"} - assert set(store.listdir("meta/root/" + path)) == {"bar", "bar.group.json"} - assert set(store.listdir("data/root/" + path)) == {"bar"} - assert foo["bar"]["baz"][(0, 0, 0)] == 1 - - def test_not_fsspec(self): - path = tempfile.mkdtemp() - with pytest.raises(ValueError, match="storage_options"): - zarr.v2.open_array(path, mode="w", storage_options={"some": "kwargs"}) - with pytest.raises(ValueError, match="storage_options"): - zarr.v2.open_group(path, mode="w", storage_options={"some": "kwargs"}) - zarr.v2.open_array("file://" + path, mode="w", shape=(1,), dtype="f8") - - def test_create(self): - path1 = tempfile.mkdtemp() - path2 = tempfile.mkdtemp() - g = zarr.v2.open_group("file://" + path1, mode="w", storage_options={"auto_mkdir": True}) - a = g.create_dataset("data", shape=(8,)) - a[:4] = [0, 1, 2, 3] - assert "data" in os.listdir(path1) - assert ".zgroup" in os.listdir(path1) - - # consolidated metadata (GH#915) - consolidate_metadata("file://" + path1) - assert ".zmetadata" in os.listdir(path1) - - g = zarr.v2.open_group( - "simplecache::file://" + path1, - mode="r", - storage_options={"cache_storage": path2, "same_names": True}, - ) - assert g.data[:].tolist() == [0, 1, 2, 3, 0, 0, 0, 0] - with pytest.raises(PermissionError): - g.data[:] = 1 - - @pytest.mark.parametrize("mode,allowed", [("r", False), ("r+", True)]) - def test_modify_consolidated(self, mode, allowed): - url = "file://" + tempfile.mkdtemp() - - # create - root = zarr.v2.open_group(url, mode="w") - root.zeros("baz", shape=(10000, 10000), chunks=(1000, 1000), dtype="i4") - zarr.v2.consolidate_metadata(url) - - # reopen and modify - root = zarr.v2.open_consolidated(url, mode=mode) - if allowed: - root["baz"][0, 0] = 7 - - root = zarr.v2.open_consolidated(url, mode="r") - assert root["baz"][0, 0] == 7 - else: - with pytest.raises(zarr.v2.errors.ReadOnlyError): - root["baz"][0, 0] = 7 - - @pytest.mark.parametrize("mode", ["r", "r+"]) - def test_modify_consolidated_metadata_raises(self, mode): - url = "file://" + tempfile.mkdtemp() - - # create - root = zarr.v2.open_group(url, mode="w") - root.zeros("baz", shape=(10000, 10000), chunks=(1000, 1000), dtype="i4") - zarr.v2.consolidate_metadata(url) - - # reopen and modify - root = zarr.v2.open_consolidated(url, mode=mode) - with pytest.raises(zarr.v2.errors.ReadOnlyError): - root["baz"].resize(100, 100) - - def test_read_only(self): - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - store = self.create_store(path=path) - store[self.root + "foo"] = b"bar" - - store = self.create_store(path=path, mode="r") - - with pytest.raises(PermissionError): - store[self.root + "foo"] = b"hex" - - with pytest.raises(PermissionError): - del store[self.root + "foo"] - - with pytest.raises(PermissionError): - store.delitems([self.root + "foo"]) - - with pytest.raises(PermissionError): - store.setitems({self.root + "foo": b"baz"}) - - with pytest.raises(PermissionError): - store.clear() - - with pytest.raises(PermissionError): - store.rmdir(self.root + "anydir") - - assert store[self.root + "foo"] == b"bar" - - def test_eq(self): - store1 = self.create_store(path="anypath") - store2 = self.create_store(path="anypath") - assert store1 == store2 - - @pytest.mark.usefixtures("s3") - def test_s3(self): - g = zarr.v2.open_group("s3://test/out.zarr", mode="w", storage_options=self.s3so) - a = g.create_dataset("data", shape=(8,)) - a[:4] = [0, 1, 2, 3] - - g = zarr.v2.open_group("s3://test/out.zarr", mode="r", storage_options=self.s3so) - - assert g.data[:].tolist() == [0, 1, 2, 3, 0, 0, 0, 0] - - # test via convenience - g = zarr.v2.open("s3://test/out.zarr", mode="r", storage_options=self.s3so) - assert g.data[:].tolist() == [0, 1, 2, 3, 0, 0, 0, 0] - - @pytest.mark.usefixtures("s3") - def test_s3_complex(self): - g = zarr.v2.open_group("s3://test/out.zarr", mode="w", storage_options=self.s3so) - expected = np.empty((8, 8, 8), dtype="int64") - expected[:] = -1 - a = g.create_dataset( - "data", shape=(8, 8, 8), fill_value=-1, chunks=(1, 1, 1), overwrite=True - ) - expected[0] = 0 - expected[3] = 3 - expected[6, 6, 6] = 6 - a[6, 6, 6] = 6 - a[:4] = expected[:4] - - b = g.create_dataset( - "data_f", - shape=(8,), - chunks=(1,), - dtype=[("foo", "S3"), ("bar", "i4")], - fill_value=(b"b", 1), - ) - b[:4] = (b"aaa", 2) - g2 = zarr.v2.open_group("s3://test/out.zarr", mode="r", storage_options=self.s3so) - - assert (g2.data[:] == expected).all() - a.chunk_store.fs.invalidate_cache("test/out.zarr/data") - a[:] = 5 - assert (a[:] == 5).all() - - assert g2.data_f["foo"].tolist() == [b"aaa"] * 4 + [b"b"] * 4 - with pytest.raises(PermissionError): - g2.data[:] = 5 - - with pytest.raises(PermissionError): - g2.store.setitems({}) - - with pytest.raises(PermissionError): - # even though overwrite=True, store is read-only, so fails - g2.create_dataset( - "data", shape=(8, 8, 8), fill_value=-1, chunks=(1, 1, 1), overwrite=True - ) - - a = g.create_dataset( - "data", shape=(8, 8, 8), fill_value=-1, chunks=(1, 1, 1), overwrite=True - ) - assert (a[:] == -np.ones((8, 8, 8))).all() - - -@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") -class TestFSStoreWithKeySeparator(StoreTests): - def create_store(self, normalize_keys=False, key_separator=".", **kwargs): - # Since the user is passing key_separator, that will take priority. - skip_if_nested_chunks(**kwargs) - - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - return FSStore(path, normalize_keys=normalize_keys, key_separator=key_separator) - - -@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") -class TestFSStoreFromFilesystem(StoreTests): - def create_store(self, normalize_keys=False, dimension_separator=".", path=None, **kwargs): - import fsspec - - fs = fsspec.filesystem("file") - - if path is None: - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - - with pytest.raises(ValueError): - # can't specify storage_options when passing an - # existing fs object - _ = FSStore(path, fs=fs, auto_mkdir=True) - - store = FSStore( - path, - normalize_keys=normalize_keys, - dimension_separator=dimension_separator, - fs=fs, - **kwargs, - ) - - return store - - -@pytest.fixture() -def s3(request): - # writable local S3 system - pytest.skip("old v3 tests are disabled", allow_module_level=True) - - import shlex - import subprocess - import time - - if "BOTO_CONFIG" not in os.environ: # pragma: no cover - os.environ["BOTO_CONFIG"] = "/dev/null" - if "AWS_ACCESS_KEY_ID" not in os.environ: # pragma: no cover - os.environ["AWS_ACCESS_KEY_ID"] = "foo" - if "AWS_SECRET_ACCESS_KEY" not in os.environ: # pragma: no cover - os.environ["AWS_SECRET_ACCESS_KEY"] = "bar" - requests = pytest.importorskip("requests") - s3fs = pytest.importorskip("s3fs") - pytest.importorskip("moto") - - port = 5556 - endpoint_uri = "http://127.0.0.1:%d/" % port - proc = subprocess.Popen( - shlex.split("moto_server s3 -p %d" % port), - stderr=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, - ) - - timeout = 5 - while timeout > 0: - try: - r = requests.get(endpoint_uri) - if r.ok: - break - except Exception: # pragma: no cover - pass - timeout -= 0.1 # pragma: no cover - time.sleep(0.1) # pragma: no cover - s3so = dict(client_kwargs={"endpoint_url": endpoint_uri}, use_listings_cache=False) - s3fs.S3FileSystem.clear_instance_cache() - s3 = s3fs.S3FileSystem(anon=False, **s3so) - s3.mkdir("test") - request.cls.s3so = s3so - yield - proc.terminate() - proc.wait() - - -class TestNestedDirectoryStore(TestDirectoryStore): - def create_store(self, normalize_keys=False, **kwargs): - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - store = NestedDirectoryStore(path, normalize_keys=normalize_keys, **kwargs) - return store - - def test_init_array(self): - store = self.create_store() - assert store._dimension_separator == "/" - init_array(store, shape=1000, chunks=100) - - # check metadata - assert array_meta_key in store - meta = store._metadata_class.decode_array_metadata(store[array_meta_key]) - assert ZARR_FORMAT == meta["zarr_format"] - assert (1000,) == meta["shape"] - assert (100,) == meta["chunks"] - assert np.dtype(None) == meta["dtype"] - assert meta["dimension_separator"] == "/" - - def test_chunk_nesting(self): - store = self.create_store() - # any path where last segment looks like a chunk key gets special handling - store[self.root + "0.0"] = b"xxx" - assert b"xxx" == store[self.root + "0.0"] - # assert b'xxx' == store['0/0'] - store[self.root + "foo/10.20.30"] = b"yyy" - assert b"yyy" == store[self.root + "foo/10.20.30"] - # assert b'yyy' == store['foo/10/20/30'] - store[self.root + "42"] = b"zzz" - assert b"zzz" == store[self.root + "42"] - - def test_listdir(self): - store = self.create_store() - z = zarr.v2.zeros((10, 10), chunks=(5, 5), store=store) - z[:] = 1 # write to all chunks - for k in store.listdir(): - assert store.get(k) is not None - - -class TestNestedDirectoryStoreNone: - def test_value_error(self): - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - store = NestedDirectoryStore(path, normalize_keys=True, dimension_separator=None) - assert store._dimension_separator == "/" - - -class TestNestedDirectoryStoreWithWrongValue: - def test_value_error(self): - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - with pytest.raises(ValueError): - NestedDirectoryStore(path, normalize_keys=True, dimension_separator=".") - - -class TestN5Store(TestNestedDirectoryStore): - def create_store(self, normalize_keys=False): - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - store = N5Store(path, normalize_keys=normalize_keys) - return store - - def test_equal(self): - store_a = self.create_store() - store_b = N5Store(store_a.path) - assert store_a == store_b - - @pytest.mark.parametrize("zarr_meta_key", [".zarray", ".zattrs", ".zgroup"]) - def test_del_zarr_meta_key(self, zarr_meta_key): - store = self.create_store() - store[n5_attrs_key] = json_dumps({"foo": "bar"}) - del store[zarr_meta_key] - assert n5_attrs_key not in store - - def test_chunk_nesting(self): - store = self.create_store() - store["0.0"] = b"xxx" - assert "0.0" in store - assert b"xxx" == store["0.0"] - # assert b'xxx' == store['0/0'] - store["foo/10.20.30"] = b"yyy" - assert "foo/10.20.30" in store - assert b"yyy" == store["foo/10.20.30"] - # N5 reverses axis order - assert b"yyy" == store["foo/30/20/10"] - del store["foo/10.20.30"] - assert "foo/30/20/10" not in store - store["42"] = b"zzz" - assert "42" in store - assert b"zzz" == store["42"] - - def test_init_array(self): - store = self.create_store() - init_array(store, shape=1000, chunks=100) - - # check metadata - assert array_meta_key in store - meta = store._metadata_class.decode_array_metadata(store[array_meta_key]) - assert ZARR_FORMAT == meta["zarr_format"] - assert (1000,) == meta["shape"] - assert (100,) == meta["chunks"] - assert np.dtype(None) == meta["dtype"] - # N5Store wraps the actual compressor - compressor_config = meta["compressor"]["compressor_config"] - assert default_compressor.get_config() == compressor_config - # N5Store always has a fill value of 0 - assert meta["fill_value"] == 0 - assert meta["dimension_separator"] == "." - # Top-level groups AND arrays should have - # the n5 keyword in metadata - raw_n5_meta = json.loads(store[n5_attrs_key]) - assert raw_n5_meta.get("n5", None) == N5_FORMAT - - def test_init_array_path(self): - path = "foo/bar" - store = self.create_store() - init_array(store, shape=1000, chunks=100, path=path) - - # check metadata - key = path + "/" + array_meta_key - assert key in store - meta = store._metadata_class.decode_array_metadata(store[key]) - assert ZARR_FORMAT == meta["zarr_format"] - assert (1000,) == meta["shape"] - assert (100,) == meta["chunks"] - assert np.dtype(None) == meta["dtype"] - # N5Store wraps the actual compressor - compressor_config = meta["compressor"]["compressor_config"] - assert default_compressor.get_config() == compressor_config - # N5Store always has a fill value of 0 - assert meta["fill_value"] == 0 - - def test_init_array_compat(self): - store = self.create_store() - init_array(store, shape=1000, chunks=100, compressor="none") - meta = store._metadata_class.decode_array_metadata(store[array_meta_key]) - # N5Store wraps the actual compressor - compressor_config = meta["compressor"]["compressor_config"] - assert compressor_config is None - - def test_init_array_overwrite(self): - self._test_init_array_overwrite("C") - - def test_init_array_overwrite_path(self): - self._test_init_array_overwrite_path("C") - - def test_init_array_overwrite_chunk_store(self): - self._test_init_array_overwrite_chunk_store("C") - - def test_init_group_overwrite(self): - self._test_init_group_overwrite("C") - - def test_init_group_overwrite_path(self): - self._test_init_group_overwrite_path("C") - - def test_init_group_overwrite_chunk_store(self): - self._test_init_group_overwrite_chunk_store("C") - - def test_init_group(self): - store = self.create_store() - init_group(store) - store[".zattrs"] = json_dumps({"foo": "bar"}) - # check metadata - assert group_meta_key in store - assert group_meta_key in store.listdir() - assert group_meta_key in store.listdir("") - meta = store._metadata_class.decode_group_metadata(store[group_meta_key]) - assert ZARR_FORMAT == meta["zarr_format"] - - def test_filters(self): - all_filters, all_errors = zip( - *[ - (None, does_not_raise()), - ([], does_not_raise()), - ([AsType("f4", "f8")], pytest.raises(ValueError)), - ] - ) - for filters, error in zip(all_filters, all_errors): - store = self.create_store() - with error: - init_array(store, shape=1000, chunks=100, filters=filters) - - -@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") -class TestN5FSStore(TestFSStore): - def create_store(self, normalize_keys=False, path=None, **kwargs): - if path is None: - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - - store = N5FSStore(path, normalize_keys=normalize_keys, **kwargs) - return store - - def test_equal(self): - store_a = self.create_store() - store_b = N5FSStore(store_a.path) - assert store_a == store_b - - # This is copied wholesale from the N5Store tests. The same test could - # be run by making TestN5FSStore inherit from both TestFSStore and - # TestN5Store, but a direct copy is arguably more explicit. - - @pytest.mark.parametrize("zarr_meta_key", [".zarray", ".zattrs", ".zgroup"]) - def test_del_zarr_meta_key(self, zarr_meta_key): - store = self.create_store() - store[n5_attrs_key] = json_dumps({"foo": "bar"}) - del store[zarr_meta_key] - assert n5_attrs_key not in store - - def test_chunk_nesting(self): - store = self.create_store() - store["0.0"] = b"xxx" - assert "0.0" in store - assert b"xxx" == store["0.0"] - # assert b'xxx' == store['0/0'] - store["foo/10.20.30"] = b"yyy" - assert "foo/10.20.30" in store - assert b"yyy" == store["foo/10.20.30"] - # N5 reverses axis order - assert b"yyy" == store["foo/30/20/10"] - del store["foo/10.20.30"] - assert "foo/30/20/10" not in store - store["42"] = b"zzz" - assert "42" in store - assert b"zzz" == store["42"] - - def test_init_array(self): - store = self.create_store() - init_array(store, shape=1000, chunks=100) - - # check metadata - assert array_meta_key in store - meta = store._metadata_class.decode_array_metadata(store[array_meta_key]) - assert ZARR_FORMAT == meta["zarr_format"] - assert (1000,) == meta["shape"] - assert (100,) == meta["chunks"] - assert np.dtype(None) == meta["dtype"] - # N5Store wraps the actual compressor - compressor_config = meta["compressor"]["compressor_config"] - assert default_compressor.get_config() == compressor_config - # N5Store always has a fill value of 0 - assert meta["fill_value"] == 0 - assert meta["dimension_separator"] == "." - # Top-level groups AND arrays should have - # the n5 keyword in metadata - raw_n5_meta = json.loads(store[n5_attrs_key]) - assert raw_n5_meta.get("n5", None) == N5_FORMAT - - def test_init_array_path(self): - path = "foo/bar" - store = self.create_store() - init_array(store, shape=1000, chunks=100, path=path) - - # check metadata - key = path + "/" + array_meta_key - assert key in store - meta = store._metadata_class.decode_array_metadata(store[key]) - assert ZARR_FORMAT == meta["zarr_format"] - assert (1000,) == meta["shape"] - assert (100,) == meta["chunks"] - assert np.dtype(None) == meta["dtype"] - # N5Store wraps the actual compressor - compressor_config = meta["compressor"]["compressor_config"] - assert default_compressor.get_config() == compressor_config - # N5Store always has a fill value of 0 - assert meta["fill_value"] == 0 - - def test_init_array_compat(self): - store = self.create_store() - init_array(store, shape=1000, chunks=100, compressor="none") - meta = store._metadata_class.decode_array_metadata(store[array_meta_key]) - # N5Store wraps the actual compressor - compressor_config = meta["compressor"]["compressor_config"] - assert compressor_config is None - - def test_init_array_overwrite(self): - self._test_init_array_overwrite("C") - - def test_init_array_overwrite_path(self): - self._test_init_array_overwrite_path("C") - - def test_init_array_overwrite_chunk_store(self): - self._test_init_array_overwrite_chunk_store("C") - - def test_init_group_overwrite(self): - self._test_init_group_overwrite("C") - - def test_init_group_overwrite_path(self): - self._test_init_group_overwrite_path("C") - - def test_init_group_overwrite_chunk_store(self): - self._test_init_group_overwrite_chunk_store("C") - - def test_dimension_separator(self): - with pytest.warns(UserWarning, match="dimension_separator"): - self.create_store(dimension_separator="/") - - def test_init_group(self): - store = self.create_store() - init_group(store) - store[".zattrs"] = json_dumps({"foo": "bar"}) - # check metadata - assert group_meta_key in store - assert group_meta_key in store.listdir() - assert group_meta_key in store.listdir("") - meta = store._metadata_class.decode_group_metadata(store[group_meta_key]) - assert ZARR_FORMAT == meta["zarr_format"] - - def test_filters(self): - all_filters, all_errors = zip( - *[ - (None, does_not_raise()), - ([], does_not_raise()), - ([AsType("f4", "f8")], pytest.raises(ValueError)), - ] - ) - for filters, error in zip(all_filters, all_errors): - store = self.create_store() - with error: - init_array(store, shape=1000, chunks=100, filters=filters) - - -@pytest.mark.skipif(have_fsspec is False, reason="needs fsspec") -class TestNestedFSStore(TestNestedDirectoryStore): - def create_store(self, normalize_keys=False, path=None, **kwargs): - if path is None: - path = tempfile.mkdtemp() - atexit.register(atexit_rmtree, path) - store = FSStore( - path, normalize_keys=normalize_keys, dimension_separator="/", auto_mkdir=True, **kwargs - ) - return store - - def test_numbered_groups(self): - # Create an array - store = self.create_store() - group = zarr.v2.group(store=store) - arr = group.create_dataset("0", shape=(10, 10)) - arr[1] = 1 - - # Read it back - store = self.create_store(path=store.path) - zarr.v2.open_group(store.path)["0"] - - -class TestTempStore(StoreTests): - def create_store(self, **kwargs): - skip_if_nested_chunks(**kwargs) - return TempStore(**kwargs) - - def test_setdel(self): - store = self.create_store() - setdel_hierarchy_checks(store, self.root) - - -class TestZipStore(StoreTests): - ZipStoreClass = ZipStore - - def create_store(self, **kwargs): - path = mktemp(suffix=".zip") - atexit.register(os.remove, path) - store = ZipStore(path, mode="w", **kwargs) - return store - - def test_mode(self): - with self.ZipStoreClass("data/store.zip", mode="w") as store: - store[self.root + "foo"] = b"bar" - store = self.ZipStoreClass("data/store.zip", mode="r") - with pytest.raises(PermissionError): - store[self.root + "foo"] = b"bar" - with pytest.raises(PermissionError): - store.clear() - - def test_flush(self): - store = self.ZipStoreClass("data/store.zip", mode="w") - store[self.root + "foo"] = b"bar" - store.flush() - assert store[self.root + "foo"] == b"bar" - store.close() - - store = self.ZipStoreClass("data/store.zip", mode="r") - store.flush() # no-op - - def test_context_manager(self): - with self.create_store() as store: - store[self.root + "foo"] = b"bar" - store[self.root + "baz"] = b"qux" - assert 2 == len(store) - - def test_pop(self): - # override because not implemented - store = self.create_store() - store[self.root + "foo"] = b"bar" - with pytest.raises(NotImplementedError): - store.pop(self.root + "foo") - - def test_popitem(self): - # override because not implemented - store = self.create_store() - store[self.root + "foo"] = b"bar" - with pytest.raises(NotImplementedError): - store.popitem() - - def test_permissions(self): - store = self.ZipStoreClass("data/store.zip", mode="w") - foo_key = "foo" if self.version == 2 else self.root + "foo" - # TODO: cannot provide key ending in / for v3 - # how to create an empty folder in that case? - baz_key = "baz/" if self.version == 2 else self.root + "baz" - store[foo_key] = b"bar" - store[baz_key] = b"" - - store.flush() - store.close() - z = ZipFile("data/store.zip", "r") - info = z.getinfo(foo_key) - perm = oct(info.external_attr >> 16) - assert perm == "0o644" - info = z.getinfo(baz_key) - perm = oct(info.external_attr >> 16) - # only for posix platforms - if os.name == "posix": - if self.version == 2: - assert perm == "0o40775" - else: - # baz/ on v2, but baz on v3, so not a directory - assert perm == "0o644" - z.close() - - def test_store_and_retrieve_ndarray(self): - store = ZipStore("data/store.zip") - x = np.array([[1, 2], [3, 4]]) - store["foo"] = x - y = np.frombuffer(store["foo"], dtype=x.dtype).reshape(x.shape) - assert np.array_equiv(y, x) - - -class TestDBMStore(StoreTests): - def create_store(self, dimension_separator=None): - path = mktemp(suffix=".anydbm") - atexit.register(atexit_rmglob, path + "*") - # create store using default dbm implementation - store = DBMStore(path, flag="n", dimension_separator=dimension_separator) - return store - - def test_context_manager(self): - with self.create_store() as store: - store[self.root + "foo"] = b"bar" - store[self.root + "baz"] = b"qux" - assert 2 == len(store) - - -class TestDBMStoreDumb(TestDBMStore): - def create_store(self, **kwargs): - path = mktemp(suffix=".dumbdbm") - atexit.register(atexit_rmglob, path + "*") - - import dbm.dumb as dumbdbm - - store = DBMStore(path, flag="n", open=dumbdbm.open, **kwargs) - return store - - -class TestDBMStoreGnu(TestDBMStore): - def create_store(self, **kwargs): - gdbm = pytest.importorskip("dbm.gnu") - path = mktemp(suffix=".gdbm") # pragma: no cover - atexit.register(os.remove, path) # pragma: no cover - store = DBMStore( - path, flag="n", open=gdbm.open, write_lock=False, **kwargs - ) # pragma: no cover - return store # pragma: no cover - - -class TestDBMStoreNDBM(TestDBMStore): - def create_store(self, **kwargs): - ndbm = pytest.importorskip("dbm.ndbm") - path = mktemp(suffix=".ndbm") # pragma: no cover - atexit.register(atexit_rmglob, path + "*") # pragma: no cover - store = DBMStore(path, flag="n", open=ndbm.open, **kwargs) # pragma: no cover - return store # pragma: no cover - - -class TestDBMStoreBerkeleyDB(TestDBMStore): - def create_store(self, **kwargs): - bsddb3 = pytest.importorskip("bsddb3") - path = mktemp(suffix=".dbm") - atexit.register(os.remove, path) - store = DBMStore(path, flag="n", open=bsddb3.btopen, write_lock=False, **kwargs) - return store - - -class TestLMDBStore(StoreTests): - def create_store(self, **kwargs): - pytest.importorskip("lmdb") - path = mktemp(suffix=".lmdb") - atexit.register(atexit_rmtree, path) - buffers = True - store = LMDBStore(path, buffers=buffers, **kwargs) - return store - - def test_context_manager(self): - with self.create_store() as store: - store[self.root + "foo"] = b"bar" - store[self.root + "baz"] = b"qux" - assert 2 == len(store) - - -class TestSQLiteStore(StoreTests): - def create_store(self, **kwargs): - pytest.importorskip("sqlite3") - path = mktemp(suffix=".db") - atexit.register(atexit_rmtree, path) - store = SQLiteStore(path, **kwargs) - return store - - def test_underscore_in_name(self): - path = mktemp(suffix=".db") - atexit.register(atexit_rmtree, path) - store = SQLiteStore(path) - store["a"] = b"aaa" - store["a_b"] = b"aa_bb" - store.rmdir("a") - assert "a_b" in store - - -class TestSQLiteStoreInMemory(TestSQLiteStore): - def create_store(self, **kwargs): - pytest.importorskip("sqlite3") - store = SQLiteStore(":memory:", **kwargs) - return store - - def test_pickle(self): - # setup store - store = self.create_store() - store[self.root + "foo"] = b"bar" - store[self.root + "baz"] = b"quux" - - # round-trip through pickle - with pytest.raises(PicklingError): - pickle.dumps(store) - - -@skip_test_env_var("ZARR_TEST_MONGO") -class TestMongoDBStore(StoreTests): - def create_store(self, **kwargs): - pytest.importorskip("pymongo") - store = MongoDBStore( - host="127.0.0.1", database="zarr_tests", collection="zarr_tests", **kwargs - ) - # start with an empty store - store.clear() - return store - - -@skip_test_env_var("ZARR_TEST_REDIS") -class TestRedisStore(StoreTests): - def create_store(self, **kwargs): - # TODO: this is the default host for Redis on Travis, - # we probably want to generalize this though - pytest.importorskip("redis") - store = RedisStore(host="localhost", port=6379, **kwargs) - # start with an empty store - store.clear() - return store - - -class TestLRUStoreCache(StoreTests): - CountingClass = CountingDict - LRUStoreClass = LRUStoreCache - - def create_store(self, **kwargs): - # wrapper therefore no dimension_separator argument - skip_if_nested_chunks(**kwargs) - return self.LRUStoreClass(dict(), max_size=2**27) - - def test_cache_values_no_max_size(self): - # setup store - store = self.CountingClass() - foo_key = self.root + "foo" - bar_key = self.root + "bar" - store[foo_key] = b"xxx" - store[bar_key] = b"yyy" - assert 0 == store.counter["__getitem__", foo_key] - assert 1 == store.counter["__setitem__", foo_key] - assert 0 == store.counter["__getitem__", bar_key] - assert 1 == store.counter["__setitem__", bar_key] - - # setup cache - cache = self.LRUStoreClass(store, max_size=None) - assert 0 == cache.hits - assert 0 == cache.misses - - # test first __getitem__, cache miss - assert b"xxx" == cache[foo_key] - assert 1 == store.counter["__getitem__", foo_key] - assert 1 == store.counter["__setitem__", foo_key] - assert 0 == cache.hits - assert 1 == cache.misses - - # test second __getitem__, cache hit - assert b"xxx" == cache[foo_key] - assert 1 == store.counter["__getitem__", foo_key] - assert 1 == store.counter["__setitem__", foo_key] - assert 1 == cache.hits - assert 1 == cache.misses - - # test __setitem__, __getitem__ - cache[foo_key] = b"zzz" - assert 1 == store.counter["__getitem__", foo_key] - assert 2 == store.counter["__setitem__", foo_key] - # should be a cache hit - assert b"zzz" == cache[foo_key] - assert 1 == store.counter["__getitem__", foo_key] - assert 2 == store.counter["__setitem__", foo_key] - assert 2 == cache.hits - assert 1 == cache.misses - - # manually invalidate all cached values - cache.invalidate_values() - assert b"zzz" == cache[foo_key] - assert 2 == store.counter["__getitem__", foo_key] - assert 2 == store.counter["__setitem__", foo_key] - cache.invalidate() - assert b"zzz" == cache[foo_key] - assert 3 == store.counter["__getitem__", foo_key] - assert 2 == store.counter["__setitem__", foo_key] - - # test __delitem__ - del cache[foo_key] - with pytest.raises(KeyError): - # noinspection PyStatementEffect - cache[foo_key] - with pytest.raises(KeyError): - # noinspection PyStatementEffect - store[foo_key] - - # verify other keys untouched - assert 0 == store.counter["__getitem__", bar_key] - assert 1 == store.counter["__setitem__", bar_key] - - def test_cache_values_with_max_size(self): - # setup store - store = self.CountingClass() - foo_key = self.root + "foo" - bar_key = self.root + "bar" - store[foo_key] = b"xxx" - store[bar_key] = b"yyy" - assert 0 == store.counter["__getitem__", foo_key] - assert 0 == store.counter["__getitem__", bar_key] - # setup cache - can only hold one item - cache = self.LRUStoreClass(store, max_size=5) - assert 0 == cache.hits - assert 0 == cache.misses - - # test first 'foo' __getitem__, cache miss - assert b"xxx" == cache[foo_key] - assert 1 == store.counter["__getitem__", foo_key] - assert 0 == cache.hits - assert 1 == cache.misses - - # test second 'foo' __getitem__, cache hit - assert b"xxx" == cache[foo_key] - assert 1 == store.counter["__getitem__", foo_key] - assert 1 == cache.hits - assert 1 == cache.misses - - # test first 'bar' __getitem__, cache miss - assert b"yyy" == cache[bar_key] - assert 1 == store.counter["__getitem__", bar_key] - assert 1 == cache.hits - assert 2 == cache.misses - - # test second 'bar' __getitem__, cache hit - assert b"yyy" == cache[bar_key] - assert 1 == store.counter["__getitem__", bar_key] - assert 2 == cache.hits - assert 2 == cache.misses - - # test 'foo' __getitem__, should have been evicted, cache miss - assert b"xxx" == cache[foo_key] - assert 2 == store.counter["__getitem__", foo_key] - assert 2 == cache.hits - assert 3 == cache.misses - - # test 'bar' __getitem__, should have been evicted, cache miss - assert b"yyy" == cache[bar_key] - assert 2 == store.counter["__getitem__", bar_key] - assert 2 == cache.hits - assert 4 == cache.misses - - # setup store - store = self.CountingClass() - store[foo_key] = b"xxx" - store[bar_key] = b"yyy" - assert 0 == store.counter["__getitem__", foo_key] - assert 0 == store.counter["__getitem__", bar_key] - # setup cache - can hold two items - cache = self.LRUStoreClass(store, max_size=6) - assert 0 == cache.hits - assert 0 == cache.misses - - # test first 'foo' __getitem__, cache miss - assert b"xxx" == cache[foo_key] - assert 1 == store.counter["__getitem__", foo_key] - assert 0 == cache.hits - assert 1 == cache.misses - - # test second 'foo' __getitem__, cache hit - assert b"xxx" == cache[foo_key] - assert 1 == store.counter["__getitem__", foo_key] - assert 1 == cache.hits - assert 1 == cache.misses - - # test first 'bar' __getitem__, cache miss - assert b"yyy" == cache[bar_key] - assert 1 == store.counter["__getitem__", bar_key] - assert 1 == cache.hits - assert 2 == cache.misses - - # test second 'bar' __getitem__, cache hit - assert b"yyy" == cache[bar_key] - assert 1 == store.counter["__getitem__", bar_key] - assert 2 == cache.hits - assert 2 == cache.misses - - # test 'foo' __getitem__, should still be cached - assert b"xxx" == cache[foo_key] - assert 1 == store.counter["__getitem__", foo_key] - assert 3 == cache.hits - assert 2 == cache.misses - - # test 'bar' __getitem__, should still be cached - assert b"yyy" == cache[bar_key] - assert 1 == store.counter["__getitem__", bar_key] - assert 4 == cache.hits - assert 2 == cache.misses - - def test_cache_keys(self): - # setup - store = self.CountingClass() - foo_key = self.root + "foo" - bar_key = self.root + "bar" - baz_key = self.root + "baz" - store[foo_key] = b"xxx" - store[bar_key] = b"yyy" - assert 0 == store.counter["__contains__", foo_key] - assert 0 == store.counter["__iter__"] - assert 0 == store.counter["keys"] - cache = self.LRUStoreClass(store, max_size=None) - - # keys should be cached on first call - keys = sorted(cache.keys()) - assert keys == [bar_key, foo_key] - assert 1 == store.counter["keys"] - # keys should now be cached - assert keys == sorted(cache.keys()) - assert 1 == store.counter["keys"] - assert foo_key in cache - assert 1 == store.counter["__contains__", foo_key] - # the next check for `foo_key` is cached - assert foo_key in cache - assert 1 == store.counter["__contains__", foo_key] - assert keys == sorted(cache) - assert 0 == store.counter["__iter__"] - assert 1 == store.counter["keys"] - - # cache should be cleared if store is modified - crude but simple for now - cache[baz_key] = b"zzz" - keys = sorted(cache.keys()) - assert keys == [bar_key, baz_key, foo_key] - assert 2 == store.counter["keys"] - # keys should now be cached - assert keys == sorted(cache.keys()) - assert 2 == store.counter["keys"] - - # manually invalidate keys - cache.invalidate_keys() - keys = sorted(cache.keys()) - assert keys == [bar_key, baz_key, foo_key] - assert 3 == store.counter["keys"] - assert 1 == store.counter["__contains__", foo_key] - assert 0 == store.counter["__iter__"] - cache.invalidate_keys() - keys = sorted(cache) - assert keys == [bar_key, baz_key, foo_key] - assert 4 == store.counter["keys"] - assert 1 == store.counter["__contains__", foo_key] - assert 0 == store.counter["__iter__"] - cache.invalidate_keys() - assert foo_key in cache - assert 4 == store.counter["keys"] - assert 2 == store.counter["__contains__", foo_key] - assert 0 == store.counter["__iter__"] - - # check these would get counted if called directly - assert foo_key in store - assert 3 == store.counter["__contains__", foo_key] - assert keys == sorted(store) - assert 1 == store.counter["__iter__"] - - -def test_getsize(): - store = KVStore(dict()) - store["foo"] = b"aaa" - store["bar"] = b"bbbb" - store["baz/quux"] = b"ccccc" - assert 7 == getsize(store) - assert 5 == getsize(store, "baz") - - store = KVStore(dict()) - store["boo"] = None - assert -1 == getsize(store) - - -@pytest.mark.parametrize("dict_store", [False, True]) -def test_migrate_1to2(dict_store): - # N.B., version 1 did not support hierarchies, so we only have to be - # concerned about migrating a single array at the root of the store - - # setup - store = dict() if dict_store else KVStore(dict()) - meta = dict( - shape=(100,), - chunks=(10,), - dtype=np.dtype("f4"), - compression="zlib", - compression_opts=1, - fill_value=None, - order="C", - ) - meta_json = meta_v1.encode_metadata(meta) - store["meta"] = meta_json - store["attrs"] = json.dumps(dict()).encode("ascii") - - # run migration - migrate_1to2(store) - - # check results - assert "meta" not in store - assert array_meta_key in store - assert "attrs" not in store - assert attrs_key in store - meta_migrated = decode_array_metadata(store[array_meta_key]) - assert 2 == meta_migrated["zarr_format"] - - # preserved fields - for f in "shape", "chunks", "dtype", "fill_value", "order": - assert meta[f] == meta_migrated[f] - - # migrate should have added empty filters field - assert meta_migrated["filters"] is None - - # check compression and compression_opts migrated to compressor - assert "compression" not in meta_migrated - assert "compression_opts" not in meta_migrated - assert meta_migrated["compressor"] == Zlib(1).get_config() - - # check dict compression_opts - store = dict() if dict_store else KVStore(dict()) - meta["compression"] = "blosc" - meta["compression_opts"] = dict(cname="lz4", clevel=5, shuffle=1) - meta_json = meta_v1.encode_metadata(meta) - store["meta"] = meta_json - store["attrs"] = json.dumps(dict()).encode("ascii") - migrate_1to2(store) - meta_migrated = decode_array_metadata(store[array_meta_key]) - assert "compression" not in meta_migrated - assert "compression_opts" not in meta_migrated - assert meta_migrated["compressor"] == Blosc(cname="lz4", clevel=5, shuffle=1).get_config() - - # check 'none' compression is migrated to None (null in JSON) - store = dict() if dict_store else KVStore(dict()) - meta["compression"] = "none" - meta_json = meta_v1.encode_metadata(meta) - store["meta"] = meta_json - store["attrs"] = json.dumps(dict()).encode("ascii") - migrate_1to2(store) - meta_migrated = decode_array_metadata(store[array_meta_key]) - assert "compression" not in meta_migrated - assert "compression_opts" not in meta_migrated - assert meta_migrated["compressor"] is None - - -def test_format_compatibility(): - # This test is intended to catch any unintended changes that break the ability to - # read data stored with a previous minor version (which should be format-compatible). - - # fixture data - fixture_path = pathlib.Path(__file__).parent / "fixture" / "test_format_compatibility" - fixture = group(store=DirectoryStore(fixture_path)) - - # set seed to get consistent random data - np.random.seed(42) - - arrays_chunks = [ - (np.arange(1111, dtype="" == actual[-8:] - - -def test_tree_get_icon(): - assert tree_get_icon("Array") == tree_array_icon - assert tree_get_icon("Group") == tree_group_icon - with pytest.raises(ValueError): - tree_get_icon("Baz") - - -@mock.patch.dict("sys.modules", {"ipytree": None}) -def test_tree_widget_missing_ipytree(): - pattern = ( - "Run `pip install zarr[jupyter]` or `conda install ipytree`" - "to get the required ipytree dependency for displaying the tree " - "widget. If using jupyterlab<3, you also need to run " - "`jupyter labextension install ipytree`" - ) - with pytest.raises(ImportError, match=re.escape(pattern)): - tree_widget(None, None, None) - - -def test_retry_call(): - class Fixture: - def __init__(self, pass_on=1): - self.c = 0 - self.pass_on = pass_on - - def __call__(self): - self.c += 1 - if self.c != self.pass_on: - raise PermissionError - - for x in range(1, 11): - # Any number of failures less than 10 will be accepted. - fixture = Fixture(pass_on=x) - retry_call(fixture, exceptions=(PermissionError,), wait=0) - assert fixture.c == x - - def fail(x): - # Failures after 10 will cause an error to be raised. - retry_call(Fixture(pass_on=x), exceptions=(Exception,), wait=0) - - for x in range(11, 15): - pytest.raises(PermissionError, fail, x) - - -def test_flatten(): - assert list( - flatten( - [ - "0", - [ - "1", - [ - "2", - [ - "3", - [ - 4, - ], - ], - ], - ], - ] - ) - ) == ["0", "1", "2", "3", 4] - assert list(flatten("foo")) == ["f", "o", "o"] - assert list(flatten(["foo"])) == ["foo"] - - -def test_all_equal(): - assert all_equal(0, np.zeros((10, 10, 10))) - assert not all_equal(1, np.zeros((10, 10, 10))) - - assert all_equal(1, np.ones((10, 10, 10))) - assert not all_equal(1, 1 + np.ones((10, 10, 10))) - - assert all_equal(np.nan, np.array([np.nan, np.nan])) - assert not all_equal(np.nan, np.array([np.nan, 1.0])) - - assert all_equal({"a": -1}, np.array([{"a": -1}, {"a": -1}], dtype="object")) - assert not all_equal({"a": -1}, np.array([{"a": -1}, {"a": 2}], dtype="object")) - - assert all_equal(np.timedelta64(999, "D"), np.array([999, 999], dtype="timedelta64[D]")) - assert not all_equal(np.timedelta64(999, "D"), np.array([999, 998], dtype="timedelta64[D]")) - - # all_equal(None, *) always returns False - assert not all_equal(None, np.array([None, None])) - assert not all_equal(None, np.array([None, 10])) - - -def test_json_dumps_numpy_dtype(): - assert json_dumps(np.int64(0)) == json_dumps(0) - assert json_dumps(np.float32(0)) == json_dumps(float(0)) - # Check that we raise the error of the superclass for unsupported object - with pytest.raises(TypeError): - json_dumps(Array) - - -def test_constant_map(): - val = object() - m = ConstantMap(keys=[1, 2], constant=val) - assert len(m) == 2 - assert m[1] is val - assert m[2] is val - assert 1 in m - assert 0 not in m - with pytest.raises(KeyError): - m[0] - assert repr(m) == repr({1: val, 2: val}) diff --git a/tests/v2/util.py b/tests/v2/util.py deleted file mode 100644 index 12c5e379f6..0000000000 --- a/tests/v2/util.py +++ /dev/null @@ -1,91 +0,0 @@ -import collections -import os -import tempfile -from typing import Any, Mapping, Sequence -from zarr.v2.context import Context - -from zarr.v2.storage import Store - -import pytest - - -class CountingDict(Store): - def __init__(self): - self.wrapped = dict() - self.counter = collections.Counter() - - def __len__(self): - self.counter["__len__"] += 1 - return len(self.wrapped) - - def keys(self): - self.counter["keys"] += 1 - return self.wrapped.keys() - - def __iter__(self): - self.counter["__iter__"] += 1 - return iter(self.wrapped) - - def __contains__(self, item): - self.counter["__contains__", item] += 1 - return item in self.wrapped - - def __getitem__(self, item): - self.counter["__getitem__", item] += 1 - return self.wrapped[item] - - def __setitem__(self, key, value): - self.counter["__setitem__", key] += 1 - self.wrapped[key] = value - - def __delitem__(self, key): - self.counter["__delitem__", key] += 1 - del self.wrapped[key] - - def getitems( - self, keys: Sequence[str], *, contexts: Mapping[str, Context] - ) -> Mapping[str, Any]: - for key in keys: - self.counter["__getitem__", key] += 1 - return {k: self.wrapped[k] for k in keys if k in self.wrapped} - - -def skip_test_env_var(name): - """Checks for environment variables indicating whether tests requiring services should be run""" - value = os.environ.get(name, "0") - return pytest.mark.skipif(value == "0", reason="Tests not enabled via environment variable") - - -try: - import fsspec # noqa: F401 - - have_fsspec = True -except ImportError: # pragma: no cover - have_fsspec = False - - -def abs_container(): - from azure.core.exceptions import ResourceExistsError - import azure.storage.blob as asb - - URL = "http://127.0.0.1:10000" - ACCOUNT_NAME = "devstoreaccount1" - KEY = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==" - CONN_STR = ( - f"DefaultEndpointsProtocol=http;AccountName={ACCOUNT_NAME};" - f"AccountKey={KEY};BlobEndpoint={URL}/{ACCOUNT_NAME};" - ) - - blob_service_client = asb.BlobServiceClient.from_connection_string(CONN_STR) - try: - container_client = blob_service_client.create_container("test") - except ResourceExistsError: - container_client = blob_service_client.get_container_client("test") - - return container_client - - -def mktemp(**kwargs): - f = tempfile.NamedTemporaryFile(**kwargs) - f.close() - return f.name diff --git a/tests/v3/conftest.py b/tests/v3/conftest.py deleted file mode 100644 index 0a672d1f2e..0000000000 --- a/tests/v3/conftest.py +++ /dev/null @@ -1,136 +0,0 @@ -from __future__ import annotations - -from collections.abc import Iterator -from types import ModuleType -from typing import TYPE_CHECKING - -from _pytest.compat import LEGACY_PATH - -from zarr import config -from zarr.abc.store import Store -from zarr.common import ChunkCoords, MemoryOrder, ZarrFormat -from zarr.group import AsyncGroup - -if TYPE_CHECKING: - from typing import Any, Literal -import pathlib -from dataclasses import dataclass, field - -import numpy as np -import pytest -from hypothesis import HealthCheck, Verbosity, settings - -from zarr.store import LocalStore, MemoryStore, StorePath -from zarr.store.remote import RemoteStore - - -async def parse_store( - store: Literal["local", "memory", "remote"], path: str -) -> LocalStore | MemoryStore | RemoteStore: - if store == "local": - return await LocalStore.open(path, mode="w") - if store == "memory": - return await MemoryStore.open(mode="w") - if store == "remote": - return await RemoteStore.open(url=path, mode="w") - raise AssertionError - - -@pytest.fixture(params=[str, pathlib.Path]) -def path_type(request: pytest.FixtureRequest) -> Any: - return request.param - - -# todo: harmonize this with local_store fixture -@pytest.fixture -async def store_path(tmpdir: LEGACY_PATH) -> StorePath: - store = await LocalStore.open(str(tmpdir), mode="w") - p = StorePath(store) - return p - - -@pytest.fixture(scope="function") -async def local_store(tmpdir: LEGACY_PATH) -> LocalStore: - return await LocalStore.open(str(tmpdir), mode="w") - - -@pytest.fixture(scope="function") -async def remote_store(url: str) -> RemoteStore: - return await RemoteStore.open(url, mode="w") - - -@pytest.fixture(scope="function") -async def memory_store() -> MemoryStore: - return await MemoryStore.open(mode="w") - - -@pytest.fixture(scope="function") -async def store(request: pytest.FixtureRequest, tmpdir: LEGACY_PATH) -> Store: - param = request.param - return await parse_store(param, str(tmpdir)) - - -@dataclass -class AsyncGroupRequest: - zarr_format: ZarrFormat - store: Literal["local", "remote", "memory"] - attributes: dict[str, Any] = field(default_factory=dict) - - -@pytest.fixture(scope="function") -async def async_group(request: pytest.FixtureRequest, tmpdir: LEGACY_PATH) -> AsyncGroup: - param: AsyncGroupRequest = request.param - - store = await parse_store(param.store, str(tmpdir)) - agroup = await AsyncGroup.create( - store, - attributes=param.attributes, - zarr_format=param.zarr_format, - exists_ok=False, - ) - return agroup - - -@pytest.fixture(params=["numpy", "cupy"]) -def xp(request: pytest.FixtureRequest) -> Iterator[ModuleType]: - """Fixture to parametrize over numpy-like libraries""" - - yield pytest.importorskip(request.param) - - -@pytest.fixture(autouse=True) -def reset_config(): - config.reset() - yield - config.reset() - - -@dataclass -class ArrayRequest: - shape: ChunkCoords - dtype: str - order: MemoryOrder - - -@pytest.fixture -def array_fixture(request: pytest.FixtureRequest) -> np.ndarray: - array_request: ArrayRequest = request.param - return ( - np.arange(np.prod(array_request.shape)) - .reshape(array_request.shape, order=array_request.order) - .astype(array_request.dtype) - ) - - -settings.register_profile( - "ci", - max_examples=1000, - deadline=None, - suppress_health_check=[HealthCheck.filter_too_much, HealthCheck.too_slow], -) -settings.register_profile( - "local", - max_examples=300, - suppress_health_check=[HealthCheck.filter_too_much, HealthCheck.too_slow], - verbosity=Verbosity.verbose, -) diff --git a/tests/v3/package_with_entrypoint/__init__.py b/tests/v3/package_with_entrypoint/__init__.py deleted file mode 100644 index 4d626808d8..0000000000 --- a/tests/v3/package_with_entrypoint/__init__.py +++ /dev/null @@ -1,65 +0,0 @@ -from collections.abc import Iterable - -from numpy import ndarray - -from zarr.abc.codec import ArrayBytesCodec, CodecInput, CodecPipeline -from zarr.array_spec import ArraySpec -from zarr.buffer import Buffer, NDBuffer -from zarr.codecs import BytesCodec -from zarr.common import BytesLike - - -class TestEntrypointCodec(ArrayBytesCodec): - is_fixed_size = True - - async def encode( - self, - chunks_and_specs: Iterable[tuple[CodecInput | None, ArraySpec]], - ) -> BytesLike | None: - pass - - async def decode( - self, - chunks_and_specs: Iterable[tuple[CodecInput | None, ArraySpec]], - ) -> ndarray: - pass - - def compute_encoded_size(self, input_byte_length: int, chunk_spec: ArraySpec) -> int: - return input_byte_length - - -class TestEntrypointCodecPipeline(CodecPipeline): - def __init__(self, batch_size: int = 1): - pass - - async def encode( - self, chunks_and_specs: Iterable[tuple[CodecInput | None, ArraySpec]] - ) -> BytesLike: - pass - - async def decode( - self, chunks_and_specs: Iterable[tuple[CodecInput | None, ArraySpec]] - ) -> ndarray: - pass - - -class TestEntrypointBuffer(Buffer): - pass - - -class TestEntrypointNDBuffer(NDBuffer): - pass - - -class TestEntrypointGroup: - class Codec(BytesCodec): - pass - - class Buffer(Buffer): - pass - - class NDBuffer(NDBuffer): - pass - - class Pipeline(CodecPipeline): - pass diff --git a/tests/v3/test_api.py b/tests/v3/test_api.py deleted file mode 100644 index 002678be88..0000000000 --- a/tests/v3/test_api.py +++ /dev/null @@ -1,851 +0,0 @@ -import numpy as np -import pytest -from numpy.testing import assert_array_equal -from pytest_asyncio import fixture - -import zarr -from zarr import Array, Group -from zarr.abc.store import Store -from zarr.api.synchronous import create, load, open, open_group, save, save_array, save_group - - -def test_create_array(memory_store: Store) -> None: - store = memory_store - - # create array - z = create(shape=100, store=store) - assert isinstance(z, Array) - assert z.shape == (100,) - - # create array, overwrite, specify chunk shape - z = create(shape=200, chunk_shape=20, store=store, overwrite=True) - assert isinstance(z, Array) - assert z.shape == (200,) - assert z.chunks == (20,) - - # create array, overwrite, specify chunk shape via chunks param - z = create(shape=400, chunks=40, store=store, overwrite=True) - assert isinstance(z, Array) - assert z.shape == (400,) - assert z.chunks == (40,) - - -async def test_open_array(memory_store: Store) -> None: - store = memory_store - - # open array, create if doesn't exist - z = open(store=store, shape=100) - assert isinstance(z, Array) - assert z.shape == (100,) - - # open array, overwrite - store._store_dict = {} - z = open(store=store, shape=200, mode="w") # mode="w" - assert isinstance(z, Array) - assert z.shape == (200,) - - # open array, read-only - store_cls = type(store) - ro_store = await store_cls.open(store_dict=store._store_dict, mode="r") - z = open(store=ro_store) - assert isinstance(z, Array) - assert z.shape == (200,) - assert z.read_only - - # path not found - with pytest.raises(FileNotFoundError): - open(store="doesnotexist", mode="r") - - -async def test_open_group(memory_store: Store) -> None: - store = memory_store - - # open group, create if doesn't exist - g = open_group(store=store) - g.create_group("foo") - assert isinstance(g, Group) - assert "foo" in g - - # open group, overwrite - # g = open_group(store=store) - # assert isinstance(g, Group) - # assert "foo" not in g - - # open group, read-only - store_cls = type(store) - ro_store = await store_cls.open(store_dict=store._store_dict, mode="r") - g = open_group(store=ro_store) - assert isinstance(g, Group) - # assert g.read_only - - -def test_save_errors() -> None: - with pytest.raises(ValueError): - # no arrays provided - save_group("data/group.zarr") - with pytest.raises(TypeError): - # no array provided - save_array("data/group.zarr") - with pytest.raises(ValueError): - # no arrays provided - save("data/group.zarr") - - -@fixture -def tmppath(tmpdir): - return str(tmpdir / "example.zarr") - - -def test_open_with_mode_r(tmppath) -> None: - # 'r' means read only (must exist) - with pytest.raises(FileNotFoundError): - zarr.open(store=tmppath, mode="r") - zarr.ones(store=tmppath, shape=(3, 3)) - z2 = zarr.open(store=tmppath, mode="r") - assert (z2[:] == 1).all() - with pytest.raises(ValueError): - z2[:] = 3 - - -def test_open_with_mode_r_plus(tmppath) -> None: - # 'r+' means read/write (must exist) - with pytest.raises(FileNotFoundError): - zarr.open(store=tmppath, mode="r+") - zarr.ones(store=tmppath, shape=(3, 3)) - z2 = zarr.open(store=tmppath, mode="r+") - assert (z2[:] == 1).all() - z2[:] = 3 - - -def test_open_with_mode_a(tmppath) -> None: - # 'a' means read/write (create if doesn't exist) - zarr.open(store=tmppath, mode="a", shape=(3, 3))[...] = 1 - z2 = zarr.open(store=tmppath, mode="a") - assert (z2[:] == 1).all() - z2[:] = 3 - - -def test_open_with_mode_w(tmppath) -> None: - # 'w' means create (overwrite if exists); - zarr.open(store=tmppath, mode="w", shape=(3, 3))[...] = 3 - z2 = zarr.open(store=tmppath, mode="w", shape=(3, 3)) - assert not (z2[:] == 3).all() - z2[:] = 3 - - -def test_open_with_mode_w_minus(tmppath) -> None: - # 'w-' means create (fail if exists) - zarr.open(store=tmppath, mode="w-", shape=(3, 3))[...] = 1 - with pytest.raises(FileExistsError): - zarr.open(store=tmppath, mode="w-") - - -# def test_lazy_loader(): -# foo = np.arange(100) -# bar = np.arange(100, 0, -1) -# store = "data/group.zarr" -# save(store, foo=foo, bar=bar) -# loader = load(store) -# assert "foo" in loader -# assert "bar" in loader -# assert "baz" not in loader -# assert len(loader) == 2 -# assert sorted(loader) == ["bar", "foo"] -# assert_array_equal(foo, loader["foo"]) -# assert_array_equal(bar, loader["bar"]) -# assert "LazyLoader: " in repr(loader) - - -def test_load_array(memory_store: Store) -> None: - store = memory_store - foo = np.arange(100) - bar = np.arange(100, 0, -1) - save(store, foo=foo, bar=bar) - - # can also load arrays directly into a numpy array - for array_name in ["foo", "bar"]: - array = load(store, path=array_name) - assert isinstance(array, np.ndarray) - if array_name == "foo": - assert_array_equal(foo, array) - else: - assert_array_equal(bar, array) - - -def test_tree() -> None: - g1 = zarr.group() - g1.create_group("foo") - g3 = g1.create_group("bar") - g3.create_group("baz") - g5 = g3.create_group("qux") - g5.create_array("baz", shape=100, chunks=10) - # TODO: complete after tree has been reimplemented - # assert repr(zarr.tree(g1)) == repr(g1.tree()) - # assert str(zarr.tree(g1)) == str(g1.tree()) - - -# @pytest.mark.parametrize("stores_from_path", [False, True]) -# @pytest.mark.parametrize( -# "with_chunk_store,listable", -# [(False, True), (True, True), (False, False)], -# ids=["default-listable", "with_chunk_store-listable", "default-unlistable"], -# ) -# def test_consolidate_metadata(with_chunk_store, listable, monkeypatch, stores_from_path): -# # setup initial data -# if stores_from_path: -# store = tempfile.mkdtemp() -# atexit.register(atexit_rmtree, store) -# if with_chunk_store: -# chunk_store = tempfile.mkdtemp() -# atexit.register(atexit_rmtree, chunk_store) -# else: -# chunk_store = None -# else: -# store = MemoryStore() -# chunk_store = MemoryStore() if with_chunk_store else None -# path = None -# z = group(store, chunk_store=chunk_store, path=path) - -# # Reload the actual store implementation in case str -# store_to_copy = z.store - -# z.create_group("g1") -# g2 = z.create_group("g2") -# g2.attrs["hello"] = "world" -# arr = g2.create_array("arr", shape=(20, 20), chunks=(5, 5), dtype="f8") -# assert 16 == arr.nchunks -# assert 0 == arr.nchunks_initialized -# arr.attrs["data"] = 1 -# arr[:] = 1.0 -# assert 16 == arr.nchunks_initialized - -# if stores_from_path: -# # get the actual store class for use with consolidate_metadata -# store_class = z._store -# else: -# store_class = store - -# # perform consolidation -# out = consolidate_metadata(store_class, path=path) -# assert isinstance(out, Group) -# assert ["g1", "g2"] == list(out) -# if not stores_from_path: -# assert isinstance(out._store, ConsolidatedMetadataStore) -# assert ".zmetadata" in store -# meta_keys = [ -# ".zgroup", -# "g1/.zgroup", -# "g2/.zgroup", -# "g2/.zattrs", -# "g2/arr/.zarray", -# "g2/arr/.zattrs", -# ] - -# for key in meta_keys: -# del store[key] - -# # https://github.com/zarr-developers/zarr-python/issues/993 -# # Make sure we can still open consolidated on an unlistable store: -# if not listable: -# fs_memory = pytest.importorskip("fsspec.implementations.memory") -# monkeypatch.setattr(fs_memory.MemoryFileSystem, "isdir", lambda x, y: False) -# monkeypatch.delattr(fs_memory.MemoryFileSystem, "ls") -# fs = fs_memory.MemoryFileSystem() -# store_to_open = FSStore("", fs=fs) -# # copy original store to new unlistable store -# store_to_open.update(store_to_copy) - -# else: -# store_to_open = store - -# # open consolidated -# z2 = open_consolidated(store_to_open, chunk_store=chunk_store, path=path) -# assert ["g1", "g2"] == list(z2) -# assert "world" == z2.g2.attrs["hello"] -# assert 1 == z2.g2.arr.attrs["data"] -# assert (z2.g2.arr[:] == 1.0).all() -# assert 16 == z2.g2.arr.nchunks -# if listable: -# assert 16 == z2.g2.arr.nchunks_initialized -# else: -# with pytest.raises(NotImplementedError): -# _ = z2.g2.arr.nchunks_initialized - -# if stores_from_path: -# # path string is note a BaseStore subclass so cannot be used to -# # initialize a ConsolidatedMetadataStore. - -# with pytest.raises(ValueError): -# cmd = ConsolidatedMetadataStore(store) -# else: -# # tests del/write on the store - -# cmd = ConsolidatedMetadataStore(store) -# with pytest.raises(PermissionError): -# del cmd[".zgroup"] -# with pytest.raises(PermissionError): -# cmd[".zgroup"] = None - -# # test getsize on the store -# assert isinstance(getsize(cmd), Integral) - -# # test new metadata are not writeable -# with pytest.raises(PermissionError): -# z2.create_group("g3") -# with pytest.raises(PermissionError): -# z2.create_dataset("spam", shape=42, chunks=7, dtype="i4") -# with pytest.raises(PermissionError): -# del z2["g2"] - -# # test consolidated metadata are not writeable -# with pytest.raises(PermissionError): -# z2.g2.attrs["hello"] = "universe" -# with pytest.raises(PermissionError): -# z2.g2.arr.attrs["foo"] = "bar" - -# # test the data are writeable -# z2.g2.arr[:] = 2 -# assert (z2.g2.arr[:] == 2).all() - -# # test invalid modes -# with pytest.raises(ValueError): -# open_consolidated(store, chunk_store=chunk_store, mode="a", path=path) -# with pytest.raises(ValueError): -# open_consolidated(store, chunk_store=chunk_store, mode="w", path=path) -# with pytest.raises(ValueError): -# open_consolidated(store, chunk_store=chunk_store, mode="w-", path=path) - -# # make sure keyword arguments are passed through without error -# open_consolidated( -# store, -# chunk_store=chunk_store, -# path=path, -# cache_attrs=True, -# synchronizer=None, -# ) - - -# @pytest.mark.parametrize( -# "options", -# ( -# {"dimension_separator": "/"}, -# {"dimension_separator": "."}, -# {"dimension_separator": None}, -# ), -# ) -# def test_save_array_separator(tmpdir, options): -# data = np.arange(6).reshape((3, 2)) -# url = tmpdir.join("test.zarr") -# save_array(url, data, **options) - - -# class TestCopyStore(unittest.TestCase): -# _version = 2 - -# def setUp(self): -# source = dict() -# source["foo"] = b"xxx" -# source["bar/baz"] = b"yyy" -# source["bar/qux"] = b"zzz" -# self.source = source - -# def _get_dest_store(self): -# return dict() - -# def test_no_paths(self): -# source = self.source -# dest = self._get_dest_store() -# copy_store(source, dest) -# assert len(source) == len(dest) -# for key in source: -# assert source[key] == dest[key] - -# def test_source_path(self): -# source = self.source -# # paths should be normalized -# for source_path in "bar", "bar/", "/bar", "/bar/": -# dest = self._get_dest_store() -# copy_store(source, dest, source_path=source_path) -# assert 2 == len(dest) -# for key in source: -# if key.startswith("bar/"): -# dest_key = key.split("bar/")[1] -# assert source[key] == dest[dest_key] -# else: -# assert key not in dest - -# def test_dest_path(self): -# source = self.source -# # paths should be normalized -# for dest_path in "new", "new/", "/new", "/new/": -# dest = self._get_dest_store() -# copy_store(source, dest, dest_path=dest_path) -# assert len(source) == len(dest) -# for key in source: -# if self._version == 3: -# dest_key = key[:10] + "new/" + key[10:] -# else: -# dest_key = "new/" + key -# assert source[key] == dest[dest_key] - -# def test_source_dest_path(self): -# source = self.source -# # paths should be normalized -# for source_path in "bar", "bar/", "/bar", "/bar/": -# for dest_path in "new", "new/", "/new", "/new/": -# dest = self._get_dest_store() -# copy_store(source, dest, source_path=source_path, dest_path=dest_path) -# assert 2 == len(dest) -# for key in source: -# if key.startswith("bar/"): -# dest_key = "new/" + key.split("bar/")[1] -# assert source[key] == dest[dest_key] -# else: -# assert key not in dest -# assert ("new/" + key) not in dest - -# def test_excludes_includes(self): -# source = self.source - -# # single excludes -# dest = self._get_dest_store() -# excludes = "f.*" -# copy_store(source, dest, excludes=excludes) -# assert len(dest) == 2 - -# root = "" -# assert root + "foo" not in dest - -# # multiple excludes -# dest = self._get_dest_store() -# excludes = "b.z", ".*x" -# copy_store(source, dest, excludes=excludes) -# assert len(dest) == 1 -# assert root + "foo" in dest -# assert root + "bar/baz" not in dest -# assert root + "bar/qux" not in dest - -# # excludes and includes -# dest = self._get_dest_store() -# excludes = "b.*" -# includes = ".*x" -# copy_store(source, dest, excludes=excludes, includes=includes) -# assert len(dest) == 2 -# assert root + "foo" in dest -# assert root + "bar/baz" not in dest -# assert root + "bar/qux" in dest - -# def test_dry_run(self): -# source = self.source -# dest = self._get_dest_store() -# copy_store(source, dest, dry_run=True) -# assert 0 == len(dest) - -# def test_if_exists(self): -# source = self.source -# dest = self._get_dest_store() -# root = "" -# dest[root + "bar/baz"] = b"mmm" - -# # default ('raise') -# with pytest.raises(CopyError): -# copy_store(source, dest) - -# # explicit 'raise' -# with pytest.raises(CopyError): -# copy_store(source, dest, if_exists="raise") - -# # skip -# copy_store(source, dest, if_exists="skip") -# assert 3 == len(dest) -# assert dest[root + "foo"] == b"xxx" -# assert dest[root + "bar/baz"] == b"mmm" -# assert dest[root + "bar/qux"] == b"zzz" - -# # replace -# copy_store(source, dest, if_exists="replace") -# assert 3 == len(dest) -# assert dest[root + "foo"] == b"xxx" -# assert dest[root + "bar/baz"] == b"yyy" -# assert dest[root + "bar/qux"] == b"zzz" - -# # invalid option -# with pytest.raises(ValueError): -# copy_store(source, dest, if_exists="foobar") - - -# def check_copied_array(original, copied, without_attrs=False, expect_props=None): -# # setup -# source_h5py = original.__module__.startswith("h5py.") -# dest_h5py = copied.__module__.startswith("h5py.") -# zarr_to_zarr = not (source_h5py or dest_h5py) -# h5py_to_h5py = source_h5py and dest_h5py -# zarr_to_h5py = not source_h5py and dest_h5py -# h5py_to_zarr = source_h5py and not dest_h5py -# if expect_props is None: -# expect_props = dict() -# else: -# expect_props = expect_props.copy() - -# # common properties in zarr and h5py -# for p in "dtype", "shape", "chunks": -# expect_props.setdefault(p, getattr(original, p)) - -# # zarr-specific properties -# if zarr_to_zarr: -# for p in "compressor", "filters", "order", "fill_value": -# expect_props.setdefault(p, getattr(original, p)) - -# # h5py-specific properties -# if h5py_to_h5py: -# for p in ( -# "maxshape", -# "compression", -# "compression_opts", -# "shuffle", -# "scaleoffset", -# "fletcher32", -# "fillvalue", -# ): -# expect_props.setdefault(p, getattr(original, p)) - -# # common properties with some name differences -# if h5py_to_zarr: -# expect_props.setdefault("fill_value", original.fillvalue) -# if zarr_to_h5py: -# expect_props.setdefault("fillvalue", original.fill_value) - -# # compare properties -# for k, v in expect_props.items(): -# assert v == getattr(copied, k) - -# # compare data -# assert_array_equal(original[:], copied[:]) - -# # compare attrs -# if without_attrs: -# for k in original.attrs.keys(): -# assert k not in copied.attrs -# else: -# if dest_h5py and "filters" in original.attrs: -# # special case in v3 (storing filters metadata under attributes) -# # we explicitly do not copy this info over to HDF5 -# original_attrs = original.attrs.asdict().copy() -# original_attrs.pop("filters") -# else: -# original_attrs = original.attrs -# assert sorted(original_attrs.items()) == sorted(copied.attrs.items()) - - -# def check_copied_group(original, copied, without_attrs=False, expect_props=None, shallow=False): -# # setup -# if expect_props is None: -# expect_props = dict() -# else: -# expect_props = expect_props.copy() - -# # compare children -# for k, v in original.items(): -# if hasattr(v, "shape"): -# assert k in copied -# check_copied_array(v, copied[k], without_attrs=without_attrs, expect_props=expect_props) -# elif shallow: -# assert k not in copied -# else: -# assert k in copied -# check_copied_group( -# v, -# copied[k], -# without_attrs=without_attrs, -# shallow=shallow, -# expect_props=expect_props, -# ) - -# # compare attrs -# if without_attrs: -# for k in original.attrs.keys(): -# assert k not in copied.attrs -# else: -# assert sorted(original.attrs.items()) == sorted(copied.attrs.items()) - - -# def test_copy_all(): -# """ -# https://github.com/zarr-developers/zarr-python/issues/269 - -# copy_all used to not copy attributes as `.keys()` does not return hidden `.zattrs`. - -# """ -# original_group = zarr.group(store=MemoryStore(), overwrite=True) -# original_group.attrs["info"] = "group attrs" -# original_subgroup = original_group.create_group("subgroup") -# original_subgroup.attrs["info"] = "sub attrs" - -# destination_group = zarr.group(store=MemoryStore(), overwrite=True) - -# # copy from memory to directory store -# copy_all( -# original_group, -# destination_group, -# dry_run=False, -# ) - -# assert "subgroup" in destination_group -# assert destination_group.attrs["info"] == "group attrs" -# assert destination_group.subgroup.attrs["info"] == "sub attrs" - - -# class TestCopy: -# @pytest.fixture(params=[False, True], ids=["zarr", "hdf5"]) -# def source(self, request, tmpdir): -# def prep_source(source): -# foo = source.create_group("foo") -# foo.attrs["experiment"] = "weird science" -# baz = foo.create_dataset("bar/baz", data=np.arange(100), chunks=(50,)) -# baz.attrs["units"] = "metres" -# if request.param: -# extra_kws = dict( -# compression="gzip", -# compression_opts=3, -# fillvalue=84, -# shuffle=True, -# fletcher32=True, -# ) -# else: -# extra_kws = dict(compressor=Zlib(3), order="F", fill_value=42, filters=[Adler32()]) -# source.create_dataset( -# "spam", -# data=np.arange(100, 200).reshape(20, 5), -# chunks=(10, 2), -# dtype="i2", -# **extra_kws, -# ) -# return source - -# if request.param: -# h5py = pytest.importorskip("h5py") -# fn = tmpdir.join("source.h5") -# with h5py.File(str(fn), mode="w") as h5f: -# yield prep_source(h5f) -# else: -# yield prep_source(group()) - -# @pytest.fixture(params=[False, True], ids=["zarr", "hdf5"]) -# def dest(self, request, tmpdir): -# if request.param: -# h5py = pytest.importorskip("h5py") -# fn = tmpdir.join("dest.h5") -# with h5py.File(str(fn), mode="w") as h5f: -# yield h5f -# else: -# yield group() - -# def test_copy_array(self, source, dest): -# # copy array with default options -# copy(source["foo/bar/baz"], dest) -# check_copied_array(source["foo/bar/baz"], dest["baz"]) -# copy(source["spam"], dest) -# check_copied_array(source["spam"], dest["spam"]) - -# def test_copy_bad_dest(self, source, dest): -# # try to copy to an array, dest must be a group -# dest = dest.create_dataset("eggs", shape=(100,)) -# with pytest.raises(ValueError): -# copy(source["foo/bar/baz"], dest) - -# def test_copy_array_name(self, source, dest): -# # copy array with name -# copy(source["foo/bar/baz"], dest, name="qux") -# assert "baz" not in dest -# check_copied_array(source["foo/bar/baz"], dest["qux"]) - -# def test_copy_array_create_options(self, source, dest): -# dest_h5py = dest.__module__.startswith("h5py.") - -# # copy array, provide creation options -# compressor = Zlib(9) -# create_kws = dict(chunks=(10,)) -# if dest_h5py: -# create_kws.update( -# compression="gzip", compression_opts=9, shuffle=True, fletcher32=True, fillvalue=42 -# ) -# else: -# create_kws.update(compressor=compressor, fill_value=42, order="F", filters=[Adler32()]) -# copy(source["foo/bar/baz"], dest, without_attrs=True, **create_kws) -# check_copied_array( -# source["foo/bar/baz"], dest["baz"], without_attrs=True, expect_props=create_kws -# ) - -# def test_copy_array_exists_array(self, source, dest): -# # copy array, dest array in the way -# dest.create_dataset("baz", shape=(10,)) - -# # raise -# with pytest.raises(CopyError): -# # should raise by default -# copy(source["foo/bar/baz"], dest) -# assert (10,) == dest["baz"].shape -# with pytest.raises(CopyError): -# copy(source["foo/bar/baz"], dest, if_exists="raise") -# assert (10,) == dest["baz"].shape - -# # skip -# copy(source["foo/bar/baz"], dest, if_exists="skip") -# assert (10,) == dest["baz"].shape - -# # replace -# copy(source["foo/bar/baz"], dest, if_exists="replace") -# check_copied_array(source["foo/bar/baz"], dest["baz"]) - -# # invalid option -# with pytest.raises(ValueError): -# copy(source["foo/bar/baz"], dest, if_exists="foobar") - -# def test_copy_array_exists_group(self, source, dest): -# # copy array, dest group in the way -# dest.create_group("baz") - -# # raise -# with pytest.raises(CopyError): -# copy(source["foo/bar/baz"], dest) -# assert not hasattr(dest["baz"], "shape") -# with pytest.raises(CopyError): -# copy(source["foo/bar/baz"], dest, if_exists="raise") -# assert not hasattr(dest["baz"], "shape") - -# # skip -# copy(source["foo/bar/baz"], dest, if_exists="skip") -# assert not hasattr(dest["baz"], "shape") - -# # replace -# copy(source["foo/bar/baz"], dest, if_exists="replace") -# check_copied_array(source["foo/bar/baz"], dest["baz"]) - -# def test_copy_array_skip_initialized(self, source, dest): -# dest_h5py = dest.__module__.startswith("h5py.") - -# dest.create_dataset("baz", shape=(100,), chunks=(10,), dtype="i8") -# assert not np.all(source["foo/bar/baz"][:] == dest["baz"][:]) - -# if dest_h5py: -# with pytest.raises(ValueError): -# # not available with copy to h5py -# copy(source["foo/bar/baz"], dest, if_exists="skip_initialized") - -# else: -# # copy array, dest array exists but not yet initialized -# copy(source["foo/bar/baz"], dest, if_exists="skip_initialized") -# check_copied_array(source["foo/bar/baz"], dest["baz"]) - -# # copy array, dest array exists and initialized, will be skipped -# dest["baz"][:] = np.arange(100, 200) -# copy(source["foo/bar/baz"], dest, if_exists="skip_initialized") -# assert_array_equal(np.arange(100, 200), dest["baz"][:]) -# assert not np.all(source["foo/bar/baz"][:] == dest["baz"][:]) - -# def test_copy_group(self, source, dest): -# # copy group, default options -# copy(source["foo"], dest) -# check_copied_group(source["foo"], dest["foo"]) - -# def test_copy_group_no_name(self, source, dest): -# with pytest.raises(TypeError): -# # need a name if copy root -# copy(source, dest) - -# copy(source, dest, name="root") -# check_copied_group(source, dest["root"]) - -# def test_copy_group_options(self, source, dest): -# # copy group, non-default options -# copy(source["foo"], dest, name="qux", without_attrs=True) -# assert "foo" not in dest -# check_copied_group(source["foo"], dest["qux"], without_attrs=True) - -# def test_copy_group_shallow(self, source, dest): -# # copy group, shallow -# copy(source, dest, name="eggs", shallow=True) -# check_copied_group(source, dest["eggs"], shallow=True) - -# def test_copy_group_exists_group(self, source, dest): -# # copy group, dest groups exist -# dest.create_group("foo/bar") -# copy(source["foo"], dest) -# check_copied_group(source["foo"], dest["foo"]) - -# def test_copy_group_exists_array(self, source, dest): -# # copy group, dest array in the way -# dest.create_dataset("foo/bar", shape=(10,)) - -# # raise -# with pytest.raises(CopyError): -# copy(source["foo"], dest) -# assert dest["foo/bar"].shape == (10,) -# with pytest.raises(CopyError): -# copy(source["foo"], dest, if_exists="raise") -# assert dest["foo/bar"].shape == (10,) - -# # skip -# copy(source["foo"], dest, if_exists="skip") -# assert dest["foo/bar"].shape == (10,) - -# # replace -# copy(source["foo"], dest, if_exists="replace") -# check_copied_group(source["foo"], dest["foo"]) - -# def test_copy_group_dry_run(self, source, dest): -# # dry run, empty destination -# n_copied, n_skipped, n_bytes_copied = copy( -# source["foo"], dest, dry_run=True, return_stats=True -# ) -# assert 0 == len(dest) -# assert 3 == n_copied -# assert 0 == n_skipped -# assert 0 == n_bytes_copied - -# # dry run, array exists in destination -# baz = np.arange(100, 200) -# dest.create_dataset("foo/bar/baz", data=baz) -# assert not np.all(source["foo/bar/baz"][:] == dest["foo/bar/baz"][:]) -# assert 1 == len(dest) - -# # raise -# with pytest.raises(CopyError): -# copy(source["foo"], dest, dry_run=True) -# assert 1 == len(dest) - -# # skip -# n_copied, n_skipped, n_bytes_copied = copy( -# source["foo"], dest, dry_run=True, if_exists="skip", return_stats=True -# ) -# assert 1 == len(dest) -# assert 2 == n_copied -# assert 1 == n_skipped -# assert 0 == n_bytes_copied -# assert_array_equal(baz, dest["foo/bar/baz"]) - -# # replace -# n_copied, n_skipped, n_bytes_copied = copy( -# source["foo"], dest, dry_run=True, if_exists="replace", return_stats=True -# ) -# assert 1 == len(dest) -# assert 3 == n_copied -# assert 0 == n_skipped -# assert 0 == n_bytes_copied -# assert_array_equal(baz, dest["foo/bar/baz"]) - -# def test_logging(self, source, dest, tmpdir): -# # callable log -# copy(source["foo"], dest, dry_run=True, log=print) - -# # file name -# fn = str(tmpdir.join("log_name")) -# copy(source["foo"], dest, dry_run=True, log=fn) - -# # file -# with tmpdir.join("log_file").open(mode="w") as f: -# copy(source["foo"], dest, dry_run=True, log=f) - -# # bad option -# with pytest.raises(TypeError): -# copy(source["foo"], dest, dry_run=True, log=True) diff --git a/tests/v3/test_array.py b/tests/v3/test_array.py deleted file mode 100644 index 9fd135ad5c..0000000000 --- a/tests/v3/test_array.py +++ /dev/null @@ -1,138 +0,0 @@ -from typing import Literal - -import numpy as np -import pytest - -from zarr.array import Array -from zarr.common import ZarrFormat -from zarr.errors import ContainsArrayError, ContainsGroupError -from zarr.group import Group -from zarr.store import LocalStore, MemoryStore -from zarr.store.core import StorePath - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -@pytest.mark.parametrize("zarr_format", (2, 3)) -@pytest.mark.parametrize("exists_ok", [True, False]) -@pytest.mark.parametrize("extant_node", ["array", "group"]) -def test_array_creation_existing_node( - store: LocalStore | MemoryStore, - zarr_format: ZarrFormat, - exists_ok: bool, - extant_node: Literal["array", "group"], -) -> None: - """ - Check that an existing array or group is handled as expected during array creation. - """ - spath = StorePath(store) - group = Group.create(spath, zarr_format=zarr_format) - expected_exception: type[ContainsArrayError] | type[ContainsGroupError] - if extant_node == "array": - expected_exception = ContainsArrayError - _ = group.create_array("extant", shape=(10,), dtype="uint8") - elif extant_node == "group": - expected_exception = ContainsGroupError - _ = group.create_group("extant") - else: - raise AssertionError - - new_shape = (2, 2) - new_dtype = "float32" - - if exists_ok: - arr_new = Array.create( - spath / "extant", - shape=new_shape, - dtype=new_dtype, - exists_ok=exists_ok, - zarr_format=zarr_format, - ) - assert arr_new.shape == new_shape - assert arr_new.dtype == new_dtype - else: - with pytest.raises(expected_exception): - arr_new = Array.create( - spath / "extant", - shape=new_shape, - dtype=new_dtype, - exists_ok=exists_ok, - zarr_format=zarr_format, - ) - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -@pytest.mark.parametrize("zarr_format", (2, 3)) -def test_array_name_properties_no_group( - store: LocalStore | MemoryStore, zarr_format: ZarrFormat -) -> None: - arr = Array.create(store=store, shape=(100,), chunks=(10,), zarr_format=zarr_format, dtype="i4") - assert arr.path == "" - assert arr.name is None - assert arr.basename is None - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -@pytest.mark.parametrize("zarr_format", (2, 3)) -def test_array_name_properties_with_group( - store: LocalStore | MemoryStore, zarr_format: ZarrFormat -) -> None: - root = Group.create(store=store, zarr_format=zarr_format) - foo = root.create_array("foo", shape=(100,), chunks=(10,), dtype="i4") - assert foo.path == "foo" - assert foo.name == "/foo" - assert foo.basename == "foo" - - bar = root.create_group("bar") - spam = bar.create_array("spam", shape=(100,), chunks=(10,), dtype="i4") - - assert spam.path == "bar/spam" - assert spam.name == "/bar/spam" - assert spam.basename == "spam" - - -@pytest.mark.parametrize("store", ["memory"], indirect=True) -@pytest.mark.parametrize("specifiy_fill_value", [True, False]) -@pytest.mark.parametrize("dtype_str", ["bool", "uint8", "complex64"]) -def test_array_v3_fill_value_default( - store: MemoryStore, specifiy_fill_value: bool, dtype_str: str -) -> None: - """ - Test that creating an array with the fill_value parameter set to None, or unspecified, - results in the expected fill_value attribute of the array, i.e. 0 cast to the array's dtype. - """ - shape = (10,) - default_fill_value = 0 - if specifiy_fill_value: - arr = Array.create( - store=store, - shape=shape, - dtype=dtype_str, - zarr_format=3, - chunk_shape=shape, - fill_value=None, - ) - else: - arr = Array.create( - store=store, shape=shape, dtype=dtype_str, zarr_format=3, chunk_shape=shape - ) - - assert arr.fill_value == np.dtype(dtype_str).type(default_fill_value) - assert arr.fill_value.dtype == arr.dtype - - -@pytest.mark.parametrize("store", ["memory"], indirect=True) -@pytest.mark.parametrize("fill_value", [False, 0.0, 1, 2.3]) -@pytest.mark.parametrize("dtype_str", ["bool", "uint8", "float32", "complex64"]) -def test_array_v3_fill_value(store: MemoryStore, fill_value: int, dtype_str: str) -> None: - shape = (10,) - arr = Array.create( - store=store, - shape=shape, - dtype=dtype_str, - zarr_format=3, - chunk_shape=shape, - fill_value=fill_value, - ) - - assert arr.fill_value == np.dtype(dtype_str).type(fill_value) - assert arr.fill_value.dtype == arr.dtype diff --git a/tests/v3/test_buffer.py b/tests/v3/test_buffer.py deleted file mode 100644 index d53e98d42d..0000000000 --- a/tests/v3/test_buffer.py +++ /dev/null @@ -1,91 +0,0 @@ -from __future__ import annotations - -import numpy as np -import pytest - -from zarr.array import AsyncArray -from zarr.buffer import ArrayLike, BufferPrototype, NDArrayLike, numpy_buffer_prototype -from zarr.codecs.blosc import BloscCodec -from zarr.codecs.bytes import BytesCodec -from zarr.codecs.crc32c_ import Crc32cCodec -from zarr.codecs.gzip import GzipCodec -from zarr.codecs.transpose import TransposeCodec -from zarr.codecs.zstd import ZstdCodec -from zarr.store.core import StorePath -from zarr.testing.buffer import ( - NDBufferUsingTestNDArrayLike, - StoreExpectingTestBuffer, - TestBuffer, - TestNDArrayLike, -) - - -def test_nd_array_like(xp): - ary = xp.arange(10) - assert isinstance(ary, ArrayLike) - assert isinstance(ary, NDArrayLike) - - -@pytest.mark.asyncio -async def test_async_array_prototype(): - """Test the use of a custom buffer prototype""" - - expect = np.zeros((9, 9), dtype="uint16", order="F") - a = await AsyncArray.create( - StorePath(StoreExpectingTestBuffer(mode="w")) / "test_async_array_prototype", - shape=expect.shape, - chunk_shape=(5, 5), - dtype=expect.dtype, - fill_value=0, - ) - expect[1:4, 3:6] = np.ones((3, 3)) - - my_prototype = BufferPrototype(buffer=TestBuffer, nd_buffer=NDBufferUsingTestNDArrayLike) - - await a.setitem( - selection=(slice(1, 4), slice(3, 6)), - value=np.ones((3, 3)), - prototype=my_prototype, - ) - got = await a.getitem(selection=(slice(0, 9), slice(0, 9)), prototype=my_prototype) - assert isinstance(got, TestNDArrayLike) - assert np.array_equal(expect, got) - - -@pytest.mark.asyncio -async def test_codecs_use_of_prototype(): - expect = np.zeros((10, 10), dtype="uint16", order="F") - a = await AsyncArray.create( - StorePath(StoreExpectingTestBuffer(mode="w")) / "test_codecs_use_of_prototype", - shape=expect.shape, - chunk_shape=(5, 5), - dtype=expect.dtype, - fill_value=0, - codecs=[ - TransposeCodec(order=(1, 0)), - BytesCodec(), - BloscCodec(), - Crc32cCodec(), - GzipCodec(), - ZstdCodec(), - ], - ) - expect[:] = np.arange(100).reshape(10, 10) - - my_prototype = BufferPrototype(buffer=TestBuffer, nd_buffer=NDBufferUsingTestNDArrayLike) - - await a.setitem( - selection=(slice(0, 10), slice(0, 10)), - value=expect[:], - prototype=my_prototype, - ) - got = await a.getitem(selection=(slice(0, 10), slice(0, 10)), prototype=my_prototype) - assert isinstance(got, TestNDArrayLike) - assert np.array_equal(expect, got) - - -def test_numpy_buffer_prototype(): - buffer = numpy_buffer_prototype().buffer.create_zero_length() - ndbuffer = numpy_buffer_prototype().nd_buffer.create(shape=(1, 2), dtype=np.dtype("int64")) - assert isinstance(buffer.as_array_like(), np.ndarray) - assert isinstance(ndbuffer.as_ndarray_like(), np.ndarray) diff --git a/tests/v3/test_chunk_grids.py b/tests/v3/test_chunk_grids.py deleted file mode 100644 index 3cc6b64e57..0000000000 --- a/tests/v3/test_chunk_grids.py +++ /dev/null @@ -1,18 +0,0 @@ -import numpy as np -import pytest - -from zarr.chunk_grids import _guess_chunks - - -@pytest.mark.parametrize( - "shape", ((0,), (0,) * 2, (1, 2, 0, 4, 5), (10, 0), (10,), (100,) * 3, (1000000,), (10000,) * 2) -) -@pytest.mark.parametrize("itemsize", (1, 2, 4)) -def test_guess_chunks(shape: tuple[int, ...], itemsize: int) -> None: - chunks = _guess_chunks(shape, itemsize) - chunk_size = np.prod(chunks) * itemsize - assert isinstance(chunks, tuple) - assert len(chunks) == len(shape) - assert chunk_size < (64 * 1024 * 1024) - # doesn't make any sense to allow chunks to have zero length dimension - assert all(0 < c <= max(s, 1) for c, s in zip(chunks, shape, strict=False)) diff --git a/tests/v3/test_codec_entrypoints.py b/tests/v3/test_codec_entrypoints.py deleted file mode 100644 index 9e2932fdd5..0000000000 --- a/tests/v3/test_codec_entrypoints.py +++ /dev/null @@ -1,49 +0,0 @@ -import os.path -import sys - -import pytest - -import zarr.registry -from zarr import config - -here = os.path.abspath(os.path.dirname(__file__)) - - -@pytest.fixture() -def set_path(): - sys.path.append(here) - zarr.registry._collect_entrypoints() - yield - sys.path.remove(here) - registries = zarr.registry._collect_entrypoints() - for registry in registries: - registry.lazy_load_list.clear() - config.reset() - - -@pytest.mark.usefixtures("set_path") -@pytest.mark.parametrize("codec_name", ["TestEntrypointCodec", "TestEntrypointGroup.Codec"]) -def test_entrypoint_codec(codec_name): - config.set({"codecs.test": "package_with_entrypoint." + codec_name}) - cls_test = zarr.registry.get_codec_class("test") - assert cls_test.__qualname__ == codec_name - - -@pytest.mark.usefixtures("set_path") -def test_entrypoint_pipeline(): - config.set({"codec_pipeline.path": "package_with_entrypoint.TestEntrypointCodecPipeline"}) - cls = zarr.registry.get_pipeline_class() - assert cls.__name__ == "TestEntrypointCodecPipeline" - - -@pytest.mark.usefixtures("set_path") -@pytest.mark.parametrize("buffer_name", ["TestEntrypointBuffer", "TestEntrypointGroup.Buffer"]) -def test_entrypoint_buffer(buffer_name): - config.set( - { - "buffer": "package_with_entrypoint." + buffer_name, - "ndbuffer": "package_with_entrypoint.TestEntrypointNDBuffer", - } - ) - assert zarr.registry.get_buffer_class().__qualname__ == buffer_name - assert zarr.registry.get_ndbuffer_class().__name__ == "TestEntrypointNDBuffer" diff --git a/tests/v3/test_codecs/test_blosc.py b/tests/v3/test_codecs/test_blosc.py deleted file mode 100644 index 33ca9eba77..0000000000 --- a/tests/v3/test_codecs/test_blosc.py +++ /dev/null @@ -1,57 +0,0 @@ -import json - -import numpy as np -import pytest - -from zarr.abc.store import Store -from zarr.array import AsyncArray -from zarr.buffer import default_buffer_prototype -from zarr.codecs import BloscCodec, BytesCodec, ShardingCodec -from zarr.store.core import StorePath - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -@pytest.mark.parametrize("dtype", ["uint8", "uint16"]) -async def test_blosc_evolve(store: Store, dtype: str) -> None: - typesize = np.dtype(dtype).itemsize - path = "blosc_evolve" - spath = StorePath(store, path) - await AsyncArray.create( - spath, - shape=(16, 16), - chunk_shape=(16, 16), - dtype=dtype, - fill_value=0, - codecs=[BytesCodec(), BloscCodec()], - ) - - zarr_json = json.loads( - (await store.get(f"{path}/zarr.json", prototype=default_buffer_prototype())).to_bytes() - ) - blosc_configuration_json = zarr_json["codecs"][1]["configuration"] - assert blosc_configuration_json["typesize"] == typesize - if typesize == 1: - assert blosc_configuration_json["shuffle"] == "bitshuffle" - else: - assert blosc_configuration_json["shuffle"] == "shuffle" - - path2 = "blosc_evolve_sharding" - spath2 = StorePath(store, path2) - await AsyncArray.create( - spath2, - shape=(16, 16), - chunk_shape=(16, 16), - dtype=dtype, - fill_value=0, - codecs=[ShardingCodec(chunk_shape=(16, 16), codecs=[BytesCodec(), BloscCodec()])], - ) - - zarr_json = json.loads( - (await store.get(f"{path2}/zarr.json", prototype=default_buffer_prototype())).to_bytes() - ) - blosc_configuration_json = zarr_json["codecs"][0]["configuration"]["codecs"][1]["configuration"] - assert blosc_configuration_json["typesize"] == typesize - if typesize == 1: - assert blosc_configuration_json["shuffle"] == "bitshuffle" - else: - assert blosc_configuration_json["shuffle"] == "shuffle" diff --git a/tests/v3/test_codecs/test_codecs.py b/tests/v3/test_codecs/test_codecs.py deleted file mode 100644 index a2b459f60d..0000000000 --- a/tests/v3/test_codecs/test_codecs.py +++ /dev/null @@ -1,486 +0,0 @@ -from __future__ import annotations - -import json -from dataclasses import dataclass - -import numpy as np -import pytest - -import zarr.v2 -from zarr.abc.codec import Codec -from zarr.abc.store import Store -from zarr.array import Array, AsyncArray -from zarr.buffer import default_buffer_prototype -from zarr.codecs import ( - BytesCodec, - GzipCodec, - ShardingCodec, - TransposeCodec, -) -from zarr.common import MemoryOrder -from zarr.config import config -from zarr.indexing import Selection, morton_order_iter -from zarr.store import StorePath -from zarr.testing.utils import assert_bytes_equal - - -@dataclass(frozen=True) -class _AsyncArrayProxy: - array: AsyncArray - - def __getitem__(self, selection: Selection) -> _AsyncArraySelectionProxy: - return _AsyncArraySelectionProxy(self.array, selection) - - -@dataclass(frozen=True) -class _AsyncArraySelectionProxy: - array: AsyncArray - selection: Selection - - async def get(self) -> np.ndarray: - return await self.array.getitem(self.selection) - - async def set(self, value: np.ndarray) -> None: - return await self.array.setitem(self.selection, value) - - -def order_from_dim(order: MemoryOrder, ndim: int) -> tuple[int, ...]: - if order == "F": - return tuple(ndim - x - 1 for x in range(ndim)) - else: - return tuple(range(ndim)) - - -def test_sharding_pickle() -> None: - """ - Test that sharding codecs can be pickled - """ - pass - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -@pytest.mark.parametrize("input_order", ["F", "C"]) -@pytest.mark.parametrize("store_order", ["F", "C"]) -@pytest.mark.parametrize("runtime_write_order", ["F", "C"]) -@pytest.mark.parametrize("runtime_read_order", ["F", "C"]) -@pytest.mark.parametrize("with_sharding", [True, False]) -async def test_order( - store: Store, - input_order: MemoryOrder, - store_order: MemoryOrder, - runtime_write_order: MemoryOrder, - runtime_read_order: MemoryOrder, - with_sharding: bool, -) -> None: - data = np.arange(0, 256, dtype="uint16").reshape((32, 8), order=input_order) - path = "order" - spath = StorePath(store, path=path) - codecs_: list[Codec] = ( - [ - ShardingCodec( - chunk_shape=(16, 8), - codecs=[TransposeCodec(order=order_from_dim(store_order, data.ndim)), BytesCodec()], - ) - ] - if with_sharding - else [TransposeCodec(order=order_from_dim(store_order, data.ndim)), BytesCodec()] - ) - - with config.set({"array.order": runtime_write_order}): - a = await AsyncArray.create( - spath, - shape=data.shape, - chunk_shape=(32, 8), - dtype=data.dtype, - fill_value=0, - chunk_key_encoding=("v2", "."), - codecs=codecs_, - ) - - await _AsyncArrayProxy(a)[:, :].set(data) - read_data = await _AsyncArrayProxy(a)[:, :].get() - assert np.array_equal(data, read_data) - - with config.set({"array.order": runtime_read_order}): - a = await AsyncArray.open( - spath, - ) - read_data = await _AsyncArrayProxy(a)[:, :].get() - assert np.array_equal(data, read_data) - - if runtime_read_order == "F": - assert read_data.flags["F_CONTIGUOUS"] - assert not read_data.flags["C_CONTIGUOUS"] - else: - assert not read_data.flags["F_CONTIGUOUS"] - assert read_data.flags["C_CONTIGUOUS"] - - if not with_sharding: - # Compare with zarr-python - z = zarr.v2.create( - shape=data.shape, - chunks=(32, 8), - dtype=" None: - data = np.arange(0, 256, dtype="uint16").reshape((16, 16), order=input_order) - path = "order_implicit" - spath = StorePath(store, path) - codecs_: list[Codec] | None = [ShardingCodec(chunk_shape=(8, 8))] if with_sharding else None - - with config.set({"array.order": runtime_write_order}): - a = Array.create( - spath, - shape=data.shape, - chunk_shape=(16, 16), - dtype=data.dtype, - fill_value=0, - codecs=codecs_, - ) - - a[:, :] = data - - with config.set({"array.order": runtime_read_order}): - a = Array.open(spath) - read_data = a[:, :] - assert np.array_equal(data, read_data) - - if runtime_read_order == "F": - assert read_data.flags["F_CONTIGUOUS"] - assert not read_data.flags["C_CONTIGUOUS"] - else: - assert not read_data.flags["F_CONTIGUOUS"] - assert read_data.flags["C_CONTIGUOUS"] - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -def test_open(store: Store) -> None: - spath = StorePath(store) - a = Array.create( - spath, - shape=(16, 16), - chunk_shape=(16, 16), - dtype="int32", - fill_value=0, - ) - b = Array.open(spath) - assert a.metadata == b.metadata - - -def test_morton() -> None: - assert list(morton_order_iter((2, 2))) == [(0, 0), (1, 0), (0, 1), (1, 1)] - assert list(morton_order_iter((2, 2, 2))) == [ - (0, 0, 0), - (1, 0, 0), - (0, 1, 0), - (1, 1, 0), - (0, 0, 1), - (1, 0, 1), - (0, 1, 1), - (1, 1, 1), - ] - assert list(morton_order_iter((2, 2, 2, 2))) == [ - (0, 0, 0, 0), - (1, 0, 0, 0), - (0, 1, 0, 0), - (1, 1, 0, 0), - (0, 0, 1, 0), - (1, 0, 1, 0), - (0, 1, 1, 0), - (1, 1, 1, 0), - (0, 0, 0, 1), - (1, 0, 0, 1), - (0, 1, 0, 1), - (1, 1, 0, 1), - (0, 0, 1, 1), - (1, 0, 1, 1), - (0, 1, 1, 1), - (1, 1, 1, 1), - ] - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -def test_write_partial_chunks(store: Store) -> None: - data = np.arange(0, 256, dtype="uint16").reshape((16, 16)) - spath = StorePath(store) - a = Array.create( - spath, - shape=data.shape, - chunk_shape=(20, 20), - dtype=data.dtype, - fill_value=1, - ) - a[0:16, 0:16] = data - assert np.array_equal(a[0:16, 0:16], data) - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -async def test_delete_empty_chunks(store: Store) -> None: - data = np.ones((16, 16)) - path = "delete_empty_chunks" - spath = StorePath(store, path) - a = await AsyncArray.create( - spath, - shape=data.shape, - chunk_shape=(32, 32), - dtype=data.dtype, - fill_value=1, - ) - await _AsyncArrayProxy(a)[:16, :16].set(np.zeros((16, 16))) - await _AsyncArrayProxy(a)[:16, :16].set(data) - assert np.array_equal(await _AsyncArrayProxy(a)[:16, :16].get(), data) - assert await store.get(f"{path}/c0/0", prototype=default_buffer_prototype()) is None - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -async def test_zarr_compat(store: Store) -> None: - data = np.zeros((16, 18), dtype="uint16") - path = "zarr_compat3" - spath = StorePath(store, path) - a = await AsyncArray.create( - spath, - shape=data.shape, - chunk_shape=(10, 10), - dtype=data.dtype, - chunk_key_encoding=("v2", "."), - fill_value=1, - ) - - z2 = zarr.v2.create( - shape=data.shape, - chunks=(10, 10), - dtype=data.dtype, - compressor=None, - fill_value=1, - ) - - await _AsyncArrayProxy(a)[:16, :18].set(data) - z2[:16, :18] = data - assert np.array_equal(data, await _AsyncArrayProxy(a)[:16, :18].get()) - assert np.array_equal(data, z2[:16, :18]) - - assert_bytes_equal( - z2._store["0.0"], await store.get(f"{path}/0.0", prototype=default_buffer_prototype()) - ) - assert_bytes_equal( - z2._store["0.1"], await store.get(f"{path}/0.1", prototype=default_buffer_prototype()) - ) - assert_bytes_equal( - z2._store["1.0"], await store.get(f"{path}/1.0", prototype=default_buffer_prototype()) - ) - assert_bytes_equal( - z2._store["1.1"], await store.get(f"{path}/1.1", prototype=default_buffer_prototype()) - ) - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -async def test_zarr_compat_F(store: Store) -> None: - data = np.zeros((16, 18), dtype="uint16", order="F") - path = "zarr_compatF3" - spath = StorePath(store, path) - a = await AsyncArray.create( - spath, - shape=data.shape, - chunk_shape=(10, 10), - dtype=data.dtype, - chunk_key_encoding=("v2", "."), - fill_value=1, - codecs=[TransposeCodec(order=order_from_dim("F", data.ndim)), BytesCodec()], - ) - - z2 = zarr.v2.create( - shape=data.shape, - chunks=(10, 10), - dtype=data.dtype, - compressor=None, - order="F", - fill_value=1, - ) - - await _AsyncArrayProxy(a)[:16, :18].set(data) - z2[:16, :18] = data - assert np.array_equal(data, await _AsyncArrayProxy(a)[:16, :18].get()) - assert np.array_equal(data, z2[:16, :18]) - - assert_bytes_equal( - z2._store["0.0"], await store.get(f"{path}/0.0", prototype=default_buffer_prototype()) - ) - assert_bytes_equal( - z2._store["0.1"], await store.get(f"{path}/0.1", prototype=default_buffer_prototype()) - ) - assert_bytes_equal( - z2._store["1.0"], await store.get(f"{path}/1.0", prototype=default_buffer_prototype()) - ) - assert_bytes_equal( - z2._store["1.1"], await store.get(f"{path}/1.1", prototype=default_buffer_prototype()) - ) - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -async def test_dimension_names(store: Store) -> None: - data = np.arange(0, 256, dtype="uint16").reshape((16, 16)) - path = "dimension_names" - spath = StorePath(store, path) - await AsyncArray.create( - spath, - shape=data.shape, - chunk_shape=(16, 16), - dtype=data.dtype, - fill_value=0, - dimension_names=("x", "y"), - ) - - assert (await AsyncArray.open(spath)).metadata.dimension_names == ( - "x", - "y", - ) - path2 = "dimension_names2" - spath2 = StorePath(store, path2) - await AsyncArray.create( - spath2, - shape=data.shape, - chunk_shape=(16, 16), - dtype=data.dtype, - fill_value=0, - ) - - assert (await AsyncArray.open(spath2)).metadata.dimension_names is None - zarr_json_buffer = await store.get(f"{path2}/zarr.json", prototype=default_buffer_prototype()) - assert zarr_json_buffer is not None - assert "dimension_names" not in json.loads(zarr_json_buffer.to_bytes()) - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -def test_invalid_metadata(store: Store) -> None: - spath = StorePath(store, "invalid_metadata") - with pytest.raises(ValueError): - Array.create( - spath, - shape=(16, 16, 16), - chunk_shape=(16, 16), - dtype=np.dtype("uint8"), - fill_value=0, - ) - spath2 = StorePath(store, "invalid_endian") - with pytest.raises(ValueError): - Array.create( - spath2, - shape=(16, 16), - chunk_shape=(16, 16), - dtype=np.dtype("uint8"), - fill_value=0, - codecs=[ - BytesCodec(endian="big"), - TransposeCodec(order=order_from_dim("F", 2)), - ], - ) - spath3 = StorePath(store, "invalid_order") - with pytest.raises(TypeError): - Array.create( - spath3, - shape=(16, 16), - chunk_shape=(16, 16), - dtype=np.dtype("uint8"), - fill_value=0, - codecs=[ - BytesCodec(), - TransposeCodec(order="F"), - ], - ) - spath4 = StorePath(store, "invalid_missing_bytes_codec") - with pytest.raises(ValueError): - Array.create( - spath4, - shape=(16, 16), - chunk_shape=(16, 16), - dtype=np.dtype("uint8"), - fill_value=0, - codecs=[ - TransposeCodec(order=order_from_dim("F", 2)), - ], - ) - spath5 = StorePath(store, "invalid_inner_chunk_shape") - with pytest.raises(ValueError): - Array.create( - spath5, - shape=(16, 16), - chunk_shape=(16, 16), - dtype=np.dtype("uint8"), - fill_value=0, - codecs=[ - ShardingCodec(chunk_shape=(8,)), - ], - ) - spath6 = StorePath(store, "invalid_inner_chunk_shape") - with pytest.raises(ValueError): - Array.create( - spath6, - shape=(16, 16), - chunk_shape=(16, 16), - dtype=np.dtype("uint8"), - fill_value=0, - codecs=[ - ShardingCodec(chunk_shape=(8, 7)), - ], - ) - spath7 = StorePath(store, "warning_inefficient_codecs") - with pytest.warns(UserWarning): - Array.create( - spath7, - shape=(16, 16), - chunk_shape=(16, 16), - dtype=np.dtype("uint8"), - fill_value=0, - codecs=[ - ShardingCodec(chunk_shape=(8, 8)), - GzipCodec(), - ], - ) - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -async def test_resize(store: Store) -> None: - data = np.zeros((16, 18), dtype="uint16") - path = "resize" - spath = StorePath(store, path) - a = await AsyncArray.create( - spath, - shape=data.shape, - chunk_shape=(10, 10), - dtype=data.dtype, - chunk_key_encoding=("v2", "."), - fill_value=1, - ) - - await _AsyncArrayProxy(a)[:16, :18].set(data) - assert await store.get(f"{path}/1.1", prototype=default_buffer_prototype()) is not None - assert await store.get(f"{path}/0.0", prototype=default_buffer_prototype()) is not None - assert await store.get(f"{path}/0.1", prototype=default_buffer_prototype()) is not None - assert await store.get(f"{path}/1.0", prototype=default_buffer_prototype()) is not None - - a = await a.resize((10, 12)) - assert a.metadata.shape == (10, 12) - assert await store.get(f"{path}/0.0", prototype=default_buffer_prototype()) is not None - assert await store.get(f"{path}/0.1", prototype=default_buffer_prototype()) is not None - assert await store.get(f"{path}/1.0", prototype=default_buffer_prototype()) is None - assert await store.get(f"{path}/1.1", prototype=default_buffer_prototype()) is None diff --git a/tests/v3/test_codecs/test_endian.py b/tests/v3/test_codecs/test_endian.py deleted file mode 100644 index 6f3e1c9482..0000000000 --- a/tests/v3/test_codecs/test_endian.py +++ /dev/null @@ -1,87 +0,0 @@ -from typing import Literal - -import numpy as np -import pytest - -import zarr.v2 -from zarr.abc.store import Store -from zarr.array import AsyncArray -from zarr.buffer import default_buffer_prototype -from zarr.codecs import BytesCodec -from zarr.store.core import StorePath -from zarr.testing.utils import assert_bytes_equal - -from .test_codecs import _AsyncArrayProxy - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -@pytest.mark.parametrize("endian", ["big", "little"]) -async def test_endian(store: Store, endian: Literal["big", "little"]) -> None: - data = np.arange(0, 256, dtype="uint16").reshape((16, 16)) - path = "endian" - spath = StorePath(store, path) - a = await AsyncArray.create( - spath, - shape=data.shape, - chunk_shape=(16, 16), - dtype=data.dtype, - fill_value=0, - chunk_key_encoding=("v2", "."), - codecs=[BytesCodec(endian=endian)], - ) - - await _AsyncArrayProxy(a)[:, :].set(data) - readback_data = await _AsyncArrayProxy(a)[:, :].get() - assert np.array_equal(data, readback_data) - - # Compare with v2 - z = zarr.v2.create( - shape=data.shape, - chunks=(16, 16), - dtype=">u2" if endian == "big" else "u2", "u2", " None: - data = np.arange(0, 256, dtype=dtype_input_endian).reshape((16, 16)) - path = "endian" - spath = StorePath(store, path) - a = await AsyncArray.create( - spath, - shape=data.shape, - chunk_shape=(16, 16), - dtype="uint16", - fill_value=0, - chunk_key_encoding=("v2", "."), - codecs=[BytesCodec(endian=dtype_store_endian)], - ) - - await _AsyncArrayProxy(a)[:, :].set(data) - readback_data = await _AsyncArrayProxy(a)[:, :].get() - assert np.array_equal(data, readback_data) - - # Compare with zarr-python - z = zarr.v2.create( - shape=data.shape, - chunks=(16, 16), - dtype=">u2" if dtype_store_endian == "big" else " None: - data = np.arange(0, 256, dtype="uint16").reshape((16, 16)) - - a = Array.create( - StorePath(store), - shape=data.shape, - chunk_shape=(16, 16), - dtype=data.dtype, - fill_value=0, - codecs=[BytesCodec(), GzipCodec()], - ) - - a[:, :] = data - assert np.array_equal(data, a[:, :]) diff --git a/tests/v3/test_codecs/test_sharding.py b/tests/v3/test_codecs/test_sharding.py deleted file mode 100644 index 27667ca9dd..0000000000 --- a/tests/v3/test_codecs/test_sharding.py +++ /dev/null @@ -1,324 +0,0 @@ -import pickle - -import numpy as np -import pytest - -from zarr.abc.store import Store -from zarr.array import Array, AsyncArray -from zarr.buffer import default_buffer_prototype -from zarr.codecs import ( - BloscCodec, - BytesCodec, - ShardingCodec, - ShardingCodecIndexLocation, - TransposeCodec, -) -from zarr.store.core import StorePath - -from ..conftest import ArrayRequest -from .test_codecs import _AsyncArrayProxy, order_from_dim - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -@pytest.mark.parametrize("index_location", ["start", "end"]) -@pytest.mark.parametrize( - "array_fixture", - [ - ArrayRequest(shape=(128,) * 1, dtype="uint8", order="C"), - ArrayRequest(shape=(128,) * 2, dtype="uint8", order="C"), - ArrayRequest(shape=(128,) * 3, dtype="uint16", order="F"), - ], - indirect=["array_fixture"], -) -@pytest.mark.parametrize("offset", [0, 10]) -def test_sharding( - store: Store, array_fixture: np.ndarray, index_location: ShardingCodecIndexLocation, offset: int -) -> None: - """ - Test that we can create an array with a sharding codec, write data to that array, and get - the same data out via indexing. - """ - data = array_fixture - spath = StorePath(store) - arr = Array.create( - spath, - shape=tuple(s + offset for s in data.shape), - chunk_shape=(64,) * data.ndim, - dtype=data.dtype, - fill_value=6, - codecs=[ - ShardingCodec( - chunk_shape=(32,) * data.ndim, - codecs=[ - TransposeCodec(order=order_from_dim("F", data.ndim)), - BytesCodec(), - BloscCodec(cname="lz4"), - ], - index_location=index_location, - ) - ], - ) - write_region = tuple(slice(offset, None) for dim in range(data.ndim)) - arr[write_region] = data - - if offset > 0: - empty_region = tuple(slice(0, offset) for dim in range(data.ndim)) - assert np.all(arr[empty_region] == arr.metadata.fill_value) - - read_data = arr[write_region] - assert data.shape == read_data.shape - assert np.array_equal(data, read_data) - - -@pytest.mark.parametrize("index_location", ["start", "end"]) -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -@pytest.mark.parametrize( - "array_fixture", - [ - ArrayRequest(shape=(128,) * 3, dtype="uint16", order="F"), - ], - indirect=["array_fixture"], -) -def test_sharding_partial( - store: Store, array_fixture: np.ndarray, index_location: ShardingCodecIndexLocation -) -> None: - data = array_fixture - spath = StorePath(store) - a = Array.create( - spath, - shape=tuple(a + 10 for a in data.shape), - chunk_shape=(64, 64, 64), - dtype=data.dtype, - fill_value=0, - codecs=[ - ShardingCodec( - chunk_shape=(32, 32, 32), - codecs=[ - TransposeCodec(order=order_from_dim("F", data.ndim)), - BytesCodec(), - BloscCodec(cname="lz4"), - ], - index_location=index_location, - ) - ], - ) - - a[10:, 10:, 10:] = data - - read_data = a[0:10, 0:10, 0:10] - assert np.all(read_data == 0) - - read_data = a[10:, 10:, 10:] - assert data.shape == read_data.shape - assert np.array_equal(data, read_data) - - -@pytest.mark.parametrize( - "array_fixture", - [ - ArrayRequest(shape=(128,) * 3, dtype="uint16", order="F"), - ], - indirect=["array_fixture"], -) -@pytest.mark.parametrize("index_location", ["start", "end"]) -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -def test_sharding_partial_read( - store: Store, array_fixture: np.ndarray, index_location: ShardingCodecIndexLocation -) -> None: - data = array_fixture - spath = StorePath(store) - a = Array.create( - spath, - shape=tuple(a + 10 for a in data.shape), - chunk_shape=(64, 64, 64), - dtype=data.dtype, - fill_value=1, - codecs=[ - ShardingCodec( - chunk_shape=(32, 32, 32), - codecs=[ - TransposeCodec(order=order_from_dim("F", data.ndim)), - BytesCodec(), - BloscCodec(cname="lz4"), - ], - index_location=index_location, - ) - ], - ) - - read_data = a[0:10, 0:10, 0:10] - assert np.all(read_data == 1) - - -@pytest.mark.parametrize( - "array_fixture", - [ - ArrayRequest(shape=(128,) * 3, dtype="uint16", order="F"), - ], - indirect=["array_fixture"], -) -@pytest.mark.parametrize("index_location", ["start", "end"]) -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -def test_sharding_partial_overwrite( - store: Store, array_fixture: np.ndarray, index_location: ShardingCodecIndexLocation -) -> None: - data = array_fixture[:10, :10, :10] - spath = StorePath(store) - a = Array.create( - spath, - shape=tuple(a + 10 for a in data.shape), - chunk_shape=(64, 64, 64), - dtype=data.dtype, - fill_value=1, - codecs=[ - ShardingCodec( - chunk_shape=(32, 32, 32), - codecs=[ - TransposeCodec(order=order_from_dim("F", data.ndim)), - BytesCodec(), - BloscCodec(cname="lz4"), - ], - index_location=index_location, - ) - ], - ) - - a[:10, :10, :10] = data - - read_data = a[0:10, 0:10, 0:10] - assert np.array_equal(data, read_data) - - data = data + 10 - a[:10, :10, :10] = data - read_data = a[0:10, 0:10, 0:10] - assert np.array_equal(data, read_data) - - -@pytest.mark.parametrize( - "array_fixture", - [ - ArrayRequest(shape=(128,) * 3, dtype="uint16", order="F"), - ], - indirect=["array_fixture"], -) -@pytest.mark.parametrize( - "outer_index_location", - ["start", "end"], -) -@pytest.mark.parametrize( - "inner_index_location", - ["start", "end"], -) -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -def test_nested_sharding( - store: Store, - array_fixture: np.ndarray, - outer_index_location: ShardingCodecIndexLocation, - inner_index_location: ShardingCodecIndexLocation, -) -> None: - data = array_fixture - spath = StorePath(store) - a = Array.create( - spath, - shape=data.shape, - chunk_shape=(64, 64, 64), - dtype=data.dtype, - fill_value=0, - codecs=[ - ShardingCodec( - chunk_shape=(32, 32, 32), - codecs=[ - ShardingCodec(chunk_shape=(16, 16, 16), index_location=inner_index_location) - ], - index_location=outer_index_location, - ) - ], - ) - - a[:, :, :] = data - - read_data = a[0 : data.shape[0], 0 : data.shape[1], 0 : data.shape[2]] - assert data.shape == read_data.shape - assert np.array_equal(data, read_data) - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -def test_open_sharding(store: Store) -> None: - path = "open_sharding" - spath = StorePath(store, path) - a = Array.create( - spath, - shape=(16, 16), - chunk_shape=(16, 16), - dtype="int32", - fill_value=0, - codecs=[ - ShardingCodec( - chunk_shape=(8, 8), - codecs=[ - TransposeCodec(order=order_from_dim("F", 2)), - BytesCodec(), - BloscCodec(), - ], - ) - ], - ) - b = Array.open(spath) - assert a.metadata == b.metadata - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -def test_write_partial_sharded_chunks(store: Store) -> None: - data = np.arange(0, 16 * 16, dtype="uint16").reshape((16, 16)) - spath = StorePath(store) - a = Array.create( - spath, - shape=(40, 40), - chunk_shape=(20, 20), - dtype=data.dtype, - fill_value=1, - codecs=[ - ShardingCodec( - chunk_shape=(10, 10), - codecs=[ - BytesCodec(), - BloscCodec(), - ], - ) - ], - ) - a[0:16, 0:16] = data - assert np.array_equal(a[0:16, 0:16], data) - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -async def test_delete_empty_shards(store: Store) -> None: - path = "delete_empty_shards" - spath = StorePath(store, path) - a = await AsyncArray.create( - spath, - shape=(16, 16), - chunk_shape=(8, 16), - dtype="uint16", - fill_value=1, - codecs=[ShardingCodec(chunk_shape=(8, 8))], - ) - await _AsyncArrayProxy(a)[:, :].set(np.zeros((16, 16))) - await _AsyncArrayProxy(a)[8:, :].set(np.ones((8, 16))) - await _AsyncArrayProxy(a)[:, 8:].set(np.ones((16, 8))) - # chunk (0, 0) is full - # chunks (0, 1), (1, 0), (1, 1) are empty - # shard (0, 0) is half-full - # shard (1, 0) is empty - - data = np.ones((16, 16), dtype="uint16") - data[:8, :8] = 0 - assert np.array_equal(data, await _AsyncArrayProxy(a)[:, :].get()) - assert await store.get(f"{path}/c/1/0", prototype=default_buffer_prototype()) is None - chunk_bytes = await store.get(f"{path}/c/0/0", prototype=default_buffer_prototype()) - assert chunk_bytes is not None and len(chunk_bytes) == 16 * 2 + 8 * 8 * 2 + 4 - - -def test_pickle() -> None: - codec = ShardingCodec(chunk_shape=(8, 8)) - assert pickle.loads(pickle.dumps(codec)) == codec diff --git a/tests/v3/test_codecs/test_transpose.py b/tests/v3/test_codecs/test_transpose.py deleted file mode 100644 index bea7435122..0000000000 --- a/tests/v3/test_codecs/test_transpose.py +++ /dev/null @@ -1,121 +0,0 @@ -import numpy as np -import pytest - -import zarr.v2 -from zarr.abc.codec import Codec -from zarr.abc.store import Store -from zarr.array import Array, AsyncArray -from zarr.buffer import default_buffer_prototype -from zarr.codecs import BytesCodec, ShardingCodec, TransposeCodec -from zarr.common import MemoryOrder -from zarr.config import config -from zarr.store.core import StorePath - -from .test_codecs import _AsyncArrayProxy - - -@pytest.mark.parametrize("input_order", ["F", "C"]) -@pytest.mark.parametrize("runtime_write_order", ["F", "C"]) -@pytest.mark.parametrize("runtime_read_order", ["F", "C"]) -@pytest.mark.parametrize("with_sharding", [True, False]) -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -async def test_transpose( - store: Store, - input_order: MemoryOrder, - runtime_write_order: MemoryOrder, - runtime_read_order: MemoryOrder, - with_sharding: bool, -) -> None: - data = np.arange(0, 256, dtype="uint16").reshape((1, 32, 8), order=input_order) - spath = StorePath(store, path="transpose") - codecs_: list[Codec] = ( - [ - ShardingCodec( - chunk_shape=(1, 16, 8), - codecs=[TransposeCodec(order=(2, 1, 0)), BytesCodec()], - ) - ] - if with_sharding - else [TransposeCodec(order=(2, 1, 0)), BytesCodec()] - ) - with config.set({"array.order": runtime_write_order}): - a = await AsyncArray.create( - spath, - shape=data.shape, - chunk_shape=(1, 32, 8), - dtype=data.dtype, - fill_value=0, - chunk_key_encoding=("v2", "."), - codecs=codecs_, - ) - - await _AsyncArrayProxy(a)[:, :].set(data) - read_data = await _AsyncArrayProxy(a)[:, :].get() - assert np.array_equal(data, read_data) - - with config.set({"array.order": runtime_read_order}): - a = await AsyncArray.open( - spath, - ) - read_data = await _AsyncArrayProxy(a)[:, :].get() - assert np.array_equal(data, read_data) - - if runtime_read_order == "F": - assert read_data.flags["F_CONTIGUOUS"] - assert not read_data.flags["C_CONTIGUOUS"] - else: - assert not read_data.flags["F_CONTIGUOUS"] - assert read_data.flags["C_CONTIGUOUS"] - - if not with_sharding: - # Compare with zarr-python - z = zarr.v2.create( - shape=data.shape, - chunks=(1, 32, 8), - dtype=" None: - shape = [i + 3 for i in range(len(order))] - data = np.arange(0, np.prod(shape), dtype="uint16").reshape(shape) - spath = StorePath(store, "transpose_non_self_inverse") - a = Array.create( - spath, - shape=data.shape, - chunk_shape=data.shape, - dtype=data.dtype, - fill_value=0, - codecs=[TransposeCodec(order=order), BytesCodec()], - ) - a[:, :] = data - read_data = a[:, :] - assert np.array_equal(data, read_data) - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -def test_transpose_invalid( - store: Store, -) -> None: - data = np.arange(0, 256, dtype="uint16").reshape((1, 32, 8)) - spath = StorePath(store, "transpose_invalid") - for order in [(1, 0), (3, 2, 1), (3, 3, 1)]: - with pytest.raises(ValueError): - Array.create( - spath, - shape=data.shape, - chunk_shape=(1, 32, 8), - dtype=data.dtype, - fill_value=0, - chunk_key_encoding=("v2", "."), - codecs=[TransposeCodec(order=order), BytesCodec()], - ) diff --git a/tests/v3/test_codecs/test_zstd.py b/tests/v3/test_codecs/test_zstd.py deleted file mode 100644 index 1e1b1e02c9..0000000000 --- a/tests/v3/test_codecs/test_zstd.py +++ /dev/null @@ -1,25 +0,0 @@ -import numpy as np -import pytest - -from zarr.abc.store import Store -from zarr.array import Array -from zarr.codecs import BytesCodec, ZstdCodec -from zarr.store.core import StorePath - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -@pytest.mark.parametrize("checksum", [True, False]) -def test_zstd(store: Store, checksum: bool) -> None: - data = np.arange(0, 256, dtype="uint16").reshape((16, 16)) - - a = Array.create( - StorePath(store, path="zstd"), - shape=data.shape, - chunk_shape=(16, 16), - dtype=data.dtype, - fill_value=0, - codecs=[BytesCodec(), ZstdCodec(level=0, checksum=checksum)], - ) - - a[:, :] = data - assert np.array_equal(data, a[:, :]) diff --git a/tests/v3/test_common.py b/tests/v3/test_common.py deleted file mode 100644 index bb59789843..0000000000 --- a/tests/v3/test_common.py +++ /dev/null @@ -1,118 +0,0 @@ -from __future__ import annotations - -from collections.abc import Iterable -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from typing import Any, Literal - -import numpy as np -import pytest - -from zarr.common import parse_name, parse_shapelike, product -from zarr.config import parse_indexing_order - - -@pytest.mark.parametrize("data", [(0, 0, 0, 0), (1, 3, 4, 5, 6), (2, 4)]) -def test_product(data: tuple[int, ...]) -> None: - assert product(data) == np.prod(data) - - -# todo: test -def test_concurrent_map() -> None: ... - - -# todo: test -def test_to_thread() -> None: ... - - -# todo: test -def test_enum_names() -> None: ... - - -# todo: test -def test_parse_enum() -> None: ... - - -@pytest.mark.parametrize("data", [("foo", "bar"), (10, 11)]) -def test_parse_name_invalid(data: tuple[Any, Any]) -> None: - observed, expected = data - if isinstance(observed, str): - with pytest.raises(ValueError, match=f"Expected '{expected}'. Got {observed} instead."): - parse_name(observed, expected) - else: - with pytest.raises( - TypeError, match=f"Expected a string, got an instance of {type(observed)}." - ): - parse_name(observed, expected) - - -@pytest.mark.parametrize("data", [("foo", "foo"), ("10", "10")]) -def test_parse_name_valid(data: tuple[Any, Any]) -> None: - observed, expected = data - assert parse_name(observed, expected) == observed - - -@pytest.mark.parametrize("data", [0, 1, "hello", "f"]) -def test_parse_indexing_order_invalid(data: Any) -> None: - with pytest.raises(ValueError, match="Expected one of"): - parse_indexing_order(data) - - -@pytest.mark.parametrize("data", ["C", "F"]) -def parse_indexing_order_valid(data: Literal["C", "F"]) -> None: - assert parse_indexing_order(data) == data - - -@pytest.mark.parametrize("data", [lambda v: v, slice(None)]) -def test_parse_shapelike_invalid_single_type(data: Any) -> None: - """ - Test that we get the expected error message when passing in a value that is not an integer - or an iterable of integers. - """ - with pytest.raises(TypeError, match="Expected an integer or an iterable of integers."): - parse_shapelike(data) - - -def test_parse_shapelike_invalid_single_value() -> None: - """ - Test that we get the expected error message when passing in a negative integer. - """ - with pytest.raises(ValueError, match="Expected a non-negative integer."): - parse_shapelike(-1) - - -@pytest.mark.parametrize("data", ["shape", ("0", 1, 2, 3), {"0": "0"}, ((1, 2), (2, 2)), (4.0, 2)]) -def test_parse_shapelike_invalid_iterable_types(data: Any) -> None: - """ - Test that we get the expected error message when passing in an iterable containing - non-integer elements - """ - with pytest.raises(TypeError, match="Expected an iterable of integers"): - parse_shapelike(data) - - -@pytest.mark.parametrize("data", [(1, 2, 3, -1), (-10,)]) -def test_parse_shapelike_invalid_iterable_values(data: Any) -> None: - """ - Test that we get the expected error message when passing in an iterable containing negative - integers - """ - with pytest.raises(ValueError, match="Expected all values to be non-negative."): - parse_shapelike(data) - - -@pytest.mark.parametrize("data", [range(10), [0, 1, 2, 3], (3, 4, 5), ()]) -def test_parse_shapelike_valid(data: Iterable[int]) -> None: - assert parse_shapelike(data) == tuple(data) - - -# todo: more dtypes -@pytest.mark.parametrize("data", [("uint8", np.uint8), ("float64", np.float64)]) -def parse_dtype(data: tuple[str, np.dtype]) -> None: - unparsed, parsed = data - assert parse_dtype(unparsed) == parsed - - -# todo: figure out what it means to test this -def test_parse_fill_value() -> None: ... diff --git a/tests/v3/test_config.py b/tests/v3/test_config.py deleted file mode 100644 index 8e7b868520..0000000000 --- a/tests/v3/test_config.py +++ /dev/null @@ -1,228 +0,0 @@ -import os -from collections.abc import Iterable -from typing import Any -from unittest import mock -from unittest.mock import Mock - -import numpy as np -import pytest - -import zarr -from zarr import Array, zeros -from zarr.abc.codec import CodecInput, CodecOutput, CodecPipeline -from zarr.abc.store import ByteSetter -from zarr.array_spec import ArraySpec -from zarr.buffer import NDBuffer -from zarr.codecs import BatchedCodecPipeline, BloscCodec, BytesCodec, Crc32cCodec, ShardingCodec -from zarr.config import BadConfigError, config -from zarr.indexing import SelectorTuple -from zarr.registry import ( - fully_qualified_name, - get_buffer_class, - get_codec_class, - get_ndbuffer_class, - get_pipeline_class, - register_buffer, - register_codec, - register_ndbuffer, - register_pipeline, -) -from zarr.testing.buffer import ( - NDBufferUsingTestNDArrayLike, - StoreExpectingTestBuffer, - TestBuffer, - TestNDArrayLike, -) - - -def test_config_defaults_set() -> None: - # regression test for available defaults - assert config.defaults == [ - { - "array": {"order": "C"}, - "async": {"concurrency": None, "timeout": None}, - "json_indent": 2, - "codec_pipeline": { - "path": "zarr.codecs.pipeline.BatchedCodecPipeline", - "batch_size": 1, - }, - "buffer": "zarr.buffer.Buffer", - "ndbuffer": "zarr.buffer.NDBuffer", - "codecs": { - "blosc": "zarr.codecs.blosc.BloscCodec", - "gzip": "zarr.codecs.gzip.GzipCodec", - "zstd": "zarr.codecs.zstd.ZstdCodec", - "bytes": "zarr.codecs.bytes.BytesCodec", - "endian": "zarr.codecs.bytes.BytesCodec", - "crc32c": "zarr.codecs.crc32c_.Crc32cCodec", - "sharding_indexed": "zarr.codecs.sharding.ShardingCodec", - "transpose": "zarr.codecs.transpose.TransposeCodec", - }, - } - ] - assert config.get("array.order") == "C" - assert config.get("async.concurrency") is None - assert config.get("async.timeout") is None - assert config.get("codec_pipeline.batch_size") == 1 - assert config.get("json_indent") == 2 - - -@pytest.mark.parametrize( - "key, old_val, new_val", - [("array.order", "C", "F"), ("async.concurrency", None, 10), ("json_indent", 2, 0)], -) -def test_config_defaults_can_be_overridden(key: str, old_val: Any, new_val: Any) -> None: - assert config.get(key) == old_val - with config.set({key: new_val}): - assert config.get(key) == new_val - - -def test_fully_qualified_name(): - class MockClass: - pass - - assert "v3.test_config.test_fully_qualified_name..MockClass" == fully_qualified_name( - MockClass - ) - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -def test_config_codec_pipeline_class(store): - # has default value - assert get_pipeline_class().__name__ != "" - - config.set({"codec_pipeline.name": "zarr.codecs.pipeline.BatchedCodecPipeline"}) - assert get_pipeline_class() == zarr.codecs.pipeline.BatchedCodecPipeline - - _mock = Mock() - - class MockCodecPipeline(BatchedCodecPipeline): - async def write( - self, - batch_info: Iterable[tuple[ByteSetter, ArraySpec, SelectorTuple, SelectorTuple]], - value: NDBuffer, - drop_axes: tuple[int, ...] = (), - ) -> None: - _mock.call() - - register_pipeline(MockCodecPipeline) - config.set({"codec_pipeline.path": fully_qualified_name(MockCodecPipeline)}) - - assert get_pipeline_class() == MockCodecPipeline - - # test if codec is used - arr = Array.create( - store=store, - shape=(100,), - chunks=(10,), - zarr_format=3, - dtype="i4", - ) - arr[:] = range(100) - - _mock.call.assert_called() - - with pytest.raises(BadConfigError): - config.set({"codec_pipeline.path": "wrong_name"}) - get_pipeline_class() - - class MockEnvCodecPipeline(CodecPipeline): - pass - - register_pipeline(MockEnvCodecPipeline) - - with mock.patch.dict( - os.environ, {"ZARR_CODEC_PIPELINE__PATH": fully_qualified_name(MockEnvCodecPipeline)} - ): - assert get_pipeline_class(reload_config=True) == MockEnvCodecPipeline - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -def test_config_codec_implementation(store): - # has default value - assert fully_qualified_name(get_codec_class("blosc")) == config.defaults[0]["codecs"]["blosc"] - - _mock = Mock() - - class MockBloscCodec(BloscCodec): - async def _encode_single( - self, chunk_data: CodecInput, chunk_spec: ArraySpec - ) -> CodecOutput | None: - _mock.call() - - config.set({"codecs.blosc": fully_qualified_name(MockBloscCodec)}) - register_codec("blosc", MockBloscCodec) - assert get_codec_class("blosc") == MockBloscCodec - - # test if codec is used - arr = Array.create( - store=store, - shape=(100,), - chunks=(10,), - zarr_format=3, - dtype="i4", - codecs=[BytesCodec(), {"name": "blosc", "configuration": {}}], - ) - arr[:] = range(100) - _mock.call.assert_called() - - with mock.patch.dict(os.environ, {"ZARR_CODECS__BLOSC": fully_qualified_name(BloscCodec)}): - assert get_codec_class("blosc", reload_config=True) == BloscCodec - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -def test_config_ndbuffer_implementation(store): - # has default value - assert fully_qualified_name(get_ndbuffer_class()) == config.defaults[0]["ndbuffer"] - - # set custom ndbuffer with TestNDArrayLike implementation - register_ndbuffer(NDBufferUsingTestNDArrayLike) - config.set({"ndbuffer": fully_qualified_name(NDBufferUsingTestNDArrayLike)}) - assert get_ndbuffer_class() == NDBufferUsingTestNDArrayLike - arr = Array.create( - store=store, - shape=(100,), - chunks=(10,), - zarr_format=3, - dtype="i4", - ) - got = arr[:] - print(type(got)) - assert isinstance(got, TestNDArrayLike) - - -def test_config_buffer_implementation(): - # has default value - assert fully_qualified_name(get_buffer_class()) == config.defaults[0]["buffer"] - - arr = zeros(shape=(100), store=StoreExpectingTestBuffer(mode="w")) - - # AssertionError of StoreExpectingTestBuffer when not using my buffer - with pytest.raises(AssertionError): - arr[:] = np.arange(100) - - register_buffer(TestBuffer) - config.set({"buffer": fully_qualified_name(TestBuffer)}) - assert get_buffer_class() == TestBuffer - - # no error using TestBuffer - data = np.arange(100) - arr[:] = np.arange(100) - assert np.array_equal(arr[:], data) - - data2d = np.arange(1000).reshape(100, 10) - arr_sharding = zeros( - shape=(100, 10), - store=StoreExpectingTestBuffer(mode="w"), - codecs=[ShardingCodec(chunk_shape=(10, 10))], - ) - arr_sharding[:] = data2d - assert np.array_equal(arr_sharding[:], data2d) - - arr_Crc32c = zeros( - shape=(100, 10), - store=StoreExpectingTestBuffer(mode="w"), - codecs=[BytesCodec(), Crc32cCodec()], - ) - arr_Crc32c[:] = data2d - assert np.array_equal(arr_Crc32c[:], data2d) diff --git a/tests/v3/test_group.py b/tests/v3/test_group.py deleted file mode 100644 index daa5979b27..0000000000 --- a/tests/v3/test_group.py +++ /dev/null @@ -1,655 +0,0 @@ -from __future__ import annotations - -from typing import Any, Literal, cast - -import numpy as np -import pytest -from _pytest.compat import LEGACY_PATH - -from zarr.array import Array, AsyncArray -from zarr.buffer import Buffer -from zarr.common import ZarrFormat -from zarr.errors import ContainsArrayError, ContainsGroupError -from zarr.group import AsyncGroup, Group, GroupMetadata -from zarr.store import LocalStore, MemoryStore, StorePath -from zarr.store.core import make_store_path -from zarr.sync import sync - -from .conftest import parse_store - - -@pytest.fixture(params=["local", "memory"]) -async def store(request: pytest.FixtureRequest, tmpdir: LEGACY_PATH) -> LocalStore | MemoryStore: - result = await parse_store(request.param, str(tmpdir)) - if not isinstance(result, MemoryStore | LocalStore): - raise TypeError("Wrong store class returned by test fixture! got " + result + " instead") - return result - - -@pytest.fixture(params=[True, False]) -def exists_ok(request: pytest.FixtureRequest) -> bool: - result = request.param - if not isinstance(result, bool): - raise TypeError("Wrong type returned by test fixture.") - return result - - -@pytest.fixture(params=[2, 3], ids=["zarr2", "zarr3"]) -def zarr_format(request: pytest.FixtureRequest) -> ZarrFormat: - result = request.param - if result not in (2, 3): - raise ValueError("Wrong value returned from test fixture.") - return cast(ZarrFormat, result) - - -def test_group_init(store: LocalStore | MemoryStore, zarr_format: ZarrFormat) -> None: - """ - Test that initializing a group from an asyncgroup works. - """ - agroup = sync(AsyncGroup.create(store=store, zarr_format=zarr_format)) - group = Group(agroup) - assert group._async_group == agroup - - -def test_group_name_properties(store: LocalStore | MemoryStore, zarr_format: ZarrFormat) -> None: - """ - Test basic properties of groups - """ - root = Group.create(store=store, zarr_format=zarr_format) - assert root.path == "" - assert root.name == "/" - assert root.basename == "" - - foo = root.create_group("foo") - assert foo.path == "foo" - assert foo.name == "/foo" - assert foo.basename == "foo" - - bar = root.create_group("foo/bar") - assert bar.path == "foo/bar" - assert bar.name == "/foo/bar" - assert bar.basename == "bar" - - -def test_group_members(store: MemoryStore | LocalStore, zarr_format: ZarrFormat) -> None: - """ - Test that `Group.members` returns correct values, i.e. the arrays and groups - (explicit and implicit) contained in that group. - """ - - path = "group" - agroup = AsyncGroup( - metadata=GroupMetadata(zarr_format=zarr_format), - store_path=StorePath(store=store, path=path), - ) - group = Group(agroup) - members_expected: dict[str, Array | Group] = {} - - members_expected["subgroup"] = group.create_group("subgroup") - # make a sub-sub-subgroup, to ensure that the children calculation doesn't go - # too deep in the hierarchy - _ = members_expected["subgroup"].create_group("subsubgroup") # type: ignore - - members_expected["subarray"] = group.create_array( - "subarray", shape=(100,), dtype="uint8", chunk_shape=(10,), exists_ok=True - ) - - # add an extra object to the domain of the group. - # the list of children should ignore this object. - sync(store.set(f"{path}/extra_object-1", Buffer.from_bytes(b"000000"))) - # add an extra object under a directory-like prefix in the domain of the group. - # this creates a directory with a random key in it - # this should not show up as a member - sync(store.set(f"{path}/extra_directory/extra_object-2", Buffer.from_bytes(b"000000"))) - members_observed = group.members - # members are not guaranteed to be ordered, so sort before comparing - assert sorted(dict(members_observed)) == sorted(members_expected) - - -def test_group(store: MemoryStore | LocalStore, zarr_format: ZarrFormat) -> None: - """ - Test basic Group routines. - """ - store_path = StorePath(store) - agroup = AsyncGroup(metadata=GroupMetadata(zarr_format=zarr_format), store_path=store_path) - group = Group(agroup) - assert agroup.metadata is group.metadata - assert agroup.store_path == group.store_path == store_path - - # create two groups - foo = group.create_group("foo") - bar = foo.create_group("bar", attributes={"baz": "qux"}) - - # create an array from the "bar" group - data = np.arange(0, 4 * 4, dtype="uint16").reshape((4, 4)) - arr = bar.create_array( - "baz", shape=data.shape, dtype=data.dtype, chunk_shape=(2, 2), exists_ok=True - ) - arr[:] = data - - # check the array - assert arr == bar["baz"] - assert arr.shape == data.shape - assert arr.dtype == data.dtype - - # TODO: update this once the array api settles down - assert arr.chunks == (2, 2) - - bar2 = foo["bar"] - assert dict(bar2.attrs) == {"baz": "qux"} - - # update a group's attributes - bar2.attrs.update({"name": "bar"}) - # bar.attrs was modified in-place - assert dict(bar2.attrs) == {"baz": "qux", "name": "bar"} - - # and the attrs were modified in the store - bar3 = foo["bar"] - assert dict(bar3.attrs) == {"baz": "qux", "name": "bar"} - - -def test_group_create( - store: MemoryStore | LocalStore, exists_ok: bool, zarr_format: ZarrFormat -) -> None: - """ - Test that `Group.create` works as expected. - """ - attributes = {"foo": 100} - group = Group.create(store, attributes=attributes, zarr_format=zarr_format, exists_ok=exists_ok) - - assert group.attrs == attributes - - if not exists_ok: - with pytest.raises(ContainsGroupError): - group = Group.create( - store, attributes=attributes, exists_ok=exists_ok, zarr_format=zarr_format - ) - - -def test_group_open( - store: MemoryStore | LocalStore, zarr_format: ZarrFormat, exists_ok: bool -) -> None: - """ - Test the `Group.open` method. - """ - spath = StorePath(store) - # attempt to open a group that does not exist - with pytest.raises(FileNotFoundError): - Group.open(store) - - # create the group - attrs = {"path": "foo"} - group_created = Group.create( - store, attributes=attrs, zarr_format=zarr_format, exists_ok=exists_ok - ) - assert group_created.attrs == attrs - assert group_created.metadata.zarr_format == zarr_format - assert group_created.store_path == spath - - # attempt to create a new group in place, to test exists_ok - new_attrs = {"path": "bar"} - if not exists_ok: - with pytest.raises(ContainsGroupError): - Group.create(store, attributes=attrs, zarr_format=zarr_format, exists_ok=exists_ok) - else: - group_created_again = Group.create( - store, attributes=new_attrs, zarr_format=zarr_format, exists_ok=exists_ok - ) - assert group_created_again.attrs == new_attrs - assert group_created_again.metadata.zarr_format == zarr_format - assert group_created_again.store_path == spath - - -def test_group_getitem(store: MemoryStore | LocalStore, zarr_format: ZarrFormat) -> None: - """ - Test the `Group.__getitem__` method. - """ - - group = Group.create(store, zarr_format=zarr_format) - subgroup = group.create_group(name="subgroup") - subarray = group.create_array(name="subarray", shape=(10,), chunk_shape=(10,)) - - assert group["subgroup"] == subgroup - assert group["subarray"] == subarray - with pytest.raises(KeyError): - group["nope"] - - -def test_group_delitem(store: MemoryStore | LocalStore, zarr_format: ZarrFormat) -> None: - """ - Test the `Group.__delitem__` method. - """ - - group = Group.create(store, zarr_format=zarr_format) - subgroup = group.create_group(name="subgroup") - subarray = group.create_array(name="subarray", shape=(10,), chunk_shape=(10,)) - - assert group["subgroup"] == subgroup - assert group["subarray"] == subarray - - del group["subgroup"] - with pytest.raises(KeyError): - group["subgroup"] - - del group["subarray"] - with pytest.raises(KeyError): - group["subarray"] - - -def test_group_iter(store: MemoryStore | LocalStore, zarr_format: ZarrFormat) -> None: - """ - Test the `Group.__iter__` method. - """ - - group = Group.create(store, zarr_format=zarr_format) - with pytest.raises(NotImplementedError): - [x for x in group] # type: ignore - - -def test_group_len(store: MemoryStore | LocalStore, zarr_format: ZarrFormat) -> None: - """ - Test the `Group.__len__` method. - """ - - group = Group.create(store, zarr_format=zarr_format) - with pytest.raises(NotImplementedError): - len(group) # type: ignore - - -def test_group_setitem(store: MemoryStore | LocalStore, zarr_format: ZarrFormat) -> None: - """ - Test the `Group.__setitem__` method. - """ - group = Group.create(store, zarr_format=zarr_format) - with pytest.raises(NotImplementedError): - group["key"] = 10 - - -def test_group_contains(store: MemoryStore | LocalStore, zarr_format: ZarrFormat) -> None: - """ - Test the `Group.__contains__` method - """ - group = Group.create(store, zarr_format=zarr_format) - assert "foo" not in group - _ = group.create_group(name="foo") - assert "foo" in group - - -def test_group_subgroups(store: MemoryStore | LocalStore, zarr_format: ZarrFormat) -> None: - """ - Test the behavior of `Group` methods for accessing subgroups, namely `Group.group_keys` and `Group.groups` - """ - group = Group.create(store, zarr_format=zarr_format) - keys = ("foo", "bar") - subgroups_expected = tuple(group.create_group(k) for k in keys) - # create a sub-array as well - _ = group.create_array("array", shape=(10,)) - subgroups_observed = group.groups() - assert set(group.group_keys()) == set(keys) - assert len(subgroups_observed) == len(subgroups_expected) - assert all(a in subgroups_observed for a in subgroups_expected) - - -def test_group_subarrays(store: MemoryStore | LocalStore, zarr_format: ZarrFormat) -> None: - """ - Test the behavior of `Group` methods for accessing subgroups, namely `Group.group_keys` and `Group.groups` - """ - group = Group.create(store, zarr_format=zarr_format) - keys = ("foo", "bar") - subarrays_expected = tuple(group.create_array(k, shape=(10,)) for k in keys) - # create a sub-group as well - _ = group.create_group("group") - subarrays_observed = group.arrays() - assert set(group.array_keys()) == set(keys) - assert len(subarrays_observed) == len(subarrays_expected) - assert all(a in subarrays_observed for a in subarrays_expected) - - -def test_group_update_attributes(store: MemoryStore | LocalStore, zarr_format: ZarrFormat) -> None: - """ - Test the behavior of `Group.update_attributes` - """ - attrs = {"foo": 100} - group = Group.create(store, zarr_format=zarr_format, attributes=attrs) - assert group.attrs == attrs - new_attrs = {"bar": 100} - new_group = group.update_attributes(new_attrs) - assert new_group.attrs == new_attrs - - -async def test_group_update_attributes_async( - store: MemoryStore | LocalStore, zarr_format: ZarrFormat -) -> None: - """ - Test the behavior of `Group.update_attributes_async` - """ - attrs = {"foo": 100} - group = Group.create(store, zarr_format=zarr_format, attributes=attrs) - assert group.attrs == attrs - new_attrs = {"bar": 100} - new_group = await group.update_attributes_async(new_attrs) - assert new_group.attrs == new_attrs - - -@pytest.mark.parametrize("method", ["create_array", "array"]) -def test_group_create_array( - store: MemoryStore | LocalStore, - zarr_format: ZarrFormat, - exists_ok: bool, - method: Literal["create_array", "array"], -) -> None: - """ - Test `Group.create_array` - """ - group = Group.create(store, zarr_format=zarr_format) - shape = (10, 10) - dtype = "uint8" - data = np.arange(np.prod(shape)).reshape(shape).astype(dtype) - - if method == "create_array": - array = group.create_array(name="array", shape=shape, dtype=dtype, data=data) - elif method == "array": - array = group.array(name="array", shape=shape, dtype=dtype, data=data) - else: - raise AssertionError - - if not exists_ok: - if method == "create_array": - with pytest.raises(ContainsArrayError): - group.create_array(name="array", shape=shape, dtype=dtype, data=data) - elif method == "array": - with pytest.raises(ContainsArrayError): - group.array(name="array", shape=shape, dtype=dtype, data=data) - assert array.shape == shape - assert array.dtype == np.dtype(dtype) - assert np.array_equal(array[:], data) - - -@pytest.mark.parametrize("store", ("local", "memory"), indirect=["store"]) -@pytest.mark.parametrize("zarr_format", (2, 3)) -@pytest.mark.parametrize("exists_ok", [True, False]) -@pytest.mark.parametrize("extant_node", ["array", "group"]) -def test_group_creation_existing_node( - store: LocalStore | MemoryStore, - zarr_format: ZarrFormat, - exists_ok: bool, - extant_node: Literal["array", "group"], -) -> None: - """ - Check that an existing array or group is handled as expected during group creation. - """ - spath = StorePath(store) - group = Group.create(spath, zarr_format=zarr_format) - expected_exception: type[ContainsArrayError] | type[ContainsGroupError] - attributes = {"old": True} - - if extant_node == "array": - expected_exception = ContainsArrayError - _ = group.create_array("extant", shape=(10,), dtype="uint8", attributes=attributes) - elif extant_node == "group": - expected_exception = ContainsGroupError - _ = group.create_group("extant", attributes=attributes) - else: - raise AssertionError - - new_attributes = {"new": True} - - if exists_ok: - node_new = Group.create( - spath / "extant", - attributes=new_attributes, - zarr_format=zarr_format, - exists_ok=exists_ok, - ) - assert node_new.attrs == new_attributes - else: - with pytest.raises(expected_exception): - node_new = Group.create( - spath / "extant", - attributes=new_attributes, - zarr_format=zarr_format, - exists_ok=exists_ok, - ) - - -async def test_asyncgroup_create( - store: MemoryStore | LocalStore, - exists_ok: bool, - zarr_format: ZarrFormat, -) -> None: - """ - Test that `AsyncGroup.create` works as expected. - """ - spath = StorePath(store=store) - attributes = {"foo": 100} - agroup = await AsyncGroup.create( - store, - attributes=attributes, - exists_ok=exists_ok, - zarr_format=zarr_format, - ) - - assert agroup.metadata == GroupMetadata(zarr_format=zarr_format, attributes=attributes) - assert agroup.store_path == await make_store_path(store) - - if not exists_ok: - with pytest.raises(ContainsGroupError): - agroup = await AsyncGroup.create( - spath, - attributes=attributes, - exists_ok=exists_ok, - zarr_format=zarr_format, - ) - # create an array at our target path - collision_name = "foo" - _ = await AsyncArray.create( - spath / collision_name, shape=(10,), dtype="uint8", zarr_format=zarr_format - ) - with pytest.raises(ContainsArrayError): - _ = await AsyncGroup.create( - StorePath(store=store) / collision_name, - attributes=attributes, - exists_ok=exists_ok, - zarr_format=zarr_format, - ) - - -async def test_asyncgroup_attrs(store: LocalStore | MemoryStore, zarr_format: ZarrFormat) -> None: - attributes = {"foo": 100} - agroup = await AsyncGroup.create(store, zarr_format=zarr_format, attributes=attributes) - - assert agroup.attrs == agroup.metadata.attributes == attributes - - -async def test_asyncgroup_info(store: LocalStore | MemoryStore, zarr_format: ZarrFormat) -> None: - agroup = await AsyncGroup.create( # noqa - store, - zarr_format=zarr_format, - ) - pytest.xfail("Info is not implemented for metadata yet") - # assert agroup.info == agroup.metadata.info - - -async def test_asyncgroup_open( - store: LocalStore | MemoryStore, - zarr_format: ZarrFormat, -) -> None: - """ - Create an `AsyncGroup`, then ensure that we can open it using `AsyncGroup.open` - """ - attributes = {"foo": 100} - group_w = await AsyncGroup.create( - store=store, - attributes=attributes, - exists_ok=False, - zarr_format=zarr_format, - ) - - group_r = await AsyncGroup.open(store=store, zarr_format=zarr_format) - - assert group_w.attrs == group_w.attrs == attributes - assert group_w == group_r - - -async def test_asyncgroup_open_wrong_format( - store: LocalStore | MemoryStore, - zarr_format: ZarrFormat, -) -> None: - _ = await AsyncGroup.create(store=store, exists_ok=False, zarr_format=zarr_format) - zarr_format_wrong: ZarrFormat - # try opening with the wrong zarr format - if zarr_format == 3: - zarr_format_wrong = 2 - elif zarr_format == 2: - zarr_format_wrong = 3 - else: - raise AssertionError - - with pytest.raises(FileNotFoundError): - await AsyncGroup.open(store=store, zarr_format=zarr_format_wrong) - - -# todo: replace the dict[str, Any] type with something a bit more specific -# should this be async? -@pytest.mark.parametrize( - "data", - ( - {"zarr_format": 3, "node_type": "group", "attributes": {"foo": 100}}, - {"zarr_format": 2, "attributes": {"foo": 100}}, - ), -) -def test_asyncgroup_from_dict(store: MemoryStore | LocalStore, data: dict[str, Any]) -> None: - """ - Test that we can create an AsyncGroup from a dict - """ - path = "test" - store_path = StorePath(store=store, path=path) - group = AsyncGroup.from_dict(store_path, data=data) - - assert group.metadata.zarr_format == data["zarr_format"] - assert group.metadata.attributes == data["attributes"] - - -# todo: replace this with a declarative API where we model a full hierarchy - - -async def test_asyncgroup_getitem(store: LocalStore | MemoryStore, zarr_format: ZarrFormat) -> None: - """ - Create an `AsyncGroup`, then create members of that group, and ensure that we can access those - members via the `AsyncGroup.getitem` method. - """ - agroup = await AsyncGroup.create(store=store, zarr_format=zarr_format) - - sub_array_path = "sub_array" - sub_array = await agroup.create_array( - path=sub_array_path, shape=(10,), dtype="uint8", chunk_shape=(2,) - ) - assert await agroup.getitem(sub_array_path) == sub_array - - sub_group_path = "sub_group" - sub_group = await agroup.create_group(sub_group_path, attributes={"foo": 100}) - assert await agroup.getitem(sub_group_path) == sub_group - - # check that asking for a nonexistent key raises KeyError - with pytest.raises(KeyError): - await agroup.getitem("foo") - - -async def test_asyncgroup_delitem(store: LocalStore | MemoryStore, zarr_format: ZarrFormat) -> None: - agroup = await AsyncGroup.create(store=store, zarr_format=zarr_format) - sub_array_path = "sub_array" - _ = await agroup.create_array( - path=sub_array_path, shape=(10,), dtype="uint8", chunk_shape=(2,), attributes={"foo": 100} - ) - await agroup.delitem(sub_array_path) - - # todo: clean up the code duplication here - if zarr_format == 2: - assert not await agroup.store_path.store.exists(sub_array_path + "/" + ".zarray") - assert not await agroup.store_path.store.exists(sub_array_path + "/" + ".zattrs") - elif zarr_format == 3: - assert not await agroup.store_path.store.exists(sub_array_path + "/" + "zarr.json") - else: - raise AssertionError - - sub_group_path = "sub_group" - _ = await agroup.create_group(sub_group_path, attributes={"foo": 100}) - await agroup.delitem(sub_group_path) - if zarr_format == 2: - assert not await agroup.store_path.store.exists(sub_array_path + "/" + ".zgroup") - assert not await agroup.store_path.store.exists(sub_array_path + "/" + ".zattrs") - elif zarr_format == 3: - assert not await agroup.store_path.store.exists(sub_array_path + "/" + "zarr.json") - else: - raise AssertionError - - -async def test_asyncgroup_create_group( - store: LocalStore | MemoryStore, - zarr_format: ZarrFormat, -) -> None: - agroup = await AsyncGroup.create(store=store, zarr_format=zarr_format) - sub_node_path = "sub_group" - attributes = {"foo": 999} - subnode = await agroup.create_group(path=sub_node_path, attributes=attributes) - - assert isinstance(subnode, AsyncGroup) - assert subnode.attrs == attributes - assert subnode.store_path.path == sub_node_path - assert subnode.store_path.store == store - assert subnode.metadata.zarr_format == zarr_format - - -async def test_asyncgroup_create_array( - store: LocalStore | MemoryStore, zarr_format: ZarrFormat, exists_ok: bool -) -> None: - """ - Test that the AsyncGroup.create_array method works correctly. We ensure that array properties - specified in create_array are present on the resulting array. - """ - - agroup = await AsyncGroup.create(store=store, zarr_format=zarr_format) - - if not exists_ok: - with pytest.raises(ContainsGroupError): - agroup = await AsyncGroup.create(store=store, zarr_format=zarr_format) - - shape = (10,) - dtype = "uint8" - chunk_shape = (4,) - attributes = {"foo": 100} - - sub_node_path = "sub_array" - subnode = await agroup.create_array( - path=sub_node_path, - shape=shape, - dtype=dtype, - chunk_shape=chunk_shape, - attributes=attributes, - ) - assert isinstance(subnode, AsyncArray) - assert subnode.attrs == attributes - assert subnode.store_path.path == sub_node_path - assert subnode.store_path.store == store - assert subnode.shape == shape - assert subnode.dtype == dtype - # todo: fix the type annotation of array.metadata.chunk_grid so that we get some autocomplete - # here. - assert subnode.metadata.chunk_grid.chunk_shape == chunk_shape - assert subnode.metadata.zarr_format == zarr_format - - -async def test_asyncgroup_update_attributes( - store: LocalStore | MemoryStore, zarr_format: ZarrFormat -) -> None: - """ - Test that the AsyncGroup.update_attributes method works correctly. - """ - attributes_old = {"foo": 10} - attributes_new = {"baz": "new"} - agroup = await AsyncGroup.create( - store=store, zarr_format=zarr_format, attributes=attributes_old - ) - - agroup_new_attributes = await agroup.update_attributes(attributes_new) - assert agroup_new_attributes.attrs == attributes_new diff --git a/tests/v3/test_indexing.py b/tests/v3/test_indexing.py deleted file mode 100644 index 12547765a9..0000000000 --- a/tests/v3/test_indexing.py +++ /dev/null @@ -1,1782 +0,0 @@ -from __future__ import annotations - -from collections import Counter -from collections.abc import Iterator -from typing import Any -from uuid import uuid4 - -import numpy as np -import numpy.typing as npt -import pytest -from numpy.testing import assert_array_equal - -import zarr -from zarr.abc.store import Store -from zarr.buffer import BufferPrototype, NDBuffer -from zarr.common import ChunkCoords -from zarr.indexing import ( - make_slice_selection, - normalize_integer_selection, - oindex, - oindex_set, - replace_ellipsis, -) -from zarr.registry import get_ndbuffer_class -from zarr.store.core import StorePath -from zarr.store.memory import MemoryStore - - -@pytest.fixture -async def store() -> Iterator[Store]: - yield StorePath(await MemoryStore.open(mode="w")) - - -def zarr_array_from_numpy_array( - store: StorePath, - a: npt.NDArray[Any], - chunk_shape: ChunkCoords | None = None, -) -> zarr.Array: - z = zarr.Array.create( - store=store / str(uuid4()), - shape=a.shape, - dtype=a.dtype, - chunk_shape=chunk_shape or a.shape, - chunk_key_encoding=("v2", "."), - ) - z[()] = a - return z - - -class CountingDict(MemoryStore): - @classmethod - async def open(cls): - store = await super().open(mode="w") - store.counter = Counter() - return store - - async def get(self, key, prototype: BufferPrototype, byte_range=None): - key_suffix = "/".join(key.split("/")[1:]) - self.counter["__getitem__", key_suffix] += 1 - return await super().get(key, prototype, byte_range) - - async def set(self, key, value, byte_range=None): - key_suffix = "/".join(key.split("/")[1:]) - self.counter["__setitem__", key_suffix] += 1 - return await super().set(key, value, byte_range) - - -def test_normalize_integer_selection(): - assert 1 == normalize_integer_selection(1, 100) - assert 99 == normalize_integer_selection(-1, 100) - with pytest.raises(IndexError): - normalize_integer_selection(100, 100) - with pytest.raises(IndexError): - normalize_integer_selection(1000, 100) - with pytest.raises(IndexError): - normalize_integer_selection(-1000, 100) - - -def test_replace_ellipsis(): - # 1D, single item - assert (0,) == replace_ellipsis(0, (100,)) - - # 1D - assert (slice(None),) == replace_ellipsis(Ellipsis, (100,)) - assert (slice(None),) == replace_ellipsis(slice(None), (100,)) - assert (slice(None, 100),) == replace_ellipsis(slice(None, 100), (100,)) - assert (slice(0, None),) == replace_ellipsis(slice(0, None), (100,)) - assert (slice(None),) == replace_ellipsis((slice(None), Ellipsis), (100,)) - assert (slice(None),) == replace_ellipsis((Ellipsis, slice(None)), (100,)) - - # 2D, single item - assert (0, 0) == replace_ellipsis((0, 0), (100, 100)) - assert (-1, 1) == replace_ellipsis((-1, 1), (100, 100)) - - # 2D, single col/row - assert (0, slice(None)) == replace_ellipsis((0, slice(None)), (100, 100)) - assert (0, slice(None)) == replace_ellipsis((0,), (100, 100)) - assert (slice(None), 0) == replace_ellipsis((slice(None), 0), (100, 100)) - - # 2D slice - assert (slice(None), slice(None)) == replace_ellipsis(Ellipsis, (100, 100)) - assert (slice(None), slice(None)) == replace_ellipsis(slice(None), (100, 100)) - assert (slice(None), slice(None)) == replace_ellipsis((slice(None), slice(None)), (100, 100)) - assert (slice(None), slice(None)) == replace_ellipsis((Ellipsis, slice(None)), (100, 100)) - assert (slice(None), slice(None)) == replace_ellipsis((slice(None), Ellipsis), (100, 100)) - assert (slice(None), slice(None)) == replace_ellipsis( - (slice(None), Ellipsis, slice(None)), (100, 100) - ) - assert (slice(None), slice(None)) == replace_ellipsis( - (Ellipsis, slice(None), slice(None)), (100, 100) - ) - assert (slice(None), slice(None)) == replace_ellipsis( - (slice(None), slice(None), Ellipsis), (100, 100) - ) - - -@pytest.mark.parametrize( - "value, dtype", - [ - (42, "uint8"), - pytest.param( - (b"aaa", 1, 4.2), [("foo", "S3"), ("bar", "i4"), ("baz", "f8")], marks=pytest.mark.xfail - ), - ], -) -@pytest.mark.parametrize("use_out", (True, False)) -def test_get_basic_selection_0d(store: StorePath, use_out: bool, value: Any, dtype: Any) -> None: - # setup - arr_np = np.array(value, dtype=dtype) - arr_z = zarr_array_from_numpy_array(store, arr_np) - - assert_array_equal(arr_np, arr_z.get_basic_selection(Ellipsis)) - assert_array_equal(arr_np, arr_z[...]) - assert value == arr_z.get_basic_selection(()) - assert value == arr_z[()] - - if use_out: - # test out param - b = NDBuffer.from_numpy_array(np.zeros_like(arr_np)) - arr_z.get_basic_selection(Ellipsis, out=b) - assert_array_equal(arr_np, b.as_ndarray_like()) - - # todo: uncomment the structured array tests when we can make them pass, - # or delete them if we formally decide not to support structured dtypes. - - # test structured array - # value = (b"aaa", 1, 4.2) - # a = np.array(value, dtype=[("foo", "S3"), ("bar", "i4"), ("baz", "f8")]) - # z = zarr_array_from_numpy_array(store, a) - # z[()] = value - # assert_array_equal(a, z.get_basic_selection(Ellipsis)) - # assert_array_equal(a, z[...]) - # assert a[()] == z.get_basic_selection(()) - # assert a[()] == z[()] - # assert b"aaa" == z.get_basic_selection((), fields="foo") - # assert b"aaa" == z["foo"] - # assert a[["foo", "bar"]] == z.get_basic_selection((), fields=["foo", "bar"]) - # assert a[["foo", "bar"]] == z["foo", "bar"] - # # test out param - # b = NDBuffer.from_numpy_array(np.zeros_like(a)) - # z.get_basic_selection(Ellipsis, out=b) - # assert_array_equal(a, b) - # c = NDBuffer.from_numpy_array(np.zeros_like(a[["foo", "bar"]])) - # z.get_basic_selection(Ellipsis, out=c, fields=["foo", "bar"]) - # assert_array_equal(a[["foo", "bar"]], c) - - -basic_selections_1d = [ - # single value - 42, - -1, - # slices - slice(0, 1050), - slice(50, 150), - slice(0, 2000), - slice(-150, -50), - slice(-2000, 2000), - slice(0, 0), # empty result - slice(-1, 0), # empty result - # total selections - slice(None), - Ellipsis, - (), - (Ellipsis, slice(None)), - # slice with step - slice(None), - slice(None, None), - slice(None, None, 1), - slice(None, None, 10), - slice(None, None, 100), - slice(None, None, 1000), - slice(None, None, 10000), - slice(0, 1050), - slice(0, 1050, 1), - slice(0, 1050, 10), - slice(0, 1050, 100), - slice(0, 1050, 1000), - slice(0, 1050, 10000), - slice(1, 31, 3), - slice(1, 31, 30), - slice(1, 31, 300), - slice(81, 121, 3), - slice(81, 121, 30), - slice(81, 121, 300), - slice(50, 150), - slice(50, 150, 1), - slice(50, 150, 10), -] - -basic_selections_1d_bad = [ - # only positive step supported - slice(None, None, -1), - slice(None, None, -10), - slice(None, None, -100), - slice(None, None, -1000), - slice(None, None, -10000), - slice(1050, -1, -1), - slice(1050, -1, -10), - slice(1050, -1, -100), - slice(1050, -1, -1000), - slice(1050, -1, -10000), - slice(1050, 0, -1), - slice(1050, 0, -10), - slice(1050, 0, -100), - slice(1050, 0, -1000), - slice(1050, 0, -10000), - slice(150, 50, -1), - slice(150, 50, -10), - slice(31, 1, -3), - slice(121, 81, -3), - slice(-1, 0, -1), - # bad stuff - 2.3, - "foo", - b"xxx", - None, - (0, 0), - (slice(None), slice(None)), -] - - -def _test_get_basic_selection(a, z, selection): - expect = a[selection] - actual = z.get_basic_selection(selection) - assert_array_equal(expect, actual) - actual = z[selection] - assert_array_equal(expect, actual) - - # test out param - b = NDBuffer.from_numpy_array(np.empty(shape=expect.shape, dtype=expect.dtype)) - z.get_basic_selection(selection, out=b) - assert_array_equal(expect, b.as_numpy_array()) - - -# noinspection PyStatementEffect -def test_get_basic_selection_1d(store: StorePath): - # setup - a = np.arange(1050, dtype=int) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - - for selection in basic_selections_1d: - _test_get_basic_selection(a, z, selection) - - for selection in basic_selections_1d_bad: - with pytest.raises(IndexError): - z.get_basic_selection(selection) - with pytest.raises(IndexError): - z[selection] - - with pytest.raises(IndexError): - z.get_basic_selection([1, 0]) - - -basic_selections_2d = [ - # single row - 42, - -1, - (42, slice(None)), - (-1, slice(None)), - # single col - (slice(None), 4), - (slice(None), -1), - # row slices - slice(None), - slice(0, 1000), - slice(250, 350), - slice(0, 2000), - slice(-350, -250), - slice(0, 0), # empty result - slice(-1, 0), # empty result - slice(-2000, 0), - slice(-2000, 2000), - # 2D slices - (slice(None), slice(1, 5)), - (slice(250, 350), slice(None)), - (slice(250, 350), slice(1, 5)), - (slice(250, 350), slice(-5, -1)), - (slice(250, 350), slice(-50, 50)), - (slice(250, 350, 10), slice(1, 5)), - (slice(250, 350), slice(1, 5, 2)), - (slice(250, 350, 33), slice(1, 5, 3)), - # total selections - (slice(None), slice(None)), - Ellipsis, - (), - (Ellipsis, slice(None)), - (Ellipsis, slice(None), slice(None)), -] - -basic_selections_2d_bad = [ - # bad stuff - 2.3, - "foo", - b"xxx", - None, - (2.3, slice(None)), - # only positive step supported - slice(None, None, -1), - (slice(None, None, -1), slice(None)), - (0, 0, 0), - (slice(None), slice(None), slice(None)), -] - - -# noinspection PyStatementEffect -def test_get_basic_selection_2d(store: StorePath): - # setup - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - - for selection in basic_selections_2d: - _test_get_basic_selection(a, z, selection) - - bad_selections = basic_selections_2d_bad + [ - # integer arrays - [0, 1], - (slice(None), [0, 1]), - ] - for selection in bad_selections: - with pytest.raises(IndexError): - z.get_basic_selection(selection) - # check fallback on fancy indexing - fancy_selection = ([0, 1], [0, 1]) - np.testing.assert_array_equal(z[fancy_selection], [0, 11]) - - -def test_fancy_indexing_fallback_on_get_setitem(store: StorePath): - z = zarr_array_from_numpy_array(store, np.zeros((20, 20))) - z[[1, 2, 3], [1, 2, 3]] = 1 - np.testing.assert_array_equal( - z[:4, :4], - [ - [0, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 1, 0], - [0, 0, 0, 1], - ], - ) - np.testing.assert_array_equal(z[[1, 2, 3], [1, 2, 3]], 1) - # test broadcasting - np.testing.assert_array_equal(z[1, [1, 2, 3]], [1, 0, 0]) - # test 1D fancy indexing - z2 = zarr_array_from_numpy_array(store, np.zeros(5)) - z2[[1, 2, 3]] = 1 - np.testing.assert_array_equal(z2[:], [0, 1, 1, 1, 0]) - - -@pytest.mark.parametrize( - "index,expected_result", - [ - # Single iterable of integers - ([0, 1], [[0, 1, 2], [3, 4, 5]]), - # List first, then slice - (([0, 1], slice(None)), [[0, 1, 2], [3, 4, 5]]), - # List first, then slice - (([0, 1], slice(1, None)), [[1, 2], [4, 5]]), - # Slice first, then list - ((slice(0, 2), [0, 2]), [[0, 2], [3, 5]]), - # Slices only - ((slice(0, 2), slice(0, 2)), [[0, 1], [3, 4]]), - # List with repeated index - (([1, 0, 1], slice(1, None)), [[4, 5], [1, 2], [4, 5]]), - # 1D indexing - (([1, 0, 1]), [[3, 4, 5], [0, 1, 2], [3, 4, 5]]), - ], -) -def test_orthogonal_indexing_fallback_on_getitem_2d(store: StorePath, index, expected_result): - """ - Tests the orthogonal indexing fallback on __getitem__ for a 2D matrix. - - In addition to checking expected behavior, all indexing - is also checked against numpy. - """ - # [0, 1, 2], - # [3, 4, 5], - # [6, 7, 8] - a = np.arange(9).reshape(3, 3) - z = zarr_array_from_numpy_array(store, a) - - np.testing.assert_array_equal(z[index], a[index], err_msg="Indexing disagrees with numpy") - np.testing.assert_array_equal(z[index], expected_result) - - -@pytest.mark.parametrize( - "index,expected_result", - [ - # Single iterable of integers - ([0, 1], [[[0, 1, 2], [3, 4, 5], [6, 7, 8]], [[9, 10, 11], [12, 13, 14], [15, 16, 17]]]), - # One slice, two integers - ((slice(0, 2), 1, 1), [4, 13]), - # One integer, two slices - ((slice(0, 2), 1, slice(0, 2)), [[3, 4], [12, 13]]), - # Two slices and a list - ((slice(0, 2), [1, 2], slice(0, 2)), [[[3, 4], [6, 7]], [[12, 13], [15, 16]]]), - ], -) -def test_orthogonal_indexing_fallback_on_getitem_3d(store: StorePath, index, expected_result): - """ - Tests the orthogonal indexing fallback on __getitem__ for a 3D matrix. - - In addition to checking expected behavior, all indexing - is also checked against numpy. - """ - # [[[ 0, 1, 2], - # [ 3, 4, 5], - # [ 6, 7, 8]], - - # [[ 9, 10, 11], - # [12, 13, 14], - # [15, 16, 17]], - - # [[18, 19, 20], - # [21, 22, 23], - # [24, 25, 26]]] - a = np.arange(27).reshape(3, 3, 3) - z = zarr_array_from_numpy_array(store, a) - - np.testing.assert_array_equal(z[index], a[index], err_msg="Indexing disagrees with numpy") - np.testing.assert_array_equal(z[index], expected_result) - - -@pytest.mark.parametrize( - "index,expected_result", - [ - # Single iterable of integers - ([0, 1], [[1, 1, 1], [1, 1, 1], [0, 0, 0]]), - # List and slice combined - (([0, 1], slice(1, 3)), [[0, 1, 1], [0, 1, 1], [0, 0, 0]]), - # Index repetition is ignored on setitem - (([0, 1, 1, 1, 1, 1, 1], slice(1, 3)), [[0, 1, 1], [0, 1, 1], [0, 0, 0]]), - # Slice with step - (([0, 2], slice(None, None, 2)), [[1, 0, 1], [0, 0, 0], [1, 0, 1]]), - ], -) -def test_orthogonal_indexing_fallback_on_setitem_2d(store: StorePath, index, expected_result): - """ - Tests the orthogonal indexing fallback on __setitem__ for a 3D matrix. - - In addition to checking expected behavior, all indexing - is also checked against numpy. - """ - # Slice + fancy index - a = np.zeros((3, 3)) - z = zarr_array_from_numpy_array(store, a) - z[index] = 1 - a[index] = 1 - np.testing.assert_array_equal(z[:], expected_result) - np.testing.assert_array_equal(z[:], a, err_msg="Indexing disagrees with numpy") - - -def test_fancy_indexing_doesnt_mix_with_implicit_slicing(store: StorePath): - z2 = zarr_array_from_numpy_array(store, np.zeros((5, 5, 5))) - with pytest.raises(IndexError): - z2[[1, 2, 3], [1, 2, 3]] = 2 - with pytest.raises(IndexError): - np.testing.assert_array_equal(z2[[1, 2, 3], [1, 2, 3]], 0) - with pytest.raises(IndexError): - z2[..., [1, 2, 3]] = 2 - with pytest.raises(IndexError): - np.testing.assert_array_equal(z2[..., [1, 2, 3]], 0) - - -@pytest.mark.parametrize( - "value, dtype", - [ - (42, "uint8"), - pytest.param( - (b"aaa", 1, 4.2), [("foo", "S3"), ("bar", "i4"), ("baz", "f8")], marks=pytest.mark.xfail - ), - ], -) -def test_set_basic_selection_0d( - store: StorePath, value: Any, dtype: str | list[tuple[str, str]] -) -> None: - arr_np = np.array(value, dtype=dtype) - arr_np_zeros = np.zeros_like(arr_np, dtype=dtype) - arr_z = zarr_array_from_numpy_array(store, arr_np_zeros) - assert_array_equal(arr_np_zeros, arr_z) - - arr_z.set_basic_selection(Ellipsis, value) - assert_array_equal(value, arr_z) - arr_z[...] = 0 - assert_array_equal(arr_np_zeros, arr_z) - arr_z[...] = value - assert_array_equal(value, arr_z) - - # todo: uncomment the structured array tests when we can make them pass, - # or delete them if we formally decide not to support structured dtypes. - - # arr_z.set_basic_selection(Ellipsis, v["foo"], fields="foo") - # assert v["foo"] == arr_z["foo"] - # assert arr_np_zeros["bar"] == arr_z["bar"] - # assert arr_np_zeros["baz"] == arr_z["baz"] - # arr_z["bar"] = v["bar"] - # assert v["foo"] == arr_z["foo"] - # assert v["bar"] == arr_z["bar"] - # assert arr_np_zeros["baz"] == arr_z["baz"] - # # multiple field assignment not supported - # with pytest.raises(IndexError): - # arr_z.set_basic_selection(Ellipsis, v[["foo", "bar"]], fields=["foo", "bar"]) - # with pytest.raises(IndexError): - # arr_z[..., "foo", "bar"] = v[["foo", "bar"]] - - -def _test_get_orthogonal_selection(a, z, selection): - expect = oindex(a, selection) - actual = z.get_orthogonal_selection(selection) - assert_array_equal(expect, actual) - actual = z.oindex[selection] - assert_array_equal(expect, actual) - - -# noinspection PyStatementEffect -def test_get_orthogonal_selection_1d_bool(store: StorePath): - # setup - a = np.arange(1050, dtype=int) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - _test_get_orthogonal_selection(a, z, ix) - - # test errors - with pytest.raises(IndexError): - z.oindex[np.zeros(50, dtype=bool)] # too short - with pytest.raises(IndexError): - z.oindex[np.zeros(2000, dtype=bool)] # too long - with pytest.raises(IndexError): - z.oindex[[[True, False], [False, True]]] # too many dimensions - - -# noinspection PyStatementEffect -def test_get_orthogonal_selection_1d_int(store: StorePath): - # setup - a = np.arange(1050, dtype=int) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 2, 0.5, 0.1, 0.01: - # unordered - ix = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - _test_get_orthogonal_selection(a, z, ix) - # increasing - ix.sort() - _test_get_orthogonal_selection(a, z, ix) - # decreasing - ix = ix[::-1] - _test_get_orthogonal_selection(a, z, ix) - - selections = basic_selections_1d + [ - # test wraparound - [0, 3, 10, -23, -12, -1], - # explicit test not sorted - [3, 105, 23, 127], - ] - for selection in selections: - _test_get_orthogonal_selection(a, z, selection) - - bad_selections = basic_selections_1d_bad + [ - [a.shape[0] + 1], # out of bounds - [-(a.shape[0] + 1)], # out of bounds - [[2, 4], [6, 8]], # too many dimensions - ] - for selection in bad_selections: - with pytest.raises(IndexError): - z.get_orthogonal_selection(selection) - with pytest.raises(IndexError): - z.oindex[selection] - - -def _test_get_orthogonal_selection_2d(a, z, ix0, ix1): - selections = [ - # index both axes with array - (ix0, ix1), - # mixed indexing with array / slice - (ix0, slice(1, 5)), - (ix0, slice(1, 5, 2)), - (slice(250, 350), ix1), - (slice(250, 350, 10), ix1), - # mixed indexing with array / int - (ix0, 4), - (42, ix1), - ] - for selection in selections: - _test_get_orthogonal_selection(a, z, selection) - - -# noinspection PyStatementEffect -def test_get_orthogonal_selection_2d(store: StorePath): - # setup - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - # boolean arrays - ix0 = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - ix1 = np.random.binomial(1, 0.5, size=a.shape[1]).astype(bool) - _test_get_orthogonal_selection_2d(a, z, ix0, ix1) - - # mixed int array / bool array - selections = ( - (ix0, np.nonzero(ix1)[0]), - (np.nonzero(ix0)[0], ix1), - ) - for selection in selections: - _test_get_orthogonal_selection(a, z, selection) - - # integer arrays - ix0 = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - ix1 = np.random.choice(a.shape[1], size=int(a.shape[1] * 0.5), replace=True) - _test_get_orthogonal_selection_2d(a, z, ix0, ix1) - ix0.sort() - ix1.sort() - _test_get_orthogonal_selection_2d(a, z, ix0, ix1) - ix0 = ix0[::-1] - ix1 = ix1[::-1] - _test_get_orthogonal_selection_2d(a, z, ix0, ix1) - - for selection in basic_selections_2d: - _test_get_orthogonal_selection(a, z, selection) - - for selection in basic_selections_2d_bad: - with pytest.raises(IndexError): - z.get_orthogonal_selection(selection) - with pytest.raises(IndexError): - z.oindex[selection] - - -def _test_get_orthogonal_selection_3d(a, z, ix0, ix1, ix2): - selections = [ - # single value - (84, 42, 4), - (-1, -1, -1), - # index all axes with array - (ix0, ix1, ix2), - # mixed indexing with single array / slices - (ix0, slice(15, 25), slice(1, 5)), - (slice(50, 70), ix1, slice(1, 5)), - (slice(50, 70), slice(15, 25), ix2), - (ix0, slice(15, 25, 5), slice(1, 5, 2)), - (slice(50, 70, 3), ix1, slice(1, 5, 2)), - (slice(50, 70, 3), slice(15, 25, 5), ix2), - # mixed indexing with single array / ints - (ix0, 42, 4), - (84, ix1, 4), - (84, 42, ix2), - # mixed indexing with single array / slice / int - (ix0, slice(15, 25), 4), - (42, ix1, slice(1, 5)), - (slice(50, 70), 42, ix2), - # mixed indexing with two array / slice - (ix0, ix1, slice(1, 5)), - (slice(50, 70), ix1, ix2), - (ix0, slice(15, 25), ix2), - # mixed indexing with two array / integer - (ix0, ix1, 4), - (42, ix1, ix2), - (ix0, 42, ix2), - ] - for selection in selections: - _test_get_orthogonal_selection(a, z, selection) - - -def test_get_orthogonal_selection_3d(store: StorePath): - # setup - a = np.arange(100000, dtype=int).reshape(200, 50, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(60, 20, 3)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - # boolean arrays - ix0 = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - ix1 = np.random.binomial(1, 0.5, size=a.shape[1]).astype(bool) - ix2 = np.random.binomial(1, 0.5, size=a.shape[2]).astype(bool) - _test_get_orthogonal_selection_3d(a, z, ix0, ix1, ix2) - - # integer arrays - ix0 = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - ix1 = np.random.choice(a.shape[1], size=int(a.shape[1] * 0.5), replace=True) - ix2 = np.random.choice(a.shape[2], size=int(a.shape[2] * 0.5), replace=True) - _test_get_orthogonal_selection_3d(a, z, ix0, ix1, ix2) - ix0.sort() - ix1.sort() - ix2.sort() - _test_get_orthogonal_selection_3d(a, z, ix0, ix1, ix2) - ix0 = ix0[::-1] - ix1 = ix1[::-1] - ix2 = ix2[::-1] - _test_get_orthogonal_selection_3d(a, z, ix0, ix1, ix2) - - -def test_orthogonal_indexing_edge_cases(store: StorePath): - a = np.arange(6).reshape(1, 2, 3) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(1, 2, 3)) - - expect = oindex(a, (0, slice(None), [0, 1, 2])) - actual = z.oindex[0, :, [0, 1, 2]] - assert_array_equal(expect, actual) - - expect = oindex(a, (0, slice(None), [True, True, True])) - actual = z.oindex[0, :, [True, True, True]] - assert_array_equal(expect, actual) - - -def _test_set_orthogonal_selection(v, a, z, selection): - for value in 42, oindex(v, selection), oindex(v, selection).tolist(): - if isinstance(value, list) and value == []: - # skip these cases as cannot preserve all dimensions - continue - # setup expectation - a[:] = 0 - oindex_set(a, selection, value) - # long-form API - z[:] = 0 - z.set_orthogonal_selection(selection, value) - assert_array_equal(a, z[:]) - # short-form API - z[:] = 0 - z.oindex[selection] = value - assert_array_equal(a, z[:]) - - -def test_set_orthogonal_selection_1d(store: StorePath): - # setup - v = np.arange(1050, dtype=int) - a = np.empty(v.shape, dtype=int) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - - # test with different degrees of sparseness - np.random.seed(42) - for p in 0.5, 0.1, 0.01: - # boolean arrays - ix = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - _test_set_orthogonal_selection(v, a, z, ix) - - # integer arrays - ix = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - _test_set_orthogonal_selection(v, a, z, ix) - ix.sort() - _test_set_orthogonal_selection(v, a, z, ix) - ix = ix[::-1] - _test_set_orthogonal_selection(v, a, z, ix) - - # basic selections - for selection in basic_selections_1d: - _test_set_orthogonal_selection(v, a, z, selection) - - -def _test_set_orthogonal_selection_2d(v, a, z, ix0, ix1): - selections = [ - # index both axes with array - (ix0, ix1), - # mixed indexing with array / slice or int - (ix0, slice(1, 5)), - (slice(250, 350), ix1), - (ix0, 4), - (42, ix1), - ] - for selection in selections: - _test_set_orthogonal_selection(v, a, z, selection) - - -def test_set_orthogonal_selection_2d(store: StorePath): - # setup - v = np.arange(10000, dtype=int).reshape(1000, 10) - a = np.empty_like(v) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - # boolean arrays - ix0 = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - ix1 = np.random.binomial(1, 0.5, size=a.shape[1]).astype(bool) - _test_set_orthogonal_selection_2d(v, a, z, ix0, ix1) - - # integer arrays - ix0 = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - ix1 = np.random.choice(a.shape[1], size=int(a.shape[1] * 0.5), replace=True) - _test_set_orthogonal_selection_2d(v, a, z, ix0, ix1) - ix0.sort() - ix1.sort() - _test_set_orthogonal_selection_2d(v, a, z, ix0, ix1) - ix0 = ix0[::-1] - ix1 = ix1[::-1] - _test_set_orthogonal_selection_2d(v, a, z, ix0, ix1) - - for selection in basic_selections_2d: - _test_set_orthogonal_selection(v, a, z, selection) - - -def _test_set_orthogonal_selection_3d(v, a, z, ix0, ix1, ix2): - selections = ( - # single value - (84, 42, 4), - (-1, -1, -1), - # index all axes with bool array - (ix0, ix1, ix2), - # mixed indexing with single bool array / slice or int - (ix0, slice(15, 25), slice(1, 5)), - (slice(50, 70), ix1, slice(1, 5)), - (slice(50, 70), slice(15, 25), ix2), - (ix0, 42, 4), - (84, ix1, 4), - (84, 42, ix2), - (ix0, slice(15, 25), 4), - (slice(50, 70), ix1, 4), - (slice(50, 70), 42, ix2), - # indexing with two arrays / slice - (ix0, ix1, slice(1, 5)), - # indexing with two arrays / integer - (ix0, ix1, 4), - ) - for selection in selections: - _test_set_orthogonal_selection(v, a, z, selection) - - -def test_set_orthogonal_selection_3d(store: StorePath): - # setup - v = np.arange(100000, dtype=int).reshape(200, 50, 10) - a = np.empty_like(v) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(60, 20, 3)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - # boolean arrays - ix0 = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - ix1 = np.random.binomial(1, 0.5, size=a.shape[1]).astype(bool) - ix2 = np.random.binomial(1, 0.5, size=a.shape[2]).astype(bool) - _test_set_orthogonal_selection_3d(v, a, z, ix0, ix1, ix2) - - # integer arrays - ix0 = np.random.choice(a.shape[0], size=int(a.shape[0] * p), replace=True) - ix1 = np.random.choice(a.shape[1], size=int(a.shape[1] * 0.5), replace=True) - ix2 = np.random.choice(a.shape[2], size=int(a.shape[2] * 0.5), replace=True) - _test_set_orthogonal_selection_3d(v, a, z, ix0, ix1, ix2) - - # sorted increasing - ix0.sort() - ix1.sort() - ix2.sort() - _test_set_orthogonal_selection_3d(v, a, z, ix0, ix1, ix2) - - # sorted decreasing - ix0 = ix0[::-1] - ix1 = ix1[::-1] - ix2 = ix2[::-1] - _test_set_orthogonal_selection_3d(v, a, z, ix0, ix1, ix2) - - -def test_orthogonal_indexing_fallback_on_get_setitem(store: StorePath): - z = zarr_array_from_numpy_array(store, np.zeros((20, 20))) - z[[1, 2, 3], [1, 2, 3]] = 1 - np.testing.assert_array_equal( - z[:4, :4], - [ - [0, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 1, 0], - [0, 0, 0, 1], - ], - ) - np.testing.assert_array_equal(z[[1, 2, 3], [1, 2, 3]], 1) - # test broadcasting - np.testing.assert_array_equal(z[1, [1, 2, 3]], [1, 0, 0]) - # test 1D fancy indexing - z2 = zarr_array_from_numpy_array(store, np.zeros(5)) - z2[[1, 2, 3]] = 1 - np.testing.assert_array_equal(z2[:], [0, 1, 1, 1, 0]) - - -def _test_get_coordinate_selection(a, z, selection): - expect = a[selection] - actual = z.get_coordinate_selection(selection) - assert_array_equal(expect, actual) - actual = z.vindex[selection] - assert_array_equal(expect, actual) - - -coordinate_selections_1d_bad = [ - # slice not supported - slice(5, 15), - slice(None), - Ellipsis, - # bad stuff - 2.3, - "foo", - b"xxx", - None, - (0, 0), - (slice(None), slice(None)), -] - - -# noinspection PyStatementEffect -def test_get_coordinate_selection_1d(store: StorePath): - # setup - a = np.arange(1050, dtype=int) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 2, 0.5, 0.1, 0.01: - n = int(a.size * p) - ix = np.random.choice(a.shape[0], size=n, replace=True) - _test_get_coordinate_selection(a, z, ix) - ix.sort() - _test_get_coordinate_selection(a, z, ix) - ix = ix[::-1] - _test_get_coordinate_selection(a, z, ix) - - selections = [ - # test single item - 42, - -1, - # test wraparound - [0, 3, 10, -23, -12, -1], - # test out of order - [3, 105, 23, 127], # not monotonically increasing - # test multi-dimensional selection - np.array([[2, 4], [6, 8]]), - ] - for selection in selections: - _test_get_coordinate_selection(a, z, selection) - - # test errors - bad_selections = coordinate_selections_1d_bad + [ - [a.shape[0] + 1], # out of bounds - [-(a.shape[0] + 1)], # out of bounds - ] - for selection in bad_selections: - with pytest.raises(IndexError): - z.get_coordinate_selection(selection) - with pytest.raises(IndexError): - z.vindex[selection] - - -def test_get_coordinate_selection_2d(store: StorePath): - # setup - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 2, 0.5, 0.1, 0.01: - n = int(a.size * p) - ix0 = np.random.choice(a.shape[0], size=n, replace=True) - ix1 = np.random.choice(a.shape[1], size=n, replace=True) - selections = [ - # single value - (42, 4), - (-1, -1), - # index both axes with array - (ix0, ix1), - # mixed indexing with array / int - (ix0, 4), - (42, ix1), - (42, 4), - ] - for selection in selections: - _test_get_coordinate_selection(a, z, selection) - - # not monotonically increasing (first dim) - ix0 = [3, 3, 4, 2, 5] - ix1 = [1, 3, 5, 7, 9] - _test_get_coordinate_selection(a, z, (ix0, ix1)) - - # not monotonically increasing (second dim) - ix0 = [1, 1, 2, 2, 5] - ix1 = [1, 3, 2, 1, 0] - _test_get_coordinate_selection(a, z, (ix0, ix1)) - - # multi-dimensional selection - ix0 = np.array([[1, 1, 2], [2, 2, 5]]) - ix1 = np.array([[1, 3, 2], [1, 0, 0]]) - _test_get_coordinate_selection(a, z, (ix0, ix1)) - - with pytest.raises(IndexError): - selection = slice(5, 15), [1, 2, 3] - z.get_coordinate_selection(selection) - with pytest.raises(IndexError): - selection = [1, 2, 3], slice(5, 15) - z.get_coordinate_selection(selection) - with pytest.raises(IndexError): - selection = Ellipsis, [1, 2, 3] - z.get_coordinate_selection(selection) - with pytest.raises(IndexError): - selection = Ellipsis - z.get_coordinate_selection(selection) - - -def _test_set_coordinate_selection(v, a, z, selection): - for value in 42, v[selection], v[selection].tolist(): - # setup expectation - a[:] = 0 - a[selection] = value - # test long-form API - z[:] = 0 - z.set_coordinate_selection(selection, value) - assert_array_equal(a, z[:]) - # test short-form API - z[:] = 0 - z.vindex[selection] = value - assert_array_equal(a, z[:]) - - -def test_set_coordinate_selection_1d(store: StorePath): - # setup - v = np.arange(1050, dtype=int) - a = np.empty(v.shape, dtype=v.dtype) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 2, 0.5, 0.1, 0.01: - n = int(a.size * p) - ix = np.random.choice(a.shape[0], size=n, replace=True) - _test_set_coordinate_selection(v, a, z, ix) - - # multi-dimensional selection - ix = np.array([[2, 4], [6, 8]]) - _test_set_coordinate_selection(v, a, z, ix) - - for selection in coordinate_selections_1d_bad: - with pytest.raises(IndexError): - z.set_coordinate_selection(selection, 42) - with pytest.raises(IndexError): - z.vindex[selection] = 42 - - -def test_set_coordinate_selection_2d(store: StorePath): - # setup - v = np.arange(10000, dtype=int).reshape(1000, 10) - a = np.empty_like(v) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 2, 0.5, 0.1, 0.01: - n = int(a.size * p) - ix0 = np.random.choice(a.shape[0], size=n, replace=True) - ix1 = np.random.choice(a.shape[1], size=n, replace=True) - - selections = ( - (42, 4), - (-1, -1), - # index both axes with array - (ix0, ix1), - # mixed indexing with array / int - (ix0, 4), - (42, ix1), - ) - for selection in selections: - _test_set_coordinate_selection(v, a, z, selection) - - # multi-dimensional selection - ix0 = np.array([[1, 2, 3], [4, 5, 6]]) - ix1 = np.array([[1, 3, 2], [2, 0, 5]]) - _test_set_coordinate_selection(v, a, z, (ix0, ix1)) - - -def _test_get_block_selection(a, z, selection, expected_idx): - expect = a[expected_idx] - actual = z.get_block_selection(selection) - assert_array_equal(expect, actual) - actual = z.blocks[selection] - assert_array_equal(expect, actual) - - -block_selections_1d = [ - # test single item - 0, - 5, - # test wraparound - -1, - -4, - # test slice - slice(5), - slice(None, 3), - slice(5, 6), - slice(-3, -1), - slice(None), # Full slice -] - -block_selections_1d_array_projection = [ - # test single item - slice(100), - slice(500, 600), - # test wraparound - slice(1000, None), - slice(700, 800), - # test slice - slice(500), - slice(None, 300), - slice(500, 600), - slice(800, 1000), - slice(None), -] - -block_selections_1d_bad = [ - # slice not supported - slice(3, 8, 2), - # bad stuff - 2.3, - # "foo", # TODO - b"xxx", - None, - (0, 0), - (slice(None), slice(None)), - [0, 5, 3], -] - - -def test_get_block_selection_1d(store: StorePath): - # setup - a = np.arange(1050, dtype=int) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - - for selection, expected_idx in zip( - block_selections_1d, block_selections_1d_array_projection, strict=True - ): - _test_get_block_selection(a, z, selection, expected_idx) - - bad_selections = block_selections_1d_bad + [ - z.metadata.chunk_grid.get_nchunks(z.shape) + 1, # out of bounds - -(z.metadata.chunk_grid.get_nchunks(z.shape) + 1), # out of bounds - ] - - for selection in bad_selections: - with pytest.raises(IndexError): - z.get_block_selection(selection) - with pytest.raises(IndexError): - z.blocks[selection] - - -block_selections_2d = [ - # test single item - (0, 0), - (1, 2), - # test wraparound - (-1, -1), - (-3, -2), - # test slice - (slice(1), slice(2)), - (slice(None, 2), slice(-2, -1)), - (slice(2, 3), slice(-2, None)), - (slice(-3, -1), slice(-3, -2)), - (slice(None), slice(None)), # Full slice -] - -block_selections_2d_array_projection = [ - # test single item - (slice(300), slice(3)), - (slice(300, 600), slice(6, 9)), - # test wraparound - (slice(900, None), slice(9, None)), - (slice(300, 600), slice(6, 9)), - # test slice - (slice(300), slice(6)), - (slice(None, 600), slice(6, 9)), - (slice(600, 900), slice(6, None)), - (slice(300, 900), slice(3, 6)), - (slice(None), slice(None)), # Full slice -] - - -def test_get_block_selection_2d(store: StorePath): - # setup - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - - for selection, expected_idx in zip( - block_selections_2d, block_selections_2d_array_projection, strict=True - ): - _test_get_block_selection(a, z, selection, expected_idx) - - with pytest.raises(IndexError): - selection = slice(5, 15), [1, 2, 3] - z.get_block_selection(selection) - with pytest.raises(IndexError): - selection = Ellipsis, [1, 2, 3] - z.get_block_selection(selection) - with pytest.raises(IndexError): # out of bounds - selection = slice(15, 20), slice(None) - z.get_block_selection(selection) - - -def _test_set_block_selection(v: np.ndarray, a: np.ndarray, z: zarr.Array, selection, expected_idx): - for value in 42, v[expected_idx], v[expected_idx].tolist(): - # setup expectation - a[:] = 0 - a[expected_idx] = value - # test long-form API - z[:] = 0 - z.set_block_selection(selection, value) - assert_array_equal(a, z[:]) - # test short-form API - z[:] = 0 - z.blocks[selection] = value - assert_array_equal(a, z[:]) - - -def test_set_block_selection_1d(store: StorePath): - # setup - v = np.arange(1050, dtype=int) - a = np.empty(v.shape, dtype=v.dtype) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - - for selection, expected_idx in zip( - block_selections_1d, block_selections_1d_array_projection, strict=True - ): - _test_set_block_selection(v, a, z, selection, expected_idx) - - for selection in block_selections_1d_bad: - with pytest.raises(IndexError): - z.set_block_selection(selection, 42) - with pytest.raises(IndexError): - z.blocks[selection] = 42 - - -def test_set_block_selection_2d(store: StorePath): - # setup - v = np.arange(10000, dtype=int).reshape(1000, 10) - a = np.empty(v.shape, dtype=v.dtype) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - - for selection, expected_idx in zip( - block_selections_2d, block_selections_2d_array_projection, strict=True - ): - _test_set_block_selection(v, a, z, selection, expected_idx) - - with pytest.raises(IndexError): - selection = slice(5, 15), [1, 2, 3] - z.set_block_selection(selection, 42) - with pytest.raises(IndexError): - selection = Ellipsis, [1, 2, 3] - z.set_block_selection(selection, 42) - with pytest.raises(IndexError): # out of bounds - selection = slice(15, 20), slice(None) - z.set_block_selection(selection, 42) - - -def _test_get_mask_selection(a, z, selection): - expect = a[selection] - actual = z.get_mask_selection(selection) - assert_array_equal(expect, actual) - actual = z.vindex[selection] - assert_array_equal(expect, actual) - actual = z[selection] - assert_array_equal(expect, actual) - - -mask_selections_1d_bad = [ - # slice not supported - slice(5, 15), - slice(None), - Ellipsis, - # bad stuff - 2.3, - "foo", - b"xxx", - None, - (0, 0), - (slice(None), slice(None)), -] - - -# noinspection PyStatementEffect -def test_get_mask_selection_1d(store: StorePath): - # setup - a = np.arange(1050, dtype=int) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - _test_get_mask_selection(a, z, ix) - - # test errors - bad_selections = mask_selections_1d_bad + [ - np.zeros(50, dtype=bool), # too short - np.zeros(2000, dtype=bool), # too long - [[True, False], [False, True]], # too many dimensions - ] - for selection in bad_selections: - with pytest.raises(IndexError): - z.get_mask_selection(selection) - with pytest.raises(IndexError): - z.vindex[selection] - - -# noinspection PyStatementEffect -def test_get_mask_selection_2d(store: StorePath): - # setup - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix = np.random.binomial(1, p, size=a.size).astype(bool).reshape(a.shape) - _test_get_mask_selection(a, z, ix) - - # test errors - with pytest.raises(IndexError): - z.vindex[np.zeros((1000, 5), dtype=bool)] # too short - with pytest.raises(IndexError): - z.vindex[np.zeros((2000, 10), dtype=bool)] # too long - with pytest.raises(IndexError): - z.vindex[[True, False]] # wrong no. dimensions - - -def _test_set_mask_selection(v, a, z, selection): - a[:] = 0 - z[:] = 0 - a[selection] = v[selection] - z.set_mask_selection(selection, v[selection]) - assert_array_equal(a, z[:]) - z[:] = 0 - z.vindex[selection] = v[selection] - assert_array_equal(a, z[:]) - z[:] = 0 - z[selection] = v[selection] - assert_array_equal(a, z[:]) - - -def test_set_mask_selection_1d(store: StorePath): - # setup - v = np.arange(1050, dtype=int) - a = np.empty_like(v) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - _test_set_mask_selection(v, a, z, ix) - - for selection in mask_selections_1d_bad: - with pytest.raises(IndexError): - z.set_mask_selection(selection, 42) - with pytest.raises(IndexError): - z.vindex[selection] = 42 - - -def test_set_mask_selection_2d(store: StorePath): - # setup - v = np.arange(10000, dtype=int).reshape(1000, 10) - a = np.empty_like(v) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix = np.random.binomial(1, p, size=a.size).astype(bool).reshape(a.shape) - _test_set_mask_selection(v, a, z, ix) - - -def test_get_selection_out(store: StorePath): - # basic selections - a = np.arange(1050) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - - selections = [ - slice(50, 150), - slice(0, 1050), - slice(1, 2), - ] - for selection in selections: - expect = a[selection] - out = get_ndbuffer_class().from_numpy_array(np.empty(expect.shape)) - z.get_basic_selection(selection, out=out) - assert_array_equal(expect, out.as_numpy_array()[:]) - - with pytest.raises(TypeError): - z.get_basic_selection(Ellipsis, out=[]) - - # orthogonal selections - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - ix0 = np.random.binomial(1, p, size=a.shape[0]).astype(bool) - ix1 = np.random.binomial(1, 0.5, size=a.shape[1]).astype(bool) - selections = [ - # index both axes with array - (ix0, ix1), - # mixed indexing with array / slice - (ix0, slice(1, 5)), - (slice(250, 350), ix1), - # mixed indexing with array / int - (ix0, 4), - (42, ix1), - # mixed int array / bool array - (ix0, np.nonzero(ix1)[0]), - (np.nonzero(ix0)[0], ix1), - ] - for selection in selections: - expect = oindex(a, selection) - out = get_ndbuffer_class().from_numpy_array(np.zeros(expect.shape, dtype=expect.dtype)) - z.get_orthogonal_selection(selection, out=out) - assert_array_equal(expect, out.as_numpy_array()[:]) - - # coordinate selections - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - np.random.seed(42) - # test with different degrees of sparseness - for p in 0.5, 0.1, 0.01: - n = int(a.size * p) - ix0 = np.random.choice(a.shape[0], size=n, replace=True) - ix1 = np.random.choice(a.shape[1], size=n, replace=True) - selections = [ - # index both axes with array - (ix0, ix1), - # mixed indexing with array / int - (ix0, 4), - (42, ix1), - ] - for selection in selections: - expect = a[selection] - out = get_ndbuffer_class().from_numpy_array(np.zeros(expect.shape, dtype=expect.dtype)) - z.get_coordinate_selection(selection, out=out) - assert_array_equal(expect, out.as_numpy_array()[:]) - - -@pytest.mark.xfail(reason="fields are not supported in v3") -def test_get_selections_with_fields(store: StorePath): - a = [("aaa", 1, 4.2), ("bbb", 2, 8.4), ("ccc", 3, 12.6)] - a = np.array(a, dtype=[("foo", "S3"), ("bar", "i4"), ("baz", "f8")]) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(2,)) - - fields_fixture = [ - "foo", - ["foo"], - ["foo", "bar"], - ["foo", "baz"], - ["bar", "baz"], - ["foo", "bar", "baz"], - ["bar", "foo"], - ["baz", "bar", "foo"], - ] - - for fields in fields_fixture: - # total selection - expect = a[fields] - actual = z.get_basic_selection(Ellipsis, fields=fields) - assert_array_equal(expect, actual) - # alternative API - if isinstance(fields, str): - actual = z[fields] - assert_array_equal(expect, actual) - elif len(fields) == 2: - actual = z[fields[0], fields[1]] - assert_array_equal(expect, actual) - if isinstance(fields, str): - actual = z[..., fields] - assert_array_equal(expect, actual) - elif len(fields) == 2: - actual = z[..., fields[0], fields[1]] - assert_array_equal(expect, actual) - - # basic selection with slice - expect = a[fields][0:2] - actual = z.get_basic_selection(slice(0, 2), fields=fields) - assert_array_equal(expect, actual) - # alternative API - if isinstance(fields, str): - actual = z[0:2, fields] - assert_array_equal(expect, actual) - elif len(fields) == 2: - actual = z[0:2, fields[0], fields[1]] - assert_array_equal(expect, actual) - - # basic selection with single item - expect = a[fields][1] - actual = z.get_basic_selection(1, fields=fields) - assert_array_equal(expect, actual) - # alternative API - if isinstance(fields, str): - actual = z[1, fields] - assert_array_equal(expect, actual) - elif len(fields) == 2: - actual = z[1, fields[0], fields[1]] - assert_array_equal(expect, actual) - - # orthogonal selection - ix = [0, 2] - expect = a[fields][ix] - actual = z.get_orthogonal_selection(ix, fields=fields) - assert_array_equal(expect, actual) - # alternative API - if isinstance(fields, str): - actual = z.oindex[ix, fields] - assert_array_equal(expect, actual) - elif len(fields) == 2: - actual = z.oindex[ix, fields[0], fields[1]] - assert_array_equal(expect, actual) - - # coordinate selection - ix = [0, 2] - expect = a[fields][ix] - actual = z.get_coordinate_selection(ix, fields=fields) - assert_array_equal(expect, actual) - # alternative API - if isinstance(fields, str): - actual = z.vindex[ix, fields] - assert_array_equal(expect, actual) - elif len(fields) == 2: - actual = z.vindex[ix, fields[0], fields[1]] - assert_array_equal(expect, actual) - - # mask selection - ix = [True, False, True] - expect = a[fields][ix] - actual = z.get_mask_selection(ix, fields=fields) - assert_array_equal(expect, actual) - # alternative API - if isinstance(fields, str): - actual = z.vindex[ix, fields] - assert_array_equal(expect, actual) - elif len(fields) == 2: - actual = z.vindex[ix, fields[0], fields[1]] - assert_array_equal(expect, actual) - - # missing/bad fields - with pytest.raises(IndexError): - z.get_basic_selection(Ellipsis, fields=["notafield"]) - with pytest.raises(IndexError): - z.get_basic_selection(Ellipsis, fields=slice(None)) - - -@pytest.mark.xfail(reason="fields are not supported in v3") -def test_set_selections_with_fields(store: StorePath): - v = [("aaa", 1, 4.2), ("bbb", 2, 8.4), ("ccc", 3, 12.6)] - v = np.array(v, dtype=[("foo", "S3"), ("bar", "i4"), ("baz", "f8")]) - a = np.empty_like(v) - z = zarr_array_from_numpy_array(store, v, chunk_shape=(2,)) - - fields_fixture = [ - "foo", - [], - ["foo"], - ["foo", "bar"], - ["foo", "baz"], - ["bar", "baz"], - ["foo", "bar", "baz"], - ["bar", "foo"], - ["baz", "bar", "foo"], - ] - - for fields in fields_fixture: - # currently multi-field assignment is not supported in numpy, so we won't support - # it either - if isinstance(fields, list) and len(fields) > 1: - with pytest.raises(IndexError): - z.set_basic_selection(Ellipsis, v, fields=fields) - with pytest.raises(IndexError): - z.set_orthogonal_selection([0, 2], v, fields=fields) - with pytest.raises(IndexError): - z.set_coordinate_selection([0, 2], v, fields=fields) - with pytest.raises(IndexError): - z.set_mask_selection([True, False, True], v, fields=fields) - - else: - if isinstance(fields, list) and len(fields) == 1: - # work around numpy does not support multi-field assignment even if there - # is only one field - key = fields[0] - elif isinstance(fields, list) and len(fields) == 0: - # work around numpy ambiguity about what is a field selection - key = Ellipsis - else: - key = fields - - # setup expectation - a[:] = ("", 0, 0) - z[:] = ("", 0, 0) - assert_array_equal(a, z[:]) - a[key] = v[key] - # total selection - z.set_basic_selection(Ellipsis, v[key], fields=fields) - assert_array_equal(a, z[:]) - - # basic selection with slice - a[:] = ("", 0, 0) - z[:] = ("", 0, 0) - a[key][0:2] = v[key][0:2] - z.set_basic_selection(slice(0, 2), v[key][0:2], fields=fields) - assert_array_equal(a, z[:]) - - # orthogonal selection - a[:] = ("", 0, 0) - z[:] = ("", 0, 0) - ix = [0, 2] - a[key][ix] = v[key][ix] - z.set_orthogonal_selection(ix, v[key][ix], fields=fields) - assert_array_equal(a, z[:]) - - # coordinate selection - a[:] = ("", 0, 0) - z[:] = ("", 0, 0) - ix = [0, 2] - a[key][ix] = v[key][ix] - z.set_coordinate_selection(ix, v[key][ix], fields=fields) - assert_array_equal(a, z[:]) - - # mask selection - a[:] = ("", 0, 0) - z[:] = ("", 0, 0) - ix = [True, False, True] - a[key][ix] = v[key][ix] - z.set_mask_selection(ix, v[key][ix], fields=fields) - assert_array_equal(a, z[:]) - - -def test_slice_selection_uints(): - arr = np.arange(24).reshape((4, 6)) - idx = np.uint64(3) - slice_sel = make_slice_selection((idx,)) - assert arr[tuple(slice_sel)].shape == (1, 6) - - -def test_numpy_int_indexing(store: StorePath): - a = np.arange(1050) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(100,)) - assert a[42] == z[42] - assert a[np.int64(42)] == z[np.int64(42)] - - -@pytest.mark.parametrize( - "shape, chunks, ops", - [ - # 1D test cases - ((1070,), (50,), [("__getitem__", (slice(200, 400),))]), - ((1070,), (50,), [("__getitem__", (slice(200, 400, 100),))]), - ( - (1070,), - (50,), - [ - ("__getitem__", (slice(200, 400),)), - ("__setitem__", (slice(200, 400, 100),)), - ], - ), - # 2D test cases - ( - (40, 50), - (5, 8), - [ - ("__getitem__", (slice(6, 37, 13), (slice(4, 10)))), - ("__setitem__", (slice(None), (slice(None)))), - ], - ), - ], -) -async def test_accessed_chunks(shape, chunks, ops): - # Test that only the required chunks are accessed during basic selection operations - # shape: array shape - # chunks: chunk size - # ops: list of tuples with (optype, tuple of slices) - # optype = "__getitem__" or "__setitem__", tuple length must match number of dims - import itertools - - # Use a counting dict as the backing store so we can track the items access - store = await CountingDict.open() - z = zarr_array_from_numpy_array(StorePath(store), np.zeros(shape), chunk_shape=chunks) - - for ii, (optype, slices) in enumerate(ops): - # Resolve the slices into the accessed chunks for each dimension - chunks_per_dim = [] - for N, C, sl in zip(shape, chunks, slices, strict=True): - chunk_ind = np.arange(N, dtype=int)[sl] // C - chunks_per_dim.append(np.unique(chunk_ind)) - - # Combine and generate the cartesian product to determine the chunks keys that - # will be accessed - chunks_accessed = [] - for comb in itertools.product(*chunks_per_dim): - chunks_accessed.append(".".join([str(ci) for ci in comb])) - - counts_before = store.counter.copy() - - # Perform the operation - if optype == "__getitem__": - z[slices] - else: - z[slices] = ii - - # Get the change in counts - delta_counts = store.counter - counts_before - - # Check that the access counts for the operation have increased by one for all - # the chunks we expect to be included - for ci in chunks_accessed: - assert delta_counts.pop((optype, ci)) == 1 - - # If the chunk was partially written to it will also have been read once. We - # don't determine if the chunk was actually partial here, just that the - # counts are consistent that this might have happened - if optype == "__setitem__": - assert ("__getitem__", ci) not in delta_counts or delta_counts.pop( - ("__getitem__", ci) - ) == 1 - # Check that no other chunks were accessed - assert len(delta_counts) == 0 - - -@pytest.mark.parametrize( - "selection", - [ - # basic selection - [...], - [1, ...], - [slice(None)], - [1, 3], - [[1, 2, 3], 9], - [np.arange(1000)], - [slice(5, 15)], - [slice(2, 4), 4], - [[1, 3]], - # mask selection - [np.tile([True, False], (1000, 5))], - [np.full((1000, 10), False)], - # coordinate selection - [[1, 2, 3, 4], [5, 6, 7, 8]], - [[100, 200, 300], [4, 5, 6]], - ], -) -def test_indexing_equals_numpy(store, selection): - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - # note: in python 3.10 a[*selection] is not valid unpacking syntax - expected = a[(*selection,)] - actual = z[(*selection,)] - assert_array_equal(expected, actual, err_msg=f"selection: {selection}") - - -@pytest.mark.parametrize( - "selection", - [ - [np.tile([True, False], 500), np.tile([True, False], 5)], - [np.full(1000, False), np.tile([True, False], 5)], - [np.full(1000, True), np.full(10, True)], - [np.full(1000, True), [True, False] * 5], - ], -) -def test_orthogonal_bool_indexing_like_numpy_ix(store, selection): - a = np.arange(10000, dtype=int).reshape(1000, 10) - z = zarr_array_from_numpy_array(store, a, chunk_shape=(300, 3)) - expected = a[np.ix_(*selection)] - # note: in python 3.10 z[*selection] is not valid unpacking syntax - actual = z[(*selection,)] - assert_array_equal(expected, actual, err_msg=f"{selection=}") diff --git a/tests/v3/test_metadata/test_v2.py b/tests/v3/test_metadata/test_v2.py deleted file mode 100644 index 2d6f4d0cf5..0000000000 --- a/tests/v3/test_metadata/test_v2.py +++ /dev/null @@ -1,72 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING, Literal - -from zarr.abc.codec import Codec - -if TYPE_CHECKING: - from typing import Any - -import pytest - -from zarr.codecs import GzipCodec -from zarr.metadata import ArrayV2Metadata, parse_zarr_format_v2 - - -def test_parse_zarr_format_valid() -> None: - assert parse_zarr_format_v2(2) == 2 - - -@pytest.mark.parametrize("data", [None, 1, 3, 4, 5, "3"]) -def test_parse_zarr_format_invalid(data: Any) -> None: - with pytest.raises(ValueError, match=f"Invalid value. Expected 2. Got {data}"): - parse_zarr_format_v2(data) - - -@pytest.mark.parametrize("attributes", [None, {"foo": "bar"}]) -@pytest.mark.parametrize("filters", [(), (GzipCodec().to_dict())]) -@pytest.mark.parametrize("compressor", [None, GzipCodec().to_dict()]) -@pytest.mark.parametrize("fill_value", [0, 1]) -@pytest.mark.parametrize("order", ["C", "F"]) -@pytest.mark.parametrize("dimension_separator", [".", "/", None]) -def test_metadata_to_dict( - compressor: Codec | None, - filters: list[Codec] | None, - fill_value: Any, - order: Literal["C", "F"], - dimension_separator: Literal[".", "/"] | None, - attributes: None | dict[str, Any], -) -> None: - shape = (1, 2, 3) - chunks = (1,) * len(shape) - data_type = "|u1" - metadata_dict = { - "zarr_format": 2, - "shape": shape, - "chunks": chunks, - "dtype": data_type, - "order": order, - "compressor": compressor, - "filters": filters, - "fill_value": fill_value, - } - - if attributes is not None: - metadata_dict["attributes"] = attributes - if dimension_separator is not None: - metadata_dict["dimension_separator"] = dimension_separator - - metadata = ArrayV2Metadata.from_dict(metadata_dict) - observed = metadata.to_dict() - expected = metadata_dict.copy() - - if attributes is None: - assert observed["attributes"] == {} - observed.pop("attributes") - - if dimension_separator is None: - expected_dimension_sep = "." - assert observed["dimension_separator"] == expected_dimension_sep - observed.pop("dimension_separator") - - assert observed == expected diff --git a/tests/v3/test_metadata/test_v3.py b/tests/v3/test_metadata/test_v3.py deleted file mode 100644 index 2b25c776e0..0000000000 --- a/tests/v3/test_metadata/test_v3.py +++ /dev/null @@ -1,232 +0,0 @@ -from __future__ import annotations - -import re -from typing import TYPE_CHECKING, Literal - -from zarr.abc.codec import Codec -from zarr.chunk_key_encodings import DefaultChunkKeyEncoding, V2ChunkKeyEncoding -from zarr.codecs.bytes import BytesCodec - -if TYPE_CHECKING: - from typing import Any - -from collections.abc import Sequence - -import numpy as np -import pytest - -from zarr.metadata import ArrayV3Metadata, parse_dimension_names -from zarr.metadata import parse_fill_value_v3 as parse_fill_value -from zarr.metadata import parse_zarr_format_v3 as parse_zarr_format - -bool_dtypes = ("bool",) - -int_dtypes = ( - "int8", - "int16", - "int32", - "int64", - "uint8", - "uint16", - "uint32", - "uint64", -) - -float_dtypes = ( - "float16", - "float32", - "float64", -) - -complex_dtypes = ("complex64", "complex128") - -dtypes = (*bool_dtypes, *int_dtypes, *float_dtypes, *complex_dtypes) - - -@pytest.mark.parametrize("data", [None, 1, 2, 4, 5, "3"]) -def test_parse_zarr_format_invalid(data: Any) -> None: - with pytest.raises(ValueError, match=f"Invalid value. Expected 3. Got {data}"): - parse_zarr_format(data) - - -def test_parse_zarr_format_valid() -> None: - assert parse_zarr_format(3) == 3 - - -@pytest.mark.parametrize("data", [(), [1, 2, "a"], {"foo": 10}]) -def parse_dimension_names_invalid(data: Any) -> None: - with pytest.raises(TypeError, match="Expected either None or iterable of str,"): - parse_dimension_names(data) - - -@pytest.mark.parametrize("data", [None, ("a", "b", "c"), ["a", "a", "a"]]) -def parse_dimension_names_valid(data: Sequence[str] | None) -> None: - assert parse_dimension_names(data) == data - - -@pytest.mark.parametrize("dtype_str", dtypes) -def test_parse_auto_fill_value(dtype_str: str) -> None: - """ - Test that parse_fill_value(None, dtype) results in the 0 value for the given dtype. - """ - dtype = np.dtype(dtype_str) - fill_value = None - assert parse_fill_value(fill_value, dtype) == dtype.type(0) - - -@pytest.mark.parametrize("fill_value", [0, 1.11, False, True]) -@pytest.mark.parametrize("dtype_str", dtypes) -def test_parse_fill_value_valid(fill_value: Any, dtype_str: str) -> None: - """ - Test that parse_fill_value(fill_value, dtype) casts fill_value to the given dtype. - """ - dtype = np.dtype(dtype_str) - assert parse_fill_value(fill_value, dtype) == dtype.type(fill_value) - - -@pytest.mark.parametrize("fill_value", ["not a valid value"]) -@pytest.mark.parametrize("dtype_str", [*int_dtypes, *float_dtypes, *complex_dtypes]) -def test_parse_fill_value_invalid_value(fill_value: Any, dtype_str: str) -> None: - """ - Test that parse_fill_value(fill_value, dtype) raises ValueError for invalid values. - This test excludes bool because the bool constructor takes anything. - """ - dtype = np.dtype(dtype_str) - with pytest.raises(ValueError): - parse_fill_value(fill_value, dtype) - - -@pytest.mark.parametrize("fill_value", [[1.0, 0.0], [0, 1], complex(1, 1), np.complex64(0)]) -@pytest.mark.parametrize("dtype_str", [*complex_dtypes]) -def test_parse_fill_value_complex(fill_value: Any, dtype_str: str) -> None: - """ - Test that parse_fill_value(fill_value, dtype) correctly handles complex values represented - as length-2 sequences - """ - dtype = np.dtype(dtype_str) - if isinstance(fill_value, list): - expected = dtype.type(complex(*fill_value)) - else: - expected = dtype.type(fill_value) - assert expected == parse_fill_value(fill_value, dtype) - - -@pytest.mark.parametrize("fill_value", [[1.0, 0.0, 3.0], [0, 1, 3], [1]]) -@pytest.mark.parametrize("dtype_str", [*complex_dtypes]) -def test_parse_fill_value_complex_invalid(fill_value: Any, dtype_str: str) -> None: - """ - Test that parse_fill_value(fill_value, dtype) correctly rejects sequences with length not - equal to 2 - """ - dtype = np.dtype(dtype_str) - match = ( - f"Got an invalid fill value for complex data type {dtype}." - f"Expected a sequence with 2 elements, but {fill_value} has " - f"length {len(fill_value)}." - ) - with pytest.raises(ValueError, match=re.escape(match)): - parse_fill_value(fill_value=fill_value, dtype=dtype) - - -@pytest.mark.parametrize("fill_value", [{"foo": 10}]) -@pytest.mark.parametrize("dtype_str", [*int_dtypes, *float_dtypes, *complex_dtypes]) -def test_parse_fill_value_invalid_type(fill_value: Any, dtype_str: str) -> None: - """ - Test that parse_fill_value(fill_value, dtype) raises TypeError for invalid non-sequential types. - This test excludes bool because the bool constructor takes anything. - """ - dtype = np.dtype(dtype_str) - match = "must be" - with pytest.raises(TypeError, match=match): - parse_fill_value(fill_value, dtype) - - -@pytest.mark.parametrize( - "fill_value", - [ - [ - 1, - ], - (1, 23, 4), - ], -) -@pytest.mark.parametrize("dtype_str", [*int_dtypes, *float_dtypes]) -def test_parse_fill_value_invalid_type_sequence(fill_value: Any, dtype_str: str) -> None: - """ - Test that parse_fill_value(fill_value, dtype) raises TypeError for invalid sequential types. - This test excludes bool because the bool constructor takes anything, and complex because - complex values can be created from length-2 sequences. - """ - dtype = np.dtype(dtype_str) - match = f"Cannot parse non-string sequence {fill_value} as a scalar with type {dtype}" - with pytest.raises(TypeError, match=re.escape(match)): - parse_fill_value(fill_value, dtype) - - -@pytest.mark.parametrize("chunk_grid", ["regular"]) -@pytest.mark.parametrize("attributes", [None, {"foo": "bar"}]) -@pytest.mark.parametrize("codecs", [[BytesCodec()]]) -@pytest.mark.parametrize("fill_value", [0, 1]) -@pytest.mark.parametrize("chunk_key_encoding", ["v2", "default"]) -@pytest.mark.parametrize("dimension_separator", [".", "/", None]) -@pytest.mark.parametrize("dimension_names", ["nones", "strings", "missing"]) -def test_metadata_to_dict( - chunk_grid: str, - codecs: list[Codec], - fill_value: Any, - chunk_key_encoding: Literal["v2", "default"], - dimension_separator: Literal[".", "/"] | None, - dimension_names: Literal["nones", "strings", "missing"], - attributes: None | dict[str, Any], -) -> None: - shape = (1, 2, 3) - data_type = "uint8" - if chunk_grid == "regular": - cgrid = {"name": "regular", "configuration": {"chunk_shape": (1, 1, 1)}} - - cke: dict[str, Any] - cke_name_dict = {"name": chunk_key_encoding} - if dimension_separator is not None: - cke = cke_name_dict | {"configuration": {"separator": dimension_separator}} - else: - cke = cke_name_dict - dnames: tuple[str | None, ...] | None - - if dimension_names == "strings": - dnames = tuple(map(str, range(len(shape)))) - elif dimension_names == "missing": - dnames = None - elif dimension_names == "nones": - dnames = (None,) * len(shape) - - metadata_dict = { - "zarr_format": 3, - "node_type": "array", - "shape": shape, - "chunk_grid": cgrid, - "data_type": data_type, - "chunk_key_encoding": cke, - "codecs": tuple(c.to_dict() for c in codecs), - "fill_value": fill_value, - } - - if attributes is not None: - metadata_dict["attributes"] = attributes - if dnames is not None: - metadata_dict["dimension_names"] = dnames - - metadata = ArrayV3Metadata.from_dict(metadata_dict) - observed = metadata.to_dict() - expected = metadata_dict.copy() - if attributes is None: - assert observed["attributes"] == {} - observed.pop("attributes") - if dimension_separator is None: - if chunk_key_encoding == "default": - expected_cke_dict = DefaultChunkKeyEncoding(separator="/").to_dict() - else: - expected_cke_dict = V2ChunkKeyEncoding(separator=".").to_dict() - assert observed["chunk_key_encoding"] == expected_cke_dict - observed.pop("chunk_key_encoding") - expected.pop("chunk_key_encoding") - assert observed == expected diff --git a/tests/v3/test_properties.py b/tests/v3/test_properties.py deleted file mode 100644 index d339f5dff6..0000000000 --- a/tests/v3/test_properties.py +++ /dev/null @@ -1,69 +0,0 @@ -import numpy as np -import pytest -from numpy.testing import assert_array_equal - -pytest.importorskip("hypothesis") - -import hypothesis.extra.numpy as npst # noqa -import hypothesis.strategies as st # noqa -from hypothesis import given, settings # noqa -from zarr.strategies import arrays, np_arrays, basic_indices # noqa - - -@given(st.data()) -def test_roundtrip(data): - nparray = data.draw(np_arrays) - zarray = data.draw(arrays(arrays=st.just(nparray))) - assert_array_equal(nparray, zarray[:]) - - -@given(data=st.data()) -def test_basic_indexing(data): - zarray = data.draw(arrays()) - nparray = zarray[:] - indexer = data.draw(basic_indices(shape=nparray.shape)) - actual = zarray[indexer] - assert_array_equal(nparray[indexer], actual) - - new_data = np.ones_like(actual) - zarray[indexer] = new_data - nparray[indexer] = new_data - assert_array_equal(nparray, zarray[:]) - - -@given(data=st.data()) -def test_vindex(data): - zarray = data.draw(arrays()) - nparray = zarray[:] - - indexer = data.draw( - npst.integer_array_indices( - shape=nparray.shape, result_shape=npst.array_shapes(max_dims=None) - ) - ) - actual = zarray.vindex[indexer] - assert_array_equal(nparray[indexer], actual) - - -# @st.composite -# def advanced_indices(draw, *, shape): -# basic_idxr = draw( -# basic_indices( -# shape=shape, min_dims=len(shape), max_dims=len(shape), allow_ellipsis=False -# ).filter(lambda x: isinstance(x, tuple)) -# ) - -# int_idxr = draw( -# npst.integer_array_indices(shape=shape, result_shape=npst.array_shapes(max_dims=1)) -# ) -# args = tuple( -# st.sampled_from((l, r)) for l, r in zip_longest(basic_idxr, int_idxr, fillvalue=slice(None)) -# ) -# return draw(st.tuples(*args)) - - -# @given(st.data()) -# def test_roundtrip_object_array(data): -# nparray = data.draw(np_arrays) -# zarray = data.draw(arrays(arrays=st.just(nparray))) -# assert_array_equal(nparray, zarray[:]) diff --git a/tests/v3/test_store/test_core.py b/tests/v3/test_store/test_core.py deleted file mode 100644 index 1d277cf502..0000000000 --- a/tests/v3/test_store/test_core.py +++ /dev/null @@ -1,36 +0,0 @@ -from pathlib import Path - -import pytest - -from zarr.store.core import make_store_path -from zarr.store.local import LocalStore -from zarr.store.memory import MemoryStore - - -async def test_make_store_path(tmpdir) -> None: - # None - store_path = await make_store_path(None) - assert isinstance(store_path.store, MemoryStore) - - # str - store_path = await make_store_path(str(tmpdir)) - assert isinstance(store_path.store, LocalStore) - assert Path(store_path.store.root) == Path(tmpdir) - - # Path - store_path = await make_store_path(Path(tmpdir)) - assert isinstance(store_path.store, LocalStore) - assert Path(store_path.store.root) == Path(tmpdir) - - # Store - store_path = await make_store_path(store_path.store) - assert isinstance(store_path.store, LocalStore) - assert Path(store_path.store.root) == Path(tmpdir) - - # StorePath - store_path = await make_store_path(store_path) - assert isinstance(store_path.store, LocalStore) - assert Path(store_path.store.root) == Path(tmpdir) - - with pytest.raises(TypeError): - await make_store_path(1) diff --git a/tests/v3/test_store/test_local.py b/tests/v3/test_store/test_local.py deleted file mode 100644 index 6b7f91b87d..0000000000 --- a/tests/v3/test_store/test_local.py +++ /dev/null @@ -1,39 +0,0 @@ -from __future__ import annotations - -import pytest - -from zarr.buffer import Buffer -from zarr.store.local import LocalStore -from zarr.testing.store import StoreTests - - -class TestLocalStore(StoreTests[LocalStore]): - store_cls = LocalStore - - def get(self, store: LocalStore, key: str) -> Buffer: - return Buffer.from_bytes((store.root / key).read_bytes()) - - def set(self, store: LocalStore, key: str, value: Buffer) -> None: - parent = (store.root / key).parent - if not parent.exists(): - parent.mkdir(parents=True) - (store.root / key).write_bytes(value.to_bytes()) - - @pytest.fixture - def store_kwargs(self, tmpdir) -> dict[str, str]: - return {"root": str(tmpdir), "mode": "r+"} - - def test_store_repr(self, store: LocalStore) -> None: - assert str(store) == f"file://{store.root!s}" - - def test_store_supports_writes(self, store: LocalStore) -> None: - assert store.supports_writes - - def test_store_supports_partial_writes(self, store: LocalStore) -> None: - assert store.supports_partial_writes - - def test_store_supports_listing(self, store: LocalStore) -> None: - assert store.supports_listing - - def test_list_prefix(self, store: LocalStore) -> None: - assert True diff --git a/tests/v3/test_store/test_memory.py b/tests/v3/test_store/test_memory.py deleted file mode 100644 index 5b8f1ef875..0000000000 --- a/tests/v3/test_store/test_memory.py +++ /dev/null @@ -1,42 +0,0 @@ -from __future__ import annotations - -import pytest - -from zarr.buffer import Buffer -from zarr.store.memory import MemoryStore -from zarr.testing.store import StoreTests - - -class TestMemoryStore(StoreTests[MemoryStore]): - store_cls = MemoryStore - - def set(self, store: MemoryStore, key: str, value: Buffer) -> None: - store._store_dict[key] = value - - def get(self, store: MemoryStore, key: str) -> Buffer: - return store._store_dict[key] - - @pytest.fixture(scope="function", params=[None, {}]) - def store_kwargs( - self, request: pytest.FixtureRequest - ) -> dict[str, str | None | dict[str, Buffer]]: - return {"store_dict": request.param, "mode": "r+"} - - @pytest.fixture(scope="function") - def store(self, store_kwargs: str | None | dict[str, Buffer]) -> MemoryStore: - return self.store_cls(**store_kwargs) - - def test_store_repr(self, store: MemoryStore) -> None: - assert str(store) == f"memory://{id(store._store_dict)}" - - def test_store_supports_writes(self, store: MemoryStore) -> None: - assert store.supports_writes - - def test_store_supports_listing(self, store: MemoryStore) -> None: - assert store.supports_listing - - def test_store_supports_partial_writes(self, store: MemoryStore) -> None: - assert store.supports_partial_writes - - def test_list_prefix(self, store: MemoryStore) -> None: - assert True diff --git a/tests/v3/test_store/test_remote.py b/tests/v3/test_store/test_remote.py deleted file mode 100644 index be9fa5ef67..0000000000 --- a/tests/v3/test_store/test_remote.py +++ /dev/null @@ -1,157 +0,0 @@ -import os - -import fsspec -import pytest -from upath import UPath - -from zarr.buffer import Buffer, default_buffer_prototype -from zarr.store import RemoteStore -from zarr.sync import sync -from zarr.testing.store import StoreTests - -s3fs = pytest.importorskip("s3fs") -requests = pytest.importorskip("requests") -moto_server = pytest.importorskip("moto.moto_server.threaded_moto_server") -moto = pytest.importorskip("moto") - -# ### amended from s3fs ### # -test_bucket_name = "test" -secure_bucket_name = "test-secure" -port = 5555 -endpoint_url = f"http://127.0.0.1:{port}/" - - -@pytest.fixture(scope="module") -def s3_base(): - # writable local S3 system - - # This fixture is module-scoped, meaning that we can reuse the MotoServer across all tests - server = moto_server.ThreadedMotoServer(ip_address="127.0.0.1", port=port) - server.start() - if "AWS_SECRET_ACCESS_KEY" not in os.environ: - os.environ["AWS_SECRET_ACCESS_KEY"] = "foo" - if "AWS_ACCESS_KEY_ID" not in os.environ: - os.environ["AWS_ACCESS_KEY_ID"] = "foo" - - yield - server.stop() - - -def get_boto3_client(): - from botocore.session import Session - - # NB: we use the sync botocore client for setup - session = Session() - return session.create_client("s3", endpoint_url=endpoint_url) - - -@pytest.fixture(autouse=True, scope="function") -def s3(s3_base): - """ - Quoting Martin Durant: - pytest-asyncio creates a new event loop for each async test. - When an async-mode s3fs instance is made from async, it will be assigned to the loop from - which it is made. That means that if you use s3fs again from a subsequent test, - you will have the same identical instance, but be running on a different loop - which fails. - - For the rest: it's very convenient to clean up the state of the store between tests, - make sure we start off blank each time. - - https://github.com/zarr-developers/zarr-python/pull/1785#discussion_r1634856207 - """ - client = get_boto3_client() - client.create_bucket(Bucket=test_bucket_name, ACL="public-read") - s3fs.S3FileSystem.clear_instance_cache() - s3 = s3fs.S3FileSystem(anon=False, client_kwargs={"endpoint_url": endpoint_url}) - session = sync(s3.set_session()) - s3.invalidate_cache() - yield s3 - requests.post(f"{endpoint_url}/moto-api/reset") - client.close() - sync(session.close()) - - -# ### end from s3fs ### # - - -async def alist(it): - out = [] - async for a in it: - out.append(a) - return out - - -async def test_basic(): - store = await RemoteStore.open( - f"s3://{test_bucket_name}", mode="w", endpoint_url=endpoint_url, anon=False - ) - assert not await alist(store.list()) - assert not await store.exists("foo") - data = b"hello" - await store.set("foo", Buffer.from_bytes(data)) - assert await store.exists("foo") - assert (await store.get("foo", prototype=default_buffer_prototype())).to_bytes() == data - out = await store.get_partial_values( - prototype=default_buffer_prototype(), key_ranges=[("foo", (1, None))] - ) - assert out[0].to_bytes() == data[1:] - - -class TestRemoteStoreS3(StoreTests[RemoteStore]): - store_cls = RemoteStore - - @pytest.fixture(scope="function", params=("use_upath", "use_str")) - def store_kwargs(self, request) -> dict[str, str | bool]: - url = f"s3://{test_bucket_name}" - anon = False - mode = "r+" - if request.param == "use_upath": - return {"mode": mode, "url": UPath(url, endpoint_url=endpoint_url, anon=anon)} - elif request.param == "use_str": - return {"url": url, "mode": mode, "anon": anon, "endpoint_url": endpoint_url} - - raise AssertionError - - @pytest.fixture(scope="function") - def store(self, store_kwargs: dict[str, str | bool]) -> RemoteStore: - url = store_kwargs["url"] - mode = store_kwargs["mode"] - if isinstance(url, UPath): - out = self.store_cls(url=url, mode=mode) - else: - endpoint_url = store_kwargs["endpoint_url"] - out = self.store_cls(url=url, asynchronous=True, mode=mode, endpoint_url=endpoint_url) - return out - - def get(self, store: RemoteStore, key: str) -> Buffer: - # make a new, synchronous instance of the filesystem because this test is run in sync code - fs, _ = fsspec.url_to_fs( - url=store._url, - asynchronous=False, - anon=store._fs.anon, - endpoint_url=store._fs.endpoint_url, - ) - return Buffer.from_bytes(fs.cat(f"{store.path}/{key}")) - - def set(self, store: RemoteStore, key: str, value: Buffer) -> None: - # make a new, synchronous instance of the filesystem because this test is run in sync code - fs, _ = fsspec.url_to_fs( - url=store._url, - asynchronous=False, - anon=store._fs.anon, - endpoint_url=store._fs.endpoint_url, - ) - fs.write_bytes(f"{store.path}/{key}", value.to_bytes()) - - def test_store_repr(self, store: RemoteStore) -> None: - assert str(store) == f"s3://{test_bucket_name}" - - def test_store_supports_writes(self, store: RemoteStore) -> None: - assert True - - @pytest.mark.xfail - def test_store_supports_partial_writes(self, store: RemoteStore) -> None: - raise AssertionError - - def test_store_supports_listing(self, store: RemoteStore) -> None: - assert True diff --git a/tests/v3/test_sync.py b/tests/v3/test_sync.py deleted file mode 100644 index 7e3b8dd111..0000000000 --- a/tests/v3/test_sync.py +++ /dev/null @@ -1,124 +0,0 @@ -import asyncio -from collections.abc import AsyncGenerator -from unittest.mock import AsyncMock, patch - -import pytest - -from zarr.sync import SyncError, SyncMixin, _get_lock, _get_loop, sync - - -@pytest.fixture(params=[True, False]) -def sync_loop(request) -> asyncio.AbstractEventLoop | None: - if request.param is True: - return _get_loop() - - if request.param is False: - return None - - -def test_get_loop() -> None: - # test that calling _get_loop() twice returns the same loop - loop = _get_loop() - loop2 = _get_loop() - assert loop is loop2 - - -def test_get_lock() -> None: - # test that calling _get_lock() twice returns the same lock - lock = _get_lock() - lock2 = _get_lock() - assert lock is lock2 - - -def test_sync(sync_loop: asyncio.AbstractEventLoop | None) -> None: - foo = AsyncMock(return_value="foo") - assert sync(foo(), loop=sync_loop) == "foo" - foo.assert_awaited_once() - - -def test_sync_raises(sync_loop: asyncio.AbstractEventLoop | None) -> None: - foo = AsyncMock(side_effect=ValueError("foo-bar")) - with pytest.raises(ValueError, match="foo-bar"): - sync(foo(), loop=sync_loop) - foo.assert_awaited_once() - - -def test_sync_timeout() -> None: - duration = 0.002 - - async def foo() -> None: - await asyncio.sleep(duration) - - with pytest.raises(asyncio.TimeoutError): - sync(foo(), timeout=duration / 2) - - -def test_sync_raises_if_no_coroutine(sync_loop: asyncio.AbstractEventLoop | None) -> None: - def foo() -> str: - return "foo" - - with pytest.raises(TypeError): - sync(foo(), loop=sync_loop) - - -@pytest.mark.filterwarnings("ignore:coroutine.*was never awaited") -def test_sync_raises_if_loop_is_closed() -> None: - loop = _get_loop() - - foo = AsyncMock(return_value="foo") - with patch.object(loop, "is_closed", return_value=True): - with pytest.raises(RuntimeError): - sync(foo(), loop=loop) - foo.assert_not_awaited() - - -@pytest.mark.filterwarnings("ignore:coroutine.*was never awaited") -def test_sync_raises_if_calling_sync_from_within_a_running_loop( - sync_loop: asyncio.AbstractEventLoop | None, -) -> None: - def foo() -> str: - # technically, this should be an async function but doing that - # yields a warning because it is never awaited by the inner function - return "foo" - - async def bar() -> str: - return sync(foo(), loop=sync_loop) - - with pytest.raises(SyncError): - sync(bar(), loop=sync_loop) - - -@pytest.mark.filterwarnings("ignore:coroutine.*was never awaited") -def test_sync_raises_if_loop_is_invalid_type() -> None: - foo = AsyncMock(return_value="foo") - with pytest.raises(TypeError): - sync(foo(), loop=1) - foo.assert_not_awaited() - - -def test_sync_mixin(sync_loop) -> None: - class AsyncFoo: - def __init__(self) -> None: - pass - - async def foo(self) -> str: - return "foo" - - async def bar(self) -> AsyncGenerator: - for i in range(10): - yield i - - class SyncFoo(SyncMixin): - def __init__(self, async_foo: AsyncFoo) -> None: - self._async_foo = async_foo - - def foo(self) -> str: - return self._sync(self._async_foo.foo()) - - def bar(self) -> list[int]: - return self._sync_iter(self._async_foo.bar()) - - async_foo = AsyncFoo() - foo = SyncFoo(async_foo) - assert foo.foo() == "foo" - assert foo.bar() == list(range(10)) diff --git a/tests/v3/test_v2.py b/tests/v3/test_v2.py deleted file mode 100644 index 7a7d728067..0000000000 --- a/tests/v3/test_v2.py +++ /dev/null @@ -1,29 +0,0 @@ -from collections.abc import Iterator - -import numpy as np -import pytest - -from zarr.abc.store import Store -from zarr.array import Array -from zarr.store import MemoryStore, StorePath - - -@pytest.fixture -async def store() -> Iterator[Store]: - yield StorePath(await MemoryStore.open(mode="w")) - - -def test_simple(store: Store): - data = np.arange(0, 256, dtype="uint16").reshape((16, 16)) - - a = Array.create( - store / "simple_v2", - zarr_format=2, - shape=data.shape, - chunks=(16, 16), - dtype=data.dtype, - fill_value=0, - ) - - a[:, :] = data - assert np.array_equal(data, a[:, :]) diff --git a/uv.lock b/uv.lock new file mode 100644 index 0000000000..327d3e0822 --- /dev/null +++ b/uv.lock @@ -0,0 +1,3756 @@ +version = 1 +revision = 3 +requires-python = ">=3.12" +resolution-markers = [ + "python_full_version >= '3.15'", + "python_full_version < '3.15'", +] + +[[package]] +name = "aiobotocore" +version = "3.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiohttp" }, + { name = "aioitertools" }, + { name = "botocore" }, + { name = "jmespath" }, + { name = "multidict" }, + { name = "python-dateutil" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e7/75/42cce839c2ec263ff74b10b650fe36b066fbb124cbee6f247eac0983e1ab/aiobotocore-3.7.0.tar.gz", hash = "sha256:c64d871ed5491a6571948dd48eabd185b46c6c23b64e3afd0c059fc7593ada30", size = 127054, upload-time = "2026-05-09T10:02:52.332Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/90/5f/85535dfb3cfd6442d66d1df1694062c5d6df02f895329e7e120b2a3d2b8b/aiobotocore-3.7.0-py3-none-any.whl", hash = "sha256:680bde7c64679a821a9312641b759d9497f790ba8b2e88c6959e6273ee765b8e", size = 89539, upload-time = "2026-05-09T10:02:50.389Z" }, +] + +[[package]] +name = "aiohappyeyeballs" +version = "2.6.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/26/30/f84a107a9c4331c14b2b586036f40965c128aa4fee4dda5d3d51cb14ad54/aiohappyeyeballs-2.6.1.tar.gz", hash = "sha256:c3f9d0113123803ccadfdf3f0faa505bc78e6a72d1cc4806cbd719826e943558", size = 22760, upload-time = "2025-03-12T01:42:48.764Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0f/15/5bf3b99495fb160b63f95972b81750f18f7f4e02ad051373b669d17d44f2/aiohappyeyeballs-2.6.1-py3-none-any.whl", hash = "sha256:f349ba8f4b75cb25c99c5c2d84e997e485204d2902a9597802b0371f09331fb8", size = 15265, upload-time = "2025-03-12T01:42:47.083Z" }, +] + +[[package]] +name = "aiohttp" +version = "3.14.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiohappyeyeballs" }, + { name = "aiosignal" }, + { name = "attrs" }, + { name = "frozenlist" }, + { name = "multidict" }, + { name = "propcache" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "yarl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/58/d9/22ce5786ac0c1653ae8b6c23bded02c1686d11f0dbb45b31ce128e0df985/aiohttp-3.14.3.tar.gz", hash = "sha256:9491196535a88924a60afd5b5f434b5b203b6cc616250878dbdb223a8f7844bc", size = 7971213, upload-time = "2026-07-23T01:57:27.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/d4/eb96299230e20acf2efae207cb8d69051f1f68e357e5ea5e479bf6fb097a/aiohttp-3.14.3-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:39aded8c7f3b935b54aab1d8d73c70ec0ee2d3ec3b943e0e86611bc150ba47f5", size = 754690, upload-time = "2026-07-23T01:53:47.332Z" }, + { url = "https://files.pythonhosted.org/packages/88/11/e7a70a209eb9a067c0d3212b518a0134e3484f5178c7533878b6b514d469/aiohttp-3.14.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:5bcb6ff3fdab1258a192679ff1a05d44f59626430aa05cd1a9d2447423599228", size = 509484, upload-time = "2026-07-23T01:53:51.159Z" }, + { url = "https://files.pythonhosted.org/packages/30/07/4bbc222cc8dbe31d4c3e8a5baad2286e4d42026ac0c570027b89afce6344/aiohttp-3.14.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:617105e2c3018ee38d0c8ce5ee3c84f621a6d8b9f723202aacaff28449ca91ee", size = 511949, upload-time = "2026-07-23T01:53:55.083Z" }, + { url = "https://files.pythonhosted.org/packages/54/b9/42e74c46b7b7c794b995bbc1f573fb48950c38b19d8600c62a6804ee2d67/aiohttp-3.14.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f631fe87a6f30df5fbe6d79640b25e4cffb38c31c7fb6f10871517b84b0f8c1a", size = 1765282, upload-time = "2026-07-23T01:53:59.662Z" }, + { url = "https://files.pythonhosted.org/packages/6b/ed/62bc4d74363ad346d518e0720363a949f63e2e23439a79eb5813d4d29bb3/aiohttp-3.14.3-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:a94dbaae5ae27bd849c93570669bff91e0510f33a80805738e3de72a7be0447b", size = 1741511, upload-time = "2026-07-23T01:54:04.063Z" }, + { url = "https://files.pythonhosted.org/packages/d0/9f/181e8a8bc79e47d13c7fc4540bd7a3b729d9505609c61f392a8dd2fbfe55/aiohttp-3.14.3-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8f2f1c4c032c7cedd7d8da6f54c97b70266c6570c3108d3fdffee7188bb70529", size = 1810680, upload-time = "2026-07-23T01:54:09.882Z" }, + { url = "https://files.pythonhosted.org/packages/5c/9a/dec94d6ad694552fe3424e3f1928d7a606a5d9d9433a04e7ecdd9d38ae7f/aiohttp-3.14.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ea05e1f97ceea523942d9b2a7d7c0359d781d683d6b043f5943a602b14da4787", size = 1905646, upload-time = "2026-07-23T01:54:13.475Z" }, + { url = "https://files.pythonhosted.org/packages/52/b7/7cd31f29d6055bd711ae6e669367fba6f5ae9de463910a793e30556a8db7/aiohttp-3.14.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:543906c127fb1d929b95076db19b83fa2d46751006ff1e23b093aa5ac4d8db42", size = 1792122, upload-time = "2026-07-23T01:54:15.752Z" }, + { url = "https://files.pythonhosted.org/packages/66/73/10b1ef93afa61f4963c746257b70ced619cf31a4798671de5fdb2608501d/aiohttp-3.14.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0a5ff2dfbb9ce645fa5b8ef3e02c6c0b9cc3f6030ff863d0c51fffc50cb5541b", size = 1591127, upload-time = "2026-07-23T01:54:19.489Z" }, + { url = "https://files.pythonhosted.org/packages/49/ed/3b203fa6de1b338c14acdc06bf6ca9b043b7944f005966958c2ced932cde/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:041badb8f84396357c4d3ad26de6afd7a32b112f43d3c63045c0c8278cfd2043", size = 1725210, upload-time = "2026-07-23T01:54:24.129Z" }, + { url = "https://files.pythonhosted.org/packages/28/b7/1c2aab8c706436dcc28598452488ac9cd7c409da815237c28c27d58993e6/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:530125ee1163c4219af35dc3aa1206e541e7b31b6efc1a3f93b70a136f65d427", size = 1764848, upload-time = "2026-07-23T01:54:27.973Z" }, + { url = "https://files.pythonhosted.org/packages/54/50/94c28f08b131c4bf10984ea2c7a536c9920608bb2d6e7f95642c30cc87b7/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:c8653fd547c93a61aadc612007790f5555cdd18946fa48cf45e26d8ea4ea473d", size = 1777102, upload-time = "2026-07-23T01:54:31.775Z" }, + { url = "https://files.pythonhosted.org/packages/13/d4/e7d09ba7d345fb2d74440fd2fa033c5e079fac05552927705986f41a364f/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:89176250f686cb9853c0fb7ead90e639e915b84a6f43eedc2a4e7ec21f1037f0", size = 1580205, upload-time = "2026-07-23T01:54:34.518Z" }, + { url = "https://files.pythonhosted.org/packages/a3/84/072a91d68e1e1eb587985b54baab94221277f877e8ef274fc213a0ceae28/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:3a26434dafe408229ff3403458ca58de24fb51936504decac49ce6755f77e59d", size = 1797219, upload-time = "2026-07-23T01:54:36.995Z" }, + { url = "https://files.pythonhosted.org/packages/e0/eb/aad34e897e668424d6e995da5dff8a4a09af93363d3392488772957a63aa/aiohttp-3.14.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d1558173930a5a8d3069cee5c92fc91c87c4dbcb099debbb3622053717145a19", size = 1768629, upload-time = "2026-07-23T01:54:40.103Z" }, + { url = "https://files.pythonhosted.org/packages/b6/2b/6bb88ddba0fecd9122aa3ebcad25996cf6c083a4a7040dbb3a4f97972af6/aiohttp-3.14.3-cp312-cp312-win32.whl", hash = "sha256:16100ad3ab8d649fdfbee87602d9d2dcdca9df0b9eda8a1b5fdc0d41f96da559", size = 451481, upload-time = "2026-07-23T01:54:42.547Z" }, + { url = "https://files.pythonhosted.org/packages/76/9b/f2f8f108da17ecef2cc3efc424e8b7ad3782b1a8360f7b8eae8ced84f6ea/aiohttp-3.14.3-cp312-cp312-win_amd64.whl", hash = "sha256:33a2d7c28d33797a2e99923dffa63f83d908a19b6bf26cfe80fa790aa5e1a75a", size = 476845, upload-time = "2026-07-23T01:54:44.853Z" }, + { url = "https://files.pythonhosted.org/packages/3e/44/28dac80a8941b604f4da10ce21097614ca1bf905ce93dca28d8d7de9c1e7/aiohttp-3.14.3-cp312-cp312-win_arm64.whl", hash = "sha256:362a3fd481769cac1a824514bcd86fda51c65e8fe6e051099e008fddde6db17c", size = 448050, upload-time = "2026-07-23T01:54:47.087Z" }, + { url = "https://files.pythonhosted.org/packages/57/be/5afd201cc0ab139029aadb75392efe85a293403d9dd3a3226161c21ce00c/aiohttp-3.14.3-cp313-cp313-android_21_arm64_v8a.whl", hash = "sha256:2e9878ae68e4a5f1c0abe4dd497dbc3d51946f5837b56759e2a02e78fa90ef86", size = 506269, upload-time = "2026-07-23T01:54:49.075Z" }, + { url = "https://files.pythonhosted.org/packages/22/09/dec8189d62b45ade009f6792a2264b942a90cb88aeaf181239933cd72c3c/aiohttp-3.14.3-cp313-cp313-android_21_x86_64.whl", hash = "sha256:f3d2669fe7dec7fc359ecdb5984b29b50d85d5d00f8c1cb61de4f4a24ee42627", size = 515166, upload-time = "2026-07-23T01:54:51.894Z" }, + { url = "https://files.pythonhosted.org/packages/28/24/2854869d29ed8a8b19d74f9ec6629515f7e04d02dd329d9d179201e58e47/aiohttp-3.14.3-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:cc7cb243a68167172f48c1fd43cee91ec4b1d40cefd190edd43369d1a6bc9c82", size = 486263, upload-time = "2026-07-23T01:54:54.223Z" }, + { url = "https://files.pythonhosted.org/packages/d4/dd/57187c8be2a35aea65eaee3bd2c3dcbbcf0204f5106c89637e3610380cd1/aiohttp-3.14.3-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:78253b573e6ffab5028924fc98bc281aae05445969982a10864bc360dea2016c", size = 492299, upload-time = "2026-07-23T01:54:56.236Z" }, + { url = "https://files.pythonhosted.org/packages/b9/11/06ae6ed8f0d414edf4068861e233d8fe23ee699bfd4b3ceb8663db948a62/aiohttp-3.14.3-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:7041d52c3a7fa20c9e8c182b534704abb19502c8bdcbde7ab23bfda6f642394f", size = 502235, upload-time = "2026-07-23T01:54:58.377Z" }, + { url = "https://files.pythonhosted.org/packages/7e/a3/559639c34a345d2cf7c52dff6838119f2eaf29eb508227b5b83f573af813/aiohttp-3.14.3-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ac74facc01463f138b0da5580329cfcc82818dea5656e83ddcd11268fc12ff80", size = 750883, upload-time = "2026-07-23T01:55:00.65Z" }, + { url = "https://files.pythonhosted.org/packages/91/cd/41e131f13afd1e7b0172a9d9eda085ef90eb8439f41f0d279db81ed3ae60/aiohttp-3.14.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:d6218d92e450824e9b4881f44e8c09f1853b490f9a64130801024a4793b1b3b0", size = 508473, upload-time = "2026-07-23T01:55:02.945Z" }, + { url = "https://files.pythonhosted.org/packages/bc/6b/e7f13410d391c6e55b4c007a8de024355389d7d459e3d64c42b2d33617e5/aiohttp-3.14.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:11fb37ef075669eee52ab1928fbf6e1741fada40409fa309ebde9607a962aebf", size = 509190, upload-time = "2026-07-23T01:55:05.173Z" }, + { url = "https://files.pythonhosted.org/packages/97/21/6464573e53d69672cc1eada3e5c5cb2d2efa82701e8305a0f2047a576967/aiohttp-3.14.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:55bdcc472aafe2de4a253045cc128007a64f1e0264fb675791e132ea5edaa3bd", size = 1761478, upload-time = "2026-07-23T01:55:07.383Z" }, + { url = "https://files.pythonhosted.org/packages/1a/81/d217043a4c17fbce360905e3b2bdd20139ebc9a2de836d035d179c4da006/aiohttp-3.14.3-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c39846c3aad97a8530c89d7a3869a8f8e9e3762c6ac0504481e5c80948f7e807", size = 1735092, upload-time = "2026-07-23T01:55:09.803Z" }, + { url = "https://files.pythonhosted.org/packages/a1/66/e13a02d0eeb1a9a502402a977abb4e4abff9fe4051c26f80558c57a7c975/aiohttp-3.14.3-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5895ef58c4620afe02fa16044f023dc4dafec08158f9d08874a46a7dbc0341b8", size = 1800546, upload-time = "2026-07-23T01:55:12.012Z" }, + { url = "https://files.pythonhosted.org/packages/26/5e/57d42fca1d18cb5acc1cad945d017fabc5d6ae71d8a08ad66be8dc3ee544/aiohttp-3.14.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fa9467a8113aa69d3d7c55a70ef0b7c636010a40993f3df9d9d0d73b3eb7ef24", size = 1895250, upload-time = "2026-07-23T01:55:14.357Z" }, + { url = "https://files.pythonhosted.org/packages/ca/1c/7da8d08e74d56f00070822f9638ff3f1c563f8ad87d1efa996c87bfc8644/aiohttp-3.14.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d7d2deec16eeedf55f2c7cf75b521ea3856a5177e123844f8fd0f114ce252cb5", size = 1789289, upload-time = "2026-07-23T01:55:16.668Z" }, + { url = "https://files.pythonhosted.org/packages/cd/0f/cf16bcf56896981c1a0319f5d5db9337994b5165730c48a8fa07e9b34be6/aiohttp-3.14.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:dd54d0e8717de95939766febac482ac0474d8ac3b048115f9f2b1d23a16e7db4", size = 1586706, upload-time = "2026-07-23T01:55:18.913Z" }, + { url = "https://files.pythonhosted.org/packages/fe/6f/76eac12a7f2480e1e304f842efdb07db33256b0d9165b866b6ef0806c202/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:df82f3787c940c94986b34222d59c9e38843fba85139f36e85255a82ad5355a9", size = 1724652, upload-time = "2026-07-23T01:55:21.296Z" }, + { url = "https://files.pythonhosted.org/packages/39/b6/19c8c592baeeb94b75f966547d40c02ac7590902306ec5863d5c027cf506/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:42a67efc36300d052fb4508a53e8b6901b9284b599ae63945c377569c5fcc1e1", size = 1756239, upload-time = "2026-07-23T01:55:23.705Z" }, + { url = "https://files.pythonhosted.org/packages/dc/c9/4e9383150296f97f873b680c4de8fb2cd88608fb9f48c79edcb111611abc/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:7a75aa63cbf9b21cfaf60dc2657e19df2c2867d91707d653fee171ffeedd1371", size = 1769161, upload-time = "2026-07-23T01:55:26.082Z" }, + { url = "https://files.pythonhosted.org/packages/aa/1e/147bdc6cc5de5f3ab011be8bf5d6e786633249f22c20bae06f85e45f5387/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:e92eb8acc45eb6a9f4935071a77edf5b85cc6f8dfad5cd99e97653c26593cdde", size = 1578759, upload-time = "2026-07-23T01:55:28.846Z" }, + { url = "https://files.pythonhosted.org/packages/fd/31/78388a9d6040ece2e11df62ea229a822cf5e52d238374b220ae9975b2623/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:b014a6ed7cf912e787149fdc529166d3ceabac23f26efeea3158c9aba2354e7e", size = 1792025, upload-time = "2026-07-23T01:55:31.457Z" }, + { url = "https://files.pythonhosted.org/packages/03/51/a3d29fdf2c25d796746af8ad6fe56a45d6256c38b0a8a2ed752e1160b3a2/aiohttp-3.14.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:3d4f72af88ac2474bb5bca640030320e3d38a0163a1d7533500e87be458eef71", size = 1768477, upload-time = "2026-07-23T01:55:33.87Z" }, + { url = "https://files.pythonhosted.org/packages/29/a6/442e18b5afeade534d877a2dc3c3e392aff8d49787890b0cf84790410267/aiohttp-3.14.3-cp313-cp313-win32.whl", hash = "sha256:5f08ec777f35ee70720233b8b9811d3bb5d728137f30ac91b7457709c3261ac0", size = 451069, upload-time = "2026-07-23T01:55:36.121Z" }, + { url = "https://files.pythonhosted.org/packages/9d/69/3d876ac02659f271cf7f6769f14a8e3de5b6e888ed8b5a7e998086a4cec8/aiohttp-3.14.3-cp313-cp313-win_amd64.whl", hash = "sha256:dff9461ec275f22135650d5ba4b4931a11f3958df7dfbb8db630000d4dee0883", size = 476518, upload-time = "2026-07-23T01:55:38.303Z" }, + { url = "https://files.pythonhosted.org/packages/b2/0e/50d6e6471cd31edce8b282bdec59375a3a69124d8a989a0b1313355cae52/aiohttp-3.14.3-cp313-cp313-win_arm64.whl", hash = "sha256:ddcac3c6b382e81f1dd0499199d4136b877beb4cb5ef770bbbfba56c4b8f55d2", size = 447676, upload-time = "2026-07-23T01:55:40.451Z" }, + { url = "https://files.pythonhosted.org/packages/c8/20/887fdcf832326571b370ffc347b3e70abe101096f3720126aac161b1d872/aiohttp-3.14.3-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:49f7325beb0f85ef4aef5f48f490269575f83e6e2acad00a1d80b807eb027062", size = 509067, upload-time = "2026-07-23T01:55:42.618Z" }, + { url = "https://files.pythonhosted.org/packages/ad/a3/92cec936f78cc4bf0fa5554ebe593b73459d94e3c62303e1902a4cccb6f7/aiohttp-3.14.3-cp314-cp314-android_24_x86_64.whl", hash = "sha256:e3be98a7c30b8c25d573dafba7171d66dfb05ee6a9070fc46535464ff97700a6", size = 514774, upload-time = "2026-07-23T01:55:44.937Z" }, + { url = "https://files.pythonhosted.org/packages/29/ba/2a0c38df3fc557620b6a5acd98364af050053b6285b4dc7ee74100c63c18/aiohttp-3.14.3-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:614c61d478b83953e261d02bb2df750f17227cd33ef8002945bf5aebbde21919", size = 488134, upload-time = "2026-07-23T01:55:47.135Z" }, + { url = "https://files.pythonhosted.org/packages/48/d6/d51b7d4bf309af3693940d8ffd2b9ed0b682434ef85959b7c9c137f60cf8/aiohttp-3.14.3-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:1caa7b0d05f3e3a36f87788c59e970a7ee1cefcfcbb924a9f138c4a6551c9cb7", size = 494201, upload-time = "2026-07-23T01:55:49.451Z" }, + { url = "https://files.pythonhosted.org/packages/3f/5a/8f624384e5f1efabb5229b94157eb966b021e97bdb188c62860c2ae243c2/aiohttp-3.14.3-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:dfa68deb2a443bdaa3ea5297b0699c1464f08aef3812b486d1348eee61b07dc0", size = 502766, upload-time = "2026-07-23T01:55:51.656Z" }, + { url = "https://files.pythonhosted.org/packages/a6/26/4ff0164370deec18fb19254ee4ab10b7a73304ac0c860b13f5f84663759b/aiohttp-3.14.3-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:e72ee89e28d907a18f46959b4eb0bb06701cc7f8cf4366e00029e2ccfaaf5924", size = 756557, upload-time = "2026-07-23T01:55:53.964Z" }, + { url = "https://files.pythonhosted.org/packages/97/a3/7056b86dc0d9ec709ea9777eae3b0161428f943372f8b98c01c11593b682/aiohttp-3.14.3-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ad4c8b7488d745d2ca4838ebd8ae5ba9b56341d30b1da43640e4ce87f9f49646", size = 510168, upload-time = "2026-07-23T01:55:56.22Z" }, + { url = "https://files.pythonhosted.org/packages/85/ed/0357a015892fd68058bf2d39d3fd1958e459b997a7db30aaa6aaa434ae96/aiohttp-3.14.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:db332af25642007330fca8be5c4d194caf2bea7a7fc84415aff3497af5dfee6b", size = 512957, upload-time = "2026-07-23T01:55:58.437Z" }, + { url = "https://files.pythonhosted.org/packages/47/d1/8aba53f15ccb2238405f5e9d30e2a8ca44f93878c26e7165ade00d374b1c/aiohttp-3.14.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:25bd2708db6bdf6a6630dd37bdcdfcb47c4434d22ac69c64665b802910140b30", size = 1750149, upload-time = "2026-07-23T01:56:00.856Z" }, + { url = "https://files.pythonhosted.org/packages/49/bd/40c3fee327529284375c6701cbb0fa4600cc2e8432af1378f897e2ef7d3a/aiohttp-3.14.3-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:cef89a58e628c4efcac3275c2d68083f82426dcdc89c1492a6f654f9f7ea6ab9", size = 1707685, upload-time = "2026-07-23T01:56:03.371Z" }, + { url = "https://files.pythonhosted.org/packages/2a/a3/ca0cc6724cca8114b05694abd916060758c79894c3aa5b012cdadc1bc28e/aiohttp-3.14.3-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c23ec8ee9d5ab2f5421f9c7fffce208435607af27fd46d4a44e031954352838f", size = 1803911, upload-time = "2026-07-23T01:56:05.817Z" }, + { url = "https://files.pythonhosted.org/packages/95/b5/85b099c299c3ffd38ad9b3e43694c8a346934e4a30c88c4fd5a841234f77/aiohttp-3.14.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e2667f0bbe7eb6c74eae5e9691441ad186e5845ca3cff63230fc09c4e7514f5d", size = 1876929, upload-time = "2026-07-23T01:56:08.413Z" }, + { url = "https://files.pythonhosted.org/packages/d5/b7/1da684a04175473fa4cddbf9a2f572e79514c3fd27a74597f43057d4f3da/aiohttp-3.14.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:18cb43369747b2ae007bd2655fb8e63a099c2ff1d207962943636dac989b3147", size = 1761112, upload-time = "2026-07-23T01:56:10.918Z" }, + { url = "https://files.pythonhosted.org/packages/d1/16/bc4b55e3e5cb175fd69c53c90d60d2f47797cb343da5106e23863dc4dba4/aiohttp-3.14.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d77640cc618c1d99fc4f8589c0f24a730adfa54eb1e57ef7bf0c8dfb78da898c", size = 1583500, upload-time = "2026-07-23T01:56:13.613Z" }, + { url = "https://files.pythonhosted.org/packages/2a/e8/13a9d957a1ee40837f46aa30f0f4c657e673ad86a2e6362a9f9be20d26d9/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:53e5179d8abb5710f8e83ba207c41c8d1261fcffd4616500e15ca2b7a33be10a", size = 1713940, upload-time = "2026-07-23T01:56:15.969Z" }, + { url = "https://files.pythonhosted.org/packages/38/05/d33c680c1bcf1c7e130f9cbfc1fc02fe8bb0c4af2a94a53dd5fb56131e5c/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:cd817772b2fcf2b8c0905795318485f9ec16eae60b29feb7f4c77085311637f0", size = 1724413, upload-time = "2026-07-23T01:56:18.591Z" }, + { url = "https://files.pythonhosted.org/packages/85/1d/af798d306f7a74b6a632dbcabcf62a4c91391b7582d2a8c6d7712e2cc54e/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:4e3ac92d90e92773b2362d506068e9a948192bd553e743c5b2429e28527c8661", size = 1770748, upload-time = "2026-07-23T01:56:21.074Z" }, + { url = "https://files.pythonhosted.org/packages/a8/92/ad720d472556a995049206867765e9410969684f86ee09423ff9969044c1/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:3f42e9b78301f11c8f861746175d8b9c1ccef713fcad9eab396e2f6db8ed4a22", size = 1577564, upload-time = "2026-07-23T01:56:23.475Z" }, + { url = "https://files.pythonhosted.org/packages/60/ad/0ed7586cbef7a884e23a752fa2bb987a122e6a5dd50dab109258d0a95193/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:9d9edccfe496b476db5f398d97b865e9a6752bcf8aec4eef8390ce20fb64bb41", size = 1782080, upload-time = "2026-07-23T01:56:25.994Z" }, + { url = "https://files.pythonhosted.org/packages/97/ea/dbaed0d73e8a69aad653b045dab451c67c2454bb731a37b45a86593e9422/aiohttp-3.14.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:1c5ec8fb1bcc31a8466f74aaf26c345d5c386fa4bd08a3f0eb9c7a4a3fe8b5bf", size = 1745813, upload-time = "2026-07-23T01:56:28.604Z" }, + { url = "https://files.pythonhosted.org/packages/81/1b/6893d4bc57e434fc93a6c9217c637d967a0b651d989f6e3265179375754a/aiohttp-3.14.3-cp314-cp314-win32.whl", hash = "sha256:38901a84da3ce22249f6e860bf8f90d141bcab7da090cc398f8bb58c0e44b7da", size = 455872, upload-time = "2026-07-23T01:56:31.031Z" }, + { url = "https://files.pythonhosted.org/packages/f5/8b/c7baa1ba1eda4db6989baefe5de6d99834921b84ebd7918624febcb9f290/aiohttp-3.14.3-cp314-cp314-win_amd64.whl", hash = "sha256:8b3b60de05f3dcb6f6a00f818bb2ec781cee4de0645f59ccaf99b1d1823b6100", size = 481030, upload-time = "2026-07-23T01:56:33.365Z" }, + { url = "https://files.pythonhosted.org/packages/22/8c/c29d067df825a2df88ca432db848aa2fe8199598359cc06c12b09320cac9/aiohttp-3.14.3-cp314-cp314-win_arm64.whl", hash = "sha256:1576145bdceeb92382d899751e12743a3a5b8e460a841e3e50543859e54864dc", size = 453669, upload-time = "2026-07-23T01:56:35.731Z" }, + { url = "https://files.pythonhosted.org/packages/6a/a4/9c033beb355d39b6147980597ec9645e4729243f686ee4dc73945de72030/aiohttp-3.14.3-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:8800c996b01c2772a783e3e46f3e1abd5823029adca0df54231960de9bfefa5b", size = 791403, upload-time = "2026-07-23T01:56:37.972Z" }, + { url = "https://files.pythonhosted.org/packages/80/ca/87c32a0a7704583cfc49660bd817889bae5b830bf53b5dcb4e92145ac2da/aiohttp-3.14.3-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:ebe8e504f058fe91223351cecd2d9d6946c9d241bb0250d898ffbdf584cc72b0", size = 526413, upload-time = "2026-07-23T01:56:40.523Z" }, + { url = "https://files.pythonhosted.org/packages/9e/d8/8ec0e471248c500acdce2be3f46db8fb62b5eb60efef072529cc85ee1d26/aiohttp-3.14.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:30402d03a7c0ff52bce290b57e564e9079fd9d0cb545c8aba73f86a103162d2e", size = 532135, upload-time = "2026-07-23T01:56:42.876Z" }, + { url = "https://files.pythonhosted.org/packages/fe/45/f8919fd936e8b79fcd9bda7b6d8e62613462a713f4f17987fd7c34399142/aiohttp-3.14.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9fc7b5bfec6573f3ae844f457fdde5adeb713f8b8e4a81ad64fc207b49383716", size = 1922742, upload-time = "2026-07-23T01:56:45.528Z" }, + { url = "https://files.pythonhosted.org/packages/f6/ec/9ca76b28a27525b0cc53e20842e0228b022f301ce1f436b7d814b4aaf2df/aiohttp-3.14.3-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8a5fd34f7f7410d1730d5c2ba873cacb2eed3fede366feb268a70ba22581ed8f", size = 1787371, upload-time = "2026-07-23T01:56:48.045Z" }, + { url = "https://files.pythonhosted.org/packages/b1/04/6acdbf17315f7b55f1937e3387acb89a3cddeb4995689553d064af8e92ab/aiohttp-3.14.3-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:270d3dace9ca2f10f0da5d8ebe519b7a310fc6112ed916e32df5866df0888553", size = 1912623, upload-time = "2026-07-23T01:56:50.605Z" }, + { url = "https://files.pythonhosted.org/packages/86/e6/438b0c79ca6f45eb9fd9817dd4c01a91919a38c0de5ee9e05e2b4dc0ece7/aiohttp-3.14.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:3ae5b3a59436d089b5395d910121a390feed4d00578eb95a0fd1a329fe963100", size = 2005515, upload-time = "2026-07-23T01:56:53.153Z" }, + { url = "https://files.pythonhosted.org/packages/bb/6b/62cbd6577758699525f5c712d1ddef57d9875fbab0ae8d5f5a202fd598f8/aiohttp-3.14.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2498f0fe69ead802f9675beca44a7c21c62fdaa4ec5145ea1c3ad6edbee29f85", size = 1879906, upload-time = "2026-07-23T01:56:55.818Z" }, + { url = "https://files.pythonhosted.org/packages/00/95/18bcbf830a21dc3aae24d8f6b6feaf3db1d2090242d00a7868db2ffb0b67/aiohttp-3.14.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a0dc483c00da8b673abbb367eb6f8d8f4bcec30eb58529ea13cb42e7fd2dfa33", size = 1675849, upload-time = "2026-07-23T01:56:58.861Z" }, + { url = "https://files.pythonhosted.org/packages/a9/19/47f4968659c5e23606c3790c80fc624e691c153d036148449ee84d31b287/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c7d3a97c678d34fc5b59da671ee9cd630096ddc643e7b5a30d54a2a6f3574d3f", size = 1843496, upload-time = "2026-07-23T01:57:01.591Z" }, + { url = "https://files.pythonhosted.org/packages/64/af/38c33c4dd82fddcb4e56c4653b6f1072a8edbc6b7fa15809f14932c41e2d/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:f8fb78a83c9e5f741ca3a68cfb455c1f5bb83b4e7249a3848b3cd78d0a8563b0", size = 1827746, upload-time = "2026-07-23T01:57:05.131Z" }, + { url = "https://files.pythonhosted.org/packages/a1/9d/0537cda4885ac8f5b7053d164dd06312f4c483a4edcb8ee5b8aaf2a989bf/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:74ab5b6a9fb13e873e5a90946588baecaf488745e1db1a4a5c433f971f035098", size = 1853810, upload-time = "2026-07-23T01:57:08.043Z" }, + { url = "https://files.pythonhosted.org/packages/19/fe/26f9c5e6458385aa86497836b0dea6fb2f027827d63f37c7856cce9286ee/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:bd52f811e65f6fb634b1047159657c98f52b407f8efec907bcfc09da9a4c0a25", size = 1668895, upload-time = "2026-07-23T01:57:10.837Z" }, + { url = "https://files.pythonhosted.org/packages/ec/4c/618b1db9b9ba079b8875d2cdf78e7c4a3bf72903bd5850fee7dd9544600a/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:f0f177d1b195b9e06376cfd7d308d8a1b920909a609d03ac82a8c73bbb16d3b9", size = 1883833, upload-time = "2026-07-23T01:57:13.672Z" }, + { url = "https://files.pythonhosted.org/packages/94/c6/bd959bd1e4771f9fd944e9e436224c48c77b018b73b519b5aad346335bcc/aiohttp-3.14.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:498c6c623134f8e09a3c4e60bcd607a0b4590dd7dbf08dd40851b27cbb520ccb", size = 1844251, upload-time = "2026-07-23T01:57:16.593Z" }, + { url = "https://files.pythonhosted.org/packages/5e/19/08d41839658bdd44a0ed2480f3891705ecb487ce28c0dde62c9040c997e0/aiohttp-3.14.3-cp314-cp314t-win32.whl", hash = "sha256:b304db572b4368edd8dda8a2274f73156fe15558fca4a917cb8a09fc47af5963", size = 474180, upload-time = "2026-07-23T01:57:19.306Z" }, + { url = "https://files.pythonhosted.org/packages/99/5d/3cd6ef0a2b2851f7ab913b5b079334781bd50ff56a323e4454063377a080/aiohttp-3.14.3-cp314-cp314t-win_amd64.whl", hash = "sha256:b20032766aedf6261c7a566585a40867d092ac03a0d81592d5370ef9b054f99b", size = 500528, upload-time = "2026-07-23T01:57:21.762Z" }, + { url = "https://files.pythonhosted.org/packages/a4/37/cfd1ed540a4d318da025590d96b728e63713c09e9377950fc655dadeb856/aiohttp-3.14.3-cp314-cp314t-win_arm64.whl", hash = "sha256:2e1161602f45a54de2ce0905243a95f58cb42dcd378402f3697f5e0b21e9d2e7", size = 469280, upload-time = "2026-07-23T01:57:24.241Z" }, +] + +[[package]] +name = "aioitertools" +version = "0.13.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/3c/53c4a17a05fb9ea2313ee1777ff53f5e001aefd5cc85aa2f4c2d982e1e38/aioitertools-0.13.0.tar.gz", hash = "sha256:620bd241acc0bbb9ec819f1ab215866871b4bbd1f73836a55f799200ee86950c", size = 19322, upload-time = "2025-11-06T22:17:07.609Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/a1/510b0a7fadc6f43a6ce50152e69dbd86415240835868bb0bd9b5b88b1e06/aioitertools-0.13.0-py3-none-any.whl", hash = "sha256:0be0292b856f08dfac90e31f4739432f4cb6d7520ab9eb73e143f4f2fa5259be", size = 24182, upload-time = "2025-11-06T22:17:06.502Z" }, +] + +[[package]] +name = "aiosignal" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "frozenlist" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/62/06741b579156360248d1ec624842ad0edf697050bbaf7c3e46394e106ad1/aiosignal-1.4.0.tar.gz", hash = "sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7", size = 25007, upload-time = "2025-07-03T22:54:43.528Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" }, +] + +[[package]] +name = "alabaster" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a6/f8/d9c74d0daf3f742840fd818d69cfae176fa332022fd44e3469487d5a9420/alabaster-1.0.0.tar.gz", hash = "sha256:c00dca57bca26fa62a6d7d0a9fcce65f3e026e9bfe33e9c538fd3fbb2144fd9e", size = 24210, upload-time = "2024-07-26T18:15:03.762Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/b3/6b4067be973ae96ba0d615946e314c5ae35f9f993eca561b356540bb0c2b/alabaster-1.0.0-py3-none-any.whl", hash = "sha256:fc6786402dc3fcb2de3cabd5fe455a2db534b371124f1f21de8731783dec828b", size = 13929, upload-time = "2024-07-26T18:15:02.05Z" }, +] + +[[package]] +name = "annotated-doc" +version = "0.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/57/ba/046ceea27344560984e26a590f90bc7f4a75b06701f653222458922b558c/annotated_doc-0.0.4.tar.gz", hash = "sha256:fbcda96e87e9c92ad167c2e53839e57503ecfda18804ea28102353485033faa4", size = 7288, upload-time = "2025-11-10T22:07:42.062Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/d3/26bf1008eb3d2daa8ef4cacc7f3bfdc11818d111f7e2d0201bc6e3b49d45/annotated_doc-0.0.4-py3-none-any.whl", hash = "sha256:571ac1dc6991c450b25a9c2d84a3705e2ae7a53467b5d111c24fa8baabbed320", size = 5303, upload-time = "2025-11-10T22:07:40.673Z" }, +] + +[[package]] +name = "annotated-types" +version = "0.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ee/67/531ea369ba64dcff5ec9c3402f9f51bf748cec26dde048a2f973a4eea7f5/annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89", size = 16081, upload-time = "2024-05-20T21:33:25.928Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643, upload-time = "2024-05-20T21:33:24.1Z" }, +] + +[[package]] +name = "antlr4-python3-runtime" +version = "4.13.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/5f/2cdf6f7aca3b20d3f316e9f505292e1f256a32089bd702034c29ebde6242/antlr4_python3_runtime-4.13.2.tar.gz", hash = "sha256:909b647e1d2fc2b70180ac586df3933e38919c85f98ccc656a96cd3f25ef3916", size = 117467, upload-time = "2024-08-03T19:00:12.757Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/89/03/a851e84fcbb85214dc637b6378121ef9a0dd61b4c65264675d8a5c9b1ae7/antlr4_python3_runtime-4.13.2-py3-none-any.whl", hash = "sha256:fe3835eb8d33daece0e799090eda89719dbccee7aa39ef94eed3818cafa5a7e8", size = 144462, upload-time = "2024-08-03T19:00:11.134Z" }, +] + +[[package]] +name = "ast-serialize" +version = "0.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/58/ad/0d70a3a2d6e01968d985415259e8ec7ad3f777903f9b1c1f3c8c44642c60/ast_serialize-0.6.0.tar.gz", hash = "sha256:aadd3ffcf4858c9726bf3515f7b199c7eadbe504f96028e4a87172c0da65a8fe", size = 61489, upload-time = "2026-06-30T20:02:55.555Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3f/12/3e5f575f156555547c250a8b0d1347517a3a20fc7f4492e9703a69d4f45e/ast_serialize-0.6.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:a7520b672827885bafeae7501f684d14d47d17e5f45256f9df547686cca52264", size = 1177640, upload-time = "2026-06-30T20:02:06.708Z" }, + { url = "https://files.pythonhosted.org/packages/a2/a4/921a9e27951627983b0f368859ea00f8330a551dc0bf4c2fdcb11855a98b/ast_serialize-0.6.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a14191beec7e0c078d2fc1f6edc0aee88bcd4db9f18e1bc9f8052b559c22dddc", size = 1168111, upload-time = "2026-06-30T20:02:08.366Z" }, + { url = "https://files.pythonhosted.org/packages/00/69/950cf404de7b8782cf95e5c1237e25e2aa46177b287f39f9eeddf481fd6f/ast_serialize-0.6.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:32ef62ec34cf6be20ad77d4799556638fbdf187f3ae10698dfb20ef9f2c89516", size = 1227656, upload-time = "2026-06-30T20:02:09.843Z" }, + { url = "https://files.pythonhosted.org/packages/4c/a8/46f8f6a6479d9d2273980957bb091a506c55f5b95d3c029ee58518a78407/ast_serialize-0.6.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:13b7769970a39983b0adf2f38917b1cd3b8946f76df045756c3d741bc689f089", size = 1227706, upload-time = "2026-06-30T20:02:11.367Z" }, + { url = "https://files.pythonhosted.org/packages/b7/b9/9ac415bda0a40e49eab8fea3b2741c19c98bb84d57d62c4cfc6230eb67be/ast_serialize-0.6.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6f7a408601bb3edaefb3bc67a4c01f5235e3253653b6a5729a2ee2382b35341c", size = 1431705, upload-time = "2026-06-30T20:02:12.737Z" }, + { url = "https://files.pythonhosted.org/packages/e5/06/8807115d441444879f7561b5eede5ac18fc80392f11826d61ccf31f503b1/ast_serialize-0.6.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8670bfa51208a2c0c8d138928e40e998fab158f9200d53bb80c088b5b8eda7b8", size = 1249533, upload-time = "2026-06-30T20:02:14.571Z" }, + { url = "https://files.pythonhosted.org/packages/3e/c0/c2ba82ef9618650357d9421a1fdb27ffec862a7f57e8e2de82a3ccd11e12/ast_serialize-0.6.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a4826809eb8597a8cd59fd924b6d7c285b8969a1e0007e2cb652cab62376270f", size = 1252619, upload-time = "2026-06-30T20:02:16.219Z" }, + { url = "https://files.pythonhosted.org/packages/0f/a7/fa31d52dd4102cede29fb9634e98d214129b2783b4f95528c6dc6a8f6587/ast_serialize-0.6.0-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:577a6c189068686869f5f1ddc38363f3ae1808a4753b577266f9202071a7bb66", size = 1242983, upload-time = "2026-06-30T20:02:17.813Z" }, + { url = "https://files.pythonhosted.org/packages/b1/20/ddf742b5ad3c4bafd3466f2265037cfd99bc1b9a5ee46a5d58c90d523242/ast_serialize-0.6.0-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:085de7f62dc9cc247eb01e965a362707d1d90b1d89a82c5bf78301a60a3c417b", size = 1296148, upload-time = "2026-06-30T20:02:19.146Z" }, + { url = "https://files.pythonhosted.org/packages/24/cb/9f6f217cce8b3b632c5568b478d195a35e79dce4dbe309438cb89ba6ea4f/ast_serialize-0.6.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:9f8a8b78b13173de6a9ec22111d9be674874cd5bdccda04f14ae5ebc2bef403a", size = 1403826, upload-time = "2026-06-30T20:02:20.696Z" }, + { url = "https://files.pythonhosted.org/packages/2d/f8/9d16d4f0107a183924425cc0e7618d8bf76f96b45afa9ff19f924ed1ad57/ast_serialize-0.6.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:f2ff3baffc3a29c1f15bc9098aa0c09763410262d5e6cef42116f7356c184554", size = 1502943, upload-time = "2026-06-30T20:02:22.034Z" }, + { url = "https://files.pythonhosted.org/packages/80/dd/bbc1c38756350dddf7e24acae1c9482ef42051c267417e019aecc1ed4075/ast_serialize-0.6.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:0067b25fce104eaae5b88383de9ab803faeb671831e14ca698b771b356e2600f", size = 1497632, upload-time = "2026-06-30T20:02:23.517Z" }, + { url = "https://files.pythonhosted.org/packages/42/7e/9daffefcf5b97e6bb4c3e0b3c024c1aee9722f23d3cf7cd2ff80d6fb4a40/ast_serialize-0.6.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:c617417f9cbb0cb144f6283c3cbe0d2e0f01beaf9f608f662b21191058a626ec", size = 1448858, upload-time = "2026-06-30T20:02:24.889Z" }, + { url = "https://files.pythonhosted.org/packages/e5/1f/f9baaab81a677ea0af7d2458cac2f94ebcc85958f8a3c15ba9d9e5dab653/ast_serialize-0.6.0-cp314-cp314t-win32.whl", hash = "sha256:5337cb256dcea3df9288205213d1601581536526b8f4da44b6974f1180f3252a", size = 1052600, upload-time = "2026-06-30T20:02:26.263Z" }, + { url = "https://files.pythonhosted.org/packages/9e/1f/41b535866519512d8cf6669cb2cff7823b7672bb6279c0333b4ff89d7d9f/ast_serialize-0.6.0-cp314-cp314t-win_amd64.whl", hash = "sha256:2d947e45cafc4b09bd7528917fa84c517654a43de173c79785574b7b3068ac24", size = 1095570, upload-time = "2026-06-30T20:02:27.639Z" }, + { url = "https://files.pythonhosted.org/packages/50/64/e472fe3e3a2d33d874b987e8518aedf24562919e3b6161a4fa1797e89c0f/ast_serialize-0.6.0-cp314-cp314t-win_arm64.whl", hash = "sha256:6e15ec740436e1a0d62de848641abe5f3a2f89a7f94907d534795ac91bbacf14", size = 1067267, upload-time = "2026-06-30T20:02:28.949Z" }, + { url = "https://files.pythonhosted.org/packages/52/19/ac8348ae8711c9b5ae834634f635780cab62a0f5e6f988882e048b89c2ae/ast_serialize-0.6.0-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:093cb8bb91b720d8523580498d031791bb1bbaa048599c3d21085d380e11a596", size = 1185367, upload-time = "2026-06-30T20:02:30.427Z" }, + { url = "https://files.pythonhosted.org/packages/c1/f6/ec7ec652c51db77c2f61d8573338e13e4704303265ccc658cb4031d9f354/ast_serialize-0.6.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:e61580a69faf47e3689795367ed211f2a10fd741478cc0f36a0f128793360aad", size = 1178657, upload-time = "2026-06-30T20:02:31.964Z" }, + { url = "https://files.pythonhosted.org/packages/6f/02/613a7534a41d0122f37d1e0c64aa8ac78bfb831f8c92f6db057a311abb3c/ast_serialize-0.6.0-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:305802f2ce2a7c4e87835078ea85c58b586ddda8095b92fe2ead9364ae19c80a", size = 1238620, upload-time = "2026-06-30T20:02:33.664Z" }, + { url = "https://files.pythonhosted.org/packages/4d/21/087957bba486242afc52f49b2d9e21c9dad00289356cf9efe67084015a9d/ast_serialize-0.6.0-cp39-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c7b8b8f0c42f752ea00b2b7d7c090b3f80d9c1c5c75cadf16423790a0cc74081", size = 1236075, upload-time = "2026-06-30T20:02:34.936Z" }, + { url = "https://files.pythonhosted.org/packages/82/04/78128bbb170071c2c72a210a181f1c00e11cc1cec60a8beef747b07f9201/ast_serialize-0.6.0-cp39-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:cd5b91b9e6f2356ace3a556963b0cd783b395fbbb0bb17b4defc283415466e77", size = 1441348, upload-time = "2026-06-30T20:02:36.245Z" }, + { url = "https://files.pythonhosted.org/packages/64/64/62fb99d6faf199b4c3e5b08a07136e9a0d7664bb249c6de3670e5b63e9b6/ast_serialize-0.6.0-cp39-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4d6ef91590258ada18909b9caea344dac4de2013906b035473cd674a43f4b790", size = 1258580, upload-time = "2026-06-30T20:02:37.53Z" }, + { url = "https://files.pythonhosted.org/packages/ca/87/b4d6c38e0ccd5e85dc54cecdf933a152c60b28fe5d993a6d8a72fa6d5896/ast_serialize-0.6.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dcbed41e9386059fc0261d602445ede0976c2ecec2939688bcbcb9ed0b6f28b7", size = 1261693, upload-time = "2026-06-30T20:02:39.123Z" }, + { url = "https://files.pythonhosted.org/packages/0e/4b/3676ca2191f39bafb75f93f99b2f429ec464586158fece2165f3572805dc/ast_serialize-0.6.0-cp39-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:cdc4e6f930b9090c2f92c9036ad12ffb8e6e44d4a5ba06f1458a05d60f203f7b", size = 1252517, upload-time = "2026-06-30T20:02:40.511Z" }, + { url = "https://files.pythonhosted.org/packages/f3/58/494ef8c4b4acb2f4a265ac934caf45f792a08fe27d6b853de35ad991941a/ast_serialize-0.6.0-cp39-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:897ac47b5637be41c0c07061c8a912fafa967ef1dc73fa115e4bfa70882a093b", size = 1304843, upload-time = "2026-06-30T20:02:41.961Z" }, + { url = "https://files.pythonhosted.org/packages/b1/f2/13736d920ab3d49bbee80ef1a277dd7b7aaf3b3545efd9d2a8114fe05525/ast_serialize-0.6.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c4af9a1386166e40ed01464991806f89038a2d89782576c7774876fa77034e32", size = 1413698, upload-time = "2026-06-30T20:02:44.179Z" }, + { url = "https://files.pythonhosted.org/packages/a8/5a/e046f3899e2acba4677d7427b76431443a1aa1a0e583dfb05b55b69d55cf/ast_serialize-0.6.0-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:c901adbd750029b9ac4ad3d6aa56853e0ad4875119fbf52b7b8298afc223828b", size = 1512209, upload-time = "2026-06-30T20:02:45.584Z" }, + { url = "https://files.pythonhosted.org/packages/cc/c7/e42aaca7bb2d22a7c06d5a8c7930086c5a334e93d716e6fa5e6647a4515f/ast_serialize-0.6.0-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:3ae22a366b752ab4496191525b78b097b5b72d531752e3c1dd7e383a8f2c8a1a", size = 1508464, upload-time = "2026-06-30T20:02:46.942Z" }, + { url = "https://files.pythonhosted.org/packages/95/93/5524a3dc6c3f593de3228ed9cbef73afa047625b7000ec21b7f58e6eb4d4/ast_serialize-0.6.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:4ed29121da8b3fdc291002801a1de0f76248fa07dce89157a5f277842cf6126e", size = 1457164, upload-time = "2026-06-30T20:02:48.294Z" }, + { url = "https://files.pythonhosted.org/packages/4f/c0/36a6ffb4d653cf621427b4c4928671f53ad800c453474de2b82564a44ad9/ast_serialize-0.6.0-cp39-abi3-pyemscripten_2026_0_wasm32.whl", hash = "sha256:b1dac4e09d341c1300ba69cdcbe62867b32a8c75d90db9bf4d083bec3b039f0b", size = 863014, upload-time = "2026-06-30T20:02:49.742Z" }, + { url = "https://files.pythonhosted.org/packages/09/c7/7d5ad8b49e1278e1c2a1e0274bd7850560b3f09313aa00c13bc8d5544792/ast_serialize-0.6.0-cp39-abi3-win32.whl", hash = "sha256:82c312a7844d2fdeb4d5c48bd3d215bf940dafd4704e1a9bcf252a99010a99b1", size = 1063165, upload-time = "2026-06-30T20:02:50.98Z" }, + { url = "https://files.pythonhosted.org/packages/47/ae/6710c14ecb276031cf10249f6adf5a59e2d3fdb3b5183bd59f70524067ee/ast_serialize-0.6.0-cp39-abi3-win_amd64.whl", hash = "sha256:113b58346f9ceb664352032770caca817d4a3c86f611c6088e6ef65ddaa70f0e", size = 1101444, upload-time = "2026-06-30T20:02:52.554Z" }, + { url = "https://files.pythonhosted.org/packages/66/40/c53deb2cd0c9b0fb636d24d9f40924cf2e65028e6b20b10cd5c1eeb2c730/ast_serialize-0.6.0-cp39-abi3-win_arm64.whl", hash = "sha256:ccd132fe8db56f61fe743b1f644d01b8d65b83248a8da506f3132bda86d6ed5e", size = 1072965, upload-time = "2026-06-30T20:02:54.097Z" }, +] + +[[package]] +name = "astor" +version = "0.8.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5a/21/75b771132fee241dfe601d39ade629548a9626d1d39f333fde31bc46febe/astor-0.8.1.tar.gz", hash = "sha256:6a6effda93f4e1ce9f618779b2dd1d9d84f1e32812c23a29b3fff6fd7f63fa5e", size = 35090, upload-time = "2019-12-10T01:50:35.51Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c3/88/97eef84f48fa04fbd6750e62dcceafba6c63c81b7ac1420856c8dcc0a3f9/astor-0.8.1-py2.py3-none-any.whl", hash = "sha256:070a54e890cefb5b3739d19f30f5a5ec840ffc9c50ffa7d23cc9fc1a38ebbfc5", size = 27488, upload-time = "2019-12-10T01:50:33.628Z" }, +] + +[[package]] +name = "astroid" +version = "4.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/a0/fc1c9f396c354456d859eb09fa13186bda34cb5b000f47a7103fcf84fe66/astroid-4.3.0.tar.gz", hash = "sha256:2b5b5048d6edc40e748e2728790e444b81c3d358e19cc89db6e973236192362f", size = 438804, upload-time = "2026-08-07T20:28:28.363Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/00/0a/f277a39699ac334e332c991b6ce9e47a30bb2bdac6d2141fdbd2d39835a9/astroid-4.3.0-py3-none-any.whl", hash = "sha256:47f329c1f4709c479f84f824c4f3a132816603a749cd4aa6ee9030e69951491a", size = 286532, upload-time = "2026-08-07T20:28:26.602Z" }, +] + +[[package]] +name = "attrs" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, +] + +[[package]] +name = "aws-sam-translator" +version = "1.109.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "boto3" }, + { name = "jsonschema" }, + { name = "pydantic" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e0/09/f62aa8d076f6ba85080ec6291e61af345e9be0daf8a4094101555e054ec7/aws_sam_translator-1.109.0.tar.gz", hash = "sha256:0c5e60223ae8434ce0c6bdb9a491d69ba3ec97e15c0d825d3803f7806382d804", size = 369016, upload-time = "2026-04-08T23:34:32.535Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/89/29/db13205af6bbebdc8dae9dd603ef97ee10a23cd8a3e26d9de728948b2e33/aws_sam_translator-1.109.0-py3-none-any.whl", hash = "sha256:9a6376e7c6d4fee173342b8b557035a8e3ec36e795e175e870411c8e4238873d", size = 432447, upload-time = "2026-04-08T23:34:30.881Z" }, +] + +[[package]] +name = "aws-xray-sdk" +version = "2.15.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "botocore" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/14/25/0cbd7a440080def5e6f063720c3b190a25f8aa2938c1e34415dc18241596/aws_xray_sdk-2.15.0.tar.gz", hash = "sha256:794381b96e835314345068ae1dd3b9120bd8b4e21295066c37e8814dbb341365", size = 76315, upload-time = "2025-10-29T20:59:45Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/c3/f30a7a63e664acc7c2545ca0491b6ce8264536e0e5cad3965f1d1b91e960/aws_xray_sdk-2.15.0-py2.py3-none-any.whl", hash = "sha256:422d62ad7d52e373eebb90b642eb1bb24657afe03b22a8df4a8b2e5108e278a3", size = 103228, upload-time = "2025-10-29T21:00:24.12Z" }, +] + +[[package]] +name = "babel" +version = "2.18.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/b2/51899539b6ceeeb420d40ed3cd4b7a40519404f9baf3d4ac99dc413a834b/babel-2.18.0.tar.gz", hash = "sha256:b80b99a14bd085fcacfa15c9165f651fbb3406e66cc603abf11c5750937c992d", size = 9959554, upload-time = "2026-02-01T12:30:56.078Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/77/f5/21d2de20e8b8b0408f0681956ca2c69f1320a3848ac50e6e7f39c6159675/babel-2.18.0-py3-none-any.whl", hash = "sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35", size = 10196845, upload-time = "2026-02-01T12:30:53.445Z" }, +] + +[[package]] +name = "backrefs" +version = "7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5e/a7/a7dd63622beef68cc0d3c3c36d472e143dd95443d5ebf14cd1a5b4dfbf11/backrefs-7.0.tar.gz", hash = "sha256:4989bb9e1e99eb23647c7160ed51fb21d0b41b5d200f2d3017da41e023097e82", size = 7012453, upload-time = "2026-04-28T16:28:04.215Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d4/39/39a31d7eae729ea14ed10c3ccef79371197177b9355a86cb3525709e8502/backrefs-7.0-py310-none-any.whl", hash = "sha256:b57cd227ea556b0aed3dc9b8da4628db4eabc0402c6d7fcfc69283a93955f7e9", size = 380824, upload-time = "2026-04-28T16:27:55.647Z" }, + { url = "https://files.pythonhosted.org/packages/c9/b5/9302644225ba7dfa934a2ff2b9c7bb85701313a90dddb3dfaf693fa5bae2/backrefs-7.0-py311-none-any.whl", hash = "sha256:a0fa7360c63509e9e077e174ef4e6d3c21c8db94189b9d957289ae6d794b9475", size = 392626, upload-time = "2026-04-28T16:27:57.42Z" }, + { url = "https://files.pythonhosted.org/packages/36/da/87912ddec6e06feffbaa3d7aa18fc6352bee2e8f1fee185d7d1690f8f4e8/backrefs-7.0-py312-none-any.whl", hash = "sha256:ca42ce6a49ace3d75684dfa9937f3373902a63284ecb385ce36d15e5dcb41c12", size = 398537, upload-time = "2026-04-28T16:27:58.913Z" }, + { url = "https://files.pythonhosted.org/packages/00/bb/90ba423612b6aa0adccc6b1874bcd4a9b44b660c0c16f346611e00f64ac3/backrefs-7.0-py313-none-any.whl", hash = "sha256:f2c52955d631b9e1ac4cd56209f0a3a946d592b98e7790e77699339ae01c102a", size = 400491, upload-time = "2026-04-28T16:28:00.928Z" }, + { url = "https://files.pythonhosted.org/packages/3e/5c/fb93d3092640a24dfb7bd7727a24016d7c01774ca013e60efd3f683c8002/backrefs-7.0-py314-none-any.whl", hash = "sha256:a6448b28180e3ca01134c9cf09dcebafad8531072e09903c5451748a05f24bc9", size = 412349, upload-time = "2026-04-28T16:28:02.412Z" }, +] + +[[package]] +name = "blinker" +version = "1.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/21/28/9b3f50ce0e048515135495f198351908d99540d69bfdc8c1d15b73dc55ce/blinker-1.9.0.tar.gz", hash = "sha256:b4ce2265a7abece45e7cc896e98dbebe6cead56bcf805a3d23136d145f5445bf", size = 22460, upload-time = "2024-11-08T17:25:47.436Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc", size = 8458, upload-time = "2024-11-08T17:25:46.184Z" }, +] + +[[package]] +name = "boto3" +version = "1.43.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "botocore" }, + { name = "jmespath" }, + { name = "s3transfer" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b7/65/47670987f2f9e181397872c7ee6415b7b95156d711b7eab6c55f66e575bc/boto3-1.43.0.tar.gz", hash = "sha256:80d44a943ef90aba7958ab31d30c155c198acc8a9581b5846b3878b2c8951086", size = 113143, upload-time = "2026-04-29T22:07:49.084Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/a0/3e6a0b1c1ea6bec76f71473727ef27abf3cd40e9709b3ebcbfbcfaae6f79/boto3-1.43.0-py3-none-any.whl", hash = "sha256:8ebe03754a4b73a5cb6ec2f14cca03ac33bd4760d0adea53da4724845130258b", size = 140497, upload-time = "2026-04-29T22:07:46.216Z" }, +] + +[[package]] +name = "botocore" +version = "1.43.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jmespath" }, + { name = "python-dateutil" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/28/79/2f4be1896db3db7ccf44504253a175d56b6bd6b669619edc5147d1aa21ea/botocore-1.43.0.tar.gz", hash = "sha256:e933b31a2d644253e1d029d7d39e99ba41b87e29300534f189744cc438cdf928", size = 15286817, upload-time = "2026-04-29T22:07:31.723Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bf/4b/afc1fef8a43bafb139f57f73bbd70df82807af5934321e8112ae50668827/botocore-1.43.0-py3-none-any.whl", hash = "sha256:cc5b15eaec3c6eac05d8012cb5ef17ebe891beb88a16ca13c374bfaece1241e6", size = 14970102, upload-time = "2026-04-29T22:07:27Z" }, +] + +[[package]] +name = "cairocffi" +version = "1.7.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/70/c5/1a4dc131459e68a173cbdab5fad6b524f53f9c1ef7861b7698e998b837cc/cairocffi-1.7.1.tar.gz", hash = "sha256:2e48ee864884ec4a3a34bfa8c9ab9999f688286eb714a15a43ec9d068c36557b", size = 88096, upload-time = "2024-06-18T10:56:06.741Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/93/d8/ba13451aa6b745c49536e87b6bf8f629b950e84bd0e8308f7dc6883b67e2/cairocffi-1.7.1-py3-none-any.whl", hash = "sha256:9803a0e11f6c962f3b0ae2ec8ba6ae45e957a146a004697a1ac1bbf16b073b3f", size = 75611, upload-time = "2024-06-18T10:55:59.489Z" }, +] + +[[package]] +name = "cairosvg" +version = "2.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cairocffi" }, + { name = "cssselect2" }, + { name = "defusedxml" }, + { name = "pillow" }, + { name = "tinycss2" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/38/07/e8412a13019b3f737972dea23a2c61ca42becafc16c9338f4ca7a0caa993/cairosvg-2.9.0.tar.gz", hash = "sha256:1debb00cd2da11350d8b6f5ceb739f1b539196d71d5cf5eb7363dbd1bfbc8dc5", size = 40877, upload-time = "2026-03-13T15:42:00.564Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bf/e0/5011747466414c12cac8a8df77aa235068669a6a5a5df301a96209db6054/cairosvg-2.9.0-py3-none-any.whl", hash = "sha256:4b82d07d145377dffdfc19d9791bd5fb65539bb4da0adecf0bdbd9cd4ffd7c68", size = 45962, upload-time = "2026-03-14T13:56:33.512Z" }, +] + +[[package]] +name = "cast-value-rs" +version = "0.4.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/56/a4/634d1917ac49ea69291471e87eee9c1aa45d71d6da9b2cd5e1bfe82729de/cast_value_rs-0.4.2.tar.gz", hash = "sha256:fd621b8dd4f7e93bbffdb119882d85e2731c2f0fb1d30de85f29e8e04c044822", size = 86862, upload-time = "2026-08-13T09:16:59.199Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/67/c7/9db59d415df2d1c9f905c4da951fe023c6259a162584ef68bd81c171d448/cast_value_rs-0.4.2-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:6d8e1c6d7b0fec6b1060f83867d20ebd0cb1ac6fa2954cd82f418a31a96ac504", size = 494354, upload-time = "2026-08-13T09:14:41.627Z" }, + { url = "https://files.pythonhosted.org/packages/8f/53/10ece0b4ba4a0c156674c2db7e5d05ce9b04efe72e191417546e111d645c/cast_value_rs-0.4.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8c953321ff7954e0fe1b25c1baf96f0a9cae0961b8a56ce63dc7b94e2ea7d85c", size = 458463, upload-time = "2026-08-13T09:14:43.371Z" }, + { url = "https://files.pythonhosted.org/packages/91/0b/e50ac2eb271eb6c34402b4abe317c795bc7d650d332d0bf422ae868aa2cd/cast_value_rs-0.4.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:68492eef745691c80754cd027e216dbd5f7a4ce2e07fddfded3ee59bd947afb5", size = 487628, upload-time = "2026-08-13T09:14:44.86Z" }, + { url = "https://files.pythonhosted.org/packages/a9/0f/69befc7905af2e73a2739b26444787cd528331c041f37235f3853bf15f75/cast_value_rs-0.4.2-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:fbf145ed6f724fa7f5ddc9715f78e0d450ac141fc05299c83b2e7d627793ddaf", size = 555538, upload-time = "2026-08-13T09:14:46.305Z" }, + { url = "https://files.pythonhosted.org/packages/4a/1b/4105fabec3268139bda3555422808211ec29428e17fa56566c1af7957c04/cast_value_rs-0.4.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:73fb23256dda16e4e9f49bfedebe0e068f00ece85091b526c102618f66144216", size = 650896, upload-time = "2026-08-13T09:14:48.049Z" }, + { url = "https://files.pythonhosted.org/packages/83/2a/452cf37675af02c3ac8bfa01fc962cb744a1392c51bccfb6d1faca423067/cast_value_rs-0.4.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8184135c78ebcabb904574a1b3bc5704c131140feae1b58d65c888fe08b46029", size = 561036, upload-time = "2026-08-13T09:14:49.431Z" }, + { url = "https://files.pythonhosted.org/packages/d4/87/edb215d17da304a6b36489fc51b8eb785c5b041c2fcc5f200f16adde3133/cast_value_rs-0.4.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:686ea86aad1ffebd0b6793549043108600593a85032457eb88a3a0513a4100f5", size = 549187, upload-time = "2026-08-13T09:14:50.801Z" }, + { url = "https://files.pythonhosted.org/packages/63/82/0f9963ef0bcb434cd1244cb2620123c2d71763d429d017ceb98fbb6faf48/cast_value_rs-0.4.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d6c425d2803e13408755a0022faa9efd0ab0becdf3573a1a8a7af64b1adee4ba", size = 591027, upload-time = "2026-08-13T09:14:52.281Z" }, + { url = "https://files.pythonhosted.org/packages/90/97/b489f8048491f2ece21bf99d5a1fea3bbfaf3cd0e9f555ac4a0352c11d81/cast_value_rs-0.4.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:92556f1bb9d6b222736d967228565ec745c640c29bc291d1cb730a1011d3dcac", size = 665201, upload-time = "2026-08-13T09:14:53.769Z" }, + { url = "https://files.pythonhosted.org/packages/ce/9f/fabffd9788f0b2d3f49ca4582b8859ab58b929b1b8837ec0be1263399279/cast_value_rs-0.4.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:1b0881c23a8f5ff1dc6c70542179f2fc9191e0b7fa7a02f65316fb48904cd8d1", size = 831085, upload-time = "2026-08-13T09:14:55.244Z" }, + { url = "https://files.pythonhosted.org/packages/b5/66/ca653bf9b51eb624615623611db28ec9428a351259fcf5625c5520faf759/cast_value_rs-0.4.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:8a67648bf47d9b740388efaf6f05185f22dea783e97eba895efdd1dbafe8e3cc", size = 788462, upload-time = "2026-08-13T09:14:56.666Z" }, + { url = "https://files.pythonhosted.org/packages/f1/54/3a9280f791c8765a54f7814a010d2f460c7d5f5483be3e5634f4d9b38d75/cast_value_rs-0.4.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:decf297bc576675fff2139885fb88f84844e27b99e5d28eaa01909db7a327c4b", size = 753055, upload-time = "2026-08-13T09:14:58.302Z" }, + { url = "https://files.pythonhosted.org/packages/06/26/09f4618dbab2de8ea427e817c349b8391b4d559316de899e9b54dde6143e/cast_value_rs-0.4.2-cp312-cp312-win_amd64.whl", hash = "sha256:79a8c13af39bf65014dd6567dc5fa7c42dfda246e4335ab52814f3dd6fb42cac", size = 442068, upload-time = "2026-08-13T09:15:00.414Z" }, + { url = "https://files.pythonhosted.org/packages/fc/49/7def5933625ff3c98e7d20cbd7de0aa1e83098ffa425a9df087764657767/cast_value_rs-0.4.2-cp312-cp312-win_arm64.whl", hash = "sha256:b8af7de3639271ad9e62aba4d15ddd22819c706bd7c7859663fdbb022397bdad", size = 397846, upload-time = "2026-08-13T09:15:02.022Z" }, + { url = "https://files.pythonhosted.org/packages/6f/fc/1f48ae9ea1f10caf3bbc31b288d08137835d8965188f6ddcccdb3c7d398e/cast_value_rs-0.4.2-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:297445abc64891a2e62af93e4f35bb280f874ac548646d0a6b04a86d45e636a5", size = 494394, upload-time = "2026-08-13T09:15:03.604Z" }, + { url = "https://files.pythonhosted.org/packages/7f/f3/d633218979cd8839fcfbade64a277c0ff9d8ff59d21bbd8a59f1467085b4/cast_value_rs-0.4.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:b8b6e0781b4ce61a559cc050d836a52157bd30b1f59d63fdeee79fbc19ab7e57", size = 458677, upload-time = "2026-08-13T09:15:04.947Z" }, + { url = "https://files.pythonhosted.org/packages/97/e4/96d72ccf5e00dd7af7bf55c96313df2ffba1f34a224f10430716232775c0/cast_value_rs-0.4.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8399dc89570c01537c07adc03fc2fc0e43a517be8a198e2f9e3f8a70dd003be0", size = 487289, upload-time = "2026-08-13T09:15:06.493Z" }, + { url = "https://files.pythonhosted.org/packages/93/30/18313de8c1d3826e9a6abd883b7a7981b19391f674dcd52ff2635d19f8ee/cast_value_rs-0.4.2-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:939417d72c9945ce24eb959e6b2cd32f7aa7d0a50a06a0fac484056b10b650dd", size = 555221, upload-time = "2026-08-13T09:15:08.28Z" }, + { url = "https://files.pythonhosted.org/packages/e9/1f/ed22b2e536ccbd4c5b234d869fc8f478347a45f7b940273023a0d6013134/cast_value_rs-0.4.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:101318e594ee998a5ccbc5ea7ed045cbd9fd22d45cac467c745fbd30309f1343", size = 650972, upload-time = "2026-08-13T09:15:10.103Z" }, + { url = "https://files.pythonhosted.org/packages/d7/d2/39f9ff9b678dfb01d206aec6be0f486137d5e9669ebadf0d1f356d2a7324/cast_value_rs-0.4.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d23bac26b2c2fe6a2368d10fbb072a71671f6e0d4d8cf9e893f62ed3530bbd1b", size = 560869, upload-time = "2026-08-13T09:15:11.602Z" }, + { url = "https://files.pythonhosted.org/packages/60/18/f63e8378db66b5a99e96c1422c68ba02a4e35de34355b90cf6d169d99ae6/cast_value_rs-0.4.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b9d799a20d7517974d61d7c4dd54e5d7ef439e726012c087bada31bc644b1535", size = 548885, upload-time = "2026-08-13T09:15:13.18Z" }, + { url = "https://files.pythonhosted.org/packages/98/af/12349007b670b11e16d3be51c29ab2398550b2653dae692a5d788d3dda87/cast_value_rs-0.4.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:b9f0f04815efcc47592474e91f61f24810139396696f0690f3d0bf0e6ff3bb4a", size = 590846, upload-time = "2026-08-13T09:15:14.67Z" }, + { url = "https://files.pythonhosted.org/packages/a3/cf/6a39df104923bc397ae58f90e21d1e87edd62d17f24fe3d6777e6c4d3e5f/cast_value_rs-0.4.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e69f81dab0b47c74c1f30c79198c412938b6c41510b8124dbd08fb36d13a8807", size = 665064, upload-time = "2026-08-13T09:15:16.527Z" }, + { url = "https://files.pythonhosted.org/packages/36/df/0a9ac5bae4e1d3b7b4a79795054d822c26bdbc3bedad71fe13e8ce666c4b/cast_value_rs-0.4.2-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:59e15ec495e8707447180e0111e65e083464da60236edd5c3387efedce3da997", size = 830909, upload-time = "2026-08-13T09:15:18.088Z" }, + { url = "https://files.pythonhosted.org/packages/2f/7d/9e99c969dd76087dbf731667982d8bb6b390d29c8f37c09dd330657b0487/cast_value_rs-0.4.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:f9e787397588fabb28a146a28159150f44e8ef85a25abe364f989044f1b7159d", size = 788217, upload-time = "2026-08-13T09:15:19.706Z" }, + { url = "https://files.pythonhosted.org/packages/21/a9/5d7410d37be26bed1dc740c885a0c7fdb213b93e9b13ac76fb3282aa50ea/cast_value_rs-0.4.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:5c66ca6ad21758993830a9f4d24263065727bf767e4524d79ded0c0b61e3da9d", size = 752817, upload-time = "2026-08-13T09:15:21.197Z" }, + { url = "https://files.pythonhosted.org/packages/65/10/9c18cb01104bb211c9b0d9a956fae3f1a40f743c35bbc6763d0114ec36a7/cast_value_rs-0.4.2-cp313-cp313-win_amd64.whl", hash = "sha256:26fe305d5bd35d21c5ee72c5651892895447e175ba3019a24713c565d965c0ef", size = 442025, upload-time = "2026-08-13T09:15:22.575Z" }, + { url = "https://files.pythonhosted.org/packages/64/49/42a0b48a71aca3ebb0abd0948fa9d484723c3562af30a8d6904b874abb2f/cast_value_rs-0.4.2-cp313-cp313-win_arm64.whl", hash = "sha256:9ce6678fc4b1bdc459178225347acd8019f1d22bca1e13ab86cc2a3e4ecb2f46", size = 397871, upload-time = "2026-08-13T09:15:23.906Z" }, + { url = "https://files.pythonhosted.org/packages/be/e9/baf39cd3991962705ffd055fce071e23e7707f62df3fb44af2ffe0e84d11/cast_value_rs-0.4.2-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:cefdcfd4d2b95e3b35fd98b3d3d865be9b3ef1bc1264db3bc1b8c50c5e8ac999", size = 495672, upload-time = "2026-08-13T09:15:25.168Z" }, + { url = "https://files.pythonhosted.org/packages/ed/9f/7ac6bf95d160f3fd89020aa952ffb4a49216b85a3fda02f84bc2c2612a2f/cast_value_rs-0.4.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:cbcec2cfd199c1e404f5bda71b273b4a7470762f4b55c1c21f09d60d2762e339", size = 458480, upload-time = "2026-08-13T09:15:26.647Z" }, + { url = "https://files.pythonhosted.org/packages/65/e5/46c2985ccbae41c8140f04f2acc9080761f10e8d2f8101c46083e632f812/cast_value_rs-0.4.2-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c224a9b30c2521cd06eac4bb1ac3860f41c902695e6f806344bc039d7a8a1d93", size = 486807, upload-time = "2026-08-13T09:15:28.129Z" }, + { url = "https://files.pythonhosted.org/packages/18/13/97851c45b275fbc9d42b5d5a340fd5ea430525b60c2eacfe6a36399d69ef/cast_value_rs-0.4.2-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:1eaa7c3d5fe418a74928f78514f9baeaeb8e31b93db96b1761edd6144f0d2eff", size = 555335, upload-time = "2026-08-13T09:15:29.648Z" }, + { url = "https://files.pythonhosted.org/packages/7f/b3/c84c1e820786ddb062b162112b80e5dfc1b5b54b11125618f38c1e18d075/cast_value_rs-0.4.2-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3bddec46b36f29964c8d4bbe82b8270575fbe1c0fb41c404bb3da1778f390a24", size = 650347, upload-time = "2026-08-13T09:15:31.044Z" }, + { url = "https://files.pythonhosted.org/packages/60/38/52b4cc31570384e0286e28a03164a357d53a8aba7421ef83e500843d5449/cast_value_rs-0.4.2-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ab3fd77144d26e2da2a113f862c05ea1cf465df347daf5deb6cf1689253fddfa", size = 561498, upload-time = "2026-08-13T09:15:32.485Z" }, + { url = "https://files.pythonhosted.org/packages/41/c8/313e1d016b0adfccd1ead2bb28d2c94313ab62534bd6e11db19a480d3b55/cast_value_rs-0.4.2-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e4affe8668a2f17764ed978c2dddb2b49554f36a71389e6928a8a5523c1a4173", size = 548676, upload-time = "2026-08-13T09:15:33.912Z" }, + { url = "https://files.pythonhosted.org/packages/81/8b/a11f8e514598ebfc084507b0db390ecbdc6bfcffbf91ae666e0de93e6c25/cast_value_rs-0.4.2-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a67316b00ca01a78865d222badef2b1cb6c60ad5ebd360bf4fa3b224e87b8ffa", size = 590803, upload-time = "2026-08-13T09:15:35.384Z" }, + { url = "https://files.pythonhosted.org/packages/94/1e/ed86da6fe69eff312cc83e348cf4715d4168ab2699783febd24bfd477cd8/cast_value_rs-0.4.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:9946054c77d7c5df579e9e99ebebd4d8a220cb04a6af1b6467112dfe07eee72d", size = 664118, upload-time = "2026-08-13T09:15:36.797Z" }, + { url = "https://files.pythonhosted.org/packages/0b/01/58a3eadff1233bd98d5809e2f6b5dc6d1b8c4c770664145f57fd0bdce756/cast_value_rs-0.4.2-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:95b064458233a7ef0525481eccfd2d37e86620d877ab1535ae809d37355cf131", size = 830686, upload-time = "2026-08-13T09:15:38.645Z" }, + { url = "https://files.pythonhosted.org/packages/e6/40/a234d9d06013a0bee08f662ab083b3a55decfa2dbb315094fdf06693d425/cast_value_rs-0.4.2-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:d7de068a1dcc65d1aaf4e93228198b588776bd25b62ef42478ab7efe5245a6f3", size = 787835, upload-time = "2026-08-13T09:15:40.078Z" }, + { url = "https://files.pythonhosted.org/packages/d6/72/93f906345d03972de52e3e74dd4ed12b56aab53bec85cc96020690ba6dbe/cast_value_rs-0.4.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ae0cbdd44290a74e34519eb990b33bf0f8e96f0fde95ffc799913ff1aab27719", size = 753039, upload-time = "2026-08-13T09:15:41.702Z" }, + { url = "https://files.pythonhosted.org/packages/e3/a5/47b6db4f68da086db3f3768775f545b9b7f660cab8f61039c91de1f813c4/cast_value_rs-0.4.2-cp314-cp314-win32.whl", hash = "sha256:d438517530d3a8d6bc810ab6dee831c48b45287435513fea1b0476b5d4fda07d", size = 387092, upload-time = "2026-08-13T09:15:43.218Z" }, + { url = "https://files.pythonhosted.org/packages/d3/9c/5f71a5e94875bb999646227a583792dbbe9a2b257df0d961e8a2da879f9e/cast_value_rs-0.4.2-cp314-cp314-win_amd64.whl", hash = "sha256:7e7bb9faa4820b7eb0d99074fd61efff3a7392e72b6abe4b41c9d6b6d14fe457", size = 442126, upload-time = "2026-08-13T09:15:44.623Z" }, + { url = "https://files.pythonhosted.org/packages/95/1c/8e7546a044da8e92eafbb12594169301cc94e2a071fd3e34204595d0a05f/cast_value_rs-0.4.2-cp314-cp314-win_arm64.whl", hash = "sha256:1f57e762a06102d61e940548a6ab841e05ad1f51f1c4e2aa26bc27a8c59a5abc", size = 398200, upload-time = "2026-08-13T09:15:46.117Z" }, + { url = "https://files.pythonhosted.org/packages/a0/09/527646deeb622e5a597e4271e9e06d9d7cd24d64de77b8cb4ce250128c18/cast_value_rs-0.4.2-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:230f6440db74d2d11e513060d0e72aa3f897546465bc778d30aaeac90f8e733e", size = 485197, upload-time = "2026-08-13T09:15:47.622Z" }, + { url = "https://files.pythonhosted.org/packages/b9/79/aaa713cb151a902439b670a4774ea76d0a5dadf1f03954f6a34af2a6cb1e/cast_value_rs-0.4.2-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:37538170dc1fedbfd62dd56670e443b881474e7eda7f583a3c989c83a9ff15fc", size = 538669, upload-time = "2026-08-13T09:15:49.148Z" }, + { url = "https://files.pythonhosted.org/packages/d3/b1/2cf4f4f13f74caaa4dab4ddf4924fdeeffb39920d5ec30a80112aa041efa/cast_value_rs-0.4.2-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:86d00b9cef0d38d0c5631ba63270c38c5d7c85aa87c609644f204919f939f0c9", size = 649341, upload-time = "2026-08-13T09:15:50.614Z" }, + { url = "https://files.pythonhosted.org/packages/39/8b/1faa6b27cda3dd793635c7945118e49188b6714d6bf23bb072efd718e467/cast_value_rs-0.4.2-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:89434eebb7a12f66e99382e08c32648f055e24d9fce66274adef6620af2aebbd", size = 555253, upload-time = "2026-08-13T09:15:52.252Z" }, + { url = "https://files.pythonhosted.org/packages/8b/c2/d31f177025b51a3fda70c5888b92f5fd30ec53bc2df2c046fc9a2717cd36/cast_value_rs-0.4.2-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:704171aec75f417f5a70a3eb5f107fbfc79183620093c9d9074290920a5981f1", size = 547964, upload-time = "2026-08-13T09:15:53.669Z" }, + { url = "https://files.pythonhosted.org/packages/64/99/521c2d6347ca39deef237909dfee61c6d2cb806dcc20d74636e209bc646e/cast_value_rs-0.4.2-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2add2599d299436ec161661a8e119a69742c763a0936e542db92b1ce9d6e0c04", size = 574778, upload-time = "2026-08-13T09:15:55.479Z" }, + { url = "https://files.pythonhosted.org/packages/f0/70/35c7cb37839454aeb93b9576b42daebd8249dd59e3834cd1be020b4b0660/cast_value_rs-0.4.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:da5df79a926bdcc1f5494612f621027970a9702eb49d556068025166d4c0ace2", size = 662461, upload-time = "2026-08-13T09:15:56.97Z" }, + { url = "https://files.pythonhosted.org/packages/24/4f/a71bfaea1286bd12cc912733d650bd89a07c4430ee715202551c6e3eb0b0/cast_value_rs-0.4.2-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:5552e3c80d43de7a8a821793cb57da0dd3720a377051a5bf86bcabe094e87777", size = 814743, upload-time = "2026-08-13T09:15:58.652Z" }, + { url = "https://files.pythonhosted.org/packages/94/a3/b04e0f42dafeae30604abca079cce303ebb69ba24f3c4debbf211ecc781c/cast_value_rs-0.4.2-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:73978c6dd2ce45a05a59ec7090df8b3f2a579ee86db9b1c7df21ede17f32189e", size = 782340, upload-time = "2026-08-13T09:16:00.135Z" }, + { url = "https://files.pythonhosted.org/packages/3a/6c/913de75054092de796509dc04b92fc6ac1bf83dc86901f1f482667dead16/cast_value_rs-0.4.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:45d630592afb18880d4df0d7afb28b8cfc0ba6aa742d8db115f616df284b453a", size = 754068, upload-time = "2026-08-13T09:16:01.572Z" }, +] + +[[package]] +name = "certifi" +version = "2026.4.22" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/25/ee/6caf7a40c36a1220410afe15a1cc64993a1f864871f698c0f93acb72842a/certifi-2026.4.22.tar.gz", hash = "sha256:8d455352a37b71bf76a79caa83a3d6c25afee4a385d632127b6afb3963f1c580", size = 137077, upload-time = "2026-04-22T11:26:11.191Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/30/7cd8fdcdfbc5b869528b079bfb76dcdf6056b1a2097a662e5e8c04f42965/certifi-2026.4.22-py3-none-any.whl", hash = "sha256:3cb2210c8f88ba2318d29b0388d1023c8492ff72ecdde4ebdaddbb13a31b1c4a", size = 135707, upload-time = "2026-04-22T11:26:09.372Z" }, +] + +[[package]] +name = "cffi" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pycparser", marker = "implementation_name != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/eb/56/b1ba7935a17738ae8453301356628e8147c79dbb825bcbc73dc7401f9846/cffi-2.0.0.tar.gz", hash = "sha256:44d1b5909021139fe36001ae048dbdde8214afa20200eda0f64c068cac5d5529", size = 523588, upload-time = "2025-09-08T23:24:04.541Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ea/47/4f61023ea636104d4f16ab488e268b93008c3d0bb76893b1b31db1f96802/cffi-2.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d02d6655b0e54f54c4ef0b94eb6be0607b70853c45ce98bd278dc7de718be5d", size = 185271, upload-time = "2025-09-08T23:22:44.795Z" }, + { url = "https://files.pythonhosted.org/packages/df/a2/781b623f57358e360d62cdd7a8c681f074a71d445418a776eef0aadb4ab4/cffi-2.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8eca2a813c1cb7ad4fb74d368c2ffbbb4789d377ee5bb8df98373c2cc0dee76c", size = 181048, upload-time = "2025-09-08T23:22:45.938Z" }, + { url = "https://files.pythonhosted.org/packages/ff/df/a4f0fbd47331ceeba3d37c2e51e9dfc9722498becbeec2bd8bc856c9538a/cffi-2.0.0-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:21d1152871b019407d8ac3985f6775c079416c282e431a4da6afe7aefd2bccbe", size = 212529, upload-time = "2025-09-08T23:22:47.349Z" }, + { url = "https://files.pythonhosted.org/packages/d5/72/12b5f8d3865bf0f87cf1404d8c374e7487dcf097a1c91c436e72e6badd83/cffi-2.0.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b21e08af67b8a103c71a250401c78d5e0893beff75e28c53c98f4de42f774062", size = 220097, upload-time = "2025-09-08T23:22:48.677Z" }, + { url = "https://files.pythonhosted.org/packages/c2/95/7a135d52a50dfa7c882ab0ac17e8dc11cec9d55d2c18dda414c051c5e69e/cffi-2.0.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:1e3a615586f05fc4065a8b22b8152f0c1b00cdbc60596d187c2a74f9e3036e4e", size = 207983, upload-time = "2025-09-08T23:22:50.06Z" }, + { url = "https://files.pythonhosted.org/packages/3a/c8/15cb9ada8895957ea171c62dc78ff3e99159ee7adb13c0123c001a2546c1/cffi-2.0.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:81afed14892743bbe14dacb9e36d9e0e504cd204e0b165062c488942b9718037", size = 206519, upload-time = "2025-09-08T23:22:51.364Z" }, + { url = "https://files.pythonhosted.org/packages/78/2d/7fa73dfa841b5ac06c7b8855cfc18622132e365f5b81d02230333ff26e9e/cffi-2.0.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3e17ed538242334bf70832644a32a7aae3d83b57567f9fd60a26257e992b79ba", size = 219572, upload-time = "2025-09-08T23:22:52.902Z" }, + { url = "https://files.pythonhosted.org/packages/07/e0/267e57e387b4ca276b90f0434ff88b2c2241ad72b16d31836adddfd6031b/cffi-2.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3925dd22fa2b7699ed2617149842d2e6adde22b262fcbfada50e3d195e4b3a94", size = 222963, upload-time = "2025-09-08T23:22:54.518Z" }, + { url = "https://files.pythonhosted.org/packages/b6/75/1f2747525e06f53efbd878f4d03bac5b859cbc11c633d0fb81432d98a795/cffi-2.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2c8f814d84194c9ea681642fd164267891702542f028a15fc97d4674b6206187", size = 221361, upload-time = "2025-09-08T23:22:55.867Z" }, + { url = "https://files.pythonhosted.org/packages/7b/2b/2b6435f76bfeb6bbf055596976da087377ede68df465419d192acf00c437/cffi-2.0.0-cp312-cp312-win32.whl", hash = "sha256:da902562c3e9c550df360bfa53c035b2f241fed6d9aef119048073680ace4a18", size = 172932, upload-time = "2025-09-08T23:22:57.188Z" }, + { url = "https://files.pythonhosted.org/packages/f8/ed/13bd4418627013bec4ed6e54283b1959cf6db888048c7cf4b4c3b5b36002/cffi-2.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:da68248800ad6320861f129cd9c1bf96ca849a2771a59e0344e88681905916f5", size = 183557, upload-time = "2025-09-08T23:22:58.351Z" }, + { url = "https://files.pythonhosted.org/packages/95/31/9f7f93ad2f8eff1dbc1c3656d7ca5bfd8fb52c9d786b4dcf19b2d02217fa/cffi-2.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:4671d9dd5ec934cb9a73e7ee9676f9362aba54f7f34910956b84d727b0d73fb6", size = 177762, upload-time = "2025-09-08T23:22:59.668Z" }, + { url = "https://files.pythonhosted.org/packages/4b/8d/a0a47a0c9e413a658623d014e91e74a50cdd2c423f7ccfd44086ef767f90/cffi-2.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:00bdf7acc5f795150faa6957054fbbca2439db2f775ce831222b66f192f03beb", size = 185230, upload-time = "2025-09-08T23:23:00.879Z" }, + { url = "https://files.pythonhosted.org/packages/4a/d2/a6c0296814556c68ee32009d9c2ad4f85f2707cdecfd7727951ec228005d/cffi-2.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:45d5e886156860dc35862657e1494b9bae8dfa63bf56796f2fb56e1679fc0bca", size = 181043, upload-time = "2025-09-08T23:23:02.231Z" }, + { url = "https://files.pythonhosted.org/packages/b0/1e/d22cc63332bd59b06481ceaac49d6c507598642e2230f201649058a7e704/cffi-2.0.0-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:07b271772c100085dd28b74fa0cd81c8fb1a3ba18b21e03d7c27f3436a10606b", size = 212446, upload-time = "2025-09-08T23:23:03.472Z" }, + { url = "https://files.pythonhosted.org/packages/a9/f5/a2c23eb03b61a0b8747f211eb716446c826ad66818ddc7810cc2cc19b3f2/cffi-2.0.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d48a880098c96020b02d5a1f7d9251308510ce8858940e6fa99ece33f610838b", size = 220101, upload-time = "2025-09-08T23:23:04.792Z" }, + { url = "https://files.pythonhosted.org/packages/f2/7f/e6647792fc5850d634695bc0e6ab4111ae88e89981d35ac269956605feba/cffi-2.0.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:f93fd8e5c8c0a4aa1f424d6173f14a892044054871c771f8566e4008eaa359d2", size = 207948, upload-time = "2025-09-08T23:23:06.127Z" }, + { url = "https://files.pythonhosted.org/packages/cb/1e/a5a1bd6f1fb30f22573f76533de12a00bf274abcdc55c8edab639078abb6/cffi-2.0.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:dd4f05f54a52fb558f1ba9f528228066954fee3ebe629fc1660d874d040ae5a3", size = 206422, upload-time = "2025-09-08T23:23:07.753Z" }, + { url = "https://files.pythonhosted.org/packages/98/df/0a1755e750013a2081e863e7cd37e0cdd02664372c754e5560099eb7aa44/cffi-2.0.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c8d3b5532fc71b7a77c09192b4a5a200ea992702734a2e9279a37f2478236f26", size = 219499, upload-time = "2025-09-08T23:23:09.648Z" }, + { url = "https://files.pythonhosted.org/packages/50/e1/a969e687fcf9ea58e6e2a928ad5e2dd88cc12f6f0ab477e9971f2309b57c/cffi-2.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d9b29c1f0ae438d5ee9acb31cadee00a58c46cc9c0b2f9038c6b0b3470877a8c", size = 222928, upload-time = "2025-09-08T23:23:10.928Z" }, + { url = "https://files.pythonhosted.org/packages/36/54/0362578dd2c9e557a28ac77698ed67323ed5b9775ca9d3fe73fe191bb5d8/cffi-2.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6d50360be4546678fc1b79ffe7a66265e28667840010348dd69a314145807a1b", size = 221302, upload-time = "2025-09-08T23:23:12.42Z" }, + { url = "https://files.pythonhosted.org/packages/eb/6d/bf9bda840d5f1dfdbf0feca87fbdb64a918a69bca42cfa0ba7b137c48cb8/cffi-2.0.0-cp313-cp313-win32.whl", hash = "sha256:74a03b9698e198d47562765773b4a8309919089150a0bb17d829ad7b44b60d27", size = 172909, upload-time = "2025-09-08T23:23:14.32Z" }, + { url = "https://files.pythonhosted.org/packages/37/18/6519e1ee6f5a1e579e04b9ddb6f1676c17368a7aba48299c3759bbc3c8b3/cffi-2.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:19f705ada2530c1167abacb171925dd886168931e0a7b78f5bffcae5c6b5be75", size = 183402, upload-time = "2025-09-08T23:23:15.535Z" }, + { url = "https://files.pythonhosted.org/packages/cb/0e/02ceeec9a7d6ee63bb596121c2c8e9b3a9e150936f4fbef6ca1943e6137c/cffi-2.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:256f80b80ca3853f90c21b23ee78cd008713787b1b1e93eae9f3d6a7134abd91", size = 177780, upload-time = "2025-09-08T23:23:16.761Z" }, + { url = "https://files.pythonhosted.org/packages/92/c4/3ce07396253a83250ee98564f8d7e9789fab8e58858f35d07a9a2c78de9f/cffi-2.0.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:fc33c5141b55ed366cfaad382df24fe7dcbc686de5be719b207bb248e3053dc5", size = 185320, upload-time = "2025-09-08T23:23:18.087Z" }, + { url = "https://files.pythonhosted.org/packages/59/dd/27e9fa567a23931c838c6b02d0764611c62290062a6d4e8ff7863daf9730/cffi-2.0.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c654de545946e0db659b3400168c9ad31b5d29593291482c43e3564effbcee13", size = 181487, upload-time = "2025-09-08T23:23:19.622Z" }, + { url = "https://files.pythonhosted.org/packages/d6/43/0e822876f87ea8a4ef95442c3d766a06a51fc5298823f884ef87aaad168c/cffi-2.0.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:24b6f81f1983e6df8db3adc38562c83f7d4a0c36162885ec7f7b77c7dcbec97b", size = 220049, upload-time = "2025-09-08T23:23:20.853Z" }, + { url = "https://files.pythonhosted.org/packages/b4/89/76799151d9c2d2d1ead63c2429da9ea9d7aac304603de0c6e8764e6e8e70/cffi-2.0.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:12873ca6cb9b0f0d3a0da705d6086fe911591737a59f28b7936bdfed27c0d47c", size = 207793, upload-time = "2025-09-08T23:23:22.08Z" }, + { url = "https://files.pythonhosted.org/packages/bb/dd/3465b14bb9e24ee24cb88c9e3730f6de63111fffe513492bf8c808a3547e/cffi-2.0.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:d9b97165e8aed9272a6bb17c01e3cc5871a594a446ebedc996e2397a1c1ea8ef", size = 206300, upload-time = "2025-09-08T23:23:23.314Z" }, + { url = "https://files.pythonhosted.org/packages/47/d9/d83e293854571c877a92da46fdec39158f8d7e68da75bf73581225d28e90/cffi-2.0.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:afb8db5439b81cf9c9d0c80404b60c3cc9c3add93e114dcae767f1477cb53775", size = 219244, upload-time = "2025-09-08T23:23:24.541Z" }, + { url = "https://files.pythonhosted.org/packages/2b/0f/1f177e3683aead2bb00f7679a16451d302c436b5cbf2505f0ea8146ef59e/cffi-2.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:737fe7d37e1a1bffe70bd5754ea763a62a066dc5913ca57e957824b72a85e205", size = 222828, upload-time = "2025-09-08T23:23:26.143Z" }, + { url = "https://files.pythonhosted.org/packages/c6/0f/cafacebd4b040e3119dcb32fed8bdef8dfe94da653155f9d0b9dc660166e/cffi-2.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:38100abb9d1b1435bc4cc340bb4489635dc2f0da7456590877030c9b3d40b0c1", size = 220926, upload-time = "2025-09-08T23:23:27.873Z" }, + { url = "https://files.pythonhosted.org/packages/3e/aa/df335faa45b395396fcbc03de2dfcab242cd61a9900e914fe682a59170b1/cffi-2.0.0-cp314-cp314-win32.whl", hash = "sha256:087067fa8953339c723661eda6b54bc98c5625757ea62e95eb4898ad5e776e9f", size = 175328, upload-time = "2025-09-08T23:23:44.61Z" }, + { url = "https://files.pythonhosted.org/packages/bb/92/882c2d30831744296ce713f0feb4c1cd30f346ef747b530b5318715cc367/cffi-2.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:203a48d1fb583fc7d78a4c6655692963b860a417c0528492a6bc21f1aaefab25", size = 185650, upload-time = "2025-09-08T23:23:45.848Z" }, + { url = "https://files.pythonhosted.org/packages/9f/2c/98ece204b9d35a7366b5b2c6539c350313ca13932143e79dc133ba757104/cffi-2.0.0-cp314-cp314-win_arm64.whl", hash = "sha256:dbd5c7a25a7cb98f5ca55d258b103a2054f859a46ae11aaf23134f9cc0d356ad", size = 180687, upload-time = "2025-09-08T23:23:47.105Z" }, + { url = "https://files.pythonhosted.org/packages/3e/61/c768e4d548bfa607abcda77423448df8c471f25dbe64fb2ef6d555eae006/cffi-2.0.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:9a67fc9e8eb39039280526379fb3a70023d77caec1852002b4da7e8b270c4dd9", size = 188773, upload-time = "2025-09-08T23:23:29.347Z" }, + { url = "https://files.pythonhosted.org/packages/2c/ea/5f76bce7cf6fcd0ab1a1058b5af899bfbef198bea4d5686da88471ea0336/cffi-2.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7a66c7204d8869299919db4d5069a82f1561581af12b11b3c9f48c584eb8743d", size = 185013, upload-time = "2025-09-08T23:23:30.63Z" }, + { url = "https://files.pythonhosted.org/packages/be/b4/c56878d0d1755cf9caa54ba71e5d049479c52f9e4afc230f06822162ab2f/cffi-2.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:7cc09976e8b56f8cebd752f7113ad07752461f48a58cbba644139015ac24954c", size = 221593, upload-time = "2025-09-08T23:23:31.91Z" }, + { url = "https://files.pythonhosted.org/packages/e0/0d/eb704606dfe8033e7128df5e90fee946bbcb64a04fcdaa97321309004000/cffi-2.0.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:92b68146a71df78564e4ef48af17551a5ddd142e5190cdf2c5624d0c3ff5b2e8", size = 209354, upload-time = "2025-09-08T23:23:33.214Z" }, + { url = "https://files.pythonhosted.org/packages/d8/19/3c435d727b368ca475fb8742ab97c9cb13a0de600ce86f62eab7fa3eea60/cffi-2.0.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b1e74d11748e7e98e2f426ab176d4ed720a64412b6a15054378afdb71e0f37dc", size = 208480, upload-time = "2025-09-08T23:23:34.495Z" }, + { url = "https://files.pythonhosted.org/packages/d0/44/681604464ed9541673e486521497406fadcc15b5217c3e326b061696899a/cffi-2.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:28a3a209b96630bca57cce802da70c266eb08c6e97e5afd61a75611ee6c64592", size = 221584, upload-time = "2025-09-08T23:23:36.096Z" }, + { url = "https://files.pythonhosted.org/packages/25/8e/342a504ff018a2825d395d44d63a767dd8ebc927ebda557fecdaca3ac33a/cffi-2.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7553fb2090d71822f02c629afe6042c299edf91ba1bf94951165613553984512", size = 224443, upload-time = "2025-09-08T23:23:37.328Z" }, + { url = "https://files.pythonhosted.org/packages/e1/5e/b666bacbbc60fbf415ba9988324a132c9a7a0448a9a8f125074671c0f2c3/cffi-2.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:6c6c373cfc5c83a975506110d17457138c8c63016b563cc9ed6e056a82f13ce4", size = 223437, upload-time = "2025-09-08T23:23:38.945Z" }, + { url = "https://files.pythonhosted.org/packages/a0/1d/ec1a60bd1a10daa292d3cd6bb0b359a81607154fb8165f3ec95fe003b85c/cffi-2.0.0-cp314-cp314t-win32.whl", hash = "sha256:1fc9ea04857caf665289b7a75923f2c6ed559b8298a1b8c49e59f7dd95c8481e", size = 180487, upload-time = "2025-09-08T23:23:40.423Z" }, + { url = "https://files.pythonhosted.org/packages/bf/41/4c1168c74fac325c0c8156f04b6749c8b6a8f405bbf91413ba088359f60d/cffi-2.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:d68b6cef7827e8641e8ef16f4494edda8b36104d79773a334beaa1e3521430f6", size = 191726, upload-time = "2025-09-08T23:23:41.742Z" }, + { url = "https://files.pythonhosted.org/packages/ae/3a/dbeec9d1ee0844c679f6bb5d6ad4e9f198b1224f4e7a32825f47f6192b0c/cffi-2.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0a1527a803f0a659de1af2e1fd700213caba79377e27e4693648c2923da066f9", size = 184195, upload-time = "2025-09-08T23:23:43.004Z" }, +] + +[[package]] +name = "cfn-lint" +version = "1.51.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aws-sam-translator" }, + { name = "jsonpatch" }, + { name = "networkx" }, + { name = "pyyaml" }, + { name = "regex" }, + { name = "sympy" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5e/ea/bc4954dcbff3ecb500e2593e4b64d0e9a552973249b2a27dd22eee3fb5b0/cfn_lint-1.51.0.tar.gz", hash = "sha256:05d2a59708c99363afe3af6ac7325de95a5b37f8eef7728f41ae567d088a61f1", size = 4088652, upload-time = "2026-05-12T20:34:25.712Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/48/12/016d6b4a43bb7eb2e430770e04325ef159d73d4183dce94c6fa6dc144902/cfn_lint-1.51.0-py3-none-any.whl", hash = "sha256:116d4f9c7c7d039e69c01c31fe9ff309ff79f0884c859ea92b353507903dd89e", size = 6065464, upload-time = "2026-05-12T20:34:22.885Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.4.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e7/a1/67fe25fac3c7642725500a3f6cfe5821ad557c3abb11c9d20d12c7008d3e/charset_normalizer-3.4.7.tar.gz", hash = "sha256:ae89db9e5f98a11a4bf50407d4363e7b09b31e55bc117b4f7d80aab97ba009e5", size = 144271, upload-time = "2026-04-02T09:28:39.342Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/eb/4fc8d0a7110eb5fc9cc161723a34a8a6c200ce3b4fbf681bc86feee22308/charset_normalizer-3.4.7-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:eca9705049ad3c7345d574e3510665cb2cf844c2f2dcfe675332677f081cbd46", size = 311328, upload-time = "2026-04-02T09:26:24.331Z" }, + { url = "https://files.pythonhosted.org/packages/f8/e3/0fadc706008ac9d7b9b5be6dc767c05f9d3e5df51744ce4cc9605de7b9f4/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6178f72c5508bfc5fd446a5905e698c6212932f25bcdd4b47a757a50605a90e2", size = 208061, upload-time = "2026-04-02T09:26:25.568Z" }, + { url = "https://files.pythonhosted.org/packages/42/f0/3dd1045c47f4a4604df85ec18ad093912ae1344ac706993aff91d38773a2/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e1421b502d83040e6d7fb2fb18dff63957f720da3d77b2fbd3187ceb63755d7b", size = 229031, upload-time = "2026-04-02T09:26:26.865Z" }, + { url = "https://files.pythonhosted.org/packages/dc/67/675a46eb016118a2fbde5a277a5d15f4f69d5f3f5f338e5ee2f8948fcf43/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:edac0f1ab77644605be2cbba52e6b7f630731fc42b34cb0f634be1a6eface56a", size = 225239, upload-time = "2026-04-02T09:26:28.044Z" }, + { url = "https://files.pythonhosted.org/packages/4b/f8/d0118a2f5f23b02cd166fa385c60f9b0d4f9194f574e2b31cef350ad7223/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5649fd1c7bade02f320a462fdefd0b4bd3ce036065836d4f42e0de958038e116", size = 216589, upload-time = "2026-04-02T09:26:29.239Z" }, + { url = "https://files.pythonhosted.org/packages/b1/f1/6d2b0b261b6c4ceef0fcb0d17a01cc5bc53586c2d4796fa04b5c540bc13d/charset_normalizer-3.4.7-cp312-cp312-manylinux_2_31_armv7l.whl", hash = "sha256:203104ed3e428044fd943bc4bf45fa73c0730391f9621e37fe39ecf477b128cb", size = 202733, upload-time = "2026-04-02T09:26:30.5Z" }, + { url = "https://files.pythonhosted.org/packages/6f/c0/7b1f943f7e87cc3db9626ba17807d042c38645f0a1d4415c7a14afb5591f/charset_normalizer-3.4.7-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:298930cec56029e05497a76988377cbd7457ba864beeea92ad7e844fe74cd1f1", size = 212652, upload-time = "2026-04-02T09:26:31.709Z" }, + { url = "https://files.pythonhosted.org/packages/38/dd/5a9ab159fe45c6e72079398f277b7d2b523e7f716acc489726115a910097/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:708838739abf24b2ceb208d0e22403dd018faeef86ddac04319a62ae884c4f15", size = 211229, upload-time = "2026-04-02T09:26:33.282Z" }, + { url = "https://files.pythonhosted.org/packages/d5/ff/531a1cad5ca855d1c1a8b69cb71abfd6d85c0291580146fda7c82857caa1/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:0f7eb884681e3938906ed0434f20c63046eacd0111c4ba96f27b76084cd679f5", size = 203552, upload-time = "2026-04-02T09:26:34.845Z" }, + { url = "https://files.pythonhosted.org/packages/c1/4c/a5fb52d528a8ca41f7598cb619409ece30a169fbdf9cdce592e53b46c3a6/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:4dc1e73c36828f982bfe79fadf5919923f8a6f4df2860804db9a98c48824ce8d", size = 230806, upload-time = "2026-04-02T09:26:36.152Z" }, + { url = "https://files.pythonhosted.org/packages/59/7a/071feed8124111a32b316b33ae4de83d36923039ef8cf48120266844285b/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:aed52fea0513bac0ccde438c188c8a471c4e0f457c2dd20cdbf6ea7a450046c7", size = 212316, upload-time = "2026-04-02T09:26:37.672Z" }, + { url = "https://files.pythonhosted.org/packages/fd/35/f7dba3994312d7ba508e041eaac39a36b120f32d4c8662b8814dab876431/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:fea24543955a6a729c45a73fe90e08c743f0b3334bbf3201e6c4bc1b0c7fa464", size = 227274, upload-time = "2026-04-02T09:26:38.93Z" }, + { url = "https://files.pythonhosted.org/packages/8a/2d/a572df5c9204ab7688ec1edc895a73ebded3b023bb07364710b05dd1c9be/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:bb6d88045545b26da47aa879dd4a89a71d1dce0f0e549b1abcb31dfe4a8eac49", size = 218468, upload-time = "2026-04-02T09:26:40.17Z" }, + { url = "https://files.pythonhosted.org/packages/86/eb/890922a8b03a568ca2f336c36585a4713c55d4d67bf0f0c78924be6315ca/charset_normalizer-3.4.7-cp312-cp312-win32.whl", hash = "sha256:2257141f39fe65a3fdf38aeccae4b953e5f3b3324f4ff0daf9f15b8518666a2c", size = 148460, upload-time = "2026-04-02T09:26:41.416Z" }, + { url = "https://files.pythonhosted.org/packages/35/d9/0e7dffa06c5ab081f75b1b786f0aefc88365825dfcd0ac544bdb7b2b6853/charset_normalizer-3.4.7-cp312-cp312-win_amd64.whl", hash = "sha256:5ed6ab538499c8644b8a3e18debabcd7ce684f3fa91cf867521a7a0279cab2d6", size = 159330, upload-time = "2026-04-02T09:26:42.554Z" }, + { url = "https://files.pythonhosted.org/packages/9e/5d/481bcc2a7c88ea6b0878c299547843b2521ccbc40980cb406267088bc701/charset_normalizer-3.4.7-cp312-cp312-win_arm64.whl", hash = "sha256:56be790f86bfb2c98fb742ce566dfb4816e5a83384616ab59c49e0604d49c51d", size = 147828, upload-time = "2026-04-02T09:26:44.075Z" }, + { url = "https://files.pythonhosted.org/packages/c1/3b/66777e39d3ae1ddc77ee606be4ec6d8cbd4c801f65e5a1b6f2b11b8346dd/charset_normalizer-3.4.7-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:f496c9c3cc02230093d8330875c4c3cdfc3b73612a5fd921c65d39cbcef08063", size = 309627, upload-time = "2026-04-02T09:26:45.198Z" }, + { url = "https://files.pythonhosted.org/packages/2e/4e/b7f84e617b4854ade48a1b7915c8ccfadeba444d2a18c291f696e37f0d3b/charset_normalizer-3.4.7-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0ea948db76d31190bf08bd371623927ee1339d5f2a0b4b1b4a4439a65298703c", size = 207008, upload-time = "2026-04-02T09:26:46.824Z" }, + { url = "https://files.pythonhosted.org/packages/c4/bb/ec73c0257c9e11b268f018f068f5d00aa0ef8c8b09f7753ebd5f2880e248/charset_normalizer-3.4.7-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a277ab8928b9f299723bc1a2dabb1265911b1a76341f90a510368ca44ad9ab66", size = 228303, upload-time = "2026-04-02T09:26:48.397Z" }, + { url = "https://files.pythonhosted.org/packages/85/fb/32d1f5033484494619f701e719429c69b766bfc4dbc61aa9e9c8c166528b/charset_normalizer-3.4.7-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:3bec022aec2c514d9cf199522a802bd007cd588ab17ab2525f20f9c34d067c18", size = 224282, upload-time = "2026-04-02T09:26:49.684Z" }, + { url = "https://files.pythonhosted.org/packages/fa/07/330e3a0dda4c404d6da83b327270906e9654a24f6c546dc886a0eb0ffb23/charset_normalizer-3.4.7-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e044c39e41b92c845bc815e5ae4230804e8e7bc29e399b0437d64222d92809dd", size = 215595, upload-time = "2026-04-02T09:26:50.915Z" }, + { url = "https://files.pythonhosted.org/packages/e3/7c/fc890655786e423f02556e0216d4b8c6bcb6bdfa890160dc66bf52dee468/charset_normalizer-3.4.7-cp313-cp313-manylinux_2_31_armv7l.whl", hash = "sha256:f495a1652cf3fbab2eb0639776dad966c2fb874d79d87ca07f9d5f059b8bd215", size = 201986, upload-time = "2026-04-02T09:26:52.197Z" }, + { url = "https://files.pythonhosted.org/packages/d8/97/bfb18b3db2aed3b90cf54dc292ad79fdd5ad65c4eae454099475cbeadd0d/charset_normalizer-3.4.7-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e712b419df8ba5e42b226c510472b37bd57b38e897d3eca5e8cfd410a29fa859", size = 211711, upload-time = "2026-04-02T09:26:53.49Z" }, + { url = "https://files.pythonhosted.org/packages/6f/a5/a581c13798546a7fd557c82614a5c65a13df2157e9ad6373166d2a3e645d/charset_normalizer-3.4.7-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:7804338df6fcc08105c7745f1502ba68d900f45fd770d5bdd5288ddccb8a42d8", size = 210036, upload-time = "2026-04-02T09:26:54.975Z" }, + { url = "https://files.pythonhosted.org/packages/8c/bf/b3ab5bcb478e4193d517644b0fb2bf5497fbceeaa7a1bc0f4d5b50953861/charset_normalizer-3.4.7-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:481551899c856c704d58119b5025793fa6730adda3571971af568f66d2424bb5", size = 202998, upload-time = "2026-04-02T09:26:56.303Z" }, + { url = "https://files.pythonhosted.org/packages/e7/4e/23efd79b65d314fa320ec6017b4b5834d5c12a58ba4610aa353af2e2f577/charset_normalizer-3.4.7-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:f59099f9b66f0d7145115e6f80dd8b1d847176df89b234a5a6b3f00437aa0832", size = 230056, upload-time = "2026-04-02T09:26:57.554Z" }, + { url = "https://files.pythonhosted.org/packages/b9/9f/1e1941bc3f0e01df116e68dc37a55c4d249df5e6fa77f008841aef68264f/charset_normalizer-3.4.7-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:f59ad4c0e8f6bba240a9bb85504faa1ab438237199d4cce5f622761507b8f6a6", size = 211537, upload-time = "2026-04-02T09:26:58.843Z" }, + { url = "https://files.pythonhosted.org/packages/80/0f/088cbb3020d44428964a6c97fe1edfb1b9550396bf6d278330281e8b709c/charset_normalizer-3.4.7-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:3dedcc22d73ec993f42055eff4fcfed9318d1eeb9a6606c55892a26964964e48", size = 226176, upload-time = "2026-04-02T09:27:00.437Z" }, + { url = "https://files.pythonhosted.org/packages/6a/9f/130394f9bbe06f4f63e22641d32fc9b202b7e251c9aef4db044324dac493/charset_normalizer-3.4.7-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:64f02c6841d7d83f832cd97ccf8eb8a906d06eb95d5276069175c696b024b60a", size = 217723, upload-time = "2026-04-02T09:27:02.021Z" }, + { url = "https://files.pythonhosted.org/packages/73/55/c469897448a06e49f8fa03f6caae97074fde823f432a98f979cc42b90e69/charset_normalizer-3.4.7-cp313-cp313-win32.whl", hash = "sha256:4042d5c8f957e15221d423ba781e85d553722fc4113f523f2feb7b188cc34c5e", size = 148085, upload-time = "2026-04-02T09:27:03.192Z" }, + { url = "https://files.pythonhosted.org/packages/5d/78/1b74c5bbb3f99b77a1715c91b3e0b5bdb6fe302d95ace4f5b1bec37b0167/charset_normalizer-3.4.7-cp313-cp313-win_amd64.whl", hash = "sha256:3946fa46a0cf3e4c8cb1cc52f56bb536310d34f25f01ca9b6c16afa767dab110", size = 158819, upload-time = "2026-04-02T09:27:04.454Z" }, + { url = "https://files.pythonhosted.org/packages/68/86/46bd42279d323deb8687c4a5a811fd548cb7d1de10cf6535d099877a9a9f/charset_normalizer-3.4.7-cp313-cp313-win_arm64.whl", hash = "sha256:80d04837f55fc81da168b98de4f4b797ef007fc8a79ab71c6ec9bc4dd662b15b", size = 147915, upload-time = "2026-04-02T09:27:05.971Z" }, + { url = "https://files.pythonhosted.org/packages/97/c8/c67cb8c70e19ef1960b97b22ed2a1567711de46c4ddf19799923adc836c2/charset_normalizer-3.4.7-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:c36c333c39be2dbca264d7803333c896ab8fa7d4d6f0ab7edb7dfd7aea6e98c0", size = 309234, upload-time = "2026-04-02T09:27:07.194Z" }, + { url = "https://files.pythonhosted.org/packages/99/85/c091fdee33f20de70d6c8b522743b6f831a2f1cd3ff86de4c6a827c48a76/charset_normalizer-3.4.7-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1c2aed2e5e41f24ea8ef1590b8e848a79b56f3a5564a65ceec43c9d692dc7d8a", size = 208042, upload-time = "2026-04-02T09:27:08.749Z" }, + { url = "https://files.pythonhosted.org/packages/87/1c/ab2ce611b984d2fd5d86a5a8a19c1ae26acac6bad967da4967562c75114d/charset_normalizer-3.4.7-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:54523e136b8948060c0fa0bc7b1b50c32c186f2fceee897a495406bb6e311d2b", size = 228706, upload-time = "2026-04-02T09:27:09.951Z" }, + { url = "https://files.pythonhosted.org/packages/a8/29/2b1d2cb00bf085f59d29eb773ce58ec2d325430f8c216804a0a5cd83cbca/charset_normalizer-3.4.7-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:715479b9a2802ecac752a3b0efa2b0b60285cf962ee38414211abdfccc233b41", size = 224727, upload-time = "2026-04-02T09:27:11.175Z" }, + { url = "https://files.pythonhosted.org/packages/47/5c/032c2d5a07fe4d4855fea851209cca2b6f03ebeb6d4e3afdb3358386a684/charset_normalizer-3.4.7-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bd6c2a1c7573c64738d716488d2cdd3c00e340e4835707d8fdb8dc1a66ef164e", size = 215882, upload-time = "2026-04-02T09:27:12.446Z" }, + { url = "https://files.pythonhosted.org/packages/2c/c2/356065d5a8b78ed04499cae5f339f091946a6a74f91e03476c33f0ab7100/charset_normalizer-3.4.7-cp314-cp314-manylinux_2_31_armv7l.whl", hash = "sha256:c45e9440fb78f8ddabcf714b68f936737a121355bf59f3907f4e17721b9d1aae", size = 200860, upload-time = "2026-04-02T09:27:13.721Z" }, + { url = "https://files.pythonhosted.org/packages/0c/cd/a32a84217ced5039f53b29f460962abb2d4420def55afabe45b1c3c7483d/charset_normalizer-3.4.7-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:3534e7dcbdcf757da6b85a0bbf5b6868786d5982dd959b065e65481644817a18", size = 211564, upload-time = "2026-04-02T09:27:15.272Z" }, + { url = "https://files.pythonhosted.org/packages/44/86/58e6f13ce26cc3b8f4a36b94a0f22ae2f00a72534520f4ae6857c4b81f89/charset_normalizer-3.4.7-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e8ac484bf18ce6975760921bb6148041faa8fef0547200386ea0b52b5d27bf7b", size = 211276, upload-time = "2026-04-02T09:27:16.834Z" }, + { url = "https://files.pythonhosted.org/packages/8f/fe/d17c32dc72e17e155e06883efa84514ca375f8a528ba2546bee73fc4df81/charset_normalizer-3.4.7-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:a5fe03b42827c13cdccd08e6c0247b6a6d4b5e3cdc53fd1749f5896adcdc2356", size = 201238, upload-time = "2026-04-02T09:27:18.229Z" }, + { url = "https://files.pythonhosted.org/packages/6a/29/f33daa50b06525a237451cdb6c69da366c381a3dadcd833fa5676bc468b3/charset_normalizer-3.4.7-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:2d6eb928e13016cea4f1f21d1e10c1cebd5a421bc57ddf5b1142ae3f86824fab", size = 230189, upload-time = "2026-04-02T09:27:19.445Z" }, + { url = "https://files.pythonhosted.org/packages/b6/6e/52c84015394a6a0bdcd435210a7e944c5f94ea1055f5cc5d56c5fe368e7b/charset_normalizer-3.4.7-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:e74327fb75de8986940def6e8dee4f127cc9752bee7355bb323cc5b2659b6d46", size = 211352, upload-time = "2026-04-02T09:27:20.79Z" }, + { url = "https://files.pythonhosted.org/packages/8c/d7/4353be581b373033fb9198bf1da3cf8f09c1082561e8e922aa7b39bf9fe8/charset_normalizer-3.4.7-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:d6038d37043bced98a66e68d3aa2b6a35505dc01328cd65217cefe82f25def44", size = 227024, upload-time = "2026-04-02T09:27:22.063Z" }, + { url = "https://files.pythonhosted.org/packages/30/45/99d18aa925bd1740098ccd3060e238e21115fffbfdcb8f3ece837d0ace6c/charset_normalizer-3.4.7-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:7579e913a5339fb8fa133f6bbcfd8e6749696206cf05acdbdca71a1b436d8e72", size = 217869, upload-time = "2026-04-02T09:27:23.486Z" }, + { url = "https://files.pythonhosted.org/packages/5c/05/5ee478aa53f4bb7996482153d4bfe1b89e0f087f0ab6b294fcf92d595873/charset_normalizer-3.4.7-cp314-cp314-win32.whl", hash = "sha256:5b77459df20e08151cd6f8b9ef8ef1f961ef73d85c21a555c7eed5b79410ec10", size = 148541, upload-time = "2026-04-02T09:27:25.146Z" }, + { url = "https://files.pythonhosted.org/packages/48/77/72dcb0921b2ce86420b2d79d454c7022bf5be40202a2a07906b9f2a35c97/charset_normalizer-3.4.7-cp314-cp314-win_amd64.whl", hash = "sha256:92a0a01ead5e668468e952e4238cccd7c537364eb7d851ab144ab6627dbbe12f", size = 159634, upload-time = "2026-04-02T09:27:26.642Z" }, + { url = "https://files.pythonhosted.org/packages/c6/a3/c2369911cd72f02386e4e340770f6e158c7980267da16af8f668217abaa0/charset_normalizer-3.4.7-cp314-cp314-win_arm64.whl", hash = "sha256:67f6279d125ca0046a7fd386d01b311c6363844deac3e5b069b514ba3e63c246", size = 148384, upload-time = "2026-04-02T09:27:28.271Z" }, + { url = "https://files.pythonhosted.org/packages/94/09/7e8a7f73d24dba1f0035fbbf014d2c36828fc1bf9c88f84093e57d315935/charset_normalizer-3.4.7-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:effc3f449787117233702311a1b7d8f59cba9ced946ba727bdc329ec69028e24", size = 330133, upload-time = "2026-04-02T09:27:29.474Z" }, + { url = "https://files.pythonhosted.org/packages/8d/da/96975ddb11f8e977f706f45cddd8540fd8242f71ecdb5d18a80723dcf62c/charset_normalizer-3.4.7-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fbccdc05410c9ee21bbf16a35f4c1d16123dcdeb8a1d38f33654fa21d0234f79", size = 216257, upload-time = "2026-04-02T09:27:30.793Z" }, + { url = "https://files.pythonhosted.org/packages/e5/e8/1d63bf8ef2d388e95c64b2098f45f84758f6d102a087552da1485912637b/charset_normalizer-3.4.7-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:733784b6d6def852c814bce5f318d25da2ee65dd4839a0718641c696e09a2960", size = 234851, upload-time = "2026-04-02T09:27:32.44Z" }, + { url = "https://files.pythonhosted.org/packages/9b/40/e5ff04233e70da2681fa43969ad6f66ca5611d7e669be0246c4c7aaf6dc8/charset_normalizer-3.4.7-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a89c23ef8d2c6b27fd200a42aa4ac72786e7c60d40efdc76e6011260b6e949c4", size = 233393, upload-time = "2026-04-02T09:27:34.03Z" }, + { url = "https://files.pythonhosted.org/packages/be/c1/06c6c49d5a5450f76899992f1ee40b41d076aee9279b49cf9974d2f313d5/charset_normalizer-3.4.7-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6c114670c45346afedc0d947faf3c7f701051d2518b943679c8ff88befe14f8e", size = 223251, upload-time = "2026-04-02T09:27:35.369Z" }, + { url = "https://files.pythonhosted.org/packages/2b/9f/f2ff16fb050946169e3e1f82134d107e5d4ae72647ec8a1b1446c148480f/charset_normalizer-3.4.7-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:a180c5e59792af262bf263b21a3c49353f25945d8d9f70628e73de370d55e1e1", size = 206609, upload-time = "2026-04-02T09:27:36.661Z" }, + { url = "https://files.pythonhosted.org/packages/69/d5/a527c0cd8d64d2eab7459784fb4169a0ac76e5a6fc5237337982fd61347e/charset_normalizer-3.4.7-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:3c9a494bc5ec77d43cea229c4f6db1e4d8fe7e1bbffa8b6f0f0032430ff8ab44", size = 220014, upload-time = "2026-04-02T09:27:38.019Z" }, + { url = "https://files.pythonhosted.org/packages/7e/80/8a7b8104a3e203074dc9aa2c613d4b726c0e136bad1cc734594b02867972/charset_normalizer-3.4.7-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8d828b6667a32a728a1ad1d93957cdf37489c57b97ae6c4de2860fa749b8fc1e", size = 218979, upload-time = "2026-04-02T09:27:39.37Z" }, + { url = "https://files.pythonhosted.org/packages/02/9a/b759b503d507f375b2b5c153e4d2ee0a75aa215b7f2489cf314f4541f2c0/charset_normalizer-3.4.7-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:cf1493cd8607bec4d8a7b9b004e699fcf8f9103a9284cc94962cb73d20f9d4a3", size = 209238, upload-time = "2026-04-02T09:27:40.722Z" }, + { url = "https://files.pythonhosted.org/packages/c2/4e/0f3f5d47b86bdb79256e7290b26ac847a2832d9a4033f7eb2cd4bcf4bb5b/charset_normalizer-3.4.7-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:0c96c3b819b5c3e9e165495db84d41914d6894d55181d2d108cc1a69bfc9cce0", size = 236110, upload-time = "2026-04-02T09:27:42.33Z" }, + { url = "https://files.pythonhosted.org/packages/96/23/bce28734eb3ed2c91dcf93abeb8a5cf393a7b2749725030bb630e554fdd8/charset_normalizer-3.4.7-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:752a45dc4a6934060b3b0dab47e04edc3326575f82be64bc4fc293914566503e", size = 219824, upload-time = "2026-04-02T09:27:43.924Z" }, + { url = "https://files.pythonhosted.org/packages/2c/6f/6e897c6984cc4d41af319b077f2f600fc8214eb2fe2d6bcb79141b882400/charset_normalizer-3.4.7-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:8778f0c7a52e56f75d12dae53ae320fae900a8b9b4164b981b9c5ce059cd1fcb", size = 233103, upload-time = "2026-04-02T09:27:45.348Z" }, + { url = "https://files.pythonhosted.org/packages/76/22/ef7bd0fe480a0ae9b656189ec00744b60933f68b4f42a7bb06589f6f576a/charset_normalizer-3.4.7-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ce3412fbe1e31eb81ea42f4169ed94861c56e643189e1e75f0041f3fe7020abe", size = 225194, upload-time = "2026-04-02T09:27:46.706Z" }, + { url = "https://files.pythonhosted.org/packages/c5/a7/0e0ab3e0b5bc1219bd80a6a0d4d72ca74d9250cb2382b7c699c147e06017/charset_normalizer-3.4.7-cp314-cp314t-win32.whl", hash = "sha256:c03a41a8784091e67a39648f70c5f97b5b6a37f216896d44d2cdcb82615339a0", size = 159827, upload-time = "2026-04-02T09:27:48.053Z" }, + { url = "https://files.pythonhosted.org/packages/7a/1d/29d32e0fb40864b1f878c7f5a0b343ae676c6e2b271a2d55cc3a152391da/charset_normalizer-3.4.7-cp314-cp314t-win_amd64.whl", hash = "sha256:03853ed82eeebbce3c2abfdbc98c96dc205f32a79627688ac9a27370ea61a49c", size = 174168, upload-time = "2026-04-02T09:27:49.795Z" }, + { url = "https://files.pythonhosted.org/packages/de/32/d92444ad05c7a6e41fb2036749777c163baf7a0301a040cb672d6b2b1ae9/charset_normalizer-3.4.7-cp314-cp314t-win_arm64.whl", hash = "sha256:c35abb8bfff0185efac5878da64c45dafd2b37fb0383add1be155a763c1f083d", size = 153018, upload-time = "2026-04-02T09:27:51.116Z" }, + { url = "https://files.pythonhosted.org/packages/db/8f/61959034484a4a7c527811f4721e75d02d653a35afb0b6054474d8185d4c/charset_normalizer-3.4.7-py3-none-any.whl", hash = "sha256:3dce51d0f5e7951f8bb4900c257dad282f49190fdbebecd4ba99bcc41fef404d", size = 61958, upload-time = "2026-04-02T09:28:37.794Z" }, +] + +[[package]] +name = "click" +version = "8.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bb/63/f9e1ea081ce35720d8b92acde70daaedace594dc93b693c869e0d5910718/click-8.3.3.tar.gz", hash = "sha256:398329ad4837b2ff7cbe1dd166a4c0f8900c3ca3a218de04466f38f6497f18a2", size = 328061, upload-time = "2026-04-22T15:11:27.506Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ae/44/c1221527f6a71a01ec6fbad7fa78f1d50dfa02217385cf0fa3eec7087d59/click-8.3.3-py3-none-any.whl", hash = "sha256:a2bf429bb3033c89fa4936ffb35d5cb471e3719e1f3c8a7c3fff0b8314305613", size = 110502, upload-time = "2026-04-22T15:11:25.044Z" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "coverage" +version = "7.15.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/be/c3/4f2195f512fb172aa425a8803a874b2baa9ba7f80ff7b6080998761fc701/coverage-7.15.4.tar.gz", hash = "sha256:0548198fff07ccf4faf469520bce1c2eceb1ce3e62891921138dec10907f9d00", size = 936952, upload-time = "2026-08-06T13:50:24.442Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1d/48/bc8d4ba7b37551a767bd863f15b3f80182b271c2f55975356f5f7dbe94c2/coverage-7.15.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d4fedd1f7f428f9fe83b1ead5e7cc87a43427be31aadafbac3ac0636dc7abb22", size = 222543, upload-time = "2026-08-06T13:47:37.562Z" }, + { url = "https://files.pythonhosted.org/packages/20/dd/88d6f83f1fffc974a3691a34a97951c5b12df7512a6782c5963883cbc058/coverage-7.15.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:37e2f0cdf58e2e1fed4e4d5a8f8786ae2f7eb80b478016876667dc4a01d60a97", size = 222905, upload-time = "2026-08-06T13:47:38.927Z" }, + { url = "https://files.pythonhosted.org/packages/bd/5c/54ee0d4748585bb0acab9891cd8d92f2d3593165b4e59fc9de113bfb3140/coverage-7.15.4-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:fb55d0e70bb15f2e81477613627286581414693d74ac7963c93a790dd453ca9d", size = 254407, upload-time = "2026-08-06T13:47:40.488Z" }, + { url = "https://files.pythonhosted.org/packages/8c/3f/f0642a372f494bd0d7dad3b497083b910194a5f1c88be2c94fef707c3b59/coverage-7.15.4-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:899b9da30f3c6c336566e3707495bb23e8302d39d862f01fa78c48b99b9437e2", size = 257145, upload-time = "2026-08-06T13:47:41.931Z" }, + { url = "https://files.pythonhosted.org/packages/71/17/8b46d0ed68251016002ec972c8fc0119961a765d0984cafb8bf317c43758/coverage-7.15.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d15715e8c46552827e5e4f30a35575a2dbcad14454cf3284c54483946bd16931", size = 258257, upload-time = "2026-08-06T13:47:43.527Z" }, + { url = "https://files.pythonhosted.org/packages/30/b8/8498a0e72d0adbe15477dd07463d2b3bb2c9f6a4815e8589e50939e2c3ae/coverage-7.15.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:002a438859f7b430bc99afeaf01a6d187dad1d0dc907b64cdeffc632a5db8fd8", size = 260517, upload-time = "2026-08-06T13:47:45.121Z" }, + { url = "https://files.pythonhosted.org/packages/41/e1/7dce19c3bdb1e3dd63e769508216500edad81bd5f69a26d724e32aceaf78/coverage-7.15.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e4193a04b518f7968f3099755f5509ee7cccc6dc2b92a6b14841934d22e222c9", size = 254785, upload-time = "2026-08-06T13:47:46.541Z" }, + { url = "https://files.pythonhosted.org/packages/dd/b1/e1494703c675a2561723cd9b89f45c9168782c31280c611b1f767851e57c/coverage-7.15.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e98dcc55d572b38e69d117da7e8e8efb8500f1f5eaf81ecd460a63220790b839", size = 256176, upload-time = "2026-08-06T13:47:48.155Z" }, + { url = "https://files.pythonhosted.org/packages/73/76/a5629d270fb638a43a4b10466f51e2f49d532c1aa4da2913cbbb150bbe0a/coverage-7.15.4-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:af6c538498ce66c10d3fd541c2a8d5b03da5850355add34e6cba564210cb9e72", size = 254321, upload-time = "2026-08-06T13:47:49.757Z" }, + { url = "https://files.pythonhosted.org/packages/ff/4f/9c44447218435d5766b911534f9d798144a5560f85e9a54ebe5f3f5d19f9/coverage-7.15.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1d10025d96ea89fc2f73714dbc4cbd433fe012c1ac9e23f895d7728b238b6e52", size = 258390, upload-time = "2026-08-06T13:47:51.248Z" }, + { url = "https://files.pythonhosted.org/packages/de/36/c1e127616fb3fa18a9ff71e76c417f2fd7424332a4870015ac224ef4c039/coverage-7.15.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:d802e1947603162ded419bff83ac7489820355d2b856dfb09206574e3a37ac0c", size = 253894, upload-time = "2026-08-06T13:47:52.816Z" }, + { url = "https://files.pythonhosted.org/packages/e9/b9/fdb92c8ae7a8bb9b850cc253b7b3b9c8526f68130002048b5671cd510d09/coverage-7.15.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c2de40895718f91951b86712b4c5b694acaf9a0a49be13874896f599a1eed3f4", size = 255763, upload-time = "2026-08-06T13:47:54.296Z" }, + { url = "https://files.pythonhosted.org/packages/6f/c0/a7d51b2587c7bdb76e71b0896d2565bf7d60436b5122fc83e511adb1f7cd/coverage-7.15.4-cp312-cp312-win32.whl", hash = "sha256:5c3431b2161279b7db5c2a1aa58ae02e5cb8c3c42d93a5094be3f5537bd5b11b", size = 224597, upload-time = "2026-08-06T13:47:56.074Z" }, + { url = "https://files.pythonhosted.org/packages/49/b9/5c5f80cc55f5acaaca6dee677626bfcec8c87204a7809b438b08e84f4571/coverage-7.15.4-cp312-cp312-win_amd64.whl", hash = "sha256:6befeab5fb2b51c958ca4ac6c5d141a1e8240f4f76e46350f1911963deda49cd", size = 225135, upload-time = "2026-08-06T13:47:57.52Z" }, + { url = "https://files.pythonhosted.org/packages/47/e4/2a4561f89ff6bf7c925c287d0f2cce8bdf139c3a33735c87e3203401cf94/coverage-7.15.4-cp312-cp312-win_arm64.whl", hash = "sha256:67bc345491ab55b837277d76f5775d057e8c7f1ac44d890d8c2c82adde258c6f", size = 224515, upload-time = "2026-08-06T13:47:58.977Z" }, + { url = "https://files.pythonhosted.org/packages/f1/84/651a9310859673aaa3b3203f1aa1641ca60fcf2494683e1c9474c7172780/coverage-7.15.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:c705b28feb2775dc82a25f1d473a370bc37ff93f5177f4e29ce2425f560f6921", size = 222565, upload-time = "2026-08-06T13:48:00.796Z" }, + { url = "https://files.pythonhosted.org/packages/82/f9/4dcf700137e8af550670f4d74d1b63828ce93e1e2b05e5f10710eb2ea987/coverage-7.15.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:3ff205ab5e3ecc670f6a4dd19d9cbf12ede53dd41cfc1e15716ec961ea6d314e", size = 222936, upload-time = "2026-08-06T13:48:02.391Z" }, + { url = "https://files.pythonhosted.org/packages/07/4a/612ff1e780b3fbfd637486f542f84adc5503873d8b5d279dec1ffeef9414/coverage-7.15.4-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:5172326e861a38b48b48befca15e0f477a26b283337a33a739c8fed229934e36", size = 253926, upload-time = "2026-08-06T13:48:04.382Z" }, + { url = "https://files.pythonhosted.org/packages/b0/04/d1cff1c2ead4708a6a79c01d3736b6a25bd38a36678398f72a8dd33dfad9/coverage-7.15.4-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:12b59c90084e3234fb11184886bf4a40f4f16a8c8f867be2e087b81f8e8868d4", size = 256523, upload-time = "2026-08-06T13:48:05.996Z" }, + { url = "https://files.pythonhosted.org/packages/b9/80/d34e13fb4b293cbdb9665838cf5522077b8ad14ef947550631a4bced36a5/coverage-7.15.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:349062d66f00b40fa2c1c222438bad25fabf755631b5d82937fe985c8008615c", size = 257759, upload-time = "2026-08-06T13:48:08.036Z" }, + { url = "https://files.pythonhosted.org/packages/0f/e7/2c5fe7636fdb0732fe0f09f308a5b066864078b7fc61f6678e8478554f2e/coverage-7.15.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4256ced708e598e05209bc1a8ab4074e04a51dba4c62fb45926a229af675ace7", size = 259890, upload-time = "2026-08-06T13:48:09.834Z" }, + { url = "https://files.pythonhosted.org/packages/92/28/9689f0858dfff59c2ea688938ab9fa2925631235df67126a42b6c5c70ae1/coverage-7.15.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d80f974b20782d9612c8b4c9beeca867074c7cf4079d1419843fa25a26428b25", size = 254121, upload-time = "2026-08-06T13:48:11.459Z" }, + { url = "https://files.pythonhosted.org/packages/f9/e2/785077c230c157243eb5aa9a26c3be260ecd02001bead54a3cada3df8e03/coverage-7.15.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:2e179f19bfe1d31f8eeeaa12990194d761c4f62f0759661000bca6cd8729f40b", size = 255891, upload-time = "2026-08-06T13:48:13.209Z" }, + { url = "https://files.pythonhosted.org/packages/d4/90/e20371b17b40f912f21305c2db2f30efa3de306f7320fc916804872c85a4/coverage-7.15.4-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:8bc16bb47b7679670eceff71d78bfb7d6e5b143f6c2cd117487ec7c75e0d4b78", size = 253859, upload-time = "2026-08-06T13:48:14.736Z" }, + { url = "https://files.pythonhosted.org/packages/05/49/25371987ee459a5f67c0427fb75c74f9358e65f2c71fe75bf41c1b6c5fcb/coverage-7.15.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:1cd685005cd2c4200adfc14cf39a603b9320efab3f18a8f7f156d20c9cc3345f", size = 258011, upload-time = "2026-08-06T13:48:16.464Z" }, + { url = "https://files.pythonhosted.org/packages/30/6e/32e67467f6154bf4f1c4f63b05acc5097cba4237d45bbeeea446b52e8ac1/coverage-7.15.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:337399ad2c93b3acd2a937627dae8b3e86b66707cd3d3e856347999aadf1ef8d", size = 253676, upload-time = "2026-08-06T13:48:18.493Z" }, + { url = "https://files.pythonhosted.org/packages/03/c1/8b24192e89286399765155251f99ee9f070a9d637109018ac23d99b99f6f/coverage-7.15.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:96e257121228ec5cd2bb919276e94ac11074471bc37d68dbae0e8308cce15fff", size = 255453, upload-time = "2026-08-06T13:48:20.057Z" }, + { url = "https://files.pythonhosted.org/packages/16/6f/8b41ebdf67c87854e17c035336a90f1cfbad0c14c2a584301be6ff148718/coverage-7.15.4-cp313-cp313-win32.whl", hash = "sha256:c65a9e0dfc6143491879da4e13b5e30f8be192055de508d737fb14601edbd22c", size = 224605, upload-time = "2026-08-06T13:48:21.655Z" }, + { url = "https://files.pythonhosted.org/packages/e0/e2/2946c7f0b42b152ecb21ff1bdad72e3d301e790c0c487e4a86e8c9f69347/coverage-7.15.4-cp313-cp313-win_amd64.whl", hash = "sha256:2ff8f5e9b8f7a94f0c11c45631eee103dbcb7d63274edd12c56efe1be690b3b4", size = 225148, upload-time = "2026-08-06T13:48:23.376Z" }, + { url = "https://files.pythonhosted.org/packages/9e/83/3f4a69957f48ae7a0aba76c34743f88963d607b19e03f3f8e66f91cae0f9/coverage-7.15.4-cp313-cp313-win_arm64.whl", hash = "sha256:6e0a8a5083b096487d6cfced94cdd514d8f5db6f113610fb36c0620edb1028cf", size = 224536, upload-time = "2026-08-06T13:48:25.117Z" }, + { url = "https://files.pythonhosted.org/packages/ea/ac/748cf29eeb2d6be34a3176ce26a4f49e38085ee08e8935f05f6f26ed7e0f/coverage-7.15.4-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:770e9325ab5ea6d56f77e59b29ecfe0ac20b57a82a601876f90494a4dda0386f", size = 222608, upload-time = "2026-08-06T13:48:26.806Z" }, + { url = "https://files.pythonhosted.org/packages/0b/02/1abbf5c984677b0aa439cdacaccbf38d248939d8ef8fe1cc7a50d73edb77/coverage-7.15.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d12b33a3a50a1676b7784dc8d00a0c6d66a9f2add4b85a041c19b6a7e53ef23c", size = 222940, upload-time = "2026-08-06T13:48:28.432Z" }, + { url = "https://files.pythonhosted.org/packages/eb/e1/ff8f9f53d9fcf586125b55d0b1f04ec1c14955fee41e83d5814bee141bb5/coverage-7.15.4-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:5669c8378ebde86f5def7a25d29586631b58acc27ffde04399f678f3dfc6e082", size = 253985, upload-time = "2026-08-06T13:48:29.995Z" }, + { url = "https://files.pythonhosted.org/packages/a1/26/595759762e514e81be1d7d01ed03444303bcd152226a6529998d253f9201/coverage-7.15.4-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:ff97a14362eef486483ed44042ca2027ea257df6ff768e62358ee0c9776925ac", size = 256492, upload-time = "2026-08-06T13:48:31.634Z" }, + { url = "https://files.pythonhosted.org/packages/24/68/b79aabac54d482be23b5fcdd4f4662bff24a78edc4ee29201726929936d5/coverage-7.15.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5a325e815318638aed1655d9c06e6d7c2d3d46c09231ce988070428a8762d734", size = 257837, upload-time = "2026-08-06T13:48:33.186Z" }, + { url = "https://files.pythonhosted.org/packages/09/0f/bf7f297885a5bf6fd71e5782404e0ff059ca09e8711ceb3a08544abde45a/coverage-7.15.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:474223409d88eb20d2d6a0d37ea60e8647a65a90cc008dc1f0410af5f64f1e0d", size = 260152, upload-time = "2026-08-06T13:48:34.75Z" }, + { url = "https://files.pythonhosted.org/packages/fd/f1/296744e854ff8368542343457414380465e9ceefb9192342feb9d3bc461d/coverage-7.15.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7f2f62ae3cd189dd2e13aece758c57b3eecbd27be070dbd4cbd10936049e5dbf", size = 253978, upload-time = "2026-08-06T13:48:36.434Z" }, + { url = "https://files.pythonhosted.org/packages/55/b0/bbdb2e9057493e66220a2e149ca2d301ba0e3a58a83bd6b90de9826d16f3/coverage-7.15.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:39ece820e29e0a2ba34b3ecb3be83c27e997eed8926f2ba6fe7ce7a0bda5843b", size = 255846, upload-time = "2026-08-06T13:48:38.317Z" }, + { url = "https://files.pythonhosted.org/packages/96/e4/38015b2b6d21258713bd17e76b59d033b191efb5703589cffd037dfbca20/coverage-7.15.4-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:f21b56dcace11dfe013014201f577dcd592b2a9b72182d930361b47cf6f73f25", size = 253808, upload-time = "2026-08-06T13:48:39.993Z" }, + { url = "https://files.pythonhosted.org/packages/0b/64/0d515c1e60ee6fbfd1a0e79c07cd87d388a233b7adc37758735677203808/coverage-7.15.4-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:93a3a0b662abcc10c73a47cbc72cd60f63618d6989fb2d1286e50eacd974f303", size = 258081, upload-time = "2026-08-06T13:48:41.971Z" }, + { url = "https://files.pythonhosted.org/packages/91/71/04d9e7a3642146c6351338aef4ef85ab11dbbb54744c13245caba1aad1c0/coverage-7.15.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:141fae2cabf5569b782c10afc4c850ce10f618c13f8db54765cba99cc839da1f", size = 253624, upload-time = "2026-08-06T13:48:43.731Z" }, + { url = "https://files.pythonhosted.org/packages/b4/a7/6c28b74c81ebff66987b0e2522ba5cffa3e90b0c33cb6a2eb264d4ee8cf1/coverage-7.15.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:81294c7e6ab30c5f74c0353b11b2fd6320e72d9bee6ac73b357caa8b916323a5", size = 255280, upload-time = "2026-08-06T13:48:45.58Z" }, + { url = "https://files.pythonhosted.org/packages/52/af/bc19996a7014b98d7bbb0f0939453c67074af65784a3aa16a789a07381fa/coverage-7.15.4-cp314-cp314-win32.whl", hash = "sha256:7bbd7d6418e0dab31a206af5203bd43ae36edb8e7fba1940b055d3e9249290d7", size = 224768, upload-time = "2026-08-06T13:48:47.525Z" }, + { url = "https://files.pythonhosted.org/packages/ee/90/219484e476d6e101ba0a444852579e05f5b75c37c611a42ed1190f73ef62/coverage-7.15.4-cp314-cp314-win_amd64.whl", hash = "sha256:f0204ed122758782970526057093f448051a39db9d810d4e344bb87a3546f425", size = 225259, upload-time = "2026-08-06T13:48:49.513Z" }, + { url = "https://files.pythonhosted.org/packages/b7/66/fa77daf4e383e5f776dac62c2409b6af81910ae6fe326bd5170dba74cc63/coverage-7.15.4-cp314-cp314-win_arm64.whl", hash = "sha256:9e71e7bc71c686a123347ae47a0de33a175e797a85bb57b791492adf4eec8ed8", size = 224684, upload-time = "2026-08-06T13:48:51.235Z" }, + { url = "https://files.pythonhosted.org/packages/58/5b/f03bf0ce362bbf3f785fa5219620d00778d4ac6fc9e407734828e9c672f6/coverage-7.15.4-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7c922735321eef3f87c280a3d39afff6b646723a2880b862cda4ac7a093b8aa8", size = 223338, upload-time = "2026-08-06T13:48:52.896Z" }, + { url = "https://files.pythonhosted.org/packages/0f/76/e77d0ae22501831cc9f92193e8a957a5caa1dd177f90a6d1d9b106242d92/coverage-7.15.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f41c17c4668a655ce96d090d8d5ffdc24ef64b5a02f9753884d08483e8a4a41a", size = 223609, upload-time = "2026-08-06T13:48:54.688Z" }, + { url = "https://files.pythonhosted.org/packages/82/1a/b1f089da8d38ac612fa2dd6dc7f4a1a7657d12f3e261d2996edd3a838d0b/coverage-7.15.4-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:46822e9b6ff1c6a72b518c162c44a8f45a61a1d609c51084bf5b16c023c5037b", size = 264970, upload-time = "2026-08-06T13:48:56.403Z" }, + { url = "https://files.pythonhosted.org/packages/bf/31/e66d98d6e9c7fcc88470f1e234eaf6b1950dc0dfbf797f7282c1c861da24/coverage-7.15.4-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3d6f4955b73b5445271379a59e3792b0d978f42d4a01e0cf7a67d9c33a3bb0a5", size = 267088, upload-time = "2026-08-06T13:48:58.41Z" }, + { url = "https://files.pythonhosted.org/packages/59/a1/ae94eb2c541add426378408379f233591e069040b1e2cdb33df9498a0682/coverage-7.15.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3fc9e047706fb4a9abb54f719d3aa643e80e5bb3818182c40aee01ac0f0247ba", size = 269508, upload-time = "2026-08-06T13:49:00.42Z" }, + { url = "https://files.pythonhosted.org/packages/9c/c7/88a10694a1c6a213569766aba9f25847b28155d4ac731b13226db216356d/coverage-7.15.4-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:05e491d4f3165d62d4f5c8fd48dfeabf2ae8f42cbbd484319af33ea851b78982", size = 270629, upload-time = "2026-08-06T13:49:02.234Z" }, + { url = "https://files.pythonhosted.org/packages/b3/34/d8b8232e5e55169933b59aabcef2fedfa4b9d8897361bb80fcbda146505f/coverage-7.15.4-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:226c66e80ec0598d3b9b4874123df167ccca342aca8714f77cac6829688ee09c", size = 264043, upload-time = "2026-08-06T13:49:04.102Z" }, + { url = "https://files.pythonhosted.org/packages/7e/35/58b009dbf8c471c7224716478b9fed4a7e1af15320e1ed41660978504663/coverage-7.15.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ac41cc14bebda0dbfb0628036b7f75706935c95bcc07fefe9a0f93614aa60a57", size = 266963, upload-time = "2026-08-06T13:49:05.821Z" }, + { url = "https://files.pythonhosted.org/packages/62/aa/57fbda1b42c892968273c56b6ee9dc0f1310850859230a507bc7873b1f65/coverage-7.15.4-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:8af623e5cd92080acddd02b38f2f406a2c3a0893c38950b211890361448fbf26", size = 264569, upload-time = "2026-08-06T13:49:07.706Z" }, + { url = "https://files.pythonhosted.org/packages/98/8a/360e6e7f24d477b7e889703af0afa878d15b6d4d8d2a822b2835c169a879/coverage-7.15.4-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:07545711d4f0f32852a18f18ad11f76f0109909d09e78b9008b4cfc67e829429", size = 268299, upload-time = "2026-08-06T13:49:09.587Z" }, + { url = "https://files.pythonhosted.org/packages/4e/89/6f701261aee21b6b5fa8f7872229406dc917e125069448292223bf213606/coverage-7.15.4-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:a0865421cfdc53654b342d515e5a233187590882d20b95752150e53f65460017", size = 263413, upload-time = "2026-08-06T13:49:11.604Z" }, + { url = "https://files.pythonhosted.org/packages/3f/0f/6f04036edc260ed425af83e834f627fad48941ce97b50bfe6edd8b6fa623/coverage-7.15.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:460115e32ee40566476db5048f9bec1e842c127ad8e6f8be745aad3ac9cbc839", size = 265725, upload-time = "2026-08-06T13:49:13.38Z" }, + { url = "https://files.pythonhosted.org/packages/c4/ce/d19b5d4d5c49a7bfb925fd74310fee7d28bc99520ac3367ccbc54e662518/coverage-7.15.4-cp314-cp314t-win32.whl", hash = "sha256:cbde877ef9dd7baf272b9bfef2b8a25edd45d9170fc326951dd20eb480335e85", size = 225079, upload-time = "2026-08-06T13:49:15.265Z" }, + { url = "https://files.pythonhosted.org/packages/26/bb/7aa1b3b173faee0679037ca950bbbe1247273656697994d8d13f80f8d4b4/coverage-7.15.4-cp314-cp314t-win_amd64.whl", hash = "sha256:3da9e92d1c551fd7563833e9ade686efb0c4b7363ab7681a94283958c950bf5e", size = 225911, upload-time = "2026-08-06T13:49:17.279Z" }, + { url = "https://files.pythonhosted.org/packages/81/1c/4ea9e47426d80038d9222db3c4534cb6021a74b237d3ff97ffd33b6600dd/coverage-7.15.4-cp314-cp314t-win_arm64.whl", hash = "sha256:3a54f5a0d85050c73a38f6793090ee83974531e67fe5e57a1da9bee11398aa5e", size = 225219, upload-time = "2026-08-06T13:49:19.293Z" }, + { url = "https://files.pythonhosted.org/packages/2b/c4/dc5d2ac8f9142e7ec7de66e7bf0591db29d78955a040bd915870d9c0e657/coverage-7.15.4-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:2c9872e4d9dc5d3cf616bf4b382f5a00359305a5be666a3dd0b5cdb4e49597f9", size = 222604, upload-time = "2026-08-06T13:49:21.279Z" }, + { url = "https://files.pythonhosted.org/packages/70/39/33e63df81fe2ee100897451841c821467635923e58e37c6bd4b46dd8106c/coverage-7.15.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:e101dbb4b9b72f0cddd8cdc8c9c5b47f456766f5e0ac82dbfb75e5c55409b78a", size = 222944, upload-time = "2026-08-06T13:49:23.187Z" }, + { url = "https://files.pythonhosted.org/packages/99/1f/ef3ffb5557febc75a0d97aa459d0266d7d741110265121cc6d8539343d44/coverage-7.15.4-cp315-cp315-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:7d1abebdb047729e852b9c77a00497dfbeb11eb3a117e037d7dbc3ac8e5f5c54", size = 254050, upload-time = "2026-08-06T13:49:25.008Z" }, + { url = "https://files.pythonhosted.org/packages/6f/f5/1f0f6f77698c3601ca0ae7431e34b24c62ca2f06fecb23b73ed1f651d2be/coverage-7.15.4-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:d28a4a899354d0ea6214cc59b4fa19eefbce1b9ff1688ab579acf49e894bd3fb", size = 256967, upload-time = "2026-08-06T13:49:26.896Z" }, + { url = "https://files.pythonhosted.org/packages/03/7a/2ed9bed79925f4367c83c77f66a89e5ca7229c288d2d19ad5f36d1ca0070/coverage-7.15.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ffb3c2aacea411cc7e1d27712490c11108e2de1d39019ae32915493a59a8b9ed", size = 258587, upload-time = "2026-08-06T13:49:28.692Z" }, + { url = "https://files.pythonhosted.org/packages/45/8c/fa34044f71b7cc4ecb6da9c2408770959b0591fa9b5fb6fb6bca38f94298/coverage-7.15.4-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a9447978a92f405d301123cfd39ff49895490efb769a758fe2734c7f631bf8ce", size = 260785, upload-time = "2026-08-06T13:49:30.472Z" }, + { url = "https://files.pythonhosted.org/packages/4f/54/d5727ce36b4524a7394ab9f5f1df378e1f23affcdab01037dc8655185cc7/coverage-7.15.4-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:050467a7983b8e2fe7dd41a78bb30c3e7f8c0b8cafda14b1c46f8b5e3cf2dd3c", size = 254545, upload-time = "2026-08-06T13:49:32.271Z" }, + { url = "https://files.pythonhosted.org/packages/dc/e6/6e3783e576719590194bdffb6dd6d85490801785b7c331e35a245d8cb8b5/coverage-7.15.4-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:d003b7a5708ddad5c206c79607a6b92abb6fc13c57d99d8a4468cc03a2941ced", size = 256682, upload-time = "2026-08-06T13:49:34.089Z" }, + { url = "https://files.pythonhosted.org/packages/dc/f2/bacdbde18b69ed2de424fcf64d9fb0a4913753d4f0eca8bae9daad69f4bd/coverage-7.15.4-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:c38efe30fd74e5c19e9433f11fb1f5dc9c6522770971b7c6145bbaa413dc8800", size = 254560, upload-time = "2026-08-06T13:49:36.052Z" }, + { url = "https://files.pythonhosted.org/packages/6c/a3/1fb927196e3477c1b48831169ab58ba08f451ba87ae311ff1de68b26a616/coverage-7.15.4-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:1f4f826d70f772ab8b0c052329580d7fe8b8abd191e4ce0c8f81aec6614665d3", size = 258792, upload-time = "2026-08-06T13:49:38.01Z" }, + { url = "https://files.pythonhosted.org/packages/41/58/30d4c149c69053de0edfe325614c1d28d508f62b1783e0e4a234d2e49136/coverage-7.15.4-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:4a4bf917c9953f57c957be31c1cd504e3bd2f34d4a352b9d391a3025336f6768", size = 253968, upload-time = "2026-08-06T13:49:39.934Z" }, + { url = "https://files.pythonhosted.org/packages/89/e4/77f639371b918aad30dda4051f95404b43578f7f2e2f87ba73e02ed1ff37/coverage-7.15.4-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:1c9bf40ebef178a45192c75c4964760bb261b0e6ad725da5fc4c93f674f19753", size = 255893, upload-time = "2026-08-06T13:49:41.825Z" }, + { url = "https://files.pythonhosted.org/packages/5c/62/13be29b3ddab35f14c87967a4820a05106d2a3eccb4fa4ff550bf30b75e0/coverage-7.15.4-cp315-cp315-win32.whl", hash = "sha256:43619d04c3671792d2c4706ae8bf45e265dc87bbd4078189ef8b847ea1e74be2", size = 224768, upload-time = "2026-08-06T13:49:44.08Z" }, + { url = "https://files.pythonhosted.org/packages/a1/70/af0c6be0f964af6954f6b74bc109b0dbca02824696d2520fb17fe1ab06e3/coverage-7.15.4-cp315-cp315-win_amd64.whl", hash = "sha256:be619439dbcd31a2eab10b32de9fff62c26ed4bab69dc32b8363fdaaa0882809", size = 225242, upload-time = "2026-08-06T13:49:45.899Z" }, + { url = "https://files.pythonhosted.org/packages/4f/2d/f3bd3aab899fc9efc18b53133ee68f5f98574ef480649b23e12962226387/coverage-7.15.4-cp315-cp315-win_arm64.whl", hash = "sha256:def597967dafc2e8d97c9097ea453c464e0bb8ed38f193a43070f10dc623bb6d", size = 224674, upload-time = "2026-08-06T13:49:48.322Z" }, + { url = "https://files.pythonhosted.org/packages/f5/ca/f69251cd63eabc6438321aea22148754cce758a26bde07dd490e3fe7cfc5/coverage-7.15.4-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c7dbc748ac8a1e3e59a2b28bea47675e6e778081dbbf081bde0d75def2fcbe1d", size = 223333, upload-time = "2026-08-06T13:49:50.293Z" }, + { url = "https://files.pythonhosted.org/packages/a7/a7/037b53b2885b0d8447064432491a4d5a1014cd9f97a594d53acd0c04541a/coverage-7.15.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:2413074a5ecbb61a01a7888fc72db0ca324d13588c5b38bc0dd8564cdcdfea26", size = 223630, upload-time = "2026-08-06T13:49:52.637Z" }, + { url = "https://files.pythonhosted.org/packages/80/4f/152b8a4779ae90da11bb24f7467df8a59f0be48a5c52acb856325ca48289/coverage-7.15.4-cp315-cp315t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:4e6f6f632b7b2f714bf7a1346e8f97b650ee71f3c298aaad42a2ab60f0f07645", size = 264489, upload-time = "2026-08-06T13:49:54.52Z" }, + { url = "https://files.pythonhosted.org/packages/10/2d/84b4b9e0e1dd6528a51920ff7031f35b789382e467a28ec6a5a578cb8812/coverage-7.15.4-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8df457da2249d3c75ca2e5e835d59c725abfe92d27fdff6cd99eed85b51d5e9a", size = 267567, upload-time = "2026-08-06T13:49:56.721Z" }, + { url = "https://files.pythonhosted.org/packages/53/fc/ba01cc25299f9f8a2c8b02d3b28c53f3543d9fbfbe4e74fa2760b48f163e/coverage-7.15.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:050f66a08805acb5b8a23c6d4a517b1ecf82c08e81ed0e4bd727df065e5c6624", size = 270123, upload-time = "2026-08-06T13:49:58.736Z" }, + { url = "https://files.pythonhosted.org/packages/cf/d0/db2647cbf40b14f8c308f94ff7bf89c06d564e59f396906edf50086ec788/coverage-7.15.4-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1587fb771d1ccceef708fdde1e5af8c7ed24b486b61d13a321acb7d8145390aa", size = 271107, upload-time = "2026-08-06T13:50:00.811Z" }, + { url = "https://files.pythonhosted.org/packages/70/ff/4d2d17924552c458bb4f77dd631f0e3bc92fbbdf2d2d916cd4b33bbfd5b1/coverage-7.15.4-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8b4f1c3a69ca580f3fbd6b2046915f536d7f586874f25c1bb23add2a3c88d50f", size = 264955, upload-time = "2026-08-06T13:50:03.023Z" }, + { url = "https://files.pythonhosted.org/packages/ee/de/dc010c7a3691f396d93bbc26bfcafa1c2a3a351cd520470f15faf5795bd5/coverage-7.15.4-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:ffb58d7eff5b7f6ecc6fa21d6288ab7f968a212cb67d682c269c09b9eba3b66f", size = 267949, upload-time = "2026-08-06T13:50:05.557Z" }, + { url = "https://files.pythonhosted.org/packages/78/ea/dc96a11375e83c045c2f7c61fb6918277cfe9401db7c0f7b1d111a84b2e5/coverage-7.15.4-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:d9df165544774574ee004b953023d1bebada1894a80b1052a43d798b0f676e67", size = 264421, upload-time = "2026-08-06T13:50:07.612Z" }, + { url = "https://files.pythonhosted.org/packages/c8/86/b77131a0f9503ce461cd577076147d7a9040f0c5dda772686f729e2cc9cb/coverage-7.15.4-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:f9de0a24a4079b53e523b5c5e2c5945ec251ab486652659955187cf255a259bc", size = 269121, upload-time = "2026-08-06T13:50:09.58Z" }, + { url = "https://files.pythonhosted.org/packages/24/24/944bc35007862955e7ebf05754e645419dcf5d7526c52735cfa2715e8ebf/coverage-7.15.4-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:150089274bdc9f940628552cb92844e0223c987f1902ab8efe9f45a2ec758d88", size = 264565, upload-time = "2026-08-06T13:50:11.722Z" }, + { url = "https://files.pythonhosted.org/packages/c7/cc/a3bb9f93e7e740659163e2ea584f8196ddcd2c456a5dbe15f6c50105fec1/coverage-7.15.4-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:a58a94fed5da6997d258e8f7668c1e195fbd04a691d781b7558f1e468f9e68bc", size = 266522, upload-time = "2026-08-06T13:50:13.786Z" }, + { url = "https://files.pythonhosted.org/packages/49/dd/e0e40f3560d878d888c580698ff5ad1179f5e1c3ac949684ef66b41a3817/coverage-7.15.4-cp315-cp315t-win32.whl", hash = "sha256:ebd5a6d8466ff30836572f3ba2cae8a5e8f85029b1c6d5e2ed338dc472a5166a", size = 225068, upload-time = "2026-08-06T13:50:15.825Z" }, + { url = "https://files.pythonhosted.org/packages/c6/7e/37732ea80eebc30e976e4cdab15c190bc42d96959a42e38ddf6f8c60468f/coverage-7.15.4-cp315-cp315t-win_amd64.whl", hash = "sha256:288bde2a2d7ab6b6c2d7252fcde8b524387f2d970bdba9658fc6f8bbcaef0f9b", size = 225895, upload-time = "2026-08-06T13:50:17.928Z" }, + { url = "https://files.pythonhosted.org/packages/c6/08/1e00f7923eaaba45fb3d51dd794125fc766304b1df264f3a9c6557bfb30e/coverage-7.15.4-cp315-cp315t-win_arm64.whl", hash = "sha256:68be5e1de60ff13c9095bbec0e5a7fa45b33b101752215b91345ea1f61c4a278", size = 225213, upload-time = "2026-08-06T13:50:19.981Z" }, + { url = "https://files.pythonhosted.org/packages/b4/d9/e70c286c979378f061d8266e279b686ab0b0b688e1fe0af864684f23a77d/coverage-7.15.4-py3-none-any.whl", hash = "sha256:964730a1e9de9c0cf11be6a1a3c79ce419c34882842abd256086ba4698705e84", size = 214332, upload-time = "2026-08-06T13:50:22.192Z" }, +] + +[[package]] +name = "cryptography" +version = "50.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/de/41/6cbdcf9142d00fe82836fbb51e503e58088575cf7a0fe1dbff6695bf0840/cryptography-50.0.0.tar.gz", hash = "sha256:eeac2acb5a20ed25e0ad6d1df9891a520b78b404266b6d11778f25d5d691a6c9", size = 880201, upload-time = "2026-07-31T14:25:10.11Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c5/5c/59086b4aac5e879d38ddbcf74e4be7ade89cebc3eb199a55da998c3bb46a/cryptography-50.0.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:031e2d5dd4bb9caa3ca9c82e5a197fd8ae680232cee62603d1a813f3f07e3d03", size = 4001252, upload-time = "2026-07-31T14:23:33.331Z" }, + { url = "https://files.pythonhosted.org/packages/57/ef/8f2df13c7216bcad3e1c74e07f6e193d93e998e114f524a53877c9af27ad/cryptography-50.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fd9192b7b70c573d7f214eb1ae35e00d359f6f5e4b27c7e21e30de1fc6204645", size = 4719554, upload-time = "2026-07-31T14:23:35.611Z" }, + { url = "https://files.pythonhosted.org/packages/d9/41/029086c34d91052fc3b88bcc8056f709a7c915c7a23b235a54eb800b1c97/cryptography-50.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:06a32a980526a6ab9a4b9bf8f7385800791e2bb960903cb6b530e4817509a3b7", size = 4702130, upload-time = "2026-07-31T14:23:37.635Z" }, + { url = "https://files.pythonhosted.org/packages/7d/ff/b6ce0954962e7f7b969f850a883744197bb3910bdfd7b6da162eab7d9f68/cryptography-50.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a1b30560f2acc95aa8b2e06e716a13dbfc97314747b80d9707e307f77b40d6b3", size = 4725244, upload-time = "2026-07-31T14:23:39.471Z" }, + { url = "https://files.pythonhosted.org/packages/06/1e/63a1027cb7fec360a182208e1b7767d5aa1fe57be3d6aa856e69a321edc0/cryptography-50.0.0-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:8d89f3976b10b4ce31118de72329025f70d2c6ead14a8217c5514dd2c6d5a78f", size = 5342265, upload-time = "2026-07-31T14:23:41.286Z" }, + { url = "https://files.pythonhosted.org/packages/6b/72/a1116d683a6d7ece94590013882515de087edf9ef0e6292aae615a44df73/cryptography-50.0.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:b42a28c1844fd9de8f3f7d540e36b66f3a9c83fceac7170ebc7a6a19edd9dcae", size = 4734609, upload-time = "2026-07-31T14:23:43.139Z" }, + { url = "https://files.pythonhosted.org/packages/15/37/36a9c479bbe49acea2636c7fd3360d20f7b7e079c300352011c44850b181/cryptography-50.0.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:900131fafd8aead39ac7dd3a7e833be754c17a95cfd91221636949fe4eb0aa8a", size = 4356517, upload-time = "2026-07-31T14:23:44.939Z" }, + { url = "https://files.pythonhosted.org/packages/32/98/8a151d64367204cbc63ec65d37502f1d9c53cf4bfc6ec3c532614dbec60d/cryptography-50.0.0-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:07949c449a1abcf60d1ee6e88956d89404c7df3c8258f46589e912988e551987", size = 4724529, upload-time = "2026-07-31T14:23:46.93Z" }, + { url = "https://files.pythonhosted.org/packages/22/f6/ec13b470172126464a86bf54d2294a46d29837fc51ba3e45d4047946fb5e/cryptography-50.0.0-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f89831ef99dd7dd169ab06d63a831adb9e20a87aac6d380266bbda5823349169", size = 5299852, upload-time = "2026-07-31T14:23:48.851Z" }, + { url = "https://files.pythonhosted.org/packages/da/3a/f05e32c99d440c9bb891ea0e36c9091891e36be5a9a87ab2ee6ea20729f6/cryptography-50.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:82148ec5bddac30b51a5b3c1945075f896fa022cb93f8e4a01e9f6ee95292c5f", size = 4734462, upload-time = "2026-07-31T14:23:50.861Z" }, + { url = "https://files.pythonhosted.org/packages/ca/dc/bd72b26be8953f80625f63151efd38eee71c76ca6cf591c08ff34615a79e/cryptography-50.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1489e263a8048bb8b6a8bac662eb2d402ea5d2b7b4699b72f385f1e2772db105", size = 4852708, upload-time = "2026-07-31T14:23:52.715Z" }, + { url = "https://files.pythonhosted.org/packages/27/20/c930314a2ab476d15dec966ec87e2e9637bb02b06106b12c0396c57bb603/cryptography-50.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7cec5b856506da6defb290f30c9ee687d5f5e8cb0bd3f6459dde43b0b4fa40ef", size = 5004179, upload-time = "2026-07-31T14:23:54.887Z" }, + { url = "https://files.pythonhosted.org/packages/32/2e/c9db68a0c4bfa28e310707527c0ee3a2bd254104d2e02e68f368e197aa4c/cryptography-50.0.0-cp311-abi3-win_amd64.whl", hash = "sha256:bd1c592e4d5974f0d08d4888e432157adba757c66da0246918e43677fafa2d30", size = 3840395, upload-time = "2026-07-31T14:23:56.677Z" }, + { url = "https://files.pythonhosted.org/packages/c3/fb/951032a3bf22a5697c83183fb6294a4843772947a70e616c57b3ff5f522e/cryptography-50.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:49e7d93abdbd2990caced757e5fade25302f719c3c8fb6e6fff2dde98999fc41", size = 3989258, upload-time = "2026-07-31T14:23:58.881Z" }, + { url = "https://files.pythonhosted.org/packages/d4/67/91eb047e69c5e845f2f14b8a2e4a1aab0f283cb885531e9e22c8adb176bc/cryptography-50.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:19736989797678c6af1e55cd49055cdbcb55d8f6b5583ac5335f933aba9101dc", size = 4700648, upload-time = "2026-07-31T14:24:00.702Z" }, + { url = "https://files.pythonhosted.org/packages/30/82/85f0f7425c856b9f96459411eb12e74ef72df9caf6f8f15bf23a33ff131f/cryptography-50.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:80b63928fa35083b33966ce1efb70e5b9607181e49dcd1c22c8c005e319f667f", size = 4682442, upload-time = "2026-07-31T14:24:02.538Z" }, + { url = "https://files.pythonhosted.org/packages/1a/28/b555a365adff1cca2fbe7b9e487d68a40de6bc67ff2cb587473eb43de0e7/cryptography-50.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:d58c3db7cd6eed54e6c06744db55456b65ebd7492ddeae9c1e93cfca7aa857d3", size = 4707596, upload-time = "2026-07-31T14:24:04.394Z" }, + { url = "https://files.pythonhosted.org/packages/72/d8/f52538140cc719df62a01cf87d1c7142318d235817109d6f4054d7c352d6/cryptography-50.0.0-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:df2a58a472f332225671c35b0a830208b86d004f82baa8530fa3782c85646533", size = 5314552, upload-time = "2026-07-31T14:24:06.31Z" }, + { url = "https://files.pythonhosted.org/packages/38/14/6120e5bd7c5aa022ad15424ba4d5c5269d0d9448ed4d55e492ea91e3c1c4/cryptography-50.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:11b74db56cdbe3cdee6e3f6982ecb70334fa10dce99ed58bf7894aaaa3b2a037", size = 4717113, upload-time = "2026-07-31T14:24:08.349Z" }, + { url = "https://files.pythonhosted.org/packages/fa/71/190bf38c3ee2e0f8efc9860ae100c9df4169742eef274b91e7aa1cb133b9/cryptography-50.0.0-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:f59e38625469987d7ef6d495323c55e7db6c212eaf6112267e0d3b565a2e9c9f", size = 4338580, upload-time = "2026-07-31T14:24:10.227Z" }, + { url = "https://files.pythonhosted.org/packages/3a/63/504ccfbbe61fd8aa983f7f146399cdf034c72c2fc55f5b2dfdcdcdb20c99/cryptography-50.0.0-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:ecfed7367f965a0328cfbdd70da860f15441f002f613185668c6e6ebf5a0ac11", size = 4707038, upload-time = "2026-07-31T14:24:12.169Z" }, + { url = "https://files.pythonhosted.org/packages/01/77/2cf79bbfc4d12ca106437a6e170d6aaa01a373e93093118aaaef0e801bd4/cryptography-50.0.0-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:9aa87839c383bdbab6ef865787a1fb877af8dd03464c4400322726feaaadfc6d", size = 5273110, upload-time = "2026-07-31T14:24:14.38Z" }, + { url = "https://files.pythonhosted.org/packages/e5/45/8aae2972c520145377ea3559a605a899bebe227bf070b33cdb445929a9b9/cryptography-50.0.0-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:6ba6a53445bd3cfa809ef3ef5f1589aa6ba08784a1d962bf47d0940e871dab1c", size = 4716439, upload-time = "2026-07-31T14:24:16.415Z" }, + { url = "https://files.pythonhosted.org/packages/7b/20/4fe50b619a48c2525cc46e2dbc1ac490708d704be5d467bdaac6dc955682/cryptography-50.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:3f5735ffe4996d28b809371756219f5354864902a3b9e7c0b9ee87041209fc9c", size = 4837383, upload-time = "2026-07-31T14:24:18.553Z" }, + { url = "https://files.pythonhosted.org/packages/92/91/3a31366e183343d3703f8995c095f5734676bd6938118047e50fcf279eb4/cryptography-50.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:1b4a266766514614f8aa60416e71f2fc6e575d36e7bdc90f644fadb2f4b75b95", size = 4985772, upload-time = "2026-07-31T14:24:20.385Z" }, + { url = "https://files.pythonhosted.org/packages/74/9a/02ffe35b2853d121689871eb5dce862092562b3a1ed5cc98f1aaed441506/cryptography-50.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:12b9c6996425c76ea6c457ace4f3073e715b8c545add07cd1a8f3a4f90691269", size = 3816291, upload-time = "2026-07-31T14:24:22.125Z" }, + { url = "https://files.pythonhosted.org/packages/03/37/73d005be173aff344af30e9fd2a576575cb2391a7101d9cd3842e1fa8cce/cryptography-50.0.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:ccdc4a71a4dabae05de219404f9f4abc38e3b58422177ff93d0da05967dafa07", size = 4036009, upload-time = "2026-07-31T14:24:24.122Z" }, + { url = "https://files.pythonhosted.org/packages/ff/c6/7a6202a534e32103a285b7834a120869557fe198d51d7cfe59754c8bda9c/cryptography-50.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:910e1d2668e7de9648f2bcee30e180db2a6b15c30f887d7c4c93ddf96e3992e3", size = 4745252, upload-time = "2026-07-31T14:24:26.118Z" }, + { url = "https://files.pythonhosted.org/packages/85/4f/0fa8c2f4428198f15d9ff8d63400e27afbf94ce833f6108da1eb3753f945/cryptography-50.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a91296cb61e8df6f86d0c19cc4068228da256bf59bf86049fbd821084565327f", size = 4728939, upload-time = "2026-07-31T14:24:27.994Z" }, + { url = "https://files.pythonhosted.org/packages/d1/63/54dd723490ba2dc09b299682c10b38db38f159728bcaae8c591b8af2f22d/cryptography-50.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:e722f16708d854fe924790e051061f6704a472c3bac347b6fd88033ea8dd0dc5", size = 4748483, upload-time = "2026-07-31T14:24:30.254Z" }, + { url = "https://files.pythonhosted.org/packages/1d/dd/7c77d26285cc7f6991efce64a0f5b4f9383bfa5dd8c5033003eaf7db4cdb/cryptography-50.0.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:d764dcf130c428ef66786f866dd750f53182bc608813489915e9fc106bb0c82f", size = 5367599, upload-time = "2026-07-31T14:24:32.457Z" }, + { url = "https://files.pythonhosted.org/packages/46/c9/f60aed34c013f317f92817b6c171c2d22a78270fa41109bd4b08af26b194/cryptography-50.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:105110f43a471dbd0060b9c9516cb8a6a79233631a04cc2ba16f28323ac6e025", size = 4762647, upload-time = "2026-07-31T14:24:34.599Z" }, + { url = "https://files.pythonhosted.org/packages/be/f3/f9a0173b139372c3a48ed98154b45cc6b9de17c789d5ab552e621c293609/cryptography-50.0.0-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:828743d939e9629bc267b8e2d08d8bb67cd4319c771a33d4b18b22dd8fb7440a", size = 4385197, upload-time = "2026-07-31T14:24:36.647Z" }, + { url = "https://files.pythonhosted.org/packages/d8/36/83bb81f6e569bc38e1e4a7bc80f29b46bb9601920bc455fc8e888f5d5742/cryptography-50.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:2a8183b489dc1f7f80f135780fadc1108f14b31b8a40411c7a5b17425f65f28b", size = 4748095, upload-time = "2026-07-31T14:24:39.493Z" }, + { url = "https://files.pythonhosted.org/packages/6b/16/d3008eff98c764979865834c3d386d4fd041b5f52e7f34fc29ac1a5eb515/cryptography-50.0.0-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:6e7d61120573a7f2cd94cc095f9e81f6967c61ccdf194285aa143ecec8e0b708", size = 5325948, upload-time = "2026-07-31T14:24:41.556Z" }, + { url = "https://files.pythonhosted.org/packages/9c/f8/d97f9603efda3888187bfdb893f26c41be4735c10631d05d284ee6b047c4/cryptography-50.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:37fdb0d0111f1e2ff07139dfb79f1b49531f8e213c46f1163dd7642979b58c47", size = 4762400, upload-time = "2026-07-31T14:24:43.636Z" }, + { url = "https://files.pythonhosted.org/packages/64/a2/4615c8f7d81a00b1d6e6afe19f694e1543582349fb5f4076f6cb5dc36485/cryptography-50.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c87f62a3d3b9888ed0fdde100ec06aa61ca9cd44bad9057d1dff9a516b5f5bb9", size = 4878208, upload-time = "2026-07-31T14:24:45.522Z" }, + { url = "https://files.pythonhosted.org/packages/d2/1a/efcfb02f91407149a0dacffffab791f7e19bf6385f63b3666dc8b5e5c9c8/cryptography-50.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:65c2c3add92b45fd0709db8594536aea39c2a67af0e27ffcf049c498501140b7", size = 5037050, upload-time = "2026-07-31T14:24:47.697Z" }, + { url = "https://files.pythonhosted.org/packages/57/30/4a22984d4f1bdfb8c054f07a92bc176b97a3134cc1d6c4b3bffb1f3688b4/cryptography-50.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:d24fead1d4d076e1bfb006dcec392074a3cd8d7b4fc8a595aa64073b2b7a96ba", size = 3874135, upload-time = "2026-07-31T14:24:50.085Z" }, +] + +[[package]] +name = "cssselect2" +version = "0.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tinycss2" }, + { name = "webencodings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e0/20/92eaa6b0aec7189fa4b75c890640e076e9e793095721db69c5c81142c2e1/cssselect2-0.9.0.tar.gz", hash = "sha256:759aa22c216326356f65e62e791d66160a0f9c91d1424e8d8adc5e74dddfc6fb", size = 35595, upload-time = "2026-02-12T17:16:39.614Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/21/0e/8459ca4413e1a21a06c97d134bfaf18adfd27cea068813dc0faae06cbf00/cssselect2-0.9.0-py3-none-any.whl", hash = "sha256:6a99e5f91f9a016a304dd929b0966ca464bcfda15177b6fb4a118fc0fb5d9563", size = 15453, upload-time = "2026-02-12T17:16:38.317Z" }, +] + +[[package]] +name = "cuda-pathfinder" +version = "1.5.4" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/11/d0/c177e29701cf1d3008d7d2b16b5fc626592ce13bd535f8795c5f57187e0e/cuda_pathfinder-1.5.4-py3-none-any.whl", hash = "sha256:9563d3175ce1828531acf4b94e1c1c7d67208c347ca002493e2654878b26f4b7", size = 51657, upload-time = "2026-04-27T22:42:07.712Z" }, +] + +[[package]] +name = "cupy-cuda12x" +version = "14.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cuda-pathfinder" }, + { name = "numpy" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/a3/6e/290ee2d7cc4ad63d66e67acfd7ff3026f2b648dd04449a1bf88ffaa36b1e/cupy_cuda12x-14.1.1-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:7aae7d3bed37985e2aa39f0914b88ad90dbd3a6141d3e8198d73fce65859013c", size = 144383812, upload-time = "2026-06-01T04:52:23.799Z" }, + { url = "https://files.pythonhosted.org/packages/f6/6e/dc03c1ddc940f33b3d32803898e2fdae5c9538a2127a25f499494c84b183/cupy_cuda12x-14.1.1-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:a1138f20080489a46209291498cd12f792226d0a57d50c64a586c162a875a069", size = 133516927, upload-time = "2026-06-01T04:52:35.765Z" }, + { url = "https://files.pythonhosted.org/packages/cc/da/d4a8045b533af634bc791572e8c87981065e4a27b5d3e09d0d4d285742fd/cupy_cuda12x-14.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:85bebce86ffc25ecf31727b25da7b3793daf07b6fd9952704546af574d250988", size = 95238722, upload-time = "2026-06-01T04:52:46.296Z" }, + { url = "https://files.pythonhosted.org/packages/30/90/00fe874c47207b26c9b6ac950d0cecc533b4a145491641932df17e573f3c/cupy_cuda12x-14.1.1-cp313-cp313-manylinux2014_aarch64.whl", hash = "sha256:afbb3d1fa9484b0ae20d76372c5939a8c5da327e3fc8711b77b2354566cac355", size = 143920086, upload-time = "2026-06-01T04:52:51.726Z" }, + { url = "https://files.pythonhosted.org/packages/89/a4/c46ff91dba0dbe2a0a557974faf4c090a3159d6e7296431ca6846038d047/cupy_cuda12x-14.1.1-cp313-cp313-manylinux2014_x86_64.whl", hash = "sha256:76ea35469e2aa0a8332b88f72505ea2f7871a0bc8f9b0c87184f57e47c9aa3bf", size = 133071615, upload-time = "2026-06-01T04:52:57.428Z" }, + { url = "https://files.pythonhosted.org/packages/ec/a0/46778424035ad3fc920d49471f079687a054f74d179142e9520014c2514e/cupy_cuda12x-14.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:64072f4139b44df38215f0519a6badc14138fa0e4bb5b2db44fe94d05f8b9c8b", size = 95219598, upload-time = "2026-06-01T04:53:02.774Z" }, + { url = "https://files.pythonhosted.org/packages/b6/99/d72336481264c3483b162ea128d58f80abb50009f1df82ca82905e0b8fd7/cupy_cuda12x-14.1.1-cp314-cp314-manylinux2014_aarch64.whl", hash = "sha256:22d0ff2755a7f29cb225d1d5fb979a73428c5534ea0bca91b0c02698e9948f84", size = 143788629, upload-time = "2026-06-01T04:53:09.404Z" }, + { url = "https://files.pythonhosted.org/packages/c7/77/c43a67e6809e03780d88caf690fa44a8b3152db2d8f848714bec327c9881/cupy_cuda12x-14.1.1-cp314-cp314-manylinux2014_x86_64.whl", hash = "sha256:1059581507343e7cf6231facce30932a195c7aad4fa7771d00e4a252683915a1", size = 132406367, upload-time = "2026-06-01T04:53:16.232Z" }, + { url = "https://files.pythonhosted.org/packages/7d/dc/96cd37de6da41239e02fc7f17e3364d60f99bd6816673d622916a06113ec/cupy_cuda12x-14.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:e707e0eceee174d323be21652e87bb97be982e6966b5dc241756307df42842aa", size = 95793971, upload-time = "2026-06-01T04:53:21.478Z" }, + { url = "https://files.pythonhosted.org/packages/20/c6/0ddec1be851de546e883ae3da5f03c1ea69738628b38234dce4362b5e38b/cupy_cuda12x-14.1.1-cp314-cp314t-manylinux2014_aarch64.whl", hash = "sha256:e09897636b7468a90efa1152109f0b19ba49ebc9a423d5dbd4682ed589e57843", size = 144093057, upload-time = "2026-06-01T04:53:28.647Z" }, + { url = "https://files.pythonhosted.org/packages/a4/80/5e05de89ba61df072aab6f8a6ee3ffeec57db68a0a456825b3b4ce608426/cupy_cuda12x-14.1.1-cp314-cp314t-manylinux2014_x86_64.whl", hash = "sha256:238080487174268d0f09770fe518de7c5b206527bef5c6792aef7ba0626a1c48", size = 132635338, upload-time = "2026-06-01T04:53:35.229Z" }, +] + +[[package]] +name = "defusedxml" +version = "0.7.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0f/d5/c66da9b79e5bdb124974bfe172b4daf3c984ebd9c2a06e2b8a4dc7331c72/defusedxml-0.7.1.tar.gz", hash = "sha256:1bb3032db185915b62d7c6209c5a8792be6a32ab2fedacc84e01b52c51aa3e69", size = 75520, upload-time = "2021-03-08T10:59:26.269Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/07/6c/aa3f2f849e01cb6a001cd8554a88d4c77c5c1a31c95bdf1cf9301e6d9ef4/defusedxml-0.7.1-py2.py3-none-any.whl", hash = "sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61", size = 25604, upload-time = "2021-03-08T10:59:24.45Z" }, +] + +[[package]] +name = "docker" +version = "7.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pywin32", marker = "sys_platform == 'win32'" }, + { name = "requests" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/91/9b/4a2ea29aeba62471211598dac5d96825bb49348fa07e906ea930394a83ce/docker-7.1.0.tar.gz", hash = "sha256:ad8c70e6e3f8926cb8a92619b832b4ea5299e2831c14284663184e200546fa6c", size = 117834, upload-time = "2024-05-23T11:13:57.216Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl", hash = "sha256:c96b93b7f0a746f9e77d325bcfb87422a3d8bd4f03136ae8a85b37f1898d5fc0", size = 147774, upload-time = "2024-05-23T11:13:55.01Z" }, +] + +[[package]] +name = "docutils" +version = "0.22.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ae/b6/03bb70946330e88ffec97aefd3ea75ba575cb2e762061e0e62a213befee8/docutils-0.22.4.tar.gz", hash = "sha256:4db53b1fde9abecbb74d91230d32ab626d94f6badfc575d6db9194a49df29968", size = 2291750, upload-time = "2025-12-18T19:00:26.443Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/02/10/5da547df7a391dcde17f59520a231527b8571e6f46fc8efb02ccb370ab12/docutils-0.22.4-py3-none-any.whl", hash = "sha256:d0013f540772d1420576855455d050a2180186c91c15779301ac2ccb3eeb68de", size = 633196, upload-time = "2025-12-18T19:00:18.077Z" }, +] + +[[package]] +name = "donfig" +version = "0.8.1.post1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/25/71/80cc718ff6d7abfbabacb1f57aaa42e9c1552bfdd01e64ddd704e4a03638/donfig-0.8.1.post1.tar.gz", hash = "sha256:3bef3413a4c1c601b585e8d297256d0c1470ea012afa6e8461dc28bfb7c23f52", size = 19506, upload-time = "2024-05-23T14:14:31.513Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/d5/c5db1ea3394c6e1732fb3286b3bd878b59507a8f77d32a2cebda7d7b7cd4/donfig-0.8.1.post1-py3-none-any.whl", hash = "sha256:2a3175ce74a06109ff9307d90a230f81215cbac9a751f4d1c6194644b8204f9d", size = 21592, upload-time = "2024-05-23T14:13:55.283Z" }, +] + +[[package]] +name = "execnet" +version = "2.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/89/780e11f9588d9e7128a3f87788354c7946a9cbb1401ad38a48c4db9a4f07/execnet-2.1.2.tar.gz", hash = "sha256:63d83bfdd9a23e35b9c6a3261412324f964c2ec8dcd8d3c6916ee9373e0befcd", size = 166622, upload-time = "2025-11-12T09:56:37.75Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ab/84/02fc1827e8cdded4aa65baef11296a9bbe595c474f0d6d758af082d849fd/execnet-2.1.2-py3-none-any.whl", hash = "sha256:67fba928dd5a544b783f6056f449e5e3931a5c378b128bc18501f7ea79e296ec", size = 40708, upload-time = "2025-11-12T09:56:36.333Z" }, +] + +[[package]] +name = "flask" +version = "3.1.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "blinker" }, + { name = "click" }, + { name = "itsdangerous" }, + { name = "jinja2" }, + { name = "markupsafe" }, + { name = "werkzeug" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz", hash = "sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb", size = 759004, upload-time = "2026-02-19T05:00:57.678Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/9c/34f6962f9b9e9c71f6e5ed806e0d0ff03c9d1b0b2340088a0cf4bce09b18/flask-3.1.3-py3-none-any.whl", hash = "sha256:f4bcbefc124291925f1a26446da31a5178f9483862233b23c0c96a20701f670c", size = 103424, upload-time = "2026-02-19T05:00:56.027Z" }, +] + +[[package]] +name = "flask-cors" +version = "6.0.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flask" }, + { name = "werkzeug" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/70/74/0fc0fa68d62f21daef41017dafab19ef4b36551521260987eb3a5394c7ba/flask_cors-6.0.2.tar.gz", hash = "sha256:6e118f3698249ae33e429760db98ce032a8bf9913638d085ca0f4c5534ad2423", size = 13472, upload-time = "2025-12-12T20:31:42.861Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4f/af/72ad54402e599152de6d067324c46fe6a4f531c7c65baf7e96c63db55eaf/flask_cors-6.0.2-py3-none-any.whl", hash = "sha256:e57544d415dfd7da89a9564e1e3a9e515042df76e12130641ca6f3f2f03b699a", size = 13257, upload-time = "2025-12-12T20:31:41.3Z" }, +] + +[[package]] +name = "frozenlist" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2d/f5/c831fac6cc817d26fd54c7eaccd04ef7e0288806943f7cc5bbf69f3ac1f0/frozenlist-1.8.0.tar.gz", hash = "sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad", size = 45875, upload-time = "2025-10-06T05:38:17.865Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/29/948b9aa87e75820a38650af445d2ef2b6b8a6fab1a23b6bb9e4ef0be2d59/frozenlist-1.8.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:78f7b9e5d6f2fdb88cdde9440dc147259b62b9d3b019924def9f6478be254ac1", size = 87782, upload-time = "2025-10-06T05:36:06.649Z" }, + { url = "https://files.pythonhosted.org/packages/64/80/4f6e318ee2a7c0750ed724fa33a4bdf1eacdc5a39a7a24e818a773cd91af/frozenlist-1.8.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:229bf37d2e4acdaf808fd3f06e854a4a7a3661e871b10dc1f8f1896a3b05f18b", size = 50594, upload-time = "2025-10-06T05:36:07.69Z" }, + { url = "https://files.pythonhosted.org/packages/2b/94/5c8a2b50a496b11dd519f4a24cb5496cf125681dd99e94c604ccdea9419a/frozenlist-1.8.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f833670942247a14eafbb675458b4e61c82e002a148f49e68257b79296e865c4", size = 50448, upload-time = "2025-10-06T05:36:08.78Z" }, + { url = "https://files.pythonhosted.org/packages/6a/bd/d91c5e39f490a49df14320f4e8c80161cfcce09f1e2cde1edd16a551abb3/frozenlist-1.8.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:494a5952b1c597ba44e0e78113a7266e656b9794eec897b19ead706bd7074383", size = 242411, upload-time = "2025-10-06T05:36:09.801Z" }, + { url = "https://files.pythonhosted.org/packages/8f/83/f61505a05109ef3293dfb1ff594d13d64a2324ac3482be2cedc2be818256/frozenlist-1.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96f423a119f4777a4a056b66ce11527366a8bb92f54e541ade21f2374433f6d4", size = 243014, upload-time = "2025-10-06T05:36:11.394Z" }, + { url = "https://files.pythonhosted.org/packages/d8/cb/cb6c7b0f7d4023ddda30cf56b8b17494eb3a79e3fda666bf735f63118b35/frozenlist-1.8.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3462dd9475af2025c31cc61be6652dfa25cbfb56cbbf52f4ccfe029f38decaf8", size = 234909, upload-time = "2025-10-06T05:36:12.598Z" }, + { url = "https://files.pythonhosted.org/packages/31/c5/cd7a1f3b8b34af009fb17d4123c5a778b44ae2804e3ad6b86204255f9ec5/frozenlist-1.8.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c4c800524c9cd9bac5166cd6f55285957fcfc907db323e193f2afcd4d9abd69b", size = 250049, upload-time = "2025-10-06T05:36:14.065Z" }, + { url = "https://files.pythonhosted.org/packages/c0/01/2f95d3b416c584a1e7f0e1d6d31998c4a795f7544069ee2e0962a4b60740/frozenlist-1.8.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d6a5df73acd3399d893dafc71663ad22534b5aa4f94e8a2fabfe856c3c1b6a52", size = 256485, upload-time = "2025-10-06T05:36:15.39Z" }, + { url = "https://files.pythonhosted.org/packages/ce/03/024bf7720b3abaebcff6d0793d73c154237b85bdf67b7ed55e5e9596dc9a/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:405e8fe955c2280ce66428b3ca55e12b3c4e9c336fb2103a4937e891c69a4a29", size = 237619, upload-time = "2025-10-06T05:36:16.558Z" }, + { url = "https://files.pythonhosted.org/packages/69/fa/f8abdfe7d76b731f5d8bd217827cf6764d4f1d9763407e42717b4bed50a0/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:908bd3f6439f2fef9e85031b59fd4f1297af54415fb60e4254a95f75b3cab3f3", size = 250320, upload-time = "2025-10-06T05:36:17.821Z" }, + { url = "https://files.pythonhosted.org/packages/f5/3c/b051329f718b463b22613e269ad72138cc256c540f78a6de89452803a47d/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:294e487f9ec720bd8ffcebc99d575f7eff3568a08a253d1ee1a0378754b74143", size = 246820, upload-time = "2025-10-06T05:36:19.046Z" }, + { url = "https://files.pythonhosted.org/packages/0f/ae/58282e8f98e444b3f4dd42448ff36fa38bef29e40d40f330b22e7108f565/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:74c51543498289c0c43656701be6b077f4b265868fa7f8a8859c197006efb608", size = 250518, upload-time = "2025-10-06T05:36:20.763Z" }, + { url = "https://files.pythonhosted.org/packages/8f/96/007e5944694d66123183845a106547a15944fbbb7154788cbf7272789536/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:776f352e8329135506a1d6bf16ac3f87bc25b28e765949282dcc627af36123aa", size = 239096, upload-time = "2025-10-06T05:36:22.129Z" }, + { url = "https://files.pythonhosted.org/packages/66/bb/852b9d6db2fa40be96f29c0d1205c306288f0684df8fd26ca1951d461a56/frozenlist-1.8.0-cp312-cp312-win32.whl", hash = "sha256:433403ae80709741ce34038da08511d4a77062aa924baf411ef73d1146e74faf", size = 39985, upload-time = "2025-10-06T05:36:23.661Z" }, + { url = "https://files.pythonhosted.org/packages/b8/af/38e51a553dd66eb064cdf193841f16f077585d4d28394c2fa6235cb41765/frozenlist-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:34187385b08f866104f0c0617404c8eb08165ab1272e884abc89c112e9c00746", size = 44591, upload-time = "2025-10-06T05:36:24.958Z" }, + { url = "https://files.pythonhosted.org/packages/a7/06/1dc65480ab147339fecc70797e9c2f69d9cea9cf38934ce08df070fdb9cb/frozenlist-1.8.0-cp312-cp312-win_arm64.whl", hash = "sha256:fe3c58d2f5db5fbd18c2987cba06d51b0529f52bc3a6cdc33d3f4eab725104bd", size = 40102, upload-time = "2025-10-06T05:36:26.333Z" }, + { url = "https://files.pythonhosted.org/packages/2d/40/0832c31a37d60f60ed79e9dfb5a92e1e2af4f40a16a29abcc7992af9edff/frozenlist-1.8.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8d92f1a84bb12d9e56f818b3a746f3efba93c1b63c8387a73dde655e1e42282a", size = 85717, upload-time = "2025-10-06T05:36:27.341Z" }, + { url = "https://files.pythonhosted.org/packages/30/ba/b0b3de23f40bc55a7057bd38434e25c34fa48e17f20ee273bbde5e0650f3/frozenlist-1.8.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:96153e77a591c8adc2ee805756c61f59fef4cf4073a9275ee86fe8cba41241f7", size = 49651, upload-time = "2025-10-06T05:36:28.855Z" }, + { url = "https://files.pythonhosted.org/packages/0c/ab/6e5080ee374f875296c4243c381bbdef97a9ac39c6e3ce1d5f7d42cb78d6/frozenlist-1.8.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f21f00a91358803399890ab167098c131ec2ddd5f8f5fd5fe9c9f2c6fcd91e40", size = 49417, upload-time = "2025-10-06T05:36:29.877Z" }, + { url = "https://files.pythonhosted.org/packages/d5/4e/e4691508f9477ce67da2015d8c00acd751e6287739123113a9fca6f1604e/frozenlist-1.8.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:fb30f9626572a76dfe4293c7194a09fb1fe93ba94c7d4f720dfae3b646b45027", size = 234391, upload-time = "2025-10-06T05:36:31.301Z" }, + { url = "https://files.pythonhosted.org/packages/40/76/c202df58e3acdf12969a7895fd6f3bc016c642e6726aa63bd3025e0fc71c/frozenlist-1.8.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eaa352d7047a31d87dafcacbabe89df0aa506abb5b1b85a2fb91bc3faa02d822", size = 233048, upload-time = "2025-10-06T05:36:32.531Z" }, + { url = "https://files.pythonhosted.org/packages/f9/c0/8746afb90f17b73ca5979c7a3958116e105ff796e718575175319b5bb4ce/frozenlist-1.8.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:03ae967b4e297f58f8c774c7eabcce57fe3c2434817d4385c50661845a058121", size = 226549, upload-time = "2025-10-06T05:36:33.706Z" }, + { url = "https://files.pythonhosted.org/packages/7e/eb/4c7eefc718ff72f9b6c4893291abaae5fbc0c82226a32dcd8ef4f7a5dbef/frozenlist-1.8.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f6292f1de555ffcc675941d65fffffb0a5bcd992905015f85d0592201793e0e5", size = 239833, upload-time = "2025-10-06T05:36:34.947Z" }, + { url = "https://files.pythonhosted.org/packages/c2/4e/e5c02187cf704224f8b21bee886f3d713ca379535f16893233b9d672ea71/frozenlist-1.8.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:29548f9b5b5e3460ce7378144c3010363d8035cea44bc0bf02d57f5a685e084e", size = 245363, upload-time = "2025-10-06T05:36:36.534Z" }, + { url = "https://files.pythonhosted.org/packages/1f/96/cb85ec608464472e82ad37a17f844889c36100eed57bea094518bf270692/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ec3cc8c5d4084591b4237c0a272cc4f50a5b03396a47d9caaf76f5d7b38a4f11", size = 229314, upload-time = "2025-10-06T05:36:38.582Z" }, + { url = "https://files.pythonhosted.org/packages/5d/6f/4ae69c550e4cee66b57887daeebe006fe985917c01d0fff9caab9883f6d0/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:517279f58009d0b1f2e7c1b130b377a349405da3f7621ed6bfae50b10adf20c1", size = 243365, upload-time = "2025-10-06T05:36:40.152Z" }, + { url = "https://files.pythonhosted.org/packages/7a/58/afd56de246cf11780a40a2c28dc7cbabbf06337cc8ddb1c780a2d97e88d8/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:db1e72ede2d0d7ccb213f218df6a078a9c09a7de257c2fe8fcef16d5925230b1", size = 237763, upload-time = "2025-10-06T05:36:41.355Z" }, + { url = "https://files.pythonhosted.org/packages/cb/36/cdfaf6ed42e2644740d4a10452d8e97fa1c062e2a8006e4b09f1b5fd7d63/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:b4dec9482a65c54a5044486847b8a66bf10c9cb4926d42927ec4e8fd5db7fed8", size = 240110, upload-time = "2025-10-06T05:36:42.716Z" }, + { url = "https://files.pythonhosted.org/packages/03/a8/9ea226fbefad669f11b52e864c55f0bd57d3c8d7eb07e9f2e9a0b39502e1/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:21900c48ae04d13d416f0e1e0c4d81f7931f73a9dfa0b7a8746fb2fe7dd970ed", size = 233717, upload-time = "2025-10-06T05:36:44.251Z" }, + { url = "https://files.pythonhosted.org/packages/1e/0b/1b5531611e83ba7d13ccc9988967ea1b51186af64c42b7a7af465dcc9568/frozenlist-1.8.0-cp313-cp313-win32.whl", hash = "sha256:8b7b94a067d1c504ee0b16def57ad5738701e4ba10cec90529f13fa03c833496", size = 39628, upload-time = "2025-10-06T05:36:45.423Z" }, + { url = "https://files.pythonhosted.org/packages/d8/cf/174c91dbc9cc49bc7b7aab74d8b734e974d1faa8f191c74af9b7e80848e6/frozenlist-1.8.0-cp313-cp313-win_amd64.whl", hash = "sha256:878be833caa6a3821caf85eb39c5ba92d28e85df26d57afb06b35b2efd937231", size = 43882, upload-time = "2025-10-06T05:36:46.796Z" }, + { url = "https://files.pythonhosted.org/packages/c1/17/502cd212cbfa96eb1388614fe39a3fc9ab87dbbe042b66f97acb57474834/frozenlist-1.8.0-cp313-cp313-win_arm64.whl", hash = "sha256:44389d135b3ff43ba8cc89ff7f51f5a0bb6b63d829c8300f79a2fe4fe61bcc62", size = 39676, upload-time = "2025-10-06T05:36:47.8Z" }, + { url = "https://files.pythonhosted.org/packages/d2/5c/3bbfaa920dfab09e76946a5d2833a7cbdf7b9b4a91c714666ac4855b88b4/frozenlist-1.8.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:e25ac20a2ef37e91c1b39938b591457666a0fa835c7783c3a8f33ea42870db94", size = 89235, upload-time = "2025-10-06T05:36:48.78Z" }, + { url = "https://files.pythonhosted.org/packages/d2/d6/f03961ef72166cec1687e84e8925838442b615bd0b8854b54923ce5b7b8a/frozenlist-1.8.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:07cdca25a91a4386d2e76ad992916a85038a9b97561bf7a3fd12d5d9ce31870c", size = 50742, upload-time = "2025-10-06T05:36:49.837Z" }, + { url = "https://files.pythonhosted.org/packages/1e/bb/a6d12b7ba4c3337667d0e421f7181c82dda448ce4e7ad7ecd249a16fa806/frozenlist-1.8.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:4e0c11f2cc6717e0a741f84a527c52616140741cd812a50422f83dc31749fb52", size = 51725, upload-time = "2025-10-06T05:36:50.851Z" }, + { url = "https://files.pythonhosted.org/packages/bc/71/d1fed0ffe2c2ccd70b43714c6cab0f4188f09f8a67a7914a6b46ee30f274/frozenlist-1.8.0-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b3210649ee28062ea6099cfda39e147fa1bc039583c8ee4481cb7811e2448c51", size = 284533, upload-time = "2025-10-06T05:36:51.898Z" }, + { url = "https://files.pythonhosted.org/packages/c9/1f/fb1685a7b009d89f9bf78a42d94461bc06581f6e718c39344754a5d9bada/frozenlist-1.8.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:581ef5194c48035a7de2aefc72ac6539823bb71508189e5de01d60c9dcd5fa65", size = 292506, upload-time = "2025-10-06T05:36:53.101Z" }, + { url = "https://files.pythonhosted.org/packages/e6/3b/b991fe1612703f7e0d05c0cf734c1b77aaf7c7d321df4572e8d36e7048c8/frozenlist-1.8.0-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3ef2d026f16a2b1866e1d86fc4e1291e1ed8a387b2c333809419a2f8b3a77b82", size = 274161, upload-time = "2025-10-06T05:36:54.309Z" }, + { url = "https://files.pythonhosted.org/packages/ca/ec/c5c618767bcdf66e88945ec0157d7f6c4a1322f1473392319b7a2501ded7/frozenlist-1.8.0-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5500ef82073f599ac84d888e3a8c1f77ac831183244bfd7f11eaa0289fb30714", size = 294676, upload-time = "2025-10-06T05:36:55.566Z" }, + { url = "https://files.pythonhosted.org/packages/7c/ce/3934758637d8f8a88d11f0585d6495ef54b2044ed6ec84492a91fa3b27aa/frozenlist-1.8.0-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:50066c3997d0091c411a66e710f4e11752251e6d2d73d70d8d5d4c76442a199d", size = 300638, upload-time = "2025-10-06T05:36:56.758Z" }, + { url = "https://files.pythonhosted.org/packages/fc/4f/a7e4d0d467298f42de4b41cbc7ddaf19d3cfeabaf9ff97c20c6c7ee409f9/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:5c1c8e78426e59b3f8005e9b19f6ff46e5845895adbde20ece9218319eca6506", size = 283067, upload-time = "2025-10-06T05:36:57.965Z" }, + { url = "https://files.pythonhosted.org/packages/dc/48/c7b163063d55a83772b268e6d1affb960771b0e203b632cfe09522d67ea5/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:eefdba20de0d938cec6a89bd4d70f346a03108a19b9df4248d3cf0d88f1b0f51", size = 292101, upload-time = "2025-10-06T05:36:59.237Z" }, + { url = "https://files.pythonhosted.org/packages/9f/d0/2366d3c4ecdc2fd391e0afa6e11500bfba0ea772764d631bbf82f0136c9d/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:cf253e0e1c3ceb4aaff6df637ce033ff6535fb8c70a764a8f46aafd3d6ab798e", size = 289901, upload-time = "2025-10-06T05:37:00.811Z" }, + { url = "https://files.pythonhosted.org/packages/b8/94/daff920e82c1b70e3618a2ac39fbc01ae3e2ff6124e80739ce5d71c9b920/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:032efa2674356903cd0261c4317a561a6850f3ac864a63fc1583147fb05a79b0", size = 289395, upload-time = "2025-10-06T05:37:02.115Z" }, + { url = "https://files.pythonhosted.org/packages/e3/20/bba307ab4235a09fdcd3cc5508dbabd17c4634a1af4b96e0f69bfe551ebd/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:6da155091429aeba16851ecb10a9104a108bcd32f6c1642867eadaee401c1c41", size = 283659, upload-time = "2025-10-06T05:37:03.711Z" }, + { url = "https://files.pythonhosted.org/packages/fd/00/04ca1c3a7a124b6de4f8a9a17cc2fcad138b4608e7a3fc5877804b8715d7/frozenlist-1.8.0-cp313-cp313t-win32.whl", hash = "sha256:0f96534f8bfebc1a394209427d0f8a63d343c9779cda6fc25e8e121b5fd8555b", size = 43492, upload-time = "2025-10-06T05:37:04.915Z" }, + { url = "https://files.pythonhosted.org/packages/59/5e/c69f733a86a94ab10f68e496dc6b7e8bc078ebb415281d5698313e3af3a1/frozenlist-1.8.0-cp313-cp313t-win_amd64.whl", hash = "sha256:5d63a068f978fc69421fb0e6eb91a9603187527c86b7cd3f534a5b77a592b888", size = 48034, upload-time = "2025-10-06T05:37:06.343Z" }, + { url = "https://files.pythonhosted.org/packages/16/6c/be9d79775d8abe79b05fa6d23da99ad6e7763a1d080fbae7290b286093fd/frozenlist-1.8.0-cp313-cp313t-win_arm64.whl", hash = "sha256:bf0a7e10b077bf5fb9380ad3ae8ce20ef919a6ad93b4552896419ac7e1d8e042", size = 41749, upload-time = "2025-10-06T05:37:07.431Z" }, + { url = "https://files.pythonhosted.org/packages/f1/c8/85da824b7e7b9b6e7f7705b2ecaf9591ba6f79c1177f324c2735e41d36a2/frozenlist-1.8.0-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:cee686f1f4cadeb2136007ddedd0aaf928ab95216e7691c63e50a8ec066336d0", size = 86127, upload-time = "2025-10-06T05:37:08.438Z" }, + { url = "https://files.pythonhosted.org/packages/8e/e8/a1185e236ec66c20afd72399522f142c3724c785789255202d27ae992818/frozenlist-1.8.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:119fb2a1bd47307e899c2fac7f28e85b9a543864df47aa7ec9d3c1b4545f096f", size = 49698, upload-time = "2025-10-06T05:37:09.48Z" }, + { url = "https://files.pythonhosted.org/packages/a1/93/72b1736d68f03fda5fdf0f2180fb6caaae3894f1b854d006ac61ecc727ee/frozenlist-1.8.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:4970ece02dbc8c3a92fcc5228e36a3e933a01a999f7094ff7c23fbd2beeaa67c", size = 49749, upload-time = "2025-10-06T05:37:10.569Z" }, + { url = "https://files.pythonhosted.org/packages/a7/b2/fabede9fafd976b991e9f1b9c8c873ed86f202889b864756f240ce6dd855/frozenlist-1.8.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:cba69cb73723c3f329622e34bdbf5ce1f80c21c290ff04256cff1cd3c2036ed2", size = 231298, upload-time = "2025-10-06T05:37:11.993Z" }, + { url = "https://files.pythonhosted.org/packages/3a/3b/d9b1e0b0eed36e70477ffb8360c49c85c8ca8ef9700a4e6711f39a6e8b45/frozenlist-1.8.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:778a11b15673f6f1df23d9586f83c4846c471a8af693a22e066508b77d201ec8", size = 232015, upload-time = "2025-10-06T05:37:13.194Z" }, + { url = "https://files.pythonhosted.org/packages/dc/94/be719d2766c1138148564a3960fc2c06eb688da592bdc25adcf856101be7/frozenlist-1.8.0-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0325024fe97f94c41c08872db482cf8ac4800d80e79222c6b0b7b162d5b13686", size = 225038, upload-time = "2025-10-06T05:37:14.577Z" }, + { url = "https://files.pythonhosted.org/packages/e4/09/6712b6c5465f083f52f50cf74167b92d4ea2f50e46a9eea0523d658454ae/frozenlist-1.8.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:97260ff46b207a82a7567b581ab4190bd4dfa09f4db8a8b49d1a958f6aa4940e", size = 240130, upload-time = "2025-10-06T05:37:15.781Z" }, + { url = "https://files.pythonhosted.org/packages/f8/d4/cd065cdcf21550b54f3ce6a22e143ac9e4836ca42a0de1022da8498eac89/frozenlist-1.8.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:54b2077180eb7f83dd52c40b2750d0a9f175e06a42e3213ce047219de902717a", size = 242845, upload-time = "2025-10-06T05:37:17.037Z" }, + { url = "https://files.pythonhosted.org/packages/62/c3/f57a5c8c70cd1ead3d5d5f776f89d33110b1addae0ab010ad774d9a44fb9/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:2f05983daecab868a31e1da44462873306d3cbfd76d1f0b5b69c473d21dbb128", size = 229131, upload-time = "2025-10-06T05:37:18.221Z" }, + { url = "https://files.pythonhosted.org/packages/6c/52/232476fe9cb64f0742f3fde2b7d26c1dac18b6d62071c74d4ded55e0ef94/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:33f48f51a446114bc5d251fb2954ab0164d5be02ad3382abcbfe07e2531d650f", size = 240542, upload-time = "2025-10-06T05:37:19.771Z" }, + { url = "https://files.pythonhosted.org/packages/5f/85/07bf3f5d0fb5414aee5f47d33c6f5c77bfe49aac680bfece33d4fdf6a246/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:154e55ec0655291b5dd1b8731c637ecdb50975a2ae70c606d100750a540082f7", size = 237308, upload-time = "2025-10-06T05:37:20.969Z" }, + { url = "https://files.pythonhosted.org/packages/11/99/ae3a33d5befd41ac0ca2cc7fd3aa707c9c324de2e89db0e0f45db9a64c26/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:4314debad13beb564b708b4a496020e5306c7333fa9a3ab90374169a20ffab30", size = 238210, upload-time = "2025-10-06T05:37:22.252Z" }, + { url = "https://files.pythonhosted.org/packages/b2/60/b1d2da22f4970e7a155f0adde9b1435712ece01b3cd45ba63702aea33938/frozenlist-1.8.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:073f8bf8becba60aa931eb3bc420b217bb7d5b8f4750e6f8b3be7f3da85d38b7", size = 231972, upload-time = "2025-10-06T05:37:23.5Z" }, + { url = "https://files.pythonhosted.org/packages/3f/ab/945b2f32de889993b9c9133216c068b7fcf257d8595a0ac420ac8677cab0/frozenlist-1.8.0-cp314-cp314-win32.whl", hash = "sha256:bac9c42ba2ac65ddc115d930c78d24ab8d4f465fd3fc473cdedfccadb9429806", size = 40536, upload-time = "2025-10-06T05:37:25.581Z" }, + { url = "https://files.pythonhosted.org/packages/59/ad/9caa9b9c836d9ad6f067157a531ac48b7d36499f5036d4141ce78c230b1b/frozenlist-1.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:3e0761f4d1a44f1d1a47996511752cf3dcec5bbdd9cc2b4fe595caf97754b7a0", size = 44330, upload-time = "2025-10-06T05:37:26.928Z" }, + { url = "https://files.pythonhosted.org/packages/82/13/e6950121764f2676f43534c555249f57030150260aee9dcf7d64efda11dd/frozenlist-1.8.0-cp314-cp314-win_arm64.whl", hash = "sha256:d1eaff1d00c7751b7c6662e9c5ba6eb2c17a2306ba5e2a37f24ddf3cc953402b", size = 40627, upload-time = "2025-10-06T05:37:28.075Z" }, + { url = "https://files.pythonhosted.org/packages/c0/c7/43200656ecc4e02d3f8bc248df68256cd9572b3f0017f0a0c4e93440ae23/frozenlist-1.8.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:d3bb933317c52d7ea5004a1c442eef86f426886fba134ef8cf4226ea6ee1821d", size = 89238, upload-time = "2025-10-06T05:37:29.373Z" }, + { url = "https://files.pythonhosted.org/packages/d1/29/55c5f0689b9c0fb765055629f472c0de484dcaf0acee2f7707266ae3583c/frozenlist-1.8.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:8009897cdef112072f93a0efdce29cd819e717fd2f649ee3016efd3cd885a7ed", size = 50738, upload-time = "2025-10-06T05:37:30.792Z" }, + { url = "https://files.pythonhosted.org/packages/ba/7d/b7282a445956506fa11da8c2db7d276adcbf2b17d8bb8407a47685263f90/frozenlist-1.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2c5dcbbc55383e5883246d11fd179782a9d07a986c40f49abe89ddf865913930", size = 51739, upload-time = "2025-10-06T05:37:32.127Z" }, + { url = "https://files.pythonhosted.org/packages/62/1c/3d8622e60d0b767a5510d1d3cf21065b9db874696a51ea6d7a43180a259c/frozenlist-1.8.0-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:39ecbc32f1390387d2aa4f5a995e465e9e2f79ba3adcac92d68e3e0afae6657c", size = 284186, upload-time = "2025-10-06T05:37:33.21Z" }, + { url = "https://files.pythonhosted.org/packages/2d/14/aa36d5f85a89679a85a1d44cd7a6657e0b1c75f61e7cad987b203d2daca8/frozenlist-1.8.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92db2bf818d5cc8d9c1f1fc56b897662e24ea5adb36ad1f1d82875bd64e03c24", size = 292196, upload-time = "2025-10-06T05:37:36.107Z" }, + { url = "https://files.pythonhosted.org/packages/05/23/6bde59eb55abd407d34f77d39a5126fb7b4f109a3f611d3929f14b700c66/frozenlist-1.8.0-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:2dc43a022e555de94c3b68a4ef0b11c4f747d12c024a520c7101709a2144fb37", size = 273830, upload-time = "2025-10-06T05:37:37.663Z" }, + { url = "https://files.pythonhosted.org/packages/d2/3f/22cff331bfad7a8afa616289000ba793347fcd7bc275f3b28ecea2a27909/frozenlist-1.8.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cb89a7f2de3602cfed448095bab3f178399646ab7c61454315089787df07733a", size = 294289, upload-time = "2025-10-06T05:37:39.261Z" }, + { url = "https://files.pythonhosted.org/packages/a4/89/5b057c799de4838b6c69aa82b79705f2027615e01be996d2486a69ca99c4/frozenlist-1.8.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:33139dc858c580ea50e7e60a1b0ea003efa1fd42e6ec7fdbad78fff65fad2fd2", size = 300318, upload-time = "2025-10-06T05:37:43.213Z" }, + { url = "https://files.pythonhosted.org/packages/30/de/2c22ab3eb2a8af6d69dc799e48455813bab3690c760de58e1bf43b36da3e/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:168c0969a329b416119507ba30b9ea13688fafffac1b7822802537569a1cb0ef", size = 282814, upload-time = "2025-10-06T05:37:45.337Z" }, + { url = "https://files.pythonhosted.org/packages/59/f7/970141a6a8dbd7f556d94977858cfb36fa9b66e0892c6dd780d2219d8cd8/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:28bd570e8e189d7f7b001966435f9dac6718324b5be2990ac496cf1ea9ddb7fe", size = 291762, upload-time = "2025-10-06T05:37:46.657Z" }, + { url = "https://files.pythonhosted.org/packages/c1/15/ca1adae83a719f82df9116d66f5bb28bb95557b3951903d39135620ef157/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:b2a095d45c5d46e5e79ba1e5b9cb787f541a8dee0433836cea4b96a2c439dcd8", size = 289470, upload-time = "2025-10-06T05:37:47.946Z" }, + { url = "https://files.pythonhosted.org/packages/ac/83/dca6dc53bf657d371fbc88ddeb21b79891e747189c5de990b9dfff2ccba1/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:eab8145831a0d56ec9c4139b6c3e594c7a83c2c8be25d5bcf2d86136a532287a", size = 289042, upload-time = "2025-10-06T05:37:49.499Z" }, + { url = "https://files.pythonhosted.org/packages/96/52/abddd34ca99be142f354398700536c5bd315880ed0a213812bc491cff5e4/frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:974b28cf63cc99dfb2188d8d222bc6843656188164848c4f679e63dae4b0708e", size = 283148, upload-time = "2025-10-06T05:37:50.745Z" }, + { url = "https://files.pythonhosted.org/packages/af/d3/76bd4ed4317e7119c2b7f57c3f6934aba26d277acc6309f873341640e21f/frozenlist-1.8.0-cp314-cp314t-win32.whl", hash = "sha256:342c97bf697ac5480c0a7ec73cd700ecfa5a8a40ac923bd035484616efecc2df", size = 44676, upload-time = "2025-10-06T05:37:52.222Z" }, + { url = "https://files.pythonhosted.org/packages/89/76/c615883b7b521ead2944bb3480398cbb07e12b7b4e4d073d3752eb721558/frozenlist-1.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:06be8f67f39c8b1dc671f5d83aaefd3358ae5cdcf8314552c57e7ed3e6475bdd", size = 49451, upload-time = "2025-10-06T05:37:53.425Z" }, + { url = "https://files.pythonhosted.org/packages/e0/a3/5982da14e113d07b325230f95060e2169f5311b1017ea8af2a29b374c289/frozenlist-1.8.0-cp314-cp314t-win_arm64.whl", hash = "sha256:102e6314ca4da683dca92e3b1355490fed5f313b768500084fbe6371fddfdb79", size = 42507, upload-time = "2025-10-06T05:37:54.513Z" }, + { url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" }, +] + +[[package]] +name = "fsspec" +version = "2026.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/00/78/f34251dadb8f3921264a1d9b8946f5e542014ee2614b285261b4e40e6775/fsspec-2026.7.0.tar.gz", hash = "sha256:c803c40f4cf860b49dea58ee3e1c33cb9c790520e233537e1340049f89b82a88", size = 317040, upload-time = "2026-07-28T16:34:51.052Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fd/3c/6a2bf344106328fd04963664a60b9bb6496fc25df8e962fcdc1367285fb9/fsspec-2026.7.0-py3-none-any.whl", hash = "sha256:b57ddbafedfaef7018c1ecab32aa200a9d7ca26b77965f64e48b70061249d279", size = 206583, upload-time = "2026-07-28T16:34:49.538Z" }, +] + +[[package]] +name = "ghp-import" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d9/29/d40217cbe2f6b1359e00c6c307bb3fc876ba74068cbab3dde77f03ca0dc4/ghp-import-2.1.0.tar.gz", hash = "sha256:9c535c4c61193c2df8871222567d7fd7e5014d835f97dc7b7439069e2413d343", size = 10943, upload-time = "2022-05-02T15:47:16.11Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f7/ec/67fbef5d497f86283db54c22eec6f6140243aae73265799baaaa19cd17fb/ghp_import-2.1.0-py3-none-any.whl", hash = "sha256:8337dd7b50877f163d4c0289bc1f1c7f127550241988d568c1db512c4324a619", size = 11034, upload-time = "2022-05-02T15:47:14.552Z" }, +] + +[[package]] +name = "google-crc32c" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/03/41/4b9c02f99e4c5fb477122cd5437403b552873f014616ac1d19ac8221a58d/google_crc32c-1.8.0.tar.gz", hash = "sha256:a428e25fb7691024de47fecfbff7ff957214da51eddded0da0ae0e0f03a2cf79", size = 14192, upload-time = "2025-12-16T00:35:25.142Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e9/5f/7307325b1198b59324c0fa9807cafb551afb65e831699f2ce211ad5c8240/google_crc32c-1.8.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:4b8286b659c1335172e39563ab0a768b8015e88e08329fa5321f774275fc3113", size = 31300, upload-time = "2025-12-16T00:21:56.723Z" }, + { url = "https://files.pythonhosted.org/packages/21/8e/58c0d5d86e2220e6a37befe7e6a94dd2f6006044b1a33edf1ff6d9f7e319/google_crc32c-1.8.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:2a3dc3318507de089c5384cc74d54318401410f82aa65b2d9cdde9d297aca7cb", size = 30867, upload-time = "2025-12-16T00:38:31.302Z" }, + { url = "https://files.pythonhosted.org/packages/ce/a9/a780cc66f86335a6019f557a8aaca8fbb970728f0efd2430d15ff1beae0e/google_crc32c-1.8.0-cp312-cp312-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:14f87e04d613dfa218d6135e81b78272c3b904e2a7053b841481b38a7d901411", size = 33364, upload-time = "2025-12-16T00:40:22.96Z" }, + { url = "https://files.pythonhosted.org/packages/21/3f/3457ea803db0198c9aaca2dd373750972ce28a26f00544b6b85088811939/google_crc32c-1.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb5c869c2923d56cb0c8e6bcdd73c009c36ae39b652dbe46a05eb4ef0ad01454", size = 33740, upload-time = "2025-12-16T00:40:23.96Z" }, + { url = "https://files.pythonhosted.org/packages/df/c0/87c2073e0c72515bb8733d4eef7b21548e8d189f094b5dad20b0ecaf64f6/google_crc32c-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:3cc0c8912038065eafa603b238abf252e204accab2a704c63b9e14837a854962", size = 34437, upload-time = "2025-12-16T00:35:21.395Z" }, + { url = "https://files.pythonhosted.org/packages/d1/db/000f15b41724589b0e7bc24bc7a8967898d8d3bc8caf64c513d91ef1f6c0/google_crc32c-1.8.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:3ebb04528e83b2634857f43f9bb8ef5b2bbe7f10f140daeb01b58f972d04736b", size = 31297, upload-time = "2025-12-16T00:23:20.709Z" }, + { url = "https://files.pythonhosted.org/packages/d7/0d/8ebed0c39c53a7e838e2a486da8abb0e52de135f1b376ae2f0b160eb4c1a/google_crc32c-1.8.0-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:450dc98429d3e33ed2926fc99ee81001928d63460f8538f21a5d6060912a8e27", size = 30867, upload-time = "2025-12-16T00:43:14.628Z" }, + { url = "https://files.pythonhosted.org/packages/ce/42/b468aec74a0354b34c8cbf748db20d6e350a68a2b0912e128cabee49806c/google_crc32c-1.8.0-cp313-cp313-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3b9776774b24ba76831609ffbabce8cdf6fa2bd5e9df37b594221c7e333a81fa", size = 33344, upload-time = "2025-12-16T00:40:24.742Z" }, + { url = "https://files.pythonhosted.org/packages/1c/e8/b33784d6fc77fb5062a8a7854e43e1e618b87d5ddf610a88025e4de6226e/google_crc32c-1.8.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:89c17d53d75562edfff86679244830599ee0a48efc216200691de8b02ab6b2b8", size = 33694, upload-time = "2025-12-16T00:40:25.505Z" }, + { url = "https://files.pythonhosted.org/packages/92/b1/d3cbd4d988afb3d8e4db94ca953df429ed6db7282ed0e700d25e6c7bfc8d/google_crc32c-1.8.0-cp313-cp313-win_amd64.whl", hash = "sha256:57a50a9035b75643996fbf224d6661e386c7162d1dfdab9bc4ca790947d1007f", size = 34435, upload-time = "2025-12-16T00:35:22.107Z" }, + { url = "https://files.pythonhosted.org/packages/21/88/8ecf3c2b864a490b9e7010c84fd203ec8cf3b280651106a3a74dd1b0ca72/google_crc32c-1.8.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:e6584b12cb06796d285d09e33f63309a09368b9d806a551d8036a4207ea43697", size = 31301, upload-time = "2025-12-16T00:24:48.527Z" }, + { url = "https://files.pythonhosted.org/packages/36/c6/f7ff6c11f5ca215d9f43d3629163727a272eabc356e5c9b2853df2bfe965/google_crc32c-1.8.0-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:f4b51844ef67d6cf2e9425983274da75f18b1597bb2c998e1c0a0e8d46f8f651", size = 30868, upload-time = "2025-12-16T00:48:12.163Z" }, + { url = "https://files.pythonhosted.org/packages/56/15/c25671c7aad70f8179d858c55a6ae8404902abe0cdcf32a29d581792b491/google_crc32c-1.8.0-cp314-cp314-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b0d1a7afc6e8e4635564ba8aa5c0548e3173e41b6384d7711a9123165f582de2", size = 33381, upload-time = "2025-12-16T00:40:26.268Z" }, + { url = "https://files.pythonhosted.org/packages/42/fa/f50f51260d7b0ef5d4898af122d8a7ec5a84e2984f676f746445f783705f/google_crc32c-1.8.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8b3f68782f3cbd1bce027e48768293072813469af6a61a86f6bb4977a4380f21", size = 33734, upload-time = "2025-12-16T00:40:27.028Z" }, + { url = "https://files.pythonhosted.org/packages/08/a5/7b059810934a09fb3ccb657e0843813c1fee1183d3bc2c8041800374aa2c/google_crc32c-1.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:d511b3153e7011a27ab6ee6bb3a5404a55b994dc1a7322c0b87b29606d9790e2", size = 34878, upload-time = "2025-12-16T00:35:23.142Z" }, +] + +[[package]] +name = "graphql-core" +version = "3.2.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/68/c5/36aa96205c3ecbb3d34c7c24189e4553c7ca2ebc7e1dd07432339b980272/graphql_core-3.2.8.tar.gz", hash = "sha256:015457da5d996c924ddf57a43f4e959b0b94fb695b85ed4c29446e508ed65cf3", size = 513181, upload-time = "2026-03-05T19:55:37.332Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/86/41/cb887d9afc5dabd78feefe6ccbaf83ff423c206a7a1b7aeeac05120b2125/graphql_core-3.2.8-py3-none-any.whl", hash = "sha256:cbee07bee1b3ed5e531723685369039f32ff815ef60166686e0162f540f1520c", size = 207349, upload-time = "2026-03-05T19:55:35.911Z" }, +] + +[[package]] +name = "griffe-inherited-docstrings" +version = "1.1.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "griffelib" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cb/da/fd002dc5f215cd896bfccaebe8b4aa1cdeed8ea1d9d60633685bd61ff933/griffe_inherited_docstrings-1.1.3.tar.gz", hash = "sha256:cd1f937ec9336a790e5425e7f9b92f5a5ab17f292ba86917f1c681c0704cb64e", size = 26738, upload-time = "2026-02-21T09:38:44.312Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/16/20/4bc15f242181daad1c104e0a7d33be49e712461ea89e548152be0365b9ea/griffe_inherited_docstrings-1.1.3-py3-none-any.whl", hash = "sha256:aa7f6e624515c50d9325a5cfdf4b2acac547f1889aca89092d5da7278f739695", size = 6710, upload-time = "2026-02-20T11:06:38.75Z" }, +] + +[[package]] +name = "griffelib" +version = "2.0.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9d/82/74f4a3310cdabfbb10da554c3a672847f1ed33c6f61dd472681ce7f1fe67/griffelib-2.0.2.tar.gz", hash = "sha256:3cf20b3bc470e83763ffbf236e0076b1211bac1bc67de13daf494640f2de707e", size = 166461, upload-time = "2026-03-27T11:34:51.091Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/11/8c/c9138d881c79aa0ea9ed83cbd58d5ca75624378b38cee225dcf5c42cc91f/griffelib-2.0.2-py3-none-any.whl", hash = "sha256:925c857658fb1ba40c0772c37acbc2ab650bd794d9c1b9726922e36ea4117ea1", size = 142357, upload-time = "2026-03-27T11:34:46.275Z" }, +] + +[[package]] +name = "hypothesis" +version = "6.165.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sortedcontainers" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7a/3a/b840ea8b26e0c4795584dc93c832c5d1a9ff37db1818cc91b2ee8110f757/hypothesis-6.165.5.tar.gz", hash = "sha256:0df7fdefd2e10bbfe7d690eb22c7181a739e8040026907207faa305d86e6e4db", size = 503056, upload-time = "2026-08-12T22:34:58.164Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/46/fba332db906bb26f3c27285d17f5210bee54c3d7e1545e4d1bcae08ec437/hypothesis-6.165.5-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e9ee79ccf2de7b185821ed8364eccfea7300b52b30a8c626f6b7213f3b38e5d5", size = 782500, upload-time = "2026-08-12T22:33:48.567Z" }, + { url = "https://files.pythonhosted.org/packages/cd/68/f3cd7814a571ecf58c97a40686c97814c9f6be95dd258d9144d909f0900e/hypothesis-6.165.5-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:b732ea0c758e9c587eea8bb89ea27c985cb7609304e484ff8e5ffdb890f56ae5", size = 778047, upload-time = "2026-08-12T22:33:44.541Z" }, + { url = "https://files.pythonhosted.org/packages/85/a4/e0825ff8e353bf92b77f9b990c3e0e1160a0f2953feb95647cf2ced0b1a0/hypothesis-6.165.5-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:edb08b192ea64a75e82dcc0b49e515f9ca86e4523c678bf8035c993f3bf7323f", size = 1107271, upload-time = "2026-08-12T22:33:31.315Z" }, + { url = "https://files.pythonhosted.org/packages/63/85/1005fece1e0f59f8974c2e4be3fae1d0436a77b9fbee9a6203d7b250536d/hypothesis-6.165.5-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:eb74178189e0a8451e0b7cde4a236f4c8bee848ce01d42df968623ac11a4671a", size = 1135836, upload-time = "2026-08-12T22:34:06.044Z" }, + { url = "https://files.pythonhosted.org/packages/8d/8a/6f51cf111f590b883f5fcdb21b54345beeab516ad9c07d4256b731d66ef4/hypothesis-6.165.5-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a970cfb945f31b3115b013ede9fe3f0d68b37ff5b86499cc44ccec3d3fe1eeaa", size = 1156825, upload-time = "2026-08-12T22:34:28.263Z" }, + { url = "https://files.pythonhosted.org/packages/4c/7e/fbf54b49173d118681576259acdec61e045b825d516ca1fd5155f7a14ac1/hypothesis-6.165.5-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:569a7cd8b737019420a5530584ee28fba9dfa3ed877621764a2627f804e983c6", size = 1112117, upload-time = "2026-08-12T22:34:13.239Z" }, + { url = "https://files.pythonhosted.org/packages/d2/95/98bd41c67215950f73f8df711b7d13e40f0fad21c1ff61271b676abc4e19/hypothesis-6.165.5-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:61f30a43dc377ba94885e1990be785434686d76a8f37605336dd697c696dad4c", size = 1148864, upload-time = "2026-08-12T22:34:22.427Z" }, + { url = "https://files.pythonhosted.org/packages/0b/07/9dac0e757abc9dd0500b173adbfe018b1742af5ab35c46169cea290bbf65/hypothesis-6.165.5-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:6a25168ab05d52a084e216f8f033472a8bd18167e0e8fc25a8774722db884be2", size = 1282719, upload-time = "2026-08-12T22:33:55.326Z" }, + { url = "https://files.pythonhosted.org/packages/62/9a/0dcce83dfa414427c2632be45a2338edb5b80e2b9b1c7d88c70c2478c90d/hypothesis-6.165.5-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:6984a5b7e62b19ddd78643d954dfa90ec8dabbdac4df43a4e63f60fa06514eb2", size = 1409219, upload-time = "2026-08-12T22:33:39.521Z" }, + { url = "https://files.pythonhosted.org/packages/31/8f/82ed9fe9dae7cb79714c5de9cbccd5c4847348971e4ee61c5ad2013417d9/hypothesis-6.165.5-cp310-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:77b57c6c5154357955d724a5ba198aa421f1273a9f88a6ae24d23a1c6d1c91b8", size = 1281995, upload-time = "2026-08-12T22:34:38.42Z" }, + { url = "https://files.pythonhosted.org/packages/b9/4b/06ca1631cce0a9a9806ef15535b9502967751a066dfd620876ff4b8e1eaf/hypothesis-6.165.5-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:d77557a13f3cfbabc9b96909fc985563e474627208d981689e4925dc4708722f", size = 1324044, upload-time = "2026-08-12T22:33:57.817Z" }, + { url = "https://files.pythonhosted.org/packages/b0/d7/ac8ae1cf829faa5204a743db0e06880ff71bdd105927592b504e34368391/hypothesis-6.165.5-cp310-abi3-win32.whl", hash = "sha256:7c5fd96d54f63fca065cbc21579be0e9b75190af48ff77d5cb759111fe5edae0", size = 668283, upload-time = "2026-08-12T22:33:32.83Z" }, + { url = "https://files.pythonhosted.org/packages/1c/62/77acaaea919da21dbf9e76b78a87f9ac66fb44dc2e95afce07dad6da1185/hypothesis-6.165.5-cp310-abi3-win_amd64.whl", hash = "sha256:bcc3f34121b046e6091b35901b77e24dd1c674fc234b6e09b102e5efb03afa11", size = 674433, upload-time = "2026-08-12T22:34:47.75Z" }, + { url = "https://files.pythonhosted.org/packages/e6/d0/176ea6d8480d35a1a4fc2ffb1a61126441b2ac067216737052358581d5a7/hypothesis-6.165.5-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:1f330c91d532810bc2ac849e4d0d44a5a4f72508b4c92f1af91b7f2c90c4379a", size = 784074, upload-time = "2026-08-12T22:34:20.56Z" }, + { url = "https://files.pythonhosted.org/packages/3e/0c/3d128243dfc0ae059935c6607869f244efdc5676bb6e0006a2795cfebaeb/hypothesis-6.165.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:331e8026a380629c8b3b01850f0504a5191617694fe8703ffbb7de32cfbb370e", size = 775642, upload-time = "2026-08-12T22:34:14.757Z" }, + { url = "https://files.pythonhosted.org/packages/6f/40/e80bb810b26fe5807f7c8e3c3c5c3c7556d7128a195e0a57f2480b8a78e2/hypothesis-6.165.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d4ebe628c589b512a0e20b99aa3799e2331ba2c590dadf411d3bee95f9edb914", size = 1106103, upload-time = "2026-08-12T22:33:53.788Z" }, + { url = "https://files.pythonhosted.org/packages/a6/1c/14648fa3d821bfe4f132e5482837320f191bc60f38a4bd2b687096adf6e5/hypothesis-6.165.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:397685c7e74e6c489bab521bf437c7aba366e275e54f8bb03a6f4571df71faa8", size = 1156164, upload-time = "2026-08-12T22:34:04.621Z" }, + { url = "https://files.pythonhosted.org/packages/59/59/74718a2b859e3b6673589f1591785dd15cdec2ff02b7c8d18f3fc0a42ed2/hypothesis-6.165.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ed071268fb878d206ff3172dfef29681cda4982c2752d57e3ad1cf70aa3d7535", size = 1280047, upload-time = "2026-08-12T22:33:51.258Z" }, + { url = "https://files.pythonhosted.org/packages/72/5f/1de655e95992c4657f302ec0eca0dd2cfb6bfaaa3b698836432daedac992/hypothesis-6.165.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:381bb61f342c47d0bbfed6af7fecc93f1a8d4778e0c12e7415bdfe0f9bdc9121", size = 1323384, upload-time = "2026-08-12T22:34:03.192Z" }, + { url = "https://files.pythonhosted.org/packages/52/e9/1f265bf5f575396e8097010c39b11c2c4dd905064c694a0f53dffff58445/hypothesis-6.165.5-cp312-cp312-win_amd64.whl", hash = "sha256:92f2dfb1417bfaf93fdbe654261c68dbbfd573b74473a570895bf81958c045e7", size = 671570, upload-time = "2026-08-12T22:34:51.694Z" }, + { url = "https://files.pythonhosted.org/packages/f1/af/2c3357cda375d8ba1276dec4d0a7b51404f86cc6855f1541b424cf99d5f7/hypothesis-6.165.5-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:55b907b33ece350a8b69890a7f09b22b6a93761a8724c3ed12a9cd71b2a03eb1", size = 783966, upload-time = "2026-08-12T22:34:40.078Z" }, + { url = "https://files.pythonhosted.org/packages/0b/64/71cbfa9e741a0d657570af6b42f5f81ca795fdd0bddca44bc89309b46e16/hypothesis-6.165.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2cf1a6b2ccaf36e0a2b1f95515edec4db6db14a4e7afd9c36ff477552ffc0f11", size = 775594, upload-time = "2026-08-12T22:34:00.589Z" }, + { url = "https://files.pythonhosted.org/packages/ac/1f/ccb8f0034c8e17f488bc60d74ac21ac0e8945f507ed0b6e8634b67da925e/hypothesis-6.165.5-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5faa41aca389826d21f311ae5e59b36eb8bb38933a88bc07ad08bd868af6daae", size = 1106007, upload-time = "2026-08-12T22:34:25.431Z" }, + { url = "https://files.pythonhosted.org/packages/13/9d/64f7f7e1398fb04286816b9770138a35d730f008ac45b44b6425dcc0dd61/hypothesis-6.165.5-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a194f401e5d0345ef459f5aa80a50676a64e146c4f57474d70f7ccbe11c886c7", size = 1155990, upload-time = "2026-08-12T22:33:37.139Z" }, + { url = "https://files.pythonhosted.org/packages/21/e9/4bc808417bac59e9c154cbfb38705613adba4f1f37a815607211ab9ee0ab/hypothesis-6.165.5-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:dd2acd36004b990504125c4e679cf98addf3ca2ce873b38a52f71c66716cc7a6", size = 1280030, upload-time = "2026-08-12T22:34:53.359Z" }, + { url = "https://files.pythonhosted.org/packages/7b/ff/dd0de28497f64ca01c059e32eca7e06a69c39f50ab614969ae636b7ceb3f/hypothesis-6.165.5-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:709d61590c8cd627479fb4255e085239b91b29a4d386e83f910c5117cfe5b25b", size = 1323111, upload-time = "2026-08-12T22:33:41.959Z" }, + { url = "https://files.pythonhosted.org/packages/45/45/756e1050f26041f6c3aeae2b7e41b10160b2560de0ec46fd3341f6a3cb52/hypothesis-6.165.5-cp313-cp313-win_amd64.whl", hash = "sha256:de4b6d24a0e6adfdd99b2ee1f8d9f43e6ba6146b3860a643e8bce6b41fcebdc6", size = 671569, upload-time = "2026-08-12T22:34:33.938Z" }, + { url = "https://files.pythonhosted.org/packages/63/5e/e4178b39d5e7307d3658ec54733f3b7d953df12a38681b91ab1929b740cb/hypothesis-6.165.5-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:6f877ace8cb1bc0af9e3c83bf2a63f0a29f54f99ec813d1ecc9c3224b514c036", size = 784066, upload-time = "2026-08-12T22:34:42.97Z" }, + { url = "https://files.pythonhosted.org/packages/7b/f1/9c338484238ef0169f77ae7fdd28e34d1dacc0501f003cf7b0009f1f1f58/hypothesis-6.165.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:f9d0b87ba2fa7ae53c09650e07cb74a117b383d7ab4839415341ac802596d1e5", size = 775741, upload-time = "2026-08-12T22:34:31.002Z" }, + { url = "https://files.pythonhosted.org/packages/a8/79/4502ccc73f5dbaa29c9cc1f33af0337aa28cc03c86ae289530bb70c0fc73/hypothesis-6.165.5-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:842481f603ef919c2594784bfbaa600916250a35e9d54cc4260e27d415eacc0a", size = 1106541, upload-time = "2026-08-12T22:34:24.067Z" }, + { url = "https://files.pythonhosted.org/packages/b8/e9/10575fe56720cc6be25f7bc8cef708ee1b6e6669ca0b7fd16f7dbf460190/hypothesis-6.165.5-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c1ecee1a9241db6c2d51ebbe58aa2575364f4fa21583f5d22ac2a8885bbe9490", size = 1156172, upload-time = "2026-08-12T22:33:35.018Z" }, + { url = "https://files.pythonhosted.org/packages/c1/3e/b89e390f580d55b2d65bf726d7602a80f7725cc414bd60526bed0caf507b/hypothesis-6.165.5-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c108e99e4029318ed85ec5c39f5687c36604606394de3ff4da6e42356a2cceff", size = 1280392, upload-time = "2026-08-12T22:34:18.877Z" }, + { url = "https://files.pythonhosted.org/packages/9a/81/b33b5c0aedf35c298011748c679d652839a86b55ea616ca7561b85ac233f/hypothesis-6.165.5-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a811fe1f763e725692fa730c8b27ee3909f652f9c885dd89ee06f2583fd80944", size = 1323482, upload-time = "2026-08-12T22:34:49.696Z" }, + { url = "https://files.pythonhosted.org/packages/f2/8f/0361d9fce27af669ae936f535ad8275c35736cccf7d9ed66275f3eca874d/hypothesis-6.165.5-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:38353c9aaf946f76fd2d7d5e59c1564eac93ad362e98c7d6ffa705aa0e38974d", size = 615638, upload-time = "2026-08-12T22:34:54.979Z" }, + { url = "https://files.pythonhosted.org/packages/2d/fa/f49d197e125db4dd6725f248a838c1a8230e50d91889237fbf21705b6d45/hypothesis-6.165.5-cp314-cp314-win_amd64.whl", hash = "sha256:377af80792d187cc222bb2666e979c7e559ebb0f1b312c5376d7216f9c91bbf1", size = 671380, upload-time = "2026-08-12T22:33:36.096Z" }, + { url = "https://files.pythonhosted.org/packages/28/90/f939079a65499cad6352f566c3c632da5292f80e2253a72cc9bf6684d4bb/hypothesis-6.165.5-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:e2c423f947be24a7a7324962bf4984bc2231d61c01a4ce4d794e5c7e72b918f3", size = 782526, upload-time = "2026-08-12T22:33:33.895Z" }, + { url = "https://files.pythonhosted.org/packages/51/55/8afa60314542179289b2ef7eb6623cc8d9a6405488d2f3266e7610e003d4/hypothesis-6.165.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:05e7e8288b2f5fbb34a30b45c9df72a5ce9da0d5ce90705c76b28dda75aac984", size = 774157, upload-time = "2026-08-12T22:33:56.544Z" }, + { url = "https://files.pythonhosted.org/packages/6b/83/93ba4b711c0bfa5a2acc200d60f6fb3c947ea1a4b7f6ef0dacc02ac90de0/hypothesis-6.165.5-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3837b9e586a78f961aa7c0eedb979fa1cf3dcc8302103ac1e75c2520e943555f", size = 1104748, upload-time = "2026-08-12T22:33:46.901Z" }, + { url = "https://files.pythonhosted.org/packages/57/b9/c0b04ab66762526855fc97c18ecafe038fb1b428f48b2234e3c17b75b4ad/hypothesis-6.165.5-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eb8fac650e976dfe4d48682f902224a70e2e64ec0716a8822818fa958b456053", size = 1154827, upload-time = "2026-08-12T22:34:17.53Z" }, + { url = "https://files.pythonhosted.org/packages/4c/9b/9368493ef62fba5a3ae8b09164466c3ad166b329ae2df01c897dfc3f3790/hypothesis-6.165.5-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:0a5004c3fe761b642ca556abf4551bc9a94d190320bcf7ce118cf8b792eaf71c", size = 1278417, upload-time = "2026-08-12T22:34:16.196Z" }, + { url = "https://files.pythonhosted.org/packages/6f/21/5eef54851cb51f47ebe123312c4c737934cb6469f6af38bd6e052037f89c/hypothesis-6.165.5-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:df05b18c2dcb1701532044d4d119cecc08b7d91fcf72e78a17b03257053cc6e9", size = 1322104, upload-time = "2026-08-12T22:33:38.255Z" }, + { url = "https://files.pythonhosted.org/packages/9e/4e/9ed7f0b7c6b0a5d0d6aa0e0a5c05420db8ce21de6c96ce17139c0dbd8d2c/hypothesis-6.165.5-cp314-cp314t-win_amd64.whl", hash = "sha256:56f3a5b0b21695cdc6c8ccb7cf8da63f5822de4691cf23b9d95b5931b042af00", size = 671372, upload-time = "2026-08-12T22:34:46.023Z" }, +] + +[[package]] +name = "idna" +version = "3.15" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/82/77/7b3966d0b9d1d31a36ddf1746926a11dface89a83409bf1483f0237aa758/idna-3.15.tar.gz", hash = "sha256:ca962446ea538f7092a95e057da437618e886f4d349216d2b1e294abfdb65fdc", size = 199245, upload-time = "2026-05-12T22:45:57.011Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d2/23/408243171aa9aaba178d3e2559159c24c1171a641aa83b67bdd3394ead8e/idna-3.15-py3-none-any.whl", hash = "sha256:048adeaf8c2d788c40fee287673ccaa74c24ffd8dcf09ffa555a2fbb59f10ac8", size = 72340, upload-time = "2026-05-12T22:45:55.733Z" }, +] + +[[package]] +name = "imagesize" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6c/e6/7bf14eeb8f8b7251141944835abd42eb20a658d89084b7e1f3e5fe394090/imagesize-2.0.0.tar.gz", hash = "sha256:8e8358c4a05c304f1fccf7ff96f036e7243a189e9e42e90851993c558cfe9ee3", size = 1773045, upload-time = "2026-03-03T14:18:29.941Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5f/53/fb7122b71361a0d121b669dcf3d31244ef75badbbb724af388948de543e2/imagesize-2.0.0-py2.py3-none-any.whl", hash = "sha256:5667c5bbb57ab3f1fa4bc366f4fbc971db3d5ed011fd2715fd8001f782718d96", size = 9441, upload-time = "2026-03-03T14:18:27.892Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, +] + +[[package]] +name = "itsdangerous" +version = "2.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9c/cb/8ac0172223afbccb63986cc25049b154ecfb5e85932587206f42317be31d/itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173", size = 54410, upload-time = "2024-04-16T21:28:15.614Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/96/92447566d16df59b2a776c0fb82dbc4d9e07cd95062562af01e408583fc4/itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef", size = 16234, upload-time = "2024-04-16T21:28:14.499Z" }, +] + +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, +] + +[[package]] +name = "jmespath" +version = "1.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d3/59/322338183ecda247fb5d1763a6cbe46eff7222eaeebafd9fa65d4bf5cb11/jmespath-1.1.0.tar.gz", hash = "sha256:472c87d80f36026ae83c6ddd0f1d05d4e510134ed462851fd5f754c8c3cbb88d", size = 27377, upload-time = "2026-01-22T16:35:26.279Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/14/2f/967ba146e6d58cf6a652da73885f52fc68001525b4197effc174321d70b4/jmespath-1.1.0-py3-none-any.whl", hash = "sha256:a5663118de4908c91729bea0acadca56526eb2698e83de10cd116ae0f4e97c64", size = 20419, upload-time = "2026-01-22T16:35:24.919Z" }, +] + +[[package]] +name = "joserfc" +version = "1.6.8" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cryptography" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5d/ac/d4fd5b30f82900eac60d765f179f0ba005825ac462cc8ced6e13ec685ab3/joserfc-1.6.8.tar.gz", hash = "sha256:878620c553a6ebdd76ccdc356782fee3f735f21a356d079a546b42a4670ace5f", size = 232930, upload-time = "2026-05-27T03:22:37.819Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/98/8c/5cdce2cf3ce8155849baf9a5e2ce77e89dc87ec3bdb38259e5d85fbc45bd/joserfc-1.6.8-py3-none-any.whl", hash = "sha256:22fb31a69094a5e6f44632002a9df2c30c941fc6c8ce1b037e92c03de954cf9f", size = 70927, upload-time = "2026-05-27T03:22:35.796Z" }, +] + +[[package]] +name = "jsonpatch" +version = "1.33" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jsonpointer" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/42/78/18813351fe5d63acad16aec57f94ec2b70a09e53ca98145589e185423873/jsonpatch-1.33.tar.gz", hash = "sha256:9fcd4009c41e6d12348b4a0ff2563ba56a2923a7dfee731d004e212e1ee5030c", size = 21699, upload-time = "2023-06-26T12:07:29.144Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/73/07/02e16ed01e04a374e644b575638ec7987ae846d25ad97bcc9945a3ee4b0e/jsonpatch-1.33-py2.py3-none-any.whl", hash = "sha256:0ae28c0cd062bbd8b8ecc26d7d164fbbea9652a1a3693f3b956c1eae5145dade", size = 12898, upload-time = "2023-06-16T21:01:28.466Z" }, +] + +[[package]] +name = "jsonpath-ng" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/32/58/250751940d75c8019659e15482d548a4aa3b6ce122c515102a4bfdac50e3/jsonpath_ng-1.8.0.tar.gz", hash = "sha256:54252968134b5e549ea5b872f1df1168bd7defe1a52fed5a358c194e1943ddc3", size = 74513, upload-time = "2026-02-24T14:42:06.182Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/03/99/33c7d78a3fb70d545fd5411ac67a651c81602cc09c9cf0df383733f068c5/jsonpath_ng-1.8.0-py3-none-any.whl", hash = "sha256:b8dde192f8af58d646fc031fac9c99fe4d00326afc4148f1f043c601a8cfe138", size = 67844, upload-time = "2026-02-28T00:53:19.637Z" }, +] + +[[package]] +name = "jsonpointer" +version = "3.1.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/18/c7/af399a2e7a67fd18d63c40c5e62d3af4e67b836a2107468b6a5ea24c4304/jsonpointer-3.1.1.tar.gz", hash = "sha256:0b801c7db33a904024f6004d526dcc53bbb8a4a0f4e32bfd10beadf60adf1900", size = 9068, upload-time = "2026-03-23T22:32:32.458Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/6a/a83720e953b1682d2d109d3c2dbb0bc9bf28cc1cbc205be4ef4be5da709d/jsonpointer-3.1.1-py3-none-any.whl", hash = "sha256:8ff8b95779d071ba472cf5bc913028df06031797532f08a7d5b602d8b2a488ca", size = 7659, upload-time = "2026-03-23T22:32:31.568Z" }, +] + +[[package]] +name = "jsonschema" +version = "4.26.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "jsonschema-specifications" }, + { name = "referencing" }, + { name = "rpds-py" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b3/fc/e067678238fa451312d4c62bf6e6cf5ec56375422aee02f9cb5f909b3047/jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326", size = 366583, upload-time = "2026-01-07T13:41:07.246Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/90/f63fb5873511e014207a475e2bb4e8b2e570d655b00ac19a9a0ca0a385ee/jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce", size = 90630, upload-time = "2026-01-07T13:41:05.306Z" }, +] + +[[package]] +name = "jsonschema-path" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pathable" }, + { name = "pyyaml" }, + { name = "referencing" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/01/86/cfee6dd25843bec0760f456599a4f7e7e40221a934b9229fda0662c859bc/jsonschema_path-0.4.6.tar.gz", hash = "sha256:c89eb635f4d497c9ac328eeff359c489755838806a7d033510a692e9576f5c4b", size = 15302, upload-time = "2026-04-27T18:57:08.412Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6c/43/3d3065c05a04bb550c143bfbb8e4fd7022cd327e1082bf257bac74923783/jsonschema_path-0.4.6-py3-none-any.whl", hash = "sha256:451354b5311fa955c3144e6e4e255388c751c0121c5570ec5bb9291dd42d08c9", size = 19565, upload-time = "2026-04-27T18:57:06.792Z" }, +] + +[[package]] +name = "jsonschema-specifications" +version = "2025.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "referencing" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/74/a633ee74eb36c44aa6d1095e7cc5569bebf04342ee146178e2d36600708b/jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d", size = 32855, upload-time = "2025-09-08T01:34:59.186Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" }, +] + +[[package]] +name = "lazy-object-proxy" +version = "1.12.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/08/a2/69df9c6ba6d316cfd81fe2381e464db3e6de5db45f8c43c6a23504abf8cb/lazy_object_proxy-1.12.0.tar.gz", hash = "sha256:1f5a462d92fd0cfb82f1fab28b51bfb209fabbe6aabf7f0d51472c0c124c0c61", size = 43681, upload-time = "2025-08-22T13:50:06.783Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0d/1b/b5f5bd6bda26f1e15cd3232b223892e4498e34ec70a7f4f11c401ac969f1/lazy_object_proxy-1.12.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8ee0d6027b760a11cc18281e702c0309dd92da458a74b4c15025d7fc490deede", size = 26746, upload-time = "2025-08-22T13:42:37.572Z" }, + { url = "https://files.pythonhosted.org/packages/55/64/314889b618075c2bfc19293ffa9153ce880ac6153aacfd0a52fcabf21a66/lazy_object_proxy-1.12.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:4ab2c584e3cc8be0dfca422e05ad30a9abe3555ce63e9ab7a559f62f8dbc6ff9", size = 71457, upload-time = "2025-08-22T13:42:38.743Z" }, + { url = "https://files.pythonhosted.org/packages/11/53/857fc2827fc1e13fbdfc0ba2629a7d2579645a06192d5461809540b78913/lazy_object_proxy-1.12.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:14e348185adbd03ec17d051e169ec45686dcd840a3779c9d4c10aabe2ca6e1c0", size = 71036, upload-time = "2025-08-22T13:42:40.184Z" }, + { url = "https://files.pythonhosted.org/packages/2b/24/e581ffed864cd33c1b445b5763d617448ebb880f48675fc9de0471a95cbc/lazy_object_proxy-1.12.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c4fcbe74fb85df8ba7825fa05eddca764138da752904b378f0ae5ab33a36c308", size = 69329, upload-time = "2025-08-22T13:42:41.311Z" }, + { url = "https://files.pythonhosted.org/packages/78/be/15f8f5a0b0b2e668e756a152257d26370132c97f2f1943329b08f057eff0/lazy_object_proxy-1.12.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:563d2ec8e4d4b68ee7848c5ab4d6057a6d703cb7963b342968bb8758dda33a23", size = 70690, upload-time = "2025-08-22T13:42:42.51Z" }, + { url = "https://files.pythonhosted.org/packages/5d/aa/f02be9bbfb270e13ee608c2b28b8771f20a5f64356c6d9317b20043c6129/lazy_object_proxy-1.12.0-cp312-cp312-win_amd64.whl", hash = "sha256:53c7fd99eb156bbb82cbc5d5188891d8fdd805ba6c1e3b92b90092da2a837073", size = 26563, upload-time = "2025-08-22T13:42:43.685Z" }, + { url = "https://files.pythonhosted.org/packages/f4/26/b74c791008841f8ad896c7f293415136c66cc27e7c7577de4ee68040c110/lazy_object_proxy-1.12.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:86fd61cb2ba249b9f436d789d1356deae69ad3231dc3c0f17293ac535162672e", size = 26745, upload-time = "2025-08-22T13:42:44.982Z" }, + { url = "https://files.pythonhosted.org/packages/9b/52/641870d309e5d1fb1ea7d462a818ca727e43bfa431d8c34b173eb090348c/lazy_object_proxy-1.12.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:81d1852fb30fab81696f93db1b1e55a5d1ff7940838191062f5f56987d5fcc3e", size = 71537, upload-time = "2025-08-22T13:42:46.141Z" }, + { url = "https://files.pythonhosted.org/packages/47/b6/919118e99d51c5e76e8bf5a27df406884921c0acf2c7b8a3b38d847ab3e9/lazy_object_proxy-1.12.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:be9045646d83f6c2664c1330904b245ae2371b5c57a3195e4028aedc9f999655", size = 71141, upload-time = "2025-08-22T13:42:47.375Z" }, + { url = "https://files.pythonhosted.org/packages/e5/47/1d20e626567b41de085cf4d4fb3661a56c159feaa73c825917b3b4d4f806/lazy_object_proxy-1.12.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:67f07ab742f1adfb3966c40f630baaa7902be4222a17941f3d85fd1dae5565ff", size = 69449, upload-time = "2025-08-22T13:42:48.49Z" }, + { url = "https://files.pythonhosted.org/packages/58/8d/25c20ff1a1a8426d9af2d0b6f29f6388005fc8cd10d6ee71f48bff86fdd0/lazy_object_proxy-1.12.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:75ba769017b944fcacbf6a80c18b2761a1795b03f8899acdad1f1c39db4409be", size = 70744, upload-time = "2025-08-22T13:42:49.608Z" }, + { url = "https://files.pythonhosted.org/packages/c0/67/8ec9abe15c4f8a4bcc6e65160a2c667240d025cbb6591b879bea55625263/lazy_object_proxy-1.12.0-cp313-cp313-win_amd64.whl", hash = "sha256:7b22c2bbfb155706b928ac4d74c1a63ac8552a55ba7fff4445155523ea4067e1", size = 26568, upload-time = "2025-08-22T13:42:57.719Z" }, + { url = "https://files.pythonhosted.org/packages/23/12/cd2235463f3469fd6c62d41d92b7f120e8134f76e52421413a0ad16d493e/lazy_object_proxy-1.12.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:4a79b909aa16bde8ae606f06e6bbc9d3219d2e57fb3e0076e17879072b742c65", size = 27391, upload-time = "2025-08-22T13:42:50.62Z" }, + { url = "https://files.pythonhosted.org/packages/60/9e/f1c53e39bbebad2e8609c67d0830cc275f694d0ea23d78e8f6db526c12d3/lazy_object_proxy-1.12.0-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:338ab2f132276203e404951205fe80c3fd59429b3a724e7b662b2eb539bb1be9", size = 80552, upload-time = "2025-08-22T13:42:51.731Z" }, + { url = "https://files.pythonhosted.org/packages/4c/b6/6c513693448dcb317d9d8c91d91f47addc09553613379e504435b4cc8b3e/lazy_object_proxy-1.12.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8c40b3c9faee2e32bfce0df4ae63f4e73529766893258eca78548bac801c8f66", size = 82857, upload-time = "2025-08-22T13:42:53.225Z" }, + { url = "https://files.pythonhosted.org/packages/12/1c/d9c4aaa4c75da11eb7c22c43d7c90a53b4fca0e27784a5ab207768debea7/lazy_object_proxy-1.12.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:717484c309df78cedf48396e420fa57fc8a2b1f06ea889df7248fdd156e58847", size = 80833, upload-time = "2025-08-22T13:42:54.391Z" }, + { url = "https://files.pythonhosted.org/packages/0b/ae/29117275aac7d7d78ae4f5a4787f36ff33262499d486ac0bf3e0b97889f6/lazy_object_proxy-1.12.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:a6b7ea5ea1ffe15059eb44bcbcb258f97bcb40e139b88152c40d07b1a1dfc9ac", size = 79516, upload-time = "2025-08-22T13:42:55.812Z" }, + { url = "https://files.pythonhosted.org/packages/19/40/b4e48b2c38c69392ae702ae7afa7b6551e0ca5d38263198b7c79de8b3bdf/lazy_object_proxy-1.12.0-cp313-cp313t-win_amd64.whl", hash = "sha256:08c465fb5cd23527512f9bd7b4c7ba6cec33e28aad36fbbe46bf7b858f9f3f7f", size = 27656, upload-time = "2025-08-22T13:42:56.793Z" }, + { url = "https://files.pythonhosted.org/packages/ef/3a/277857b51ae419a1574557c0b12e0d06bf327b758ba94cafc664cb1e2f66/lazy_object_proxy-1.12.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c9defba70ab943f1df98a656247966d7729da2fe9c2d5d85346464bf320820a3", size = 26582, upload-time = "2025-08-22T13:49:49.366Z" }, + { url = "https://files.pythonhosted.org/packages/1a/b6/c5e0fa43535bb9c87880e0ba037cdb1c50e01850b0831e80eb4f4762f270/lazy_object_proxy-1.12.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:6763941dbf97eea6b90f5b06eb4da9418cc088fce0e3883f5816090f9afcde4a", size = 71059, upload-time = "2025-08-22T13:49:50.488Z" }, + { url = "https://files.pythonhosted.org/packages/06/8a/7dcad19c685963c652624702f1a968ff10220b16bfcc442257038216bf55/lazy_object_proxy-1.12.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fdc70d81235fc586b9e3d1aeef7d1553259b62ecaae9db2167a5d2550dcc391a", size = 71034, upload-time = "2025-08-22T13:49:54.224Z" }, + { url = "https://files.pythonhosted.org/packages/12/ac/34cbfb433a10e28c7fd830f91c5a348462ba748413cbb950c7f259e67aa7/lazy_object_proxy-1.12.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:0a83c6f7a6b2bfc11ef3ed67f8cbe99f8ff500b05655d8e7df9aab993a6abc95", size = 69529, upload-time = "2025-08-22T13:49:55.29Z" }, + { url = "https://files.pythonhosted.org/packages/6f/6a/11ad7e349307c3ca4c0175db7a77d60ce42a41c60bcb11800aabd6a8acb8/lazy_object_proxy-1.12.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:256262384ebd2a77b023ad02fbcc9326282bcfd16484d5531154b02bc304f4c5", size = 70391, upload-time = "2025-08-22T13:49:56.35Z" }, + { url = "https://files.pythonhosted.org/packages/59/97/9b410ed8fbc6e79c1ee8b13f8777a80137d4bc189caf2c6202358e66192c/lazy_object_proxy-1.12.0-cp314-cp314-win_amd64.whl", hash = "sha256:7601ec171c7e8584f8ff3f4e440aa2eebf93e854f04639263875b8c2971f819f", size = 26988, upload-time = "2025-08-22T13:49:57.302Z" }, +] + +[[package]] +name = "librt" +version = "0.13.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/dc/2f/3908645ddddab7120b46295e541ead308109fa48dbec7d67d7a778870d60/librt-0.13.0.tar.gz", hash = "sha256:1d2a610c14ac0d0750ee0a3ab8548e83155258387891caaca04def4bf7289781", size = 211402, upload-time = "2026-07-08T12:26:29.834Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f0/f4/b2933ddae222dac338476abb872641169a5cfed2c2bb5444a5b07b32b0c3/librt-0.13.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:30536798f4504c0fad0885b1d371b0539abb081e4570c9d7c641cb51141b49f0", size = 150990, upload-time = "2026-07-08T12:25:02.42Z" }, + { url = "https://files.pythonhosted.org/packages/90/ef/db98f744ca50e6efc9c95c70ee49b77aefac31f6a3fc7c83754a42d6a74f/librt-0.13.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:93d24ebb82aa4420b1409c389e7857bc35bd0b668007ac8172427d5c73cc8cc5", size = 155238, upload-time = "2026-07-08T12:25:03.681Z" }, + { url = "https://files.pythonhosted.org/packages/03/e7/a197e7bc72baf2c61ce7fdc6906a5054dc05bd8da0819aa894e4857bf87e/librt-0.13.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cb8a1adce42d8b75485a5d56a9623a50bcab995b6079f1dac59fc44034dd93d9", size = 503073, upload-time = "2026-07-08T12:25:05.049Z" }, + { url = "https://files.pythonhosted.org/packages/f8/e7/7887712e27da7c1ab80fcabb1de6eb24243964f6557cae530d4b70706dbd/librt-0.13.0-cp312-cp312-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:0763ca2ab66058174f9dee426dc64f5e0a89c24a7df8d3fe3f1836c04e25de4b", size = 496528, upload-time = "2026-07-08T12:25:06.26Z" }, + { url = "https://files.pythonhosted.org/packages/94/f0/f2283385bb6b950b26a1410f4ce51ec27231e0b3a4b925c46366d218b198/librt-0.13.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b222493da6e7b6199db9bd79502436cf5a27da3c1f7fa83c7e285444fc93fd03", size = 531786, upload-time = "2026-07-08T12:25:07.658Z" }, + { url = "https://files.pythonhosted.org/packages/36/11/69ac3b54766ffba5fd7e5acebfb048d66dbe1f9f2d14516c2b3edc59cf87/librt-0.13.0-cp312-cp312-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:fadc63331f4388c3dc90090448f682a7e9feafc11481391c1e94f2f907a3976e", size = 524393, upload-time = "2026-07-08T12:25:09.121Z" }, + { url = "https://files.pythonhosted.org/packages/61/5f/d72f95fd444a926a3c14b4e24979474116988dd57a45be242077c45d3c22/librt-0.13.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:70d9c62a4cffd9f23396cd5ef93fc5d11b31596b9b7d6306074abe3d5fcf09bd", size = 543026, upload-time = "2026-07-08T12:25:10.459Z" }, + { url = "https://files.pythonhosted.org/packages/c4/08/dcd9993ad192737a004ba263d549f8ea605b326b952e7d6205c7d4170b76/librt-0.13.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:66c0e7e6b02a155576df2c77ec933a70b72da726e248c494abf690923e624348", size = 546829, upload-time = "2026-07-08T12:25:11.716Z" }, + { url = "https://files.pythonhosted.org/packages/96/d5/6d9bb2f54e4109a956b7128836529653eb9d740f784bc47ed10a02c1000e/librt-0.13.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:ac04bcd3328eb91d99dfedf6a60d9c1f15d3434e6f6daf922f0420f7d90b85c7", size = 535700, upload-time = "2026-07-08T12:25:13.144Z" }, + { url = "https://files.pythonhosted.org/packages/8c/f2/10946922503858a359492fa27f13e86228bde702116a740ac7b3cd185f24/librt-0.13.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:db327e7271e653c32040b85ae6188059c924b57d7e1e29f935523fa017cd4e82", size = 573566, upload-time = "2026-07-08T12:25:14.336Z" }, + { url = "https://files.pythonhosted.org/packages/48/a8/94f00e3c99479a18088af3685ea016c42f3c7d5d1964d8dbb40c08d7f1aa/librt-0.13.0-cp312-cp312-win32.whl", hash = "sha256:860bd1d8ba48456ce08feaf8d343a8aaeb2fa086f2bcaa2a923fa3f7a3ff9aa3", size = 106099, upload-time = "2026-07-08T12:25:16.159Z" }, + { url = "https://files.pythonhosted.org/packages/c9/7b/2da9c74c1ed25a89cc4e1c8e007ea2eb4a0f1fafa3e70d757fe3242c5c5c/librt-0.13.0-cp312-cp312-win_amd64.whl", hash = "sha256:e54a315caf843c8d77e388cadc56ea9ded569935ee2d2347d7ea94992e5aa6fa", size = 126934, upload-time = "2026-07-08T12:25:17.275Z" }, + { url = "https://files.pythonhosted.org/packages/d0/65/aead61bbf3b5358593f9d4779d2a0e88eaf6ec191a6342dde36dd1df6371/librt-0.13.0-cp312-cp312-win_arm64.whl", hash = "sha256:c718e99a0992127af84385378460db624103b559ab260435abcfe77a4e4ed1c1", size = 112236, upload-time = "2026-07-08T12:25:18.425Z" }, + { url = "https://files.pythonhosted.org/packages/67/3b/18e7b63255297a2bdc9c25c8d6d4ca8eca9f63aceb1252c0f7427ac7099e/librt-0.13.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:a468951af16155824e88bdd8326ebe5bdb371f3ec0ac04642994b98201d914f3", size = 151027, upload-time = "2026-07-08T12:25:19.638Z" }, + { url = "https://files.pythonhosted.org/packages/4d/68/e2248452c00d1a03b45fee1752cdc8f790a476efd2402b75181da88a9e61/librt-0.13.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:ae01d8512cc17079e53425635327dbf3f7ff57a42c00dec348bf79791c56444c", size = 155152, upload-time = "2026-07-08T12:25:20.851Z" }, + { url = "https://files.pythonhosted.org/packages/0e/16/52b1c99bf19057a062aac39c900cbb81499f6f75d6c537c14463d247ba78/librt-0.13.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:32c26893cd085c1efe83219e78d866da23fb20a066101b8f68210004361d224c", size = 502499, upload-time = "2026-07-08T12:25:22.055Z" }, + { url = "https://files.pythonhosted.org/packages/9f/54/b811151805c795f55e0dedee6ec687b75f9982a8105d240ea3910737a77b/librt-0.13.0-cp313-cp313-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:5929da1981a46bcf4b28b1b9499905f0ff58e2419da402a048234e9783acbc4b", size = 496108, upload-time = "2026-07-08T12:25:23.296Z" }, + { url = "https://files.pythonhosted.org/packages/8f/f8/094d6b2bd93f3fdaa54db54cc788c4a365333bddad65ab02e04da0b1d004/librt-0.13.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:94b85d664d777bab6c0d709416cb42938251fda9e221b79e3a2215d85df5f4f9", size = 531576, upload-time = "2026-07-08T12:25:24.648Z" }, + { url = "https://files.pythonhosted.org/packages/2e/40/541733d5755824f968f7ec39d78ffbd75d145964157ae5e69a09ec6d7326/librt-0.13.0-cp313-cp313-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:531b2df3e9fe96b1fcf73a6d165921e4656be5f58d631d384ebce344298368db", size = 524390, upload-time = "2026-07-08T12:25:25.898Z" }, + { url = "https://files.pythonhosted.org/packages/c6/b5/255673cfdbf5ba663339d36cd863c897289ab4337577e19f9405ce059f36/librt-0.13.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:109b84a9edf69ad89dc1f66358659e14a031baca95e3e5b0060bd903ede8efd6", size = 543053, upload-time = "2026-07-08T12:25:27.436Z" }, + { url = "https://files.pythonhosted.org/packages/9e/11/ab5005e9c9850710f21e354201bf090646349d3fabf5f951eaf70235729e/librt-0.13.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:1304368a3e7ffc3e9db986796cc5326fdb5943a3567ecc137cff318e4240c0e7", size = 546387, upload-time = "2026-07-08T12:25:28.65Z" }, + { url = "https://files.pythonhosted.org/packages/a2/04/a5d7ce1d1df1afd15ca283dcdf7530ac073e12d69ae8c40879dda96f7868/librt-0.13.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:e4f9b472e7d308d94b62c801982065661158c6ed02790d6c7ddb4337cea0f9c1", size = 535970, upload-time = "2026-07-08T12:25:30.171Z" }, + { url = "https://files.pythonhosted.org/packages/5a/76/927e267a6daa290174ac281b23c9804c8829b042ade9c6f24a065f540958/librt-0.13.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:9f836c37478f167a81200d8c8b2c920a22224564bed2c23d7aeec760965c367a", size = 573582, upload-time = "2026-07-08T12:25:31.507Z" }, + { url = "https://files.pythonhosted.org/packages/10/24/b6c5213efe39c19f9e13605644d0cf063b4ddaa33ac2e45b088e23a70e2e/librt-0.13.0-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:4000d961ff9598ac6ea603c6c836a5ed49bc205ade5fc378b998dfe1e2c36628", size = 82189, upload-time = "2026-07-08T12:25:32.675Z" }, + { url = "https://files.pythonhosted.org/packages/4c/00/d29736be177a906ac0b84a5b04b4fbfa22c776dc2f366de4172b0f968c08/librt-0.13.0-cp313-cp313-win32.whl", hash = "sha256:79e44cff71750d299d61a678e49995b0d5935a9cda238c2574daeca3ba536927", size = 106193, upload-time = "2026-07-08T12:25:33.692Z" }, + { url = "https://files.pythonhosted.org/packages/c8/ac/aff6fb45393cb8912f39dfb156ef6b2d1cadb207ff465fc8f66141054be8/librt-0.13.0-cp313-cp313-win_amd64.whl", hash = "sha256:54dab44a847d5ad1acd05c8a83fe518ae685516ecf4d3f7cc6e3df2a66767650", size = 126962, upload-time = "2026-07-08T12:25:34.769Z" }, + { url = "https://files.pythonhosted.org/packages/d9/3a/d68cb2b334d53fd30fac81d3a489ce4ba0d9506f4df43fcf676b68352b19/librt-0.13.0-cp313-cp313-win_arm64.whl", hash = "sha256:d4cb6fbfdf874340ab5e51450753c0f817b6958a3621125ee695bbc3de866566", size = 112127, upload-time = "2026-07-08T12:25:35.981Z" }, + { url = "https://files.pythonhosted.org/packages/7b/66/f49ae0d592bd45b6941e9a8bafcb6a87cddcd501ee7874707e767f01b585/librt-0.13.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:25218d94b1d2cbc0ba1d8a3f9dc9af578d9646e5ed16443a70cde1dfdcce6d71", size = 149818, upload-time = "2026-07-08T12:25:37.203Z" }, + { url = "https://files.pythonhosted.org/packages/3d/50/51c76d74014d04fb95b6506d286808984b78a2f7a41039094e6b2194ac48/librt-0.13.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:f26629539d4893c2957a16c41bb058e1e135c1f150f6a2e25ed047f64cf3f5c6", size = 154071, upload-time = "2026-07-08T12:25:39.399Z" }, + { url = "https://files.pythonhosted.org/packages/b8/fe/f19b0f5f82d5a1f2da736586bc840abd00ce07d6388136ae80b7333883fc/librt-0.13.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a4517d47b2b8af26975a406fba7d314de9696d864252e0257c6ea90238cfe27f", size = 494168, upload-time = "2026-07-08T12:25:40.641Z" }, + { url = "https://files.pythonhosted.org/packages/94/bc/b8550c75775127fd31a5f20e8775997f7b527ad661fc8ddccd7497c064f7/librt-0.13.0-cp314-cp314-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:f19e181de5b3a1148bb3420b8c4b0b0ea0fce6950099724ad151d6cea5acc180", size = 491054, upload-time = "2026-07-08T12:25:41.905Z" }, + { url = "https://files.pythonhosted.org/packages/30/14/4d0204867623df3f33f86efd3d3692ba5e01321443f4d6eab35a22697618/librt-0.13.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22034924f5b42d5a56371cf271771bfeaabf235a7a8b6264bef2d20013f786c6", size = 523006, upload-time = "2026-07-08T12:25:43.327Z" }, + { url = "https://files.pythonhosted.org/packages/19/0a/c45fc9a260934696bace1ac5df1e148ac92bd71767aee3bf7cd7a4534f4c/librt-0.13.0-cp314-cp314-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c7897db4e95e22468bdda33d8e012ceacd0182abf001e6389d763f0def6286b9", size = 515058, upload-time = "2026-07-08T12:25:44.541Z" }, + { url = "https://files.pythonhosted.org/packages/13/0a/50c5ce45b326854ef8fa6ae4c36cf5142e5c55315eaf9e51d0ae73ac4da3/librt-0.13.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:1ce61b3746545029d4f5c17d6bd74b676254ad98433086c846ffb5e8fa73f007", size = 534025, upload-time = "2026-07-08T12:25:45.825Z" }, + { url = "https://files.pythonhosted.org/packages/89/2d/08c413c8f93fc13b8103624fce38e5caa86cd08cbbc8465870ab287af54b/librt-0.13.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:46c330e82565962c761dbce7941be2cff7db674ee807455a8d0cadc5f9b759b0", size = 540557, upload-time = "2026-07-08T12:25:47.059Z" }, + { url = "https://files.pythonhosted.org/packages/b3/c1/93af71fb4a364952210051811dd4e40174e79656b050c89cacac18af3330/librt-0.13.0-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:375f5af8f99cbaa99dd293af986e3d57caabc9ba81a5d3f021603764854197a1", size = 523201, upload-time = "2026-07-08T12:25:48.392Z" }, + { url = "https://files.pythonhosted.org/packages/c1/6e/9766f07b676a4889d9f8bc2864e9ba5fff165653143ef4dda7df6aa34d16/librt-0.13.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9320d34c3376ae204b2cd176e8d4883a013934e0aef822f1aed9c536490c275d", size = 565740, upload-time = "2026-07-08T12:25:49.678Z" }, + { url = "https://files.pythonhosted.org/packages/a2/1e/664e3472ce2b6e10e9b83f29d4a36eb982ff6b5a169ae7567bba3a4c4ff5/librt-0.13.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:9af313c66157a69dc69ea0059a66961692250e0dc95af9c385a48ffb770a0d16", size = 81611, upload-time = "2026-07-08T12:25:50.857Z" }, + { url = "https://files.pythonhosted.org/packages/2f/d4/8582a4d65e2234673685e07309d02c230b28a85724eb0acbf13f019b7f6e/librt-0.13.0-cp314-cp314-win32.whl", hash = "sha256:f2a7253458e34f33543551394ae4fe104b497ec2a65ac266074de64c1df82e37", size = 100106, upload-time = "2026-07-08T12:25:52.03Z" }, + { url = "https://files.pythonhosted.org/packages/63/ce/0cb99efe6086b46cd985dc26672166fae312a239690e75871f7fafbd3fc5/librt-0.13.0-cp314-cp314-win_amd64.whl", hash = "sha256:a3dfe4edf10e8ed7e55b026a8bfc2c2a8704218b659cd4bffdf604fab966dc39", size = 121209, upload-time = "2026-07-08T12:25:53.166Z" }, + { url = "https://files.pythonhosted.org/packages/26/85/4f3ccb083a3c9b0d42e223acdb3c3f507953324a59cdcab4826e8e2e3b89/librt-0.13.0-cp314-cp314-win_arm64.whl", hash = "sha256:68a5faee4bba381cb93b5961f684a514cf0053cb92308ff9c792c2fea0b174c6", size = 106404, upload-time = "2026-07-08T12:25:54.253Z" }, + { url = "https://files.pythonhosted.org/packages/b2/77/333191499538c8e8189de7a4cba8e6f49ee949fd6d6e6324b21fd1522466/librt-0.13.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:a38fb81d8376dfa2f8963b265fec07637802b0d01e2a127c19c66cb070fb24f5", size = 159231, upload-time = "2026-07-08T12:25:55.432Z" }, + { url = "https://files.pythonhosted.org/packages/7a/9e/2aa83758f22c278b837a1d8025898434ce2b8bff36678d5330ecaef56dff/librt-0.13.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:d4c8d9bd5abce34b2e75edb3bf37ab0f34e49b1f915a40ae8468eb7c85bc5b46", size = 161300, upload-time = "2026-07-08T12:25:56.585Z" }, + { url = "https://files.pythonhosted.org/packages/bb/c0/86791e936553ca763d6b3c2fb4d31d596cd00e14fa631c283a40ba01559a/librt-0.13.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:387e2f1d27e89bffe0d3f520f0da0662c973fd607ca16c1808f8a5085419485e", size = 582056, upload-time = "2026-07-08T12:25:58.144Z" }, + { url = "https://files.pythonhosted.org/packages/a8/d3/a9ec15984a185e000c4d2a16ba28bd623124ad4c38a10974c7ff78e3a893/librt-0.13.0-cp314-cp314t-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:4f6db193d2e5e0ed60359b9a5a682cd67205d0d3b1e459a867dd4b5c4e7eaa7a", size = 562758, upload-time = "2026-07-08T12:25:59.544Z" }, + { url = "https://files.pythonhosted.org/packages/3c/af/dbe36b78b19c06a55097f99305e4ea9458e2273e6ae16a3cbecaad7ee978/librt-0.13.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0d38604854e8d22faadf683ec6c02bb0f886e2ba56ef981a1c36ee275f21ea22", size = 602095, upload-time = "2026-07-08T12:26:00.991Z" }, + { url = "https://files.pythonhosted.org/packages/2a/a8/2966891b4dd2830f5203fbee92ac2c4947653a2390ba73dfa44244fad025/librt-0.13.0-cp314-cp314t-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:371f7ce73026815dafd51c50ce38416e91428b28c4b2ec97cd39271164b0045c", size = 593452, upload-time = "2026-07-08T12:26:02.352Z" }, + { url = "https://files.pythonhosted.org/packages/61/f5/4df8bfc8405ecf8c0d525b4d69636f694bdd8620b313ec8b76e54a5926cc/librt-0.13.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:3aaedf52171bee90860704c560bc798fe83b76247df47568e0197e9b13c735a0", size = 623729, upload-time = "2026-07-08T12:26:04.294Z" }, + { url = "https://files.pythonhosted.org/packages/d6/13/9ac202dffc8db06f75d06c08c2f9f6ff054be67d21272dcc078fa1cc0c57/librt-0.13.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:96bad8725a4f196a798366c25ce075d1f7543a4ec045ffc13e6a7ec095cdab04", size = 617077, upload-time = "2026-07-08T12:26:05.845Z" }, + { url = "https://files.pythonhosted.org/packages/6e/f0/ebe38610716aee5cb28efd95089bb90192096179802779381e1c5dcf239c/librt-0.13.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:6bf6a559ffe4a93bbea6cf31ddf01a7fd9ba342ef51f27beb178e318b74acd61", size = 599561, upload-time = "2026-07-08T12:26:07.21Z" }, + { url = "https://files.pythonhosted.org/packages/4f/5c/c2e72e236fff7abc716d5b1753b8b8cd3ea85ac46fe17d2e7c51d4e1c723/librt-0.13.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:301067672387902c55f94b51d5022304b36c966ea9fe1f21caab99a9bef487c9", size = 645511, upload-time = "2026-07-08T12:26:08.562Z" }, + { url = "https://files.pythonhosted.org/packages/0c/99/6203ce619dee940d6bfbe099ec3fe4be00a68e9d60f70abf906cf124fe66/librt-0.13.0-cp314-cp314t-win32.whl", hash = "sha256:5fdcf34f86de8fb66d7dc7589f96ba91c4aa46671200d400e6fd6f109a483f18", size = 104357, upload-time = "2026-07-08T12:26:09.828Z" }, + { url = "https://files.pythonhosted.org/packages/52/dd/843b6314087c41657c7036d7914d8f294bdf9b580aa8513ea0588c8e9a3d/librt-0.13.0-cp314-cp314t-win_amd64.whl", hash = "sha256:260c33e92263fa629b4f6d3c51967a1c2158fe6c33237aaa3ebeac586b085259", size = 126998, upload-time = "2026-07-08T12:26:10.975Z" }, + { url = "https://files.pythonhosted.org/packages/5f/5d/3dcec2884ba1b0806d1408612555c38dd5d68e90156b59f75f6e36435c3a/librt-0.13.0-cp314-cp314t-win_arm64.whl", hash = "sha256:2f281549a4c52ac7bb97997f14353f8bd0e53a34ca0dad1c905cfd0b4a58ae99", size = 110771, upload-time = "2026-07-08T12:26:12.303Z" }, +] + +[[package]] +name = "markdown" +version = "3.10.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2b/f4/69fa6ed85ae003c2378ffa8f6d2e3234662abd02c10d216c0ba96081a238/markdown-3.10.2.tar.gz", hash = "sha256:994d51325d25ad8aa7ce4ebaec003febcce822c3f8c911e3b17c52f7f589f950", size = 368805, upload-time = "2026-02-09T14:57:26.942Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/1f/77fa3081e4f66ca3576c896ae5d31c3002ac6607f9747d2e3aa49227e464/markdown-3.10.2-py3-none-any.whl", hash = "sha256:e91464b71ae3ee7afd3017d9f358ef0baf158fd9a298db92f1d4761133824c36", size = 108180, upload-time = "2026-02-09T14:57:25.787Z" }, +] + +[[package]] +name = "markdown-exec" +version = "1.12.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pymdown-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6d/76/c47da8edb6a12b066728432fb3724109d9d91de5331df5073d12d272493f/markdown_exec-1.12.3.tar.gz", hash = "sha256:006b9cac46470a9499797bc9c579305ae4719e0a8e495e5401dfbf1e66ce7fb4", size = 77841, upload-time = "2026-07-07T09:53:13.838Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ad/a7/0279016386d611183ccc508c5688eb1e2133e8182164d7a2c6213b176f69/markdown_exec-1.12.3-py3-none-any.whl", hash = "sha256:48ac12a565f3f4331b1acd9efc48a0773e717eb7ca7c38e23c1d72ee61660de6", size = 37995, upload-time = "2026-07-07T09:53:12.619Z" }, +] + +[package.optional-dependencies] +ansi = [ + { name = "pygments-ansi-color" }, +] + +[[package]] +name = "markdown-it-py" +version = "4.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mdurl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/ff/7841249c247aa650a76b9ee4bbaeae59370dc8bfd2f6c01f3630c35eb134/markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49", size = 82454, upload-time = "2026-05-07T12:08:28.36Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/81/4da04ced5a082363ecfa159c010d200ecbd959ae410c10c0264a38cac0f5/markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a", size = 91687, upload-time = "2026-05-07T12:08:27.182Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5a/72/147da192e38635ada20e0a2e1a51cf8823d2119ce8883f7053879c2199b5/markupsafe-3.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e", size = 11615, upload-time = "2025-09-27T18:36:30.854Z" }, + { url = "https://files.pythonhosted.org/packages/9a/81/7e4e08678a1f98521201c3079f77db69fb552acd56067661f8c2f534a718/markupsafe-3.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce", size = 12020, upload-time = "2025-09-27T18:36:31.971Z" }, + { url = "https://files.pythonhosted.org/packages/1e/2c/799f4742efc39633a1b54a92eec4082e4f815314869865d876824c257c1e/markupsafe-3.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d", size = 24332, upload-time = "2025-09-27T18:36:32.813Z" }, + { url = "https://files.pythonhosted.org/packages/3c/2e/8d0c2ab90a8c1d9a24f0399058ab8519a3279d1bd4289511d74e909f060e/markupsafe-3.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d", size = 22947, upload-time = "2025-09-27T18:36:33.86Z" }, + { url = "https://files.pythonhosted.org/packages/2c/54/887f3092a85238093a0b2154bd629c89444f395618842e8b0c41783898ea/markupsafe-3.0.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a", size = 21962, upload-time = "2025-09-27T18:36:35.099Z" }, + { url = "https://files.pythonhosted.org/packages/c9/2f/336b8c7b6f4a4d95e91119dc8521402461b74a485558d8f238a68312f11c/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b", size = 23760, upload-time = "2025-09-27T18:36:36.001Z" }, + { url = "https://files.pythonhosted.org/packages/32/43/67935f2b7e4982ffb50a4d169b724d74b62a3964bc1a9a527f5ac4f1ee2b/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f", size = 21529, upload-time = "2025-09-27T18:36:36.906Z" }, + { url = "https://files.pythonhosted.org/packages/89/e0/4486f11e51bbba8b0c041098859e869e304d1c261e59244baa3d295d47b7/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b", size = 23015, upload-time = "2025-09-27T18:36:37.868Z" }, + { url = "https://files.pythonhosted.org/packages/2f/e1/78ee7a023dac597a5825441ebd17170785a9dab23de95d2c7508ade94e0e/markupsafe-3.0.3-cp312-cp312-win32.whl", hash = "sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d", size = 14540, upload-time = "2025-09-27T18:36:38.761Z" }, + { url = "https://files.pythonhosted.org/packages/aa/5b/bec5aa9bbbb2c946ca2733ef9c4ca91c91b6a24580193e891b5f7dbe8e1e/markupsafe-3.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c", size = 15105, upload-time = "2025-09-27T18:36:39.701Z" }, + { url = "https://files.pythonhosted.org/packages/e5/f1/216fc1bbfd74011693a4fd837e7026152e89c4bcf3e77b6692fba9923123/markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f", size = 13906, upload-time = "2025-09-27T18:36:40.689Z" }, + { url = "https://files.pythonhosted.org/packages/38/2f/907b9c7bbba283e68f20259574b13d005c121a0fa4c175f9bed27c4597ff/markupsafe-3.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e1cf1972137e83c5d4c136c43ced9ac51d0e124706ee1c8aa8532c1287fa8795", size = 11622, upload-time = "2025-09-27T18:36:41.777Z" }, + { url = "https://files.pythonhosted.org/packages/9c/d9/5f7756922cdd676869eca1c4e3c0cd0df60ed30199ffd775e319089cb3ed/markupsafe-3.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:116bb52f642a37c115f517494ea5feb03889e04df47eeff5b130b1808ce7c219", size = 12029, upload-time = "2025-09-27T18:36:43.257Z" }, + { url = "https://files.pythonhosted.org/packages/00/07/575a68c754943058c78f30db02ee03a64b3c638586fba6a6dd56830b30a3/markupsafe-3.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:133a43e73a802c5562be9bbcd03d090aa5a1fe899db609c29e8c8d815c5f6de6", size = 24374, upload-time = "2025-09-27T18:36:44.508Z" }, + { url = "https://files.pythonhosted.org/packages/a9/21/9b05698b46f218fc0e118e1f8168395c65c8a2c750ae2bab54fc4bd4e0e8/markupsafe-3.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccfcd093f13f0f0b7fdd0f198b90053bf7b2f02a3927a30e63f3ccc9df56b676", size = 22980, upload-time = "2025-09-27T18:36:45.385Z" }, + { url = "https://files.pythonhosted.org/packages/7f/71/544260864f893f18b6827315b988c146b559391e6e7e8f7252839b1b846a/markupsafe-3.0.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:509fa21c6deb7a7a273d629cf5ec029bc209d1a51178615ddf718f5918992ab9", size = 21990, upload-time = "2025-09-27T18:36:46.916Z" }, + { url = "https://files.pythonhosted.org/packages/c2/28/b50fc2f74d1ad761af2f5dcce7492648b983d00a65b8c0e0cb457c82ebbe/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a4afe79fb3de0b7097d81da19090f4df4f8d3a2b3adaa8764138aac2e44f3af1", size = 23784, upload-time = "2025-09-27T18:36:47.884Z" }, + { url = "https://files.pythonhosted.org/packages/ed/76/104b2aa106a208da8b17a2fb72e033a5a9d7073c68f7e508b94916ed47a9/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:795e7751525cae078558e679d646ae45574b47ed6e7771863fcc079a6171a0fc", size = 21588, upload-time = "2025-09-27T18:36:48.82Z" }, + { url = "https://files.pythonhosted.org/packages/b5/99/16a5eb2d140087ebd97180d95249b00a03aa87e29cc224056274f2e45fd6/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8485f406a96febb5140bfeca44a73e3ce5116b2501ac54fe953e488fb1d03b12", size = 23041, upload-time = "2025-09-27T18:36:49.797Z" }, + { url = "https://files.pythonhosted.org/packages/19/bc/e7140ed90c5d61d77cea142eed9f9c303f4c4806f60a1044c13e3f1471d0/markupsafe-3.0.3-cp313-cp313-win32.whl", hash = "sha256:bdd37121970bfd8be76c5fb069c7751683bdf373db1ed6c010162b2a130248ed", size = 14543, upload-time = "2025-09-27T18:36:51.584Z" }, + { url = "https://files.pythonhosted.org/packages/05/73/c4abe620b841b6b791f2edc248f556900667a5a1cf023a6646967ae98335/markupsafe-3.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5", size = 15113, upload-time = "2025-09-27T18:36:52.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/3a/fa34a0f7cfef23cf9500d68cb7c32dd64ffd58a12b09225fb03dd37d5b80/markupsafe-3.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:7e68f88e5b8799aa49c85cd116c932a1ac15caaa3f5db09087854d218359e485", size = 13911, upload-time = "2025-09-27T18:36:53.513Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d7/e05cd7efe43a88a17a37b3ae96e79a19e846f3f456fe79c57ca61356ef01/markupsafe-3.0.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:218551f6df4868a8d527e3062d0fb968682fe92054e89978594c28e642c43a73", size = 11658, upload-time = "2025-09-27T18:36:54.819Z" }, + { url = "https://files.pythonhosted.org/packages/99/9e/e412117548182ce2148bdeacdda3bb494260c0b0184360fe0d56389b523b/markupsafe-3.0.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:3524b778fe5cfb3452a09d31e7b5adefeea8c5be1d43c4f810ba09f2ceb29d37", size = 12066, upload-time = "2025-09-27T18:36:55.714Z" }, + { url = "https://files.pythonhosted.org/packages/bc/e6/fa0ffcda717ef64a5108eaa7b4f5ed28d56122c9a6d70ab8b72f9f715c80/markupsafe-3.0.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4e885a3d1efa2eadc93c894a21770e4bc67899e3543680313b09f139e149ab19", size = 25639, upload-time = "2025-09-27T18:36:56.908Z" }, + { url = "https://files.pythonhosted.org/packages/96/ec/2102e881fe9d25fc16cb4b25d5f5cde50970967ffa5dddafdb771237062d/markupsafe-3.0.3-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8709b08f4a89aa7586de0aadc8da56180242ee0ada3999749b183aa23df95025", size = 23569, upload-time = "2025-09-27T18:36:57.913Z" }, + { url = "https://files.pythonhosted.org/packages/4b/30/6f2fce1f1f205fc9323255b216ca8a235b15860c34b6798f810f05828e32/markupsafe-3.0.3-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b8512a91625c9b3da6f127803b166b629725e68af71f8184ae7e7d54686a56d6", size = 23284, upload-time = "2025-09-27T18:36:58.833Z" }, + { url = "https://files.pythonhosted.org/packages/58/47/4a0ccea4ab9f5dcb6f79c0236d954acb382202721e704223a8aafa38b5c8/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9b79b7a16f7fedff2495d684f2b59b0457c3b493778c9eed31111be64d58279f", size = 24801, upload-time = "2025-09-27T18:36:59.739Z" }, + { url = "https://files.pythonhosted.org/packages/6a/70/3780e9b72180b6fecb83a4814d84c3bf4b4ae4bf0b19c27196104149734c/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:12c63dfb4a98206f045aa9563db46507995f7ef6d83b2f68eda65c307c6829eb", size = 22769, upload-time = "2025-09-27T18:37:00.719Z" }, + { url = "https://files.pythonhosted.org/packages/98/c5/c03c7f4125180fc215220c035beac6b9cb684bc7a067c84fc69414d315f5/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8f71bc33915be5186016f675cd83a1e08523649b0e33efdb898db577ef5bb009", size = 23642, upload-time = "2025-09-27T18:37:01.673Z" }, + { url = "https://files.pythonhosted.org/packages/80/d6/2d1b89f6ca4bff1036499b1e29a1d02d282259f3681540e16563f27ebc23/markupsafe-3.0.3-cp313-cp313t-win32.whl", hash = "sha256:69c0b73548bc525c8cb9a251cddf1931d1db4d2258e9599c28c07ef3580ef354", size = 14612, upload-time = "2025-09-27T18:37:02.639Z" }, + { url = "https://files.pythonhosted.org/packages/2b/98/e48a4bfba0a0ffcf9925fe2d69240bfaa19c6f7507b8cd09c70684a53c1e/markupsafe-3.0.3-cp313-cp313t-win_amd64.whl", hash = "sha256:1b4b79e8ebf6b55351f0d91fe80f893b4743f104bff22e90697db1590e47a218", size = 15200, upload-time = "2025-09-27T18:37:03.582Z" }, + { url = "https://files.pythonhosted.org/packages/0e/72/e3cc540f351f316e9ed0f092757459afbc595824ca724cbc5a5d4263713f/markupsafe-3.0.3-cp313-cp313t-win_arm64.whl", hash = "sha256:ad2cf8aa28b8c020ab2fc8287b0f823d0a7d8630784c31e9ee5edea20f406287", size = 13973, upload-time = "2025-09-27T18:37:04.929Z" }, + { url = "https://files.pythonhosted.org/packages/33/8a/8e42d4838cd89b7dde187011e97fe6c3af66d8c044997d2183fbd6d31352/markupsafe-3.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe", size = 11619, upload-time = "2025-09-27T18:37:06.342Z" }, + { url = "https://files.pythonhosted.org/packages/b5/64/7660f8a4a8e53c924d0fa05dc3a55c9cee10bbd82b11c5afb27d44b096ce/markupsafe-3.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026", size = 12029, upload-time = "2025-09-27T18:37:07.213Z" }, + { url = "https://files.pythonhosted.org/packages/da/ef/e648bfd021127bef5fa12e1720ffed0c6cbb8310c8d9bea7266337ff06de/markupsafe-3.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737", size = 24408, upload-time = "2025-09-27T18:37:09.572Z" }, + { url = "https://files.pythonhosted.org/packages/41/3c/a36c2450754618e62008bf7435ccb0f88053e07592e6028a34776213d877/markupsafe-3.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97", size = 23005, upload-time = "2025-09-27T18:37:10.58Z" }, + { url = "https://files.pythonhosted.org/packages/bc/20/b7fdf89a8456b099837cd1dc21974632a02a999ec9bf7ca3e490aacd98e7/markupsafe-3.0.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d", size = 22048, upload-time = "2025-09-27T18:37:11.547Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a7/591f592afdc734f47db08a75793a55d7fbcc6902a723ae4cfbab61010cc5/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda", size = 23821, upload-time = "2025-09-27T18:37:12.48Z" }, + { url = "https://files.pythonhosted.org/packages/7d/33/45b24e4f44195b26521bc6f1a82197118f74df348556594bd2262bda1038/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf", size = 21606, upload-time = "2025-09-27T18:37:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/ff/0e/53dfaca23a69fbfbbf17a4b64072090e70717344c52eaaaa9c5ddff1e5f0/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe", size = 23043, upload-time = "2025-09-27T18:37:14.408Z" }, + { url = "https://files.pythonhosted.org/packages/46/11/f333a06fc16236d5238bfe74daccbca41459dcd8d1fa952e8fbd5dccfb70/markupsafe-3.0.3-cp314-cp314-win32.whl", hash = "sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9", size = 14747, upload-time = "2025-09-27T18:37:15.36Z" }, + { url = "https://files.pythonhosted.org/packages/28/52/182836104b33b444e400b14f797212f720cbc9ed6ba34c800639d154e821/markupsafe-3.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581", size = 15341, upload-time = "2025-09-27T18:37:16.496Z" }, + { url = "https://files.pythonhosted.org/packages/6f/18/acf23e91bd94fd7b3031558b1f013adfa21a8e407a3fdb32745538730382/markupsafe-3.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4", size = 14073, upload-time = "2025-09-27T18:37:17.476Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f0/57689aa4076e1b43b15fdfa646b04653969d50cf30c32a102762be2485da/markupsafe-3.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab", size = 11661, upload-time = "2025-09-27T18:37:18.453Z" }, + { url = "https://files.pythonhosted.org/packages/89/c3/2e67a7ca217c6912985ec766c6393b636fb0c2344443ff9d91404dc4c79f/markupsafe-3.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175", size = 12069, upload-time = "2025-09-27T18:37:19.332Z" }, + { url = "https://files.pythonhosted.org/packages/f0/00/be561dce4e6ca66b15276e184ce4b8aec61fe83662cce2f7d72bd3249d28/markupsafe-3.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634", size = 25670, upload-time = "2025-09-27T18:37:20.245Z" }, + { url = "https://files.pythonhosted.org/packages/50/09/c419f6f5a92e5fadde27efd190eca90f05e1261b10dbd8cbcb39cd8ea1dc/markupsafe-3.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50", size = 23598, upload-time = "2025-09-27T18:37:21.177Z" }, + { url = "https://files.pythonhosted.org/packages/22/44/a0681611106e0b2921b3033fc19bc53323e0b50bc70cffdd19f7d679bb66/markupsafe-3.0.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e", size = 23261, upload-time = "2025-09-27T18:37:22.167Z" }, + { url = "https://files.pythonhosted.org/packages/5f/57/1b0b3f100259dc9fffe780cfb60d4be71375510e435efec3d116b6436d43/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5", size = 24835, upload-time = "2025-09-27T18:37:23.296Z" }, + { url = "https://files.pythonhosted.org/packages/26/6a/4bf6d0c97c4920f1597cc14dd720705eca0bf7c787aebc6bb4d1bead5388/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523", size = 22733, upload-time = "2025-09-27T18:37:24.237Z" }, + { url = "https://files.pythonhosted.org/packages/14/c7/ca723101509b518797fedc2fdf79ba57f886b4aca8a7d31857ba3ee8281f/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc", size = 23672, upload-time = "2025-09-27T18:37:25.271Z" }, + { url = "https://files.pythonhosted.org/packages/fb/df/5bd7a48c256faecd1d36edc13133e51397e41b73bb77e1a69deab746ebac/markupsafe-3.0.3-cp314-cp314t-win32.whl", hash = "sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d", size = 14819, upload-time = "2025-09-27T18:37:26.285Z" }, + { url = "https://files.pythonhosted.org/packages/1a/8a/0402ba61a2f16038b48b39bccca271134be00c5c9f0f623208399333c448/markupsafe-3.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9", size = 15426, upload-time = "2025-09-27T18:37:27.316Z" }, + { url = "https://files.pythonhosted.org/packages/70/bc/6f1c2f612465f5fa89b95bead1f44dcb607670fd42891d8fdcd5d039f4f4/markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa", size = 14146, upload-time = "2025-09-27T18:37:28.327Z" }, +] + +[[package]] +name = "mdurl" +version = "0.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, +] + +[[package]] +name = "mergedeep" +version = "1.3.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3a/41/580bb4006e3ed0361b8151a01d324fb03f420815446c7def45d02f74c270/mergedeep-1.3.4.tar.gz", hash = "sha256:0096d52e9dad9939c3d975a774666af186eda617e6ca84df4c94dec30004f2a8", size = 4661, upload-time = "2021-02-05T18:55:30.623Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/19/04f9b178c2d8a15b076c8b5140708fa6ffc5601fb6f1e975537072df5b2a/mergedeep-1.3.4-py3-none-any.whl", hash = "sha256:70775750742b25c0d8f36c55aed03d24c3384d17c951b3175d898bd778ef0307", size = 6354, upload-time = "2021-02-05T18:55:29.583Z" }, +] + +[[package]] +name = "mike" +version = "2.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jinja2" }, + { name = "mkdocs" }, + { name = "pyparsing" }, + { name = "pyyaml" }, + { name = "pyyaml-env-tag" }, + { name = "verspec" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b4/47/fa87e9d56bef16cdfe34b059a437e8c6f7ec6f1b9c378871c3cf95ebea9c/mike-2.2.0.tar.gz", hash = "sha256:1e3858e32c0f125aac14432fc7848434358f9ae0962c5c5cde387ad47f6ad25e", size = 38450, upload-time = "2026-04-14T04:59:03.944Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/76/8e/56ccb09c7232a55403a7637caa21922f3b65901a37f5e8bdb405d0de0946/mike-2.2.0-py3-none-any.whl", hash = "sha256:e1f4981c1152eec7c2490a3401142292cc47d686194188416db2648fdfe1d040", size = 34026, upload-time = "2026-04-14T04:59:02.602Z" }, +] + +[[package]] +name = "mkdocs" +version = "1.6.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "ghp-import" }, + { name = "jinja2" }, + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mergedeep" }, + { name = "mkdocs-get-deps" }, + { name = "packaging" }, + { name = "pathspec" }, + { name = "pyyaml" }, + { name = "pyyaml-env-tag" }, + { name = "watchdog" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bc/c6/bbd4f061bd16b378247f12953ffcb04786a618ce5e904b8c5a01a0309061/mkdocs-1.6.1.tar.gz", hash = "sha256:7b432f01d928c084353ab39c57282f29f92136665bdd6abf7c1ec8d822ef86f2", size = 3889159, upload-time = "2024-08-30T12:24:06.899Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/5b/dbc6a8cddc9cfa9c4971d59fb12bb8d42e161b7e7f8cc89e49137c5b279c/mkdocs-1.6.1-py3-none-any.whl", hash = "sha256:db91759624d1647f3f34aa0c3f327dd2601beae39a366d6e064c03468d35c20e", size = 3864451, upload-time = "2024-08-30T12:24:05.054Z" }, +] + +[[package]] +name = "mkdocs-autorefs" +version = "1.4.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mkdocs" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/52/c0/f641843de3f612a6b48253f39244165acff36657a91cc903633d456ae1ac/mkdocs_autorefs-1.4.4.tar.gz", hash = "sha256:d54a284f27a7346b9c38f1f852177940c222da508e66edc816a0fa55fc6da197", size = 56588, upload-time = "2026-02-10T15:23:55.105Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/28/de/a3e710469772c6a89595fc52816da05c1e164b4c866a89e3cb82fb1b67c5/mkdocs_autorefs-1.4.4-py3-none-any.whl", hash = "sha256:834ef5408d827071ad1bc69e0f39704fa34c7fc05bc8e1c72b227dfdc5c76089", size = 25530, upload-time = "2026-02-10T15:23:53.817Z" }, +] + +[[package]] +name = "mkdocs-get-deps" +version = "0.2.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mergedeep" }, + { name = "platformdirs" }, + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ce/25/b3cccb187655b9393572bde9b09261d267c3bf2f2cdabe347673be5976a6/mkdocs_get_deps-0.2.2.tar.gz", hash = "sha256:8ee8d5f316cdbbb2834bc1df6e69c08fe769a83e040060de26d3c19fad3599a1", size = 11047, upload-time = "2026-03-10T02:46:33.632Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/29/744136411e785c4b0b744d5413e56555265939ab3a104c6a4b719dad33fd/mkdocs_get_deps-0.2.2-py3-none-any.whl", hash = "sha256:e7878cbeac04860b8b5e0ca31d3abad3df9411a75a32cde82f8e44b6c16ff650", size = 9555, upload-time = "2026-03-10T02:46:32.256Z" }, +] + +[[package]] +name = "mkdocs-material" +version = "9.7.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "babel" }, + { name = "backrefs" }, + { name = "colorama" }, + { name = "jinja2" }, + { name = "markdown" }, + { name = "mkdocs" }, + { name = "mkdocs-material-extensions" }, + { name = "paginate" }, + { name = "pygments" }, + { name = "pymdown-extensions" }, + { name = "requests" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f1/cd/c05d3a530ba7934f144fb45f7203cd236adc25c7bdcc34673d202f4b0278/mkdocs_material-9.7.7.tar.gz", hash = "sha256:c0649c065b1b0512d60aad8c10f947f8e455284475239b364b610f2deb4d0855", size = 4097923, upload-time = "2026-07-17T16:21:33.156Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ad/21/17c1bc9e6f47c972ad66fb2ac2568f99f90f1207eeb6fc3b34d094dba7b5/mkdocs_material-9.7.7-py3-none-any.whl", hash = "sha256:8ea9bb1737a5b524a5f9dcf2e1b4ebda8274ae3008aa7845720a97083bef708f", size = 9305438, upload-time = "2026-07-17T16:21:30.017Z" }, +] + +[package.optional-dependencies] +imaging = [ + { name = "cairosvg" }, + { name = "pillow" }, +] + +[[package]] +name = "mkdocs-material-extensions" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/79/9b/9b4c96d6593b2a541e1cb8b34899a6d021d208bb357042823d4d2cabdbe7/mkdocs_material_extensions-1.3.1.tar.gz", hash = "sha256:10c9511cea88f568257f960358a467d12b970e1f7b2c0e5fb2bb48cab1928443", size = 11847, upload-time = "2023-11-22T19:09:45.208Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5b/54/662a4743aa81d9582ee9339d4ffa3c8fd40a4965e033d77b9da9774d3960/mkdocs_material_extensions-1.3.1-py3-none-any.whl", hash = "sha256:adff8b62700b25cb77b53358dad940f3ef973dd6db797907c49e3c2ef3ab4e31", size = 8728, upload-time = "2023-11-22T19:09:43.465Z" }, +] + +[[package]] +name = "mkdocs-redirects" +version = "1.2.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mkdocs" }, + { name = "properdocs" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/73/25/49725f78ca5d3026b09973f7a2b3a8b179cc2e8c15e43d5a13bc79f6b274/mkdocs_redirects-1.2.3.tar.gz", hash = "sha256:5e980330999299729a2d6a125347d1af78023d68a23681a4de3053ce7dfe2e51", size = 7712, upload-time = "2026-03-28T13:57:41.766Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c6/90/871b1cddc01d2ba1637b858eeeabc2e3013dc8df591306b5567b98ef0870/mkdocs_redirects-1.2.3-py3-none-any.whl", hash = "sha256:ec7312fff462d03ec16395d0c001006a418f8d0c21cdf2b47ff11cf839dc3ce0", size = 6245, upload-time = "2026-03-28T13:57:40.466Z" }, +] + +[[package]] +name = "mkdocstrings" +version = "1.0.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jinja2" }, + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mkdocs" }, + { name = "mkdocs-autorefs" }, + { name = "pymdown-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/53/71/f85bdf13355073ae15a7375f09879375a830553552e58c1c4b7e0bbc5c8b/mkdocstrings-1.0.6.tar.gz", hash = "sha256:a0b8c2bdd29a6416c80d717aa369bbf7831946bd9f23c2a66db1b1dbe7693dbd", size = 100649, upload-time = "2026-07-11T19:38:05.732Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/5b/4c1902e8bdd5c4db63284e9d101dece4038d4025d6d88850ffe0a1578980/mkdocstrings-1.0.6-py3-none-any.whl", hash = "sha256:2703708697487d1b6d6d7b412e176fa436edf120c1bf81dc9e126b12d00893c7", size = 35787, upload-time = "2026-07-11T19:38:04.417Z" }, +] + +[[package]] +name = "mkdocstrings-python" +version = "2.0.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "griffelib" }, + { name = "mkdocs-autorefs" }, + { name = "mkdocstrings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/b6/e858701499d57eee8b3fd8e78168083956c6683ddbe727b46758b19e1119/mkdocstrings_python-2.0.5.tar.gz", hash = "sha256:3a4d92556ad39637e88af94a5374213af9a8e3040c3824ceaed04b486c017594", size = 199578, upload-time = "2026-06-19T10:41:08.868Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/fc/10ab7e80650a9c9e8f4f1105f8c8e73567f88ed0c06ada589ab81d38687c/mkdocstrings_python-2.0.5-py3-none-any.whl", hash = "sha256:30c837bbff016549f659fcba6539ac351303f0fd7e713c89a040611072236e9d", size = 104951, upload-time = "2026-06-19T10:41:07.378Z" }, +] + +[[package]] +name = "moto" +version = "5.2.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "boto3" }, + { name = "botocore" }, + { name = "cryptography" }, + { name = "requests" }, + { name = "responses" }, + { name = "werkzeug" }, + { name = "xmltodict" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/47/63/d944f387582cc53f53febbff2b3fa36a6d2ed7c1feef8990bf646cfa9cba/moto-5.2.2.tar.gz", hash = "sha256:aac8023a429e125e91c91f8f4730a67b54f518cda587352f7e67252fe3168f75", size = 8678761, upload-time = "2026-06-06T18:57:54.931Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/45/13cff46f4f617a6e97e1d497d75abd913e250bb4c823a4985668c6e593e4/moto-5.2.2-py3-none-any.whl", hash = "sha256:3817f1e39721ca833579b921e53e3b68547ace6a34d848c9486fbb5905808de9", size = 6698689, upload-time = "2026-06-06T18:57:51.435Z" }, +] + +[package.optional-dependencies] +s3 = [ + { name = "py-partiql-parser" }, + { name = "pyyaml" }, +] +server = [ + { name = "antlr4-python3-runtime" }, + { name = "aws-xray-sdk" }, + { name = "cfn-lint" }, + { name = "docker" }, + { name = "flask" }, + { name = "flask-cors" }, + { name = "graphql-core" }, + { name = "joserfc" }, + { name = "jsonpath-ng" }, + { name = "openapi-spec-validator" }, + { name = "py-partiql-parser" }, + { name = "pyparsing" }, + { name = "pyyaml" }, + { name = "setuptools" }, +] + +[[package]] +name = "mpmath" +version = "1.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106, upload-time = "2023-03-07T16:47:11.061Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" }, +] + +[[package]] +name = "msgpack" +version = "1.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/31/f9/c0a1c127f9049db9155afc316952ea571720dd01833ff5e4d7e8e6352dbb/msgpack-1.2.1.tar.gz", hash = "sha256:04c721c2c7448767e9e3f2520a475663d8ee0f09c31890f6d2bd70fd636a9647", size = 183960, upload-time = "2026-06-18T16:13:52.594Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bc/dd/9e8cbd8f5582ca4b590336f2b91ee5662f6a6ca562b565abaf696a0f81ff/msgpack-1.2.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2ef59c659f289eddf8aa6623823f19fa2f40a4029266889eac7a2505dd210c35", size = 83531, upload-time = "2026-06-18T16:12:58.249Z" }, + { url = "https://files.pythonhosted.org/packages/50/2e/ebdb85a8da151397a2790363676b7ed7c125924fe618e4c6d8befb0cc62c/msgpack-1.2.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d3567748a5107cb40cdf66a275430c2f87c07777698f4bfd25c35f44d533258c", size = 82657, upload-time = "2026-06-18T16:12:59.396Z" }, + { url = "https://files.pythonhosted.org/packages/26/aa/753ad8b007b464e1d8aa0c8e650b9c5f4f725e658fc5ac8a7635c55b7f6e/msgpack-1.2.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:60926b75d00c8e816ef98f3034f484a8bc64242d66839cef4cf7e503142316a0", size = 410634, upload-time = "2026-06-18T16:13:00.383Z" }, + { url = "https://files.pythonhosted.org/packages/6a/fd/6adabd4f6d5e686f97dd02ce7fce3fe4cf672cbac36b8f67ff4040e8ad8b/msgpack-1.2.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:020e881a764b20d8d7ca1a54fc01b8175519d108e3c3f194fddc200bda95951a", size = 419989, upload-time = "2026-06-18T16:13:01.776Z" }, + { url = "https://files.pythonhosted.org/packages/5a/cc/85039b7b0eb168aaad7383a23c97e291a11f08351cb45a606ce865e4e3f1/msgpack-1.2.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4202c74688ca06591f78cb18988228bd4cca2cc75d57b60008372892d2f1e6e6", size = 377544, upload-time = "2026-06-18T16:13:03.637Z" }, + { url = "https://files.pythonhosted.org/packages/ed/bf/35963899493b32030c85fc513b723ae66144ac70c11ebc52e889e16e3d99/msgpack-1.2.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8b267ce94efb76fbd1b3373511420074ee3187f0f7811bf394531de13294735a", size = 400842, upload-time = "2026-06-18T16:13:05.012Z" }, + { url = "https://files.pythonhosted.org/packages/a6/df/8e2ac970c8f99264cd9997d1c73df5466bc19da3301d7dc5500862a9b089/msgpack-1.2.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:e4f1d0f8f98ade9634e01fb704a408f9336c0a8f1117b369f5db83dc7551d8b1", size = 374108, upload-time = "2026-06-18T16:13:06.232Z" }, + { url = "https://files.pythonhosted.org/packages/17/dd/fa8bd265110dfa51c20cb529f9e6d240a16fafe7e645004c6af2d01353ba/msgpack-1.2.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f02cf17a6ca1abe29b5f980644f7551f94d71f2011509b26d8625ce038f0df64", size = 414939, upload-time = "2026-06-18T16:13:07.478Z" }, + { url = "https://files.pythonhosted.org/packages/2e/b9/8377a5ad8953fc0437c70cc98d9ae29f27fe5ac5109fbec0812085865735/msgpack-1.2.1-cp312-cp312-win32.whl", hash = "sha256:0c0d9802354507bcba62af19c17918e3eb437cc25e6f50657d511b5856a77aac", size = 64504, upload-time = "2026-06-18T16:13:08.822Z" }, + { url = "https://files.pythonhosted.org/packages/57/7f/ce1e377df7e62461fefd9eb23bfb93a4a523f40a517b377b8f844d836828/msgpack-1.2.1-cp312-cp312-win_amd64.whl", hash = "sha256:5c24aa15d5963051e1a5c62b12c50cd705992502b5ec1f3bece6046f33c9fc24", size = 71421, upload-time = "2026-06-18T16:13:09.828Z" }, + { url = "https://files.pythonhosted.org/packages/8f/32/ebfe84c9929f08f188d56c7a2fd913406a9ddad76a634697c1c43b8112e6/msgpack-1.2.1-cp312-cp312-win_arm64.whl", hash = "sha256:4227224aaec8f7fbcbfbd4272319347b2bb4030366502600f8c45588c5187b07", size = 64775, upload-time = "2026-06-18T16:13:11.056Z" }, + { url = "https://files.pythonhosted.org/packages/b0/ac/dcddcab6f6c20ecb387ca5e980371cdb3f87ff69aeca388be97eebc4c074/msgpack-1.2.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0a70e3cf2804a300d921bb0940426e35f4e489a23adfb77a808892241db0a064", size = 83151, upload-time = "2026-06-18T16:13:12.173Z" }, + { url = "https://files.pythonhosted.org/packages/64/71/fbcfa83a1d6a9c6091942d1cfd070962244664b87427a9a49a6897b1b219/msgpack-1.2.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:491cc39455ca765fad51fb451bf2915eb2cf41192ab5801ce8d67c1d614fe056", size = 82351, upload-time = "2026-06-18T16:13:13.194Z" }, + { url = "https://files.pythonhosted.org/packages/e3/10/ddf7b06db879e8792d13934ddda09ff20bd2a583fd84c9b59aae9b0e650b/msgpack-1.2.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f310233ef7fb9c14e201c93639fe5f5260b005f56f0b29048e999c30935596cc", size = 407518, upload-time = "2026-06-18T16:13:14.233Z" }, + { url = "https://files.pythonhosted.org/packages/79/d3/36a46a8ed992b781acbc05928bd5bee3c810cb0c3563bf81a7b0c04a1a76/msgpack-1.2.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:787c9bebb5833e8f6fc8abca3c0597683d8d87f56a8842b6b89c75a5f3176e2d", size = 416405, upload-time = "2026-06-18T16:13:15.435Z" }, + { url = "https://files.pythonhosted.org/packages/f9/84/e8e9598b557c0ba6ddae901a73780a4c75ac667dddf59414b1e56a42fb34/msgpack-1.2.1-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:dc871b997a9370d855b7394465f2f350e847a5b806dd38dcc9c989e7d87da155", size = 376257, upload-time = "2026-06-18T16:13:17.022Z" }, + { url = "https://files.pythonhosted.org/packages/40/16/738fe6d875ad7e2a9429c165322a4ec088f4f273cdfae63d96a89c467961/msgpack-1.2.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:85f57e960d877f2977f6430896191b04a21f8901b3b4baf2e4604329f4db5402", size = 397469, upload-time = "2026-06-18T16:13:18.287Z" }, + { url = "https://files.pythonhosted.org/packages/ca/be/6d5952df75a7f24f35833af764c3a6860780364cb3a0030beb8099e1b2b4/msgpack-1.2.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:1233ee2dd0cefba127583de50ea654677277047d238303521db35def3d7b2e7c", size = 372802, upload-time = "2026-06-18T16:13:19.685Z" }, + { url = "https://files.pythonhosted.org/packages/e1/39/e2ef7dbf0473bcb8dc7c50bf782a892d67414877b63e47fc88eb189ef5e6/msgpack-1.2.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e3dc2feb0876209d9c38aa56cb1de169bd6c4348f1aa48271f241226590993e6", size = 411273, upload-time = "2026-06-18T16:13:21.028Z" }, + { url = "https://files.pythonhosted.org/packages/ef/c5/133f4512a56e983a93445c836c9d94d88f3bc2e0980ff4b9e577bd8416ce/msgpack-1.2.1-cp313-cp313-win32.whl", hash = "sha256:6d09badf350af2be9d189184e04e64cf54ad93569ab3d96fca58bd3e84aad707", size = 64471, upload-time = "2026-06-18T16:13:22.293Z" }, + { url = "https://files.pythonhosted.org/packages/e2/98/577e10b055096a7dd40732358cabaf7180a20c79ed1dcdbb618e4b9deac7/msgpack-1.2.1-cp313-cp313-win_amd64.whl", hash = "sha256:33f14fba63278b714efe6ad07e50ea5f03d91537aa6a1c5f1ceca4cf44013ca9", size = 71274, upload-time = "2026-06-18T16:13:23.455Z" }, + { url = "https://files.pythonhosted.org/packages/ba/ee/0c0048e7cfbef23c6a94791b8959ab28155232e7956de8a305b5ff588f05/msgpack-1.2.1-cp313-cp313-win_arm64.whl", hash = "sha256:afc5febcd4c99effbc02b528e49d6fd0760b2b7d48c05239e345a5fa6e743d9a", size = 64795, upload-time = "2026-06-18T16:13:24.687Z" }, + { url = "https://files.pythonhosted.org/packages/77/58/cce442852c6b9e1639c7c8ac8fd9143121cb32dab0f308df4d1426a8eb9c/msgpack-1.2.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:05f340e47e7e47d2da8db9b53e1bb1d294369e9ef45a747441309f6650b8351d", size = 83610, upload-time = "2026-06-18T16:13:25.724Z" }, + { url = "https://files.pythonhosted.org/packages/60/5c/15b4c7a0182f75ffa90751958ba36a9c01cafee367d49a3edc10ed140b01/msgpack-1.2.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:810b916696c86ef0deb3b74588480224df4c1b071136c34183e4a2a4284d7ac7", size = 83138, upload-time = "2026-06-18T16:13:26.781Z" }, + { url = "https://files.pythonhosted.org/packages/b8/a6/99e58722feaffc5f2fbcc0c8c0d1451ab9f84097f7af87291b46af2390f4/msgpack-1.2.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ca0dacff965c47afdc3749a8469d7302a8f801d6a28758d55120d75e66ce6889", size = 406090, upload-time = "2026-06-18T16:13:28.072Z" }, + { url = "https://files.pythonhosted.org/packages/19/03/8c63e8cf52958534ef688625965ab04c269a6cadd8caef16758b380a821a/msgpack-1.2.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0e2bf9280bceb5efca998435904b5d3e9fdbcc11d90dc9df30aec7973252b720", size = 412106, upload-time = "2026-06-18T16:13:29.427Z" }, + { url = "https://files.pythonhosted.org/packages/63/d2/155d9e71b40e41fd934bc0c48b9b2770f22263e1ac20aad8e29fdca7be3f/msgpack-1.2.1-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:aa6c4be5d1c02a42b066ca6ddb71adf36432868fdcdb6ee87e634e86e0674190", size = 374851, upload-time = "2026-06-18T16:13:30.631Z" }, + { url = "https://files.pythonhosted.org/packages/98/48/deaf2326262a8d5ea3295ce9649912ecd3f551ba7ec8e33c665d2ba583f3/msgpack-1.2.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ec0e675d59150a6269ddc9139087c722292664a37d071a849c05c473350f1f2d", size = 396168, upload-time = "2026-06-18T16:13:31.977Z" }, + { url = "https://files.pythonhosted.org/packages/10/2a/b4410f906c2ec0008f1608d3ab5143afc3ad3f4e6da0fed3ea2231d0bef4/msgpack-1.2.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:dd3bfe82d53edfe4b7fc9a7ec9761e23a7a5b1dac22264505af428253c29ed24", size = 371959, upload-time = "2026-06-18T16:13:33.282Z" }, + { url = "https://files.pythonhosted.org/packages/59/86/1edc67270099a528fa2093ea60fe191233cd238e4bd30cfacf7db79fc959/msgpack-1.2.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5ad5467fc3f68b5468e06c5f788d712e9f8ffc8b0cd1bcb160c105c1ee92dae7", size = 408457, upload-time = "2026-06-18T16:13:34.567Z" }, + { url = "https://files.pythonhosted.org/packages/82/90/8b630fef07d8c5ab457b71ff2c217910c83d333c7a68472c186e87cc504a/msgpack-1.2.1-cp314-cp314-win32.whl", hash = "sha256:98b58bdb89c46190e4609bb36abe17c6d4105ad13f9c5f8f6f64d320f8ced3fb", size = 65942, upload-time = "2026-06-18T16:13:36.056Z" }, + { url = "https://files.pythonhosted.org/packages/16/f1/467b81e98b24dd3885d7b1857728797b4ffc76a7a7483af4fb321a07de3c/msgpack-1.2.1-cp314-cp314-win_amd64.whl", hash = "sha256:74847557e28ce71bd3c438a447ca90e4b507e997ddbdef8a12a7b283b86c156b", size = 72627, upload-time = "2026-06-18T16:13:37.079Z" }, + { url = "https://files.pythonhosted.org/packages/a7/1d/5d8c4c89985feb6acefb82a09e501c60392261856d2408d20bfe4f0360b1/msgpack-1.2.1-cp314-cp314-win_arm64.whl", hash = "sha256:b50b727bd652bdc37d950336c848ef20ec54a4cafc38dce19b1cd86ad625d0f7", size = 66908, upload-time = "2026-06-18T16:13:38.23Z" }, + { url = "https://files.pythonhosted.org/packages/1b/02/ad2afb678b4de94496cd432b581759b756a92c1192d8c767edd6b132efdc/msgpack-1.2.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:8d00f177ca88a77c1cf848d204a38f249751650b601cb6532acc68805d8a8273", size = 86000, upload-time = "2026-06-18T16:13:39.44Z" }, + { url = "https://files.pythonhosted.org/packages/54/74/0b797484013128837f3b1cbb6cea019277c4de4e377dc512b4d9a0f92940/msgpack-1.2.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5bb9c386f0a329c035ddbab4b72d1028bf9627add8dda41070288563d57ed1b1", size = 86544, upload-time = "2026-06-18T16:13:40.447Z" }, + { url = "https://files.pythonhosted.org/packages/a9/b4/b774d7eb95561739907fec675582f83203cf41c597a418c2589b4bfb8e9d/msgpack-1.2.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20466cca18c49c7292a8984bc15d65857b171e7264bdcb5f96baf8be238791fc", size = 427661, upload-time = "2026-06-18T16:13:41.574Z" }, + { url = "https://files.pythonhosted.org/packages/b2/f9/3243191dc9937e00756c8bc1b0272fed8f23758e43df2a3b46f533e5090f/msgpack-1.2.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:196300e7e5d6e74d50f1607ab9c06c4a1484c383cd22defd727902591f7e8dde", size = 426375, upload-time = "2026-06-18T16:13:42.936Z" }, + { url = "https://files.pythonhosted.org/packages/23/c7/1693111db9944ba4ad4b67a1e788400d78a0b6af7a6523dc7e4e58f8274b/msgpack-1.2.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:575957e79cd51903a4e8495a242442949641e08f1efd5197b43bebd3ea7682b4", size = 380495, upload-time = "2026-06-18T16:13:44.306Z" }, + { url = "https://files.pythonhosted.org/packages/3e/2b/92f86956a0c13e8662f7e2ad630c4eb4db07497b967589bd5245e018b2c1/msgpack-1.2.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8c2ed1e48cc0f460bf3c7780e7137ff21a4e18433451916f2442c1b21036cd7d", size = 410897, upload-time = "2026-06-18T16:13:45.629Z" }, + { url = "https://files.pythonhosted.org/packages/da/ea/1479f72d200313a76fc2f823a79d1e07ed052ab7b8a0280640aa7b95de42/msgpack-1.2.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:5f6277e5f783c36786a145e0247fc189a03f35f84b251646e53592d2bc12b355", size = 378519, upload-time = "2026-06-18T16:13:46.998Z" }, + { url = "https://files.pythonhosted.org/packages/f5/4d/fa006060ffa1011d32bfae826fe766fe73e02982183601633b7121058ab3/msgpack-1.2.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f9389552ecf4784886345ead0647e4edc96bee37cbab05b75540f542f766c48c", size = 419815, upload-time = "2026-06-18T16:13:48.205Z" }, + { url = "https://files.pythonhosted.org/packages/2f/e1/aab6c946570496b78e67804721f3d5e2d62a93081b9b37df77764ef56347/msgpack-1.2.1-cp314-cp314t-win32.whl", hash = "sha256:c1c79a604a2969a868a78b6ebd27a887e00c624f14f66b3038e0590cb23332d1", size = 70914, upload-time = "2026-06-18T16:13:49.385Z" }, + { url = "https://files.pythonhosted.org/packages/13/0a/e608956488a2af014cfe6e3d665e090b8ee42aa14b07f8f95b8880d66b09/msgpack-1.2.1-cp314-cp314t-win_amd64.whl", hash = "sha256:f12038a35fabd52e56a3547bab42401af49a45caa6dd00b34c44de235bc93ee2", size = 77999, upload-time = "2026-06-18T16:13:50.467Z" }, + { url = "https://files.pythonhosted.org/packages/d2/8a/27e2e57055176e366a46b85d02d68e7a5bcfbdd8474c9706375d965f24d3/msgpack-1.2.1-cp314-cp314t-win_arm64.whl", hash = "sha256:0adcf06ffde0777c0e1a9b771a2b1c4226ba1bbf748c8efcc02fcdeca3299107", size = 71160, upload-time = "2026-06-18T16:13:51.498Z" }, +] + +[[package]] +name = "msgspec" +version = "0.21.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/60/f79b9b013a16fa3a58350c9295ddc6789f2e335f36ea61ed10a21b215364/msgspec-0.21.1.tar.gz", hash = "sha256:2313508e394b0d208f8f56892ca9b2799e2561329de9763b19619595a6c0f72c", size = 319193, upload-time = "2026-04-12T21:44:50.394Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6e/cf/317224852c00248c620a9bcf4b26e2e4ab8afd752f18d2a6ef73ebd423b6/msgspec-0.21.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d4248cf0b6129b7d230eacd493c17cc2d4f3989f3bb7f633a928a85b7dcfa251", size = 196188, upload-time = "2026-04-12T21:44:07.181Z" }, + { url = "https://files.pythonhosted.org/packages/6d/81/074612945c0666078f7366f40000013de9f6ba687491d450df699bceebc9/msgspec-0.21.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:5102c7e9b3acff82178449b85006d96310e690291bb1ea0142f1b24bcb8aabcb", size = 188473, upload-time = "2026-04-12T21:44:08.736Z" }, + { url = "https://files.pythonhosted.org/packages/8a/37/655101799590bcc5fddb2bd3fe0e6194e816c2d1da7c361725f5eb89a910/msgspec-0.21.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:846758412e9518252b2ac9bffd6f0e54d9ff614f5f9488df7749f81ff5c80920", size = 218871, upload-time = "2026-04-12T21:44:09.917Z" }, + { url = "https://files.pythonhosted.org/packages/b5/d1/d4cd9fe89c7d400d7a18f86ccc94daa3f0927f53558846fcb60791dce5d6/msgspec-0.21.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:21995e74b5c598c2e004110ad66ec7f1b8c20bf2bcf3b2de8fd9a3094422d3ff", size = 225025, upload-time = "2026-04-12T21:44:11.191Z" }, + { url = "https://files.pythonhosted.org/packages/24/bf/e20549e602b9edccadeeff98760345a416f9cce846a657e8b18e3396b212/msgspec-0.21.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6129f0cca52992e898fd5344187f7c8127b63d810b2fd73e36fca73b4c6475ee", size = 222672, upload-time = "2026-04-12T21:44:12.481Z" }, + { url = "https://files.pythonhosted.org/packages/b4/68/04d7a8f0f786545cf9b8c280c57aa6befb5977af6e884b8b54191cbe44b3/msgspec-0.21.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ef3ec2296248d1f8b9231acb051b6d471dfde8f21819e86c9adaaa9f42918521", size = 227303, upload-time = "2026-04-12T21:44:13.709Z" }, + { url = "https://files.pythonhosted.org/packages/cc/4d/619866af2840875be408047bf9e70ceafbae6ab50660de7134ed1b25eb86/msgspec-0.21.1-cp312-cp312-win_amd64.whl", hash = "sha256:d4ab834a054c6f0cbeef6df9e7e1b33d5f1bc7b86dea1d2fd7cad003873e783d", size = 190017, upload-time = "2026-04-12T21:44:14.977Z" }, + { url = "https://files.pythonhosted.org/packages/5e/2e/a8f9eca8fd00e097d7a9e99ba8a4685db994494448e3d4f0b7f6e9a3c0f7/msgspec-0.21.1-cp312-cp312-win_arm64.whl", hash = "sha256:628aaa35c74950a8c59da330d7e98917e1c7188f983745782027748ee4ca573e", size = 175345, upload-time = "2026-04-12T21:44:16.431Z" }, + { url = "https://files.pythonhosted.org/packages/7e/74/f11ede02839b19ff459f88e3145df5d711626ca84da4e23520cebf819367/msgspec-0.21.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:764173717a01743f007e9f74520ed281f24672c604514f7d76c1c3a10e8edb66", size = 196176, upload-time = "2026-04-12T21:44:17.613Z" }, + { url = "https://files.pythonhosted.org/packages/bb/40/4476c1bd341418a046c4955aff632ec769315d1e3cb94e6acf86d461f9ed/msgspec-0.21.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:344c7cd0eaed1fb81d7959f99100ef71ec9b536881a376f11b9a6c4803365697", size = 188524, upload-time = "2026-04-12T21:44:18.815Z" }, + { url = "https://files.pythonhosted.org/packages/ca/d9/9e9d7d7e5061b47540d03d640fab9b3965ba7ae49c1b2154861c8f007518/msgspec-0.21.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:48943e278b3854c2f89f955ddc6f9f430d3f0784b16e47d10604ee0463cd21f5", size = 218880, upload-time = "2026-04-12T21:44:20.028Z" }, + { url = "https://files.pythonhosted.org/packages/74/66/2bb344f34abb4b57e60c7c9c761994e0417b9718ec1460bf00c296f2a7ea/msgspec-0.21.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a9aa659ebb0101b1cbc31461212b87e341d961f0ab0772aaf068a99e001ec4aa", size = 225050, upload-time = "2026-04-12T21:44:21.577Z" }, + { url = "https://files.pythonhosted.org/packages/1a/84/7c1e412f76092277bf760cef12b7979d03314d259ab5b5cafde5d0c1722d/msgspec-0.21.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7b27d1a8ead2b6f5b0c4f2d07b8be1ccfcc041c8a0e704781edebe3ae13c484", size = 222713, upload-time = "2026-04-12T21:44:22.83Z" }, + { url = "https://files.pythonhosted.org/packages/4e/27/0bba04b2b4ef05f3d068429410bc71d2cea925f1596a8f41152cccd5edb8/msgspec-0.21.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:38fe93e86b61328fe544cb7fd871fad5a27c8734bfda90f65e5dbe288ae50f61", size = 227259, upload-time = "2026-04-12T21:44:24.11Z" }, + { url = "https://files.pythonhosted.org/packages/b0/2d/09574b0eea02fed2c2c1383dbaae2c7f79dc16dcd6487a886000afb5d7c4/msgspec-0.21.1-cp313-cp313-win_amd64.whl", hash = "sha256:8bc666331c35fcce05a7cd2d6221adbe0f6058f8e750711413d22793c080ac6a", size = 189857, upload-time = "2026-04-12T21:44:25.359Z" }, + { url = "https://files.pythonhosted.org/packages/46/34/105b1576ad182879914f0c821f17ee1d13abb165cb060448f96fe2aff078/msgspec-0.21.1-cp313-cp313-win_arm64.whl", hash = "sha256:42bb1241e0750c1a4346f2aa84db26c5ffd99a4eb3a954927d9f149ff2f42898", size = 175403, upload-time = "2026-04-12T21:44:26.608Z" }, + { url = "https://files.pythonhosted.org/packages/5a/ad/86954e987d1d6a5c579e2c2e7832b65e0fff194179fdac4f581536086024/msgspec-0.21.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:fab48eb45fdbfbdb2c0edfec00ffc53b6b6085beefc6b50b61e01659f9f8757f", size = 196261, upload-time = "2026-04-12T21:44:27.807Z" }, + { url = "https://files.pythonhosted.org/packages/d1/a1/c5e46c3e42b866199365e35d11dddfd1fbd8bba4fdb3c52f965b1607ce94/msgspec-0.21.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:3cb779ea0c35bc807ff941d415875c1f69ca0be91a2e907ab99a171811d86a9a", size = 188729, upload-time = "2026-04-12T21:44:28.99Z" }, + { url = "https://files.pythonhosted.org/packages/85/7d/1e29a319d678d6cb962ae5bdf32a6858ebdf38f73bc654c0e9c742a0c2c8/msgspec-0.21.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:68604db36b3b4dd9bf160e436e12798a4738848144cea1aca1cb984011eb160f", size = 219866, upload-time = "2026-04-12T21:44:31.104Z" }, + { url = "https://files.pythonhosted.org/packages/25/1f/cca084ca2572810fff12ea9dbdcbe39eac048f40daf4a9077b49fcbe8cee/msgspec-0.21.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3d6b9dc50948eaf65df54d2fd0ff66e6d8c32f116037209ee861810eb9b676cb", size = 224993, upload-time = "2026-04-12T21:44:32.649Z" }, + { url = "https://files.pythonhosted.org/packages/71/94/d2120fc9d419a89a3a7c13e5b7078798c4b392a96a02a6e2b3ce43a8766c/msgspec-0.21.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:52c5e21930942302394429c5a582ce7e6b62c7f983b3760834c2ce107e0dd6df", size = 223535, upload-time = "2026-04-12T21:44:33.839Z" }, + { url = "https://files.pythonhosted.org/packages/75/17/42418b66a3ad972a89bab73dd78b79cc6282bb488a25e73c853cee7443b9/msgspec-0.21.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:abbb39d65681fa24ed394e01af3d59d869068324f900c61d06062b7fb9980f2f", size = 227222, upload-time = "2026-04-12T21:44:35.093Z" }, + { url = "https://files.pythonhosted.org/packages/c4/33/265c894268cca88ff67b144ca2b4c522fc8b9a6f1966a3640c70516e78e1/msgspec-0.21.1-cp314-cp314-win_amd64.whl", hash = "sha256:5666b1b560b97b6ec2eb3fca8a502298ebac56e13bbca1f88523538ce83d01ea", size = 193810, upload-time = "2026-04-12T21:44:36.612Z" }, + { url = "https://files.pythonhosted.org/packages/3b/8f/a6d35f25bf1fc63c492fdd88fdce01ba0875ead48c2b91f90f33653b4131/msgspec-0.21.1-cp314-cp314-win_arm64.whl", hash = "sha256:d8b8578e4c83b14ceea4cef0d0b747e31d9330fe4b03b2b2ad4063866a178f93", size = 179125, upload-time = "2026-04-12T21:44:38.198Z" }, + { url = "https://files.pythonhosted.org/packages/c6/39/74839641e64b99d87da55af0fc472854d42b46e2183b9e2a67fe1bb2a512/msgspec-0.21.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:15f523d51c00ebad412213bfe9f06f0a50ec2b93e0c19e824a2d267cabb48ea2", size = 200171, upload-time = "2026-04-12T21:44:39.414Z" }, + { url = "https://files.pythonhosted.org/packages/70/9b/ce0cca6d2d87fcd4b6ff97600790494e64f26a2c55d61507cd2755c16193/msgspec-0.21.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:4e47390360583ba3d5c6cb44cf0a9f61b0a06a899d3c2c00627cedebb2e2884b", size = 192879, upload-time = "2026-04-12T21:44:40.882Z" }, + { url = "https://files.pythonhosted.org/packages/a7/08/673a7bb05e5702dc787ddd3011195b509f9867927970da59052211929987/msgspec-0.21.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f60800e6299b798142dc40b0644da77ceac5ea0568be58228417eae14135c847", size = 226281, upload-time = "2026-04-12T21:44:42.181Z" }, + { url = "https://files.pythonhosted.org/packages/7d/45/86508cf57283e9070b3c447e3ab25b792a7a0855a3ea4e0c6d111ac34c97/msgspec-0.21.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5f8e9dfcd98419cf7568808470c4317a3fb30bef0e3715b568730a2b272a20d7", size = 229863, upload-time = "2026-04-12T21:44:43.442Z" }, + { url = "https://files.pythonhosted.org/packages/2c/62/e7c9367cd08d590559faacd711edbae36840342843e669440363f33c7d36/msgspec-0.21.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:92d89dfad13bd1ea640dc3e37e724ed380da1030b272bdf5ecafb983c3ad7c75", size = 230445, upload-time = "2026-04-12T21:44:44.806Z" }, + { url = "https://files.pythonhosted.org/packages/42/b4/c0f54632103846b658a10930025f4de41c8724b5e4805a5f3b395586cb7e/msgspec-0.21.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:0d03867786e5d7ba25d666df4b11320c27170f4aeafcb8e3a8b0a50a4fb742ca", size = 231822, upload-time = "2026-04-12T21:44:46.343Z" }, + { url = "https://files.pythonhosted.org/packages/ea/1d/0d85cc79d0ccf5508e9c846cc66552a6a16bf92abd1dbd8362617f7b35cd/msgspec-0.21.1-cp314-cp314t-win_amd64.whl", hash = "sha256:740fbf1c9d59992ca3537d6fbe9ebbf9eaf726a65fbf31448e0ecbc710697a63", size = 206650, upload-time = "2026-04-12T21:44:47.601Z" }, + { url = "https://files.pythonhosted.org/packages/90/91/56c5d560f20e6c20e9e4f55bd0e458f7f162aa689ee350346c04c48eac0b/msgspec-0.21.1-cp314-cp314t-win_arm64.whl", hash = "sha256:0d2cc73df6058d811a126ac3a8ad63a4dfa210c82f9cf5a004802eaf4712de90", size = 183149, upload-time = "2026-04-12T21:44:48.833Z" }, +] + +[[package]] +name = "multidict" +version = "6.7.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1a/c2/c2d94cbe6ac1753f3fc980da97b3d930efe1da3af3c9f5125354436c073d/multidict-6.7.1.tar.gz", hash = "sha256:ec6652a1bee61c53a3e5776b6049172c53b6aaba34f18c9ad04f82712bac623d", size = 102010, upload-time = "2026-01-26T02:46:45.979Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8d/9c/f20e0e2cf80e4b2e4b1c365bf5fe104ee633c751a724246262db8f1a0b13/multidict-6.7.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:a90f75c956e32891a4eda3639ce6dd86e87105271f43d43442a3aedf3cddf172", size = 76893, upload-time = "2026-01-26T02:43:52.754Z" }, + { url = "https://files.pythonhosted.org/packages/fe/cf/18ef143a81610136d3da8193da9d80bfe1cb548a1e2d1c775f26b23d024a/multidict-6.7.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3fccb473e87eaa1382689053e4a4618e7ba7b9b9b8d6adf2027ee474597128cd", size = 45456, upload-time = "2026-01-26T02:43:53.893Z" }, + { url = "https://files.pythonhosted.org/packages/a9/65/1caac9d4cd32e8433908683446eebc953e82d22b03d10d41a5f0fefe991b/multidict-6.7.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b0fa96985700739c4c7853a43c0b3e169360d6855780021bfc6d0f1ce7c123e7", size = 43872, upload-time = "2026-01-26T02:43:55.041Z" }, + { url = "https://files.pythonhosted.org/packages/cf/3b/d6bd75dc4f3ff7c73766e04e705b00ed6dbbaccf670d9e05a12b006f5a21/multidict-6.7.1-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:cb2a55f408c3043e42b40cc8eecd575afa27b7e0b956dfb190de0f8499a57a53", size = 251018, upload-time = "2026-01-26T02:43:56.198Z" }, + { url = "https://files.pythonhosted.org/packages/fd/80/c959c5933adedb9ac15152e4067c702a808ea183a8b64cf8f31af8ad3155/multidict-6.7.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eb0ce7b2a32d09892b3dd6cc44877a0d02a33241fafca5f25c8b6b62374f8b75", size = 258883, upload-time = "2026-01-26T02:43:57.499Z" }, + { url = "https://files.pythonhosted.org/packages/86/85/7ed40adafea3d4f1c8b916e3b5cc3a8e07dfcdcb9cd72800f4ed3ca1b387/multidict-6.7.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c3a32d23520ee37bf327d1e1a656fec76a2edd5c038bf43eddfa0572ec49c60b", size = 242413, upload-time = "2026-01-26T02:43:58.755Z" }, + { url = "https://files.pythonhosted.org/packages/d2/57/b8565ff533e48595503c785f8361ff9a4fde4d67de25c207cd0ba3befd03/multidict-6.7.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9c90fed18bffc0189ba814749fdcc102b536e83a9f738a9003e569acd540a733", size = 268404, upload-time = "2026-01-26T02:44:00.216Z" }, + { url = "https://files.pythonhosted.org/packages/e0/50/9810c5c29350f7258180dfdcb2e52783a0632862eb334c4896ac717cebcb/multidict-6.7.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:da62917e6076f512daccfbbde27f46fed1c98fee202f0559adec8ee0de67f71a", size = 269456, upload-time = "2026-01-26T02:44:02.202Z" }, + { url = "https://files.pythonhosted.org/packages/f3/8d/5e5be3ced1d12966fefb5c4ea3b2a5b480afcea36406559442c6e31d4a48/multidict-6.7.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bfde23ef6ed9db7eaee6c37dcec08524cb43903c60b285b172b6c094711b3961", size = 256322, upload-time = "2026-01-26T02:44:03.56Z" }, + { url = "https://files.pythonhosted.org/packages/31/6e/d8a26d81ac166a5592782d208dd90dfdc0a7a218adaa52b45a672b46c122/multidict-6.7.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3758692429e4e32f1ba0df23219cd0b4fc0a52f476726fff9337d1a57676a582", size = 253955, upload-time = "2026-01-26T02:44:04.845Z" }, + { url = "https://files.pythonhosted.org/packages/59/4c/7c672c8aad41534ba619bcd4ade7a0dc87ed6b8b5c06149b85d3dd03f0cd/multidict-6.7.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:398c1478926eca669f2fd6a5856b6de9c0acf23a2cb59a14c0ba5844fa38077e", size = 251254, upload-time = "2026-01-26T02:44:06.133Z" }, + { url = "https://files.pythonhosted.org/packages/7b/bd/84c24de512cbafbdbc39439f74e967f19570ce7924e3007174a29c348916/multidict-6.7.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:c102791b1c4f3ab36ce4101154549105a53dc828f016356b3e3bcae2e3a039d3", size = 252059, upload-time = "2026-01-26T02:44:07.518Z" }, + { url = "https://files.pythonhosted.org/packages/fa/ba/f5449385510825b73d01c2d4087bf6d2fccc20a2d42ac34df93191d3dd03/multidict-6.7.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:a088b62bd733e2ad12c50dad01b7d0166c30287c166e137433d3b410add807a6", size = 263588, upload-time = "2026-01-26T02:44:09.382Z" }, + { url = "https://files.pythonhosted.org/packages/d7/11/afc7c677f68f75c84a69fe37184f0f82fce13ce4b92f49f3db280b7e92b3/multidict-6.7.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:3d51ff4785d58d3f6c91bdbffcb5e1f7ddfda557727043aa20d20ec4f65e324a", size = 259642, upload-time = "2026-01-26T02:44:10.73Z" }, + { url = "https://files.pythonhosted.org/packages/2b/17/ebb9644da78c4ab36403739e0e6e0e30ebb135b9caf3440825001a0bddcb/multidict-6.7.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fc5907494fccf3e7d3f94f95c91d6336b092b5fc83811720fae5e2765890dfba", size = 251377, upload-time = "2026-01-26T02:44:12.042Z" }, + { url = "https://files.pythonhosted.org/packages/ca/a4/840f5b97339e27846c46307f2530a2805d9d537d8b8bd416af031cad7fa0/multidict-6.7.1-cp312-cp312-win32.whl", hash = "sha256:28ca5ce2fd9716631133d0e9a9b9a745ad7f60bac2bccafb56aa380fc0b6c511", size = 41887, upload-time = "2026-01-26T02:44:14.245Z" }, + { url = "https://files.pythonhosted.org/packages/80/31/0b2517913687895f5904325c2069d6a3b78f66cc641a86a2baf75a05dcbb/multidict-6.7.1-cp312-cp312-win_amd64.whl", hash = "sha256:fcee94dfbd638784645b066074b338bc9cc155d4b4bffa4adce1615c5a426c19", size = 46053, upload-time = "2026-01-26T02:44:15.371Z" }, + { url = "https://files.pythonhosted.org/packages/0c/5b/aba28e4ee4006ae4c7df8d327d31025d760ffa992ea23812a601d226e682/multidict-6.7.1-cp312-cp312-win_arm64.whl", hash = "sha256:ba0a9fb644d0c1a2194cf7ffb043bd852cea63a57f66fbd33959f7dae18517bf", size = 43307, upload-time = "2026-01-26T02:44:16.852Z" }, + { url = "https://files.pythonhosted.org/packages/f2/22/929c141d6c0dba87d3e1d38fbdf1ba8baba86b7776469f2bc2d3227a1e67/multidict-6.7.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:2b41f5fed0ed563624f1c17630cb9941cf2309d4df00e494b551b5f3e3d67a23", size = 76174, upload-time = "2026-01-26T02:44:18.509Z" }, + { url = "https://files.pythonhosted.org/packages/c7/75/bc704ae15fee974f8fccd871305e254754167dce5f9e42d88a2def741a1d/multidict-6.7.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:84e61e3af5463c19b67ced91f6c634effb89ef8bfc5ca0267f954451ed4bb6a2", size = 45116, upload-time = "2026-01-26T02:44:19.745Z" }, + { url = "https://files.pythonhosted.org/packages/79/76/55cd7186f498ed080a18440c9013011eb548f77ae1b297206d030eb1180a/multidict-6.7.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:935434b9853c7c112eee7ac891bc4cb86455aa631269ae35442cb316790c1445", size = 43524, upload-time = "2026-01-26T02:44:21.571Z" }, + { url = "https://files.pythonhosted.org/packages/e9/3c/414842ef8d5a1628d68edee29ba0e5bcf235dbfb3ccd3ea303a7fe8c72ff/multidict-6.7.1-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:432feb25a1cb67fe82a9680b4d65fb542e4635cb3166cd9c01560651ad60f177", size = 249368, upload-time = "2026-01-26T02:44:22.803Z" }, + { url = "https://files.pythonhosted.org/packages/f6/32/befed7f74c458b4a525e60519fe8d87eef72bb1e99924fa2b0f9d97a221e/multidict-6.7.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e82d14e3c948952a1a85503817e038cba5905a3352de76b9a465075d072fba23", size = 256952, upload-time = "2026-01-26T02:44:24.306Z" }, + { url = "https://files.pythonhosted.org/packages/03/d6/c878a44ba877f366630c860fdf74bfb203c33778f12b6ac274936853c451/multidict-6.7.1-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:4cfb48c6ea66c83bcaaf7e4dfa7ec1b6bbcf751b7db85a328902796dfde4c060", size = 240317, upload-time = "2026-01-26T02:44:25.772Z" }, + { url = "https://files.pythonhosted.org/packages/68/49/57421b4d7ad2e9e60e25922b08ceb37e077b90444bde6ead629095327a6f/multidict-6.7.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1d540e51b7e8e170174555edecddbd5538105443754539193e3e1061864d444d", size = 267132, upload-time = "2026-01-26T02:44:27.648Z" }, + { url = "https://files.pythonhosted.org/packages/b7/fe/ec0edd52ddbcea2a2e89e174f0206444a61440b40f39704e64dc807a70bd/multidict-6.7.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:273d23f4b40f3dce4d6c8a821c741a86dec62cded82e1175ba3d99be128147ed", size = 268140, upload-time = "2026-01-26T02:44:29.588Z" }, + { url = "https://files.pythonhosted.org/packages/b0/73/6e1b01cbeb458807aa0831742232dbdd1fa92bfa33f52a3f176b4ff3dc11/multidict-6.7.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9d624335fd4fa1c08a53f8b4be7676ebde19cd092b3895c421045ca87895b429", size = 254277, upload-time = "2026-01-26T02:44:30.902Z" }, + { url = "https://files.pythonhosted.org/packages/6a/b2/5fb8c124d7561a4974c342bc8c778b471ebbeb3cc17df696f034a7e9afe7/multidict-6.7.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:12fad252f8b267cc75b66e8fc51b3079604e8d43a75428ffe193cd9e2195dfd6", size = 252291, upload-time = "2026-01-26T02:44:32.31Z" }, + { url = "https://files.pythonhosted.org/packages/5a/96/51d4e4e06bcce92577fcd488e22600bd38e4fd59c20cb49434d054903bd2/multidict-6.7.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:03ede2a6ffbe8ef936b92cb4529f27f42be7f56afcdab5ab739cd5f27fb1cbf9", size = 250156, upload-time = "2026-01-26T02:44:33.734Z" }, + { url = "https://files.pythonhosted.org/packages/db/6b/420e173eec5fba721a50e2a9f89eda89d9c98fded1124f8d5c675f7a0c0f/multidict-6.7.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:90efbcf47dbe33dcf643a1e400d67d59abeac5db07dc3f27d6bdeae497a2198c", size = 249742, upload-time = "2026-01-26T02:44:35.222Z" }, + { url = "https://files.pythonhosted.org/packages/44/a3/ec5b5bd98f306bc2aa297b8c6f11a46714a56b1e6ef5ebda50a4f5d7c5fb/multidict-6.7.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:5c4b9bfc148f5a91be9244d6264c53035c8a0dcd2f51f1c3c6e30e30ebaa1c84", size = 262221, upload-time = "2026-01-26T02:44:36.604Z" }, + { url = "https://files.pythonhosted.org/packages/cd/f7/e8c0d0da0cd1e28d10e624604e1a36bcc3353aaebdfdc3a43c72bc683a12/multidict-6.7.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:401c5a650f3add2472d1d288c26deebc540f99e2fb83e9525007a74cd2116f1d", size = 258664, upload-time = "2026-01-26T02:44:38.008Z" }, + { url = "https://files.pythonhosted.org/packages/52/da/151a44e8016dd33feed44f730bd856a66257c1ee7aed4f44b649fb7edeb3/multidict-6.7.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:97891f3b1b3ffbded884e2916cacf3c6fc87b66bb0dde46f7357404750559f33", size = 249490, upload-time = "2026-01-26T02:44:39.386Z" }, + { url = "https://files.pythonhosted.org/packages/87/af/a3b86bf9630b732897f6fc3f4c4714b90aa4361983ccbdcd6c0339b21b0c/multidict-6.7.1-cp313-cp313-win32.whl", hash = "sha256:e1c5988359516095535c4301af38d8a8838534158f649c05dd1050222321bcb3", size = 41695, upload-time = "2026-01-26T02:44:41.318Z" }, + { url = "https://files.pythonhosted.org/packages/b2/35/e994121b0e90e46134673422dd564623f93304614f5d11886b1b3e06f503/multidict-6.7.1-cp313-cp313-win_amd64.whl", hash = "sha256:960c83bf01a95b12b08fd54324a4eb1d5b52c88932b5cba5d6e712bb3ed12eb5", size = 45884, upload-time = "2026-01-26T02:44:42.488Z" }, + { url = "https://files.pythonhosted.org/packages/ca/61/42d3e5dbf661242a69c97ea363f2d7b46c567da8eadef8890022be6e2ab0/multidict-6.7.1-cp313-cp313-win_arm64.whl", hash = "sha256:563fe25c678aaba333d5399408f5ec3c383ca5b663e7f774dd179a520b8144df", size = 43122, upload-time = "2026-01-26T02:44:43.664Z" }, + { url = "https://files.pythonhosted.org/packages/6d/b3/e6b21c6c4f314bb956016b0b3ef2162590a529b84cb831c257519e7fde44/multidict-6.7.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:c76c4bec1538375dad9d452d246ca5368ad6e1c9039dadcf007ae59c70619ea1", size = 83175, upload-time = "2026-01-26T02:44:44.894Z" }, + { url = "https://files.pythonhosted.org/packages/fb/76/23ecd2abfe0957b234f6c960f4ade497f55f2c16aeb684d4ecdbf1c95791/multidict-6.7.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:57b46b24b5d5ebcc978da4ec23a819a9402b4228b8a90d9c656422b4bdd8a963", size = 48460, upload-time = "2026-01-26T02:44:46.106Z" }, + { url = "https://files.pythonhosted.org/packages/c4/57/a0ed92b23f3a042c36bc4227b72b97eca803f5f1801c1ab77c8a212d455e/multidict-6.7.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e954b24433c768ce78ab7929e84ccf3422e46deb45a4dc9f93438f8217fa2d34", size = 46930, upload-time = "2026-01-26T02:44:47.278Z" }, + { url = "https://files.pythonhosted.org/packages/b5/66/02ec7ace29162e447f6382c495dc95826bf931d3818799bbef11e8f7df1a/multidict-6.7.1-cp313-cp313t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:3bd231490fa7217cc832528e1cd8752a96f0125ddd2b5749390f7c3ec8721b65", size = 242582, upload-time = "2026-01-26T02:44:48.604Z" }, + { url = "https://files.pythonhosted.org/packages/58/18/64f5a795e7677670e872673aca234162514696274597b3708b2c0d276cce/multidict-6.7.1-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:253282d70d67885a15c8a7716f3a73edf2d635793ceda8173b9ecc21f2fb8292", size = 250031, upload-time = "2026-01-26T02:44:50.544Z" }, + { url = "https://files.pythonhosted.org/packages/c8/ed/e192291dbbe51a8290c5686f482084d31bcd9d09af24f63358c3d42fd284/multidict-6.7.1-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0b4c48648d7649c9335cf1927a8b87fa692de3dcb15faa676c6a6f1f1aabda43", size = 228596, upload-time = "2026-01-26T02:44:51.951Z" }, + { url = "https://files.pythonhosted.org/packages/1e/7e/3562a15a60cf747397e7f2180b0a11dc0c38d9175a650e75fa1b4d325e15/multidict-6.7.1-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:98bc624954ec4d2c7cb074b8eefc2b5d0ce7d482e410df446414355d158fe4ca", size = 257492, upload-time = "2026-01-26T02:44:53.902Z" }, + { url = "https://files.pythonhosted.org/packages/24/02/7d0f9eae92b5249bb50ac1595b295f10e263dd0078ebb55115c31e0eaccd/multidict-6.7.1-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1b99af4d9eec0b49927b4402bcbb58dea89d3e0db8806a4086117019939ad3dd", size = 255899, upload-time = "2026-01-26T02:44:55.316Z" }, + { url = "https://files.pythonhosted.org/packages/00/e3/9b60ed9e23e64c73a5cde95269ef1330678e9c6e34dd4eb6b431b85b5a10/multidict-6.7.1-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6aac4f16b472d5b7dc6f66a0d49dd57b0e0902090be16594dc9ebfd3d17c47e7", size = 247970, upload-time = "2026-01-26T02:44:56.783Z" }, + { url = "https://files.pythonhosted.org/packages/3e/06/538e58a63ed5cfb0bd4517e346b91da32fde409d839720f664e9a4ae4f9d/multidict-6.7.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:21f830fe223215dffd51f538e78c172ed7c7f60c9b96a2bf05c4848ad49921c3", size = 245060, upload-time = "2026-01-26T02:44:58.195Z" }, + { url = "https://files.pythonhosted.org/packages/b2/2f/d743a3045a97c895d401e9bd29aaa09b94f5cbdf1bd561609e5a6c431c70/multidict-6.7.1-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:f5dd81c45b05518b9aa4da4aa74e1c93d715efa234fd3e8a179df611cc85e5f4", size = 235888, upload-time = "2026-01-26T02:44:59.57Z" }, + { url = "https://files.pythonhosted.org/packages/38/83/5a325cac191ab28b63c52f14f1131f3b0a55ba3b9aa65a6d0bf2a9b921a0/multidict-6.7.1-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:eb304767bca2bb92fb9c5bd33cedc95baee5bb5f6c88e63706533a1c06ad08c8", size = 243554, upload-time = "2026-01-26T02:45:01.054Z" }, + { url = "https://files.pythonhosted.org/packages/20/1f/9d2327086bd15da2725ef6aae624208e2ef828ed99892b17f60c344e57ed/multidict-6.7.1-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:c9035dde0f916702850ef66460bc4239d89d08df4d02023a5926e7446724212c", size = 252341, upload-time = "2026-01-26T02:45:02.484Z" }, + { url = "https://files.pythonhosted.org/packages/e8/2c/2a1aa0280cf579d0f6eed8ee5211c4f1730bd7e06c636ba2ee6aafda302e/multidict-6.7.1-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:af959b9beeb66c822380f222f0e0a1889331597e81f1ded7f374f3ecb0fd6c52", size = 246391, upload-time = "2026-01-26T02:45:03.862Z" }, + { url = "https://files.pythonhosted.org/packages/e5/03/7ca022ffc36c5a3f6e03b179a5ceb829be9da5783e6fe395f347c0794680/multidict-6.7.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:41f2952231456154ee479651491e94118229844dd7226541788be783be2b5108", size = 243422, upload-time = "2026-01-26T02:45:05.296Z" }, + { url = "https://files.pythonhosted.org/packages/dc/1d/b31650eab6c5778aceed46ba735bd97f7c7d2f54b319fa916c0f96e7805b/multidict-6.7.1-cp313-cp313t-win32.whl", hash = "sha256:df9f19c28adcb40b6aae30bbaa1478c389efd50c28d541d76760199fc1037c32", size = 47770, upload-time = "2026-01-26T02:45:06.754Z" }, + { url = "https://files.pythonhosted.org/packages/ac/5b/2d2d1d522e51285bd61b1e20df8f47ae1a9d80839db0b24ea783b3832832/multidict-6.7.1-cp313-cp313t-win_amd64.whl", hash = "sha256:d54ecf9f301853f2c5e802da559604b3e95bb7a3b01a9c295c6ee591b9882de8", size = 53109, upload-time = "2026-01-26T02:45:08.044Z" }, + { url = "https://files.pythonhosted.org/packages/3d/a3/cc409ba012c83ca024a308516703cf339bdc4b696195644a7215a5164a24/multidict-6.7.1-cp313-cp313t-win_arm64.whl", hash = "sha256:5a37ca18e360377cfda1d62f5f382ff41f2b8c4ccb329ed974cc2e1643440118", size = 45573, upload-time = "2026-01-26T02:45:09.349Z" }, + { url = "https://files.pythonhosted.org/packages/91/cc/db74228a8be41884a567e88a62fd589a913708fcf180d029898c17a9a371/multidict-6.7.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:8f333ec9c5eb1b7105e3b84b53141e66ca05a19a605368c55450b6ba208cb9ee", size = 75190, upload-time = "2026-01-26T02:45:10.651Z" }, + { url = "https://files.pythonhosted.org/packages/d5/22/492f2246bb5b534abd44804292e81eeaf835388901f0c574bac4eeec73c5/multidict-6.7.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:a407f13c188f804c759fc6a9f88286a565c242a76b27626594c133b82883b5c2", size = 44486, upload-time = "2026-01-26T02:45:11.938Z" }, + { url = "https://files.pythonhosted.org/packages/f1/4f/733c48f270565d78b4544f2baddc2fb2a245e5a8640254b12c36ac7ac68e/multidict-6.7.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:0e161ddf326db5577c3a4cc2d8648f81456e8a20d40415541587a71620d7a7d1", size = 43219, upload-time = "2026-01-26T02:45:14.346Z" }, + { url = "https://files.pythonhosted.org/packages/24/bb/2c0c2287963f4259c85e8bcbba9182ced8d7fca65c780c38e99e61629d11/multidict-6.7.1-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:1e3a8bb24342a8201d178c3b4984c26ba81a577c80d4d525727427460a50c22d", size = 245132, upload-time = "2026-01-26T02:45:15.712Z" }, + { url = "https://files.pythonhosted.org/packages/a7/f9/44d4b3064c65079d2467888794dea218d1601898ac50222ab8a9a8094460/multidict-6.7.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:97231140a50f5d447d3164f994b86a0bed7cd016e2682f8650d6a9158e14fd31", size = 252420, upload-time = "2026-01-26T02:45:17.293Z" }, + { url = "https://files.pythonhosted.org/packages/8b/13/78f7275e73fa17b24c9a51b0bd9d73ba64bb32d0ed51b02a746eb876abe7/multidict-6.7.1-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6b10359683bd8806a200fd2909e7c8ca3a7b24ec1d8132e483d58e791d881048", size = 233510, upload-time = "2026-01-26T02:45:19.356Z" }, + { url = "https://files.pythonhosted.org/packages/4b/25/8167187f62ae3cbd52da7893f58cb036b47ea3fb67138787c76800158982/multidict-6.7.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:283ddac99f7ac25a4acadbf004cb5ae34480bbeb063520f70ce397b281859362", size = 264094, upload-time = "2026-01-26T02:45:20.834Z" }, + { url = "https://files.pythonhosted.org/packages/a1/e7/69a3a83b7b030cf283fb06ce074a05a02322359783424d7edf0f15fe5022/multidict-6.7.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:538cec1e18c067d0e6103aa9a74f9e832904c957adc260e61cd9d8cf0c3b3d37", size = 260786, upload-time = "2026-01-26T02:45:22.818Z" }, + { url = "https://files.pythonhosted.org/packages/fe/3b/8ec5074bcfc450fe84273713b4b0a0dd47c0249358f5d82eb8104ffe2520/multidict-6.7.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7eee46ccb30ff48a1e35bb818cc90846c6be2b68240e42a78599166722cea709", size = 248483, upload-time = "2026-01-26T02:45:24.368Z" }, + { url = "https://files.pythonhosted.org/packages/48/5a/d5a99e3acbca0e29c5d9cba8f92ceb15dce78bab963b308ae692981e3a5d/multidict-6.7.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fa263a02f4f2dd2d11a7b1bb4362aa7cb1049f84a9235d31adf63f30143469a0", size = 248403, upload-time = "2026-01-26T02:45:25.982Z" }, + { url = "https://files.pythonhosted.org/packages/35/48/e58cd31f6c7d5102f2a4bf89f96b9cf7e00b6c6f3d04ecc44417c00a5a3c/multidict-6.7.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:2e1425e2f99ec5bd36c15a01b690a1a2456209c5deed58f95469ffb46039ccbb", size = 240315, upload-time = "2026-01-26T02:45:27.487Z" }, + { url = "https://files.pythonhosted.org/packages/94/33/1cd210229559cb90b6786c30676bb0c58249ff42f942765f88793b41fdce/multidict-6.7.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:497394b3239fc6f0e13a78a3e1b61296e72bf1c5f94b4c4eb80b265c37a131cd", size = 245528, upload-time = "2026-01-26T02:45:28.991Z" }, + { url = "https://files.pythonhosted.org/packages/64/f2/6e1107d226278c876c783056b7db43d800bb64c6131cec9c8dfb6903698e/multidict-6.7.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:233b398c29d3f1b9676b4b6f75c518a06fcb2ea0b925119fb2c1bc35c05e1601", size = 258784, upload-time = "2026-01-26T02:45:30.503Z" }, + { url = "https://files.pythonhosted.org/packages/4d/c1/11f664f14d525e4a1b5327a82d4de61a1db604ab34c6603bb3c2cc63ad34/multidict-6.7.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:93b1818e4a6e0930454f0f2af7dfce69307ca03cdcfb3739bf4d91241967b6c1", size = 251980, upload-time = "2026-01-26T02:45:32.603Z" }, + { url = "https://files.pythonhosted.org/packages/e1/9f/75a9ac888121d0c5bbd4ecf4eead45668b1766f6baabfb3b7f66a410e231/multidict-6.7.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f33dc2a3abe9249ea5d8360f969ec7f4142e7ac45ee7014d8f8d5acddf178b7b", size = 243602, upload-time = "2026-01-26T02:45:34.043Z" }, + { url = "https://files.pythonhosted.org/packages/9a/e7/50bf7b004cc8525d80dbbbedfdc7aed3e4c323810890be4413e589074032/multidict-6.7.1-cp314-cp314-win32.whl", hash = "sha256:3ab8b9d8b75aef9df299595d5388b14530839f6422333357af1339443cff777d", size = 40930, upload-time = "2026-01-26T02:45:36.278Z" }, + { url = "https://files.pythonhosted.org/packages/e0/bf/52f25716bbe93745595800f36fb17b73711f14da59ed0bb2eba141bc9f0f/multidict-6.7.1-cp314-cp314-win_amd64.whl", hash = "sha256:5e01429a929600e7dab7b166062d9bb54a5eed752384c7384c968c2afab8f50f", size = 45074, upload-time = "2026-01-26T02:45:37.546Z" }, + { url = "https://files.pythonhosted.org/packages/97/ab/22803b03285fa3a525f48217963da3a65ae40f6a1b6f6cf2768879e208f9/multidict-6.7.1-cp314-cp314-win_arm64.whl", hash = "sha256:4885cb0e817aef5d00a2e8451d4665c1808378dc27c2705f1bf4ef8505c0d2e5", size = 42471, upload-time = "2026-01-26T02:45:38.889Z" }, + { url = "https://files.pythonhosted.org/packages/e0/6d/f9293baa6146ba9507e360ea0292b6422b016907c393e2f63fc40ab7b7b5/multidict-6.7.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:0458c978acd8e6ea53c81eefaddbbee9c6c5e591f41b3f5e8e194780fe026581", size = 82401, upload-time = "2026-01-26T02:45:40.254Z" }, + { url = "https://files.pythonhosted.org/packages/7a/68/53b5494738d83558d87c3c71a486504d8373421c3e0dbb6d0db48ad42ee0/multidict-6.7.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:c0abd12629b0af3cf590982c0b413b1e7395cd4ec026f30986818ab95bfaa94a", size = 48143, upload-time = "2026-01-26T02:45:41.635Z" }, + { url = "https://files.pythonhosted.org/packages/37/e8/5284c53310dcdc99ce5d66563f6e5773531a9b9fe9ec7a615e9bc306b05f/multidict-6.7.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:14525a5f61d7d0c94b368a42cff4c9a4e7ba2d52e2672a7b23d84dc86fb02b0c", size = 46507, upload-time = "2026-01-26T02:45:42.99Z" }, + { url = "https://files.pythonhosted.org/packages/e4/fc/6800d0e5b3875568b4083ecf5f310dcf91d86d52573160834fb4bfcf5e4f/multidict-6.7.1-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:17307b22c217b4cf05033dabefe68255a534d637c6c9b0cc8382718f87be4262", size = 239358, upload-time = "2026-01-26T02:45:44.376Z" }, + { url = "https://files.pythonhosted.org/packages/41/75/4ad0973179361cdf3a113905e6e088173198349131be2b390f9fa4da5fc6/multidict-6.7.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a7e590ff876a3eaf1c02a4dfe0724b6e69a9e9de6d8f556816f29c496046e59", size = 246884, upload-time = "2026-01-26T02:45:47.167Z" }, + { url = "https://files.pythonhosted.org/packages/c3/9c/095bb28b5da139bd41fb9a5d5caff412584f377914bd8787c2aa98717130/multidict-6.7.1-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:5fa6a95dfee63893d80a34758cd0e0c118a30b8dcb46372bf75106c591b77889", size = 225878, upload-time = "2026-01-26T02:45:48.698Z" }, + { url = "https://files.pythonhosted.org/packages/07/d0/c0a72000243756e8f5a277b6b514fa005f2c73d481b7d9e47cd4568aa2e4/multidict-6.7.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a0543217a6a017692aa6ae5cc39adb75e587af0f3a82288b1492eb73dd6cc2a4", size = 253542, upload-time = "2026-01-26T02:45:50.164Z" }, + { url = "https://files.pythonhosted.org/packages/c0/6b/f69da15289e384ecf2a68837ec8b5ad8c33e973aa18b266f50fe55f24b8c/multidict-6.7.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f99fe611c312b3c1c0ace793f92464d8cd263cc3b26b5721950d977b006b6c4d", size = 252403, upload-time = "2026-01-26T02:45:51.779Z" }, + { url = "https://files.pythonhosted.org/packages/a2/76/b9669547afa5a1a25cd93eaca91c0da1c095b06b6d2d8ec25b713588d3a1/multidict-6.7.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9004d8386d133b7e6135679424c91b0b854d2d164af6ea3f289f8f2761064609", size = 244889, upload-time = "2026-01-26T02:45:53.27Z" }, + { url = "https://files.pythonhosted.org/packages/7e/a9/a50d2669e506dad33cfc45b5d574a205587b7b8a5f426f2fbb2e90882588/multidict-6.7.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e628ef0e6859ffd8273c69412a2465c4be4a9517d07261b33334b5ec6f3c7489", size = 241982, upload-time = "2026-01-26T02:45:54.919Z" }, + { url = "https://files.pythonhosted.org/packages/c5/bb/1609558ad8b456b4827d3c5a5b775c93b87878fd3117ed3db3423dfbce1b/multidict-6.7.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:841189848ba629c3552035a6a7f5bf3b02eb304e9fea7492ca220a8eda6b0e5c", size = 232415, upload-time = "2026-01-26T02:45:56.981Z" }, + { url = "https://files.pythonhosted.org/packages/d8/59/6f61039d2aa9261871e03ab9dc058a550d240f25859b05b67fd70f80d4b3/multidict-6.7.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:ce1bbd7d780bb5a0da032e095c951f7014d6b0a205f8318308140f1a6aba159e", size = 240337, upload-time = "2026-01-26T02:45:58.698Z" }, + { url = "https://files.pythonhosted.org/packages/a1/29/fdc6a43c203890dc2ae9249971ecd0c41deaedfe00d25cb6564b2edd99eb/multidict-6.7.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:b26684587228afed0d50cf804cc71062cc9c1cdf55051c4c6345d372947b268c", size = 248788, upload-time = "2026-01-26T02:46:00.862Z" }, + { url = "https://files.pythonhosted.org/packages/a9/14/a153a06101323e4cf086ecee3faadba52ff71633d471f9685c42e3736163/multidict-6.7.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:9f9af11306994335398293f9958071019e3ab95e9a707dc1383a35613f6abcb9", size = 242842, upload-time = "2026-01-26T02:46:02.824Z" }, + { url = "https://files.pythonhosted.org/packages/41/5f/604ae839e64a4a6efc80db94465348d3b328ee955e37acb24badbcd24d83/multidict-6.7.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:b4938326284c4f1224178a560987b6cf8b4d38458b113d9b8c1db1a836e640a2", size = 240237, upload-time = "2026-01-26T02:46:05.898Z" }, + { url = "https://files.pythonhosted.org/packages/5f/60/c3a5187bf66f6fb546ff4ab8fb5a077cbdd832d7b1908d4365c7f74a1917/multidict-6.7.1-cp314-cp314t-win32.whl", hash = "sha256:98655c737850c064a65e006a3df7c997cd3b220be4ec8fe26215760b9697d4d7", size = 48008, upload-time = "2026-01-26T02:46:07.468Z" }, + { url = "https://files.pythonhosted.org/packages/0c/f7/addf1087b860ac60e6f382240f64fb99f8bfb532bb06f7c542b83c29ca61/multidict-6.7.1-cp314-cp314t-win_amd64.whl", hash = "sha256:497bde6223c212ba11d462853cfa4f0ae6ef97465033e7dc9940cdb3ab5b48e5", size = 53542, upload-time = "2026-01-26T02:46:08.809Z" }, + { url = "https://files.pythonhosted.org/packages/4c/81/4629d0aa32302ef7b2ec65c75a728cc5ff4fa410c50096174c1632e70b3e/multidict-6.7.1-cp314-cp314t-win_arm64.whl", hash = "sha256:2bbd113e0d4af5db41d5ebfe9ccaff89de2120578164f86a5d17d5a576d1e5b2", size = 44719, upload-time = "2026-01-26T02:46:11.146Z" }, + { url = "https://files.pythonhosted.org/packages/81/08/7036c080d7117f28a4af526d794aab6a84463126db031b007717c1a6676e/multidict-6.7.1-py3-none-any.whl", hash = "sha256:55d97cc6dae627efa6a6e548885712d4864b81110ac76fa4e534c03819fa4a56", size = 12319, upload-time = "2026-01-26T02:46:44.004Z" }, +] + +[[package]] +name = "mypy" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "ast-serialize" }, + { name = "librt", marker = "platform_python_implementation != 'PyPy'" }, + { name = "mypy-extensions" }, + { name = "pathspec" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/12/af/4e516a05d3ca2eb9283e9ec45b2c02225c1514dd6da49fd3c9eaa6639370/mypy-2.3.0.tar.gz", hash = "sha256:465965d41cd9a2726694e983e8ce7113259327bec798115d1e1dfa2a52fb666e", size = 3988104, upload-time = "2026-07-13T11:34:53.387Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dc/94/0e7e592619e2133596a47cdd642534b0456545c218430bd3b9d8fefdd1b1/mypy-2.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2d53fc67b9d28a43c6199077f49fea0f05839e36cf6158500331c9549225e5a5", size = 15026523, upload-time = "2026-07-13T11:34:49.206Z" }, + { url = "https://files.pythonhosted.org/packages/f6/d2/1e1731df090a857df2807177a4626863e5ac0f0256513c35780efe53986f/mypy-2.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fbc00cee7bdbb9291979ddc9d08034a29dfcda4932628c9bbc28c1edd589df0c", size = 14032189, upload-time = "2026-07-13T11:33:57.168Z" }, + { url = "https://files.pythonhosted.org/packages/44/95/cab921f4a806e171f34113e6181dd23c55358ccf6a80741269ef594a410e/mypy-2.3.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:04e617030eca5221909c8b7d8d7fd1c637948199aa2100b2ad9813feb07e1491", size = 14198696, upload-time = "2026-07-13T11:32:12.767Z" }, + { url = "https://files.pythonhosted.org/packages/66/80/e6d008bb19fe446e3662d85e0e2717bf9f2d611a2164fb29d6e067dbf46c/mypy-2.3.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:56c184d2c20ca6b6378d58d1960270a767f41f5e44acbbd27f05effef4f4e1d7", size = 15286904, upload-time = "2026-07-13T11:34:27.594Z" }, + { url = "https://files.pythonhosted.org/packages/db/83/94397c9293608a364aa03e8084fb34ede4ae976a260384b9b52929308135/mypy-2.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3961a4a34b05f7c74b0f05aa51fbfe99a2d1e126038df40318d15c8f558b7ef3", size = 15528342, upload-time = "2026-07-13T11:34:07.819Z" }, + { url = "https://files.pythonhosted.org/packages/cf/96/d8b37d819adec6cfccfb1fd3afc1735d94717ddeafb45536db9c6943e09b/mypy-2.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:b1942b9314d4c784b8ea1dbab4972603290e5dd5630f06675f13aec97526bc4c", size = 11218346, upload-time = "2026-07-13T11:28:27.745Z" }, + { url = "https://files.pythonhosted.org/packages/2b/cd/cd9f725b19b19e5b530a154cf9bcf9e94279c5d55b3c34fb42b3aa48ea1b/mypy-2.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:be51653d7669d7d7955d613b8d0bb57d5b652eaf71a873ddf65ac87254dd2595", size = 10204525, upload-time = "2026-07-13T11:31:02.552Z" }, + { url = "https://files.pythonhosted.org/packages/6e/ae/f7d056eb0294586a572d0d0d89580ec633c064db520f11d37d5a2fb833bd/mypy-2.3.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:91ad22a52ae2c7e621c2f67c94d5a17f66b3209a4cff5cf8a573579835c69e97", size = 14947298, upload-time = "2026-07-13T11:27:47.734Z" }, + { url = "https://files.pythonhosted.org/packages/32/d5/db3e7af01e7844d21662c6ddc1f7825ec7cb4053f0391ac02faf3638396f/mypy-2.3.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:99ac767cc5d3b64c8d0ae226ead10c96694f94e4e7da1668642225dcd4e75aac", size = 13950768, upload-time = "2026-07-13T11:27:57.726Z" }, + { url = "https://files.pythonhosted.org/packages/d9/fb/43c031f0190513d1ec248ed037eceb742ddd2a4d74bbf406658a28173837/mypy-2.3.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:de6d2c484742a4d7b0ed6d07b143375624d3b899c5749c7b3c947f56261f48a6", size = 14151586, upload-time = "2026-07-13T11:29:18.615Z" }, + { url = "https://files.pythonhosted.org/packages/ec/c3/f8b2ffc60883084da91be51af58e88a7ffd4ff9795acb7d902ff88d31eb1/mypy-2.3.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7da939dd335cfd2ad788bdfd081c9f4e47634ab995e5a45eb15fd1e5bc052f8b", size = 15227411, upload-time = "2026-07-13T11:30:29.904Z" }, + { url = "https://files.pythonhosted.org/packages/83/2e/16b917fc7adcf03f1aadddfc93aab804ffb234b1ab09c0ffd6d92a5d34a2/mypy-2.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:7247eb2824f996722a949530183394921ca71deb9680052a338cf53cff7925c2", size = 15478790, upload-time = "2026-07-13T11:33:14.686Z" }, + { url = "https://files.pythonhosted.org/packages/c0/88/aaa65a93c73d0cdae7e42f8adb302bf6885bb281302084f99d0290a35347/mypy-2.3.0-cp313-cp313-win_amd64.whl", hash = "sha256:75b0984bb3cbd76bb5c9291a8671f7ae66ca3b51c7584c358fc2e923259f0757", size = 11234919, upload-time = "2026-07-13T11:33:39.28Z" }, + { url = "https://files.pythonhosted.org/packages/35/19/b40de63f1a80e63bc2d40f0679a6a8dbd34e95176c8122119bdf406aa552/mypy-2.3.0-cp313-cp313-win_arm64.whl", hash = "sha256:d78fcf900b59cb7e82cb7e3a235e31b462d9333d92285bd1e4952d355b8ffba1", size = 10201510, upload-time = "2026-07-13T11:31:52.619Z" }, + { url = "https://files.pythonhosted.org/packages/a4/58/fa0ae047da911f540284009b4f44b96fe09d83c076d7c103e9d645f46303/mypy-2.3.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ea317b060ce83e26050f8f9e4d7d6bf44ed7597c8ff9990bccffbb9d1d8522db", size = 14941909, upload-time = "2026-07-13T11:32:34.332Z" }, + { url = "https://files.pythonhosted.org/packages/15/14/2ba1d61452d7c2a7fe12741e8d374e52b183476b07aa7f9e2a0d02b0720a/mypy-2.3.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:094af99f92638aa92852326188b85a89e50f4a472f44827c03362228482f0762", size = 13967581, upload-time = "2026-07-13T11:30:00.587Z" }, + { url = "https://files.pythonhosted.org/packages/ed/5a/483fb9e5ffbbb1a28dccc7b0a13d141b17ac769b6c9f488c0a0c63698962/mypy-2.3.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:de121747278144fc9ae7caa2e978cf5df12aebc82933182f5b3b86081a30baef", size = 14168807, upload-time = "2026-07-13T11:28:48.6Z" }, + { url = "https://files.pythonhosted.org/packages/ae/77/70d7a10732063beb74ad713682cf871e88f5c5fa39bfc8beff8a524bf9cb/mypy-2.3.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:37fa4de896a84e2dc9200d91e614c22563b43d1a266789d4bbac7b22ebe6192b", size = 15200144, upload-time = "2026-07-13T11:31:25.283Z" }, + { url = "https://files.pythonhosted.org/packages/56/72/766218ac783be4fdfcd699b90037b63017348a3e86fb2c1fbfb18302637d/mypy-2.3.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f1b3a98dfd21058bc759bb3337d5d1f61d0fdf9f3cf9c00f4291790fb5427bff", size = 15460389, upload-time = "2026-07-13T11:29:29.077Z" }, + { url = "https://files.pythonhosted.org/packages/38/4e/8a9db7411ecb8ec0cb1fd05dba432f28bafffcd38b4e887714a4a0506689/mypy-2.3.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:944c665d984157cb96a679dfb7a4a81dd1d36b24b9c284b699514e6e626b82d4", size = 7753664, upload-time = "2026-07-13T11:29:08.147Z" }, + { url = "https://files.pythonhosted.org/packages/65/4c/c3f8bfd6ed0e5e38b5a244403b27f821d433443df5a15a278417c10a3a3c/mypy-2.3.0-cp314-cp314-win_amd64.whl", hash = "sha256:4359424140d985192c778c1ce2c114a10c1ca58a381ed79cfa70d37df94b299f", size = 11417237, upload-time = "2026-07-13T11:33:47.467Z" }, + { url = "https://files.pythonhosted.org/packages/3c/00/89a32eaf5ccf174bc4f90db0eaea5d70636c01b8d49f384bdab2e8834390/mypy-2.3.0-cp314-cp314-win_arm64.whl", hash = "sha256:3dd0bed92c4bdec57c42505b96416fb9e6a5aa7be84d2809bcd5f2ecec2860d7", size = 10389252, upload-time = "2026-07-13T11:31:43.81Z" }, + { url = "https://files.pythonhosted.org/packages/31/56/104f93d69aa9f339b6b9d3b0a7faa699b8b466c942cf3ae86cc2a2ec0915/mypy-2.3.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:691fdc37132b1ae628d834f672e74de83462d9fb4aff621835767fb43a8dd373", size = 16385495, upload-time = "2026-07-13T11:29:49.818Z" }, + { url = "https://files.pythonhosted.org/packages/d2/03/f1d2123313f55efafdd27706960f43a771c62f1b68426c76043f3ab9ebf3/mypy-2.3.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:aec15d465d477558fd842757b487849007311cf3897849cdda0e3162ac0ac556", size = 15098155, upload-time = "2026-07-13T11:30:40.301Z" }, + { url = "https://files.pythonhosted.org/packages/e5/5d/d5f9200399b445e81726c4f23becee33f233aee81c72680b1ef3a258b641/mypy-2.3.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b352b7e49f5e6576009e8df730e1ff4f915cb565b851b396d2ffe2f5a6f5da88", size = 15514155, upload-time = "2026-07-13T11:34:38.569Z" }, + { url = "https://files.pythonhosted.org/packages/cd/ce/69977c555f08faa3190cfde44189b89dbd56861b1ab97aa18fc5f3a2e4a3/mypy-2.3.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1c6c6bf687b17f90dbfcad95b960d32eaa0154c00da45f03ab50bf8952e047fe", size = 16766351, upload-time = "2026-07-13T11:33:29.195Z" }, + { url = "https://files.pythonhosted.org/packages/bc/92/6648b6caa3ab9e00f9ac0c2a78307805f873dd48139b24a6f6f7c3667bbf/mypy-2.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f4ed18f111bfe2d599bca7468e7f9251042c1c2118f762c8de2766a56d773c60", size = 17043490, upload-time = "2026-07-13T11:30:53.927Z" }, + { url = "https://files.pythonhosted.org/packages/7c/ab/0dc91d80f3f016634c68d451f294a97320fe903a9b6f90b9e57b3f7f1717/mypy-2.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:0b025a93cffb9781d231f232be07a17912f35f10a313c24f301c81e842870654", size = 12146869, upload-time = "2026-07-13T11:29:38.874Z" }, + { url = "https://files.pythonhosted.org/packages/85/b5/4c964d02634ba81f4d1c84838e5c5b18ab06d13ed568960f5d6318495ccc/mypy-2.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:adebc76aab4f3495a88b41d48aa4aff0c03f2822501da76625afcca5975f19e5", size = 10965113, upload-time = "2026-07-13T11:28:07.056Z" }, + { url = "https://files.pythonhosted.org/packages/2c/fa/fdc54fe583ba3cafbcedfb70eeeaf03849f75b1827a07096c7bd996f582d/mypy-2.3.0-py3-none-any.whl", hash = "sha256:6b1cdb579446b60432432b2b2403a6201b4b475a004d7f488511c9ba177c9e88", size = 2753292, upload-time = "2026-07-13T11:33:18.48Z" }, +] + +[[package]] +name = "mypy-extensions" +version = "1.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a2/6e/371856a3fb9d31ca8dac321cda606860fa4548858c0cc45d9d1d4ca2628b/mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558", size = 6343, upload-time = "2025-04-22T14:54:24.164Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" }, +] + +[[package]] +name = "networkx" +version = "3.6.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6a/51/63fe664f3908c97be9d2e4f1158eb633317598cfa6e1fc14af5383f17512/networkx-3.6.1.tar.gz", hash = "sha256:26b7c357accc0c8cde558ad486283728b65b6a95d85ee1cd66bafab4c8168509", size = 2517025, upload-time = "2025-12-08T17:02:39.908Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/c9/b2622292ea83fbb4ec318f5b9ab867d0a28ab43c5717bb85b0a5f6b3b0a4/networkx-3.6.1-py3-none-any.whl", hash = "sha256:d47fbf302e7d9cbbb9e2555a0d267983d2aa476bac30e90dfbe5669bd57f3762", size = 2068504, upload-time = "2025-12-08T17:02:38.159Z" }, +] + +[[package]] +name = "numcodecs" +version = "0.16.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/44/bd/8a391e7c356366224734efd24da929cc4796fff468bfb179fe1af6548535/numcodecs-0.16.5.tar.gz", hash = "sha256:0d0fb60852f84c0bd9543cc4d2ab9eefd37fc8efcc410acd4777e62a1d300318", size = 6276387, upload-time = "2025-11-21T02:49:48.986Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/75/cc/55420f3641a67f78392dc0bc5d02cb9eb0a9dcebf2848d1ac77253ca61fa/numcodecs-0.16.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:24e675dc8d1550cd976a99479b87d872cb142632c75cc402fea04c08c4898523", size = 1656287, upload-time = "2025-11-21T02:49:25.755Z" }, + { url = "https://files.pythonhosted.org/packages/f5/6c/86644987505dcb90ba6d627d6989c27bafb0699f9fd00187e06d05ea8594/numcodecs-0.16.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:94ddfa4341d1a3ab99989d13b01b5134abb687d3dab2ead54b450aefe4ad5bd6", size = 1148899, upload-time = "2025-11-21T02:49:26.87Z" }, + { url = "https://files.pythonhosted.org/packages/97/1e/98aaddf272552d9fef1f0296a9939d1487914a239e98678f6b20f8b0a5c8/numcodecs-0.16.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b554ab9ecf69de7ca2b6b5e8bc696bd9747559cb4dd5127bd08d7a28bec59c3a", size = 8534814, upload-time = "2025-11-21T02:49:28.547Z" }, + { url = "https://files.pythonhosted.org/packages/fb/53/78c98ef5c8b2b784453487f3e4d6c017b20747c58b470393e230c78d18e8/numcodecs-0.16.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ad1a379a45bd3491deab8ae6548313946744f868c21d5340116977ea3be5b1d6", size = 9173471, upload-time = "2025-11-21T02:49:30.444Z" }, + { url = "https://files.pythonhosted.org/packages/1c/20/2fdec87fc7f8cec950d2b0bea603c12dc9f05b4966dc5924ba5a36a61bf6/numcodecs-0.16.5-cp312-cp312-win_amd64.whl", hash = "sha256:845a9857886ffe4a3172ba1c537ae5bcc01e65068c31cf1fce1a844bd1da050f", size = 801412, upload-time = "2025-11-21T02:49:32.123Z" }, + { url = "https://files.pythonhosted.org/packages/38/38/071ced5a5fd1c85ba0e14ba721b66b053823e5176298c2f707e50bed11d9/numcodecs-0.16.5-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:25be3a516ab677dad890760d357cfe081a371d9c0a2e9a204562318ac5969de3", size = 1654359, upload-time = "2025-11-21T02:49:33.673Z" }, + { url = "https://files.pythonhosted.org/packages/d1/c0/5f84ba7525577c1b9909fc2d06ef11314825fc4ad4378f61d0e4c9883b4a/numcodecs-0.16.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0107e839ef75b854e969cb577e140b1aadb9847893937636582d23a2a4c6ce50", size = 1144237, upload-time = "2025-11-21T02:49:35.294Z" }, + { url = "https://files.pythonhosted.org/packages/0b/00/787ea5f237b8ea7bc67140c99155f9c00b5baf11c49afc5f3bfefa298f95/numcodecs-0.16.5-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:015a7c859ecc2a06e2a548f64008c0ec3aaecabc26456c2c62f4278d8fc20597", size = 8483064, upload-time = "2025-11-21T02:49:36.454Z" }, + { url = "https://files.pythonhosted.org/packages/c4/e6/d359fdd37498e74d26a167f7a51e54542e642ea47181eb4e643a69a066c3/numcodecs-0.16.5-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:84230b4b9dad2392f2a84242bd6e3e659ac137b5a1ce3571d6965fca673e0903", size = 9126063, upload-time = "2025-11-21T02:49:38.018Z" }, + { url = "https://files.pythonhosted.org/packages/27/72/6663cc0382ddbb866136c255c837bcb96cc7ce5e83562efec55e1b995941/numcodecs-0.16.5-cp313-cp313-win_amd64.whl", hash = "sha256:5088145502ad1ebf677ec47d00eb6f0fd600658217db3e0c070c321c85d6cf3d", size = 799275, upload-time = "2025-11-21T02:49:39.558Z" }, + { url = "https://files.pythonhosted.org/packages/3c/9e/38e7ca8184c958b51f45d56a4aeceb1134ecde2d8bd157efadc98502cc42/numcodecs-0.16.5-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:b05647b8b769e6bc8016e9fd4843c823ce5c9f2337c089fb5c9c4da05e5275de", size = 1654721, upload-time = "2025-11-21T02:49:40.602Z" }, + { url = "https://files.pythonhosted.org/packages/a1/37/260fa42e7b2b08e6e00ad632f8dd620961a60a459426c26cea390f8c68d0/numcodecs-0.16.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:3832bd1b5af8bb3e413076b7d93318c8e7d7b68935006b9fa36ca057d1725a8f", size = 1146887, upload-time = "2025-11-21T02:49:41.721Z" }, + { url = "https://files.pythonhosted.org/packages/4e/15/e2e1151b5a8b14a15dfd4bb4abccce7fff7580f39bc34092780088835f3a/numcodecs-0.16.5-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:49f7b7d24f103187f53135bed28bb9f0ed6b2e14c604664726487bb6d7c882e1", size = 8476987, upload-time = "2025-11-21T02:49:43.363Z" }, + { url = "https://files.pythonhosted.org/packages/6d/30/16a57fc4d9fb0ba06c600408bd6634f2f1753c54a7a351c99c5e09b51ee2/numcodecs-0.16.5-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:aec9736d81b70f337d89c4070ee3ffeff113f386fd789492fa152d26a15043e4", size = 9102377, upload-time = "2025-11-21T02:49:45.508Z" }, + { url = "https://files.pythonhosted.org/packages/31/a5/a0425af36c20d55a3ea884db4b4efca25a43bea9214ba69ca7932dd997b4/numcodecs-0.16.5-cp314-cp314-win_amd64.whl", hash = "sha256:b16a14303800e9fb88abc39463ab4706c037647ac17e49e297faa5f7d7dbbf1d", size = 819022, upload-time = "2025-11-21T02:49:47.39Z" }, +] + +[package.optional-dependencies] +msgpack = [ + { name = "msgpack" }, +] + +[[package]] +name = "numpy" +version = "2.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/80/db0b4559e57ec36362bedbb05530a87fafbcb6067708c946967a41d449e7/numpy-2.5.2.tar.gz", hash = "sha256:d482d171c406ae88c5b19cad3b6a1c4c5209f886ab74bc44c2c865c23f52d860", size = 20773161, upload-time = "2026-08-09T13:48:27.962Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/72/dccb0aaf40972777283303919f613964227266d0c13adebb79ac124f1c3e/numpy-2.5.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:14e373cfc6387177e8409dac3c7159be8eb05cd77096cd7c950268b86f62831c", size = 16891693, upload-time = "2026-08-09T13:44:51.702Z" }, + { url = "https://files.pythonhosted.org/packages/60/2e/b5aee50a1f74ac815cf8331812cb8251e29024025de462e0c047641c614c/numpy-2.5.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4bbd96c833ecc8cc069ce518078fc8c60cb9cbfb0fea5b7a803ad65035596d03", size = 11903109, upload-time = "2026-08-09T13:44:55.501Z" }, + { url = "https://files.pythonhosted.org/packages/f3/f4/29e78102a80601cf034d4e9767022cffeca2c3b4c926e1754572ca95593d/numpy-2.5.2-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:6e8172ddfcf5cf74b811d372b570b83c60bd2de87a6fbfbebdadb4a9bd9c6cbb", size = 5350202, upload-time = "2026-08-09T13:44:58.401Z" }, + { url = "https://files.pythonhosted.org/packages/11/4b/dcd3b7eadaf4035d2c7a4289d232523a6964f602598ef7674e4bd7291f93/numpy-2.5.2-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:65f188481f1669e26f62b701e8205d19e460fa4a9b52a1414ba382330e4a3414", size = 6687736, upload-time = "2026-08-09T13:45:00.813Z" }, + { url = "https://files.pythonhosted.org/packages/e5/21/4947e0e9d6c9fc2e2ff15b8949049ee44f63adb9cacc729ab8793f97e712/numpy-2.5.2-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8ee9c4eeb8454b3660a8b53493563c3e121c2fc94fbd72b848ef814ed7b676a9", size = 15612696, upload-time = "2026-08-09T13:45:04.151Z" }, + { url = "https://files.pythonhosted.org/packages/3a/5f/62d28cf019460c7f1394105b4d49d9911a9c444cb77ab0bd95a204c5a6de/numpy-2.5.2-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3cdec01fa790a186d430433fdd4d4ffb70eed6f0eeb4bf05c8dbe2dce0a9bcb8", size = 16722264, upload-time = "2026-08-09T13:45:07.714Z" }, + { url = "https://files.pythonhosted.org/packages/14/25/3f0be4c1b9fdf5dd5e708a6806978564d7c46a055c000496309ff2a2f8af/numpy-2.5.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:7999d4ddb0c4025018373fd787510d46e04c769467af22869707b3c1cfd459ab", size = 16974396, upload-time = "2026-08-09T13:45:11.316Z" }, + { url = "https://files.pythonhosted.org/packages/22/72/6262cbdeeb45da9d971e40715f579d791603ba8ec0b5e2db1ac55454421d/numpy-2.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c1f017dc0875c9209d219f97feceb7d54c2661bb243deb4114478e1295808af7", size = 18476044, upload-time = "2026-08-09T13:45:14.869Z" }, + { url = "https://files.pythonhosted.org/packages/36/33/29208b8b075bde62d26a81d14b358c42b0f69b6cabd98d4ff97f37f22b05/numpy-2.5.2-cp312-cp312-win32.whl", hash = "sha256:d6a48072864e3324e194a8fbb3c657bcc5b5c869dbc64c9537b1d5c862572c0a", size = 6072817, upload-time = "2026-08-09T13:45:17.867Z" }, + { url = "https://files.pythonhosted.org/packages/7f/b9/87fea2769fe1c47c1b5b01d8310772c9d1a85d485de7cf386ef7a3332b02/numpy-2.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:28ac63476ec7651484215ee7fa15a1f78b57c14621f01e392afe17b9a1390ce4", size = 12464674, upload-time = "2026-08-09T13:45:20.734Z" }, + { url = "https://files.pythonhosted.org/packages/14/52/032b97e00461ab0809bbe4c588b035620e5a14b8cdee47ecddefc7b17d33/numpy-2.5.2-cp312-cp312-win_arm64.whl", hash = "sha256:27650bb0e7140fa3d37b9923b4803645e0b125d190f326eecfd3f4dad8e8ade1", size = 10397131, upload-time = "2026-08-09T13:45:23.73Z" }, + { url = "https://files.pythonhosted.org/packages/f5/d2/6b24738a0ef4557d189b150046cd07823c50e4273e8aebd651222e24306f/numpy-2.5.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8e4cb9a754c8a0c62eaa88273a5fba3391f4a610d1dee893c0755da31c083f15", size = 16886595, upload-time = "2026-08-09T13:45:27.323Z" }, + { url = "https://files.pythonhosted.org/packages/65/60/f2d208d366f263f39c6e69ed309290717aab41078b6d04c9be2a84fa2a07/numpy-2.5.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:52c808f96484f5571a5cc863775ce50247c17dfb3b0361f8ed6b4b0456f80080", size = 11896845, upload-time = "2026-08-09T13:45:31.638Z" }, + { url = "https://files.pythonhosted.org/packages/3c/79/81e0bf24f4d020a2b1d5cd297a9f60c3f24eeb116f9bba5870443f7b6a4a/numpy-2.5.2-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:29d81e97f668489cba8ebfd796b9bdd453525d35dd9e162e2daec94bf3fc7740", size = 5343880, upload-time = "2026-08-09T13:45:34.373Z" }, + { url = "https://files.pythonhosted.org/packages/ba/cc/e3141cf06d1a8a2c7e107543fe1269c1d1af760d4d683c0794a4ee1127c2/numpy-2.5.2-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:afb3f0632d6b2e3ba04dbce8d1e48d321b369138b73830b5ca371a0e8d479d56", size = 6682264, upload-time = "2026-08-09T13:45:36.7Z" }, + { url = "https://files.pythonhosted.org/packages/29/f1/2a64a307d92c5d98f5255a4014eb43bb6103ee477087b61ecae44a3aa9b9/numpy-2.5.2-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0aadf13b60048d501e05fa699efaf7734e2494f3498a4c2a5521d822640324f3", size = 15609566, upload-time = "2026-08-09T13:45:39.518Z" }, + { url = "https://files.pythonhosted.org/packages/7b/44/59a1eb68e773c4098d107ef34a0dbdeca501d72ffcfbff9a7707343921ce/numpy-2.5.2-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:29b86ff8a6cc556b47ec6b64b194815cc80e6bf5eedcc6cddfd65318cb0b4eee", size = 16709995, upload-time = "2026-08-09T13:45:43.661Z" }, + { url = "https://files.pythonhosted.org/packages/8a/4c/3e54d4ddbc359a1295f8b633e8106bcd4d7d4a206e82df051bdfb3058755/numpy-2.5.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:6950c4b7dd562453090548ba7f5da7e59f57f85663f15d5dcc60e249192f7e59", size = 16972511, upload-time = "2026-08-09T13:45:47.094Z" }, + { url = "https://files.pythonhosted.org/packages/f2/9f/02e371638ebf19b66d46231e4be52999e87f32d1961b113bc45656608b22/numpy-2.5.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b9727f472d2f3888053b8a75ab0cb94745a9de224bb5846dbadc0092101bc71d", size = 18465609, upload-time = "2026-08-09T13:45:50.808Z" }, + { url = "https://files.pythonhosted.org/packages/eb/ae/ad6645abc7a3510fe48e8ea1ab4598166f500057ef4ebf38bfad4f1577de/numpy-2.5.2-cp313-cp313-win32.whl", hash = "sha256:4f9744f9fbdcea0bc552e8f19e1f141f811a3f9bc2be2cc6e86d982cab23e3f4", size = 6070204, upload-time = "2026-08-09T13:45:54.111Z" }, + { url = "https://files.pythonhosted.org/packages/15/20/f3489f86d81ea460b2bcdceaed094142ca6579f6be0ec527b781d39afe68/numpy-2.5.2-cp313-cp313-win_amd64.whl", hash = "sha256:85aaccb24182c25df891ad0ec333585967e115269d5f1b17f2c9ae005bc96657", size = 12460532, upload-time = "2026-08-09T13:45:57.167Z" }, + { url = "https://files.pythonhosted.org/packages/d5/21/35b31dde1b283b79de828b80f876afd8c94e28fe1e9c375f89e261cc4c0d/numpy-2.5.2-cp313-cp313-win_arm64.whl", hash = "sha256:bd68ece1553d2023c09a4226d9e41c586ad2d20594d1a456186c33513d2cb3f2", size = 10396725, upload-time = "2026-08-09T13:46:00.478Z" }, + { url = "https://files.pythonhosted.org/packages/ac/f8/c3b222bf075b50afd8e949a07a15c4b312a4a84bd8102a332bcd953cbbb4/numpy-2.5.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d787cf769c3baeb5f6235e778edb52c08dfa923789b5958f28e6450f96107cb1", size = 16885180, upload-time = "2026-08-09T13:46:03.939Z" }, + { url = "https://files.pythonhosted.org/packages/17/e1/2c1d4b1987795a92b5bbf7c24fe249ab96aa2573ab0d7604802c189d7b86/numpy-2.5.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:24b9dc2e3d84aa58523798805194e23e736f3f6ce2d1a5b92583ae734e6dbda8", size = 11907878, upload-time = "2026-08-09T13:46:07.045Z" }, + { url = "https://files.pythonhosted.org/packages/b9/ee/d08226fc858044355983a6e5b94f08ff6f3969e0a2b160a4a89f0ddb3445/numpy-2.5.2-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:9e9413326d726c2545bfa65d2c0876871e8d8386e77f992c1d426e180bbd4323", size = 5354922, upload-time = "2026-08-09T13:46:10.04Z" }, + { url = "https://files.pythonhosted.org/packages/94/f0/6d3d933056440ebbc5e6bad92065fc6c26a48a84a36b1208580e94eea76c/numpy-2.5.2-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:60e902ac295855348a5ca2ea4c89108989a9f5fddfad3dfc0a8f36b10358567e", size = 6679168, upload-time = "2026-08-09T13:46:12.275Z" }, + { url = "https://files.pythonhosted.org/packages/c4/3b/ecd49dd90033cceb2704d88ca905d4d7d89b0e8c739608754ffd325fa820/numpy-2.5.2-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:50e500dc868e9313530ce12ba470fe50ff3afe3d62993ed6eff652dacd555b65", size = 15624501, upload-time = "2026-08-09T13:46:15.322Z" }, + { url = "https://files.pythonhosted.org/packages/c7/99/461bd36dbdfac6c1c53efa370bd55a83227542d0d118f1677dbf1a3dacd5/numpy-2.5.2-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:318b9a4c845dbea06708a29c84ee429cc3065048db34cdb799047643492050ee", size = 16713701, upload-time = "2026-08-09T13:46:18.949Z" }, + { url = "https://files.pythonhosted.org/packages/f9/9c/2b251df9e8a5d647b62b0cbc1b90a91850c1cf4859ecb532fd0b4eacff6c/numpy-2.5.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:34c319e2963be042673fb46570501b2f06c41924e17e3563d58646b4380dfb68", size = 16986065, upload-time = "2026-08-09T13:46:23.006Z" }, + { url = "https://files.pythonhosted.org/packages/8f/25/20de43f53ff1390534a124475055a19f01fe10c920a0fd11b8e18d6d6052/numpy-2.5.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f06571a052127dc1b4e8b83029b4d1b20daa2b64a31cdd181fc6bc774e9000eb", size = 18470031, upload-time = "2026-08-09T13:46:27.102Z" }, + { url = "https://files.pythonhosted.org/packages/56/5e/0c577ca308d6da5eb79b546ba10bbe5b60148192194e2da060913b1de4f1/numpy-2.5.2-cp314-cp314-win32.whl", hash = "sha256:2cc779226e476d1e1f08c74068c419e60f41a9e0e069c92f6671d31d5c985e98", size = 6121028, upload-time = "2026-08-09T13:46:30.046Z" }, + { url = "https://files.pythonhosted.org/packages/15/5c/7bcbd5b11f94199073320410cddcbb80cee62415bfeb540874b265c2d922/numpy-2.5.2-cp314-cp314-win_amd64.whl", hash = "sha256:7587f53dfbd5edc0f7b87c6217b4c6d2d1f2ef9c3da70bc1315e7db5f8d7ec9d", size = 12597627, upload-time = "2026-08-09T13:46:32.886Z" }, + { url = "https://files.pythonhosted.org/packages/87/bc/4d0b06fba0da90ccc75af62823cb9dcedb6c9ea0cffa058cb2c9ee773a77/numpy-2.5.2-cp314-cp314-win_arm64.whl", hash = "sha256:3e4c367352d3747784248a227fbec218e193b56f7e6692e3b64fc805478ecfdf", size = 10680414, upload-time = "2026-08-09T13:46:36.036Z" }, + { url = "https://files.pythonhosted.org/packages/cd/17/f429aac9dc08833a0d0f188eba38c532a751b1a1f2ca6018a37b455cb321/numpy-2.5.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:b879fb674276e331513fb136b78dbc6bd3c848309e0d841cfd63be3896c4cfc1", size = 12026967, upload-time = "2026-08-09T13:46:39.084Z" }, + { url = "https://files.pythonhosted.org/packages/ca/9f/d0849de96a2a4ceaa16662f18ee13eaa9c0aa418269fdc8c4857c56b11da/numpy-2.5.2-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:fd0d703772bba096843785bd38371e31bb4a0c1151497ad5739d182114a73f7f", size = 5473874, upload-time = "2026-08-09T13:46:42.075Z" }, + { url = "https://files.pythonhosted.org/packages/89/3c/8df216d4a4a5422a3de045301cf7df8ea47286d76f5cb7160b0128ac26b7/numpy-2.5.2-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:3a2f061cebd9e3d23bdcfaaded5e2293a4c6a5b60fa42df85d410a725ce621bf", size = 6789276, upload-time = "2026-08-09T13:46:44.387Z" }, + { url = "https://files.pythonhosted.org/packages/e6/3a/20d7e9891c4ddfadd6ff8d95bf4b29f353d8e1770553de2099880551dfb9/numpy-2.5.2-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6df895598c0edcb41030126c89e0f353b07d93238116143b7405e937359736c4", size = 15659154, upload-time = "2026-08-09T13:46:47.538Z" }, + { url = "https://files.pythonhosted.org/packages/aa/d6/f3aa3d2688bf501b858835c6bd087ae9b51a56ae6fca8e2b0990abd177af/numpy-2.5.2-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1ab3d4a901f844ea836c3e80bf463c6a27d7f3c14e8e292fcf28d348b25b9bce", size = 16748909, upload-time = "2026-08-09T13:46:51.442Z" }, + { url = "https://files.pythonhosted.org/packages/7d/8f/1c5cae8d2baf86ab802ae97a00be55bc7e21ebc11b12bbc33376c5f05342/numpy-2.5.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:cebc2d6dbb605a7703d59751dea4bd6b0ab127a5a4338a6f432df1936fef8b26", size = 17027685, upload-time = "2026-08-09T13:46:55.095Z" }, + { url = "https://files.pythonhosted.org/packages/5c/27/71d3467404aedc1c24ce79610f91b52b0b0f466c43a701aa56fc75c145ab/numpy-2.5.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:eaca7ff36f0f52e2111ec71f169d8fd3e889e7ddc0d2592e0d703fd8d3ce8fac", size = 18501181, upload-time = "2026-08-09T13:46:59.09Z" }, + { url = "https://files.pythonhosted.org/packages/14/2f/42921d27c40aea7e077f4a423ae509fd9220b028cd787bafefd8ab2b3a5f/numpy-2.5.2-cp314-cp314t-win32.whl", hash = "sha256:ddf47472af2e4280d79bac82304f5e80150211f1b9e614b760061d5fdfbb6eba", size = 6271085, upload-time = "2026-08-09T13:47:01.903Z" }, + { url = "https://files.pythonhosted.org/packages/75/e6/bad5f5d56de9b1971bac959963dda276d35c40f1854475005434bbe08692/numpy-2.5.2-cp314-cp314t-win_amd64.whl", hash = "sha256:44ef9675d908e65f9953063837c3277730f3f4437615a4cdab67b366cabaf884", size = 12787971, upload-time = "2026-08-09T13:47:04.963Z" }, + { url = "https://files.pythonhosted.org/packages/df/05/f608795cb34391acd67e38d94a3c36abd8d8576293a3a80727d7595c372c/numpy-2.5.2-cp314-cp314t-win_arm64.whl", hash = "sha256:eaa088384c46f519dacb93b7ec483a6d6b19a4a2085ae4f25ab9b1c43d387d1e", size = 10750306, upload-time = "2026-08-09T13:47:07.976Z" }, + { url = "https://files.pythonhosted.org/packages/33/c6/28de0191c5f82b7d42a0a51390ba98587048aa93a39fafb05bdbe6e8d00c/numpy-2.5.2-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:078f9b027b478c9379b9677babbf0f8b8f1ecfada27636d7b9a93990c638739f", size = 16885274, upload-time = "2026-08-09T13:47:11.439Z" }, + { url = "https://files.pythonhosted.org/packages/dd/d1/973ca116000d244897e468ea1aff30b589e5022e3c8744b71706fe33bd57/numpy-2.5.2-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:50a68f4bacd8a2b33d8da3d2269d0d78500f86ea582e4786dc10f5ef2c2c6842", size = 11907846, upload-time = "2026-08-09T13:47:15.128Z" }, + { url = "https://files.pythonhosted.org/packages/78/d9/8c4b3937ef204cb2fd88d389ccd0f265a2ffb11f35a01d2064cf46714bd6/numpy-2.5.2-cp315-cp315-macosx_14_0_arm64.whl", hash = "sha256:e79aba74ffaf5f78a050d777c184cddf8fdffabab38acf5f3ef1fecbc17895d6", size = 5354892, upload-time = "2026-08-09T13:47:18.07Z" }, + { url = "https://files.pythonhosted.org/packages/74/9b/b6ee65ea2999fdb7023935e108e6fb776ee4082aa15f159acfa857e578c8/numpy-2.5.2-cp315-cp315-macosx_14_0_x86_64.whl", hash = "sha256:9a0731745a72a184490a582fb4af2533512bd071ace67785b5fdffc0ae58dce8", size = 6679309, upload-time = "2026-08-09T13:47:20.456Z" }, + { url = "https://files.pythonhosted.org/packages/43/f3/acb18d8b137a393c8e7803a8c994c9e64bde3930692a69d826993113a159/numpy-2.5.2-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4ec954036759bcee3aa484f8603bd9c14f3e776293b85578b8734c2d72777c69", size = 15625850, upload-time = "2026-08-09T13:47:24.365Z" }, + { url = "https://files.pythonhosted.org/packages/a9/bf/a8e9bb0db815a0e265b5744ebedd3af0bd5faad8604e5b50a1cd012f3c91/numpy-2.5.2-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:dc649493697006bc90614a5f0bbc8cb3cb1866715c474e473694968d7e6b99ab", size = 16713664, upload-time = "2026-08-09T13:47:27.965Z" }, + { url = "https://files.pythonhosted.org/packages/0c/c3/6e913736b3dd6582344af32418b5fb9dab34282e8a8174ae1d54ceb0fc13/numpy-2.5.2-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:cf7de32f486e4ac9e2d93b810f9e9ac72a728dd46a32a0bb403222f27f653514", size = 16986749, upload-time = "2026-08-09T13:47:31.541Z" }, + { url = "https://files.pythonhosted.org/packages/80/09/7d3b23eff5c7428ef6c01e6f7052bb60d504c4d33e317b36b8959c24ad97/numpy-2.5.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:2ffa7bacab3e2ee1b19ed31766bb60bb380b68c23f051e199c5cc598afd68710", size = 18470495, upload-time = "2026-08-09T13:47:35.364Z" }, + { url = "https://files.pythonhosted.org/packages/a5/a4/68a321d825374f6eb677ffe8ef8c6b9a328304e6fd2e39d9530822776607/numpy-2.5.2-cp315-cp315-win32.whl", hash = "sha256:6b588cc8f902d6bff201c19fd00c43ab8545671e3554d014e12e14139e5e8617", size = 6120696, upload-time = "2026-08-09T13:47:38.561Z" }, + { url = "https://files.pythonhosted.org/packages/c8/23/deafbb1700f79fae9cd1e91220f133d124cc267de1b584da3fbf6db2f6cd/numpy-2.5.2-cp315-cp315-win_amd64.whl", hash = "sha256:07d4e89f3a9ab0a9ba24264ccdb642b3dd951b2281e8883a5481a4aa79cc31a7", size = 12597324, upload-time = "2026-08-09T13:47:41.401Z" }, + { url = "https://files.pythonhosted.org/packages/33/cd/3272ba105e3bbbdaeb11357eda31e7a6825ffe159e8171665660299a948f/numpy-2.5.2-cp315-cp315-win_arm64.whl", hash = "sha256:a610dc7e3c52edd39c2bc2375ff9c3fd59cb3ad00e4472d36f83bc1457145788", size = 10680466, upload-time = "2026-08-09T13:47:44.873Z" }, + { url = "https://files.pythonhosted.org/packages/0e/0e/58370637b1bb70a5c9ce2b43f4b521ccb224e36ccb76a6596b17ae4b447c/numpy-2.5.2-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:40f4d451aed46a8046a1aae41c4e55fb3612273df9c502480135e1501576a34b", size = 16993947, upload-time = "2026-08-09T13:47:48.97Z" }, + { url = "https://files.pythonhosted.org/packages/10/93/2abcb807712b289d6d60fe4cf30532f98974a8396d885650f3ba5a13026e/numpy-2.5.2-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:c081cbe16ba1ab53078e5ff29013621e33c509eedab055775d956427712c236e", size = 12025331, upload-time = "2026-08-09T13:47:52.646Z" }, + { url = "https://files.pythonhosted.org/packages/8b/3a/2898e003a5fbaf87e76c039b4ee1f5eb390471b4ffe74887c1f34c4e791e/numpy-2.5.2-cp315-cp315t-macosx_14_0_arm64.whl", hash = "sha256:0090ccdd57ec2703e9b49d0bf554767370581c1dd0a6b2bb2b2d9def317d042a", size = 5472336, upload-time = "2026-08-09T13:47:55.403Z" }, + { url = "https://files.pythonhosted.org/packages/61/a5/23f69d07c544597b29758b31b55c27dc9d541012a2c1496189fef702aec2/numpy-2.5.2-cp315-cp315t-macosx_14_0_x86_64.whl", hash = "sha256:6a9bb119fb8dd21ba30b3f0e555b7e2b081bd9883af21ec9c1c633d161cda3a8", size = 6788387, upload-time = "2026-08-09T13:47:58.192Z" }, + { url = "https://files.pythonhosted.org/packages/15/ea/c0dbdbcf22f43782510a3e492dd3da73c6112b69cac8929d16d127536fc4/numpy-2.5.2-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a839318485284a6fb31be4f8f2c91c8f2cb22f4543c4a8903f12b0671ffe07cc", size = 15667096, upload-time = "2026-08-09T13:48:01.562Z" }, + { url = "https://files.pythonhosted.org/packages/fc/5e/29c73c31748cdb0f7566642125ba17fd5b56780cddf891b085dab27e4466/numpy-2.5.2-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba0a474801b8dc67b66bf465548abc90e82b44d2611b5770f33008dcabffe8ec", size = 16751730, upload-time = "2026-08-09T13:48:05.706Z" }, + { url = "https://files.pythonhosted.org/packages/47/95/02501e8454796bb58dadf7a99d3181e0b464bf264e1003039572f9779fac/numpy-2.5.2-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:0a4035ae1129ff8777f08bfbd44f1e5d8e9c049ce0c2dd78fc0d92c13e7251c0", size = 17038686, upload-time = "2026-08-09T13:48:09.627Z" }, + { url = "https://files.pythonhosted.org/packages/0e/b5/53a681d91b5c82687067d8ea5035e02d917b5509d6f334cb06484a954714/numpy-2.5.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:77843ca236b777e67f8d6b3660ea116e499612703a0ecd7093f316201eb9d8e2", size = 18507727, upload-time = "2026-08-09T13:48:13.744Z" }, + { url = "https://files.pythonhosted.org/packages/42/06/6e11443f7b64ee376c860506091103bf68f92d2cab9e8d96d4501babf07c/numpy-2.5.2-cp315-cp315t-win32.whl", hash = "sha256:7354826bc6f8f69402e9b7fe28d15fcd34feebd74f856f111585c5b0c9fb0251", size = 6269775, upload-time = "2026-08-09T13:48:17.543Z" }, + { url = "https://files.pythonhosted.org/packages/f1/18/195d6b86cd72dbbc501edfa778005fa6b87afd34c153e46028cd3a0938f4/numpy-2.5.2-cp315-cp315t-win_amd64.whl", hash = "sha256:e5651f3f87add730ee6608d915009e19c911fba0cb000c7e3ea994b7d768eb12", size = 12782559, upload-time = "2026-08-09T13:48:21.023Z" }, + { url = "https://files.pythonhosted.org/packages/b4/07/458c344f0f0c178f4481dad5cca790626ffe4c34eabf9467069d06ee4999/numpy-2.5.2-cp315-cp315t-win_arm64.whl", hash = "sha256:5f8e00be2ec6f45f4e8a41a527f68d44a7d96fee92a650e4d8b1326f77f61e6e", size = 10748103, upload-time = "2026-08-09T13:48:24.21Z" }, +] + +[[package]] +name = "numpydoc" +version = "1.10.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sphinx" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e9/3c/dfccc9e7dee357fb2aa13c3890d952a370dd0ed071e0f7ed62ed0df567c1/numpydoc-1.10.0.tar.gz", hash = "sha256:3f7970f6eee30912260a6b31ac72bba2432830cd6722569ec17ee8d3ef5ffa01", size = 94027, upload-time = "2025-12-02T16:39:12.937Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/5e/3a6a3e90f35cea3853c45e5d5fb9b7192ce4384616f932cf7591298ab6e1/numpydoc-1.10.0-py3-none-any.whl", hash = "sha256:3149da9874af890bcc2a82ef7aae5484e5aa81cb2778f08e3c307ba6d963721b", size = 69255, upload-time = "2025-12-02T16:39:11.561Z" }, +] + +[[package]] +name = "obstore" +version = "0.11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/2e/2f/f83afaab7945509d72245b2b00af0b4834ce78fdd2d9ae9f0ad1a3036a91/obstore-0.11.0.tar.gz", hash = "sha256:a2f55163bcd348b4a60d12e6893eac50eddc742bad8032a1705d49140b992204", size = 130565, upload-time = "2026-06-25T18:29:49.405Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fc/b2/00c213e7e5ca8065f97e37e55294adab836e3f6a88b23e4029069aaecf95/obstore-0.11.0-cp311-abi3-macosx_10_12_x86_64.whl", hash = "sha256:42f36546c7ac44dbab1173d2330a8a1b1a3f0e37950e553b8c904e3dd0744b25", size = 5491935, upload-time = "2026-06-25T18:28:32.029Z" }, + { url = "https://files.pythonhosted.org/packages/ac/37/6a6b9a5e15a8a37c24d14317a87648097c4888593b588510c03c030d2e90/obstore-0.11.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:687bb9d3962d568b7c439c5d0c6fea19b2749862a8e5c8eebd0c058c4eccde9e", size = 4672619, upload-time = "2026-06-25T18:28:33.852Z" }, + { url = "https://files.pythonhosted.org/packages/28/f9/6745ce8c4f7bfac19dc14a4438b48a2e93a689b92b0cecfc695e41a4e8b1/obstore-0.11.0-cp311-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:010b51578c7514a41719d795cdb7a1e6529be509dac3772e477187a59422bb97", size = 5072806, upload-time = "2026-06-25T18:28:36.127Z" }, + { url = "https://files.pythonhosted.org/packages/6c/18/991d3b3cdd851c0225e55f3dc45b47fd9e249827d188995011469f805132/obstore-0.11.0-cp311-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cfaa8129a3f5d8518a3a75184d4b02348db0f6263177cd1f0951f6568243cc9e", size = 5303777, upload-time = "2026-06-25T18:28:37.89Z" }, + { url = "https://files.pythonhosted.org/packages/8d/e9/90e56015a45b5e56a84fc3188c4e5fb088b288d41992c73a629e10df6760/obstore-0.11.0-cp311-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c790a5cb9ff2970d1f464a6a708d734dce9939e9f668cb6708c5dba5d61589b2", size = 5493871, upload-time = "2026-06-25T18:28:39.981Z" }, + { url = "https://files.pythonhosted.org/packages/66/02/f1744091d59ce71c5523174eb860fbb298275c901e89b9ea6fbf3e654a33/obstore-0.11.0-cp311-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:827113e12fe8088e0281a9d57b90b2b8dbc8a6ffe3b15dadb9baa5feb3d266c1", size = 5361913, upload-time = "2026-06-25T18:28:42.089Z" }, + { url = "https://files.pythonhosted.org/packages/5d/59/3f47822683ee2b6db8685faa25829946d6343a561251ec2704548455d946/obstore-0.11.0-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a2ff6d3ed553298828fb760b4aef6347fbcc7b5c5e3ce3f8381ce805c370021a", size = 5638724, upload-time = "2026-06-25T18:28:43.897Z" }, + { url = "https://files.pythonhosted.org/packages/23/50/1df335fdf9b527b3933f1e94ab6fc720ad314260fab8591cb0b6668ff192/obstore-0.11.0-cp311-abi3-manylinux_2_24_aarch64.whl", hash = "sha256:39d04b324fcf984e7050734ebda77b81764025b0c011750201a0d8954087f7aa", size = 5413508, upload-time = "2026-06-25T18:28:45.624Z" }, + { url = "https://files.pythonhosted.org/packages/de/dc/a259aba149b841ca7c91fea177df9972a60a636b54077beed1a35b254994/obstore-0.11.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:37c0d15d775b1370ef5204ee3919a5ddf7e2592d11815213105f8db031f2ab8d", size = 5619995, upload-time = "2026-06-25T18:28:47.599Z" }, + { url = "https://files.pythonhosted.org/packages/e5/b4/ec25fdb4d6b060bc6eea647fc0e88f75fcc20fe8d16d67fb0dbe999d323b/obstore-0.11.0-cp311-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:7f468caf9b6e0f12ff151e5fe618de5fc9192befa9bd02734b06de4efd2e49f6", size = 5299512, upload-time = "2026-06-25T18:28:49.629Z" }, + { url = "https://files.pythonhosted.org/packages/a8/e5/29be060d06ec13e2af3d1b6cfb77b7c37f8be6c56b77295c945fefad73e4/obstore-0.11.0-cp311-abi3-musllinux_1_2_i686.whl", hash = "sha256:42d8e8fad85be8ee488c1a9a9b7c6a42128abb84e67175da40d3d1165c1846df", size = 5427026, upload-time = "2026-06-25T18:28:51.317Z" }, + { url = "https://files.pythonhosted.org/packages/57/b7/577a965f440e9ea64243518663f9d16be7df8eafc7123818e8e841fa21ce/obstore-0.11.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9c8fd2a544e2e0b926669c47fcfb8d2314e234abc240ea165dae04ee42e1d7ac", size = 5869187, upload-time = "2026-06-25T18:28:53.166Z" }, + { url = "https://files.pythonhosted.org/packages/e2/18/8fdbaee22bfd5b9c44e1fdff8ca0508e2fe60c42bf9fc85f0c9c27b4ecf2/obstore-0.11.0-cp311-abi3-win_amd64.whl", hash = "sha256:6fb3d4678c0f4242d3109362e9b1df5d7b27765f43d5aacb2e81af53a75cb9ef", size = 5329384, upload-time = "2026-06-25T18:28:55.305Z" }, + { url = "https://files.pythonhosted.org/packages/8b/8b/7555e48ec768728fcfc71a051c6b28d6ddaf1bececf492ce5ef995aab5f0/obstore-0.11.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:f3132393eff9f3f2b543ecbb3bcc12319a7c433fef06493b4350d6854d505a14", size = 5515763, upload-time = "2026-06-25T18:28:57.527Z" }, + { url = "https://files.pythonhosted.org/packages/23/8f/94d83f3336421cbb5e436ab0ae5695eae72f7c82990d6b1ac090712c8052/obstore-0.11.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a3a8da19b47af4c14ecc694209b3c18ac6d89f96be5656ee3a19b77947c14155", size = 4649491, upload-time = "2026-06-25T18:28:59.386Z" }, + { url = "https://files.pythonhosted.org/packages/fe/86/11f4e1f51a8c6cf21a5915c018d2357201ad3c5799d418f0c6529fafaab2/obstore-0.11.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e91298b9b6c3a0408c28eece62bca6c5b6cda2f6350351d84e07b4dc8fb2631f", size = 5060659, upload-time = "2026-06-25T18:29:01.139Z" }, + { url = "https://files.pythonhosted.org/packages/49/e7/fd3036b0923d10e878e2073020f1ef692a618ed1cc3980d3e4a468c93713/obstore-0.11.0-cp314-cp314t-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3422c532486671dfb5e3e739bf15ec9ca2a8da544a3c23b74ae3857dcab1c6a8", size = 5277058, upload-time = "2026-06-25T18:29:02.96Z" }, + { url = "https://files.pythonhosted.org/packages/2f/a7/b016c3ac6857ac856326dc0a292e3871b8500d03f25f3b90e168b05de357/obstore-0.11.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3de027ce46cf0592c2b41654e2c27dbc52a4a726f6fbc511380acc0da3a9f658", size = 5475852, upload-time = "2026-06-25T18:29:05.032Z" }, + { url = "https://files.pythonhosted.org/packages/85/9e/644ffe8db7757de7f71f94a036ab24222bccb4de290d3ca69f76547e812d/obstore-0.11.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1a80a95548678210bc336b866e37139c293565c3b163eb3fef2433d5d6640a33", size = 5363082, upload-time = "2026-06-25T18:29:06.878Z" }, + { url = "https://files.pythonhosted.org/packages/ae/0b/26af6b5fa6ba96af84086f44f78b4e5b0af1729c31402d7b28c68989d174/obstore-0.11.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:acaa261dc15efb95bbeca06f8fe9b47ee23d7302a6aa1fa3a9654baab8b23d7c", size = 5629116, upload-time = "2026-06-25T18:29:08.771Z" }, + { url = "https://files.pythonhosted.org/packages/ae/ce/f30d502991c6719b2fbd7b8385ef3e39da07bfca099108bcc5eeed8b9c20/obstore-0.11.0-cp314-cp314t-manylinux_2_24_aarch64.whl", hash = "sha256:a3300cabbc3129670987b3723629c791d83c117ef1b6a0c670c2043648e000a1", size = 5404534, upload-time = "2026-06-25T18:29:11.294Z" }, + { url = "https://files.pythonhosted.org/packages/52/20/d5bf5f816e868717ba647ed9a2109e800deb402d0265d410456b3fcb4376/obstore-0.11.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:f4e6a9480843645cd4ee122c41d5c5a46a56f1e9cdda85638826f2e0e439fe5c", size = 5613159, upload-time = "2026-06-25T18:29:13.414Z" }, + { url = "https://files.pythonhosted.org/packages/db/b4/6d4c1c211e3b06cc8554189e0d4406e8fa1f98ed55f9213b8e398a11599f/obstore-0.11.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:9fb2b1814c4314b8903f4e2ebbe8c3365fea6543669615ee9a0288b0d3a2edeb", size = 5286279, upload-time = "2026-06-25T18:29:15.424Z" }, + { url = "https://files.pythonhosted.org/packages/02/5e/d7b5589424a56171b16ab94cf92eb493490c300aaa044913bbdd94cace68/obstore-0.11.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:63fb9b072815eafe4705f617f567d896b1c858adcb390795fa1e269367791031", size = 5401780, upload-time = "2026-06-25T18:29:17.514Z" }, + { url = "https://files.pythonhosted.org/packages/c4/18/841baea8936e51a18b0e5d4c51f09c0a7798cb73b027e9794be2362a0f0b/obstore-0.11.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:086fafba314ff98cfab1c4bf7814699e862513e8889720cf6f7462296cb32787", size = 5853618, upload-time = "2026-06-25T18:29:19.354Z" }, + { url = "https://files.pythonhosted.org/packages/83/9a/d6127f5422b78e0222b0a9eadcfd7a5aa8d873a9498da7d4a77d4ac8ce2e/obstore-0.11.0-cp314-cp314t-win_amd64.whl", hash = "sha256:676d1154f6f08721110f9b7d14ee3a3c0293abaf9da135bb90f54e276dca1cac", size = 5314113, upload-time = "2026-06-25T18:29:21.209Z" }, +] + +[[package]] +name = "openapi-schema-validator" +version = "0.8.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jsonschema" }, + { name = "jsonschema-specifications" }, + { name = "pydantic" }, + { name = "pydantic-settings" }, + { name = "referencing" }, + { name = "rfc3339-validator" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/21/4b/67b24b2b23d96ea862be2cca3632a546f67a22461200831213e80c3c6011/openapi_schema_validator-0.8.1.tar.gz", hash = "sha256:4c57266ce8cbfa37bb4eb4d62cdb7d19356c3a468e3535743c4562863e1790da", size = 23134, upload-time = "2026-03-02T08:46:29.807Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6f/87/e9f29f463b230d4b47d65e17858c595153a8ca8c1775f16e406aa82d455d/openapi_schema_validator-0.8.1-py3-none-any.whl", hash = "sha256:0f5859794c5bfa433d478dc5ac5e5768d50adc56b14380c8a6fd3a8113e89c9b", size = 19211, upload-time = "2026-03-02T08:46:28.154Z" }, +] + +[[package]] +name = "openapi-spec-validator" +version = "0.8.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jsonschema" }, + { name = "jsonschema-path" }, + { name = "lazy-object-proxy" }, + { name = "openapi-schema-validator" }, + { name = "pydantic" }, + { name = "pydantic-settings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/79/3f/aa0c1150627b4e683ae5673486b7d5cf2623a8821601863ee389e430965a/openapi_spec_validator-0.8.5.tar.gz", hash = "sha256:93b04ef5321d5866b2502371123d86333e5c1444f051d323e02525d9e83c7622", size = 1756845, upload-time = "2026-04-24T15:25:21.334Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/96/d7dfe1cc0be2df22d7a97ffb0f8bb00b10d92749aa6e64ffa7cc9a041580/openapi_spec_validator-0.8.5-py3-none-any.whl", hash = "sha256:3669106361856934153991e30714616a294865a33f6411a4c25d1dc2d08cfbc2", size = 50334, upload-time = "2026-04-24T15:25:19.65Z" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + +[[package]] +name = "paginate" +version = "0.5.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/46/68dde5b6bc00c1296ec6466ab27dddede6aec9af1b99090e1107091b3b84/paginate-0.5.7.tar.gz", hash = "sha256:22bd083ab41e1a8b4f3690544afb2c60c25e5c9a63a30fa2f483f6c60c8e5945", size = 19252, upload-time = "2024-08-25T14:17:24.139Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/90/96/04b8e52da071d28f5e21a805b19cb9390aa17a47462ac87f5e2696b9566d/paginate-0.5.7-py2.py3-none-any.whl", hash = "sha256:b885e2af73abcf01d9559fd5216b57ef722f8c42affbb63942377668e35c7591", size = 13746, upload-time = "2024-08-25T14:17:22.55Z" }, +] + +[[package]] +name = "pathable" +version = "0.5.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/72/55/b748445cb4ea6b125626f15379be7c96d1035d4fa3e8fee362fa92298abf/pathable-0.5.0.tar.gz", hash = "sha256:d81938348a1cacb525e7c75166270644782c0fb9c8cecc16be033e71427e0ef1", size = 16655, upload-time = "2026-02-20T08:47:00.748Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/52/96/5a770e5c461462575474468e5af931cff9de036e7c2b4fea23c1c58d2cbe/pathable-0.5.0-py3-none-any.whl", hash = "sha256:646e3d09491a6351a0c82632a09c02cdf70a252e73196b36d8a15ba0a114f0a6", size = 16867, upload-time = "2026-02-20T08:46:59.536Z" }, +] + +[[package]] +name = "pathlib-abc" +version = "0.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/cb/448649d7f25d228bf0be3a04590ab7afa77f15e056f8fa976ed05ec9a78f/pathlib_abc-0.5.2.tar.gz", hash = "sha256:fcd56f147234645e2c59c7ae22808b34c364bb231f685ddd9f96885aed78a94c", size = 33342, upload-time = "2025-10-10T18:37:20.524Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b1/29/c028a0731e202035f0e2e0bfbf1a3e46ad6c628cbb17f6f1cc9eea5d9ff1/pathlib_abc-0.5.2-py3-none-any.whl", hash = "sha256:4c9d94cf1b23af417ce7c0417b43333b06a106c01000b286c99de230d95eefbb", size = 19070, upload-time = "2025-10-10T18:37:19.437Z" }, +] + +[[package]] +name = "pathspec" +version = "1.1.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5a/82/42f767fc1c1143d6fd36efb827202a2d997a375e160a71eb2888a925aac1/pathspec-1.1.1.tar.gz", hash = "sha256:17db5ecd524104a120e173814c90367a96a98d07c45b2e10c2f3919fff91bf5a", size = 135180, upload-time = "2026-04-27T01:46:08.907Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" }, +] + +[[package]] +name = "pillow" +version = "12.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/37/bf/fb3ebff8ddcb76aac5a01389251bbbb9519922a9b520d8247c1ca864a25d/pillow-12.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965", size = 5345969, upload-time = "2026-07-01T11:54:06.397Z" }, + { url = "https://files.pythonhosted.org/packages/d8/66/9a386a92561f402389a4fc70c18838bf6d35eb5eb5c6850b4b2dc64f5048/pillow-12.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7", size = 4780323, upload-time = "2026-07-01T11:54:09.351Z" }, + { url = "https://files.pythonhosted.org/packages/25/27/ac8f99618ffd3dde21db0f4d4b1d2ab00c0880595bfd17df103f7f39fd0c/pillow-12.3.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9", size = 6266838, upload-time = "2026-07-01T11:54:11.71Z" }, + { url = "https://files.pythonhosted.org/packages/84/21/a35af28dcc61f37ed850a2d64c65c701321dfbf25085e469d5559360cbbf/pillow-12.3.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91", size = 6940830, upload-time = "2026-07-01T11:54:13.732Z" }, + { url = "https://files.pythonhosted.org/packages/eb/51/8b08617af3ad95e33ce6d7dd2c99ed6c8298f7fb131636303956be022e25/pillow-12.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c", size = 6344383, upload-time = "2026-07-01T11:54:15.756Z" }, + { url = "https://files.pythonhosted.org/packages/1d/72/cf78ac9780bb93c28328f408973845a309d4d145041665f734572ced1b52/pillow-12.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df", size = 7052934, upload-time = "2026-07-01T11:54:17.721Z" }, + { url = "https://files.pythonhosted.org/packages/20/20/25e0f4dc178a6bc0696793720055519a0de89e7661dae886992decbd2f81/pillow-12.3.0-cp312-cp312-win32.whl", hash = "sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f", size = 6472684, upload-time = "2026-07-01T11:54:19.839Z" }, + { url = "https://files.pythonhosted.org/packages/45/89/da2f7971a317f83d807fdd4065c0af40208e59e692cc43d315a71a0e96d1/pillow-12.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09", size = 7227137, upload-time = "2026-07-01T11:54:22.025Z" }, + { url = "https://files.pythonhosted.org/packages/de/47/4845a0a6c0dbf1db8456bd9fc791f13c5ced7ced20606d08a0aacfd25b49/pillow-12.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510", size = 2568267, upload-time = "2026-07-01T11:54:24.051Z" }, + { url = "https://files.pythonhosted.org/packages/9d/ac/31fb64e1e7efb5a4b50cd3d92049ba89ac6e4d8d3bb6a74e15048ca3353e/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:21900ce7ba264168cd50defae43cd75d25c833ad4ad6e73ffc5596d12e25ac89", size = 4161684, upload-time = "2026-07-01T11:54:25.934Z" }, + { url = "https://files.pythonhosted.org/packages/87/b4/9805e23d2b4d77842b468513841fda254ee42f0289d25088340e4ff46e2d/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4e8c2a84d977f50b9daed6eeaf3baef67d00d5d74d932288f02cb94518ee3ace", size = 4255487, upload-time = "2026-07-01T11:54:27.935Z" }, + { url = "https://files.pythonhosted.org/packages/df/39/ecf519435a200c693fe053a6ee4d835b41cf963a4dfc2551c4e637cb2a71/pillow-12.3.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:ae26d61dfa7a47befdc7572b521024e8745f3d809bd95ca9505a7bba9ef849ec", size = 3696433, upload-time = "2026-07-01T11:54:29.813Z" }, + { url = "https://files.pythonhosted.org/packages/42/92/2fc3ffad878ae8dd5469ec1bc8eb83b71f48e13efdf68f02709003982a32/pillow-12.3.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66", size = 5345889, upload-time = "2026-07-01T11:54:31.97Z" }, + { url = "https://files.pythonhosted.org/packages/10/76/8803c13605b763d33d156c4678fc77f8443389c0c51c8aef707bb02015f4/pillow-12.3.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35", size = 4780109, upload-time = "2026-07-01T11:54:34.026Z" }, + { url = "https://files.pythonhosted.org/packages/1f/01/e18aff37cb0b4aac47ac90f016d347a49aca667ef97f190b06ac2aabc928/pillow-12.3.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f7401aebd7f581d7f83a439d87d474999317ee099218e5ad25d125290990ba65", size = 6263736, upload-time = "2026-07-01T11:54:36.131Z" }, + { url = "https://files.pythonhosted.org/packages/f7/62/de5bdd77d935331f4f802edc11e4d82950f642caad6cb2f949837b8560e2/pillow-12.3.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0847a763afefb695bc912d7c131e7e0632d4edc1d8698f58ddabec8e46b8b6d3", size = 6937129, upload-time = "2026-07-01T11:54:38.216Z" }, + { url = "https://files.pythonhosted.org/packages/70/4d/105627a13300c5e0df1d174230b32fd1273062c96f7745fd552b945d1e1d/pillow-12.3.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:571b9fcb07b97ef3a492028fb3d2dc0993ca23a06138b0315286566d29ef718a", size = 6339562, upload-time = "2026-07-01T11:54:40.354Z" }, + { url = "https://files.pythonhosted.org/packages/6b/1d/f13de01a553988ab895ba1c722e06cf3144d4f57656fd5b81b6d881f1179/pillow-12.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:756c768d0c9c2955feb7a56c37ea24aea2e369f8d36a88da270b6a9f19e62b5e", size = 7049439, upload-time = "2026-07-01T11:54:42.489Z" }, + { url = "https://files.pythonhosted.org/packages/c9/f9/066794cca041b969964f779ee5fa66a9498bbf34248ac39c5d7954e4198f/pillow-12.3.0-cp313-cp313-win32.whl", hash = "sha256:a876864214e136f0eb367788dbd7df045f4806801518e2cfe9e13229cfe06d8f", size = 6473287, upload-time = "2026-07-01T11:54:44.9Z" }, + { url = "https://files.pythonhosted.org/packages/a6/9b/7a58e61d62be561da3a356fe2384d4059a6345fc130e23ef1c36a5b81d24/pillow-12.3.0-cp313-cp313-win_amd64.whl", hash = "sha256:1cca606cd25738df4ed873d5ad46bbdb3d83b5cbca291f6b4ff13a4df6b0bbe8", size = 7239691, upload-time = "2026-07-01T11:54:47.141Z" }, + { url = "https://files.pythonhosted.org/packages/aa/b0/c4ed4f0ef8f8fa5ee8351537db6650bb8189f7e118842978dd6589065692/pillow-12.3.0-cp313-cp313-win_arm64.whl", hash = "sha256:b629de27fda84b42cde7edef0d85f13b958b47f6e9bbcbba9b673c562a89bd8b", size = 2568185, upload-time = "2026-07-01T11:54:49.137Z" }, + { url = "https://files.pythonhosted.org/packages/dc/01/001f65b68192f0228cc1dbbc8d2530ab5d58b61037ba0587f946fea607cd/pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:9cf95fe4d0f84c82d282745d9bb08ad9f926efa00be4697e767b814ce40d4330", size = 4161736, upload-time = "2026-07-01T11:54:51.156Z" }, + { url = "https://files.pythonhosted.org/packages/1a/d2/0219746d0fd16fc8a84498e79452375be3797d3ce4044596ce565164b84f/pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:8728f216dcdb6e6d555cf971cb34076139ad74b31fc2c14da4fafc741c5f6217", size = 4255435, upload-time = "2026-07-01T11:54:53.414Z" }, + { url = "https://files.pythonhosted.org/packages/c8/02/8d0bc62ef0302318c46ff2a512822d2610e81c7aa46c9b3abe6cbaca5ad0/pillow-12.3.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:a45650e8ce7fafffd731db8550230db6b0d306d181a90b67d3e6bca2f1990930", size = 3696262, upload-time = "2026-07-01T11:54:55.739Z" }, + { url = "https://files.pythonhosted.org/packages/85/e2/73c77d218410b14f5f2d565e8a998d5317b7b9c75368d29985139f7a46f0/pillow-12.3.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ba54cfebe86920a559a7c4d6b9050791c20513650a1952ebe3368c7dc70306f8", size = 5350344, upload-time = "2026-07-01T11:54:57.657Z" }, + { url = "https://files.pythonhosted.org/packages/c7/da/32c752228ae345f489e3a42499d817b6c3996da7e8a3bc7a04fc806b243b/pillow-12.3.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e158cb00350dc278f3b91551101aa7d12415a66ebf2c91d8d5ac14e56ddd3ad0", size = 4780131, upload-time = "2026-07-01T11:54:59.713Z" }, + { url = "https://files.pythonhosted.org/packages/b1/9d/8b2c807dbef61a5197c047afe99823787eb66f63daf9fb2432f91d6f0462/pillow-12.3.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e9aeb04d6aef139de265b29683e119b638208f88cf73cdd1658aa07221165321", size = 6263757, upload-time = "2026-07-01T11:55:01.778Z" }, + { url = "https://files.pythonhosted.org/packages/5c/44/c85361f65dbe00eea8576ee467c768d25129989efb76e94f205e9ca9bb46/pillow-12.3.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:251bf95b67017e27b13d82f5b326234ca62d70f9cf4c2b9032de2358a3b12c7b", size = 6936962, upload-time = "2026-07-01T11:55:03.93Z" }, + { url = "https://files.pythonhosted.org/packages/18/7e/e483414b35800b86b6f08dbbc7803fb5cd52c4d6f897f47d53ea2c7e6f65/pillow-12.3.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fe3cca2e4e8a592be0f269a1ca4835c25199d9f3ce815c8491048f785b0a0198", size = 6339171, upload-time = "2026-07-01T11:55:05.989Z" }, + { url = "https://files.pythonhosted.org/packages/f0/f4/68c491844841ede6bed70189546b3ee9731cf9f2cbad396faff5e1ccba45/pillow-12.3.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:23aceaa007d6172b02c277f0cd359c79492bbb14f7072b4ede9fbcaf20648130", size = 7048116, upload-time = "2026-07-01T11:55:08.131Z" }, + { url = "https://files.pythonhosted.org/packages/a3/34/77f3f793fed8efc7d243f21b33c5a3f0d1c97ee70346d3db855587e155ff/pillow-12.3.0-cp314-cp314-win32.whl", hash = "sha256:af8d94b0db561cf68b88a267c5c44b49e134f525d0dc2cb7ed413a66bc23559a", size = 6467209, upload-time = "2026-07-01T11:55:10.408Z" }, + { url = "https://files.pythonhosted.org/packages/f1/e0/492879f69d94f91f60fc8cd05ba03650e9520afebb2fb7aa12777d7c7f38/pillow-12.3.0-cp314-cp314-win_amd64.whl", hash = "sha256:fdafc9cce40277e0f7a0feabce0ee50dd2fa1800f3b38015e51296b5e814048d", size = 7237707, upload-time = "2026-07-01T11:55:12.745Z" }, + { url = "https://files.pythonhosted.org/packages/c9/ac/6b11f2875f1c2ac040d84e1bbf9cf22a88038f901ca1037898b280b38365/pillow-12.3.0-cp314-cp314-win_arm64.whl", hash = "sha256:e91206ee562682b51b98ef4b26a6ef48fd84e15fd4c4bc5ec768eb641d206838", size = 2565995, upload-time = "2026-07-01T11:55:14.736Z" }, + { url = "https://files.pythonhosted.org/packages/52/69/c2208e56af9bfc1913afb24020297a691eb1d4ef688474c8a04913f65e04/pillow-12.3.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:164b31cd1a0490ab6efae01aa5df49da7061be0af1b30e035b6e9a1bfe34ee6e", size = 5352503, upload-time = "2026-07-01T11:55:17.076Z" }, + { url = "https://files.pythonhosted.org/packages/07/70/e5686d753e898a45d778ff1718dba8516ead6ab6b95d85fc8c4b70650cf2/pillow-12.3.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5afb51d599ea772b8365ae807ae557f18bccfe46ab261fd1c2a9ed700fc6eb17", size = 4782956, upload-time = "2026-07-01T11:55:19.448Z" }, + { url = "https://files.pythonhosted.org/packages/d5/37/25c6692f06927ee973ff18c8d9ee98ad0b4d84ee67a09610c2dd1447958e/pillow-12.3.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3edce1d53195db527e0191f84b71d02022de0540bf43a16ed734ed7537b07385", size = 6322855, upload-time = "2026-07-01T11:55:21.613Z" }, + { url = "https://files.pythonhosted.org/packages/cc/91/420637fcb8f1bc11029e403b4538e6694744428d8246118e45719f944556/pillow-12.3.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bf16ba1b4d0b6b7c8e534936632270cf70eb00dbe09005bc345b2677b726855c", size = 6989642, upload-time = "2026-07-01T11:55:24.006Z" }, + { url = "https://files.pythonhosted.org/packages/10/08/b94d7811281ccf0d143a1cf768d1c49e1e54af63e7b708ab2ee3eb87face/pillow-12.3.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:24870b09b224f7ae3c39ed07d10e819d06f8720bc551847b1d623832b5b0e28d", size = 6391281, upload-time = "2026-07-01T11:55:26.252Z" }, + { url = "https://files.pythonhosted.org/packages/d2/87/24233f785f55474dc02ce3e739c5528a77e3a862e9333d1dd7a25cc31f70/pillow-12.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:30f2aa603c41533cc25c05acd0da21636e84a315768feb631c937177db558931", size = 7096716, upload-time = "2026-07-01T11:55:28.318Z" }, + { url = "https://files.pythonhosted.org/packages/23/26/fcb2f6e37175b04f53570b59937867e2b80ee1685e744023153028fc14f9/pillow-12.3.0-cp314-cp314t-win32.whl", hash = "sha256:4b0a7fe987b14c31ebda6083f74f22b561fd3739bc0ac51e019622e3d72668c7", size = 6474125, upload-time = "2026-07-01T11:55:30.956Z" }, + { url = "https://files.pythonhosted.org/packages/90/de/3634abee5f1c9e13c56787b7d5517b0ba8d6de51700b95578cf338349c9f/pillow-12.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:962864dc93511324d51ddbb5b9f8731bf71675b93ca612a07441896f4688fb8c", size = 7242939, upload-time = "2026-07-01T11:55:34.044Z" }, + { url = "https://files.pythonhosted.org/packages/ce/2a/fd13f8eb24de5714a6eb444a3d67e2842c6c576e159a43793adf23051351/pillow-12.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0740a512dc522224c77d9aa5a8d70d8b7d73fb91f2c21125d8d025d3b8990e45", size = 2567506, upload-time = "2026-07-01T11:55:35.988Z" }, + { url = "https://files.pythonhosted.org/packages/5d/dc/8fdce34ec725a33c81c6ba122b904d6b9024e50ea9ac7bede62fab54506c/pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:0feb2e9d6ad6c9e3c06effe9d00f3f1e618a6643273576b016f591e9315a7139", size = 4162063, upload-time = "2026-07-01T11:55:37.941Z" }, + { url = "https://files.pythonhosted.org/packages/76/66/2044b9a63d3b84ff048228dfcb7cd9bf0df983e8470971bf7d4c57b693de/pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:9e881fca225083806662a5c43d627d215f258ff43c890f831966c7d7ba9c7402", size = 4255549, upload-time = "2026-07-01T11:55:40.022Z" }, + { url = "https://files.pythonhosted.org/packages/52/7e/1f67e6f4ece6b582ee4b539decbcc9f848dc245a93ed8cd7338bafef72f1/pillow-12.3.0-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:4998562bf62a445225f22e07c896bb04b35b1b1f2eb6d760584c9c51d7a5f78c", size = 3696331, upload-time = "2026-07-01T11:55:41.98Z" }, + { url = "https://files.pythonhosted.org/packages/12/40/d306fc2c8e4d45d7f175c77edca7063be7b86fe7fe6e68f4353bf71d808c/pillow-12.3.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:dc624f6bc473dacdf7ef7eb8678d0d08edf15cd94fad6ae5c7d6cc67a4e4902f", size = 5350370, upload-time = "2026-07-01T11:55:44.028Z" }, + { url = "https://files.pythonhosted.org/packages/dd/44/668fb1437e8ce420f62d6106eb66e44a5971602a4d794615bdf79315d82d/pillow-12.3.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:71d6097b330eea8fd15097780c8e89cb1a8ce7838669f48c5bacd6f663dd4701", size = 4780147, upload-time = "2026-07-01T11:55:46.073Z" }, + { url = "https://files.pythonhosted.org/packages/0c/08/93fa2e70e30a2d81547e481b6ee2bb9522117221fb1e0ce4b5df70967677/pillow-12.3.0-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:28ce87c5ab450a9dd970b52e5aca5fe63ed432d18a2eaddd1979a00a1ba24ace", size = 6273659, upload-time = "2026-07-01T11:55:48.264Z" }, + { url = "https://files.pythonhosted.org/packages/f8/6d/043e96ff814fc31a33077e4cba86082167db520c93632afdf2042febbb0c/pillow-12.3.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6b02afb9b97f65fbca5f31db6a2a3ba21aa93030225f150fa3f249717e938fb4", size = 6947439, upload-time = "2026-07-01T11:55:50.503Z" }, + { url = "https://files.pythonhosted.org/packages/af/92/ba71d2ee2ac0edf3fa33bd9d5ee9ee080da70b1766f3ca3934f9938ddac9/pillow-12.3.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:1182d52bc2d5e5d7d0949503aa7e36d12f42205dc287e4883f407b1988820d39", size = 6353577, upload-time = "2026-07-01T11:55:52.697Z" }, + { url = "https://files.pythonhosted.org/packages/0f/ce/e63064e2122923ff687c8ad792d0d736a7b3920a56a46982e81a7fdd25d6/pillow-12.3.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e795b7eb908249c4e43c7c99fac7c2c75dab0c43566e37db472a355f63693d71", size = 7060394, upload-time = "2026-07-01T11:55:55.149Z" }, + { url = "https://files.pythonhosted.org/packages/54/76/a09cc3ccc8d773a7283d34c38bec1708f9e3cc932093cbc4c5e71ac4060b/pillow-12.3.0-cp315-cp315-win32.whl", hash = "sha256:57b3d78c95ba9059768b10e28b813002261d3f3dfc55cc48b0c988f625175827", size = 6467375, upload-time = "2026-07-01T11:55:57.769Z" }, + { url = "https://files.pythonhosted.org/packages/3e/03/1846c49ba3b1d5550392a4bbd06d6fb4578e1cd91a803198b5c90f5f7d53/pillow-12.3.0-cp315-cp315-win_amd64.whl", hash = "sha256:fa4ecea169a355be7a3ade2c783e2ed12f0e40d2c5621cda8b3297faf7fbb9f5", size = 7237048, upload-time = "2026-07-01T11:55:59.975Z" }, + { url = "https://files.pythonhosted.org/packages/fb/bb/89f35dcc79610423f9f195504d7def7f0d1416a711541b42867e25fe3412/pillow-12.3.0-cp315-cp315-win_arm64.whl", hash = "sha256:877c3f311ff35410f690861c4409e7ccbf0cd2f878e50628a28e5a0bb689e658", size = 2566006, upload-time = "2026-07-01T11:56:02.143Z" }, + { url = "https://files.pythonhosted.org/packages/30/88/707027ba09942dfa2c28759b5c222d769290a41c6d20ea60ec250801941f/pillow-12.3.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:e9871b1ffbfa9656b60aeee92ed5136a5742696006fa322b29ea3d8da0ecc9cf", size = 5352509, upload-time = "2026-07-01T11:56:04.2Z" }, + { url = "https://files.pythonhosted.org/packages/b0/6d/00352fa25332c2569cd387851f568cc5a4b75a9adbfb37ac4fbce4c02eec/pillow-12.3.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:53aa02d20d10c3d814d536aa4e5ac9b84ca0ff5a88377963b085ad6822f93e64", size = 4783167, upload-time = "2026-07-01T11:56:06.631Z" }, + { url = "https://files.pythonhosted.org/packages/13/4f/9e049dfa21af7c22427275720e2490267ba8138120add5c4c574deb69782/pillow-12.3.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:446c34dcc4324b084a53b705127dc15717b22c5e140ae0a3c38349d4efec071e", size = 6329237, upload-time = "2026-07-01T11:56:08.868Z" }, + { url = "https://files.pythonhosted.org/packages/36/16/cf6eeaae8d0fce8dd390a33437cf68c5d5bd73834a2bc6e2f14efda0ab45/pillow-12.3.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cf1845d02ad822a369a49f2bb9345b1614744267682e7a03527dc3bf6eea1777", size = 6997047, upload-time = "2026-07-01T11:56:11.379Z" }, + { url = "https://files.pythonhosted.org/packages/1e/69/dbf769bdd55f48bf5733cac28edc6364ffaa072ec9ba336266e4fe66be55/pillow-12.3.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:186941b6aef820ad110fb01fb06eb925374dc3a21b17e37ec9a53b250c6fe2d1", size = 6400440, upload-time = "2026-07-01T11:56:13.908Z" }, + { url = "https://files.pythonhosted.org/packages/a0/e1/ffc9cfc2eea0d178da8018e18e959301ad9d6bc9f3edb7181e748a474b97/pillow-12.3.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:f13c32a3abd6079a66d9526e18dad9b6d280384d49d7c54040cd57b6424041d9", size = 7105895, upload-time = "2026-07-01T11:56:16.575Z" }, + { url = "https://files.pythonhosted.org/packages/18/f0/a5595c1e8c3ae44b9828cb2f0fa8155e5095ef04d6327b8f61cf44a3df85/pillow-12.3.0-cp315-cp315t-win32.whl", hash = "sha256:1657923d2d45afb66526e5b933e5b3052e6bdea196c90d3abb2424e18c77dae8", size = 6474384, upload-time = "2026-07-01T11:56:18.855Z" }, + { url = "https://files.pythonhosted.org/packages/e4/04/62bcd9f844984c5938d3b05264a61d797a29d3e0812341a8204af70bbdee/pillow-12.3.0-cp315-cp315t-win_amd64.whl", hash = "sha256:8cd2f7bdda092d99c9fc2fb7391354f306d01443d22785d0cbfafa2e2c8bb418", size = 7243537, upload-time = "2026-07-01T11:56:21.214Z" }, + { url = "https://files.pythonhosted.org/packages/3d/68/1f3066acedf37673694a7141381d8f811ae97f30d34413d236abe7d489f1/pillow-12.3.0-cp315-cp315t-win_arm64.whl", hash = "sha256:06ff022112bc9cbf83b60f8e028d94ad87b60621706487e65f673de61610ab59", size = 2567491, upload-time = "2026-07-01T11:56:23.506Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.9.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9f/4a/0883b8e3802965322523f0b200ecf33d31f10991d0401162f4b23c698b42/platformdirs-4.9.6.tar.gz", hash = "sha256:3bfa75b0ad0db84096ae777218481852c0ebc6c727b3168c1b9e0118e458cf0a", size = 29400, upload-time = "2026-04-09T00:04:10.812Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/75/a6/a0a304dc33b49145b21f4808d763822111e67d1c3a32b524a1baf947b6e1/platformdirs-4.9.6-py3-none-any.whl", hash = "sha256:e61adb1d5e5cb3441b4b7710bea7e4c12250ca49439228cc1021c00dcfac0917", size = 21348, upload-time = "2026-04-09T00:04:09.463Z" }, +] + +[[package]] +name = "pluggy" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, +] + +[[package]] +name = "propcache" +version = "0.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/44/c87281c333769159c50594f22610f77398a47ccbfbbf23074e744e86f87c/propcache-0.5.2.tar.gz", hash = "sha256:01c4fc7480cd0598bb4b57022df55b9ca296da7fc5a8760bd8451a7e63a7d427", size = 50208, upload-time = "2026-05-08T21:02:12.199Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4a/cb/e27bc2b2737a0bb49962b275efa051e8f1c35a936df7d5139b6b658b7dc9/propcache-0.5.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:806719138ecd720339a12410fb9614ac9b2b2d3a5fdf8235d56981c36f4039ba", size = 95887, upload-time = "2026-05-08T21:00:11.277Z" }, + { url = "https://files.pythonhosted.org/packages/e6/13/b8ae04c59392f8d11c6cd9fb4011d1dc7c86b81225c770280300e259ffe1/propcache-0.5.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:db2b80ea58eab4f86b2beec3cc8b39e8ff9276ac20e96b7cce43c8ae84cd6b5a", size = 54654, upload-time = "2026-05-08T21:00:12.604Z" }, + { url = "https://files.pythonhosted.org/packages/2c/7d/49777a3e20b55863d4794384a38acd460c04157b0a00f8602b0d508b8431/propcache-0.5.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:e5cbfac9f61484f7e9f3597775500cd3ebe8274e9b050c38f9525c77c97520bf", size = 55190, upload-time = "2026-05-08T21:00:13.935Z" }, + { url = "https://files.pythonhosted.org/packages/44/c7/085d0cd63062e84044e3f05797749c3f8e3938ff3aeb0eb2f69d43fafc91/propcache-0.5.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5dbc581d2814337da56222fab8dc5f161cd798a434e49bac27930aaef798e144", size = 59995, upload-time = "2026-05-08T21:00:15.526Z" }, + { url = "https://files.pythonhosted.org/packages/9c/42/32cf8e3009e92b2645cf1e944f701e8ea4e924dffde1ee26db860bcbf7e4/propcache-0.5.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:857187f381f88c8e2fa2fe56ab94879d011b883d5a2ee5a1b60a8cd2a06846d9", size = 63422, upload-time = "2026-05-08T21:00:16.824Z" }, + { url = "https://files.pythonhosted.org/packages/9e/1b/f112433f99fc979431b87a39ef169e3f8df070d99a72792c56d6937ac48b/propcache-0.5.2-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:178b4a2cdaac1818e2bf1c5a99b94383fa73ea5382e032a48dec07dc5668dc42", size = 64342, upload-time = "2026-05-08T21:00:18.362Z" }, + { url = "https://files.pythonhosted.org/packages/14/15/5574111ae50dd6e879456888c0eadd4c5a869959775854e18e18a6b345f3/propcache-0.5.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f328175a2cde1f0ff2c4ed8ce968b9dcfb55f3a7153f39e2957ed994da13476", size = 61639, upload-time = "2026-05-08T21:00:19.692Z" }, + { url = "https://files.pythonhosted.org/packages/cc/da/4d775080b1490c0ae604acda868bd71aabe3a89ed16f2aa4339eb8a283e7/propcache-0.5.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5671d09a36b06d0fd4a3da0fccbcae360e9b1570924171a15e9e0997f0249fba", size = 61588, upload-time = "2026-05-08T21:00:21.155Z" }, + { url = "https://files.pythonhosted.org/packages/04/ac/f076982cbe2195ee9cf32de5a1e46951d9fb399fc207f390562dd0fd8fb2/propcache-0.5.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:80168e2ebe4d3ec6599d10ad8f520304ae1cad9b6c5a95372aef1b66b7bfb53a", size = 60029, upload-time = "2026-05-08T21:00:22.713Z" }, + { url = "https://files.pythonhosted.org/packages/70/60/189be62e0dd898dce3b331e1b8c7a543cd3a405ac0c81fe8ee8a9d5d77e1/propcache-0.5.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:45f11346f884bc47444f6e6647131055844134c3175b629f84952e2b5cd62b64", size = 56774, upload-time = "2026-05-08T21:00:24.001Z" }, + { url = "https://files.pythonhosted.org/packages/ea/9e/93377b9c7939c1ffae98f878dee955efadfd638078bc86dbc21f9d52f651/propcache-0.5.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:8e778ebd44ef4f66ed60a0416b06b489687db264a9c0b3620362f26489492913", size = 63532, upload-time = "2026-05-08T21:00:25.545Z" }, + { url = "https://files.pythonhosted.org/packages/14/f9/590ef6cfb9b8028d516d287812ece32bb0bc5f11fbb9c8bf6b2e6313fec8/propcache-0.5.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:c0cb9ed24c8964e172768d455a38254c2dd8a552905729ce006cad3d3dda59b1", size = 61592, upload-time = "2026-05-08T21:00:27.186Z" }, + { url = "https://files.pythonhosted.org/packages/b4/5e/70958b3034c297a630bba2f17ca7abc2d5f39a803ad7e370ab79d1ecd022/propcache-0.5.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:1d1ad32d9d4355e2be65574fd0bfd3677e7066b009cd5b9b2dee8aa6a6393b33", size = 64788, upload-time = "2026-05-08T21:00:28.8Z" }, + { url = "https://files.pythonhosted.org/packages/12/fd/77fe5936d8c3086ca9048f7f415f122ed82e53884a9ec193646b42deef06/propcache-0.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c80f4ba3e8f00189165999a742ee526ebeccedf6c3f7beb0c7df821e9772435a", size = 62514, upload-time = "2026-05-08T21:00:30.098Z" }, + { url = "https://files.pythonhosted.org/packages/cf/74/66bd798b5b3be70aa1b391f5cc9d6a0a5532d7fd3b19ec0b213e72e6ad9d/propcache-0.5.2-cp312-cp312-win32.whl", hash = "sha256:8c7972d8f193740d9175f0998ab38717e6cd322d5935c5b0fef8c0d323fd9031", size = 39018, upload-time = "2026-05-08T21:00:31.622Z" }, + { url = "https://files.pythonhosted.org/packages/61/7c/5c0d34aa3024694d6dcb9271cdbdd08c4e47c1c0ad95ec7e7bc74cdea145/propcache-0.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:d9ee8826a7d47863a08ac44e1a5f611a462eefc3a194b492da242128bec75b42", size = 42322, upload-time = "2026-05-08T21:00:32.918Z" }, + { url = "https://files.pythonhosted.org/packages/4d/91/875812f1a3feb20ceba818ef39fbe4d92f1081e04ac815c822496d0d038b/propcache-0.5.2-cp312-cp312-win_arm64.whl", hash = "sha256:2800a4a8ead6b28cccd1ec54b59346f0def7922ee1c7598e8499c733cfbb7c84", size = 38172, upload-time = "2026-05-08T21:00:35.124Z" }, + { url = "https://files.pythonhosted.org/packages/c5/09/f049e45385503fe67db75a6b6186a7b9f0c3930366dc960522c312a825b1/propcache-0.5.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:099aaf4b4d1a02265b92a977edf00b5c4f63b3b17ac6de39b0d637c9cac0188a", size = 94457, upload-time = "2026-05-08T21:00:36.355Z" }, + { url = "https://files.pythonhosted.org/packages/6b/65/83d1d05655baf63113731bd5a1008435e14f8d1e5a06cbe4ec5b23ad7a31/propcache-0.5.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:68ce1c44c7a813a7f71ea04315a8c7b330b63db99d059a797a4651bb6f69f117", size = 53835, upload-time = "2026-05-08T21:00:38.072Z" }, + { url = "https://files.pythonhosted.org/packages/a9/12/a6ba6482bb5ea3260c000c9b20881c95fa11c6b30173715668259f844ed7/propcache-0.5.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:fc299c129490f55f254cd90be0deca4764e36e9a7c08b4aa588479a3bbed3098", size = 54545, upload-time = "2026-05-08T21:00:39.319Z" }, + { url = "https://files.pythonhosted.org/packages/a9/19/7fa086f5764c59ec8a8e157cd93aa8497acc00aba9dcdec56bfffb32602d/propcache-0.5.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a6ae2198be502c10f09b2516e7b5d019816924bc3183a43ce792a7bd6625e6f4", size = 59886, upload-time = "2026-05-08T21:00:40.621Z" }, + { url = "https://files.pythonhosted.org/packages/a1/e4/5d7663dc8235956c8f5281698a3af1d351d8820341ddd890f59d9a9127f2/propcache-0.5.2-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6041d31504dc1779d700e1edcfb08eea334b357620b06681a4eabb57a74e574e", size = 63261, upload-time = "2026-05-08T21:00:41.775Z" }, + { url = "https://files.pythonhosted.org/packages/4a/4a/15a03adee24d6350da4292caeac44c34c033d2afe5e87eb370f38854560f/propcache-0.5.2-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f7eabc04151c78a9f4d5bbb5f1faf571e4defeb4b585e0fe95b60ff2dbe4d3d7", size = 64184, upload-time = "2026-05-08T21:00:43.018Z" }, + { url = "https://files.pythonhosted.org/packages/8b/c6/979176efdaa3d239e36d503d5af63a0a773b36662ed8f52e5b6a6d9fd40e/propcache-0.5.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4db0ba63d693afd40d249bd93f842b5f144f8fcbb83de05660373bcf30517b1d", size = 61534, upload-time = "2026-05-08T21:00:44.507Z" }, + { url = "https://files.pythonhosted.org/packages/c8/22/63e8cd1bae4c2d2be6493b6b7d10566ddafad88137cfbc99964a1119853c/propcache-0.5.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:1dbcf7675229b35d31abb6547d8ebc8c27a830ac3f9a794edff6254873ec7c0a", size = 61500, upload-time = "2026-05-08T21:00:45.796Z" }, + { url = "https://files.pythonhosted.org/packages/60/5a/28e5d9acbac1cc9ccb67045e8c1b943aa8d79fdf39c93bd73cacd68008ea/propcache-0.5.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d310c013aad2c72f1c3f2f8dd3279d460a858c551f97aeb8c63e4693cca7b4d2", size = 59994, upload-time = "2026-05-08T21:00:47.093Z" }, + { url = "https://files.pythonhosted.org/packages/f3/40/db650677f554a95b9c01a7c9d93d629e93a15562f5deb4573c9ee136fed2/propcache-0.5.2-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:06187263ddad280d05b4d8a8b3bb7d164cbebd469236544a42e6d9b28ac6a4fa", size = 56884, upload-time = "2026-05-08T21:00:48.376Z" }, + { url = "https://files.pythonhosted.org/packages/80/45/70b39b89516ff8b96bf732fa6fded8cef20f293cb1508690101c3c07ec51/propcache-0.5.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:3115559b8effafd63b142ea5ed53d63a16ea6469cbc63dce4ee194b42db5d853", size = 63464, upload-time = "2026-05-08T21:00:49.954Z" }, + { url = "https://files.pythonhosted.org/packages/f9/e2/fa59d3a89eac5534293124af4f1d0d0ada091ce4a0ab4610ce03fd2bdd8d/propcache-0.5.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:c60462af8e6dc30c35407c7237ea908d777b22862bbee27bc4699c0d8bcdc45a", size = 61588, upload-time = "2026-05-08T21:00:51.281Z" }, + { url = "https://files.pythonhosted.org/packages/0b/97/efb547a55c4bc7381cfb202d6a2239ac621045277bc1ea5dfd3a7f0516c0/propcache-0.5.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:40314bca9ac559716fe374094fc81c11dcc34b64fd6c585360f5775690505704", size = 64667, upload-time = "2026-05-08T21:00:52.602Z" }, + { url = "https://files.pythonhosted.org/packages/92/56/f5c7d9b4b7595d5127da38974d791b2153f3d1eae6c674af3583ace92ad3/propcache-0.5.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:cfa21e036ce1e1db2be04ba3b85d2df1bb1702fa01932d984c5464c665228ff4", size = 62463, upload-time = "2026-05-08T21:00:54.303Z" }, + { url = "https://files.pythonhosted.org/packages/bd/3b/484a3a65fc9f9f60c41dcd17b428bace5389544e2c680994534a20755066/propcache-0.5.2-cp313-cp313-win32.whl", hash = "sha256:f156a3529f38063b6dbaf356e15602a7f95f8055b1295a438433a6386f10463d", size = 38621, upload-time = "2026-05-08T21:00:55.808Z" }, + { url = "https://files.pythonhosted.org/packages/1c/fd/3f0f10dba4dabad3bf53102be007abf55481067952bde0fdddff439e7c61/propcache-0.5.2-cp313-cp313-win_amd64.whl", hash = "sha256:dfed59d0a5aeb01e242e66ff0300bc4a265a7c05f612d30016f0b60b1017d757", size = 41649, upload-time = "2026-05-08T21:00:57.061Z" }, + { url = "https://files.pythonhosted.org/packages/90/ec/6ce619cc32bb500a482f811f9cd509368b4e58e638d13f2c68f370d6b475/propcache-0.5.2-cp313-cp313-win_arm64.whl", hash = "sha256:ba338430e87ceb9c8f0cf754de38a9860560261e56c00376debd628698a7364f", size = 37636, upload-time = "2026-05-08T21:00:58.646Z" }, + { url = "https://files.pythonhosted.org/packages/1b/82/c1d268bbbf2ef981c5bf0fbbe746db617c66e3bcefe431a1aa8943fbe23a/propcache-0.5.2-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:a592f5f3da71c8691c788c13cb6734b6d17663d2e1cb8caddf0673d01ef8847d", size = 98872, upload-time = "2026-05-08T21:00:59.889Z" }, + { url = "https://files.pythonhosted.org/packages/f4/d4/52c871e73e864e6b34c0e2d58ac1ec5ccd149497ddc7ad2137ae98323a35/propcache-0.5.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:6a997d0489e9668a384fcfd5061b857aa5361de73191cac204d04b889cfbbafa", size = 56257, upload-time = "2026-05-08T21:01:01.195Z" }, + { url = "https://files.pythonhosted.org/packages/67/f0/9b90ca2a210b3d09bcfcd96ecd0f55545c091535abce2a45de2775cfd357/propcache-0.5.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:10734b5484ea113152ee25a91dccedf81631791805d2c9ccb054958e51842c94", size = 56696, upload-time = "2026-05-08T21:01:02.941Z" }, + { url = "https://files.pythonhosted.org/packages/9d/0e/6e9d4ba07c8e56e21ddec1e75f12148142b21ca83a51871babce095334f4/propcache-0.5.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cafca7e56c12bb02ae16d283742bef25a61122e9dab2b5b3f2ccbe589ce32164", size = 62378, upload-time = "2026-05-08T21:01:04.475Z" }, + { url = "https://files.pythonhosted.org/packages/65/19/c10badaa463dde8a27ce884f8ee2ec37e6035b7c9f5ff0c8f74f06f08dac/propcache-0.5.2-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f064f8d2b59177878b7615df1735cd8fe3462ed6be8c7b217d17a276489c2b7f", size = 65283, upload-time = "2026-05-08T21:01:05.959Z" }, + { url = "https://files.pythonhosted.org/packages/b0/b6/93bea99ca80e19cef6512a8580e5b7857bbe09422d9daa7fd4ef5723306c/propcache-0.5.2-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f78abfa8dfc32376fd1aacf597b2f2fbbe0ea751419aee718af5d4f82537ef8c", size = 66616, upload-time = "2026-05-08T21:01:07.228Z" }, + { url = "https://files.pythonhosted.org/packages/83/e4/5c7462e50625f051f37fb38b8224f7639f667184bbd34424ec83819bb1b7/propcache-0.5.2-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f7467da8a9822bf1a55336f877340c5bcbd3c482afc43a99771169f74a26dedc", size = 63773, upload-time = "2026-05-08T21:01:08.514Z" }, + { url = "https://files.pythonhosted.org/packages/ca/b6/99238894047b13c823be25027e736626cd414a52a5e30d2c3347c2733529/propcache-0.5.2-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a6ddc6ac9e25de626c1f129c1b467d7ecd33ce2237d3fd0c4e429feef0a7ee1f", size = 63664, upload-time = "2026-05-08T21:01:09.874Z" }, + { url = "https://files.pythonhosted.org/packages/85/1e/a3a1a63116a2b8edb415a8bb9a6f0c34bd03830b1e18e8ce2904e1dc1cf4/propcache-0.5.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:2f22cbbac9e26a8e864c0985ff1268d5d939d53d9d9411a9824279097e03a2cb", size = 62643, upload-time = "2026-05-08T21:01:11.132Z" }, + { url = "https://files.pythonhosted.org/packages/e4/03/893cf147de2fc6543c5eaa07ad833170e7e2a2385725bbebe8c0503723bb/propcache-0.5.2-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:fc76378c62a0f04d0cd82fbb1a2cd2d7e28fcb40d5873f28a6c44e388aaa2751", size = 59595, upload-time = "2026-05-08T21:01:12.387Z" }, + { url = "https://files.pythonhosted.org/packages/86/3b/04c1a2e12c57766568ba75ba72b3bf2042818d4c1425fab6fc07155c7cff/propcache-0.5.2-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:acd2c8edba48e31e58a363b8cf4e5c7db3b04b3f9e371f601df30d9b0d244836", size = 65711, upload-time = "2026-05-08T21:01:13.676Z" }, + { url = "https://files.pythonhosted.org/packages/1c/34/80f8d0099f8d6bacc4de1624c85672681c8cd1149ca2da0e38fd120b817f/propcache-0.5.2-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:452b5065457eb9991ec5eb38ff41d6cd4c991c9ac7c531c4d5849ae473a9a13f", size = 64247, upload-time = "2026-05-08T21:01:14.936Z" }, + { url = "https://files.pythonhosted.org/packages/f3/1a/8b08f3a5f1037e9e370c55883ceeeee0f6dd0416fb2d2d67b8bfc91f2a79/propcache-0.5.2-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:3430bb2bfe1331885c427745a751e774ee679fd4344f80b97bf879815fe8fa55", size = 67102, upload-time = "2026-05-08T21:01:16.281Z" }, + { url = "https://files.pythonhosted.org/packages/34/68/8bdb7bb7756d76e005490649d10e4a8369e610c74d619f71e1aedf889e9c/propcache-0.5.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:cef6cea3922890dd6c9654971001fa797b526c16ab5e1e46c05fd6f877be7568", size = 64964, upload-time = "2026-05-08T21:01:17.57Z" }, + { url = "https://files.pythonhosted.org/packages/0a/aa/50fb0b5d3968b61a510926ff8b8465f1d6e976b3ab74496d7a4b9fc42515/propcache-0.5.2-cp313-cp313t-win32.whl", hash = "sha256:72d61e16dd78228b58c5d47be830ff3da7e5f139abdf0aef9d86cde1c5cf2191", size = 42546, upload-time = "2026-05-08T21:01:18.946Z" }, + { url = "https://files.pythonhosted.org/packages/ae/4c/0ddbae64321bd4a95bcbfc19307238016b5b1fee645c84626c8d539e5b74/propcache-0.5.2-cp313-cp313t-win_amd64.whl", hash = "sha256:0958834041a0166d343b8d2cedcd8bcbaeb4fdbe0cf08320c5379f143c3be6e7", size = 46330, upload-time = "2026-05-08T21:01:20.162Z" }, + { url = "https://files.pythonhosted.org/packages/00/d9/9cddc8efb78d8af264c5ec9f6d10b62f57c515feda8d321595f56010fb23/propcache-0.5.2-cp313-cp313t-win_arm64.whl", hash = "sha256:6de8bd93ddde9b992cf2b2e0d796d501a19026b5b9fd87356d7d0779531a8d96", size = 40521, upload-time = "2026-05-08T21:01:21.399Z" }, + { url = "https://files.pythonhosted.org/packages/e2/ea/23ee535d90ce8bcc465a3028eb3cc0ce3bd1005f4bb27710b30587de798d/propcache-0.5.2-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:46088abff4cba581dea21ae0467a480526cb25aa5f3c269e909f800328bc3999", size = 94662, upload-time = "2026-05-08T21:01:22.683Z" }, + { url = "https://files.pythonhosted.org/packages/b5/06/c5a52f419b5d8972f8d46a7577476090d8e3263ff589ce40b5ca4968d5be/propcache-0.5.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:fc88b26f08d634f7bc819a7852e5214f5802641ab8d9fd5326892292eee1993e", size = 53928, upload-time = "2026-05-08T21:01:23.986Z" }, + { url = "https://files.pythonhosted.org/packages/63/b1/4260d67d6bd85e58a66b72d54ce15d5de789b6f3870cc6bedf8ff9667401/propcache-0.5.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:97797ebb098e670a2f92dd66f32897e30d7615b14e7f59711de23e30a9072539", size = 54650, upload-time = "2026-05-08T21:01:25.305Z" }, + { url = "https://files.pythonhosted.org/packages/70/06/2f46c318e3307cd7a6a7481def374ce838c0fe20084b39dd54b0879d0e99/propcache-0.5.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ba57fffe4ac99c5d30076161b5866336d97600769bad35cc68f7774b15298a4e", size = 59912, upload-time = "2026-05-08T21:01:26.545Z" }, + { url = "https://files.pythonhosted.org/packages/4c/29/fe1aebec2ce57ab985a9c382bded1124431f85078113aa222c5d278430d4/propcache-0.5.2-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:583c19759d9eec1e5b69e2fbef36a7d9c326041be9746cb822d335c8cedc2979", size = 63300, upload-time = "2026-05-08T21:01:27.937Z" }, + { url = "https://files.pythonhosted.org/packages/b4/18/2334b26768b6c82be8c69e83671b767d5ef426aa09b0cba6c2ea47816774/propcache-0.5.2-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d0326e2e5e1f3163fa306c834e48e8d490e5fae607a097a40c0648109b47ba80", size = 64208, upload-time = "2026-05-08T21:01:29.484Z" }, + { url = "https://files.pythonhosted.org/packages/2b/76/7f1bfd6afff4c5e38e36a3c6d68eb5f4b7311ea80baf693db78d95b603c4/propcache-0.5.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e00820e192c8dbebcafb383ebbf99030895f09905e7a0eb2e0340a0bcc2bc825", size = 61633, upload-time = "2026-05-08T21:01:31.068Z" }, + { url = "https://files.pythonhosted.org/packages/c4/46/b3ff8aba2b4953a3e50de2cf72f1b5748b8eca93b15f3dc2c84339084c09/propcache-0.5.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c66afea89b1e43725731d2004732a046fe6fe955d51f952c3e95a7314a284a39", size = 61724, upload-time = "2026-05-08T21:01:32.374Z" }, + { url = "https://files.pythonhosted.org/packages/c5/01/814cfcafbcff954f94c01cf30e097ddc88a076b5440fbcf4570753437d40/propcache-0.5.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:d4dc37dec6c6cdad0b57881a5658fd14fbf53e333b1a86cf86559f190e1d9ec4", size = 60069, upload-time = "2026-05-08T21:01:33.67Z" }, + { url = "https://files.pythonhosted.org/packages/da/68/5c6f7622d510cc666a300687e06fd060c1a43361c0c9b20d284f06d8096a/propcache-0.5.2-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:5570dbcc97571c15f68068e529c92715a12f8d54030e272d264b377e22bd17a5", size = 57099, upload-time = "2026-05-08T21:01:34.915Z" }, + { url = "https://files.pythonhosted.org/packages/55/27/9cb0b4c679124085327957d42521c99dba04c88c90c3e55a6f0b633ebccc/propcache-0.5.2-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:f814362777a9f841adddb200ecdf8f5cb1e5a3c4b7a86378edbd6ccb26edd702", size = 63391, upload-time = "2026-05-08T21:01:36.231Z" }, + { url = "https://files.pythonhosted.org/packages/f0/9d/7258aaa5bdf60fc6f27591eef6fe52768cb0beda7140be477c8b12c9794a/propcache-0.5.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:196913dea116aeb5a2ba95af4ddcb7ea85559ae07d8eee8751688310d09168c3", size = 61626, upload-time = "2026-05-08T21:01:37.545Z" }, + { url = "https://files.pythonhosted.org/packages/8e/0d/41c602003e8a9b16fe1e7eadf62c7bfba9d5474370b24200bf48b315f45f/propcache-0.5.2-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:6e7b8719005dd1175be4ab1cd25e9b98659a5e0347331506ec6760d2773a7fb5", size = 64781, upload-time = "2026-05-08T21:01:38.83Z" }, + { url = "https://files.pythonhosted.org/packages/8b/f3/38e66b1856e9bd079deea015bc4a55f7767c0e4db2f7dcf69e7e680ba4ce/propcache-0.5.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:51f96d685ab16e88cab128cd37a52c5da540809c8b879fa047731bfcb4ad35a4", size = 62570, upload-time = "2026-05-08T21:01:40.415Z" }, + { url = "https://files.pythonhosted.org/packages/95/ca/bbfe9b910ce57dde8bb4876b4520fc02a4e89497c10de26be936758a3aaa/propcache-0.5.2-cp314-cp314-win32.whl", hash = "sha256:cc6fc3cc62e8501d3ed62894425040d2728ecddb1ed072737a5c70bd537aa9f0", size = 39436, upload-time = "2026-05-08T21:01:41.654Z" }, + { url = "https://files.pythonhosted.org/packages/61/d2/45c9defbaa1ea297035d9d4cce9e8f80daafbf19319c6007f157c6256ea9/propcache-0.5.2-cp314-cp314-win_amd64.whl", hash = "sha256:81e3a30b0bb60caa22033dd0f8a3618d1d67356212514f62c57db75cb0ef410c", size = 42373, upload-time = "2026-05-08T21:01:43.041Z" }, + { url = "https://files.pythonhosted.org/packages/44/68/9ea5103f41d5217d7d6ec24db90018e23aebec070c3f9a6e54d12b841fd8/propcache-0.5.2-cp314-cp314-win_arm64.whl", hash = "sha256:0d2c9bf8528f135dbb805ce027567e09164f7efa51a2be07458a2c0420f292d0", size = 38554, upload-time = "2026-05-08T21:01:44.336Z" }, + { url = "https://files.pythonhosted.org/packages/8a/81/fadf555f42d3b762eea8a53950b0489fdc0aa9da5f8ed9e10ce0a4e01b48/propcache-0.5.2-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:4bc8ff1feffc6a61c7002ffe84634c41b822e104990ae009f44a0834430070bb", size = 99395, upload-time = "2026-05-08T21:01:45.883Z" }, + { url = "https://files.pythonhosted.org/packages/f5/c9/c61e134a686949cf7971af3a390148b1156f7be81c73bc0cd12c873e2d48/propcache-0.5.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:79aa3ff0a9b566633b642fa9caf7e21ed1c13d6feca718187873f199e1514078", size = 56653, upload-time = "2026-05-08T21:01:47.307Z" }, + { url = "https://files.pythonhosted.org/packages/cb/73/daf935ea7048ddd7ec8eec5345b4a40b619d2d178b3c0a0900796bc3c794/propcache-0.5.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1b31822f4474c4036bae62de9402710051d431a606d6a0f907fec79935a071aa", size = 56914, upload-time = "2026-05-08T21:01:48.573Z" }, + { url = "https://files.pythonhosted.org/packages/79/9f/aba959b435ea18617edd7cf0a7ad0b9c574b8fc7e3d2cd55fb59cb255d33/propcache-0.5.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:13fef48778b5a2a756523fdb781326b028ca75e32858b04f2cdd19f394564917", size = 62567, upload-time = "2026-05-08T21:01:49.903Z" }, + { url = "https://files.pythonhosted.org/packages/6c/a1/859942de9a791ff42f6141736f5b37749b8f53e65edfa49638c67dd67e6a/propcache-0.5.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8b73ab70f1a3351fbc71f663b3e645af6dd0329100c353081cf69c37433fc6fe", size = 65542, upload-time = "2026-05-08T21:01:51.204Z" }, + { url = "https://files.pythonhosted.org/packages/b5/61/315bc0fd6c0fc7f80a528b8afd209e5fc4a875ea79571b91b8f50f442907/propcache-0.5.2-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5538d2c13d93e4698af7e092b57bc7298fd35d1d58e656ae18f23ee0d0378e03", size = 66845, upload-time = "2026-05-08T21:01:52.539Z" }, + { url = "https://files.pythonhosted.org/packages/47/f7/9f8122e3132e8e354ac41975ef8f1099be7d5a16bc7ae562734e993665c0/propcache-0.5.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cd645f03898405cabe694fb8bc35241e3a9c332ec85627584fe3de201452b335", size = 63985, upload-time = "2026-05-08T21:01:53.847Z" }, + { url = "https://files.pythonhosted.org/packages/c8/54/c317819ec157cbf6f35df9df9657a6f82daf34d5faf15948b2f639c2192e/propcache-0.5.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a473b3440261e0c60706e732b2ed2f517857344fc21bf48fdfe211e2d98eb285", size = 63999, upload-time = "2026-05-08T21:01:55.179Z" }, + { url = "https://files.pythonhosted.org/packages/5a/56/387e3f7dfce0a9233df41fb888aa1c30222cb4bbbf09537c02dd9bd85fe2/propcache-0.5.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7afa37062e6650640e932e4cc9297d81f9f42d9944029cc386b8247dea4da837", size = 62779, upload-time = "2026-05-08T21:01:57.489Z" }, + { url = "https://files.pythonhosted.org/packages/a1/9c/596784cb5824ed61ee960d3f8655a3f0993e107c6e98ab6c818b7fb92ccb/propcache-0.5.2-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:8a90efd5777e996e42d568db9ac740b944d691e565cbfd31b2f7832f9184b2b8", size = 59796, upload-time = "2026-05-08T21:01:58.736Z" }, + { url = "https://files.pythonhosted.org/packages/c2/3d/1a6cfa1726a48542c1e8784a0761421476a5b68e09b7f36bf95eb954aaba/propcache-0.5.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:f19bb891234d72535764d703bfed1153cc34f4214d5bd7150aee1eec9e8f4366", size = 66023, upload-time = "2026-05-08T21:02:00.228Z" }, + { url = "https://files.pythonhosted.org/packages/e4/0e/05fd6990369477076e4e280bcb970de760fddf0161a46e988bc95f7940ec/propcache-0.5.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:32775082acd2d807ee3db715c7770d38767b817870acfa08c29e057f3c4d5b56", size = 64448, upload-time = "2026-05-08T21:02:01.888Z" }, + { url = "https://files.pythonhosted.org/packages/cd/86/5f8da315a4309c62c10c0b2516b17492d5d3bbe1bb862b96604db67e2a37/propcache-0.5.2-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:9282fb1a3bccd038da9f768b927b24a0c753e466c086b7c4f3c6982851eefb2d", size = 67329, upload-time = "2026-05-08T21:02:03.484Z" }, + { url = "https://files.pythonhosted.org/packages/da/d3/3368efe79ab21f0cdf86ef49895811c9cc933131d4cde1f28a624e22e712/propcache-0.5.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:cc49723e2f60d6b32a0f0b08a3fd6d13203c07f1cd9566cfce0f12a917c967a2", size = 65172, upload-time = "2026-05-08T21:02:04.745Z" }, + { url = "https://files.pythonhosted.org/packages/d5/07/127e8b0bacfb325396196f9d976a22453049b89b9b2b08477cc3145faa44/propcache-0.5.2-cp314-cp314t-win32.whl", hash = "sha256:2d7aa89ebca5acc98cba9d1472d976e394782f587bad6661003602a619fd1821", size = 43813, upload-time = "2026-05-08T21:02:06.025Z" }, + { url = "https://files.pythonhosted.org/packages/88/fb/46dad6c0ae49ed230ab1b16c890c2b6314e2403e6c412976f4a72d64a527/propcache-0.5.2-cp314-cp314t-win_amd64.whl", hash = "sha256:d447bb0b3054be5818458fbb171208b1d9ff11eba14e18ca18b90cbb45767370", size = 47764, upload-time = "2026-05-08T21:02:07.353Z" }, + { url = "https://files.pythonhosted.org/packages/e7/c4/a47d0a63aa309d10d59ede6e9d4cff03a344a79d1f0f4cd0cd74997b53e0/propcache-0.5.2-cp314-cp314t-win_arm64.whl", hash = "sha256:fe67a3d11cd9b4efabfa45c3d00ffba2b26811442a73a581a94b67c2b5faccf6", size = 41140, upload-time = "2026-05-08T21:02:09.065Z" }, + { url = "https://files.pythonhosted.org/packages/3a/ed/1cdcab6ba3d6ab7feca11fc14f0eeea80755bb53ef4e892079f31b10a25f/propcache-0.5.2-py3-none-any.whl", hash = "sha256:be1ddfcbb376e3de5d2e2db1d58d6d67463e6b4f9f040c000de8e300295465fe", size = 14036, upload-time = "2026-05-08T21:02:10.673Z" }, +] + +[[package]] +name = "properdocs" +version = "1.6.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "ghp-import" }, + { name = "jinja2" }, + { name = "markdown" }, + { name = "markupsafe" }, + { name = "packaging" }, + { name = "pathspec" }, + { name = "platformdirs" }, + { name = "pyyaml" }, + { name = "pyyaml-env-tag" }, + { name = "watchdog" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ec/29/f27a4e1eddf72ed3db6e47818fbafe6debbf09fd7051f9c1a007239b46ef/properdocs-1.6.7.tar.gz", hash = "sha256:adc7b16e562890af0e098a7e5b02e3a81c20894a87d6a28d345c9300de73c26e", size = 276141, upload-time = "2026-03-20T20:07:48.167Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bd/4d/fc923f5c85318ee8cc903566dc4e0ebe41b2dfc1d2ecf5546db232397ed6/properdocs-1.6.7-py3-none-any.whl", hash = "sha256:6fa0cfa2e01bf338f684892c8a506cf70ea88ae7f3479c933b6fa20168101cbd", size = 225406, upload-time = "2026-03-20T20:07:46.875Z" }, +] + +[[package]] +name = "py-cpuinfo" +version = "9.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/37/a8/d832f7293ebb21690860d2e01d8115e5ff6f2ae8bbdc953f0eb0fa4bd2c7/py-cpuinfo-9.0.0.tar.gz", hash = "sha256:3cdbbf3fac90dc6f118bfd64384f309edeadd902d7c8fb17f02ffa1fc3f49690", size = 104716, upload-time = "2022-10-25T20:38:06.303Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e0/a9/023730ba63db1e494a271cb018dcd361bd2c917ba7004c3e49d5daf795a2/py_cpuinfo-9.0.0-py3-none-any.whl", hash = "sha256:859625bc251f64e21f077d099d4162689c762b5d6a4c3c97553d56241c9674d5", size = 22335, upload-time = "2022-10-25T20:38:27.636Z" }, +] + +[[package]] +name = "py-partiql-parser" +version = "0.6.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/56/7a/a0f6bda783eb4df8e3dfd55973a1ac6d368a89178c300e1b5b91cd181e5e/py_partiql_parser-0.6.3.tar.gz", hash = "sha256:09cecf916ce6e3da2c050f0cb6106166de42c33d34a078ec2eb19377ea70389a", size = 17456, upload-time = "2025-10-18T13:56:13.441Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c9/33/a7cbfccc39056a5cf8126b7aab4c8bafbedd4f0ca68ae40ecb627a2d2cd3/py_partiql_parser-0.6.3-py2.py3-none-any.whl", hash = "sha256:deb0769c3346179d2f590dcbde556f708cdb929059fb654bad75f4cf6e07f582", size = 23752, upload-time = "2025-10-18T13:56:12.256Z" }, +] + +[[package]] +name = "pycparser" +version = "3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" }, +] + +[[package]] +name = "pydantic" +version = "2.12.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/69/44/36f1a6e523abc58ae5f928898e4aca2e0ea509b5aa6f6f392a5d882be928/pydantic-2.12.5.tar.gz", hash = "sha256:4d351024c75c0f085a9febbb665ce8c0c6ec5d30e903bdb6394b7ede26aebb49", size = 821591, upload-time = "2025-11-26T15:11:46.471Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5a/87/b70ad306ebb6f9b585f114d0ac2137d792b48be34d732d60e597c2f8465a/pydantic-2.12.5-py3-none-any.whl", hash = "sha256:e561593fccf61e8a20fc46dfc2dfe075b8be7d0188df33f221ad1f0139180f9d", size = 463580, upload-time = "2025-11-26T15:11:44.605Z" }, +] + +[[package]] +name = "pydantic-core" +version = "2.41.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/71/70/23b021c950c2addd24ec408e9ab05d59b035b39d97cdc1130e1bce647bb6/pydantic_core-2.41.5.tar.gz", hash = "sha256:08daa51ea16ad373ffd5e7606252cc32f07bc72b28284b6bc9c6df804816476e", size = 460952, upload-time = "2025-11-04T13:43:49.098Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5f/5d/5f6c63eebb5afee93bcaae4ce9a898f3373ca23df3ccaef086d0233a35a7/pydantic_core-2.41.5-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:f41a7489d32336dbf2199c8c0a215390a751c5b014c2c1c5366e817202e9cdf7", size = 2110990, upload-time = "2025-11-04T13:39:58.079Z" }, + { url = "https://files.pythonhosted.org/packages/aa/32/9c2e8ccb57c01111e0fd091f236c7b371c1bccea0fa85247ac55b1e2b6b6/pydantic_core-2.41.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:070259a8818988b9a84a449a2a7337c7f430a22acc0859c6b110aa7212a6d9c0", size = 1896003, upload-time = "2025-11-04T13:39:59.956Z" }, + { url = "https://files.pythonhosted.org/packages/68/b8/a01b53cb0e59139fbc9e4fda3e9724ede8de279097179be4ff31f1abb65a/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e96cea19e34778f8d59fe40775a7a574d95816eb150850a85a7a4c8f4b94ac69", size = 1919200, upload-time = "2025-11-04T13:40:02.241Z" }, + { url = "https://files.pythonhosted.org/packages/38/de/8c36b5198a29bdaade07b5985e80a233a5ac27137846f3bc2d3b40a47360/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ed2e99c456e3fadd05c991f8f437ef902e00eedf34320ba2b0842bd1c3ca3a75", size = 2052578, upload-time = "2025-11-04T13:40:04.401Z" }, + { url = "https://files.pythonhosted.org/packages/00/b5/0e8e4b5b081eac6cb3dbb7e60a65907549a1ce035a724368c330112adfdd/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:65840751b72fbfd82c3c640cff9284545342a4f1eb1586ad0636955b261b0b05", size = 2208504, upload-time = "2025-11-04T13:40:06.072Z" }, + { url = "https://files.pythonhosted.org/packages/77/56/87a61aad59c7c5b9dc8caad5a41a5545cba3810c3e828708b3d7404f6cef/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e536c98a7626a98feb2d3eaf75944ef6f3dbee447e1f841eae16f2f0a72d8ddc", size = 2335816, upload-time = "2025-11-04T13:40:07.835Z" }, + { url = "https://files.pythonhosted.org/packages/0d/76/941cc9f73529988688a665a5c0ecff1112b3d95ab48f81db5f7606f522d3/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eceb81a8d74f9267ef4081e246ffd6d129da5d87e37a77c9bde550cb04870c1c", size = 2075366, upload-time = "2025-11-04T13:40:09.804Z" }, + { url = "https://files.pythonhosted.org/packages/d3/43/ebef01f69baa07a482844faaa0a591bad1ef129253ffd0cdaa9d8a7f72d3/pydantic_core-2.41.5-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d38548150c39b74aeeb0ce8ee1d8e82696f4a4e16ddc6de7b1d8823f7de4b9b5", size = 2171698, upload-time = "2025-11-04T13:40:12.004Z" }, + { url = "https://files.pythonhosted.org/packages/b1/87/41f3202e4193e3bacfc2c065fab7706ebe81af46a83d3e27605029c1f5a6/pydantic_core-2.41.5-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:c23e27686783f60290e36827f9c626e63154b82b116d7fe9adba1fda36da706c", size = 2132603, upload-time = "2025-11-04T13:40:13.868Z" }, + { url = "https://files.pythonhosted.org/packages/49/7d/4c00df99cb12070b6bccdef4a195255e6020a550d572768d92cc54dba91a/pydantic_core-2.41.5-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:482c982f814460eabe1d3bb0adfdc583387bd4691ef00b90575ca0d2b6fe2294", size = 2329591, upload-time = "2025-11-04T13:40:15.672Z" }, + { url = "https://files.pythonhosted.org/packages/cc/6a/ebf4b1d65d458f3cda6a7335d141305dfa19bdc61140a884d165a8a1bbc7/pydantic_core-2.41.5-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:bfea2a5f0b4d8d43adf9d7b8bf019fb46fdd10a2e5cde477fbcb9d1fa08c68e1", size = 2319068, upload-time = "2025-11-04T13:40:17.532Z" }, + { url = "https://files.pythonhosted.org/packages/49/3b/774f2b5cd4192d5ab75870ce4381fd89cf218af999515baf07e7206753f0/pydantic_core-2.41.5-cp312-cp312-win32.whl", hash = "sha256:b74557b16e390ec12dca509bce9264c3bbd128f8a2c376eaa68003d7f327276d", size = 1985908, upload-time = "2025-11-04T13:40:19.309Z" }, + { url = "https://files.pythonhosted.org/packages/86/45/00173a033c801cacf67c190fef088789394feaf88a98a7035b0e40d53dc9/pydantic_core-2.41.5-cp312-cp312-win_amd64.whl", hash = "sha256:1962293292865bca8e54702b08a4f26da73adc83dd1fcf26fbc875b35d81c815", size = 2020145, upload-time = "2025-11-04T13:40:21.548Z" }, + { url = "https://files.pythonhosted.org/packages/f9/22/91fbc821fa6d261b376a3f73809f907cec5ca6025642c463d3488aad22fb/pydantic_core-2.41.5-cp312-cp312-win_arm64.whl", hash = "sha256:1746d4a3d9a794cacae06a5eaaccb4b8643a131d45fbc9af23e353dc0a5ba5c3", size = 1976179, upload-time = "2025-11-04T13:40:23.393Z" }, + { url = "https://files.pythonhosted.org/packages/87/06/8806241ff1f70d9939f9af039c6c35f2360cf16e93c2ca76f184e76b1564/pydantic_core-2.41.5-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:941103c9be18ac8daf7b7adca8228f8ed6bb7a1849020f643b3a14d15b1924d9", size = 2120403, upload-time = "2025-11-04T13:40:25.248Z" }, + { url = "https://files.pythonhosted.org/packages/94/02/abfa0e0bda67faa65fef1c84971c7e45928e108fe24333c81f3bfe35d5f5/pydantic_core-2.41.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:112e305c3314f40c93998e567879e887a3160bb8689ef3d2c04b6cc62c33ac34", size = 1896206, upload-time = "2025-11-04T13:40:27.099Z" }, + { url = "https://files.pythonhosted.org/packages/15/df/a4c740c0943e93e6500f9eb23f4ca7ec9bf71b19e608ae5b579678c8d02f/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0cbaad15cb0c90aa221d43c00e77bb33c93e8d36e0bf74760cd00e732d10a6a0", size = 1919307, upload-time = "2025-11-04T13:40:29.806Z" }, + { url = "https://files.pythonhosted.org/packages/9a/e3/6324802931ae1d123528988e0e86587c2072ac2e5394b4bc2bc34b61ff6e/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:03ca43e12fab6023fc79d28ca6b39b05f794ad08ec2feccc59a339b02f2b3d33", size = 2063258, upload-time = "2025-11-04T13:40:33.544Z" }, + { url = "https://files.pythonhosted.org/packages/c9/d4/2230d7151d4957dd79c3044ea26346c148c98fbf0ee6ebd41056f2d62ab5/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:dc799088c08fa04e43144b164feb0c13f9a0bc40503f8df3e9fde58a3c0c101e", size = 2214917, upload-time = "2025-11-04T13:40:35.479Z" }, + { url = "https://files.pythonhosted.org/packages/e6/9f/eaac5df17a3672fef0081b6c1bb0b82b33ee89aa5cec0d7b05f52fd4a1fa/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:97aeba56665b4c3235a0e52b2c2f5ae9cd071b8a8310ad27bddb3f7fb30e9aa2", size = 2332186, upload-time = "2025-11-04T13:40:37.436Z" }, + { url = "https://files.pythonhosted.org/packages/cf/4e/35a80cae583a37cf15604b44240e45c05e04e86f9cfd766623149297e971/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:406bf18d345822d6c21366031003612b9c77b3e29ffdb0f612367352aab7d586", size = 2073164, upload-time = "2025-11-04T13:40:40.289Z" }, + { url = "https://files.pythonhosted.org/packages/bf/e3/f6e262673c6140dd3305d144d032f7bd5f7497d3871c1428521f19f9efa2/pydantic_core-2.41.5-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:b93590ae81f7010dbe380cdeab6f515902ebcbefe0b9327cc4804d74e93ae69d", size = 2179146, upload-time = "2025-11-04T13:40:42.809Z" }, + { url = "https://files.pythonhosted.org/packages/75/c7/20bd7fc05f0c6ea2056a4565c6f36f8968c0924f19b7d97bbfea55780e73/pydantic_core-2.41.5-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:01a3d0ab748ee531f4ea6c3e48ad9dac84ddba4b0d82291f87248f2f9de8d740", size = 2137788, upload-time = "2025-11-04T13:40:44.752Z" }, + { url = "https://files.pythonhosted.org/packages/3a/8d/34318ef985c45196e004bc46c6eab2eda437e744c124ef0dbe1ff2c9d06b/pydantic_core-2.41.5-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:6561e94ba9dacc9c61bce40e2d6bdc3bfaa0259d3ff36ace3b1e6901936d2e3e", size = 2340133, upload-time = "2025-11-04T13:40:46.66Z" }, + { url = "https://files.pythonhosted.org/packages/9c/59/013626bf8c78a5a5d9350d12e7697d3d4de951a75565496abd40ccd46bee/pydantic_core-2.41.5-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:915c3d10f81bec3a74fbd4faebe8391013ba61e5a1a8d48c4455b923bdda7858", size = 2324852, upload-time = "2025-11-04T13:40:48.575Z" }, + { url = "https://files.pythonhosted.org/packages/1a/d9/c248c103856f807ef70c18a4f986693a46a8ffe1602e5d361485da502d20/pydantic_core-2.41.5-cp313-cp313-win32.whl", hash = "sha256:650ae77860b45cfa6e2cdafc42618ceafab3a2d9a3811fcfbd3bbf8ac3c40d36", size = 1994679, upload-time = "2025-11-04T13:40:50.619Z" }, + { url = "https://files.pythonhosted.org/packages/9e/8b/341991b158ddab181cff136acd2552c9f35bd30380422a639c0671e99a91/pydantic_core-2.41.5-cp313-cp313-win_amd64.whl", hash = "sha256:79ec52ec461e99e13791ec6508c722742ad745571f234ea6255bed38c6480f11", size = 2019766, upload-time = "2025-11-04T13:40:52.631Z" }, + { url = "https://files.pythonhosted.org/packages/73/7d/f2f9db34af103bea3e09735bb40b021788a5e834c81eedb541991badf8f5/pydantic_core-2.41.5-cp313-cp313-win_arm64.whl", hash = "sha256:3f84d5c1b4ab906093bdc1ff10484838aca54ef08de4afa9de0f5f14d69639cd", size = 1981005, upload-time = "2025-11-04T13:40:54.734Z" }, + { url = "https://files.pythonhosted.org/packages/ea/28/46b7c5c9635ae96ea0fbb779e271a38129df2550f763937659ee6c5dbc65/pydantic_core-2.41.5-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:3f37a19d7ebcdd20b96485056ba9e8b304e27d9904d233d7b1015db320e51f0a", size = 2119622, upload-time = "2025-11-04T13:40:56.68Z" }, + { url = "https://files.pythonhosted.org/packages/74/1a/145646e5687e8d9a1e8d09acb278c8535ebe9e972e1f162ed338a622f193/pydantic_core-2.41.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1d1d9764366c73f996edd17abb6d9d7649a7eb690006ab6adbda117717099b14", size = 1891725, upload-time = "2025-11-04T13:40:58.807Z" }, + { url = "https://files.pythonhosted.org/packages/23/04/e89c29e267b8060b40dca97bfc64a19b2a3cf99018167ea1677d96368273/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:25e1c2af0fce638d5f1988b686f3b3ea8cd7de5f244ca147c777769e798a9cd1", size = 1915040, upload-time = "2025-11-04T13:41:00.853Z" }, + { url = "https://files.pythonhosted.org/packages/84/a3/15a82ac7bd97992a82257f777b3583d3e84bdb06ba6858f745daa2ec8a85/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:506d766a8727beef16b7adaeb8ee6217c64fc813646b424d0804d67c16eddb66", size = 2063691, upload-time = "2025-11-04T13:41:03.504Z" }, + { url = "https://files.pythonhosted.org/packages/74/9b/0046701313c6ef08c0c1cf0e028c67c770a4e1275ca73131563c5f2a310a/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4819fa52133c9aa3c387b3328f25c1facc356491e6135b459f1de698ff64d869", size = 2213897, upload-time = "2025-11-04T13:41:05.804Z" }, + { url = "https://files.pythonhosted.org/packages/8a/cd/6bac76ecd1b27e75a95ca3a9a559c643b3afcd2dd62086d4b7a32a18b169/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2b761d210c9ea91feda40d25b4efe82a1707da2ef62901466a42492c028553a2", size = 2333302, upload-time = "2025-11-04T13:41:07.809Z" }, + { url = "https://files.pythonhosted.org/packages/4c/d2/ef2074dc020dd6e109611a8be4449b98cd25e1b9b8a303c2f0fca2f2bcf7/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:22f0fb8c1c583a3b6f24df2470833b40207e907b90c928cc8d3594b76f874375", size = 2064877, upload-time = "2025-11-04T13:41:09.827Z" }, + { url = "https://files.pythonhosted.org/packages/18/66/e9db17a9a763d72f03de903883c057b2592c09509ccfe468187f2a2eef29/pydantic_core-2.41.5-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2782c870e99878c634505236d81e5443092fba820f0373997ff75f90f68cd553", size = 2180680, upload-time = "2025-11-04T13:41:12.379Z" }, + { url = "https://files.pythonhosted.org/packages/d3/9e/3ce66cebb929f3ced22be85d4c2399b8e85b622db77dad36b73c5387f8f8/pydantic_core-2.41.5-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:0177272f88ab8312479336e1d777f6b124537d47f2123f89cb37e0accea97f90", size = 2138960, upload-time = "2025-11-04T13:41:14.627Z" }, + { url = "https://files.pythonhosted.org/packages/a6/62/205a998f4327d2079326b01abee48e502ea739d174f0a89295c481a2272e/pydantic_core-2.41.5-cp314-cp314-musllinux_1_1_armv7l.whl", hash = "sha256:63510af5e38f8955b8ee5687740d6ebf7c2a0886d15a6d65c32814613681bc07", size = 2339102, upload-time = "2025-11-04T13:41:16.868Z" }, + { url = "https://files.pythonhosted.org/packages/3c/0d/f05e79471e889d74d3d88f5bd20d0ed189ad94c2423d81ff8d0000aab4ff/pydantic_core-2.41.5-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:e56ba91f47764cc14f1daacd723e3e82d1a89d783f0f5afe9c364b8bb491ccdb", size = 2326039, upload-time = "2025-11-04T13:41:18.934Z" }, + { url = "https://files.pythonhosted.org/packages/ec/e1/e08a6208bb100da7e0c4b288eed624a703f4d129bde2da475721a80cab32/pydantic_core-2.41.5-cp314-cp314-win32.whl", hash = "sha256:aec5cf2fd867b4ff45b9959f8b20ea3993fc93e63c7363fe6851424c8a7e7c23", size = 1995126, upload-time = "2025-11-04T13:41:21.418Z" }, + { url = "https://files.pythonhosted.org/packages/48/5d/56ba7b24e9557f99c9237e29f5c09913c81eeb2f3217e40e922353668092/pydantic_core-2.41.5-cp314-cp314-win_amd64.whl", hash = "sha256:8e7c86f27c585ef37c35e56a96363ab8de4e549a95512445b85c96d3e2f7c1bf", size = 2015489, upload-time = "2025-11-04T13:41:24.076Z" }, + { url = "https://files.pythonhosted.org/packages/4e/bb/f7a190991ec9e3e0ba22e4993d8755bbc4a32925c0b5b42775c03e8148f9/pydantic_core-2.41.5-cp314-cp314-win_arm64.whl", hash = "sha256:e672ba74fbc2dc8eea59fb6d4aed6845e6905fc2a8afe93175d94a83ba2a01a0", size = 1977288, upload-time = "2025-11-04T13:41:26.33Z" }, + { url = "https://files.pythonhosted.org/packages/92/ed/77542d0c51538e32e15afe7899d79efce4b81eee631d99850edc2f5e9349/pydantic_core-2.41.5-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:8566def80554c3faa0e65ac30ab0932b9e3a5cd7f8323764303d468e5c37595a", size = 2120255, upload-time = "2025-11-04T13:41:28.569Z" }, + { url = "https://files.pythonhosted.org/packages/bb/3d/6913dde84d5be21e284439676168b28d8bbba5600d838b9dca99de0fad71/pydantic_core-2.41.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:b80aa5095cd3109962a298ce14110ae16b8c1aece8b72f9dafe81cf597ad80b3", size = 1863760, upload-time = "2025-11-04T13:41:31.055Z" }, + { url = "https://files.pythonhosted.org/packages/5a/f0/e5e6b99d4191da102f2b0eb9687aaa7f5bea5d9964071a84effc3e40f997/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3006c3dd9ba34b0c094c544c6006cc79e87d8612999f1a5d43b769b89181f23c", size = 1878092, upload-time = "2025-11-04T13:41:33.21Z" }, + { url = "https://files.pythonhosted.org/packages/71/48/36fb760642d568925953bcc8116455513d6e34c4beaa37544118c36aba6d/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:72f6c8b11857a856bcfa48c86f5368439f74453563f951e473514579d44aa612", size = 2053385, upload-time = "2025-11-04T13:41:35.508Z" }, + { url = "https://files.pythonhosted.org/packages/20/25/92dc684dd8eb75a234bc1c764b4210cf2646479d54b47bf46061657292a8/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5cb1b2f9742240e4bb26b652a5aeb840aa4b417c7748b6f8387927bc6e45e40d", size = 2218832, upload-time = "2025-11-04T13:41:37.732Z" }, + { url = "https://files.pythonhosted.org/packages/e2/09/f53e0b05023d3e30357d82eb35835d0f6340ca344720a4599cd663dca599/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:bd3d54f38609ff308209bd43acea66061494157703364ae40c951f83ba99a1a9", size = 2327585, upload-time = "2025-11-04T13:41:40Z" }, + { url = "https://files.pythonhosted.org/packages/aa/4e/2ae1aa85d6af35a39b236b1b1641de73f5a6ac4d5a7509f77b814885760c/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2ff4321e56e879ee8d2a879501c8e469414d948f4aba74a2d4593184eb326660", size = 2041078, upload-time = "2025-11-04T13:41:42.323Z" }, + { url = "https://files.pythonhosted.org/packages/cd/13/2e215f17f0ef326fc72afe94776edb77525142c693767fc347ed6288728d/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d0d2568a8c11bf8225044aa94409e21da0cb09dcdafe9ecd10250b2baad531a9", size = 2173914, upload-time = "2025-11-04T13:41:45.221Z" }, + { url = "https://files.pythonhosted.org/packages/02/7a/f999a6dcbcd0e5660bc348a3991c8915ce6599f4f2c6ac22f01d7a10816c/pydantic_core-2.41.5-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:a39455728aabd58ceabb03c90e12f71fd30fa69615760a075b9fec596456ccc3", size = 2129560, upload-time = "2025-11-04T13:41:47.474Z" }, + { url = "https://files.pythonhosted.org/packages/3a/b1/6c990ac65e3b4c079a4fb9f5b05f5b013afa0f4ed6780a3dd236d2cbdc64/pydantic_core-2.41.5-cp314-cp314t-musllinux_1_1_armv7l.whl", hash = "sha256:239edca560d05757817c13dc17c50766136d21f7cd0fac50295499ae24f90fdf", size = 2329244, upload-time = "2025-11-04T13:41:49.992Z" }, + { url = "https://files.pythonhosted.org/packages/d9/02/3c562f3a51afd4d88fff8dffb1771b30cfdfd79befd9883ee094f5b6c0d8/pydantic_core-2.41.5-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:2a5e06546e19f24c6a96a129142a75cee553cc018ffee48a460059b1185f4470", size = 2331955, upload-time = "2025-11-04T13:41:54.079Z" }, + { url = "https://files.pythonhosted.org/packages/5c/96/5fb7d8c3c17bc8c62fdb031c47d77a1af698f1d7a406b0f79aaa1338f9ad/pydantic_core-2.41.5-cp314-cp314t-win32.whl", hash = "sha256:b4ececa40ac28afa90871c2cc2b9ffd2ff0bf749380fbdf57d165fd23da353aa", size = 1988906, upload-time = "2025-11-04T13:41:56.606Z" }, + { url = "https://files.pythonhosted.org/packages/22/ed/182129d83032702912c2e2d8bbe33c036f342cc735737064668585dac28f/pydantic_core-2.41.5-cp314-cp314t-win_amd64.whl", hash = "sha256:80aa89cad80b32a912a65332f64a4450ed00966111b6615ca6816153d3585a8c", size = 1981607, upload-time = "2025-11-04T13:41:58.889Z" }, + { url = "https://files.pythonhosted.org/packages/9f/ed/068e41660b832bb0b1aa5b58011dea2a3fe0ba7861ff38c4d4904c1c1a99/pydantic_core-2.41.5-cp314-cp314t-win_arm64.whl", hash = "sha256:35b44f37a3199f771c3eaa53051bc8a70cd7b54f333531c59e29fd4db5d15008", size = 1974769, upload-time = "2025-11-04T13:42:01.186Z" }, + { url = "https://files.pythonhosted.org/packages/09/32/59b0c7e63e277fa7911c2fc70ccfb45ce4b98991e7ef37110663437005af/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:7da7087d756b19037bc2c06edc6c170eeef3c3bafcb8f532ff17d64dc427adfd", size = 2110495, upload-time = "2025-11-04T13:42:49.689Z" }, + { url = "https://files.pythonhosted.org/packages/aa/81/05e400037eaf55ad400bcd318c05bb345b57e708887f07ddb2d20e3f0e98/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:aabf5777b5c8ca26f7824cb4a120a740c9588ed58df9b2d196ce92fba42ff8dc", size = 1915388, upload-time = "2025-11-04T13:42:52.215Z" }, + { url = "https://files.pythonhosted.org/packages/6e/0d/e3549b2399f71d56476b77dbf3cf8937cec5cd70536bdc0e374a421d0599/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c007fe8a43d43b3969e8469004e9845944f1a80e6acd47c150856bb87f230c56", size = 1942879, upload-time = "2025-11-04T13:42:56.483Z" }, + { url = "https://files.pythonhosted.org/packages/f7/07/34573da085946b6a313d7c42f82f16e8920bfd730665de2d11c0c37a74b5/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:76d0819de158cd855d1cbb8fcafdf6f5cf1eb8e470abe056d5d161106e38062b", size = 2139017, upload-time = "2025-11-04T13:42:59.471Z" }, +] + +[[package]] +name = "pydantic-settings" +version = "2.14.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pydantic" }, + { name = "python-dotenv" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5c/b5/8f48e906c3e0205276e8bd8cb7512217a87b2685304d64be27cad5b3019f/pydantic_settings-2.14.2.tar.gz", hash = "sha256:c19dd64b19097f1de80184f0cc7b0272a13ae6e170cbf240a3e27e381ed14a5f", size = 237700, upload-time = "2026-06-19T13:44:56.324Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/77/c1/6e422f34e569cf8e18df68d1939c81c099d2b61e4f7d9621c8a77560799c/pydantic_settings-2.14.2-py3-none-any.whl", hash = "sha256:a20c97b37910b6550d5ea50fbcc2d4187defe58cd57070b73863d069419c9440", size = 61715, upload-time = "2026-06-19T13:44:55.02Z" }, +] + +[[package]] +name = "pygments" +version = "2.20.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" }, +] + +[[package]] +name = "pygments-ansi-color" +version = "0.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/50/f9/7f417aaee98a74b4f757f2b72971245181fcf25d824d2e7a190345669eaf/pygments-ansi-color-0.3.0.tar.gz", hash = "sha256:7018954cf5b11d1e734383a1bafab5af613213f246109417fee3f76da26d5431", size = 7317, upload-time = "2023-05-18T22:44:35.792Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e6/17/8306a0bcd8c88d7761c2e73e831b0be026cd6873ce1f12beb3b4c9a03ffa/pygments_ansi_color-0.3.0-py3-none-any.whl", hash = "sha256:7eb063feaecadad9d4d1fd3474cbfeadf3486b64f760a8f2a00fc25392180aba", size = 10242, upload-time = "2023-05-18T22:44:34.287Z" }, +] + +[[package]] +name = "pymdown-extensions" +version = "11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown" }, + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/47/67/f1e79672a5f91985577c7984c9709ca110e4fd37fe7fd167b60422e6ccc2/pymdown_extensions-11.0.tar.gz", hash = "sha256:8269cef0247f9e2d0a62fcea10860aba05c1cbab5470fd4b63230b96434dc589", size = 857049, upload-time = "2026-06-23T02:27:45.146Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/af/b6/1ae53367e28b9cffa3be7574e13fbe4589694272fd47710fbdbafd3d63c6/pymdown_extensions-11.0-py3-none-any.whl", hash = "sha256:fbc4acb641814fa9d17521bbd21a5240ef739a662f11c06330c4b78c93e954d6", size = 269415, upload-time = "2026-06-23T02:27:43.826Z" }, +] + +[[package]] +name = "pyparsing" +version = "3.3.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f3/91/9c6ee907786a473bf81c5f53cf703ba0957b23ab84c264080fb5a450416f/pyparsing-3.3.2.tar.gz", hash = "sha256:c777f4d763f140633dcb6d8a3eda953bf7a214dc4eff598413c070bcdc117cbc", size = 6851574, upload-time = "2026-01-21T03:57:59.36Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/bd/c038d7cc38edc1aa5bf91ab8068b63d4308c66c4c8bb3cbba7dfbc049f9c/pyparsing-3.3.2-py3-none-any.whl", hash = "sha256:850ba148bd908d7e2411587e247a1e4f0327839c40e2e5e6d05a007ecc69911d", size = 122781, upload-time = "2026-01-21T03:57:55.912Z" }, +] + +[[package]] +name = "pytest" +version = "9.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, +] + +[[package]] +name = "pytest-accept" +version = "0.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "astor" }, + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6f/42/573e6dcd8d1a5fc779d525268d5036f710d018cdeefbae2bd5559687a6d5/pytest_accept-0.3.0.tar.gz", hash = "sha256:6f4e03e2492621e10b7678a331828274498cca04686b15b0f3e704e16e651068", size = 29744, upload-time = "2026-06-11T18:44:39.03Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/06/40/79f6f13e616f580b9c35110376818c76cacc54b70d2965bf1f82be336c66/pytest_accept-0.3.0-py3-none-any.whl", hash = "sha256:5e73f27020853b861a63dc630dfe63124af4bd60e0e0bb692e1376b99798f2b5", size = 39846, upload-time = "2026-06-11T18:44:37.965Z" }, +] + +[[package]] +name = "pytest-asyncio" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/7c/d36d04db312ecf4298932ef77e6e4a9e8ad017906e24e34f0b0c361a2473/pytest_asyncio-1.4.0.tar.gz", hash = "sha256:c6c0d2259945122819f171a32ecea2c349ead889ee28176caaf492143424be42", size = 58514, upload-time = "2026-05-26T09:56:04.083Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/03/e2/08a497ef684b88559c9cc5f4ad53a37e7b99e727094a86d6ea32536d5d3c/pytest_asyncio-1.4.0-py3-none-any.whl", hash = "sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1", size = 16930, upload-time = "2026-05-26T09:56:02.576Z" }, +] + +[[package]] +name = "pytest-benchmark" +version = "5.2.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "py-cpuinfo" }, + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/24/34/9f732b76456d64faffbef6232f1f9dbec7a7c4999ff46282fa418bd1af66/pytest_benchmark-5.2.3.tar.gz", hash = "sha256:deb7317998a23c650fd4ff76e1230066a76cb45dcece0aca5607143c619e7779", size = 341340, upload-time = "2025-11-09T18:48:43.215Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/33/29/e756e715a48959f1c0045342088d7ca9762a2f509b945f362a316e9412b7/pytest_benchmark-5.2.3-py3-none-any.whl", hash = "sha256:bc839726ad20e99aaa0d11a127445457b4219bdb9e80a1afc4b51da7f96b0803", size = 45255, upload-time = "2025-11-09T18:48:39.765Z" }, +] + +[[package]] +name = "pytest-codspeed" +version = "5.0.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, + { name = "rich" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e1/b4/cf932fcd1960a2fd6d9b09eb403253a8709aeee975961afa6299239a830e/pytest_codspeed-5.0.3.tar.gz", hash = "sha256:91afef90e6a96b013495e4702ef5d6358614a449e71008cdc194ef668778b92f", size = 324571, upload-time = "2026-05-22T16:20:49.231Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c2/22/456c48160b761d5028c8afa119f085a9fc42855a783a13d73918078969f0/pytest_codspeed-5.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2eeb25fb1ac3f73c4de50e739e78fea396b89782bdb740bf2a7cd2df21f8d4ee", size = 366255, upload-time = "2026-05-22T16:20:56.214Z" }, + { url = "https://files.pythonhosted.org/packages/74/33/ac7441fa937c9d9f158083a8c46920a5a5c81ed3c5f96240fc8d650db5c2/pytest_codspeed-5.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:73c5c9d98a3372a42611989ccfa437cce3842431ac6d6b9ab42c4f0e59c070f7", size = 932325, upload-time = "2026-05-22T16:21:08.814Z" }, + { url = "https://files.pythonhosted.org/packages/77/bc/8b994adcb9e9016e7d9a808056a3dd9cca21441e432ef456eae2b697d7fe/pytest_codspeed-5.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a2e0ab65df73e837666d12357280ca50ff6d6ac03ea5266703be518b68170edf", size = 934885, upload-time = "2026-05-22T16:21:01.444Z" }, + { url = "https://files.pythonhosted.org/packages/dc/8e/e032451e9e0a06b0c4bff53105f62b693d9a54595dd8c024693741ce3380/pytest_codspeed-5.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:6524c57fec279a22ffef6112af404036afc71b4704758ae9f0abda429b8478d4", size = 366253, upload-time = "2026-05-22T16:20:46.192Z" }, + { url = "https://files.pythonhosted.org/packages/a9/7b/ae76fd8ac656b9695806a6aafd5f22ec32e6ce20e266a58f9112e01d3cd8/pytest_codspeed-5.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0c383c9121deb58a69f174188e9e4488ffc0daced0ed276abf87747182511901", size = 932360, upload-time = "2026-05-22T16:20:30.589Z" }, + { url = "https://files.pythonhosted.org/packages/a6/4a/dfd43d943fdb143be4fd62f34c2793ba349dc27aa188e521d19d629aa7ab/pytest_codspeed-5.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a4bcdb4b6522738152885ef067e0c8524d5699828d780fb6f464cdb3db44369c", size = 934928, upload-time = "2026-05-22T16:20:38.62Z" }, + { url = "https://files.pythonhosted.org/packages/04/6a/fdcec19c7f267c195f147c51d3fd2245f6b8d09b80495ed0a90c008e0842/pytest_codspeed-5.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:25464363c7f9b9bd5022e969c0addba616fa40ac9b8f0fc9e030c4538863b32d", size = 366259, upload-time = "2026-05-22T16:21:06.039Z" }, + { url = "https://files.pythonhosted.org/packages/6a/96/c6b03b81dcd21ae3d6b32cca0b3c10149fa378eb21b338d4b63c9eb8050b/pytest_codspeed-5.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:efd43f82ea03ced8488a767ded9473f050791ab7783ea8654107e1e0ac66af40", size = 932395, upload-time = "2026-05-22T16:21:04.804Z" }, + { url = "https://files.pythonhosted.org/packages/96/08/56ad8f1cc7d6962f8a680141b361e93467a2abc53d976cd9d5e1edd740e3/pytest_codspeed-5.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:782f9985b6f6b45b8bc20152d206d3a52b56dd088ba81cb70a71f0b39841be9e", size = 934994, upload-time = "2026-05-22T16:20:28.809Z" }, + { url = "https://files.pythonhosted.org/packages/0b/54/9096c4545f09da94b1b00f3be2fe4952949e86c9bcafca9a29b26aed1a75/pytest_codspeed-5.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:9aa0815b90196f3c20d736ea8691381e97f12bbe8c7d87af10a351e434b452cb", size = 366311, upload-time = "2026-05-22T16:20:41.791Z" }, + { url = "https://files.pythonhosted.org/packages/a7/3c/24c53f67a38ad48cb087105ac30a8aa0923223ee274ea9bf2dc705edaa59/pytest_codspeed-5.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:85505c96a3477c346ec2d2b7dced8478f4c651e2b1666ee102d53a832b511853", size = 933169, upload-time = "2026-05-22T16:20:43.178Z" }, + { url = "https://files.pythonhosted.org/packages/d1/de/2213f868fa7694f743f96cccbc07e757f45c920c523cccc2da97bc8652df/pytest_codspeed-5.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:20eba63765be9d1b6cacbbfad84b87d49eb04b357a7045a0899880da181f81e3", size = 935522, upload-time = "2026-05-22T16:21:03.398Z" }, + { url = "https://files.pythonhosted.org/packages/df/85/5dfea1c031d6cccc11653464828edf205c30f798caf5b2a85375aacd914a/pytest_codspeed-5.0.3-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:ec9fa6f0af0a9feb0e0bd517fb59ef28f806fbd50c0c6900ac26cbb4d080eba5", size = 366275, upload-time = "2026-05-22T16:20:59.463Z" }, + { url = "https://files.pythonhosted.org/packages/3c/2b/af4d1b612f03b98a6cf3c7d5f62678917a60110a8bf380d49ab408b31137/pytest_codspeed-5.0.3-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8df77b3409f54f4a268f77f3ff74992fe1d995cdbaf2cecf8ad74d32db217ce7", size = 932537, upload-time = "2026-05-22T16:20:54.945Z" }, + { url = "https://files.pythonhosted.org/packages/f5/a2/c7ec45e36a61b418efb2a3cccaa67a0c2fcf1f21d5880f64c33114f0c249/pytest_codspeed-5.0.3-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a5d8695a227ea1c3a41d25db5b3fe720bf1b4808bd38862be811a4efd902c792", size = 934153, upload-time = "2026-05-22T16:21:07.494Z" }, + { url = "https://files.pythonhosted.org/packages/cf/c7/d5bada9618a0af56a5c8065fc61280849cab8e7c1e24025807a51c3157ce/pytest_codspeed-5.0.3-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:bf4cc4178cbace8f4d2bd240408276bc4da3850ac5fcb5fb5f8a74ab417615bb", size = 366339, upload-time = "2026-05-22T16:20:51.968Z" }, + { url = "https://files.pythonhosted.org/packages/a8/37/fb27aeb40a81320e7349553b877a21333c897b27c8dfe215630452908f36/pytest_codspeed-5.0.3-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:abe793da40f87295d33988673d34f06ea569848b44490b847552cd416816258a", size = 933055, upload-time = "2026-05-22T16:20:44.861Z" }, + { url = "https://files.pythonhosted.org/packages/f3/d9/6f2d69e96deaf0475a695fc9195af59e7a3b5fab50782855e65c63a7bc28/pytest_codspeed-5.0.3-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c3a9ed38dfa776443b86f4b49a982e8443d0953db4974bd2673d63cc904ae1ad", size = 934481, upload-time = "2026-05-22T16:20:58.264Z" }, + { url = "https://files.pythonhosted.org/packages/c5/b2/1d2a993c532146dce9eca5b5942d51898021c3579ce18b2454f932a915f8/pytest_codspeed-5.0.3-py3-none-any.whl", hash = "sha256:fe2ea83c924c2250675b75686c3ee456b8cf0208d83d552e182a195fdf467378", size = 74033, upload-time = "2026-05-22T16:20:26.814Z" }, +] + +[[package]] +name = "pytest-cov" +version = "7.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "coverage" }, + { name = "pluggy" }, + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/51/a849f96e117386044471c8ec2bd6cfebacda285da9525c9106aeb28da671/pytest_cov-7.1.0.tar.gz", hash = "sha256:30674f2b5f6351aa09702a9c8c364f6a01c27aae0c1366ae8016160d1efc56b2", size = 55592, upload-time = "2026-03-21T20:11:16.284Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" }, +] + +[[package]] +name = "pytest-reportlog" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/93/d5/2f4a73822efaad1d6aea6660468d6290963e5f61d2f9d9ca707f7f0b1c13/pytest_reportlog-1.0.0.tar.gz", hash = "sha256:75aec3a92bb53456c3e028605a636579d26f31c6f1e035ad9f706c203cfcb74e", size = 5646, upload-time = "2025-11-11T16:05:15.98Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/05/70/807cbdac584629623c1c2f76b7a39a343e3989510cd52385f1f40581e963/pytest_reportlog-1.0.0-py3-none-any.whl", hash = "sha256:3fc837ef3be6e50f33b52aaf99f88bfbb2ec525febbc3990389d24bbfba28753", size = 6015, upload-time = "2025-11-11T16:05:14.585Z" }, +] + +[[package]] +name = "pytest-xdist" +version = "3.8.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "execnet" }, + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/78/b4/439b179d1ff526791eb921115fca8e44e596a13efeda518b9d845a619450/pytest_xdist-3.8.0.tar.gz", hash = "sha256:7e578125ec9bc6050861aa93f2d59f1d8d085595d6551c2c90b6f4fad8d3a9f1", size = 88069, upload-time = "2025-07-01T13:30:59.346Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ca/31/d4e37e9e550c2b92a9cbc2e4d0b7420a27224968580b5a447f420847c975/pytest_xdist-3.8.0-py3-none-any.whl", hash = "sha256:202ca578cfeb7370784a8c33d6d05bc6e13b4f25b5053c30a152269fd10f0b88", size = 46396, upload-time = "2025-07-01T13:30:56.632Z" }, +] + +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, +] + +[[package]] +name = "python-dotenv" +version = "1.2.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/82/ed/0301aeeac3e5353ef3d94b6ec08bbcabd04a72018415dcb29e588514bba8/python_dotenv-1.2.2.tar.gz", hash = "sha256:2c371a91fbd7ba082c2c1dc1f8bf89ca22564a087c2c287cd9b662adde799cf3", size = 50135, upload-time = "2026-03-01T16:00:26.196Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/d7/1959b9648791274998a9c3526f6d0ec8fd2233e4d4acce81bbae76b44b2a/python_dotenv-1.2.2-py3-none-any.whl", hash = "sha256:1d8214789a24de455a8b8bd8ae6fe3c6b69a5e3d64aa8a8e5d68e694bbcb285a", size = 22101, upload-time = "2026-03-01T16:00:25.09Z" }, +] + +[[package]] +name = "pywin32" +version = "311" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/ab/01ea1943d4eba0f850c3c61e78e8dd59757ff815ff3ccd0a84de5f541f42/pywin32-311-cp312-cp312-win32.whl", hash = "sha256:750ec6e621af2b948540032557b10a2d43b0cee2ae9758c54154d711cc852d31", size = 8706543, upload-time = "2025-07-14T20:13:20.765Z" }, + { url = "https://files.pythonhosted.org/packages/d1/a8/a0e8d07d4d051ec7502cd58b291ec98dcc0c3fff027caad0470b72cfcc2f/pywin32-311-cp312-cp312-win_amd64.whl", hash = "sha256:b8c095edad5c211ff31c05223658e71bf7116daa0ecf3ad85f3201ea3190d067", size = 9495040, upload-time = "2025-07-14T20:13:22.543Z" }, + { url = "https://files.pythonhosted.org/packages/ba/3a/2ae996277b4b50f17d61f0603efd8253cb2d79cc7ae159468007b586396d/pywin32-311-cp312-cp312-win_arm64.whl", hash = "sha256:e286f46a9a39c4a18b319c28f59b61de793654af2f395c102b4f819e584b5852", size = 8710102, upload-time = "2025-07-14T20:13:24.682Z" }, + { url = "https://files.pythonhosted.org/packages/a5/be/3fd5de0979fcb3994bfee0d65ed8ca9506a8a1260651b86174f6a86f52b3/pywin32-311-cp313-cp313-win32.whl", hash = "sha256:f95ba5a847cba10dd8c4d8fefa9f2a6cf283b8b88ed6178fa8a6c1ab16054d0d", size = 8705700, upload-time = "2025-07-14T20:13:26.471Z" }, + { url = "https://files.pythonhosted.org/packages/e3/28/e0a1909523c6890208295a29e05c2adb2126364e289826c0a8bc7297bd5c/pywin32-311-cp313-cp313-win_amd64.whl", hash = "sha256:718a38f7e5b058e76aee1c56ddd06908116d35147e133427e59a3983f703a20d", size = 9494700, upload-time = "2025-07-14T20:13:28.243Z" }, + { url = "https://files.pythonhosted.org/packages/04/bf/90339ac0f55726dce7d794e6d79a18a91265bdf3aa70b6b9ca52f35e022a/pywin32-311-cp313-cp313-win_arm64.whl", hash = "sha256:7b4075d959648406202d92a2310cb990fea19b535c7f4a78d3f5e10b926eeb8a", size = 8709318, upload-time = "2025-07-14T20:13:30.348Z" }, + { url = "https://files.pythonhosted.org/packages/c9/31/097f2e132c4f16d99a22bfb777e0fd88bd8e1c634304e102f313af69ace5/pywin32-311-cp314-cp314-win32.whl", hash = "sha256:b7a2c10b93f8986666d0c803ee19b5990885872a7de910fc460f9b0c2fbf92ee", size = 8840714, upload-time = "2025-07-14T20:13:32.449Z" }, + { url = "https://files.pythonhosted.org/packages/90/4b/07c77d8ba0e01349358082713400435347df8426208171ce297da32c313d/pywin32-311-cp314-cp314-win_amd64.whl", hash = "sha256:3aca44c046bd2ed8c90de9cb8427f581c479e594e99b5c0bb19b29c10fd6cb87", size = 9656800, upload-time = "2025-07-14T20:13:34.312Z" }, + { url = "https://files.pythonhosted.org/packages/c0/d2/21af5c535501a7233e734b8af901574572da66fcc254cb35d0609c9080dd/pywin32-311-cp314-cp314-win_arm64.whl", hash = "sha256:a508e2d9025764a8270f93111a970e1d0fbfc33f4153b388bb649b7eec4f9b42", size = 8932540, upload-time = "2025-07-14T20:13:36.379Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/33/422b98d2195232ca1826284a76852ad5a86fe23e31b009c9886b2d0fb8b2/pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196", size = 182063, upload-time = "2025-09-25T21:32:11.445Z" }, + { url = "https://files.pythonhosted.org/packages/89/a0/6cf41a19a1f2f3feab0e9c0b74134aa2ce6849093d5517a0c550fe37a648/pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0", size = 173973, upload-time = "2025-09-25T21:32:12.492Z" }, + { url = "https://files.pythonhosted.org/packages/ed/23/7a778b6bd0b9a8039df8b1b1d80e2e2ad78aa04171592c8a5c43a56a6af4/pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", size = 775116, upload-time = "2025-09-25T21:32:13.652Z" }, + { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011, upload-time = "2025-09-25T21:32:15.21Z" }, + { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870, upload-time = "2025-09-25T21:32:16.431Z" }, + { url = "https://files.pythonhosted.org/packages/05/c0/b3be26a015601b822b97d9149ff8cb5ead58c66f981e04fedf4e762f4bd4/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", size = 761089, upload-time = "2025-09-25T21:32:17.56Z" }, + { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181, upload-time = "2025-09-25T21:32:18.834Z" }, + { url = "https://files.pythonhosted.org/packages/74/93/7baea19427dcfbe1e5a372d81473250b379f04b1bd3c4c5ff825e2327202/pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5", size = 137658, upload-time = "2025-09-25T21:32:20.209Z" }, + { url = "https://files.pythonhosted.org/packages/86/bf/899e81e4cce32febab4fb42bb97dcdf66bc135272882d1987881a4b519e9/pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b", size = 154003, upload-time = "2025-09-25T21:32:21.167Z" }, + { url = "https://files.pythonhosted.org/packages/1a/08/67bd04656199bbb51dbed1439b7f27601dfb576fb864099c7ef0c3e55531/pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", size = 140344, upload-time = "2025-09-25T21:32:22.617Z" }, + { url = "https://files.pythonhosted.org/packages/d1/11/0fd08f8192109f7169db964b5707a2f1e8b745d4e239b784a5a1dd80d1db/pyyaml-6.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8", size = 181669, upload-time = "2025-09-25T21:32:23.673Z" }, + { url = "https://files.pythonhosted.org/packages/b1/16/95309993f1d3748cd644e02e38b75d50cbc0d9561d21f390a76242ce073f/pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1", size = 173252, upload-time = "2025-09-25T21:32:25.149Z" }, + { url = "https://files.pythonhosted.org/packages/50/31/b20f376d3f810b9b2371e72ef5adb33879b25edb7a6d072cb7ca0c486398/pyyaml-6.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c", size = 767081, upload-time = "2025-09-25T21:32:26.575Z" }, + { url = "https://files.pythonhosted.org/packages/49/1e/a55ca81e949270d5d4432fbbd19dfea5321eda7c41a849d443dc92fd1ff7/pyyaml-6.0.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5", size = 841159, upload-time = "2025-09-25T21:32:27.727Z" }, + { url = "https://files.pythonhosted.org/packages/74/27/e5b8f34d02d9995b80abcef563ea1f8b56d20134d8f4e5e81733b1feceb2/pyyaml-6.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6", size = 801626, upload-time = "2025-09-25T21:32:28.878Z" }, + { url = "https://files.pythonhosted.org/packages/f9/11/ba845c23988798f40e52ba45f34849aa8a1f2d4af4b798588010792ebad6/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6", size = 753613, upload-time = "2025-09-25T21:32:30.178Z" }, + { url = "https://files.pythonhosted.org/packages/3d/e0/7966e1a7bfc0a45bf0a7fb6b98ea03fc9b8d84fa7f2229e9659680b69ee3/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be", size = 794115, upload-time = "2025-09-25T21:32:31.353Z" }, + { url = "https://files.pythonhosted.org/packages/de/94/980b50a6531b3019e45ddeada0626d45fa85cbe22300844a7983285bed3b/pyyaml-6.0.3-cp313-cp313-win32.whl", hash = "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26", size = 137427, upload-time = "2025-09-25T21:32:32.58Z" }, + { url = "https://files.pythonhosted.org/packages/97/c9/39d5b874e8b28845e4ec2202b5da735d0199dbe5b8fb85f91398814a9a46/pyyaml-6.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c", size = 154090, upload-time = "2025-09-25T21:32:33.659Z" }, + { url = "https://files.pythonhosted.org/packages/73/e8/2bdf3ca2090f68bb3d75b44da7bbc71843b19c9f2b9cb9b0f4ab7a5a4329/pyyaml-6.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb", size = 140246, upload-time = "2025-09-25T21:32:34.663Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8c/f4bd7f6465179953d3ac9bc44ac1a8a3e6122cf8ada906b4f96c60172d43/pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac", size = 181814, upload-time = "2025-09-25T21:32:35.712Z" }, + { url = "https://files.pythonhosted.org/packages/bd/9c/4d95bb87eb2063d20db7b60faa3840c1b18025517ae857371c4dd55a6b3a/pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310", size = 173809, upload-time = "2025-09-25T21:32:36.789Z" }, + { url = "https://files.pythonhosted.org/packages/92/b5/47e807c2623074914e29dabd16cbbdd4bf5e9b2db9f8090fa64411fc5382/pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7", size = 766454, upload-time = "2025-09-25T21:32:37.966Z" }, + { url = "https://files.pythonhosted.org/packages/02/9e/e5e9b168be58564121efb3de6859c452fccde0ab093d8438905899a3a483/pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788", size = 836355, upload-time = "2025-09-25T21:32:39.178Z" }, + { url = "https://files.pythonhosted.org/packages/88/f9/16491d7ed2a919954993e48aa941b200f38040928474c9e85ea9e64222c3/pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5", size = 794175, upload-time = "2025-09-25T21:32:40.865Z" }, + { url = "https://files.pythonhosted.org/packages/dd/3f/5989debef34dc6397317802b527dbbafb2b4760878a53d4166579111411e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764", size = 755228, upload-time = "2025-09-25T21:32:42.084Z" }, + { url = "https://files.pythonhosted.org/packages/d7/ce/af88a49043cd2e265be63d083fc75b27b6ed062f5f9fd6cdc223ad62f03e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35", size = 789194, upload-time = "2025-09-25T21:32:43.362Z" }, + { url = "https://files.pythonhosted.org/packages/23/20/bb6982b26a40bb43951265ba29d4c246ef0ff59c9fdcdf0ed04e0687de4d/pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac", size = 156429, upload-time = "2025-09-25T21:32:57.844Z" }, + { url = "https://files.pythonhosted.org/packages/f4/f4/a4541072bb9422c8a883ab55255f918fa378ecf083f5b85e87fc2b4eda1b/pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3", size = 143912, upload-time = "2025-09-25T21:32:59.247Z" }, + { url = "https://files.pythonhosted.org/packages/7c/f9/07dd09ae774e4616edf6cda684ee78f97777bdd15847253637a6f052a62f/pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3", size = 189108, upload-time = "2025-09-25T21:32:44.377Z" }, + { url = "https://files.pythonhosted.org/packages/4e/78/8d08c9fb7ce09ad8c38ad533c1191cf27f7ae1effe5bb9400a46d9437fcf/pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba", size = 183641, upload-time = "2025-09-25T21:32:45.407Z" }, + { url = "https://files.pythonhosted.org/packages/7b/5b/3babb19104a46945cf816d047db2788bcaf8c94527a805610b0289a01c6b/pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c", size = 831901, upload-time = "2025-09-25T21:32:48.83Z" }, + { url = "https://files.pythonhosted.org/packages/8b/cc/dff0684d8dc44da4d22a13f35f073d558c268780ce3c6ba1b87055bb0b87/pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702", size = 861132, upload-time = "2025-09-25T21:32:50.149Z" }, + { url = "https://files.pythonhosted.org/packages/b1/5e/f77dc6b9036943e285ba76b49e118d9ea929885becb0a29ba8a7c75e29fe/pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c", size = 839261, upload-time = "2025-09-25T21:32:51.808Z" }, + { url = "https://files.pythonhosted.org/packages/ce/88/a9db1376aa2a228197c58b37302f284b5617f56a5d959fd1763fb1675ce6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065", size = 805272, upload-time = "2025-09-25T21:32:52.941Z" }, + { url = "https://files.pythonhosted.org/packages/da/92/1446574745d74df0c92e6aa4a7b0b3130706a4142b2d1a5869f2eaa423c6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65", size = 829923, upload-time = "2025-09-25T21:32:54.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/7a/1c7270340330e575b92f397352af856a8c06f230aa3e76f86b39d01b416a/pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9", size = 174062, upload-time = "2025-09-25T21:32:55.767Z" }, + { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" }, +] + +[[package]] +name = "pyyaml-env-tag" +version = "1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/eb/2e/79c822141bfd05a853236b504869ebc6b70159afc570e1d5a20641782eaa/pyyaml_env_tag-1.1.tar.gz", hash = "sha256:2eb38b75a2d21ee0475d6d97ec19c63287a7e140231e4214969d0eac923cd7ff", size = 5737, upload-time = "2025-05-13T15:24:01.64Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/11/432f32f8097b03e3cd5fe57e88efb685d964e2e5178a48ed61e841f7fdce/pyyaml_env_tag-1.1-py3-none-any.whl", hash = "sha256:17109e1a528561e32f026364712fee1264bc2ea6715120891174ed1b980d2e04", size = 4722, upload-time = "2025-05-13T15:23:59.629Z" }, +] + +[[package]] +name = "referencing" +version = "0.37.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "rpds-py" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/22/f5/df4e9027acead3ecc63e50fe1e36aca1523e1719559c499951bb4b53188f/referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8", size = 78036, upload-time = "2025-10-13T15:30:48.871Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231", size = 26766, upload-time = "2025-10-13T15:30:47.625Z" }, +] + +[[package]] +name = "regex" +version = "2026.5.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/dc/0e/49aee608ad09480e7fd276898c99ec6192985fa331abe4eb3a986094490b/regex-2026.5.9.tar.gz", hash = "sha256:a8234aa23ec39894bfe4a3f1b85616a7032481964a13ac6fc9f10de4f6fca270", size = 416074, upload-time = "2026-05-09T23:15:19.37Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/50/9b/6550044bc44e17c84d312c031c2ec42fbdb6a4ec4e29093be3a172d08772/regex-2026.5.9-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:57eeeb05db7979413dec5438f2db21d7ecbba787cde7a711df1a6f6df672aa06", size = 490451, upload-time = "2026-05-09T23:12:34.72Z" }, + { url = "https://files.pythonhosted.org/packages/1e/95/fc7ba4303b5a0f92446a12ee6778ef2c6c799233f5060042a31bf390cfe9/regex-2026.5.9-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:398c521292f4c7fb807001dcd54694d3a1fcafc179a36ad9cc56f98df85930b6", size = 292112, upload-time = "2026-05-09T23:12:36.285Z" }, + { url = "https://files.pythonhosted.org/packages/54/4b/ee27938d1b2c443e89a9a10e00d2d19aa5ee300cd3d61140644e93bb083e/regex-2026.5.9-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f7a7c26137296beba7784de6eba69c6a93a63ccebc385e4962fe67e267a91225", size = 289599, upload-time = "2026-05-09T23:12:38.089Z" }, + { url = "https://files.pythonhosted.org/packages/d8/dd/ba103dc19614e25f3880800ca67ce093d6e21b325d72b8383c7bf906e9fa/regex-2026.5.9-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6441cc660d76107934a09c22167200839a0e89604a6297f78a974e66e931d2c0", size = 796732, upload-time = "2026-05-09T23:12:40.062Z" }, + { url = "https://files.pythonhosted.org/packages/cf/e7/f035b4fd858b050b0080bf302968dc0f59ba34e391872d54936758e6844e/regex-2026.5.9-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:91328f1c23d47595ca3ef0a7557fa129c5a23404b775c770697d2f35b33e0107", size = 865440, upload-time = "2026-05-09T23:12:42.059Z" }, + { url = "https://files.pythonhosted.org/packages/0a/51/8cd301ecc899aea28124357f729f4272f44de7806fc7ca02490bfbe253e8/regex-2026.5.9-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:93a7860539414dddaefba2b40f8771765ae17949d4c7182b876ce429e11a8309", size = 912329, upload-time = "2026-05-09T23:12:44.373Z" }, + { url = "https://files.pythonhosted.org/packages/cc/1e/3fbe2fa1e8cebd62f3bb7d3321cff1640aca2e240b51d9bd624aad949260/regex-2026.5.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:dd2810d22146b6d838acc5ec15602cb6b47920aa4e33015df3868eedfd20bab8", size = 801239, upload-time = "2026-05-09T23:12:46.268Z" }, + { url = "https://files.pythonhosted.org/packages/17/2f/6f6008682bf2cf98040a0d3153a8e557b6ab728d7713d045cee4ce544ab8/regex-2026.5.9-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:daff2bdbaf1d23e52fdff7c0b7bc2048b68f978df6a4d107ac981f94caef2e66", size = 777054, upload-time = "2026-05-09T23:12:48.051Z" }, + { url = "https://files.pythonhosted.org/packages/19/2b/eee0d20a6842ba04df4b8847a920b57ef56853f14ef85405473e586b605a/regex-2026.5.9-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4eeb011098fcb77af513dcef521a3dbecbf8849b1e38940759d293b7a93f5026", size = 785098, upload-time = "2026-05-09T23:12:49.851Z" }, + { url = "https://files.pythonhosted.org/packages/4a/98/6fc1e6410feefb92159edaed5041992bfe390e8d26c721865434acbca558/regex-2026.5.9-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:ea9c8ecfa1b73c73b626534d6626e5340d429630943672b8480724f44e84b962", size = 860095, upload-time = "2026-05-09T23:12:51.666Z" }, + { url = "https://files.pythonhosted.org/packages/18/a3/bd855e0f2cb1a978ecf6fa6bb69632dd9c3f6ea3b81cde62fde14c9daec7/regex-2026.5.9-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:cd2846168eb9ee3c513902bc8225409cb1caab31d04728b145171fa1625d9621", size = 765762, upload-time = "2026-05-09T23:12:53.413Z" }, + { url = "https://files.pythonhosted.org/packages/dc/66/0ae8c092e60b14c79d24f8e0b7f0aea5bfbffdcab00b5483d13404d3c3a5/regex-2026.5.9-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:39617fb0cde9c0e6306dc70e3bfc096f3da793219879f7ae7aa341a69fbdcf6d", size = 852100, upload-time = "2026-05-09T23:12:55.256Z" }, + { url = "https://files.pythonhosted.org/packages/21/de/8dfde60fc1b21c946a893ba273403b72617edb261370cb1087099a83f088/regex-2026.5.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fd03c4f0e33280d15cae17159b899245d6b7c53d21def19b263b39655061f5ce", size = 789479, upload-time = "2026-05-09T23:12:57.573Z" }, + { url = "https://files.pythonhosted.org/packages/c3/1c/bdcc98f9a4af4fdd166c74941174619ccff4726d3ce32faa8e9a2ecd38dd/regex-2026.5.9-cp312-cp312-win32.whl", hash = "sha256:164eba9b755ea6f244b0d881196fbc1fac09714e9782c9e2732b813142033c8e", size = 266699, upload-time = "2026-05-09T23:12:59.14Z" }, + { url = "https://files.pythonhosted.org/packages/78/87/240d36864f9e48ace85f72e79ced97ceb7f27ce87739a947dcb834b4e6bc/regex-2026.5.9-cp312-cp312-win_amd64.whl", hash = "sha256:86f40a5d6444db30a125c9c9177e6b25dad981cbc37451fd838f145e6edac92e", size = 277783, upload-time = "2026-05-09T23:13:00.789Z" }, + { url = "https://files.pythonhosted.org/packages/4f/b5/7b30f312b0669dff5beebe5b0989dc2d1a312b1a44fab852199c387a5b96/regex-2026.5.9-cp312-cp312-win_arm64.whl", hash = "sha256:96f5f58b54a063d7ea9dca08e1cf57bfe10499c4d579ee672da284f57f5f0070", size = 270513, upload-time = "2026-05-09T23:13:02.426Z" }, + { url = "https://files.pythonhosted.org/packages/aa/da/797e91ecec6f84135da778ddce78c20e0af5d2a15c26f87a81bc3eadb6db/regex-2026.5.9-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:d626b84406444b165fc0ba981604edea39f0588ff1f92baa23fe50799ea9afdb", size = 490303, upload-time = "2026-05-09T23:13:04.382Z" }, + { url = "https://files.pythonhosted.org/packages/44/da/bf30abaaa737b58f4a4b8c4a03659e02fd92092c822e0197ed9e0daab917/regex-2026.5.9-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:d7bdc0ab8f3dd7e1b4f9ab88634e13374669db86bb3c72e8292f07ae313f539f", size = 292019, upload-time = "2026-05-09T23:13:06.022Z" }, + { url = "https://files.pythonhosted.org/packages/2d/e7/d0eaf5713828417b9e5648cf81fa9bacd4961f6ab98c380c2034f8716e35/regex-2026.5.9-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a8820737949116ffff55fe18f9fc644530063ba6ebfcb8314239416e78f1347c", size = 289468, upload-time = "2026-05-09T23:13:08.214Z" }, + { url = "https://files.pythonhosted.org/packages/d3/9b/b3fdd62b003baa1a9b593cd8c8699c9651c2e80cc21a5c715707983c42d7/regex-2026.5.9-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:aa0fbdbac82cb3e4450d0ccde7d7a35607f4cb2dd9fba4b8b69bfaf8c9fa6aed", size = 796749, upload-time = "2026-05-09T23:13:10.573Z" }, + { url = "https://files.pythonhosted.org/packages/d4/30/66ab84588765f5b4b271a9ca09ef7ce2b87caa95176ec3d2ad65d7bc4902/regex-2026.5.9-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:57e8915c7986aa33d25e4d3629cef711cd2863f2961b10409f0c04cb8b7d9020", size = 865445, upload-time = "2026-05-09T23:13:12.523Z" }, + { url = "https://files.pythonhosted.org/packages/1a/89/f05169e8588aac365f35ffc7f3bc3184f095ef4cfded7cfaa3c7fd5dbd89/regex-2026.5.9-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:508f56a89ba9cb26e4168cbc37dbd60a28d82430a9e18ad1d25fe0883c314ca2", size = 912322, upload-time = "2026-05-09T23:13:14.281Z" }, + { url = "https://files.pythonhosted.org/packages/30/e1/c93444052cf41581f3c884ab3fb5823daf0992f11cd4388d4275ca610558/regex-2026.5.9-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b6d189041f15691cfa2b6c4290448ec221244d225b3f5fe9e7771b34ffcdf6e2", size = 801269, upload-time = "2026-05-09T23:13:16.569Z" }, + { url = "https://files.pythonhosted.org/packages/50/fe/0cf96b882f540e62e8b9956599798203d599c44cf4c77917ca27400ff69b/regex-2026.5.9-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e82db382b44d0111b22601c509c89f64434816c9e0eef9d1989cda8cc6ff1c04", size = 777085, upload-time = "2026-05-09T23:13:18.675Z" }, + { url = "https://files.pythonhosted.org/packages/23/5c/d78d4924e7fc875557b9e9b768423925fdfaac5549d06da7810019a9bd26/regex-2026.5.9-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:2acfb48634f64996b57f90f39afa692ff362162722581921fe92239a59960f3c", size = 785153, upload-time = "2026-05-09T23:13:20.525Z" }, + { url = "https://files.pythonhosted.org/packages/bf/e0/5214774090e7b4524dcea3e3c4aa74141d43043f8beb49c1599db1c8b53a/regex-2026.5.9-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:d29eebfc9525db68cad3c97eedd7f754fa265aa5cd0cf4f863b2421e1b48fc9f", size = 860164, upload-time = "2026-05-09T23:13:22.263Z" }, + { url = "https://files.pythonhosted.org/packages/6e/e1/4a57a83350319b1271f0d7a249b8672513ed928b237a741631270de6caea/regex-2026.5.9-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:debb893095e944091c16e641a6e33c1b0f4cb61ab945ec5afbf53ce7068834d8", size = 765731, upload-time = "2026-05-09T23:13:24.277Z" }, + { url = "https://files.pythonhosted.org/packages/12/f4/499e74a20c156fc75836ee04a72a38d1a063978f600937f9760467beb1b0/regex-2026.5.9-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:d659eee77986549c9ea45b861c7567e44d6287c3dc9a4565478853f7b9fe2ff6", size = 852062, upload-time = "2026-05-09T23:13:26.125Z" }, + { url = "https://files.pythonhosted.org/packages/5b/92/7eebc0d0a01e78629695f342ba17e0deaff8fb45e79cc0d7b98287da6e3e/regex-2026.5.9-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:2efa205e6d98b24d1f3ab395c11aa15cdf10935bca283d0285e0499c284fba21", size = 789577, upload-time = "2026-05-09T23:13:27.814Z" }, + { url = "https://files.pythonhosted.org/packages/05/a4/018e71f7d2ad48c1ebe6d3ae0026f9b7cb4802fd15c7cc02fdf724355102/regex-2026.5.9-cp313-cp313-win32.whl", hash = "sha256:f3844f134e834076677dd369976e9f5068679fcb8e50102fdf6b7ac96a3ec127", size = 266691, upload-time = "2026-05-09T23:13:29.549Z" }, + { url = "https://files.pythonhosted.org/packages/e6/1d/861a93719fb9ee7dbfc3761b3797b7a3e112a5d42c6129459d2d741be9b5/regex-2026.5.9-cp313-cp313-win_amd64.whl", hash = "sha256:3527bb4942d2c14552155406cdedd906567456821848aed1cb4933a391bf5eca", size = 277747, upload-time = "2026-05-09T23:13:31.859Z" }, + { url = "https://files.pythonhosted.org/packages/d9/c6/0a2436ae4da1ba76e51cb98943c6838a9a721faa40ebe2dce07694ae34e3/regex-2026.5.9-cp313-cp313-win_arm64.whl", hash = "sha256:56a33f191f17d8c417f99945ebdc1e691d3af9605d86ec68c7e54a57e3e17af6", size = 270500, upload-time = "2026-05-09T23:13:33.525Z" }, + { url = "https://files.pythonhosted.org/packages/e8/e9/d21346f7b60ed58789371358ed66b09d00f832e1bd7c06e55d9da5679882/regex-2026.5.9-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:01f28d868834624c934b8d2e0aa1c8341337e37831f4a012f18a5afcba4cbaf3", size = 494172, upload-time = "2026-05-09T23:13:35.935Z" }, + { url = "https://files.pythonhosted.org/packages/c4/43/fd1177a2032037c681baecdb3422ee4e1424aec4e4f470ef47793d325274/regex-2026.5.9-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:48036f6374aaa79eb3b754ec29c61d1c6b1606749d705a13f8854fa2539671f6", size = 293952, upload-time = "2026-05-09T23:13:38.307Z" }, + { url = "https://files.pythonhosted.org/packages/f2/7d/9fbf919768368d3f8a4f6c692cf2aa61e482b2b81ec6a298ace4cbf02480/regex-2026.5.9-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:b96350aa424e79d4fd6b567b344dcbe2b2d6bfc48dfe7717587e1fa6d43da6ff", size = 292314, upload-time = "2026-05-09T23:13:40.353Z" }, + { url = "https://files.pythonhosted.org/packages/e2/6c/e41bfeecb589716843e7c4df09ba46ff2a42961457afece19059d85caeef/regex-2026.5.9-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8f3af7a4903c5c04a11a196a5aa75cdd7dd3f8508132f9fb3259d9f5908e3b88", size = 811681, upload-time = "2026-05-09T23:13:42.543Z" }, + { url = "https://files.pythonhosted.org/packages/87/83/a5c1c525fba0aa656e88ad0face0b1829788ef4c2fb6b26df58aa1151b84/regex-2026.5.9-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7e87577720152d2caae19fe2baaf1f8d5ca12091e9e229f03915c37d1e4b9178", size = 871135, upload-time = "2026-05-09T23:13:44.326Z" }, + { url = "https://files.pythonhosted.org/packages/18/d4/80882e799e440dd878b0979cbebf8fa4d54624a332c83037c7a701649e3f/regex-2026.5.9-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c8b9b9d294cfea3cd19c718ade7cc93492b2c4991abd9a68d0b3477ae6d8e100", size = 917265, upload-time = "2026-05-09T23:13:47.295Z" }, + { url = "https://files.pythonhosted.org/packages/ae/ff/8db60211e2286e396aad7dc7725356c502bff0901ea05bd6cdc2e1a042b9/regex-2026.5.9-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:728d8bfd28a8845c8b6bc5dc7ce010453d206396786c0765c2740cb65f37791e", size = 816311, upload-time = "2026-05-09T23:13:49.885Z" }, + { url = "https://files.pythonhosted.org/packages/4c/47/742ef579c61730f8d268e5cf1f9ce0e37e2ea041ad0f5644724f2378e463/regex-2026.5.9-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7e30b874d341fac767d7df5a0870540541c2c054b80cfaac116e8d367a8a7ff2", size = 785498, upload-time = "2026-05-09T23:13:52.25Z" }, + { url = "https://files.pythonhosted.org/packages/7f/ab/cb0999802dcb0fb95b1ab005e8d4163d8afdd67efc2cb6b6630ac13f8cb1/regex-2026.5.9-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:fd190e88a895a8901325fad284a3f74ea52b1da8525b76cc811fa9b1edf0ce2b", size = 801348, upload-time = "2026-05-09T23:13:54.127Z" }, + { url = "https://files.pythonhosted.org/packages/7d/62/8ca59a24c55bc34d166eefaf3717bd77772f329fdbf984d86581e0a3571c/regex-2026.5.9-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:8e76e8161ad00694cfce6767d5dea860c6391ac5b83e5c3a39661e696f11fc7e", size = 866493, upload-time = "2026-05-09T23:13:56.067Z" }, + { url = "https://files.pythonhosted.org/packages/8d/3d/30f2ae62cef3278bb5bb821f467277a55fb73f01032cf85997e15e8289a8/regex-2026.5.9-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:ddda5340e6c01a293027dd46232fa79eaff1b48058ce7a98f572b6445b088041", size = 772811, upload-time = "2026-05-09T23:13:57.867Z" }, + { url = "https://files.pythonhosted.org/packages/d8/ae/7d2089bcd78ad0c0161bc684339df50032acb438a7bd3305e7ddb1193cec/regex-2026.5.9-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:205109e96b3cf5adf8f4cd62bedde9487feb282b9497a3535451e5a24cd706a0", size = 856584, upload-time = "2026-05-09T23:13:59.679Z" }, + { url = "https://files.pythonhosted.org/packages/a9/29/92ff47f75990131ea4f24ba17819e5a9d141e10819807e09addd73409af6/regex-2026.5.9-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:dfbe4579b9f08036aa7d101d1835437a20783574ac66327e6b29b4018a138081", size = 803453, upload-time = "2026-05-09T23:14:01.978Z" }, + { url = "https://files.pythonhosted.org/packages/04/99/eff29f1037dcab36702c9ee5d6858cf1ce2336ea8ea2987f64245b99ea5e/regex-2026.5.9-cp313-cp313t-win32.whl", hash = "sha256:ed2c9e8068b614c574d8d30e543d617cf5379b0535d46f97ef00e904745a08b5", size = 269951, upload-time = "2026-05-09T23:14:03.661Z" }, + { url = "https://files.pythonhosted.org/packages/0e/9d/8870b8981d27b22cda77bb26a5ac7ebfa9c7d9e0dea195a834a82380e748/regex-2026.5.9-cp313-cp313t-win_amd64.whl", hash = "sha256:b46b0f094dc1d3b90356c85a0bd2c9bafc4a6a190b9d6f8ddd5a033b6e088ed4", size = 281240, upload-time = "2026-05-09T23:14:05.56Z" }, + { url = "https://files.pythonhosted.org/packages/72/b1/3379415e8f135c13ac551353397cc4fe97b4978f3cac73c5fcbcded548b8/regex-2026.5.9-cp313-cp313t-win_arm64.whl", hash = "sha256:872acc074bd29ffc9913ecdfedf6ea77502312ca44a4aa0d3779089c6069d8de", size = 272383, upload-time = "2026-05-09T23:14:07.843Z" }, + { url = "https://files.pythonhosted.org/packages/13/3e/9c3cd292d8808b3645a2ce517e200179b6d0e903f176300bd8b542e14de5/regex-2026.5.9-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:1bd7587a2948b4085195d5a3374eaf4a425dc3e55784c038175355ecf3bbbf8a", size = 490376, upload-time = "2026-05-09T23:14:09.64Z" }, + { url = "https://files.pythonhosted.org/packages/60/70/d43ee8a2ca0a8b68d167f21658b85520ac0574617c7f320367c5047f7556/regex-2026.5.9-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:dea2e88e1cce4522496cce630e11e67b98b7076620bc4336c3f674bc21a375f4", size = 291964, upload-time = "2026-05-09T23:14:11.424Z" }, + { url = "https://files.pythonhosted.org/packages/21/91/9d50b433828d8e74196904e168a43abf1e6e88b2a15d47ed742456720c37/regex-2026.5.9-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:2099f7e7ff7b6aa3192312650a56e91cc091e49d50b04e4f6f8b6e28b3b27f1c", size = 289682, upload-time = "2026-05-09T23:14:13.123Z" }, + { url = "https://files.pythonhosted.org/packages/3e/d2/b835e3cafbb9d977736912436259ff551d60919f7d7b3d37d46659c63564/regex-2026.5.9-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ecd353045824e4477562a2ac718c25799cdaaa41f7aa925a806a8a3e6848a5b9", size = 796996, upload-time = "2026-05-09T23:14:14.923Z" }, + { url = "https://files.pythonhosted.org/packages/2c/a6/9f992d00019166b9de01c546dd4549bc679f2a68df11b877740b0760b7c2/regex-2026.5.9-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:65c8c8c37377794bd5b2f3ebe51919042bf17aec802e23c833d89782ed0c78af", size = 866089, upload-time = "2026-05-09T23:14:17.757Z" }, + { url = "https://files.pythonhosted.org/packages/e0/08/4d32af657e049b19cb62b02e46e38fe1518797bfb2203ee93a510b21b0dc/regex-2026.5.9-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5b73ab8afcf66c622db143d1c6fda4e58e4d537ee4f125229ad47b1ab80f34c0", size = 911530, upload-time = "2026-05-09T23:14:20.353Z" }, + { url = "https://files.pythonhosted.org/packages/d9/27/2af43dd1dc201d1fecefda64a45f4ad0995855b92724f795a777b402ee69/regex-2026.5.9-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0de5cf193997384ed2ca6f1cd4f78055b255d93d82d5a8cd6ba0d11c10b167e4", size = 800643, upload-time = "2026-05-09T23:14:22.265Z" }, + { url = "https://files.pythonhosted.org/packages/a4/dd/23a249047013b5321d4a60c4d2437462086f601b061776a525e5fba2a59f/regex-2026.5.9-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d641a8c9a61618047796d572a39a79b26167b0411d2c3031937b2fe2d081e2cf", size = 777223, upload-time = "2026-05-09T23:14:24.179Z" }, + { url = "https://files.pythonhosted.org/packages/94/6a/e85ed9538cd19586d0465076a4578a12e093ce776d15f3f8ce92733a8dd6/regex-2026.5.9-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:24b2355ef5cc9aa5b8f07d17704face1c166fdcc2290fa7bd6e6c925655a8346", size = 785760, upload-time = "2026-05-09T23:14:26.065Z" }, + { url = "https://files.pythonhosted.org/packages/2a/c4/f25473209438638e947c55f9156fd8f236f74169229028cc99116380868e/regex-2026.5.9-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:a24852d3c29ad9e47593593d8a247c44ccc3d0548ef12c822d6ed0810affe676", size = 860891, upload-time = "2026-05-09T23:14:28.17Z" }, + { url = "https://files.pythonhosted.org/packages/f9/f7/f4f86e3c74419c37370e91f150ae0c2ef7d34b2e0e4cdd5da046a02e4022/regex-2026.5.9-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:916714069da19329ef7de197dcbc77bb3104145c7c2c864dbfbe318f46b88b14", size = 765891, upload-time = "2026-05-09T23:14:30.06Z" }, + { url = "https://files.pythonhosted.org/packages/26/70/704d8e13765939146b1cd0ef4e2feb71d7929727d2290f026eed10095955/regex-2026.5.9-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:fa411799ca8da32a8d38d020a88faa5b6f91657d284761352940ecf9f7c3bbdd", size = 851380, upload-time = "2026-05-09T23:14:32.123Z" }, + { url = "https://files.pythonhosted.org/packages/26/29/1a13582a8460038edc38e49f64ceb0dd7c60f5caba77571f4bf6601965d9/regex-2026.5.9-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:1e6da47d679b7010ef27556b6e0f99771b744936db1792a10ceac6547ae1503e", size = 789350, upload-time = "2026-05-09T23:14:34.799Z" }, + { url = "https://files.pythonhosted.org/packages/73/56/3dcafe34fc72e271d62ad9a291801e88a1457bb251c132f15fcc2e5aad1a/regex-2026.5.9-cp314-cp314-win32.whl", hash = "sha256:98bd73080e8756255137e1bd3f3f00295bbc5aa383c0e0f973920e9134d7c4ad", size = 272130, upload-time = "2026-05-09T23:14:36.729Z" }, + { url = "https://files.pythonhosted.org/packages/d0/9c/02eebf0be95efe416c664db7fb8b6b05b7a0b06a7544f2884f2558b0526f/regex-2026.5.9-cp314-cp314-win_amd64.whl", hash = "sha256:ff8d372ac2acdc048d1c19916f27ee61bc5722728458ba6ca5052f2c72d51763", size = 280999, upload-time = "2026-05-09T23:14:39.126Z" }, + { url = "https://files.pythonhosted.org/packages/70/5a/1dd1abee76cb7a846a0bcf42fdc87e5720c3c33c24f3e37814310a513d9f/regex-2026.5.9-cp314-cp314-win_arm64.whl", hash = "sha256:e1d93bf647916292e8edcec150c07ddf3dc50179ccaf770c04a7f9e452155372", size = 273500, upload-time = "2026-05-09T23:14:41.059Z" }, + { url = "https://files.pythonhosted.org/packages/86/c1/c5f619b0057a7965cb78ec559c1d7a45ce8c99a35bea95483d64959a93d9/regex-2026.5.9-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:83d0ee4a57d1c87cb549e195ec300b8f0ec3a82eba66d835e4e2ed8634fe4499", size = 494269, upload-time = "2026-05-09T23:14:42.869Z" }, + { url = "https://files.pythonhosted.org/packages/05/2c/5d01f1aee33de4bbe60c8452945bfc8477ca7c5ae4450f6bfe711036cb36/regex-2026.5.9-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:d3d7eb5c9a7f6df82ed3cfac9beb93882a5cbcb5b8b157b56cb2b3b276574ac1", size = 293954, upload-time = "2026-05-09T23:14:44.822Z" }, + { url = "https://files.pythonhosted.org/packages/7a/fe/e8988b2ae2108c6ef71bd4aa8d87fbe257976dd0810e826cd75f701c68b6/regex-2026.5.9-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:075160bf16658e16d35233300b8453aac25de4cbea808d22348b6979668e924d", size = 292405, upload-time = "2026-05-09T23:14:47.211Z" }, + { url = "https://files.pythonhosted.org/packages/79/34/d2b0937faa7859263f7f0a3c6b103a1296306be6952dc173d0154e9a2f49/regex-2026.5.9-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45375819235558a4ff1c4971dc32881f022613abdb180128f5cb4768c1765a1c", size = 811855, upload-time = "2026-05-09T23:14:49.21Z" }, + { url = "https://files.pythonhosted.org/packages/80/fe/daf53a47457a8486db66c66c01ceb9c2303eecee3f87197f1e77eb1a736d/regex-2026.5.9-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ead4b163ac30a29574510cd4b3e2e985ac5290c05fc7095557d6a5f403fc31b5", size = 871189, upload-time = "2026-05-09T23:14:51.555Z" }, + { url = "https://files.pythonhosted.org/packages/1c/75/058fc4470cbfbf57d800aff1a0022b929a3f9fa553ee10a0cdf2070eb31f/regex-2026.5.9-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8c6e4218fbdfbcd4f6c19efca40930d24a621bf4b48cb76bc6640543bd28ef20", size = 917485, upload-time = "2026-05-09T23:14:53.633Z" }, + { url = "https://files.pythonhosted.org/packages/88/e7/179cfda3a28bc843b5c6cfe7f79f23489c791ed95f151083803660878432/regex-2026.5.9-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6351571c8a42b505eb555c0dc47d740d0fb66977dc142919eea6f4325b7c56a0", size = 816369, upload-time = "2026-05-09T23:14:56.198Z" }, + { url = "https://files.pythonhosted.org/packages/41/90/6f0cc422071688266d344fca8462d787cba0a2c144acb25721f9a61ec265/regex-2026.5.9-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:002205cafd2a9e78c6290c7d1df277bf3277b3b7a30e0b4bb0dac2e2e3f7cb2d", size = 785869, upload-time = "2026-05-09T23:14:58.602Z" }, + { url = "https://files.pythonhosted.org/packages/02/67/a31f1760f09c27b251ef39e9beb541f462cf977381d067faa764c2c0e393/regex-2026.5.9-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8abd33fef90b2a9efac5557d6033ca82d1195ed3a15fea5af15ba7b463c6a63b", size = 801427, upload-time = "2026-05-09T23:15:00.642Z" }, + { url = "https://files.pythonhosted.org/packages/e3/c4/1a80654597b6bc1e1ea0494824c31200e8a956abe290afae9b19a166a148/regex-2026.5.9-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:31037c82eccb44b7ea2e9e221d7c01429430e989a1f4b91ea5a855f6017b509a", size = 866482, upload-time = "2026-05-09T23:15:03.384Z" }, + { url = "https://files.pythonhosted.org/packages/d1/11/960724e06482c08466ff5611e242e86f80062949cdf6b4b9cc317b9dd93d/regex-2026.5.9-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:5604dfd046dc37eca90250fc3be938b076c8059fa772ac0ed6f499b0f0fb0415", size = 773022, upload-time = "2026-05-09T23:15:05.625Z" }, + { url = "https://files.pythonhosted.org/packages/50/a8/a9979c3e7918280e93159ebcab5ef1a65116dd4f3bd6091be0eae4a126e8/regex-2026.5.9-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:0e1b1b4e496afbb24f4a62aba855ee4f88f25578927697b340702e48c9ee6bc2", size = 856642, upload-time = "2026-05-09T23:15:07.966Z" }, + { url = "https://files.pythonhosted.org/packages/fe/d4/a9b732f2f0072c0ab12227483abb24fffcb9f73f8a2b203df0a6d0434735/regex-2026.5.9-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:be3372b9df6ddecff6486d37e19095a7b4973137caf5512407a89f4455361f41", size = 803552, upload-time = "2026-05-09T23:15:10.215Z" }, + { url = "https://files.pythonhosted.org/packages/d5/fe/1b3113817447a1d4155e4ac76d2e072f42c0bcba2f43fa8a0e756ea2cd91/regex-2026.5.9-cp314-cp314t-win32.whl", hash = "sha256:3ddd90103f9e5c471c49c7852ecc1fe27c7e45eb99e977aefe7caa4e779f4f58", size = 275746, upload-time = "2026-05-09T23:15:12.609Z" }, + { url = "https://files.pythonhosted.org/packages/92/73/93d42045302636c91f2e5ef588b65b84b01428f28ec77de256b1dfdfbe5c/regex-2026.5.9-cp314-cp314t-win_amd64.whl", hash = "sha256:ca518ed29c46eecba6010b15f1b9a479314d2de409536e71b6a13aa04e3b8a77", size = 285685, upload-time = "2026-05-09T23:15:15.086Z" }, + { url = "https://files.pythonhosted.org/packages/da/80/35b4c33c804a165a7f55289afda3ea9e3eb6d15800341a2d66455c0f1f30/regex-2026.5.9-cp314-cp314t-win_arm64.whl", hash = "sha256:5e41809d2683fcde7d5a8c87a6567ba1fb1ce0de9f31bff578de00a4b2d76daa", size = 275713, upload-time = "2026-05-09T23:15:16.98Z" }, +] + +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + +[[package]] +name = "responses" +version = "0.26.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyyaml" }, + { name = "requests" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9f/b4/b7e040379838cc71bf5aabdb26998dfbe5ee73904c92c1c161faf5de8866/responses-0.26.0.tar.gz", hash = "sha256:c7f6923e6343ef3682816ba421c006626777893cb0d5e1434f674b649bac9eb4", size = 81303, upload-time = "2026-02-19T14:38:05.574Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ce/04/7f73d05b556da048923e31a0cc878f03be7c5425ed1f268082255c75d872/responses-0.26.0-py3-none-any.whl", hash = "sha256:03ec4409088cd5c66b71ecbbbd27fe2c58ddfad801c66203457b3e6a04868c37", size = 35099, upload-time = "2026-02-19T14:38:03.847Z" }, +] + +[[package]] +name = "rfc3339-validator" +version = "0.1.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/28/ea/a9387748e2d111c3c2b275ba970b735e04e15cdb1eb30693b6b5708c4dbd/rfc3339_validator-0.1.4.tar.gz", hash = "sha256:138a2abdf93304ad60530167e51d2dfb9549521a836871b88d7f4695d0022f6b", size = 5513, upload-time = "2021-05-12T16:37:54.178Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7b/44/4e421b96b67b2daff264473f7465db72fbdf36a07e05494f50300cc7b0c6/rfc3339_validator-0.1.4-py2.py3-none-any.whl", hash = "sha256:24f6ec1eda14ef823da9e36ec7113124b39c04d50a4d3d3a3c2859577e7791fa", size = 3490, upload-time = "2021-05-12T16:37:52.536Z" }, +] + +[[package]] +name = "rich" +version = "15.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" }, +] + +[[package]] +name = "roman-numerals" +version = "4.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ae/f9/41dc953bbeb056c17d5f7a519f50fdf010bd0553be2d630bc69d1e022703/roman_numerals-4.1.0.tar.gz", hash = "sha256:1af8b147eb1405d5839e78aeb93131690495fe9da5c91856cb33ad55a7f1e5b2", size = 9077, upload-time = "2025-12-17T18:25:34.381Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/54/6f679c435d28e0a568d8e8a7c0a93a09010818634c3c3907fc98d8983770/roman_numerals-4.1.0-py3-none-any.whl", hash = "sha256:647ba99caddc2cc1e55a51e4360689115551bf4476d90e8162cf8c345fe233c7", size = 7676, upload-time = "2025-12-17T18:25:33.098Z" }, +] + +[[package]] +name = "rpds-py" +version = "0.30.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/20/af/3f2f423103f1113b36230496629986e0ef7e199d2aa8392452b484b38ced/rpds_py-0.30.0.tar.gz", hash = "sha256:dd8ff7cf90014af0c0f787eea34794ebf6415242ee1d6fa91eaba725cc441e84", size = 69469, upload-time = "2025-11-30T20:24:38.837Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/03/e7/98a2f4ac921d82f33e03f3835f5bf3a4a40aa1bfdc57975e74a97b2b4bdd/rpds_py-0.30.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:a161f20d9a43006833cd7068375a94d035714d73a172b681d8881820600abfad", size = 375086, upload-time = "2025-11-30T20:22:17.93Z" }, + { url = "https://files.pythonhosted.org/packages/4d/a1/bca7fd3d452b272e13335db8d6b0b3ecde0f90ad6f16f3328c6fb150c889/rpds_py-0.30.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6abc8880d9d036ecaafe709079969f56e876fcf107f7a8e9920ba6d5a3878d05", size = 359053, upload-time = "2025-11-30T20:22:19.297Z" }, + { url = "https://files.pythonhosted.org/packages/65/1c/ae157e83a6357eceff62ba7e52113e3ec4834a84cfe07fa4b0757a7d105f/rpds_py-0.30.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ca28829ae5f5d569bb62a79512c842a03a12576375d5ece7d2cadf8abe96ec28", size = 390763, upload-time = "2025-11-30T20:22:21.661Z" }, + { url = "https://files.pythonhosted.org/packages/d4/36/eb2eb8515e2ad24c0bd43c3ee9cd74c33f7ca6430755ccdb240fd3144c44/rpds_py-0.30.0-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a1010ed9524c73b94d15919ca4d41d8780980e1765babf85f9a2f90d247153dd", size = 408951, upload-time = "2025-11-30T20:22:23.408Z" }, + { url = "https://files.pythonhosted.org/packages/d6/65/ad8dc1784a331fabbd740ef6f71ce2198c7ed0890dab595adb9ea2d775a1/rpds_py-0.30.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f8d1736cfb49381ba528cd5baa46f82fdc65c06e843dab24dd70b63d09121b3f", size = 514622, upload-time = "2025-11-30T20:22:25.16Z" }, + { url = "https://files.pythonhosted.org/packages/63/8e/0cfa7ae158e15e143fe03993b5bcd743a59f541f5952e1546b1ac1b5fd45/rpds_py-0.30.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d948b135c4693daff7bc2dcfc4ec57237a29bd37e60c2fabf5aff2bbacf3e2f1", size = 414492, upload-time = "2025-11-30T20:22:26.505Z" }, + { url = "https://files.pythonhosted.org/packages/60/1b/6f8f29f3f995c7ffdde46a626ddccd7c63aefc0efae881dc13b6e5d5bb16/rpds_py-0.30.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47f236970bccb2233267d89173d3ad2703cd36a0e2a6e92d0560d333871a3d23", size = 394080, upload-time = "2025-11-30T20:22:27.934Z" }, + { url = "https://files.pythonhosted.org/packages/6d/d5/a266341051a7a3ca2f4b750a3aa4abc986378431fc2da508c5034d081b70/rpds_py-0.30.0-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:2e6ecb5a5bcacf59c3f912155044479af1d0b6681280048b338b28e364aca1f6", size = 408680, upload-time = "2025-11-30T20:22:29.341Z" }, + { url = "https://files.pythonhosted.org/packages/10/3b/71b725851df9ab7a7a4e33cf36d241933da66040d195a84781f49c50490c/rpds_py-0.30.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a8fa71a2e078c527c3e9dc9fc5a98c9db40bcc8a92b4e8858e36d329f8684b51", size = 423589, upload-time = "2025-11-30T20:22:31.469Z" }, + { url = "https://files.pythonhosted.org/packages/00/2b/e59e58c544dc9bd8bd8384ecdb8ea91f6727f0e37a7131baeff8d6f51661/rpds_py-0.30.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:73c67f2db7bc334e518d097c6d1e6fed021bbc9b7d678d6cc433478365d1d5f5", size = 573289, upload-time = "2025-11-30T20:22:32.997Z" }, + { url = "https://files.pythonhosted.org/packages/da/3e/a18e6f5b460893172a7d6a680e86d3b6bc87a54c1f0b03446a3c8c7b588f/rpds_py-0.30.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:5ba103fb455be00f3b1c2076c9d4264bfcb037c976167a6047ed82f23153f02e", size = 599737, upload-time = "2025-11-30T20:22:34.419Z" }, + { url = "https://files.pythonhosted.org/packages/5c/e2/714694e4b87b85a18e2c243614974413c60aa107fd815b8cbc42b873d1d7/rpds_py-0.30.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7cee9c752c0364588353e627da8a7e808a66873672bcb5f52890c33fd965b394", size = 563120, upload-time = "2025-11-30T20:22:35.903Z" }, + { url = "https://files.pythonhosted.org/packages/6f/ab/d5d5e3bcedb0a77f4f613706b750e50a5a3ba1c15ccd3665ecc636c968fd/rpds_py-0.30.0-cp312-cp312-win32.whl", hash = "sha256:1ab5b83dbcf55acc8b08fc62b796ef672c457b17dbd7820a11d6c52c06839bdf", size = 223782, upload-time = "2025-11-30T20:22:37.271Z" }, + { url = "https://files.pythonhosted.org/packages/39/3b/f786af9957306fdc38a74cef405b7b93180f481fb48453a114bb6465744a/rpds_py-0.30.0-cp312-cp312-win_amd64.whl", hash = "sha256:a090322ca841abd453d43456ac34db46e8b05fd9b3b4ac0c78bcde8b089f959b", size = 240463, upload-time = "2025-11-30T20:22:39.021Z" }, + { url = "https://files.pythonhosted.org/packages/f3/d2/b91dc748126c1559042cfe41990deb92c4ee3e2b415f6b5234969ffaf0cc/rpds_py-0.30.0-cp312-cp312-win_arm64.whl", hash = "sha256:669b1805bd639dd2989b281be2cfd951c6121b65e729d9b843e9639ef1fd555e", size = 230868, upload-time = "2025-11-30T20:22:40.493Z" }, + { url = "https://files.pythonhosted.org/packages/ed/dc/d61221eb88ff410de3c49143407f6f3147acf2538c86f2ab7ce65ae7d5f9/rpds_py-0.30.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:f83424d738204d9770830d35290ff3273fbb02b41f919870479fab14b9d303b2", size = 374887, upload-time = "2025-11-30T20:22:41.812Z" }, + { url = "https://files.pythonhosted.org/packages/fd/32/55fb50ae104061dbc564ef15cc43c013dc4a9f4527a1f4d99baddf56fe5f/rpds_py-0.30.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e7536cd91353c5273434b4e003cbda89034d67e7710eab8761fd918ec6c69cf8", size = 358904, upload-time = "2025-11-30T20:22:43.479Z" }, + { url = "https://files.pythonhosted.org/packages/58/70/faed8186300e3b9bdd138d0273109784eea2396c68458ed580f885dfe7ad/rpds_py-0.30.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2771c6c15973347f50fece41fc447c054b7ac2ae0502388ce3b6738cd366e3d4", size = 389945, upload-time = "2025-11-30T20:22:44.819Z" }, + { url = "https://files.pythonhosted.org/packages/bd/a8/073cac3ed2c6387df38f71296d002ab43496a96b92c823e76f46b8af0543/rpds_py-0.30.0-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:0a59119fc6e3f460315fe9d08149f8102aa322299deaa5cab5b40092345c2136", size = 407783, upload-time = "2025-11-30T20:22:46.103Z" }, + { url = "https://files.pythonhosted.org/packages/77/57/5999eb8c58671f1c11eba084115e77a8899d6e694d2a18f69f0ba471ec8b/rpds_py-0.30.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:76fec018282b4ead0364022e3c54b60bf368b9d926877957a8624b58419169b7", size = 515021, upload-time = "2025-11-30T20:22:47.458Z" }, + { url = "https://files.pythonhosted.org/packages/e0/af/5ab4833eadc36c0a8ed2bc5c0de0493c04f6c06de223170bd0798ff98ced/rpds_py-0.30.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:692bef75a5525db97318e8cd061542b5a79812d711ea03dbc1f6f8dbb0c5f0d2", size = 414589, upload-time = "2025-11-30T20:22:48.872Z" }, + { url = "https://files.pythonhosted.org/packages/b7/de/f7192e12b21b9e9a68a6d0f249b4af3fdcdff8418be0767a627564afa1f1/rpds_py-0.30.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9027da1ce107104c50c81383cae773ef5c24d296dd11c99e2629dbd7967a20c6", size = 394025, upload-time = "2025-11-30T20:22:50.196Z" }, + { url = "https://files.pythonhosted.org/packages/91/c4/fc70cd0249496493500e7cc2de87504f5aa6509de1e88623431fec76d4b6/rpds_py-0.30.0-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:9cf69cdda1f5968a30a359aba2f7f9aa648a9ce4b580d6826437f2b291cfc86e", size = 408895, upload-time = "2025-11-30T20:22:51.87Z" }, + { url = "https://files.pythonhosted.org/packages/58/95/d9275b05ab96556fefff73a385813eb66032e4c99f411d0795372d9abcea/rpds_py-0.30.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a4796a717bf12b9da9d3ad002519a86063dcac8988b030e405704ef7d74d2d9d", size = 422799, upload-time = "2025-11-30T20:22:53.341Z" }, + { url = "https://files.pythonhosted.org/packages/06/c1/3088fc04b6624eb12a57eb814f0d4997a44b0d208d6cace713033ff1a6ba/rpds_py-0.30.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5d4c2aa7c50ad4728a094ebd5eb46c452e9cb7edbfdb18f9e1221f597a73e1e7", size = 572731, upload-time = "2025-11-30T20:22:54.778Z" }, + { url = "https://files.pythonhosted.org/packages/d8/42/c612a833183b39774e8ac8fecae81263a68b9583ee343db33ab571a7ce55/rpds_py-0.30.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ba81a9203d07805435eb06f536d95a266c21e5b2dfbf6517748ca40c98d19e31", size = 599027, upload-time = "2025-11-30T20:22:56.212Z" }, + { url = "https://files.pythonhosted.org/packages/5f/60/525a50f45b01d70005403ae0e25f43c0384369ad24ffe46e8d9068b50086/rpds_py-0.30.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:945dccface01af02675628334f7cf49c2af4c1c904748efc5cf7bbdf0b579f95", size = 563020, upload-time = "2025-11-30T20:22:58.2Z" }, + { url = "https://files.pythonhosted.org/packages/0b/5d/47c4655e9bcd5ca907148535c10e7d489044243cc9941c16ed7cd53be91d/rpds_py-0.30.0-cp313-cp313-win32.whl", hash = "sha256:b40fb160a2db369a194cb27943582b38f79fc4887291417685f3ad693c5a1d5d", size = 223139, upload-time = "2025-11-30T20:23:00.209Z" }, + { url = "https://files.pythonhosted.org/packages/f2/e1/485132437d20aa4d3e1d8b3fb5a5e65aa8139f1e097080c2a8443201742c/rpds_py-0.30.0-cp313-cp313-win_amd64.whl", hash = "sha256:806f36b1b605e2d6a72716f321f20036b9489d29c51c91f4dd29a3e3afb73b15", size = 240224, upload-time = "2025-11-30T20:23:02.008Z" }, + { url = "https://files.pythonhosted.org/packages/24/95/ffd128ed1146a153d928617b0ef673960130be0009c77d8fbf0abe306713/rpds_py-0.30.0-cp313-cp313-win_arm64.whl", hash = "sha256:d96c2086587c7c30d44f31f42eae4eac89b60dabbac18c7669be3700f13c3ce1", size = 230645, upload-time = "2025-11-30T20:23:03.43Z" }, + { url = "https://files.pythonhosted.org/packages/ff/1b/b10de890a0def2a319a2626334a7f0ae388215eb60914dbac8a3bae54435/rpds_py-0.30.0-cp313-cp313t-macosx_10_12_x86_64.whl", hash = "sha256:eb0b93f2e5c2189ee831ee43f156ed34e2a89a78a66b98cadad955972548be5a", size = 364443, upload-time = "2025-11-30T20:23:04.878Z" }, + { url = "https://files.pythonhosted.org/packages/0d/bf/27e39f5971dc4f305a4fb9c672ca06f290f7c4e261c568f3dea16a410d47/rpds_py-0.30.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:922e10f31f303c7c920da8981051ff6d8c1a56207dbdf330d9047f6d30b70e5e", size = 353375, upload-time = "2025-11-30T20:23:06.342Z" }, + { url = "https://files.pythonhosted.org/packages/40/58/442ada3bba6e8e6615fc00483135c14a7538d2ffac30e2d933ccf6852232/rpds_py-0.30.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cdc62c8286ba9bf7f47befdcea13ea0e26bf294bda99758fd90535cbaf408000", size = 383850, upload-time = "2025-11-30T20:23:07.825Z" }, + { url = "https://files.pythonhosted.org/packages/14/14/f59b0127409a33c6ef6f5c1ebd5ad8e32d7861c9c7adfa9a624fc3889f6c/rpds_py-0.30.0-cp313-cp313t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:47f9a91efc418b54fb8190a6b4aa7813a23fb79c51f4bb84e418f5476c38b8db", size = 392812, upload-time = "2025-11-30T20:23:09.228Z" }, + { url = "https://files.pythonhosted.org/packages/b3/66/e0be3e162ac299b3a22527e8913767d869e6cc75c46bd844aa43fb81ab62/rpds_py-0.30.0-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1f3587eb9b17f3789ad50824084fa6f81921bbf9a795826570bda82cb3ed91f2", size = 517841, upload-time = "2025-11-30T20:23:11.186Z" }, + { url = "https://files.pythonhosted.org/packages/3d/55/fa3b9cf31d0c963ecf1ba777f7cf4b2a2c976795ac430d24a1f43d25a6ba/rpds_py-0.30.0-cp313-cp313t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:39c02563fc592411c2c61d26b6c5fe1e51eaa44a75aa2c8735ca88b0d9599daa", size = 408149, upload-time = "2025-11-30T20:23:12.864Z" }, + { url = "https://files.pythonhosted.org/packages/60/ca/780cf3b1a32b18c0f05c441958d3758f02544f1d613abf9488cd78876378/rpds_py-0.30.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:51a1234d8febafdfd33a42d97da7a43f5dcb120c1060e352a3fbc0c6d36e2083", size = 383843, upload-time = "2025-11-30T20:23:14.638Z" }, + { url = "https://files.pythonhosted.org/packages/82/86/d5f2e04f2aa6247c613da0c1dd87fcd08fa17107e858193566048a1e2f0a/rpds_py-0.30.0-cp313-cp313t-manylinux_2_31_riscv64.whl", hash = "sha256:eb2c4071ab598733724c08221091e8d80e89064cd472819285a9ab0f24bcedb9", size = 396507, upload-time = "2025-11-30T20:23:16.105Z" }, + { url = "https://files.pythonhosted.org/packages/4b/9a/453255d2f769fe44e07ea9785c8347edaf867f7026872e76c1ad9f7bed92/rpds_py-0.30.0-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:6bdfdb946967d816e6adf9a3d8201bfad269c67efe6cefd7093ef959683c8de0", size = 414949, upload-time = "2025-11-30T20:23:17.539Z" }, + { url = "https://files.pythonhosted.org/packages/a3/31/622a86cdc0c45d6df0e9ccb6becdba5074735e7033c20e401a6d9d0e2ca0/rpds_py-0.30.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:c77afbd5f5250bf27bf516c7c4a016813eb2d3e116139aed0096940c5982da94", size = 565790, upload-time = "2025-11-30T20:23:19.029Z" }, + { url = "https://files.pythonhosted.org/packages/1c/5d/15bbf0fb4a3f58a3b1c67855ec1efcc4ceaef4e86644665fff03e1b66d8d/rpds_py-0.30.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:61046904275472a76c8c90c9ccee9013d70a6d0f73eecefd38c1ae7c39045a08", size = 590217, upload-time = "2025-11-30T20:23:20.885Z" }, + { url = "https://files.pythonhosted.org/packages/6d/61/21b8c41f68e60c8cc3b2e25644f0e3681926020f11d06ab0b78e3c6bbff1/rpds_py-0.30.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:4c5f36a861bc4b7da6516dbdf302c55313afa09b81931e8280361a4f6c9a2d27", size = 555806, upload-time = "2025-11-30T20:23:22.488Z" }, + { url = "https://files.pythonhosted.org/packages/f9/39/7e067bb06c31de48de3eb200f9fc7c58982a4d3db44b07e73963e10d3be9/rpds_py-0.30.0-cp313-cp313t-win32.whl", hash = "sha256:3d4a69de7a3e50ffc214ae16d79d8fbb0922972da0356dcf4d0fdca2878559c6", size = 211341, upload-time = "2025-11-30T20:23:24.449Z" }, + { url = "https://files.pythonhosted.org/packages/0a/4d/222ef0b46443cf4cf46764d9c630f3fe4abaa7245be9417e56e9f52b8f65/rpds_py-0.30.0-cp313-cp313t-win_amd64.whl", hash = "sha256:f14fc5df50a716f7ece6a80b6c78bb35ea2ca47c499e422aa4463455dd96d56d", size = 225768, upload-time = "2025-11-30T20:23:25.908Z" }, + { url = "https://files.pythonhosted.org/packages/86/81/dad16382ebbd3d0e0328776d8fd7ca94220e4fa0798d1dc5e7da48cb3201/rpds_py-0.30.0-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:68f19c879420aa08f61203801423f6cd5ac5f0ac4ac82a2368a9fcd6a9a075e0", size = 362099, upload-time = "2025-11-30T20:23:27.316Z" }, + { url = "https://files.pythonhosted.org/packages/2b/60/19f7884db5d5603edf3c6bce35408f45ad3e97e10007df0e17dd57af18f8/rpds_py-0.30.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:ec7c4490c672c1a0389d319b3a9cfcd098dcdc4783991553c332a15acf7249be", size = 353192, upload-time = "2025-11-30T20:23:29.151Z" }, + { url = "https://files.pythonhosted.org/packages/bf/c4/76eb0e1e72d1a9c4703c69607cec123c29028bff28ce41588792417098ac/rpds_py-0.30.0-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f251c812357a3fed308d684a5079ddfb9d933860fc6de89f2b7ab00da481e65f", size = 384080, upload-time = "2025-11-30T20:23:30.785Z" }, + { url = "https://files.pythonhosted.org/packages/72/87/87ea665e92f3298d1b26d78814721dc39ed8d2c74b86e83348d6b48a6f31/rpds_py-0.30.0-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ac98b175585ecf4c0348fd7b29c3864bda53b805c773cbf7bfdaffc8070c976f", size = 394841, upload-time = "2025-11-30T20:23:32.209Z" }, + { url = "https://files.pythonhosted.org/packages/77/ad/7783a89ca0587c15dcbf139b4a8364a872a25f861bdb88ed99f9b0dec985/rpds_py-0.30.0-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3e62880792319dbeb7eb866547f2e35973289e7d5696c6e295476448f5b63c87", size = 516670, upload-time = "2025-11-30T20:23:33.742Z" }, + { url = "https://files.pythonhosted.org/packages/5b/3c/2882bdac942bd2172f3da574eab16f309ae10a3925644e969536553cb4ee/rpds_py-0.30.0-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4e7fc54e0900ab35d041b0601431b0a0eb495f0851a0639b6ef90f7741b39a18", size = 408005, upload-time = "2025-11-30T20:23:35.253Z" }, + { url = "https://files.pythonhosted.org/packages/ce/81/9a91c0111ce1758c92516a3e44776920b579d9a7c09b2b06b642d4de3f0f/rpds_py-0.30.0-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47e77dc9822d3ad616c3d5759ea5631a75e5809d5a28707744ef79d7a1bcfcad", size = 382112, upload-time = "2025-11-30T20:23:36.842Z" }, + { url = "https://files.pythonhosted.org/packages/cf/8e/1da49d4a107027e5fbc64daeab96a0706361a2918da10cb41769244b805d/rpds_py-0.30.0-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:b4dc1a6ff022ff85ecafef7979a2c6eb423430e05f1165d6688234e62ba99a07", size = 399049, upload-time = "2025-11-30T20:23:38.343Z" }, + { url = "https://files.pythonhosted.org/packages/df/5a/7ee239b1aa48a127570ec03becbb29c9d5a9eb092febbd1699d567cae859/rpds_py-0.30.0-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:4559c972db3a360808309e06a74628b95eaccbf961c335c8fe0d590cf587456f", size = 415661, upload-time = "2025-11-30T20:23:40.263Z" }, + { url = "https://files.pythonhosted.org/packages/70/ea/caa143cf6b772f823bc7929a45da1fa83569ee49b11d18d0ada7f5ee6fd6/rpds_py-0.30.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:0ed177ed9bded28f8deb6ab40c183cd1192aa0de40c12f38be4d59cd33cb5c65", size = 565606, upload-time = "2025-11-30T20:23:42.186Z" }, + { url = "https://files.pythonhosted.org/packages/64/91/ac20ba2d69303f961ad8cf55bf7dbdb4763f627291ba3d0d7d67333cced9/rpds_py-0.30.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:ad1fa8db769b76ea911cb4e10f049d80bf518c104f15b3edb2371cc65375c46f", size = 591126, upload-time = "2025-11-30T20:23:44.086Z" }, + { url = "https://files.pythonhosted.org/packages/21/20/7ff5f3c8b00c8a95f75985128c26ba44503fb35b8e0259d812766ea966c7/rpds_py-0.30.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:46e83c697b1f1c72b50e5ee5adb4353eef7406fb3f2043d64c33f20ad1c2fc53", size = 553371, upload-time = "2025-11-30T20:23:46.004Z" }, + { url = "https://files.pythonhosted.org/packages/72/c7/81dadd7b27c8ee391c132a6b192111ca58d866577ce2d9b0ca157552cce0/rpds_py-0.30.0-cp314-cp314-win32.whl", hash = "sha256:ee454b2a007d57363c2dfd5b6ca4a5d7e2c518938f8ed3b706e37e5d470801ed", size = 215298, upload-time = "2025-11-30T20:23:47.696Z" }, + { url = "https://files.pythonhosted.org/packages/3e/d2/1aaac33287e8cfb07aab2e6b8ac1deca62f6f65411344f1433c55e6f3eb8/rpds_py-0.30.0-cp314-cp314-win_amd64.whl", hash = "sha256:95f0802447ac2d10bcc69f6dc28fe95fdf17940367b21d34e34c737870758950", size = 228604, upload-time = "2025-11-30T20:23:49.501Z" }, + { url = "https://files.pythonhosted.org/packages/e8/95/ab005315818cc519ad074cb7784dae60d939163108bd2b394e60dc7b5461/rpds_py-0.30.0-cp314-cp314-win_arm64.whl", hash = "sha256:613aa4771c99f03346e54c3f038e4cc574ac09a3ddfb0e8878487335e96dead6", size = 222391, upload-time = "2025-11-30T20:23:50.96Z" }, + { url = "https://files.pythonhosted.org/packages/9e/68/154fe0194d83b973cdedcdcc88947a2752411165930182ae41d983dcefa6/rpds_py-0.30.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:7e6ecfcb62edfd632e56983964e6884851786443739dbfe3582947e87274f7cb", size = 364868, upload-time = "2025-11-30T20:23:52.494Z" }, + { url = "https://files.pythonhosted.org/packages/83/69/8bbc8b07ec854d92a8b75668c24d2abcb1719ebf890f5604c61c9369a16f/rpds_py-0.30.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a1d0bc22a7cdc173fedebb73ef81e07faef93692b8c1ad3733b67e31e1b6e1b8", size = 353747, upload-time = "2025-11-30T20:23:54.036Z" }, + { url = "https://files.pythonhosted.org/packages/ab/00/ba2e50183dbd9abcce9497fa5149c62b4ff3e22d338a30d690f9af970561/rpds_py-0.30.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0d08f00679177226c4cb8c5265012eea897c8ca3b93f429e546600c971bcbae7", size = 383795, upload-time = "2025-11-30T20:23:55.556Z" }, + { url = "https://files.pythonhosted.org/packages/05/6f/86f0272b84926bcb0e4c972262f54223e8ecc556b3224d281e6598fc9268/rpds_py-0.30.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:5965af57d5848192c13534f90f9dd16464f3c37aaf166cc1da1cae1fd5a34898", size = 393330, upload-time = "2025-11-30T20:23:57.033Z" }, + { url = "https://files.pythonhosted.org/packages/cb/e9/0e02bb2e6dc63d212641da45df2b0bf29699d01715913e0d0f017ee29438/rpds_py-0.30.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9a4e86e34e9ab6b667c27f3211ca48f73dba7cd3d90f8d5b11be56e5dbc3fb4e", size = 518194, upload-time = "2025-11-30T20:23:58.637Z" }, + { url = "https://files.pythonhosted.org/packages/ee/ca/be7bca14cf21513bdf9c0606aba17d1f389ea2b6987035eb4f62bd923f25/rpds_py-0.30.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e5d3e6b26f2c785d65cc25ef1e5267ccbe1b069c5c21b8cc724efee290554419", size = 408340, upload-time = "2025-11-30T20:24:00.2Z" }, + { url = "https://files.pythonhosted.org/packages/c2/c7/736e00ebf39ed81d75544c0da6ef7b0998f8201b369acf842f9a90dc8fce/rpds_py-0.30.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:626a7433c34566535b6e56a1b39a7b17ba961e97ce3b80ec62e6f1312c025551", size = 383765, upload-time = "2025-11-30T20:24:01.759Z" }, + { url = "https://files.pythonhosted.org/packages/4a/3f/da50dfde9956aaf365c4adc9533b100008ed31aea635f2b8d7b627e25b49/rpds_py-0.30.0-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:acd7eb3f4471577b9b5a41baf02a978e8bdeb08b4b355273994f8b87032000a8", size = 396834, upload-time = "2025-11-30T20:24:03.687Z" }, + { url = "https://files.pythonhosted.org/packages/4e/00/34bcc2565b6020eab2623349efbdec810676ad571995911f1abdae62a3a0/rpds_py-0.30.0-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:fe5fa731a1fa8a0a56b0977413f8cacac1768dad38d16b3a296712709476fbd5", size = 415470, upload-time = "2025-11-30T20:24:05.232Z" }, + { url = "https://files.pythonhosted.org/packages/8c/28/882e72b5b3e6f718d5453bd4d0d9cf8df36fddeb4ddbbab17869d5868616/rpds_py-0.30.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:74a3243a411126362712ee1524dfc90c650a503502f135d54d1b352bd01f2404", size = 565630, upload-time = "2025-11-30T20:24:06.878Z" }, + { url = "https://files.pythonhosted.org/packages/3b/97/04a65539c17692de5b85c6e293520fd01317fd878ea1995f0367d4532fb1/rpds_py-0.30.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:3e8eeb0544f2eb0d2581774be4c3410356eba189529a6b3e36bbbf9696175856", size = 591148, upload-time = "2025-11-30T20:24:08.445Z" }, + { url = "https://files.pythonhosted.org/packages/85/70/92482ccffb96f5441aab93e26c4d66489eb599efdcf96fad90c14bbfb976/rpds_py-0.30.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:dbd936cde57abfee19ab3213cf9c26be06d60750e60a8e4dd85d1ab12c8b1f40", size = 556030, upload-time = "2025-11-30T20:24:10.956Z" }, + { url = "https://files.pythonhosted.org/packages/20/53/7c7e784abfa500a2b6b583b147ee4bb5a2b3747a9166bab52fec4b5b5e7d/rpds_py-0.30.0-cp314-cp314t-win32.whl", hash = "sha256:dc824125c72246d924f7f796b4f63c1e9dc810c7d9e2355864b3c3a73d59ade0", size = 211570, upload-time = "2025-11-30T20:24:12.735Z" }, + { url = "https://files.pythonhosted.org/packages/d0/02/fa464cdfbe6b26e0600b62c528b72d8608f5cc49f96b8d6e38c95d60c676/rpds_py-0.30.0-cp314-cp314t-win_amd64.whl", hash = "sha256:27f4b0e92de5bfbc6f86e43959e6edd1425c33b5e69aab0984a72047f2bcf1e3", size = 226532, upload-time = "2025-11-30T20:24:14.634Z" }, +] + +[[package]] +name = "ruff" +version = "0.16.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/73/e1/4508a569211b35599016e84ba65c1a992b7a4004b4b6c4bea02a851cba1b/ruff-0.16.2.tar.gz", hash = "sha256:c3d7828d12e8927a6fc65fe38e2c2541b9e762d360a1786d752cb1b8883b3c9c", size = 4885811, upload-time = "2026-08-07T13:31:01.432Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/14/57/db19951540f98859c956b50bdb4d31089b4d91e9f15e2968e7d5193806d5/ruff-0.16.2-py3-none-linux_armv6l.whl", hash = "sha256:3c8de4cf2181f01d57946d87d777aa52916976fc09942aed89938fab5e013318", size = 10847925, upload-time = "2026-08-07T13:30:14.468Z" }, + { url = "https://files.pythonhosted.org/packages/13/5a/995fe85a8470d3e391ac0f7fa8054bb454eaf33ee138196d6172ed1079c0/ruff-0.16.2-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9a48cc05c6fbc811ca81b5d7ba95375affea6582d1b8024e455e41afbbf55344", size = 11072662, upload-time = "2026-08-07T13:30:18.143Z" }, + { url = "https://files.pythonhosted.org/packages/32/53/370d767c61c71a971a4ace36703a7ecd8c393956349a7325d7fab2b56827/ruff-0.16.2-py3-none-macosx_11_0_arm64.whl", hash = "sha256:a2c0d14fcbb26c91f0f867a6dc9bd71bbc30b1b6151829c884f23faeab2e5700", size = 10566771, upload-time = "2026-08-07T13:30:20.899Z" }, + { url = "https://files.pythonhosted.org/packages/85/d6/9d96948caf5a632be62d62202d5ec914d6856f204fd79eb036e5915e79ea/ruff-0.16.2-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:335c621622c4650330be50842561c6586ac6971bb8ab5407fe34dcc9efb16bbe", size = 10975825, upload-time = "2026-08-07T13:30:23.517Z" }, + { url = "https://files.pythonhosted.org/packages/3b/92/ea87129b3414acb0b5770563779c51804d37ac67675c7ba35447ddb14773/ruff-0.16.2-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:20e66910f2c37cc753f9ef6580c914a621b80c4fa3549d3e3521e29d0f5bfc3f", size = 10649437, upload-time = "2026-08-07T13:30:26.097Z" }, + { url = "https://files.pythonhosted.org/packages/ac/43/f8f291dcd4af5bb7872b74fdfa41a7cd7c856ca1d4069670971cf1b9f5cb/ruff-0.16.2-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c7e36fbfba65510548156902bcf1350a979a958ce0347ce0f90d73894036b39f", size = 11446761, upload-time = "2026-08-07T13:30:28.752Z" }, + { url = "https://files.pythonhosted.org/packages/71/4a/ef991fb2fcf516ab71f0808adcdd8da5e18c8cde447f4ceaf5f47a5132a5/ruff-0.16.2-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f0eab35f80df8f134aae5d1630e751901321d317cc8e50dc39e36fa3ed34cd12", size = 12336364, upload-time = "2026-08-07T13:30:31.468Z" }, + { url = "https://files.pythonhosted.org/packages/f3/24/f615e74f307e6ca0e56a482872477b856c70d530aa356abfb6dfe5ca8a80/ruff-0.16.2-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:40ea8c0594feb894e89c8c61ab9c103d38b0ea72dfde6c594107147ca31b1140", size = 11630720, upload-time = "2026-08-07T13:30:34.426Z" }, + { url = "https://files.pythonhosted.org/packages/c5/d3/8ef50149e8412a77f7ab409efdef0e2b23803707a3863da4fc64cb23d459/ruff-0.16.2-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ab3d62dde0b19facdd632008cc4827fc28ada7736c6bd35ab6f1050f0bfed53f", size = 11466130, upload-time = "2026-08-07T13:30:36.958Z" }, + { url = "https://files.pythonhosted.org/packages/dd/a7/a19334985c4dea8c381981fa252cd854c7ee52dc4b1686dc16f4a911c702/ruff-0.16.2-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:e43e1f5b8388da9eca1b9e88328d47a5cec794633ccf6f7484ac2dd15eee92c0", size = 11523634, upload-time = "2026-08-07T13:30:39.822Z" }, + { url = "https://files.pythonhosted.org/packages/6e/6c/96d192b0e742412ceda08c0a50f9669b253dde9fd6a60ea1a10c9fa79a63/ruff-0.16.2-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:c24788a980581e1d7ea3a0cbe4344c4fbeb0a6a9b1f4713aa46bb104f8294690", size = 10949807, upload-time = "2026-08-07T13:30:42.745Z" }, + { url = "https://files.pythonhosted.org/packages/fa/51/e26599ceca11e79ee255c7df515995561edf87e9ca1893284e44d98f5a86/ruff-0.16.2-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:81806b08329130005dd4a8a8394a0c9da8c6f4cafb16ba438d2a2ee6a18bedf1", size = 10646891, upload-time = "2026-08-07T13:30:45.522Z" }, + { url = "https://files.pythonhosted.org/packages/68/01/800c4b1f97bc8d7c6029e06b1f20473a3cf1e13c4933d8f3342add83fc55/ruff-0.16.2-py3-none-musllinux_1_2_i686.whl", hash = "sha256:4ce4e02bad779bef557f541a1b31f20d6abeae1cc05ed1b1ac019d4ffd1044c8", size = 11162063, upload-time = "2026-08-07T13:30:48.131Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d0/1477ea50fc5a0d4b0b71d1d63d50770bdd794d90b43e37a7618e63ec9894/ruff-0.16.2-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:e0422abdf70070255fc4073ce9dfc814cc03db577013761ddd09bc1e4a9a4fbd", size = 11556038, upload-time = "2026-08-07T13:30:50.686Z" }, + { url = "https://files.pythonhosted.org/packages/b8/76/a7776f32048d991e16d4fa8ff91790b877342d3596cc3ed04acdbf1aaedc/ruff-0.16.2-py3-none-win32.whl", hash = "sha256:bf3a63d78fb39f4bf5ac8ae52051c5520505301abe19ba4e204c453b3f09bb0b", size = 10872850, upload-time = "2026-08-07T13:30:53.471Z" }, + { url = "https://files.pythonhosted.org/packages/00/0d/929c800d920e61397d82a01b60bffc68da3052c17d31de59efaad2e4ed75/ruff-0.16.2-py3-none-win_amd64.whl", hash = "sha256:bcabe2f6d0fc7819f1431793005af4e4de7371927d037345bf941252b195b9fa", size = 12023338, upload-time = "2026-08-07T13:30:56.193Z" }, + { url = "https://files.pythonhosted.org/packages/5b/6c/93e26c22c5f78ff87363e07da49c84955affbeb1098bd1936bf3b3f293bf/ruff-0.16.2-py3-none-win_arm64.whl", hash = "sha256:d614e95cedf38a2053fd351c55b103ba30d017d61688fdbfd40ee0412852a99f", size = 11374065, upload-time = "2026-08-07T13:30:58.775Z" }, +] + +[[package]] +name = "s3fs" +version = "2026.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiobotocore" }, + { name = "aiohttp" }, + { name = "fsspec" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/12/60/69fc080b72a32971b2fb5acbc80802b0e876b606f6e27b1689caac4bb57b/s3fs-2026.7.0.tar.gz", hash = "sha256:76b062d1b2bc7bf4bcd9e7d8f1eb2b5dd9d5cee96ce888664c4ddb5f563146bf", size = 87595, upload-time = "2026-07-28T17:14:10.595Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/98/cc/bcde19a37952ecc58e7d9d67ecaa048e1e21b17d014ce0863a6a6101e606/s3fs-2026.7.0-py3-none-any.whl", hash = "sha256:64edf3c01ebffab1eec38ff9c09eefbf86a3db14c87d248f795da0e7b801d698", size = 32659, upload-time = "2026-07-28T17:14:09.497Z" }, +] + +[[package]] +name = "s3transfer" +version = "0.17.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "botocore" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9b/ec/7c692cde9125b77e84b307354d4fb705f98b8ccad59a036d5957ca75bfc3/s3transfer-0.17.0.tar.gz", hash = "sha256:9edeb6d1c3c2f89d6050348548834ad8289610d886e5bf7b7207728bd43ce33a", size = 155337, upload-time = "2026-04-29T22:07:36.33Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/72/c6c32d2b657fa3dad1de340254e14390b1e334ce38268b7ad51abda3c8c2/s3transfer-0.17.0-py3-none-any.whl", hash = "sha256:ce3801712acf4ad3e89fb9990df97b4972e93f4b3b0004d214be5bce12814c20", size = 86811, upload-time = "2026-04-29T22:07:34.966Z" }, +] + +[[package]] +name = "setuptools" +version = "83.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/34/26/f5d29e25ffdb535afef2d35cdb55b325298f96debd670da4c325e08d70f4/setuptools-83.0.0.tar.gz", hash = "sha256:025bccbbf0fa05b6192bc64ae1e7b16e001fd6d6d4d5de03c97b1c1ade523bef", size = 1154254, upload-time = "2026-07-04T15:31:22.699Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/40/e1e72872c6354b306daef1703549e8e83b4d43cfea356311bf722a043752/setuptools-83.0.0-py3-none-any.whl", hash = "sha256:29b23c360f22f414dc7336bb39178cc7bcbf6021ed2733cde173f09dba19abb3", size = 1008090, upload-time = "2026-07-04T15:31:20.885Z" }, +] + +[[package]] +name = "shellingham" +version = "1.5.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/58/15/8b3609fd3830ef7b27b655beb4b4e9c62313a4e8da8c676e142cc210d58e/shellingham-1.5.4.tar.gz", hash = "sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de", size = 10310, upload-time = "2023-10-24T04:13:40.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + +[[package]] +name = "snowballstemmer" +version = "3.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/75/a7/9810d872919697c9d01295633f5d574fb416d47e535f258272ca1f01f447/snowballstemmer-3.0.1.tar.gz", hash = "sha256:6d5eeeec8e9f84d4d56b847692bacf79bc2c8e90c7f80ca4444ff8b6f2e52895", size = 105575, upload-time = "2025-05-09T16:34:51.843Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c8/78/3565d011c61f5a43488987ee32b6f3f656e7f107ac2782dd57bdd7d91d9a/snowballstemmer-3.0.1-py3-none-any.whl", hash = "sha256:6cd7b3897da8d6c9ffb968a6781fa6532dce9c3618a4b127d920dab764a19064", size = 103274, upload-time = "2025-05-09T16:34:50.371Z" }, +] + +[[package]] +name = "sortedcontainers" +version = "2.4.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e8/c4/ba2f8066cceb6f23394729afe52f3bf7adec04bf9ed2c820b39e19299111/sortedcontainers-2.4.0.tar.gz", hash = "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88", size = 30594, upload-time = "2021-05-16T22:03:42.897Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl", hash = "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0", size = 29575, upload-time = "2021-05-16T22:03:41.177Z" }, +] + +[[package]] +name = "sphinx" +version = "9.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "alabaster" }, + { name = "babel" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "docutils" }, + { name = "imagesize" }, + { name = "jinja2" }, + { name = "packaging" }, + { name = "pygments" }, + { name = "requests" }, + { name = "roman-numerals" }, + { name = "snowballstemmer" }, + { name = "sphinxcontrib-applehelp" }, + { name = "sphinxcontrib-devhelp" }, + { name = "sphinxcontrib-htmlhelp" }, + { name = "sphinxcontrib-jsmath" }, + { name = "sphinxcontrib-qthelp" }, + { name = "sphinxcontrib-serializinghtml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cd/bd/f08eb0f4eed5c83f1ba2a3bd18f7745a2b1525fad70660a1c00224ec468a/sphinx-9.1.0.tar.gz", hash = "sha256:7741722357dd75f8190766926071fed3bdc211c74dd2d7d4df5404da95930ddb", size = 8718324, upload-time = "2025-12-31T15:09:27.646Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/73/f7/b1884cb3188ab181fc81fa00c266699dab600f927a964df02ec3d5d1916a/sphinx-9.1.0-py3-none-any.whl", hash = "sha256:c84fdd4e782504495fe4f2c0b3413d6c2bf388589bb352d439b2a3bb99991978", size = 3921742, upload-time = "2025-12-31T15:09:25.561Z" }, +] + +[[package]] +name = "sphinxcontrib-applehelp" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/6e/b837e84a1a704953c62ef8776d45c3e8d759876b4a84fe14eba2859106fe/sphinxcontrib_applehelp-2.0.0.tar.gz", hash = "sha256:2f29ef331735ce958efa4734873f084941970894c6090408b079c61b2e1c06d1", size = 20053, upload-time = "2024-07-29T01:09:00.465Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/85/9ebeae2f76e9e77b952f4b274c27238156eae7979c5421fba91a28f4970d/sphinxcontrib_applehelp-2.0.0-py3-none-any.whl", hash = "sha256:4cd3f0ec4ac5dd9c17ec65e9ab272c9b867ea77425228e68ecf08d6b28ddbdb5", size = 119300, upload-time = "2024-07-29T01:08:58.99Z" }, +] + +[[package]] +name = "sphinxcontrib-devhelp" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/d2/5beee64d3e4e747f316bae86b55943f51e82bb86ecd325883ef65741e7da/sphinxcontrib_devhelp-2.0.0.tar.gz", hash = "sha256:411f5d96d445d1d73bb5d52133377b4248ec79db5c793ce7dbe59e074b4dd1ad", size = 12967, upload-time = "2024-07-29T01:09:23.417Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/35/7a/987e583882f985fe4d7323774889ec58049171828b58c2217e7f79cdf44e/sphinxcontrib_devhelp-2.0.0-py3-none-any.whl", hash = "sha256:aefb8b83854e4b0998877524d1029fd3e6879210422ee3780459e28a1f03a8a2", size = 82530, upload-time = "2024-07-29T01:09:21.945Z" }, +] + +[[package]] +name = "sphinxcontrib-htmlhelp" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/43/93/983afd9aa001e5201eab16b5a444ed5b9b0a7a010541e0ddfbbfd0b2470c/sphinxcontrib_htmlhelp-2.1.0.tar.gz", hash = "sha256:c9e2916ace8aad64cc13a0d233ee22317f2b9025b9cf3295249fa985cc7082e9", size = 22617, upload-time = "2024-07-29T01:09:37.889Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/7b/18a8c0bcec9182c05a0b3ec2a776bba4ead82750a55ff798e8d406dae604/sphinxcontrib_htmlhelp-2.1.0-py3-none-any.whl", hash = "sha256:166759820b47002d22914d64a075ce08f4c46818e17cfc9470a9786b759b19f8", size = 98705, upload-time = "2024-07-29T01:09:36.407Z" }, +] + +[[package]] +name = "sphinxcontrib-jsmath" +version = "1.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b2/e8/9ed3830aeed71f17c026a07a5097edcf44b692850ef215b161b8ad875729/sphinxcontrib-jsmath-1.0.1.tar.gz", hash = "sha256:a9925e4a4587247ed2191a22df5f6970656cb8ca2bd6284309578f2153e0c4b8", size = 5787, upload-time = "2019-01-21T16:10:16.347Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c2/42/4c8646762ee83602e3fb3fbe774c2fac12f317deb0b5dbeeedd2d3ba4b77/sphinxcontrib_jsmath-1.0.1-py2.py3-none-any.whl", hash = "sha256:2ec2eaebfb78f3f2078e73666b1415417a116cc848b72e5172e596c871103178", size = 5071, upload-time = "2019-01-21T16:10:14.333Z" }, +] + +[[package]] +name = "sphinxcontrib-qthelp" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/68/bc/9104308fc285eb3e0b31b67688235db556cd5b0ef31d96f30e45f2e51cae/sphinxcontrib_qthelp-2.0.0.tar.gz", hash = "sha256:4fe7d0ac8fc171045be623aba3e2a8f613f8682731f9153bb2e40ece16b9bbab", size = 17165, upload-time = "2024-07-29T01:09:56.435Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/27/83/859ecdd180cacc13b1f7e857abf8582a64552ea7a061057a6c716e790fce/sphinxcontrib_qthelp-2.0.0-py3-none-any.whl", hash = "sha256:b18a828cdba941ccd6ee8445dbe72ffa3ef8cbe7505d8cd1fa0d42d3f2d5f3eb", size = 88743, upload-time = "2024-07-29T01:09:54.885Z" }, +] + +[[package]] +name = "sphinxcontrib-serializinghtml" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3b/44/6716b257b0aa6bfd51a1b31665d1c205fb12cb5ad56de752dfa15657de2f/sphinxcontrib_serializinghtml-2.0.0.tar.gz", hash = "sha256:e9d912827f872c029017a53f0ef2180b327c3f7fd23c87229f7a8e8b70031d4d", size = 16080, upload-time = "2024-07-29T01:10:09.332Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/52/a7/d2782e4e3f77c8450f727ba74a8f12756d5ba823d81b941f1b04da9d033a/sphinxcontrib_serializinghtml-2.0.0-py3-none-any.whl", hash = "sha256:6e2cb0eef194e10c27ec0023bfeb25badbbb5868244cf5bc5bdc04e4464bf331", size = 92072, upload-time = "2024-07-29T01:10:08.203Z" }, +] + +[[package]] +name = "sympy" +version = "1.14.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mpmath" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" }, +] + +[[package]] +name = "tinycss2" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "webencodings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7a/fd/7a5ee21fd08ff70d3d33a5781c255cbe779659bd03278feb98b19ee550f4/tinycss2-1.4.0.tar.gz", hash = "sha256:10c0972f6fc0fbee87c3edb76549357415e94548c1ae10ebccdea16fb404a9b7", size = 87085, upload-time = "2024-10-24T14:58:29.895Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e6/34/ebdc18bae6aa14fbee1a08b63c015c72b64868ff7dae68808ab500c492e2/tinycss2-1.4.0-py3-none-any.whl", hash = "sha256:3a49cf47b7675da0b15d0c6e1df8df4ebd96e9394bb905a5775adb0d884c5289", size = 26610, upload-time = "2024-10-24T14:58:28.029Z" }, +] + +[[package]] +name = "tomlkit" +version = "0.15.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/96/e07752635b98536177fa1f37671c8f3cdde2e724c6bcf6034b2cfb571565/tomlkit-0.15.1.tar.gz", hash = "sha256:e25bbf38843005246210a12982776f27f99cb9be67160e14434d0c0d21ee1e97", size = 180129, upload-time = "2026-07-17T01:48:04.562Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/13/bc/8c13eb66537dce1d2bd3a57132902f38d0e7f5bb46fa9f4daed9fe9d76ee/tomlkit-0.15.1-py3-none-any.whl", hash = "sha256:177a05aece5a8ca5266fd3c448abb47b8d352f09d477d3ca8332db4d89b24304", size = 49449, upload-time = "2026-07-17T01:48:05.728Z" }, +] + +[[package]] +name = "towncrier" +version = "25.8.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "jinja2" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c2/eb/5bf25a34123698d3bbab39c5bc5375f8f8bcbcc5a136964ade66935b8b9d/towncrier-25.8.0.tar.gz", hash = "sha256:eef16d29f831ad57abb3ae32a0565739866219f1ebfbdd297d32894eb9940eb1", size = 76322, upload-time = "2025-08-30T11:41:55.393Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/42/06/8ba22ec32c74ac1be3baa26116e3c28bc0e76a5387476921d20b6fdade11/towncrier-25.8.0-py3-none-any.whl", hash = "sha256:b953d133d98f9aeae9084b56a3563fd2519dfc6ec33f61c9cd2c61ff243fb513", size = 65101, upload-time = "2025-08-30T11:41:53.644Z" }, +] + +[[package]] +name = "typer" +version = "0.27.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-doc" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "rich" }, + { name = "shellingham" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ae/40/4a3db7990d1f62a53182aa96eaef57aeb2886a27f90a195bc66713565d31/typer-0.27.1.tar.gz", hash = "sha256:a79bef8469a79c45498e7b814ecf8d603cc7644e9acbd9e19cac0334240b18df", size = 203994, upload-time = "2026-08-03T14:41:03.438Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/89/9518bc0c3929bee36b3a4a8e3daddd6e03f92f9961c66d4983b837160543/typer-0.27.1-py3-none-any.whl", hash = "sha256:53150287edd11baeb4e4722c8e394fcdf8181c0ae89485cba8d25c778d5edd56", size = 122874, upload-time = "2026-08-03T14:41:04.391Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "typing-inspection" +version = "0.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/55/e3/70399cb7dd41c10ac53367ae42139cf4b1ca5f36bb3dc6c9d33acdb43655/typing_inspection-0.4.2.tar.gz", hash = "sha256:ba561c48a67c5958007083d386c3295464928b01faa735ab8547c5692e87f464", size = 75949, upload-time = "2025-10-01T02:14:41.687Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dc/9b/47798a6c91d8bdb567fe2698fe81e0c6b7cb7ef4d13da4114b41d239f65d/typing_inspection-0.4.2-py3-none-any.whl", hash = "sha256:4ed1cacbdc298c220f1bd249ed5287caa16f34d44ef4e9c3d0cbad5b521545e7", size = 14611, upload-time = "2025-10-01T02:14:40.154Z" }, +] + +[[package]] +name = "universal-pathlib" +version = "0.3.10" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "fsspec" }, + { name = "pathlib-abc" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/3d/6e/d997a70ee8f4c61f9a7e2f4f8af721cf072a3326848fc881b05187e52558/universal_pathlib-0.3.10.tar.gz", hash = "sha256:4487cbc90730a48cfb64f811d99e14b6faed6d738420cd5f93f59f48e6930bfb", size = 261110, upload-time = "2026-02-22T14:40:58.87Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dd/1a/5d9a402b39ec892d856bbdd9db502ff73ce28cdf4aff72eb1ce1d6843506/universal_pathlib-0.3.10-py3-none-any.whl", hash = "sha256:dfaf2fb35683d2eb1287a3ed7b215e4d6016aa6eaf339c607023d22f90821c66", size = 83528, upload-time = "2026-02-22T14:40:57.316Z" }, +] + +[[package]] +name = "urllib3" +version = "2.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, +] + +[[package]] +name = "uv" +version = "0.12.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3c/fa/19a665278931fca142cf1c21927b18b36cffb5fd137bf5228f937a977f84/uv-0.12.3.tar.gz", hash = "sha256:1eb3fea456aea47489d92e10451c9129b7dd9fd8854c4eb17020ba68489d5d9a", size = 5877698, upload-time = "2026-08-07T16:33:32.486Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0e/b1/eabb1f57339a63630a9b195f8bcdbcca101f4f5cbc5556e6f592d6049d80/uv-0.12.3-py3-none-linux_armv6l.whl", hash = "sha256:0c0561cd369002a5968e138ea477e86507a337b3ede44f441c90d85ed2f54714", size = 21777249, upload-time = "2026-08-07T16:32:18.631Z" }, + { url = "https://files.pythonhosted.org/packages/ed/52/7d23602e140bdd5bb25ffa8bf3943a86688e8cd558a9894dfbb83728e943/uv-0.12.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:0550669163cc67d5a7dc8e1702bc011e4a075a4ae52ad50891be654fc6635e0d", size = 20081726, upload-time = "2026-08-07T16:32:23.182Z" }, + { url = "https://files.pythonhosted.org/packages/e4/66/ba257c91d69921d773f523c9e4c3ffb04e233694c415517f5ef797403a4f/uv-0.12.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:7c99f2524fe4b11d74dec85cef9b4d8b725d142dec04cd237f1c06fbdae1ee54", size = 18426262, upload-time = "2026-08-07T16:32:27.55Z" }, + { url = "https://files.pythonhosted.org/packages/c4/e4/7e93226f4f33c3cc25dc942056f46be9c48e846338f8644a700123726dc8/uv-0.12.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.musllinux_1_1_aarch64.whl", hash = "sha256:ac21bea426ddf95fa76d8dc1f67350faed7b4a81951825cf2aaef99fc4144815", size = 21156889, upload-time = "2026-08-07T16:32:31.447Z" }, + { url = "https://files.pythonhosted.org/packages/bd/b7/2504476931b7102cc6bfec5289efefe1279fe03964cb8ad7113691372605/uv-0.12.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.musllinux_1_1_armv7l.whl", hash = "sha256:1e569258e17a536c1bd90a68935dc8250b0ecc81ba80efd814ed169c33de0f93", size = 21319192, upload-time = "2026-08-07T16:32:35.638Z" }, + { url = "https://files.pythonhosted.org/packages/e3/83/e9a93bf4d737bf00d7fa4e2a82ed0ed23bc30d44262127f5f8b9a4dd9150/uv-0.12.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:6c8e5a2d2ce4ea511293f919357c427dab0f12104ebfdd6602727f5c38958c22", size = 21334826, upload-time = "2026-08-07T16:32:40.034Z" }, + { url = "https://files.pythonhosted.org/packages/5a/ef/19215f66a02451ca2698062e98690d5f2a7e65574104ba04c188c4b59c70/uv-0.12.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:115e96e176fa3525ffb999572ec6041b915f15189403613ccefcc1f128f0ea0c", size = 22014926, upload-time = "2026-08-07T16:32:44.159Z" }, + { url = "https://files.pythonhosted.org/packages/7c/a3/38526a97a5d376c59955025e54740ae35a4c7d8d80c6dfbee13fae588964/uv-0.12.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:913dc068e906f459df892cac789e6e9e10ac9d6af0bbb3c36fcc09347b0c986c", size = 23248637, upload-time = "2026-08-07T16:32:48.342Z" }, + { url = "https://files.pythonhosted.org/packages/38/63/a7a98d075383669b6a3ff4ca410cb9c18b6d0921df1c524bd0859a8474fe/uv-0.12.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:77fa7f501baa7c4d097b0c424914d7924db8e54f882c4f40056228ecf56feb98", size = 22929428, upload-time = "2026-08-07T16:32:52.452Z" }, + { url = "https://files.pythonhosted.org/packages/8d/c4/97fdd4fca11d06633bb500849f70e4e6b201bcba3833894732e709be2d60/uv-0.12.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1482d1462b1aecd18ee33627363fe1c63d6a194f12d40d37efc446d9e0d800a1", size = 22346263, upload-time = "2026-08-07T16:32:56.563Z" }, + { url = "https://files.pythonhosted.org/packages/c4/46/ab0906c8c3b6eeaf2412ab5af6077a38930db90e2c99c1b82e066f240a81/uv-0.12.3-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:248b6b282f96f98d79dddecd1b2acd1893efd84667321f26703feffff6433211", size = 21288225, upload-time = "2026-08-07T16:33:00.578Z" }, + { url = "https://files.pythonhosted.org/packages/2e/0f/f40530b0b336212fff1bc50887d263a9f03d8859e6c1c5210e11d104df10/uv-0.12.3-py3-none-manylinux_2_31_riscv64.musllinux_1_1_riscv64.whl", hash = "sha256:9201c7a1edadb07f64b695f17eac9db2d264eeb4b888c195aa11e7908d0ebf41", size = 21981757, upload-time = "2026-08-07T16:33:05.101Z" }, + { url = "https://files.pythonhosted.org/packages/0a/cf/240a3bebd15be490f867e155aa59522889d8d6310985421902f87d1fad99/uv-0.12.3-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:6114afd294411995a761c4cde0b721d550ff6d2fc2312046e8403eca6adacda5", size = 22117547, upload-time = "2026-08-07T16:33:09.124Z" }, + { url = "https://files.pythonhosted.org/packages/2f/da/fb143759f86b260f20634e11a27b9312eb6ff9c43c6756102e82875cd82d/uv-0.12.3-py3-none-musllinux_1_1_i686.whl", hash = "sha256:ba034f32abf966a101cf2434455faaf8d54dfacfff0d4b4c70d673f36e985728", size = 21255639, upload-time = "2026-08-07T16:33:13.38Z" }, + { url = "https://files.pythonhosted.org/packages/91/40/c1e0b626919792bf66847429d0c0bbf580a5f148a37268c10d9132f4871a/uv-0.12.3-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:13535c7d40faa7821c3763f5b6c605eef8556ea16277dc1a07a21203fd3c19e4", size = 22560342, upload-time = "2026-08-07T16:33:17.484Z" }, + { url = "https://files.pythonhosted.org/packages/fa/bf/246d088b4baf0239c8a06afa0ce155ce460942d08a9ac505fac5d0f99fe1/uv-0.12.3-py3-none-win32.whl", hash = "sha256:67b639a56dd36193b55a3bcea10f9dffcab37ed3c1eb26e964e52896df0bb205", size = 19420018, upload-time = "2026-08-07T16:33:21.544Z" }, + { url = "https://files.pythonhosted.org/packages/59/ed/3f816f972357578f1a21afdff8af9c93e87416afd0e150fc60be7eb280ab/uv-0.12.3-py3-none-win_amd64.whl", hash = "sha256:aeafd6e02b9a8d8beb447040bfc57ab172bdf244208f7147b4f7bbc327135797", size = 20215028, upload-time = "2026-08-07T16:33:25.751Z" }, + { url = "https://files.pythonhosted.org/packages/ff/63/0b08bf418b4d00e911465ad24a5f09040cc51247c362ffe56f859173e99f/uv-0.12.3-py3-none-win_arm64.whl", hash = "sha256:59121ef7217567adf4af41f7d3b04e42abb0c6a11bc87c930b838f9354f9c651", size = 19120228, upload-time = "2026-08-07T16:33:29.609Z" }, +] + +[[package]] +name = "verspec" +version = "0.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e7/44/8126f9f0c44319b2efc65feaad589cadef4d77ece200ae3c9133d58464d0/verspec-0.1.0.tar.gz", hash = "sha256:c4504ca697b2056cdb4bfa7121461f5a0e81809255b41c03dda4ba823637c01e", size = 27123, upload-time = "2020-11-30T02:24:09.646Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a4/ce/3b6fee91c85626eaf769d617f1be9d2e15c1cca027bbdeb2e0d751469355/verspec-0.1.0-py3-none-any.whl", hash = "sha256:741877d5633cc9464c45a469ae2a31e801e6dbbaa85b9675d481cda100f11c31", size = 19640, upload-time = "2020-11-30T02:24:08.387Z" }, +] + +[[package]] +name = "watchdog" +version = "6.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/db/7d/7f3d619e951c88ed75c6037b246ddcf2d322812ee8ea189be89511721d54/watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282", size = 131220, upload-time = "2024-11-01T14:07:13.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/ea/3930d07dafc9e286ed356a679aa02d777c06e9bfd1164fa7c19c288a5483/watchdog-6.0.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:bdd4e6f14b8b18c334febb9c4425a878a2ac20efd1e0b231978e7b150f92a948", size = 96471, upload-time = "2024-11-01T14:06:37.745Z" }, + { url = "https://files.pythonhosted.org/packages/12/87/48361531f70b1f87928b045df868a9fd4e253d9ae087fa4cf3f7113be363/watchdog-6.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c7c15dda13c4eb00d6fb6fc508b3c0ed88b9d5d374056b239c4ad1611125c860", size = 88449, upload-time = "2024-11-01T14:06:39.748Z" }, + { url = "https://files.pythonhosted.org/packages/5b/7e/8f322f5e600812e6f9a31b75d242631068ca8f4ef0582dd3ae6e72daecc8/watchdog-6.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6f10cb2d5902447c7d0da897e2c6768bca89174d0c6e1e30abec5421af97a5b0", size = 89054, upload-time = "2024-11-01T14:06:41.009Z" }, + { url = "https://files.pythonhosted.org/packages/68/98/b0345cabdce2041a01293ba483333582891a3bd5769b08eceb0d406056ef/watchdog-6.0.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:490ab2ef84f11129844c23fb14ecf30ef3d8a6abafd3754a6f75ca1e6654136c", size = 96480, upload-time = "2024-11-01T14:06:42.952Z" }, + { url = "https://files.pythonhosted.org/packages/85/83/cdf13902c626b28eedef7ec4f10745c52aad8a8fe7eb04ed7b1f111ca20e/watchdog-6.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:76aae96b00ae814b181bb25b1b98076d5fc84e8a53cd8885a318b42b6d3a5134", size = 88451, upload-time = "2024-11-01T14:06:45.084Z" }, + { url = "https://files.pythonhosted.org/packages/fe/c4/225c87bae08c8b9ec99030cd48ae9c4eca050a59bf5c2255853e18c87b50/watchdog-6.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a175f755fc2279e0b7312c0035d52e27211a5bc39719dd529625b1930917345b", size = 89057, upload-time = "2024-11-01T14:06:47.324Z" }, + { url = "https://files.pythonhosted.org/packages/a9/c7/ca4bf3e518cb57a686b2feb4f55a1892fd9a3dd13f470fca14e00f80ea36/watchdog-6.0.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7607498efa04a3542ae3e05e64da8202e58159aa1fa4acddf7678d34a35d4f13", size = 79079, upload-time = "2024-11-01T14:06:59.472Z" }, + { url = "https://files.pythonhosted.org/packages/5c/51/d46dc9332f9a647593c947b4b88e2381c8dfc0942d15b8edc0310fa4abb1/watchdog-6.0.0-py3-none-manylinux2014_armv7l.whl", hash = "sha256:9041567ee8953024c83343288ccc458fd0a2d811d6a0fd68c4c22609e3490379", size = 79078, upload-time = "2024-11-01T14:07:01.431Z" }, + { url = "https://files.pythonhosted.org/packages/d4/57/04edbf5e169cd318d5f07b4766fee38e825d64b6913ca157ca32d1a42267/watchdog-6.0.0-py3-none-manylinux2014_i686.whl", hash = "sha256:82dc3e3143c7e38ec49d61af98d6558288c415eac98486a5c581726e0737c00e", size = 79076, upload-time = "2024-11-01T14:07:02.568Z" }, + { url = "https://files.pythonhosted.org/packages/ab/cc/da8422b300e13cb187d2203f20b9253e91058aaf7db65b74142013478e66/watchdog-6.0.0-py3-none-manylinux2014_ppc64.whl", hash = "sha256:212ac9b8bf1161dc91bd09c048048a95ca3a4c4f5e5d4a7d1b1a7d5752a7f96f", size = 79077, upload-time = "2024-11-01T14:07:03.893Z" }, + { url = "https://files.pythonhosted.org/packages/2c/3b/b8964e04ae1a025c44ba8e4291f86e97fac443bca31de8bd98d3263d2fcf/watchdog-6.0.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:e3df4cbb9a450c6d49318f6d14f4bbc80d763fa587ba46ec86f99f9e6876bb26", size = 79078, upload-time = "2024-11-01T14:07:05.189Z" }, + { url = "https://files.pythonhosted.org/packages/62/ae/a696eb424bedff7407801c257d4b1afda455fe40821a2be430e173660e81/watchdog-6.0.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:2cce7cfc2008eb51feb6aab51251fd79b85d9894e98ba847408f662b3395ca3c", size = 79077, upload-time = "2024-11-01T14:07:06.376Z" }, + { url = "https://files.pythonhosted.org/packages/b5/e8/dbf020b4d98251a9860752a094d09a65e1b436ad181faf929983f697048f/watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:20ffe5b202af80ab4266dcd3e91aae72bf2da48c0d33bdb15c66658e685e94e2", size = 79078, upload-time = "2024-11-01T14:07:07.547Z" }, + { url = "https://files.pythonhosted.org/packages/07/f6/d0e5b343768e8bcb4cda79f0f2f55051bf26177ecd5651f84c07567461cf/watchdog-6.0.0-py3-none-win32.whl", hash = "sha256:07df1fdd701c5d4c8e55ef6cf55b8f0120fe1aef7ef39a1c6fc6bc2e606d517a", size = 79065, upload-time = "2024-11-01T14:07:09.525Z" }, + { url = "https://files.pythonhosted.org/packages/db/d9/c495884c6e548fce18a8f40568ff120bc3a4b7b99813081c8ac0c936fa64/watchdog-6.0.0-py3-none-win_amd64.whl", hash = "sha256:cbafb470cf848d93b5d013e2ecb245d4aa1c8fd0504e863ccefa32445359d680", size = 79070, upload-time = "2024-11-01T14:07:10.686Z" }, + { url = "https://files.pythonhosted.org/packages/33/e8/e40370e6d74ddba47f002a32919d91310d6074130fe4e17dabcafc15cbf1/watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f", size = 79067, upload-time = "2024-11-01T14:07:11.845Z" }, +] + +[[package]] +name = "webencodings" +version = "0.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0b/02/ae6ceac1baeda530866a85075641cec12989bd8d31af6d5ab4a3e8c92f47/webencodings-0.5.1.tar.gz", hash = "sha256:b36a1c245f2d304965eb4e0a82848379241dc04b865afcc4aab16748587e1923", size = 9721, upload-time = "2017-04-05T20:21:34.189Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/24/2a3e3df732393fed8b3ebf2ec078f05546de641fe1b667ee316ec1dcf3b7/webencodings-0.5.1-py2.py3-none-any.whl", hash = "sha256:a0af1213f3c2226497a97e2b3aa01a7e4bee4f403f95be16fc9acd2947514a78", size = 11774, upload-time = "2017-04-05T20:21:32.581Z" }, +] + +[[package]] +name = "werkzeug" +version = "3.1.8" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/dd/b2/381be8cfdee792dd117872481b6e378f85c957dd7c5bca38897b08f765fd/werkzeug-3.1.8.tar.gz", hash = "sha256:9bad61a4268dac112f1c5cd4630a56ede601b6ed420300677a869083d70a4c44", size = 875852, upload-time = "2026-04-02T18:49:14.268Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/93/8c/2e650f2afeb7ee576912636c23ddb621c91ac6a98e66dc8d29c3c69446e1/werkzeug-3.1.8-py3-none-any.whl", hash = "sha256:63a77fb8892bf28ebc3178683445222aa500e48ebad5ec77b0ad80f8726b1f50", size = 226459, upload-time = "2026-04-02T18:49:12.72Z" }, +] + +[[package]] +name = "wrapt" +version = "2.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2e/64/925f213fdcbb9baeb1530449ac71a4d57fc361c053d06bf78d0c5c7cd80c/wrapt-2.1.2.tar.gz", hash = "sha256:3996a67eecc2c68fd47b4e3c564405a5777367adfd9b8abb58387b63ee83b21e", size = 81678, upload-time = "2026-03-06T02:53:25.134Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4c/b6/1db817582c49c7fcbb7df6809d0f515af29d7c2fbf57eb44c36e98fb1492/wrapt-2.1.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ff2aad9c4cda28a8f0653fc2d487596458c2a3f475e56ba02909e950a9efa6a9", size = 61255, upload-time = "2026-03-06T02:52:45.663Z" }, + { url = "https://files.pythonhosted.org/packages/a2/16/9b02a6b99c09227c93cd4b73acc3678114154ec38da53043c0ddc1fba0dc/wrapt-2.1.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6433ea84e1cfacf32021d2a4ee909554ade7fd392caa6f7c13f1f4bf7b8e8748", size = 61848, upload-time = "2026-03-06T02:53:48.728Z" }, + { url = "https://files.pythonhosted.org/packages/af/aa/ead46a88f9ec3a432a4832dfedb84092fc35af2d0ba40cd04aea3889f247/wrapt-2.1.2-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:c20b757c268d30d6215916a5fa8461048d023865d888e437fab451139cad6c8e", size = 121433, upload-time = "2026-03-06T02:54:40.328Z" }, + { url = "https://files.pythonhosted.org/packages/3a/9f/742c7c7cdf58b59085a1ee4b6c37b013f66ac33673a7ef4aaed5e992bc33/wrapt-2.1.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:79847b83eb38e70d93dc392c7c5b587efe65b3e7afcc167aa8abd5d60e8761c8", size = 123013, upload-time = "2026-03-06T02:53:26.58Z" }, + { url = "https://files.pythonhosted.org/packages/e8/44/2c3dd45d53236b7ed7c646fcf212251dc19e48e599debd3926b52310fafb/wrapt-2.1.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f8fba1bae256186a83d1875b2b1f4e2d1242e8fac0f58ec0d7e41b26967b965c", size = 117326, upload-time = "2026-03-06T02:53:11.547Z" }, + { url = "https://files.pythonhosted.org/packages/74/e2/b17d66abc26bd96f89dec0ecd0ef03da4a1286e6ff793839ec431b9fae57/wrapt-2.1.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e3d3b35eedcf5f7d022291ecd7533321c4775f7b9cd0050a31a68499ba45757c", size = 121444, upload-time = "2026-03-06T02:54:09.5Z" }, + { url = "https://files.pythonhosted.org/packages/3c/62/e2977843fdf9f03daf1586a0ff49060b1b2fc7ff85a7ea82b6217c1ae36e/wrapt-2.1.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:6f2c5390460de57fa9582bc8a1b7a6c86e1a41dfad74c5225fc07044c15cc8d1", size = 116237, upload-time = "2026-03-06T02:54:03.884Z" }, + { url = "https://files.pythonhosted.org/packages/88/dd/27fc67914e68d740bce512f11734aec08696e6b17641fef8867c00c949fc/wrapt-2.1.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7dfa9f2cf65d027b951d05c662cc99ee3bd01f6e4691ed39848a7a5fffc902b2", size = 120563, upload-time = "2026-03-06T02:53:20.412Z" }, + { url = "https://files.pythonhosted.org/packages/ec/9f/b750b3692ed2ef4705cb305bd68858e73010492b80e43d2a4faa5573cbe7/wrapt-2.1.2-cp312-cp312-win32.whl", hash = "sha256:eba8155747eb2cae4a0b913d9ebd12a1db4d860fc4c829d7578c7b989bd3f2f0", size = 58198, upload-time = "2026-03-06T02:53:37.732Z" }, + { url = "https://files.pythonhosted.org/packages/8e/b2/feecfe29f28483d888d76a48f03c4c4d8afea944dbee2b0cd3380f9df032/wrapt-2.1.2-cp312-cp312-win_amd64.whl", hash = "sha256:1c51c738d7d9faa0b3601708e7e2eda9bf779e1b601dce6c77411f2a1b324a63", size = 60441, upload-time = "2026-03-06T02:52:47.138Z" }, + { url = "https://files.pythonhosted.org/packages/44/e1/e328f605d6e208547ea9fd120804fcdec68536ac748987a68c47c606eea8/wrapt-2.1.2-cp312-cp312-win_arm64.whl", hash = "sha256:c8e46ae8e4032792eb2f677dbd0d557170a8e5524d22acc55199f43efedd39bf", size = 58836, upload-time = "2026-03-06T02:53:22.053Z" }, + { url = "https://files.pythonhosted.org/packages/4c/7a/d936840735c828b38d26a854e85d5338894cda544cb7a85a9d5b8b9c4df7/wrapt-2.1.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:787fd6f4d67befa6fe2abdffcbd3de2d82dfc6fb8a6d850407c53332709d030b", size = 61259, upload-time = "2026-03-06T02:53:41.922Z" }, + { url = "https://files.pythonhosted.org/packages/5e/88/9a9b9a90ac8ca11c2fdb6a286cb3a1fc7dd774c00ed70929a6434f6bc634/wrapt-2.1.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:4bdf26e03e6d0da3f0e9422fd36bcebf7bc0eeb55fdf9c727a09abc6b9fe472e", size = 61851, upload-time = "2026-03-06T02:52:48.672Z" }, + { url = "https://files.pythonhosted.org/packages/03/a9/5b7d6a16fd6533fed2756900fc8fc923f678179aea62ada6d65c92718c00/wrapt-2.1.2-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:bbac24d879aa22998e87f6b3f481a5216311e7d53c7db87f189a7a0266dafffb", size = 121446, upload-time = "2026-03-06T02:54:14.013Z" }, + { url = "https://files.pythonhosted.org/packages/45/bb/34c443690c847835cfe9f892be78c533d4f32366ad2888972c094a897e39/wrapt-2.1.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:16997dfb9d67addc2e3f41b62a104341e80cac52f91110dece393923c0ebd5ca", size = 123056, upload-time = "2026-03-06T02:54:10.829Z" }, + { url = "https://files.pythonhosted.org/packages/93/b9/ff205f391cb708f67f41ea148545f2b53ff543a7ac293b30d178af4d2271/wrapt-2.1.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:162e4e2ba7542da9027821cb6e7c5e068d64f9a10b5f15512ea28e954893a267", size = 117359, upload-time = "2026-03-06T02:53:03.623Z" }, + { url = "https://files.pythonhosted.org/packages/1f/3d/1ea04d7747825119c3c9a5e0874a40b33594ada92e5649347c457d982805/wrapt-2.1.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f29c827a8d9936ac320746747a016c4bc66ef639f5cd0d32df24f5eacbf9c69f", size = 121479, upload-time = "2026-03-06T02:53:45.844Z" }, + { url = "https://files.pythonhosted.org/packages/78/cc/ee3a011920c7a023b25e8df26f306b2484a531ab84ca5c96260a73de76c0/wrapt-2.1.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:a9dd9813825f7ecb018c17fd147a01845eb330254dff86d3b5816f20f4d6aaf8", size = 116271, upload-time = "2026-03-06T02:54:46.356Z" }, + { url = "https://files.pythonhosted.org/packages/98/fd/e5ff7ded41b76d802cf1191288473e850d24ba2e39a6ec540f21ae3b57cb/wrapt-2.1.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6f8dbdd3719e534860d6a78526aafc220e0241f981367018c2875178cf83a413", size = 120573, upload-time = "2026-03-06T02:52:50.163Z" }, + { url = "https://files.pythonhosted.org/packages/47/c5/242cae3b5b080cd09bacef0591691ba1879739050cc7c801ff35c8886b66/wrapt-2.1.2-cp313-cp313-win32.whl", hash = "sha256:5c35b5d82b16a3bc6e0a04349b606a0582bc29f573786aebe98e0c159bc48db6", size = 58205, upload-time = "2026-03-06T02:53:47.494Z" }, + { url = "https://files.pythonhosted.org/packages/12/69/c358c61e7a50f290958809b3c61ebe8b3838ea3e070d7aac9814f95a0528/wrapt-2.1.2-cp313-cp313-win_amd64.whl", hash = "sha256:f8bc1c264d8d1cf5b3560a87bbdd31131573eb25f9f9447bb6252b8d4c44a3a1", size = 60452, upload-time = "2026-03-06T02:53:30.038Z" }, + { url = "https://files.pythonhosted.org/packages/8e/66/c8a6fcfe321295fd8c0ab1bd685b5a01462a9b3aa2f597254462fc2bc975/wrapt-2.1.2-cp313-cp313-win_arm64.whl", hash = "sha256:3beb22f674550d5634642c645aba4c72a2c66fb185ae1aebe1e955fae5a13baf", size = 58842, upload-time = "2026-03-06T02:52:52.114Z" }, + { url = "https://files.pythonhosted.org/packages/da/55/9c7052c349106e0b3f17ae8db4b23a691a963c334de7f9dbd60f8f74a831/wrapt-2.1.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0fc04bc8664a8bc4c8e00b37b5355cffca2535209fba1abb09ae2b7c76ddf82b", size = 63075, upload-time = "2026-03-06T02:53:19.108Z" }, + { url = "https://files.pythonhosted.org/packages/09/a8/ce7b4006f7218248dd71b7b2b732d0710845a0e49213b18faef64811ffef/wrapt-2.1.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:a9b9d50c9af998875a1482a038eb05755dfd6fe303a313f6a940bb53a83c3f18", size = 63719, upload-time = "2026-03-06T02:54:33.452Z" }, + { url = "https://files.pythonhosted.org/packages/e4/e5/2ca472e80b9e2b7a17f106bb8f9df1db11e62101652ce210f66935c6af67/wrapt-2.1.2-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2d3ff4f0024dd224290c0eabf0240f1bfc1f26363431505fb1b0283d3b08f11d", size = 152643, upload-time = "2026-03-06T02:52:42.721Z" }, + { url = "https://files.pythonhosted.org/packages/36/42/30f0f2cefca9d9cbf6835f544d825064570203c3e70aa873d8ae12e23791/wrapt-2.1.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3278c471f4468ad544a691b31bb856374fbdefb7fee1a152153e64019379f015", size = 158805, upload-time = "2026-03-06T02:54:25.441Z" }, + { url = "https://files.pythonhosted.org/packages/bb/67/d08672f801f604889dcf58f1a0b424fe3808860ede9e03affc1876b295af/wrapt-2.1.2-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a8914c754d3134a3032601c6984db1c576e6abaf3fc68094bb8ab1379d75ff92", size = 145990, upload-time = "2026-03-06T02:53:57.456Z" }, + { url = "https://files.pythonhosted.org/packages/68/a7/fd371b02e73babec1de6ade596e8cd9691051058cfdadbfd62a5898f3295/wrapt-2.1.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:ff95d4264e55839be37bafe1536db2ab2de19da6b65f9244f01f332b5286cfbf", size = 155670, upload-time = "2026-03-06T02:54:55.309Z" }, + { url = "https://files.pythonhosted.org/packages/86/2d/9fe0095dfdb621009f40117dcebf41d7396c2c22dca6eac779f4c007b86c/wrapt-2.1.2-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:76405518ca4e1b76fbb1b9f686cff93aebae03920cc55ceeec48ff9f719c5f67", size = 144357, upload-time = "2026-03-06T02:54:24.092Z" }, + { url = "https://files.pythonhosted.org/packages/0e/b6/ec7b4a254abbe4cde9fa15c5d2cca4518f6b07d0f1b77d4ee9655e30280e/wrapt-2.1.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:c0be8b5a74c5824e9359b53e7e58bef71a729bacc82e16587db1c4ebc91f7c5a", size = 150269, upload-time = "2026-03-06T02:53:31.268Z" }, + { url = "https://files.pythonhosted.org/packages/6e/6b/2fabe8ebf148f4ee3c782aae86a795cc68ffe7d432ef550f234025ce0cfa/wrapt-2.1.2-cp313-cp313t-win32.whl", hash = "sha256:f01277d9a5fc1862f26f7626da9cf443bebc0abd2f303f41c5e995b15887dabd", size = 59894, upload-time = "2026-03-06T02:54:15.391Z" }, + { url = "https://files.pythonhosted.org/packages/ca/fb/9ba66fc2dedc936de5f8073c0217b5d4484e966d87723415cc8262c5d9c2/wrapt-2.1.2-cp313-cp313t-win_amd64.whl", hash = "sha256:84ce8f1c2104d2f6daa912b1b5b039f331febfeee74f8042ad4e04992bd95c8f", size = 63197, upload-time = "2026-03-06T02:54:41.943Z" }, + { url = "https://files.pythonhosted.org/packages/c0/1c/012d7423c95d0e337117723eb8ecf73c622ce15a97847e84cf3f8f26cd7e/wrapt-2.1.2-cp313-cp313t-win_arm64.whl", hash = "sha256:a93cd767e37faeddbe07d8fc4212d5cba660af59bdb0f6372c93faaa13e6e679", size = 60363, upload-time = "2026-03-06T02:54:48.093Z" }, + { url = "https://files.pythonhosted.org/packages/39/25/e7ea0b417db02bb796182a5316398a75792cd9a22528783d868755e1f669/wrapt-2.1.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:1370e516598854e5b4366e09ce81e08bfe94d42b0fd569b88ec46cc56d9164a9", size = 61418, upload-time = "2026-03-06T02:53:55.706Z" }, + { url = "https://files.pythonhosted.org/packages/ec/0f/fa539e2f6a770249907757eaeb9a5ff4deb41c026f8466c1c6d799088a9b/wrapt-2.1.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:6de1a3851c27e0bd6a04ca993ea6f80fc53e6c742ee1601f486c08e9f9b900a9", size = 61914, upload-time = "2026-03-06T02:52:53.37Z" }, + { url = "https://files.pythonhosted.org/packages/53/37/02af1867f5b1441aaeda9c82deed061b7cd1372572ddcd717f6df90b5e93/wrapt-2.1.2-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:de9f1a2bbc5ac7f6012ec24525bdd444765a2ff64b5985ac6e0692144838542e", size = 120417, upload-time = "2026-03-06T02:54:30.74Z" }, + { url = "https://files.pythonhosted.org/packages/c3/b7/0138a6238c8ba7476c77cf786a807f871672b37f37a422970342308276e7/wrapt-2.1.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:970d57ed83fa040d8b20c52fe74a6ae7e3775ae8cff5efd6a81e06b19078484c", size = 122797, upload-time = "2026-03-06T02:54:51.539Z" }, + { url = "https://files.pythonhosted.org/packages/e1/ad/819ae558036d6a15b7ed290d5b14e209ca795dd4da9c58e50c067d5927b0/wrapt-2.1.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:3969c56e4563c375861c8df14fa55146e81ac11c8db49ea6fb7f2ba58bc1ff9a", size = 117350, upload-time = "2026-03-06T02:54:37.651Z" }, + { url = "https://files.pythonhosted.org/packages/8b/2d/afc18dc57a4600a6e594f77a9ae09db54f55ba455440a54886694a84c71b/wrapt-2.1.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:57d7c0c980abdc5f1d98b11a2aa3bb159790add80258c717fa49a99921456d90", size = 121223, upload-time = "2026-03-06T02:54:35.221Z" }, + { url = "https://files.pythonhosted.org/packages/b9/5b/5ec189b22205697bc56eb3b62aed87a1e0423e9c8285d0781c7a83170d15/wrapt-2.1.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:776867878e83130c7a04237010463372e877c1c994d449ca6aaafeab6aab2586", size = 116287, upload-time = "2026-03-06T02:54:19.654Z" }, + { url = "https://files.pythonhosted.org/packages/f7/2d/f84939a7c9b5e6cdd8a8d0f6a26cabf36a0f7e468b967720e8b0cd2bdf69/wrapt-2.1.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:fab036efe5464ec3291411fabb80a7a39e2dd80bae9bcbeeca5087fdfa891e19", size = 119593, upload-time = "2026-03-06T02:54:16.697Z" }, + { url = "https://files.pythonhosted.org/packages/0b/fe/ccd22a1263159c4ac811ab9374c061bcb4a702773f6e06e38de5f81a1bdc/wrapt-2.1.2-cp314-cp314-win32.whl", hash = "sha256:e6ed62c82ddf58d001096ae84ce7f833db97ae2263bff31c9b336ba8cfe3f508", size = 58631, upload-time = "2026-03-06T02:53:06.498Z" }, + { url = "https://files.pythonhosted.org/packages/65/0a/6bd83be7bff2e7efaac7b4ac9748da9d75a34634bbbbc8ad077d527146df/wrapt-2.1.2-cp314-cp314-win_amd64.whl", hash = "sha256:467e7c76315390331c67073073d00662015bb730c566820c9ca9b54e4d67fd04", size = 60875, upload-time = "2026-03-06T02:53:50.252Z" }, + { url = "https://files.pythonhosted.org/packages/6c/c0/0b3056397fe02ff80e5a5d72d627c11eb885d1ca78e71b1a5c1e8c7d45de/wrapt-2.1.2-cp314-cp314-win_arm64.whl", hash = "sha256:da1f00a557c66225d53b095a97eace0fc5349e3bfda28fa34ffae238978ee575", size = 59164, upload-time = "2026-03-06T02:53:59.128Z" }, + { url = "https://files.pythonhosted.org/packages/71/ed/5d89c798741993b2371396eb9d4634f009ff1ad8a6c78d366fe2883ea7a6/wrapt-2.1.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:62503ffbc2d3a69891cf29beeaccdb4d5e0a126e2b6a851688d4777e01428dbb", size = 63163, upload-time = "2026-03-06T02:52:54.873Z" }, + { url = "https://files.pythonhosted.org/packages/c6/8c/05d277d182bf36b0a13d6bd393ed1dec3468a25b59d01fba2dd70fe4d6ae/wrapt-2.1.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c7e6cd120ef837d5b6f860a6ea3745f8763805c418bb2f12eeb1fa6e25f22d22", size = 63723, upload-time = "2026-03-06T02:52:56.374Z" }, + { url = "https://files.pythonhosted.org/packages/f4/27/6c51ec1eff4413c57e72d6106bb8dec6f0c7cdba6503d78f0fa98767bcc9/wrapt-2.1.2-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3769a77df8e756d65fbc050333f423c01ae012b4f6731aaf70cf2bef61b34596", size = 152652, upload-time = "2026-03-06T02:53:23.79Z" }, + { url = "https://files.pythonhosted.org/packages/db/4c/d7dd662d6963fc7335bfe29d512b02b71cdfa23eeca7ab3ac74a67505deb/wrapt-2.1.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a76d61a2e851996150ba0f80582dd92a870643fa481f3b3846f229de88caf044", size = 158807, upload-time = "2026-03-06T02:53:35.742Z" }, + { url = "https://files.pythonhosted.org/packages/b4/4d/1e5eea1a78d539d346765727422976676615814029522c76b87a95f6bcdd/wrapt-2.1.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6f97edc9842cf215312b75fe737ee7c8adda75a89979f8e11558dfff6343cc4b", size = 146061, upload-time = "2026-03-06T02:52:57.574Z" }, + { url = "https://files.pythonhosted.org/packages/89/bc/62cabea7695cd12a288023251eeefdcb8465056ddaab6227cb78a2de005b/wrapt-2.1.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:4006c351de6d5007aa33a551f600404ba44228a89e833d2fadc5caa5de8edfbf", size = 155667, upload-time = "2026-03-06T02:53:39.422Z" }, + { url = "https://files.pythonhosted.org/packages/e9/99/6f2888cd68588f24df3a76572c69c2de28287acb9e1972bf0c83ce97dbc1/wrapt-2.1.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:a9372fc3639a878c8e7d87e1556fa209091b0a66e912c611e3f833e2c4202be2", size = 144392, upload-time = "2026-03-06T02:54:22.41Z" }, + { url = "https://files.pythonhosted.org/packages/40/51/1dfc783a6c57971614c48e361a82ca3b6da9055879952587bc99fe1a7171/wrapt-2.1.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3144b027ff30cbd2fca07c0a87e67011adb717eb5f5bd8496325c17e454257a3", size = 150296, upload-time = "2026-03-06T02:54:07.848Z" }, + { url = "https://files.pythonhosted.org/packages/6c/38/cbb8b933a0201076c1f64fc42883b0023002bdc14a4964219154e6ff3350/wrapt-2.1.2-cp314-cp314t-win32.whl", hash = "sha256:3b8d15e52e195813efe5db8cec156eebe339aaf84222f4f4f051a6c01f237ed7", size = 60539, upload-time = "2026-03-06T02:54:00.594Z" }, + { url = "https://files.pythonhosted.org/packages/82/dd/e5176e4b241c9f528402cebb238a36785a628179d7d8b71091154b3e4c9e/wrapt-2.1.2-cp314-cp314t-win_amd64.whl", hash = "sha256:08ffa54146a7559f5b8df4b289b46d963a8e74ed16ba3687f99896101a3990c5", size = 63969, upload-time = "2026-03-06T02:54:39Z" }, + { url = "https://files.pythonhosted.org/packages/5c/99/79f17046cf67e4a95b9987ea129632ba8bcec0bc81f3fb3d19bdb0bd60cd/wrapt-2.1.2-cp314-cp314t-win_arm64.whl", hash = "sha256:72aaa9d0d8e4ed0e2e98019cea47a21f823c9dd4b43c7b77bba6679ffcca6a00", size = 60554, upload-time = "2026-03-06T02:53:14.132Z" }, + { url = "https://files.pythonhosted.org/packages/1a/c7/8528ac2dfa2c1e6708f647df7ae144ead13f0a31146f43c7264b4942bf12/wrapt-2.1.2-py3-none-any.whl", hash = "sha256:b8fd6fa2b2c4e7621808f8c62e8317f4aae56e59721ad933bac5239d913cf0e8", size = 43993, upload-time = "2026-03-06T02:53:12.905Z" }, +] + +[[package]] +name = "xmltodict" +version = "1.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/19/70/80f3b7c10d2630aa66414bf23d210386700aa390547278c789afa994fd7e/xmltodict-1.0.4.tar.gz", hash = "sha256:6d94c9f834dd9e44514162799d344d815a3a4faec913717a9ecbfa5be1bb8e61", size = 26124, upload-time = "2026-02-22T02:21:22.074Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/34/98a2f52245f4d47be93b580dae5f9861ef58977d73a79eb47c58f1ad1f3a/xmltodict-1.0.4-py3-none-any.whl", hash = "sha256:a4a00d300b0e1c59fc2bfccb53d7b2e88c32f200df138a0dd2229f842497026a", size = 13580, upload-time = "2026-02-22T02:21:21.039Z" }, +] + +[[package]] +name = "yarl" +version = "1.23.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "multidict" }, + { name = "propcache" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/23/6e/beb1beec874a72f23815c1434518bfc4ed2175065173fb138c3705f658d4/yarl-1.23.0.tar.gz", hash = "sha256:53b1ea6ca88ebd4420379c330aea57e258408dd0df9af0992e5de2078dc9f5d5", size = 194676, upload-time = "2026-03-01T22:07:53.373Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/8a/94615bc31022f711add374097ad4144d569e95ff3c38d39215d07ac153a0/yarl-1.23.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:1932b6b8bba8d0160a9d1078aae5838a66039e8832d41d2992daa9a3a08f7860", size = 124737, upload-time = "2026-03-01T22:05:12.897Z" }, + { url = "https://files.pythonhosted.org/packages/e3/6f/c6554045d59d64052698add01226bc867b52fe4a12373415d7991fdca95d/yarl-1.23.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:411225bae281f114067578891bc75534cfb3d92a3b4dfef7a6ca78ba354e6069", size = 87029, upload-time = "2026-03-01T22:05:14.376Z" }, + { url = "https://files.pythonhosted.org/packages/19/2a/725ecc166d53438bc88f76822ed4b1e3b10756e790bafd7b523fe97c322d/yarl-1.23.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:13a563739ae600a631c36ce096615fe307f131344588b0bc0daec108cdb47b25", size = 86310, upload-time = "2026-03-01T22:05:15.71Z" }, + { url = "https://files.pythonhosted.org/packages/99/30/58260ed98e6ff7f90ba84442c1ddd758c9170d70327394a6227b310cd60f/yarl-1.23.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9cbf44c5cb4a7633d078788e1b56387e3d3cf2b8139a3be38040b22d6c3221c8", size = 97587, upload-time = "2026-03-01T22:05:17.384Z" }, + { url = "https://files.pythonhosted.org/packages/76/0a/8b08aac08b50682e65759f7f8dde98ae8168f72487e7357a5d684c581ef9/yarl-1.23.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:53ad387048f6f09a8969631e4de3f1bf70c50e93545d64af4f751b2498755072", size = 92528, upload-time = "2026-03-01T22:05:18.804Z" }, + { url = "https://files.pythonhosted.org/packages/52/07/0b7179101fe5f8385ec6c6bb5d0cb9f76bd9fb4a769591ab6fb5cdbfc69a/yarl-1.23.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4a59ba56f340334766f3a4442e0efd0af895fae9e2b204741ef885c446b3a1a8", size = 105339, upload-time = "2026-03-01T22:05:20.235Z" }, + { url = "https://files.pythonhosted.org/packages/d3/8a/36d82869ab5ec829ca8574dfcb92b51286fcfb1e9c7a73659616362dc880/yarl-1.23.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:803a3c3ce4acc62eaf01eaca1208dcf0783025ef27572c3336502b9c232005e7", size = 105061, upload-time = "2026-03-01T22:05:22.268Z" }, + { url = "https://files.pythonhosted.org/packages/66/3e/868e5c3364b6cee19ff3e1a122194fa4ce51def02c61023970442162859e/yarl-1.23.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a3d2bff8f37f8d0f96c7ec554d16945050d54462d6e95414babaa18bfafc7f51", size = 100132, upload-time = "2026-03-01T22:05:23.638Z" }, + { url = "https://files.pythonhosted.org/packages/cf/26/9c89acf82f08a52cb52d6d39454f8d18af15f9d386a23795389d1d423823/yarl-1.23.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c75eb09e8d55bceb4367e83496ff8ef2bc7ea6960efb38e978e8073ea59ecb67", size = 99289, upload-time = "2026-03-01T22:05:25.749Z" }, + { url = "https://files.pythonhosted.org/packages/6f/54/5b0db00d2cb056922356104468019c0a132e89c8d3ab67d8ede9f4483d2a/yarl-1.23.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:877b0738624280e34c55680d6054a307aa94f7d52fa0e3034a9cc6e790871da7", size = 96950, upload-time = "2026-03-01T22:05:27.318Z" }, + { url = "https://files.pythonhosted.org/packages/f6/40/10fa93811fd439341fad7e0718a86aca0de9548023bbb403668d6555acab/yarl-1.23.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:b5405bb8f0e783a988172993cfc627e4d9d00432d6bbac65a923041edacf997d", size = 93960, upload-time = "2026-03-01T22:05:28.738Z" }, + { url = "https://files.pythonhosted.org/packages/bc/d2/8ae2e6cd77d0805f4526e30ec43b6f9a3dfc542d401ac4990d178e4bf0cf/yarl-1.23.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1c3a3598a832590c5a3ce56ab5576361b5688c12cb1d39429cf5dba30b510760", size = 104703, upload-time = "2026-03-01T22:05:30.438Z" }, + { url = "https://files.pythonhosted.org/packages/2f/0c/b3ceacf82c3fe21183ce35fa2acf5320af003d52bc1fcf5915077681142e/yarl-1.23.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:8419ebd326430d1cbb7efb5292330a2cf39114e82df5cc3d83c9a0d5ebeaf2f2", size = 98325, upload-time = "2026-03-01T22:05:31.835Z" }, + { url = "https://files.pythonhosted.org/packages/9d/e0/12900edd28bdab91a69bd2554b85ad7b151f64e8b521fe16f9ad2f56477a/yarl-1.23.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:be61f6fff406ca40e3b1d84716fde398fc08bc63dd96d15f3a14230a0973ed86", size = 105067, upload-time = "2026-03-01T22:05:33.358Z" }, + { url = "https://files.pythonhosted.org/packages/15/61/74bb1182cf79c9bbe4eb6b1f14a57a22d7a0be5e9cedf8e2d5c2086474c3/yarl-1.23.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3ceb13c5c858d01321b5d9bb65e4cf37a92169ea470b70fec6f236b2c9dd7e34", size = 100285, upload-time = "2026-03-01T22:05:35.4Z" }, + { url = "https://files.pythonhosted.org/packages/69/7f/cd5ef733f2550de6241bd8bd8c3febc78158b9d75f197d9c7baa113436af/yarl-1.23.0-cp312-cp312-win32.whl", hash = "sha256:fffc45637bcd6538de8b85f51e3df3223e4ad89bccbfca0481c08c7fc8b7ed7d", size = 82359, upload-time = "2026-03-01T22:05:36.811Z" }, + { url = "https://files.pythonhosted.org/packages/f5/be/25216a49daeeb7af2bec0db22d5e7df08ed1d7c9f65d78b14f3b74fd72fc/yarl-1.23.0-cp312-cp312-win_amd64.whl", hash = "sha256:f69f57305656a4852f2a7203efc661d8c042e6cc67f7acd97d8667fb448a426e", size = 87674, upload-time = "2026-03-01T22:05:38.171Z" }, + { url = "https://files.pythonhosted.org/packages/d2/35/aeab955d6c425b227d5b7247eafb24f2653fedc32f95373a001af5dfeb9e/yarl-1.23.0-cp312-cp312-win_arm64.whl", hash = "sha256:6e87a6e8735b44816e7db0b2fbc9686932df473c826b0d9743148432e10bb9b9", size = 81879, upload-time = "2026-03-01T22:05:40.006Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4b/a0a6e5d0ee8a2f3a373ddef8a4097d74ac901ac363eea1440464ccbe0898/yarl-1.23.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:16c6994ac35c3e74fb0ae93323bf8b9c2a9088d55946109489667c510a7d010e", size = 123796, upload-time = "2026-03-01T22:05:41.412Z" }, + { url = "https://files.pythonhosted.org/packages/67/b6/8925d68af039b835ae876db5838e82e76ec87b9782ecc97e192b809c4831/yarl-1.23.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:4a42e651629dafb64fd5b0286a3580613702b5809ad3f24934ea87595804f2c5", size = 86547, upload-time = "2026-03-01T22:05:42.841Z" }, + { url = "https://files.pythonhosted.org/packages/ae/50/06d511cc4b8e0360d3c94af051a768e84b755c5eb031b12adaaab6dec6e5/yarl-1.23.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:7c6b9461a2a8b47c65eef63bb1c76a4f1c119618ffa99ea79bc5bb1e46c5821b", size = 85854, upload-time = "2026-03-01T22:05:44.85Z" }, + { url = "https://files.pythonhosted.org/packages/c4/f4/4e30b250927ffdab4db70da08b9b8d2194d7c7b400167b8fbeca1e4701ca/yarl-1.23.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2569b67d616eab450d262ca7cb9f9e19d2f718c70a8b88712859359d0ab17035", size = 98351, upload-time = "2026-03-01T22:05:46.836Z" }, + { url = "https://files.pythonhosted.org/packages/86/fc/4118c5671ea948208bdb1492d8b76bdf1453d3e73df051f939f563e7dcc5/yarl-1.23.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e9d9a4d06d3481eab79803beb4d9bd6f6a8e781ec078ac70d7ef2dcc29d1bea5", size = 92711, upload-time = "2026-03-01T22:05:48.316Z" }, + { url = "https://files.pythonhosted.org/packages/56/11/1ed91d42bd9e73c13dc9e7eb0dd92298d75e7ac4dd7f046ad0c472e231cd/yarl-1.23.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f514f6474e04179d3d33175ed3f3e31434d3130d42ec153540d5b157deefd735", size = 106014, upload-time = "2026-03-01T22:05:50.028Z" }, + { url = "https://files.pythonhosted.org/packages/ce/c9/74e44e056a23fbc33aca71779ef450ca648a5bc472bdad7a82339918f818/yarl-1.23.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fda207c815b253e34f7e1909840fd14299567b1c0eb4908f8c2ce01a41265401", size = 105557, upload-time = "2026-03-01T22:05:51.416Z" }, + { url = "https://files.pythonhosted.org/packages/66/fe/b1e10b08d287f518994f1e2ff9b6d26f0adeecd8dd7d533b01bab29a3eda/yarl-1.23.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:34b6cf500e61c90f305094911f9acc9c86da1a05a7a3f5be9f68817043f486e4", size = 101559, upload-time = "2026-03-01T22:05:52.872Z" }, + { url = "https://files.pythonhosted.org/packages/72/59/c5b8d94b14e3d3c2a9c20cb100119fd534ab5a14b93673ab4cc4a4141ea5/yarl-1.23.0-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d7504f2b476d21653e4d143f44a175f7f751cd41233525312696c76aa3dbb23f", size = 100502, upload-time = "2026-03-01T22:05:54.954Z" }, + { url = "https://files.pythonhosted.org/packages/77/4f/96976cb54cbfc5c9fd73ed4c51804f92f209481d1fb190981c0f8a07a1d7/yarl-1.23.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:578110dd426f0d209d1509244e6d4a3f1a3e9077655d98c5f22583d63252a08a", size = 98027, upload-time = "2026-03-01T22:05:56.409Z" }, + { url = "https://files.pythonhosted.org/packages/63/6e/904c4f476471afdbad6b7e5b70362fb5810e35cd7466529a97322b6f5556/yarl-1.23.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:609d3614d78d74ebe35f54953c5bbd2ac647a7ddb9c30a5d877580f5e86b22f2", size = 95369, upload-time = "2026-03-01T22:05:58.141Z" }, + { url = "https://files.pythonhosted.org/packages/9d/40/acfcdb3b5f9d68ef499e39e04d25e141fe90661f9d54114556cf83be8353/yarl-1.23.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:4966242ec68afc74c122f8459abd597afd7d8a60dc93d695c1334c5fd25f762f", size = 105565, upload-time = "2026-03-01T22:06:00.286Z" }, + { url = "https://files.pythonhosted.org/packages/5e/c6/31e28f3a6ba2869c43d124f37ea5260cac9c9281df803c354b31f4dd1f3c/yarl-1.23.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:e0fd068364a6759bc794459f0a735ab151d11304346332489c7972bacbe9e72b", size = 99813, upload-time = "2026-03-01T22:06:01.712Z" }, + { url = "https://files.pythonhosted.org/packages/08/1f/6f65f59e72d54aa467119b63fc0b0b1762eff0232db1f4720cd89e2f4a17/yarl-1.23.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:39004f0ad156da43e86aa71f44e033de68a44e5a31fc53507b36dd253970054a", size = 105632, upload-time = "2026-03-01T22:06:03.188Z" }, + { url = "https://files.pythonhosted.org/packages/a3/c4/18b178a69935f9e7a338127d5b77d868fdc0f0e49becd286d51b3a18c61d/yarl-1.23.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e5723c01a56c5028c807c701aa66722916d2747ad737a046853f6c46f4875543", size = 101895, upload-time = "2026-03-01T22:06:04.651Z" }, + { url = "https://files.pythonhosted.org/packages/8f/54/f5b870b5505663911dba950a8e4776a0dbd51c9c54c0ae88e823e4b874a0/yarl-1.23.0-cp313-cp313-win32.whl", hash = "sha256:1b6b572edd95b4fa8df75de10b04bc81acc87c1c7d16bcdd2035b09d30acc957", size = 82356, upload-time = "2026-03-01T22:06:06.04Z" }, + { url = "https://files.pythonhosted.org/packages/7a/84/266e8da36879c6edcd37b02b547e2d9ecdfea776be49598e75696e3316e1/yarl-1.23.0-cp313-cp313-win_amd64.whl", hash = "sha256:baaf55442359053c7d62f6f8413a62adba3205119bcb6f49594894d8be47e5e3", size = 87515, upload-time = "2026-03-01T22:06:08.107Z" }, + { url = "https://files.pythonhosted.org/packages/00/fd/7e1c66efad35e1649114fa13f17485f62881ad58edeeb7f49f8c5e748bf9/yarl-1.23.0-cp313-cp313-win_arm64.whl", hash = "sha256:fb4948814a2a98e3912505f09c9e7493b1506226afb1f881825368d6fb776ee3", size = 81785, upload-time = "2026-03-01T22:06:10.181Z" }, + { url = "https://files.pythonhosted.org/packages/9c/fc/119dd07004f17ea43bb91e3ece6587759edd7519d6b086d16bfbd3319982/yarl-1.23.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:aecfed0b41aa72b7881712c65cf764e39ce2ec352324f5e0837c7048d9e6daaa", size = 130719, upload-time = "2026-03-01T22:06:11.708Z" }, + { url = "https://files.pythonhosted.org/packages/e6/0d/9f2348502fbb3af409e8f47730282cd6bc80dec6630c1e06374d882d6eb2/yarl-1.23.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:a41bcf68efd19073376eb8cf948b8d9be0af26256403e512bb18f3966f1f9120", size = 89690, upload-time = "2026-03-01T22:06:13.429Z" }, + { url = "https://files.pythonhosted.org/packages/50/93/e88f3c80971b42cfc83f50a51b9d165a1dbf154b97005f2994a79f212a07/yarl-1.23.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:cde9a2ecd91668bcb7f077c4966d8ceddb60af01b52e6e3e2680e4cf00ad1a59", size = 89851, upload-time = "2026-03-01T22:06:15.53Z" }, + { url = "https://files.pythonhosted.org/packages/1c/07/61c9dd8ba8f86473263b4036f70fb594c09e99c0d9737a799dfd8bc85651/yarl-1.23.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5023346c4ee7992febc0068e7593de5fa2bf611848c08404b35ebbb76b1b0512", size = 95874, upload-time = "2026-03-01T22:06:17.553Z" }, + { url = "https://files.pythonhosted.org/packages/9e/e9/f9ff8ceefba599eac6abddcfb0b3bee9b9e636e96dbf54342a8577252379/yarl-1.23.0-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:d1009abedb49ae95b136a8904a3f71b342f849ffeced2d3747bf29caeda218c4", size = 88710, upload-time = "2026-03-01T22:06:19.004Z" }, + { url = "https://files.pythonhosted.org/packages/eb/78/0231bfcc5d4c8eec220bc2f9ef82cb4566192ea867a7c5b4148f44f6cbcd/yarl-1.23.0-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a8d00f29b42f534cc8aa3931cfe773b13b23e561e10d2b26f27a8d309b0e82a1", size = 101033, upload-time = "2026-03-01T22:06:21.203Z" }, + { url = "https://files.pythonhosted.org/packages/cd/9b/30ea5239a61786f18fd25797151a17fbb3be176977187a48d541b5447dd4/yarl-1.23.0-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:95451e6ce06c3e104556d73b559f5da6c34a069b6b62946d3ad66afcd51642ea", size = 100817, upload-time = "2026-03-01T22:06:22.738Z" }, + { url = "https://files.pythonhosted.org/packages/62/e2/a4980481071791bc83bce2b7a1a1f7adcabfa366007518b4b845e92eeee3/yarl-1.23.0-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:531ef597132086b6cf96faa7c6c1dcd0361dd5f1694e5cc30375907b9b7d3ea9", size = 97482, upload-time = "2026-03-01T22:06:24.21Z" }, + { url = "https://files.pythonhosted.org/packages/e5/1e/304a00cf5f6100414c4b5a01fc7ff9ee724b62158a08df2f8170dfc72a2d/yarl-1.23.0-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:88f9fb0116fbfcefcab70f85cf4b74a2b6ce5d199c41345296f49d974ddb4123", size = 95949, upload-time = "2026-03-01T22:06:25.697Z" }, + { url = "https://files.pythonhosted.org/packages/68/03/093f4055ed4cae649ac53bca3d180bd37102e9e11d048588e9ab0c0108d0/yarl-1.23.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:e7b0460976dc75cb87ad9cc1f9899a4b97751e7d4e77ab840fc9b6d377b8fd24", size = 95839, upload-time = "2026-03-01T22:06:27.309Z" }, + { url = "https://files.pythonhosted.org/packages/b9/28/4c75ebb108f322aa8f917ae10a8ffa4f07cae10a8a627b64e578617df6a0/yarl-1.23.0-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:115136c4a426f9da976187d238e84139ff6b51a20839aa6e3720cd1026d768de", size = 90696, upload-time = "2026-03-01T22:06:29.048Z" }, + { url = "https://files.pythonhosted.org/packages/23/9c/42c2e2dd91c1a570402f51bdf066bfdb1241c2240ba001967bad778e77b7/yarl-1.23.0-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:ead11956716a940c1abc816b7df3fa2b84d06eaed8832ca32f5c5e058c65506b", size = 100865, upload-time = "2026-03-01T22:06:30.525Z" }, + { url = "https://files.pythonhosted.org/packages/74/05/1bcd60a8a0a914d462c305137246b6f9d167628d73568505fce3f1cb2e65/yarl-1.23.0-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:fe8f8f5e70e6dbdfca9882cd9deaac058729bcf323cf7a58660901e55c9c94f6", size = 96234, upload-time = "2026-03-01T22:06:32.692Z" }, + { url = "https://files.pythonhosted.org/packages/90/b2/f52381aac396d6778ce516b7bc149c79e65bfc068b5de2857ab69eeea3b7/yarl-1.23.0-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:a0e317df055958a0c1e79e5d2aa5a5eaa4a6d05a20d4b0c9c3f48918139c9fc6", size = 100295, upload-time = "2026-03-01T22:06:34.268Z" }, + { url = "https://files.pythonhosted.org/packages/e5/e8/638bae5bbf1113a659b2435d8895474598afe38b4a837103764f603aba56/yarl-1.23.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:6f0fd84de0c957b2d280143522c4f91a73aada1923caee763e24a2b3fda9f8a5", size = 97784, upload-time = "2026-03-01T22:06:35.864Z" }, + { url = "https://files.pythonhosted.org/packages/80/25/a3892b46182c586c202629fc2159aa13975d3741d52ebd7347fd501d48d5/yarl-1.23.0-cp313-cp313t-win32.whl", hash = "sha256:93a784271881035ab4406a172edb0faecb6e7d00f4b53dc2f55919d6c9688595", size = 88313, upload-time = "2026-03-01T22:06:37.39Z" }, + { url = "https://files.pythonhosted.org/packages/43/68/8c5b36aa5178900b37387937bc2c2fe0e9505537f713495472dcf6f6fccc/yarl-1.23.0-cp313-cp313t-win_amd64.whl", hash = "sha256:dd00607bffbf30250fe108065f07453ec124dbf223420f57f5e749b04295e090", size = 94932, upload-time = "2026-03-01T22:06:39.579Z" }, + { url = "https://files.pythonhosted.org/packages/c6/cc/d79ba8292f51f81f4dc533a8ccfb9fc6992cabf0998ed3245de7589dc07c/yarl-1.23.0-cp313-cp313t-win_arm64.whl", hash = "sha256:ac09d42f48f80c9ee1635b2fcaa819496a44502737660d3c0f2ade7526d29144", size = 84786, upload-time = "2026-03-01T22:06:41.988Z" }, + { url = "https://files.pythonhosted.org/packages/90/98/b85a038d65d1b92c3903ab89444f48d3cee490a883477b716d7a24b1a78c/yarl-1.23.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:21d1b7305a71a15b4794b5ff22e8eef96ff4a6d7f9657155e5aa419444b28912", size = 124455, upload-time = "2026-03-01T22:06:43.615Z" }, + { url = "https://files.pythonhosted.org/packages/39/54/bc2b45559f86543d163b6e294417a107bb87557609007c007ad889afec18/yarl-1.23.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:85610b4f27f69984932a7abbe52703688de3724d9f72bceb1cca667deff27474", size = 86752, upload-time = "2026-03-01T22:06:45.425Z" }, + { url = "https://files.pythonhosted.org/packages/24/f9/e8242b68362bffe6fb536c8db5076861466fc780f0f1b479fc4ffbebb128/yarl-1.23.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:23f371bd662cf44a7630d4d113101eafc0cfa7518a2760d20760b26021454719", size = 86291, upload-time = "2026-03-01T22:06:46.974Z" }, + { url = "https://files.pythonhosted.org/packages/ea/d8/d1cb2378c81dd729e98c716582b1ccb08357e8488e4c24714658cc6630e8/yarl-1.23.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c4a80f77dc1acaaa61f0934176fccca7096d9b1ff08c8ba9cddf5ae034a24319", size = 99026, upload-time = "2026-03-01T22:06:48.459Z" }, + { url = "https://files.pythonhosted.org/packages/0a/ff/7196790538f31debe3341283b5b0707e7feb947620fc5e8236ef28d44f72/yarl-1.23.0-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:bd654fad46d8d9e823afbb4f87c79160b5a374ed1ff5bde24e542e6ba8f41434", size = 92355, upload-time = "2026-03-01T22:06:50.306Z" }, + { url = "https://files.pythonhosted.org/packages/c1/56/25d58c3eddde825890a5fe6aa1866228377354a3c39262235234ab5f616b/yarl-1.23.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:682bae25f0a0dd23a056739f23a134db9f52a63e2afd6bfb37ddc76292bbd723", size = 106417, upload-time = "2026-03-01T22:06:52.1Z" }, + { url = "https://files.pythonhosted.org/packages/51/8a/882c0e7bc8277eb895b31bce0138f51a1ba551fc2e1ec6753ffc1e7c1377/yarl-1.23.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a82836cab5f197a0514235aaf7ffccdc886ccdaa2324bc0aafdd4ae898103039", size = 106422, upload-time = "2026-03-01T22:06:54.424Z" }, + { url = "https://files.pythonhosted.org/packages/42/2b/fef67d616931055bf3d6764885990a3ac647d68734a2d6a9e1d13de437a2/yarl-1.23.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1c57676bdedc94cd3bc37724cf6f8cd2779f02f6aba48de45feca073e714fe52", size = 101915, upload-time = "2026-03-01T22:06:55.895Z" }, + { url = "https://files.pythonhosted.org/packages/18/6a/530e16aebce27c5937920f3431c628a29a4b6b430fab3fd1c117b26ff3f6/yarl-1.23.0-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c7f8dc16c498ff06497c015642333219871effba93e4a2e8604a06264aca5c5c", size = 100690, upload-time = "2026-03-01T22:06:58.21Z" }, + { url = "https://files.pythonhosted.org/packages/88/08/93749219179a45e27b036e03260fda05190b911de8e18225c294ac95bbc9/yarl-1.23.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:5ee586fb17ff8f90c91cf73c6108a434b02d69925f44f5f8e0d7f2f260607eae", size = 98750, upload-time = "2026-03-01T22:06:59.794Z" }, + { url = "https://files.pythonhosted.org/packages/d9/cf/ea424a004969f5d81a362110a6ac1496d79efdc6d50c2c4b2e3ea0fc2519/yarl-1.23.0-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:17235362f580149742739cc3828b80e24029d08cbb9c4bda0242c7b5bc610a8e", size = 94685, upload-time = "2026-03-01T22:07:01.375Z" }, + { url = "https://files.pythonhosted.org/packages/e2/b7/14341481fe568e2b0408bcf1484c652accafe06a0ade9387b5d3fd9df446/yarl-1.23.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:0793e2bd0cf14234983bbb371591e6bea9e876ddf6896cdcc93450996b0b5c85", size = 106009, upload-time = "2026-03-01T22:07:03.151Z" }, + { url = "https://files.pythonhosted.org/packages/0a/e6/5c744a9b54f4e8007ad35bce96fbc9218338e84812d36f3390cea616881a/yarl-1.23.0-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:3650dc2480f94f7116c364096bc84b1d602f44224ef7d5c7208425915c0475dd", size = 100033, upload-time = "2026-03-01T22:07:04.701Z" }, + { url = "https://files.pythonhosted.org/packages/0c/23/e3bfc188d0b400f025bc49d99793d02c9abe15752138dcc27e4eaf0c4a9e/yarl-1.23.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:f40e782d49630ad384db66d4d8b73ff4f1b8955dc12e26b09a3e3af064b3b9d6", size = 106483, upload-time = "2026-03-01T22:07:06.231Z" }, + { url = "https://files.pythonhosted.org/packages/72/42/f0505f949a90b3f8b7a363d6cbdf398f6e6c58946d85c6d3a3bc70595b26/yarl-1.23.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:94f8575fbdf81749008d980c17796097e645574a3b8c28ee313931068dad14fe", size = 102175, upload-time = "2026-03-01T22:07:08.4Z" }, + { url = "https://files.pythonhosted.org/packages/aa/65/b39290f1d892a9dd671d1c722014ca062a9c35d60885d57e5375db0404b5/yarl-1.23.0-cp314-cp314-win32.whl", hash = "sha256:c8aa34a5c864db1087d911a0b902d60d203ea3607d91f615acd3f3108ac32169", size = 83871, upload-time = "2026-03-01T22:07:09.968Z" }, + { url = "https://files.pythonhosted.org/packages/a9/5b/9b92f54c784c26e2a422e55a8d2607ab15b7ea3349e28359282f84f01d43/yarl-1.23.0-cp314-cp314-win_amd64.whl", hash = "sha256:63e92247f383c85ab00dd0091e8c3fa331a96e865459f5ee80353c70a4a42d70", size = 89093, upload-time = "2026-03-01T22:07:11.501Z" }, + { url = "https://files.pythonhosted.org/packages/e0/7d/8a84dc9381fd4412d5e7ff04926f9865f6372b4c2fd91e10092e65d29eb8/yarl-1.23.0-cp314-cp314-win_arm64.whl", hash = "sha256:70efd20be968c76ece7baa8dafe04c5be06abc57f754d6f36f3741f7aa7a208e", size = 83384, upload-time = "2026-03-01T22:07:13.069Z" }, + { url = "https://files.pythonhosted.org/packages/dd/8d/d2fad34b1c08aa161b74394183daa7d800141aaaee207317e82c790b418d/yarl-1.23.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:9a18d6f9359e45722c064c97464ec883eb0e0366d33eda61cb19a244bf222679", size = 131019, upload-time = "2026-03-01T22:07:14.903Z" }, + { url = "https://files.pythonhosted.org/packages/19/ff/33009a39d3ccf4b94d7d7880dfe17fb5816c5a4fe0096d9b56abceea9ac7/yarl-1.23.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:2803ed8b21ca47a43da80a6fd1ed3019d30061f7061daa35ac54f63933409412", size = 89894, upload-time = "2026-03-01T22:07:17.372Z" }, + { url = "https://files.pythonhosted.org/packages/0c/f1/dab7ac5e7306fb79c0190766a3c00b4cb8d09a1f390ded68c85a5934faf5/yarl-1.23.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:394906945aa8b19fc14a61cf69743a868bb8c465efe85eee687109cc540b98f4", size = 89979, upload-time = "2026-03-01T22:07:19.361Z" }, + { url = "https://files.pythonhosted.org/packages/aa/b1/08e95f3caee1fad6e65017b9f26c1d79877b502622d60e517de01e72f95d/yarl-1.23.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:71d006bee8397a4a89f469b8deb22469fe7508132d3c17fa6ed871e79832691c", size = 95943, upload-time = "2026-03-01T22:07:21.266Z" }, + { url = "https://files.pythonhosted.org/packages/c0/cc/6409f9018864a6aa186c61175b977131f373f1988e198e031236916e87e4/yarl-1.23.0-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:62694e275c93d54f7ccedcfef57d42761b2aad5234b6be1f3e3026cae4001cd4", size = 88786, upload-time = "2026-03-01T22:07:23.129Z" }, + { url = "https://files.pythonhosted.org/packages/76/40/cc22d1d7714b717fde2006fad2ced5efe5580606cb059ae42117542122f3/yarl-1.23.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a31de1613658308efdb21ada98cbc86a97c181aa050ba22a808120bb5be3ab94", size = 101307, upload-time = "2026-03-01T22:07:24.689Z" }, + { url = "https://files.pythonhosted.org/packages/8f/0d/476c38e85ddb4c6ec6b20b815bdd779aa386a013f3d8b85516feee55c8dc/yarl-1.23.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fb1e8b8d66c278b21d13b0a7ca22c41dd757a7c209c6b12c313e445c31dd3b28", size = 100904, upload-time = "2026-03-01T22:07:26.287Z" }, + { url = "https://files.pythonhosted.org/packages/72/32/0abe4a76d59adf2081dcb0397168553ece4616ada1c54d1c49d8936c74f8/yarl-1.23.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50f9d8d531dfb767c565f348f33dd5139a6c43f5cbdf3f67da40d54241df93f6", size = 97728, upload-time = "2026-03-01T22:07:27.906Z" }, + { url = "https://files.pythonhosted.org/packages/b7/35/7b30f4810fba112f60f5a43237545867504e15b1c7647a785fbaf588fac2/yarl-1.23.0-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:575aa4405a656e61a540f4a80eaa5260f2a38fff7bfdc4b5f611840d76e9e277", size = 95964, upload-time = "2026-03-01T22:07:30.198Z" }, + { url = "https://files.pythonhosted.org/packages/2d/86/ed7a73ab85ef00e8bb70b0cb5421d8a2a625b81a333941a469a6f4022828/yarl-1.23.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:041b1a4cefacf65840b4e295c6985f334ba83c30607441ae3cf206a0eed1a2e4", size = 95882, upload-time = "2026-03-01T22:07:32.132Z" }, + { url = "https://files.pythonhosted.org/packages/19/90/d56967f61a29d8498efb7afb651e0b2b422a1e9b47b0ab5f4e40a19b699b/yarl-1.23.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:d38c1e8231722c4ce40d7593f28d92b5fc72f3e9774fe73d7e800ec32299f63a", size = 90797, upload-time = "2026-03-01T22:07:34.404Z" }, + { url = "https://files.pythonhosted.org/packages/72/00/8b8f76909259f56647adb1011d7ed8b321bcf97e464515c65016a47ecdf0/yarl-1.23.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:d53834e23c015ee83a99377db6e5e37d8484f333edb03bd15b4bc312cc7254fb", size = 101023, upload-time = "2026-03-01T22:07:35.953Z" }, + { url = "https://files.pythonhosted.org/packages/ac/e2/cab11b126fb7d440281b7df8e9ddbe4851e70a4dde47a202b6642586b8d9/yarl-1.23.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:2e27c8841126e017dd2a054a95771569e6070b9ee1b133366d8b31beb5018a41", size = 96227, upload-time = "2026-03-01T22:07:37.594Z" }, + { url = "https://files.pythonhosted.org/packages/c2/9b/2c893e16bfc50e6b2edf76c1a9eb6cb0c744346197e74c65e99ad8d634d0/yarl-1.23.0-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:76855800ac56f878847a09ce6dba727c93ca2d89c9e9d63002d26b916810b0a2", size = 100302, upload-time = "2026-03-01T22:07:39.334Z" }, + { url = "https://files.pythonhosted.org/packages/28/ec/5498c4e3a6d5f1003beb23405671c2eb9cdbf3067d1c80f15eeafe301010/yarl-1.23.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:e09fd068c2e169a7070d83d3bde728a4d48de0549f975290be3c108c02e499b4", size = 98202, upload-time = "2026-03-01T22:07:41.717Z" }, + { url = "https://files.pythonhosted.org/packages/fe/c3/cd737e2d45e70717907f83e146f6949f20cc23cd4bf7b2688727763aa458/yarl-1.23.0-cp314-cp314t-win32.whl", hash = "sha256:73309162a6a571d4cbd3b6a1dcc703c7311843ae0d1578df6f09be4e98df38d4", size = 90558, upload-time = "2026-03-01T22:07:43.433Z" }, + { url = "https://files.pythonhosted.org/packages/e1/19/3774d162f6732d1cfb0b47b4140a942a35ca82bb19b6db1f80e9e7bdc8f8/yarl-1.23.0-cp314-cp314t-win_amd64.whl", hash = "sha256:4503053d296bc6e4cbd1fad61cf3b6e33b939886c4f249ba7c78b602214fabe2", size = 97610, upload-time = "2026-03-01T22:07:45.773Z" }, + { url = "https://files.pythonhosted.org/packages/51/47/3fa2286c3cb162c71cdb34c4224d5745a1ceceb391b2bd9b19b668a8d724/yarl-1.23.0-cp314-cp314t-win_arm64.whl", hash = "sha256:44bb7bef4ea409384e3f8bc36c063d77ea1b8d4a5b2706956c0d6695f07dcc25", size = 86041, upload-time = "2026-03-01T22:07:49.026Z" }, + { url = "https://files.pythonhosted.org/packages/69/68/c8739671f5699c7dc470580a4f821ef37c32c4cb0b047ce223a7f115757f/yarl-1.23.0-py3-none-any.whl", hash = "sha256:a2df6afe50dea8ae15fa34c9f824a3ee958d785fd5d089063d960bae1daa0a3f", size = 48288, upload-time = "2026-03-01T22:07:51.388Z" }, +] + +[[package]] +name = "zarr" +source = { editable = "." } +dependencies = [ + { name = "donfig" }, + { name = "google-crc32c" }, + { name = "msgspec" }, + { name = "numcodecs" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "typing-extensions" }, +] + +[package.optional-dependencies] +cast-value-rs = [ + { name = "cast-value-rs" }, +] +cli = [ + { name = "typer" }, +] +gpu = [ + { name = "cupy-cuda12x", marker = "sys_platform != 'darwin'" }, +] +optional = [ + { name = "universal-pathlib" }, +] +remote = [ + { name = "fsspec" }, + { name = "obstore" }, +] + +[package.dev-dependencies] +dev = [ + { name = "astroid" }, + { name = "botocore" }, + { name = "coverage" }, + { name = "fsspec" }, + { name = "griffe-inherited-docstrings" }, + { name = "hypothesis" }, + { name = "markdown-exec", extra = ["ansi"] }, + { name = "mike" }, + { name = "mkdocs" }, + { name = "mkdocs-material", extra = ["imaging"] }, + { name = "mkdocs-redirects" }, + { name = "mkdocstrings" }, + { name = "mkdocstrings-python" }, + { name = "moto", extra = ["s3", "server"] }, + { name = "mypy" }, + { name = "numcodecs", extra = ["msgpack"] }, + { name = "numpydoc" }, + { name = "obstore" }, + { name = "pytest" }, + { name = "pytest-accept" }, + { name = "pytest-asyncio" }, + { name = "pytest-benchmark" }, + { name = "pytest-codspeed" }, + { name = "pytest-cov" }, + { name = "pytest-reportlog" }, + { name = "pytest-xdist" }, + { name = "requests" }, + { name = "ruff" }, + { name = "s3fs" }, + { name = "tomlkit" }, + { name = "towncrier" }, + { name = "universal-pathlib" }, + { name = "uv" }, +] +docs = [ + { name = "astroid" }, + { name = "griffe-inherited-docstrings" }, + { name = "markdown-exec", extra = ["ansi"] }, + { name = "mike" }, + { name = "mkdocs" }, + { name = "mkdocs-material", extra = ["imaging"] }, + { name = "mkdocs-redirects" }, + { name = "mkdocstrings" }, + { name = "mkdocstrings-python" }, + { name = "numcodecs", extra = ["msgpack"] }, + { name = "pytest" }, + { name = "ruff" }, + { name = "s3fs" }, + { name = "towncrier" }, +] +release = [ + { name = "towncrier" }, +] +remote-tests = [ + { name = "botocore" }, + { name = "coverage" }, + { name = "fsspec" }, + { name = "hypothesis" }, + { name = "moto", extra = ["s3", "server"] }, + { name = "numpydoc" }, + { name = "obstore" }, + { name = "pytest" }, + { name = "pytest-accept" }, + { name = "pytest-asyncio" }, + { name = "pytest-benchmark" }, + { name = "pytest-codspeed" }, + { name = "pytest-cov" }, + { name = "pytest-reportlog" }, + { name = "pytest-xdist" }, + { name = "requests" }, + { name = "s3fs" }, + { name = "tomlkit" }, + { name = "uv" }, +] +test = [ + { name = "coverage" }, + { name = "hypothesis" }, + { name = "numpydoc" }, + { name = "pytest" }, + { name = "pytest-accept" }, + { name = "pytest-asyncio" }, + { name = "pytest-benchmark" }, + { name = "pytest-codspeed" }, + { name = "pytest-cov" }, + { name = "pytest-reportlog" }, + { name = "pytest-xdist" }, + { name = "tomlkit" }, + { name = "uv" }, +] + +[package.metadata] +requires-dist = [ + { name = "cast-value-rs", marker = "extra == 'cast-value-rs'", specifier = ">=0.4.2" }, + { name = "cupy-cuda12x", marker = "sys_platform != 'darwin' and extra == 'gpu'" }, + { name = "donfig", specifier = ">=0.8" }, + { name = "fsspec", marker = "extra == 'remote'", specifier = ">=2023.10.0" }, + { name = "google-crc32c", specifier = ">=1.5" }, + { name = "msgspec", specifier = ">=0.19" }, + { name = "numcodecs", specifier = ">=0.14" }, + { name = "numpy", specifier = ">=2" }, + { name = "obstore", marker = "extra == 'remote'", specifier = ">=0.5.1" }, + { name = "packaging", specifier = ">=22.0" }, + { name = "typer", marker = "extra == 'cli'" }, + { name = "typing-extensions", specifier = ">=4.14" }, + { name = "universal-pathlib", marker = "extra == 'optional'" }, +] +provides-extras = ["cast-value-rs", "cli", "gpu", "optional", "remote"] + +[package.metadata.requires-dev] +dev = [ + { name = "astroid", specifier = "==4.3.0" }, + { name = "botocore" }, + { name = "coverage", specifier = "==7.15.4" }, + { name = "fsspec", specifier = ">=2023.10.0" }, + { name = "griffe-inherited-docstrings", specifier = "==1.1.3" }, + { name = "hypothesis", specifier = "==6.165.5" }, + { name = "markdown-exec", extras = ["ansi"], specifier = "==1.12.3" }, + { name = "mike", specifier = "==2.2.0" }, + { name = "mkdocs", specifier = "==1.6.1" }, + { name = "mkdocs-material", extras = ["imaging"], specifier = "==9.7.7" }, + { name = "mkdocs-redirects", specifier = "==1.2.3" }, + { name = "mkdocstrings", specifier = "==1.0.6" }, + { name = "mkdocstrings-python", specifier = "==2.0.5" }, + { name = "moto", extras = ["s3", "server"], specifier = "==5.2.2" }, + { name = "mypy", specifier = "==2.3.0" }, + { name = "numcodecs", extras = ["msgpack"] }, + { name = "numpydoc", specifier = "==1.10.0" }, + { name = "obstore", specifier = ">=0.5.1" }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "pytest-accept", specifier = "==0.3.0" }, + { name = "pytest-asyncio", specifier = "==1.4.0" }, + { name = "pytest-benchmark", specifier = "==5.2.3" }, + { name = "pytest-codspeed", specifier = "==5.0.3" }, + { name = "pytest-cov", specifier = "==7.1.0" }, + { name = "pytest-reportlog", specifier = "==1.0.0" }, + { name = "pytest-xdist", specifier = "==3.8.0" }, + { name = "requests", specifier = "==2.34.2" }, + { name = "ruff", specifier = "==0.16.2" }, + { name = "s3fs", specifier = ">=2023.10.0" }, + { name = "tomlkit", specifier = "==0.15.1" }, + { name = "towncrier", specifier = "==25.8.0" }, + { name = "universal-pathlib" }, + { name = "uv", specifier = "==0.12.3" }, +] +docs = [ + { name = "astroid", specifier = "==4.3.0" }, + { name = "griffe-inherited-docstrings", specifier = "==1.1.3" }, + { name = "markdown-exec", extras = ["ansi"], specifier = "==1.12.3" }, + { name = "mike", specifier = "==2.2.0" }, + { name = "mkdocs", specifier = "==1.6.1" }, + { name = "mkdocs-material", extras = ["imaging"], specifier = "==9.7.7" }, + { name = "mkdocs-redirects", specifier = "==1.2.3" }, + { name = "mkdocstrings", specifier = "==1.0.6" }, + { name = "mkdocstrings-python", specifier = "==2.0.5" }, + { name = "numcodecs", extras = ["msgpack"] }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "ruff", specifier = "==0.16.2" }, + { name = "s3fs", specifier = ">=2023.10.0" }, + { name = "towncrier", specifier = "==25.8.0" }, +] +release = [{ name = "towncrier", specifier = "==25.8.0" }] +remote-tests = [ + { name = "botocore" }, + { name = "coverage", specifier = "==7.15.4" }, + { name = "fsspec", specifier = ">=2023.10.0" }, + { name = "hypothesis", specifier = "==6.165.5" }, + { name = "moto", extras = ["s3", "server"], specifier = "==5.2.2" }, + { name = "numpydoc", specifier = "==1.10.0" }, + { name = "obstore", specifier = ">=0.5.1" }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "pytest-accept", specifier = "==0.3.0" }, + { name = "pytest-asyncio", specifier = "==1.4.0" }, + { name = "pytest-benchmark", specifier = "==5.2.3" }, + { name = "pytest-codspeed", specifier = "==5.0.3" }, + { name = "pytest-cov", specifier = "==7.1.0" }, + { name = "pytest-reportlog", specifier = "==1.0.0" }, + { name = "pytest-xdist", specifier = "==3.8.0" }, + { name = "requests", specifier = "==2.34.2" }, + { name = "s3fs", specifier = ">=2023.10.0" }, + { name = "tomlkit", specifier = "==0.15.1" }, + { name = "uv", specifier = "==0.12.3" }, +] +test = [ + { name = "coverage", specifier = "==7.15.4" }, + { name = "hypothesis", specifier = "==6.165.5" }, + { name = "numpydoc", specifier = "==1.10.0" }, + { name = "pytest", specifier = "==9.1.1" }, + { name = "pytest-accept", specifier = "==0.3.0" }, + { name = "pytest-asyncio", specifier = "==1.4.0" }, + { name = "pytest-benchmark", specifier = "==5.2.3" }, + { name = "pytest-codspeed", specifier = "==5.0.3" }, + { name = "pytest-cov", specifier = "==7.1.0" }, + { name = "pytest-reportlog", specifier = "==1.0.0" }, + { name = "pytest-xdist", specifier = "==3.8.0" }, + { name = "tomlkit", specifier = "==0.15.1" }, + { name = "uv", specifier = "==0.12.3" }, +]