diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..bdc9b8e --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,3 @@ +# Default owners for everything in the repo. These users are requested for +# review on every pull request. +* @ab93 @BeataLuczywek @stenhaug diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..41db63f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,28 @@ +--- +name: Bug report +about: Something is not working as expected +labels: bug +--- + +**What happened** + +**What you expected** + +**Minimal reproducible example** + +```python + +``` + +**Environment** + +- multilift version: +- Python version: +- OS: +- numpy / pandas / scikit-learn / lightgbm versions: + +**Full traceback** + +``` + +``` diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..8cff19b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Question or discussion + url: https://github.com/intuit/multilift/discussions + about: Ask usage questions and discuss ideas here rather than in issues. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..f1bcd6a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,13 @@ +--- +name: Feature request +about: Suggest an addition or change +labels: enhancement +--- + +**Problem** + +What are you trying to do that is hard or impossible today? + +**Proposed solution** + +**Alternatives considered** diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..6fcb1b0 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,10 @@ +## Summary + + + +## Checklist + +- [ ] `make lint` and `make test` pass locally +- [ ] Tests added or updated for the change +- [ ] Docs / docstrings updated if the public API changed +- [ ] `CHANGELOG.md` updated under **Unreleased** diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..72341ce --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,139 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +# One run per ref; a new push cancels the stale run. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +# Least privilege by default; jobs that need more request it explicitly. +permissions: + contents: read + +env: + POETRY_VERSION: "2.4.1" + PYTHONUNBUFFERED: "1" + PIP_DISABLE_PIP_VERSION_CHECK: "1" + +jobs: + lint: + name: Lint + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - name: Install Poetry + run: pipx install "poetry==${POETRY_VERSION}" + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: poetry + - run: poetry install --only main,dev --no-interaction + - name: Lock file must be consistent and resolve from PyPI only + run: | + poetry check --lock + if grep -q '^\[package\.source\]' poetry.lock; then + echo "::error file=poetry.lock::lock references a non-PyPI package source" + exit 1 + fi + - run: poetry run isort --check-only --diff . + - run: poetry run black --check --diff . + - run: poetry run ruff check --output-format=github . + + test: + name: Test (py${{ matrix.python-version }}) + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + python-version: ["3.11", "3.12", "3.13", "3.14"] + steps: + - uses: actions/checkout@v4 + - name: Install libgomp (LightGBM runtime dependency) + run: sudo apt-get update -q && sudo apt-get install -y -q --no-install-recommends libgomp1 + - name: Install Poetry + run: pipx install "poetry==${POETRY_VERSION}" + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + cache: poetry + - run: poetry install --only main,dev --no-interaction + - name: Run tests + run: > + poetry run pytest + -p no:cacheprovider + -o log_cli=false + --cov=multilift + --cov-report=term + --cov-report=xml + --junitxml=junit.xml + - name: Upload test results + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v4 + with: + name: test-results-py${{ matrix.python-version }} + path: junit.xml + retention-days: 14 + - name: Upload coverage + if: ${{ matrix.python-version == '3.12' && !cancelled() }} + uses: actions/upload-artifact@v4 + with: + name: coverage-xml + path: coverage.xml + retention-days: 14 + + docs: + name: Docs + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - name: Install Poetry + run: pipx install "poetry==${POETRY_VERSION}" + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: poetry + - run: poetry install --only main,docs --no-interaction + - name: Build docs (warnings are errors) + run: poetry run sphinx-build -W --keep-going -b html docs docs/_build/html + + build: + name: Build distribution + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - name: Install Poetry + run: pipx install "poetry==${POETRY_VERSION}" + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: poetry build + - name: Check metadata renders on PyPI + run: pipx run twine check --strict dist/* + - uses: actions/upload-artifact@v4 + with: + name: dist + path: dist/ + retention-days: 14 + + # Single required status check for branch protection: point the rule at + # "CI passed" instead of enumerating every matrix leg. + ci-passed: + name: CI passed + if: always() + needs: [lint, test, docs, build] + runs-on: ubuntu-latest + timeout-minutes: 2 + steps: + - name: Fail if any dependency failed or was cancelled + if: ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }} + run: exit 1 + - run: echo "All CI jobs passed." diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d544b52 --- /dev/null +++ b/.gitignore @@ -0,0 +1,232 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[codz] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py.cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +#uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock +#poetry.toml + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. +# https://pdm-project.org/en/latest/usage/project/#working-with-version-control +#pdm.lock +#pdm.toml +.pdm-python +.pdm-build/ + +# pixi +# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. +#pixi.lock +# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one +# in the .venv directory. It is recommended not to include this directory in version control. +.pixi + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Abstra +# Abstra is an AI-powered process automation framework. +# Ignore directories containing user credentials, local state, and settings. +# Learn more at https://abstra.io/docs +.abstra/ + +# Visual Studio Code +# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore +# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore +# and can be added to the global gitignore or merged into this file. However, if you prefer, +# you could uncomment the following to ignore the entire vscode folder +# .vscode/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Cursor +# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to +# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data +# refer to https://docs.cursor.com/context/ignore-files +.cursorignore +.cursorindexingignore + +# Marimo +marimo/_static/ +marimo/_lsp/ +__marimo__/ + +# macOS +.DS_Store + +# Data artifacts - never commit datasets or pickled models +*.pkl +*.joblib +*.csv +*.parquet +*.zip + +# Per-env coverage databases (tox) +.coverage_db_* +coverage_*.xml +htmlcov_*/ + +# Local scratch space +scratch/** +!scratch/README.md + +.idea/ + +# Private keys and certificates +*.pem +*.key diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..2b3151f --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,36 @@ +repos: + - repo: https://github.com/pycqa/isort + rev: 9.0.2 + hooks: + - id: isort + name: isort (python) + - repo: https://github.com/psf/black + rev: 26.10.1 + hooks: + - id: black + args: [ --config=pyproject.toml, --diff, --color ] + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.17.3 + hooks: + - id: ruff + args: [ --fix ] + - repo: https://github.com/adamchainz/blacken-docs + rev: "1.20.0" + hooks: + - id: blacken-docs + additional_dependencies: + - black==22.12.0 + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v6.0.0 + hooks: + - id: end-of-file-fixer + - id: trailing-whitespace + - id: check-toml + - id: check-added-large-files + - id: check-ast + - id: check-case-conflict + - id: check-docstring-first + - repo: https://github.com/python-poetry/poetry + rev: "2.5.1" + hooks: + - id: poetry-check diff --git a/AUTHORS.md b/AUTHORS.md new file mode 100644 index 0000000..d66b193 --- /dev/null +++ b/AUTHORS.md @@ -0,0 +1,23 @@ +# Authors + +`multilift` began as an internal library and was released as open source with a fresh commit +history. Attribution for that earlier development is recorded here. + +## Original authors + +- Avik Basu ([@ab93](https://github.com/ab93)) +- Beata Luczywek ([@BeataLuczywek](https://github.com/BeataLuczywek)) + +## Maintainers + +Current maintainers review pull requests and cut releases. This list mirrors +`.github/CODEOWNERS` and the `maintainers` field in `pyproject.toml`. + +- Avik Basu ([@ab93](https://github.com/ab93)) +- Beata Luczywek ([@BeataLuczywek](https://github.com/BeataLuczywek)) +- Benjamin Stenhaug ([@stenhaug](https://github.com/stenhaug)) + +## Contributors + +Thanks to everyone who has contributed since the open-source release. See the +[contributor graph](https://github.com/intuit/multilift/graphs/contributors) for the full list. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..6eafccc --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,27 @@ +# Changelog + +All notable changes to this project are documented here. The format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project adheres to +[Semantic Versioning](https://semver.org/). + +## [Unreleased] + +## [0.1.0] - Unreleased + +Initial open-source release. + +### Added + +- `UpliftRegressorPipeline` and `UpliftClassifierPipeline`: end-to-end multi-treatment + uplift pipelines with preprocessing, prediction, policy assignment, evaluation, SHAP + explanation, and save/load. +- S-Learner and T-Learner meta-learners in regressor and classifier form, with + per-treatment independent learners for the T-Learner. +- `UpliftExploreEvaluator` for randomized data and `UpliftExploitEvaluator` for + policy-assigned deployment data. +- Qini curve, Qini AUC, binned uplift, and inverse-propensity-weighting utilities. +- `SLearnerTuner` and `TLearnerTuner` with Qini and top-decile scoring. +- `OneHotPreprocessor` with fitted-state guard. + +[Unreleased]: https://github.com/intuit/multilift/compare/v0.1.0...HEAD +[0.1.0]: https://github.com/intuit/multilift/releases/tag/v0.1.0 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..95f8f94 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,130 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official email address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +[TechOpenSource@intuit.com](mailto:TechOpenSource@intuit.com). + +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +https://www.contributor-covenant.org/version/2/1/code_of_conduct.html. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][mozilla coc]. + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. + +[homepage]: https://www.contributor-covenant.org +[mozilla coc]: https://github.com/mozilla/diversity diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..a17dffe --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,89 @@ +# Contributing to multilift + +Contributions are welcome — bug reports, documentation fixes, and new features alike. + +This project follows the [Contributor Covenant](./CODE_OF_CONDUCT.md). By +participating, you agree to abide by its terms. + +## Reporting bugs + +Open a GitHub issue with: + +- what you expected and what happened instead +- a minimal reproducible example +- versions (`python --version`, `pip show multilift`, and the relevant + numpy / pandas / scikit-learn / lightgbm versions) +- the full traceback + +## Development setup + +This project uses [Poetry](https://python-poetry.org/). + +```shell +git clone https://github.com//multilift.git +cd multilift +make setup # poetry lock && poetry install --all-groups +poetry run pre-commit install # optional, runs the linters on commit +``` + +Verify your environment: + +```shell +make test +``` + +## Making a change + +1. Fork the repository and create a branch from `main` + (`feat/...`, `fix/...`, or `docs/...`). +2. Write a failing test first where practical — the suite is the specification. +3. Implement the change. +4. Run `make lint` and `make test` until both pass. +5. Open a pull request describing the motivation and the approach. + +## Code standards + +- **Style** — PEP 8 with a 100-character line limit, enforced by `isort`, `black`, + and `ruff`. Run `make lint`; do not add per-file formatting exceptions. +- **Type hints** — required on all public functions and methods. +- **Docstrings** — numpy style (`ruff` is configured with `convention = "numpy"`). + Document parameters, returns, and raised exceptions. +- **Comments** — keep them minimal. Explain *why*, not *what*; the code should make the + *what* obvious. +- **Python** — target 3.11+. Use `X | Y` unions rather than `Union[X, Y]`. +- **Imports** — prefer module-level imports. + +## Testing + +- Framework is `pytest`, with `pytest-cov` and `pytest-xdist` available. +- Mirror the source layout: tests for `multilift/uplift/classifier.py` live in + `tests/uplift/test_uplift_classifier.py`. +- Generate test data in-process. Do not commit datasets, `.csv`/`.parquet` files, or + pickled models — `.gitignore` blocks them deliberately. +- Fitting models is slow, so data-generation and fitted-model fixtures use + `scope="module"`. A test that **mutates** a fixture must build its own local instance + instead, or it will corrupt state for every later test in the module. +- Use a broad coverage target (`--cov=multilift.uplift`). Narrow targets such as + `--cov=multilift.uplift.classifier` raise a `TypeError` from coverage's tracing of + numpy/pandas. + +## Architecture notes + +- **Pipelines wrap meta-learners.** `UpliftRegressorPipeline` and + `UpliftClassifierPipeline` add preprocessing, policy assignment, evaluation, SHAP, and + save/load on top of the learners in `multilift/uplift/meta/`. +- **The regressor leads; the classifier follows.** When adding a feature, implement it in + `regressor.py` first, then bring `classifier.py` to parity so the two interfaces stay + symmetrical. +- **Shared logic lives in `_utils.py`.** Helpers used by both pipelines (for example + `_apply_threshold`) belong in `multilift/uplift/_utils.py`, not duplicated. + +## Documentation + +Public API changes need a matching entry in `docs/api/uplift.rst`. Build and check the +docs locally with `make docs`. + +## License + +By contributing, you agree that your contributions are licensed under the +[Apache License 2.0](./LICENSE). diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..c13144c --- /dev/null +++ b/Makefile @@ -0,0 +1,33 @@ +.PHONY: clean lint tox test setup docs docs-clean + +clean: + @rm -rf build dist .eggs *.egg-info + @rm -rf .benchmarks .coverage coverage.xml htmlcov report.xml .tox + @find . -type d -name '.mypy_cache' -exec rm -rf {} + + @find . -type d -name '__pycache__' -exec rm -rf {} + + @find . -type d -name '*pytest_cache*' -exec rm -rf {} + + @find . -type f -name "*.py[co]" -exec rm -rf {} + + @find . -type f -name "coverage*.xml" -exec rm -rf {} + + @find . -type f -name ".coverage_db*" -exec rm -rf {} + + @find . -type d -name "htmlcov_*" -exec rm -rf {} + + +lint: + poetry run isort . + poetry run black . + poetry run ruff check --fix . + +tox: + poetry run tox -e lint + +test: + poetry run pytest + +setup: + poetry lock + poetry install --all-groups + +docs: + poetry run sphinx-build -M html docs docs/_build + +docs-clean: + rm -rf docs/_build diff --git a/README.md b/README.md new file mode 100644 index 0000000..53c5ef4 --- /dev/null +++ b/README.md @@ -0,0 +1,195 @@ +# multilift + +![Python versions](https://img.shields.io/badge/python-3.11_|_3.12_|_3.13_|_3.14-blue?logo=python) +[![CI](https://github.com/intuit/multilift/actions/workflows/ci.yml/badge.svg)](https://github.com/intuit/multilift/actions/workflows/ci.yml) +[![License](https://img.shields.io/badge/license-Apache%202.0-green.svg)](./LICENSE) + +Multi-treatment uplift modeling in Python. `multilift` provides S-Learner and T-Learner +meta-learners for both continuous and binary outcomes, Qini-based evaluation, and +hyperparameter tuning — built on scikit-learn and LightGBM. + +Unlike libraries that assume a single treatment arm, `multilift` treats +**multiple simultaneous treatments** as the default case: fit once, then ask which +treatment (if any) to assign to each unit. + +## Features + +- **Meta-learners** — S-Learner and T-Learner, each in regressor and classifier form +- **Pipelines** — `UpliftRegressorPipeline` / `UpliftClassifierPipeline` wrap + preprocessing, fitting, prediction, policy assignment, evaluation, SHAP, and + save/load behind one object +- **Policy assignment** — pick the best treatment per unit, with optional global or + per-treatment uplift thresholds +- **Evaluation** — Qini curves and AUC, binned uplift, inverse-propensity weighting, + and separate evaluators for randomized (`explore`) and policy-assigned (`exploit`) data +- **Tuning** — randomized search with Qini or top-decile scoring + +## Installation + +```shell +pip install multilift +``` + +Requires Python 3.11 or newer. + +## Quick Start + +### Continuous outcomes + +```python +from multilift.uplift import UpliftRegressorPipeline + +# X: feature DataFrame +# t: treatment assignment per row, e.g. "control" / "treatment_A" / "treatment_B" +# y: continuous outcome + +pipeline = UpliftRegressorPipeline( + "control", # control group name (first positional arg) + "treatment_A", # one or more treatment group names + "treatment_B", + model_type="S", # "S" for S-Learner, "T" for T-Learner + n_estimators=100, + learning_rate=0.1, +) +pipeline.fit(X_train, t_train, y_train) + +# Per-unit uplift for every treatment +predictions = pipeline.predict(X_test) + +# Recommended treatment per unit +policy_df = pipeline.policy(X_test) + +# Qini AUC and the underlying curve +qini_auc, qini_df = pipeline.evaluate(X_test, t_test, y_test) + +pipeline.plot(X_test, t_test, y_test, name="Qini Curve") +pipeline.plot_uplift_bins(X_test, t_test, y_test, n_bins=10) + +pipeline.save("model.joblib", version="1.0.0") +loaded = UpliftRegressorPipeline.load("model.joblib") +``` + +### Binary outcomes + +`UpliftClassifierPipeline` has the same interface; `y` must be binary (0/1). + +```python +from multilift.uplift import UpliftClassifierPipeline + +pipeline = UpliftClassifierPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="S", + n_estimators=100, +) +pipeline.fit(X_train, t_train, y_train) +policy_df = pipeline.policy(X_test) +qini_auc, qini_df = pipeline.evaluate(X_test, t_test, y_test) +``` + +### Thresholded single-treatment policy + +To evaluate one treatment against control and only act above a minimum uplift: + +```python +policy_df = pipeline.policy_single( + X_test, + treatment_idx=0, # which treatment to evaluate + threshold=0.05, # minimum uplift required to treat +) +``` + +### Hyperparameter tuning + +```python +from multilift.uplift import TLearnerTuner + +tuner = TLearnerTuner( + "control", + "treatment_A", + "treatment_B", + param_grid={ + "n_estimators": [50, 100, 200], + "max_depth": [3, 5, 7], + "learning_rate": [0.05, 0.1], + }, +) +results = tuner.tune(X_train, t_train, y_train, X_val, t_val, y_val) +best_pipeline = tuner.fit_best(X_train, t_train, y_train) +``` + +`SLearnerTuner` is the equivalent for S-Learner models. + +## API Reference + +### Pipelines + +| Class | Description | +|-------|-------------| +| `UpliftRegressorPipeline` | End-to-end uplift pipeline for continuous outcomes | +| `UpliftClassifierPipeline` | End-to-end uplift pipeline for binary outcomes | + +### Meta-learners (`multilift.uplift.meta`) + +| Class | Description | +|-------|-------------| +| `SLearnerRegressor` | Single model with treatment as a feature | +| `TLearnerRegressor` | One model per treatment arm | +| `SLearnerClassifier` | S-Learner for binary outcomes | +| `TLearnerClassifier` | T-Learner for binary outcomes | + +### Tuners (`multilift.uplift.tuner`) + +| Name | Description | +|------|-------------| +| `SLearnerTuner` / `TLearnerTuner` | Randomized-search hyperparameter tuning | +| `TunerResult` | Container for tuning results | +| `qini_scorer` / `top_decile_scorer` | Built-in scoring functions | + +### Evaluation (`multilift.uplift.eval`) + +| Name | Description | +|------|-------------| +| `compute_qini` / `compute_qini_auc` | Qini curve and AUC | +| `compute_best_uplift` | Best uplift among treatments, per unit | +| `compute_binned_uplift` | Observed uplift by predicted-uplift bin | +| `compute_ipw` | Inverse-propensity weights | +| `plot_qini_curve` / `plot_uplift_bins` | Plotting helpers | +| `UpliftExploreEvaluator` | Evaluation on randomized data | +| `UpliftExploitEvaluator` | Evaluation on policy-assigned data | + +### Preprocessing + +| Name | Description | +|------|-------------| +| `multilift.preproc.OneHotPreprocessor` | One-hot encoder with fitted-state guard | + +## Development + +```shell +# Install Poetry, then: +make setup # poetry lock && poetry install --all-groups + +make test # pytest +make lint # isort, black, ruff --fix +make docs # build Sphinx HTML into docs/_build +``` + +Coverage: + +```shell +poetry run pytest --cov=multilift.uplift --cov-report=term +``` + +Use a broad `--cov` target such as `multilift.uplift`. Narrow targets like +`--cov=multilift.uplift.classifier` trigger a `TypeError` from coverage's interaction with +numpy/pandas. + +## Contributing + +See [CONTRIBUTING.md](./CONTRIBUTING.md). + +## License + +Apache License 2.0 — see [LICENSE](./LICENSE). diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..269fef3 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,17 @@ +# Minimal makefile for Sphinx documentation + +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = . +BUILDDIR = _build + +.PHONY: help clean html + +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +clean: + rm -rf $(BUILDDIR) + +html: + @$(SPHINXBUILD) -M html "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/_static/.gitkeep b/docs/_static/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/docs/api/uplift.rst b/docs/api/uplift.rst new file mode 100644 index 0000000..151e68d --- /dev/null +++ b/docs/api/uplift.rst @@ -0,0 +1,90 @@ +Uplift Module +============= + +The uplift module provides tools for uplift modeling, including model training, +evaluation, and policy recommendation. + +UpliftRegressorPipeline +----------------------- + +.. autoclass:: multilift.uplift.UpliftRegressorPipeline + :members: + :show-inheritance: + +UpliftClassifierPipeline +------------------------ + +.. autoclass:: multilift.uplift.UpliftClassifierPipeline + :members: + :show-inheritance: + +Meta-Learners (Regression) +-------------------------- + +.. autoclass:: multilift.uplift.meta.SLearnerRegressor + :members: + :show-inheritance: + +.. autoclass:: multilift.uplift.meta.TLearnerRegressor + :members: + :show-inheritance: + +Meta-Learners (Classification) +------------------------------ + +.. autoclass:: multilift.uplift.meta.SLearnerClassifier + :members: + :show-inheritance: + +.. autoclass:: multilift.uplift.meta.TLearnerClassifier + :members: + :show-inheritance: + +TLearnerTuner +------------- + +.. autoclass:: multilift.uplift.TLearnerTuner + :members: + :show-inheritance: + +SLearnerTuner +------------- + +.. autoclass:: multilift.uplift.tuner.SLearnerTuner + :members: + :show-inheritance: + +TunerResult +----------- + +.. autoclass:: multilift.uplift.TunerResult + :members: + :show-inheritance: + +Evaluation Functions +-------------------- + +.. autofunction:: multilift.uplift.eval.compute_qini + +.. autofunction:: multilift.uplift.eval.compute_qini_auc + +.. autofunction:: multilift.uplift.eval.compute_best_uplift + +.. autofunction:: multilift.uplift.eval.compute_best_uplift_among_treatments + +.. autofunction:: multilift.uplift.eval.compute_binned_uplift + +.. autofunction:: multilift.uplift.eval.plot_qini_curve + +.. autofunction:: multilift.uplift.eval.plot_uplift_bins + +Evaluator Classes +----------------- + +.. autoclass:: multilift.uplift.eval.UpliftExploreEvaluator + :members: + :show-inheritance: + +.. autoclass:: multilift.uplift.eval.UpliftExploitEvaluator + :members: + :show-inheritance: diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..c0bc1d5 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,75 @@ +"""Sphinx configuration for multilift documentation.""" + +import os +import sys + +# Add the project root to the path so autodoc can find the modules +sys.path.insert(0, os.path.abspath("..")) + +# -- Project information ----------------------------------------------------- +project = "multilift" +copyright = "2026, multilift contributors" +author = "multilift contributors" + +from multilift import __version__ # noqa: E402 + +version = __version__ +release = __version__ + +# -- General configuration --------------------------------------------------- +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.napoleon", + "sphinx.ext.viewcode", + "sphinx.ext.intersphinx", + "sphinx_autodoc_typehints", +] + +# Napoleon settings for numpy-style docstrings +napoleon_google_docstring = False +napoleon_numpy_docstring = True +napoleon_include_init_with_doc = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_param = True +napoleon_use_rtype = True +napoleon_type_aliases = None + +# Autodoc settings +autodoc_default_options = { + "members": True, + "member-order": "bysource", + "special-members": "__init__", + "undoc-members": False, + "exclude-members": "__weakref__", +} +autodoc_typehints = "description" +autodoc_class_signature = "separated" + +# Intersphinx mapping for external libraries +intersphinx_mapping = { + "python": ("https://docs.python.org/3", None), + "numpy": ("https://numpy.org/doc/stable/", None), + "pandas": ("https://pandas.pydata.org/docs/", None), + "sklearn": ("https://scikit-learn.org/stable/", None), + "lightgbm": ("https://lightgbm.readthedocs.io/en/latest/", None), + "shap": ("https://shap.readthedocs.io/en/latest/", None), +} +intersphinx_timeout = 30 +suppress_warnings = ["intersphinx.external"] + +# Templates and static files +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] + +# -- Options for HTML output ------------------------------------------------- +html_theme = "sphinx_rtd_theme" +html_static_path = ["_static"] +html_theme_options = { + "navigation_depth": 4, + "collapse_navigation": False, + "sticky_navigation": True, +} + +# -- Options for autodoc-typehints ------------------------------------------- +typehints_fully_qualified = False +always_document_param_types = True diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..48fc050 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,76 @@ +multilift Documentation +======================= + +A Python library for multi-treatment uplift modeling: S-Learner and T-Learner +meta-learners for both continuous and binary outcomes, Qini-based evaluation, and +hyperparameter tuning. + +Features +-------- + +- **Uplift Modeling**: Complete pipelines for uplift modeling with S-Learner and T-Learner approaches +- **Regression & Classification**: Support for both continuous and binary outcomes +- **Model Evaluation**: Qini curves, uplift bins, and SHAP values for model interpretability +- **Hyperparameter Tuning**: Built-in tuners for optimizing uplift models + +Quick Start +----------- + +For continuous outcomes, use ``UpliftRegressorPipeline``: + +.. code-block:: python + + from multilift.uplift import UpliftRegressorPipeline + + # Initialize and fit the pipeline + pipeline = UpliftRegressorPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="S", + n_estimators=100, + ) + pipeline.fit(X_train, t_train, y_train) + + # Get policy recommendations + policy_df = pipeline.policy(X_test) + + # Evaluate model + qini_auc, qini_df = pipeline.evaluate(X_test, t_test, y_test) + +For binary outcomes (classification), use ``UpliftClassifierPipeline``: + +.. code-block:: python + + from multilift.uplift import UpliftClassifierPipeline + + # Initialize and fit the classifier pipeline + pipeline = UpliftClassifierPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="S", + n_estimators=100, + ) + pipeline.fit(X_train, t_train, y_train) # y_train should be binary (0/1) + + # Get policy recommendations + policy_df = pipeline.policy(X_test) + + # Evaluate model + qini_auc, qini_df = pipeline.evaluate(X_test, t_test, y_test) + +Contents +-------- + +.. toctree:: + :maxdepth: 2 + :caption: API Reference + + api/uplift + +Indices and tables +------------------ + +* :ref:`genindex` +* :ref:`modindex` diff --git a/multilift/__init__.py b/multilift/__init__.py new file mode 100644 index 0000000..5986a67 --- /dev/null +++ b/multilift/__init__.py @@ -0,0 +1,10 @@ +import logging +from importlib.metadata import PackageNotFoundError, version + +try: + __version__ = version("multilift") +except PackageNotFoundError: # running from a source tree that was never installed + __version__ = "0.0.0.dev0" + +logger = logging.getLogger(__name__) +logger.addHandler(logging.NullHandler()) diff --git a/multilift/constants.py b/multilift/constants.py new file mode 100644 index 0000000..23026dc --- /dev/null +++ b/multilift/constants.py @@ -0,0 +1,17 @@ +"""Default hyperparameters and settings shared across uplift models.""" + +DEFAULT_RANDOM_SEED = 42 + +DEFAULT_TOP_N_MODELS = 5 + +DEFAULT_PARAM_GRID = { + "n_estimators": [100, 200, 300, 500, 1000], + "max_depth": [4, 6, 8, 10, 12], + "learning_rate": [0.01, 0.05, 0.1], + "num_leaves": [31, 63, 127], + "subsample": [0.7, 0.85, 1.0], + "colsample_bytree": [0.7, 0.85, 1.0], + "reg_alpha": [0.0, 0.1], + "reg_lambda": [0.0, 0.1], + "min_child_samples": [10, 20], +} diff --git a/multilift/exceptions.py b/multilift/exceptions.py new file mode 100644 index 0000000..2546063 --- /dev/null +++ b/multilift/exceptions.py @@ -0,0 +1,4 @@ +class ModelNotFittedError(Exception): + """Raised when a model is used before it has been fitted.""" + + pass diff --git a/multilift/preproc.py b/multilift/preproc.py new file mode 100644 index 0000000..a34bab2 --- /dev/null +++ b/multilift/preproc.py @@ -0,0 +1,225 @@ +import logging + +import numpy as np +import pandas as pd +from sklearn.preprocessing import OneHotEncoder + +from multilift.exceptions import ModelNotFittedError +from multilift.typing import PandasDF + +_logger = logging.getLogger(__name__) + + +def set_categorical_dtype( + df: PandasDF, category_map: dict | None = None +) -> tuple[PandasDF, list[str]]: + """ + Set categorical data type for object columns. + + Parameters + ---------- + df: The PandasDF + category_map: mapping of category columns to their existing categories + + Returns + ------- + tuple: + - The DataFrame + - list of categorical features including + converted object columns and existing category columns + """ + obj_cols = df.select_dtypes(include="object").columns + category_map = category_map or {} + for c in obj_cols: + df[c] = pd.Categorical(df[c], categories=category_map.get(c)) + existing_cat_cols = df.select_dtypes(include="category").columns + cat_features = set(existing_cat_cols).union(set(obj_cols)) + return df, list(cat_features) + + +def drop_na_columns(df: PandasDF) -> PandasDF: + """ + Remove columns from a Pandas DataFrame if they contain more NaN values than non-NaN values. + + Args: + df (pd.DataFrame): The input DataFrame. + + Returns + ------- + pd.DataFrame: The DataFrame with specified columns removed. + """ + columns_to_drop = df.columns[df.isnull().sum() > len(df) / 2] + return df.drop(columns=columns_to_drop) + + +class OneHotPreprocessor: + """ + Preprocessor for one-hot encoding categorical features. + + Parameters + ---------- + oh_dtype: The data type for the one-hot encoded features + drop: Whether to drop the first column (default is "first") + handle_unknown: Whether to handle unknown categories + keep_cols: The columns to keep + drop_cols: The columns to drop + """ + + def __init__( + self, + oh_dtype=np.int32, + drop: str = "first", + handle_unknown: str = "ignore", + keep_cols: list[str] | None = None, + drop_cols: list[str] | None = None, + ): + self.categorical_cols = None + self.numeric_cols = None + self.cat_feature_names = None + self.is_fitted = False + + self.keep_cols = keep_cols or [] + self.drop_cols = drop_cols or [] + + self._ohe = OneHotEncoder( + sparse_output=False, + handle_unknown=handle_unknown, + drop=drop, + dtype=oh_dtype, + ) + + def __repr__(self) -> str: + """Get important information about the preprocessor.""" + return ( + f"OneHotPreprocessor(" + f"num_numeric_cols={len(self.numeric_cols)}, " + f"num_categorical_cols={len(self.categorical_cols)}, " + f"is_fitted={self.is_fitted})" + ) + + @property + def ohe(self) -> OneHotEncoder: + """Return the OneHotEncoder.""" + return self._ohe + + def _handle_drop_cols(self, df: PandasDF) -> PandasDF: + """ + Handle dropping columns with graceful error handling for missing columns. + + Parameters + ---------- + df: DataFrame to drop columns from + + Returns + ------- + DataFrame with specified columns dropped + """ + if not self.drop_cols: + return df + + # Check which columns actually exist + existing_cols = set(df.columns) + existing_cols_to_drop = [col for col in self.drop_cols if col in existing_cols] + missing_cols = [col for col in self.drop_cols if col not in existing_cols] + + if missing_cols: + _logger.warning( + "The following columns in drop_cols were not found in the DataFrame: %s", + missing_cols, + ) + + if existing_cols_to_drop: + _logger.info("Dropping columns: %s", existing_cols_to_drop) + df = df.drop(columns=existing_cols_to_drop) + + return df + + def fit(self, df: PandasDF) -> "OneHotPreprocessor": + """ + Fit the preprocessor to the DataFrame. + + Parameters + ---------- + df: The DataFrame to fit + """ + df = self._handle_drop_cols(df) + + if self.keep_cols: + _logger.info("Keeping columns: %s", self.keep_cols) + df = df[self.keep_cols] + + _categorical_types = ["object", "category", "string"] + + self.categorical_cols = df.select_dtypes(include=_categorical_types).columns.tolist() + self.numeric_cols = df.select_dtypes(exclude=_categorical_types).columns.tolist() + + if len(self.categorical_cols) > 0: + cat_df = df[self.categorical_cols] + # Convert category dtype to object to allow fillna with new values + for col in cat_df.columns: + if cat_df[col].dtype.name == "category": + cat_df[col] = cat_df[col].astype(object) + cat_df = cat_df.fillna("") + + self._ohe.fit(cat_df) + self.cat_feature_names = self._ohe.get_feature_names_out(self.categorical_cols) + else: + self.cat_feature_names = [] + + self.is_fitted = True + return self + + def fit_transform(self, df: PandasDF) -> PandasDF: + """Fit the preprocessor to the DataFrame and transform it.""" + self.fit(df) + return self.transform(df) + + def transform(self, df: PandasDF) -> PandasDF: + """Transform the DataFrame.""" + df = self._handle_drop_cols(df) + + if not self.is_fitted: + raise ModelNotFittedError( + "OneHotPreprocessor must be fitted before transform. Call fit() first." + ) + + # Get numeric data + num_df = ( + df[self.numeric_cols] if len(self.numeric_cols) > 0 else pd.DataFrame(index=df.index) + ) + + if len(self.numeric_cols) > 0: + num_df = num_df.astype(np.float32) + + # Handle categorical data if present + if len(self.categorical_cols) > 0: + cat_df = df[self.categorical_cols] + # Convert category dtype to object to allow fillna with new values + for col in cat_df.columns: + if cat_df[col].dtype.name == "category": + cat_df[col] = cat_df[col].astype(object) + cat_df = cat_df.fillna("") + cat_transformed = self._ohe.transform(cat_df) + cat_df = pd.DataFrame(cat_transformed, columns=self.cat_feature_names, index=df.index) + + # Combine numerical and categorical + if len(self.numeric_cols) > 0: + return pd.concat([num_df, cat_df], axis=1) + return cat_df + return num_df + + def get_feature_names_out(self) -> list[str]: + """Get the names of the output features.""" + if not self.is_fitted: + raise ValueError("OneHotPreprocessor must be fitted before getting feature names.") + + feature_names = [] + feature_names.extend(self.numeric_cols) + feature_names.extend(self.cat_feature_names) + return feature_names + + def get_raw_feature_names_out(self) -> list[str]: + """Get the names of the raw features.""" + if not self.is_fitted: + raise ValueError("OneHotPreprocessor must be fitted before getting feature names.") + return self.numeric_cols + self.categorical_cols diff --git a/multilift/py.typed b/multilift/py.typed new file mode 100644 index 0000000..945a9a8 --- /dev/null +++ b/multilift/py.typed @@ -0,0 +1,3 @@ +# Marker file for PEP 561. This package uses inline types. +# see https://mypy.readthedocs.io/en/stable/getting_started.html +# or https://peps.python.org/pep-0561/ diff --git a/multilift/typing.py b/multilift/typing.py new file mode 100644 index 0000000..9a3aec8 --- /dev/null +++ b/multilift/typing.py @@ -0,0 +1,11 @@ +from typing import TypeAlias + +import numpy as np +import pandas as pd + +# DataFrame types +PandasDF: TypeAlias = pd.DataFrame + +# Array and numeric types +NDArray: TypeAlias = np.ndarray +Series: TypeAlias = pd.Series diff --git a/multilift/uplift/__init__.py b/multilift/uplift/__init__.py new file mode 100644 index 0000000..56412d1 --- /dev/null +++ b/multilift/uplift/__init__.py @@ -0,0 +1,16 @@ +"""Uplift modeling module.""" + +from multilift.uplift.classifier import UpliftClassifierPipeline +from multilift.uplift.eval import compute_best_uplift, compute_qini, compute_qini_auc +from multilift.uplift.regressor import UpliftRegressorPipeline +from multilift.uplift.tuner import TLearnerTuner, TunerResult + +__all__ = [ + "TLearnerTuner", + "TunerResult", + "UpliftClassifierPipeline", + "UpliftRegressorPipeline", + "compute_best_uplift", + "compute_qini", + "compute_qini_auc", +] diff --git a/multilift/uplift/_utils.py b/multilift/uplift/_utils.py new file mode 100644 index 0000000..e5358cc --- /dev/null +++ b/multilift/uplift/_utils.py @@ -0,0 +1,66 @@ +"""Shared utilities for uplift pipelines.""" + +import numpy as np +import pandas as pd + +from multilift.typing import NDArray +from multilift.uplift.eval import compute_best_uplift + + +def _apply_threshold( + tau: NDArray, + recipe_names_arr: NDArray, + control_name: str, + threshold: float | dict[str, float], +) -> "pd.Series": + """ + Return a ``policy`` Series based on *tau* and *threshold*. + + Parameters + ---------- + tau : NDArray, shape (n, m) + Predicted uplift matrix. + recipe_names_arr : NDArray, shape (m,) + Treatment names aligned with tau columns. + control_name : str + Label used when no treatment qualifies. + threshold : float or dict[str, float] + A single cutoff or per-recipe cutoffs. + + Returns + ------- + pd.Series + Policy assignments (treatment name or *control_name*). + """ + if isinstance(threshold, dict): + unknown = set(threshold) - set(recipe_names_arr) + if unknown: + raise ValueError(f"Unknown recipe names in threshold: {unknown}") + if any(v < 0 for v in threshold.values()): + raise ValueError("All threshold values must be non-negative.") + + cutoffs = np.array( + [threshold.get(name, 0.0) for name in recipe_names_arr], + dtype=np.float32, + ) + eligible = tau >= cutoffs + masked_tau = np.where(eligible, tau, -np.inf) + any_eligible = eligible.any(axis=1) + + best_idx = np.argmax(masked_tau, axis=1) + best_names = recipe_names_arr[best_idx] + return pd.Series( + np.where(any_eligible, best_names, control_name), + name="policy", + ) + + if threshold < 0: + raise ValueError("Threshold must be non-negative.") + + max_uplifts = compute_best_uplift(tau) + best_idx = np.argmax(tau, axis=1) + best_names = recipe_names_arr[best_idx] + return pd.Series( + np.where(max_uplifts > threshold, best_names, control_name), + name="policy", + ) diff --git a/multilift/uplift/classifier.py b/multilift/uplift/classifier.py new file mode 100644 index 0000000..37fc262 --- /dev/null +++ b/multilift/uplift/classifier.py @@ -0,0 +1,833 @@ +import logging +import warnings +from pathlib import Path +from typing import Any + +import joblib +import numpy as np +import pandas as pd +from lightgbm import LGBMClassifier +from matplotlib import pyplot as plt + +from multilift.constants import DEFAULT_RANDOM_SEED +from multilift.exceptions import ModelNotFittedError +from multilift.preproc import OneHotPreprocessor +from multilift.typing import NDArray, PandasDF, Series +from multilift.uplift._utils import _apply_threshold +from multilift.uplift.eval import ( + UpliftExploreEvaluator, + compute_best_uplift, + compute_qini, + plot_uplift_bins, +) +from multilift.uplift.meta import SLearnerClassifier, TLearnerClassifier + +_logger = logging.getLogger(__name__) + + +class UpliftClassifierPipeline: + """ + A complete pipeline for uplift modeling with classification-based learners. + + This class combines uplift model training, preprocessing, and evaluation + into a single pipeline. It uses S-Learner or T-Learner with LightGBM + classifier as the base learner and provides methods for policy + recommendations and Qini curve evaluation. + + Parameters + ---------- + control_name : str + Name of the control group/treatment. + *treatment_names : str + Names of the treatment groups. + keep_cols : list[str], optional + Columns to keep during preprocessing. + drop_cols : list[str], optional + Columns to drop during preprocessing. + random_seed : int, default=42 + Random seed for reproducibility. + model_type : str, default="S" + Type of meta-learner to use ("S" for S-Learner, "T" for T-Learner). + preprocessor : OneHotPreprocessor, optional + Pre-fitted preprocessor to use. If None, a new one will be created. + lbm_verbosity : int, default=-1 + Verbosity level for LightGBM. + **model_params : Any + Additional parameters to pass to the LightGBM classifier. + If model_type is "T", then control_learner_params and + treatment_learner_params can also be passed. + + Examples + -------- + >>> X_train, y_train, t_train = ... # Your training data + >>> X_test, y_test, t_test = ... # Your test data + ... + >>> pipeline = UpliftClassifierPipeline( + ... "control", + ... "treatment_A", "treatment_B", + ... n_estimators=100, + ... learning_rate=0.1 + ... ) + >>> pipeline.fit(X_train, y_train, t_train) + >>> qini_auc, _ = pipeline.evaluate(X_test, y_test, t_test) + """ + + def __init__( + self, + control_name: str, + *treatment_names: str, + keep_cols: list[str] | None = None, + drop_cols: list[str] | None = None, + random_seed: int = DEFAULT_RANDOM_SEED, + model_type: str = "S", + preprocessor: OneHotPreprocessor | None = None, + lbm_verbosity: int = -1, + **model_params: Any, + ): + self._control_name = control_name + self._treatment_names = list(treatment_names) + + # check if it is not a list of list + if isinstance(self._treatment_names[0], list): + raise TypeError(f"Treatment_names should not be nested lists: {self._treatment_names}") + + self._keep_cols = keep_cols + self._drop_cols = drop_cols + self._model_params = model_params or {} + self._model_type = model_type + self._random_seed = random_seed + self._lbm_verbosity = lbm_verbosity + + self._preprocessor: OneHotPreprocessor | None = preprocessor + self._model = None + self._version = None + + seed = self._model_params.pop("random_state", None) + if seed is not None: + _logger.warning( + "Random seed is set in model_params. Using random_seed=%s instead.", random_seed + ) + + def __repr__(self): + """Return a string representation of the object.""" + return ( + f"UpliftClassifierPipeline(" + f"control_name={self._control_name}, " + f"treatment_names={self._treatment_names}), " + f"model_type={self._model_type})" + ) + + def _check_if_fitted(self): + if self._model is None: + raise ModelNotFittedError("Model is not fitted. Call fit() first.") + + @property + def control_name(self) -> str: + """Return the control name.""" + return self._control_name + + @property + def treatment_names(self) -> list[str]: + """Return the treatment names.""" + return self._treatment_names + + @property + def preprocessor(self) -> OneHotPreprocessor | None: + """Return the preprocessor.""" + return self._preprocessor + + @property + def model(self) -> SLearnerClassifier | TLearnerClassifier | None: + """Return the model.""" + return self._model + + @preprocessor.setter + def preprocessor(self, preprocessor: OneHotPreprocessor) -> None: + """Set the preprocessor.""" + self._preprocessor = preprocessor + + @model.setter + def model(self, model: SLearnerClassifier | TLearnerClassifier) -> None: + """Set the model.""" + self._model = model + + @property + def version(self) -> str | None: + """Return the version.""" + return self._version + + @version.setter + def version(self, version: str) -> None: + """Set the version.""" + self._version = version + + def get_feature_names(self, raw: bool = True) -> list[str]: + """Return the feature names. + + Parameters + ---------- + raw: Whether to return the non-transformed feature names + + Returns + ------- + list[str] + The feature names + """ + if not self._preprocessor: + raise RuntimeError("Preprocess is not initialized!") + if raw: + return self._preprocessor.get_raw_feature_names_out() + return self._preprocessor.get_feature_names_out() + + def preprocess(self, X: PandasDF, training: bool = False) -> PandasDF: + """ + Preprocess the input DataFrame. + + Parameters + ---------- + X: The input DataFrame + training: Whether the preprocessing is for training + + Returns + ------- + PandasDF + The preprocessed DataFrame + + Raises + ------ + ModelNotFittedError + If the preprocessor is not fitted and training is False + """ + if self._preprocessor is None: + if not training: + raise ModelNotFittedError("Preprocessor is not fitted. Call fit() first.") + + self._preprocessor = OneHotPreprocessor( + keep_cols=self._keep_cols, drop_cols=self._drop_cols + ) + if training and not self._preprocessor.is_fitted: + self._preprocessor.fit(X) + x_encoded = self._preprocessor.transform(X) + _logger.info("Preprocessed features shape: %s", x_encoded.shape) + return x_encoded + + @staticmethod + def _is_per_treatment_params(params: dict[str, Any]) -> bool: + """Check if params is per-treatment (dict-of-dicts) vs shared (flat).""" + return bool(params) and all(isinstance(v, dict) for v in params.values()) + + def _init_t_learner(self): + control_learner_params = self._model_params.get("control_learner_params", {}) + treatment_learner_params = self._model_params.get("treatment_learner_params", {}) + + if not control_learner_params and not treatment_learner_params: + # No specific params — use shared model_params for all models + learner = LGBMClassifier( + random_state=self._random_seed, verbose=self._lbm_verbosity, **self._model_params + ) + _logger.info( + "Initializing T-Learner Classifier with shared params: %s", self._model_params + ) + self._model = TLearnerClassifier(control_name=self._control_name, learner=learner) + return + + control_learner = LGBMClassifier( + random_state=self._random_seed, verbose=self._lbm_verbosity, **control_learner_params + ) + + if self._is_per_treatment_params(treatment_learner_params): + # Per-treatment: {"T1": {params}, "T2": {params}} + _logger.info("Initializing T-Learner Classifier with per-treatment params.") + treatment_learners = { + name: LGBMClassifier( + random_state=self._random_seed, verbose=self._lbm_verbosity, **params + ) + for name, params in treatment_learner_params.items() + } + self._model = TLearnerClassifier( + control_name=self._control_name, + control_learner=control_learner, + treatment_learners=treatment_learners, + ) + else: + # Shared treatment params: {params} applied to all treatments + _logger.info("Initializing T-Learner Classifier with shared treatment params.") + treatment_learner = LGBMClassifier( + random_state=self._random_seed, + verbose=self._lbm_verbosity, + **treatment_learner_params, + ) + self._model = TLearnerClassifier( + control_name=self._control_name, + control_learner=control_learner, + treatment_learners=treatment_learner, + ) + + def fit(self, X: PandasDF, t: Series, y: Series) -> "UpliftClassifierPipeline": + """ + Fit the model. + + Parameters + ---------- + X: The input DataFrame + t: The treatment Series + y: The target Series (binary classification target: 0 or 1) + + Returns + ------- + UpliftClassifierPipeline + The fitted pipeline + """ + x_encoded = self.preprocess(X, training=True) + + if self._model_type == "S": + learner = LGBMClassifier( + random_state=self._random_seed, verbose=self._lbm_verbosity, **self._model_params + ) + _logger.info("Initializing S-Learner Classifier with params: %s", self._model_params) + self._model = SLearnerClassifier(learner=learner, control_name=self._control_name) + elif self._model_type == "T": + self._init_t_learner() + elif self._model_type == "X": + raise NotImplementedError("X-Learner is not implemented yet.") + else: + raise ValueError(f"Invalid model type: {self._model_type}") + + self._model.fit(x_encoded, t, y) + return self + + def predict( + self, + X: PandasDF, + t: Series | None = None, + y: Series | None = None, + treatment_idx: int | None = None, + treatment_indices: list[int] | None = None, + ) -> PandasDF: + """ + Predict the uplift for each treatment. + + Parameters + ---------- + X : PandasDF + The input DataFrame. + t : Series, optional + The treatment Series. + y : Series, optional + The target Series. + treatment_idx : int, optional + Single treatment index. Returns uplift for the specified treatment. + Cannot be used with treatment_indices. + treatment_indices : list[int], optional + List of treatment indices. Returns uplift for the specified treatments. + Cannot be used with treatment_idx. + + Returns + ------- + PandasDF of shape (n, m) + The predicted uplift for each treatment (or selected treatments). + + Raises + ------ + ValueError + If both treatment_idx and treatment_indices are provided. + + IndexError + If any treatment index is out of bounds. + """ + self._check_if_fitted() + x_encoded = self.preprocess(X, training=False) + tau = self._model.predict(x_encoded, treatment=t, y=y) + + if treatment_indices is None and treatment_idx is None: + return pd.DataFrame(tau, columns=self._treatment_names, dtype=np.float32) + + if treatment_idx is not None and treatment_indices is not None: + raise ValueError("Only one of treatment_idx or treatment_indices can be provided.") + + if treatment_idx is not None: + treatment_indices = [treatment_idx] + + treatment_indices = np.array(treatment_indices) + if any(treatment_indices < 0) or any(treatment_indices >= len(self._treatment_names)): + raise IndexError(f"Invalid treatment indices: {treatment_indices}") + + treatment_names = np.array(self._treatment_names)[treatment_indices] + _logger.info("Predicting uplift for treatments: %s", treatment_names) + tau = tau[:, treatment_indices] + return pd.DataFrame(tau, columns=treatment_names, dtype=np.float32) + + def policy( + self, + X: PandasDF, + control_name: str | None = None, + recipe_names: list[str] | None = None, + threshold: float | dict[str, float] = 0.0, + ) -> PandasDF: + """ + Get optimal treatment policy for each individual. + + For each individual, selects the treatment with the highest positive uplift. + If no treatment has positive uplift, recommends control. + + When *threshold* is a dict, each recipe has its own minimum cutoff. + Treatments whose predicted uplift falls below their cutoff are masked + out before the argmax selection. Recipes absent from the dict default + to a cutoff of 0. + + Parameters + ---------- + X : PandasDF + The input DataFrame with features. + control_name : str, optional + The name of the control group. If None, uses the name + provided during initialization. + recipe_names : list[str], optional + The names of the treatments to recommend. If None, uses the names + provided during initialization. + threshold : float or dict[str, float], optional + A single non-negative threshold (default 0.0) applied to the best + uplift, **or** a mapping of ``{recipe_name: cutoff}`` for + per-recipe cutoffs. + + Returns + ------- + PandasDF + A DataFrame with the predicted uplift for each treatment, + the maximum uplift, and the recommended policy. + + Raises + ------ + ModelNotFittedError + If the model hasn't been fitted yet. + + ValueError + - If recipe names do not match the number of treatments. + - If any threshold value is negative. + - If threshold dict contains unknown recipe names. + """ + self._check_if_fitted() + + if (recipe_names is not None) and (len(recipe_names) != len(self._treatment_names)): + raise ValueError( + f"Recipe names must match the number of treatments: " + f"{recipe_names} != {self._treatment_names}" + ) + + recipe_names = recipe_names or self._treatment_names + control_name = control_name or self._control_name + + tau = self.predict(X).to_numpy(dtype=np.float32) + max_uplifts = pd.Series(compute_best_uplift(tau), name="max_uplift") + recipe_names_arr = np.array(recipe_names) + + _logger.info("Applying policy with threshold: %s", threshold) + policies = _apply_threshold(tau, recipe_names_arr, control_name, threshold) + + tau = pd.DataFrame(tau, columns=recipe_names) + return pd.concat([tau, max_uplifts, policies], axis=1) + + def policy_subset( + self, + X: PandasDF, + treatment_indices: list[int], + control_name: str | None = None, + recipe_names: list[str] | None = None, + threshold: float | dict[str, float] = 0.0, + ) -> PandasDF: + """ + Get optimal policy from a subset of treatments. + + For each individual, selects the treatment with the highest uplift + among the specified subset. If the max uplift exceeds the threshold, + recommends that treatment; otherwise recommends control. + + Parameters + ---------- + X : PandasDF + The input DataFrame with features. + treatment_indices : list[int] + List of treatment indices to consider (0-indexed). + control_name : str, optional + The name of the control group. If None, uses the name + provided during initialization. + recipe_names : list[str], optional + The names of the treatments to recommend. Must match the length + of treatment_indices. If None, uses the names corresponding to + treatment_indices from initialization. + threshold : float or dict[str, float], optional + A single non-negative threshold (default 0.0) applied to the best + uplift, **or** a mapping of ``{recipe_name: cutoff}`` for + per-recipe cutoffs. + + Returns + ------- + PandasDF + A DataFrame with the predicted uplift for selected treatments, + the maximum uplift, and the recommended policy. + + Raises + ------ + ModelNotFittedError + If the model hasn't been fitted yet. + ValueError + If treatment_indices is empty. + If recipe_names length doesn't match treatment_indices. + If any threshold value is negative. + If any treatment index is out of bounds. + """ + self._check_if_fitted() + + if not treatment_indices: + raise ValueError("treatment_indices cannot be empty.") + + if recipe_names is not None and len(recipe_names) != len(treatment_indices): + raise ValueError( + f"recipe_names length ({len(recipe_names)}) must match " + f"treatment_indices length ({len(treatment_indices)})" + ) + + control_name = control_name or self._control_name + tau = self.predict(X, treatment_indices=treatment_indices).to_numpy(dtype=np.float32) + + if recipe_names is None: + recipe_names = [self._treatment_names[i] for i in treatment_indices] + + _logger.info("Predicting policy for treatments: %s", recipe_names) + max_uplifts = pd.Series(compute_best_uplift(tau), name="max_uplift") + recipe_names_arr = np.array(recipe_names) + + policies = _apply_threshold(tau, recipe_names_arr, control_name, threshold) + + tau = pd.DataFrame(tau, columns=recipe_names) + return pd.concat([tau, max_uplifts, policies], axis=1) + + def policy_single( + self, + X: PandasDF, + treatment_idx: int, + control_name: str | None = None, + recipe_name: str | None = None, + threshold: float = 0.0, + ) -> PandasDF: + """ + Get optimal policy between a single treatment and control. + + .. deprecated:: + Use :meth:`policy_subset` with a single-element list instead. + + Parameters + ---------- + X : PandasDF + The input DataFrame with features. + treatment_idx : int + The index of the treatment to evaluate (0-indexed). + control_name : str, optional + The name of the control group. If None, uses the name + provided during initialization. + recipe_name : str, optional + The name of the treatment to recommend. If None, uses the name + corresponding to treatment_idx from initialization. + threshold : float, optional + A non-negative threshold for the uplift, defaults to 0.0. If the uplift + is less than or equal to this threshold, control is recommended. + + Returns + ------- + PandasDF + A DataFrame with the predicted uplift for the treatment, + the maximum uplift, and the recommended policy. + + Raises + ------ + ModelNotFittedError + If the model hasn't been fitted yet. + IndexError + If treatment_idx is out of bounds. + ValueError + If threshold is negative. + """ + warnings.warn( + "policy_single is deprecated, use policy_subset with a single-element list instead.", + DeprecationWarning, + stacklevel=2, + ) + recipe_names = [recipe_name] if recipe_name is not None else None + return self.policy_subset( + X, + treatment_indices=[treatment_idx], + control_name=control_name, + recipe_names=recipe_names, + threshold=threshold, + ) + + def evaluate(self, X: PandasDF, t: Series, y: Series) -> tuple[float, PandasDF]: + """ + Evaluate the model. + + Parameters + ---------- + X: The input DataFrame + t: The treatment Series + y: The target Series + + Returns + ------- + float + The Qini AUC + PandasDF + The Qini DataFrame + """ + self._check_if_fitted() + tau = self.predict(X).to_numpy(dtype=np.float32) + qini_auc, qini_df = compute_qini(tau, t, y, self._control_name, *self._treatment_names) + _logger.info("Qini AUC: %s", qini_auc) + return qini_auc, qini_df + + def plot( + self, + X: PandasDF, + t: Series, + y: Series, + treatment_names: list[str] | None = None, + name: str = "Binned Actual Uplift", + **plot_kw, + ) -> plt.Axes: + """ + Plot the Qini curve. + + Parameters + ---------- + X: The input DataFrame + t: The treatment Series + y: The target Series + treatment_names: Optional subset of treatment names to plot + name: The name of the plot + plot_kw: Additional keyword arguments for plot_binned_actual_uplift + + Returns + ------- + plt.Axes + The axes of the plot + """ + self._check_if_fitted() + if not treatment_names: + evaluator = UpliftExploreEvaluator(self._control_name, *self._treatment_names) + tau = self.predict(X).to_numpy(dtype=np.float32) + return evaluator.plot_binned_actual_uplift(t, y, tau, title=name, **plot_kw) + + if set(treatment_names) - set(self._treatment_names): + raise ValueError("treatment_names must be a subset of treatment_names") + + evaluator = UpliftExploreEvaluator(self._control_name, *treatment_names) + treatment_idxs = [self._treatment_names.index(name) for name in treatment_names] + _logger.info( + "Plotting for treatment names: %s, indices: %s", treatment_names, treatment_idxs + ) + + tau = self.predict(X, treatment_indices=treatment_idxs) + allowed_recipes = [self._control_name, *treatment_names] + mask = t.isin(allowed_recipes) + + return evaluator.plot_binned_actual_uplift( + t[mask], + y[mask], + tau[mask].to_numpy(dtype=np.float32), + title=name, + **plot_kw, + ) + + def plot_uplift_bins( + self, + X: PandasDF, + t: Series, + y: Series, + n_bins: int = 10, + name: str = "Uplift Bins", + **plot_kw, + ): + """ + Plot the uplift bins. + + Parameters + ---------- + X: The input DataFrame + t: The treatment Series + y: The target Series + n_bins: The number of bins + name: The name of the plot + plot_kw: Additional keyword arguments for plot_uplift_bins + + Returns + ------- + plt.Axes + The axes of the plot + """ + self._check_if_fitted() + tau = compute_best_uplift(self.predict(X)) + return plot_uplift_bins( + t, + y, + tau, + self._control_name, + *self._treatment_names, + n_bins=n_bins, + name=name, + **plot_kw, + ) + + def save(self, filepath: str | Path, version: str, compress: int | bool = 3) -> Path: + """ + Save the fitted pipeline to disk. + + Parameters + ---------- + filepath : str or Path + Path where the pipeline will be saved. Will add .joblib extension if not present. + version : str + Version of the model. + compress : int or bool, default=3 + Compression level (0-9). 0 or False means no compression, + higher values mean more compression but slower save/load. + + Returns + ------- + Path + The path where the model was saved + + Raises + ------ + ModelNotFittedError + If the model hasn't been fitted yet. + + Examples + -------- + >>> uplift_pl = UpliftClassifierPipeline("control", "treatment") + >>> uplift_pl.save('models/uplift_model', version="1.0.0") # saves as uplift_model.joblib + >>> uplift_pl.save( + ... 'models/uplift_model.pkl', version="1.0.1", compress=False + ... ) # no compression + """ + self._check_if_fitted() + filepath = Path(filepath) + + # Add extension if not present + if not filepath.suffix: + filepath = filepath.with_suffix(".joblib") + + # Create parent directory if it doesn't exist + filepath.parent.mkdir(parents=True, exist_ok=True) + self._version = version + + # Prepare the state dictionary + state = { + # config + "control_name": self._control_name, + "treatment_names": self._treatment_names, + "keep_cols": self._keep_cols, + "drop_cols": self._drop_cols, + "model_params": self._model_params, + "model_type": self._model_type, + "random_seed": self._random_seed, + # Fitted objects + "preprocessor": self._preprocessor, + "model": self._model, + # Metadata + "version": self._version, + "class_name": self.__class__.__name__, + } + + joblib.dump(state, filepath, compress=compress) + _logger.info("Saved model to %s", filepath) + return filepath + + def shap(self, X: PandasDF, **plot_kw) -> dict[str, NDArray]: + """ + Compute and plot SHAP values for model interpretability. + + Parameters + ---------- + X : PandasDF + Input features to compute SHAP values for. + + Returns + ------- + dict[str, NDArray] + SHAP values for each treatment. + + Raises + ------ + ModelNotFittedError + If the model hasn't been fitted yet. + """ + self._check_if_fitted() + x_encoded = self.preprocess(X, training=False) + feature_names = self.get_feature_names(raw=False) + + _logger.info("Computing SHAP for %s observations", x_encoded.shape[0]) + + shap_dict = self._model.get_shap_values(X=x_encoded) + self._model.plot_shap_values( + X=x_encoded, features=feature_names, shap_dict=shap_dict, **plot_kw + ) + return shap_dict + + @classmethod + def load(cls, filepath: str | Path) -> "UpliftClassifierPipeline": + """ + Load a fitted pipeline from disk. + + Parameters + ---------- + filepath : str or Path + Path to the saved pipeline file. + + Returns + ------- + UpliftClassifierPipeline + The loaded pipeline ready for prediction. + + Raises + ------ + FileNotFoundError + If the file doesn't exist. + ValueError + If the file format is incompatible. + + Examples + -------- + >>> X = ... # Your input data + >>> pipeline = UpliftClassifierPipeline.load('models/uplift_model.joblib') + >>> predictions = pipeline.predict(X) + """ + filepath = Path(filepath) + + if not filepath.exists(): + raise FileNotFoundError(f"Model file not found: {filepath}") + + # Load the state dictionary + try: + state = joblib.load(filepath) + except Exception as e: + raise ValueError(f"Failed to load model from {filepath}: {e}") + + # Reconstruct the pipeline + treatment_names = state["treatment_names"] + if isinstance(treatment_names[0], list): + treatment_names = [t[0] for t in treatment_names] + + uplift_pl = cls( + state["control_name"], + *treatment_names, + keep_cols=state.get("keep_cols"), + drop_cols=state.get("drop_cols"), + random_seed=state.get("random_seed", DEFAULT_RANDOM_SEED), + model_type=state.get("model_type", "S"), + **state.get("model_params", {}), + ) + uplift_pl.preprocessor = state["preprocessor"] + uplift_pl.model = state["model"] + uplift_pl.version = state.get("version") + + _logger.info("Loaded model from %s", filepath) + return uplift_pl diff --git a/multilift/uplift/eval/__init__.py b/multilift/uplift/eval/__init__.py new file mode 100644 index 0000000..4caa47b --- /dev/null +++ b/multilift/uplift/eval/__init__.py @@ -0,0 +1,27 @@ +from multilift.uplift.eval._exploit import UpliftExploitEvaluator +from multilift.uplift.eval._explore import UpliftExploreEvaluator +from multilift.uplift.eval.utils import ( + compute_best_uplift, + compute_best_uplift_among_treatments, + compute_binned_uplift, + compute_ipw, + compute_pop_frac, + compute_qini, + compute_qini_auc, + plot_qini_curve, + plot_uplift_bins, +) + +__all__ = [ + "UpliftExploitEvaluator", + "UpliftExploreEvaluator", + "compute_best_uplift", + "compute_best_uplift_among_treatments", + "compute_binned_uplift", + "compute_ipw", + "compute_pop_frac", + "compute_qini", + "compute_qini_auc", + "plot_qini_curve", + "plot_uplift_bins", +] diff --git a/multilift/uplift/eval/_exploit.py b/multilift/uplift/eval/_exploit.py new file mode 100644 index 0000000..cb65356 --- /dev/null +++ b/multilift/uplift/eval/_exploit.py @@ -0,0 +1,1152 @@ +import warnings +from collections.abc import Sequence + +import numpy as np +import pandas as pd +from matplotlib import pyplot as plt + +from multilift.typing import NDArray +from multilift.uplift.eval.utils import ( + _add_footnote_to_plot, + _get_significance_stars, + assign_bins, +) + + +class UpliftExploitEvaluator: + """ + Evaluates uplift for exploitation scenarios in multi-arm experiments. + + This class provides methods to analyze uplift performance for exploitation phases, + where you compare outcomes between an uplift recipe (with treatments) and a control + recipe (no treatments). Unlike UpliftExploreEvaluator which handles multiple treatment + arms, this class is designed to evaluate ONE exploitation recipe at a time. + + Parameters + ---------- + control_name : str + Name/label for the control recipe (e.g., "A" for recipe with no treatments) + treatment_name : str + Name/label for the single uplift/treatment recipe (e.g., "D1" for recipe with treatments). + NOTE: Only ONE treatment recipe is supported. To evaluate multiple exploitation recipes, + create separate evaluator instances for each. + n_bins : int, default=10 + Number of bins to create for analysis + + Usage + ----- + >>> from multilift.uplift.eval import UpliftExploitEvaluator + >>> # Correct: Single exploitation recipe + >>> evaluator = UpliftExploitEvaluator("A", "D1", n_bins=10) + >>> + >>> # To evaluate multiple recipes, create separate instances: + >>> evaluator_d1 = UpliftExploitEvaluator("A", "D1") + >>> evaluator_d2 = UpliftExploitEvaluator("A", "D2") + + Notes + ----- + This class evaluates exploitation by comparing outcomes from explore experiment predictions: + - The explore model predicts uplift for different treatments + - The exploit recipe uses these predictions to assign treatments + - This evaluator compares exploit recipe outcomes vs control recipe outcomes + """ + + def __init__(self, control_name: str, treatment_name: str, n_bins: int = 10): + """ + Initialize the UpliftExploitEvaluator. + + Parameters + ---------- + control_name : str + Name/label for the control recipe (recipe with no treatments) + treatment_name : str + Name/label for the single uplift/treatment recipe. + Only one treatment recipe is allowed per evaluator instance. + n_bins : int, default=10 + Number of bins to create for analysis + + Raises + ------ + ValueError + If treatment_name is not provided or if multiple treatment names are passed + """ + self.control_name = control_name + + # Store as tuple for consistency with explore evaluator, but only allow one + if not treatment_name: + raise ValueError( + "UpliftExploitEvaluator requires exactly one treatment_name. " + "To evaluate multiple exploitation recipes, create separate evaluator instances." + ) + + self.treatment_names = (treatment_name,) + self.n_bins = n_bins + + @staticmethod + def _drop_missing_tau( + recipe: pd.Series, y: pd.Series, tau: NDArray | pd.DataFrame + ) -> tuple[pd.Series, pd.Series, NDArray | pd.DataFrame]: + """Drop rows where predicted uplift (tau) contains NaN values. + + Parameters + ---------- + recipe : pd.Series + Recipe assignment series. + y : pd.Series + Outcome series. + tau : NDArray | pd.DataFrame + Predicted uplift array (1-D or 2-D). + + Returns + ------- + tuple[pd.Series, pd.Series, NDArray | pd.DataFrame] + Filtered (recipe, y, tau) with NaN-tau rows removed. + """ + tau_arr = np.asarray(tau, dtype=np.float64) + nan_mask = np.isnan(tau_arr).any(axis=1) if tau_arr.ndim > 1 else np.isnan(tau_arr) + n_missing = int(nan_mask.sum()) + + if n_missing > 0: + n_total = len(tau_arr) + warnings.warn( + f"Dropped {n_missing} out of {n_total} observations " + f"due to missing predicted uplift (tau).", + UserWarning, + stacklevel=3, + ) + keep = ~nan_mask + recipe = recipe.iloc[keep.nonzero()[0]].reset_index(drop=True) + y = y.iloc[keep.nonzero()[0]].reset_index(drop=True) + tau = ( + tau_arr[keep] + if not isinstance(tau, pd.DataFrame) + else tau.iloc[keep.nonzero()[0]].reset_index(drop=True) + ) + + return recipe, y, tau + + @staticmethod + def _mute_color(color: str, factor: float = 0.5) -> tuple: + """Lighten a color by blending it towards white. + + Parameters + ---------- + color : str + A matplotlib color string (e.g. ``"tab:green"``). + factor : float, default=0.5 + Blending factor where 0 = original color and 1 = white. + + Returns + ------- + tuple + RGBA tuple of the lightened color. + """ + from matplotlib.colors import to_rgba + + r, g, b, a = to_rgba(color) + return (r + (1 - r) * factor, g + (1 - g) * factor, b + (1 - b) * factor, a) + + def compute_binned_actual_uplift( # noqa: C901, PLR0912, PLR0915 + self, + recipe: pd.Series, + y: pd.Series, + tau: NDArray | pd.DataFrame, + uplift_recipe_name: str | None = None, + treatment_idx: int | None = None, + return_se: bool = False, + ) -> pd.DataFrame | tuple[pd.DataFrame, pd.DataFrame]: + """ + Compute actual uplift by bin based on recipe assignment. + + This method bins observations by their best predicted uplift score and calculates + the actual uplift in each bin using the formula: + + Uplift_{i,b} = E[Y | recipe = uplift, Bin = b] - E[Y | recipe = Control, Bin = b] + + Parameters + ---------- + recipe : pd.Series + Series containing the experimental recipe assignments for each observation. + This represents whether the customer received the uplift recipe (with treatments) + or the control recipe (no treatments). Examples: "Control", "D1", "A", "B" + y : pd.Series + Observed outcome values + tau : NDArray | pd.DataFrame + Predicted uplift scores. If DataFrame, will extract values. + If multi-treatment (2D array), will use the maximum across treatments + unless ``treatment_idx`` is specified. + uplift_recipe_name : str, optional + Name of the uplift recipe (the recipe with treatments) to compare against + the control recipe. If not provided, uses the first treatment name from the + class initialization. For example, "D1" if that's your uplift recipe name. + treatment_idx : int, optional + 0-based column index of a specific treatment in ``tau`` to use for binning. + When provided, bins are ranked by that treatment's predicted uplift instead + of the maximum across all treatments. Useful when the rollout targets a + single treatment from the explore model. + return_se : bool, default=False + If True, also returns a DataFrame with standard errors for each uplift estimate. + Standard errors are computed as: SE = sqrt(var_t/n_t + var_c/n_c) where var_t + and var_c are the variances in uplift/control recipe groups, n_t and n_c are sizes. + + Returns + ------- + pd.DataFrame or tuple[pd.DataFrame, pd.DataFrame] + If return_se=False (default), returns a single DataFrame with bins as index + containing columns: uplift_recipe_mean, control_recipe_mean, actual_uplift, + uplift_recipe_count, and control_recipe_count. + If return_se=True, returns a tuple of (uplift_df, se_df) where uplift_df + has the same structure and se_df contains se_actual_uplift for each bin. + + Examples + -------- + >>> evaluator = UpliftExploitEvaluator("A", "D1", n_bins=10) + >>> # Get uplift estimates only (uses "D1" from class initialization) + >>> result = evaluator.compute_binned_actual_uplift( + ... recipe=df['recipe'], + ... y=df['outcome'], + ... tau=predicted_uplift + ... ) + >>> + >>> # Get uplift estimates with standard errors + >>> uplift_df, se_df = evaluator.compute_binned_actual_uplift( + ... recipe=df['recipe'], + ... y=df['outcome'], + ... tau=predicted_uplift, + ... return_se=True + ... ) + >>> + >>> # Bin by a specific treatment's predicted uplift (e.g. treatment 0) + >>> result = evaluator.compute_binned_actual_uplift( + ... recipe=df['recipe'], + ... y=df['outcome'], + ... tau=predicted_uplift, + ... treatment_idx=0 + ... ) + """ + # Drop observations with missing predicted uplift + recipe, y, tau = self._drop_missing_tau(recipe, y, tau) + + # Default to first treatment name if not specified + if uplift_recipe_name is None: + if len(self.treatment_names) == 0: + raise ValueError( + "No treatment names provided in class initialization. " + "Either provide treatment_names during initialization or specify " + "uplift_recipe_name." + ) + uplift_recipe_name = self.treatment_names[0] + + # Convert inputs to arrays/series + y = pd.Series(y).reset_index(drop=True) + recipe = pd.Series(recipe).reset_index(drop=True) + + # Handle tau: extract best uplift if multi-treatment + if isinstance(tau, pd.DataFrame): + tau = tau.values + + tau = np.asarray(tau) + + TWO_DIM = 2 + if treatment_idx is not None: + if tau.ndim != TWO_DIM: + raise ValueError( + "treatment_idx can only be used when tau is 2-D (multi-treatment)." + ) + if treatment_idx < 0 or treatment_idx >= tau.shape[1]: + raise ValueError( + f"treatment_idx={treatment_idx} out of range. " + f"tau has {tau.shape[1]} treatment columns (indices 0-{tau.shape[1] - 1})." + ) + best_tau = tau[:, treatment_idx] + elif tau.ndim == TWO_DIM: + best_tau = tau.max(axis=1) + else: + best_tau = tau.flatten() + + # Create bins based on best predicted uplift + # Bin 1 = highest predicted uplift, Bin n_bins = lowest + bin_edges = np.percentile(best_tau, np.linspace(0, 100, self.n_bins + 1)) + bin_edges[-1] += 1e-10 # Ensure the max value is included in the last bin + + # Assign bins (reverse so bin 1 = highest uplift) + bins = np.digitize(best_tau, bin_edges) + bins = self.n_bins + 1 - bins # Reverse: 1=highest, n_bins=lowest + + # Create DataFrame for analysis + df = pd.DataFrame( + { + "bin": bins, + "recipe": recipe, + "y": y, + } + ) + + # Calculate mean outcome by bin and recipe + results = [] + se_results = [] if return_se else None + + for bin_num in range(1, self.n_bins + 1): + bin_data = df[df["bin"] == bin_num] + + # Get data for uplift recipe and control recipe + uplift_data = bin_data[bin_data["recipe"] == uplift_recipe_name] + control_data = bin_data[bin_data["recipe"] == self.control_name] + + # Calculate means + uplift_mean = uplift_data["y"].mean() if len(uplift_data) > 0 else np.nan + control_mean = control_data["y"].mean() if len(control_data) > 0 else np.nan + + # Calculate actual uplift + actual_uplift = ( + uplift_mean - control_mean + if not np.isnan(uplift_mean) and not np.isnan(control_mean) + else np.nan + ) + + # Build result row + row = { + "bin": bin_num, + "uplift_recipe_mean": uplift_mean, + "control_recipe_mean": control_mean, + "actual_uplift": actual_uplift, + "uplift_recipe_count": len(uplift_data), + "control_recipe_count": len(control_data), + } + results.append(row) + + # Calculate standard error if requested + if return_se: + se_row = {"bin": bin_num} + if len(uplift_data) > 0 and len(control_data) > 0: + n_uplift = len(uplift_data) + n_control = len(control_data) + var_uplift = uplift_data["y"].var(ddof=1) if n_uplift > 1 else 0 + var_control = control_data["y"].var(ddof=1) if n_control > 1 else 0 + se = np.sqrt(var_uplift / n_uplift + var_control / n_control) + se_row["se_actual_uplift"] = se + else: + se_row["se_actual_uplift"] = np.nan + se_results.append(se_row) + + result_df = pd.DataFrame(results).set_index("bin") + + if return_se: + se_df = pd.DataFrame(se_results).set_index("bin") + return result_df, se_df + + return result_df + + def plot_binned_actual_uplift( # noqa: C901, PLR0912, PLR0915 + self, + recipe: pd.Series, + y: pd.Series, + tau: NDArray | pd.DataFrame, + uplift_recipe_name: str | None = None, + treatment_idx: int | None = None, + rollout_threshold: float | None = None, + title: str = "Actual Uplift by Bins (Recipe-Based)", + subtitle: str | None = None, + footnote_extra: str | Sequence[str] | None = None, + show_ci: bool = True, + confidence_level: float = 0.95, + metric_format: str = "currency", + figsize: tuple[int] = (10, 6), + ) -> plt.Axes: + """ + Plot actual observed uplift by bin based on recipe assignment. + + This function bins individuals by their predicted uplift, then calculates and plots + the actual observed uplift for each bin using the formula: + Uplift = E[Y | recipe = uplift, Bin] - E[Y | recipe = Control, Bin] + + Parameters + ---------- + recipe : pd.Series + Series containing the experimental recipe assignments for each observation. + This represents whether the customer received the uplift recipe (with treatments) + or the control recipe (no treatments). Examples: "Control", "D1", "A", "B" + y : pd.Series + Observed outcome values + tau : NDArray | pd.DataFrame + Predicted uplift scores. If DataFrame, will extract values. + If multi-treatment (2D array), will use the maximum across treatments + unless ``treatment_idx`` is specified. + uplift_recipe_name : str, optional + Name of the uplift recipe (the recipe with treatments) to compare against + the control recipe. If not provided, uses the first treatment name from + class initialization. + treatment_idx : int, optional + 0-based column index of a specific treatment in ``tau`` to use for binning. + When provided, bins are ranked by that treatment's predicted uplift instead + of the maximum across all treatments. Useful when the rollout targets a + single treatment from the explore model. + rollout_threshold : float, optional + Predicted uplift (tau) value used as the rollout cutoff. When provided, a + dashed vertical line is drawn at the threshold position and bars for bins + whose observations fall below the threshold are shown in muted colors. + title : str, default="Actual Uplift by Bins (Recipe-Based)" + Main title for the plot + subtitle : str, optional + Subtitle displayed below the main title + footnote_extra : str or list of str, optional + Additional text to append to the automatic footnote + show_ci : bool, default=True + Whether to show confidence interval error bars on the plot. + If True, also affects bar coloring based on whether CI crosses zero. + confidence_level : float, default=0.95 + Confidence level for error bars (e.g., 0.95 for 95% confidence intervals). + Only used if show_ci=True. + metric_format : str, default="currency" + Format for y-axis values: "currency" for dollar amounts, "number" for plain values + figsize : tuple[int], default=(10, 6) + Figure size (width, height) + + Returns + ------- + plt.Axes + The matplotlib axes object containing the plot + + Notes + ----- + - Bins are created based on best predicted uplift (highest to lowest) + - Uplift compares outcomes between uplift recipe and control recipe within each bin + - Bar coloring (when show_ci=True): + * Green: Confidence interval entirely above 0 (statistically significant positive) + * Red: Confidence interval entirely below 0 (statistically significant negative) + * Orange: Confidence interval crosses 0 (not statistically significant) + - Bar coloring (when show_ci=False): + * Green: Point estimate above 0 + * Red: Point estimate below 0 + - When rollout_threshold is set, bars beyond the threshold are rendered in + muted (lighter) versions of the same colors. + + Examples + -------- + >>> evaluator = UpliftExploitEvaluator("A", "D1", n_bins=10) + >>> evaluator.plot_binned_actual_uplift( + ... recipe=df['recipe'], + ... y=df['outcome'], + ... tau=predicted_uplift, + ... title="Exploitation Phase: Actual Uplift by Bin" + ... ) + >>> + >>> # Bin by a specific treatment and apply rollout threshold + >>> evaluator.plot_binned_actual_uplift( + ... recipe=df['recipe'], + ... y=df['outcome'], + ... tau=predicted_uplift, + ... treatment_idx=0, + ... rollout_threshold=0.5, + ... title="Uplift by Bin — Treatment 0 with Rollout Cutoff" + ... ) + """ + # Drop observations with missing predicted uplift + recipe, y, tau = self._drop_missing_tau(recipe, y, tau) + + # Get the computed results with standard errors if needed + if show_ci: + results_df, se_df = self.compute_binned_actual_uplift( + recipe=recipe, + y=y, + tau=tau, + uplift_recipe_name=uplift_recipe_name, + treatment_idx=treatment_idx, + return_se=True, + ) + + # Calculate confidence intervals using z-score + from scipy import stats + + z_score = stats.norm.ppf((1 + confidence_level) / 2) + ci_lower = results_df["actual_uplift"] - z_score * se_df["se_actual_uplift"] + ci_upper = results_df["actual_uplift"] + z_score * se_df["se_actual_uplift"] + else: + results_df = self.compute_binned_actual_uplift( + recipe=recipe, + y=y, + tau=tau, + uplift_recipe_name=uplift_recipe_name, + treatment_idx=treatment_idx, + return_se=False, + ) + ci_lower = None + ci_upper = None + + # Determine bar colors based on CI bounds (if available) or point estimates + if show_ci: + # Color based on whether CI crosses zero + colors = pd.Series("tab:orange", index=results_df.index) # overlaps 0 + colors[ci_lower > 0] = "tab:green" # CI entirely > 0 (stat. sig. positive) + colors[ci_upper < 0] = "tab:red" # CI entirely < 0 (stat. sig. negative) + else: + # Color based on point estimate sign + colors = pd.Series("tab:orange", index=results_df.index) + colors[results_df["actual_uplift"] >= 0] = "tab:green" + colors[results_df["actual_uplift"] < 0] = "tab:red" + + # Compute threshold position and mute colors beyond it + threshold_x: float | None = None + if rollout_threshold is not None: + _tau_vals = tau.values if isinstance(tau, pd.DataFrame) else np.asarray(tau) + TWO_DIM = 2 + if treatment_idx is not None and _tau_vals.ndim == TWO_DIM: + _best_tau = _tau_vals[:, treatment_idx] + elif _tau_vals.ndim == TWO_DIM: + _best_tau = _tau_vals.max(axis=1) + else: + _best_tau = _tau_vals.flatten() + + n_above = int(np.sum(_best_tau >= rollout_threshold)) + n_bins_plotted = len(results_df) + threshold_x = (n_above / len(_best_tau)) * n_bins_plotted - 0.5 + + color_list = colors.tolist() + for i in range(len(color_list)): + if i > threshold_x: + color_list[i] = self._mute_color(color_list[i]) + else: + color_list = colors.tolist() + + # Create bar chart + fig, ax = plt.subplots(figsize=figsize) + + x_positions = np.arange(len(results_df)) + ax.bar(x_positions, results_df["actual_uplift"], color=color_list) + + # Add error bars for confidence intervals (if requested) + if show_ci: + uplift_values = results_df["actual_uplift"].values + errors_lower = uplift_values - ci_lower.values + errors_upper = ci_upper.values - uplift_values + errors = np.array([errors_lower, errors_upper]) + + ax.errorbar( + x_positions, + uplift_values, + yerr=errors, + fmt="none", + ecolor="black", + elinewidth=1.5, + capsize=4, + capthick=1.5, + zorder=3, + ) + + # Draw rollout threshold line + if threshold_x is not None: + ax.axvline( + x=threshold_x, + color="black", + linestyle="--", + linewidth=1.5, + zorder=4, + label=f"Rollout threshold (τ ≥ {rollout_threshold})", + ) + ax.legend(loc="upper right", fontsize=9) + + ax.set_xticks(x_positions) + ax.set_xticklabels(results_df.index.astype(str)) + ax.axhline(y=0, color="black", linestyle="-", linewidth=1, alpha=1) + + # Determine x-axis label based on number of treatments in tau (explore experiment) + # Convert tau to numpy array to check shape + if isinstance(tau, pd.DataFrame): + tau_arr = tau.values + else: + tau_arr = np.asarray(tau) + + # Check if single or multi-treatment based on tau shape + TWO_DIM = 2 + is_single_treatment = tau_arr.ndim == 1 or ( + tau_arr.ndim == TWO_DIM and tau_arr.shape[1] == 1 + ) + + if treatment_idx is not None: + x_label = f"Bin (Ranked by predicted uplift for treatment {treatment_idx}: high → low)" + elif is_single_treatment: + x_label = "Bin (Ranked by predicted uplift: high → low)" + else: + x_label = "Bin (Ranked by best predicted uplift across all treatments: high → low)" + + ax.set_xlabel(x_label, fontsize=10) + ax.set_ylabel("Actual Uplift (from experiment)", fontsize=10) + ax.tick_params(axis="both", which="major", labelsize=9) + + # Format y-axis + if metric_format == "currency": + from matplotlib.ticker import FuncFormatter + + def y_axis_formatter(value, pos): + return f"${value:,.2f}" + + ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter)) + + ax.grid(True, axis="y", linestyle="--", linewidth=0.7, alpha=0.7) + ax.set_axisbelow(True) + + # Add title and subtitle + fig.suptitle(title, fontsize=14, fontweight="bold", y=0.98) + if subtitle: + fig.text(0.5, 0.935, subtitle, ha="center", va="top", fontsize=10) + + plt.tight_layout(rect=[0, 0.05, 1, 0.96]) + + # Add footnote + n_obs = len(recipe) + + footnote_lines = ["Average observed uplift per bin. "] + + if show_ci: + ci_pct = int(confidence_level * 100) + footnote_lines.append(f"Error bars show {ci_pct}% confidence intervals. ") + + footnote_lines.append(f"N = {n_obs:,} observations.") + + if rollout_threshold is not None: + footnote_lines.append( + f"Dashed line marks rollout threshold (τ ≥ {rollout_threshold}); " + f"muted bars indicate bins below threshold." + ) + + if footnote_extra: + if isinstance(footnote_extra, str): + footnote_lines.append(footnote_extra) + else: + footnote_lines.extend(footnote_extra) + + footnote_text = " ".join(footnote_lines) + _add_footnote_to_plot(fig, ax, footnote_text) + + plt.show() + + return ax + + def plot_binned_deployment_mix( # noqa: C901, PLR0912, PLR0915 + self, + tau: NDArray | pd.DataFrame, + rollout_threshold: float = 0.0, + treatment_names: list[str] | tuple[str] | None = None, + title: str = "Actual Deployment Mix by Bin", + subtitle: str | None = None, + footnote_extra: str | Sequence[str] | None = None, + figsize: tuple[int] = (10, 6), + ) -> None: + """ + Plot actual treatment deployment mix by predicted uplift bin. + + This function shows what treatment was actually deployed to customers based on the + rollout rule: deploy the treatment with highest predicted uplift if it exceeds the + threshold, otherwise deploy control. Displays as a stacked bar chart showing the + proportion of each bin deployed to each treatment (or control). + + Parameters + ---------- + tau : NDArray | pd.DataFrame + Predicted uplift scores from the exploration model. + Shape: (n_samples, n_treatments) for multi-treatment or (n_samples,) for single. + rollout_threshold : float, default=0.0 + Minimum predicted uplift required to deploy a treatment. + If max(tau) <= rollout_threshold, customer is deployed to control. + treatment_names : list[str] or tuple[str], optional + Names for the treatments from the explore experiment. MUST match the order + of treatments in tau (i.e., treatment_names[0] corresponds to tau[:, 0]). + If tau is a DataFrame, column names will be used automatically. + If not provided and tau is an array, defaults to "Treatment 1", "Treatment 2", etc. + Example: ["B: WTP", "C: WTP -5 State"] + title : str, default="Actual Deployment Mix by Bin" + Main title for the plot + subtitle : str, optional + Subtitle displayed below the main title + footnote_extra : str or list of str, optional + Additional text to append to the automatic footnote + figsize : tuple[int], default=(10, 6) + Figure size (width, height) + + Returns + ------- + None + Displays the plot using plt.show() + + Notes + ----- + - Bins are created by ranking individuals by their best predicted uplift + - Deployment logic: + * If max(tau) > rollout_threshold: Deploy treatment with highest tau + * If max(tau) <= rollout_threshold: Deploy control + - Each bar represents one bin and stacks to 1.0 (100%) + - Control is included in the deployment options + + Examples + -------- + >>> evaluator = UpliftExploitEvaluator("A", "D1", n_bins=10) + >>> evaluator.plot_binned_deployment_mix( + ... tau=tau_predictions, + ... rollout_threshold=0.0, + ... treatment_names=["B: WTP", "C: WTP -5 State"], + ... title="Actual Treatment Deployment", + ... subtitle="Based on tau > 0 rollout rule" + ... ) + """ + from textwrap import dedent + + from matplotlib.ticker import FuncFormatter, MaxNLocator + + # Convert tau to numpy array and extract column names if DataFrame + tau_column_names = None + if isinstance(tau, pd.DataFrame): + tau_column_names = list(tau.columns) + tau_arr = tau.values + else: + tau_arr = np.asarray(tau) + + # Ensure 2D shape + if tau_arr.ndim == 1: + tau_arr = tau_arr.reshape(-1, 1) + + n_samples, n_treatments = tau_arr.shape + + # Determine treatment names with priority: explicit parameter > DataFrame columns > default + if treatment_names is not None: + # User explicitly provided names + if len(treatment_names) != n_treatments: + raise ValueError( + f"Number of treatment_names ({len(treatment_names)}) must match " + f"number of treatments in tau ({n_treatments})" + ) + # Warn if DataFrame columns differ from provided names + if tau_column_names is not None and list(treatment_names) != tau_column_names: + import warnings + + warnings.warn( + f"Provided treatment_names {treatment_names} differ from tau DataFrame " + f"columns {tau_column_names}. Using provided treatment_names. " + f"Ensure treatment_names[i] corresponds to tau column i.", + UserWarning, + stacklevel=2, + ) + elif tau_column_names is not None: + # Use DataFrame column names + treatment_names = tau_column_names + else: + # Default generic names + treatment_names = [f"Treatment {i + 1}" for i in range(n_treatments)] + + # Get best uplift for binning + best_tau = tau_arr.max(axis=1) + bins = assign_bins(pd.Series(best_tau), self.n_bins) + + # Determine deployment for each person based on rollout rule + deployments = [] + for i in range(n_samples): + max_tau = tau_arr[i].max() + if max_tau > rollout_threshold: + # Deploy treatment with highest uplift + best_treatment_idx = tau_arr[i].argmax() + deployments.append(treatment_names[best_treatment_idx]) + else: + deployments.append("Control") + + # Create DataFrame with bins and deployments + df = pd.DataFrame({"bin": bins, "deployment": deployments}) + + # Calculate proportions by bin + results = [] + for bin_num in range(1, self.n_bins + 1): + bin_data = df[df["bin"] == bin_num] + if len(bin_data) == 0: + continue + + # Count deployments + deployment_counts = bin_data["deployment"].value_counts() + total = len(bin_data) + + row = {"bin": bin_num} + # Add control + row["Control"] = deployment_counts.get("Control", 0) / total + + # Add treatments using custom names + for t_name in treatment_names: + row[t_name] = deployment_counts.get(t_name, 0) / total + + results.append(row) + + result_df = pd.DataFrame(results) + + # Ensure all columns exist (even if 0) + all_categories = ["Control", *list(treatment_names)] + for cat in all_categories: + if cat not in result_df.columns: + result_df[cat] = 0.0 + + # Reorder columns: Control first, then treatments + column_order = ["bin", "Control", *list(treatment_names)] + result_df = result_df[column_order] + + # Plot stacked bars + x = np.arange(len(result_df)) + bottoms = np.zeros(len(result_df)) + + fig, ax = plt.subplots(figsize=figsize) + deployment_cols = [col for col in result_df.columns if col != "bin"] + + for col in deployment_cols: + vals = result_df[col].to_numpy() + ax.bar(x, vals, bottom=bottoms, label=col) + bottoms += vals + + ax.set_ylim(0, 1) + # Set y-axis tick labels + yticks = ax.get_yticks() + ax.set_yticks(yticks) + ax.set_yticklabels([f"{tick:.1f}" for tick in yticks], fontsize=10) + + # Set x-axis ticks and labels - use actual bin numbers + bin_labels = result_df["bin"].to_numpy() + ax.xaxis.set_major_locator(MaxNLocator(nbins=12, integer=True)) + ax.xaxis.set_major_formatter( + FuncFormatter( + lambda v, p: str(bin_labels[int(v)]) if 0 <= int(v) < len(bin_labels) else "" + ) + ) + ax.set_xlabel("Bin", fontsize=10) + ax.set_ylabel("Share of deployed treatment", fontsize=10) + + # Add title and subtitle + fig.suptitle(title, fontsize=14, fontweight="bold", y=0.98) + if subtitle: + fig.text(0.5, 0.935, subtitle, ha="center", va="top", fontsize=10) + + ax.tick_params(axis="both", which="major", labelsize=9) + + # Make room for the outside legend + fig.tight_layout(rect=[0, 0, 0.82, 1]) + + # Legend + leg = ax.legend( + title="Deployment", + loc="upper left", + bbox_to_anchor=(1.02, 1), + ncol=1, + borderaxespad=0, + frameon=True, + ) + leg.get_frame().set_facecolor("none") + leg.get_frame().set_alpha(0) + leg.get_frame().set_edgecolor("none") + + # Gridlines behind bars + ax.set_axisbelow(True) + ax.grid(True, axis="y", linestyle="--", linewidth=0.7, alpha=1) + + # Footnote + base_foot = dedent(f""" + Share of actual deployment by predicted-uplift bin. Deployment rule: deploy treatment + with highest predicted uplift if > {rollout_threshold}, otherwise control. N = {n_samples:,} + observations split into {self.n_bins} bins + """).strip() + + if footnote_extra: + if isinstance(footnote_extra, list | tuple): + extra = "\n".join(s.strip() for s in footnote_extra if s is not None) + else: + extra = str(footnote_extra).strip() + foot = f"{base_foot} {extra}" if extra else base_foot + else: + foot = base_foot + + try: + _add_footnote_to_plot(fig, ax, foot, fontsize=9, gap_pts=8, color="0.35") + except Exception: + pass + + plt.show() + + def describe_average_customer( # noqa: C901, PLR0912, PLR0915 + self, + tau: NDArray | pd.DataFrame, + X: pd.DataFrame, + covariates: list[str], + rollout_threshold: float = 0.0, + treatment_names: list[str] | tuple[str] | None = None, + covariate_names: dict[str, str] | None = None, + trim_outliers: float | None = None, + categorical_covariates: list[str] | None = None, + show_significance: bool = False, + ) -> pd.DataFrame: + """ + Describe the average characteristics of customers by deployed treatment group. + + This function segments customers based on actual deployment (determined by rollout rule), + then calculates the average value of specified covariates for each deployed treatment + group (including control). + + Parameters + ---------- + tau : NDArray | pd.DataFrame + Predicted uplift scores from the exploration model. + Shape: (n_samples, n_treatments) for multi-treatment or (n_samples,) for single. + X : pd.DataFrame + DataFrame containing customer features/covariates to analyze + covariates : list[str] + List of column names in X to include in the analysis + rollout_threshold : float, default=0.0 + Minimum predicted uplift required to deploy a treatment. + If max(tau) <= rollout_threshold, customer is deployed to control. + treatment_names : list[str] or tuple[str], optional + Names for the treatments from the explore experiment. MUST match the order + of treatments in tau. If tau is a DataFrame, column names will be used automatically. + If not provided, defaults to "Treatment 1", "Treatment 2", etc. + covariate_names : dict[str, str], optional + Dictionary mapping covariate column names to display names. + Example: {"py_revenue": "Prior Year Revenue"} + trim_outliers : float, optional + If provided, removes outliers beyond this percentile from both ends before + calculating means (e.g., 5.0 removes bottom 5% and top 5%). Must be between 0 and 50. + categorical_covariates : list[str], optional + List of covariates that should be treated as categorical. These will be one-hot + encoded and proportions will be shown instead of means. + show_significance : bool, default=False + If True, performs statistical tests comparing each treatment group to control + and displays significance stars (1 star p<0.1, 2 stars p<0.05, 3 stars p<0.01) + in difference columns. + + Returns + ------- + pd.DataFrame + DataFrame with covariates as rows and deployment groups as columns. + Last row shows counts for each group. If show_significance=True, + includes "Diff" columns showing differences from control with + significance stars. + + Examples + -------- + >>> evaluator = UpliftExploitEvaluator("A", "D1", n_bins=10) + >>> description = evaluator.describe_average_customer( + ... tau=tau_predictions, + ... X=customer_df, + ... covariates=["py_revenue", "py_tax_amount"], + ... rollout_threshold=0.0, + ... treatment_names=["B: WTP", "C: WTP -5 State"] + ... ) + """ + # Convert tau to numpy array and extract column names if DataFrame + tau_column_names = None + if isinstance(tau, pd.DataFrame): + tau_column_names = list(tau.columns) + tau_arr = tau.values + else: + tau_arr = np.asarray(tau) + + # Ensure 2D shape + if tau_arr.ndim == 1: + tau_arr = tau_arr.reshape(-1, 1) + + n_samples, n_treatments = tau_arr.shape + + # Determine treatment names with same logic as plot_binned_deployment_mix + if treatment_names is not None: + if len(treatment_names) != n_treatments: + raise ValueError( + f"Number of treatment_names ({len(treatment_names)}) must match " + f"number of treatments in tau ({n_treatments})" + ) + if tau_column_names is not None and list(treatment_names) != tau_column_names: + import warnings + + warnings.warn( + f"Provided treatment_names {treatment_names} differ from tau DataFrame " + f"columns {tau_column_names}. Using provided treatment_names. " + f"Ensure treatment_names[i] corresponds to tau column i.", + UserWarning, + stacklevel=2, + ) + elif tau_column_names is not None: + treatment_names = tau_column_names + else: + treatment_names = [f"Treatment {i + 1}" for i in range(n_treatments)] + + # Validate categorical covariates + if categorical_covariates is None: + categorical_covariates = [] + else: + missing_categorical = [col for col in categorical_covariates if col not in covariates] + if missing_categorical: + raise ValueError( + f"categorical_covariates must be a subset of argument supplied in " + f"covariates parameter. Missing: {missing_categorical}" + ) + + # Separate numeric and categorical covariates + numeric_covariates = [col for col in covariates if col not in categorical_covariates] + + # Determine deployment for each person based on rollout rule + deployments = [] + for i in range(n_samples): + max_tau = tau_arr[i].max() + if max_tau > rollout_threshold: + best_treatment_idx = tau_arr[i].argmax() + deployments.append(treatment_names[best_treatment_idx]) + else: + deployments.append("Control") + + deployment_series = pd.Series(deployments, index=X.index) + + # Get unique deployment groups in order: Control, then treatments + groups = ["Control", *list(treatment_names)] + groups = [g for g in groups if g in deployment_series.unique()] + + # Store raw data for significance testing if needed + raw_data_by_group = {} + for group in groups: + group_mask = deployment_series == group + raw_data_by_group[group] = X[group_mask][covariates].copy() + + # Calculate averages for each group + results = {} + for group in groups: + group_data = raw_data_by_group[group] + group_results = {} + + # Handle numeric covariates + if numeric_covariates: + numeric_data = group_data[numeric_covariates] + + # Apply outlier trimming if requested (only for numeric) + if trim_outliers is not None: + MAX_TRIM_PERCENTAGE = 50 + if not 0 < trim_outliers < MAX_TRIM_PERCENTAGE: + raise ValueError( + f"trim_outliers must be between 0 and {MAX_TRIM_PERCENTAGE}, " + f"got {trim_outliers}" + ) + # For each numeric covariate, trim outliers + trimmed_data = numeric_data.copy() + for col in numeric_covariates: + lower_percentile = trim_outliers + upper_percentile = 100 - trim_outliers + lower_bound = trimmed_data[col].quantile(lower_percentile / 100) + upper_bound = trimmed_data[col].quantile(upper_percentile / 100) + trimmed_data.loc[ + (trimmed_data[col] < lower_bound) | (trimmed_data[col] > upper_bound), + col, + ] = np.nan + numeric_means = trimmed_data.mean() + else: + numeric_means = numeric_data.mean() + + for col in numeric_covariates: + group_results[col] = numeric_means[col] + + # Handle categorical covariates (show proportions) + if categorical_covariates: + for col in categorical_covariates: + # One-hot encode and calculate proportions + value_counts = group_data[col].value_counts(normalize=True) + # Use most common value or show proportion of most common + if len(value_counts) > 0: + # Show proportion of most common category + most_common_value = value_counts.index[0] + proportion = value_counts.iloc[0] + group_results[f"{col}_{most_common_value}"] = proportion + + # Add count + group_results["count"] = len(group_data) + results[group] = group_results + + # Create DataFrame + result_df = pd.DataFrame(results) + + # Add significance testing if requested + if show_significance and "Control" in result_df.columns: + control_data = raw_data_by_group["Control"] + + # Create new DataFrame with interleaved treatment and diff columns + new_result_df = pd.DataFrame(index=result_df.index) + new_result_df["Control"] = result_df["Control"] + + for treat in treatment_names: + if treat not in result_df.columns: + continue + + treatment_data = raw_data_by_group[treat] + new_result_df[treat] = result_df[treat] + + # Create difference column with proper dtype + new_result_df[f"{treat} Diff"] = pd.Series(dtype=object) + + # Perform t-tests for numeric covariates + for cov in numeric_covariates: + if cov in control_data.columns and cov in treatment_data.columns: + control_vals = control_data[cov].dropna() + treatment_vals = treatment_data[cov].dropna() + + if len(control_vals) > 1 and len(treatment_vals) > 1: + from scipy import stats as scipy_stats + + _, p_value = scipy_stats.ttest_ind( + treatment_vals, control_vals, equal_var=False + ) + diff = result_df.loc[cov, treat] - result_df.loc[cov, "Control"] + stars = _get_significance_stars(p_value) + new_result_df.loc[cov, f"{treat} Diff"] = f"{diff:.3f}{stars}" + else: + new_result_df.loc[cov, f"{treat} Diff"] = None + + # Perform tests for categorical proportions + for cov in categorical_covariates: + # Find the one-hot encoded column name + matching_cols = [c for c in result_df.index if c.startswith(f"{cov}_")] + if matching_cols: + for cat_col in matching_cols: + # Get the category value from column name + category_value = cat_col.replace(f"{cov}_", "") + + # Create binary indicators + control_binary = (control_data[cov] == category_value).astype(int) + treatment_binary = (treatment_data[cov] == category_value).astype(int) + + if len(control_binary) > 1 and len(treatment_binary) > 1: + from scipy import stats as scipy_stats + + _, p_value = scipy_stats.ttest_ind( + treatment_binary, control_binary, equal_var=False + ) + diff = ( + result_df.loc[cat_col, treat] + - result_df.loc[cat_col, "Control"] + ) + stars = _get_significance_stars(p_value) + new_result_df.loc[cat_col, f"{treat} Diff"] = f"{diff:.3f}{stars}" + else: + new_result_df.loc[cat_col, f"{treat} Diff"] = None + + # No diff for count row + new_result_df.loc["count", f"{treat} Diff"] = None + + result_df = new_result_df + + # Round numeric values + for col in result_df.columns: + if "Diff" not in col: + for idx in result_df.index: + if idx != "count" and pd.notna(result_df.loc[idx, col]): + result_df.loc[idx, col] = round(result_df.loc[idx, col], 3) + + # Apply custom covariate names if provided + if covariate_names: + # Create a mapping for renaming, check both original covariates and result_df index + # This handles both regular covariates and categorical one-hot encoded columns + rename_mapping = {} + for idx in result_df.index: + if idx in covariate_names: + rename_mapping[idx] = covariate_names[idx] + result_df = result_df.rename(index=rename_mapping) + + # Ensure count row has integer type for non-diff columns + if "count" in result_df.index: + for col in result_df.columns: + if "Diff" not in col and pd.notna(result_df.loc["count", col]): + result_df.loc["count", col] = int(result_df.loc["count", col]) + + return result_df diff --git a/multilift/uplift/eval/_explore.py b/multilift/uplift/eval/_explore.py new file mode 100644 index 0000000..938c0d3 --- /dev/null +++ b/multilift/uplift/eval/_explore.py @@ -0,0 +1,5341 @@ +import warnings +from collections.abc import Sequence +from textwrap import dedent + +import numpy as np +import pandas as pd +from matplotlib import pyplot as plt +from matplotlib.ticker import FuncFormatter, MaxNLocator + +from multilift.constants import DEFAULT_RANDOM_SEED +from multilift.typing import NDArray, Series +from multilift.uplift.eval.utils import ( + _add_footnote_to_plot, + _get_significance_stars, + assign_bins, + compute_best_uplift, + compute_best_uplift_among_treatments, + compute_binned_uplift, + compute_qini, +) + + +class UpliftExploreEvaluator: + """ + Evaluates uplift by bin for multi-arm experiments. + + This class provides methods to analyze uplift performance by binning observations + based on predicted uplift scores and comparing actual vs predicted uplift across bins. + + Parameters + ---------- + control_name : str + Name/label for the control group + *treatment_names : str + Names/labels for treatment groups + n_bins : int, default=10 + Number of bins to create for analysis + + Usage + -------- + >>> import pandas as pd + >>> import numpy as np + >>> from multilift.uplift.eval import UpliftExploreEvaluator + ... + >>> # Create sample data + >>> t = pd.Series(['control', 'treatment_A', 'control', 'treatment_B'] * 25) + >>> y = pd.Series(np.random.normal(10, 2, 100)) + + ... # Predicted uplift for each treatment vs control + ... # In a real scenario, this would come from a model + ... # tau = model.predict(df) + import multilift.uplift.eval.utils >>> tau = np.random.uniform(-1, 5, (100, 1)) + ... + ... # Initialize evaluator + >>> evaluator = UpliftExploreEvaluator("control", 'treatment_A', 'treatment_B') + ... + ... # Plot results + >>> evaluator.plot_binned_actual_uplift(t, y, tau) + ... + ... # Compute binned uplift + >>> results_df = multilift.uplift.eval.utils.compute_binned_uplift(t, y, tau) + ... + ... # Compute uplift for each observation + >>> summary_df = evaluator.compute_uplift(t, y, tau) + ... + ... # Plot uplift for a specific treatment + >>> evaluator.plot_treatment(t, y, tau, treatment_name='treatment_A') + ... + ... # Get recommended treatment for each observation + >>> recommendations = evaluator.get_recommended_treatment(tau) + """ + + def __init__(self, control_name: str, *treatment_names: str, n_bins: int = 10): + self.control_name = control_name + self.treatment_names = treatment_names + self.n_bins = n_bins + + def get_recommended_treatment(self, tau: NDArray) -> pd.Series: + """Determine which treatment is recommended for each observation. + + Pick argmax; if there's a tie at the max, choose uniformly among tied treatments. + """ + tau = np.asarray(tau) + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + row_max = tau.max(axis=1, keepdims=True) + is_max = np.isclose(tau, row_max, atol=1e-12) + noise = rng.random(tau.shape) + tie_break_scores = np.where(is_max, noise, -np.inf) + chosen_idx = tie_break_scores.argmax(axis=1) + mapping = {i: name for i, name in enumerate(self.treatment_names)} + return pd.Series(chosen_idx).map(mapping) + + def plot_predicted_uplift( # noqa: C901, PLR0912, PLR0915 + self, + tau: NDArray | pd.DataFrame, + treatment_name: str | None = None, + treatment_idx: int | None = None, + title: str = "Predicted Uplift Curve", + subtitle: str | None = None, + footnote_extra: str | Sequence[str] | None = None, + figsize: tuple[int] = (10, 6), + show: bool = True, + save: bool = False, + path: str = "predicted_uplift.png", + ) -> None: + """ + Plot predicted uplift curve. + + This flexible function handles both single and multi-treatment uplift models: + + - **Single-treatment models**: Automatically plots the uplift for that treatment + - **Multi-treatment models**: by default (no treatment specified) plots + best uplift across all treatments. Specify ``treatment_name`` or + ``treatment_idx`` to plot a single treatment. + + Individuals are ranked by predicted uplift (highest to lowest) and plotted against + population fraction (0-1), making it easy to identify what percentage of the + population has positive predicted uplift. + + This plot helps answer questions like: + - What fraction of customers should we target? + - Where does the predicted uplift turn negative? + - What's the distribution of predicted uplift values? + - How does uplift vary between different treatments? + + Parameters + ---------- + tau : array-like or DataFrame + Predicted uplift (CATE) for each treatment vs control. Accepts a + 1-D array ``(n_samples,)`` or 2-D array ``(n_samples, n_treatments)`` + for single- or multi-treatment models, or a DataFrame with + treatment columns. + treatment_name : str, optional + Name of specific treatment to plot (for multi-treatment models only). + Must match a name in self.treatment_names (e.g., "B: WTP"). + If None, plots best uplift across all treatments. + treatment_idx : int, optional + Index of specific treatment to plot (0-based). Alternative to treatment_name. + For multi-treatment models: 0 = first treatment, 1 = second treatment, etc. + If None, plots best uplift across all treatments. + title : str, default="Predicted Uplift Curve" + Main title for the plot. + subtitle : str, optional + Subtitle displayed below the main title. Pass None to hide subtitle. + footnote_extra : str or list of str, optional + Additional text to append to the automatic footnote. Can be a string or list of strings. + figsize : tuple[int], default=(10, 6) + Figure size (width, height) in inches. + show : bool, default=True + Whether to display the plot using plt.show() + save : bool, default=False + Whether to save the plot to a file + path : str, default="predicted_uplift.png" + File path for saving the plot (only used if save=True) + + Returns + ------- + None + + Raises + ------ + ValueError + - If treatment_name not found in self.treatment_names + - If treatment_idx out of range for the number of treatments + + Notes + ----- + - The plot includes a marker showing where predicted uplift crosses zero (if applicable) + - X-axis shows population fraction from 0 to 1 (ranked by predicted uplift) + - Y-axis shows predicted uplift value + - A horizontal line at y=0 helps identify positive vs negative predictions + + Examples + -------- + **Example 1: Single-treatment model** + + >>> # Model with only one treatment arm + >>> evaluator = UpliftBinEvaluator("Control", "Treatment A") + >>> tau = model.predict(test_df) # shape: (n, 1) or (n, ) + >>> evaluator.plot_predicted_uplift( + ... tau=tau, + ... title="Treatment A Uplift Curve", + ... subtitle="Single-Treatment Model - Test Set" + ... ) + + **Example 2: Multi-treatment - best across all treatments (default)** + + >>> # Model with multiple treatment arms - show best uplift + >>> evaluator = UpliftBinEvaluator("Control", "B: WTP", "C: WTP -5 State") + >>> tau = model.predict(test_df) # shape: (n, 2) + >>> evaluator.plot_predicted_uplift( + ... tau=tau, + ... title="Best Uplift Across All Treatments", + ... subtitle="WTP Model v1.1.0 - Test Set", + ... footnote_extra="Shows max uplift per individual" + ... ) + + **Example 3: Multi-treatment - specific treatment by name** + + >>> # Plot predicted uplift for "B: WTP" only + >>> evaluator.plot_predicted_uplift( + ... tau=tau, + ... treatment_name="B: WTP", + ... title="Recipe B Uplift Curve", + ... subtitle="WTP Model v1.1.0 | Recipe B Only" + ... ) + + **Example 4: Multi-treatment - specific treatment by index** + + >>> # Plot predicted uplift for second treatment (Recipe C) + >>> evaluator.plot_predicted_uplift( + ... tau=tau, + ... treatment_idx=1, # 0-indexed: 0=B, 1=C + ... title="Recipe C Uplift Curve", + ... subtitle="WTP Model v1.1.0 | Recipe C Only" + ... ) + """ + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + # Determine number of arms and convert to numpy + if isinstance(tau, pd.DataFrame): + n_arms = tau.shape[1] + tau_arr = tau.to_numpy(dtype=np.float32) + else: + tau_arr = np.asarray(tau, dtype=np.float32) + n_arms = tau_arr.shape[1] if tau_arr.ndim == 2 else 1 # noqa: PLR2004 + + # Determine what to plot + if n_arms == 1: + # Single treatment model + tau_to_plot = tau_arr.flatten() + treat_label = self.treatment_names[0] if self.treatment_names else "treatment" + xlabel = ( + f"Population fraction ranked by predicted uplift for {treat_label} (high → low)" + ) + ylabel = "Predicted Uplift" + elif treatment_name is not None or treatment_idx is not None: + # Multi-treatment: plot specific treatment + if treatment_idx is None: + if treatment_name not in self.treatment_names: + raise ValueError( + f"Treatment '{treatment_name}' not found. " + f"Available treatments: {self.treatment_names}" + ) + treatment_idx = self.treatment_names.index(treatment_name) + + if treatment_idx < 0 or treatment_idx >= n_arms: + raise ValueError( + f"treatment_idx={treatment_idx} out of range. " + f"Model has {n_arms} treatment arms (indices 0-{n_arms - 1})" + ) + + tau_to_plot = tau_arr[:, treatment_idx] + treat_label = self.treatment_names[treatment_idx] + xlabel = ( + f"Population fraction ranked by predicted uplift for {treat_label} (high → low)" + ) + ylabel = "Predicted Uplift" + else: + # Multi-treatment: plot best across all treatments (default) + tau_to_plot = compute_best_uplift_among_treatments(tau_arr) + treat_label = "best treatment" + xlabel = "Population fraction ranked by model's best predicted uplift (high → low)" + ylabel = "Best Predicted Uplift" + + # Create DataFrame and sort + out = pd.DataFrame({"tau": tau_to_plot}) + out = out.sort_values("tau", ascending=False).reset_index(drop=True) + + # Plot + fig, ax = plt.subplots(figsize=figsize, constrained_layout=False) + x_pct = np.arange(1, len(out) + 1) / len(out) + ax.plot(x_pct, out["tau"], linewidth=2) + ax.axhline(0, color="black", linewidth=1, alpha=0.5) + + ax.set_xlim(0, 1) + ax.set_xlabel(xlabel, fontsize=10) + ax.set_ylabel(ylabel, fontsize=10) + + fig.suptitle(title, fontsize=14, fontweight="bold", y=0.98) + if subtitle: + fig.text(0.5, 0.935, subtitle, ha="center", va="top", fontsize=10) + + ax.tick_params(axis="both", which="major", labelsize=9) + ax.grid(True, alpha=0.3) + + plt.tight_layout(rect=[0, 0, 1, 0.90]) + + # Add zero-crossing marker + tau_vals = out["tau"].to_numpy() + chg_idx = np.where(np.diff(np.signbit(tau_vals)))[0] + + if chg_idx.size: + i = chg_idx[0] + x0, x1 = x_pct[i], x_pct[i + 1] + y0, y1 = tau_vals[i], tau_vals[i + 1] + x_cross = x0 + (0 - y0) * (x1 - x0) / (y1 - y0) + + ax.scatter([x_cross], [0], s=160, zorder=5) + + ylo, yhi = ax.get_ylim() + y_offset = 0.02 * (yhi - ylo) + ax.annotate( + f"Pred. uplift ≈ 0 at ~{x_cross * 100:.1f}th percentile", + xy=(x_cross, 0), + xytext=(x_cross, 0 + y_offset), + ha="center", + va="bottom", + arrowprops=dict(arrowstyle="-", lw=1), + ) + + # Add footnote + if n_arms == 1 or (treatment_name is not None or treatment_idx is not None): + # Single treatment or specific treatment + base_foot = dedent(f""" + Predicted uplift for {treat_label}. Each individual ranked from highest to lowest + predicted uplift on the horizontal axis. N = {len(out):,} + """).strip() + else: + # Best across all treatments + base_foot = dedent(f""" + Predicted uplift for {treat_label} across all {len(self.treatment_names)} treatment + arms for each individual, ranked from highest to lowest on the horizontal axis. + N = {len(out):,} + """).strip() + + if footnote_extra: + if isinstance(footnote_extra, list | tuple): + extra = "\n".join(s.strip() for s in footnote_extra if s is not None) + else: + extra = str(footnote_extra).strip() + foot = f"{base_foot} {extra}" if extra else base_foot + else: + foot = base_foot + + try: + _add_footnote_to_plot(fig, ax, foot, fontsize=9, gap_pts=8, color="0.35") + except Exception: + pass + + if save: + fig.savefig(path, bbox_inches="tight") + if show: + plt.show() + + def compute_binned_treatment_mix(self, tau: NDArray | pd.DataFrame) -> pd.DataFrame: + """ + Compute percent of recommended treatment by bin. + + Note: This function is most useful for multi-treatment uplift models where + different treatments may be recommended for different individuals. For + single-treatment models, all observations will be assigned to the same treatment. + + Parameters + ---------- + tau : array-like or DataFrame, shape (n_samples, n_treatments) + Predicted uplift (CATE) for each treatment vs control. + Works with both single-treatment and multi-treatment models. + + Returns + ------- + pd.DataFrame + Pandas DataFrame with columns: bin, , , ... + Values are fractions in [0,1] representing the proportion of each bin + recommended for each treatment. + """ + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + # Determine number of arms + if isinstance(tau, pd.DataFrame): + n_arms = tau.shape[1] + tau_arr = tau.to_numpy(dtype=np.float32) + else: + tau_arr = np.asarray(tau, dtype=np.float32) + n_arms = tau_arr.shape[1] if tau_arr.ndim == 2 else 1 # noqa: PLR2004 + + if n_arms <= 1: + warnings.warn( + "Treatment mix plots are more informative for multi-treatment uplift models. " + "With only one treatment, all observations will be assigned to the same treatment.", + UserWarning, + stacklevel=2, + ) + + # Compute best uplift and bins + tau_best = compute_best_uplift(tau_arr) + bins = assign_bins(pd.Series(tau_best), self.n_bins) + recommended = self.get_recommended_treatment(tau_arr) + + # Create DataFrame + df = pd.DataFrame({"bin": bins, "recommended_treatment": recommended}) + + # % of rows in each bin where each treatment is recommended + shares = ( + df.groupby("bin", observed=True)["recommended_treatment"] + .value_counts(normalize=True) + .rename("pct") + .reset_index() + ) + + out = ( + shares.pivot(index="bin", columns="recommended_treatment", values="pct") + .fillna(0.0) + .reset_index() + ) + out.columns.name = None + + # Reindex columns so all treatments appear (even if 0% in a bin) + # Use treatment names if tau is a DataFrame, otherwise use column indices + if isinstance(tau, pd.DataFrame): + treatment_cols = list(tau.columns) + else: + treatment_cols = list(self.treatment_names) + + cols = ["bin", *treatment_cols] + for c in treatment_cols: + if c not in out.columns: + out[c] = 0.0 + return out.reindex(columns=cols) + + def plot_binned_treatment_mix( # noqa: PLR0915 + self, + tau: NDArray | pd.DataFrame, + title: str = "Recommended Treatment Mix by Bin", + subtitle: str | None = None, + footnote_extra: str | Sequence[str] | None = None, + figsize: tuple[int] = (10, 6), + show: bool = True, + save: bool = False, + path: str = "binned_treatment_mix.png", + ) -> None: + """ + Plot treatment recommendation mix by predicted uplift bin. + + Divides individuals into bins based on their predicted uplift and shows what proportion + of each bin is recommended for each treatment. This is a stacked bar chart where each + bar represents one bin and sums to 1.0 (100% of that bin). + + Note: This plot is most informative for multi-treatment uplift models where different + treatments may be recommended for different individuals. For single-treatment models, + all observations will be assigned to the same treatment, resulting in uniform bars. + + This plot helps answer questions like: + - Are high-uplift bins dominated by one treatment recommendation? + - How does the recommended treatment mix change across uplift bins? + - Is the model recommending different treatments for different customer segments? + + Parameters + ---------- + tau : array-like or DataFrame, shape (n_samples, n_treatments) + Predicted uplift (CATE) for each treatment vs control. + Works with both single-treatment and multi-treatment models. + If DataFrame, columns should correspond to treatment names. + title : str, default="Recommended Treatment Mix by Bin" + Main title for the plot. + subtitle : str, optional + Subtitle displayed below the main title. Pass None to hide subtitle. + footnote_extra : str or list of str, optional + Additional text to append to the automatic footnote. Can be a string or list of strings. + figsize : tuple[int], default=(10, 6) + Figure size (width, height) in inches. + show : bool, default=True + Whether to display the plot using plt.show() + save : bool, default=False + Whether to save the plot to a file + path : str, default="binned_treatment_mix.png" + File path for saving the plot (only used if save=True) + + Returns + ------- + None + + Notes + ----- + - Each bar represents one uplift bin (from high predicted uplift to low) + - Bars are stacked and sum to 1.0 (representing 100% of observations in that bin) + - Colors correspond to different treatment recommendations + - Bins are created by ranking individuals by their best predicted uplift + - The number of bins is determined by self.n_bins (set when creating UpliftBinEvaluator) + - A warning will be issued for single-treatment models + + Examples + -------- + >>> # Create evaluator with 10 bins + >>> evaluator = UpliftBinEvaluator("Control", "B: WTP", "C: WTP -5 State", n_bins=10) + >>> + >>> # Predict uplift for test set + >>> tau = model.predict(test_df) # shape: (n, 2) + >>> + >>> # Plot treatment mix by bin + >>> evaluator.plot_binned_treatment_mix( + ... tau=tau, + ... title="Treatment Recommendations", + ... subtitle="WTP Model v1.1.0 - Test Set", + ... footnote_extra="Model recommends treatment based on highest predicted uplift" + ... ) + """ + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + out = self.compute_binned_treatment_mix(tau) + + # Plot stacked bars + x = np.arange(len(out)) + bottoms = np.zeros(len(out)) + + fig, ax = plt.subplots(figsize=figsize) + treatment_cols = [col for col in out.columns if col != "bin"] + for col in treatment_cols: + vals = out[col].to_numpy() + ax.bar(x, vals, bottom=bottoms, label=col) + bottoms += vals + + ax.set_ylim(0, 1) + # Set y-axis tick labels + yticks = ax.get_yticks() + ax.set_yticks(yticks) + ax.set_yticklabels([f"{tick:.1f}" for tick in yticks], fontsize=10) + # Set x-axis ticks and labels - use actual bin numbers (1-based) + bin_labels = out["bin"].to_numpy() # bin numbers from assign_bins (1-based) + ax.xaxis.set_major_locator( + MaxNLocator(nbins=12, integer=True) + ) # auto choose up to ~12 ticks + ax.xaxis.set_major_formatter( + FuncFormatter( + lambda v, p: str(bin_labels[int(v)]) if 0 <= int(v) < len(bin_labels) else "" + ) + ) + ax.set_xlabel("Bin", fontsize=10) + ax.set_ylabel("Share of recommended treatment", fontsize=10) + + # Add title and subtitle + fig.suptitle(title, fontsize=14, fontweight="bold", y=0.98) + if subtitle: + fig.text(0.5, 0.935, subtitle, ha="center", va="top", fontsize=10) + + ax.tick_params(axis="both", which="major", labelsize=9) + + # Make room for the outside legend + fig.tight_layout(rect=[0, 0, 0.82, 1]) + + # Legend + leg = ax.legend( + title="Treatment", + loc="upper left", + bbox_to_anchor=(1.02, 1), + ncol=1, + borderaxespad=0, + frameon=True, + ) + leg.get_frame().set_facecolor("none") # transparent fill + leg.get_frame().set_alpha(0) # ensure no opacity + leg.get_frame().set_edgecolor("none") # optional: hide border + + # gridlines behind bars + ax.set_axisbelow(True) + ax.grid(True, axis="y", linestyle="--", linewidth=0.7, alpha=1) + + # Footnote + base_foot = dedent(f""" + Share of model-recommended treatment by predicted-uplift bin. Model recommends treatment + based on highest predicted uplift. N = {len(tau):,} observations split evenly into + {self.n_bins} bins + """).strip() + + if footnote_extra: + if isinstance(footnote_extra, list | tuple): + extra = "\n".join(s.strip() for s in footnote_extra if s is not None) + else: + extra = str(footnote_extra).strip() + foot = f"{base_foot} {extra}" if extra else base_foot + else: + foot = base_foot + + try: + _add_footnote_to_plot(fig, ax, foot, fontsize=9, gap_pts=8, color="0.35") + except Exception: + pass # don't fail the plot if footnote layout trips + + if save: + fig.savefig(path, bbox_inches="tight") + if show: + plt.show() + + def compute_uplift(self, t: Series, y: Series, tau: NDArray) -> pd.DataFrame: + """ + Compute uplift by bin for a multi-arm experiment. + + Parameters + ---------- + t : Series + Treatment assignment series (0=control, 1=treatment1, 2=treatment2, etc.) + y : Series + Outcome series (e.g., revenue, conversion) + tau : NDArray, shape (n, m) + Predicted uplift (CATE) for each treatment vs control + + Returns + ------- + pd.DataFrame + A summary DataFrame with actual uplift per user + """ + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + df = pd.DataFrame({"t": t, "y": y}) + if isinstance(tau, pd.DataFrame): + tau = tau.to_numpy(dtype=np.float32) + + # Add tau columns + for i, _ in enumerate(self.treatment_names): + df[f"tau_{i}"] = tau[:, i] + + df["tau_best"] = compute_best_uplift(tau) + df["bin"] = assign_bins(df["tau_best"], self.n_bins) + df["recommended_treatment"] = self.get_recommended_treatment(tau) + + for i, _ in enumerate(self.treatment_names): + agg_df, assigned_bins = compute_binned_uplift( + t, + y, + tau[:, i], + control_name=self.control_name, + treatment_name=self.treatment_names[i], + n_bins=self.n_bins, + ) + assigned_bins = assigned_bins.rename(f"bin_{i}") + agg_df = agg_df.rename( + columns={ + self.control_name: "y_ctrl", + "bin": f"bin_{i}", + "uplift": f"tau_{i}_actual", + **{t: f"y_{i}" for i, t in enumerate(self.treatment_names)}, + } + ) + df = df.join(assigned_bins) + df = df.merge( + agg_df[[f"tau_{i}_actual"]], + left_on=assigned_bins.name, + right_index=True, + how="left", + ) + + df["tau_actual"] = pd.Series(np.nan, index=df.index, dtype=np.float32) + + for i, treatment_label in enumerate(self.treatment_names): + mask = df["recommended_treatment"] == treatment_label + uplift_col = f"tau_{i}_actual" + df.loc[mask, "tau_actual"] = df.loc[mask, uplift_col].astype(np.float32) + + return df + + def compute_binned_uplift(self, t: Series, y: Series, tau: NDArray) -> pd.DataFrame: + """ + Analyze the uplift by bin for a multi-arm experiment. + + Parameters + ---------- + t : Series + Treatment assignment series (0=control, 1=treatment1, 2=treatment2, etc.) + y : Series + Outcome series (e.g., revenue, conversion) + tau : NDArray, shape (n, m) + Predicted uplift (CATE) for each treatment vs control + + Returns + ------- + pd.DataFrame + A DataFrame with the mean outcome by bin and treatment (n_bins, 1) + """ + eval_df = self.compute_uplift(t, y, tau) + return eval_df.groupby(["bin"], observed=True)["tau_actual"].agg(mean="mean").reset_index() + + def _create_uplift_plot( + self, + results_df: pd.DataFrame, + title: str, + figsize: tuple[int], + add_footnote: bool = False, + total_observations: int | None = None, + ) -> plt.Axes: + """Create a standardized uplift plot from results DataFrame. + + Parameters + ---------- + results_df : pd.DataFrame + Pandas DataFrame with 'mean' column containing uplift values + title : str + Title for the plot + figsize : tuple[int] + Figure size + add_footnote : bool, default=False + Whether to add a footnote with observation count + total_observations : int, optional + Total number of observations for footnote + + Returns + ------- + plt.Axes + """ + colors = pd.Series("tab:orange", index=results_df.index) + colors[results_df["mean"] >= 0] = "tab:green" + colors[results_df["mean"] < 0] = "tab:red" + + # Create plot + fig, ax = plt.subplots(figsize=figsize) + ax.bar(results_df.index.astype(str), results_df["mean"], color=colors.tolist()) + ax.axhline(0, color="black", linestyle="-", linewidth=1, alpha=1) + + ax.set_title(title) + ax.set_xlabel("Binned Score (model's uplift predictions ranked high → low)", fontsize=10) + ax.set_ylabel("Actual Uplift Per User (from experiment)", fontsize=10) + + # Format y-axis with dollar signs + ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: f"${x:,.2f}" if x != 0 else "$0")) + + # Style the plot + ax.spines["top"].set_visible(False) + ax.spines["right"].set_visible(False) + ax.set_axisbelow(True) + ax.yaxis.grid(True, which="major", linewidth=0.8, alpha=0.35) + ax.tick_params(axis="both", which="major", labelsize=9) + + # Add footnote if requested + if add_footnote and total_observations is not None: + try: + fig = ax.get_figure() + plt.tight_layout() + footnote_text = dedent(f""" + In this graph, there are {total_observations:,} + observations split into {self.n_bins} bins. + """).strip() + _add_footnote_to_plot(fig, ax, footnote_text, fontsize=9, gap_pts=8) + except Exception: + # If we can't add footnote (e.g., in subplot), just continue + pass + + return ax + + def plot_binned_uplift( + self, + t: Series, + y: Series, + tau: NDArray, + title: str = "Actual Uplift by Bins", + subtitle: str | None = None, + footnote_extra: str | Sequence[str] | None = None, + figsize: tuple[int] = (10, 6), + show: bool = True, + save: bool = False, + path: str = "uplift_bins.png", + ) -> plt.Axes: + """ + Plot actual uplift by predicted uplift bins. + + This function bins individuals by their predicted uplift and shows the actual + observed uplift for each bin. This helps validate model performance by comparing + predicted vs actual uplift patterns. + + Parameters + ---------- + t : Series + Treatment assignment series (values should match control_name and treatment_names) + y : Series + Outcome series (e.g., revenue, conversion) + tau : NDArray, shape (n_samples, n_treatments) + Predicted uplift (CATE) for each treatment vs control + title : str, default="Actual Uplift by Bins" + Main title for the plot + subtitle : str, optional + Subtitle displayed below the main title. Pass None to hide subtitle. + footnote_extra : str or list of str, optional + Additional text to append to the automatic footnote. Can be a string or list of strings. + figsize : tuple[int], default=(10, 6) + Figure size (width, height) in inches + show : bool, default=True + Whether to display the plot using plt.show() + save : bool, default=False + Whether to save the plot to a file + path : str, default="uplift_bins.png" + File path for saving the plot (only used if save=True) + + Returns + ------- + plt.Axes + The axes object of the plot + + Examples + -------- + >>> evaluator = UpliftExploreEvaluator("Control", "Treatment A", "Treatment B", n_bins=10) + >>> evaluator.plot_binned_uplift( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... title="Model Performance: Actual Uplift by Bin", + ... save=True, + ... path="uplift_validation.png" + ... ) + """ + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + results_df = self.compute_binned_uplift(t, y, tau) + ax = self._create_uplift_plot( + results_df, title, figsize, add_footnote=True, total_observations=len(t) + ) + + # Add subtitle if provided + if subtitle is not None: + ax.set_title(subtitle, fontsize=10, pad=10, loc="center") + + # Add footnote if provided + if footnote_extra is not None: + try: + fig = ax.get_figure() + if isinstance(footnote_extra, str): + footnote_text = footnote_extra + else: + footnote_text = " ".join(footnote_extra) + _add_footnote_to_plot(fig, ax, footnote_text) + except Exception: + pass + + if save: + ax.get_figure().savefig(path, bbox_inches="tight") + if show: + plt.show() + + return ax + + @staticmethod + def _drop_missing_tau(t: Series, y: Series, tau: NDArray) -> tuple[Series, Series, NDArray]: + """Drop rows where predicted uplift (tau) contains NaN values. + + Parameters + ---------- + t : Series + Treatment assignment series. + y : Series + Outcome series. + tau : NDArray + Predicted uplift array (1-D or 2-D). + + Returns + ------- + tuple[Series, Series, NDArray] + Filtered (t, y, tau) with NaN-tau rows removed. + """ + tau_arr = np.asarray(tau, dtype=np.float64) + nan_mask = np.isnan(tau_arr).any(axis=1) if tau_arr.ndim > 1 else np.isnan(tau_arr) + n_missing = int(nan_mask.sum()) + + if n_missing > 0: + n_total = len(tau_arr) + warnings.warn( + f"Dropped {n_missing} out of {n_total} observations " + f"due to missing predicted uplift (tau).", + UserWarning, + stacklevel=3, + ) + keep = ~nan_mask + t = t.iloc[keep.nonzero()[0]].reset_index(drop=True) + y = y.iloc[keep.nonzero()[0]].reset_index(drop=True) + tau = ( + tau_arr[keep] + if not isinstance(tau, pd.DataFrame) + else tau.iloc[keep.nonzero()[0]].reset_index(drop=True) + ) + + return t, y, tau + + def compute_binned_actual_uplift( # noqa: C901, PLR0912, PLR0915 + self, + t: Series, + y: Series, + tau: NDArray, + treatment_name: str | None = None, + treatment_idx: int | None = None, + return_se: bool = False, + ) -> pd.DataFrame | tuple[pd.DataFrame, pd.DataFrame]: + """ + Compute actual observed uplift by bin for the recommended treatments. + + This function bins individuals by their predicted uplift, then calculates the + actual observed uplift for each treatment within each bin. The final combined + uplift is a weighted average of individual treatment uplifts, weighted by the + proportion of people recommended for each treatment in that bin. + + Parameters + ---------- + t : Series + Treatment assignment series (values should match control_name and treatment_names) + y : Series + Outcome series (e.g., revenue, conversion) + tau : NDArray, shape (n_samples, n_treatments) + Predicted uplift (CATE) for each treatment vs control + treatment_name : str, optional + Name of specific treatment to analyze. If provided, only analyzes this treatment. + Cannot be used with treatment_idx. + treatment_idx : int, optional + Index of specific treatment to analyze (0-based). If provided, only analyzes + this treatment. Cannot be used with treatment_name. + return_se : bool, default=False + If True, also returns a DataFrame with standard errors for each uplift estimate. + Standard errors are computed as: SE = sqrt(var_t/n_t + var_c/n_c) where var_t + and var_c are the variances in treatment/control groups, n_t and n_c are sizes. + + Returns + ------- + pd.DataFrame or tuple[pd.DataFrame, pd.DataFrame] + If ``return_se=False`` (default), returns a single DataFrame with + uplift estimates. + + If ``return_se=True``, returns a tuple ``(uplift_df, se_df)`` where + ``uplift_df`` contains uplift estimates and ``se_df`` contains + matching standard errors. + + For **multi-treatment** models the uplift DataFrame contains columns + ``bin``, ``uplift_``, ``weight_`` (per treatment), + and ``combined_uplift``. The SE DataFrame contains ``bin``, + ``se_`` (per treatment), and ``se_combined``. + + For **single-treatment** models the uplift DataFrame contains + ``bin`` and ``uplift``. The SE DataFrame contains ``bin`` and ``se``. + + Notes + ----- + - Bins are created based on tau_best (highest predicted uplift) + - Uplift for each treatment is calculated only among individuals recommended that treatment + - Combined uplift uses recommendation proportions as weights + - Standard errors account for sampling variability in both treatment and control groups + - For combined uplift, SE is computed as: sqrt(sum((weight_i * SE_i)^2)) + - For single-treatment models, output columns are simplified for clarity + - This helps validate whether the model's treatment recommendations lead to actual uplift + + Examples + -------- + >>> evaluator = UpliftExploreEvaluator("Control", "Treatment A", "Treatment B", n_bins=10) + >>> # Get uplift estimates only + >>> results = evaluator.compute_binned_actual_uplift( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau + ... ) + >>> + >>> # Get uplift estimates with standard errors + >>> uplift_df, se_df = evaluator.compute_binned_actual_uplift( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... return_se=True + ... ) + >>> print("Uplift:", uplift_df["combined_uplift"].iloc[0]) + >>> print("SE:", se_df["se_combined"].iloc[0]) + """ + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + # Drop observations with missing predicted uplift + t, y, tau = self._drop_missing_tau(t, y, tau) + + # Convert tau to numpy array if needed + if isinstance(tau, pd.DataFrame): + tau_arr = tau.to_numpy(dtype=np.float32) + else: + tau_arr = np.asarray(tau, dtype=np.float32) + + # Handle specific treatment selection + if treatment_name is not None and treatment_idx is not None: + raise ValueError("Cannot specify both treatment_name and treatment_idx") + + if treatment_name is not None: + if treatment_name not in self.treatment_names: + raise ValueError( + f"treatment_name='{treatment_name}' not found in treatment_names. " + f"Available treatments: {self.treatment_names}" + ) + treatment_idx = self.treatment_names.index(treatment_name) + + if treatment_idx is not None: + n_arms = tau_arr.shape[1] if tau_arr.ndim == 2 else 1 # noqa: PLR2004 + if treatment_idx < 0 or treatment_idx >= n_arms: + raise ValueError( + f"treatment_idx={treatment_idx} out of range. " + f"Model has {n_arms} treatment arms (indices 0-{n_arms - 1})" + ) + # Select only the specified treatment + tau_arr = tau_arr[:, treatment_idx : treatment_idx + 1] + treatments_to_analyze = [self.treatment_names[treatment_idx]] + else: + treatments_to_analyze = list(self.treatment_names) + + is_single_treatment = len(treatments_to_analyze) == 1 + + # Compute tau_best and assign bins + # For single-treatment analysis, use raw predicted uplift (no clip at 0) + # so that negative predictions are ranked meaningfully across lower bins. + if is_single_treatment: + tau_best = compute_best_uplift_among_treatments(tau_arr) + else: + tau_best = compute_best_uplift(tau_arr) + bins = assign_bins(pd.Series(tau_best), self.n_bins) + + # Get recommended treatment for each individual + # For specific treatment selection, all individuals are "recommended" that treatment + if treatment_name is not None or treatment_idx is not None: + recommended = pd.Series([treatments_to_analyze[0]] * len(tau_arr)) + else: + recommended = self.get_recommended_treatment(tau_arr) + + # Create working DataFrame + df = pd.DataFrame( + {"bin": bins, "t": t.values, "y": y.values, "recommended_treatment": recommended} + ) + + # Initialize results list + results = [] + se_results = [] if return_se else None + + # Process each bin + for bin_num in range(1, self.n_bins + 1): + bin_mask = df["bin"] == bin_num + bin_data = df[bin_mask] + + if len(bin_data) == 0: + continue + + row = {"bin": bin_num} + se_row = {"bin": bin_num} if return_se else None + treatment_uplifts = [] + treatment_weights = [] + treatment_ses = [] + + # Calculate uplift for each treatment + for treat_name in treatments_to_analyze: + # Filter to individuals recommended this treatment in this bin + recommended_mask = bin_data["recommended_treatment"] == treat_name + recommended_data = bin_data[recommended_mask] + + if len(recommended_data) == 0: + if not is_single_treatment: + row[f"uplift_{treat_name}"] = np.nan + row[f"weight_{treat_name}"] = 0.0 + if return_se: + se_row[f"se_{treat_name}"] = np.nan + continue + + # Calculate weight (proportion recommended this treatment) + weight = len(recommended_data) / len(bin_data) + if not is_single_treatment: + row[f"weight_{treat_name}"] = weight + + # Get outcomes for those who received this treatment + treatment_mask = recommended_data["t"] == treat_name + treatment_outcomes = recommended_data[treatment_mask]["y"] + + # Get outcomes for those who received control (but were recommended this treatment) + control_mask = recommended_data["t"] == self.control_name + control_outcomes = recommended_data[control_mask]["y"] + + # Calculate uplift and standard error + if len(treatment_outcomes) > 0 and len(control_outcomes) > 0: + uplift = treatment_outcomes.mean() - control_outcomes.mean() + if not is_single_treatment: + row[f"uplift_{treat_name}"] = uplift + treatment_uplifts.append(uplift) + treatment_weights.append(weight) + + # Calculate standard error for uplift + if return_se: + n_t = len(treatment_outcomes) + n_c = len(control_outcomes) + var_t = treatment_outcomes.var(ddof=1) if n_t > 1 else 0 + var_c = control_outcomes.var(ddof=1) if n_c > 1 else 0 + se = np.sqrt(var_t / n_t + var_c / n_c) + if not is_single_treatment: + se_row[f"se_{treat_name}"] = se + treatment_ses.append(se) + elif not is_single_treatment: + row[f"uplift_{treat_name}"] = np.nan + if return_se: + se_row[f"se_{treat_name}"] = np.nan + + # Calculate combined uplift as weighted average + if len(treatment_uplifts) > 0: + # Normalize weights to sum to 1 (in case of missing data) + total_weight = sum(treatment_weights) + if total_weight > 0: + normalized_weights = [w / total_weight for w in treatment_weights] + combined = sum(u * w for u, w in zip(treatment_uplifts, normalized_weights)) + row["combined_uplift"] = combined + + # Calculate combined SE using weighted SE formula + if return_se and len(treatment_ses) > 0: + combined_se = np.sqrt( + sum((w * se) ** 2 for w, se in zip(normalized_weights, treatment_ses)) + ) + se_row["se_combined"] = combined_se + else: + row["combined_uplift"] = np.nan + if return_se: + se_row["se_combined"] = np.nan + else: + row["combined_uplift"] = np.nan + if return_se: + se_row["se_combined"] = np.nan + + results.append(row) + if return_se: + se_results.append(se_row) + + # Create results DataFrame + results_df = pd.DataFrame(results) + + # For single treatment, rename "combined_uplift" to just "uplift" for clarity + if is_single_treatment and "combined_uplift" in results_df.columns: + results_df = results_df.rename(columns={"combined_uplift": "uplift"}) + + if return_se: + se_df = pd.DataFrame(se_results) + # Rename SE column for single treatment + if is_single_treatment and "se_combined" in se_df.columns: + se_df = se_df.rename(columns={"se_combined": "se"}) + return results_df, se_df + return results_df + + def plot_binned_actual_uplift( # noqa: PLR0915, C901, PLR0912 + self, + t: Series, + y: Series, + tau: NDArray, + treatment_name: str | None = None, + treatment_idx: int | None = None, + title: str = "Actual Uplift by Bins", + subtitle: str | None = None, + footnote_extra: str | Sequence[str] | None = None, + show_ci: bool = True, + confidence_level: float = 0.95, + metric_format: str = "currency", + figsize: tuple[int] = (10, 6), + show: bool = True, + save: bool = False, + path: str = "binned_actual_uplift.png", + ) -> plt.Axes: + """ + Plot actual observed uplift by bin for the recommended treatments. + + This function bins individuals by their predicted uplift, then calculates the + actual observed uplift for each treatment within each bin. The final combined + uplift is a weighted average of individual treatment uplifts, weighted by the + proportion of people recommended for each treatment in that bin. + + Parameters + ---------- + t : Series + Treatment assignment series (values should match control_name and treatment_names) + y : Series + Outcome series (e.g., revenue, conversion) + tau : NDArray, shape (n_samples, n_treatments) + Predicted uplift (CATE) for each treatment vs control + treatment_name : str, optional + Name of specific treatment to plot. If provided, only plots this treatment. + Cannot be used with treatment_idx. + treatment_idx : int, optional + Index of specific treatment to plot (0-based). If provided, only plots this treatment. + Cannot be used with treatment_name. + title : str, default="Actual Uplift by Bins" + Main title for the plot + subtitle : str, optional + Subtitle displayed below the main title + footnote_extra : str or list of str, optional + Additional text to append to the automatic footnote + show_ci : bool, default=True + Whether to show confidence interval error bars on the plot. + If True, also affects bar coloring based on whether CI crosses zero. + confidence_level : float, default=0.95 + Confidence level for error bars (e.g., 0.95 for 95% confidence intervals). + Only used if show_ci=True. Confidence intervals computed: CI = mean ± z * SE. + metric_format : str, default="number" + Format for y-axis values: "currency" for dollar amounts, "number" for plain values + figsize : tuple[int], default=(10, 6) + Figure size (width, height) + show : bool, default=True + Whether to display the plot using plt.show() + save : bool, default=False + Whether to save the plot to a file + path : str, default="binned_actual_uplift.png" + File path for saving the plot (only used if save=True) + + Returns + ------- + ax : plt.Axes + The axes of the plot + + Notes + ----- + - Bins are created based on tau_best (highest predicted uplift) + - Uplift for each treatment is calculated only among individuals recommended that treatment + - Combined uplift uses recommendation proportions as weights + - Bar coloring when ``show_ci=True``: green if CI entirely above 0 + (stat. sig. positive), red if CI entirely below 0 (stat. sig. negative), + orange if CI crosses 0 (not significant). + - Bar coloring when ``show_ci=False``: green if point estimate >= 0, + red if point estimate < 0. + - Error bars show confidence intervals based on standard errors of the uplift estimates + - Standard errors account for sampling variability within treatment and control groups + - For combined uplift, standard errors are computed using the weighted combination formula + - This helps validate whether the model's treatment recommendations lead to actual uplift + + Examples + -------- + >>> evaluator = UpliftBinEvaluator("Control", "Treatment A", "Treatment B", n_bins=10) + >>> # Default: 95% confidence intervals + >>> evaluator.plot_binned_actual_uplift( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... title="Actual Uplift by Predicted Uplift Bin", + ... subtitle="Test Set Results" + ... ) + >>> + >>> # Custom confidence level: 99% CI + >>> evaluator.plot_binned_actual_uplift( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... confidence_level=0.99, + ... title="Actual Uplift with 99% Confidence Intervals" + ... ) + >>> + >>> # Analyze specific treatment only + >>> evaluator.plot_binned_actual_uplift( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... treatment_name="Treatment A", + ... title="Treatment A: Actual Uplift by Bin" + ... ) + >>> + >>> # Without confidence intervals (faster, simpler coloring) + >>> evaluator.plot_binned_actual_uplift( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... show_ci=False, + ... title="Actual Uplift by Bin (No CI)" + ... ) + """ + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + # Drop observations with missing predicted uplift + t, y, tau = self._drop_missing_tau(t, y, tau) + + # Get the computed results, with standard errors only if needed + if show_ci: + results_df, se_df = self.compute_binned_actual_uplift( + t, + y, + tau, + treatment_name=treatment_name, + treatment_idx=treatment_idx, + return_se=True, + ) + + # Determine which uplift and SE columns to use + uplift_col = "uplift" if "uplift" in results_df.columns else "combined_uplift" + se_col = "se" if "se" in se_df.columns else "se_combined" + + # Calculate confidence intervals using z-score + from scipy import stats + + z_score = stats.norm.ppf((1 + confidence_level) / 2) + ci_lower = results_df[uplift_col] - z_score * se_df[se_col] + ci_upper = results_df[uplift_col] + z_score * se_df[se_col] + else: + results_df = self.compute_binned_actual_uplift( + t, + y, + tau, + treatment_name=treatment_name, + treatment_idx=treatment_idx, + return_se=False, + ) + uplift_col = "uplift" if "uplift" in results_df.columns else "combined_uplift" + ci_lower = None + ci_upper = None + + # Determine what was analyzed for axis labels + # Check if this is a single-treatment scenario + n_treatments = len(self.treatment_names) + is_specific_treatment = treatment_name is not None or treatment_idx is not None + + if is_specific_treatment or n_treatments == 1: + # Single treatment or specific treatment selected + if treatment_name is not None: + ranking_label = f"Ranked by predicted uplift for {treatment_name} (high → low)" + elif treatment_idx is not None: + treat_label = self.treatment_names[treatment_idx] + ranking_label = f"Ranked by predicted uplift for {treat_label} (high → low)" + else: + # Single treatment model - just say "Ranked by predicted uplift" + ranking_label = "Ranked by predicted uplift (high → low)" + else: + # Multi-treatment model analyzing all treatments + ranking_label = "Ranked by best predicted uplift across all treatments (high → low)" + + # Determine bar colors based on CI bounds (if available) or point estimates + if show_ci: + # Color based on whether CI crosses zero + colors = pd.Series("tab:orange", index=results_df.index) # overlaps 0 + colors[ci_lower > 0] = "tab:green" # CI entirely > 0 (stat. sig. positive) + colors[ci_upper < 0] = "tab:red" # CI entirely < 0 (stat. sig. negative) + else: + # Color based on point estimate sign + colors = pd.Series("tab:orange", index=results_df.index) + colors[results_df[uplift_col] >= 0] = "tab:green" + colors[results_df[uplift_col] < 0] = "tab:red" + + # Create bar chart + fig, ax = plt.subplots(figsize=figsize) + + x_positions = np.arange(len(results_df)) + ax.bar(x_positions, results_df[uplift_col], color=colors.tolist()) + + # Add error bars for confidence intervals (if requested) + if show_ci: + uplift_values = results_df[uplift_col].values + errors_lower = uplift_values - ci_lower.values + errors_upper = ci_upper.values - uplift_values + errors = np.array([errors_lower, errors_upper]) + + ax.errorbar( + x_positions, + uplift_values, + yerr=errors, + fmt="none", + ecolor="black", + elinewidth=1.5, + capsize=4, + capthick=1.5, + zorder=3, + ) + + ax.set_xticks(x_positions) + ax.set_xticklabels(results_df["bin"].astype(str)) + ax.axhline(y=0, color="black", linestyle="-", linewidth=1, alpha=1) + + ax.set_xlabel(f"Bin ({ranking_label})", fontsize=10) + ax.set_ylabel("Actual Uplift (from experiment)", fontsize=10) + ax.tick_params(axis="both", which="major", labelsize=9) + + # Format y-axis with dollar sign and proper decimals for currency + if metric_format == "currency": + from matplotlib.ticker import FuncFormatter + + def y_axis_formatter(value, pos): + prefix = "$" + # Always show at most 2 decimal places for currency + return f"{prefix}{value:,.2f}" + + ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter)) + + ax.grid(True, axis="y", linestyle="--", linewidth=0.7, alpha=0.7) + ax.set_axisbelow(True) + + # Add title and subtitle + fig.suptitle(title, fontsize=14, fontweight="bold", y=0.98) + if subtitle: + fig.text(0.5, 0.935, subtitle, ha="center", va="top", fontsize=10) + + plt.tight_layout(rect=[0, 0.05, 1, 0.96]) + + # Add footnote + n_obs = len(t) + + # Determine if this is single-treatment or multi-treatment scenario + n_treatments = len(self.treatment_names) + is_single_treatment = ( + treatment_name is not None or treatment_idx is not None or n_treatments == 1 + ) + + if show_ci: + ci_pct = int(confidence_level * 100) + if is_single_treatment: + # Single treatment: simple difference in means + base_foot = dedent(f""" + Average observed uplift per bin. + Error bars show {ci_pct}% confidence intervals. + N = {n_obs:,} observations split into {self.n_bins} bins + """).strip() + else: + # Multi-treatment: weighted average across treatments + base_foot = dedent(f""" + Actual uplift by bin, computed as weighted average across treatments where + weights are the model's treatment recommendations. + Error bars show {ci_pct}% confidence intervals. + N = {n_obs:,} observations split into {self.n_bins} bins + """).strip() + elif is_single_treatment: + # Single treatment: simple difference in means + base_foot = dedent(f""" + Average observed uplift per bin. + N = {n_obs:,} observations split into {self.n_bins} bins + """).strip() + else: + # Multi-treatment: weighted average across treatments + base_foot = dedent(f""" + Uplift by predicted uplift bin (ranked by best predicted uplift), weighted by + the model's treatment recommendations. + N = {n_obs:,} observations split into {self.n_bins} bins + """).strip() + + if footnote_extra: + if isinstance(footnote_extra, list | tuple): + extra = "\n".join(s.strip() for s in footnote_extra if s is not None) + else: + extra = str(footnote_extra).strip() + foot = f"{base_foot} {extra}" if extra else base_foot + else: + foot = base_foot + + try: + _add_footnote_to_plot(fig, ax, foot, fontsize=9, gap_pts=8, color="0.35") + except Exception: + pass + + if save: + fig.savefig(path, bbox_inches="tight") + + if show: + plt.show() + + return ax + + def compute_cumulative_gain_table( # noqa: PLR0915 + self, + t: Series, + y: Series, + tau: NDArray, + treatment_name: str | None = None, + treatment_idx: int | None = None, + population_size: int = 1, + return_se: bool = False, + ) -> pd.DataFrame | tuple[pd.DataFrame, pd.Series]: + """ + Compute cumulative gain table by predicted uplift bin. + + This function bins individuals by their best predicted uplift, then calculates + cumulative incremental gains across bins. The cumulative gain represents the + total uplift achieved by targeting individuals in the top N bins. + + Parameters + ---------- + t : Series + Treatment assignment series (values should match control_name and treatment_names) + y : Series + Outcome series (e.g., revenue, conversion) + tau : NDArray, shape (n_samples, n_treatments) + Predicted uplift (CATE) for each treatment vs control + treatment_name : str, optional + Name of specific treatment to analyze. If provided, only analyzes this treatment. + Cannot be used with treatment_idx. + treatment_idx : int, optional + Index of specific treatment to analyze (0-based). If provided, only analyzes + this treatment. Cannot be used with treatment_name. + population_size : int, default=1 + Target population size to scale the gains to. Default is 1 (per-person impact). + Set to a larger number to project total impact. For example, if your test + data has 10,000 observations, and you set population_size=1,000,000, the gains will + be scaled up 100x to show the projected impact on 1 million customers. + return_se : bool, default=False + If True, also returns standard errors for cumulative gains. Returns a tuple + (DataFrame, Series) where Series has SEs for cum_incremental_uplift. + + Returns + ------- + pd.DataFrame or tuple[pd.DataFrame, pd.Series] + If ``return_se=False``, returns a DataFrame with columns ``bin``, + ``bin_n``, ``total_n``, ``coverage``, ``uplift``, + ``total_incremental_uplift``, ``total_incremental_uplift_scaled``, + and ``cum_incremental_uplift``. + + If ``return_se=True``, returns a tuple ``(DataFrame, Series)`` where + the Series contains standard errors for ``cum_incremental_uplift``. + + Notes + ----- + - Bins are created based on tau_best (highest predicted uplift) + - Incremental gain for a bin = (uplift per person) * (number of people in bin) + - Cumulative gain = sum of incremental gains from bin 1 to current bin + - All gains are scaled: gain_scaled = gain * (population_size / test_size) + - With population_size=1 (default): Shows per-person impact + - With population_size=N: Shows total impact projected to N customers + - This helps answer: "What total uplift do I get by targeting the top X% of customers?" + - With large population_size: "What's the total revenue impact if I deploy to N customers?" + + Examples + -------- + >>> evaluator = UpliftBinEvaluator("Control", "Treatment A", "Treatment B", n_bins=10) + >>> # Get per-person gains (default) + >>> cg_table = evaluator.compute_cumulative_gain_table( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau + ... ) + >>> print(cg_table[["bin", "coverage", "cum_incremental_uplift"]]) + >>> print(f"Per-person uplift: ${cg_table['cum_incremental_uplift'].max():.2f}") + >>> + >>> # Project gains to 1 million customer population + >>> cg_table_scaled = evaluator.compute_cumulative_gain_table( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... population_size=1_000_000 + ... ) + >>> max_uplift = cg_table_scaled['cum_incremental_uplift'].max() + >>> print(f"Total revenue impact on 1M customers: ${max_uplift:,.0f}") + """ + # Convert tau to numpy array if needed + if isinstance(tau, pd.DataFrame): + tau_arr = tau.to_numpy(dtype=np.float32) + else: + tau_arr = np.asarray(tau, dtype=np.float32) + + # Bin on tau_best (best predicted uplift) + tau_best = compute_best_uplift(tau_arr) + bin_idx = assign_bins(pd.Series(tau_best), self.n_bins) + bin_counts = pd.Series(bin_idx).value_counts().sort_index() + bin_df = pd.DataFrame({"bin": bin_counts.index.astype(int), "bin_n": bin_counts.values}) + bin_df["total_n"] = bin_df["bin_n"].sum() + bin_df["coverage"] = bin_df["bin_n"].cumsum() / bin_df["total_n"] + + # Get per-bin uplifts from compute_binned_actual_uplift (with SE if requested) + if return_se: + res, se_res = self.compute_binned_actual_uplift( + t, + y, + tau, + treatment_name=treatment_name, + treatment_idx=treatment_idx, + return_se=True, + ) + else: + res = self.compute_binned_actual_uplift( + t, + y, + tau, + treatment_name=treatment_name, + treatment_idx=treatment_idx, + return_se=False, + ) + + # Auto-detect the uplift metric column + if "combined_uplift" in res.columns: + metric_col = "combined_uplift" + se_col = "se_combined" if return_se else None + elif "uplift" in res.columns: + metric_col = "uplift" + se_col = "se" if return_se else None + else: + raise ValueError( + f"No uplift column found in data. Available columns: {res.columns.tolist()}" + ) + + # Select relevant columns + res_slim = res[["bin", metric_col]].copy() + + # Merge and compute cumulative gain fields + cg = ( + pd.merge(bin_df, res_slim, on="bin", how="left") + .sort_values("bin") + .reset_index(drop=True) + ) + + # Calculate scaling factor + test_size = cg["total_n"].iloc[0] + scaling = population_size / test_size + + # Incremental gain = uplift per person * number of people in bin + inc = cg[metric_col] * cg["bin_n"] + cg["total_incremental_uplift"] = inc + cg["total_incremental_uplift_scaled"] = inc * scaling + # Cumulative gain = running sum of scaled incremental gains + cg["cum_incremental_uplift"] = cg["total_incremental_uplift_scaled"].cumsum() + + if return_se: + # Compute standard errors for cumulative gains + # SE for incremental gain in each bin + se_incremental = se_res[se_col].values * cg["bin_n"].values * scaling + # SE for cumulative gain = sqrt(sum of squared SEs) + se_cumulative = pd.Series( + [np.sqrt(np.sum(se_incremental[: i + 1] ** 2)) for i in range(len(se_incremental))], + index=cg.index, + ) + return cg, se_cumulative + return cg + + def plot_cumulative_gain_curve( # noqa: PLR0915, C901, PLR0912, PLR0913 + self, + t: Series, + y: Series, + tau: NDArray, + treatment_name: str | None = None, + treatment_idx: int | None = None, + population_size: int = 1, + title: str = "Cumulative Incremental Gain", + subtitle: str | None = None, + footnote_extra: str | Sequence[str] | None = None, + metric_format: str = "currency", + show_ci: bool = True, + confidence_level: float = 0.95, + show_summary_box: bool = True, + figsize: tuple[int] = (10, 6), + show: bool = True, + save: bool = False, + path: str | None = None, + ) -> None: + """ + Plot cumulative incremental gain curve by population coverage. + + This plot shows the total uplift achieved by targeting individuals in order + of their predicted uplift (highest to lowest). The x-axis represents the + fraction of the population targeted, and the y-axis shows the cumulative + uplift achieved. + + Parameters + ---------- + t : Series + Treatment assignment series (values should match control_name and treatment_names) + y : Series + Outcome series (e.g., revenue, conversion) + tau : NDArray, shape (n_samples, n_treatments) + Predicted uplift (CATE) for each treatment vs control + treatment_name : str, optional + Name of specific treatment to plot. If provided, only plots this treatment. + Cannot be used with treatment_idx. + treatment_idx : int, optional + Index of specific treatment to plot (0-based). If provided, only plots this treatment. + Cannot be used with treatment_name. + population_size : int, default=1 + Target population size to scale the gains to. Default is 1 (per-person impact). + Set to a larger number to project total impact. For example, if your test + data has 10,000 observations and you set population_size=1,000,000, the gains will + be scaled up 100x to show the projected impact on 1 million customers. + title : str, default="Cumulative Incremental Gain" + Main title for the plot + subtitle : str, optional + Subtitle displayed below the main title. If None, automatically generates + a subtitle showing "Uplift targeting beats treat-all by $X/customer" (default + with population_size=1) or total impact (with population_size > 1). + footnote_extra : str or list of str, optional + Additional text to append to the automatic footnote + metric_format : str, default="currency" + Format for displaying metric values. One of ``"currency"`` + (formats as $X.XX), ``"decimal"`` (formats as X.XX), or + ``"integer"`` (formats as X). + show_ci : bool, default=True + Whether to display confidence intervals as a shaded band around the curve + confidence_level : float, default=0.95 + Confidence level for the confidence intervals (e.g., 0.95 for 95% CI) + show_summary_box : bool, default=True + Whether to display a summary box with key metrics in the lower left corner + figsize : tuple[int], default=(10, 6) + Figure size (width, height) + + Returns + ------- + None + Displays the plot using plt.show() + + Notes + ----- + Plot Interpretation: + + - The curve shows cumulative uplift as you target more of the population + - Steeper curves at the left indicate better model targeting + - The curve helps answer: "How much total uplift if I target the top X%?" + - Coverage ranges from 0 to 1 (0% to 100% population coverage) + + Conditional Labeling Based on population_size: + + - When population_size=1 (default): Y-axis shows "per customer", subtitle + shows per-customer value, summary box shows per-customer values. + - When population_size > 1: Y-axis shows scaled values, subtitle shows + total impact, summary box shows scaled values with population size. + + Summary Box Contents: + + - Max gain at peak bin (highest cumulative uplift achieved) + - Treat-all baseline (cumulative uplift at 100% coverage) + - Value of uplift targeting vs treat-all + - Value vs treat-none (total uplift vs no treatment) + """ + from matplotlib.offsetbox import AnchoredOffsetbox, TextArea, VPacker + + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + # Define formatting functions based on metric_format + def format_value(v: float) -> str: # noqa: PLR0911 + if metric_format == "currency": + # Format large currency values with M/K suffixes + abs_v = abs(v) + if abs_v >= 1_000_000: # noqa: PLR2004 + return f"${v / 1_000_000:.2f}M" + if abs_v >= 1_000: # noqa: PLR2004 + return f"${v / 1_000:.2f}K" + return f"${v:,.2f}" + if metric_format == "decimal": + return f"{v:.2f}" + if metric_format == "integer": + # Format large integers with M/K suffixes + abs_v = abs(v) + if abs_v >= 1_000_000: # noqa: PLR2004 + if v % 1_000_000 == 0: + return f"{int(v // 1_000_000)}M" + return f"{v / 1_000_000:.2f}M" + if abs_v >= 1_000: # noqa: PLR2004 + if v % 1_000 == 0: + return f"{int(v // 1_000)}K" + return f"{v / 1_000:.2f}K" + return f"{int(v):,}" + return f"{v:,.2f}" + + # Format population size (e.g., 1,000,000 -> "1M", 5,000 -> "5K") + def format_population(pop: int) -> str: + if pop >= 1_000_000: # noqa: PLR2004 + if pop % 1_000_000 == 0: + return f"{pop // 1_000_000}M" + return f"{pop / 1_000_000:.1f}M" + if pop >= 1_000: # noqa: PLR2004 + if pop % 1_000 == 0: + return f"{pop // 1_000}K" + return f"{pop / 1_000:.1f}K" + return f"{pop:,}" + + # Compute cumulative gain table + cg = self.compute_cumulative_gain_table( + t, + y, + tau, + treatment_name=treatment_name, + treatment_idx=treatment_idx, + population_size=population_size, + ) + + # Determine what was analyzed for axis labels + # Check if this is a single-treatment scenario + n_treatments = len(self.treatment_names) + is_specific_treatment = treatment_name is not None or treatment_idx is not None + + if is_specific_treatment or n_treatments == 1: + # Single treatment or specific treatment selected + if treatment_name is not None: + ranking_label = f"ranked by predicted uplift for {treatment_name}" + elif treatment_idx is not None: + treat_label = self.treatment_names[treatment_idx] + ranking_label = f"ranked by predicted uplift for {treat_label}" + else: + # Single treatment model - just say "ranked by predicted uplift" + ranking_label = "ranked by predicted uplift" + else: + # Multi-treatment model analyzing all treatments + ranking_label = "ranked by best predicted uplift across all treatments" + + # Extract data for plotting + x = cg["coverage"].values + y_vals = cg["cum_incremental_uplift"].values + bins = cg["bin"].values if "bin" in cg.columns else None + + # Prepend (0, 0) to start the curve at the origin + x = np.concatenate([[0], x]) + y_vals = np.concatenate([[0], y_vals]) + + # Compute confidence intervals if requested + if show_ci: + from scipy import stats + + z_score = stats.norm.ppf((1 + confidence_level) / 2) + _, se_cumulative = self.compute_cumulative_gain_table( + t, + y, + tau, + treatment_name=treatment_name, + treatment_idx=treatment_idx, + population_size=population_size, + return_se=True, + ) + ci_low = y_vals[1:] - z_score * se_cumulative.values # Skip first point (0,0) + ci_high = y_vals[1:] + z_score * se_cumulative.values + # Prepend 0 for the origin point + ci_low = np.concatenate([[0], ci_low]) + ci_high = np.concatenate([[0], ci_high]) + else: + ci_low = None + ci_high = None + + # Find peak and final values (adjusting indices for the prepended point) + peak_idx = int(np.argmax(y_vals)) + peak_bin = int(bins[peak_idx - 1]) if bins is not None and peak_idx > 0 else None + peak_val = float(y_vals[peak_idx]) + final_val = float(y_vals[-1]) + additional_vs_final = peak_val - final_val + + # Create plot + fig, ax = plt.subplots(figsize=figsize) + + # Confidence band (if enabled and available) + if show_ci and ci_low is not None and ci_high is not None: + ax.fill_between(x, ci_low, ci_high, alpha=0.2, color="#2E86AB") + + # Main curve + ax.plot(x, y_vals, marker="o", linewidth=2, markersize=8, color="#2E86AB") + + # Zero baseline (solid line) + ax.axhline(0, linewidth=1.5, linestyle="-", color="#000000", alpha=0.8, zorder=1) + + # Treat-all baseline (final bin value) + # - only show for single-treatment or specific treatment + if is_specific_treatment or n_treatments == 1: + ax.axhline( + final_val, linewidth=1.2, linestyle="--", color="#444444", alpha=0.7, zorder=0 + ) + + # Peak value lines and marker + max_color = "#1a7f37" # dark green + ax.axhline(peak_val, linewidth=1.0, linestyle=":", color=max_color, alpha=0.95, zorder=0) + ax.axvline(x[peak_idx], linewidth=1.0, linestyle=":", color=max_color, alpha=0.95, zorder=0) + ax.scatter( + [x[peak_idx]], + [peak_val], + s=60, + color=max_color, + edgecolor="white", + linewidth=0.9, + zorder=3, + ) + + ax.set_xlabel(f"Coverage (fraction of population {ranking_label})", fontsize=10) + + # Y-axis label depends on whether we're showing per-person or total impact + if population_size > 1: + pop_str = format_population(population_size) + ylabel = f"Cumulative incremental gain (scaled to {pop_str} customers)" + ax.set_ylabel(ylabel, fontsize=10) + else: + ax.set_ylabel("Cumulative incremental gain (per customer)", fontsize=10) + + # Custom Y-axis formatter to show "in millions" or "in thousands" + # instead of scientific notation + from matplotlib.ticker import FuncFormatter + + def y_axis_formatter(value, pos): + abs_val = abs(value) + prefix = "$" if metric_format == "currency" else "" + if abs_val >= 1_000_000: # noqa: PLR2004 + return f"{prefix}{value / 1_000_000:.1f}" + if abs_val >= 1_000: # noqa: PLR2004 + return f"{prefix}{value / 1_000:.1f}" + # For all other values (including small ones), show 2 decimal places max + return f"{prefix}{value:,.2f}" + + # Determine scale and add label to y-axis + max_y = max(abs(y_vals.min()), abs(y_vals.max())) + if show_ci: + max_y = max(max_y, abs(ci_low.min()), abs(ci_high.max())) + + # Always apply formatter (for currency symbol, etc.) + ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter)) + + # Add scale label for large values + if max_y >= 1_000_000: # noqa: PLR2004 + # Add "in millions" text inside the plot (upper left) + ax.text( + 0.02, + 0.98, + "(in millions)", + transform=ax.transAxes, + fontsize=9, + va="top", + ha="left", + bbox=dict(boxstyle="round,pad=0.3", facecolor="white", edgecolor="gray", alpha=0.8), + ) + elif max_y >= 1_000: # noqa: PLR2004 + # Add "in thousands" text inside the plot (upper left) + ax.text( + 0.02, + 0.98, + "(in thousands)", + transform=ax.transAxes, + fontsize=9, + va="top", + ha="left", + bbox=dict(boxstyle="round,pad=0.3", facecolor="white", edgecolor="gray", alpha=0.8), + ) + + ax.tick_params(axis="both", which="major", labelsize=9) + ax.grid(True, axis="both", linestyle="--", linewidth=0.7, alpha=0.7) + ax.set_axisbelow(True) + + # Add title + fig.suptitle(title, fontsize=14, fontweight="bold", y=0.98) + + # Add subtitle (auto-generate if not provided) + if subtitle is None: + # For multi-treatment (all treatments shown), compare to treat-none + # For single-treatment or specific treatment, compare to treat-all + if not is_specific_treatment and n_treatments > 1: + # Multi-treatment scenario: show value vs treat-none (peak value) + if population_size > 1: + subtitle = f"Uplift targeting beats treat-none by {format_value(peak_val)}" + else: + subtitle = ( + f"Uplift targeting beats treat-none by {format_value(peak_val)}/customer" + ) + # Single-treatment or specific treatment: show value vs treat-all + elif population_size > 1: + subtitle = ( + f"Uplift targeting beats treat-all by {format_value(additional_vs_final)}" + ) + else: + value_str = format_value(additional_vs_final) + subtitle = f"Uplift targeting beats treat-all by {value_str}/customer" + fig.text(0.5, 0.935, subtitle, ha="center", va="top", fontsize=10) + + # Initial layout adjustment + plt.tight_layout(rect=[0, 0.05, 1, 0.96]) + + # Reserve space for summary box if needed + box_height_frac = 0.13 if show_summary_box else 0.0 + gap_between_frac = 0.01 if show_summary_box else 0.0 + reserved_for_box = box_height_frac + gap_between_frac + + # Add footnote with reserved space for box below it + n_obs = len(t) + + # Customize first line for multi-treatment vs single-treatment + if not is_specific_treatment and n_treatments > 1: + first_line = ( + "Cumulative incremental gain from treating with " + "model recommended treatment by population coverage." + ) + else: + first_line = "Cumulative incremental gain by population coverage." + + # Add line descriptions (conditional based on scenario) + if is_specific_treatment or n_treatments == 1: + # Single-treatment or specific treatment: show both lines + line_descriptions = ( + "Green dotted lines mark the peak gain (optimal targeting). " + "Gray dashed line shows treat-all baseline (100% coverage)." + ) + else: + # Multi-treatment: only show green lines (no treat-all baseline) + line_descriptions = "Green dotted lines mark the peak gain (optimal targeting)." + + if show_ci and ci_low is not None: + ci_pct = int(confidence_level * 100) + base_foot = dedent(f""" + {first_line} + {line_descriptions} + Shaded band shows {ci_pct}% confidence interval. + N = {n_obs:,} observations split into {self.n_bins} bins + """).strip() + else: + base_foot = dedent(f""" + {first_line} + {line_descriptions} + N = {n_obs:,} observations split into {self.n_bins} bins + """).strip() + + if footnote_extra: + if isinstance(footnote_extra, list | tuple): + extra = "\n".join(s.strip() for s in footnote_extra if s is not None) + else: + extra = str(footnote_extra).strip() + foot = f"{base_foot} {extra}" if extra else base_foot + else: + foot = base_foot + + try: + _footnote_ax, _footnote_height_frac = _add_footnote_to_plot( + fig, + ax, + foot, + fontsize=9, + gap_pts=8, + color="0.35", + extra_reserved_frac=reserved_for_box, + ) + except Exception: + pass + + # Add summary box in the reserved strip at the bottom + if show_summary_box: + # Labels depend on whether we're showing per-person or total impact + if population_size > 1: + pop_str = format_population(population_size) + unit_label = f" (scaled to {pop_str})" + else: + unit_label = "/customer" + + # Different summary box for multi-treatment (all) vs single/specific treatment + if not is_specific_treatment and n_treatments > 1: + # Multi-treatment scenario: show per-treatment uplift vs treat-all + lines = [] + + # Line 1: Max gain (same for all scenarios) + line1 = TextArea( + f"Max gain (uplift, bin={peak_bin}): {format_value(peak_val)}{unit_label}", + textprops=dict(color=max_color, fontsize=9), + ) + lines.append(line1) + + # Lines 2-N: Per-treatment uplift vs treat-all for that treatment + for idx, treat_name in enumerate(self.treatment_names): + # Calculate cumulative gain for this specific treatment + cg_treatment = self.compute_cumulative_gain_table( + t, y, tau, treatment_idx=idx, population_size=population_size + ) + peak_idx_treatment = cg_treatment["cum_incremental_uplift"].idxmax() + peak_val_treatment = float( + cg_treatment.loc[peak_idx_treatment, "cum_incremental_uplift"] + ) + final_val_treatment = float(cg_treatment["cum_incremental_uplift"].iloc[-1]) + additional_vs_final_treatment = peak_val_treatment - final_val_treatment + + line_treatment = TextArea( + f"Value of uplift vs Treat-All with {treat_name}: " + f"+{format_value(additional_vs_final_treatment)}{unit_label}", + textprops=dict(fontsize=9), + ) + lines.append(line_treatment) + + # Last line: Value vs Treat-None + line_last = TextArea( + f"Value vs Treat-None: +{format_value(peak_val)}{unit_label}", + textprops=dict(fontsize=9), + ) + lines.append(line_last) + + vbox = VPacker(children=lines, align="left", pad=0, sep=2) + else: + # Single-treatment or specific treatment: original 4-line format + line1 = TextArea( + f"Max gain (uplift, bin={peak_bin}): {format_value(peak_val)}{unit_label}", + textprops=dict(color=max_color, fontsize=9), + ) + line2 = TextArea( + f"Treat-All (bin={self.n_bins}): {format_value(final_val)}{unit_label}", + textprops=dict(fontsize=9), + ) + line3 = TextArea( + f"Value of uplift vs Treat-All: " + f"+{format_value(additional_vs_final)}{unit_label}", + textprops=dict(fontsize=9), + ) + line4 = TextArea( + f"Value vs Treat-None: +{format_value(peak_val)}{unit_label}", + textprops=dict(fontsize=9), + ) + + vbox = VPacker(children=[line1, line2, line3, line4], align="left", pad=0, sep=2) + + # Calculate where the footnote ends (y position where footnote starts) + # The footnote is positioned at extra_reserved_frac (bottom of footnote strip) + # We want the box to start at the very bottom (y=0) + # This ensures the box sits in the reserved space below the footnote + box_y_position = -0.05 + + # Place box in the reserved strip at the very bottom + anchored = AnchoredOffsetbox( + loc="lower left", + child=vbox, + frameon=True, + bbox_to_anchor=(0.02, box_y_position), + bbox_transform=fig.transFigure, + borderpad=0.4, + ) + anchored.patch.set_facecolor("white") + anchored.patch.set_alpha(0.95) + anchored.patch.set_edgecolor("gray") + fig.add_artist(anchored) + + if save: + fig.savefig(path, bbox_inches="tight") + if show: + plt.show() + + def plot_treatment( # noqa: C901 + self, + t: Series, + y: Series, + tau: NDArray, + treatment_name: str | None = None, + treatment_idx: int | None = None, + title: str | None = None, + subtitle: str | None = None, + footnote_extra: str | Sequence[str] | None = None, + figsize: tuple[int] = (10, 6), + show: bool = True, + save: bool = False, + path: str = "uplift_bins.png", + ) -> plt.Axes: + """ + Plot actual uplift by bins for a specific treatment. + + This function analyzes a single treatment arm from a multi-treatment experiment, + binning individuals by their predicted uplift for that specific treatment and + showing the actual observed uplift. + + Parameters + ---------- + t : Series + Treatment assignment series (values should match control_name and treatment_names) + y : Series + Outcome series (e.g., revenue, conversion) + tau : NDArray, shape (n_samples, n_treatments) + Predicted uplift (CATE) for each treatment vs control + treatment_name : str, optional + Name of the treatment to plot. Must match a name in self.treatment_names. + If None, treatment_idx must be provided. + treatment_idx : int, optional + Index of the treatment to plot (0-based). + If None, treatment_name must be provided. + title : str, optional + Main title for the plot. If None, auto-generates title with treatment name. + subtitle : str, optional + Subtitle displayed below the main title. Pass None to hide subtitle. + footnote_extra : str or list of str, optional + Additional text to append to the automatic footnote. Can be a string or list of strings. + figsize : tuple[int], default=(10, 6) + Figure size (width, height) in inches + show : bool, default=True + Whether to display the plot using plt.show() + save : bool, default=False + Whether to save the plot to a file + path : str, default="uplift_bins.png" + File path for saving the plot (only used if save=True) + + Returns + ------- + plt.Axes + The axes object of the plot + + Raises + ------ + ValueError + If neither treatment_name nor treatment_idx is provided + + Examples + -------- + >>> evaluator = UpliftBinEvaluator("Control", "Treatment A", "Treatment B", n_bins=10) + >>> # Plot specific treatment by name + >>> evaluator.plot_treatment( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... treatment_name="Treatment A" + ... ) + >>> # Plot specific treatment by index + >>> evaluator.plot_treatment( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... treatment_idx=0, + ... save=True, + ... path="treatment_a_uplift.png" + ... ) + """ + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + if treatment_name is None and treatment_idx is None: + raise ValueError("Either treatment_name or treatment_idx must be provided") + + if treatment_idx is None: + treatment_idx = self.treatment_names.index(treatment_name) + + if treatment_name is None: + treatment_name = self.treatment_names[treatment_idx] + + eval_df = self.compute_uplift(t, y, tau) + results_df = ( + eval_df.groupby([f"bin_{treatment_idx}"], observed=True)[f"tau_{treatment_idx}_actual"] + .agg(mean="mean") + .reset_index() + ) + + # Auto-generate title if not provided + if title is None: + title = f"Actual Uplift by Bins for {treatment_name}" + + ax = self._create_uplift_plot(results_df, title, figsize) + + # Add subtitle if provided + if subtitle is not None: + ax.set_title(subtitle, fontsize=10, pad=10, loc="center") + + # Add footnote if provided + if footnote_extra is not None: + try: + fig = ax.get_figure() + if isinstance(footnote_extra, str): + footnote_text = footnote_extra + else: + footnote_text = " ".join(footnote_extra) + _add_footnote_to_plot(fig, ax, footnote_text) + except Exception: + pass + + if save: + ax.get_figure().savefig(path, bbox_inches="tight") + if show: + plt.show() + + return ax + + def plot_uplift_distribution( # noqa: C901, PLR0912, PLR0915 + self, + tau: NDArray | pd.DataFrame, + treatment_name: str | None = None, + treatment_idx: int | None = None, + title: str = "Predicted Uplift Distribution", + subtitle: str | None = None, + footnote_extra: str | Sequence[str] | None = None, + figsize: tuple[int] = (12, 6), + bins: int = 50, + include_best_tau: bool = True, + show: bool = True, + save: bool = False, + path: str = "uplift_distribution.png", + ) -> None: + """ + Plot the distribution of predicted uplift values by treatment. + + Creates histogram(s) showing the distribution of predicted uplift values. For + multi-treatment models, displays a faceted plot with one subplot per treatment + (unless a specific treatment is selected). For single-treatment models, displays + a single histogram. + + Parameters + ---------- + tau : NDArray or pd.DataFrame, shape (n_samples, n_treatments) + Predicted uplift (CATE) for each treatment vs control. + If DataFrame, columns should correspond to treatment names. + treatment_name : str, optional + Name of specific treatment to plot. If provided, only plots this treatment. + Cannot be used with treatment_idx. + treatment_idx : int, optional + Index of specific treatment to plot (0-based). If provided, only plots + this treatment. Cannot be used with treatment_name. + title : str, default="Predicted Uplift Distribution" + Main title for the plot + subtitle : str, optional + Subtitle displayed below the main title + footnote_extra : str or list of str, optional + Additional text to append to the automatic footnote + figsize : tuple[int], default=(12, 6) + Figure size (width, height) in inches. For multi-treatment plots, + width is adjusted automatically based on number of treatments. + bins : int, default=50 + Number of bins for the histogram + include_best_tau : bool, default=True + If True and multi-treatment model, adds an extra subplot showing the + distribution of the best (maximum) predicted uplift across all treatments. + show : bool, default=True + Whether to display the plot using plt.show() + save : bool, default=False + Whether to save the plot to a file + path : str, default="uplift_distribution.png" + File path for saving the plot (only used if save=True) + + Returns + ------- + None + + Notes + ----- + - Histograms show the frequency distribution of predicted uplift values + - Vertical dashed line indicates the mean uplift for each treatment + - For multi-treatment models, subplots are arranged in a single row + - Useful for understanding the range and distribution of model predictions + - Can help identify if the model predicts mostly positive, negative, or mixed uplifts + + Examples + -------- + >>> evaluator = UpliftEvaluator("Control", "Treatment A", "Treatment B", n_bins=10) + >>> + >>> # Plot all treatments (multi-treatment model) + >>> evaluator.plot_uplift_distribution( + ... tau=predicted_tau, + ... title="Predicted Uplift Distributions", + ... subtitle="Test Set - Model v1.1.0" + ... ) + >>> + >>> # Plot specific treatment only + >>> evaluator.plot_uplift_distribution( + ... tau=predicted_tau, + ... treatment_name="Treatment A", + ... title="Treatment A: Predicted Uplift Distribution" + ... ) + >>> + >>> # Plot with more bins for finer detail + >>> evaluator.plot_uplift_distribution( + ... tau=predicted_tau, + ... bins=100, + ... title="High Resolution Uplift Distribution" + ... ) + """ + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + # Convert tau to numpy array if needed + if isinstance(tau, pd.DataFrame): + tau_arr = tau.to_numpy(dtype=np.float32) + else: + tau_arr = np.asarray(tau, dtype=np.float32) + + # Ensure tau is 2D + if tau_arr.ndim == 1: + tau_arr = tau_arr.reshape(-1, 1) + + # Handle specific treatment selection + if treatment_name is not None and treatment_idx is not None: + raise ValueError("Cannot specify both treatment_name and treatment_idx") + + if treatment_name is not None: + if treatment_name not in self.treatment_names: + raise ValueError( + f"treatment_name='{treatment_name}' not found in treatment_names. " + f"Available treatments: {self.treatment_names}" + ) + treatment_idx = self.treatment_names.index(treatment_name) + + if treatment_idx is not None: + n_arms = tau_arr.shape[1] + if treatment_idx < 0 or treatment_idx >= n_arms: + raise ValueError( + f"treatment_idx={treatment_idx} out of range. " + f"Model has {n_arms} treatment arms (indices 0-{n_arms - 1})" + ) + # Select only the specified treatment + tau_arr = tau_arr[:, treatment_idx : treatment_idx + 1] + treatments_to_plot = [self.treatment_names[treatment_idx]] + else: + treatments_to_plot = list(self.treatment_names) + + n_treatments = len(treatments_to_plot) + + # Determine if we should add best_tau subplot + is_multi_treatment = tau_arr.shape[1] > 1 + add_best_tau = include_best_tau and is_multi_treatment and treatment_idx is None + + # Calculate number of subplots + n_subplots = n_treatments + (1 if add_best_tau else 0) + + # Adjust figure size for multiple treatments + if n_subplots > 1: + adjusted_figsize = (figsize[0] * min(n_subplots, 3) / 2, figsize[1]) + else: + adjusted_figsize = figsize + + # Create subplots + fig, axes = plt.subplots(1, n_subplots, figsize=adjusted_figsize, squeeze=False) + axes = axes.flatten() + + # Plot histogram for each treatment + for i, (treatment, ax) in enumerate(zip(treatments_to_plot, axes)): + uplift_values = tau_arr[:, i] + + # Create histogram + ax.hist(uplift_values, bins=bins, color="steelblue", alpha=0.7, edgecolor="black") + + # Add mean line + mean_uplift = uplift_values.mean() + std_uplift = uplift_values.std() + ax.axvline( + mean_uplift, + color="red", + linestyle="--", + linewidth=2, + label=f"Mean: {mean_uplift:.2f}, Std: {std_uplift:.2f}", + ) + + # Formatting + ax.set_xlabel(f"Predicted uplift for {treatment}", fontsize=10) + ax.set_ylabel("Frequency", fontsize=10) + ax.tick_params(axis="both", labelsize=9) + ax.set_title(treatment, fontsize=11, fontweight="bold") + ax.legend(loc="upper right", fontsize=10) + ax.grid(True, axis="y", linestyle="--", linewidth=0.7, alpha=0.7) + ax.set_axisbelow(True) + + # Add best_tau subplot if requested + if add_best_tau: + best_tau_values = tau_arr.max(axis=1) + ax_best = axes[n_treatments] # Last subplot + + # Create histogram + ax_best.hist( + best_tau_values, bins=bins, color="darkgreen", alpha=0.7, edgecolor="black" + ) + + # Add mean line + mean_best = best_tau_values.mean() + std_best = best_tau_values.std() + ax_best.axvline( + mean_best, + color="red", + linestyle="--", + linewidth=2, + label=f"Mean: {mean_best:.2f}, Std: {std_best:.2f}", + ) + + # Formatting + ax_best.set_xlabel("Predicted uplift for best treatment", fontsize=10) + ax_best.set_ylabel("Frequency", fontsize=10) + ax_best.tick_params(axis="both", labelsize=9) + ax_best.set_title("Best Tau", fontsize=11, fontweight="bold") + ax_best.legend(loc="upper right", fontsize=10) + ax_best.grid(True, axis="y", linestyle="--", linewidth=0.7, alpha=0.7) + ax_best.set_axisbelow(True) + + # Add main title and subtitle + fig.suptitle(title, fontsize=14, fontweight="bold", y=0.98) + if subtitle: + fig.text(0.5, 0.93, subtitle, ha="center", va="top", fontsize=10) + + plt.tight_layout(rect=[0, 0.05, 1, 0.96 if subtitle else 0.92]) + + # Add footnote + n_obs = tau_arr.shape[0] + if n_treatments == 1: + base_foot = f"Distribution of predicted uplift values. N = {n_obs:,} observations" + else: + base_foot = ( + f"N = {n_obs:,} observations. " + f"Distribution of predicted uplift values for each treatment" + ) + + if footnote_extra: + if isinstance(footnote_extra, list | tuple): + extra = "\n".join(s.strip() for s in footnote_extra if s is not None) + else: + extra = str(footnote_extra).strip() + foot = f"{base_foot} {extra}" if extra else base_foot + else: + foot = base_foot + + try: + _add_footnote_to_plot(fig, axes[0], foot, fontsize=9, gap_pts=8, color="0.35") + except Exception: + pass + + if save: + fig.savefig(path, bbox_inches="tight") + if show: + plt.show() + + # ==================== Metric Functions ==================== + + def metric_max_business_value( + self, + t: Series, + y: Series, + tau: NDArray, + treatment_name: str | None = None, + treatment_idx: int | None = None, + population_size: int = 1, + return_ci: bool = False, + confidence_level: float = 0.95, + ) -> tuple[float, float] | tuple[float, float, float, float]: + """ + Calculate the maximum business value achievable by treating the optimal percentage. + + This function finds the optimal point on the cumulative gain curve where business value + is maximized. It bins individuals by their predicted uplift and calculates cumulative gains + for each bin, returning both the maximum value and the population coverage that achieves it. + + Parameters + ---------- + t : Series + Treatment assignment series (values should match control_name and treatment_names) + y : Series + Outcome series (e.g., revenue, conversion) + tau : NDArray, shape (n_samples, n_treatments) + Predicted uplift (CATE) for each treatment vs control + treatment_name : str, optional + Name of specific treatment to analyze. If provided, only analyzes this treatment. + Cannot be used with treatment_idx. + treatment_idx : int, optional + Index of specific treatment to analyze (0-based). If provided, + only analyzes this treatment. + Cannot be used with treatment_name. + population_size : int, default=1 + Target population size to scale the gains to. Default is 1 (per-person impact). + Set to a larger number to project total impact. For example, if your test + data has 10,000 observations and you set population_size=1,000,000, the gains will + be scaled up 100x to show the projected impact on 1 million customers. + return_ci : bool, default=False + If True, returns confidence intervals for the + max business value along with the estimate. + confidence_level : float, default=0.95 + Confidence level for intervals (e.g., 0.95 for 95% CI). Only used if return_ci=True. + + Returns + ------- + tuple[float, float] or tuple[float, float, float, float] + If return_ci=False (default), returns (max_business_value, optimal_coverage). + If return_ci=True, returns (max_business_value, optimal_coverage, ci_low, ci_high). + max_business_value is the maximum cumulative business value achievable. + optimal_coverage is the fraction of population (0 to 1) to treat. + ci_low and ci_high are confidence interval bounds for max business value. + + Notes + ----- + - The function finds the optimal targeting strategy by identifying the peak + of the cumulative gain curve + - "Optimal coverage" represents what percentage of the population should receive treatment + - With population_size=1 (default): Returns per-person impact + - With population_size>1: Returns total impact scaled to that population size + - Coverage is determined by n_bins (e.g., with n_bins=10, coverage will be multiples of 10%) + - Confidence intervals are computed from the standard errors of cumulative gains + + Examples + -------- + >>> evaluator = UpliftBinEvaluator("Control", ["Treatment A", "Treatment B"], n_bins=10) + >>> + >>> # Example 1: Per-person maximum value + >>> max_val, optimal_cov = evaluator.metric_max_business_value( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau + ... ) + >>> print(f"Max value per customer: ${max_val:.2f}") + >>> print(f"Treat top {optimal_cov*100:.0f}% of customers") + >>> # Output: "Max value per customer: $12.50" + >>> # "Treat top 60% of customers" + >>> + >>> # Example 2: Total value for 1 million customers + >>> max_val, optimal_cov = evaluator.metric_max_business_value( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... population_size=1_000_000 + ... ) + >>> print(f"Max total value: ${max_val:,.0f}") + >>> print( + ... f"Optimal strategy: Treat top {optimal_cov*100:.0f}% " + ... f"({int(optimal_cov*1_000_000):,} customers)" + ... ) + >>> # Output: "Max total value: $12,500,000" + >>> # "Optimal strategy: Treat top 60% (600,000 customers)" + >>> + >>> # Example 3: Analyze specific treatment only + >>> max_val, optimal_cov = evaluator.metric_max_business_value( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... treatment_name="Treatment A", + ... population_size=500_000 + ... ) + >>> print(f"Treatment A max value: ${max_val:,.0f} at {optimal_cov*100:.0f}% coverage") + >>> + >>> # Example 4: With confidence intervals + >>> max_val, optimal_cov, ci_low, ci_high = evaluator.metric_max_business_value( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... return_ci=True, + ... confidence_level=0.95 + ... ) + >>> print(f"Max value: ${max_val:.2f} (95% CI: ${ci_low:.2f} + to ${ci_high:.2f})") + >>> print(f"Optimal coverage: {optimal_cov*100:.0f}%") + """ + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + # Get the cumulative gain table (with SE if CI requested) + if return_ci: + cg, se_cumulative = self.compute_cumulative_gain_table( + t, + y, + tau, + treatment_name=treatment_name, + treatment_idx=treatment_idx, + population_size=population_size, + return_se=True, + ) + else: + cg = self.compute_cumulative_gain_table( + t, + y, + tau, + treatment_name=treatment_name, + treatment_idx=treatment_idx, + population_size=population_size, + ) + + # Find the maximum cumulative gain and the coverage at which it occurs + max_idx = cg["cum_incremental_uplift"].idxmax() + max_business_value = float(cg.loc[max_idx, "cum_incremental_uplift"]) + optimal_coverage = float(cg.loc[max_idx, "coverage"]) + + if return_ci: + from scipy import stats + + # Get the standard error at the optimal point + se_at_max = float(se_cumulative.iloc[max_idx]) + + # Calculate confidence interval + z_score = stats.norm.ppf((1 + confidence_level) / 2) + ci_low = max_business_value - z_score * se_at_max + ci_high = max_business_value + z_score * se_at_max + + return max_business_value, optimal_coverage, float(ci_low), float(ci_high) + + return max_business_value, optimal_coverage + + def metric_ate_optimal_policy( # noqa: C901, PLR0912, PLR0915 + self, + t: Series, + y: Series, + tau: NDArray, + treatment_name: str | None = None, + treatment_idx: int | None = None, + return_ci: bool = False, + confidence_level: float = 0.95, + ) -> float | tuple[float, float, float]: + """ + Calculate the Average Treatment Effect (ATE) of the optimal treatment policy. + + The optimal policy assigns each individual to the treatment with the highest + predicted uplift, or to control if all predicted uplifts are negative. This metric + evaluates the average effect of following this personalized treatment assignment + strategy. Specifically, it measures the average treatment effect if everyone is + treated according to the model's recommendations. + + For single-treatment models, this is the standard ATE: mean(y|treatment) - mean(y|control). + For multi-treatment models, this is the weighted average treatment effect where weights + are the proportion of individuals recommended each treatment, and effects are calculated + only among those who were actually assigned their recommended treatment. + + Parameters + ---------- + t : Series + Treatment assignment series (values should match control_name and treatment_names) + y : Series + Outcome series (e.g., revenue, conversion) + tau : NDArray, shape (n_samples, n_treatments) + Predicted uplift (CATE) for each treatment vs control + treatment_name : str, optional + Name of specific treatment to analyze. If provided, only analyzes this treatment. + Cannot be used with treatment_idx. + treatment_idx : int, optional + Index of specific treatment to analyze (0-based). If provided, only analyzes + this treatment. Cannot be used with treatment_name. + return_ci : bool, default=False + If True, returns confidence intervals along with the ATE. + confidence_level : float, default=0.95 + Confidence level for intervals (e.g., 0.95 for 95% CI). Only used if return_ci=True. + + Returns + ------- + float or tuple[float, float, float] + If return_ci=False: Returns the ATE as a single float + If return_ci=True: Returns tuple (ate, ci_low, ci_high) + + Notes + ----- + **Single Treatment Case:** + - Calculates standard ATE: mean(y | t=treatment) - mean(y | t=control) + - This is the average effect across the entire test population + + **Multi-Treatment Case (Optimal Policy):** + - For each treatment, calculates: mean(y | t=i, recommended=i) + - mean(y | t=control, recommended=i) + - Weights each treatment effect by the proportion of people recommended that treatment + - Returns: Σ [weight_i * treatment_effect_i] + - This represents the expected ATE if everyone follows the model's recommendations + + **Confidence Intervals:** + - Calculated using standard errors: SE = sqrt(var_t/n_t + var_c/n_c) + - CI = ATE ± z * SE, where z is the z-score for the specified confidence level + - For multi-treatment, uses weighted combination of individual SEs + + Examples + -------- + >>> evaluator = UpliftBinEvaluator("Control", ["Treatment A", "Treatment B"], n_bins=10) + >>> + >>> # Example 1: Simple ATE (single treatment or analyzing one treatment) + >>> ate = evaluator.metric_ate_optimal_policy( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau + ... ) + >>> print(f"ATE of optimal policy: ${ate:.2f}") + >>> # Output: "ATE of optimal policy: $8.45" + >>> + >>> # Example 2: ATE with confidence intervals + >>> ate, ci_low, ci_high = evaluator.metric_ate_optimal_policy( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... return_ci=True, + ... confidence_level=0.95 + ... ) + >>> print(f"ATE: ${ate:.2f} (95% CI: ${ci_low:.2f} to ${ci_high:.2f})") + >>> # Output: "ATE: $8.45 (95% CI: $7.20 to $9.70)" + >>> + >>> # Example 3: ATE for specific treatment + >>> ate = evaluator.metric_ate_optimal_policy( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... treatment_name="Treatment A" + ... ) + >>> print(f"ATE for Treatment A: ${ate:.2f}") + """ + from scipy import stats + + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + # Convert tau to numpy array if needed + if isinstance(tau, pd.DataFrame): + tau_arr = tau.to_numpy(dtype=np.float32) + else: + tau_arr = np.asarray(tau, dtype=np.float32) + + # Handle specific treatment selection + if treatment_name is not None and treatment_idx is not None: + raise ValueError("Cannot specify both treatment_name and treatment_idx") + + if treatment_name is not None: + if treatment_name not in self.treatment_names: + raise ValueError( + f"treatment_name '{treatment_name}' not found in {self.treatment_names}" + ) + treatment_idx = self.treatment_names.index(treatment_name) + + # Determine if this is a single-treatment scenario + n_treatments = len(self.treatment_names) + is_single_treatment = treatment_idx is not None or n_treatments == 1 + + if is_single_treatment: + # Single treatment case: standard ATE + if treatment_idx is not None: + treat_name = self.treatment_names[treatment_idx] + else: + treat_name = self.treatment_names[0] + + # Filter to treatment and control groups + treatment_mask = t == treat_name + control_mask = t == self.control_name + + treatment_outcomes = y[treatment_mask] + control_outcomes = y[control_mask] + + # Calculate ATE + ate = float(treatment_outcomes.mean() - control_outcomes.mean()) + + if return_ci: + # Calculate standard error + n_t = len(treatment_outcomes) + n_c = len(control_outcomes) + var_t = treatment_outcomes.var(ddof=1) if n_t > 1 else 0 + var_c = control_outcomes.var(ddof=1) if n_c > 1 else 0 + se = np.sqrt(var_t / n_t + var_c / n_c) + + # Calculate CI + z_score = stats.norm.ppf((1 + confidence_level) / 2) + ci_low = ate - z_score * se + ci_high = ate + z_score * se + + return ate, float(ci_low), float(ci_high) + return ate + + # Multi-treatment case: weighted ATE across recommended treatments + # Get recommended treatment for each individual + recommended = self.get_recommended_treatment(tau_arr) + + # Create a dataframe for easier manipulation + data = pd.DataFrame({"t": t, "y": y, "recommended": recommended}) + + treatment_effects = [] + treatment_weights = [] + treatment_ses = [] + + # Calculate effect for each treatment + for treat_name in self.treatment_names: + # Filter to individuals recommended this treatment + recommended_data = data[data["recommended"] == treat_name] + + if len(recommended_data) == 0: + continue + + # Calculate weight (proportion recommended this treatment) + weight = len(recommended_data) / len(data) + + # Get outcomes for those who received this treatment (and were recommended it) + treatment_outcomes = recommended_data[recommended_data["t"] == treat_name]["y"] + + # Get outcomes for those who received control (but were recommended this treatment) + control_outcomes = recommended_data[recommended_data["t"] == self.control_name]["y"] + + # Calculate treatment effect + if len(treatment_outcomes) > 0 and len(control_outcomes) > 0: + effect = treatment_outcomes.mean() - control_outcomes.mean() + treatment_effects.append(effect) + treatment_weights.append(weight) + + # Calculate standard error if needed + if return_ci: + n_t = len(treatment_outcomes) + n_c = len(control_outcomes) + var_t = treatment_outcomes.var(ddof=1) if n_t > 1 else 0 + var_c = control_outcomes.var(ddof=1) if n_c > 1 else 0 + se = np.sqrt(var_t / n_t + var_c / n_c) + treatment_ses.append(se) + + # Calculate weighted average ATE + if len(treatment_effects) > 0: + total_weight = sum(treatment_weights) + normalized_weights = [w / total_weight for w in treatment_weights] + ate = float(sum(eff * w for eff, w in zip(treatment_effects, normalized_weights))) + + if return_ci: + # Calculate weighted SE + weighted_se = np.sqrt( + sum((w * se) ** 2 for w, se in zip(normalized_weights, treatment_ses)) + ) + + # Calculate CI + z_score = stats.norm.ppf((1 + confidence_level) / 2) + ci_low = ate - z_score * weighted_se + ci_high = ate + z_score * weighted_se + + return ate, float(ci_low), float(ci_high) + return ate + # No valid treatment effects calculated + if return_ci: + return np.nan, np.nan, np.nan + return np.nan + + def metric_avg_value_at_coverage( + self, + t: Series, + y: Series, + tau: NDArray, + treatment_name: str | None = None, + treatment_idx: int | None = None, + top_fraction: float = 0.1, + population_size: int = 1, + return_ci: bool = False, + confidence_level: float = 0.95, + ) -> float | tuple[float, float, float]: + """ + Calculate the average business value per person at a specified population coverage level. + + This function calculates the cumulative gain at a specified population coverage level + (default: 10%) and returns the average value per person. It answers: "What's the average + value per customer if I treat the top X% of people ranked by predicted uplift?" + + Parameters + ---------- + t : Series + Treatment assignment series (values should match control_name and treatment_names) + y : Series + Outcome series (e.g., revenue, conversion) + tau : NDArray, shape (n_samples, n_treatments) + Predicted uplift (CATE) for each treatment vs control + treatment_name : str, optional + Name of specific treatment to analyze. If provided, only analyzes this treatment. + Cannot be used with treatment_idx. + treatment_idx : int, optional + Index of specific treatment to analyze (0-based). If provided, + only analyzes this treatment. + Cannot be used with treatment_name. + top_fraction : float, default=0.1 + The population coverage level (e.g., 0.1 for 10% coverage, 0.2 for 20% coverage). + Must be between 0 and 1. Represents the fraction of the population (ranked by + predicted uplift) to evaluate. + population_size : int, default=1 + Target population size to scale the result to. Default is 1 (per-person impact). + Set to a larger number to get total impact for that population. The per-person + calculation remains the same: total_value / (top_fraction `*` population_size). + return_ci : bool, default=False + If True, returns confidence intervals for the per-person value along with the estimate. + confidence_level : float, default=0.95 + Confidence level for intervals (e.g., 0.95 for 95% CI). Only used if return_ci=True. + + Returns + ------- + float or tuple[float, float, float] + If ``return_ci=False`` (default), returns the average business value + per person at the specified coverage level. + + If ``return_ci=True``, returns a tuple ``(avg_value, ci_low, ci_high)`` + where ``avg_value`` is the average business value per person, + ``ci_low`` is the lower bound, and ``ci_high`` is the upper bound of + the confidence interval. + + Notes + ----- + - This metric is calculated from the cumulative gain curve at the specified coverage level + - The function finds the bin closest to the desired coverage (top_fraction) + - Average value = cumulative_gain_at_coverage / (coverage * population_size) + - Useful for answering: "If I deploy to 10% coverage, what's the average value per person?" + - Can be used to compare different targeting strategies (10% vs 20% coverage, etc.) + - Confidence intervals are computed from the standard error of cumulative gain + at the target coverage + - CI = value +/- z * (SE / num_people_treated), where z is the z-score + for the specified confidence level + + Examples + -------- + >>> evaluator = UpliftBinEvaluator("Control", ["Treatment A", "Treatment B"], n_bins=20) + >>> + >>> # Example 1: Average value at 10% coverage (default) + >>> value = evaluator.metric_avg_value_at_coverage( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau + ... ) + >>> print(f"Avg value per person (10% coverage): ${value:.2f}") + >>> # Output: "Avg value per person (10% coverage): $15.30" + >>> + >>> # Example 2: Compare different coverage levels + >>> value_5pct = evaluator.metric_avg_value_at_coverage( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... top_fraction=0.05 + ... ) + >>> value_20pct = evaluator.metric_avg_value_at_coverage( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... top_fraction=0.20 + ... ) + >>> print(f"5% coverage: ${value_5pct:.2f}/person, 20% coverage: ${value_20pct:.2f}/person") + >>> # Output: "5% coverage: $22.40/person, 20% coverage: $11.20/person" + >>> + >>> # Example 3: Total impact calculation for 1M customers at 10% coverage + >>> value = evaluator.metric_avg_value_at_coverage( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... population_size=1_000_000 + ... ) + >>> total_impact = value * (0.1 * 1_000_000) # value/person * num people + >>> print(f"Per person: ${value:.2f}, Total for 100K customers: ${total_impact:,.0f}") + >>> # Output: "Per person: $15.30, Total for 100K customers: $1,530,000" + >>> + >>> # Example 4: Analyze specific treatment at 10% coverage + >>> value = evaluator.metric_avg_value_at_coverage( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... treatment_name="Treatment A", + ... top_fraction=0.1 + ... ) + >>> print(f"Treatment A avg value (10% coverage): ${value:.2f}/person") + >>> + >>> # Example 5: With confidence intervals + >>> value, ci_low, ci_high = evaluator.metric_avg_value_at_coverage( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... top_fraction=0.1, + ... return_ci=True, + ... confidence_level=0.95 + ... ) + >>> print( + ... f"Avg value (10% coverage): ${value:.2f} " + ... f"(95% CI: ${ci_low:.2f} to ${ci_high:.2f})" + ... ) + """ + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + # Validate top_fraction + if not 0 < top_fraction <= 1: + raise ValueError(f"top_fraction must be between 0 and 1, got {top_fraction}") + + # Get the cumulative gain table (with SE if CI requested) + if return_ci: + cg, se_cumulative = self.compute_cumulative_gain_table( + t, + y, + tau, + treatment_name=treatment_name, + treatment_idx=treatment_idx, + population_size=population_size, + return_se=True, + ) + else: + cg = self.compute_cumulative_gain_table( + t, + y, + tau, + treatment_name=treatment_name, + treatment_idx=treatment_idx, + population_size=population_size, + ) + + # Find the bin closest to the desired top_fraction + # coverage column contains cumulative coverage (0 to 1) + idx_closest = (cg["coverage"] - top_fraction).abs().idxmin() + + # Get the cumulative gain at this coverage + cumulative_gain = float(cg.loc[idx_closest, "cum_incremental_uplift"]) + actual_coverage = float(cg.loc[idx_closest, "coverage"]) + + # Calculate per-person value + # cumulative_gain is already scaled by population_size + # We want: gain / number_of_people_treated + # number_of_people_treated = actual_coverage * population_size + num_people_treated = actual_coverage * population_size + value_per_person = ( + cumulative_gain / num_people_treated if num_people_treated > 0 else np.nan + ) + + if return_ci: + from scipy import stats + + # Get the standard error at the target coverage + se_at_coverage = float(se_cumulative.iloc[idx_closest]) + + # SE for per-person value: SE(cumulative_gain) / num_people_treated + se_per_person = ( + se_at_coverage / num_people_treated if num_people_treated > 0 else np.nan + ) + + # Calculate confidence interval + z_score = stats.norm.ppf((1 + confidence_level) / 2) + ci_low = value_per_person - z_score * se_per_person + ci_high = value_per_person + z_score * se_per_person + + return float(value_per_person), float(ci_low), float(ci_high) + + return float(value_per_person) + + def metric_predicted_uplift_at_coverage( # noqa: PLR0915,C901 + self, + tau: NDArray | pd.DataFrame, + top_fraction: float = 0.1, + treatment_name: str | None = None, + treatment_idx: int | None = None, + ) -> float: + """ + Calculate the predicted uplift at a specified population coverage threshold. + + This function answers: "What is the predicted uplift value at the X% coverage + threshold?" (i.e., the uplift of the marginal person at that cutoff). + + Unlike metric_avg_value_at_coverage which uses actual experimental outcomes, + this function uses only the model's predictions (tau) to find the predicted + uplift value at the exact coverage threshold point. + + Parameters + ---------- + tau : NDArray or pd.DataFrame, shape (n_samples, n_treatments) + Predicted uplift (CATE) for each treatment vs control. + If DataFrame, columns should correspond to treatment names. + top_fraction : float, default=0.1 + The fraction of the population to treat (0 < top_fraction <= 1). + E.g., 0.1 means treat the top 10% of people ranked by predicted uplift. + treatment_name : str, optional + Name of specific treatment to analyze. If provided, only analyzes this treatment. + Cannot be used with treatment_idx. + treatment_idx : int, optional + Index of specific treatment to analyze (0-based). If provided, only analyzes + this treatment. Cannot be used with treatment_name. + + Returns + ------- + float + The predicted uplift at the coverage threshold (the marginal person's uplift). + + Notes + ----- + - For single-treatment models: Ranks individuals by their predicted uplift for + that treatment and returns the uplift of the person at the X% threshold + - For multi-treatment models (when no specific treatment is selected): Ranks + individuals by their best predicted uplift across all treatments, then + returns the uplift at the threshold point + - This is a model-based metric (uses only tau, not actual outcomes) + - Useful for: setting targeting thresholds, understanding where uplift drops off, + and determining coverage cutoff points + - Returns the uplift of the marginal individual at the coverage boundary, + not the average of everyone above the threshold + + Examples + -------- + >>> evaluator = UpliftEvaluator("Control", "Treatment A", "Treatment B", n_bins=10) + >>> + >>> # Example 1: What's the predicted uplift at the 10% threshold? + >>> predicted_uplift = evaluator.metric_predicted_uplift_at_coverage( + ... tau=predicted_tau, + ... top_fraction=0.1 + ... ) + >>> print(f"Predicted uplift at 10% coverage: ${predicted_uplift:.2f}") + >>> # Output: "Predicted uplift at 10% coverage: $45.32" + >>> + >>> # Example 2: What about at the 25% threshold? + >>> predicted_uplift = evaluator.metric_predicted_uplift_at_coverage( + ... tau=predicted_tau, + ... top_fraction=0.25 + ... ) + >>> print(f"Predicted uplift at 25% coverage: ${predicted_uplift:.2f}") + >>> + >>> # Example 3: For a specific treatment only + >>> predicted_uplift = evaluator.metric_predicted_uplift_at_coverage( + ... tau=predicted_tau, + ... top_fraction=0.15, + ... treatment_name="Treatment A" + ... ) + >>> print(f"Treatment A predicted uplift at 15% threshold: ${predicted_uplift:.2f}") + >>> + >>> # Example 4: Compare predicted vs actual + >>> predicted = evaluator.metric_predicted_uplift_at_coverage( + ... tau=predicted_tau, + ... top_fraction=0.2 + ... ) + >>> actual = evaluator.metric_avg_value_at_coverage( + ... t=test_df["treatment"], + ... y=test_df["outcome"], + ... tau=predicted_tau, + ... top_fraction=0.2 + ... ) + >>> print(f"Model predicts: ${predicted:.2f}, Actual: ${actual:.2f}") + """ + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + # Validate top_fraction + if not 0 < top_fraction <= 1: + raise ValueError(f"top_fraction must be between 0 and 1, got {top_fraction}") + + # Convert tau to numpy array if needed + if isinstance(tau, pd.DataFrame): + tau_arr = tau.to_numpy(dtype=np.float32) + else: + tau_arr = np.asarray(tau, dtype=np.float32) + + # Ensure tau is 2D + if tau_arr.ndim == 1: + tau_arr = tau_arr.reshape(-1, 1) + + # Handle specific treatment selection + if treatment_name is not None and treatment_idx is not None: + raise ValueError("Cannot specify both treatment_name and treatment_idx") + + if treatment_name is not None: + if treatment_name not in self.treatment_names: + raise ValueError( + f"treatment_name='{treatment_name}' not found in treatment_names. " + f"Available treatments: {self.treatment_names}" + ) + treatment_idx = self.treatment_names.index(treatment_name) + + if treatment_idx is not None: + n_arms = tau_arr.shape[1] + if treatment_idx < 0 or treatment_idx >= n_arms: + raise ValueError( + f"treatment_idx={treatment_idx} out of range. " + f"Model has {n_arms} treatment arms (indices 0-{n_arms - 1})" + ) + # Select only the specified treatment + tau_arr = tau_arr[:, treatment_idx : treatment_idx + 1] + + n_samples = tau_arr.shape[0] + is_single_treatment = tau_arr.shape[1] == 1 + + if is_single_treatment: + # For single treatment: rank by that treatment's uplift + uplift_values = tau_arr[:, 0] + sorted_uplift = np.sort(uplift_values)[::-1] # descending order + # Get the uplift at the threshold (the last person to be treated) + threshold_idx = int(np.ceil(top_fraction * n_samples)) - 1 + threshold_idx = max(0, min(threshold_idx, n_samples - 1)) # boundary check + uplift_at_threshold = sorted_uplift[threshold_idx] + else: + # For multi-treatment: rank by best uplift + # Get the best uplift for each individual + tau_best = tau_arr.max(axis=1) + sorted_best_uplift = np.sort(tau_best)[::-1] # descending order + # Get the uplift at the threshold + threshold_idx = int(np.ceil(top_fraction * n_samples)) - 1 + threshold_idx = max(0, min(threshold_idx, n_samples - 1)) # boundary check + uplift_at_threshold = sorted_best_uplift[threshold_idx] + + return float(uplift_at_threshold) + + def describe_average_customer( # noqa: C901, PLR0912, PLR0915 + self, + tau: NDArray | pd.DataFrame, + X: pd.DataFrame, + covariates: list[str], + rollout_threshold: float = 0.0, + covariate_names: dict[str, str] | None = None, + trim_outliers: float | None = None, + categorical_covariates: list[str] | None = None, + show_significance: bool = False, + ) -> pd.DataFrame: + """ + Describe the average characteristics of customers by recommended treatment group. + + This function segments customers based on the model's treatment recommendations + (applying a rollout rule/threshold), then calculates the average value of specified + covariates for each segment. This helps answer: "What do customers recommended for + each treatment look like on average?" + + Parameters + ---------- + tau : NDArray or pd.DataFrame, shape (n_samples, n_treatments) + Predicted uplift (CATE) for each treatment vs control. + If DataFrame, columns should correspond to treatment names. + X : pd.DataFrame + DataFrame containing the covariate features to describe. + Must have the same number of rows as tau. + covariates : list[str] + List of column names from X to include in the description. + E.g., ["py_revenue", "py_agi", "age"] + rollout_threshold : float, default=0.0 + Threshold for the rollout rule. Customers with best predicted uplift + above this threshold are assigned their best treatment; others are + assigned to Control. Default is 0.0 (only treat if positive uplift). + covariate_names : dict[str, str], optional + Optional dictionary mapping covariate column names to display names. + E.g., {"py_revenue": "Prior Year Revenue", "py_agi": "Adjusted Gross Income"}. + If not provided, original column names are used. + trim_outliers : float, optional + If provided, trims outliers before calculating means. Removes values below + the trim_outliers percentile and above the (100 - trim_outliers) percentile. + E.g., trim_outliers=1 removes the bottom 1% and top 1% of values for each + covariate. Default is None (no trimming). + categorical_covariates : list[str], optional + List of covariate names that are categorical. These will be one-hot encoded + and the proportion of each category will be shown for each treatment group. + E.g., ["filing_status", "state"] will show the distribution of categories + within each treatment group. + show_significance : bool, default=False + If True, adds significance stars to treatment group values indicating + whether they are statistically different from the Control group. + Uses t-test for numeric covariates and chi-square test for categorical. + Stars indicate: 1 star = p < 0.1, 2 stars = p < 0.05, 3 stars = p < 0.01 + + Returns + ------- + pd.DataFrame + DataFrame with covariates as rows (plus a ``"count"`` row showing + sample sizes) and treatment groups as columns (``"Control"``, + ``treatment_1``, ``treatment_2``, etc.). Values are the mean of + each covariate for each group. + + Notes + ----- + - Customers are assigned to treatments based on their best predicted + uplift: if it is <= ``rollout_threshold`` they are assigned to Control, + otherwise to the best treatment. + - For multi-treatment models, "best treatment" is the one with highest uplift + - This is purely predictive (uses only tau and X, not actual outcomes) + - Useful for understanding which customer segments are targeted for each treatment + - Can help validate that the model is making sensible recommendations + - Values are rounded to 3 decimal places; count row shows integers + - To suppress scientific notation when displaying, set + ``pd.options.display.float_format = '{:.3f}'.format`` before printing. + + Examples + -------- + >>> evaluator = UpliftExploreEvaluator("Control", "Treatment A", "Treatment B", n_bins=10) + >>> + >>> # Example 1: Basic usage with default rollout rule (uplift > 0) + >>> description = evaluator.describe_average_customer( + ... tau=predicted_tau, + ... X=test_df, + ... covariates=["py_revenue", "py_agi", "age"] + ... ) + >>> print(description) + >>> + >>> # Example 2: More conservative rollout (only treat if uplift > $10) + >>> description = evaluator.describe_average_customer( + ... tau=predicted_tau, + ... X=test_df, + ... covariates=["py_revenue", "py_agi", "age"], + ... rollout_threshold=10.0 + ... ) + >>> print(description) + >>> + >>> # Example 3: Include many covariates + >>> description = evaluator.describe_average_customer( + ... tau=predicted_tau, + ... X=test_df, + ... covariates=[ + ... "py_revenue", "py_agi", "age", "state_count", + ... "has_dependents", "filing_status" + ... ] + ... ) + >>> # Save to CSV for reporting + >>> description.to_csv("customer_segments.csv") + >>> + >>> # Example 4: Use custom display names + >>> description = evaluator.describe_average_customer( + ... tau=predicted_tau, + ... X=test_df, + ... covariates=["py_total_revenue", "py_tax_amount_total_income", "py_tax_agi_grp"], + ... covariate_names={ + ... "py_total_revenue": "Prior Year Revenue", + ... "py_tax_amount_total_income": "Total Income", + ... "py_tax_agi_grp": "AGI Group" + ... } + ... ) + >>> print(description) + >>> + >>> # Example 5: Trim outliers to get more robust averages + >>> description = evaluator.describe_average_customer( + ... tau=predicted_tau, + ... X=test_df, + ... covariates=["py_total_revenue", "py_tax_amount_total_income"], + ... trim_outliers=1.0 # Remove bottom 1% and top 1% + ... ) + >>> print(description) # More robust to extreme values + >>> + >>> # Example 6: Include categorical variables + >>> description = evaluator.describe_average_customer( + ... tau=predicted_tau, + ... X=test_df, + ... covariates=["py_revenue", "filing_status", "state"], + ... categorical_covariates=["filing_status", "state"] + ... ) + >>> print(description) # Shows proportions for each category + >>> + >>> # Example 7: Show statistical significance + >>> description = evaluator.describe_average_customer( + ... tau=predicted_tau, + ... X=test_df, + ... covariates=["py_revenue", "py_agi", "filing_status"], + ... categorical_covariates=["filing_status"], + ... show_significance=True + ... ) + >>> print(description) # Adds * ** *** to indicate significance vs Control + """ + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + # Convert tau to numpy array if needed + if isinstance(tau, pd.DataFrame): + tau_arr = tau.to_numpy(dtype=np.float32) + else: + tau_arr = np.asarray(tau, dtype=np.float32) + + # Ensure tau is 2D + if tau_arr.ndim == 1: + tau_arr = tau_arr.reshape(-1, 1) + + # Validate dimensions + if tau_arr.shape[0] != len(X): + raise ValueError( + f"tau and X must have the same number of rows. " + f"Got tau: {tau_arr.shape[0]}, X: {len(X)}" + ) + + # Validate covariates + missing_covariates = [col for col in covariates if col not in X.columns] + if missing_covariates: + raise ValueError(f"The following covariates are not in X: {missing_covariates}") + + # Validate categorical_covariates + if categorical_covariates is None: + categorical_covariates = [] + else: + missing_categorical = [col for col in categorical_covariates if col not in covariates] + if missing_categorical: + raise ValueError( + f"categorical_covariates must be a subset of argument supplied in " + f"covariates parameter. Missing: {missing_categorical}" + ) + + # Separate numeric and categorical covariates + numeric_covariates = [col for col in covariates if col not in categorical_covariates] + + # Get the best uplift for each individual + tau_best = tau_arr.max(axis=1) + + # Get recommended treatment using the existing method + recommended_treatments = self.get_recommended_treatment(tau_arr) + + # Apply rollout threshold: if best uplift <= threshold, assign to Control + recommended = [] + for i, best_uplift in enumerate(tau_best): + if best_uplift <= rollout_threshold: + recommended.append("Control") + else: + # Use the recommended treatment from get_recommended_treatment + recommended.append(recommended_treatments.iloc[i]) + + # Create a DataFrame with recommendations + recommendation_df = pd.DataFrame({"recommended": recommended}) + + # Get unique groups in the order: Control, then treatments + groups = ["Control", *list(self.treatment_names)] + groups = [g for g in groups if g in recommendation_df["recommended"].unique()] + + # Store raw data for significance testing if needed + raw_data_by_group = {} + for group in groups: + mask = recommendation_df["recommended"] == group + raw_data_by_group[group] = X.loc[mask, covariates] + + # Calculate means/proportions for each covariate by group + results = {} + for group in groups: + group_data = raw_data_by_group[group] + group_results = {} + + # Handle numeric covariates + if numeric_covariates: + numeric_data = group_data[numeric_covariates] + + # Apply outlier trimming if requested (only for numeric) + if trim_outliers is not None: + MAX_TRIM_PERCENTAGE = 50 + if not 0 < trim_outliers < MAX_TRIM_PERCENTAGE: + raise ValueError( + f"trim_outliers must be between 0 and {MAX_TRIM_PERCENTAGE}, " + f"got {trim_outliers}" + ) + # For each numeric covariate, trim outliers + trimmed_data = numeric_data.copy() + for col in numeric_covariates: + lower_percentile = trim_outliers + upper_percentile = 100 - trim_outliers + lower_bound = numeric_data[col].quantile(lower_percentile / 100) + upper_bound = numeric_data[col].quantile(upper_percentile / 100) + # Set outliers to NaN (they'll be excluded from mean calculation) + trimmed_data.loc[ + (numeric_data[col] < lower_bound) | (numeric_data[col] > upper_bound), + col, + ] = np.nan + group_results.update(trimmed_data.mean().to_dict()) + else: + group_results.update(numeric_data.mean().to_dict()) + + # Handle categorical covariates (one-hot encode and show proportions) + if categorical_covariates: + for cat_col in categorical_covariates: + cat_data = group_data[cat_col] + # Get value counts as proportions + proportions = cat_data.value_counts(normalize=True) + # Add each category as a separate row + for category, proportion in proportions.items(): + # Create row name as "covariate_name: category_value" + row_name = f"{cat_col}: {category}" + group_results[row_name] = proportion + + results[group] = pd.Series(group_results) + + # Create results DataFrame + result_df = pd.DataFrame(results) + + # Round to 3 decimals for mean values + result_df = result_df.round(3) + + # Add difference columns with significance stars if requested + if show_significance and "Control" in result_df.columns: + from scipy import stats + + # For each treatment group (excluding Control) + treatment_groups = [g for g in groups if g != "Control"] + control_data = raw_data_by_group["Control"] + + # We'll build a new DataFrame with interleaved columns + new_columns = ["Control"] + for treatment_group in treatment_groups: + new_columns.append(treatment_group) + new_columns.append(f"{treatment_group} Diff") + + # Create new DataFrame with the interleaved column structure + new_result_df = pd.DataFrame(index=result_df.index) + new_result_df["Control"] = result_df["Control"] + + for treatment_group in treatment_groups: + treatment_data = raw_data_by_group[treatment_group] + + # Copy treatment column + new_result_df[treatment_group] = result_df[treatment_group] + + # Create difference column (as object dtype to hold strings with stars) + diff_col_name = f"{treatment_group} Diff" + new_result_df[diff_col_name] = pd.Series(dtype=object) + + # Test numeric covariates with t-test + for col in numeric_covariates: + if col in result_df.index: + control_values = control_data[col].dropna() + treatment_values = treatment_data[col].dropna() + + if len(control_values) > 1 and len(treatment_values) > 1: + # Calculate difference + control_mean = result_df.loc[col, "Control"] + treatment_mean = result_df.loc[col, treatment_group] + diff = treatment_mean - control_mean + + # Two-sample t-test + _, p_value = stats.ttest_ind( + treatment_values, control_values, equal_var=False + ) + stars = _get_significance_stars(p_value) + + # Format difference with stars + new_result_df.loc[col, diff_col_name] = f"{diff:.3f}{stars}" + + # Test categorical covariates with t-test on proportions + for cat_col in categorical_covariates: + control_cat = control_data[cat_col] + treatment_cat = treatment_data[cat_col] + + # Get all categories for this variable + all_categories = set(control_cat.unique()) | set(treatment_cat.unique()) + + for category in all_categories: + row_name = f"{cat_col}: {category}" + if row_name in result_df.index: + # Get proportions + control_prop = (control_cat == category).mean() + treatment_prop = (treatment_cat == category).mean() + diff = treatment_prop - control_prop + + # Create binary indicators for t-test + control_binary = (control_cat == category).astype(int) + treatment_binary = (treatment_cat == category).astype(int) + + if len(control_binary) > 1 and len(treatment_binary) > 1: + # Two-sample t-test on binary indicator + _, p_value = stats.ttest_ind( + treatment_binary, control_binary, equal_var=False + ) + stars = _get_significance_stars(p_value) + + # Format difference with stars + new_result_df.loc[row_name, diff_col_name] = f"{diff:.3f}{stars}" + + result_df = new_result_df + + # Add count row (as integers, not floats) + count_row = {} + if show_significance and "Control" in result_df.columns: + # Need to add counts for both treatment and diff columns + count_row["Control"] = int((recommendation_df["recommended"] == "Control").sum()) + for treatment_group in [g for g in groups if g != "Control"]: + mask = recommendation_df["recommended"] == treatment_group + count_row[treatment_group] = int(mask.sum()) + # No count for diff columns - leave as None + count_row[f"{treatment_group} Diff"] = None + else: + for group in groups: + mask = recommendation_df["recommended"] == group + count_row[group] = int(mask.sum()) + + # Append count as a new row + count_df = pd.DataFrame([count_row], index=["count"]) + result_df = pd.concat([result_df, count_df]) + + # Apply custom covariate names if provided + if covariate_names is not None: + # Create a mapping for renaming, check both original covariates and result_df index + # This handles both regular covariates and categorical one-hot encoded columns + rename_mapping = {} + for idx in result_df.index: + if idx in covariate_names: + rename_mapping[idx] = covariate_names[idx] + result_df = result_df.rename(index=rename_mapping) + + # Ensure count row has integer type for non-diff columns (convert to int to avoid .0) + if "count" in result_df.index: + for col in result_df.columns: + # Only convert to int if not a diff column and not None + if "Diff" not in col and pd.notna(result_df.loc["count", col]): + result_df.loc["count", col] = int(result_df.loc["count", col]) + + return result_df + + def permutation_test( # noqa: C901, PLR0912, PLR0915 + self, + t: pd.Series, + y: pd.Series, + tau: NDArray | pd.DataFrame, + metric: str = "max_business_value", + n_permutations: int = 1000, + random_seed: int = 42, + treatment_name: str | None = None, + treatment_idx: int | None = None, + population_size: int = 1, + top_fraction: float = 0.1, + title: str | None = None, + subtitle: str | None = None, + footnote_extra: str | Sequence[str] | None = None, + figsize: tuple[int] = (10, 6), + ) -> tuple[float, list[float]]: + """ + Perform a permutation test by shuffling treatment labels and computing business value. + + This function tests whether the observed metric value is statistically significant by + comparing it against a null distribution generated by randomly shuffling treatment + assignments. The test answers the question: "If I randomly reassign who got which + treatment (shuffle t), but still use my model's original predictions (original tau), + do I still get good business value/Qini/etc.?" + + If the model is good, randomly reassigning treatments should destroy the predictive + value, and the observed metric should be significantly better than the permuted values. + + Parameters + ---------- + t : pd.Series + Treatment assignment series (values should match control_name and treatment_names) + y : pd.Series + Outcome series (e.g., revenue, conversion) + tau : NDArray or pd.DataFrame + Pre-computed predicted uplift. This will be used for both observed and permuted + calculations (original predictions are kept fixed while treatments are shuffled). + metric : str, default="max_business_value" + Which metric to use for the permutation test. One of + ``"max_business_value"`` (default), ``"qini"``, or + ``"avg_value_at_coverage"``. + n_permutations : int, default=1000 + Number of permutations to perform (M) + random_seed : int, default=42 + Random seed for reproducibility + treatment_name : str, optional + Name of specific treatment to analyze. Used for "max_business_value" and + "avg_value_at_coverage" metrics. + treatment_idx : int, optional + Index of specific treatment to analyze. Used for "max_business_value" and + "avg_value_at_coverage" metrics. + population_size : int, default=1 + Target population size to scale gains. Used for "max_business_value" and + "avg_value_at_coverage" metrics. + top_fraction : float, default=0.1 + Fraction of top predicted uplift population to evaluate. Used for + "avg_value_at_coverage" metric only. Must be between 0 and 1. + title : str, optional + Title for the histogram plot. If None, a default title based on the metric is used. + subtitle : str, optional + Subtitle displayed below the main title + footnote_extra : str or list of str, optional + Additional text to append to the automatic footnote + figsize : tuple[int], default=(10, 6) + Figure size (width, height) + + Returns + ------- + tuple[float, list[float]] + A tuple ``(observed_value, permuted_values)`` where + ``observed_value`` is the actual metric with true treatment + assignments and ``permuted_values`` is a list of metric values + from permuted treatment assignments. + + Notes + ----- + - Creates a histogram showing the null distribution (permuted values) + - Red vertical line indicates the observed value from actual data + - If observed value is far in the tail, it suggests true treatment effect + - Uses reproducible random seeds for each permutation + - P-value can be calculated as: (# permuted >= observed) / n_permutations + - Supported metrics: ``"max_business_value"`` (tests if targeting strategy + maximizes business value), ``"qini"`` (tests if model predictions + correlate with actual uplift), and ``"avg_value_at_coverage"`` (tests + average value at a specific coverage threshold). + + Examples + -------- + >>> evaluator = UpliftExploreEvaluator("Control", "Treatment_A", "Treatment_B") + >>> + >>> # Test max business value (default) + >>> observed, permuted = evaluator.permutation_test( + ... t=test_treatments, + ... y=test_outcomes, + ... tau=predicted_tau, + ... n_permutations=1000 + ... ) + >>> + >>> # Test Qini coefficient + >>> observed_qini, permuted_qini = evaluator.permutation_test( + ... t=test_treatments, + ... y=test_outcomes, + ... tau=predicted_tau, + ... metric="qini", + ... n_permutations=1000 + ... ) + >>> + >>> # Test average value at 10% coverage + >>> observed_avg, permuted_avg = evaluator.permutation_test( + ... t=test_treatments, + ... y=test_outcomes, + ... tau=predicted_tau, + ... metric="avg_value_at_coverage", + ... top_fraction=0.1, + ... n_permutations=1000 + ... ) + >>> + >>> # Calculate p-value + >>> p_value = sum(p >= observed for p in permuted) / len(permuted) + >>> print(f"P-value: {p_value:.4f}") + >>> + >>> # Interpretation: Low p-value means your model's predictions are significantly + >>> # better than random. If p-value is high, the model may not be capturing + >>> # real treatment effects. + """ + if tau.shape[1] != len(self.treatment_names): + raise ValueError("tau must have the same number of columns as treatment_names") + + # Validate metric parameter + valid_metrics = ["max_business_value", "qini", "avg_value_at_coverage"] + if metric not in valid_metrics: + msg = f"metric must be one of {valid_metrics}, got '{metric}'" + raise ValueError(msg) + + # Warn if top_fraction is specified but metric is not avg_value_at_coverage + DEFAULT_TOP_FRACTION = 0.1 + if top_fraction != DEFAULT_TOP_FRACTION and metric != "avg_value_at_coverage": + warnings.warn( + f"top_fraction parameter is only used with metric='avg_value_at_coverage', " + f"but metric='{metric}' was specified. The top_fraction value will be ignored.", + UserWarning, + stacklevel=2, + ) + + # Set default title based on metric if not provided + if title is None: + if metric == "max_business_value": + title = "Permutation Test: Business Value Distribution" + elif metric == "qini": + title = "Permutation Test: Qini Coefficient Distribution" + elif metric == "avg_value_at_coverage": + title = f"Permutation Test: Avg Value at {top_fraction:.0%} Coverage" + + # Ensure data has clean indices for alignment + t_reset = t.reset_index(drop=True) + y_reset = y.reset_index(drop=True) + + # Use provided tau for observed value + tau_observed = tau.reset_index(drop=True) if hasattr(tau, "reset_index") else tau + if isinstance(tau_observed, pd.DataFrame): + tau_observed = tau_observed.values + + # Calculate observed metric value with actual treatment assignments + if metric == "max_business_value": + observed_value, _ = self.metric_max_business_value( + t=t_reset, + y=y_reset, + tau=tau_observed, + treatment_name=treatment_name, + treatment_idx=treatment_idx, + population_size=population_size, + return_ci=False, + ) + metric_label = "Maximum Business Value" + elif metric == "qini": + observed_value, _ = compute_qini( + tau_observed, + t_reset, + y_reset, + self.control_name, + *self.treatment_names, + ) + metric_label = "Qini Coefficient" + elif metric == "avg_value_at_coverage": + observed_value = self.metric_avg_value_at_coverage( + t=t_reset, + y=y_reset, + tau=tau_observed, + top_fraction=top_fraction, + treatment_name=treatment_name, + treatment_idx=treatment_idx, + population_size=population_size, + return_ci=False, + ) + metric_label = f"Avg Value at {top_fraction:.0%} Coverage" + + # Perform permutations + # Key insight: Keep tau (predictions) fixed, shuffle t (treatment assignments) + # This tests if the model's predictions still work when treatments are randomly reassigned + permuted_values = [] + + for i in range(n_permutations): + # Shuffle treatment assignments to break the treatment-outcome relationship + t_shuffled = t_reset.sample(frac=1, random_state=random_seed + i).reset_index(drop=True) + + # Calculate metric value with shuffled treatments but ORIGINAL predictions + # This tests: "Do my predictions still work if I randomly reassign treatments?" + if metric == "max_business_value": + perm_value, _ = self.metric_max_business_value( + t=t_shuffled, + y=y_reset, + tau=tau_observed, # Use original tau, not re-predicted + treatment_name=treatment_name, + treatment_idx=treatment_idx, + population_size=population_size, + return_ci=False, + ) + elif metric == "qini": + perm_value, _ = compute_qini( + tau_observed, # Use original tau, not re-predicted + t_shuffled, + y_reset, + self.control_name, + *self.treatment_names, + ) + elif metric == "avg_value_at_coverage": + perm_value = self.metric_avg_value_at_coverage( + t=t_shuffled, + y=y_reset, + tau=tau_observed, # Use original tau, not re-predicted + top_fraction=top_fraction, + treatment_name=treatment_name, + treatment_idx=treatment_idx, + population_size=population_size, + return_ci=False, + ) + + permuted_values.append(perm_value) + + # Create histogram plot + fig, ax = plt.subplots(figsize=figsize) + + ax.hist(permuted_values, bins=50, alpha=0.7, color="skyblue", edgecolor="black") + ax.axvline( + observed_value, + color="red", + linestyle="--", + linewidth=2, + label=f"Actual {metric_label.lower()} = {observed_value:.2f}", + ) + + ax.set_xlabel(metric_label, fontsize=11) + ax.set_ylabel("Frequency", fontsize=11) + ax.tick_params(axis="both", labelsize=9) + + # Add title and subtitle (consistent with other plots) + fig.suptitle(title, fontsize=14, fontweight="bold", y=0.98) + if subtitle: + fig.text(0.5, 0.935, subtitle, ha="center", va="top", fontsize=10) + + ax.legend(fontsize=10) + ax.grid(True, axis="y", alpha=0.3) + + # Calculate and display p-value + p_value = sum(p >= observed_value for p in permuted_values) / n_permutations + n_perm_above = sum(p >= observed_value for p in permuted_values) + ax.text( + 0.02, + 0.98, + f"P-value = {p_value:.4f}\n({n_perm_above}/{n_permutations} permutations ≥ observed)", + transform=ax.transAxes, + fontsize=10, + verticalalignment="top", + bbox=dict(boxstyle="round", facecolor="wheat", alpha=0.5), + ) + + # Add footnote (consistent with other plots) + if metric == "max_business_value": + metric_name = "business value" + elif metric == "qini": + metric_name = "Qini coefficient" + elif metric == "avg_value_at_coverage": + metric_name = f"average value at {top_fraction:.0%} coverage" + + base_foot = ( + f"Permutation test: Treatment labels were randomly shuffled {n_permutations:,} times " + f"while keeping model predictions fixed. For each shuffle, {metric_name} " + "was calculated. The histogram shows the null distribution; the red line shows " + "the observed value with actual labels." + ) + + if footnote_extra: + if isinstance(footnote_extra, list | tuple): + extra = " ".join(s.strip() for s in footnote_extra if s is not None) + else: + extra = str(footnote_extra).strip() + footnote = f"{base_foot} {extra}" if extra else base_foot + else: + footnote = base_foot + + fig.text( + 0.5, + 0.01, + footnote, + ha="center", + fontsize=9, + wrap=True, + ) + + plt.tight_layout(rect=[0, 0.05, 1, 0.96 if subtitle else 0.92]) + plt.show() + + return observed_value, permuted_values + + def _get_recommended_policy( + self, + tau: NDArray, + threshold: float, + ) -> pd.Series: + """Get recommended policy for each observation based on uplift predictions. + + Unlike get_recommended_treatment, this method includes a threshold check + and recommends control when max uplift <= threshold. + """ + best_uplift = np.max(tau, axis=1) + best_treatment_idx = np.argmax(tau, axis=1) + recommendations = np.where( + best_uplift > threshold, + np.array(self.treatment_names)[best_treatment_idx], + self.control_name, + ) + return pd.Series(recommendations) + + def _get_slice_indices( + self, + tau: NDArray, + top_fraction: float, + fraction_range: tuple[float, float] | None, + ) -> NDArray: + """Get indices of observations in the specified slice based on uplift ranking.""" + n_samples = len(tau) + best_uplift = np.max(tau, axis=1) if tau.ndim > 1 else tau + ranks = np.argsort(np.argsort(best_uplift)[::-1]) + percentiles = ranks / n_samples + + if fraction_range is not None: + low, high = fraction_range + mask = (percentiles >= low) & (percentiles < high) + else: + mask = percentiles < top_fraction + + return np.where(mask)[0] + + def _build_crosstab( + self, + recs1: pd.Series, + recs2: pd.Series, + all_categories: list[str], + normalize: bool, + ) -> pd.DataFrame: + """Build a crosstab of recommendations from two models with totals.""" + crosstab = pd.crosstab(recs1, recs2, normalize="all" if normalize else False) + + for cat in all_categories: + if cat not in crosstab.index: + crosstab.loc[cat] = 0 + if cat not in crosstab.columns: + crosstab[cat] = 0 + + crosstab = crosstab.reindex(index=all_categories, columns=all_categories, fill_value=0) + + # Add totals row and column + crosstab["Total"] = crosstab.sum(axis=1) + crosstab.loc["Total"] = crosstab.sum(axis=0) + + return crosstab + + def _compute_detailed_overlap(self, tau1: NDArray, tau2: NDArray, n_bins: int) -> pd.DataFrame: + """Compute detailed bin distribution for model overlap.""" + bins1 = assign_bins(pd.Series(tau1), n_bins) + bins2 = assign_bins(pd.Series(tau2), n_bins) + + top_bin = 1 + model1_top_mask = bins1 == top_bin + model2_top_mask = bins2 == top_bin + + dist_model1_top_in_model2 = bins2[model1_top_mask].value_counts(normalize=True).sort_index() + dist_model2_top_in_model1 = bins1[model2_top_mask].value_counts(normalize=True).sort_index() + + all_bins = pd.Index(range(1, n_bins + 1), name="bin") + dist_model1_top_in_model2 = dist_model1_top_in_model2.reindex(all_bins, fill_value=0.0) + dist_model2_top_in_model1 = dist_model2_top_in_model1.reindex(all_bins, fill_value=0.0) + + result = pd.DataFrame( + { + "model1_top_in_model2_bins": dist_model1_top_in_model2, + "model2_top_in_model1_bins": dist_model2_top_in_model1, + } + ) + result.index.name = "bin" + return result + + def compare_model_overlap( + self, + tau1: NDArray, + tau2: NDArray, + top_fraction: float = 0.1, + detailed: bool = False, + n_bins: int | None = None, + ) -> float | pd.DataFrame: + """ + Compare overlap between top segments of two uplift models. + + This method answers the question: "What percent of people in the top decile + (or top_fraction) are the same across two models?" + + Parameters + ---------- + tau1 : array-like + Predicted uplift from model 1. Can be 1D or 2D array. + If 2D, the best uplift across treatments is used. + tau2 : array-like + Predicted uplift from model 2. Can be 1D or 2D array. + If 2D, the best uplift across treatments is used. + top_fraction : float, default=0.1 + Fraction of population to consider as "top" segment (e.g., 0.1 = top 10%). + detailed : bool, default=False + If False, returns only the overlap percentage. + If True, returns a DataFrame showing the distribution of each model's + top segment across the other model's deciles. + n_bins : int, optional + Number of bins to use for the detailed breakdown. If None, uses + the evaluator's n_bins attribute. + + Returns + ------- + float or pd.DataFrame + If detailed=False: Percentage of overlap (0-1) between top segments. + If detailed=True: DataFrame with two columns showing distribution of + each model's top segment across the other model's bins. + + Examples + -------- + >>> evaluator = UpliftExploreEvaluator("Control", "Treat A", "Treat B") + >>> tau1 = model1.predict(X) + >>> tau2 = model2.predict(X) + >>> # Simple overlap percentage + >>> overlap = evaluator.compare_model_overlap(tau1, tau2, top_fraction=0.1) + >>> print(f"Top decile overlap: {overlap:.1%}") + Top decile overlap: 65.3% + + >>> # Detailed breakdown + >>> breakdown = evaluator.compare_model_overlap(tau1, tau2, detailed=True) + >>> print(breakdown) + + Notes + ----- + This comparison only makes sense when both models are predicting uplift + for the same (or comparable) treatments. Comparing models trained on + different treatments would not yield meaningful results. + """ + tau1 = np.asarray(tau1) + tau2 = np.asarray(tau2) + + if tau1.shape[0] != tau2.shape[0]: + raise ValueError( + f"tau1 and tau2 must have the same number of observations. " + f"Got {tau1.shape[0]} and {tau2.shape[0]}." + ) + + # Flatten to 1D: use best uplift across treatments if multi-treatment + if tau1.ndim > 1 and tau1.shape[1] > 1: + tau1 = compute_best_uplift_among_treatments(tau1) + else: + tau1 = tau1.flatten() + + if tau2.ndim > 1 and tau2.shape[1] > 1: + tau2 = compute_best_uplift_among_treatments(tau2) + else: + tau2 = tau2.flatten() + + n_samples = len(tau1) + top_n = int(np.ceil(n_samples * top_fraction)) + + top_indices_1 = set(np.argsort(tau1)[::-1][:top_n]) + top_indices_2 = set(np.argsort(tau2)[::-1][:top_n]) + + overlap_count = len(top_indices_1 & top_indices_2) + overlap_fraction = overlap_count / top_n + + if not detailed: + return overlap_fraction + + n_bins = n_bins or self.n_bins + return self._compute_detailed_overlap(tau1, tau2, n_bins) + + def compare_treatment_recommendations( # noqa: PLR0915 + self, + tau1: NDArray, + tau2: NDArray, + threshold1: float = 0.0, + threshold2: float = 0.0, + top_fraction: float | None = None, + fraction_range: tuple[float, float] | None = None, + detailed: bool = False, + normalize: bool = True, + ) -> dict[str, float] | dict[str, pd.DataFrame]: + """ + Compare treatment recommendations between two uplift models. + + This method analyzes whether two models recommend the same treatment + for users in a specified slice (e.g., top decile) of the population. + + Parameters + ---------- + tau1 : array-like, shape (n_samples, n_treatments) + Predicted uplift from model 1. + tau2 : array-like, shape (n_samples, n_treatments) + Predicted uplift from model 2. + threshold1 : float, default=0.0 + Threshold for model 1 recommendations. If max uplift <= threshold1, + control is recommended. + threshold2 : float, default=0.0 + Threshold for model 2 recommendations. If max uplift <= threshold2, + control is recommended. + top_fraction : float, optional + Fraction of population to consider as "top" segment (e.g., 0.1 = top 10%). + If None (default), analyzes the entire population. + Ignored if fraction_range is provided. + fraction_range : tuple[float, float], optional + Custom range of percentiles to analyze, e.g., (0.05, 0.15) for the + 5th to 15th percentile from the top. Overrides top_fraction if provided. + detailed : bool, default=False + If False, returns agreement rates for each model's slice. + If True, returns crosstab DataFrames showing recommendation distributions. + normalize : bool, default=True + If True, crosstab values are proportions (sum to 1.0). + If False, crosstab values are counts. Only applies when detailed=True. + + Returns + ------- + dict[str, float] or dict[str, pd.DataFrame] + If ``detailed=False``, returns a dict with agreement rates: + ``"overall_agreement"`` (overall agreement rate across all users, or + sliced users if top_fraction/fraction_range specified), + ``"model1_slice_agreement"`` and ``"model2_slice_agreement"`` + (only present when slicing is applied). + + If ``detailed=True``, returns a dict with crosstab DataFrames: + ``"overall"`` (crosstab for all or sliced users), + ``"model1_slice"`` and ``"model2_slice"`` (only present when + slicing is applied). + + Examples + -------- + >>> evaluator = UpliftExploreEvaluator("Control", "Treat A", "Treat B") + >>> tau1 = model1.predict(X) + >>> tau2 = model2.predict(X) + + >>> # Entire population agreement + >>> agreement = evaluator.compare_treatment_recommendations(tau1, tau2) + >>> print(f"Overall agreement: {agreement['overall_agreement']:.1%}") + + >>> # Top decile only + >>> agreement = evaluator.compare_treatment_recommendations( + ... tau1, tau2, top_fraction=0.1 + ... ) + >>> print(f"Agreement in Model 1's top decile: {agreement['model1_slice_agreement']:.1%}") + + >>> # Detailed crosstabs for entire population + >>> crosstabs = evaluator.compare_treatment_recommendations( + ... tau1, tau2, detailed=True + ... ) + >>> print(crosstabs["overall"]) + + >>> # Custom slice (5th to 15th percentile) + >>> result = evaluator.compare_treatment_recommendations( + ... tau1, tau2, fraction_range=(0.05, 0.15) + ... ) + + >>> # Different thresholds for each model + >>> result = evaluator.compare_treatment_recommendations( + ... tau1, tau2, threshold1=5.0, threshold2=0.0 + ... ) + + Notes + ----- + This comparison only makes sense when both models are predicting uplift + for the same treatments. + + - If no slicing (``top_fraction=None`` and ``fraction_range=None``), + analyzes agreement across the entire population. + - If slicing is specified, analyzes both directions: + (1) users in Model 1's top slice and whether they get the same + recommendation from Model 2, and (2) the reverse. + """ + tau1 = np.asarray(tau1) + tau2 = np.asarray(tau2) + + if tau1.shape[0] != tau2.shape[0]: + raise ValueError( + f"tau1 and tau2 must have the same number of observations. " + f"Got {tau1.shape[0]} and {tau2.shape[0]}." + ) + + n_treatments = len(self.treatment_names) + if tau1.shape[1] != n_treatments or tau2.shape[1] != n_treatments: + raise ValueError( + f"Number of treatments in tau arrays must match treatment_names. " + f"Got tau1: {tau1.shape[1]}, tau2: {tau2.shape[1]}, " + f"treatment_names: {n_treatments}." + ) + + recs1 = self._get_recommended_policy(tau1, threshold1) + recs2 = self._get_recommended_policy(tau2, threshold2) + + all_categories = [self.control_name, *list(self.treatment_names)] + + # Check if slicing is requested + use_slicing = top_fraction is not None or fraction_range is not None + + if not use_slicing: + # No slicing - analyze entire population + if not detailed: + overall_agreement = (recs1 == recs2).mean() + return {"overall_agreement": overall_agreement} + overall_crosstab = self._build_crosstab(recs1, recs2, all_categories, normalize) + return {"overall": overall_crosstab} + + # Slicing requested - analyze both model's slices + slice_indices_1 = self._get_slice_indices(tau1, top_fraction, fraction_range) + slice_indices_2 = self._get_slice_indices(tau2, top_fraction, fraction_range) + + recs1_in_slice1 = recs1.iloc[slice_indices_1] + recs2_in_slice1 = recs2.iloc[slice_indices_1] + + recs1_in_slice2 = recs1.iloc[slice_indices_2] + recs2_in_slice2 = recs2.iloc[slice_indices_2] + + if not detailed: + agreement1 = (recs1_in_slice1 == recs2_in_slice1).mean() + agreement2 = (recs1_in_slice2 == recs2_in_slice2).mean() + return { + "model1_slice_agreement": agreement1, + "model2_slice_agreement": agreement2, + } + + # detailed=True with slicing + crosstab1 = self._build_crosstab( + recs1_in_slice1, recs2_in_slice1, all_categories, normalize + ) + crosstab1.index.name = "Model 1 Recommends" + crosstab1.columns.name = "Model 2 Recommends" + + crosstab2 = self._build_crosstab( + recs2_in_slice2, recs1_in_slice2, all_categories, normalize + ) + crosstab2.index.name = "Model 2 Recommends" + crosstab2.columns.name = "Model 1 Recommends" + + return { + "model1_slice": crosstab1, + "model2_slice": crosstab2, + } + + def compare_rank_correlation( # noqa: C901, PLR0912, PLR0915 + self, + tau1: NDArray, + tau2: NDArray, + method: str = "kendall", + top_fraction: float | None = None, + fraction_range: tuple[float, float] | None = None, + slice_by: str = "both", + plot: bool = False, + figsize: tuple[int, int] = (8, 8), + vmin: float | None = None, + vmax: float | None = None, + ) -> float: + """ + Compare rank correlation between two uplift models. + + This method measures how similarly two models rank individuals, + regardless of the absolute uplift values they predict. + + Parameters + ---------- + tau1 : array-like + Predicted uplift from model 1. Can be 1D or 2D array. + If 2D, the best uplift across treatments is used. + tau2 : array-like + Predicted uplift from model 2. Can be 1D or 2D array. + If 2D, the best uplift across treatments is used. + method : str, default="kendall" + Correlation method: "kendall" or "spearman". + top_fraction : float, optional + If provided, only include individuals in the top X% (e.g., 0.1 = top 10%). + The slice is determined by ``slice_by`` parameter. + fraction_range : tuple[float, float], optional + Custom range of percentiles, e.g., (0.05, 0.15) for 5th to 15th percentile. + Overrides top_fraction if provided. + slice_by : str, default="both" + How to determine the slice. One of ``"model1"`` (Model 1's top + segment), ``"model2"`` (Model 2's top segment), or ``"both"`` + (intersection of both models' top segments). + plot : bool, default=False + If True, display a scatter plot of Model 1 ranks vs Model 2 ranks. + figsize : tuple[int, int], default=(8, 8) + Figure size for the scatter plot. + vmin : float, optional + Minimum value for hexbin color scale. If None, uses data minimum. + Useful for consistent color scales across multiple comparison plots. + vmax : float, optional + Maximum value for hexbin color scale. If None, uses data maximum. + Useful for consistent color scales across multiple comparison plots. + + Returns + ------- + float + The rank correlation coefficient (-1 to +1). + +1 = perfect agreement, 0 = no relationship, -1 = complete reversal. + + Examples + -------- + >>> evaluator = UpliftExploreEvaluator("Control", "Treat A", "Treat B") + >>> tau1 = model1.predict(X) + >>> tau2 = model2.predict(X) + >>> # Overall rank correlation + >>> corr = evaluator.compare_rank_correlation(tau1, tau2) + >>> print(f"Kendall correlation: {corr:.3f}") + + >>> # Correlation among top 20% of both models + >>> corr = evaluator.compare_rank_correlation( + ... tau1, tau2, top_fraction=0.2, slice_by="both" + ... ) + + >>> # With scatter plot + >>> corr = evaluator.compare_rank_correlation(tau1, tau2, plot=True) + + >>> # With consistent color scale across multiple plots + >>> corr_1_2 = evaluator.compare_rank_correlation(tau1, tau2, plot=True, vmin=1, vmax=100) + >>> corr_1_3 = evaluator.compare_rank_correlation(tau1, tau3, plot=True, vmin=1, vmax=100) + """ + from scipy.stats import kendalltau, spearmanr + + tau1 = np.asarray(tau1) + tau2 = np.asarray(tau2) + + if tau1.shape[0] != tau2.shape[0]: + raise ValueError( + f"tau1 and tau2 must have the same number of observations. " + f"Got {tau1.shape[0]} and {tau2.shape[0]}." + ) + + if method not in ("kendall", "spearman"): + raise ValueError(f"method must be 'kendall' or 'spearman', got '{method}'") + + if slice_by not in ("model1", "model2", "both"): + raise ValueError(f"slice_by must be 'model1', 'model2', or 'both', got '{slice_by}'") + + # Flatten to 1D: use best uplift across treatments if multi-treatment + if tau1.ndim > 1 and tau1.shape[1] > 1: + tau1 = compute_best_uplift_among_treatments(tau1) + else: + tau1 = tau1.flatten() + + if tau2.ndim > 1 and tau2.shape[1] > 1: + tau2 = compute_best_uplift_among_treatments(tau2) + else: + tau2 = tau2.flatten() + + # Compute ranks (1 = highest uplift) + ranks1 = len(tau1) - np.argsort(np.argsort(tau1)) + ranks2 = len(tau2) - np.argsort(np.argsort(tau2)) + + # Apply slicing if requested + if top_fraction is not None or fraction_range is not None: + indices1 = self._get_slice_indices(tau1, top_fraction or 0.1, fraction_range) + indices2 = self._get_slice_indices(tau2, top_fraction or 0.1, fraction_range) + + if slice_by == "model1": + mask = np.isin(np.arange(len(tau1)), indices1) + elif slice_by == "model2": + mask = np.isin(np.arange(len(tau2)), indices2) + else: # both + mask = np.isin(np.arange(len(tau1)), indices1) & np.isin( + np.arange(len(tau2)), indices2 + ) + + ranks1 = ranks1[mask] + ranks2 = ranks2[mask] + + # Compute correlation + if method == "kendall": + corr, _ = kendalltau(ranks1, ranks2) + else: + corr, _ = spearmanr(ranks1, ranks2) + + # Plot if requested + if plot: + _fig, ax = plt.subplots(figsize=figsize) + + # Use hexbin to show density with optional vmin/vmax + hexbin = ax.hexbin( + ranks1, + ranks2, + gridsize=30, + cmap="Blues", + mincnt=1, + alpha=0.8, + vmin=vmin, + vmax=vmax, + ) + plt.colorbar(hexbin, ax=ax, label="Count") + + # Add diagonal reference line + min_rank = min(ranks1.min(), ranks2.min()) + max_rank = max(ranks1.max(), ranks2.max()) + ax.plot( + [min_rank, max_rank], + [min_rank, max_rank], + "r--", + linewidth=2, + label="Perfect agreement", + ) + + ax.set_xlabel("Model 1 Rank (1 = highest uplift)", fontsize=11) + ax.set_ylabel("Model 2 Rank (1 = highest uplift)", fontsize=11) + + title = f"Rank Comparison ({method.capitalize()} correlation: {corr:.3f})" + ax.set_title(title, fontsize=12, fontweight="bold") + + # Add subtitle if sliced + if top_fraction is not None or fraction_range is not None: + if fraction_range: + slice_desc = f"{fraction_range[0]:.0%} to {fraction_range[1]:.0%}" + else: + slice_desc = f"top {top_fraction:.0%}" + subtitle = f"Slice: {slice_desc} (by {slice_by}), n={len(ranks1):,}" + ax.text(0.5, 1.02, subtitle, transform=ax.transAxes, ha="center", fontsize=10) + + ax.legend(loc="upper left") + ax.grid(True, alpha=0.3) + + plt.tight_layout() + plt.show() + + return corr + + def summarize_treatment_margins( # noqa: PLR0915 + self, + tau: NDArray, + threshold: float | None = None, + top_fraction: float | None = None, + fraction_range: tuple[float, float] | None = None, + ) -> dict[str, float | pd.DataFrame]: + """ + Summarize treatment margins to understand model decisiveness. + + This method analyzes how decisive the model is in choosing treatments. + For each individual, it computes the margin between the best and second-best + treatment uplift. Larger margins indicate more confident/decisive predictions. + + Parameters + ---------- + tau : array-like, shape (n_samples, n_treatments) + Predicted uplift for each treatment vs control. + threshold : float, optional + Margin threshold for "clear winner". If None (default), uses 1 standard + deviation of the best uplift distribution across all individuals. + top_fraction : float, optional + If provided, only analyze individuals in the top X% (e.g., 0.1 = top 10%). + Based on best uplift ranking. + fraction_range : tuple[float, float], optional + Custom range of percentiles, e.g., (0.05, 0.15) for 5th to 15th percentile. + Overrides top_fraction if provided. + + Returns + ------- + dict + Dictionary with the following keys: + + - "threshold": The margin threshold used for "clear winner" determination. + - "summary": DataFrame with columns ``recommended_treatment``, + ``count``, ``mean_margin``, ``median_margin``, ``std_margin``, and + ``pct_clear_winner`` (proportion with margin > threshold, 0-1). + Includes an "Overall" row summarizing all individuals. + - "treatment__details": For each treatment (0-indexed), a DataFrame + showing what the second-best treatment was, with the same statistics. + Returns None for treatments with no recommendations. + Example keys: "treatment_0_details", "treatment_1_details". + + Examples + -------- + >>> evaluator = UpliftExploreEvaluator("Control", "Treat A", "Treat B") + >>> tau = model.predict(X) + >>> result = evaluator.summarize_treatment_margins(tau) + >>> print(f"Clear winner threshold: {result['threshold']:.2f}") + >>> print(result['summary']) + >>> print(result['treatment_0_details']) # Detailed breakdown for first treatment + + >>> # Top decile only + >>> result = evaluator.summarize_treatment_margins(tau, top_fraction=0.1) + + >>> # Custom threshold + >>> result = evaluator.summarize_treatment_margins(tau, threshold=5.0) + + Notes + ----- + For single-treatment models, a warning is issued and the function returns + metrics based on uplift vs control (margin is the uplift itself). + """ + import warnings + + tau = np.asarray(tau) + + if tau.ndim == 1 or (tau.ndim == 2 and tau.shape[1] == 1): # noqa: PLR2004 + warnings.warn( + "Single-treatment model detected. Margins are computed as uplift vs control " + "(best treatment vs doing nothing). For multi-treatment models, margin is " + "the gap between best and second-best treatment.", + UserWarning, + stacklevel=2, + ) + tau = tau.reshape(-1, 1) + single_treatment = True + else: + single_treatment = False + + n_treatments = tau.shape[1] + + # Apply slicing if requested + if top_fraction is not None or fraction_range is not None: + best_uplift_all = np.max(tau, axis=1) + indices = self._get_slice_indices(best_uplift_all, top_fraction or 0.1, fraction_range) + tau = tau[indices] + + # Compute best and second-best uplift + if single_treatment: + best_uplift = tau.flatten() + second_best_uplift = np.zeros(len(best_uplift)) + margins = best_uplift # Margin vs control + else: + sorted_tau = np.sort(tau, axis=1)[:, ::-1] + best_uplift = sorted_tau[:, 0] + second_best_uplift = sorted_tau[:, 1] if n_treatments > 1 else np.zeros(len(tau)) + margins = best_uplift - second_best_uplift + + # Determine threshold + if threshold is None: + threshold = np.std(best_uplift) + + # Get recommended treatment and second-best treatment + best_treatment_idx = np.argmax(tau, axis=1) + recommendations = np.where( + best_uplift > 0, + np.array(self.treatment_names)[best_treatment_idx], + self.control_name, + ) + + # Get second-best treatment for detailed breakdown + if not single_treatment and n_treatments > 1: + # Create augmented array with control (uplift=0) as first column + tau_with_control = np.column_stack([np.zeros(len(tau)), tau]) + # Sort all options (control + treatments) to find second-best + sorted_indices = np.argsort(tau_with_control, axis=1)[:, ::-1] + second_best_idx = sorted_indices[:, 1] + # Map indices: 0 = control, 1+ = treatments + all_options = np.array([self.control_name, *self.treatment_names]) + second_best_treatments = all_options[second_best_idx] + else: + second_best_treatments = np.array([self.control_name] * len(tau)) + + # Build DataFrame + df = pd.DataFrame( + { + "recommended_treatment": recommendations, + "second_best_treatment": second_best_treatments, + "margin": margins, + "is_clear": margins > threshold, + } + ) + + # Compute stats by recommended treatment + stats = ( + df.groupby("recommended_treatment", observed=True) + .agg( + count=("margin", "size"), + mean_margin=("margin", "mean"), + median_margin=("margin", "median"), + std_margin=("margin", "std"), + pct_clear_winner=("is_clear", "mean"), + ) + .reset_index() + ) + + # Add overall row + overall = pd.DataFrame( + { + "recommended_treatment": ["Overall"], + "count": [len(df)], + "mean_margin": [df["margin"].mean()], + "median_margin": [df["margin"].median()], + "std_margin": [df["margin"].std()], + "pct_clear_winner": [df["is_clear"].mean()], + } + ) + + summary = pd.concat([stats, overall], ignore_index=True) + + # Create detailed breakdown for each treatment + result = {"threshold": threshold, "summary": summary} + + # For each treatment (except control), create detailed breakdown + for idx, treatment in enumerate(self.treatment_names): + # Filter to rows where this treatment was recommended + treatment_df = df[df["recommended_treatment"] == treatment].copy() + + if len(treatment_df) == 0: + result[f"treatment_{idx}_details"] = None + continue + + # Compute stats by second-best treatment + second_best_stats = ( + treatment_df.groupby("second_best_treatment", observed=True) + .agg( + count=("margin", "size"), + mean_margin=("margin", "mean"), + median_margin=("margin", "median"), + std_margin=("margin", "std"), + pct_clear_winner=("is_clear", "mean"), + ) + .reset_index() + ) + + # Add overall row for this treatment + treatment_overall = pd.DataFrame( + { + "second_best_treatment": ["Overall"], + "count": [len(treatment_df)], + "mean_margin": [treatment_df["margin"].mean()], + "median_margin": [treatment_df["margin"].median()], + "std_margin": [treatment_df["margin"].std()], + "pct_clear_winner": [treatment_df["is_clear"].mean()], + } + ) + + treatment_details = pd.concat([second_best_stats, treatment_overall], ignore_index=True) + result[f"treatment_{idx}_details"] = treatment_details + + return result + + def compare_feature_importance( # noqa: PLR0915 + self, + importance1: NDArray, + importance2: NDArray, + feature_names: list[str], + top_n: int = 10, + detailed: bool = False, + sort_by: str = "model1_importance", + unique_top_n: int = 15, + ) -> dict | pd.DataFrame: + """ + Compare feature importance between two uplift models. + + This method analyzes whether two models rely on similar features + for making predictions. + + Parameters + ---------- + importance1 : array-like + Feature importance values from model 1 (e.g., ``feature_importances_``, + SHAP values, or permutation importance). + importance2 : array-like + Feature importance values from model 2. + feature_names : list[str] + Names of the features corresponding to the importance arrays. + top_n : int, default=10 + Number of top features to use for overlap calculation. + detailed : bool, default=False + If False, returns summary metrics only. + If True, returns detailed DataFrame with per-feature comparison. + sort_by : str, default="model1_importance" + How to sort the detailed DataFrame. One of ``"model1_importance"`` + (sort by model 1's importance, high to low), + ``"model2_importance"`` (sort by model 2's importance, high to low), + or ``"abs_rank_diff"`` (sort by absolute rank difference, high to + low — features with zero importance in both models are filtered out). + unique_top_n : int, default=15 + Number of unique features to show in model1_unique and model2_unique tables. + Only applies when detailed=True. + + Returns + ------- + dict or pd.DataFrame + If ``detailed=False``, returns a dictionary with summary metrics: + ``"top_N_overlap"`` (proportion of top N features that overlap, 0-1), + ``"top_N_overlap_count"`` (number of features in both top N), and + ``"mean_rank_diff"`` (average absolute rank difference across all features). + + If ``detailed=True``, returns a dictionary with DataFrames: + + - ``"comparison"``: Main comparison DataFrame with columns + ``feature``, ``model1_importance``, ``model2_importance``, + ``model1_rank``, ``model2_rank``, ``rank_diff``, + ``abs_rank_diff``, and ``in_both_topN``. + - ``"model1_unique"``: Top features important in model 1 but zero + in model 2. + - ``"model2_unique"``: Top features important in model 2 but zero + in model 1. + + Examples + -------- + >>> evaluator = UpliftExploreEvaluator("Control", "Treat A", "Treat B") + >>> pipeline1 = UpliftRegressorPipeline.load("model1.joblib") + >>> pipeline2 = UpliftRegressorPipeline.load("model2.joblib") + >>> importance1 = pipeline1.model.learner.feature_importances_ + >>> importance2 = pipeline2.model.learner.feature_importances_ + >>> feature_names = pipeline1.get_feature_names(raw=False) + >>> # Simple summary + >>> summary = evaluator.compare_feature_importance(importance1, importance2, feature_names) + >>> print(f"Top 10 overlap: {summary['top_10_overlap']:.1%}") + + >>> # Detailed comparison + >>> details = evaluator.compare_feature_importance( + ... importance1, importance2, feature_names, detailed=True + ... ) + >>> print(details.head(10)) + + >>> # Sort by disagreement + >>> details = evaluator.compare_feature_importance( + ... importance1, importance2, feature_names, + ... detailed=True, sort_by="abs_rank_diff" + ... ) + """ + importance1 = np.asarray(importance1) + importance2 = np.asarray(importance2) + + if len(importance1) != len(importance2): + raise ValueError( + f"importance1 and importance2 must have the same length. " + f"Got {len(importance1)} and {len(importance2)}." + ) + + if len(importance1) != len(feature_names): + raise ValueError( + f"Length of importance arrays must match feature_names. " + f"Got importance length: {len(importance1)}, feature_names: {len(feature_names)}." + ) + + if sort_by not in ("model1_importance", "model2_importance", "abs_rank_diff"): + raise ValueError( + f"sort_by must be 'model1_importance', 'model2_importance', or 'abs_rank_diff', " + f"got '{sort_by}'" + ) + + # Compute ranks (1 = most important) + ranks1 = len(importance1) - np.argsort(np.argsort(importance1)) + ranks2 = len(importance2) - np.argsort(np.argsort(importance2)) + + # Build DataFrame + df = pd.DataFrame( + { + "feature": feature_names, + "model1_importance": importance1, + "model2_importance": importance2, + "model1_rank": ranks1, + "model2_rank": ranks2, + } + ) + + df["rank_diff"] = df["model1_rank"] - df["model2_rank"] + df["abs_rank_diff"] = df["rank_diff"].abs() + + # Identify top N features + top_n_model1 = set(df.nsmallest(top_n, "model1_rank")["feature"]) + top_n_model2 = set(df.nsmallest(top_n, "model2_rank")["feature"]) + df["in_both_topN"] = df["feature"].isin(top_n_model1 & top_n_model2) + + if not detailed: + overlap_count = len(top_n_model1 & top_n_model2) + return { + f"top_{top_n}_overlap": overlap_count / top_n, + f"top_{top_n}_overlap_count": overlap_count, + "mean_rank_diff": df["abs_rank_diff"].mean(), + } + + # Filter out zero-in-both when sorting by rank difference + comparison_df = df.copy() + if sort_by == "abs_rank_diff": + comparison_df = comparison_df[ + (comparison_df["model1_importance"] != 0) + | (comparison_df["model2_importance"] != 0) + ] + + # Sort comparison DataFrame + if sort_by == "model1_importance": + comparison_df = comparison_df.sort_values("model1_importance", ascending=False) + elif sort_by == "model2_importance": + comparison_df = comparison_df.sort_values("model2_importance", ascending=False) + else: # abs_rank_diff + comparison_df = comparison_df.sort_values("abs_rank_diff", ascending=False) + + comparison_df = comparison_df.reset_index(drop=True) + + # Find unique features: important in one model but zero in the other + model1_unique = ( + df[(df["model1_rank"] <= top_n) & (df["model2_importance"] == 0)] + .nsmallest(unique_top_n, "model1_rank")[ + ["feature", "model1_importance", "model1_rank", "model2_importance", "model2_rank"] + ] + .reset_index(drop=True) + ) + + model2_unique = ( + df[(df["model2_rank"] <= top_n) & (df["model1_importance"] == 0)] + .nsmallest(unique_top_n, "model2_rank")[ + ["feature", "model1_importance", "model1_rank", "model2_importance", "model2_rank"] + ] + .reset_index(drop=True) + ) + + return { + "comparison": comparison_df, + "model1_unique": model1_unique, + "model2_unique": model2_unique, + } + + def analyze_subgroup_performance( # noqa: C901, PLR0912, PLR0915 + self, + tau: NDArray, + y: Series, + t: Series, + subgroups: Series | NDArray | list[Series | NDArray], + top_fraction: float | None = None, + fraction_range: tuple[float, float] | None = None, + ) -> pd.DataFrame: + """ + Analyze model performance across subgroups. + + This method evaluates how well the model performs for different customer + segments or cohorts by computing actual uplift within each subgroup. + + Parameters + ---------- + tau : array-like, shape (n_samples, n_treatments) + Predicted uplift for each treatment vs control. + y : Series + Actual outcomes (e.g., revenue, conversion). + t : Series + Actual treatment assignments. + subgroups : Series, array-like, or list of Series/arrays + Grouping variable(s) defining subgroups. Pass a single Series + (e.g., ``X["age_bucket"]``) or a list of Series + (e.g., ``[X["age_bucket"], X["state"]]``) for cross-tabulation. + top_fraction : float, optional + If provided, only analyze individuals in the top X% by predicted uplift. + fraction_range : tuple[float, float], optional + Custom range of percentiles, e.g., (0.05, 0.15) for 5th to 15th percentile. + Overrides top_fraction if provided. + + Returns + ------- + pd.DataFrame + DataFrame with the grouping column(s) from ``subgroups`` plus + columns ``count``, ``mean_pred_uplift``, + ``mean_actual_uplift_best``, and + ``mean_actual_uplift_treatment_`` for each treatment. + + Examples + -------- + >>> evaluator = UpliftExploreEvaluator("Control", "Treat A", "Treat B") + >>> tau = model.predict(X) + >>> # Analyze by age bucket + >>> result = evaluator.analyze_subgroup_performance(tau, y, t, X["age_bucket"]) + + >>> # Analyze top decile only + >>> result = evaluator.analyze_subgroup_performance( + ... tau, y, t, X["age_bucket"], top_fraction=0.1 + ... ) + + >>> # Multiple grouping variables + >>> result = evaluator.analyze_subgroup_performance( + ... tau, y, t, [X["age_bucket"], X["state"]] + ... ) + + Notes + ----- + Actual uplift is computed as the difference in mean outcomes between + treatment and control groups within each subgroup (ATE estimation). + """ + tau = np.asarray(tau) + y = pd.Series(y).reset_index(drop=True) + t = pd.Series(t).reset_index(drop=True) + + # Handle single or multiple subgroup columns + if not isinstance(subgroups, list): + subgroups = [subgroups] + + # Convert to Series and reset index + subgroup_series = [] + for i, sg_item in enumerate(subgroups): + if isinstance(sg_item, pd.Series): + sg_reset = sg_item.reset_index(drop=True) + subgroup_series.append( + sg_reset.rename(f"subgroup_{i}" if sg_reset.name is None else sg_reset.name) + ) + else: + subgroup_series.append(pd.Series(sg_item, name=f"subgroup_{i}")) + + # Apply slicing if requested + if top_fraction is not None or fraction_range is not None: + best_uplift = np.max(tau, axis=1) if tau.ndim > 1 else tau.flatten() + indices = self._get_slice_indices(best_uplift, top_fraction or 0.1, fraction_range) + tau = tau[indices] + y = y.iloc[indices].reset_index(drop=True) + t = t.iloc[indices].reset_index(drop=True) + subgroup_series = [sg.iloc[indices].reset_index(drop=True) for sg in subgroup_series] + + # Compute predicted uplift (best across treatments) + if tau.ndim > 1 and tau.shape[1] > 1: + pred_uplift_best = compute_best_uplift_among_treatments(tau) + else: + pred_uplift_best = tau.flatten() + + # Build DataFrame + df = pd.DataFrame({"y": y, "t": t, "pred_uplift_best": pred_uplift_best}) + for sg in subgroup_series: + df[sg.name] = sg.values + + # Add treatment-specific predicted uplifts + if tau.ndim > 1: + for i in range(tau.shape[1]): + df[f"pred_uplift_treatment_{i}"] = tau[:, i] + + # Group by subgroups + groupby_cols = [sg.name for sg in subgroup_series] + + results = [] + + for group_key, group_df in df.groupby(groupby_cols, observed=True): + # Ensure group_key is iterable + group_vals_tuple = group_key if isinstance(group_key, tuple) else (group_key,) + + row = dict(zip(groupby_cols, group_vals_tuple)) + row["count"] = len(group_df) + row["mean_pred_uplift"] = group_df["pred_uplift_best"].mean() + + # Compute actual uplift for best treatment + mean_y_control = group_df[group_df["t"] == self.control_name]["y"].mean() + mean_y_treated = group_df[group_df["t"] != self.control_name]["y"].mean() + row["mean_actual_uplift_best"] = mean_y_treated - mean_y_control + + # Compute actual uplift for each treatment + if tau.ndim > 1: + for i, treatment in enumerate(self.treatment_names): + mean_y_treatment = group_df[group_df["t"] == treatment]["y"].mean() + row[f"mean_actual_uplift_treatment_{i}"] = mean_y_treatment - mean_y_control + + results.append(row) + + return pd.DataFrame(results) + + def analyze_disagreements( # noqa: C901, PLR0912, PLR0915 + self, + tau1: NDArray, + tau2: NDArray, + X: pd.DataFrame, + covariates: list[str], + threshold1: float = 0.0, + threshold2: float = 0.0, + categorical_covariates: list[str] | None = None, + detailed: bool = False, + top_fraction: float | None = None, + fraction_range: tuple[float, float] | None = None, + ) -> dict[str, float | pd.DataFrame]: + """ + Analyze disagreements between two models' treatment recommendations. + + When two models recommend different treatments for the same customers, + this function identifies those disagreements and describes the characteristics + of customers where models disagree. + + Parameters + ---------- + tau1 : array-like, shape (n_samples, n_treatments) + Predicted uplift from model 1. + tau2 : array-like, shape (n_samples, n_treatments) + Predicted uplift from model 2. + X : pd.DataFrame + DataFrame containing customer features/covariates. + covariates : list[str] + List of column names from X to describe (e.g., ["age", "revenue", "state"]). + Include both continuous and categorical variables here. + threshold1 : float, default=0.0 + Rollout threshold for model 1. Recommend treatment if uplift > threshold1. + threshold2 : float, default=0.0 + Rollout threshold for model 2. Recommend treatment if uplift > threshold2. + categorical_covariates : list[str], optional + List of covariate names that are categorical (must also be in covariates list). + These will be one-hot encoded and proportions shown for each category. + E.g., ["state", "filing_status"]. + Warning: If any categorical has > 5 unique values, a warning will be issued. + detailed : bool, default=False + If False, return simple Agree vs Disagree breakdown. + If True, return detailed breakdown by (model1_rec, model2_rec) pairs. + top_fraction : float, optional + If provided, only analyze disagreements among top X% by model 1's predictions. + fraction_range : tuple[float, float], optional + Custom percentile range (e.g., (0.05, 0.15)) based on model 1's predictions. + Overrides top_fraction if provided. + + Returns + ------- + dict + Dictionary with ``"agreement_rate"`` (float, proportion of + customers where models agree) and ``"results"`` (DataFrame with + disagreement analysis). + + When ``detailed=False`` the DataFrame contains columns + ``agreement_status``, ``count``, ``pct_of_total``, plus columns + for each continuous covariate (averages) and one-hot columns for + categorical covariates (proportions). + + When ``detailed=True`` the DataFrame contains columns + ``model1_rec``, ``model2_rec``, ``count``, ``pct_of_total``, + plus the same covariate columns. + + Examples + -------- + >>> evaluator = UpliftExploreEvaluator("Control", "Treat A", "Treat B") + >>> result = evaluator.analyze_disagreements( + ... tau1, tau2, X, + ... covariates=["age", "revenue", "state"], + ... categorical_covariates=["state"], + ... threshold1=0.0, + ... threshold2=0.0, + ... detailed=True + ... ) + >>> print(f"Agreement rate: {result['agreement_rate']:.2%}") + >>> print(result['results']) + + >>> # Focus on top 20% customers only + >>> result = evaluator.analyze_disagreements( + ... tau1, tau2, X, + ... covariates=["age", "revenue"], + ... top_fraction=0.2 + ... ) + + Notes + ----- + - Slicing (top_fraction/fraction_range) is based on model 1's predictions + - Disagreement occurs when model1_rec != model2_rec + - Useful for understanding which customer segments models disagree about + - Categorical variables are one-hot encoded and proportions shown + - For continuous variables, means are shown + """ + tau1 = np.asarray(tau1) + tau2 = np.asarray(tau2) + X = X.reset_index(drop=True) + + if categorical_covariates is None: + categorical_covariates = [] + + # Validate categorical_covariates are in covariates + for cat_cov in categorical_covariates: + if cat_cov not in covariates: + msg = f"Categorical covariate '{cat_cov}' must be in covariates list." + raise ValueError(msg) + + # Check for high-cardinality categoricals and issue warnings + import warnings + + max_categories = 5 + for cat_cov in categorical_covariates: + n_unique = X[cat_cov].nunique() + if n_unique > max_categories: + warnings.warn( + f"Categorical variable '{cat_cov}' has {n_unique} categories (> 5). " + "Consider grouping categories or using a different variable " + "for clearer analysis.", + stacklevel=2, + ) + + # Separate continuous and categorical covariates + continuous_covariates = [cov for cov in covariates if cov not in categorical_covariates] + + # Separate continuous and categorical covariates + continuous_covariates = [cov for cov in covariates if cov not in categorical_covariates] + + # Apply slicing if requested (based on model 1) + if top_fraction is not None or fraction_range is not None: + best_uplift1 = np.max(tau1, axis=1) if tau1.ndim > 1 else tau1.flatten() + indices = self._get_slice_indices(best_uplift1, top_fraction or 0.1, fraction_range) + tau1 = tau1[indices] + tau2 = tau2[indices] + X = X.iloc[indices].reset_index(drop=True) + + # Get recommendations from both models + recs1 = self._get_recommended_policy(tau1, threshold1) + recs2 = self._get_recommended_policy(tau2, threshold2) + + # Calculate agreement + agrees = recs1 == recs2 + agreement_rate = agrees.mean() + + # Build DataFrame with all data + df = X[covariates].copy() + df["model1_rec"] = recs1.values + df["model2_rec"] = recs2.values + df["agrees"] = agrees.values + + # One-hot encode categorical variables + categorical_dummies = {} + for cat_cov in categorical_covariates: + dummies = pd.get_dummies(df[cat_cov], prefix=cat_cov) + categorical_dummies[cat_cov] = dummies + df = pd.concat([df, dummies], axis=1) + + n_total = len(df) + + if not detailed: + # Simple breakdown: Agree vs Disagree + results = [] + + for agreement_status in ["Agree", "Disagree"]: + is_group = df["agrees"] == (agreement_status == "Agree") + group_df = df[is_group] + + row = {"agreement_status": agreement_status} + row["count"] = len(group_df) + row["pct_of_total"] = len(group_df) / n_total + + # Calculate mean for continuous covariates + for cov in continuous_covariates: + row[cov] = group_df[cov].mean() + + # Calculate proportions for categorical covariates + for cat_cov in categorical_covariates: + for col in categorical_dummies[cat_cov].columns: + row[col] = group_df[col].mean() + + results.append(row) + + results_df = pd.DataFrame(results) + + else: + # Detailed breakdown by (model1_rec, model2_rec) pairs + results = [] + + for (rec1, rec2), group_df in df.groupby(["model1_rec", "model2_rec"], observed=True): + row = { + "model1_rec": rec1, + "model2_rec": rec2, + "count": len(group_df), + "pct_of_total": len(group_df) / n_total, + } + + # Calculate mean for continuous covariates + for cov in continuous_covariates: + row[cov] = group_df[cov].mean() + + # Calculate proportions for categorical covariates + for cat_cov in categorical_covariates: + for col in categorical_dummies[cat_cov].columns: + row[col] = group_df[col].mean() + + results.append(row) + + results_df = pd.DataFrame(results) + # Sort by count descending + results_df = results_df.sort_values("count", ascending=False).reset_index(drop=True) + + return {"agreement_rate": agreement_rate, "results": results_df} + + def validate_uplift_predictions( # noqa: PLR0915 + self, + tau: NDArray, + y: Series, + t: Series, + treatment_idx: int, + n_bins: int | None = None, + plot: bool = False, + figsize: tuple[int, int] = (10, 6), + ) -> pd.DataFrame: + """ + Validate uplift model predictions against actual outcomes (calibration check). + + This function checks if the model's predicted uplift values are calibrated + to actual observed uplift. Customers are binned by their predicted uplift, + and within each bin, predicted uplift is compared to actual uplift. + + Parameters + ---------- + tau : array-like, shape (n_samples,) or (n_samples, n_treatments) + Predicted uplift for each treatment vs control. + For multi-treatment models, must specify which treatment to validate. + y : Series + Actual outcomes (e.g., revenue, conversion). + t : Series + Actual treatment assignments. + treatment_idx : int + Index of the treatment to validate (0-indexed). + For single treatment: use 0. + For multi-treatment: specify which treatment column to validate (0, 1, 2, ...). + n_bins : int, optional + Number of bins to create. If None, uses self.n_bins from evaluator. + plot : bool, default=False + If True, creates a calibration plot showing predicted vs actual uplift. + figsize : tuple[int, int], default=(10, 6) + Figure size for the plot (if plot=True). + + Returns + ------- + pd.DataFrame + DataFrame with columns ``bin``, ``count``, ``pred_uplift_min``, + ``pred_uplift_max``, ``mean_pred_uplift``, ``mean_actual_uplift``, + and ``calibration_error`` (actual minus predicted). + + Examples + -------- + >>> evaluator = UpliftExploreEvaluator("Control", "Treatment A", n_bins=10) + >>> # Single treatment validation + >>> result = evaluator.validate_uplift_predictions( + ... tau, y, t, treatment_idx=0, plot=True + ... ) + + >>> # Multi-treatment: validate Treatment B (index 1) + >>> evaluator = UpliftExploreEvaluator("Control", "Treat A", "Treat B") + >>> result = evaluator.validate_uplift_predictions( + ... tau, y, t, treatment_idx=1, n_bins=20 + ... ) + + Notes + ----- + - For multi-treatment models, this validates ONE treatment at a time. + It does NOT validate "best" uplift across treatments, as that would + be methodologically problematic due to selection bias. + - Actual uplift is computed as: mean(y | t=treatment) - mean(y | t=control) + using only observations where t equals the specified treatment or control. + - Calibration error = 0 indicates perfect calibration + - Calibration error > 0 indicates under-prediction (actual > predicted) + - Calibration error < 0 indicates over-prediction (predicted > actual) + - The calibration plot shows a diagonal line (y=x) for perfect calibration + """ + tau = np.asarray(tau) + y = pd.Series(y).reset_index(drop=True) + t = pd.Series(t).reset_index(drop=True) + + if n_bins is None: + n_bins = self.n_bins + + # Handle 1D or 2D tau + if tau.ndim == 1: + if treatment_idx != 0: + msg = ( + f"tau is 1D (single treatment), but treatment_idx={treatment_idx}. " + "Use treatment_idx=0." + ) + raise ValueError(msg) + pred_uplift = tau + treatment_name = self.treatment_names[0] + else: + if treatment_idx < 0 or treatment_idx >= tau.shape[1]: + msg = ( + f"treatment_idx={treatment_idx} is out of bounds. " + f"tau has {tau.shape[1]} treatments (valid indices: 0-{tau.shape[1]-1})." + ) + raise ValueError(msg) + pred_uplift = tau[:, treatment_idx] + treatment_name = self.treatment_names[treatment_idx] + + # Create bins based on predicted uplift + df = pd.DataFrame({"pred_uplift": pred_uplift, "y": y, "t": t}) + df["bin"] = assign_bins(df["pred_uplift"], n_bins) + + # Calculate actual uplift within each bin + results = [] + for bin_num in range(1, n_bins + 1): + bin_df = df[df["bin"] == bin_num] + + if len(bin_df) == 0: + continue + + # Calculate actual uplift for this treatment + control_mask = bin_df["t"] == self.control_name + treatment_mask = bin_df["t"] == treatment_name + + mean_y_control = bin_df.loc[control_mask, "y"].mean() + mean_y_treatment = bin_df.loc[treatment_mask, "y"].mean() + + # Skip bin if we don't have both control and treatment observations + if pd.isna(mean_y_control) or pd.isna(mean_y_treatment): + continue + + actual_uplift = mean_y_treatment - mean_y_control + + row = { + "bin": bin_num, + "count": len(bin_df), + "pred_uplift_min": bin_df["pred_uplift"].min(), + "pred_uplift_max": bin_df["pred_uplift"].max(), + "mean_pred_uplift": bin_df["pred_uplift"].mean(), + "mean_actual_uplift": actual_uplift, + "calibration_error": actual_uplift - bin_df["pred_uplift"].mean(), + } + results.append(row) + + results_df = pd.DataFrame(results) + + # Create calibration plot if requested + if plot: + import matplotlib.pyplot as plt + + _fig, ax = plt.subplots(figsize=figsize) + + # Plot points + ax.scatter( + results_df["mean_pred_uplift"], + results_df["mean_actual_uplift"], + s=100, + alpha=0.6, + edgecolors="black", + linewidth=1.5, + ) + + # Plot perfect calibration line (y=x) + min_val = min( + results_df["mean_pred_uplift"].min(), results_df["mean_actual_uplift"].min() + ) + max_val = max( + results_df["mean_pred_uplift"].max(), results_df["mean_actual_uplift"].max() + ) + ax.plot( + [min_val, max_val], + [min_val, max_val], + "r--", + linewidth=2, + label="Perfect Calibration", + ) + + ax.set_xlabel("Mean Predicted Uplift", fontsize=12) + ax.set_ylabel("Mean Actual Uplift", fontsize=12) + ax.set_title(f"Calibration Plot: {treatment_name} vs {self.control_name}", fontsize=14) + ax.legend() + ax.grid(True, alpha=0.3) + + plt.tight_layout() + plt.show() + + return results_df diff --git a/multilift/uplift/eval/utils.py b/multilift/uplift/eval/utils.py new file mode 100644 index 0000000..41d491c --- /dev/null +++ b/multilift/uplift/eval/utils.py @@ -0,0 +1,526 @@ +import numpy as np +import pandas as pd +from matplotlib import pyplot as plt +from scipy.stats import sem + +from multilift.typing import NDArray, PandasDF, Series + +# np.trapz was removed in NumPy 2.0, replaced by np.trapezoid +_trapz = np.trapezoid if hasattr(np, "trapezoid") else np.trapz + + +def compute_best_uplift(tau: NDArray) -> NDArray: + """ + Compute the best positive uplift among all recipes (including control). + + Parameters + ---------- + tau : array-like, shape (n, m) + Predicted uplift (CATE) for each treatment vs control. + + Returns + ------- + best_uplift : array-like + Best positive uplift (0 if both negative). + """ + return np.maximum(0, np.max(tau, axis=1)) + + +def compute_best_uplift_among_treatments(tau: NDArray) -> NDArray: + """ + Compute the best positive uplift from two treatment arms. + + Parameters + ---------- + tau : array-like, shape (n, m) + Predicted uplift (CATE) for each treatment vs control. + + Returns + ------- + best_uplift : array-like + Best uplift among all treatments (negative if best treatment has negative predicted uplift). + """ + return np.max(tau, axis=1) + + +def compute_ipw(arm_assignments: NDArray, normalize: bool = True) -> NDArray: + """ + Compute inverse propensity weights based on arm assignment proportions. + + Parameters + ---------- + arm_assignments : array-like + Actual arm assignments (0=control, 1=B, 2=C). + + normalize: bool + Whether to normalize the weights to sum to the number of observations. + + Returns + ------- + weights : array-like + Inverse propensity weights. + """ + arm_series = pd.Series(arm_assignments) + prop = arm_series.value_counts(normalize=True).to_dict() + raw_weights = arm_series.map(lambda a: 1.0 / prop[a]).to_numpy() + + if normalize: + norm_factor = len(arm_series) / raw_weights.sum() + return raw_weights * norm_factor + return raw_weights + + +def compute_qini_auc(uplift_curve: NDArray, total_uplift: float) -> float: + """ + Compute area under the Qini curve. + + Parameters + ---------- + uplift_curve : array-like + Cumulative uplift values. + total_uplift : float + Total uplift across the full experiment. + + Returns + ------- + auc : float + Area under the Qini curve. + """ + n = len(uplift_curve) + pop_frac = np.arange(1, n + 1) / n + baseline = pop_frac * total_uplift + qini = uplift_curve - baseline + return _trapz(qini, pop_frac) + + +def compute_pop_frac(data: NDArray | PandasDF) -> NDArray: + """ + Compute population fraction for each observation. + + Parameters + ---------- + data : DataFrame or array-like + + Returns + ------- + pop_frac : array-like + Population fraction for each observation. + """ + n = len(data) + return np.arange(1, n + 1) / n + + +def compute_qini( + tau: NDArray, t: Series, y: Series, control_name: str, *treatment_names: str +) -> tuple[float, PandasDF]: + """ + Calculate Qini AUC for multi-arm uplift predictions. + + Parameters + ---------- + tau : array-like, shape (n, m) + Predicted uplift (CATE) for each treatment vs control. + t : array-like, shape (n,) + Actual arm assignments (control_name, treatment_names[0], treatment_names[1], ...). + y : array-like, shape (n,) + Observed outcome (e.g. revenue). + control_name : str + Name of the control arm. + treatment_names : str + Names of the treatment arms. + + Returns + ------- + qini_auc : float + Area under the Qini curve. + + data : DataFrame + A DataFrame with pop_frac, uplift, qini columns. + """ + num_treatments = tau.shape[1] + if len(treatment_names) != num_treatments: + raise ValueError( + f"Number of treatment names ({len(treatment_names)}) " + f"must match number of treatments ({num_treatments})." + ) + + df = pd.DataFrame({"arm": t, "y": y}) + + # Compute policy decision + df["best_uplift"] = compute_best_uplift(tau) + best_treatment_idx = np.argmax(tau, axis=1) + treatment_names_arr = np.array(treatment_names) + best_treatment_names = treatment_names_arr[best_treatment_idx] + df["policy_arm"] = np.where(df["best_uplift"] == 0, control_name, best_treatment_names) + + # Compute inverse propensity weights + df["wgt"] = compute_ipw(df["arm"], normalize=True) + df["y_w"] = df["y"] * df["wgt"] + + # Sort by predicted uplift (descending) + df = df.sort_values("best_uplift", ascending=False).reset_index(drop=True) + + # Compute cumulative uplift curve + ctrl_cum = (df["y_w"] * (df["arm"] == control_name)).cumsum() + + # Sum cumulative outcomes across all treatments + treated_cum = pd.Series(np.zeros(len(df)), index=df.index) + for treatment_name in treatment_names: + treated_cum += (df["y_w"] * (df["arm"] == treatment_name)).cumsum() + + uplift_curve = treated_cum - ctrl_cum + + pop_frac = compute_pop_frac(df) + + total_uplift = ( + df.loc[df["arm"] != control_name, "y_w"].sum() + - df.loc[df["arm"] == control_name, "y_w"].sum() + ) + random_targeting = pop_frac * total_uplift + + qini = uplift_curve - random_targeting + qini_auc = _trapz(qini, pop_frac) + + return qini_auc, pd.DataFrame( + { + "pop_frac": pop_frac, + "uplift": uplift_curve, + "qini": qini, + "random_targeting": random_targeting, + } + ) + + +def plot_uplift_bins( + t: Series, + y: Series, + tau: Series, + control_name: str, + *treatment_names: str, + ax: plt.Axes = None, + n_bins: int = 10, + name: str = "Uplift Bins", + figsize: tuple[int] = (10, 6), +) -> plt.Axes: + """ + Plot the uplift bins. + + Parameters + ---------- + t: Series + The treatment Series. + y: Series + The target Series. + tau: Series + The uplift Series. + control_name: str + The name of the control treatment. + treatment_names: str + The names of the treatment treatments. + ax: plt.Axes + The axes of the plot. + n_bins: int + The number of bins. + name: str + The name of the plot. + figsize: tuple[int] + The size of the figure. + + Returns + ------- + plt.Axes + The axes of the plot. + """ + bin_df = pd.DataFrame({"t": t, "y": y, "tau": tau}) + bin_df = bin_df.sort_values("tau", ascending=False).reset_index(drop=True) + bin_df["t"] = bin_df["t"].map( + {control_name: "control"} | {v: "treatment" for v in treatment_names} + ) + bin_df["bin"] = pd.qcut(bin_df.index, q=n_bins, labels=range(1, n_bins + 1)) + + grouped = ( + bin_df.groupby(["bin", "t"], observed=True)["y"] + .agg(mean="mean", sem=lambda x: sem(x, nan_policy="omit"), count="count") + .reset_index() + ) + bin_df = grouped.pivot(index="bin", columns="t", values=["mean", "sem"]).sort_index() + bin_df[("mean", "actual_uplift")] = bin_df["mean"]["treatment"] - bin_df["mean"]["control"] + bin_df[("sem", "actual_uplift")] = np.sqrt( + bin_df["sem"]["treatment"] ** 2 + bin_df["sem"]["control"] ** 2 + ) + + if ax is None: + _fig, ax = plt.subplots(figsize=figsize) + else: + pass + + colors = ["red" if x < 0 else "green" for x in bin_df["mean"]["actual_uplift"]] + ax.bar( + bin_df.index.astype(str), + bin_df["mean"]["actual_uplift"], + yerr=bin_df["sem"]["actual_uplift"], + capsize=4, + color=colors, + ) + ax.axhline(0, color="black", linestyle="--", linewidth=1, alpha=1) + ax.set_xlabel("Bin") + ax.set_ylabel("Actual Uplift Mean ($)") + ax.set_title(name) + ax.grid(True, alpha=0.3) + plt.tight_layout() + return ax + + +def plot_qini_curve( + qini_df: PandasDF, + title: str = "", + figsize: tuple[int] = (10, 6), + show: bool = True, + save: bool = False, + path: str = "qini_curve.png", +) -> plt.Axes: + """ + Plot the Qini curve. + + Parameters + ---------- + qini_df : DataFrame + A DataFrame with pop_frac, uplift, qini columns. + title : str, optional + Title for the entire figure (centered above both subplots). + figsize : tuple[int], optional + The size of the figure (default is (10, 6)). + show : bool, optional + Whether to show the plot (default is True). + save : bool, optional + Whether to save the plot (default is False). + path : str, optional + The path to save the plot (default is "qini_curve.png"). + + Returns + ------- + plt.Axes + The axes of the plot. + """ + plt.style.use("default") + fig, axs = plt.subplots(1, 2, figsize=figsize) + + q_auc = _trapz(qini_df["qini"], qini_df["pop_frac"]) + + # Left subplot: Uplift Curve + axs[0].plot(qini_df["pop_frac"], qini_df["uplift"], label="Uplift", linewidth=2) + axs[0].plot( + qini_df["pop_frac"], qini_df["random_targeting"], "k--", label="Random Targeting", alpha=0.5 + ) + axs[0].set_xlabel("Population Fraction") + axs[0].set_ylabel("Cumulative Uplift") + axs[0].set_title("Uplift Curve") + axs[0].legend() + axs[0].grid(True, alpha=0.3) + + # Right subplot: Qini Curve + axs[1].plot(qini_df["pop_frac"], qini_df["qini"], label="Qini", linewidth=2) + axs[1].fill_between(qini_df["pop_frac"], 0, qini_df["qini"], alpha=0.2) + axs[1].axhline(y=0, color="k", linestyle="--", alpha=0.6, label="Random Targeting") + axs[1].set_xlabel("Population Fraction") + axs[1].set_ylabel("Qini (Above Random)") + axs[1].set_title("Qini Curve") + axs[1].legend() + axs[1].grid(True, alpha=0.3) + axs[1].text( + 0.05, + 0.95, + f"Qini AUC: {q_auc:.0f}", + transform=axs[1].transAxes, + bbox=dict(boxstyle="round,pad=0.3", facecolor="white", alpha=0.8), + ) + + # Add centered title above both subplots + if title: + fig.suptitle(title, fontsize=14, fontweight="bold", y=1.02) + + # Adjust layout to prevent overlap + plt.tight_layout() + + if save: + plt.savefig(path, bbox_inches="tight") + + if show: + plt.show() + + return axs + + +def assign_bins(scores: pd.Series, n_bins: int) -> pd.Series: + """ + Map numeric scores to 1...n bins by rank. + + Avoids qcut duplicate-edge errors. Uses a stable tie-break + (method="first"). NaNs are kept but excluded from the rank. + Converts percentile rank to bins via ceil(pct * n_bins). + High scores map to bin 1 when descending=True. + + Example + ---------- + n_bins=2 + scores = [0.9, 0.9, 0.9, 0.7] + pct = [0.25, 0.50, 0.75, 1.00] → bins = [1, 1, 2, 2] + Equal 0.9s split across bins because their ranks straddle the 50% boundary. + + Parameters + ---------- + scores : pd.Series + Numeric scores to bin. + n_bins : int + Number of bins. + + Returns + ------- + pd.Series + Binned scores. + """ + ranks = scores.rank(method="first", ascending=False, na_option="keep", pct=True) + bins = np.ceil(ranks * n_bins).astype("Int64") # 1..n, preserves NaN + return bins.clip(1, n_bins) + + +def _add_footnote_to_plot( + fig, + ax, + text: str, + fontsize: int = 9, + gap_pts: int = 6, + color: str = "0.35", + extra_reserved_frac: float = 0.0, +): + """Add a wrapped footnote below the x-axis, reserving extra bottom space if requested.""" + # Let Matplotlib arrange layout first + plt.tight_layout() + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + _width_px, height_px = fig.canvas.get_width_height() + pos = ax.get_position() + + # Create temporary axes to measure text height + temp_ax = fig.add_axes([pos.x0, 0, pos.width, 1e-3]) + temp_ax.set_axis_off() + temp_text = temp_ax.text( + 0, + 1, + text, + ha="left", + va="top", + fontsize=fontsize, + wrap=True, + transform=temp_ax.transAxes, + color=color, + ) + fig.canvas.draw() + note_height_frac = temp_text.get_window_extent(renderer=renderer).height / height_px + temp_ax.remove() + + # Calculate gap and adjust bottom margin (including extra reserved space) + gap_frac = ((gap_pts / 72.0) * fig.dpi) / height_px + new_bottom = pos.y0 + note_height_frac + gap_frac + extra_reserved_frac + fig.subplots_adjust(bottom=new_bottom) + fig.canvas.draw() + + # Create final footnote axes above the reserved strip + pos = ax.get_position() # Get updated position + note_ax = fig.add_axes([pos.x0, extra_reserved_frac, pos.width, note_height_frac]) + note_ax.set_axis_off() + note_ax.text( + 0, + 0, + text, + ha="left", + va="bottom", + fontsize=fontsize, + wrap=True, + transform=note_ax.transAxes, + color=color, + ) + return note_ax, note_height_frac + + +def compute_binned_uplift( + t: Series, + y: Series, + tau: Series, + control_name: str | None = None, + treatment_name: str | None = None, + n_bins: int = 10, +) -> tuple[pd.DataFrame, pd.Series]: + """ + Compute uplift by bin for a single-treatment uplift experiment. + + If control_name and treatment_name are provided, the function also computes + the uplift for each bin. + + Parameters + ---------- + t : Series + Treatment assignment series (0=control, 1=treatment1, 2=treatment2, etc.) + y : Series + Outcome series (e.g., revenue, conversion) + tau : Series + Predicted uplift (CATE) for the treatment vs control + + control_name : str, optional + Name/label for the control group + + treatment_name : str, optional + Name/label for the treatment group + + n_bins : int, default=10 + Number of bins to create for analysis + + Returns + ------- + tuple + A tuple containing: + - A DataFrame with the mean outcome by bin and treatment + - A Series with the bin assignment for each observation + """ + # check if only a single treatment is provided + if tau.ndim > 1 and tau.shape[1] > 1: + raise ValueError("Only a single treatment can be provided") + + df = pd.DataFrame({"t": t, "y": y, "tau": tau}).copy() + df["bin"] = assign_bins(df["tau"], n_bins) + + grouped = df.groupby(["bin", "t"], observed=True)["y"].agg(mean="mean").reset_index() + + agg_df = grouped.pivot(index="bin", columns="t", values="mean").sort_index() + if control_name and treatment_name: + agg_df["uplift"] = agg_df[treatment_name] - agg_df[control_name] + + return agg_df, df["bin"] + + +def _get_significance_stars(p_value: float) -> str: + """ + Convert p-value to significance stars. + + Parameters + ---------- + p_value : float + The p-value from a statistical test + + Returns + ------- + str + Significance stars: *** for p<0.01, ** for p<0.05, * for p<0.1, empty string otherwise + """ + # Define significance thresholds + P_VALUE_HIGH_SIGNIFICANCE = 0.01 + P_VALUE_MEDIUM_SIGNIFICANCE = 0.05 + P_VALUE_LOW_SIGNIFICANCE = 0.1 + + if p_value < P_VALUE_HIGH_SIGNIFICANCE: + return "***" + if p_value < P_VALUE_MEDIUM_SIGNIFICANCE: + return "**" + if p_value < P_VALUE_LOW_SIGNIFICANCE: + return "*" + return "" diff --git a/multilift/uplift/meta/__init__.py b/multilift/uplift/meta/__init__.py new file mode 100644 index 0000000..79a68ab --- /dev/null +++ b/multilift/uplift/meta/__init__.py @@ -0,0 +1,13 @@ +"""Meta-learner implementations for uplift modeling.""" + +from multilift.uplift.meta._slearner import SLearnerRegressor +from multilift.uplift.meta._slearner_classifier import SLearnerClassifier +from multilift.uplift.meta._tlearner import TLearnerRegressor +from multilift.uplift.meta._tlearner_classifier import TLearnerClassifier + +__all__ = [ + "SLearnerClassifier", + "SLearnerRegressor", + "TLearnerClassifier", + "TLearnerRegressor", +] diff --git a/multilift/uplift/meta/_slearner.py b/multilift/uplift/meta/_slearner.py new file mode 100644 index 0000000..bb7aaaf --- /dev/null +++ b/multilift/uplift/meta/_slearner.py @@ -0,0 +1,247 @@ +"""S-Learner implementation for uplift regression.""" + +import logging +from copy import deepcopy +from pathlib import Path +from typing import Any + +import matplotlib.pyplot as plt +import numpy as np +import shap +from sklearn.base import BaseEstimator + +from multilift.exceptions import ModelNotFittedError +from multilift.typing import NDArray, PandasDF +from multilift.uplift.meta._tlearner import _to_numpy + +_logger = logging.getLogger(__name__) + + +class SLearnerRegressor: + """ + S-Learner for uplift regression. + + Trains one model per treatment group on ``[w, X]`` where ``w`` is a + binary indicator (1 = treatment, 0 = control). Uplift is estimated as + ``model([1, X]) - model([0, X])``. + + Implements the standard S-Learner formulation (Künzel et al., 2019), + adding direct (non-surrogate) SHAP support and save/show control for + plots. + + Parameters + ---------- + control_name : str + Name of the control group. + learner : BaseEstimator + Learner template, deep-copied for each treatment group. + + Examples + -------- + >>> from lightgbm import LGBMRegressor + >>> model = SLearnerRegressor( + ... control_name="control", + ... learner=LGBMRegressor(n_estimators=200), + ... ) + """ + + def __init__(self, control_name: str, learner: BaseEstimator) -> None: + self.control_name = control_name + self._learner = learner + + # Populated during fit + self.t_groups: np.ndarray | None = None + self._classes: dict[str, int] = {} + self.models: dict[str, BaseEstimator] = {} + + @property + def is_fitted(self) -> bool: + """Whether the model has been fitted.""" + return self.t_groups is not None and len(self.models) > 0 + + # ------------------------------------------------------------------ + # Core API + # ------------------------------------------------------------------ + + def fit(self, X: NDArray, treatment: NDArray, target: NDArray) -> "SLearnerRegressor": + """ + Fit one model per treatment group on ``[w, X]``. + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix. + treatment : NDArray of shape (n_samples,) + Treatment assignment vector. + target : NDArray of shape (n_samples,) + Outcome vector. + + Returns + ------- + self + """ + X, treatment, target = _to_numpy(X, treatment, target) + + self.t_groups = np.sort(np.unique(treatment[treatment != self.control_name])) + self._classes = {group: i for i, group in enumerate(self.t_groups)} + self.models = {} + + for group in self.t_groups: + mask = (treatment == group) | (treatment == self.control_name) + treatment_filt = treatment[mask] + X_filt = X[mask] + y_filt = target[mask] + + w = (treatment_filt == group).astype(int) + X_new = np.hstack((w.reshape((-1, 1)), X_filt)) + + model = deepcopy(self._learner) + model.fit(X_new, y_filt) + self.models[group] = model + + _logger.info("Fitted S-learner model '%s' on %d observations.", group, mask.sum()) + + return self + + def predict(self, X: NDArray, **_: Any) -> NDArray: + """ + Predict treatment effects (uplift). + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix. + + Returns + ------- + NDArray of shape (n_samples, n_treatments) + Predicted uplift for each treatment group. + Column order matches ``self.t_groups``. + """ + if not self.is_fitted: + raise ModelNotFittedError("Model is not fitted. Call fit() first.") + + (X,) = _to_numpy(X) + + te = np.empty((X.shape[0], len(self.t_groups))) + for i, group in enumerate(self.t_groups): + model = self.models[group] + X_control = np.hstack((np.zeros((X.shape[0], 1)), X)) + yhat_c = model.predict(X_control) + + X_treat = np.hstack((np.ones((X.shape[0], 1)), X)) + yhat_t = model.predict(X_treat) + + te[:, i] = yhat_t - yhat_c + + return te + + # ------------------------------------------------------------------ + # SHAP support + # ------------------------------------------------------------------ + + def get_shap_values(self, X: NDArray | PandasDF, **_: Any) -> dict[str, NDArray]: + """ + Compute SHAP values for uplift directly from fitted models. + + For each treatment model (trained on ``[w, X]``), computes SHAP + values with treatment=1 and treatment=0, then subtracts. Only the + feature columns are returned (the treatment indicator is dropped). + + This is exact for tree-based learners and avoids the surrogate + model approximation used by causalml. + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix (without the treatment indicator). + + Returns + ------- + dict[str, NDArray] + Mapping of treatment group name to SHAP value arrays of + shape ``(n_samples, n_features)``. + """ + if not self.is_fitted: + raise ModelNotFittedError("Model is not fitted. Call fit() first.") + + (X,) = _to_numpy(X) + + shap_dict: dict[str, NDArray] = {} + for group in self.t_groups: + model = self.models[group] + explainer = shap.TreeExplainer(model) + + X_treat = np.hstack((np.ones((X.shape[0], 1)), X)) + shap_t = explainer.shap_values(X_treat) + + X_control = np.hstack((np.zeros((X.shape[0], 1)), X)) + shap_c = explainer.shap_values(X_control) + + # Drop column 0 (treatment indicator), keep only feature columns + shap_dict[group] = shap_t[:, 1:] - shap_c[:, 1:] + + return shap_dict + + def plot_shap_values( + self, + X: NDArray | PandasDF, + features: list[str] | None = None, + shap_dict: dict[str, NDArray] | None = None, + max_display: int = 15, + show: bool = True, + save_dir: str | Path | None = None, + **kwargs: Any, + ) -> None: + """ + Plot SHAP summary plots for uplift per treatment group. + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix (used for coloring the summary plot). + features : list[str], optional + Feature names for display. + shap_dict : dict[str, NDArray], optional + Pre-computed SHAP values from ``get_shap_values``. + If None, they are computed automatically. + max_display : int, optional + Maximum number of features to display. + show : bool, optional + Whether to display the plot. + save_dir : str or Path, optional + Directory to save plots to. Files are named + ``shap_{group}.png``. If None, plots are only displayed. + **kwargs + Passed to ``shap.plots.beeswarm``. + """ + (X,) = _to_numpy(X) + + if shap_dict is None: + shap_dict = self.get_shap_values(X) + + if save_dir is not None: + save_dir = Path(save_dir) + save_dir.mkdir(parents=True, exist_ok=True) + + for group, values in shap_dict.items(): + explanation = shap.Explanation( + values=values, + data=X, + feature_names=features, + ) + plt.figure() + shap.plots.beeswarm( + explanation, + max_display=max_display, + show=False, + **kwargs, + ) + plt.title(f"Uplift SHAP — {group}") + plt.tight_layout() + if save_dir is not None: + filepath = save_dir / f"shap_{group}.png" + plt.savefig(filepath, dpi=150, bbox_inches="tight") + _logger.info("Saved SHAP plot to %s", filepath) + if show: + plt.show() diff --git a/multilift/uplift/meta/_slearner_classifier.py b/multilift/uplift/meta/_slearner_classifier.py new file mode 100644 index 0000000..f03b5cc --- /dev/null +++ b/multilift/uplift/meta/_slearner_classifier.py @@ -0,0 +1,233 @@ +"""S-Learner implementation for uplift classification.""" + +import logging +from copy import deepcopy +from pathlib import Path +from typing import Any + +import matplotlib.pyplot as plt +import numpy as np +import shap +from sklearn.base import BaseEstimator + +from multilift.exceptions import ModelNotFittedError +from multilift.typing import NDArray, PandasDF +from multilift.uplift.meta._tlearner import _to_numpy + +_logger = logging.getLogger(__name__) + + +class SLearnerClassifier: + """ + S-Learner for uplift classification. + + Trains one model per treatment group on ``[w, X]`` where ``w`` is a + binary indicator (1 = treatment, 0 = control). Uplift is estimated as + ``P(Y=1|T=1,X) - P(Y=1|T=0,X)`` using ``predict_proba``. + + Parameters + ---------- + control_name : str + Name of the control group. + learner : BaseEstimator + Classifier template, deep-copied for each treatment group. + """ + + def __init__(self, control_name: str, learner: BaseEstimator) -> None: + self.control_name = control_name + self._learner = learner + + # Populated during fit + self.t_groups: np.ndarray | None = None + self._classes: dict[str, int] = {} + self.models: dict[str, BaseEstimator] = {} + + @property + def is_fitted(self) -> bool: + """Whether the model has been fitted.""" + return self.t_groups is not None and len(self.models) > 0 + + # ------------------------------------------------------------------ + # Core API + # ------------------------------------------------------------------ + + def fit(self, X: NDArray, treatment: NDArray, target: NDArray) -> "SLearnerClassifier": + """ + Fit one model per treatment group on ``[w, X]``. + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix. + treatment : NDArray of shape (n_samples,) + Treatment assignment vector. + target : NDArray of shape (n_samples,) + Binary outcome vector. + + Returns + ------- + self + """ + X, treatment, target = _to_numpy(X, treatment, target) + + self.t_groups = np.sort(np.unique(treatment[treatment != self.control_name])) + self._classes = {group: i for i, group in enumerate(self.t_groups)} + self.models = {} + + for group in self.t_groups: + mask = (treatment == group) | (treatment == self.control_name) + treatment_filt = treatment[mask] + X_filt = X[mask] + y_filt = target[mask] + + w = (treatment_filt == group).astype(int) + X_new = np.hstack((w.reshape((-1, 1)), X_filt)) + + model = deepcopy(self._learner) + model.fit(X_new, y_filt) + self.models[group] = model + + _logger.info("Fitted S-learner classifier '%s' on %d observations.", group, mask.sum()) + + return self + + def predict(self, X: NDArray, **_: Any) -> NDArray: + """ + Predict treatment effects (uplift) using predicted probabilities. + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix. + + Returns + ------- + NDArray of shape (n_samples, n_treatments) + Predicted uplift for each treatment group. + """ + if not self.is_fitted: + raise ModelNotFittedError("Model is not fitted. Call fit() first.") + + (X,) = _to_numpy(X) + + te = np.empty((X.shape[0], len(self.t_groups))) + for i, group in enumerate(self.t_groups): + model = self.models[group] + X_control = np.hstack((np.zeros((X.shape[0], 1)), X)) + prob_c = model.predict_proba(X_control)[:, 1] + + X_treat = np.hstack((np.ones((X.shape[0], 1)), X)) + prob_t = model.predict_proba(X_treat)[:, 1] + + te[:, i] = prob_t - prob_c + + return te + + # ------------------------------------------------------------------ + # SHAP support + # ------------------------------------------------------------------ + + def get_shap_values(self, X: NDArray | PandasDF, **_: Any) -> dict[str, NDArray]: + """ + Compute SHAP values for uplift directly from fitted models. + + For classifiers, ``TreeExplainer.shap_values()`` may return a list + of arrays (one per class). We use index ``[1]`` (positive class) + for both treatment and control, then subtract. + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix (without the treatment indicator). + + Returns + ------- + dict[str, NDArray] + Mapping of treatment group name to SHAP value arrays of + shape ``(n_samples, n_features)``. + """ + if not self.is_fitted: + raise ModelNotFittedError("Model is not fitted. Call fit() first.") + + (X,) = _to_numpy(X) + + shap_dict: dict[str, NDArray] = {} + for group in self.t_groups: + model = self.models[group] + explainer = shap.TreeExplainer(model) + + X_treat = np.hstack((np.ones((X.shape[0], 1)), X)) + shap_t = explainer.shap_values(X_treat) + if isinstance(shap_t, list): + shap_t = shap_t[1] + + X_control = np.hstack((np.zeros((X.shape[0], 1)), X)) + shap_c = explainer.shap_values(X_control) + if isinstance(shap_c, list): + shap_c = shap_c[1] + + # Drop column 0 (treatment indicator), keep only feature columns + shap_dict[group] = shap_t[:, 1:] - shap_c[:, 1:] + + return shap_dict + + def plot_shap_values( + self, + X: NDArray | PandasDF, + features: list[str] | None = None, + shap_dict: dict[str, NDArray] | None = None, + max_display: int = 15, + show: bool = True, + save_dir: str | Path | None = None, + **kwargs: Any, + ) -> None: + """ + Plot SHAP summary plots for uplift per treatment group. + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix (used for coloring the summary plot). + features : list[str], optional + Feature names for display. + shap_dict : dict[str, NDArray], optional + Pre-computed SHAP values from ``get_shap_values``. + max_display : int, optional + Maximum number of features to display. + show : bool, optional + Whether to display the plot. + save_dir : str or Path, optional + Directory to save plots to. + **kwargs + Passed to ``shap.plots.beeswarm``. + """ + (X,) = _to_numpy(X) + + if shap_dict is None: + shap_dict = self.get_shap_values(X) + + if save_dir is not None: + save_dir = Path(save_dir) + save_dir.mkdir(parents=True, exist_ok=True) + + for group, values in shap_dict.items(): + explanation = shap.Explanation( + values=values, + data=X, + feature_names=features, + ) + plt.figure() + shap.plots.beeswarm( + explanation, + max_display=max_display, + show=False, + **kwargs, + ) + plt.title(f"Uplift SHAP — {group}") + plt.tight_layout() + if save_dir is not None: + filepath = save_dir / f"shap_{group}.png" + plt.savefig(filepath, dpi=150, bbox_inches="tight") + _logger.info("Saved SHAP plot to %s", filepath) + if show: + plt.show() diff --git a/multilift/uplift/meta/_tlearner.py b/multilift/uplift/meta/_tlearner.py new file mode 100644 index 0000000..fbe08a0 --- /dev/null +++ b/multilift/uplift/meta/_tlearner.py @@ -0,0 +1,317 @@ +"""T-Learner implementation for uplift regression.""" + +import logging +from pathlib import Path +from typing import Any + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import shap +from sklearn.base import BaseEstimator, clone + +from multilift.exceptions import ModelNotFittedError +from multilift.typing import NDArray, PandasDF + +_logger = logging.getLogger(__name__) + + +def _to_numpy(*arrays: pd.DataFrame | pd.Series | NDArray | None) -> tuple[NDArray | None, ...]: + """Convert pandas objects to numpy arrays, passing through None and NDArray.""" + return tuple(a.to_numpy() if isinstance(a, pd.DataFrame | pd.Series) else a for a in arrays) + + +class TLearnerRegressor: + """ + T-Learner for uplift regression with per-treatment learner support. + + Trains a single control outcome model and one treatment outcome model + per treatment group. Uplift is estimated as + ``E[Y|X, T=t] - E[Y|X, T=control]``. + + Supports independent learners (and therefore independent hyperparameters) + per treatment group, rather than cloning a single learner template across + all groups. + + A single control model is trained once on all control observations, + yielding ``1 + n_treatments`` models total (e.g. 5 models for + 4 treatments and 1 control). + + Parameters + ---------- + control_name : str + Name of the control group. + learner : BaseEstimator, optional + Default learner template, cloned for any group that does not have + an explicit override. At least ``learner`` or both + ``control_learner`` and ``treatment_learners`` must be provided. + control_learner : BaseEstimator, optional + Learner for the control model. Overrides ``learner`` for control. + treatment_learners : dict[str, BaseEstimator] or BaseEstimator, optional + If a single estimator, cloned for every treatment group. + If a dict, keys must match the treatment names discovered during + ``fit``. Missing keys fall back to ``learner``. + + Raises + ------ + ValueError + If neither ``learner`` nor the combination of ``control_learner`` + and ``treatment_learners`` is provided. + + Examples + -------- + Shared learner (same hyperparameters for all models): + + >>> from lightgbm import LGBMRegressor + >>> model = TLearnerRegressor( + ... control_name="control", + ... learner=LGBMRegressor(n_estimators=200), + ... ) + + Per-treatment independent hyperparameters: + + >>> model = TLearnerRegressor( + ... control_name="control", + ... control_learner=LGBMRegressor(n_estimators=200, max_depth=6), + ... treatment_learners={ + ... "T1": LGBMRegressor(n_estimators=100, max_depth=4), + ... "T2": LGBMRegressor(n_estimators=300, max_depth=8), + ... }, + ... ) + """ + + def __init__( + self, + control_name: str, + learner: BaseEstimator | None = None, + control_learner: BaseEstimator | None = None, + treatment_learners: dict[str, BaseEstimator] | BaseEstimator | None = None, + ) -> None: + if learner is None and (control_learner is None or treatment_learners is None): + raise ValueError( + "Provide either `learner` (shared template) or both " + "`control_learner` and `treatment_learners`." + ) + + self.control_name = control_name + self._learner = learner + self._control_learner = control_learner + self._treatment_learners = treatment_learners + + # Populated during fit + self._t_groups: np.ndarray | None = None + self._classes: dict[str, int] = {} + self.model_c: BaseEstimator | None = None + self.models_t: dict[str, BaseEstimator] = {} + + # ------------------------------------------------------------------ + # Properties + # ------------------------------------------------------------------ + + @property + def t_groups(self) -> np.ndarray: + """Sorted array of treatment group names.""" + if self._t_groups is None: + raise ModelNotFittedError("Model is not fitted. Call fit() first.") + return self._t_groups + + @property + def is_fitted(self) -> bool: + """Whether the model has been fitted.""" + return self._t_groups is not None and self.model_c is not None + + # ------------------------------------------------------------------ + # Internal helpers + # ------------------------------------------------------------------ + + def _resolve_control_learner(self) -> BaseEstimator: + """Return a fresh (unfitted) control learner.""" + template = self._control_learner or self._learner + return clone(template) + + def _resolve_treatment_learner(self, group: str) -> BaseEstimator: + """Return a fresh (unfitted) treatment learner for *group*.""" + if isinstance(self._treatment_learners, dict): + if group in self._treatment_learners: + return clone(self._treatment_learners[group]) + if self._learner is not None: + return clone(self._learner) + raise ValueError( + f"No learner found for treatment group '{group}'. " + "Provide it in `treatment_learners` or set a default `learner`." + ) + + template = self._treatment_learners or self._learner + return clone(template) + + # ------------------------------------------------------------------ + # Core API + # ------------------------------------------------------------------ + + def fit(self, X: NDArray, treatment: NDArray, target: NDArray) -> "TLearnerRegressor": + """ + Fit one control model and one treatment model per group. + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix. + treatment : NDArray of shape (n_samples,) + Treatment assignment vector. + target : NDArray of shape (n_samples,) + Outcome vector. + + Returns + ------- + self + """ + X, treatment, target = _to_numpy(X, treatment, target) + + self._t_groups = np.sort(np.unique(treatment[treatment != self.control_name])) + self._classes = {group: i for i, group in enumerate(self._t_groups)} + + # Single control model trained on all control observations + control_mask = treatment == self.control_name + self.model_c = self._resolve_control_learner() + self.model_c.fit(X[control_mask], target[control_mask]) + _logger.info("Fitted control model on %d observations.", control_mask.sum()) + + # One treatment model per group + self.models_t = {} + for group in self._t_groups: + treatment_mask = treatment == group + self.models_t[group] = self._resolve_treatment_learner(group) + self.models_t[group].fit(X[treatment_mask], target[treatment_mask]) + _logger.info( + "Fitted treatment model '%s' on %d observations.", + group, + treatment_mask.sum(), + ) + + return self + + def predict(self, X: NDArray, **_) -> NDArray: + """ + Predict treatment effects (uplift). + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix. + + Returns + ------- + NDArray of shape (n_samples, n_treatments) + Predicted uplift for each treatment group. + Column order matches ``self.t_groups``. + """ + if not self.is_fitted: + raise ModelNotFittedError("Model is not fitted. Call fit() first.") + + (X,) = _to_numpy(X) + + yhat_c = self.model_c.predict(X) + + tau = np.empty((X.shape[0], len(self._t_groups))) + for i, group in enumerate(self._t_groups): + tau[:, i] = self.models_t[group].predict(X) - yhat_c + + return tau + + # ------------------------------------------------------------------ + # SHAP support + # ------------------------------------------------------------------ + + def get_shap_values(self, X: NDArray | PandasDF, **_: Any) -> dict[str, NDArray]: + """Compute SHAP values for uplift via control/treatment subtraction. + + Uses the actual fitted models (no surrogate). This is exact for + tree-based learners via ``shap.TreeExplainer``. + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix. + + Returns + ------- + dict[str, NDArray] + Mapping of treatment group name to SHAP value arrays of + shape ``(n_samples, n_features)``. + """ + if not self.is_fitted: + raise ModelNotFittedError("Model is not fitted. Call fit() first.") + + (X,) = _to_numpy(X) + + shap_c = shap.TreeExplainer(self.model_c).shap_values(X) + + shap_dict: dict[str, NDArray] = {} + for group in self._t_groups: + shap_t = shap.TreeExplainer(self.models_t[group]).shap_values(X) + shap_dict[group] = shap_t - shap_c + + return shap_dict + + def plot_shap_values( + self, + X: NDArray | PandasDF, + features: list[str] | None = None, + shap_dict: dict[str, NDArray] | None = None, + max_display: int = 15, + show: bool = True, + save_dir: str | Path | None = None, + **kwargs: Any, + ) -> None: + """ + Plot SHAP summary plots for uplift per treatment group. + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix (used for coloring the summary plot). + features : list[str], optional + Feature names for display. + shap_dict : dict[str, NDArray], optional + Pre-computed SHAP values from ``get_shap_values``. + If None, they are computed automatically. + max_display : int, optional + Maximum number of features to display. + show : bool, optional + Whether to display the plot. + save_dir : str or Path, optional + Directory to save plots to. Files are named + ``shap_{group}.png``. If None, plots are only displayed. + **kwargs + Passed to ``shap.plots.beeswarm``. + """ + (X,) = _to_numpy(X) + + if shap_dict is None: + shap_dict = self.get_shap_values(X) + + if save_dir is not None: + save_dir = Path(save_dir) + save_dir.mkdir(parents=True, exist_ok=True) + + for group, values in shap_dict.items(): + explanation = shap.Explanation( + values=values, + data=X, + feature_names=features, + ) + plt.figure() + shap.plots.beeswarm( + explanation, + max_display=max_display, + show=False, + **kwargs, + ) + plt.title(f"Uplift SHAP — {group}") + plt.tight_layout() + if save_dir is not None: + filepath = save_dir / f"shap_{group}.png" + plt.savefig(filepath, dpi=150, bbox_inches="tight") + _logger.info("Saved SHAP plot to %s", filepath) + if show: + plt.show() diff --git a/multilift/uplift/meta/_tlearner_classifier.py b/multilift/uplift/meta/_tlearner_classifier.py new file mode 100644 index 0000000..2351d9c --- /dev/null +++ b/multilift/uplift/meta/_tlearner_classifier.py @@ -0,0 +1,281 @@ +"""T-Learner implementation for uplift classification.""" + +import logging +from pathlib import Path +from typing import Any + +import matplotlib.pyplot as plt +import numpy as np +import shap +from sklearn.base import BaseEstimator, clone + +from multilift.exceptions import ModelNotFittedError +from multilift.typing import NDArray, PandasDF +from multilift.uplift.meta._tlearner import _to_numpy + +_logger = logging.getLogger(__name__) + + +class TLearnerClassifier: + """ + T-Learner for uplift classification with per-treatment learner support. + + Trains a single control outcome model and one treatment outcome model + per treatment group. Uplift is estimated as + ``P(Y=1|X, T=t) - P(Y=1|X, T=control)`` using ``predict_proba``. + + Parameters + ---------- + control_name : str + Name of the control group. + learner : BaseEstimator, optional + Default learner template, cloned for any group without an override. + control_learner : BaseEstimator, optional + Learner for the control model. Overrides ``learner`` for control. + treatment_learners : dict[str, BaseEstimator] or BaseEstimator, optional + If a single estimator, cloned for every treatment group. + If a dict, keys must match treatment names discovered during ``fit``. + + Raises + ------ + ValueError + If neither ``learner`` nor both ``control_learner`` and + ``treatment_learners`` is provided. + """ + + def __init__( + self, + control_name: str, + learner: BaseEstimator | None = None, + control_learner: BaseEstimator | None = None, + treatment_learners: dict[str, BaseEstimator] | BaseEstimator | None = None, + ) -> None: + if learner is None and (control_learner is None or treatment_learners is None): + raise ValueError( + "Provide either `learner` (shared template) or both " + "`control_learner` and `treatment_learners`." + ) + + self.control_name = control_name + self._learner = learner + self._control_learner = control_learner + self._treatment_learners = treatment_learners + + # Populated during fit + self._t_groups: np.ndarray | None = None + self._classes: dict[str, int] = {} + self.model_c: BaseEstimator | None = None + self.models_t: dict[str, BaseEstimator] = {} + + # ------------------------------------------------------------------ + # Properties + # ------------------------------------------------------------------ + + @property + def t_groups(self) -> np.ndarray: + """Sorted array of treatment group names.""" + if self._t_groups is None: + raise ModelNotFittedError("Model is not fitted. Call fit() first.") + return self._t_groups + + @property + def is_fitted(self) -> bool: + """Whether the model has been fitted.""" + return self._t_groups is not None and self.model_c is not None + + # ------------------------------------------------------------------ + # Internal helpers + # ------------------------------------------------------------------ + + def _resolve_control_learner(self) -> BaseEstimator: + """Return a fresh (unfitted) control learner.""" + template = self._control_learner or self._learner + return clone(template) + + def _resolve_treatment_learner(self, group: str) -> BaseEstimator: + """Return a fresh (unfitted) treatment learner for *group*.""" + if isinstance(self._treatment_learners, dict): + if group in self._treatment_learners: + return clone(self._treatment_learners[group]) + if self._learner is not None: + return clone(self._learner) + raise ValueError( + f"No learner found for treatment group '{group}'. " + "Provide it in `treatment_learners` or set a default `learner`." + ) + + template = self._treatment_learners or self._learner + return clone(template) + + # ------------------------------------------------------------------ + # Core API + # ------------------------------------------------------------------ + + def fit(self, X: NDArray, treatment: NDArray, target: NDArray) -> "TLearnerClassifier": + """ + Fit one control model and one treatment model per group. + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix. + treatment : NDArray of shape (n_samples,) + Treatment assignment vector. + target : NDArray of shape (n_samples,) + Binary outcome vector. + + Returns + ------- + self + """ + X, treatment, target = _to_numpy(X, treatment, target) + + self._t_groups = np.sort(np.unique(treatment[treatment != self.control_name])) + self._classes = {group: i for i, group in enumerate(self._t_groups)} + + # Single control model trained on all control observations + control_mask = treatment == self.control_name + self.model_c = self._resolve_control_learner() + self.model_c.fit(X[control_mask], target[control_mask]) + _logger.info("Fitted control classifier on %d observations.", control_mask.sum()) + + # One treatment model per group + self.models_t = {} + for group in self._t_groups: + treatment_mask = treatment == group + self.models_t[group] = self._resolve_treatment_learner(group) + self.models_t[group].fit(X[treatment_mask], target[treatment_mask]) + _logger.info( + "Fitted treatment classifier '%s' on %d observations.", + group, + treatment_mask.sum(), + ) + + return self + + def predict(self, X: NDArray, **_) -> NDArray: + """ + Predict treatment effects (uplift) using predicted probabilities. + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix. + + Returns + ------- + NDArray of shape (n_samples, n_treatments) + Predicted uplift for each treatment group. + """ + if not self.is_fitted: + raise ModelNotFittedError("Model is not fitted. Call fit() first.") + + (X,) = _to_numpy(X) + + prob_c = self.model_c.predict_proba(X)[:, 1] + + tau = np.empty((X.shape[0], len(self._t_groups))) + for i, group in enumerate(self._t_groups): + tau[:, i] = self.models_t[group].predict_proba(X)[:, 1] - prob_c + + return tau + + # ------------------------------------------------------------------ + # SHAP support + # ------------------------------------------------------------------ + + def get_shap_values(self, X: NDArray | PandasDF, **_: Any) -> dict[str, NDArray]: + """ + Compute SHAP values for uplift via control/treatment subtraction. + + For classifiers, uses the positive class (index 1) SHAP values. + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix. + + Returns + ------- + dict[str, NDArray] + Mapping of treatment group name to SHAP value arrays of + shape ``(n_samples, n_features)``. + """ + if not self.is_fitted: + raise ModelNotFittedError("Model is not fitted. Call fit() first.") + + (X,) = _to_numpy(X) + + shap_c = shap.TreeExplainer(self.model_c).shap_values(X) + if isinstance(shap_c, list): + shap_c = shap_c[1] + + shap_dict: dict[str, NDArray] = {} + for group in self._t_groups: + shap_t = shap.TreeExplainer(self.models_t[group]).shap_values(X) + if isinstance(shap_t, list): + shap_t = shap_t[1] + shap_dict[group] = shap_t - shap_c + + return shap_dict + + def plot_shap_values( + self, + X: NDArray | PandasDF, + features: list[str] | None = None, + shap_dict: dict[str, NDArray] | None = None, + max_display: int = 15, + show: bool = True, + save_dir: str | Path | None = None, + **kwargs: Any, + ) -> None: + """ + Plot SHAP summary plots for uplift per treatment group. + + Parameters + ---------- + X : NDArray of shape (n_samples, n_features) + Feature matrix (used for coloring the summary plot). + features : list[str], optional + Feature names for display. + shap_dict : dict[str, NDArray], optional + Pre-computed SHAP values from ``get_shap_values``. + max_display : int, optional + Maximum number of features to display. + show : bool, optional + Whether to display the plot. + save_dir : str or Path, optional + Directory to save plots to. + **kwargs + Passed to ``shap.plots.beeswarm``. + """ + (X,) = _to_numpy(X) + + if shap_dict is None: + shap_dict = self.get_shap_values(X) + + if save_dir is not None: + save_dir = Path(save_dir) + save_dir.mkdir(parents=True, exist_ok=True) + + for group, values in shap_dict.items(): + explanation = shap.Explanation( + values=values, + data=X, + feature_names=features, + ) + plt.figure() + shap.plots.beeswarm( + explanation, + max_display=max_display, + show=False, + **kwargs, + ) + plt.title(f"Uplift SHAP — {group}") + plt.tight_layout() + if save_dir is not None: + filepath = save_dir / f"shap_{group}.png" + plt.savefig(filepath, dpi=150, bbox_inches="tight") + _logger.info("Saved SHAP plot to %s", filepath) + if show: + plt.show() diff --git a/multilift/uplift/regressor.py b/multilift/uplift/regressor.py new file mode 100644 index 0000000..e15dcfb --- /dev/null +++ b/multilift/uplift/regressor.py @@ -0,0 +1,827 @@ +import logging +import warnings +from pathlib import Path +from typing import Any + +import joblib +import numpy as np +import pandas as pd +from lightgbm import LGBMRegressor +from matplotlib import pyplot as plt + +from multilift.constants import DEFAULT_RANDOM_SEED +from multilift.exceptions import ModelNotFittedError +from multilift.preproc import OneHotPreprocessor +from multilift.typing import NDArray, PandasDF, Series +from multilift.uplift._utils import _apply_threshold +from multilift.uplift.eval import ( + UpliftExploreEvaluator, + compute_best_uplift, + compute_qini, + plot_uplift_bins, +) +from multilift.uplift.meta import SLearnerRegressor, TLearnerRegressor + +_logger = logging.getLogger(__name__) + + +class UpliftRegressorPipeline: + """ + A complete pipeline for uplift modeling with preprocessing and evaluation. + + This class combines uplift model training, preprocessing, and evaluation + into a single pipeline. It uses S-Learner with LightGBM as the base learner + and provides methods for policy recommendations and Qini curve evaluation. + + Parameters + ---------- + control_name : str + Name of the control group/treatment. + *treatment_names : str + Names of the treatment groups. + keep_cols : list[str], optional + Columns to keep during preprocessing. + drop_cols : list[str], optional + Columns to drop during preprocessing. + random_seed : int, default=42 + Random seed for reproducibility. + lbm_verbosity : int, default=-1 + Verbosity level for LightGBM. + **model_params : Any + Additional parameters to pass to the LightGBM regressor. + If model_type is "T", then control_learner and treatment_learner are also passed. + + Examples + -------- + >>> X_train, y_train, t_train = ... # Your training data + >>> X_test, y_test, t_test = ... # Your test data + ... + >>> pipeline = UpliftRegressorPipeline( + ... "control", + ... "treatment_A", "treatment_B", + ... n_estimators=100, + ... learning_rate=0.1 + ... ) + >>> pipeline.fit(X_train, y_train, t_train) + >>> qini_auc, _ = pipeline.evaluate(X_test, y_test, t_test) + """ + + def __init__( + self, + control_name: str, + *treatment_names: str, + keep_cols: list[str] | None = None, + drop_cols: list[str] | None = None, + random_seed: int = DEFAULT_RANDOM_SEED, + model_type: str = "S", + preprocessor: OneHotPreprocessor | None = None, + lbm_verbosity: int = -1, + **model_params: Any, + ): + self._control_name = control_name + self._treatment_names = list(treatment_names) + + # check if it is not a list of list + if isinstance(self._treatment_names[0], list): + raise TypeError(f"Treatment_names should not be nested lists: {self._treatment_names}") + + self._keep_cols = keep_cols + self._drop_cols = drop_cols + self._model_params = model_params or {} + self._model_type = model_type + self._random_seed = random_seed + self._lbm_verbosity = lbm_verbosity + + self._preprocessor: OneHotPreprocessor | None = preprocessor + self._model = None + self._version = None + + seed = self._model_params.pop("random_state", None) + if seed is not None: + _logger.warning( + "Random seed is set in model_params. Using random_seed=%s instead.", random_seed + ) + + def __repr__(self): + """Return a string representation of the object.""" + return ( + f"UpliftRegressorPipeline(" + f"control_name={self._control_name}, " + f"treatment_names={self._treatment_names}), " + f"model_type={self._model_type})" + ) + + def _check_if_fitted(self): + if self._model is None: + raise ModelNotFittedError("Model is not fitted. Call fit() first.") + + @property + def control_name(self) -> str: + """Return the control name.""" + return self._control_name + + @property + def treatment_names(self) -> list[str]: + """Return the treatment names.""" + return self._treatment_names + + @property + def preprocessor(self) -> OneHotPreprocessor | None: + """Return the preprocessor.""" + return self._preprocessor + + @property + def model(self) -> SLearnerRegressor | TLearnerRegressor | None: + """Return the model.""" + return self._model + + @preprocessor.setter + def preprocessor(self, preprocessor: OneHotPreprocessor) -> None: + """Set the preprocessor.""" + self._preprocessor = preprocessor + + @model.setter + def model(self, model: SLearnerRegressor | TLearnerRegressor) -> None: + """Set the model.""" + self._model = model + + @property + def version(self) -> str | None: + """Return the version.""" + return self._version + + @version.setter + def version(self, version: str) -> None: + """Set the version.""" + self._version = version + + def get_feature_names(self, raw: bool = True) -> list[str]: + """Return the feature names. + + Parameters + ---------- + raw: Whether to return the non-transformed feature names + + Returns + ------- + list[str] + The feature names + """ + if not self._preprocessor: + raise RuntimeError("Preprocess is not initialized!") + if raw: + return self._preprocessor.get_raw_feature_names_out() + return self._preprocessor.get_feature_names_out() + + def preprocess(self, X: PandasDF, training: bool = False) -> PandasDF: + """ + Preprocess the input DataFrame. + + Parameters + ---------- + X: The input DataFrame + training: Whether the preprocessing is for training + + Returns + ------- + PandasDF + The preprocessed DataFrame + + Raises + ------ + ModelNotFittedError + If the preprocessor is not fitted and training is False + """ + if self._preprocessor is None: + if not training: + raise ModelNotFittedError("Preprocessor is not fitted. Call fit() first.") + + self._preprocessor = OneHotPreprocessor( + keep_cols=self._keep_cols, drop_cols=self._drop_cols + ) + if training and not self._preprocessor.is_fitted: + self._preprocessor.fit(X) + x_encoded = self._preprocessor.transform(X) + _logger.info("Preprocessed features shape: %s", x_encoded.shape) + return x_encoded + + @staticmethod + def _is_per_treatment_params(params: dict[str, Any]) -> bool: + """Check if params is per-treatment (dict-of-dicts) vs shared (flat).""" + return bool(params) and all(isinstance(v, dict) for v in params.values()) + + def _init_t_learner(self): + control_learner_params = self._model_params.get("control_learner_params", {}) + treatment_learner_params = self._model_params.get("treatment_learner_params", {}) + + if not control_learner_params and not treatment_learner_params: + # No specific params — use shared model_params for all models + learner = LGBMRegressor( + random_state=self._random_seed, verbose=self._lbm_verbosity, **self._model_params + ) + _logger.info("Initializing T-Learner with shared params: %s", self._model_params) + self._model = TLearnerRegressor(control_name=self._control_name, learner=learner) + return + + control_learner = LGBMRegressor( + random_state=self._random_seed, verbose=self._lbm_verbosity, **control_learner_params + ) + + if self._is_per_treatment_params(treatment_learner_params): + # Per-treatment: {"T1": {params}, "T2": {params}} + _logger.info("Initializing T-Learner with per-treatment params.") + treatment_learners = { + name: LGBMRegressor( + random_state=self._random_seed, verbose=self._lbm_verbosity, **params + ) + for name, params in treatment_learner_params.items() + } + self._model = TLearnerRegressor( + control_name=self._control_name, + control_learner=control_learner, + treatment_learners=treatment_learners, + ) + else: + # Shared treatment params: {params} applied to all treatments + _logger.info("Initializing T-Learner with shared treatment params.") + treatment_learner = LGBMRegressor( + random_state=self._random_seed, + verbose=self._lbm_verbosity, + **treatment_learner_params, + ) + self._model = TLearnerRegressor( + control_name=self._control_name, + control_learner=control_learner, + treatment_learners=treatment_learner, + ) + + def fit(self, X: PandasDF, t: Series, y: Series) -> "UpliftRegressorPipeline": + """ + Fit the model. + + Parameters + ---------- + X: The input DataFrame + t: The treatment Series + y: The target Series + + Returns + ------- + UpliftRegressorPipeline + The fitted pipeline + """ + x_encoded = self.preprocess(X, training=True) + + if self._model_type == "S": + learner = LGBMRegressor( + random_state=self._random_seed, verbose=self._lbm_verbosity, **self._model_params + ) + _logger.info("Initializing S-Learner with params: %s", self._model_params) + self._model = SLearnerRegressor(learner=learner, control_name=self._control_name) + elif self._model_type == "T": + self._init_t_learner() + elif self._model_type == "X": + raise NotImplementedError("X-Learner is not implemented yet.") + else: + raise ValueError(f"Invalid model type: {self._model_type}") + + self._model.fit(x_encoded, t, y) + return self + + def predict( + self, + X: PandasDF, + t: Series | None = None, + y: Series | None = None, + treatment_idx: int | None = None, + treatment_indices: list[int] | None = None, + ) -> PandasDF: + """ + Predict the uplift for each treatment. + + Parameters + ---------- + X : PandasDF + The input DataFrame. + t : Series, optional + The treatment Series. + y : Series, optional + The target Series. + treatment_idx : int, optional + Single treatment index. Returns uplift for the specified treatment. + Cannot be used with treatment_indices. + treatment_indices : list[int], optional + List of treatment indices. Returns uplift for the specified treatments. + Cannot be used with treatment_idx. + + Returns + ------- + PandasDF of shape (n, m) + The predicted uplift for each treatment (or selected treatments). + + Raises + ------ + ValueError + If both treatment_idx and treatment_indices are provided. + + IndexError + If any treatment index is out of bounds. + """ + self._check_if_fitted() + x_encoded = self.preprocess(X, training=False) + tau = self._model.predict(x_encoded, treatment=t, y=y) + + if treatment_indices is None and treatment_idx is None: + return pd.DataFrame(tau, columns=self._treatment_names, dtype=np.float32) + + if treatment_idx is not None and treatment_indices is not None: + raise ValueError("Only one of treatment_idx or treatment_indices can be provided.") + + if treatment_idx is not None: + treatment_indices = [treatment_idx] + + treatment_indices = np.array(treatment_indices) + if any(treatment_indices < 0) or any(treatment_indices >= len(self._treatment_names)): + raise IndexError(f"Invalid treatment indices: {treatment_indices}") + + treatment_names = np.array(self._treatment_names)[treatment_indices] + _logger.info("Predicting uplift for treatments: %s", treatment_names) + tau = tau[:, treatment_indices] + return pd.DataFrame(tau, columns=treatment_names, dtype=np.float32) + + def policy( + self, + X: PandasDF, + control_name: str | None = None, + recipe_names: list[str] | None = None, + threshold: float | dict[str, float] = 0.0, + ) -> PandasDF: + """ + Get optimal treatment policy for each individual. + + For each individual, selects the treatment with the highest positive uplift. + If no treatment has positive uplift, recommends control. + + When *threshold* is a dict, each recipe has its own minimum cutoff. + Treatments whose predicted uplift falls below their cutoff are masked + out before the argmax selection. Recipes absent from the dict default + to a cutoff of 0. + + Parameters + ---------- + X : PandasDF + The input DataFrame with features. + control_name : str, optional + The name of the control group. If None, uses the name + provided during initialization. + recipe_names : list[str], optional + The names of the treatments to recommend. If None, uses the names + provided during initialization. + threshold : float or dict[str, float], optional + A single non-negative threshold (default 0.0) applied to the best + uplift, **or** a mapping of ``{recipe_name: cutoff}`` for + per-recipe cutoffs. + + Returns + ------- + PandasDF + A DataFrame with the predicted uplift for each treatment, + the maximum uplift, and the recommended policy. + + Raises + ------ + ModelNotFittedError + If the model hasn't been fitted yet. + + ValueError + - If recipe names do not match the number of treatments. + - If any threshold value is negative. + - If threshold dict contains unknown recipe names. + """ + self._check_if_fitted() + + if (recipe_names is not None) and (len(recipe_names) != len(self._treatment_names)): + raise ValueError( + f"Recipe names must match the number of treatments: " + f"{recipe_names} != {self._treatment_names}" + ) + + recipe_names = recipe_names or self._treatment_names + control_name = control_name or self._control_name + + tau = self.predict(X).to_numpy(dtype=np.float32) + max_uplifts = pd.Series(compute_best_uplift(tau), name="max_uplift") + recipe_names_arr = np.array(recipe_names) + + _logger.info("Applying policy with threshold: %s", threshold) + policies = _apply_threshold(tau, recipe_names_arr, control_name, threshold) + + tau = pd.DataFrame(tau, columns=recipe_names) + return pd.concat([tau, max_uplifts, policies], axis=1) + + def policy_subset( + self, + X: PandasDF, + treatment_indices: list[int], + control_name: str | None = None, + recipe_names: list[str] | None = None, + threshold: float | dict[str, float] = 0.0, + ) -> PandasDF: + """ + Get optimal policy from a subset of treatments. + + For each individual, selects the treatment with the highest uplift + among the specified subset. If the max uplift exceeds the threshold, + recommends that treatment; otherwise recommends control. + + Parameters + ---------- + X : PandasDF + The input DataFrame with features. + treatment_indices : list[int] + List of treatment indices to consider (0-indexed). + control_name : str, optional + The name of the control group. If None, uses the name + provided during initialization. + recipe_names : list[str], optional + The names of the treatments to recommend. Must match the length + of treatment_indices. If None, uses the names corresponding to + treatment_indices from initialization. + threshold : float or dict[str, float], optional + A single non-negative threshold (default 0.0) applied to the best + uplift, **or** a mapping of ``{recipe_name: cutoff}`` for + per-recipe cutoffs. + + Returns + ------- + PandasDF + A DataFrame with the predicted uplift for selected treatments, + the maximum uplift, and the recommended policy. + + Raises + ------ + ModelNotFittedError + If the model hasn't been fitted yet. + ValueError + If treatment_indices is empty. + If recipe_names length doesn't match treatment_indices. + If any threshold value is negative. + If any treatment index is out of bounds. + """ + self._check_if_fitted() + + if not treatment_indices: + raise ValueError("treatment_indices cannot be empty.") + + if recipe_names is not None and len(recipe_names) != len(treatment_indices): + raise ValueError( + f"recipe_names length ({len(recipe_names)}) must match " + f"treatment_indices length ({len(treatment_indices)})" + ) + + control_name = control_name or self._control_name + tau = self.predict(X, treatment_indices=treatment_indices).to_numpy(dtype=np.float32) + + if recipe_names is None: + recipe_names = [self._treatment_names[i] for i in treatment_indices] + + _logger.info("Predicting policy for treatments: %s", recipe_names) + max_uplifts = pd.Series(compute_best_uplift(tau), name="max_uplift") + recipe_names_arr = np.array(recipe_names) + + policies = _apply_threshold(tau, recipe_names_arr, control_name, threshold) + + tau = pd.DataFrame(tau, columns=recipe_names) + return pd.concat([tau, max_uplifts, policies], axis=1) + + def policy_single( + self, + X: PandasDF, + treatment_idx: int, + control_name: str | None = None, + recipe_name: str | None = None, + threshold: float = 0.0, + ) -> PandasDF: + """ + Get optimal policy between a single treatment and control. + + .. deprecated:: + Use :meth:`policy_subset` with a single-element list instead. + + For each individual, recommends the specified treatment if its uplift + exceeds the threshold, otherwise recommends control. + + Parameters + ---------- + X : PandasDF + The input DataFrame with features. + treatment_idx : int + The index of the treatment to evaluate (0-indexed). + control_name : str, optional + The name of the control group. If None, uses the name + provided during initialization. + recipe_name : str, optional + The name of the treatment to recommend. If None, uses the name + corresponding to treatment_idx from initialization. + threshold : float, optional + A non-negative threshold for the uplift, defaults to 0.0. If the uplift + is less than or equal to this threshold, control is recommended. + + Returns + ------- + PandasDF + A DataFrame with the predicted uplift for the treatment, + the maximum uplift, and the recommended policy. + + Raises + ------ + ModelNotFittedError + If the model hasn't been fitted yet. + IndexError + If treatment_idx is out of bounds. + ValueError + If threshold is negative. + """ + warnings.warn( + "policy_single is deprecated, use policy_subset with a single-element list instead.", + DeprecationWarning, + stacklevel=2, + ) + recipe_names = [recipe_name] if recipe_name is not None else None + return self.policy_subset( + X, + treatment_indices=[treatment_idx], + control_name=control_name, + recipe_names=recipe_names, + threshold=threshold, + ) + + def evaluate(self, X: PandasDF, t: Series, y: Series) -> tuple[float, PandasDF]: + """ + Evaluate the model. + + Parameters + ---------- + X: The input DataFrame + t: The treatment Series + y: The target Series + + Returns + ------- + float + The Qini AUC + PandasDF + The Qini DataFrame + """ + self._check_if_fitted() + tau = self.predict(X).to_numpy(dtype=np.float32) + qini_auc, qini_df = compute_qini(tau, t, y, self._control_name, *self._treatment_names) + _logger.info("Qini AUC: %s", qini_auc) + return qini_auc, qini_df + + def plot( + self, + X: PandasDF, + t: Series, + y: Series, + treatment_names: list[str] | None = None, + name: str = "Binned Actual Uplift", + **plot_kw, + ) -> plt.Axes: + """ + Plot the Qini curve. + + Parameters + ---------- + X: The input DataFrame + t: The treatment Series + y: The target Series + name: The name of the plot + plot_kw: Additional keyword arguments for plot_binned_actual_uplift + + Returns + ------- + plt.Axes + The axes of the plot + """ + self._check_if_fitted() + if not treatment_names: + evaluator = UpliftExploreEvaluator(self._control_name, *self._treatment_names) + tau = self.predict(X).to_numpy(dtype=np.float32) + return evaluator.plot_binned_actual_uplift(t, y, tau, title=name, **plot_kw) + + if set(treatment_names) - set(self._treatment_names): + raise ValueError("treatment_names must be a subset of treatment_names") + + evaluator = UpliftExploreEvaluator(self._control_name, *treatment_names) + treatment_idxs = [self._treatment_names.index(name) for name in treatment_names] + _logger.info( + "Plotting for treatment names: %s, indices: %s", treatment_names, treatment_idxs + ) + + tau = self.predict(X, treatment_indices=treatment_idxs) + allowed_recipes = [self._control_name, *treatment_names] + mask = t.isin(allowed_recipes) + + return evaluator.plot_binned_actual_uplift( + t[mask], + y[mask], + tau[mask].to_numpy(dtype=np.float32), + title=name, + **plot_kw, + ) + + def plot_uplift_bins( + self, + X: PandasDF, + t: Series, + y: Series, + n_bins: int = 10, + name: str = "Uplift Bins", + **plot_kw, + ): + """ + Plot the uplift bins. + + Parameters + ---------- + X: The input DataFrame + t: The treatment Series + y: The target Series + n_bins: The number of bins + name: The name of the plot + plot_kw: Additional keyword arguments for plot_uplift_bins + + Returns + ------- + plt.Axes + The axes of the plot + """ + self._check_if_fitted() + tau = compute_best_uplift(self.predict(X)) + return plot_uplift_bins( + t, + y, + tau, + self._control_name, + *self._treatment_names, + n_bins=n_bins, + name=name, + **plot_kw, + ) + + def save(self, filepath: str | Path, version: str, compress: int | bool = 3) -> Path: + """ + Save the fitted pipeline to disk. + + Parameters + ---------- + filepath : str or Path + Path where the pipeline will be saved. Will add .joblib extension if not present. + version : str + Version of the model. + compress : int or bool, default=3 + Compression level (0-9). 0 or False means no compression, + higher values mean more compression but slower save/load. + + Returns + ------- + Path + The path where the model was saved + + Raises + ------ + ModelNotFittedError + If the model hasn't been fitted yet. + + Examples + -------- + >>> uplift_pl = UpliftRegressorPipeline("control", "treatment") + >>> uplift_pl.save('models/uplift_model', version="1.0.0") # saves as uplift_model.joblib + >>> uplift_pl.save( + ... 'models/uplift_model.pkl', version="1.0.1", compress=False + ... ) # no compression + """ + self._check_if_fitted() + filepath = Path(filepath) + + # Add extension if not present + if not filepath.suffix: + filepath = filepath.with_suffix(".joblib") + + # Create parent directory if it doesn't exist + filepath.parent.mkdir(parents=True, exist_ok=True) + self._version = version + + # Prepare the state dictionary + state = { + # config + "control_name": self._control_name, + "treatment_names": self._treatment_names, + "keep_cols": self._keep_cols, + "drop_cols": self._drop_cols, + "model_params": self._model_params, + "model_type": self._model_type, + "random_seed": self._random_seed, + # Fitted objects + "preprocessor": self._preprocessor, + "model": self._model, + # Metadata + "version": self._version, + "class_name": self.__class__.__name__, + } + + joblib.dump(state, filepath, compress=compress) + _logger.info("Saved model to %s", filepath) + return filepath + + def shap(self, X: PandasDF, **plot_kw) -> dict[str, NDArray]: + """ + Compute and plot SHAP values for model interpretability. + + Parameters + ---------- + X : PandasDF + Input features to compute SHAP values for. + + Returns + ------- + dict[str, NDArray] + SHAP values for each treatment. + + Raises + ------ + ModelNotFittedError + If the model hasn't been fitted yet. + """ + self._check_if_fitted() + x_encoded = self.preprocess(X, training=False) + feature_names = self.get_feature_names(raw=False) + + _logger.info("Computing SHAP for %s observations", x_encoded.shape[0]) + + shap_dict = self._model.get_shap_values(X=x_encoded) + self._model.plot_shap_values( + X=x_encoded, features=feature_names, shap_dict=shap_dict, **plot_kw + ) + return shap_dict + + @classmethod + def load(cls, filepath: str | Path) -> "UpliftRegressorPipeline": + """ + Load a fitted pipeline from disk. + + Parameters + ---------- + filepath : str or Path + Path to the saved pipeline file. + + Returns + ------- + UpliftRegressorPipeline + The loaded pipeline ready for prediction. + + Raises + ------ + FileNotFoundError + If the file doesn't exist. + ValueError + If the file format is incompatible. + + Examples + -------- + >>> X = ... # Your input data + >>> pipeline = UpliftRegressorPipeline.load('models/uplift_model.joblib') + >>> predictions = pipeline.predict(X) + """ + filepath = Path(filepath) + + if not filepath.exists(): + raise FileNotFoundError(f"Model file not found: {filepath}") + + # Load the state dictionary + try: + state = joblib.load(filepath) + except Exception as e: + raise ValueError(f"Failed to load model from {filepath}: {e}") + + # Reconstruct the pipeline + treatment_names = state["treatment_names"] + if isinstance(treatment_names[0], list): + treatment_names = [t[0] for t in treatment_names] + + uplift_pl = cls( + state["control_name"], + *treatment_names, + keep_cols=state.get("keep_cols"), + drop_cols=state.get("drop_cols"), + random_seed=state.get("random_seed", DEFAULT_RANDOM_SEED), + model_type=state.get("model_type", "S"), + **state.get("model_params", {}), + ) + uplift_pl.preprocessor = state["preprocessor"] + uplift_pl.model = state["model"] + uplift_pl.version = state.get("version") + + _logger.info("Loaded model from %s", filepath) + return uplift_pl diff --git a/multilift/uplift/tuner/__init__.py b/multilift/uplift/tuner/__init__.py new file mode 100644 index 0000000..220ada8 --- /dev/null +++ b/multilift/uplift/tuner/__init__.py @@ -0,0 +1,19 @@ +"""Hyperparameter tuning for uplift models.""" + +from multilift.uplift.tuner._slearner import SLearnerTuner +from multilift.uplift.tuner._tlearner import TLearnerTuner +from multilift.uplift.tuner._utils import ( + ScoringFn, + TunerResult, + qini_scorer, + top_decile_scorer, +) + +__all__ = [ + "SLearnerTuner", + "ScoringFn", + "TLearnerTuner", + "TunerResult", + "qini_scorer", + "top_decile_scorer", +] diff --git a/multilift/uplift/tuner/_slearner.py b/multilift/uplift/tuner/_slearner.py new file mode 100644 index 0000000..dc959f8 --- /dev/null +++ b/multilift/uplift/tuner/_slearner.py @@ -0,0 +1,412 @@ +"""Hyperparameter tuner for S-Learner uplift models.""" + +import logging +from collections.abc import Sequence +from pathlib import Path +from typing import Any, Literal + +import numpy as np +from sklearn.model_selection import ParameterSampler + +from multilift.constants import ( + DEFAULT_PARAM_GRID, + DEFAULT_RANDOM_SEED, + DEFAULT_TOP_N_MODELS, +) +from multilift.exceptions import ModelNotFittedError +from multilift.typing import PandasDF, Series +from multilift.uplift.regressor import UpliftRegressorPipeline +from multilift.uplift.tuner._utils import ( + ScoringFn, + TunerResult, + qini_scorer, + top_decile_scorer, +) + +_logger = logging.getLogger(__name__) + + +class SLearnerTuner: + """ + Hyperparameter tuner for S-Learner uplift models. + + This tuner tunes a single model that learns both control and treatment + outcomes together. Unlike T-Learner, S-Learner uses a single set of + hyperparameters for the entire model. + + Parameters + ---------- + control_name : str + Name of the control group. + treatment_names : list[str] + Names of the treatment groups. + scoring : str or callable, optional + Scoring metric. If "qini" (default), uses Qini AUC. + If callable, should have signature: + `(tau, t, y, control_name, treatment_names) -> float` + random_seed : int, optional + Random seed for reproducibility. + + Examples + -------- + >>> tuner = SLearnerTuner("control", ["treatment_A", "treatment_B"]) + ... + >>> X_train, t_train, y_train = ... # get training data + >>> X_val, t_val, y_val = ... # get validation data + ... + >>> param_grid = { + ... "n_estimators": [100, 200], + ... "max_depth": [4, 6, 8], + ... "learning_rate": [0.05, 0.1], + ... } + >>> result = tuner.tune( + ... X_train, t_train, y_train, + ... X_val, t_val, y_val, + ... param_grid=param_grid, + ... n_iter=20, + ... ) + >>> print(result.best_params) + """ + + def __init__( + self, + control_name: str, + treatment_names: list[str], + scoring: Literal["qini"] | ScoringFn = "top_decile", + random_seed: int = DEFAULT_RANDOM_SEED, + ): + self.control_name = control_name + self.treatment_names = treatment_names + self.random_seed = random_seed + + self.tuner_result = None + + # Set up scoring function + if scoring == "top_decile": + self._scorer = top_decile_scorer + elif scoring == "qini": + self._scorer = qini_scorer + elif callable(scoring): + self._scorer = scoring + else: + raise ValueError(f"Unknown scoring metric: {scoring}. Use 'qini' or a callable.") + + def _evaluate( + self, + pipeline: UpliftRegressorPipeline, + X: PandasDF, + t: Series, + y: Series, + ) -> float: + """Evaluate pipeline and return score.""" + tau = pipeline.predict(X).to_numpy(dtype=np.float32) + return self._scorer(tau, t, y, self.control_name, tuple(self.treatment_names)) + + def _train_and_score( + self, + params: dict[str, Any], + X_train: PandasDF, + t_train: Series, + y_train: Series, + X_val: PandasDF, + t_val: Series, + y_val: Series, + keep_cols: list[str] | None = None, + drop_cols: list[str] | None = None, + ) -> float: + """Train a model with given parameters and return validation score.""" + try: + pipeline = UpliftRegressorPipeline( + self.control_name, + *self.treatment_names, + keep_cols=keep_cols, + drop_cols=drop_cols, + random_seed=self.random_seed, + model_type="S", + **params, + ) + pipeline.fit(X_train, t_train, y_train) + return self._evaluate(pipeline, X_val, t_val, y_val) + except Exception: + _logger.exception("Training failed with params %s:", params) + return -np.inf + + def _sample_params( + self, + param_grid: dict[str, list[Any]] | None, + n_iter: int, + ) -> list[dict[str, Any]]: + """Sample parameter combinations for tuning.""" + grid = param_grid or DEFAULT_PARAM_GRID.copy() + + rng = np.random.RandomState(self.random_seed) + return list(ParameterSampler(grid, n_iter=n_iter, random_state=rng)) + + def tune( + self, + X_train: PandasDF, + t_train: Series, + y_train: Series, + X_val: PandasDF, + t_val: Series, + y_val: Series, + param_grid: dict[str, list[Any]] | None = None, + n_iter: int = 20, + keep_cols: list[str] | None = None, + drop_cols: list[str] | None = None, + verbose: bool = True, + ) -> TunerResult: + """ + Tune hyperparameters using random search. + + Parameters + ---------- + X_train : PandasDF + Training features. + t_train : Series + Training treatment assignments. + y_train : Series + Training outcomes. + X_val : PandasDF + Validation features. + t_val : Series + Validation treatment assignments. + y_val : Series + Validation outcomes. + param_grid : dict[str, list], optional + Parameter grid for the S-Learner model. + If not provided, a default grid is used. + n_iter : int, default=20 + Number of parameter combinations to try. + keep_cols : list[str], optional + Columns to keep during preprocessing. + drop_cols : list[str], optional + Columns to drop during preprocessing. + verbose : bool, default=True + Whether to log progress. + + Returns + ------- + TunerResult + Object containing the best parameters, best score, and all results. + """ + param_samples = self._sample_params(param_grid, n_iter) + + results: list[dict[str, Any]] = [] + best_score = -np.inf + best_params: dict[str, Any] = {} + + for i, params in enumerate(param_samples): + score = self._train_and_score( + params, + X_train, + t_train, + y_train, + X_val, + t_val, + y_val, + keep_cols=keep_cols, + drop_cols=drop_cols, + ) + + results.append( + { + "params": dict(params), + "score": score, + } + ) + + if score > best_score: + best_score = score + best_params = dict(params) + if verbose: + _logger.info("Iter %d/%d: New best score: %.4f", i + 1, n_iter, score) + elif verbose: + _logger.info("Iter %d/%d: Score: %.4f", i + 1, n_iter, score) + + if verbose: + _logger.info("Best score: %.4f", best_score) + + self.tuner_result = TunerResult( + best_params=best_params, best_score=best_score, all_results=results + ) + return self.tuner_result + + def fit_best( + self, + X_train: PandasDF, + t_train: Series, + y_train: Series, + keep_cols: list[str] | None = None, + drop_cols: list[str] | None = None, + ) -> UpliftRegressorPipeline: + """ + Fit a pipeline with the best parameters found during tuning. + + Parameters + ---------- + X_train : PandasDF + Training features. + t_train : Series + Training treatment assignments. + y_train : Series + Training outcomes. + keep_cols : list[str], optional + Columns to keep during preprocessing. + drop_cols : list[str], optional + Columns to drop during preprocessing. + + Returns + ------- + UpliftRegressorPipeline + Fitted pipeline with the best parameters. + """ + pipeline = UpliftRegressorPipeline( + self.control_name, + *self.treatment_names, + keep_cols=keep_cols, + drop_cols=drop_cols, + random_seed=self.random_seed, + model_type="S", + **self.tuner_result.best_params, + ) + pipeline.fit(X_train, t_train, y_train) + return pipeline + + def fit_model_at_index( + self, + idx: int, + X_train: PandasDF, + t_train: Series, + y_train: Series, + keep_cols: Sequence[str] | None = None, + drop_cols: Sequence[str] | None = None, + ) -> UpliftRegressorPipeline: + """ + Fit a pipeline with the parameters at the given rank found during tuning. + + Parameters + ---------- + idx : int + Index of the model to fit (ordered by score descending). + X_train : PandasDF + Training features. + t_train : Series + Training treatment assignments. + y_train : Series + Training outcomes. + keep_cols : Sequence[str], optional + Columns to keep during preprocessing. + drop_cols : Sequence[str], optional + Columns to drop during preprocessing. + + Returns + ------- + UpliftRegressorPipeline + Fitted pipeline with the selected parameters. + """ + if idx < 0 or idx >= DEFAULT_TOP_N_MODELS: + raise ValueError( + f"Index out of range. Must be between 0 and {DEFAULT_TOP_N_MODELS - 1}. Got {idx}." + ) + + if self.tuner_result is None: + raise ModelNotFittedError("Tuner result is not set. Call tune() first.") + + result = self.tuner_result.top_n(DEFAULT_TOP_N_MODELS)[idx] + params = result.get("params", {}) + + _logger.info("Fitting model %d with params: %s", idx, params) + + pipeline = UpliftRegressorPipeline( + self.control_name, + *self.treatment_names, + keep_cols=keep_cols, + drop_cols=drop_cols, + random_seed=self.random_seed, + model_type="S", + **params, + ) + return pipeline.fit(X_train, t=t_train, y=y_train) + + def save(self, filepath: str | Path) -> Path: + """ + Save the tuner state to disk. + + Persists the tuner configuration and ``tuner_result`` so that + ``fit_best`` / ``fit_model_at_index`` can be called after loading + without re-running ``tune``. + + Parameters + ---------- + filepath : str or Path + Destination path. A ``.joblib`` extension is added if absent. + + Returns + ------- + Path + The path the file was written to. + + Raises + ------ + ModelNotFittedError + If ``tune`` has not been called yet. + """ + if self.tuner_result is None: + raise ModelNotFittedError("Nothing to save. Call tune() first.") + + filepath = Path(filepath) + if not filepath.suffix: + filepath = filepath.with_suffix(".joblib") + filepath.parent.mkdir(parents=True, exist_ok=True) + + import joblib + + state = { + "control_name": self.control_name, + "treatment_names": self.treatment_names, + "random_seed": self.random_seed, + "tuner_result": self.tuner_result, + } + joblib.dump(state, filepath) + _logger.info("Saved SLearnerTuner state to %s", filepath) + return filepath + + @classmethod + def load(cls, filepath: str | Path) -> "SLearnerTuner": + """ + Load a previously saved tuner state from disk. + + The returned instance has ``tuner_result`` populated so + ``fit_best`` / ``fit_model_at_index`` work immediately. + + Parameters + ---------- + filepath : str or Path + Path to the saved tuner file. + + Returns + ------- + SLearnerTuner + Reconstructed tuner with results ready. + + Raises + ------ + FileNotFoundError + If the file does not exist. + """ + filepath = Path(filepath) + if not filepath.exists(): + raise FileNotFoundError(f"Tuner file not found: {filepath}") + + import joblib + + state = joblib.load(filepath) + tuner = cls( + control_name=state["control_name"], + treatment_names=state["treatment_names"], + random_seed=state.get("random_seed", DEFAULT_RANDOM_SEED), + ) + tuner.tuner_result = state["tuner_result"] + _logger.info("Loaded SLearnerTuner state from %s", filepath) + return tuner diff --git a/multilift/uplift/tuner/_tlearner.py b/multilift/uplift/tuner/_tlearner.py new file mode 100644 index 0000000..2895bbd --- /dev/null +++ b/multilift/uplift/tuner/_tlearner.py @@ -0,0 +1,546 @@ +"""Hyperparameter tuner for T-Learner uplift models.""" + +import logging +from collections.abc import Sequence +from pathlib import Path +from typing import Any, Literal + +import numpy as np +from sklearn.model_selection import ParameterSampler + +from multilift.constants import ( + DEFAULT_PARAM_GRID, + DEFAULT_RANDOM_SEED, + DEFAULT_TOP_N_MODELS, +) +from multilift.exceptions import ModelNotFittedError +from multilift.typing import PandasDF, Series +from multilift.uplift.regressor import UpliftRegressorPipeline +from multilift.uplift.tuner._utils import ( + ScoringFn, + TunerResult, + qini_scorer, + top_decile_scorer, +) + +_logger = logging.getLogger(__name__) + + +class TLearnerTuner: + """ + Hyperparameter tuner for T-Learner uplift models. + + This tuner always tunes control and treatment models independently, + allowing the best model to have different hyperparameters for each. + You can provide a single param_grid (sampled independently for both) + or separate grids for control and treatment. + + Parameters + ---------- + control_name : str + Name of the control group. + treatment_names : list[str] + Names of the treatment groups. + scoring_treatment_names : list[str], optional + Names of the treatment groups to score on. + scoring : str or callable, optional + Scoring metric. If "qini" (default), uses Qini AUC. + If callable, should have signature: + `(tau, t, y, control_name, treatment_names) -> float` + random_seed : int, optional + Random seed for reproducibility. + + Examples + -------- + >>> tuner = TLearnerTuner("control", ["treatment_A", "treatment_B"]) + ... + >>> X_train, t_train, y_train = ... # get training data + >>> X_val, t_val, y_val = ... # get validation data + ... + >>> param_grid = { + ... "n_estimators": [100, 200], + ... "max_depth": [4, 6, 8], + ... "learning_rate": [0.05, 0.1], + ... } + >>> result = tuner.tune( + ... X_train, t_train, y_train, + ... X_val, t_val, y_val, + ... param_grid=param_grid, + ... n_iter=20, + ... ) + >>> print(result.best_params) + """ + + def __init__( + self, + control_name: str, + treatment_names: list[str], + scoring_treatment_names: list[str] | None = None, + scoring: Literal["qini", "top_decile"] | ScoringFn = "top_decile", + random_seed: int = DEFAULT_RANDOM_SEED, + ): + self.control_name = control_name + self.treatment_names = treatment_names + self.scoring_treatment_names = scoring_treatment_names or treatment_names.copy() + + if set(self.scoring_treatment_names) - set(self.treatment_names): + raise ValueError("scoring_treatment_names must be a subset of treatment_names") + + self.random_seed = random_seed + + self.tuner_result = None + + # Set up scoring function + if scoring == "top_decile": + self._scorer = top_decile_scorer + elif scoring == "qini": + self._scorer = qini_scorer + elif callable(scoring): + self._scorer = scoring + else: + raise ValueError(f"Unknown scoring metric: {scoring}. Use 'qini' or a callable.") + + def _evaluate( + self, + pipeline: UpliftRegressorPipeline, + X: PandasDF, + t: Series, + y: Series, + ) -> float: + """Evaluate pipeline and return score.""" + if self.treatment_names == self.scoring_treatment_names: + tau = pipeline.predict(X).to_numpy(dtype=np.float32) + else: + treatment_idxs = [ + self.treatment_names.index(name) for name in self.scoring_treatment_names + ] + _logger.info( + "Scoring with treatment names: %s, indices: %s", + self.scoring_treatment_names, + treatment_idxs, + ) + # Select only the rows with treatment in treatment_names + + allowed_recipes = [self.control_name, *self.scoring_treatment_names] + + tau = pipeline.predict( + X[t.isin(allowed_recipes)], treatment_indices=treatment_idxs + ).to_numpy(dtype=np.float32) + + return self._scorer( + tau, + t[t.isin(allowed_recipes)], + y[t.isin(allowed_recipes)], + self.control_name, + self.scoring_treatment_names, + ) + return self._scorer(tau, t, y, self.control_name, self.scoring_treatment_names) + + def _train_and_score( + self, + control_params: dict[str, Any], + treatment_params: dict[str, Any] | dict[str, dict[str, Any]], + X_train: PandasDF, + t_train: Series, + y_train: Series, + X_val: PandasDF, + t_val: Series, + y_val: Series, + keep_cols: Sequence[str] | None = None, + drop_cols: Sequence[str] | None = None, + ) -> float: + """Train a model with given parameters and return validation score.""" + try: + pipeline = UpliftRegressorPipeline( + self.control_name, + *self.treatment_names, + keep_cols=keep_cols, + drop_cols=drop_cols, + random_seed=self.random_seed, + model_type="T", + control_learner_params=control_params, + treatment_learner_params=treatment_params, + ) + pipeline.fit(X_train, t_train, y_train) + return self._evaluate(pipeline, X_val, t_val, y_val) + except Exception as e: + _logger.warning("Training failed with params %s: %s", control_params, e) + return -np.inf + + def _sample_params( + self, + param_grid: dict[str, list[Any]] | None, + control_param_grid: dict[str, list[Any]] | None, + treatment_param_grid: dict[str, list[Any]] | None, + n_iter: int, + independent_treatments: bool = False, + ) -> list[tuple[dict[str, Any], dict[str, Any] | dict[str, dict[str, Any]]]]: + """ + Sample parameter combinations for tuning. + + Parameters + ---------- + param_grid : dict, optional + Shared grid for control and treatment models. + control_param_grid : dict, optional + Grid for control model only. + treatment_param_grid : dict, optional + Grid for treatment models. + n_iter : int + Number of parameter combinations to sample. + independent_treatments : bool + If True, sample independently for each treatment group, + returning a dict-of-dicts for treatment params. + """ + if param_grid is not None: + ctrl_grid = param_grid + treat_grid = param_grid + else: + ctrl_grid = control_param_grid or DEFAULT_PARAM_GRID.copy() + treat_grid = treatment_param_grid or DEFAULT_PARAM_GRID.copy() + + if ctrl_grid is None: + ctrl_grid = DEFAULT_PARAM_GRID.copy() + if treat_grid is None: + treat_grid = DEFAULT_PARAM_GRID.copy() + + rng = np.random.RandomState(self.random_seed) + ctrl_samples = list(ParameterSampler(ctrl_grid, n_iter=n_iter, random_state=rng)) + + if not independent_treatments: + treat_samples = list(ParameterSampler(treat_grid, n_iter=n_iter, random_state=rng)) + return list(zip(ctrl_samples, treat_samples)) + + # Independent: sample separately for each treatment group + treatment_samples = { + name: list(ParameterSampler(treat_grid, n_iter=n_iter, random_state=rng)) + for name in self.treatment_names + } + + # ParameterSampler may return fewer than n_iter if the space is small + effective_n = min( + len(ctrl_samples), + *(len(s) for s in treatment_samples.values()), + ) + per_treatment: list[dict[str, dict[str, Any]]] = [ + {name: treatment_samples[name][i] for name in self.treatment_names} + for i in range(effective_n) + ] + + return list(zip(ctrl_samples[:effective_n], per_treatment)) + + def tune( + self, + X_train: PandasDF, + t_train: Series, + y_train: Series, + X_val: PandasDF, + t_val: Series, + y_val: Series, + param_grid: dict[str, list[Any]] | None = None, + control_param_grid: dict[str, list[Any]] | None = None, + treatment_param_grid: dict[str, list[Any]] | None = None, + n_iter: int = 20, + independent_treatments: bool = False, + keep_cols: Sequence[str] | None = None, + drop_cols: Sequence[str] | None = None, + verbose: bool = True, + ) -> TunerResult: + """ + Tune hyperparameters using random search. + + Parameters + ---------- + X_train : PandasDF + Training features. + t_train : Series + Training treatment assignments. + y_train : Series + Training outcomes. + X_val : PandasDF + Validation features. + t_val : Series + Validation treatment assignments. + y_val : Series + Validation outcomes. + param_grid : dict[str, list], optional + Shared parameter grid for both control and treatment models. + If provided, control_param_grid and treatment_param_grid are ignored. + control_param_grid : dict[str, list], optional + Parameter grid for control model only. + treatment_param_grid : dict[str, list], optional + Parameter grid for treatment model only. + n_iter : int, default=20 + Number of parameter combinations to try. + independent_treatments : bool, default=False + If True, hyperparameters are sampled independently for each + treatment group, allowing every treatment model to have its own + configuration. If False, a single set of treatment parameters + is shared across all treatment models. + keep_cols : Sequence[str], optional + Columns to keep during preprocessing. + drop_cols : Sequence[str], optional + Columns to drop during preprocessing. + verbose : bool, default=True + Whether to log progress. + + Returns + ------- + TunerResult + Object containing the best parameters, best score, and all results. + + Notes + ----- + Control and treatment models are always tuned independently, even when + using a shared ``param_grid``. This allows the best model to have + different hyperparameters for control vs treatment. + + When ``independent_treatments=True``, treatment parameters in the + results are stored as a dict-of-dicts keyed by treatment name, + and the pipeline receives per-treatment learner configurations. + + If no grids are provided, a default grid is used for both. + """ + param_pairs = self._sample_params( + param_grid, + control_param_grid, + treatment_param_grid, + n_iter, + independent_treatments=independent_treatments, + ) + + results: list[dict[str, Any]] = [] + best_score = -np.inf + best_params: dict[str, Any] = {} + + for i, (ctrl_params, treat_params) in enumerate(param_pairs): + score = self._train_and_score( + ctrl_params, + treat_params, + X_train, + t_train, + y_train, + X_val, + t_val, + y_val, + keep_cols=keep_cols, + drop_cols=drop_cols, + ) + + # Normalize treat_params for storage + if isinstance(treat_params, dict) and all( + isinstance(v, dict) for v in treat_params.values() + ): + stored_treat = {k: dict(v) for k, v in treat_params.items()} + else: + stored_treat = dict(treat_params) + + results.append( + { + "control_params": dict(ctrl_params), + "treatment_params": stored_treat, + "score": score, + } + ) + + if score > best_score: + best_score = score + best_params = { + "control_learner_params": dict(ctrl_params), + "treatment_learner_params": stored_treat, + } + if verbose: + _logger.info("Iter %d/%d: New best score: %.4f", i + 1, n_iter, score) + elif verbose: + _logger.info("Iter %d/%d: Score: %.4f", i + 1, n_iter, score) + + if verbose: + _logger.info("Best score: %.4f", best_score) + + self.tuner_result = TunerResult( + best_params=best_params, best_score=best_score, all_results=results + ) + return self.tuner_result + + def fit_best( + self, + X_train: PandasDF, + t_train: Series, + y_train: Series, + keep_cols: Sequence[str] | None = None, + drop_cols: Sequence[str] | None = None, + ) -> UpliftRegressorPipeline: + """ + Fit a pipeline with the best parameters found during tuning. + + Parameters + ---------- + X_train : PandasDF + Training features. + t_train : Series + Training treatment assignments. + y_train : Series + Training outcomes. + keep_cols : Sequence[str], optional + Columns to keep during preprocessing. + drop_cols : Sequence[str], optional + Columns to drop during preprocessing. + + Returns + ------- + UpliftRegressorPipeline + Fitted pipeline with the best parameters. + """ + pipeline = UpliftRegressorPipeline( + self.control_name, + *self.treatment_names, + keep_cols=keep_cols, + drop_cols=drop_cols, + random_seed=self.random_seed, + model_type="T", + **self.tuner_result.best_params, + ) + pipeline.fit(X_train, t_train, y_train) + return pipeline + + def fit_model_at_index( + self, + idx: int, + X_train: PandasDF, + t_train: Series, + y_train: Series, + keep_cols: Sequence[str] | None = None, + drop_cols: Sequence[str] | None = None, + ) -> UpliftRegressorPipeline: + """ + Fit a pipeline with the best parameters for the given index found during tuning. + + Parameters + ---------- + idx : int + Index of the model to fit. (Ordered by score descending) + X_train : PandasDF + Training features. + t_train : Series + Training treatment assignments. + y_train : Series + Training outcomes. + keep_cols : Sequence[str], optional + Columns to keep during preprocessing. + drop_cols : Sequence[str], optional + Columns to drop during preprocessing. + """ + if idx < 0 or idx >= DEFAULT_TOP_N_MODELS: + raise ValueError( + f"Index out of range. Must be between 0 and {DEFAULT_TOP_N_MODELS - 1}. Got {idx}." + ) + + if self.tuner_result is None: + raise ModelNotFittedError("Tuner result is not set. Call tune() first.") + + params = self.tuner_result.top_n(DEFAULT_TOP_N_MODELS)[idx] + control_params = params.get("control_params", {}) + treatment_params = params.get("treatment_params", {}) + + _logger.info( + "Fitting model %d with control params: %s and treatment params: %s", + idx, + control_params, + treatment_params, + ) + + pipeline = UpliftRegressorPipeline( + self.control_name, + *self.treatment_names, + keep_cols=keep_cols, + drop_cols=drop_cols, + random_seed=self.random_seed, + model_type="T", + control_learner_params=control_params, + treatment_learner_params=treatment_params, + ) + return pipeline.fit(X_train, t=t_train, y=y_train) + + def save(self, filepath: str | Path) -> Path: + """ + Save the tuner state to disk. + + Persists the tuner configuration and ``tuner_result`` so that + ``fit_best`` / ``fit_model_at_index`` can be called after loading + without re-running ``tune``. + + Parameters + ---------- + filepath : str or Path + Destination path. A ``.joblib`` extension is added if absent. + + Returns + ------- + Path + The path the file was written to. + + Raises + ------ + ModelNotFittedError + If ``tune`` has not been called yet. + """ + if self.tuner_result is None: + raise ModelNotFittedError("Nothing to save. Call tune() first.") + + filepath = Path(filepath) + if not filepath.suffix: + filepath = filepath.with_suffix(".joblib") + filepath.parent.mkdir(parents=True, exist_ok=True) + + import joblib + + state = { + "control_name": self.control_name, + "treatment_names": self.treatment_names, + "scoring_treatment_names": self.scoring_treatment_names, + "random_seed": self.random_seed, + "tuner_result": self.tuner_result, + } + joblib.dump(state, filepath) + _logger.info("Saved TLearnerTuner state to %s", filepath) + return filepath + + @classmethod + def load(cls, filepath: str | Path) -> "TLearnerTuner": + """ + Load a previously saved tuner state from disk. + + The returned instance has ``tuner_result`` populated so + ``fit_best`` / ``fit_model_at_index`` work immediately. + + Parameters + ---------- + filepath : str or Path + Path to the saved tuner file. + + Returns + ------- + TLearnerTuner + Reconstructed tuner with results ready. + + Raises + ------ + FileNotFoundError + If the file does not exist. + """ + filepath = Path(filepath) + if not filepath.exists(): + raise FileNotFoundError(f"Tuner file not found: {filepath}") + + import joblib + + state = joblib.load(filepath) + tuner = cls( + control_name=state["control_name"], + treatment_names=state["treatment_names"], + scoring_treatment_names=state.get("scoring_treatment_names"), + random_seed=state.get("random_seed", DEFAULT_RANDOM_SEED), + ) + tuner.tuner_result = state["tuner_result"] + _logger.info("Loaded TLearnerTuner state from %s", filepath) + return tuner diff --git a/multilift/uplift/tuner/_utils.py b/multilift/uplift/tuner/_utils.py new file mode 100644 index 0000000..0832388 --- /dev/null +++ b/multilift/uplift/tuner/_utils.py @@ -0,0 +1,135 @@ +"""Shared utilities: TunerResult dataclass and scoring functions.""" + +import logging +from collections.abc import Callable, Sequence +from dataclasses import dataclass, field +from typing import Any + +import numpy as np +import pandas as pd + +from multilift.typing import NDArray, PandasDF, Series +from multilift.uplift.eval import UpliftExploreEvaluator, compute_qini + +_logger = logging.getLogger(__name__) + +# Type alias for scoring function +ScoringFn = Callable[[np.ndarray, Series, Series, str, Sequence[str]], float] + + +def qini_scorer( + tau: NDArray, t: Series, y: Series, control_name: str, treatment_names: Sequence[str] +) -> float: + """ + Score based on Qini AUC. + + Parameters + ---------- + tau : np.ndarray + Predicted uplift values (n_samples, n_treatments). + t : Series + Treatment assignments. + y : Series + Observed outcomes. + control_name : str + Name of control group. + treatment_names : tuple[str, ...] + Names of treatment groups. + + Returns + ------- + float + Qini AUC score. + """ + qini_auc, _ = compute_qini(tau, t, y, control_name, *treatment_names) + return qini_auc + + +def top_decile_scorer( + tau: NDArray, t: Series, y: Series, control_name: str, treatment_names: Sequence[str] +): + """ + Score based on decile uplift. + + Parameters + ---------- + tau : np.ndarray + Predicted uplift values (n_samples, n_treatments). + t : Series + Treatment assignments. + y : Series + Observed outcomes. + control_name : str + Name of control group. + treatment_names : tuple[str, ...] + Names of treatment groups. + + Returns + ------- + float + Decile uplift score. + """ + _evaluator = UpliftExploreEvaluator(control_name, *treatment_names) + _logger.info("Scoring on available treatments: %s, shape: %s", t.unique().tolist(), tau.shape) + return _evaluator.metric_avg_value_at_coverage(t, y, tau, top_fraction=0.1) + + +@dataclass +class TunerResult: + """Container for hyperparameter tuning results.""" + + best_params: dict[str, Any] + best_score: float + all_results: list[dict[str, Any]] = field(default_factory=list) + + @staticmethod + def _is_per_treatment(params: dict[str, Any]) -> bool: + """Check if treatment_params is a per-treatment dict-of-dicts.""" + return bool(params) and all(isinstance(v, dict) for v in params.values()) + + def to_dataframe(self) -> PandasDF: + """ + Convert results to a DataFrame. + + Returns + ------- + PandasDF + DataFrame with columns for each hyperparameter and the score. + + For per-treatment results, columns are prefixed with + ``treatment_{group}_{param}``. + """ + if not self.all_results: + return pd.DataFrame() + + rows = [] + for result in self.all_results: + row: dict[str, Any] = {"score": result["score"]} + # S-Learner format (single params dict) + for k, v in result.get("params", {}).items(): + row[k] = v + # T-Learner control params + for k, v in result.get("control_params", {}).items(): + row[f"control_{k}"] = v + # T-Learner treatment params (flat or per-treatment) + treat_params = result.get("treatment_params", {}) + if self._is_per_treatment(treat_params): + for group, params in treat_params.items(): + for k, v in params.items(): + row[f"treatment_{group}_{k}"] = v + else: + for k, v in treat_params.items(): + row[f"treatment_{k}"] = v + rows.append(row) + + return pd.DataFrame(rows).sort_values("score", ascending=False).reset_index(drop=True) + + @property + def top_n(self) -> Callable[[int], list[dict[str, Any]]]: + """Return top N results.""" + + def _top_n(n: int = 5) -> list[dict[str, Any]]: + sorted_results = sorted(self.all_results, key=lambda x: x["score"], reverse=True) + return sorted_results[:n] + + return _top_n diff --git a/poetry.lock b/poetry.lock new file mode 100644 index 0000000..10aa5b4 --- /dev/null +++ b/poetry.lock @@ -0,0 +1,3619 @@ +# This file is automatically @generated by Poetry 2.4.1 and should not be changed by hand. + +[[package]] +name = "alabaster" +version = "0.7.16" +description = "A light, configurable Sphinx theme" +optional = false +python-versions = ">=3.9" +groups = ["docs"] +files = [ + {file = "alabaster-0.7.16-py3-none-any.whl", hash = "sha256:b46733c07dce03ae4e150330b975c75737fa60f0a7c591b6c8bf4928a28e2c92"}, + {file = "alabaster-0.7.16.tar.gz", hash = "sha256:75a8b99c28a5dad50dd7f8ccdd447a121ddb3892da9e53d1ca5cca3106d58d65"}, +] + + +[[package]] +name = "babel" +version = "2.18.0" +description = "Internationalization utilities" +optional = false +python-versions = ">=3.8" +groups = ["docs"] +files = [ + {file = "babel-2.18.0-py3-none-any.whl", hash = "sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35"}, + {file = "babel-2.18.0.tar.gz", hash = "sha256:b80b99a14bd085fcacfa15c9165f651fbb3406e66cc603abf11c5750937c992d"}, +] + +[package.extras] +dev = ["backports.zoneinfo ; python_version < \"3.9\"", "freezegun (>=1.0,<2.0)", "jinja2 (>=3.0)", "pytest (>=6.0)", "pytest-cov", "pytz", "setuptools", "tzdata ; sys_platform == \"win32\""] + + +[[package]] +name = "black" +version = "26.5.1" +description = "The uncompromising code formatter." +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "black-26.5.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:9942db8888e06943c5dde66ca0037dcff82a2a4ec1ad0ada9e0d2ee9d9823893"}, + {file = "black-26.5.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:89c93167a74d3a75dfaa38a5c7cca015537d5820dd7f17d63267d674a61cae90"}, + {file = "black-26.5.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22f2cd76d069cc54c71f10360744ba8983fbb616903b4304a85b734915c8e1b4"}, + {file = "black-26.5.1-cp310-cp310-win_amd64.whl", hash = "sha256:87ed5c6f450580a2f6790bc7cbfb016dfc73bc750249762268a3695361315eef"}, + {file = "black-26.5.1-cp310-cp310-win_arm64.whl", hash = "sha256:58b4bd92cf88aacf83d88479c8f9caee044b1ec55f2451a337354a7ea2590a22"}, + {file = "black-26.5.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:96ae2c733b2aabdd9986e2c5df628ff3473676cd1c5faded1ff496cf6d74083c"}, + {file = "black-26.5.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:0e48b87e03bf109288e55cfceadcfa15ff5470aca2851a851950ed2926f450d7"}, + {file = "black-26.5.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5119fa92ae61f786e8c3662fd60aece1d0a2dd5cca5d0c79417a95e7a4272a59"}, + {file = "black-26.5.1-cp311-cp311-win_amd64.whl", hash = "sha256:30d3c14661f2792e9142cce3eeeb1cbc175b3eb5f733be0c8eeb99651e52b0c3"}, + {file = "black-26.5.1-cp311-cp311-win_arm64.whl", hash = "sha256:1ef92b76f7733f282fd096ea406200b5a286c42947412b0eaff3a74e3616cefe"}, + {file = "black-26.5.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4ad6fa01f941920f54f2bbb35f3df7673428a0ef98a0b0840c2eaef3b110efa8"}, + {file = "black-26.5.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3915f256e75a2d7cf88d8953d37f780455dc586cc72dee059c528fe77f581217"}, + {file = "black-26.5.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9d98d4137277c75dfb898ec8d846c4fd68ba1e9cf77f95e2865c203dc18f4c3d"}, + {file = "black-26.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:a1dca32d9f1784af512a13410ec204c6f7f0aa9797a111c42e1c03449821c264"}, + {file = "black-26.5.1-cp312-cp312-win_arm64.whl", hash = "sha256:1037d5ac7b7b310b2632ad867ec8d0e4c4819dcdb0b820f63135da746a24e418"}, + {file = "black-26.5.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2b36cf2ddf5566e205f6535f782a62194a184d33e175b64ae8c40b1737522be3"}, + {file = "black-26.5.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:1f7ea64ebfa01b50f693508fc39f875e264446d3b097088f84f203b9d09618a0"}, + {file = "black-26.5.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ecb3e624844c798144e9bd986954e0adc81d8911a1f30f375e1252fe26e8c294"}, + {file = "black-26.5.1-cp313-cp313-win_amd64.whl", hash = "sha256:e1a26503279b6b310669fb0b219c39e4820b77e8189fe80f522bb511f247db0a"}, + {file = "black-26.5.1-cp313-cp313-win_arm64.whl", hash = "sha256:5c34b25da232ead53a6f335b76dbea124f4d152ad568b9080d6f944bc2b34b52"}, + {file = "black-26.5.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:e88976690a64b0af98312ca958415849cb42423423c5f2ee74af4b49a97a2168"}, + {file = "black-26.5.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:32d5ea7f6c8bdfa6e648326ebca1f02b0764e2a029edc6f8dce2627e19d468c3"}, + {file = "black-26.5.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ea8d16dc41655aa113cd64665e7219446cd7e4ff2248d7178eaa905190c86b18"}, + {file = "black-26.5.1-cp314-cp314-win_amd64.whl", hash = "sha256:577f21094ea469ef92ec1adaf2c9441a226d2144d01a5be2fa823cecf6543e50"}, + {file = "black-26.5.1-cp314-cp314-win_arm64.whl", hash = "sha256:ed1a20af114c301a0269bf01163d51dbef72737fd65f850001e7cbe7f3c7abae"}, + {file = "black-26.5.1-py3-none-any.whl", hash = "sha256:4ed7f7da04046d2e488437170797d3b4a4ad83906683bcb7dfc68b673bbce5e2"}, + {file = "black-26.5.1.tar.gz", hash = "sha256:dd321f668053961824bcc1be1cc1df748b2d7e4fa28086b08331e577b0100a73"}, +] + +[package.dependencies] +click = ">=8.0.0" +mypy-extensions = ">=0.4.3" +packaging = ">=22.0" +pathspec = ">=1.0.0" +platformdirs = ">=2" +pytokens = ">=0.4.0,<0.5.0" +tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} +typing-extensions = {version = ">=4.0.1", markers = "python_version < \"3.11\""} + +[package.extras] +colorama = ["colorama (>=0.4.3)"] +d = ["aiohttp (>=3.10)"] +jupyter = ["ipython (>=7.8.0)", "tokenize-rt (>=3.2.0)"] +uvloop = ["uvloop (>=0.15.2) ; sys_platform != \"win32\"", "winloop (>=0.5.0) ; sys_platform == \"win32\""] + + +[[package]] +name = "certifi" +version = "2026.7.22" +description = "Python package for providing Mozilla's CA Bundle." +optional = false +python-versions = ">=3.7" +groups = ["docs"] +files = [ + {file = "certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775"}, + {file = "certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55"}, +] + + +[[package]] +name = "cfgv" +version = "3.5.0" +description = "Validate configuration and produce human readable error messages." +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "cfgv-3.5.0-py2.py3-none-any.whl", hash = "sha256:a8dc6b26ad22ff227d2634a65cb388215ce6cc96bbcc5cfde7641ae87e8dacc0"}, + {file = "cfgv-3.5.0.tar.gz", hash = "sha256:d5b1034354820651caa73ede66a6294d6e95c1b00acc5e9b098e917404669132"}, +] + + +[[package]] +name = "charset-normalizer" +version = "3.5.1" +description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." +optional = false +python-versions = ">=3.7" +groups = ["docs"] +files = [ + {file = "charset_normalizer-3.5.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:d1ee1e296209fdce05b81b663250eefa02213a2da7b41bf26f7829b8ba3545aa"}, + {file = "charset_normalizer-3.5.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e9fbdce1e47394b09bc9f26ab117dfc8d6491977a11d86f592bb42c779db2fda"}, + {file = "charset_normalizer-3.5.1-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:00668ebb0609751758682eb0b5857e7c35b9f00e84dfdef062e103244ec94d45"}, + {file = "charset_normalizer-3.5.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ba2f37ee79e6338845261a3c5b1784e5d1acdff2c0785b284f1b633033d136ab"}, + {file = "charset_normalizer-3.5.1-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ce854f5f478050ade5a238731c4ca985a7d3b3cb53ff600a9b5c3b689b5f0a7a"}, + {file = "charset_normalizer-3.5.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:96eefc178f8636b9c760c5829345307fd81cfae9ab1e80997dbddeb0f54ee9a3"}, + {file = "charset_normalizer-3.5.1-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:366ec70f5547c640d3ce1985722490f23faf4eb5216a7eeba78277490e78dacb"}, + {file = "charset_normalizer-3.5.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:950f23cb393f85543777b0433f082cddd25b51ab398eac7971146495679efe5f"}, + {file = "charset_normalizer-3.5.1-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:c1dcc36dcb96abc02236e182d17e0f71430152a6c2c7447421da2d2dc144edea"}, + {file = "charset_normalizer-3.5.1-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:07ffd07412fc5d5e84cd8952acf9ff7e4ed7a708e69d1bada19d8ba91711353f"}, + {file = "charset_normalizer-3.5.1-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:f5542f9b941279d82d41eb0aa9f98eba36fe4df5c7086c651df7944935b37182"}, + {file = "charset_normalizer-3.5.1-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:a545775cfe815855ea32d7c27731d79da358ef2055b4a25830231b1622dd18aa"}, + {file = "charset_normalizer-3.5.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:494b70049a4d69aec6e8137c13af4cf8db8c9f9820a1392ac293b0dd2987a818"}, + {file = "charset_normalizer-3.5.1-cp310-cp310-win32.whl", hash = "sha256:94fbf1c0c6cc0d3d5e50f9a9313a8cdca90dd696d34b381cd1704f8c9e939f20"}, + {file = "charset_normalizer-3.5.1-cp310-cp310-win_amd64.whl", hash = "sha256:be47f99644b208bff7766314013f9acf57b056b04191d570d68ad14022cf5b1d"}, + {file = "charset_normalizer-3.5.1-cp310-cp310-win_arm64.whl", hash = "sha256:a6d095662e73e74f0a49988e0593373e243e3a52e27bfeea0a859e88acf4a0f5"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:eda059b6bc8bc0812d626fd91a7ce01bf583df0a61296eff390fd94141a34e30"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:aa2bb0b37202dca27175591f761108b5d34096ade1191ffe4808bdf6b1571488"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0b2b1b3fa5670c127b246df1d0c059defd41f689a868a3b9d79df9b1cac42d22"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6e5e4d73d588ca5ed09df1b7dcd1b203d1df3c542e3f50d126c947d432b10731"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b54e7e13267d49ffbfe68e25b3cbd774dab38fa37238f71265e91b36146eb21c"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c7b742bf31c88566b4bb6335a7f393bb322e580b6bb98df7bd0c25e6e3519ce8"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6ba32c4d2abf1d2fe7cf27d280f4cca5664233b0f885549c7761719eb977f486"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0722590aabf9dc6a6c0343d523c05458fa2b5047dbe6302fd526bb570600753f"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:aa1099b956fb795e686d073568f6dc002a0bb89765ea6d5b055dd7d9bf1b116c"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:bd6c173f04743d483881bffa1478d5a4624475b8cd1d2194956a75548e191c18"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:f298e218441525d3794428b4c8b8fb8662c6d3ea79925d4807ee6b9a96a3bca5"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:6e2912d4babbc65196ac13c2f53468dc57fb8b9c25ef913e8c59ddf7c6dc0e1b"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:3d27167433c0d5f18dc850f07d0b3816221984fecdc405d6c157a6f0b8f8e9e6"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-win32.whl", hash = "sha256:ac00177c4831ffa650f8609e4bdddd5fe09c03b1c0c47acece7e6ea20421598b"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-win_amd64.whl", hash = "sha256:f9b1e28d0e8dbfa858abdba91d6b547beaf2df1a59bec6da6faae7b96a4991a9"}, + {file = "charset_normalizer-3.5.1-cp311-cp311-win_arm64.whl", hash = "sha256:ae31a1a1db2ee6cc2942fccaf695c934bc7f3db9f2133a3fef1f367cf1a4ab10"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:5b6d1386bf0096d26d3a863dc0a487a5b4eb9aa93cf5ba69683d29dde6b9d60f"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4582c27e8c889d64811987b5967fbd3ae0c823fe1fd933b543d55ac20bb475fa"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1d1c7a53a6c2103925cdd6d7229f8c567379f211c869793df679f2e9f738c369"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e6621fb2a4988d6e53eedc455e5903e2679f3967b8acb3d639f1b63c14a2e893"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7c0c10730342b0c9b35dd1d619beb8214e520bd96a1f870f452680b238aab3e0"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b9af956078716df40d985fb0dfeb2c2120c5ca92ba4ff4b388acfd01cdc14d08"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f9f8405c2c758532c74fed975dbee57be1f31a6e865c031870c79a6ed3212ada"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:96fef3e886d6a9874b14f27fc193fbdc69d5d8035783d86aa4e1cea594e695f9"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:5d8531a6569d025f68e2321e7638fb7978f23db58e5f69f56913837aae03816e"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:aae2ee51122d3ae968a3837d97dc24a0aeebb0dea23694422cd172bd30017cd6"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:7235dc28fc6dd9d832ac7c7bce95367dedb85929f17368a0c2bee1e080b9acbf"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:4abdc5f9ad448c1ecbfae2974b820535d6bc6e7eef63babbab3d81cf46968c71"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ba501e667c17d8411f98e67a022d9604ef179aff0e459b7e292c796837c13573"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-win32.whl", hash = "sha256:cfa1c0cc3a8f9f53f1243a5a99ac36fd003880199383b37672e86ddda9cb07e2"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:3617ac3cfd8b9888f145ad89dd6e692285834b0201c6074a5eeaad3fd4d668c2"}, + {file = "charset_normalizer-3.5.1-cp312-cp312-win_arm64.whl", hash = "sha256:88e85ab89cb822c1e635f51d6d32e488f94e002e70e2f492bdb8b945543f345a"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:4f298bdadb8f0b9e5672877f647d1be9373ef5320c9e2f049795e26cad28b6a9"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-android_24_x86_64.whl", hash = "sha256:88ca277405c2d3b71c4e1c2ee0e7966e807bcba86a69d11e19ba199d18ae4491"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:9362dd90aa7dab48c0054a21187791ccf05473f7dba5d92b8033ae62164675e7"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:977cdbd483a9cff38179bea4fd754289a6f2195c7abd414aba85410b3e66cc5e"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:e90251c0c7bdd54a100a0dce3c07b7e637278c93af29dbf78ebb89a58c4bac7d"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:94d78ecec2605a8d0398b0f365d5f12a63248438516f5dac536a5eff7337df4a"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:d59b75732e9b6f27388e10c14b0259cc5f2e48c78627d185e6a177b58ad3cffe"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:0d929fc574b4d6fd9e7c0f5c2ede8716a41911923aa7fa5fce38e0818aa4a1ac"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:394fea06235c8543390050ed5f529187074b029fb027213f6c46ac11ab5d950e"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:62b55f6722735a6c472f88361cde6640608773d9443cebdbb51abf436a1fcdd3"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:fa48b1b63d639f9483e0633e092f5851e2348c352f1f9bb6c8182f87884ef876"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:c71fb0d56c920c269cd3e2e3fe7c610e3f1fdb21a6ce60efa6430ff63676cea6"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:485a0d363cafefcd2538a73c7c838daa2035f09b2c9f9b5e3133f80c6aeb84c2"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:5c0ea61a470e070686aa30892fed79e297d2c8d0ab46b8bcdf027d38c51da591"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:90b7481fb62fbe172c558bc6fd1c4c98d82004a54a7551f20e11ac9bf0b8708c"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:35fe081843b35aad20ffeccec3eeffbe637b15d14f3fb22cc1b59cd8ec17e93c"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:fd0350afdc3aabd5576f60ea109228bd5538139713c7b094c5cd27c73a98bc6f"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:9d9a0dc7cbe9bec24c3f767c9122c41fe5a1bc43f47cd099d00d393e09769de4"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-win32.whl", hash = "sha256:d63600d620ad0064c3a748b950ac5ea38a80190e5498532efefa4b7b3f1da1f3"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-win_amd64.whl", hash = "sha256:aea996a6aba25260827c9ea511d1addfde2da9eb686ac961838509086188b7e6"}, + {file = "charset_normalizer-3.5.1-cp313-cp313-win_arm64.whl", hash = "sha256:fd0a274c0e5f9a21565cd9d3dd749b61f96b7aa1e20a93aa1ba4029518f2e5c0"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:774d157f112367ff4abd29019f38f023c24e00e56edc7829c20e358a5a913ad8"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-android_24_x86_64.whl", hash = "sha256:26422d45fd13551cf564c58932f7d72b4f58b93b0fcf18c35ba6be12b46bb102"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:09a7bba9f739468c8e78c36a75c33768e53cb1959fc638f510454c14683f00d5"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4c9548dc78002099910abaebc0a72ac58b7d30931869e0351c09b507dff4ece3"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:c428c6c31eb5f4277d7f8eccaf767fbd548ddd5ce3c8b4f4cbbfab3d96b5904c"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2f06b7eae9dbe77fe1d644ca244dad508de8d302870a43f3c559b521270938a0"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6b7430cf5728e68f6c462254009a6ef4086e1bea43cf2f57aa9c55fb4f50ff96"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ab743e9bc90c1f73552ec33e10e3331315acd2c397b36065b591b0181de533cc"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f6f7deae3feb4edfa2efaf7c574fe88cbf055038a6abdb40188e4fff66d5699f"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:15f024313246a4ed976c60f440bb8d257815513a681d212ff74fd46f7d715a90"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:823f82903d189af463d7df250ef1f7f696f3cee08cc8d91deb565e8d425f6506"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:01e93745f7f219b703b60ba7afead36cfc4242782be5af484673fc500df12da5"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:329fc3ccb63ad22d867d84c2adea759a64079a37ba4a343433b02c7a2816871e"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:bb57753e36e4855b8ca375069482250a6246372331a3e4f3407eaebb007443f5"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:fce8cbd4997efeb450bd298b54f755dcdff18d496f7a5ddbb4867c6d7c88fdc3"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:6c9cdde8becb25a7fde49924511aa2644d6f8081cc8df8e9452724303348d8e3"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9ac4444d8d4fd4c4bd08bf451ed3167aa9e7ec6cdb41b648794f1d1103652e36"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:f03ac127268b43ef4fe9e6ab6794a6794b49485a0cc0c1db79876d2f33f75bc7"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-win32.whl", hash = "sha256:1f5883d77fd409a261abb5dc8ccbe335720d798b1de4abb3b1d47ccbbc76b53b"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-win_amd64.whl", hash = "sha256:c658c50ac0c98cd755a2dd50b7977d3bca7df401dcc47fbdfa87db53ef7d4e8b"}, + {file = "charset_normalizer-3.5.1-cp314-cp314-win_arm64.whl", hash = "sha256:4bea7f8ebe90bbd7f0e4a2de42ca6924ba23e3e76418c408ff82f1d46fabd687"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:fbc597639158fd7c14d55e808718848319540f51b0e6746e3eefa59723a4a348"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e71c909f353863b2b89c83de2ebed71ea6d0df8a6ef65a128193c5e650766bef"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:7ac76cf9afd34929d76eb7fcb63be476a4853d8a96f0dcf2d0db68a0cbdf9885"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a3a370082ce34d0612f421e15fe011c53bb1feff21a26d06ad4fb244dab5a375"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:256dd4d85d9e4dc595e2bc983c980e73f62ddeb3165c58b4c3dfe78c5c8548c1"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:58d4aa13a59c969dbfdf9e6a9560e242cbfd9e8a8f50c2747714df1a423adf65"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0c6dfb5ca6723eeed15aa8e564a014d69fcb8812f94eef11fe3631e0508199f5"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c010f5581d9c612804cc59fcf7b524b707fbcb72828551237ab545bb5c7034af"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:52ec005752a56ae79547a05c0139ca2501a0c866390b6115008456b9f0e7cde1"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:2bced4061f000f7187254a02ad3433ae17eaf991747ceea2f478422590a5bba9"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:9eea3ab2597a5e65fe65296e2d6a84570845a6b55532d90333d740d48bbc850a"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:496846868fea80e479324862fa877f02411f2fd0f83b79ccee2607aa68b2a032"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:85d5855daafc240cc045c026d7a15fd198a09b0fc8ff6f5ecbb5297b509cb11e"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-win32.whl", hash = "sha256:58d3e12c88e0950bca850ae1f7c256055c097639c2edb9eb123af9807d8b15e4"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-win_amd64.whl", hash = "sha256:acaf604462bf330b0d07e7a07c1d6e4adac79e5fb13e9c5140590542cafacc00"}, + {file = "charset_normalizer-3.5.1-cp314-cp314t-win_arm64.whl", hash = "sha256:fdb8a068947befafba9952162645dc2fecaeb400e64584829ed5e9b2fbe21a7f"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:9085f87b0e38a2b92b8923059b4e8789fe40d9279712d15dcc670048d77079af"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2679de311c7946dde5d3b6f44941844133ff5c7cb86099c0061ab1e8901c20a8"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:baf3775a2635e5a11fbd5e4e64ee69c7e86875d224a5c72aca4c141064589a90"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8ac8c94b6539074e0f40899301273ac8402b9b3e01c7b7ba269ff30340aaaf20"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8fe532b3c966d1fb794e0698e4589d0444017ae77fc0b31edea13c0e35bcc449"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5c84bec0ab5ae0c64bfe73a7d2adcb5ce73b467523fc27fd6a28ab2aa6cbe35a"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:854066be00447fa8de2ccbbe893e2ffc4b123ef16d897af794c1e18bd4a714b0"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:21b82d8082f6f5e7f456ef0bd16323d08de1266efbfeb476e64b2a91d1471a4e"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:838648accb3a7fd9803fd45c87bce8509648eb0c11bc34e216141300977244f2"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:195ce897c6153c0700078142cf8efe3e6454ca4cf4357499e4078dfd83396626"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:978eab16f55b4ab2c2a745be9a0a840bf8f09a7f227d9c76eb30214d078865a5"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:cc0329df4caaceb950d2f580b5ac716a377f7059624a0bafaeaf8a218c6ed774"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:687c9ca3035544b113bea2055e180af96fb63c0c476e22a9180f51925186e7b7"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-win32.whl", hash = "sha256:706bfd38730a5ac7a365793269a00f4e988178cec121391f4248d84ad8c972e9"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-win_amd64.whl", hash = "sha256:92caef967d287a407085d61176fce4012b1dd62daed4eb6d5ceb26d3d2538712"}, + {file = "charset_normalizer-3.5.1-cp315-cp315-win_arm64.whl", hash = "sha256:5fc45d653ea8c9a20479167e11d4a0f8cb2fa3470737ab6f9c827532313187b7"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:59171c6e45bf07d0d5cab3b0bf81d945035530f6873398b3b531c31184d46663"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9dbdd9205662134957cf0c324f639bdc5031c0ca056e2369e238db75187c0f11"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e4b018dc5a0eee4676e38fe84a47a427816c590b93b55d9025274ec4d6ffc2dc"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ced3fdd71aaa83ce593746c2edb42b7a59cb4c19c8b5c407781c72e493aae55a"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:19a3dd5aa73cef1c99687c4fc57db016a9c17104ae1185da88ba566a5d3bebe4"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cc5d36d96478aa9c60654bd932525bf32964c62a7281eafdf16d85003a8d6004"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:04368edf83514385ffc3e1cfd4546e595f4f1272dd23ba437a93a9cc3741d47b"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:9b5db6052055d34d41230fb78d7c439c23dc536a9896f6cb039e8dd92cfc1263"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:252d099029bcbea642f2a06c4ed5046bdf8b5a8150b64afa5e027e88b106e5ee"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:6199d5606e2bbf2b096cf64d03f8b6790c91081d5ac866b8e7bb6422738cc60c"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:77efcff2b23071c349402ac1066667a3d011f62398d81408c9b88ad991747c9e"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:a5cbd90ecf0fc62e64726917ad083b73001f0563657a87ec3c0b504e277dc90d"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:4d26f14f041e83dd8edfd61f4cd4fa7285d31798b5bf1f28e70c367ba6c41d61"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-win32.whl", hash = "sha256:ac13b004224fb341e1e25a1ed5e19d32f57cdb2a403e01f003b46f051a550f6f"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-win_amd64.whl", hash = "sha256:35aea775dc2bd5f54cd84a1cd2696cc3207c479cb9cf0bd346f0d343e4300ddb"}, + {file = "charset_normalizer-3.5.1-cp315-cp315t-win_arm64.whl", hash = "sha256:fb78f6e7fcd8ad785d28cd577168bc1aaee827b25bb8755638f694794ea98f0a"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:41876ee62a3dddf48ff1121ad8f0798032aa03f2fd35f21f34a4cab14f18d8d2"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:a6dac12ff6b846103483683f60c5f8fee205121adc58ffd87e90a90a3af69e99"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cee5dd7c6fb5dd52a0fe2a740f9bc6e3593f5f8b1788bde49de02086f30182b2"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:343fb4f2821043bd87095f7b08a1a181febc8e36ac64212143bbfd0a0e1bc235"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ae4a097991662cd4fff0ddc74e0fe7874f82e00042fa0ea00855645ed0c79598"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4b599739b93b2cbeded49645ae3c8d1405c29ddfbceac1545c87a3f9580a9e96"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b39b69b347e5e47a3b5b8cfc005c68c1ba347474e3960236c4944a8ecd174962"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a2028475ba855475b8b4d3cfeb4994269c967aea8b9892dfba907f4263a863a3"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:36047af20e17097c3bb9476c2b7655f2f7aa51322c0ba58c07695bedf755a950"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:4c4fb141a727957c93edfe5c32a26ceb6b5f6461d67146e2d39f51e16170bea8"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:2f293479cce755c75f1697e87c409b7ae4c555c7dfecb6e988ad13abba943031"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:3588e376b3ea2eea84976f67273d679f229e24c66dce7b82ae45aef04ff6e072"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e199fb99720074809a7720f1c0b4d919eea8b87e88713e0f8f602f7bef543d9d"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-win32.whl", hash = "sha256:dd732602a7009217f658d5863d12d79d373a4de0eebc111094bcdd3bb8e0a6cc"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-win_amd64.whl", hash = "sha256:70055ff39b97c99e7ae40ea3e393fb62aa2e44dbd9b29f8d14f42fb0025c3959"}, + {file = "charset_normalizer-3.5.1-cp37-abi3-win_arm64.whl", hash = "sha256:87e4f41d375c0b9be2fb5251aee4b8a689169e134535aed81bf085c3b647451e"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:85de3134b5379856e323ba37c19c9256d39425f7b76a63af52b09fb4664c2e8f"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3e5e1224c0a6a90e05843e07adfec669edebec17801c67072f51e59561d63c0b"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:5e2d0e146dcb57034f8b97dc58d2d512cb90aba253960ce449f695fec6a82c6f"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e06efa066f7dbadbc84ebc126a97c452a6451dfcf589d89d788484949e1cf795"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:994e883d17c559cdfd38c84003c8b27d25424a1077272a17e7cd27bfe0bf57b2"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:789b8982559ae28dad2356519f841655756cdcd96616410590ae0b17454ee64f"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a951ad59cad9145664a730d3036b40b844e74d2d3683da40111463cd3a83845d"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:55261ac0d2941c42f196dd576f543d87a8ee03cd6f5e30dfb4d807b2e3b9121a"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:5ca0555312ae2fe82715cada7fac375530c2f3349e1eaa1bcb33d0283ac79a18"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:2e9cf9253119d8e5d111f05d71626786fd3d6193817316eab1ca088cdb8593cf"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-musllinux_1_2_riscv64.whl", hash = "sha256:433c5a81eade63b47e522303bad236f59dba55ea6951746f5558355eeed8c75d"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:13e3afe97712e8887cd516e960c63f0b93122971e5b5e4b2622fe7701771e838"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:eb12fb2ba69ffa05f8695f61c69e591dc4b4a12ac3757ac8af8adb259bf56d17"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-win32.whl", hash = "sha256:56490c595a28b1bb27dfc583e816152a9767721ef58b2c03b13f954d2f707420"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-win_amd64.whl", hash = "sha256:012a22b88a77ca2e59b98ac5889b0deb604147666032f45e6d6e217634d2550d"}, + {file = "charset_normalizer-3.5.1-cp39-cp39-win_arm64.whl", hash = "sha256:29880d17a8eb0b5cfdfd8944b468322928059aa35f1f5fa8ff22b149ec0b42f8"}, + {file = "charset_normalizer-3.5.1-py3-none-any.whl", hash = "sha256:6df0ec430f9a831772c23ca5a224cba36517a58a84bb32c32bb59a9fa67c47f6"}, + {file = "charset_normalizer-3.5.1.tar.gz", hash = "sha256:6117b84ea48435e5356dc737f5121485c30920ba43375fa7b434fd753df0eac3"}, +] + + +[[package]] +name = "click" +version = "8.5.0" +description = "Composable command line interface toolkit" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "click-8.5.0-py3-none-any.whl", hash = "sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360"}, + {file = "click-8.5.0.tar.gz", hash = "sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34"}, +] + + +[[package]] +name = "cloudpickle" +version = "3.1.2" +description = "Pickler class to extend the standard pickle.Pickler functionality" +optional = false +python-versions = ">=3.8" +groups = ["main"] +files = [ + {file = "cloudpickle-3.1.2-py3-none-any.whl", hash = "sha256:9acb47f6afd73f60dc1df93bb801b472f05ff42fa6c84167d25cb206be1fbf4a"}, + {file = "cloudpickle-3.1.2.tar.gz", hash = "sha256:7fda9eb655c9c230dab534f1983763de5835249750e85fbcef43aaa30a9a2414"}, +] + + +[[package]] +name = "colorama" +version = "0.4.6" +description = "Cross-platform colored terminal text." +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" +groups = ["main", "dev", "docs"] +files = [ + {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"}, + {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"}, +] +markers = {main = "platform_system == \"Windows\"", dev = "sys_platform == \"win32\" or platform_system == \"Windows\"", docs = "sys_platform == \"win32\""} + + +[[package]] +name = "contourpy" +version = "1.3.2" +description = "Python library for calculating contours of 2D quadrilateral grids" +optional = false +python-versions = ">=3.10" +groups = ["main"] +markers = "python_version == \"3.10\"" +files = [ + {file = "contourpy-1.3.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:ba38e3f9f330af820c4b27ceb4b9c7feee5fe0493ea53a8720f4792667465934"}, + {file = "contourpy-1.3.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:dc41ba0714aa2968d1f8674ec97504a8f7e334f48eeacebcaa6256213acb0989"}, + {file = "contourpy-1.3.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9be002b31c558d1ddf1b9b415b162c603405414bacd6932d031c5b5a8b757f0d"}, + {file = "contourpy-1.3.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8d2e74acbcba3bfdb6d9d8384cdc4f9260cae86ed9beee8bd5f54fee49a430b9"}, + {file = "contourpy-1.3.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e259bced5549ac64410162adc973c5e2fb77f04df4a439d00b478e57a0e65512"}, + {file = "contourpy-1.3.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ad687a04bc802cbe8b9c399c07162a3c35e227e2daccf1668eb1f278cb698631"}, + {file = "contourpy-1.3.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:cdd22595308f53ef2f891040ab2b93d79192513ffccbd7fe19be7aa773a5e09f"}, + {file = "contourpy-1.3.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:b4f54d6a2defe9f257327b0f243612dd051cc43825587520b1bf74a31e2f6ef2"}, + {file = "contourpy-1.3.2-cp310-cp310-win32.whl", hash = "sha256:f939a054192ddc596e031e50bb13b657ce318cf13d264f095ce9db7dc6ae81c0"}, + {file = "contourpy-1.3.2-cp310-cp310-win_amd64.whl", hash = "sha256:c440093bbc8fc21c637c03bafcbef95ccd963bc6e0514ad887932c18ca2a759a"}, + {file = "contourpy-1.3.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6a37a2fb93d4df3fc4c0e363ea4d16f83195fc09c891bc8ce072b9d084853445"}, + {file = "contourpy-1.3.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:b7cd50c38f500bbcc9b6a46643a40e0913673f869315d8e70de0438817cb7773"}, + {file = "contourpy-1.3.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d6658ccc7251a4433eebd89ed2672c2ed96fba367fd25ca9512aa92a4b46c4f1"}, + {file = "contourpy-1.3.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:70771a461aaeb335df14deb6c97439973d253ae70660ca085eec25241137ef43"}, + {file = "contourpy-1.3.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:65a887a6e8c4cd0897507d814b14c54a8c2e2aa4ac9f7686292f9769fcf9a6ab"}, + {file = "contourpy-1.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3859783aefa2b8355697f16642695a5b9792e7a46ab86da1118a4a23a51a33d7"}, + {file = "contourpy-1.3.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:eab0f6db315fa4d70f1d8ab514e527f0366ec021ff853d7ed6a2d33605cf4b83"}, + {file = "contourpy-1.3.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d91a3ccc7fea94ca0acab82ceb77f396d50a1f67412efe4c526f5d20264e6ecd"}, + {file = "contourpy-1.3.2-cp311-cp311-win32.whl", hash = "sha256:1c48188778d4d2f3d48e4643fb15d8608b1d01e4b4d6b0548d9b336c28fc9b6f"}, + {file = "contourpy-1.3.2-cp311-cp311-win_amd64.whl", hash = "sha256:5ebac872ba09cb8f2131c46b8739a7ff71de28a24c869bcad554477eb089a878"}, + {file = "contourpy-1.3.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4caf2bcd2969402bf77edc4cb6034c7dd7c0803213b3523f111eb7460a51b8d2"}, + {file = "contourpy-1.3.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:82199cb78276249796419fe36b7386bd8d2cc3f28b3bc19fe2454fe2e26c4c15"}, + {file = "contourpy-1.3.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:106fab697af11456fcba3e352ad50effe493a90f893fca6c2ca5c033820cea92"}, + {file = "contourpy-1.3.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d14f12932a8d620e307f715857107b1d1845cc44fdb5da2bc8e850f5ceba9f87"}, + {file = "contourpy-1.3.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:532fd26e715560721bb0d5fc7610fce279b3699b018600ab999d1be895b09415"}, + {file = "contourpy-1.3.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f26b383144cf2d2c29f01a1e8170f50dacf0eac02d64139dcd709a8ac4eb3cfe"}, + {file = "contourpy-1.3.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c49f73e61f1f774650a55d221803b101d966ca0c5a2d6d5e4320ec3997489441"}, + {file = "contourpy-1.3.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3d80b2c0300583228ac98d0a927a1ba6a2ba6b8a742463c564f1d419ee5b211e"}, + {file = "contourpy-1.3.2-cp312-cp312-win32.whl", hash = "sha256:90df94c89a91b7362e1142cbee7568f86514412ab8a2c0d0fca72d7e91b62912"}, + {file = "contourpy-1.3.2-cp312-cp312-win_amd64.whl", hash = "sha256:8c942a01d9163e2e5cfb05cb66110121b8d07ad438a17f9e766317bcb62abf73"}, + {file = "contourpy-1.3.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:de39db2604ae755316cb5967728f4bea92685884b1e767b7c24e983ef5f771cb"}, + {file = "contourpy-1.3.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:3f9e896f447c5c8618f1edb2bafa9a4030f22a575ec418ad70611450720b5b08"}, + {file = "contourpy-1.3.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:71e2bd4a1c4188f5c2b8d274da78faab884b59df20df63c34f74aa1813c4427c"}, + {file = "contourpy-1.3.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:de425af81b6cea33101ae95ece1f696af39446db9682a0b56daaa48cfc29f38f"}, + {file = "contourpy-1.3.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:977e98a0e0480d3fe292246417239d2d45435904afd6d7332d8455981c408b85"}, + {file = "contourpy-1.3.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:434f0adf84911c924519d2b08fc10491dd282b20bdd3fa8f60fd816ea0b48841"}, + {file = "contourpy-1.3.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:c66c4906cdbc50e9cba65978823e6e00b45682eb09adbb78c9775b74eb222422"}, + {file = "contourpy-1.3.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8b7fc0cd78ba2f4695fd0a6ad81a19e7e3ab825c31b577f384aa9d7817dc3bef"}, + {file = "contourpy-1.3.2-cp313-cp313-win32.whl", hash = "sha256:15ce6ab60957ca74cff444fe66d9045c1fd3e92c8936894ebd1f3eef2fff075f"}, + {file = "contourpy-1.3.2-cp313-cp313-win_amd64.whl", hash = "sha256:e1578f7eafce927b168752ed7e22646dad6cd9bca673c60bff55889fa236ebf9"}, + {file = "contourpy-1.3.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0475b1f6604896bc7c53bb070e355e9321e1bc0d381735421a2d2068ec56531f"}, + {file = "contourpy-1.3.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:c85bb486e9be652314bb5b9e2e3b0d1b2e643d5eec4992c0fbe8ac71775da739"}, + {file = "contourpy-1.3.2-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:745b57db7758f3ffc05a10254edd3182a2a83402a89c00957a8e8a22f5582823"}, + {file = "contourpy-1.3.2-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:970e9173dbd7eba9b4e01aab19215a48ee5dd3f43cef736eebde064a171f89a5"}, + {file = "contourpy-1.3.2-cp313-cp313t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c6c4639a9c22230276b7bffb6a850dfc8258a2521305e1faefe804d006b2e532"}, + {file = "contourpy-1.3.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cc829960f34ba36aad4302e78eabf3ef16a3a100863f0d4eeddf30e8a485a03b"}, + {file = "contourpy-1.3.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:d32530b534e986374fc19eaa77fcb87e8a99e5431499949b828312bdcd20ac52"}, + {file = "contourpy-1.3.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:e298e7e70cf4eb179cc1077be1c725b5fd131ebc81181bf0c03525c8abc297fd"}, + {file = "contourpy-1.3.2-cp313-cp313t-win32.whl", hash = "sha256:d0e589ae0d55204991450bb5c23f571c64fe43adaa53f93fc902a84c96f52fe1"}, + {file = "contourpy-1.3.2-cp313-cp313t-win_amd64.whl", hash = "sha256:78e9253c3de756b3f6a5174d024c4835acd59eb3f8e2ca13e775dbffe1558f69"}, + {file = "contourpy-1.3.2-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:fd93cc7f3139b6dd7aab2f26a90dde0aa9fc264dbf70f6740d498a70b860b82c"}, + {file = "contourpy-1.3.2-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:107ba8a6a7eec58bb475329e6d3b95deba9440667c4d62b9b6063942b61d7f16"}, + {file = "contourpy-1.3.2-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:ded1706ed0c1049224531b81128efbd5084598f18d8a2d9efae833edbd2b40ad"}, + {file = "contourpy-1.3.2-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:5f5964cdad279256c084b69c3f412b7801e15356b16efa9d78aa974041903da0"}, + {file = "contourpy-1.3.2-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:49b65a95d642d4efa8f64ba12558fcb83407e58a2dfba9d796d77b63ccfcaff5"}, + {file = "contourpy-1.3.2-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:8c5acb8dddb0752bf252e01a3035b21443158910ac16a3b0d20e7fed7d534ce5"}, + {file = "contourpy-1.3.2.tar.gz", hash = "sha256:b6945942715a034c671b7fc54f9588126b0b8bf23db2696e3ca8328f3ff0ab54"}, +] + +[package.dependencies] +numpy = ">=1.23" + +[package.extras] +bokeh = ["bokeh", "selenium"] +docs = ["furo", "sphinx (>=7.2)", "sphinx-copybutton"] +mypy = ["bokeh", "contourpy[bokeh,docs]", "docutils-stubs", "mypy (==1.15.0)", "types-Pillow"] +test = ["Pillow", "contourpy[test-no-images]", "matplotlib"] +test-no-images = ["pytest", "pytest-cov", "pytest-rerunfailures", "pytest-xdist", "wurlitzer"] + + +[[package]] +name = "contourpy" +version = "1.3.3" +description = "Python library for calculating contours of 2D quadrilateral grids" +optional = false +python-versions = ">=3.11" +groups = ["main"] +markers = "python_version == \"3.11\"" +files = [ + {file = "contourpy-1.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:709a48ef9a690e1343202916450bc48b9e51c049b089c7f79a267b46cffcdaa1"}, + {file = "contourpy-1.3.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:23416f38bfd74d5d28ab8429cc4d63fa67d5068bd711a85edb1c3fb0c3e2f381"}, + {file = "contourpy-1.3.3-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:929ddf8c4c7f348e4c0a5a3a714b5c8542ffaa8c22954862a46ca1813b667ee7"}, + {file = "contourpy-1.3.3-cp311-cp311-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e999574eddae35f1312c2b4b717b7885d4edd6cb46700e04f7f02db454e67c1"}, + {file = "contourpy-1.3.3-cp311-cp311-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0bf67e0e3f482cb69779dd3061b534eb35ac9b17f163d851e2a547d56dba0a3a"}, + {file = "contourpy-1.3.3-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:51e79c1f7470158e838808d4a996fa9bac72c498e93d8ebe5119bc1e6becb0db"}, + {file = "contourpy-1.3.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:598c3aaece21c503615fd59c92a3598b428b2f01bfb4b8ca9c4edeecc2438620"}, + {file = "contourpy-1.3.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:322ab1c99b008dad206d406bb61d014cf0174df491ae9d9d0fac6a6fda4f977f"}, + {file = "contourpy-1.3.3-cp311-cp311-win32.whl", hash = "sha256:fd907ae12cd483cd83e414b12941c632a969171bf90fc937d0c9f268a31cafff"}, + {file = "contourpy-1.3.3-cp311-cp311-win_amd64.whl", hash = "sha256:3519428f6be58431c56581f1694ba8e50626f2dd550af225f82fb5f5814d2a42"}, + {file = "contourpy-1.3.3-cp311-cp311-win_arm64.whl", hash = "sha256:15ff10bfada4bf92ec8b31c62bf7c1834c244019b4a33095a68000d7075df470"}, + {file = "contourpy-1.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b08a32ea2f8e42cf1d4be3169a98dd4be32bafe4f22b6c4cb4ba810fa9e5d2cb"}, + {file = "contourpy-1.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:556dba8fb6f5d8742f2923fe9457dbdd51e1049c4a43fd3986a0b14a1d815fc6"}, + {file = "contourpy-1.3.3-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92d9abc807cf7d0e047b95ca5d957cf4792fcd04e920ca70d48add15c1a90ea7"}, + {file = "contourpy-1.3.3-cp312-cp312-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b2e8faa0ed68cb29af51edd8e24798bb661eac3bd9f65420c1887b6ca89987c8"}, + {file = "contourpy-1.3.3-cp312-cp312-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:626d60935cf668e70a5ce6ff184fd713e9683fb458898e4249b63be9e28286ea"}, + {file = "contourpy-1.3.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4d00e655fcef08aba35ec9610536bfe90267d7ab5ba944f7032549c55a146da1"}, + {file = "contourpy-1.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:451e71b5a7d597379ef572de31eeb909a87246974d960049a9848c3bc6c41bf7"}, + {file = "contourpy-1.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:459c1f020cd59fcfe6650180678a9993932d80d44ccde1fa1868977438f0b411"}, + {file = "contourpy-1.3.3-cp312-cp312-win32.whl", hash = "sha256:023b44101dfe49d7d53932be418477dba359649246075c996866106da069af69"}, + {file = "contourpy-1.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:8153b8bfc11e1e4d75bcb0bff1db232f9e10b274e0929de9d608027e0d34ff8b"}, + {file = "contourpy-1.3.3-cp312-cp312-win_arm64.whl", hash = "sha256:07ce5ed73ecdc4a03ffe3e1b3e3c1166db35ae7584be76f65dbbe28a7791b0cc"}, + {file = "contourpy-1.3.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:177fb367556747a686509d6fef71d221a4b198a3905fe824430e5ea0fda54eb5"}, + {file = "contourpy-1.3.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d002b6f00d73d69333dac9d0b8d5e84d9724ff9ef044fd63c5986e62b7c9e1b1"}, + {file = "contourpy-1.3.3-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:348ac1f5d4f1d66d3322420f01d42e43122f43616e0f194fc1c9f5d830c5b286"}, + {file = "contourpy-1.3.3-cp313-cp313-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:655456777ff65c2c548b7c454af9c6f33f16c8884f11083244b5819cc214f1b5"}, + {file = "contourpy-1.3.3-cp313-cp313-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:644a6853d15b2512d67881586bd03f462c7ab755db95f16f14d7e238f2852c67"}, + {file = "contourpy-1.3.3-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4debd64f124ca62069f313a9cb86656ff087786016d76927ae2cf37846b006c9"}, + {file = "contourpy-1.3.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a15459b0f4615b00bbd1e91f1b9e19b7e63aea7483d03d804186f278c0af2659"}, + {file = "contourpy-1.3.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:ca0fdcd73925568ca027e0b17ab07aad764be4706d0a925b89227e447d9737b7"}, + {file = "contourpy-1.3.3-cp313-cp313-win32.whl", hash = "sha256:b20c7c9a3bf701366556e1b1984ed2d0cedf999903c51311417cf5f591d8c78d"}, + {file = "contourpy-1.3.3-cp313-cp313-win_amd64.whl", hash = "sha256:1cadd8b8969f060ba45ed7c1b714fe69185812ab43bd6b86a9123fe8f99c3263"}, + {file = "contourpy-1.3.3-cp313-cp313-win_arm64.whl", hash = "sha256:fd914713266421b7536de2bfa8181aa8c699432b6763a0ea64195ebe28bff6a9"}, + {file = "contourpy-1.3.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:88df9880d507169449d434c293467418b9f6cbe82edd19284aa0409e7fdb933d"}, + {file = "contourpy-1.3.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:d06bb1f751ba5d417047db62bca3c8fde202b8c11fb50742ab3ab962c81e8216"}, + {file = "contourpy-1.3.3-cp313-cp313t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e4e6b05a45525357e382909a4c1600444e2a45b4795163d3b22669285591c1ae"}, + {file = "contourpy-1.3.3-cp313-cp313t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ab3074b48c4e2cf1a960e6bbeb7f04566bf36b1861d5c9d4d8ac04b82e38ba20"}, + {file = "contourpy-1.3.3-cp313-cp313t-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6c3d53c796f8647d6deb1abe867daeb66dcc8a97e8455efa729516b997b8ed99"}, + {file = "contourpy-1.3.3-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50ed930df7289ff2a8d7afeb9603f8289e5704755c7e5c3bbd929c90c817164b"}, + {file = "contourpy-1.3.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:4feffb6537d64b84877da813a5c30f1422ea5739566abf0bd18065ac040e120a"}, + {file = "contourpy-1.3.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:2b7e9480ffe2b0cd2e787e4df64270e3a0440d9db8dc823312e2c940c167df7e"}, + {file = "contourpy-1.3.3-cp313-cp313t-win32.whl", hash = "sha256:283edd842a01e3dcd435b1c5116798d661378d83d36d337b8dde1d16a5fc9ba3"}, + {file = "contourpy-1.3.3-cp313-cp313t-win_amd64.whl", hash = "sha256:87acf5963fc2b34825e5b6b048f40e3635dd547f590b04d2ab317c2619ef7ae8"}, + {file = "contourpy-1.3.3-cp313-cp313t-win_arm64.whl", hash = "sha256:3c30273eb2a55024ff31ba7d052dde990d7d8e5450f4bbb6e913558b3d6c2301"}, + {file = "contourpy-1.3.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:fde6c716d51c04b1c25d0b90364d0be954624a0ee9d60e23e850e8d48353d07a"}, + {file = "contourpy-1.3.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:cbedb772ed74ff5be440fa8eee9bd49f64f6e3fc09436d9c7d8f1c287b121d77"}, + {file = "contourpy-1.3.3-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:22e9b1bd7a9b1d652cd77388465dc358dafcd2e217d35552424aa4f996f524f5"}, + {file = "contourpy-1.3.3-cp314-cp314-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a22738912262aa3e254e4f3cb079a95a67132fc5a063890e224393596902f5a4"}, + {file = "contourpy-1.3.3-cp314-cp314-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:afe5a512f31ee6bd7d0dda52ec9864c984ca3d66664444f2d72e0dc4eb832e36"}, + {file = "contourpy-1.3.3-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f64836de09927cba6f79dcd00fdd7d5329f3fccc633468507079c829ca4db4e3"}, + {file = "contourpy-1.3.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:1fd43c3be4c8e5fd6e4f2baeae35ae18176cf2e5cced681cca908addf1cdd53b"}, + {file = "contourpy-1.3.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6afc576f7b33cf00996e5c1102dc2a8f7cc89e39c0b55df93a0b78c1bd992b36"}, + {file = "contourpy-1.3.3-cp314-cp314-win32.whl", hash = "sha256:66c8a43a4f7b8df8b71ee1840e4211a3c8d93b214b213f590e18a1beca458f7d"}, + {file = "contourpy-1.3.3-cp314-cp314-win_amd64.whl", hash = "sha256:cf9022ef053f2694e31d630feaacb21ea24224be1c3ad0520b13d844274614fd"}, + {file = "contourpy-1.3.3-cp314-cp314-win_arm64.whl", hash = "sha256:95b181891b4c71de4bb404c6621e7e2390745f887f2a026b2d99e92c17892339"}, + {file = "contourpy-1.3.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:33c82d0138c0a062380332c861387650c82e4cf1747aaa6938b9b6516762e772"}, + {file = "contourpy-1.3.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ea37e7b45949df430fe649e5de8351c423430046a2af20b1c1961cae3afcda77"}, + {file = "contourpy-1.3.3-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d304906ecc71672e9c89e87c4675dc5c2645e1f4269a5063b99b0bb29f232d13"}, + {file = "contourpy-1.3.3-cp314-cp314t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ca658cd1a680a5c9ea96dc61cdbae1e85c8f25849843aa799dfd3cb370ad4fbe"}, + {file = "contourpy-1.3.3-cp314-cp314t-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ab2fd90904c503739a75b7c8c5c01160130ba67944a7b77bbf36ef8054576e7f"}, + {file = "contourpy-1.3.3-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b7301b89040075c30e5768810bc96a8e8d78085b47d8be6e4c3f5a0b4ed478a0"}, + {file = "contourpy-1.3.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:2a2a8b627d5cc6b7c41a4beff6c5ad5eb848c88255fda4a8745f7e901b32d8e4"}, + {file = "contourpy-1.3.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:fd6ec6be509c787f1caf6b247f0b1ca598bef13f4ddeaa126b7658215529ba0f"}, + {file = "contourpy-1.3.3-cp314-cp314t-win32.whl", hash = "sha256:e74a9a0f5e3fff48fb5a7f2fd2b9b70a3fe014a67522f79b7cca4c0c7e43c9ae"}, + {file = "contourpy-1.3.3-cp314-cp314t-win_amd64.whl", hash = "sha256:13b68d6a62db8eafaebb8039218921399baf6e47bf85006fd8529f2a08ef33fc"}, + {file = "contourpy-1.3.3-cp314-cp314t-win_arm64.whl", hash = "sha256:b7448cb5a725bb1e35ce88771b86fba35ef418952474492cf7c764059933ff8b"}, + {file = "contourpy-1.3.3-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:cd5dfcaeb10f7b7f9dc8941717c6c2ade08f587be2226222c12b25f0483ed497"}, + {file = "contourpy-1.3.3-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:0c1fc238306b35f246d61a1d416a627348b5cf0648648a031e14bb8705fcdfe8"}, + {file = "contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:70f9aad7de812d6541d29d2bbf8feb22ff7e1c299523db288004e3157ff4674e"}, + {file = "contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5ed3657edf08512fc3fe81b510e35c2012fbd3081d2e26160f27ca28affec989"}, + {file = "contourpy-1.3.3-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:3d1a3799d62d45c18bafd41c5fa05120b96a28079f2393af559b843d1a966a77"}, + {file = "contourpy-1.3.3.tar.gz", hash = "sha256:083e12155b210502d0bca491432bb04d56dc3432f95a979b429f2848c3dbe880"}, +] + +[package.dependencies] +numpy = ">=1.25" + +[package.extras] +bokeh = ["bokeh", "selenium"] +docs = ["furo", "sphinx (>=7.2)", "sphinx-copybutton"] +mypy = ["bokeh", "contourpy[bokeh,docs]", "docutils-stubs", "mypy (==1.17.0)", "types-Pillow"] +test = ["Pillow", "contourpy[test-no-images]", "matplotlib"] +test-no-images = ["pytest", "pytest-cov", "pytest-rerunfailures", "pytest-xdist", "wurlitzer"] + + +[[package]] +name = "contourpy" +version = "1.4.0" +description = "Python library for calculating contours of 2D quadrilateral grids" +optional = false +python-versions = ">=3.12" +groups = ["main"] +markers = "python_version >= \"3.12\"" +files = [ + {file = "contourpy-1.4.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:186ba929df36d61b6127da2e89cd1357e4cb79aca647381ab1a6feb0b152877b"}, + {file = "contourpy-1.4.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c76f3a5318164db7d9401132fc1b5364b784c613c93fa506e3b5e6d1bf353ec8"}, + {file = "contourpy-1.4.0-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:43c3ccbb32c6294b183dcc8e8c46dacf5ecef809497e3d48a5be298eef185ad0"}, + {file = "contourpy-1.4.0-cp312-cp312-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:86d05cec773c9507a3950122e0e40ce77c23c75ceeb2fc189514e71893cbb34b"}, + {file = "contourpy-1.4.0-cp312-cp312-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2deb580178ca19437a84bd77e4bc2cd91a8ccad212413a83c273900868b5978c"}, + {file = "contourpy-1.4.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:875f42444c9cf48d56f724f2637e60d0f73b3b12c9041e1484580a233edf9591"}, + {file = "contourpy-1.4.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f863c6100bf926cf47d13f3cd75f9bb8ebd98aaab230eeb4468b91f98f39a6b3"}, + {file = "contourpy-1.4.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3863ef2e2b13fe93f8c0ebb08ee400cb07153b8b0e91c5acb26e4537f283634f"}, + {file = "contourpy-1.4.0-cp312-cp312-win32.whl", hash = "sha256:5450f091ac1be0be3ad3a2a3b3f23b5e443e78c670ced4fd347d626f92a28fd2"}, + {file = "contourpy-1.4.0-cp312-cp312-win_amd64.whl", hash = "sha256:6e697d94e69f499ff6bebb899cae97a58d5d14f0e1fe9568b43a0248d2f9af8c"}, + {file = "contourpy-1.4.0-cp312-cp312-win_arm64.whl", hash = "sha256:0c7a4c2716a4e98342221954416a836cca77c996c14ddbf22b5f01d5d93ca09c"}, + {file = "contourpy-1.4.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e21d1d4a9db5b3a793649c7ab0ddb4697f2818929eec871a7b9c45fce7b2a1ea"}, + {file = "contourpy-1.4.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:196759a3e4db60e1546167e361090ebb6d199aa3aafc9e34ea17a5ac3b23e814"}, + {file = "contourpy-1.4.0-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9c0e07c691f3b3321913ed9b8161c50ea5f77fadd006f52f5e755359b0dcbfc5"}, + {file = "contourpy-1.4.0-cp313-cp313-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7f861af508fca2384eef392bc1d8377cfa349b2b854cb11b45d89c75780e2561"}, + {file = "contourpy-1.4.0-cp313-cp313-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a03b32c2e7eda8b17757c022162c13c86f5c3d6f937dddf9ba3c3ff7b513953b"}, + {file = "contourpy-1.4.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f1219a8898523cba821085f2da8a1b962cc696325763f09d7f93538ba43b2d70"}, + {file = "contourpy-1.4.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:20da2f86bfaed60dbba729fe738c8241b1dd22b6cf7e8cbbf30df290bd04ba28"}, + {file = "contourpy-1.4.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6ced1670fafee703b8277ab1645072a226e74f167166eae146fb743916119b67"}, + {file = "contourpy-1.4.0-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:abd0f7e51ecc52bf8c95713bd80b1c17c516a71fa391c54475308a4377903c2b"}, + {file = "contourpy-1.4.0-cp313-cp313-win32.whl", hash = "sha256:510f7d93d94cf6ebf4e2cd0640bea16ab8affac7547230175b6745b596ce0599"}, + {file = "contourpy-1.4.0-cp313-cp313-win_amd64.whl", hash = "sha256:6507a016976a75a15aee47809a34605de6244ccc056e6164bf9fb14b27eecad4"}, + {file = "contourpy-1.4.0-cp313-cp313-win_arm64.whl", hash = "sha256:423bd5f4b3f11d54a8c597234e513382e3454bb106b8ec7ae32ba4ed63f8d99b"}, + {file = "contourpy-1.4.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:a3e67bc1a6a4618a1dac7c3053a9ffece5ddfa2046b2670b342cf430bb0b87d1"}, + {file = "contourpy-1.4.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:072a702e2e178f4fcf96f04775d0c059e4c917925abf0d3208ebb6865df3c23d"}, + {file = "contourpy-1.4.0-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:404dbcd9233513dfd1323b66ea593fef90e899f658f6b8a9ed8e93bd0ca669db"}, + {file = "contourpy-1.4.0-cp314-cp314-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:61624f6722480aa7e168fd746164e7bfdf48f8ccb6542f1613741200dc37e2b1"}, + {file = "contourpy-1.4.0-cp314-cp314-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2e741a39dfc96babe1722561e81351aeec104526c57dbe91c167c1db606c2d55"}, + {file = "contourpy-1.4.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e439ab450c93455feb0218532ded3e946ec7a9b5f459069f122cfa44b89229f6"}, + {file = "contourpy-1.4.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:417be048f7e122cefbe2a34c51a1f2b0410f8eb35796f794d45475ddb7872d9d"}, + {file = "contourpy-1.4.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:43d80072a32299bf945de0a6dd4e034ea0162e832261de2e07a274a5adbba9c9"}, + {file = "contourpy-1.4.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:fa1b787362a3856e63dd2b89449f6c384d55ee1beb8f94f4bcc871b40f02462c"}, + {file = "contourpy-1.4.0-cp314-cp314-win32.whl", hash = "sha256:738c44fa71735a617f36da58e32810512407d283d5d1bb5b1cecb00d7eeba7cf"}, + {file = "contourpy-1.4.0-cp314-cp314-win_amd64.whl", hash = "sha256:181bea01bc742734ae672fa00c717d855dd35e1f029536406538c52e7b0cd73d"}, + {file = "contourpy-1.4.0-cp314-cp314-win_arm64.whl", hash = "sha256:64039341e2d8804f1a13bda8c69083eab935167bbd7e856cf096241f17d5bd45"}, + {file = "contourpy-1.4.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:ef47fef9a912c77e3d84b014f701e5a9340f25703e9ed3bcebe37f91fb69dc49"}, + {file = "contourpy-1.4.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:96019f059bcb3774acc0104be3360a57b36d33eaaa2e1d7f77c800ca8e07618b"}, + {file = "contourpy-1.4.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ddf5a2596d716fd3793434844caf31abc7a40b1e8718431420c89858268fb909"}, + {file = "contourpy-1.4.0-cp314-cp314t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:dd59df9e2fb0aff8bd7fd1adb9f349b7c835245a9d0f18c2f2deeb537190f2b1"}, + {file = "contourpy-1.4.0-cp314-cp314t-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b7794ea07cab575633daad8d6e963b662053391022294d3aacc1d9ba9ef54114"}, + {file = "contourpy-1.4.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a1c8a74744fa746eeaa12f0f9ed7f8b4add9d8f1b14d95e3b5e133675eac888f"}, + {file = "contourpy-1.4.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:107ec46f7aa1664266d69b1181aadc953d58d39f7d8d648fa5b795d4a060b0de"}, + {file = "contourpy-1.4.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5a4c89c7f38a0d7a94356d74e3391073c4325c4d47ad2fd065c3fe7dbae16c0c"}, + {file = "contourpy-1.4.0-cp314-cp314t-win32.whl", hash = "sha256:912c6afaa106e2f74ba22b30416b77ef7eb94e3bdc5a4df51ab147845dba9b6d"}, + {file = "contourpy-1.4.0-cp314-cp314t-win_amd64.whl", hash = "sha256:ef9440f6f8506246269a82734f5ff9e2e4c5e775b3996fc883cc491c5257eca6"}, + {file = "contourpy-1.4.0-cp314-cp314t-win_arm64.whl", hash = "sha256:fc9feef8f1f001c5b87decadc67c4a5d1eebb62ca39c4763d1237ff62cf2b707"}, + {file = "contourpy-1.4.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:79b06c60d5e569ce12c5da8f0c51217cdc484386e2349fa717c30fafb56d2871"}, + {file = "contourpy-1.4.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:6f963ea9f0d68d2b6a02d861e3c0aae09ae25ba21f243fcf281e9fed468b078d"}, + {file = "contourpy-1.4.0-cp315-cp315-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5545ff38229c15d11d822fc6f7415b932da9f4975f53e305b7b96ebfb01f889c"}, + {file = "contourpy-1.4.0-cp315-cp315-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:630d32f06cedf37b7f1dd2b6a12e4492826bd477a4c9c7b2e2fee6ce3a2cea76"}, + {file = "contourpy-1.4.0-cp315-cp315-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:be85d160e7c795113c2a93254dde2fc7e86b375322570eee78b420969426973c"}, + {file = "contourpy-1.4.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:018227e134b73090b06f911e773a526c77c9af426be29065500ce096a5accd4c"}, + {file = "contourpy-1.4.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:4bffcb2e8cc5c0e837631acab59dd04265fdac376550e7c3e310523877c68cb7"}, + {file = "contourpy-1.4.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc87f2ffa84a49a77d76cb792f28a48ff3b05a222aa0b2bddbd839ba78e1d5ca"}, + {file = "contourpy-1.4.0-cp315-cp315-pyemscripten_2026_5_wasm32.whl", hash = "sha256:c8be3392b84cf43373a488874dc1ebf46f60784a70977f92586e18019d71c7ed"}, + {file = "contourpy-1.4.0-cp315-cp315-win32.whl", hash = "sha256:618137ec5778fb76d494c9ec854b104a377fddba0d128bef7136cce2c3bf0df8"}, + {file = "contourpy-1.4.0-cp315-cp315-win_amd64.whl", hash = "sha256:ea09dc704029930cbd097f75cb0cc1db9852adbcf1a151fac7e9559f7bcbfd19"}, + {file = "contourpy-1.4.0-cp315-cp315-win_arm64.whl", hash = "sha256:a5e2bb871b90cd7a52bdee63bf80ef7acb46398d27efc66d7679240016efc5aa"}, + {file = "contourpy-1.4.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:432e89f835cf01f8d2123a130a3126b17ee6e0348e4d62c0973872b30aa873bf"}, + {file = "contourpy-1.4.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:3e0a2392533e5e2abdf277c951047516acc8d2f3c42b2dd9dc34c907c9ebabf2"}, + {file = "contourpy-1.4.0-cp315-cp315t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:758e7496cec3195fc28a28945eab3ceef348c47fb95c7afc2eca2f3901209c8c"}, + {file = "contourpy-1.4.0-cp315-cp315t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:bee6ff96653e0807cd0f8eaef00174a031e3a2effa5c20f49a5a8d574b05af23"}, + {file = "contourpy-1.4.0-cp315-cp315t-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a58b5f130afec61a093d743cdda435cc4047748b6791627e34a68f41ec3a9b07"}, + {file = "contourpy-1.4.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b9dc493e7924e5aa32d89d0b8e50986280f3d4b284968a792787bd7bcffd3cad"}, + {file = "contourpy-1.4.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:c927ec747633e68c9920bcaad48b0bcefe648812b822f18c34e2d0e2270a3d2a"}, + {file = "contourpy-1.4.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:80c7fc8e7ac217777ce7ba2db3cf8478652b5a4b335283111012ff9eaac9d842"}, + {file = "contourpy-1.4.0-cp315-cp315t-win32.whl", hash = "sha256:90feb8da006803a95ba573fddc9536357d0c3faddc3a4c9e22816ca49af52878"}, + {file = "contourpy-1.4.0-cp315-cp315t-win_amd64.whl", hash = "sha256:de503609fdb71f597634ca64fb4bd2f13d27c97f140e912b1e8ed93544840df0"}, + {file = "contourpy-1.4.0-cp315-cp315t-win_arm64.whl", hash = "sha256:78ed5c5f962b3e156109f0531b174a65ba80d13cc681a70227b12524c162e184"}, + {file = "contourpy-1.4.0.tar.gz", hash = "sha256:20156f5a1ac4f8ce02656e39a61e82164a3d359796dc8026f75b062783d500e1"}, +] + +[package.dependencies] +numpy = ">=2.0" + +[package.extras] +bokeh = ["bokeh", "selenium"] +docs = ["myst-parser", "sphinx", "sphinx-book-theme", "sphinx-copybutton"] +mypy = ["bokeh", "contourpy[bokeh,docs]", "docutils-stubs", "mypy (==2.1.0)", "types-Pillow"] +test = ["Pillow", "contourpy[test-no-images]", "matplotlib", "pre-commit"] +test-no-images = ["pytest", "pytest-cov", "pytest-rerunfailures (<16)", "pytest-xdist", "wurlitzer"] + + +[[package]] +name = "coverage" +version = "7.16.1" +description = "Code coverage measurement for Python" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "coverage-7.16.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:4f12a9e27ca7b65e40a8475d27899b2d45064d9020e6a89148939e01987b5853"}, + {file = "coverage-7.16.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8f590d46c30d9e4c1fda3efefe5443f4c2f6a4192c5ca2ba403653e9ebadf097"}, + {file = "coverage-7.16.1-cp310-cp310-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:3df82f0a3cef4e1bcfc799436056f0b978dda319d0bfd4460c6e479b2802d98a"}, + {file = "coverage-7.16.1-cp310-cp310-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:bb462d59146656e278d1e8ed913ce374d0ba68a4e081acde1867f6d3377fc881"}, + {file = "coverage-7.16.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d7db888dd0a1df1a653cae7f99d4047430d2187a3626eda51bc847b0fd6b9b43"}, + {file = "coverage-7.16.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:38a7e16f061504ac2b45370bf5bf97e8250d8d3f25e37385bae884978166554b"}, + {file = "coverage-7.16.1-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:2b26b55b18e1a53e1a159dd743728c4ddbbef28ba19000a91aaff5ce023197ec"}, + {file = "coverage-7.16.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:fdb2f528b50953e29d22033b3256c396a700193c6e45b2490222ef9c333cbbf9"}, + {file = "coverage-7.16.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:3284754371dc78592aa3ae4d661d30ee20e02b2b6b0de3590a181a936d0d3b38"}, + {file = "coverage-7.16.1-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:802d1246c540e07486d4ee1adfa19a797e4b33529ffc371dc140644e8f27da0a"}, + {file = "coverage-7.16.1-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:6fc735d6fe6d57f803e7ba021be4dde48e43e6aff94e6954350555d5332b0594"}, + {file = "coverage-7.16.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:ed5ade1bb18f62edace1bd198c66f9d4c75a8385d5fd24e87d917ea1a5958773"}, + {file = "coverage-7.16.1-cp310-cp310-win32.whl", hash = "sha256:0c309096926b119543dc16438a11ef4c80783d2f4e59ff94f7f462651a944cdc"}, + {file = "coverage-7.16.1-cp310-cp310-win_amd64.whl", hash = "sha256:7562f8067ed9360e8b9739e5703403a7686dd1b36bf0f89fc538047c54cdea90"}, + {file = "coverage-7.16.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:72e013665e25cf9d44779f01f340af26319756f9a76822b7c94ce6b1d93813da"}, + {file = "coverage-7.16.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:cb05c0ff98b56ba6969adf35556bc43bcb8d094df8bc9cb403acff53460c4e07"}, + {file = "coverage-7.16.1-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:0d0ececb32090e3fbb03e0d352b973a0485879b4de6c58daf47227b9988b99e5"}, + {file = "coverage-7.16.1-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:f0ba3892d81aacf36996c52f16bca04e39af31a6c5de930b7688ab617f4a6475"}, + {file = "coverage-7.16.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a6410b75fe07d5271eaa95fc24bd0a9177ed588d9d1c10c0cf67829adb8f0567"}, + {file = "coverage-7.16.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:d1039cb2de093225d597109342ce1675626bd127565e80b3044f4eca07c15b2e"}, + {file = "coverage-7.16.1-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cf047bc39fde5425be2628666d0f435ed8817859111c3aacc84b32d858069f5d"}, + {file = "coverage-7.16.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:2c05913d0d5badf7ac83200f35dcf9514cce5df16a7cc89e7d1d7fff0461813b"}, + {file = "coverage-7.16.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:4027bf6d7bc0a16df058ce913b69f10c5687f8e1ca668f08caa659ce101744bf"}, + {file = "coverage-7.16.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:4f48b345f831eaf4402ab6333c2dc3e2e2b5bc7b9c1b8fe12680dee3f0538f01"}, + {file = "coverage-7.16.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:8643baeb590726c558b2faed6cd59b0917480f9367fcc692026f1a86d824fd08"}, + {file = "coverage-7.16.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d06dcc420b570bf683cdb647cc8fe62b672d9e429ef711c3cbbb7a6880ca1572"}, + {file = "coverage-7.16.1-cp311-cp311-win32.whl", hash = "sha256:946f58aa59b08bcd6afcc6a7bd0ff54ed5eee844f32ad69fe6814836d15856a2"}, + {file = "coverage-7.16.1-cp311-cp311-win_amd64.whl", hash = "sha256:684c7ee9b4c04358fe6ac8b517ab51ec35fcd79d08ff0f105dd8bcd96885bbb7"}, + {file = "coverage-7.16.1-cp311-cp311-win_arm64.whl", hash = "sha256:1b24f79e25bcf6c73931aeca7a3dfc7595c0cb5e9364aba3fdf387a3de4b1c22"}, + {file = "coverage-7.16.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b7f2c26ce6ce0b1e0ca0d5fae96ea510e3a2e78b7207f06e76b7f2c87fa3d0af"}, + {file = "coverage-7.16.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:070acb9da788dff743a4d36fc015feee12d68f0349959017542017c79f59c21c"}, + {file = "coverage-7.16.1-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:e366587b370bc9b8b51b7b7272c610c56db5d5b4795b9e4a29d28ff2f440f809"}, + {file = "coverage-7.16.1-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:e82e10b9d290f60b63459cfb245a841aec347603997206296b93881463a93dcf"}, + {file = "coverage-7.16.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3d73bb1f85c4150ac208fb0755beb04b2e44897bad81414de9380f98dd74729f"}, + {file = "coverage-7.16.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3397b9032553d281ad6a9253b12675b65e0cc8cd7a3b0633cf48872c9eb13360"}, + {file = "coverage-7.16.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:77890395cf37026a5907d3ad32376aa51f41c0f163b7477fdbd4f94966cc1d08"}, + {file = "coverage-7.16.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b0944dc3bee3091039bf970d73caaf930c906013128a421bdc132e797494d941"}, + {file = "coverage-7.16.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:b89d22a89d5bc05dd95b64e08295b8394aa96dc88e08f8ba210c9ebfebbe0489"}, + {file = "coverage-7.16.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:550a2a1faf7559f13d5344f12d1eb886ad87955155d7dfab2a3fe5c8ec8fe776"}, + {file = "coverage-7.16.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:55eb268e5b81aefac759766c9162625b06c1bedb7b77d936225bafc4f038a6f6"}, + {file = "coverage-7.16.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:65a8fc80898c9ce59f04349fe8b4849b1f9787f14e52ead990e5f849ff4727a0"}, + {file = "coverage-7.16.1-cp312-cp312-win32.whl", hash = "sha256:528a61be40977c340cf201d23b69bd6a6bab507da60e9dbda85f8b30e935d70d"}, + {file = "coverage-7.16.1-cp312-cp312-win_amd64.whl", hash = "sha256:d0f02c633630e2b74522108ee95a84ad6e1204a8016a6cca5297f335ea27147e"}, + {file = "coverage-7.16.1-cp312-cp312-win_arm64.whl", hash = "sha256:2959978f9d1d20a2c0c15d0a68baaeccf615ac1aa214cf4a05a10d6f568926c8"}, + {file = "coverage-7.16.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ee5465db6e9152a7d09f3215309326878c6aa3ac509195a369f9d264ff4bfbd9"}, + {file = "coverage-7.16.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2b8256f8b525ba233d2e4cdcdce0d6673c66fc9bf70df1fd5e67c54a74e2d245"}, + {file = "coverage-7.16.1-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:d57cc400275b9a2892e905fc893f732b21ddb95271bf96406c88e2f6367848b5"}, + {file = "coverage-7.16.1-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:6b3fd0f3435ebb7a7183b32a6062a8b755f08242ced1f3f22761d30b56b3c2a5"}, + {file = "coverage-7.16.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e5eb1762e7eb5fad34ef913e8107c7788a66f19d328e598ce95bf7217f9e5c8f"}, + {file = "coverage-7.16.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:46cd3a73e9140410de62cceb66214bce0e08fb3922b9176fbfc1522fec151b41"}, + {file = "coverage-7.16.1-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d1ba5142d68dd2cb775cbd0ac8601819298152047803c8efe4eec6d7d7aa7878"}, + {file = "coverage-7.16.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:c389c6f9d1d518e1249ddcb8a7f158135644ce2c508fa6cc17b680777dad5bf2"}, + {file = "coverage-7.16.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:cdc57746c7ac0ea063351b4d651c3bb4dd4fd35e64dbb8e90c10e14eb03c4080"}, + {file = "coverage-7.16.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:5597180ed7670cc94c04c65347418a467d3a43d5f0cf52fcac647f5425f42037"}, + {file = "coverage-7.16.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:a9647a0ac46255b8fef59a433a2161f03e5483f3a35e1cbd9dfe4600baff0c6b"}, + {file = "coverage-7.16.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e306e98186b9cd109121f3583aeb7978797ad21d948f22944c5c08845cd554d0"}, + {file = "coverage-7.16.1-cp313-cp313-win32.whl", hash = "sha256:48a78a66fcce49d7f6156524bf979c0ac633d584199717c68c6ffa949fc14e6a"}, + {file = "coverage-7.16.1-cp313-cp313-win_amd64.whl", hash = "sha256:7af03247d598a353bbbbe1b925deb735276e4d845e7197c4073dc89352b236fa"}, + {file = "coverage-7.16.1-cp313-cp313-win_arm64.whl", hash = "sha256:166adae25b05b04c9a84135912066d9c97482115af38df1a419a38aacc6b6f5d"}, + {file = "coverage-7.16.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:cc0b37fe6f5ce5f1ccc62ad4fa9b1ad201d8e9b6027fd5e0170877beee4b2d15"}, + {file = "coverage-7.16.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:6618f481053b63fc6121faf8fc676bd9b7163c2a19d9e984a2e850002c28ab57"}, + {file = "coverage-7.16.1-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:fa02d561eb1d8d2f8ba43ba6e3cef4c6c402a3b632a9460fa329fcadcd5df6a3"}, + {file = "coverage-7.16.1-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:bc5354a124799f1f87b7637bbe6f18cd4bc66a1f37f6aa2b5db40f9adad531dc"}, + {file = "coverage-7.16.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:34bafe9f4094315248573e6223e11af0ec1b25f9cbca43bf0e9a26a189ba2751"}, + {file = "coverage-7.16.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:29c4d3e32a3b5efa420a3dc627c7e570deb80ef997def52c7686a474f5edc7ab"}, + {file = "coverage-7.16.1-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f2066c447fdd0bca39a9633a082d8ce67bf9a539a203b85059a364a405dc9fe9"}, + {file = "coverage-7.16.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fd8ac10cd2458b3c6343aac082fb9bd0e3fa806cb2c4975f2280153474b88412"}, + {file = "coverage-7.16.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:9d8c54ec32e5c102b9241f75d88ae26538b53662868ca491736611db448d9c7a"}, + {file = "coverage-7.16.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:6dd8dda3402a01a1a8fe8b753a282466f615128574a5590a9108acd07b1f8540"}, + {file = "coverage-7.16.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:79afa9726438912e5cddd1fe541815cea9763c92935f594835e4c432565b68a9"}, + {file = "coverage-7.16.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:3db3978211c3cead5437a80136ca0556bab8bc7828de15a762884b0598c41361"}, + {file = "coverage-7.16.1-cp314-cp314-win32.whl", hash = "sha256:49c39c7068a494f8eb427155f5682f44feee43f9b3107fd54b1e52465379c54b"}, + {file = "coverage-7.16.1-cp314-cp314-win_amd64.whl", hash = "sha256:c510dad19552d912058e4c3e3cbec3fb155dbe8d0ce0ceb7e7dbf5c5822bae0b"}, + {file = "coverage-7.16.1-cp314-cp314-win_arm64.whl", hash = "sha256:b7d4d7e6dcaf33e85f1919f03346403bdcc27437c420a78835f3805bca0ab71f"}, + {file = "coverage-7.16.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:3d0a3681c12d3e0bcdea3d9414b04087828d6c1a482802d6f7f42c37ed530152"}, + {file = "coverage-7.16.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:3f3b4469d3da3ecced775d1a8c9c5d9fc80f259e30b7b89f9fed0700d6035ecb"}, + {file = "coverage-7.16.1-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:c08ae35c1be2fe1ce4b4c628df5c6fc0dc9a87f8e5fe8e20238d249678984741"}, + {file = "coverage-7.16.1-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8ee71a38c54bb2676bbe762b8b0943a79ccb1c2fd6a52054f66e63eda392f8c1"}, + {file = "coverage-7.16.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:76491917771f179f9772efe218c5ccc65950dbdb35f4439298d8a8dfc6ec1f72"}, + {file = "coverage-7.16.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f4aa0b0a6f81fa3deb211e643f6954e78b4376b62b9c218271236cfa757664e8"}, + {file = "coverage-7.16.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:756ba2d96d073c5a2a55d67fa22784763710fadbe22c41adde2d9cfa4dd78a8c"}, + {file = "coverage-7.16.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:99bf9ea435cefcefd220f8687c3ddbbf78dc2de0bd11b57c3ae9fbbdf8d5561a"}, + {file = "coverage-7.16.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:35cbc81f937fc402971df45c897d2df2bfb2014efcd990360032aa0a651635da"}, + {file = "coverage-7.16.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:8fae08e85b334ac6ac886002b5041396a31bcf805225bbe19847627203da99e2"}, + {file = "coverage-7.16.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:83362b64e215ef00b0ba33fcf13655ace6c9fdd144d5ad2ab59ac86c2daf166e"}, + {file = "coverage-7.16.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:33300f2e140ccf26af3d8152e62bff71993f9310cfc63ba7a20940b0d246a0ae"}, + {file = "coverage-7.16.1-cp314-cp314t-win32.whl", hash = "sha256:5539304fdbb2cc144df684d35a33b81145334d23e1c2367b5a923d25107f70b2"}, + {file = "coverage-7.16.1-cp314-cp314t-win_amd64.whl", hash = "sha256:715dcb72c3280c428c3a20134b87e42c29acec9669136e899ab2de69ca86218d"}, + {file = "coverage-7.16.1-cp314-cp314t-win_arm64.whl", hash = "sha256:dac8b84c03e6029d272b8249c77018db83de59ca009a9adef7c144b4a62ee5e6"}, + {file = "coverage-7.16.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:a337dc2d54c74430cd2febb8ee04f7c508ba8b3b412bf0463f077a66cfc73743"}, + {file = "coverage-7.16.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:3acd1d78397dead78dd1b011b5fc19cc823c190349acd549e63856dff649c80e"}, + {file = "coverage-7.16.1-cp315-cp315-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:73a32694603a34ad01d7e51a481a4023410d8099e1d0757e067945695c10f0ae"}, + {file = "coverage-7.16.1-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:fbbe8265736659a6be2e6042b6a35be13545d14b243cc1d7ecf65f90d788a370"}, + {file = "coverage-7.16.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4b0359eb4c62f9993e176bc8f50450fc736a6b90dbcc05bb8584e948812699ae"}, + {file = "coverage-7.16.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:da506e669a8a851b59e122b4b219ea70996a6296f44f3a9348a852526ff961de"}, + {file = "coverage-7.16.1-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:64a2a5985d81810ed605ff0dc4ccd6555efcb5700353825532a9a0aea65826e1"}, + {file = "coverage-7.16.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:66d70132b69b861805dc1ca46cdd733e54c416890e8f1371d2fd103f70b59c9c"}, + {file = "coverage-7.16.1-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:db651a9cf325a542bc2b7b8cc8f1b2bdc6492739bae3103731b2f1c85b96cff6"}, + {file = "coverage-7.16.1-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:4184e78a4465dcda359fb403172b8951dd220929cb0984c02fabca1742fff06f"}, + {file = "coverage-7.16.1-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:bc53c3f3adaa939b7a063533ffe0ae1259e7073393c618043a99a6970a87e3df"}, + {file = "coverage-7.16.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:b44308854ef210b9b78df9cdfd4e159513382a859f5ef8464306d14a54c2a040"}, + {file = "coverage-7.16.1-cp315-cp315-win32.whl", hash = "sha256:dccc142614d3419ed71857deb43f1d757829a4c7fce9994464b71e7e38309827"}, + {file = "coverage-7.16.1-cp315-cp315-win_amd64.whl", hash = "sha256:961fc424e9d5229a99f8f1189942d8e7f4e1519147c3af64842f944aca03914d"}, + {file = "coverage-7.16.1-cp315-cp315-win_arm64.whl", hash = "sha256:681a9488c5a234397c4f013da065aa9e53eb7af4c78f1f80c6f15e7208acb855"}, + {file = "coverage-7.16.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:8bb09a2d19b04db1fa0e087a7ca4f12458f7e0e7364cfcd838441d86fb1c61f6"}, + {file = "coverage-7.16.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:2270a794600b635ca9452ce4c32e2fe81a35f9caa17ffac0eba99f14f275bd4d"}, + {file = "coverage-7.16.1-cp315-cp315t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:a4eff405b545dfcf79cf0d9d3ff750e5c5a887aa066114175193a81d249c5ee6"}, + {file = "coverage-7.16.1-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:ee1d5fc9e3bd6a217906929cc97880239a91d20dae7746f538eb0eefee705ab1"}, + {file = "coverage-7.16.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d4ec944947de098ad5a1738413f9364689a57067ecbc328e9de37218aa1e5cc1"}, + {file = "coverage-7.16.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3f73ee3956fde2d461c9e2955dd48166e4821fc8587d135e8780fb84da2a098b"}, + {file = "coverage-7.16.1-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:1ec9a4ee989c0d06ad95add0dbfdbb72b00ef53f43431ca0b612384e7878e5de"}, + {file = "coverage-7.16.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:7e5727b2508f817f3126d6c33327dda32fe69d15514badfcd61db8bc4209ecef"}, + {file = "coverage-7.16.1-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:19a3ea2f364012ef06678118fffdc92442a16bef4a5c8ad4f4019dd8f9ac8876"}, + {file = "coverage-7.16.1-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:996c2b891b441ec2b39725ee3e8386e2f11b4894b92be225fdfd54a3eeada2c8"}, + {file = "coverage-7.16.1-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:a125fac1f6b1e88488d208a86b578e1790e3c4937f2e1568d23356141d236220"}, + {file = "coverage-7.16.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:b10095528b866d322d33d6bf1709b7f8cbf959f12e8cb2ba22fc59c8717866b0"}, + {file = "coverage-7.16.1-cp315-cp315t-win32.whl", hash = "sha256:531d9be377fdcc05593b974656872eb82e808ebeb42a72515e3aaeb8bb7166f5"}, + {file = "coverage-7.16.1-cp315-cp315t-win_amd64.whl", hash = "sha256:46a88f51770df7c9bc376bd57d3f86cdc7624b8e16ac4b585a655c22b7a1b4db"}, + {file = "coverage-7.16.1-cp315-cp315t-win_arm64.whl", hash = "sha256:7580432cbe1e8b762660ae5806f04f869e1c02e519836a43f8094437e561e9f0"}, + {file = "coverage-7.16.1-py3-none-any.whl", hash = "sha256:3d8bd4e58b6a5c2018d808f297905393c6c61da466a48c3f0596a76a4900ebe4"}, + {file = "coverage-7.16.1.tar.gz", hash = "sha256:f83981779bcf9dfa06fa0a8d4cb43e0faec1706328ce07aa3e7b665b4ac0f210"}, +] + +[package.dependencies] +tomli = {version = "*", optional = true, markers = "python_full_version <= \"3.11.0a6\" and extra == \"toml\""} + +[package.extras] +toml = ["tomli ; python_full_version <= \"3.11.0a6\""] + + +[[package]] +name = "cycler" +version = "0.12.1" +description = "Composable style cycles" +optional = false +python-versions = ">=3.8" +groups = ["main"] +files = [ + {file = "cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30"}, + {file = "cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c"}, +] + +[package.extras] +docs = ["ipython", "matplotlib", "numpydoc", "sphinx"] +tests = ["pytest", "pytest-cov", "pytest-xdist"] + + +[[package]] +name = "distlib" +version = "0.4.3" +description = "Distribution utilities" +optional = false +python-versions = "*" +groups = ["dev"] +files = [ + {file = "distlib-0.4.3-py2.py3-none-any.whl", hash = "sha256:4b0ce306c966eb73bc3a7b6abad017c556dadd92c44701562cd528ac7fde4d5b"}, + {file = "distlib-0.4.3.tar.gz", hash = "sha256:f152097224a0ae24be5a0f6bae1b9359af82133bce63f98a95f86cae1aede9ed"}, +] + + +[[package]] +name = "docutils" +version = "0.21.2" +description = "Docutils -- Python Documentation Utilities" +optional = false +python-versions = ">=3.9" +groups = ["docs"] +files = [ + {file = "docutils-0.21.2-py3-none-any.whl", hash = "sha256:dafca5b9e384f0e419294eb4d2ff9fa826435bf15f15b7bd45723e8ad76811b2"}, + {file = "docutils-0.21.2.tar.gz", hash = "sha256:3a6b18732edf182daa3cd12775bbb338cf5691468f91eeeb109deff6ebfa986f"}, +] + + +[[package]] +name = "exceptiongroup" +version = "1.3.1" +description = "Backport of PEP 654 (exception groups)" +optional = false +python-versions = ">=3.7" +groups = ["dev"] +markers = "python_version == \"3.10\"" +files = [ + {file = "exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598"}, + {file = "exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219"}, +] + +[package.dependencies] +typing-extensions = {version = ">=4.6.0", markers = "python_version < \"3.13\""} + +[package.extras] +test = ["pytest (>=6)"] + + +[[package]] +name = "execnet" +version = "2.1.2" +description = "execnet: rapid multi-Python deployment" +optional = false +python-versions = ">=3.8" +groups = ["dev"] +files = [ + {file = "execnet-2.1.2-py3-none-any.whl", hash = "sha256:67fba928dd5a544b783f6056f449e5e3931a5c378b128bc18501f7ea79e296ec"}, + {file = "execnet-2.1.2.tar.gz", hash = "sha256:63d83bfdd9a23e35b9c6a3261412324f964c2ec8dcd8d3c6916ee9373e0befcd"}, +] + +[package.extras] +testing = ["hatch", "pre-commit", "pytest", "tox"] + + +[[package]] +name = "filelock" +version = "3.32.7" +description = "A platform independent file lock." +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "filelock-3.32.7-py3-none-any.whl", hash = "sha256:65ff0d0190ea42038b32bda4b77834fb05be2cad4c5b9b01aa4dfb3614536e52"}, + {file = "filelock-3.32.7.tar.gz", hash = "sha256:37b8a3d9811b0f9aef7e5ec5c71bb320de52df51e6ca9bcd6f5ad81187660da7"}, +] + + +[[package]] +name = "fonttools" +version = "4.65.0" +description = "Tools to manipulate font files" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "fonttools-4.65.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:93a73af2075036d36d7fbf856779c56a1b3b86ffcdae6abede7596604c42c156"}, + {file = "fonttools-4.65.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c130be2232e3caf8d2b476854ea78421ec1642917ff5ab695284bac31bbb072b"}, + {file = "fonttools-4.65.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e3944e0bdba42effb71959e43d91b599326b02b59c78310d5675e8a75525e7d8"}, + {file = "fonttools-4.65.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:fb53892b570f7f1f0055e75fc4de32673e32f749c4c8a606b63d5c436650e634"}, + {file = "fonttools-4.65.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:a6c8d184e523580a7c55d21cde37176a3c91cb539cf06c2aa36ffc634fd75296"}, + {file = "fonttools-4.65.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:e5ceccaf2e57d83b753a2b5db5d94aa0a8071886d4afebd2d520c9683e6bef0e"}, + {file = "fonttools-4.65.0-cp310-cp310-win32.whl", hash = "sha256:aff640a4fcb021fa83f9879d5bfa115b6931522dae991a24faa75888bd6aeff6"}, + {file = "fonttools-4.65.0-cp310-cp310-win_amd64.whl", hash = "sha256:5c1700a60e4ff23a0425d5a64abf43d092e6b55071354825781faf255904dcb4"}, + {file = "fonttools-4.65.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:06273c71e692caf5989c0437ca50875a5e49e216ddf653228fe9bb35bdc82c0f"}, + {file = "fonttools-4.65.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ca2b02d74e9ad7e21a1d11e4701425800a4b0c63cf90486e60258262feccbcbf"}, + {file = "fonttools-4.65.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7830e9fa3bebc44dbc27ff44d8201def30ea5c48a773696d58e69e6bcd9cd5d4"}, + {file = "fonttools-4.65.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a3991732c87b3f054a2a8cf86dd0d602833fa8cb37c911503173771646e1013d"}, + {file = "fonttools-4.65.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6031e77b3fb8c765055ba2b8bd8dcb17030f3bf2484c448b472fdedf4460ba80"}, + {file = "fonttools-4.65.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:6813cc1e2e883bd6c15b3e04f72c78dc65fdc4ca861063adf5f341fbaec2ca62"}, + {file = "fonttools-4.65.0-cp311-cp311-win32.whl", hash = "sha256:4a5db8442453da4b6f43ad325879381b726bf2238a2253efd9584be21a2cefc2"}, + {file = "fonttools-4.65.0-cp311-cp311-win_amd64.whl", hash = "sha256:9f201796c8e24e657be77c16fa664e798a46122144217f90838982937a964f0a"}, + {file = "fonttools-4.65.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:e844a45c9e5ced6536f184cf1a65b5d65e8f7e711993b413e10500a8223622e5"}, + {file = "fonttools-4.65.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b30e953de049bf43fc0a63c7d0c44d205c923e4bbf24716aae1518c0e65f977c"}, + {file = "fonttools-4.65.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:09c34bdeed8915bfb53bee0c8ed2254dbd8ec69c0014b7f3702f347c049bf358"}, + {file = "fonttools-4.65.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:05595385ae99f4b9626cebb973bf171b8fe38a8f40708e6e42abba0ed7537778"}, + {file = "fonttools-4.65.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d95b34dd68fbfc0e4a1740c421597656117f979ed8dc85de66e08f9f9981806e"}, + {file = "fonttools-4.65.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:924d06e6130429168318db71c40174a765ad016fc4b56ca811287e3d7373b3a6"}, + {file = "fonttools-4.65.0-cp312-cp312-win32.whl", hash = "sha256:04f73dd01005752a6e75cf4a8dc6b70dc724d1d4bc34cc89522153f4a2f07680"}, + {file = "fonttools-4.65.0-cp312-cp312-win_amd64.whl", hash = "sha256:3b5d9ba89edf778b376e669b879ae33a198bf45cf5a23c3f6514f935cf9d0d9d"}, + {file = "fonttools-4.65.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8b7bb52817a24731d2e4f4df0e71fdde05e6c806c8f8f1517b015d142fdacfa5"}, + {file = "fonttools-4.65.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e2c21772fcf70325189707b19f346812690bb1b0bd7e207e6ac205244806b303"}, + {file = "fonttools-4.65.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:64c9b26816415b5e3d899e9077109d327b22140fe3c4066644d8cdbad5bb1569"}, + {file = "fonttools-4.65.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6dd6243f60e2d6160c2966e1e14020dc261ffd741b69a2e4ca8bfd051592e4b7"}, + {file = "fonttools-4.65.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:834962fd7cf21c58e81ac50a59e6ed2306f9df5e3dd481dad1cd7d2c4c60b773"}, + {file = "fonttools-4.65.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:580eb68ff7bd6954a7a76afddd864bfc66eaaf5f5c20dd6ead9186d0055a4ffe"}, + {file = "fonttools-4.65.0-cp313-cp313-win32.whl", hash = "sha256:7a18b2ffd44249fe84289253197aa65ad4f2de554c0d381f18b1f5939bc6bc60"}, + {file = "fonttools-4.65.0-cp313-cp313-win_amd64.whl", hash = "sha256:8ae1846b0f192fd485d26a455af19b8f5cf05aff08f9836f533913d8fcea133c"}, + {file = "fonttools-4.65.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:dc87a9f846bec83c3795804f62b4632716d46e3522869a3dd9cd44a5d245b006"}, + {file = "fonttools-4.65.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:aa50dd7b9baf75e2bbd43401fc0d237f7a94a8ad2e0c57ea97160fc631af5eb0"}, + {file = "fonttools-4.65.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0d2a9892fdb3b7e2d0f4174e3b907d226ff83698249762eeefce08ec5b2de1dd"}, + {file = "fonttools-4.65.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6d815734e7fede0ad1f233f23f0f191cbe8fc64762ff041e589bc0f78e0b2397"}, + {file = "fonttools-4.65.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:71e4c67b6196a2f447f46476fd2302604721617f5e0a21b0988bdd87b6bb9687"}, + {file = "fonttools-4.65.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:b11d8a4a0c3ca74bbd4c105b7ef82501945c939e6096d9934ec7d288cdf5aaa9"}, + {file = "fonttools-4.65.0-cp314-cp314-win32.whl", hash = "sha256:8e44a34d91b3c793879767eb115867ced74d2eb94974e64e72fe9e2eea71cf1a"}, + {file = "fonttools-4.65.0-cp314-cp314-win_amd64.whl", hash = "sha256:0aa8901db22875c831d6a91796549590d7e747da37438f38b69d771b668be445"}, + {file = "fonttools-4.65.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:2e4a380ca40d3a5372e31b340f0da0d53b4583aadbb8e41f6a516afa69c509a4"}, + {file = "fonttools-4.65.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:661bd91c4be13721408b2d4b67a9b3fa7736713adc9a6c9780c9c60fc7959f90"}, + {file = "fonttools-4.65.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:62c5e42c79449def957adf8a9a65a43018efa7e2a6bc6baa3afe955e0d5fb2ab"}, + {file = "fonttools-4.65.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:36fca8efc46b5adfca327c666e739fc05b7a7a6ef17840230f81b22f53230f61"}, + {file = "fonttools-4.65.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8aa1291e4c767abf1b0b79ca2d6895f7c0b661d9d95d03b5791c883a9d1e1f08"}, + {file = "fonttools-4.65.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:fcf39949f56911348514b466714efa9118bec3d2be249e1c487263f7cda6edab"}, + {file = "fonttools-4.65.0-cp314-cp314t-win32.whl", hash = "sha256:ffc918702661f1d74d2fbb2f5551036b64f6d2d743139e105289b694bcd16f54"}, + {file = "fonttools-4.65.0-cp314-cp314t-win_amd64.whl", hash = "sha256:5a977e3645dbffaee924209828aa702a215f7ff68bc08010740c10c723787e62"}, + {file = "fonttools-4.65.0-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:7aa0518b45ff5286ad56f063938db3add3816e899aab58d782b3f9a252523caa"}, + {file = "fonttools-4.65.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:673e2b3ac4ac8e4f3607d390ecc5a606e5db5c4e88fb4cb2999593efb65afea2"}, + {file = "fonttools-4.65.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a03cff943b204a90bf3d1c04c97b9509a8aa0ee99e2e544084ca43ad995975b"}, + {file = "fonttools-4.65.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:41f684ee6212e411196ab054f8308faf6605f154950e6f4686fb8f2103d624b0"}, + {file = "fonttools-4.65.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:52ea9d2a8385075770db74d5e5718fa80b2222bb4fc62856a377dd2865ca8848"}, + {file = "fonttools-4.65.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:d0d25027ade65ec46b13c0436e51bcb7c5171a4ea255a5e7a8d0d1d3ab4cffd7"}, + {file = "fonttools-4.65.0-cp315-cp315-win32.whl", hash = "sha256:22cb846d35d278235ef3b7e947c6040b2057d72e8305a314f21d5342eca49040"}, + {file = "fonttools-4.65.0-cp315-cp315-win_amd64.whl", hash = "sha256:aecc899fdbf9ecbf728f8977977e2e1043ee4d70c257124c8fa4cbcf796fcd83"}, + {file = "fonttools-4.65.0-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:6275863dad195ee34b6e0ca3fc61c74096bc37e5d6fb8e049f4d68d65865a2b7"}, + {file = "fonttools-4.65.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:d8ffd2f62b402180b0edae8f86a071f583970e2177143117db5cf4c52da60079"}, + {file = "fonttools-4.65.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:830f91327ca83bfc1278e7060068a498938f84d05dc4869675486f84f55d4fe1"}, + {file = "fonttools-4.65.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9db2cb95847c18eef74a4ef0fe257a893ae3f4b0395f4866e2f426ab07f3d804"}, + {file = "fonttools-4.65.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:be9b9a95ed0af03375e99020e921c4bc6b41fad10e053dea7acad370521a3c46"}, + {file = "fonttools-4.65.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:bbd9faf777a9deb6790df4f2b0be611857c45fe86605e840d7154a028d828af7"}, + {file = "fonttools-4.65.0-cp315-cp315t-win32.whl", hash = "sha256:c779d838815b91889c95ed64c9be5950ad5a683279f91aeb23384cb757ddc6a3"}, + {file = "fonttools-4.65.0-cp315-cp315t-win_amd64.whl", hash = "sha256:d9484b7ee1b49b6b8a0231c849f3983723dec29e3a7366d9b1b02f4036f71944"}, + {file = "fonttools-4.65.0-py3-none-any.whl", hash = "sha256:3060b8c1fc2329fa20265b7c138614143ea7c1624e26c5c180c76aeb74deae6f"}, + {file = "fonttools-4.65.0.tar.gz", hash = "sha256:762ba5431358d0dbd4a01982484a1d494fb267e91f974cdcf20b80eab8560f6f"}, +] + +[package.extras] +all = ["brotli (>=1.0.1) ; platform_python_implementation == \"CPython\"", "brotlicffi (>=0.8.0) ; platform_python_implementation != \"CPython\"", "lxml (>=4.0)", "lz4 (>=1.7.4.2)", "matplotlib", "munkres ; platform_python_implementation == \"PyPy\"", "pycairo", "scipy ; platform_python_implementation != \"PyPy\"", "skia-pathops (>=0.5.0)", "sympy", "uharfbuzz (>=0.45.0)", "unicodedata2 (>=17.0.0) ; python_version <= \"3.14\"", "xattr ; sys_platform == \"darwin\"", "zopfli (>=0.1.4)"] +graphite = ["lz4 (>=1.7.4.2)"] +interpolatable = ["munkres ; platform_python_implementation == \"PyPy\"", "pycairo", "scipy ; platform_python_implementation != \"PyPy\""] +lxml = ["lxml (>=4.0)"] +pathops = ["skia-pathops (>=0.5.0)"] +plot = ["matplotlib"] +repacker = ["uharfbuzz (>=0.45.0)"] +symfont = ["sympy"] +type1 = ["xattr ; sys_platform == \"darwin\""] +unicode = ["unicodedata2 (>=17.0.0) ; python_version <= \"3.14\""] +woff = ["brotli (>=1.0.1) ; platform_python_implementation == \"CPython\"", "brotlicffi (>=0.8.0) ; platform_python_implementation != \"CPython\"", "zopfli (>=0.1.4)"] + + +[[package]] +name = "identify" +version = "2.6.19" +description = "File identification library for Python" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "identify-2.6.19-py2.py3-none-any.whl", hash = "sha256:20e6a87f786f768c092a721ad107fc9df0eb89347be9396cadf3f4abbd1fb78a"}, + {file = "identify-2.6.19.tar.gz", hash = "sha256:6be5020c38fcb07da56c53733538a3081ea5aa70d36a156f83044bfbf9173842"}, +] + +[package.extras] +license = ["ukkonen"] + + +[[package]] +name = "idna" +version = "3.20" +description = "Internationalized Domain Names in Applications (IDNA)" +optional = false +python-versions = ">=3.9" +groups = ["docs"] +files = [ + {file = "idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c"}, + {file = "idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44"}, +] + +[package.extras] +all = ["coverage (>=7.10.0)", "hypothesis (>=6.141.1)", "mypy (>=1.11.2)", "pytest (>=8.3.2)", "ruff (>=0.16.0)", "ty (>=0.0.37)"] + + +[[package]] +name = "imagesize" +version = "2.0.1" +description = "Get image size from headers (BMP/PNG/JPEG/JPEG2000/GIF/TIFF/SVG/Netpbm/WebP/AVIF/HEIC/HEIF)" +optional = false +python-versions = ">=3.10" +groups = ["docs"] +files = [ + {file = "imagesize-2.0.1-py3-none-any.whl", hash = "sha256:ea0c9a0384df69ed86a943a15cde37d0360b82491b3910dc2215e202e62b5b02"}, + {file = "imagesize-2.0.1.tar.gz", hash = "sha256:b2ba6a4dea487a7ebcd53248d3476aca449d30db12a2dde5e0c5ca9624fd77e5"}, +] + + +[[package]] +name = "iniconfig" +version = "2.3.0" +description = "brain-dead simple config-ini parsing" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12"}, + {file = "iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730"}, +] + + +[[package]] +name = "isort" +version = "5.13.2" +description = "A Python utility / library to sort Python imports." +optional = false +python-versions = ">=3.8.0" +groups = ["dev"] +files = [ + {file = "isort-5.13.2-py3-none-any.whl", hash = "sha256:8ca5e72a8d85860d5a3fa69b8745237f2939afe12dbf656afbcb47fe72d947a6"}, + {file = "isort-5.13.2.tar.gz", hash = "sha256:48fdfcb9face5d58a4f6dde2e72a1fb8dcaf8ab26f95ab49fab84c2ddefb0109"}, +] + +[package.extras] +colors = ["colorama (>=0.4.6)"] + + +[[package]] +name = "jinja2" +version = "3.1.6" +description = "A very fast and expressive template engine." +optional = false +python-versions = ">=3.7" +groups = ["docs"] +files = [ + {file = "jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67"}, + {file = "jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d"}, +] + +[package.dependencies] +MarkupSafe = ">=2.0" + +[package.extras] +i18n = ["Babel (>=2.7)"] + + +[[package]] +name = "joblib" +version = "1.6.0" +description = "Lightweight pipelining with Python functions" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "joblib-1.6.0-py3-none-any.whl", hash = "sha256:3dbbf9f6e4b592a2357b854608e980fe6390d131d7a82f011a377ef2ebef7aba"}, + {file = "joblib-1.6.0.tar.gz", hash = "sha256:2ccc96785b12046c08fd6d55839c12857831b54a3c1673ffadd2f04bfc4eda03"}, +] + +[package.dependencies] +cloudpickle = ">=3.0" + +[package.extras] +docs = ["distributed", "lz4", "matplotlib", "numpy", "numpydoc", "pandas", "psutil", "pydata-sphinx-theme", "sphinx", "sphinx-copybutton", "sphinx-design", "sphinx-gallery", "tqdm"] +test = ["distributed", "lz4", "memory_profiler", "numpy", "pytest", "pytest-asyncio", "pytest-cov", "pytest-run-parallel", "pytest-timeout", "threadpoolctl"] + + +[[package]] +name = "kiwisolver" +version = "1.5.1" +description = "A fast implementation of the Cassowary constraint solver" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "kiwisolver-1.5.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:1acc7e5b7ef05e9da8bb70cd6c7c4513090213d2e1ad9720f599f0bf6c52aec5"}, + {file = "kiwisolver-1.5.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:bad20d4c69c851c982a1e3606f4c293edfd5a87885786c50082412240c4b1ffd"}, + {file = "kiwisolver-1.5.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:0a4faea5c6db201c6a21391d2ac926ea97acf7dacdbc3c417189e1adb1a00837"}, + {file = "kiwisolver-1.5.1-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:e05c2f7925f1d88778e53cb44f14e0223204a3bdd09a41664750363acfb1f2ef"}, + {file = "kiwisolver-1.5.1-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c3a4e41e3096bf1f0f1b76e2ffd6d828d6547f574f702d59bdbef7acfa59db9c"}, + {file = "kiwisolver-1.5.1-cp310-cp310-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f1d56ec54d257d05e0b50f5780d967540cd07beeaf9e5f645b26d50cce79f4d8"}, + {file = "kiwisolver-1.5.1-cp310-cp310-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8de6f2a4ce7e7bd27d23dd94abf0ccafe0e0e5cc9c764b0577191f2c25f08f26"}, + {file = "kiwisolver-1.5.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:16895f553ee6620a827d2da56b871f835fb70b9216cca5d188e885caf6e3bd23"}, + {file = "kiwisolver-1.5.1-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:6b92f60017dda7d877fdc546438b5e28f31c523264f49cf5a48c1d0ce1a0dfbc"}, + {file = "kiwisolver-1.5.1-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:7824b5e8bdbf0bccb4ccd37bbb115849a1dc45437fb4de8351385ed07c437ee0"}, + {file = "kiwisolver-1.5.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:aa7d00b1700966d2917e54d278aba86897890ca9276dd8b76cf6446b6c181b92"}, + {file = "kiwisolver-1.5.1-cp310-cp310-win_amd64.whl", hash = "sha256:96c30002424670b5e1e46495c2b8cbffef39cf77c1d79e76462029d50339785b"}, + {file = "kiwisolver-1.5.1-cp310-cp310-win_arm64.whl", hash = "sha256:f0f4a42db92d6ec7677ab9d12830a2a8ec145a9c6d15db2b593466bc875c78d7"}, + {file = "kiwisolver-1.5.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:b3d78f7bb2b9d9a30345be1474b9aaa8685430b54afb51ba3639b5c6c11e9ed6"}, + {file = "kiwisolver-1.5.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:5025e36fb4fb275cef0a4e30dbb11cb4ae61d1c83deb90189cb5d7e4cafd6b55"}, + {file = "kiwisolver-1.5.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:dc1a26b8e53395a01c2c611e58602fa47461f136fba7cd5542e6db6d64be1839"}, + {file = "kiwisolver-1.5.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:95a02752aa032eef4aed01cda6d9b687c669bd0396bf4519eef8bba22a286720"}, + {file = "kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:719a35fa1156db3640555f95ebb94f60a444e64d1c69626b0edef5df78eba225"}, + {file = "kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:febcce10f2bcdbb80b4ea919238a6a4ac13dbc4c7cadbe8d5d75c3682f8b5404"}, + {file = "kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1d852545c4d0e35a72728d072cbaa59e2fa7dd84bdf01e068d670dd0ceb58eb6"}, + {file = "kiwisolver-1.5.1-cp311-cp311-manylinux_2_39_riscv64.whl", hash = "sha256:2e10ae1bba1899188b33557c10d73affcc12033edd18adddb57d209039976a4c"}, + {file = "kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b69602970994a2ed8bbfa78c2f0394a7435226c6040489702d9f0a0ad0c07052"}, + {file = "kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:d50de98e8d807dc31822fff96f50293163a62418eb65487a21b42713d72ed0b7"}, + {file = "kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3221f78211074f561c44ca42eac0619828171bec15a2c4cf6f7747d07df76e8e"}, + {file = "kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:0ba9527afc80ae3d7814ed98b6572d02bf85eaf48065678342c5f0c6dab7a8c7"}, + {file = "kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e12dfea7f5fc2a34a9080efbf79c4c44eb380ec5b9c6fea09407e08f0d1e941d"}, + {file = "kiwisolver-1.5.1-cp311-cp311-win_amd64.whl", hash = "sha256:1a7587dc335f2c0f5bd577fd0540bd16c66006bdb60f759a1059f025e6c4f071"}, + {file = "kiwisolver-1.5.1-cp311-cp311-win_arm64.whl", hash = "sha256:e4e4523d6f336708d732516e6cfca7796cf3d96c9474eb5aecf6165f2f1fefc3"}, + {file = "kiwisolver-1.5.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:63fb7294b768f444eb4b068965f2662f28c2fd4161e23bd60fcf3ff27b74c046"}, + {file = "kiwisolver-1.5.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:0ebdef3eae5336568147c39a55be6a2036ffde53faa9ca2d978989ae7c2da12c"}, + {file = "kiwisolver-1.5.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1798e83840c3f627246104c4d8a9639c60fa068adf9ce92b61791781fa8a68c1"}, + {file = "kiwisolver-1.5.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34633ecf50d16187ab8e5528b7a2530f2feb4e23f300db4672538b51cfc5cd38"}, + {file = "kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d27c2123977cb9269c30a49ba45f03a4323017ef693e19db4ec9dbe1299a3002"}, + {file = "kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6a797a1cefc8b9c93170db580337e1fe3d011ad18b1299943231279406342048"}, + {file = "kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2551cf9917af48ee7c4b29cc82320489508cf96fd26a51f6fc124de661cd44c7"}, + {file = "kiwisolver-1.5.1-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:38f6e0deb4d0a4615efe0c4efc5990b06ae450ab50a0b321c0b078b6d238c083"}, + {file = "kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:bfd1de989b3330420e29de39352f5c049905c9e3ee67233a50d550e3d652c148"}, + {file = "kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1209042a623ddfda5497e4066c7b77651dde8e1d3a9dd97599dc7e97f3b9b78c"}, + {file = "kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:26e8268480be5061d509e29669d59103c067a26377a56491630ece11762e3858"}, + {file = "kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:d79308fa689fac89cbcfbd4dbfc80b5f95c54c5a7fd4d194be221f9d33d026e6"}, + {file = "kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b03af77d77e50edba2030fd5f7c352ff209314b09030a3cba7c14edf9a09a444"}, + {file = "kiwisolver-1.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:06a6917674de9e0fe3f66f5430787f59a9f2ddb64af9b714eaec547e29ef5c19"}, + {file = "kiwisolver-1.5.1-cp312-cp312-win_arm64.whl", hash = "sha256:ad8b9671348d7c8716715652ae11f85ed0eb99e265a2df2ca490577d69860b2c"}, + {file = "kiwisolver-1.5.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b6ae6a0328f0bc035741820fdeecdcd67bf4694eee03972e843663107122f450"}, + {file = "kiwisolver-1.5.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:886fc26012f0e8b5f69d1cfe6d711f6b11f194621539bf8e6bb1c25c5dc82724"}, + {file = "kiwisolver-1.5.1-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:aefe930d113798330e9462f7874542977869c0613cba3262e2de3a8d5dee8f3a"}, + {file = "kiwisolver-1.5.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:a5ca5aebae78a0bc13c1943af4af615d4966c5b650b05d5aa83b50e427196fee"}, + {file = "kiwisolver-1.5.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:1ed0f5e49d0ceff8b72190824d9e59c062fbbc02c231b853112c78474b3f5ec2"}, + {file = "kiwisolver-1.5.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:77a4c8187a5948d7f8795adb765a3c7b553d07d86d88e43038fc32fc1fb9a3f3"}, + {file = "kiwisolver-1.5.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:74ad5c3dad54a4641b4c28cd15ded70899d04459c6c7aeacafea716be97cce6d"}, + {file = "kiwisolver-1.5.1-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:21e46b23a2da695c364124817bc01d970effd5483147f8d66a6a7167e3f6b851"}, + {file = "kiwisolver-1.5.1-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:75d9b1cf8258462dbdc1eeda718c96ea7f079324c09067f6daabfcf37712b7fe"}, + {file = "kiwisolver-1.5.1-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8fca690b00c4c48f6c2a547b0160ed511357093a4e4c9b47e0fadf3128066d89"}, + {file = "kiwisolver-1.5.1-cp313-cp313-manylinux_2_39_riscv64.whl", hash = "sha256:876bbfd276473d3daffe30e8c975df4ed9429967b41a6cb362dbb5155b6f13ad"}, + {file = "kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f942903fde7363d1d879057ec5de01310efda2597161784d752fa9953a01a71a"}, + {file = "kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:c90d3022d8a94778939cda8638c6c8da8fa757b8958dad7ec868ce29c87681b8"}, + {file = "kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:8a34616dc2521cc8dc1d7d081734da63539f021ac0450ce950908340c6e7aa2f"}, + {file = "kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:8bf4df63592c2a66b4f8edc5df2544998c288aa02f96ce0acd880cd1de8c8127"}, + {file = "kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:d09037ca068d784ebc4aec290ef952ca27ac15dd9c0b5801a88c6e1096b83e6b"}, + {file = "kiwisolver-1.5.1-cp313-cp313-win_amd64.whl", hash = "sha256:dc23390afe9f4ef9ac3bcc72a03a56eebbde03f4c571a32cb38f859cff9a6524"}, + {file = "kiwisolver-1.5.1-cp313-cp313-win_arm64.whl", hash = "sha256:186884a58486651e3c217b6acea0a53eaa9498fdd472057c46f2f0fb5c25aad5"}, + {file = "kiwisolver-1.5.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:0324cd2567259b7a095f6cf18a52b0ffc6f3de9e69528ff1bc0e7a37bd43ff1a"}, + {file = "kiwisolver-1.5.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:74ea337e0ec3f6f342a36a4f1b5cd94dd9affddcd28ba9aae2905af932ee8c6b"}, + {file = "kiwisolver-1.5.1-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:ee9df1f0d77b9c6e94f4ac0fec533fbddd5ea3a327807f18d7b069ae019ded80"}, + {file = "kiwisolver-1.5.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:fc271a6f0a2126958f4090e5507b9da5848927dae331f8f763bd4aa642b3d2cd"}, + {file = "kiwisolver-1.5.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:9b3092d8992a1d69b7a59c3e39f35e1b9be327a17f68a7c35fc17329e337d6f2"}, + {file = "kiwisolver-1.5.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c2306e8bb53601979fcb3fa09cc65e031876d9ae01eff2fcbcd7a84ef94d5bc1"}, + {file = "kiwisolver-1.5.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:18a0cfb124546a4c2e6087c5f3029c7f44b37c85b142e0ced71f73a7599ac208"}, + {file = "kiwisolver-1.5.1-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:34ec467940442c9943016fb2d4c81d1ba84351eeca2f1a78f8bc87f1ba0d414c"}, + {file = "kiwisolver-1.5.1-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a83ee7107df13abe42a54a6654670eef9bb39425cf2e27f65e0007465e1286ab"}, + {file = "kiwisolver-1.5.1-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bebb89489b279b2f5661bbbb2abcc87bcd4a46607bb4a5c966f04f1db6b8df9a"}, + {file = "kiwisolver-1.5.1-cp314-cp314-manylinux_2_39_riscv64.whl", hash = "sha256:509735237ae0d849e8a843551d423d2500d2e0a9ac1611a145658b29c0fb9f85"}, + {file = "kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:824c3d763a05ea9e9003610145186b0e9848c7584a5575c79bac5a8e7cd80bad"}, + {file = "kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:1fff05e239575b1481b6ed1a782f6fad616efbf1f0b1f44e6e85c4dfe426e483"}, + {file = "kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0627b9bceb9c3cdcf12b8a18655eedfed2692b038df27423383c120d0b7dc2d6"}, + {file = "kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:8a708a47ade1fe19e8371d5da076bac0dd4b0a5a7985ad6c637f7f7e361b6baa"}, + {file = "kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:007a5553dfc4f4e8d184f588a0200e2cd4b63a59cc8796df3c39909e679dc7a0"}, + {file = "kiwisolver-1.5.1-cp314-cp314-win_amd64.whl", hash = "sha256:f4167e87b397f273dc2356fcf1eaf50a6bac51e6105f45103ef7129c8efb0255"}, + {file = "kiwisolver-1.5.1-cp314-cp314-win_arm64.whl", hash = "sha256:5c490db2168a508088f59140dd392556a54b8bd1048fc6383c8baff13c359673"}, + {file = "kiwisolver-1.5.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:4d4ca09bf13cff792b1884f64b98ee6c2467930d632233be25c56b442d99f10e"}, + {file = "kiwisolver-1.5.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:44b8faef94f1857e77fa0238f3390ff1ac51d2ea20a487e2e452a59fd2b5f5ca"}, + {file = "kiwisolver-1.5.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2ae70bc59790d2af72a3f76f24b272403e135070340281108b447cb77ea70819"}, + {file = "kiwisolver-1.5.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:43844c1a7ad6d723d5b5b4c4fc7f5bd399c40e288120d16257c7c9e8765c6e85"}, + {file = "kiwisolver-1.5.1-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:22d5e5aaad6be121f2515765e3b1c444352cb8eb4c86510801db8f2e50757316"}, + {file = "kiwisolver-1.5.1-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3fa5855898f6d3d01b72ccd48a2d65cbdee301251603fefe34e2025bddba219c"}, + {file = "kiwisolver-1.5.1-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d66a64dd5dec136040ec2ae94aa026a912ee60fdd45bc28d3db30037fd809e88"}, + {file = "kiwisolver-1.5.1-cp314-cp314t-manylinux_2_39_riscv64.whl", hash = "sha256:9e51c119992ea8820706871c30a4642ec76de20ae82f9b50b9a45517d8e9f810"}, + {file = "kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:70ed9a45c7484d2b30cdacf60d220f494a1763b9fec1ad03285c6553fa0889f2"}, + {file = "kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:98b208a7cc42c803445ef551d6753cc42a5ea13e9cab1ee66cd8b9cb70195330"}, + {file = "kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:c6834b92dd2428e2dd85ef3d85f723d3c12f20aaf43a2ddd4f944ca25d833408"}, + {file = "kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:5d142e352eb13facc7dd047489aebdff6ba78576c239f1ea04931979caaf0567"}, + {file = "kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f9b1c4900736e489a812c529100de4b8fb617d4db075e931e213c57424b83d9b"}, + {file = "kiwisolver-1.5.1-cp314-cp314t-win_amd64.whl", hash = "sha256:5978c3340f16a35c30f8ab2fa7bcf559973c55f1a5ef6970e1f621acf3c4db13"}, + {file = "kiwisolver-1.5.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ca307d6c259e5c98d3cb9ade55342b47a6839762caf2536f3d7b46ee660cc82e"}, + {file = "kiwisolver-1.5.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:bb7c99f0673c03017a3ee01e54a5c2617a05468b11eabe513b0080e063ed95b1"}, + {file = "kiwisolver-1.5.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:0d8924877ce22e17326a99a418c3c82037da078df3c6a260b13eca677444e6e7"}, + {file = "kiwisolver-1.5.1-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:534f02c1abb31ed6dbd3515545285c330b2f12d00fdb1fdb71658b9ca5a13a6a"}, + {file = "kiwisolver-1.5.1-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:cea20da04494e662b83c872683bf4ff2345206043d036315ed0e924b652e7294"}, + {file = "kiwisolver-1.5.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:7fd82debf43c6acd0a94359d232f6bb516ee13f269a7993736a9ac9f988bb5d9"}, + {file = "kiwisolver-1.5.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:18170a77ddfecf40ec60d0928268dc95880c881864e015a8f34094ed18b9b9ad"}, + {file = "kiwisolver-1.5.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ca7f6fe0f37ca978a1e5eb7a3a68e6413f417e78e838324947ffd420202b198b"}, + {file = "kiwisolver-1.5.1-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5b973887ff782cfd6b67c9904ad8ca542e0bc5e4961503408b423b5a688b4d38"}, + {file = "kiwisolver-1.5.1-cp315-cp315-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f76fc85bd054c806960f917ec0f329e24e436f1712267d90588e4c39890caa63"}, + {file = "kiwisolver-1.5.1-cp315-cp315-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:828f75af2b0080c8a972e75f649ab46af008e92c6104a57a759157200b835b75"}, + {file = "kiwisolver-1.5.1-cp315-cp315-manylinux_2_39_riscv64.whl", hash = "sha256:431dc224a1a92a5c8f582d96e505196a3b5997a7271076678da2dfde67b77e9a"}, + {file = "kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:61e9a64c7635095a6bfe483e2ff055d437c59bd45f3617a228b37277f0185d62"}, + {file = "kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:3c24cd69455e1b00ddf770c13b6e2c33e07d6dc3f2d34add0bf9277c5c6bbd46"}, + {file = "kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:27add358abe374ebaa3b8763ef380bc99051b5a4b18d94878366a9e4f59efef0"}, + {file = "kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:255605693a483db7bd5c79f60437f7bf658f7f520d61aa42722e32257c941951"}, + {file = "kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:7d38b0c279c3032e8c9cc013b405c6df8e1668dbf15465779aa7f15f61201812"}, + {file = "kiwisolver-1.5.1-cp315-cp315-win_amd64.whl", hash = "sha256:958254518717542d02d0688d0d20cbf771da5e415e6f49543f92481c850a4540"}, + {file = "kiwisolver-1.5.1-cp315-cp315-win_arm64.whl", hash = "sha256:da3275833be0edbaf4830fae08bae3dc7219f40ce0c37eaa6c25825957e06612"}, + {file = "kiwisolver-1.5.1-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:470d420f98d368d6f010633a20659b544c5fdfa5329e6b70219f2ef08fd4a7ef"}, + {file = "kiwisolver-1.5.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:83f78128fa28705fa85d01c59771c72fe81c11bd0e6155edbb9f818983a7d761"}, + {file = "kiwisolver-1.5.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:9506e892bcc3b409831d363c6f53e5985e1c8d1f6f6b0256d00358684ff85378"}, + {file = "kiwisolver-1.5.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cea90547bfd93807e0013a004dc76552be44fad3bc1cc2b38610a9e889ed098f"}, + {file = "kiwisolver-1.5.1-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e8e4d953faaded9ec7ede36824e9814082d22d4c7b1eafbfa079ecba8cd0d076"}, + {file = "kiwisolver-1.5.1-cp315-cp315t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7e9c01d3dd7ceba4d1d436cc021d40d592466e40b9bc7f5d83dc4e98a5c9cd8c"}, + {file = "kiwisolver-1.5.1-cp315-cp315t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:37f801b5d7cc0e5a548921308e059fd2b057bb42972b591cfa3049f95423c4ed"}, + {file = "kiwisolver-1.5.1-cp315-cp315t-manylinux_2_39_riscv64.whl", hash = "sha256:e68e151428b5384f766cd25739bf77c7e4a3dc93b5ded7a12118d9fbfdf78ab6"}, + {file = "kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:8f8fddb8e323bd6eee4e54e69a39243beab22689070f4c66b472c4cc88bb89d8"}, + {file = "kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:3cc210010fd2f438a3ed430b45f1b501fd13a8618bf984dc2c5ce5b69b78752e"}, + {file = "kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:b5664603a253efd3a75716d793d1d3a6a82723b61dc6db767b2460bbbeec4c0f"}, + {file = "kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:a7b85b2cc6ea45e5f7e8c9a30bc9fabd47cda09106cbb4b967335c3e6c43b69d"}, + {file = "kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:ab620eb663952455271ac37f9aaad86b73c969c02f11f53cea405b38e96a4300"}, + {file = "kiwisolver-1.5.1-cp315-cp315t-win_amd64.whl", hash = "sha256:cb6fae641357ed2f6e533c0d3c6504a4a5703621a50c89459e46051d56b61140"}, + {file = "kiwisolver-1.5.1-cp315-cp315t-win_arm64.whl", hash = "sha256:b390aec180a7c054919c04898835e1c77bced23ea8383eb2c570213bf25d1a86"}, + {file = "kiwisolver-1.5.1-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:482676e5bd48d70ac99d9fc78863469845421e01184fa83f1f9366dc49f7e974"}, + {file = "kiwisolver-1.5.1-graalpy312-graalpy250_312_native-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:072bdb15a3c19a5b5dbc8f8fb1f4e1884bf4f3507eeb4cc6334401274d37a5c0"}, + {file = "kiwisolver-1.5.1-graalpy312-graalpy250_312_native-win_amd64.whl", hash = "sha256:a5a00665d1a0e26763a7338d7e911d4598fbc1d50dd0d6b7919b7dc6c5d6569f"}, + {file = "kiwisolver-1.5.1-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:a5716a33bfabb2c6ce27b6cf03253467b3804f83e215f4d202685cf93c6c9874"}, + {file = "kiwisolver-1.5.1-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:685929988b208a911f1285e2f8ed54210b0d681a3dc0f03e00d599d291986e7e"}, + {file = "kiwisolver-1.5.1-pp310-pypy310_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e4e49f7e1a4e7191bdf9dc67a974db714501b1fc52c24324103d06a86abd5c08"}, + {file = "kiwisolver-1.5.1-pp310-pypy310_pp73-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f0a887b6565bbfe80efde2b7f6e8890d7d9bbdb11bdb17028a3690c32fe0621f"}, + {file = "kiwisolver-1.5.1-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:1983f0974a750a6f6556f368ba11105d1d8369c735b944747c9f12ae5aea7aae"}, + {file = "kiwisolver-1.5.1-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:416ba7ff9f233b7036689bb5a3783537e838ad483f63558d2a800f75afe738b1"}, + {file = "kiwisolver-1.5.1-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:8af9b142ad719ae3a911ebf616bc4b78b32bbab84d6a40d3ad2f129670509957"}, + {file = "kiwisolver-1.5.1-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5daa1f19e097050b9c4d9a78fcc9263cb96c9dfae08037ddc1b7c4ad1889f2a2"}, + {file = "kiwisolver-1.5.1-pp311-pypy311_pp73-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cdaeeb6c350106df6bf9d873395973e5f066a9713200b72cd64f55d0a3eafab6"}, + {file = "kiwisolver-1.5.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:17851e5dad4484be0cbccbde3b15331deae036de9aebd45eed964487802b172f"}, + {file = "kiwisolver-1.5.1.tar.gz", hash = "sha256:f1303ef2eec81262a4b708c3e858afe58d7c75ad91c1c05266eda7673369859a"}, +] + + +[[package]] +name = "librt" +version = "0.15.0" +description = "Mypyc runtime library" +optional = false +python-versions = ">=3.9" +groups = ["dev"] +markers = "platform_python_implementation != \"PyPy\"" +files = [ + {file = "librt-0.15.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e1a49adf16a7c9d9646816c2946135527197b6fcf4347c7b8b761cf1bfbf4489"}, + {file = "librt-0.15.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:81a398f45b45a59200e13cd5ad1ae1d3f44334de98b148331afe2cdfee701c52"}, + {file = "librt-0.15.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4eafbaff06b9563f8b1c850621ce51605de05208e09d4d71ce490bc972b7b9e8"}, + {file = "librt-0.15.0-cp310-cp310-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:b0411b4066db926b80258c60dcb0e6db4c9cee312eab45b7e8866b17ddf9ada1"}, + {file = "librt-0.15.0-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:febb1ce6cac545a54e6b769982824e955a700fdd9fbf3a08a3d82c990968b57d"}, + {file = "librt-0.15.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b230acc1c3bfe2d6f2627ba2b95dc92e58aa494600e9722d0e6ccbc931e59702"}, + {file = "librt-0.15.0-cp310-cp310-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6da110e5f314c19ab8478464d02ae18808ae73d522c15260fa4918acdcd64da9"}, + {file = "librt-0.15.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:eab9208b00ca55bf75983ec99f7bf13acc746a36102e98953addaad7f7ea1e1b"}, + {file = "librt-0.15.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:6c013cd3a1721e69e14380ada97eaa4b7b0cdf1c6b96fa765d4ea47c875088db"}, + {file = "librt-0.15.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:567b1c430f8bd560e689421468278ac5941bab4a05303b5d95b6ae10db03f451"}, + {file = "librt-0.15.0-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:29c4cab9df457b19672c39be7f384ebb2bc925c4e2684b8780c222b43eb36389"}, + {file = "librt-0.15.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:bccbd8e5b0bffb7106cf18eb1baa3d7194b1cebb3b4b1cdbd4bdb19382a6ee6c"}, + {file = "librt-0.15.0-cp310-cp310-win32.whl", hash = "sha256:8ae493ed5f659a7761c43d42f183db514536073ded9bcf671d2d1df47e29a07e"}, + {file = "librt-0.15.0-cp310-cp310-win_amd64.whl", hash = "sha256:bc25fb356d0c7810bb49ff3df908ad1fda6995d660ab099ded69244ed7ab6053"}, + {file = "librt-0.15.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:823b92cf3c18ecd08afc70c42473888b41b6e8ef5046f3b82c05c154a2fa3d22"}, + {file = "librt-0.15.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c70bc1b602cf59917e8f0c7a2cbc8bcc6fbc14d5486136b00707a79619121d63"}, + {file = "librt-0.15.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:814ff83a25b5fce8b9c80c4dd803153fb5c5599fc74db9e022466938368957ef"}, + {file = "librt-0.15.0-cp311-cp311-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:57f5eeb6ad4c180de583b1038e61fe5fbd9796bb69a8a1c1a0c7ddbec4c8c60f"}, + {file = "librt-0.15.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:82909c8f7eb9952656b65d3147afde4cf8e6d5a991eebc86418b5e65843b0ab8"}, + {file = "librt-0.15.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f779070399f991400fc451719e0ea388eb7de313388bada2c127a35de05f798a"}, + {file = "librt-0.15.0-cp311-cp311-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:bac89069bc496ebdf4f79ebb57bbd10d0b214c8454225deb672d91002bd17e18"}, + {file = "librt-0.15.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:e0d00c708fb2f5822b152429b1ac80a58dbbbc3f6c232c4d13a3f7fcf2ea5b4c"}, + {file = "librt-0.15.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:6c6624fe268625869485553dd7cc1daf30d22558215bb2a4ff16f67a9801a31a"}, + {file = "librt-0.15.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:f56b397858a23dacf35ede366ed2212fdc03a6a57a1ad36468ad6e9dc5fac091"}, + {file = "librt-0.15.0-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:4388184646efe2054911c5b00a1077d6d1ee86a95b7e8ba96dc7850a809f3f40"}, + {file = "librt-0.15.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:97335f59082f9fe2ce6c2a9cc6433a0114bbb6cd4d5c09dd76c95c68b9f9a8b0"}, + {file = "librt-0.15.0-cp311-cp311-win32.whl", hash = "sha256:83380ffde38062a2e9bb55d83e74474f6614665528b98a6928720fc006dfffbb"}, + {file = "librt-0.15.0-cp311-cp311-win_amd64.whl", hash = "sha256:f75720477ee05d509a310e856cacc8d909adc182f7b91193c207bcc26d7ee6db"}, + {file = "librt-0.15.0-cp311-cp311-win_arm64.whl", hash = "sha256:256237037a3ab001ae8d9803b2d43562a4c3aa38739843694349e4d5ebb0fd56"}, + {file = "librt-0.15.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:e87bc679f86a99aa3b26e3c78eeb821a247c9a28eae48eaafcc32c3bf4c3bb9e"}, + {file = "librt-0.15.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:71599e011ac880e8e45d46047d714871894c7d4ab6f25626f8d4f89da21f368d"}, + {file = "librt-0.15.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c802434092b769b1d613ed2e13fac15fbfce1934a74bd10283b03c0fae231cd1"}, + {file = "librt-0.15.0-cp312-cp312-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:5500eeae393a184d14e1f35645962c27129d20c81afa4069e6ef826ebc2b3aaa"}, + {file = "librt-0.15.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6ecfc32dfb46fb7b565bcd6abf9412acf978775a998273d22888a6d7953730dd"}, + {file = "librt-0.15.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:89cc46cfd15022e35084355478c9ac809d90b1152222706ac9a7655ec21df6fa"}, + {file = "librt-0.15.0-cp312-cp312-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d5f51401d102c885b9ca509e62c79b1dbff286e1b9b047fde6f763780789356d"}, + {file = "librt-0.15.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cc30523e3f1a23fb7511cc659834a0d01a1042bb9de359bc1c131cc4ec6c9656"}, + {file = "librt-0.15.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:59fe030d8ae4a57e3fb7756bf35a858de74e04066fc8555c53d0af979132af81"}, + {file = "librt-0.15.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:5a6526a2a956bbb1e4ae3568c82e650fc99119c66bb011ea60715744955a2b4d"}, + {file = "librt-0.15.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:85ea21ec6730194d67156b0e0b5430ccb1d61f8b8b907e39b37f9812b74a13f0"}, + {file = "librt-0.15.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:1e47b8ba865d7ede071a91a7163073bbaeb72541f1ef8a07d512c45c7b5007f2"}, + {file = "librt-0.15.0-cp312-cp312-win32.whl", hash = "sha256:a5207ec414d1c4a2a7231b2086970dc036f94293cdf338190984958a013a42f1"}, + {file = "librt-0.15.0-cp312-cp312-win_amd64.whl", hash = "sha256:73b30cfa976659b3917c8f6153bdb0591c6a9ec6583599fd24a689b690622022"}, + {file = "librt-0.15.0-cp312-cp312-win_arm64.whl", hash = "sha256:a54cf9e0ef47b96af580849db5471142200568ce1e02cbf416addab551369570"}, + {file = "librt-0.15.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:db13ca398005abcbe538deda87b686d9bd08b7001cf40c4c06b444960ae10a26"}, + {file = "librt-0.15.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:aa1f1995789dca3698bc550aaceb09a51bd5df0a057ff84ff15296cd1975b801"}, + {file = "librt-0.15.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:55456ea87d8df21808446d03817be2f65e20391c1c615d9187440dff28cd08dc"}, + {file = "librt-0.15.0-cp313-cp313-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:5a86a5a08c2235316bdb359d5dbb6ce0abfca7fac06363103e2c5af571d92f95"}, + {file = "librt-0.15.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e56b6a368529bed262da40ce13f8fef590db0479819cca84f16a1f01ac356d0b"}, + {file = "librt-0.15.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:234d8d394721fa0d786af15ebf1f3fb7f3ed82fd1cd0cde45c2f247b5d4281d2"}, + {file = "librt-0.15.0-cp313-cp313-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d8363d7accb0286ac3a0e633f396e93800dafb8150494505daf9515bbda591f3"}, + {file = "librt-0.15.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:0f0ee3644d951f31055ad07d77d92520e84505dd7a432cc4cd501dd70ee06785"}, + {file = "librt-0.15.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:2cfd1a81a648806e6a7717be4cc4d1bb392fa229752bf8444ba365e381e984d6"}, + {file = "librt-0.15.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:a6cd22c9da0d866558e46a041f1cc0c2bbb26b61b137b2347fa834c332e1d101"}, + {file = "librt-0.15.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:6d5225ef8801e4ea5e482fa9b5dfb891dd9ef6f6d870f1f25d449ca2c70ac218"}, + {file = "librt-0.15.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6d28a05796b99f749bf8794f17ba9ba1612d0076b802e9cfc62c554634e9ce3b"}, + {file = "librt-0.15.0-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:2067ff438048cead9d223ca5675bae2a25e520a7c3e6c1498bf9c6892d22caab"}, + {file = "librt-0.15.0-cp313-cp313-win32.whl", hash = "sha256:1cd3b721f24c206398b9e26da3c3a9c011e6e89d06f318ba8ebefc30f1003890"}, + {file = "librt-0.15.0-cp313-cp313-win_amd64.whl", hash = "sha256:f395a4a9a03ac062dbe9a9f82e0c720502e590a38feee6a757bc82e9c63afbd8"}, + {file = "librt-0.15.0-cp313-cp313-win_arm64.whl", hash = "sha256:0a15cb554761247d84a3ec0cbdf4078d70725384f0e4662c0fa3b26266eb60ad"}, + {file = "librt-0.15.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:f5de7feedc56337a088eb15cd9fafa9938367362221d8cc62c642b7f94821993"}, + {file = "librt-0.15.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:6c0eb900c0e91f4aebe680845242e614f1864edfd44106380d0752ac29522bf8"}, + {file = "librt-0.15.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e8c9a650a188e38bac005048cbe6342e81407782944d01934540ab75e417df21"}, + {file = "librt-0.15.0-cp314-cp314-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:92bfed8deec93df30286b9fe9e3b1dd17329cc076a192b4ee5ec223841d54953"}, + {file = "librt-0.15.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ec4b19788f835711a2072f9dbe6b03b3bf32ed1f0fb30cf399bdd59d9f0c33fa"}, + {file = "librt-0.15.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d4c7bacb70930f3d0a56f4ecf1be474a1f0d941b01dd73b756f3c256d42cb879"}, + {file = "librt-0.15.0-cp314-cp314-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:3e79f05e4a08b4d880342673312bbc895b56df7765605796f15902eb5367d3ae"}, + {file = "librt-0.15.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a417149c0cba4d50b61e992e5a15e69eaf96746609b461cc4ed168aeef6b79dd"}, + {file = "librt-0.15.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:da7a94d6a3411f579d72aa3e3bc5fbca7ed4549f3dbd7e5de3aa567333374285"}, + {file = "librt-0.15.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:856f743ae607f2c1380eccb566c0038a9fb3eabf0fc2be2704d76d9f73557239"}, + {file = "librt-0.15.0-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:779a6e7c894737e5983e7790a9c78c4000c30e23c9aada08081bdbea53b0fa60"}, + {file = "librt-0.15.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:96bb17dbe8bab3c0954fbebfc69ed395599de75b6bbc35e3270a878e15d4dd65"}, + {file = "librt-0.15.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:7220697efaa6e5348fc3d18ee7f8563d4bfecd9872b37ffb915bfc1d08840622"}, + {file = "librt-0.15.0-cp314-cp314-win32.whl", hash = "sha256:f54598964d357b1c5ab77cf5d92f21e598fe0e23cdbe9618480807f81b4eba15"}, + {file = "librt-0.15.0-cp314-cp314-win_amd64.whl", hash = "sha256:3ff5893a2c23d886aa9ce786de5ac6ddc74aeeaf90743682b74d920e117d2e28"}, + {file = "librt-0.15.0-cp314-cp314-win_arm64.whl", hash = "sha256:3722a099730704c9a3d70c879fc0f51daec25fe5f1555672d97bc595abeafb95"}, + {file = "librt-0.15.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:38c0c7d4b6fc06c3324b3f9162c8391bfc4fd9dde53afe1033ce7edb48d5a714"}, + {file = "librt-0.15.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:8b2fdd7ead3c995c37940a790690660d0ca006c302db26cc51933f6766866fc3"}, + {file = "librt-0.15.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2fde98cf1fc4bac144ce23c2c4c017b924ba714509ea9334977b0b27050c837d"}, + {file = "librt-0.15.0-cp314-cp314t-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:e3b461183c5fa7681b48560f91515f53a953122fb30c71e07abc67d7ddf58c38"}, + {file = "librt-0.15.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4bbcc257e3babea20a91715c361b24554ec4e8f51aa578568afc230799fe1a19"}, + {file = "librt-0.15.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b845b8d48088fad0cadc84be4b8fda63203be7e9237b71015b3925443c1f35ab"}, + {file = "librt-0.15.0-cp314-cp314t-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b30e600e8f337b9bd7f39b86d9fdfedc73cc46e3d0f745931a23a234220bb7e2"}, + {file = "librt-0.15.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:64b0c8c35aa4c4ed79896359f3e0b285cbe4e610042106500da4811c322cc108"}, + {file = "librt-0.15.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:0da0d94cb802f32a0524653e7201f2cef72d5f700a5407678f5290483d4fcd08"}, + {file = "librt-0.15.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:4a6369168d371207339b1e50d4532b06a7121586141f82599505a3f315751d47"}, + {file = "librt-0.15.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:c434e072557ade9cbc642d052c89d031efe47d5c9614523619d0d74a02378e81"}, + {file = "librt-0.15.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:c7eec6a42018bc1d45763b1c162d3d2bf7c3b9a1b0ed30d3e91dcba390efefcc"}, + {file = "librt-0.15.0-cp314-cp314t-win32.whl", hash = "sha256:6912fa5e635d74529ac7cdb1bdf6ca3af4453da8d1edbe0110ee1cb4ad407ebf"}, + {file = "librt-0.15.0-cp314-cp314t-win_amd64.whl", hash = "sha256:8e11699ed745931c395acd3621b07062e0f840efa6935aad87a64ed0995f0915"}, + {file = "librt-0.15.0-cp314-cp314t-win_arm64.whl", hash = "sha256:5d2a91724463bfed4f573cd7a9fdc856d2e230d0c0e5a61416a93481dccd8605"}, + {file = "librt-0.15.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:8443e38dcfcfdbcf5add5118c623efd788d65ac2e25756d6251a54a06a4d0aca"}, + {file = "librt-0.15.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:6d15a29033c57490cfe2069097c6fc4049e4e65ffbb749be7dc453b7c4c68965"}, + {file = "librt-0.15.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d2c05c729b589e734c09578bf5964be48a911765484840d017bbc84f49d4c4ad"}, + {file = "librt-0.15.0-cp315-cp315-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:fa60887537e1d0cd2d9982269d33a709bf54b195cd2b9364fc0a758022af5bd9"}, + {file = "librt-0.15.0-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:d8bc24219b24c0af375718942ab75e3544b2763085f40f965be4326734ae8328"}, + {file = "librt-0.15.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:86a21a7bd3fe3a419512ef424cc1c020f6771d0b29cfddff36d1635a855e63f0"}, + {file = "librt-0.15.0-cp315-cp315-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:dbab647e88d90b3167b91efe7091e248653688ed4337e4f90907a722c7361bb9"}, + {file = "librt-0.15.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:d8edcf6f550e918dca779c069b9e156385c60b406f99fc7641f32c52f7193659"}, + {file = "librt-0.15.0-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:8b62076030baa2d8b1501a46bf0e19c27a489aa90671c55665bff7887f7660b0"}, + {file = "librt-0.15.0-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:d00d20d1818e82a07a0ee0aa89a98b17ed7916b92441090b683719cb20a59b6d"}, + {file = "librt-0.15.0-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:4e6ee93fc3cf848dcbf0cce2eca73d8e7dcd0cc2b6df3a529d57750b30a4c55c"}, + {file = "librt-0.15.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:32896a0af72508ea979e0acb4e4c04cbeeae04938167950d535c83c45597167d"}, + {file = "librt-0.15.0-cp315-cp315-pyemscripten_2026_5_wasm32.whl", hash = "sha256:ec3ba415afaf951f6951b1dd16d3c8e4f540065fc382d7e70b823a79567ca374"}, + {file = "librt-0.15.0-cp315-cp315-win32.whl", hash = "sha256:d2813ba2503764f0450680c533d13df7cff9b49df1411062eded5f67db4195b9"}, + {file = "librt-0.15.0-cp315-cp315-win_amd64.whl", hash = "sha256:b87d67e33afaf265262f2a66db578284b88ee2e6fcd224579cb5c15518677ad8"}, + {file = "librt-0.15.0-cp315-cp315-win_arm64.whl", hash = "sha256:713bd7df21170b982e729e46870f31d6b437bd1a9b4648cffb529bd3c2ec5c4b"}, + {file = "librt-0.15.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:3de789c82752730f94782a5ee518baf9c05edf85733aeaf73bb6e518755cdf54"}, + {file = "librt-0.15.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:e0b5deec9a8664eb722c797241970fd4aa1894d25fda36a1ddac0f7407606bd6"}, + {file = "librt-0.15.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5563302a8359bc2295bb7084d1a8ed1519df96afb30eb2aa4e0bff7b54228988"}, + {file = "librt-0.15.0-cp315-cp315t-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:22d6263b9d39d7bbb286fa791945646e3218f1be2d693e36fb630f1d0e59cd13"}, + {file = "librt-0.15.0-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:39ffd14646190c454f0d86e0d256b33f00a87a26ab410e619773b841d0e41416"}, + {file = "librt-0.15.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c47318cd3a61401452de11282242937e3e057c4fd3dbaf601e269d0928a06c0a"}, + {file = "librt-0.15.0-cp315-cp315t-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a56a1d4f859a82ca5b99fc4b82c9b027b15e3c455c5cd99e7d0719f27bb20b6c"}, + {file = "librt-0.15.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:077471b3182db4e17c36ae91555f36a4d2c00080b267f749bcad34a478a9a302"}, + {file = "librt-0.15.0-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:411ca4d1b905b860ceba7570dd6717a71dedaddcc4b0f77ece710aa41ee11f8d"}, + {file = "librt-0.15.0-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:1256589e0b0adb31751d685a68bce29d73407ddf4ef05d4188f49d5dcf9566d9"}, + {file = "librt-0.15.0-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:f42b74a53e5f26a0ba0007411a7455b66c67ce4022a39cc1f56fc4efd65bcbab"}, + {file = "librt-0.15.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:291bf73caf78b9e88d6fae9bfd693207ff7d832e2fdbe2cf8e746bc13f5f892b"}, + {file = "librt-0.15.0-cp315-cp315t-win32.whl", hash = "sha256:c16d15ee371643ab48dc8248a3e680ebbeca573a13af2c3dd0c985b142d77162"}, + {file = "librt-0.15.0-cp315-cp315t-win_amd64.whl", hash = "sha256:dbd605739f228912dc49027cb764456b9757750bdc2b6b7773164db7096c6fd1"}, + {file = "librt-0.15.0-cp315-cp315t-win_arm64.whl", hash = "sha256:84d244b00604d17df3fc7736c327892d6bba66181254aa4087be807b6c342bdc"}, + {file = "librt-0.15.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:0e2d0c0acf5b0ada7d045912b7cf787c21315c95b38b1fa939ef72d45d366b3d"}, + {file = "librt-0.15.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:f9ca190fe9edc0eb08eec558a509a16d28d91c35667b8f043cba40ed5e77a959"}, + {file = "librt-0.15.0-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:80811e1c42386ea95c6fb30571d3250ad43d7863f883f787f70517f441150e59"}, + {file = "librt-0.15.0-cp39-cp39-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:88c2a17815c266e6d8180204ff62cb739ab869ada4a746d4c505331526ac58f1"}, + {file = "librt-0.15.0-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a5fa8f1f916988d0bf1afea005bda37f56ac41a18016e813ccf0097a8d460ca4"}, + {file = "librt-0.15.0-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:355e3a4c725225a14262004fc1872a552b9d3634b4f791a0dfc80804aafbfd55"}, + {file = "librt-0.15.0-cp39-cp39-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:fc1ed11c4ad0b91af24def2050f2840ea4567828e3dd058fbe608d982f6e5465"}, + {file = "librt-0.15.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:1f4ef2e71db33df4309167ed7f1520c4fae5e611226e159fa9cf33f93e6ddb3d"}, + {file = "librt-0.15.0-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:1a1a8cd430c7dd0c083f455cb1b328d7fc682b05c31b940906f7845bdff80881"}, + {file = "librt-0.15.0-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:04d5387b908676c0b8d5d2f5fb58373b4ea382d81f7a6f0fab8ea2a462bb4738"}, + {file = "librt-0.15.0-cp39-cp39-musllinux_1_2_riscv64.whl", hash = "sha256:1172c6ad2a88b646e7fe3b480e3fac4ab4418b3443fd8a4061fdd531e0622fc7"}, + {file = "librt-0.15.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:52e8db01f603f5da0ca30987479acff98769382efc8e142fa3962395dcf3ffdb"}, + {file = "librt-0.15.0-cp39-cp39-win32.whl", hash = "sha256:e4c911f15a1652ca94ae9f1abd92e74cbb1b3597d2d92fdd556202f94e8cd455"}, + {file = "librt-0.15.0-cp39-cp39-win_amd64.whl", hash = "sha256:68242379c9b65a582b6e97318a1e9fbd6d445e58954f2d437991c4804ab11578"}, + {file = "librt-0.15.0.tar.gz", hash = "sha256:4e66cbe84437497d951b799d3e1551291b6fb3d643820a7014b3655d57a59162"}, +] + + +[[package]] +name = "lightgbm" +version = "4.6.0" +description = "LightGBM Python-package" +optional = false +python-versions = ">=3.7" +groups = ["main"] +files = [ + {file = "lightgbm-4.6.0-py3-none-macosx_10_15_x86_64.whl", hash = "sha256:b7a393de8a334d5c8e490df91270f0763f83f959574d504c7ccb9eee4aef70ed"}, + {file = "lightgbm-4.6.0-py3-none-macosx_12_0_arm64.whl", hash = "sha256:2dafd98d4e02b844ceb0b61450a660681076b1ea6c7adb8c566dfd66832aafad"}, + {file = "lightgbm-4.6.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:4d68712bbd2b57a0b14390cbf9376c1d5ed773fa2e71e099cac588703b590336"}, + {file = "lightgbm-4.6.0-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:cb19b5afea55b5b61cbb2131095f50538bd608a00655f23ad5d25ae3e3bf1c8d"}, + {file = "lightgbm-4.6.0-py3-none-win_amd64.whl", hash = "sha256:37089ee95664b6550a7189d887dbf098e3eadab03537e411f52c63c121e3ba4b"}, + {file = "lightgbm-4.6.0.tar.gz", hash = "sha256:cb1c59720eb569389c0ba74d14f52351b573af489f230032a1c9f314f8bab7fe"}, +] + +[package.dependencies] +numpy = ">=1.17.0" +scipy = "*" + +[package.extras] +arrow = ["cffi (>=1.15.1)", "pyarrow (>=6.0.1)"] +dask = ["dask[array,dataframe,distributed] (>=2.0.0)", "pandas (>=0.24.0)"] +pandas = ["pandas (>=0.24.0)"] +scikit-learn = ["scikit-learn (>=0.24.2)"] + + +[[package]] +name = "llvmlite" +version = "0.49.0" +description = "lightweight wrapper around basic LLVM functionality" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "llvmlite-0.49.0-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:ee81e96c15a6f870918f1eb60c913551c16aa23defb4f5f1acfa660d6a0aaac2"}, + {file = "llvmlite-0.49.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:854941c2267fd4fc5b2ce02b8af8ecdffa79fb7784591d3a89370322039ea09f"}, + {file = "llvmlite-0.49.0-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:da7b64474ac15ca595efa2644d5c6836638ccf70709fad3aba3fc56a55966928"}, + {file = "llvmlite-0.49.0-cp310-cp310-win_amd64.whl", hash = "sha256:b352c14353330c879e339b8f8d7491d565fe94242697714a24e80bd757202384"}, + {file = "llvmlite-0.49.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:4b0e710880b7cc910392bd6b9f1bbf468fed99b182e4420d51598f36114b3dce"}, + {file = "llvmlite-0.49.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a8c0fc9d624bdc30a3d2db11eb2fb98f80fb209d20b37604eda516cd9b699cf4"}, + {file = "llvmlite-0.49.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20496a5c9fdb8179fb9300e7d19f6782555d98aeeb4a322264aa7fd99f980618"}, + {file = "llvmlite-0.49.0-cp311-cp311-win_amd64.whl", hash = "sha256:6a5b06c1b5fc4ae4c9b169b065f42b719448ef1f873687ef224ef69969b75ec3"}, + {file = "llvmlite-0.49.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:b541c8fac3450db7574d1f53cf9dff83f285bfed9d69bf81fe71fc2a7d4f97fe"}, + {file = "llvmlite-0.49.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6acba646d88abbc87d5c113a3d62c1fbf8b8fee11c6493f516803e30f21ae870"}, + {file = "llvmlite-0.49.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4ec8ad805e7515cb8440a690eb3cef4d34acb29eef80b705ec4e1c1ad3c43c68"}, + {file = "llvmlite-0.49.0-cp312-cp312-win_amd64.whl", hash = "sha256:3a9c9e3af4e214acfefa4f73ebe7bc3fb35854a62b654edb3953f5ae33c08ba3"}, + {file = "llvmlite-0.49.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:039fa4054a06f537fb39248d4472284ca96be311a142ec09e69f95630ab469cc"}, + {file = "llvmlite-0.49.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ddc7aecd4f56397ed6e8f120ec5dcd5a1a8f0e6032ca4af413462792d4dca2e3"}, + {file = "llvmlite-0.49.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d3dee64784201b64c13a8df62c48a4f4218858faaa65889866bb29bdc243c038"}, + {file = "llvmlite-0.49.0-cp313-cp313-win_amd64.whl", hash = "sha256:a1b414dc6b164738ec39dd8987cea73829057b7dd92fc6d91b52838385fc1dd2"}, + {file = "llvmlite-0.49.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:80a84683d04516bb51da1bbeebddaf2c2f558809c93078a8f91807909ae331f8"}, + {file = "llvmlite-0.49.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4281a0171d66d2098adce4ba706b8c550b1b10718650f682d64cde16e84e4de5"}, + {file = "llvmlite-0.49.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b095f15fb12c4d90495df5b1a3772b4732cc408398b204a787dbedd370e09c69"}, + {file = "llvmlite-0.49.0-cp314-cp314-win_amd64.whl", hash = "sha256:294e2f0b70aef8f92d0ae7b203e2609f08beb39437eee73de59a21669331aae9"}, + {file = "llvmlite-0.49.0-cp314-cp314-win_arm64.whl", hash = "sha256:95d1071023ed858b79f6971954fd7cc1f5dbcbab987718a4ccbe1411e47d0b81"}, + {file = "llvmlite-0.49.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:f3f2ff0aeb17d34fcce9f79b99baac441cfd3efa41b83e233ca4530a72381f72"}, + {file = "llvmlite-0.49.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d5555ea1d63928481cbf7fcb1d67452b216c7e5b393a4eb7aa1401e67f2a4fc4"}, + {file = "llvmlite-0.49.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e32adb84fdaae28aeb86fdb6253084ee707ee157289a2e98fe3caf48a62bee82"}, + {file = "llvmlite-0.49.0-cp314-cp314t-win_amd64.whl", hash = "sha256:be637e465010bc9c50f070468f7f1cf5385e92fee364d192dd5e6cea790ecba9"}, + {file = "llvmlite-0.49.0.tar.gz", hash = "sha256:00f16db782f4a13c78c5804aedc434e46794a77e89999a168f9401106270e50a"}, +] + + +[[package]] +name = "markupsafe" +version = "3.0.3" +description = "Safely add untrusted strings to HTML/XML markup." +optional = false +python-versions = ">=3.9" +groups = ["docs"] +files = [ + {file = "markupsafe-3.0.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:2f981d352f04553a7171b8e44369f2af4055f888dfb147d55e42d29e29e74559"}, + {file = "markupsafe-3.0.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e1c1493fb6e50ab01d20a22826e57520f1284df32f2d8601fdd90b6304601419"}, + {file = "markupsafe-3.0.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1ba88449deb3de88bd40044603fafffb7bc2b055d626a330323a9ed736661695"}, + {file = "markupsafe-3.0.3-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f42d0984e947b8adf7dd6dde396e720934d12c506ce84eea8476409563607591"}, + {file = "markupsafe-3.0.3-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c0c0b3ade1c0b13b936d7970b1d37a57acde9199dc2aecc4c336773e1d86049c"}, + {file = "markupsafe-3.0.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:0303439a41979d9e74d18ff5e2dd8c43ed6c6001fd40e5bf2e43f7bd9bbc523f"}, + {file = "markupsafe-3.0.3-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:d2ee202e79d8ed691ceebae8e0486bd9a2cd4794cec4824e1c99b6f5009502f6"}, + {file = "markupsafe-3.0.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:177b5253b2834fe3678cb4a5f0059808258584c559193998be2601324fdeafb1"}, + {file = "markupsafe-3.0.3-cp310-cp310-win32.whl", hash = "sha256:2a15a08b17dd94c53a1da0438822d70ebcd13f8c3a95abe3a9ef9f11a94830aa"}, + {file = "markupsafe-3.0.3-cp310-cp310-win_amd64.whl", hash = "sha256:c4ffb7ebf07cfe8931028e3e4c85f0357459a3f9f9490886198848f4fa002ec8"}, + {file = "markupsafe-3.0.3-cp310-cp310-win_arm64.whl", hash = "sha256:e2103a929dfa2fcaf9bb4e7c091983a49c9ac3b19c9061b6d5427dd7d14d81a1"}, + {file = "markupsafe-3.0.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:1cc7ea17a6824959616c525620e387f6dd30fec8cb44f649e31712db02123dad"}, + {file = "markupsafe-3.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4bd4cd07944443f5a265608cc6aab442e4f74dff8088b0dfc8238647b8f6ae9a"}, + {file = "markupsafe-3.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6b5420a1d9450023228968e7e6a9ce57f65d148ab56d2313fcd589eee96a7a50"}, + {file = "markupsafe-3.0.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0bf2a864d67e76e5c9a34dc26ec616a66b9888e25e7b9460e1c76d3293bd9dbf"}, + {file = "markupsafe-3.0.3-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:bc51efed119bc9cfdf792cdeaa4d67e8f6fcccab66ed4bfdd6bde3e59bfcbb2f"}, + {file = "markupsafe-3.0.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:068f375c472b3e7acbe2d5318dea141359e6900156b5b2ba06a30b169086b91a"}, + {file = "markupsafe-3.0.3-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:7be7b61bb172e1ed687f1754f8e7484f1c8019780f6f6b0786e76bb01c2ae115"}, + {file = "markupsafe-3.0.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f9e130248f4462aaa8e2552d547f36ddadbeaa573879158d721bbd33dfe4743a"}, + {file = "markupsafe-3.0.3-cp311-cp311-win32.whl", hash = "sha256:0db14f5dafddbb6d9208827849fad01f1a2609380add406671a26386cdf15a19"}, + {file = "markupsafe-3.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:de8a88e63464af587c950061a5e6a67d3632e36df62b986892331d4620a35c01"}, + {file = "markupsafe-3.0.3-cp311-cp311-win_arm64.whl", hash = "sha256:3b562dd9e9ea93f13d53989d23a7e775fdfd1066c33494ff43f5418bc8c58a5c"}, + {file = "markupsafe-3.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e"}, + {file = "markupsafe-3.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce"}, + {file = "markupsafe-3.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d"}, + {file = "markupsafe-3.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d"}, + {file = "markupsafe-3.0.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a"}, + {file = "markupsafe-3.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b"}, + {file = "markupsafe-3.0.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f"}, + {file = "markupsafe-3.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b"}, + {file = "markupsafe-3.0.3-cp312-cp312-win32.whl", hash = "sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d"}, + {file = "markupsafe-3.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c"}, + {file = "markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f"}, + {file = "markupsafe-3.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e1cf1972137e83c5d4c136c43ced9ac51d0e124706ee1c8aa8532c1287fa8795"}, + {file = "markupsafe-3.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:116bb52f642a37c115f517494ea5feb03889e04df47eeff5b130b1808ce7c219"}, + {file = "markupsafe-3.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:133a43e73a802c5562be9bbcd03d090aa5a1fe899db609c29e8c8d815c5f6de6"}, + {file = "markupsafe-3.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccfcd093f13f0f0b7fdd0f198b90053bf7b2f02a3927a30e63f3ccc9df56b676"}, + {file = "markupsafe-3.0.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:509fa21c6deb7a7a273d629cf5ec029bc209d1a51178615ddf718f5918992ab9"}, + {file = "markupsafe-3.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a4afe79fb3de0b7097d81da19090f4df4f8d3a2b3adaa8764138aac2e44f3af1"}, + {file = "markupsafe-3.0.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:795e7751525cae078558e679d646ae45574b47ed6e7771863fcc079a6171a0fc"}, + {file = "markupsafe-3.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8485f406a96febb5140bfeca44a73e3ce5116b2501ac54fe953e488fb1d03b12"}, + {file = "markupsafe-3.0.3-cp313-cp313-win32.whl", hash = "sha256:bdd37121970bfd8be76c5fb069c7751683bdf373db1ed6c010162b2a130248ed"}, + {file = "markupsafe-3.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5"}, + {file = "markupsafe-3.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:7e68f88e5b8799aa49c85cd116c932a1ac15caaa3f5db09087854d218359e485"}, + {file = "markupsafe-3.0.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:218551f6df4868a8d527e3062d0fb968682fe92054e89978594c28e642c43a73"}, + {file = "markupsafe-3.0.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:3524b778fe5cfb3452a09d31e7b5adefeea8c5be1d43c4f810ba09f2ceb29d37"}, + {file = "markupsafe-3.0.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4e885a3d1efa2eadc93c894a21770e4bc67899e3543680313b09f139e149ab19"}, + {file = "markupsafe-3.0.3-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8709b08f4a89aa7586de0aadc8da56180242ee0ada3999749b183aa23df95025"}, + {file = "markupsafe-3.0.3-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b8512a91625c9b3da6f127803b166b629725e68af71f8184ae7e7d54686a56d6"}, + {file = "markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9b79b7a16f7fedff2495d684f2b59b0457c3b493778c9eed31111be64d58279f"}, + {file = "markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:12c63dfb4a98206f045aa9563db46507995f7ef6d83b2f68eda65c307c6829eb"}, + {file = "markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8f71bc33915be5186016f675cd83a1e08523649b0e33efdb898db577ef5bb009"}, + {file = "markupsafe-3.0.3-cp313-cp313t-win32.whl", hash = "sha256:69c0b73548bc525c8cb9a251cddf1931d1db4d2258e9599c28c07ef3580ef354"}, + {file = "markupsafe-3.0.3-cp313-cp313t-win_amd64.whl", hash = "sha256:1b4b79e8ebf6b55351f0d91fe80f893b4743f104bff22e90697db1590e47a218"}, + {file = "markupsafe-3.0.3-cp313-cp313t-win_arm64.whl", hash = "sha256:ad2cf8aa28b8c020ab2fc8287b0f823d0a7d8630784c31e9ee5edea20f406287"}, + {file = "markupsafe-3.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe"}, + {file = "markupsafe-3.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026"}, + {file = "markupsafe-3.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737"}, + {file = "markupsafe-3.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97"}, + {file = "markupsafe-3.0.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d"}, + {file = "markupsafe-3.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda"}, + {file = "markupsafe-3.0.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf"}, + {file = "markupsafe-3.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe"}, + {file = "markupsafe-3.0.3-cp314-cp314-win32.whl", hash = "sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9"}, + {file = "markupsafe-3.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581"}, + {file = "markupsafe-3.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4"}, + {file = "markupsafe-3.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab"}, + {file = "markupsafe-3.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175"}, + {file = "markupsafe-3.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634"}, + {file = "markupsafe-3.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50"}, + {file = "markupsafe-3.0.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e"}, + {file = "markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5"}, + {file = "markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523"}, + {file = "markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc"}, + {file = "markupsafe-3.0.3-cp314-cp314t-win32.whl", hash = "sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d"}, + {file = "markupsafe-3.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9"}, + {file = "markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa"}, + {file = "markupsafe-3.0.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:15d939a21d546304880945ca1ecb8a039db6b4dc49b2c5a400387cdae6a62e26"}, + {file = "markupsafe-3.0.3-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:f71a396b3bf33ecaa1626c255855702aca4d3d9fea5e051b41ac59a9c1c41edc"}, + {file = "markupsafe-3.0.3-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0f4b68347f8c5eab4a13419215bdfd7f8c9b19f2b25520968adfad23eb0ce60c"}, + {file = "markupsafe-3.0.3-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e8fc20152abba6b83724d7ff268c249fa196d8259ff481f3b1476383f8f24e42"}, + {file = "markupsafe-3.0.3-cp39-cp39-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:949b8d66bc381ee8b007cd945914c721d9aba8e27f71959d750a46f7c282b20b"}, + {file = "markupsafe-3.0.3-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:3537e01efc9d4dccdf77221fb1cb3b8e1a38d5428920e0657ce299b20324d758"}, + {file = "markupsafe-3.0.3-cp39-cp39-musllinux_1_2_riscv64.whl", hash = "sha256:591ae9f2a647529ca990bc681daebdd52c8791ff06c2bfa05b65163e28102ef2"}, + {file = "markupsafe-3.0.3-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:a320721ab5a1aba0a233739394eb907f8c8da5c98c9181d1161e77a0c8e36f2d"}, + {file = "markupsafe-3.0.3-cp39-cp39-win32.whl", hash = "sha256:df2449253ef108a379b8b5d6b43f4b1a8e81a061d6537becd5582fba5f9196d7"}, + {file = "markupsafe-3.0.3-cp39-cp39-win_amd64.whl", hash = "sha256:7c3fb7d25180895632e5d3148dbdc29ea38ccb7fd210aa27acbd1201a1902c6e"}, + {file = "markupsafe-3.0.3-cp39-cp39-win_arm64.whl", hash = "sha256:38664109c14ffc9e7437e86b4dceb442b0096dfe3541d7864d9cbe1da4cf36c8"}, + {file = "markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698"}, +] + + +[[package]] +name = "matplotlib" +version = "3.10.9" +description = "Python plotting package" +optional = false +python-versions = ">=3.10" +groups = ["main"] +markers = "python_version == \"3.10\"" +files = [ + {file = "matplotlib-3.10.9-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:77210dce9cb8153dffc967efaae990543392563d5a376d4dd8539bebcb0ed217"}, + {file = "matplotlib-3.10.9-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:1e7698ac9868428e84d2c967424803b2472ff7167d9d6590d4204ed775343c3b"}, + {file = "matplotlib-3.10.9-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1aa972116abb4c9d201bf245620b433726cb6856f3bef6a78f776a00f5c92d37"}, + {file = "matplotlib-3.10.9-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ae2f11957b27ce53497dd4d7b235c4d4f1faf383dfb39d0c5beb833bff883294"}, + {file = "matplotlib-3.10.9-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:b049278ddce116aaa1c1377ebf58adea909132dfce0281cf7e3a1ea9fc2e2c65"}, + {file = "matplotlib-3.10.9-cp310-cp310-win_amd64.whl", hash = "sha256:82834c3c292d24d3a8aae77cd2d20019de69d692a34a970e4fdb8d33e2ea3dda"}, + {file = "matplotlib-3.10.9-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:68cfdcede415f7c8f5577b03303dd94526cdb6d11036cecdc205e08733b2d2bb"}, + {file = "matplotlib-3.10.9-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:dfca0129678bd56379db26c52b5d77ed7de314c047492fbdc763aa7501710cfb"}, + {file = "matplotlib-3.10.9-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8e436d155fa8a3399dc62683f8f5d0e2e50d25d0144a73edd73f82eec8f4abfb"}, + {file = "matplotlib-3.10.9-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:56fc0bd271b00025c6edfdc7c2dcd247372c8e1544971d62e1dc7c17367e8bf9"}, + {file = "matplotlib-3.10.9-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a5a6104ed666402ba5106d7f36e0e0cdca4e8d7fa4d39708ca88019e2835a2eb"}, + {file = "matplotlib-3.10.9-cp311-cp311-win_amd64.whl", hash = "sha256:d730e984eddf56974c3e72b6129c7ca462ac38dc624338f4b0b23eb23ecba00f"}, + {file = "matplotlib-3.10.9-cp311-cp311-win_arm64.whl", hash = "sha256:51bf0ddbdc598e060d46c16b5590708f81a1624cefbaaf62f6a81bf9285b8c80"}, + {file = "matplotlib-3.10.9-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f0c3c28d9fbcc1fe7a03be236d73430cf6409c41fb2383a7ac52fe932b072cb1"}, + {file = "matplotlib-3.10.9-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:41cb28c2bd769aa3e98322c6ab09854cbcc52ab69d2759d681bba3e327b2b320"}, + {file = "matplotlib-3.10.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ae20801130378b82d647ff5047c07316295b68dc054ca6b3c13519d0ea624285"}, + {file = "matplotlib-3.10.9-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6c63ebcd8b4b169eb2f5c200552ae6b8be8999a005b6b507ed76fb8d7d674fe2"}, + {file = "matplotlib-3.10.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d75d11c949914165976c621b2324f9ef162af7ebf4b057ddf95dd1dba7e5edcf"}, + {file = "matplotlib-3.10.9-cp312-cp312-win_amd64.whl", hash = "sha256:d091f9d758b34aaaaa6331d13574bf01891d903b3dec59bfff458ef7551de5d6"}, + {file = "matplotlib-3.10.9-cp312-cp312-win_arm64.whl", hash = "sha256:10cc5ce06d10231c36f40e875f3c7e8050362a4ee8f0ee5d29a6b3277d57bb42"}, + {file = "matplotlib-3.10.9-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:b580440f1ff81a0e34122051a3dfabb7e4b7f9e380629929bde0eff9af72165f"}, + {file = "matplotlib-3.10.9-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:b1b745c489cd1a77a0dc1120a05dc87af9798faebc913601feb8c73d89bf2d1e"}, + {file = "matplotlib-3.10.9-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8f3bcac1ca5ed000a6f4337d47ba67dfddf37ed6a46c15fd7f014997f7bf865f"}, + {file = "matplotlib-3.10.9-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a8d66a55def891c33147ba3ba9bfcabf0b526a43764c818acbb4525e5ed0838"}, + {file = "matplotlib-3.10.9-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:d843374407c4017a6403b59c6c81606773d136f3259d5b6da3131bc814542cc2"}, + {file = "matplotlib-3.10.9-cp313-cp313-win_amd64.whl", hash = "sha256:f4399f64b3e94cd500195490972ae1ee81170df1636fa15364d157d5bdd7b921"}, + {file = "matplotlib-3.10.9-cp313-cp313-win_arm64.whl", hash = "sha256:ba7b3b8ef09eab7df0e86e9ae086faa433efbfbdb46afcb3aa16aabf779469a8"}, + {file = "matplotlib-3.10.9-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:09218df8a93712bd6ea133e83a153c755448cf7868316c531cffcc43f69d1cc9"}, + {file = "matplotlib-3.10.9-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:82368699727bfb7b0182e1aa13082e3c08e092fa1a25d3e1fd92405bff96f6d4"}, + {file = "matplotlib-3.10.9-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3225f4e1edcb8c86c884ddf79ebe20ecd0a67d30188f279897554ccd8fded4dc"}, + {file = "matplotlib-3.10.9-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:de2445a0c6690d21b7eb6ce071cebad6d40a2e9bdf10d039074a96ba19797b99"}, + {file = "matplotlib-3.10.9-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:b2b9516251cb89ff618d757daec0e2ed1bf21248013844a853d87ef85ab3081d"}, + {file = "matplotlib-3.10.9-cp313-cp313t-win_amd64.whl", hash = "sha256:e9fae004b941b23ff2edcf1567a857ed77bafc8086ffa258190462328434faf8"}, + {file = "matplotlib-3.10.9-cp313-cp313t-win_arm64.whl", hash = "sha256:6b63d9c7c769b88ab81e10dc86e4e0607cf56817b9f9e6cf24b2a5f1693b8e38"}, + {file = "matplotlib-3.10.9-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:172db52c9e683f5d12eaf57f0f54834190e12581fe1cc2a19595a8f5acb4e77d"}, + {file = "matplotlib-3.10.9-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:97e35e8d39ccc85859095e01a53847432ba9a53ddf7986f7a54a11b73d0e143f"}, + {file = "matplotlib-3.10.9-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:aba1615dabe83188e19d4f75a253c6a08423e04c1425e64039f800050a69de6b"}, + {file = "matplotlib-3.10.9-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:34cf8167e023ad956c15f36302911d5406bd99a9862c1a8499ea6f7c0e015dc2"}, + {file = "matplotlib-3.10.9-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:59476c6d29d612b8e9bb6ce8c5b631be6ba8f9e3a2421f22a02b192c7dd28716"}, + {file = "matplotlib-3.10.9-cp314-cp314-win_amd64.whl", hash = "sha256:336b9acc64d309063126edcdaca00db9373af3c476bb94388fe9c5a53ad13e6f"}, + {file = "matplotlib-3.10.9-cp314-cp314-win_arm64.whl", hash = "sha256:2dc9477819ffd78ad12a20df1d9d6a6bd4fec6aaa9072681465fddca052f1456"}, + {file = "matplotlib-3.10.9-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:da4e09638420548f31c354032a6250e473c68e5a4e96899b4844cf39ddea23fe"}, + {file = "matplotlib-3.10.9-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:345f6f68ecc8da0ca56fad2ea08fde1a115eda530079eca185d50a7bc3e146c6"}, + {file = "matplotlib-3.10.9-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4edcfbd8565339aa62f1cd4012f7180926fdbe71850f7b0d3c379c175cd6b66c"}, + {file = "matplotlib-3.10.9-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6be157fe17fc37cb95ac1d7374cf717ce9259616edec911a78d9d26dae8522d4"}, + {file = "matplotlib-3.10.9-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:4e42042d54db34fda4e95a7bd3e5789c2a995d2dad3eb8850232ee534092fbbf"}, + {file = "matplotlib-3.10.9-cp314-cp314t-win_amd64.whl", hash = "sha256:c27df8b3848f32a83d1767566595e43cfaa4460380974da06f4279a7ec143c39"}, + {file = "matplotlib-3.10.9-cp314-cp314t-win_arm64.whl", hash = "sha256:a49f1eadc84ca85fd72fa4e89e70e61bf86452df6f971af04b12c60761a0772c"}, + {file = "matplotlib-3.10.9-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:1872fb212a05b729e649754a72d5da61d03e0554d76e80303b6f83d1d2c0552b"}, + {file = "matplotlib-3.10.9-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:985f2238880e2e69093f588f5fe2e46771747febf0649f3cf7f7b7480875317f"}, + {file = "matplotlib-3.10.9-pp310-pypy310_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6640f75af2c6148293caa0a2b39dd806a492dd66c8a8b04035813e33d0fd2585"}, + {file = "matplotlib-3.10.9-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:42fb814efabe95c06c1994d8ab5a8385f43a249e23badd3ba931d4308e5bca20"}, + {file = "matplotlib-3.10.9-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:f76e640a5268850bfda54b5131b1b1941cc685e42c5fa98ed9f2d64038308cba"}, + {file = "matplotlib-3.10.9-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3fc0364dfbe1d07f6d15c5ebd0c5bf89e126916e5a8667dd4a7a6e84c36653d4"}, + {file = "matplotlib-3.10.9.tar.gz", hash = "sha256:fd66508e8c6877d98e586654b608a0456db8d7e8a546eb1e2600efd957302358"}, +] + +[package.dependencies] +contourpy = ">=1.0.1" +cycler = ">=0.10" +fonttools = ">=4.22.0" +kiwisolver = ">=1.3.1" +numpy = ">=1.23" +packaging = ">=20.0" +pillow = ">=8" +pyparsing = ">=3" +python-dateutil = ">=2.7" + +[package.extras] +dev = ["meson-python (>=0.13.1,<0.17.0)", "pybind11 (>=2.13.2,!=2.13.3)", "setuptools (>=64)", "setuptools_scm (>=7,<10)"] + + +[[package]] +name = "matplotlib" +version = "3.11.2" +description = "Python plotting package" +optional = false +python-versions = ">=3.11" +groups = ["main"] +markers = "python_version >= \"3.11\"" +files = [ + {file = "matplotlib-3.11.2-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:5e1e923a3fc3326b99ec0a6ff1ab1338ac6c6cc62ad9d8a9c944197c7f8c6221"}, + {file = "matplotlib-3.11.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c27e577ece613ea12a0790e00b4eb80d901c59a3e16cad474f31d8b1529690b9"}, + {file = "matplotlib-3.11.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:07d9b9fa60cd4c393692f50d0bb03123242ddf61c99bb0e95e75feb354e7c1a8"}, + {file = "matplotlib-3.11.2-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:30ec15d7eefee71de16b7c689b42ba49715a4644650b76a6c7c70d79daf24e91"}, + {file = "matplotlib-3.11.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:116cdb0eb0eb5644fc98eb2975d4b4dd4ad35e5c8e6b851c22e6976f371f7ab5"}, + {file = "matplotlib-3.11.2-cp311-cp311-win_amd64.whl", hash = "sha256:a24d5fd36e4f0e742c3851dcd20810e56a95633a342e4bf6cb591c678e8fe61f"}, + {file = "matplotlib-3.11.2-cp311-cp311-win_arm64.whl", hash = "sha256:57b9ea60a835937c2012861923cbb91f47db8565775d326d1c42fc926aa10351"}, + {file = "matplotlib-3.11.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ef752769cd962f39ea0b6ffc82d1ea43a0012c5a6157c7a075212fa509cfcff2"}, + {file = "matplotlib-3.11.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ef31985c4dedb5f1424e1aec6849a47dd37689cb7fa3c20b1b82187f26806261"}, + {file = "matplotlib-3.11.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:df4f7784aca81a94f254c0a2767d592ee25f407e488f5fa7203e51093fb6ca27"}, + {file = "matplotlib-3.11.2-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b9a7ad579856284135e401ecc918c5f8a017ee30539298862a109f51b971710"}, + {file = "matplotlib-3.11.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3aa4b8516fd26659e4363abbf317c703d9116496c5db2e9d0609a2866dd39dd2"}, + {file = "matplotlib-3.11.2-cp312-cp312-win_amd64.whl", hash = "sha256:c5c1c68ee401fc98271263410f0e5ce88285abacf7627132914e8adf3d70ff43"}, + {file = "matplotlib-3.11.2-cp312-cp312-win_arm64.whl", hash = "sha256:643ff850d8e0f5b8319337f87ed3cb59506afb3df3cc48de777d85871233be7b"}, + {file = "matplotlib-3.11.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7d43ff8cebb50840648cb6429b2228621dbd709010f3117b3740abb20abf21c0"}, + {file = "matplotlib-3.11.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2a8285cea8ef4d92aa041d1c33788bcae82248503300f93f1ca2136b9049452f"}, + {file = "matplotlib-3.11.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1944895967f87c84c9b4bad29a707b31f5b36df4a3a2339ea1f8ea3ce5105539"}, + {file = "matplotlib-3.11.2-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:af2661f6ac6bbd1d081996f54fdd9385715c625ace8cec0869055c0cfbf38981"}, + {file = "matplotlib-3.11.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:7e5a90f8a707ebb6004a713b1cff091a40cc5df4c7c1cb165e5a505ebc11c292"}, + {file = "matplotlib-3.11.2-cp313-cp313-win_amd64.whl", hash = "sha256:bc067c462a86f0e57bf52fc6e058d90171a5420007dac00c46e90153050c69a7"}, + {file = "matplotlib-3.11.2-cp313-cp313-win_arm64.whl", hash = "sha256:3e8576f7c47e02fd4f21f44171302d2d1d58d4471d46da3d71fe8899d19539d9"}, + {file = "matplotlib-3.11.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:c9721f81275499da1feeb36a2cf8192ea086283b3bd16b7dc4c9d7aedb7396d6"}, + {file = "matplotlib-3.11.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1a3040b209f3968b4e84161df7b174f07a9fad33b0f2d7e48ea3bbd3075e2863"}, + {file = "matplotlib-3.11.2-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bf3fe71fbfb8ec0e310e0bc8537c3405a01f38f25f9394ed2135e6202fed542b"}, + {file = "matplotlib-3.11.2-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8c8255de28f986d935a64c9ca71c0ec2d2f41d355691f5ea684725dc91413f71"}, + {file = "matplotlib-3.11.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a8756cc73d9af9a7fe0deb54ea2e75ef73b01d9e575877e72acad5458e660943"}, + {file = "matplotlib-3.11.2-cp314-cp314-win_amd64.whl", hash = "sha256:ecea603dd2fbf8242fd31a305a8b12a4ece2de28096870c65fdd0d1e35b8d9a6"}, + {file = "matplotlib-3.11.2-cp314-cp314-win_arm64.whl", hash = "sha256:01dc8eaaab5a9fce9ff615eca82345728f289e4715b186ee10c6d85272fc26bb"}, + {file = "matplotlib-3.11.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:79a258f58253dfa025af80a9e9bb228d75fced007f0e93ae7423fefbde81a74d"}, + {file = "matplotlib-3.11.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c0b83f044ce10a98027b105b3931548719a6e8c7ef986b4362651e0b5367c8dc"}, + {file = "matplotlib-3.11.2-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e43b188f0a5b75447bcc197728258166aa64365770ed1caa36595a5e1ca4bbba"}, + {file = "matplotlib-3.11.2-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d3304eb5a59442a8867f6920d484591c0fa09ffc29e9260be2feec3351e25869"}, + {file = "matplotlib-3.11.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:02329432ae5c6af87cf208ee575b701d698bdf0b1a3bb28cc6d53c36e967e575"}, + {file = "matplotlib-3.11.2-cp314-cp314t-win_amd64.whl", hash = "sha256:f2ac30cf5eb5dff1b584627ae0b0e1186551a4f69ae3c75073911da497a29170"}, + {file = "matplotlib-3.11.2-cp314-cp314t-win_arm64.whl", hash = "sha256:cf41ecd1b0c0b6f7177ed965a54c2afbe888715c7cf6054dc12d53bc1494002c"}, + {file = "matplotlib-3.11.2-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:894a9cbbecbe30ae6787d464df2e8fc7a8d475cfc68f87c3029f7c11152899b3"}, + {file = "matplotlib-3.11.2-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:bbf1062991d826ed27e2144f3afa4461afbb8ff56e8f703043e191a8163b1ee9"}, + {file = "matplotlib-3.11.2-cp315-cp315-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:399fef672f7046ef7d6a57572b2a6f9845f3f5afcff04e7b2df7a363a9f42190"}, + {file = "matplotlib-3.11.2-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cc82dde2a0d3e3ad472edce04897ad7146b8d8bfd1df8a32992eebb81af18fdc"}, + {file = "matplotlib-3.11.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:930efb28f59fda124e39265d177bab302625297bb147d2910de725a2fc2aef54"}, + {file = "matplotlib-3.11.2-cp315-cp315-win_amd64.whl", hash = "sha256:3da3bc0cbf7245e7db72cc6d29d12c5abef72cb73059c73b945f14e3545f3eb2"}, + {file = "matplotlib-3.11.2-cp315-cp315-win_arm64.whl", hash = "sha256:f25446b2981717dca9786bac841cb3fd7efb568e3e3c755dd980481c5cb9228d"}, + {file = "matplotlib-3.11.2-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:fea03cf56568cc1cba08b470be6a0559e71c3a5b688d54b7179bb35ba23d0821"}, + {file = "matplotlib-3.11.2-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:254d4ddb2fa8df3b4c689c0c306063aee10521df82cfb438185e499c75fe37c1"}, + {file = "matplotlib-3.11.2-cp315-cp315t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e60cf3047a51edecdc4535a9196bbd6a732936b8e9f8184aabf4d16165884aaf"}, + {file = "matplotlib-3.11.2-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:eb3712dc9b464793de0a4e42a7313d50293c751f94bddaf7332a1bc71bccdda9"}, + {file = "matplotlib-3.11.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:75b6d88402770e181b5d06a67dda4129c31da7d05004d63a21c310ec78d1b83c"}, + {file = "matplotlib-3.11.2-cp315-cp315t-win_amd64.whl", hash = "sha256:a6939df7567114b6bac7f4c5e06c84a67f197c1b2f2e4b234d4eecb3bfec9482"}, + {file = "matplotlib-3.11.2-cp315-cp315t-win_arm64.whl", hash = "sha256:d480038c83691532ed52ff3147db51fa902fc78cb2d8349993a1cdb684435bff"}, + {file = "matplotlib-3.11.2-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:854df8d7dfe9fdffcbaa6f39e44a6c24b409cb4d7561fbc09213b157d833f6a6"}, + {file = "matplotlib-3.11.2-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:eac4b07d4e3743b172451e122ea964f72f152879d4f9adcf3f3d33e518f12ead"}, + {file = "matplotlib-3.11.2-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7ef7a53b66780e5d942923724f08577fbc5be1f7322da0f0f3f9dcaa45dd803d"}, + {file = "matplotlib-3.11.2.tar.gz", hash = "sha256:cec596316640f2b394b8f0daa0ea61a8eae82d017b620b9f202befb972a59ea4"}, +] + +[package.dependencies] +contourpy = ">=1.0.1" +cycler = ">=0.10" +fonttools = ">=4.28.2" +kiwisolver = ">=1.3.1" +numpy = ">=1.25" +packaging = ">=20.0" +pillow = ">=9" +pyparsing = ">=3" +python-dateutil = ">=2.7" + + +[[package]] +name = "mypy" +version = "1.20.2" +description = "Optional static typing for Python" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "mypy-1.20.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:cf5a4db6dca263010e2c7bff081c89383c72d187ba2cf4c44759aac970e2f0c4"}, + {file = "mypy-1.20.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:7b0e817b518bff7facd7f85ea05b643ad8bdcce684cf29784987b0a7c8e1f997"}, + {file = "mypy-1.20.2-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:97d7b9a485b40f8ca425460e89bf1da2814625b2da627c0dcc6aa46c92631d14"}, + {file = "mypy-1.20.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1e1c12f6d2db3d78b909b5f77513c11eb7f2dd2782b96a3ab6dffc7d44575c99"}, + {file = "mypy-1.20.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:89dce27e142d25ffbc154c1819383b69f2e9234dc4ed4766f42e0e8cb264ab5c"}, + {file = "mypy-1.20.2-cp310-cp310-win_amd64.whl", hash = "sha256:f376e37f9bf2a946872fc5fd1199c99310748e3c26c7a26683f13f8bdb756cbd"}, + {file = "mypy-1.20.2-cp310-cp310-win_arm64.whl", hash = "sha256:6e2b469efd811707bc530fd1effef0f5d6eebcb7fe376affae69025da4b979a2"}, + {file = "mypy-1.20.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4077797a273e56e8843d001e9dfe4ba10e33323d6ade647ff260e5cd97d9758c"}, + {file = "mypy-1.20.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:cdecf62abcc4292500d7858aeae87a1f8f1150f4c4dd08fb0b336ee79b2a6df3"}, + {file = "mypy-1.20.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c566c3a88b6ece59b3d70f65bedef17304f48eb52ff040a6a18214e1917b3254"}, + {file = "mypy-1.20.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0deb80d062b2479f2c87ae568f89845afc71d11bc41b04179e58165fd9f31e98"}, + {file = "mypy-1.20.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:bba9ad231e92a3e424b3e56b65aa17704993425bba97e302c832f9466bb85bac"}, + {file = "mypy-1.20.2-cp311-cp311-win_amd64.whl", hash = "sha256:baf593f2765fa3a6b1ef95807dbaa3d25b594f6a52adcc506a6b9cb115e1be67"}, + {file = "mypy-1.20.2-cp311-cp311-win_arm64.whl", hash = "sha256:20175a1c0f49863946ec20b7f63255768058ac4f07d2b9ded6a6b46cfb5a9100"}, + {file = "mypy-1.20.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4dbfcf869f6b0517f70cf0030ba6ea1d6645e132337a7d5204a18d8d5636c02b"}, + {file = "mypy-1.20.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4b6481b228d072315b053210b01ac320e1be243dc17f9e5887ef167f23f5fae4"}, + {file = "mypy-1.20.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:34397cdced6b90b836e38182076049fdb41424322e0b0728c946b0939ebdf9f6"}, + {file = "mypy-1.20.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a5da6976f20cae27059ea8d0c86e7cef3de720e04c4bb9ee18e3690fdb792066"}, + {file = "mypy-1.20.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:56908d7e08318d39f85b1f0c6cfd47b0cac1a130da677630dac0de3e0623e102"}, + {file = "mypy-1.20.2-cp312-cp312-win_amd64.whl", hash = "sha256:d52ad8d78522da1d308789df651ee5379088e77c76cb1994858d40a426b343b9"}, + {file = "mypy-1.20.2-cp312-cp312-win_arm64.whl", hash = "sha256:785b08db19c9f214dc37d65f7c165d19a30fcecb48abfa30f31b01b5acaabb58"}, + {file = "mypy-1.20.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:edfbfca868cdd6bd8d974a60f8a3682f5565d3f5c99b327640cedd24c4264026"}, + {file = "mypy-1.20.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e2877a02380adfcdbc69071a0f74d6e9dbbf593c0dc9d174e1f223ffd5281943"}, + {file = "mypy-1.20.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7488448de6007cd5177c6cea0517ac33b4c0f5ee9b5e9f2be51ce75511a85517"}, + {file = "mypy-1.20.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bb9c2fa06887e21d6a3a868762acb82aec34e2c6fd0174064f27c93ede68ad15"}, + {file = "mypy-1.20.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:9d56a78b646f2e3daa865bc70cd5ec5a46c50045801ca8ff17a0c43abc97e3ee"}, + {file = "mypy-1.20.2-cp313-cp313-win_amd64.whl", hash = "sha256:2a4102b03bb7481d9a91a6da8d174740c9c8c4401024684b9ca3b7cc5e49852f"}, + {file = "mypy-1.20.2-cp313-cp313-win_arm64.whl", hash = "sha256:a95a9248b0c6fd933a442c03c3b113c3b61320086b88e2c444676d3fd1ca3330"}, + {file = "mypy-1.20.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:419413398fe250aae057fd2fe50166b61077083c9b82754c341cf4fd73038f30"}, + {file = "mypy-1.20.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e73c07f23009962885c197ccb9b41356a30cc0e5a1d0c2ea8fd8fb1362d7f924"}, + {file = "mypy-1.20.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0c64e5973df366b747646fc98da921f9d6eba9716d57d1db94a83c026a08e0fb"}, + {file = "mypy-1.20.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5a65aa591af023864fd08a97da9974e919452cfe19cb146c8a5dc692626445dc"}, + {file = "mypy-1.20.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:4fef51b01e638974a6e69885687e9bd40c8d1e09a6cd291cca0619625cf1f558"}, + {file = "mypy-1.20.2-cp314-cp314-win_amd64.whl", hash = "sha256:913485a03f1bcf5d279409a9d2b9ed565c151f61c09f29991e5faa14033da4c8"}, + {file = "mypy-1.20.2-cp314-cp314-win_arm64.whl", hash = "sha256:c3bae4f855d965b5453784300c12ffc63a548304ac7f99e55d4dc7c898673aa3"}, + {file = "mypy-1.20.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:2de3dcea53babc1c3237a19002bc3d228ce1833278f093b8d619e06e7cc79609"}, + {file = "mypy-1.20.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:52b176444e2e5054dfcbcb8c75b0b719865c96247b37407184bbfca5c353f2c2"}, + {file = "mypy-1.20.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:688c3312e5dadb573a2c69c82af3a298d43ecf9e6d264e0f95df960b5f6ac19c"}, + {file = "mypy-1.20.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:29752dbbf8cc53f89f6ac096d363314333045c257c9c75cbd189ca2de0455744"}, + {file = "mypy-1.20.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:803203d2b6ea644982c644895c2f78b28d0e208bba7b27d9b921e0ec5eb207c6"}, + {file = "mypy-1.20.2-cp314-cp314t-win_amd64.whl", hash = "sha256:9bcb8aa397ff0093c824182fd76a935a9ba7ad097fcbef80ae89bf6c1731d8ec"}, + {file = "mypy-1.20.2-cp314-cp314t-win_arm64.whl", hash = "sha256:e061b58443f1736f8a37c48978d7ab581636d6ab03e3d4f99e3fa90463bb9382"}, + {file = "mypy-1.20.2-py3-none-any.whl", hash = "sha256:a94c5a76ab46c5e6257c7972b6c8cff0574201ca7dc05647e33e795d78680563"}, + {file = "mypy-1.20.2.tar.gz", hash = "sha256:e8222c26daaafd9e8626dec58ae36029f82585890589576f769a650dd20fd665"}, +] + +[package.dependencies] +librt = {version = ">=0.8.0", markers = "platform_python_implementation != \"PyPy\""} +mypy_extensions = ">=1.0.0" +pathspec = ">=1.0.0" +tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} +typing_extensions = {version = ">=4.6.0", markers = "python_version < \"3.15\""} + +[package.extras] +dmypy = ["psutil (>=4.0)"] +faster-cache = ["orjson"] +install-types = ["pip"] +mypyc = ["setuptools (>=50)"] +native-parser = ["ast-serialize (>=0.1.1,<1.0.0)"] +reports = ["lxml"] + + +[[package]] +name = "mypy-extensions" +version = "1.1.0" +description = "Type system extensions for programs checked with the mypy type checker." +optional = false +python-versions = ">=3.8" +groups = ["dev"] +files = [ + {file = "mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505"}, + {file = "mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558"}, +] + + +[[package]] +name = "narwhals" +version = "2.26.0" +description = "Extremely lightweight compatibility layer between dataframe libraries" +optional = false +python-versions = ">=3.10" +groups = ["main"] +markers = "python_version >= \"3.11\"" +files = [ + {file = "narwhals-2.26.0-py3-none-any.whl", hash = "sha256:29326d74f107c347fd1009bd58e38d9f7c7c5b51e6de97bc93dbc325d9038b54"}, + {file = "narwhals-2.26.0.tar.gz", hash = "sha256:6b9cadca82f375c7e4cf584fdc86ca25da54827307a9c58f94547ee6104b82dd"}, +] + +[package.extras] +cudf = ["cudf-cu12 (>=24.10.0) ; sys_platform == \"linux\""] +dask = ["dask[dataframe] (>=2024.8)"] +duckdb = ["duckdb (>=1.1)"] +ibis = ["ibis-framework (>=6.0.0)", "packaging (>=21.3)", "pyarrow-hotfix (>=0.7)"] +modin = ["modin (>=0.22.0)"] +pandas = ["pandas (>=1.3.4)"] +polars = ["polars (>=0.20.4)"] +pyarrow = ["pyarrow (>=13.0.0)"] +pyspark = ["pyspark (>=3.5.0)"] +pyspark-connect = ["pyspark[connect] (>=3.5.0)"] +sql = ["narwhals[duckdb]", "sqlparse (>=0.5.5)"] +sqlframe = ["sqlframe (>=3.22.0,!=3.39.3)"] + + +[[package]] +name = "nodeenv" +version = "1.10.0" +description = "Node.js virtual environment builder" +optional = false +python-versions = ">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*" +groups = ["dev"] +files = [ + {file = "nodeenv-1.10.0-py2.py3-none-any.whl", hash = "sha256:5bb13e3eed2923615535339b3c620e76779af4cb4c6a90deccc9e36b274d3827"}, + {file = "nodeenv-1.10.0.tar.gz", hash = "sha256:996c191ad80897d076bdfba80a41994c2b47c68e224c542b48feba42ba00f8bb"}, +] + + +[[package]] +name = "numba" +version = "0.67.0" +description = "compiling Python code using LLVM" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "numba-0.67.0-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:8c0e88acd4341ddf40779db3c0228b9188aca7fcab5f5f3ce9949a1fc71e9a02"}, + {file = "numba-0.67.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d6c8e9ba3f9602471e8c6f563ffcce8db8046741f0bafb782a052e41dc6b6861"}, + {file = "numba-0.67.0-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:694c81c6560b2b47e5fc1dc39c29175b907adf862d9af0af801453400a022a61"}, + {file = "numba-0.67.0-cp310-cp310-win_amd64.whl", hash = "sha256:ed333e0af4386294e7f03e550e01411856b6935e717d859225e0a7338c6b6795"}, + {file = "numba-0.67.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:3fa3d1b27f96f2c0d54513d953d7197886aa1eaa7d2439a0eedc44d993fb181a"}, + {file = "numba-0.67.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8c80c847301dc33dc8f84a97a952004023d9a05578ae4512b087176264cc1960"}, + {file = "numba-0.67.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e7a7b0121466f1e9a8a074b0545fe90e16389623abf979b5d7c299dca1294d7e"}, + {file = "numba-0.67.0-cp311-cp311-win_amd64.whl", hash = "sha256:cfba1ac34f0363fb1a250a10e97240780d11e05227892f7286b26fbfd0ad58ce"}, + {file = "numba-0.67.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:6004d8d5f28d4028687fb2d972d629295b13685943bd2ed5cd8810c3b848e219"}, + {file = "numba-0.67.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f63d43db06b4756424d6d2484737c902e0ae944a0eec3e8b0b4de2c695b15caa"}, + {file = "numba-0.67.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:76d3335aaeffb9dc88309420890e73497a00be08a7530441bc2b58ffe025bfa5"}, + {file = "numba-0.67.0-cp312-cp312-win_amd64.whl", hash = "sha256:50e2b72406c18cda5dd7431b0082cb85ea94e06c64c33607248fc8bef92cfb81"}, + {file = "numba-0.67.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:77e1c7173fee57a0d84e006c7e70346689d6cb3e7db503489bae58646b4eff7b"}, + {file = "numba-0.67.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9c4953387c77864b596d8296e2cfbdef82b0eea4166ab4864b05d226c51143e0"}, + {file = "numba-0.67.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:88f6e0f5cb6c545e158b6ef0496c01b6d6958a7ccc6634a1576a94bbbab29ff2"}, + {file = "numba-0.67.0-cp313-cp313-win_amd64.whl", hash = "sha256:b68ad5125fe245339cc8dcc036081fc1ea482c5063387b9612a76ccd83dc91cd"}, + {file = "numba-0.67.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:f99f880ff25f418a67f9a1d00d0ddfbc63430f627b523e515085a592a7567f4b"}, + {file = "numba-0.67.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5269245a675abdd3e2c35ec6bb2f250355effa9032514d8f2354f0d2d10854bd"}, + {file = "numba-0.67.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f074a8e23db78490f11a3930c940be758316c10ac5985be83d2f298dc080acf7"}, + {file = "numba-0.67.0-cp314-cp314-win_amd64.whl", hash = "sha256:4d576e62bf2c9370f61312b51573c4bb1f3fe96798bbab56730847a368a316c4"}, + {file = "numba-0.67.0-cp314-cp314-win_arm64.whl", hash = "sha256:7930748ce8355d2a5a28602abab056a61fdc676d17377f27d17993905428171f"}, + {file = "numba-0.67.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:4a2ed006635bbd0fe45681ed49f3b4f4bad1abf0c233bcc5842c9e3a34cabd61"}, + {file = "numba-0.67.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aa5f002f665bec321b950dacaa26ee009e1d720f6ac9d9856eed5efe1caa03a6"}, + {file = "numba-0.67.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:83ab968b0e0fa744eba03351282dd8000796e6ec8e4518f47bd3ed86c0a20c7b"}, + {file = "numba-0.67.0-cp314-cp314t-win_amd64.whl", hash = "sha256:00c964a5b94d3ae82d83ac162cd610755875b98dadb779fdde06e6bfcdbca47e"}, + {file = "numba-0.67.0.tar.gz", hash = "sha256:cd75aa535b33fa05d9d930b1ae8af9f97a2881e96d72dfb38ec9b78284d9f851"}, +] + +[package.dependencies] +llvmlite = "==0.49.*" +numpy = ">=1.22,<2.6" + + +[[package]] +name = "numpy" +version = "2.2.6" +description = "Fundamental package for array computing in Python" +optional = false +python-versions = ">=3.10" +groups = ["main", "dev"] +markers = "python_version == \"3.10\"" +files = [ + {file = "numpy-2.2.6-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b412caa66f72040e6d268491a59f2c43bf03eb6c96dd8f0307829feb7fa2b6fb"}, + {file = "numpy-2.2.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8e41fd67c52b86603a91c1a505ebaef50b3314de0213461c7a6e99c9a3beff90"}, + {file = "numpy-2.2.6-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:37e990a01ae6ec7fe7fa1c26c55ecb672dd98b19c3d0e1d1f326fa13cb38d163"}, + {file = "numpy-2.2.6-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:5a6429d4be8ca66d889b7cf70f536a397dc45ba6faeb5f8c5427935d9592e9cf"}, + {file = "numpy-2.2.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:efd28d4e9cd7d7a8d39074a4d44c63eda73401580c5c76acda2ce969e0a38e83"}, + {file = "numpy-2.2.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc7b73d02efb0e18c000e9ad8b83480dfcd5dfd11065997ed4c6747470ae8915"}, + {file = "numpy-2.2.6-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:74d4531beb257d2c3f4b261bfb0fc09e0f9ebb8842d82a7b4209415896adc680"}, + {file = "numpy-2.2.6-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:8fc377d995680230e83241d8a96def29f204b5782f371c532579b4f20607a289"}, + {file = "numpy-2.2.6-cp310-cp310-win32.whl", hash = "sha256:b093dd74e50a8cba3e873868d9e93a85b78e0daf2e98c6797566ad8044e8363d"}, + {file = "numpy-2.2.6-cp310-cp310-win_amd64.whl", hash = "sha256:f0fd6321b839904e15c46e0d257fdd101dd7f530fe03fd6359c1ea63738703f3"}, + {file = "numpy-2.2.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f9f1adb22318e121c5c69a09142811a201ef17ab257a1e66ca3025065b7f53ae"}, + {file = "numpy-2.2.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c820a93b0255bc360f53eca31a0e676fd1101f673dda8da93454a12e23fc5f7a"}, + {file = "numpy-2.2.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3d70692235e759f260c3d837193090014aebdf026dfd167834bcba43e30c2a42"}, + {file = "numpy-2.2.6-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:481b49095335f8eed42e39e8041327c05b0f6f4780488f61286ed3c01368d491"}, + {file = "numpy-2.2.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b64d8d4d17135e00c8e346e0a738deb17e754230d7e0810ac5012750bbd85a5a"}, + {file = "numpy-2.2.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba10f8411898fc418a521833e014a77d3ca01c15b0c6cdcce6a0d2897e6dbbdf"}, + {file = "numpy-2.2.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd48227a919f1bafbdda0583705e547892342c26fb127219d60a5c36882609d1"}, + {file = "numpy-2.2.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9551a499bf125c1d4f9e250377c1ee2eddd02e01eac6644c080162c0c51778ab"}, + {file = "numpy-2.2.6-cp311-cp311-win32.whl", hash = "sha256:0678000bb9ac1475cd454c6b8c799206af8107e310843532b04d49649c717a47"}, + {file = "numpy-2.2.6-cp311-cp311-win_amd64.whl", hash = "sha256:e8213002e427c69c45a52bbd94163084025f533a55a59d6f9c5b820774ef3303"}, + {file = "numpy-2.2.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:41c5a21f4a04fa86436124d388f6ed60a9343a6f767fced1a8a71c3fbca038ff"}, + {file = "numpy-2.2.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:de749064336d37e340f640b05f24e9e3dd678c57318c7289d222a8a2f543e90c"}, + {file = "numpy-2.2.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:894b3a42502226a1cac872f840030665f33326fc3dac8e57c607905773cdcde3"}, + {file = "numpy-2.2.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:71594f7c51a18e728451bb50cc60a3ce4e6538822731b2933209a1f3614e9282"}, + {file = "numpy-2.2.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f2618db89be1b4e05f7a1a847a9c1c0abd63e63a1607d892dd54668dd92faf87"}, + {file = "numpy-2.2.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd83c01228a688733f1ded5201c678f0c53ecc1006ffbc404db9f7a899ac6249"}, + {file = "numpy-2.2.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:37c0ca431f82cd5fa716eca9506aefcabc247fb27ba69c5062a6d3ade8cf8f49"}, + {file = "numpy-2.2.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fe27749d33bb772c80dcd84ae7e8df2adc920ae8297400dabec45f0dedb3f6de"}, + {file = "numpy-2.2.6-cp312-cp312-win32.whl", hash = "sha256:4eeaae00d789f66c7a25ac5f34b71a7035bb474e679f410e5e1a94deb24cf2d4"}, + {file = "numpy-2.2.6-cp312-cp312-win_amd64.whl", hash = "sha256:c1f9540be57940698ed329904db803cf7a402f3fc200bfe599334c9bd84a40b2"}, + {file = "numpy-2.2.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0811bb762109d9708cca4d0b13c4f67146e3c3b7cf8d34018c722adb2d957c84"}, + {file = "numpy-2.2.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:287cc3162b6f01463ccd86be154f284d0893d2b3ed7292439ea97eafa8170e0b"}, + {file = "numpy-2.2.6-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:f1372f041402e37e5e633e586f62aa53de2eac8d98cbfb822806ce4bbefcb74d"}, + {file = "numpy-2.2.6-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:55a4d33fa519660d69614a9fad433be87e5252f4b03850642f88993f7b2ca566"}, + {file = "numpy-2.2.6-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f92729c95468a2f4f15e9bb94c432a9229d0d50de67304399627a943201baa2f"}, + {file = "numpy-2.2.6-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1bc23a79bfabc5d056d106f9befb8d50c31ced2fbc70eedb8155aec74a45798f"}, + {file = "numpy-2.2.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e3143e4451880bed956e706a3220b4e5cf6172ef05fcc397f6f36a550b1dd868"}, + {file = "numpy-2.2.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b4f13750ce79751586ae2eb824ba7e1e8dba64784086c98cdbbcc6a42112ce0d"}, + {file = "numpy-2.2.6-cp313-cp313-win32.whl", hash = "sha256:5beb72339d9d4fa36522fc63802f469b13cdbe4fdab4a288f0c441b74272ebfd"}, + {file = "numpy-2.2.6-cp313-cp313-win_amd64.whl", hash = "sha256:b0544343a702fa80c95ad5d3d608ea3599dd54d4632df855e4c8d24eb6ecfa1c"}, + {file = "numpy-2.2.6-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0bca768cd85ae743b2affdc762d617eddf3bcf8724435498a1e80132d04879e6"}, + {file = "numpy-2.2.6-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:fc0c5673685c508a142ca65209b4e79ed6740a4ed6b2267dbba90f34b0b3cfda"}, + {file = "numpy-2.2.6-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:5bd4fc3ac8926b3819797a7c0e2631eb889b4118a9898c84f585a54d475b7e40"}, + {file = "numpy-2.2.6-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:fee4236c876c4e8369388054d02d0e9bb84821feb1a64dd59e137e6511a551f8"}, + {file = "numpy-2.2.6-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e1dda9c7e08dc141e0247a5b8f49cf05984955246a327d4c48bda16821947b2f"}, + {file = "numpy-2.2.6-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f447e6acb680fd307f40d3da4852208af94afdfab89cf850986c3ca00562f4fa"}, + {file = "numpy-2.2.6-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:389d771b1623ec92636b0786bc4ae56abafad4a4c513d36a55dce14bd9ce8571"}, + {file = "numpy-2.2.6-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8e9ace4a37db23421249ed236fdcdd457d671e25146786dfc96835cd951aa7c1"}, + {file = "numpy-2.2.6-cp313-cp313t-win32.whl", hash = "sha256:038613e9fb8c72b0a41f025a7e4c3f0b7a1b5d768ece4796b674c8f3fe13efff"}, + {file = "numpy-2.2.6-cp313-cp313t-win_amd64.whl", hash = "sha256:6031dd6dfecc0cf9f668681a37648373bddd6421fff6c66ec1624eed0180ee06"}, + {file = "numpy-2.2.6-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:0b605b275d7bd0c640cad4e5d30fa701a8d59302e127e5f79138ad62762c3e3d"}, + {file = "numpy-2.2.6-pp310-pypy310_pp73-macosx_14_0_x86_64.whl", hash = "sha256:7befc596a7dc9da8a337f79802ee8adb30a552a94f792b9c9d18c840055907db"}, + {file = "numpy-2.2.6-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ce47521a4754c8f4593837384bd3424880629f718d87c5d44f8ed763edd63543"}, + {file = "numpy-2.2.6-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:d042d24c90c41b54fd506da306759e06e568864df8ec17ccc17e9e884634fd00"}, + {file = "numpy-2.2.6.tar.gz", hash = "sha256:e29554e2bef54a90aa5cc07da6ce955accb83f21ab5de01a62c8478897b264fd"}, +] + + +[[package]] +name = "numpy" +version = "2.4.6" +description = "Fundamental package for array computing in Python" +optional = false +python-versions = ">=3.11" +groups = ["main", "dev"] +markers = "python_version == \"3.11\"" +files = [ + {file = "numpy-2.4.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0280e0356c0829a18d9de1cb7eee50ec22ca639878d7240307ca0943d73cd2c4"}, + {file = "numpy-2.4.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:110f8b71aacb688ec69062bb7f6938a0f8acb01b7c1c4beb453c65b6d234584d"}, + {file = "numpy-2.4.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:4cfe66903cc32a9921a6733d96b19bb6abf310397581bbad89c228f5abaf0ee8"}, + {file = "numpy-2.4.6-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:8155154c7c691289fe18f510b5d4657c68c67989f293f0535a91360392ff6538"}, + {file = "numpy-2.4.6-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0ab0a9c4ffb1a6d95ef519fe4247dba8eb6b18ad93999f76b7f657039acabd47"}, + {file = "numpy-2.4.6-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:89cd468399cfd2504718f0ba50e410dca55a170b61a02ad92bb18c8a65186e93"}, + {file = "numpy-2.4.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c2d37ab77531417474168eb79d6d80b14f821a966818505d03013d0833edb7a8"}, + {file = "numpy-2.4.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f407cb6b8e9d6d8c626bc73c945db1706035af8fd632295547bf1c9e46d092d6"}, + {file = "numpy-2.4.6-cp311-cp311-win32.whl", hash = "sha256:ddea102b48f9e339f3948bf22040944184627a30fdf7f858667673b9c5f033c8"}, + {file = "numpy-2.4.6-cp311-cp311-win_amd64.whl", hash = "sha256:1e254a00cdf42b1e4d5b3d68d33af63268d41340d8885df2ab6470f2e1500147"}, + {file = "numpy-2.4.6-cp311-cp311-win_arm64.whl", hash = "sha256:ed9749eef4cbd126da3dc1d6bcb3a57f5eb7ac6a6484146bdbf743f552dfc577"}, + {file = "numpy-2.4.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:001fbb8e08d942dd57599e781f2472269ee7f2755fae407b4f67b2f0b17da3f1"}, + {file = "numpy-2.4.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ebfb099f8dcf083deef3ac1ca4c1503f387cf76296fcb3816b66f5ecb5f54fdb"}, + {file = "numpy-2.4.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:3213d622a0283a39a93d188f3cf72b26862df52fbb4ca3697f51705016523d41"}, + {file = "numpy-2.4.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:357cc07a6d7b0b182ff02249616a03742827ebb1277546b5c7cd7f7620a45698"}, + {file = "numpy-2.4.6-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5f9fb9157b4ce2971008323afe46053787b526ef624fea915b261468a8421a0f"}, + {file = "numpy-2.4.6-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:90f9849678c75fe7afa2d348ac842c168b0a4d3d61919687216dfc547976d853"}, + {file = "numpy-2.4.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c1a2af6c6ef86344a6b0db6b97834208bf598db514f2b155042439b62605601a"}, + {file = "numpy-2.4.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e5805d5a22fd19c8ccff10a9561f9df94436b0545619ea579db2d3c35294bce2"}, + {file = "numpy-2.4.6-cp312-cp312-win32.whl", hash = "sha256:e3eeb0aabd6bd5ce64faae67e9935203a6991b4bc2a485a767fbafb2c5125f45"}, + {file = "numpy-2.4.6-cp312-cp312-win_amd64.whl", hash = "sha256:d8e8286dd7cea7895157318d1b91cdacac64c479f3cbc8dce548331728484751"}, + {file = "numpy-2.4.6-cp312-cp312-win_arm64.whl", hash = "sha256:4081eb135ac24158bd51cdfbef16f1c64df7063b1143f24731387137c092bec8"}, + {file = "numpy-2.4.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:511dbaf848decaaaf4b4ca48032619fb3138710c4bf7da7617765edad1ef96b0"}, + {file = "numpy-2.4.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bf162abab1c1a736333192707cef898e735a5ca00f38f27eeedf44b39d9e85eb"}, + {file = "numpy-2.4.6-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:043191bfa8eab18c776647b62723ac9dddece59743b13f49b2016094129c2b3f"}, + {file = "numpy-2.4.6-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:6180d8b35af935aed8ece3a85e0a43f87393ae0ac87c8d2c8bd2c993f7270ef3"}, + {file = "numpy-2.4.6-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:72fbe16c6fac95aedf5937fa873445cec2110be35d8a4e9433d7501fd98dae6b"}, + {file = "numpy-2.4.6-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a7830bab239b79cda9c08c2da014761cafb48da6150e1da17ac06283f43b6089"}, + {file = "numpy-2.4.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ef4aea96ce4d3b074422cb4f2f64e216bf9e213004bb58ecfdf50ea02ea8eb9a"}, + {file = "numpy-2.4.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:dfa20cc6ca228e6b155b11da03825975ce66aea520985dbbddf0f2a5a495c605"}, + {file = "numpy-2.4.6-cp313-cp313-win32.whl", hash = "sha256:56b39e5e0622a09a25bf5baf62f4bcf0cb8a41ae6e2819cf49bbc5a74c083f91"}, + {file = "numpy-2.4.6-cp313-cp313-win_amd64.whl", hash = "sha256:c4fc99836233ea196540b17ab0983aff60ed07941751930f5f4d05bc3b3b7359"}, + {file = "numpy-2.4.6-cp313-cp313-win_arm64.whl", hash = "sha256:a7c711e21628b52034bb5ab8d1bce291f752fcc5e92accc615778acee1ff4778"}, + {file = "numpy-2.4.6-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:112b06a867b235ef466ed3508ddf0238050df9c727cafb5301ac385b899189a1"}, + {file = "numpy-2.4.6-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:eaf7fa2de5c0be8ae6ff8e9bea2ccd725e980541244521d8d4b5f3354a27babe"}, + {file = "numpy-2.4.6-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:7265a2f3d436e54ef9f2b52b5c937e6be778781bd97a590319d7348f1c1ca997"}, + {file = "numpy-2.4.6-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f74a575920ab21fe304421a3fc28793d82e299cae9eccb37084e9fc7f3617c20"}, + {file = "numpy-2.4.6-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ede83e07a75dd06bc501566c1eca2afc0d61677c1472ac9ad93fdee6e638a48d"}, + {file = "numpy-2.4.6-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:68bb27509ac1b9a3443094260f6326150663b06abe40b73a2f81160623da5b67"}, + {file = "numpy-2.4.6-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:a0df0043bdb289bde1f62da130d20df23d58b45429f752bc7a8fc5325a225ecd"}, + {file = "numpy-2.4.6-cp313-cp313t-win32.whl", hash = "sha256:29a287e0cf63ff528da061de6b9f64a4618da591ca1046aafc54062e40ca7eab"}, + {file = "numpy-2.4.6-cp313-cp313t-win_amd64.whl", hash = "sha256:25c692919ac5a01f170a3bfcd62d745b24fd095c353d50812637d6fcab442e75"}, + {file = "numpy-2.4.6-cp313-cp313t-win_arm64.whl", hash = "sha256:1e978ec1e8bd0e0e4de6bb75de9d30cbb74db6b6a2bb727618613703ca0167dd"}, + {file = "numpy-2.4.6-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:06ca2f61ec4385a07a6977c55ba998a4466c123642b4a32694d3128fce18c079"}, + {file = "numpy-2.4.6-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:38efbc8de75c7a0fc1ac190162d892787f3f47b57cc291231aafee36b80982b7"}, + {file = "numpy-2.4.6-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:d581b735e177fdcdce6fed8e7e8880a3fb6ee4e3653a3ac6af01c6f4c03effc5"}, + {file = "numpy-2.4.6-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:0a041d3d761dc3c35cc56ce0351506a02bcbc25f7b169f652435141a17db9096"}, + {file = "numpy-2.4.6-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:40fdc1ae7125e518ea98e53e69a4ebc27e1fd50510c47b7ea130cf21e5e1d42b"}, + {file = "numpy-2.4.6-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a2c306dea656c12c68f51f4cea133cbe78ca7435eb28c735eac1d3ebe73be6e8"}, + {file = "numpy-2.4.6-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:33111801a01c12a8a1e3721f0a9232f8cfc8ae2c6b7098167e6f623c6073f402"}, + {file = "numpy-2.4.6-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ae506e6902902557576a26ff33eda8695e7ecb3cb36c3b573a0765dee114ebdb"}, + {file = "numpy-2.4.6-cp314-cp314-win32.whl", hash = "sha256:aaf159caa35993cb1f56fb9b8e4610d35758e7ca005412eb1daa856a78c9c4b1"}, + {file = "numpy-2.4.6-cp314-cp314-win_amd64.whl", hash = "sha256:b507f5c4c1d508876d1819b6bf9a49d365b96320b5d4993426b33a23ca4b8261"}, + {file = "numpy-2.4.6-cp314-cp314-win_arm64.whl", hash = "sha256:6f41ae150c4e32db4f3310cdaf64b1593a03dbabe29eec77fc9b50fe64061df6"}, + {file = "numpy-2.4.6-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ece3d2cfe132e7d51f44a832b303895e6f2d499c5e74dfbdb06ee246147a304a"}, + {file = "numpy-2.4.6-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:e3e5193ef5a3dc73bceee50f7fdc2c90dbb76c42df8d8fae3d1067a583df579e"}, + {file = "numpy-2.4.6-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:17f9ade344e7d9b464a084d69bcf18fc691cb1db67c62ed80820bf4926d78f0e"}, + {file = "numpy-2.4.6-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9cd5ffd25db4e7ba6a375693b3fc0fc1791ec636c17db3720da19bde7180ec43"}, + {file = "numpy-2.4.6-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7d92c3819208a60205a12a245c91ad70cb0a85336659b19b834205573ac8456e"}, + {file = "numpy-2.4.6-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e85b752a1e912b70eaad4fafbd4d1238007ab221de2009b9a2f5ae7461239895"}, + {file = "numpy-2.4.6-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:29cb7f67d10b479ff07c17d33e39f78c07f71c40ef30d63c153d340e96cd3fb4"}, + {file = "numpy-2.4.6-cp314-cp314t-win32.whl", hash = "sha256:260a5d70215b61ab4fadf5c7baacd64821842975eea312125ed3c39a6391b063"}, + {file = "numpy-2.4.6-cp314-cp314t-win_amd64.whl", hash = "sha256:81a1cca95ed5bb92aa8b10dd2cdc9a0d3853a50fad926c28b5d7e8ea54389627"}, + {file = "numpy-2.4.6-cp314-cp314t-win_arm64.whl", hash = "sha256:0c9136e14ed34a9e343a31c533d78a9813a69a3148332bce5e9821cb2f996e66"}, + {file = "numpy-2.4.6-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:55cced7c52e981362f708ad635198e97a752dfba412cc03c23bbf3bd8d5cd662"}, + {file = "numpy-2.4.6-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:d6da64deb6b8ed903e7560180a92f2d804ee1ba5eeb849ac2748b8c1aba1f6d7"}, + {file = "numpy-2.4.6-pp311-pypy311_pp73-macosx_14_0_arm64.whl", hash = "sha256:68a5124b13fa6cc2086764a20005d30bc0548146f7f5322f02fce212ca14317f"}, + {file = "numpy-2.4.6-pp311-pypy311_pp73-macosx_14_0_x86_64.whl", hash = "sha256:948424b06129ce883307e8cff868c31396d8dc7630a59c61d70d98dbe70f222c"}, + {file = "numpy-2.4.6-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5dbbdb29840ca3d91ee0fece42fc29278886d908280bfec0a5846c6f901a3eb0"}, + {file = "numpy-2.4.6-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8ad03c0965fb3c692200e74d458ca28c1dbb4ce96f9a479a8aa041ad5fabca02"}, + {file = "numpy-2.4.6-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:2803abfebfc990042cd494d8ce2d5f82e9d847af6d35ec486923aa19dbad5e73"}, + {file = "numpy-2.4.6.tar.gz", hash = "sha256:f3a3570c4a2a16746ac2c31a7c7c7b0c186b95ce902e33db6f28094ed7387dda"}, +] + + +[[package]] +name = "numpy" +version = "2.5.3" +description = "Fundamental package for array computing in Python" +optional = false +python-versions = ">=3.12" +groups = ["main", "dev"] +markers = "python_version >= \"3.12\"" +files = [ + {file = "numpy-2.5.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:cb189f09db39283b26bfd061ec16189e14f71c6755207f72a0f7540867afe5b9"}, + {file = "numpy-2.5.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f59a878c33d6b88122d80d239bb3b845d58708750b0cb06a09aebb9b18ec696c"}, + {file = "numpy-2.5.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:a72f874bc9e10e4b8f80426fb49716d5141f64442a0c8418065093ec8017fbb0"}, + {file = "numpy-2.5.3-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:fc36dc566135b5eceec4cf89758fcb719266a019ef07dae1754ae7c9f617ef3e"}, + {file = "numpy-2.5.3-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:76c2c1e6bfa5c84adc6434dfbf013aa92096a7985221762c8f11fedfd20fff58"}, + {file = "numpy-2.5.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b7e18c623bb5c95acb3b3328861272816ba199fb531921c5d6d0b675f1fde9e3"}, + {file = "numpy-2.5.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4f8929ee6c96bfbd7b4ed2032e0c03af86fe1826740ab61ddabf9072d06e57ff"}, + {file = "numpy-2.5.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b5d93cf48f687479941d12b69c873ad2cc76bbd487f0091c2200636497f34034"}, + {file = "numpy-2.5.3-cp312-cp312-win32.whl", hash = "sha256:bf63afbe037eb5d2fe87fbcc7778e61da53ebaf21d938a4515aa73b62532a5d4"}, + {file = "numpy-2.5.3-cp312-cp312-win_amd64.whl", hash = "sha256:0a59a421a32580a009e8a1751345bf829631b990dc1794b80514ab722b435def"}, + {file = "numpy-2.5.3-cp312-cp312-win_arm64.whl", hash = "sha256:ccb32e0525d29e8b0572eb84c9a57af0e7a4e615726927506f55063c62414034"}, + {file = "numpy-2.5.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:66a78fe4556c60aceda5916f9eacd638b18e9e681016ec302dcb4682d6d4d034"}, + {file = "numpy-2.5.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:92f30e89b8ee0ecf363033576c422b2f58fed6a80bed0aa48dff6d14c654663e"}, + {file = "numpy-2.5.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:f9a2353b37a1a9e78fd82b27ad7e2a32a2d036604d18f02b05e3136c62ca3b09"}, + {file = "numpy-2.5.3-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:ccbc4665079665c3cf3bab4db9f6b095370cd6437d66be549b6c2a1fd19e1958"}, + {file = "numpy-2.5.3-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c76d5dde9f445058f83d0c02af00557a4db91de9a9a57c0df87d1535001d654b"}, + {file = "numpy-2.5.3-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a5fa86b80fd24bcd1aff83ad23be44ea323de3f787be8f8b15d4a65621e25321"}, + {file = "numpy-2.5.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:bd4cb9ad3c7889b9b3fe0a9a9fb5d2ed26f9879bff2608d9f01aed147a20d231"}, + {file = "numpy-2.5.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1302b90c0e52281681b2975adfe8a860cb7b12216a27b4b0b4207c44bf7bccf0"}, + {file = "numpy-2.5.3-cp313-cp313-win32.whl", hash = "sha256:1c80eabb4035ecf4ca9cd49cde8a9fdd69a729e63e6474887d1523ade7aa277f"}, + {file = "numpy-2.5.3-cp313-cp313-win_amd64.whl", hash = "sha256:71cad2b2a7451ab79d8f5e71b453485b6775963d5cf794179144a7463fe6e8ec"}, + {file = "numpy-2.5.3-cp313-cp313-win_arm64.whl", hash = "sha256:8e4dd766076855b5ff7ea52fa5f07ce26286726e0f8bff446b7739d02e6ea204"}, + {file = "numpy-2.5.3-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:350ba9783ce969cf9f7ce6e6a9a58e1a6e2a19ca025b7ee448c4db727706212a"}, + {file = "numpy-2.5.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:012e66aca395d795496446e52aeeb5866312a5d4d3f27da270e5a0b43f70dc5c"}, + {file = "numpy-2.5.3-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:adc1ada2662f8a5f960b8a10d9986897e7499ef07e06d4cfe7197f8cce923c07"}, + {file = "numpy-2.5.3-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:54a115e5a73b8fc44f0cebef486365a1894b5c9760685d4558b72b7c3eb846e0"}, + {file = "numpy-2.5.3-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:be5a8381859b6da607c84f4f7d6847725f1cf1853ef8a2c9e115b7d58bef47dc"}, + {file = "numpy-2.5.3-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b0521d0f4aebb6e06189451025fa17a913287b13c03d5fe05c017333b654ea5b"}, + {file = "numpy-2.5.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:9deb49575e5b0b94ed72c8a64ec4d033381adc27e9060ae842971f697ba96104"}, + {file = "numpy-2.5.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:b00eefbcf0f292945c4b4dec2ae845389ef5bcdcd596e6e4328051db5b5ba694"}, + {file = "numpy-2.5.3-cp314-cp314-win32.whl", hash = "sha256:c2381f82999704f818e2c987a865050e285ec3621262c66d40f5a96c8f899f8e"}, + {file = "numpy-2.5.3-cp314-cp314-win_amd64.whl", hash = "sha256:2c25dfa72943e4336ddb6b0ee4277b47a0c85bede0807530ec68103bf58e2c10"}, + {file = "numpy-2.5.3-cp314-cp314-win_arm64.whl", hash = "sha256:15aa985ac73a8db02db7663381aa109510449d3819d37206caed27b33a65a8a6"}, + {file = "numpy-2.5.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ac7bb1c52d445bd4f8f7f97fefe6abc3a084dc4d63df50d79b17fa2b78e89297"}, + {file = "numpy-2.5.3-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:e6ab667ba76450084eb64013762c438ea76d9d29cc676dcd6c2e9892ba37f841"}, + {file = "numpy-2.5.3-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:f7fabeb6cea87d65f3b926de33d03fb016cfdc29314c90974383b5582ae72891"}, + {file = "numpy-2.5.3-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1fb6f8fb9ff0b3a69f52c66ce397b0246583e9f28616231b0e32ca49259a5fa6"}, + {file = "numpy-2.5.3-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:93e1f5447e2b1e479d7bd74701e84746b86450cff1fc368b132d195e2b8f8211"}, + {file = "numpy-2.5.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c00abe94c1a69d75d827dcf1c025b25c8a45d230b3bcd77a9020883a1b047653"}, + {file = "numpy-2.5.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:536f963710a4e63934d80ac0dc4f478804a83e9a84b6828018f25d09953ada33"}, + {file = "numpy-2.5.3-cp314-cp314t-win32.whl", hash = "sha256:4c8a6d2ebce6305fd82fbefca827775437147052a976ee7c94b36a0c1b52ac6c"}, + {file = "numpy-2.5.3-cp314-cp314t-win_amd64.whl", hash = "sha256:9a37475425b431b4d060f23b4f52cd2f3aef6bc7c654bd760adf0040eec9d435"}, + {file = "numpy-2.5.3-cp314-cp314t-win_arm64.whl", hash = "sha256:2d8240cb4c16fd831074aa2b2cf9fc54664d826341d61c372245b96a74a49a9a"}, + {file = "numpy-2.5.3-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:a6391fafaba97500887132cd582abc6e19452b1ac775a47caa7b24490e152058"}, + {file = "numpy-2.5.3-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:09d5a423c71ad5feb5625844ad58050e35df43871004b52ac9c0ad44a56775be"}, + {file = "numpy-2.5.3-cp315-cp315-macosx_14_0_arm64.whl", hash = "sha256:f9579f383d1bf9df80081e72760e84960a7fd4f88cf0c9e535a8597c9bb646f5"}, + {file = "numpy-2.5.3-cp315-cp315-macosx_14_0_x86_64.whl", hash = "sha256:86bff898a431c0fb71f7610b75726e75a54d47b37edc9d537f48de63bb3c0b90"}, + {file = "numpy-2.5.3-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1f3ed25271581281f2fccb1adcedfcde4c07362eec69189b50baf6f90e3ae159"}, + {file = "numpy-2.5.3-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ffdc76bfcae6b255dff75202c5e7feaf95b40246bc0a17944facc1fecf9f79ab"}, + {file = "numpy-2.5.3-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:116f96cadd935c6122e9228d676fe7ede19e741f5c8bb1c3cddbe0c51ccebea2"}, + {file = "numpy-2.5.3-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:09ffa5d903faeaa5c4dd05009cf81c8bab9f2cb37c548b8d39b65b4cfa7c97f7"}, + {file = "numpy-2.5.3-cp315-cp315-win32.whl", hash = "sha256:e01c918ac3d48e18a927cf7b14a26a3e29ff2bdf2eacb976da0aecd6a43ed034"}, + {file = "numpy-2.5.3-cp315-cp315-win_amd64.whl", hash = "sha256:e931e4f499e0dc7ef29d269a8e5b35dd722e5d14be07df6240166ea7c6532fae"}, + {file = "numpy-2.5.3-cp315-cp315-win_arm64.whl", hash = "sha256:26e15e4aecd8617dfbaecb37d223e365d7b39411fba20454be2670a96aa74cb5"}, + {file = "numpy-2.5.3-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:6cef4bb1706dfec49243c05d921eefb4e190d41e2528b30d8035ea1f36b4c24a"}, + {file = "numpy-2.5.3-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:d1c89973648c85069c5046ad460f7b8a00218b29a2e42359ac8cc63e9ab94832"}, + {file = "numpy-2.5.3-cp315-cp315t-macosx_14_0_arm64.whl", hash = "sha256:214045a5bf00113a146ab9ee9730c44501af6723cdf1f6830932f7b5ef2e7af0"}, + {file = "numpy-2.5.3-cp315-cp315t-macosx_14_0_x86_64.whl", hash = "sha256:8617bbfae4486cf99c9f899966699428d19da931d06ca94ad3da986c76e15997"}, + {file = "numpy-2.5.3-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:595d020938c84e320bcf40ad71089e108eac0d377cd018e14a8c094f39e98d85"}, + {file = "numpy-2.5.3-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f24021b9f22bc6301c37b196974a92c1c18dccedb6fef3dd252e95f2d6adbe4"}, + {file = "numpy-2.5.3-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:71b39d9f935b6ec0f8753e3e2afb51e3efba6f2e05b68b32a40754d24bcd4a3c"}, + {file = "numpy-2.5.3-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:6b05c171afb3aa07adbd20abc00aea86fe375beb0fdb9ef780ec5b7f63bab1c0"}, + {file = "numpy-2.5.3-cp315-cp315t-win32.whl", hash = "sha256:f54660b0eb6b0b9f36e7fe1cdfdff472028dd0d14acd9b9b65098efbad059469"}, + {file = "numpy-2.5.3-cp315-cp315t-win_amd64.whl", hash = "sha256:1aad64d99730d013cfc6debafed22783b4fc5a7f4b8bc744d2d8cf7dcc880551"}, + {file = "numpy-2.5.3-cp315-cp315t-win_arm64.whl", hash = "sha256:befa1ae5bd6030b3f512b43ff3fa5290bbed6b84411a44244b14adf835f5b89d"}, + {file = "numpy-2.5.3.tar.gz", hash = "sha256:df2d5874ff183595a4ba404edd04f6bd9b5505c1d7708573f6a6c17489a67563"}, +] + + +[[package]] +name = "packaging" +version = "26.3" +description = "Core utilities for Python packages" +optional = false +python-versions = ">=3.9" +groups = ["main", "dev", "docs"] +files = [ + {file = "packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c"}, + {file = "packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79"}, +] + + +[[package]] +name = "pandas" +version = "2.3.3" +description = "Powerful data structures for data analysis, time series, and statistics" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "pandas-2.3.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:376c6446ae31770764215a6c937f72d917f214b43560603cd60da6408f183b6c"}, + {file = "pandas-2.3.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e19d192383eab2f4ceb30b412b22ea30690c9e618f78870357ae1d682912015a"}, + {file = "pandas-2.3.3-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5caf26f64126b6c7aec964f74266f435afef1c1b13da3b0636c7518a1fa3e2b1"}, + {file = "pandas-2.3.3-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:dd7478f1463441ae4ca7308a70e90b33470fa593429f9d4c578dd00d1fa78838"}, + {file = "pandas-2.3.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:4793891684806ae50d1288c9bae9330293ab4e083ccd1c5e383c34549c6e4250"}, + {file = "pandas-2.3.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:28083c648d9a99a5dd035ec125d42439c6c1c525098c58af0fc38dd1a7a1b3d4"}, + {file = "pandas-2.3.3-cp310-cp310-win_amd64.whl", hash = "sha256:503cf027cf9940d2ceaa1a93cfb5f8c8c7e6e90720a2850378f0b3f3b1e06826"}, + {file = "pandas-2.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:602b8615ebcc4a0c1751e71840428ddebeb142ec02c786e8ad6b1ce3c8dec523"}, + {file = "pandas-2.3.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8fe25fc7b623b0ef6b5009149627e34d2a4657e880948ec3c840e9402e5c1b45"}, + {file = "pandas-2.3.3-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b468d3dad6ff947df92dcb32ede5b7bd41a9b3cceef0a30ed925f6d01fb8fa66"}, + {file = "pandas-2.3.3-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b98560e98cb334799c0b07ca7967ac361a47326e9b4e5a7dfb5ab2b1c9d35a1b"}, + {file = "pandas-2.3.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d37b5848ba49824e5c30bedb9c830ab9b7751fd049bc7914533e01c65f79791"}, + {file = "pandas-2.3.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:db4301b2d1f926ae677a751eb2bd0e8c5f5319c9cb3f88b0becbbb0b07b34151"}, + {file = "pandas-2.3.3-cp311-cp311-win_amd64.whl", hash = "sha256:f086f6fe114e19d92014a1966f43a3e62285109afe874f067f5abbdcbb10e59c"}, + {file = "pandas-2.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d21f6d74eb1725c2efaa71a2bfc661a0689579b58e9c0ca58a739ff0b002b53"}, + {file = "pandas-2.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3fd2f887589c7aa868e02632612ba39acb0b8948faf5cc58f0850e165bd46f35"}, + {file = "pandas-2.3.3-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ecaf1e12bdc03c86ad4a7ea848d66c685cb6851d807a26aa245ca3d2017a1908"}, + {file = "pandas-2.3.3-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b3d11d2fda7eb164ef27ffc14b4fcab16a80e1ce67e9f57e19ec0afaf715ba89"}, + {file = "pandas-2.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a68e15f780eddf2b07d242e17a04aa187a7ee12b40b930bfdd78070556550e98"}, + {file = "pandas-2.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:371a4ab48e950033bcf52b6527eccb564f52dc826c02afd9a1bc0ab731bba084"}, + {file = "pandas-2.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:a16dcec078a01eeef8ee61bf64074b4e524a2a3f4b3be9326420cabe59c4778b"}, + {file = "pandas-2.3.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:56851a737e3470de7fa88e6131f41281ed440d29a9268dcbf0002da5ac366713"}, + {file = "pandas-2.3.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bdcd9d1167f4885211e401b3036c0c8d9e274eee67ea8d0758a256d60704cfe8"}, + {file = "pandas-2.3.3-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e32e7cc9af0f1cc15548288a51a3b681cc2a219faa838e995f7dc53dbab1062d"}, + {file = "pandas-2.3.3-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:318d77e0e42a628c04dc56bcef4b40de67918f7041c2b061af1da41dcff670ac"}, + {file = "pandas-2.3.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4e0a175408804d566144e170d0476b15d78458795bb18f1304fb94160cabf40c"}, + {file = "pandas-2.3.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:93c2d9ab0fc11822b5eece72ec9587e172f63cff87c00b062f6e37448ced4493"}, + {file = "pandas-2.3.3-cp313-cp313-win_amd64.whl", hash = "sha256:f8bfc0e12dc78f777f323f55c58649591b2cd0c43534e8355c51d3fede5f4dee"}, + {file = "pandas-2.3.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:75ea25f9529fdec2d2e93a42c523962261e567d250b0013b16210e1d40d7c2e5"}, + {file = "pandas-2.3.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:74ecdf1d301e812db96a465a525952f4dde225fdb6d8e5a521d47e1f42041e21"}, + {file = "pandas-2.3.3-cp313-cp313t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6435cb949cb34ec11cc9860246ccb2fdc9ecd742c12d3304989017d53f039a78"}, + {file = "pandas-2.3.3-cp313-cp313t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:900f47d8f20860de523a1ac881c4c36d65efcb2eb850e6948140fa781736e110"}, + {file = "pandas-2.3.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:a45c765238e2ed7d7c608fc5bc4a6f88b642f2f01e70c0c23d2224dd21829d86"}, + {file = "pandas-2.3.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:c4fc4c21971a1a9f4bdb4c73978c7f7256caa3e62b323f70d6cb80db583350bc"}, + {file = "pandas-2.3.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:ee15f284898e7b246df8087fc82b87b01686f98ee67d85a17b7ab44143a3a9a0"}, + {file = "pandas-2.3.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1611aedd912e1ff81ff41c745822980c49ce4a7907537be8692c8dbc31924593"}, + {file = "pandas-2.3.3-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6d2cefc361461662ac48810cb14365a365ce864afe85ef1f447ff5a1e99ea81c"}, + {file = "pandas-2.3.3-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ee67acbbf05014ea6c763beb097e03cd629961c8a632075eeb34247120abcb4b"}, + {file = "pandas-2.3.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c46467899aaa4da076d5abc11084634e2d197e9460643dd455ac3db5856b24d6"}, + {file = "pandas-2.3.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6253c72c6a1d990a410bc7de641d34053364ef8bcd3126f7e7450125887dffe3"}, + {file = "pandas-2.3.3-cp314-cp314-win_amd64.whl", hash = "sha256:1b07204a219b3b7350abaae088f451860223a52cfb8a6c53358e7948735158e5"}, + {file = "pandas-2.3.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:2462b1a365b6109d275250baaae7b760fd25c726aaca0054649286bcfbb3e8ec"}, + {file = "pandas-2.3.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0242fe9a49aa8b4d78a4fa03acb397a58833ef6199e9aa40a95f027bb3a1b6e7"}, + {file = "pandas-2.3.3-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a21d830e78df0a515db2b3d2f5570610f5e6bd2e27749770e8bb7b524b89b450"}, + {file = "pandas-2.3.3-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2e3ebdb170b5ef78f19bfb71b0dc5dc58775032361fa188e814959b74d726dd5"}, + {file = "pandas-2.3.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d051c0e065b94b7a3cea50eb1ec32e912cd96dba41647eb24104b6c6c14c5788"}, + {file = "pandas-2.3.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3869faf4bd07b3b66a9f462417d0ca3a9df29a9f6abd5d0d0dbab15dac7abe87"}, + {file = "pandas-2.3.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:c503ba5216814e295f40711470446bc3fd00f0faea8a086cbc688808e26f92a2"}, + {file = "pandas-2.3.3-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:a637c5cdfa04b6d6e2ecedcb81fc52ffb0fd78ce2ebccc9ea964df9f658de8c8"}, + {file = "pandas-2.3.3-cp39-cp39-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:854d00d556406bffe66a4c0802f334c9ad5a96b4f1f868adf036a21b11ef13ff"}, + {file = "pandas-2.3.3-cp39-cp39-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bf1f8a81d04ca90e32a0aceb819d34dbd378a98bf923b6398b9a3ec0bf44de29"}, + {file = "pandas-2.3.3-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:23ebd657a4d38268c7dfbdf089fbc31ea709d82e4923c5ffd4fbd5747133ce73"}, + {file = "pandas-2.3.3-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:5554c929ccc317d41a5e3d1234f3be588248e61f08a74dd17c9eabb535777dc9"}, + {file = "pandas-2.3.3-cp39-cp39-win_amd64.whl", hash = "sha256:d3e28b3e83862ccf4d85ff19cf8c20b2ae7e503881711ff2d534dc8f761131aa"}, + {file = "pandas-2.3.3.tar.gz", hash = "sha256:e05e1af93b977f7eafa636d043f9f94c7ee3ac81af99c13508215942e64c993b"}, +] + +[package.dependencies] +numpy = [ + {version = ">=1.22.4", markers = "python_version < \"3.11\""}, + {version = ">=1.23.2", markers = "python_version == \"3.11\""}, + {version = ">=1.26.0", markers = "python_version >= \"3.12\""}, +] +python-dateutil = ">=2.8.2" +pytz = ">=2020.1" +tzdata = ">=2022.7" + +[package.extras] +all = ["PyQt5 (>=5.15.9)", "SQLAlchemy (>=2.0.0)", "adbc-driver-postgresql (>=0.8.0)", "adbc-driver-sqlite (>=0.8.0)", "beautifulsoup4 (>=4.11.2)", "bottleneck (>=1.3.6)", "dataframe-api-compat (>=0.1.7)", "fastparquet (>=2022.12.0)", "fsspec (>=2022.11.0)", "gcsfs (>=2022.11.0)", "html5lib (>=1.1)", "hypothesis (>=6.46.1)", "jinja2 (>=3.1.2)", "lxml (>=4.9.2)", "matplotlib (>=3.6.3)", "numba (>=0.56.4)", "numexpr (>=2.8.4)", "odfpy (>=1.4.1)", "openpyxl (>=3.1.0)", "pandas-gbq (>=0.19.0)", "psycopg2 (>=2.9.6)", "pyarrow (>=10.0.1)", "pymysql (>=1.0.2)", "pyreadstat (>=1.2.0)", "pytest (>=7.3.2)", "pytest-xdist (>=2.2.0)", "python-calamine (>=0.1.7)", "pyxlsb (>=1.0.10)", "qtpy (>=2.3.0)", "s3fs (>=2022.11.0)", "scipy (>=1.10.0)", "tables (>=3.8.0)", "tabulate (>=0.9.0)", "xarray (>=2022.12.0)", "xlrd (>=2.0.1)", "xlsxwriter (>=3.0.5)", "zstandard (>=0.19.0)"] +aws = ["s3fs (>=2022.11.0)"] +clipboard = ["PyQt5 (>=5.15.9)", "qtpy (>=2.3.0)"] +compression = ["zstandard (>=0.19.0)"] +computation = ["scipy (>=1.10.0)", "xarray (>=2022.12.0)"] +consortium-standard = ["dataframe-api-compat (>=0.1.7)"] +excel = ["odfpy (>=1.4.1)", "openpyxl (>=3.1.0)", "python-calamine (>=0.1.7)", "pyxlsb (>=1.0.10)", "xlrd (>=2.0.1)", "xlsxwriter (>=3.0.5)"] +feather = ["pyarrow (>=10.0.1)"] +fss = ["fsspec (>=2022.11.0)"] +gcp = ["gcsfs (>=2022.11.0)", "pandas-gbq (>=0.19.0)"] +hdf5 = ["tables (>=3.8.0)"] +html = ["beautifulsoup4 (>=4.11.2)", "html5lib (>=1.1)", "lxml (>=4.9.2)"] +mysql = ["SQLAlchemy (>=2.0.0)", "pymysql (>=1.0.2)"] +output-formatting = ["jinja2 (>=3.1.2)", "tabulate (>=0.9.0)"] +parquet = ["pyarrow (>=10.0.1)"] +performance = ["bottleneck (>=1.3.6)", "numba (>=0.56.4)", "numexpr (>=2.8.4)"] +plot = ["matplotlib (>=3.6.3)"] +postgresql = ["SQLAlchemy (>=2.0.0)", "adbc-driver-postgresql (>=0.8.0)", "psycopg2 (>=2.9.6)"] +pyarrow = ["pyarrow (>=10.0.1)"] +spss = ["pyreadstat (>=1.2.0)"] +sql-other = ["SQLAlchemy (>=2.0.0)", "adbc-driver-postgresql (>=0.8.0)", "adbc-driver-sqlite (>=0.8.0)"] +test = ["hypothesis (>=6.46.1)", "pytest (>=7.3.2)", "pytest-xdist (>=2.2.0)"] +xml = ["lxml (>=4.9.2)"] + + +[[package]] +name = "pandas-stubs" +version = "2.3.3.260113" +description = "Type annotations for pandas" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "pandas_stubs-2.3.3.260113-py3-none-any.whl", hash = "sha256:ec070b5c576e1badf12544ae50385872f0631fc35d99d00dc598c2954ec564d3"}, + {file = "pandas_stubs-2.3.3.260113.tar.gz", hash = "sha256:076e3724bcaa73de78932b012ec64b3010463d377fa63116f4e6850643d93800"}, +] + +[package.dependencies] +numpy = ">=1.23.5" +types-pytz = ">=2022.1.1" + + +[[package]] +name = "pathspec" +version = "1.1.1" +description = "Utility library for gitignore style pattern matching of file paths." +optional = false +python-versions = ">=3.9" +groups = ["dev"] +files = [ + {file = "pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189"}, + {file = "pathspec-1.1.1.tar.gz", hash = "sha256:17db5ecd524104a120e173814c90367a96a98d07c45b2e10c2f3919fff91bf5a"}, +] + +[package.extras] +hyperscan = ["hyperscan (>=0.7)"] +optional = ["typing-extensions (>=4)"] +re2 = ["google-re2 (>=1.1)"] + + +[[package]] +name = "pillow" +version = "12.3.0" +description = "Python Imaging Library (fork)" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "pillow-12.3.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:6c0016e7b354317c4e9e525b937ac8596c38d2d232b419529b9cd7a1cd46e39a"}, + {file = "pillow-12.3.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:bcc33feacfaefce60c12fd500a277533bdc02b10a19f7f6d348763d8140bbba7"}, + {file = "pillow-12.3.0-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5594fc43d548a7ed94949d139aa1341b270f1863f11cfd37f5a6c8b778a6b67f"}, + {file = "pillow-12.3.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f0606c8bf2cdefea14a43530f7657cbbb7ecf1c4222512492ef4a4434a9501ec"}, + {file = "pillow-12.3.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:85f998ea1848bc6757289e739cfbdda3a04adfd58b02fc018ce54d754a5ce468"}, + {file = "pillow-12.3.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:25b9b82bb22e6e2b3cd07b39c68b7b862001226cb3dff7130d1cb914121b39ed"}, + {file = "pillow-12.3.0-cp310-cp310-win32.whl", hash = "sha256:37dc8f7bbb66efe481bb60defacef820c950c24713fb44962ed6aa2a50966de1"}, + {file = "pillow-12.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:300557495eb45ebb8aec96c2da9c4be642fbf7cd937278b4013ba894ea8eb0eb"}, + {file = "pillow-12.3.0-cp310-cp310-win_arm64.whl", hash = "sha256:514435a37670e3e5e08f3945b68718b6ed329bb84367777e16f9f4dfe1e61a0f"}, + {file = "pillow-12.3.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:00808c5e14ef63ac5161091d242999076604ff74b883423a11e5d7bbb38bf756"}, + {file = "pillow-12.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37d6d0a00072fd2948eb22bce7e1475f34569d90c87c59f7a2ec59541b77f7a6"}, + {file = "pillow-12.3.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bcb46e2f9feff8d06323983bd83ed00c201fdcab3d74973e7072a889b3979fcd"}, + {file = "pillow-12.3.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:23d27a3e0307ec2244cc51e7287b919aa68d097504ebe19df4e76a98a3eea5bd"}, + {file = "pillow-12.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4f883547d4b7f0495ebe7056b0cc2aea76094e7a4abc8e933540f3271df27d9c"}, + {file = "pillow-12.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:236ff70b9312fb68943c703aa842ca6a758abfa45ac187a5e7c1452e96ef72b5"}, + {file = "pillow-12.3.0-cp311-cp311-win32.whl", hash = "sha256:10e41f0fbf1eec8cfd234b8fe17a4caac7c9d0db4c204d3c173a8f9f6ef3232b"}, + {file = "pillow-12.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:8e95e1385e4998ae9694eeaa4730ba5457ff61185b3a55e2e7bea0880aef452a"}, + {file = "pillow-12.3.0-cp311-cp311-win_arm64.whl", hash = "sha256:ebaea975e03d3141d9d3a507df75c9b3ec90fa9d2ffd07567b3a978d9d790b26"}, + {file = "pillow-12.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965"}, + {file = "pillow-12.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7"}, + {file = "pillow-12.3.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9"}, + {file = "pillow-12.3.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91"}, + {file = "pillow-12.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c"}, + {file = "pillow-12.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df"}, + {file = "pillow-12.3.0-cp312-cp312-win32.whl", hash = "sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f"}, + {file = "pillow-12.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09"}, + {file = "pillow-12.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510"}, + {file = "pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:21900ce7ba264168cd50defae43cd75d25c833ad4ad6e73ffc5596d12e25ac89"}, + {file = "pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4e8c2a84d977f50b9daed6eeaf3baef67d00d5d74d932288f02cb94518ee3ace"}, + {file = "pillow-12.3.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:ae26d61dfa7a47befdc7572b521024e8745f3d809bd95ca9505a7bba9ef849ec"}, + {file = "pillow-12.3.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66"}, + {file = "pillow-12.3.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35"}, + {file = "pillow-12.3.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f7401aebd7f581d7f83a439d87d474999317ee099218e5ad25d125290990ba65"}, + {file = "pillow-12.3.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0847a763afefb695bc912d7c131e7e0632d4edc1d8698f58ddabec8e46b8b6d3"}, + {file = "pillow-12.3.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:571b9fcb07b97ef3a492028fb3d2dc0993ca23a06138b0315286566d29ef718a"}, + {file = "pillow-12.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:756c768d0c9c2955feb7a56c37ea24aea2e369f8d36a88da270b6a9f19e62b5e"}, + {file = "pillow-12.3.0-cp313-cp313-win32.whl", hash = "sha256:a876864214e136f0eb367788dbd7df045f4806801518e2cfe9e13229cfe06d8f"}, + {file = "pillow-12.3.0-cp313-cp313-win_amd64.whl", hash = "sha256:1cca606cd25738df4ed873d5ad46bbdb3d83b5cbca291f6b4ff13a4df6b0bbe8"}, + {file = "pillow-12.3.0-cp313-cp313-win_arm64.whl", hash = "sha256:b629de27fda84b42cde7edef0d85f13b958b47f6e9bbcbba9b673c562a89bd8b"}, + {file = "pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:9cf95fe4d0f84c82d282745d9bb08ad9f926efa00be4697e767b814ce40d4330"}, + {file = "pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:8728f216dcdb6e6d555cf971cb34076139ad74b31fc2c14da4fafc741c5f6217"}, + {file = "pillow-12.3.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:a45650e8ce7fafffd731db8550230db6b0d306d181a90b67d3e6bca2f1990930"}, + {file = "pillow-12.3.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ba54cfebe86920a559a7c4d6b9050791c20513650a1952ebe3368c7dc70306f8"}, + {file = "pillow-12.3.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e158cb00350dc278f3b91551101aa7d12415a66ebf2c91d8d5ac14e56ddd3ad0"}, + {file = "pillow-12.3.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e9aeb04d6aef139de265b29683e119b638208f88cf73cdd1658aa07221165321"}, + {file = "pillow-12.3.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:251bf95b67017e27b13d82f5b326234ca62d70f9cf4c2b9032de2358a3b12c7b"}, + {file = "pillow-12.3.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fe3cca2e4e8a592be0f269a1ca4835c25199d9f3ce815c8491048f785b0a0198"}, + {file = "pillow-12.3.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:23aceaa007d6172b02c277f0cd359c79492bbb14f7072b4ede9fbcaf20648130"}, + {file = "pillow-12.3.0-cp314-cp314-win32.whl", hash = "sha256:af8d94b0db561cf68b88a267c5c44b49e134f525d0dc2cb7ed413a66bc23559a"}, + {file = "pillow-12.3.0-cp314-cp314-win_amd64.whl", hash = "sha256:fdafc9cce40277e0f7a0feabce0ee50dd2fa1800f3b38015e51296b5e814048d"}, + {file = "pillow-12.3.0-cp314-cp314-win_arm64.whl", hash = "sha256:e91206ee562682b51b98ef4b26a6ef48fd84e15fd4c4bc5ec768eb641d206838"}, + {file = "pillow-12.3.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:164b31cd1a0490ab6efae01aa5df49da7061be0af1b30e035b6e9a1bfe34ee6e"}, + {file = "pillow-12.3.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5afb51d599ea772b8365ae807ae557f18bccfe46ab261fd1c2a9ed700fc6eb17"}, + {file = "pillow-12.3.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3edce1d53195db527e0191f84b71d02022de0540bf43a16ed734ed7537b07385"}, + {file = "pillow-12.3.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bf16ba1b4d0b6b7c8e534936632270cf70eb00dbe09005bc345b2677b726855c"}, + {file = "pillow-12.3.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:24870b09b224f7ae3c39ed07d10e819d06f8720bc551847b1d623832b5b0e28d"}, + {file = "pillow-12.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:30f2aa603c41533cc25c05acd0da21636e84a315768feb631c937177db558931"}, + {file = "pillow-12.3.0-cp314-cp314t-win32.whl", hash = "sha256:4b0a7fe987b14c31ebda6083f74f22b561fd3739bc0ac51e019622e3d72668c7"}, + {file = "pillow-12.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:962864dc93511324d51ddbb5b9f8731bf71675b93ca612a07441896f4688fb8c"}, + {file = "pillow-12.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0740a512dc522224c77d9aa5a8d70d8b7d73fb91f2c21125d8d025d3b8990e45"}, + {file = "pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:0feb2e9d6ad6c9e3c06effe9d00f3f1e618a6643273576b016f591e9315a7139"}, + {file = "pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:9e881fca225083806662a5c43d627d215f258ff43c890f831966c7d7ba9c7402"}, + {file = "pillow-12.3.0-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:4998562bf62a445225f22e07c896bb04b35b1b1f2eb6d760584c9c51d7a5f78c"}, + {file = "pillow-12.3.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:dc624f6bc473dacdf7ef7eb8678d0d08edf15cd94fad6ae5c7d6cc67a4e4902f"}, + {file = "pillow-12.3.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:71d6097b330eea8fd15097780c8e89cb1a8ce7838669f48c5bacd6f663dd4701"}, + {file = "pillow-12.3.0-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:28ce87c5ab450a9dd970b52e5aca5fe63ed432d18a2eaddd1979a00a1ba24ace"}, + {file = "pillow-12.3.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6b02afb9b97f65fbca5f31db6a2a3ba21aa93030225f150fa3f249717e938fb4"}, + {file = "pillow-12.3.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:1182d52bc2d5e5d7d0949503aa7e36d12f42205dc287e4883f407b1988820d39"}, + {file = "pillow-12.3.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e795b7eb908249c4e43c7c99fac7c2c75dab0c43566e37db472a355f63693d71"}, + {file = "pillow-12.3.0-cp315-cp315-win32.whl", hash = "sha256:57b3d78c95ba9059768b10e28b813002261d3f3dfc55cc48b0c988f625175827"}, + {file = "pillow-12.3.0-cp315-cp315-win_amd64.whl", hash = "sha256:fa4ecea169a355be7a3ade2c783e2ed12f0e40d2c5621cda8b3297faf7fbb9f5"}, + {file = "pillow-12.3.0-cp315-cp315-win_arm64.whl", hash = "sha256:877c3f311ff35410f690861c4409e7ccbf0cd2f878e50628a28e5a0bb689e658"}, + {file = "pillow-12.3.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:e9871b1ffbfa9656b60aeee92ed5136a5742696006fa322b29ea3d8da0ecc9cf"}, + {file = "pillow-12.3.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:53aa02d20d10c3d814d536aa4e5ac9b84ca0ff5a88377963b085ad6822f93e64"}, + {file = "pillow-12.3.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:446c34dcc4324b084a53b705127dc15717b22c5e140ae0a3c38349d4efec071e"}, + {file = "pillow-12.3.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cf1845d02ad822a369a49f2bb9345b1614744267682e7a03527dc3bf6eea1777"}, + {file = "pillow-12.3.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:186941b6aef820ad110fb01fb06eb925374dc3a21b17e37ec9a53b250c6fe2d1"}, + {file = "pillow-12.3.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:f13c32a3abd6079a66d9526e18dad9b6d280384d49d7c54040cd57b6424041d9"}, + {file = "pillow-12.3.0-cp315-cp315t-win32.whl", hash = "sha256:1657923d2d45afb66526e5b933e5b3052e6bdea196c90d3abb2424e18c77dae8"}, + {file = "pillow-12.3.0-cp315-cp315t-win_amd64.whl", hash = "sha256:8cd2f7bdda092d99c9fc2fb7391354f306d01443d22785d0cbfafa2e2c8bb418"}, + {file = "pillow-12.3.0-cp315-cp315t-win_arm64.whl", hash = "sha256:06ff022112bc9cbf83b60f8e028d94ad87b60621706487e65f673de61610ab59"}, + {file = "pillow-12.3.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:b3c777e849237620b022f7f297dd67705f9f5cf1685f09f02e46f93e92725468"}, + {file = "pillow-12.3.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:b343699e8308bdc51978310e1c959c584e7869cc8c40780058c87da7781a1e94"}, + {file = "pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fbd139c8447d25dd750ab79ee274cc5e1fe80fc56340ab10b18a195e1b6eca3e"}, + {file = "pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e7e480451b9fa137494bccd3a7d69adbe8ac65a87d97be61e11f1b1050a5bac3"}, + {file = "pillow-12.3.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a"}, + {file = "pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce"}, +] + +[package.extras] +docs = ["furo", "olefile", "sphinx (>=8.2)", "sphinx-autobuild", "sphinx-copybutton", "sphinx-inline-tabs", "sphinxext-opengraph"] +fpx = ["olefile"] +mic = ["olefile"] +test-arrow = ["arro3-compute", "arro3-core", "nanoarrow", "pyarrow"] +tests = ["coverage (>=7.4.2)", "defusedxml", "markdown2", "olefile", "packaging", "pytest", "pytest-cov", "pytest-timeout", "pytest-xdist", "setuptools", "trove-classifiers (>=2024.10.12)"] +xmp = ["defusedxml"] + + +[[package]] +name = "platformdirs" +version = "4.11.10" +description = "A small Python package for determining appropriate platform-specific dirs, e.g. a `user data dir`." +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "platformdirs-4.11.10-py3-none-any.whl", hash = "sha256:973c4c082b964958c71588448488d2b14fb253893dfbdb82325a14c84e540e8f"}, + {file = "platformdirs-4.11.10.tar.gz", hash = "sha256:9cd351c078ccf7dda1fdc5f8ccb9d8f5258984c63990e6df3627dde0b70b51d0"}, +] + + +[[package]] +name = "pluggy" +version = "1.6.0" +description = "plugin and hook calling mechanisms for python" +optional = false +python-versions = ">=3.9" +groups = ["dev"] +files = [ + {file = "pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746"}, + {file = "pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3"}, +] + +[package.extras] +dev = ["pre-commit", "tox"] +testing = ["coverage", "pytest", "pytest-benchmark"] + + +[[package]] +name = "pre-commit" +version = "4.6.2" +description = "A framework for managing and maintaining multi-language pre-commit hooks." +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "pre_commit-4.6.2-py2.py3-none-any.whl", hash = "sha256:e2dde9a75d3bce11bd3831c26d134df00a2803c1d818be6a0383c3dcda25dc4e"}, + {file = "pre_commit-4.6.2.tar.gz", hash = "sha256:8f5d7bfb021ecdbcd9d49d89847082dd24172ccde534390081a679ad046e2441"}, +] + +[package.dependencies] +cfgv = ">=2.0.0" +identify = ">=1.0.0" +nodeenv = ">=0.11.1" +pyyaml = ">=5.1" +virtualenv = ">=20.10.0" + + +[[package]] +name = "py" +version = "1.11.0" +description = "library with cross-python path, ini-parsing, io, code, log facilities" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" +groups = ["dev"] +files = [ + {file = "py-1.11.0-py2.py3-none-any.whl", hash = "sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378"}, + {file = "py-1.11.0.tar.gz", hash = "sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719"}, +] + + +[[package]] +name = "pyarrow" +version = "25.0.1" +description = "Python library for Apache Arrow" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "pyarrow-25.0.1-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:0b1edbb2f385a6a65e9711b62ba86ac54a7816a3f8d17bb3e8a5929d65fb2485"}, + {file = "pyarrow-25.0.1-cp310-cp310-macosx_12_0_x86_64.whl", hash = "sha256:a4dd8bf99a8fac133efc0ed6a92f5fddbe2adba0d0f6dd720e39ba9855cea85c"}, + {file = "pyarrow-25.0.1-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:bddd0c4f7630c2a3ddf6347c1bdaa79d97bcf6bd445f9e60c816b7d77c85a5ae"}, + {file = "pyarrow-25.0.1-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:a4d6d5e9a3d1879a97c08ded0c797579b7965eafd0f0c26c30b45ccc06db939b"}, + {file = "pyarrow-25.0.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:514ddb60285631af068875550c90eddc181db3e8e63a032b1559be189e82f056"}, + {file = "pyarrow-25.0.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:cab40b1edfef0262e0e5251aa2c58d75630f24d06dd7794480243acc001a1d7d"}, + {file = "pyarrow-25.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:60e89d8f13861a1f7f8d950fa54aebb8023b30734d0ac51ffa80beabe2df4bba"}, + {file = "pyarrow-25.0.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:51093dd9e10325fbdb3c10a2ae7c4806e5c822d94e74ae4938b26524a3323fee"}, + {file = "pyarrow-25.0.1-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:eb6203482ff3746a5632303a7279ae0b5a304c46985b49ed1378cb350ea6728d"}, + {file = "pyarrow-25.0.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:880523be3d29efcf83d3998835d206118ccf35e3871dbd2fb60408cf6b007a80"}, + {file = "pyarrow-25.0.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:25f8720bf6387d5dc2ebd2622112de630760419e4b66134405dd24110d15f37e"}, + {file = "pyarrow-25.0.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4facd65742a024a4a366328a1d2292062d72d6e023c1b7dda8d4c37544933a25"}, + {file = "pyarrow-25.0.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:aa0559502e1cd6254d6814614085dd9c5a3dd0419362978a936a3f68a9e5c3df"}, + {file = "pyarrow-25.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:62cd0d785b8aa6675ee355f9fc02252a340f4441257c42674937826fd7594325"}, + {file = "pyarrow-25.0.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:df961f2e7ae9cf496459259d798652c70625f6c080650d6952f8c04053c58ee9"}, + {file = "pyarrow-25.0.1-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:cc4aa407fde9fc660be3939e49ea31f50f3e9fec17c0ec63159f7711edd3efc9"}, + {file = "pyarrow-25.0.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:4340f0ba6c1d2e13f21658de1d7c662ca2545018568d0030a1e9afca159d87e3"}, + {file = "pyarrow-25.0.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:5389cdf79447ed1515c9e31620e6e1e2302249564d603f2ad727d4f6d313e4c3"}, + {file = "pyarrow-25.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d51592cb7561e87877c506113e7adbf1342ab579e6c21f0ef44b8ba41cb74c80"}, + {file = "pyarrow-25.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6109c94d8b9f3b17a041daca16cacb2f651ad8f1ef70a4232c2c0f37a23da2a8"}, + {file = "pyarrow-25.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:8858d7bfc22e3f51529aeaa4077225029724623e4595dc9eff8c793935c34140"}, + {file = "pyarrow-25.0.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:c7c534ec03c358a76ea3e505e74c1b6aef290af90c444dfd092dbfe23e755b85"}, + {file = "pyarrow-25.0.1-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:dda9470024204d7bbf2042b47c6e8a0e47a3eeb8e34405882dfaea6577e0c153"}, + {file = "pyarrow-25.0.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:44a9120ce5bd81936b8ab9a88076e3fd47c2c6838e0e43630fed83626aca81d9"}, + {file = "pyarrow-25.0.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:0befcf816e45a1af33ac775a9970b749e4868a230c7372f0ae5e932bee27039f"}, + {file = "pyarrow-25.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3f89685964f46e4216103c75483aac0c0692a5f72212d7ca835adba5ede56ce3"}, + {file = "pyarrow-25.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6943e2fe7954d29d84de45d29d34c8dc36ce96570e67d89aa9976e650a4a9138"}, + {file = "pyarrow-25.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:31e49a7888fcdf3a835da33ae777f6bb9a866334e5a789282fc26dcf426f7f15"}, + {file = "pyarrow-25.0.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:bf0b672390cdcb640d7288f96b826d71ff4e9abb254a86c89890baf51a29cee6"}, + {file = "pyarrow-25.0.1-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:38a9a4b4b9613380e200641891495a56c3d5a98a092db4a870af9975e220471d"}, + {file = "pyarrow-25.0.1-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:0b726ad7e7b669be982b0c71c07fe4b037d654354130da79a7902a669e93a66b"}, + {file = "pyarrow-25.0.1-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:9171748cdf796972d85a4b60157c279913e242992e350c90c7450182a9838b2a"}, + {file = "pyarrow-25.0.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:b7a296aac7a71fa0886c08e155ddb6c636a50013f801f6178daafa0f9e726188"}, + {file = "pyarrow-25.0.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0fe7c8b6c03969b49c8c66182e4a18e3819ab92d07cfab5d8370c531b9369ef0"}, + {file = "pyarrow-25.0.1-cp314-cp314-win_amd64.whl", hash = "sha256:f729cfdbd36fd99d543b67a914d2de044c84ebe45be8b34902b299b608c15c8f"}, + {file = "pyarrow-25.0.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:59a2de54c0cbd954da861eee4d1d330f8e909c45b53455baef696380f2c55033"}, + {file = "pyarrow-25.0.1-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:35935cd5de130aa5cf4dea052a63e6bf2e17006c35c3a468194242b9b2bf5956"}, + {file = "pyarrow-25.0.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:f3831aaa25c67a99f99dc8b05873cb9d64560390372e2aa197ce9dd4a3f06a44"}, + {file = "pyarrow-25.0.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:6a1fdfc6659b6b19022f2e50627fb5cf7156a66c46bf4299379955cbe742382a"}, + {file = "pyarrow-25.0.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:169d3429d5be7c752125890620f75a60776d38b0035eddae939651640822332e"}, + {file = "pyarrow-25.0.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:119297a6dc197e45d9c6d4415f7814a67ffa36c180d26f68c154c58067ae782d"}, + {file = "pyarrow-25.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:4288f27577352d608ca08553b0865e4a9b3aa14820c5d95b53337218d609835b"}, + {file = "pyarrow-25.0.1.tar.gz", hash = "sha256:9150a83248bfed9813ea3c3af74c3856c1984d444aa28e58bf7733b9750ddf6a"}, +] + + +[[package]] +name = "pygments" +version = "2.21.0" +description = "Pygments is a syntax highlighting package written in Python." +optional = false +python-versions = ">=3.9" +groups = ["docs"] +files = [ + {file = "pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9"}, + {file = "pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c"}, +] + +[package.extras] +windows-terminal = ["colorama (>=0.4.6)"] + + +[[package]] +name = "pyparsing" +version = "3.3.2" +description = "pyparsing - Classes and methods to define and execute parsing grammars" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "pyparsing-3.3.2-py3-none-any.whl", hash = "sha256:850ba148bd908d7e2411587e247a1e4f0327839c40e2e5e6d05a007ecc69911d"}, + {file = "pyparsing-3.3.2.tar.gz", hash = "sha256:c777f4d763f140633dcb6d8a3eda953bf7a214dc4eff598413c070bcdc117cbc"}, +] + +[package.extras] +diagrams = ["jinja2", "railroad-diagrams"] + + +[[package]] +name = "pytest" +version = "7.4.4" +description = "pytest: simple powerful testing with Python" +optional = false +python-versions = ">=3.7" +groups = ["dev"] +files = [ + {file = "pytest-7.4.4-py3-none-any.whl", hash = "sha256:b090cdf5ed60bf4c45261be03239c2c1c22df034fbffe691abe93cd80cea01d8"}, + {file = "pytest-7.4.4.tar.gz", hash = "sha256:2cf0005922c6ace4a3e2ec8b4080eb0d9753fdc93107415332f50ce9e7994280"}, +] + +[package.dependencies] +colorama = {version = "*", markers = "sys_platform == \"win32\""} +exceptiongroup = {version = ">=1.0.0rc8", markers = "python_version < \"3.11\""} +iniconfig = "*" +packaging = "*" +pluggy = ">=0.12,<2.0" +tomli = {version = ">=1.0.0", markers = "python_version < \"3.11\""} + +[package.extras] +testing = ["argcomplete", "attrs (>=19.2.0)", "hypothesis (>=3.56)", "mock", "nose", "pygments (>=2.7.2)", "requests", "setuptools", "xmlschema"] + + +[[package]] +name = "pytest-cov" +version = "3.0.0" +description = "Pytest plugin for measuring coverage." +optional = false +python-versions = ">=3.6" +groups = ["dev"] +files = [ + {file = "pytest-cov-3.0.0.tar.gz", hash = "sha256:e7f0f5b1617d2210a2cabc266dfe2f4c75a8d32fb89eafb7ad9d06f6d076d470"}, + {file = "pytest_cov-3.0.0-py3-none-any.whl", hash = "sha256:578d5d15ac4a25e5f961c938b85a05b09fdaae9deef3bb6de9a6e766622ca7a6"}, +] + +[package.dependencies] +coverage = {version = ">=5.2.1", extras = ["toml"]} +pytest = ">=4.6" + +[package.extras] +testing = ["fields", "hunter", "process-tests", "pytest-xdist", "six", "virtualenv"] + + +[[package]] +name = "pytest-forked" +version = "1.7.5" +description = "run tests in isolated forked subprocesses" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "pytest_forked-1.7.5-py3-none-any.whl", hash = "sha256:e9f3475fa0a42927f5e370d721de9c2d785616a06a4c506712d6cb8055e37c84"}, + {file = "pytest_forked-1.7.5.tar.gz", hash = "sha256:00f2bee51612f29b8e6b81eed2c3b2975e824c2693394f5bdaf7a1369078ba5f"}, +] + +[package.dependencies] +pytest = ">=7" + + +[[package]] +name = "pytest-xdist" +version = "2.5.0" +description = "pytest xdist plugin for distributed testing and loop-on-failing modes" +optional = false +python-versions = ">=3.6" +groups = ["dev"] +files = [ + {file = "pytest-xdist-2.5.0.tar.gz", hash = "sha256:4580deca3ff04ddb2ac53eba39d76cb5dd5edeac050cb6fbc768b0dd712b4edf"}, + {file = "pytest_xdist-2.5.0-py3-none-any.whl", hash = "sha256:6fe5c74fec98906deb8f2d2b616b5c782022744978e7bd4695d39c8f42d0ce65"}, +] + +[package.dependencies] +execnet = ">=1.1" +pytest = ">=6.2.0" +pytest-forked = "*" + +[package.extras] +psutil = ["psutil (>=3.0)"] +setproctitle = ["setproctitle"] +testing = ["filelock"] + + +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +description = "Extensions to the standard Python datetime module" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" +groups = ["main"] +files = [ + {file = "python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3"}, + {file = "python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427"}, +] + +[package.dependencies] +six = ">=1.5" + + +[[package]] +name = "python-discovery" +version = "1.6.1" +description = "Python interpreter discovery" +optional = false +python-versions = ">=3.8" +groups = ["dev"] +files = [ + {file = "python_discovery-1.6.1-py3-none-any.whl", hash = "sha256:d43fcdef879fe795352bd13ccf8d185ba5a9f86f36cfcd00529f596e737442b3"}, + {file = "python_discovery-1.6.1.tar.gz", hash = "sha256:cf87d3627dfb4412437fdd5b13eae402607722998d21567993aedbc59b23c15e"}, +] + +[package.dependencies] +filelock = ">=3.15.4" + + +[[package]] +name = "pytokens" +version = "0.4.1" +description = "A Fast, spec compliant Python 3.14+ tokenizer that runs on older Pythons." +optional = false +python-versions = ">=3.8" +groups = ["dev"] +files = [ + {file = "pytokens-0.4.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:2a44ed93ea23415c54f3face3b65ef2b844d96aeb3455b8a69b3df6beab6acc5"}, + {file = "pytokens-0.4.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:add8bf86b71a5d9fb5b89f023a80b791e04fba57960aa790cc6125f7f1d39dfe"}, + {file = "pytokens-0.4.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:670d286910b531c7b7e3c0b453fd8156f250adb140146d234a82219459b9640c"}, + {file = "pytokens-0.4.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:4e691d7f5186bd2842c14813f79f8884bb03f5995f0575272009982c5ac6c0f7"}, + {file = "pytokens-0.4.1-cp310-cp310-win_amd64.whl", hash = "sha256:27b83ad28825978742beef057bfe406ad6ed524b2d28c252c5de7b4a6dd48fa2"}, + {file = "pytokens-0.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d70e77c55ae8380c91c0c18dea05951482e263982911fc7410b1ffd1dadd3440"}, + {file = "pytokens-0.4.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a58d057208cb9075c144950d789511220b07636dd2e4708d5645d24de666bdc"}, + {file = "pytokens-0.4.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b49750419d300e2b5a3813cf229d4e5a4c728dae470bcc89867a9ad6f25a722d"}, + {file = "pytokens-0.4.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d9907d61f15bf7261d7e775bd5d7ee4d2930e04424bab1972591918497623a16"}, + {file = "pytokens-0.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:ee44d0f85b803321710f9239f335aafe16553b39106384cef8e6de40cb4ef2f6"}, + {file = "pytokens-0.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:140709331e846b728475786df8aeb27d24f48cbcf7bcd449f8de75cae7a45083"}, + {file = "pytokens-0.4.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6d6c4268598f762bc8e91f5dbf2ab2f61f7b95bdc07953b602db879b3c8c18e1"}, + {file = "pytokens-0.4.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:24afde1f53d95348b5a0eb19488661147285ca4dd7ed752bbc3e1c6242a304d1"}, + {file = "pytokens-0.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5ad948d085ed6c16413eb5fec6b3e02fa00dc29a2534f088d3302c47eb59adf9"}, + {file = "pytokens-0.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:3f901fe783e06e48e8cbdc82d631fca8f118333798193e026a50ce1b3757ea68"}, + {file = "pytokens-0.4.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:8bdb9d0ce90cbf99c525e75a2fa415144fd570a1ba987380190e8b786bc6ef9b"}, + {file = "pytokens-0.4.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5502408cab1cb18e128570f8d598981c68a50d0cbd7c61312a90507cd3a1276f"}, + {file = "pytokens-0.4.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:29d1d8fb1030af4d231789959f21821ab6325e463f0503a61d204343c9b355d1"}, + {file = "pytokens-0.4.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:970b08dd6b86058b6dc07efe9e98414f5102974716232d10f32ff39701e841c4"}, + {file = "pytokens-0.4.1-cp313-cp313-win_amd64.whl", hash = "sha256:9bd7d7f544d362576be74f9d5901a22f317efc20046efe2034dced238cbbfe78"}, + {file = "pytokens-0.4.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:4a14d5f5fc78ce85e426aa159489e2d5961acf0e47575e08f35584009178e321"}, + {file = "pytokens-0.4.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:97f50fd18543be72da51dd505e2ed20d2228c74e0464e4262e4899797803d7fa"}, + {file = "pytokens-0.4.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:dc74c035f9bfca0255c1af77ddd2d6ae8419012805453e4b0e7513e17904545d"}, + {file = "pytokens-0.4.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f66a6bbe741bd431f6d741e617e0f39ec7257ca1f89089593479347cc4d13324"}, + {file = "pytokens-0.4.1-cp314-cp314-win_amd64.whl", hash = "sha256:b35d7e5ad269804f6697727702da3c517bb8a5228afa450ab0fa787732055fc9"}, + {file = "pytokens-0.4.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:8fcb9ba3709ff77e77f1c7022ff11d13553f3c30299a9fe246a166903e9091eb"}, + {file = "pytokens-0.4.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:79fc6b8699564e1f9b521582c35435f1bd32dd06822322ec44afdeba666d8cb3"}, + {file = "pytokens-0.4.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d31b97b3de0f61571a124a00ffe9a81fb9939146c122c11060725bd5aea79975"}, + {file = "pytokens-0.4.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:967cf6e3fd4adf7de8fc73cd3043754ae79c36475c1c11d514fc72cf5490094a"}, + {file = "pytokens-0.4.1-cp314-cp314t-win_amd64.whl", hash = "sha256:584c80c24b078eec1e227079d56dc22ff755e0ba8654d8383b2c549107528918"}, + {file = "pytokens-0.4.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:da5baeaf7116dced9c6bb76dc31ba04a2dc3695f3d9f74741d7910122b456edc"}, + {file = "pytokens-0.4.1-cp38-cp38-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:11edda0942da80ff58c4408407616a310adecae1ddd22eef8c692fe266fa5009"}, + {file = "pytokens-0.4.1-cp38-cp38-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0fc71786e629cef478cbf29d7ea1923299181d0699dbe7c3c0f4a583811d9fc1"}, + {file = "pytokens-0.4.1-cp38-cp38-musllinux_1_2_x86_64.whl", hash = "sha256:dcafc12c30dbaf1e2af0490978352e0c4041a7cde31f4f81435c2a5e8b9cabb6"}, + {file = "pytokens-0.4.1-cp38-cp38-win_amd64.whl", hash = "sha256:42f144f3aafa5d92bad964d471a581651e28b24434d184871bd02e3a0d956037"}, + {file = "pytokens-0.4.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:34bcc734bd2f2d5fe3b34e7b3c0116bfb2397f2d9666139988e7a3eb5f7400e3"}, + {file = "pytokens-0.4.1-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:941d4343bf27b605e9213b26bfa1c4bf197c9c599a9627eb7305b0defcfe40c1"}, + {file = "pytokens-0.4.1-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3ad72b851e781478366288743198101e5eb34a414f1d5627cdd585ca3b25f1db"}, + {file = "pytokens-0.4.1-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:682fa37ff4d8e95f7df6fe6fe6a431e8ed8e788023c6bcc0f0880a12eab80ad1"}, + {file = "pytokens-0.4.1-cp39-cp39-win_amd64.whl", hash = "sha256:30f51edd9bb7f85c748979384165601d028b84f7bd13fe14d3e065304093916a"}, + {file = "pytokens-0.4.1-py3-none-any.whl", hash = "sha256:26cef14744a8385f35d0e095dc8b3a7583f6c953c2e3d269c7f82484bf5ad2de"}, + {file = "pytokens-0.4.1.tar.gz", hash = "sha256:292052fe80923aae2260c073f822ceba21f3872ced9a68bb7953b348e561179a"}, +] + +[package.extras] +dev = ["black", "build", "mypy", "pytest", "pytest-cov", "setuptools", "tox", "twine", "wheel"] + + +[[package]] +name = "pytz" +version = "2026.3.post1" +description = "World timezone definitions, modern and historical" +optional = false +python-versions = "*" +groups = ["main"] +files = [ + {file = "pytz-2026.3.post1-py2.py3-none-any.whl", hash = "sha256:dd95840dd199baea12d9cc096a1d452caa6596a1c1e4b5f3dbd1541855d5e815"}, + {file = "pytz-2026.3.post1.tar.gz", hash = "sha256:2211d3fcf9a797d3405cac96ac7f61d80e6a644f72a3309607282fe8a2010c5d"}, +] + + +[[package]] +name = "pyyaml" +version = "6.0.3" +description = "YAML parser and emitter for Python" +optional = false +python-versions = ">=3.8" +groups = ["dev"] +files = [ + {file = "PyYAML-6.0.3-cp38-cp38-macosx_10_13_x86_64.whl", hash = "sha256:c2514fceb77bc5e7a2f7adfaa1feb2fb311607c9cb518dbc378688ec73d8292f"}, + {file = "PyYAML-6.0.3-cp38-cp38-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9c57bb8c96f6d1808c030b1687b9b5fb476abaa47f0db9c0101f5e9f394e97f4"}, + {file = "PyYAML-6.0.3-cp38-cp38-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:efd7b85f94a6f21e4932043973a7ba2613b059c4a000551892ac9f1d11f5baf3"}, + {file = "PyYAML-6.0.3-cp38-cp38-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22ba7cfcad58ef3ecddc7ed1db3409af68d023b7f940da23c6c2a1890976eda6"}, + {file = "PyYAML-6.0.3-cp38-cp38-musllinux_1_2_x86_64.whl", hash = "sha256:6344df0d5755a2c9a276d4473ae6b90647e216ab4757f8426893b5dd2ac3f369"}, + {file = "PyYAML-6.0.3-cp38-cp38-win32.whl", hash = "sha256:3ff07ec89bae51176c0549bc4c63aa6202991da2d9a6129d7aef7f1407d3f295"}, + {file = "PyYAML-6.0.3-cp38-cp38-win_amd64.whl", hash = "sha256:5cf4e27da7e3fbed4d6c3d8e797387aaad68102272f8f9752883bc32d61cb87b"}, + {file = "pyyaml-6.0.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:214ed4befebe12df36bcc8bc2b64b396ca31be9304b8f59e25c11cf94a4c033b"}, + {file = "pyyaml-6.0.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:02ea2dfa234451bbb8772601d7b8e426c2bfa197136796224e50e35a78777956"}, + {file = "pyyaml-6.0.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b30236e45cf30d2b8e7b3e85881719e98507abed1011bf463a8fa23e9c3e98a8"}, + {file = "pyyaml-6.0.3-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:66291b10affd76d76f54fad28e22e51719ef9ba22b29e1d7d03d6777a9174198"}, + {file = "pyyaml-6.0.3-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9c7708761fccb9397fe64bbc0395abcae8c4bf7b0eac081e12b809bf47700d0b"}, + {file = "pyyaml-6.0.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:418cf3f2111bc80e0933b2cd8cd04f286338bb88bdc7bc8e6dd775ebde60b5e0"}, + {file = "pyyaml-6.0.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5e0b74767e5f8c593e8c9b5912019159ed0533c70051e9cce3e8b6aa699fcd69"}, + {file = "pyyaml-6.0.3-cp310-cp310-win32.whl", hash = "sha256:28c8d926f98f432f88adc23edf2e6d4921ac26fb084b028c733d01868d19007e"}, + {file = "pyyaml-6.0.3-cp310-cp310-win_amd64.whl", hash = "sha256:bdb2c67c6c1390b63c6ff89f210c8fd09d9a1217a465701eac7316313c915e4c"}, + {file = "pyyaml-6.0.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e"}, + {file = "pyyaml-6.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824"}, + {file = "pyyaml-6.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c"}, + {file = "pyyaml-6.0.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00"}, + {file = "pyyaml-6.0.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d"}, + {file = "pyyaml-6.0.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a"}, + {file = "pyyaml-6.0.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4"}, + {file = "pyyaml-6.0.3-cp311-cp311-win32.whl", hash = "sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b"}, + {file = "pyyaml-6.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf"}, + {file = "pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196"}, + {file = "pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0"}, + {file = "pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28"}, + {file = "pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c"}, + {file = "pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc"}, + {file = "pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e"}, + {file = "pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea"}, + {file = "pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5"}, + {file = "pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b"}, + {file = "pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd"}, + {file = "pyyaml-6.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8"}, + {file = "pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1"}, + {file = "pyyaml-6.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c"}, + {file = "pyyaml-6.0.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5"}, + {file = "pyyaml-6.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6"}, + {file = "pyyaml-6.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6"}, + {file = "pyyaml-6.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be"}, + {file = "pyyaml-6.0.3-cp313-cp313-win32.whl", hash = "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26"}, + {file = "pyyaml-6.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c"}, + {file = "pyyaml-6.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb"}, + {file = "pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac"}, + {file = "pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310"}, + {file = "pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7"}, + {file = "pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788"}, + {file = "pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5"}, + {file = "pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764"}, + {file = "pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35"}, + {file = "pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac"}, + {file = "pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3"}, + {file = "pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3"}, + {file = "pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba"}, + {file = "pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c"}, + {file = "pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702"}, + {file = "pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c"}, + {file = "pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065"}, + {file = "pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65"}, + {file = "pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9"}, + {file = "pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b"}, + {file = "pyyaml-6.0.3-cp39-cp39-macosx_10_13_x86_64.whl", hash = "sha256:b865addae83924361678b652338317d1bd7e79b1f4596f96b96c77a5a34b34da"}, + {file = "pyyaml-6.0.3-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:c3355370a2c156cffb25e876646f149d5d68f5e0a3ce86a5084dd0b64a994917"}, + {file = "pyyaml-6.0.3-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3c5677e12444c15717b902a5798264fa7909e41153cdf9ef7ad571b704a63dd9"}, + {file = "pyyaml-6.0.3-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5ed875a24292240029e4483f9d4a4b8a1ae08843b9c54f43fcc11e404532a8a5"}, + {file = "pyyaml-6.0.3-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0150219816b6a1fa26fb4699fb7daa9caf09eb1999f3b70fb6e786805e80375a"}, + {file = "pyyaml-6.0.3-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:fa160448684b4e94d80416c0fa4aac48967a969efe22931448d853ada8baf926"}, + {file = "pyyaml-6.0.3-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:27c0abcb4a5dac13684a37f76e701e054692a9b2d3064b70f5e4eb54810553d7"}, + {file = "pyyaml-6.0.3-cp39-cp39-win32.whl", hash = "sha256:1ebe39cb5fc479422b83de611d14e2c0d3bb2a18bbcb01f229ab3cfbd8fee7a0"}, + {file = "pyyaml-6.0.3-cp39-cp39-win_amd64.whl", hash = "sha256:2e71d11abed7344e42a8849600193d15b6def118602c4c176f748e4583246007"}, + {file = "pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f"}, +] + + +[[package]] +name = "requests" +version = "2.34.2" +description = "Python HTTP for Humans." +optional = false +python-versions = ">=3.10" +groups = ["docs"] +files = [ + {file = "requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0"}, + {file = "requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed"}, +] + +[package.dependencies] +certifi = ">=2023.5.7" +charset_normalizer = ">=2,<4" +idna = ">=2.5,<4" +urllib3 = ">=1.26,<3" + +[package.extras] +socks = ["PySocks (>=1.5.6,!=1.5.7)"] +use-chardet-on-py3 = ["chardet (>=3.0.2,<8)"] + + +[[package]] +name = "ruff" +version = "0.7.4" +description = "An extremely fast Python linter and code formatter, written in Rust." +optional = false +python-versions = ">=3.7" +groups = ["dev"] +files = [ + {file = "ruff-0.7.4-py3-none-linux_armv6l.whl", hash = "sha256:a4919925e7684a3f18e18243cd6bea7cfb8e968a6eaa8437971f681b7ec51478"}, + {file = "ruff-0.7.4-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:cfb365c135b830778dda8c04fb7d4280ed0b984e1aec27f574445231e20d6c63"}, + {file = "ruff-0.7.4-py3-none-macosx_11_0_arm64.whl", hash = "sha256:63a569b36bc66fbadec5beaa539dd81e0527cb258b94e29e0531ce41bacc1f20"}, + {file = "ruff-0.7.4-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0d06218747d361d06fd2fdac734e7fa92df36df93035db3dc2ad7aa9852cb109"}, + {file = "ruff-0.7.4-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e0cea28d0944f74ebc33e9f934238f15c758841f9f5edd180b5315c203293452"}, + {file = "ruff-0.7.4-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:80094ecd4793c68b2571b128f91754d60f692d64bc0d7272ec9197fdd09bf9ea"}, + {file = "ruff-0.7.4-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:997512325c6620d1c4c2b15db49ef59543ef9cd0f4aa8065ec2ae5103cedc7e7"}, + {file = "ruff-0.7.4-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:00b4cf3a6b5fad6d1a66e7574d78956bbd09abfd6c8a997798f01f5da3d46a05"}, + {file = "ruff-0.7.4-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7dbdc7d8274e1422722933d1edddfdc65b4336abf0b16dfcb9dedd6e6a517d06"}, + {file = "ruff-0.7.4-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0e92dfb5f00eaedb1501b2f906ccabfd67b2355bdf117fea9719fc99ac2145bc"}, + {file = "ruff-0.7.4-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:3bd726099f277d735dc38900b6a8d6cf070f80828877941983a57bca1cd92172"}, + {file = "ruff-0.7.4-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:2e32829c429dd081ee5ba39aef436603e5b22335c3d3fff013cd585806a6486a"}, + {file = "ruff-0.7.4-py3-none-musllinux_1_2_i686.whl", hash = "sha256:662a63b4971807623f6f90c1fb664613f67cc182dc4d991471c23c541fee62dd"}, + {file = "ruff-0.7.4-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:876f5e09eaae3eb76814c1d3b68879891d6fde4824c015d48e7a7da4cf066a3a"}, + {file = "ruff-0.7.4-py3-none-win32.whl", hash = "sha256:75c53f54904be42dd52a548728a5b572344b50d9b2873d13a3f8c5e3b91f5cac"}, + {file = "ruff-0.7.4-py3-none-win_amd64.whl", hash = "sha256:745775c7b39f914238ed1f1b0bebed0b9155a17cd8bc0b08d3c87e4703b990d6"}, + {file = "ruff-0.7.4-py3-none-win_arm64.whl", hash = "sha256:11bff065102c3ae9d3ea4dc9ecdfe5a5171349cdd0787c1fc64761212fc9cf1f"}, + {file = "ruff-0.7.4.tar.gz", hash = "sha256:cd12e35031f5af6b9b93715d8c4f40360070b2041f81273d0527683d5708fce2"}, +] + + +[[package]] +name = "scikit-learn" +version = "1.7.2" +description = "A set of python modules for machine learning and data mining" +optional = false +python-versions = ">=3.10" +groups = ["main"] +markers = "python_version == \"3.10\"" +files = [ + {file = "scikit_learn-1.7.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:6b33579c10a3081d076ab403df4a4190da4f4432d443521674637677dc91e61f"}, + {file = "scikit_learn-1.7.2-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:36749fb62b3d961b1ce4fedf08fa57a1986cd409eff2d783bca5d4b9b5fce51c"}, + {file = "scikit_learn-1.7.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7a58814265dfc52b3295b1900cfb5701589d30a8bb026c7540f1e9d3499d5ec8"}, + {file = "scikit_learn-1.7.2-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a847fea807e278f821a0406ca01e387f97653e284ecbd9750e3ee7c90347f18"}, + {file = "scikit_learn-1.7.2-cp310-cp310-win_amd64.whl", hash = "sha256:ca250e6836d10e6f402436d6463d6c0e4d8e0234cfb6a9a47835bd392b852ce5"}, + {file = "scikit_learn-1.7.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c7509693451651cd7361d30ce4e86a1347493554f172b1c72a39300fa2aea79e"}, + {file = "scikit_learn-1.7.2-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:0486c8f827c2e7b64837c731c8feff72c0bd2b998067a8a9cbc10643c31f0fe1"}, + {file = "scikit_learn-1.7.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:89877e19a80c7b11a2891a27c21c4894fb18e2c2e077815bcade10d34287b20d"}, + {file = "scikit_learn-1.7.2-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8da8bf89d4d79aaec192d2bda62f9b56ae4e5b4ef93b6a56b5de4977e375c1f1"}, + {file = "scikit_learn-1.7.2-cp311-cp311-win_amd64.whl", hash = "sha256:9b7ed8d58725030568523e937c43e56bc01cadb478fc43c042a9aca1dacb3ba1"}, + {file = "scikit_learn-1.7.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:8d91a97fa2b706943822398ab943cde71858a50245e31bc71dba62aab1d60a96"}, + {file = "scikit_learn-1.7.2-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:acbc0f5fd2edd3432a22c69bed78e837c70cf896cd7993d71d51ba6708507476"}, + {file = "scikit_learn-1.7.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e5bf3d930aee75a65478df91ac1225ff89cd28e9ac7bd1196853a9229b6adb0b"}, + {file = "scikit_learn-1.7.2-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b4d6e9deed1a47aca9fe2f267ab8e8fe82ee20b4526b2c0cd9e135cea10feb44"}, + {file = "scikit_learn-1.7.2-cp312-cp312-win_amd64.whl", hash = "sha256:6088aa475f0785e01bcf8529f55280a3d7d298679f50c0bb70a2364a82d0b290"}, + {file = "scikit_learn-1.7.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0b7dacaa05e5d76759fb071558a8b5130f4845166d88654a0f9bdf3eb57851b7"}, + {file = "scikit_learn-1.7.2-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:abebbd61ad9e1deed54cca45caea8ad5f79e1b93173dece40bb8e0c658dbe6fe"}, + {file = "scikit_learn-1.7.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:502c18e39849c0ea1a5d681af1dbcf15f6cce601aebb657aabbfe84133c1907f"}, + {file = "scikit_learn-1.7.2-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a4c328a71785382fe3fe676a9ecf2c86189249beff90bf85e22bdb7efaf9ae0"}, + {file = "scikit_learn-1.7.2-cp313-cp313-win_amd64.whl", hash = "sha256:63a9afd6f7b229aad94618c01c252ce9e6fa97918c5ca19c9a17a087d819440c"}, + {file = "scikit_learn-1.7.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:9acb6c5e867447b4e1390930e3944a005e2cb115922e693c08a323421a6966e8"}, + {file = "scikit_learn-1.7.2-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:2a41e2a0ef45063e654152ec9d8bcfc39f7afce35b08902bfe290c2498a67a6a"}, + {file = "scikit_learn-1.7.2-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:98335fb98509b73385b3ab2bd0639b1f610541d3988ee675c670371d6a87aa7c"}, + {file = "scikit_learn-1.7.2-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:191e5550980d45449126e23ed1d5e9e24b2c68329ee1f691a3987476e115e09c"}, + {file = "scikit_learn-1.7.2-cp313-cp313t-win_amd64.whl", hash = "sha256:57dc4deb1d3762c75d685507fbd0bc17160144b2f2ba4ccea5dc285ab0d0e973"}, + {file = "scikit_learn-1.7.2-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:fa8f63940e29c82d1e67a45d5297bdebbcb585f5a5a50c4914cc2e852ab77f33"}, + {file = "scikit_learn-1.7.2-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:f95dc55b7902b91331fa4e5845dd5bde0580c9cd9612b1b2791b7e80c3d32615"}, + {file = "scikit_learn-1.7.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9656e4a53e54578ad10a434dc1f993330568cfee176dff07112b8785fb413106"}, + {file = "scikit_learn-1.7.2-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96dc05a854add0e50d3f47a1ef21a10a595016da5b007c7d9cd9d0bffd1fcc61"}, + {file = "scikit_learn-1.7.2-cp314-cp314-win_amd64.whl", hash = "sha256:bb24510ed3f9f61476181e4db51ce801e2ba37541def12dc9333b946fc7a9cf8"}, + {file = "scikit_learn-1.7.2.tar.gz", hash = "sha256:20e9e49ecd130598f1ca38a1d85090e1a600147b9c02fa6f15d69cb53d968fda"}, +] + +[package.dependencies] +joblib = ">=1.2.0" +numpy = ">=1.22.0" +scipy = ">=1.8.0" +threadpoolctl = ">=3.1.0" + +[package.extras] +benchmark = ["matplotlib (>=3.5.0)", "memory_profiler (>=0.57.0)", "pandas (>=1.4.0)"] +build = ["cython (>=3.0.10)", "meson-python (>=0.17.1)", "numpy (>=1.22.0)", "scipy (>=1.8.0)"] +docs = ["Pillow (>=8.4.0)", "matplotlib (>=3.5.0)", "memory_profiler (>=0.57.0)", "numpydoc (>=1.2.0)", "pandas (>=1.4.0)", "plotly (>=5.14.0)", "polars (>=0.20.30)", "pooch (>=1.6.0)", "pydata-sphinx-theme (>=0.15.3)", "scikit-image (>=0.19.0)", "seaborn (>=0.9.0)", "sphinx (>=7.3.7)", "sphinx-copybutton (>=0.5.2)", "sphinx-design (>=0.5.0)", "sphinx-design (>=0.6.0)", "sphinx-gallery (>=0.17.1)", "sphinx-prompt (>=1.4.0)", "sphinx-remove-toctrees (>=1.0.0.post1)", "sphinxcontrib-sass (>=0.3.4)", "sphinxext-opengraph (>=0.9.1)", "towncrier (>=24.8.0)"] +examples = ["matplotlib (>=3.5.0)", "pandas (>=1.4.0)", "plotly (>=5.14.0)", "pooch (>=1.6.0)", "scikit-image (>=0.19.0)", "seaborn (>=0.9.0)"] +install = ["joblib (>=1.2.0)", "numpy (>=1.22.0)", "scipy (>=1.8.0)", "threadpoolctl (>=3.1.0)"] +maintenance = ["conda-lock (==3.0.1)"] +tests = ["matplotlib (>=3.5.0)", "mypy (>=1.15)", "numpydoc (>=1.2.0)", "pandas (>=1.4.0)", "polars (>=0.20.30)", "pooch (>=1.6.0)", "pyamg (>=4.2.1)", "pyarrow (>=12.0.0)", "pytest (>=7.1.2)", "pytest-cov (>=2.9.0)", "ruff (>=0.11.7)", "scikit-image (>=0.19.0)"] + + +[[package]] +name = "scikit-learn" +version = "1.9.1" +description = "A set of python modules for machine learning and data mining" +optional = false +python-versions = ">=3.11" +groups = ["main"] +markers = "python_version >= \"3.11\"" +files = [ + {file = "scikit_learn-1.9.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:326c188f92084bf58664229f4578eeab6176313b37cd5dfc85abd92b94130c58"}, + {file = "scikit_learn-1.9.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:b48b2b5b41d9c5fbafef5f37b042f61110df3318ad2a45baf57287ea5b9ba5a2"}, + {file = "scikit_learn-1.9.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4298fcc01b3d8fa9768d36894e99cce0747b3b2dd73bfd80779e393769d0afab"}, + {file = "scikit_learn-1.9.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:52a0703bbc07ad27f560fa63fa68e4c54dd735bfbbf65b4dd3c225dc7547b6df"}, + {file = "scikit_learn-1.9.1-cp311-cp311-win_amd64.whl", hash = "sha256:220fa18152852a5ce29c49e1eaba9d44ec44631cd2e5cf65f5a40eafa5ab3412"}, + {file = "scikit_learn-1.9.1-cp311-cp311-win_arm64.whl", hash = "sha256:8218cb8938d3031e0d23842838425490c229ecf3e99f666776e09d12ed902352"}, + {file = "scikit_learn-1.9.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:0c0f8b5d09b44101cea2767f300680bada1ea27f976fe4b48b83950a4f55a49a"}, + {file = "scikit_learn-1.9.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:8c14ce41d561f7749f990b41d6703fe02c4669fbc485e598e069e0a1967b488e"}, + {file = "scikit_learn-1.9.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e4c20a6c017d820faa7ac8c783e3d0c6a9a2e297bf9f55332ca17cdf7fd4d04d"}, + {file = "scikit_learn-1.9.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e5d7b18a5b9dca241a74695f3275fa4c895a9dadc72b3d8df5fa9d1083c9b83e"}, + {file = "scikit_learn-1.9.1-cp312-cp312-win_amd64.whl", hash = "sha256:4b59abb30618121cc46b45972d6bf53a7128b4df4cd346c6ca6f4d5f9031e49c"}, + {file = "scikit_learn-1.9.1-cp312-cp312-win_arm64.whl", hash = "sha256:d5945a2908be62350e2978344e62b56c1552c2ca4f844ebf6277c94944d647dd"}, + {file = "scikit_learn-1.9.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2c2b312fd8c02951a364fa120ea08c1cec10d863466bf1701b013152d7537835"}, + {file = "scikit_learn-1.9.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:61cd968ab831a76d0ecbaf0347ab2270268716da28f94fd022497e3d6f205f13"}, + {file = "scikit_learn-1.9.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5990f9c69e431bfaddcde1a6d7c5355243e026bc9b9e560c13893b90dab53fb4"}, + {file = "scikit_learn-1.9.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:55e79d6e9b0923f1a978179822bd43d7f5543f45e970a00fe861f43486380aba"}, + {file = "scikit_learn-1.9.1-cp313-cp313-win_amd64.whl", hash = "sha256:2070f271e5375dc42c6bb93b461ab1c0aa5841d4009267e0cfd95a39dca94a43"}, + {file = "scikit_learn-1.9.1-cp313-cp313-win_arm64.whl", hash = "sha256:613f0a783ca05aa844a4e1ac42d48425058f2c52be73f40f8cd98b7cd111acd6"}, + {file = "scikit_learn-1.9.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d5d117952769b563067656784e03c75a2d8235a7a05cf7fffa78a311e75aac08"}, + {file = "scikit_learn-1.9.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:8893bc6331f60f18d4ac75e12ed356e2dcf6a564bf767918b5b7ca54c8c8be49"}, + {file = "scikit_learn-1.9.1-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b5492cf2df5226691c32611de8734bcf42148c6547ae53c7f4e6b847793addc0"}, + {file = "scikit_learn-1.9.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:993d332ff80e62efae9e39603b7e872297c418d780f01a01855269a3489c950f"}, + {file = "scikit_learn-1.9.1-cp314-cp314-win_amd64.whl", hash = "sha256:ca9051447455dae341d4d591eece7deb2d8e3d1020298fc87a81fc51e4da8f53"}, + {file = "scikit_learn-1.9.1-cp314-cp314-win_arm64.whl", hash = "sha256:90de6573f733a9fb79476ff1371af52a397d41c8b35f9146e20923db010d67b6"}, + {file = "scikit_learn-1.9.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7b5cad1624de8b75e5b9ccb7b0ce1ff1d01306340a3efc56d5529c5ba92392eb"}, + {file = "scikit_learn-1.9.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:d137ce8a6142029fb5c35bd82f470c40cd9e760e5e2f7694b362c497c4ab3fa2"}, + {file = "scikit_learn-1.9.1-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:66f852f7325b5070bc28329005aca76055a2def78faac039548ae889aeaa45a6"}, + {file = "scikit_learn-1.9.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:748bcb0a4cc04aec470652c9e5ec68450948e867387e7dfade647107ade68d25"}, + {file = "scikit_learn-1.9.1-cp314-cp314t-win_amd64.whl", hash = "sha256:38cd925e893e5539be704d5edc64dbe081aacdab6b89d8c2977c1f6a7a453ce5"}, + {file = "scikit_learn-1.9.1-cp314-cp314t-win_arm64.whl", hash = "sha256:b01e5b01735d38474127ca3f49319b592506225a87793b27559816b5c75cea39"}, + {file = "scikit_learn-1.9.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:8dec64f31a6e0ec826aca6c1b39a51e16d946e400d4c0904316f3ca72ccfb825"}, + {file = "scikit_learn-1.9.1-cp315-cp315-macosx_12_0_arm64.whl", hash = "sha256:e1b468241f4a7a9a7a0d6479ad3cc47681cc151a4046c530f2777c3d68f08942"}, + {file = "scikit_learn-1.9.1-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8ca869d0080a5723cde2d5a8b54a2da1ff7e68735a9e9adb3da1243183a0fa01"}, + {file = "scikit_learn-1.9.1-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6754b7cabfc3df0b1f7b38f7a344f559bbae9d82f0ac5e3d48cccbd19fdcefdf"}, + {file = "scikit_learn-1.9.1-cp315-cp315-win_amd64.whl", hash = "sha256:52cfdb1fed3a34362dbc0bd96f2e761a66fd5724d6901629f5a558f1f3bd9849"}, + {file = "scikit_learn-1.9.1-cp315-cp315-win_arm64.whl", hash = "sha256:ae6571a4828c6f5019bcd2b4125e5b18c0af3dbc9c99726c891f45f41335ec8e"}, + {file = "scikit_learn-1.9.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:48fefd8eb42bd4eec3e2d348149368ccd6d71987e20c30706a56a24eb86a6e73"}, + {file = "scikit_learn-1.9.1-cp315-cp315t-macosx_12_0_arm64.whl", hash = "sha256:09f4d73049cd63575157f6b1060e06a8c83a4bd3488dbfaeedf35ccba7aad712"}, + {file = "scikit_learn-1.9.1-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b3da53831534214322d9cb240fa6f390b36cf69eba727a6d4bd3238677630d70"}, + {file = "scikit_learn-1.9.1-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:caae15634feceafa2612566b109a3082d3293167fac388eedaf77bff66b51983"}, + {file = "scikit_learn-1.9.1-cp315-cp315t-win_amd64.whl", hash = "sha256:ffbcbbbb44202fbe9bc64bced25a145759adb9ef010b3d37a8064958ac13df2a"}, + {file = "scikit_learn-1.9.1-cp315-cp315t-win_arm64.whl", hash = "sha256:800dd22dd87fe97dcea484c24e85dd93cf1734d86bd74e668ad18f7967f4d1b5"}, + {file = "scikit_learn-1.9.1.tar.gz", hash = "sha256:629cada3e33e2b9bf376cdc7614a47a4140b8aedc1d836579e359736fbd82977"}, +] + +[package.dependencies] +joblib = ">=1.4.0" +narwhals = ">=2.0.1" +numpy = ">=1.24.1" +scipy = ">=1.10.0" +threadpoolctl = ">=3.5.0" + + +[[package]] +name = "scipy" +version = "1.15.3" +description = "Fundamental algorithms for scientific computing in Python" +optional = false +python-versions = ">=3.10" +groups = ["main"] +markers = "python_version == \"3.10\"" +files = [ + {file = "scipy-1.15.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:a345928c86d535060c9c2b25e71e87c39ab2f22fc96e9636bd74d1dbf9de448c"}, + {file = "scipy-1.15.3-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:ad3432cb0f9ed87477a8d97f03b763fd1d57709f1bbde3c9369b1dff5503b253"}, + {file = "scipy-1.15.3-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:aef683a9ae6eb00728a542b796f52a5477b78252edede72b8327a886ab63293f"}, + {file = "scipy-1.15.3-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:1c832e1bd78dea67d5c16f786681b28dd695a8cb1fb90af2e27580d3d0967e92"}, + {file = "scipy-1.15.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:263961f658ce2165bbd7b99fa5135195c3a12d9bef045345016b8b50c315cb82"}, + {file = "scipy-1.15.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9e2abc762b0811e09a0d3258abee2d98e0c703eee49464ce0069590846f31d40"}, + {file = "scipy-1.15.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:ed7284b21a7a0c8f1b6e5977ac05396c0d008b89e05498c8b7e8f4a1423bba0e"}, + {file = "scipy-1.15.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5380741e53df2c566f4d234b100a484b420af85deb39ea35a1cc1be84ff53a5c"}, + {file = "scipy-1.15.3-cp310-cp310-win_amd64.whl", hash = "sha256:9d61e97b186a57350f6d6fd72640f9e99d5a4a2b8fbf4b9ee9a841eab327dc13"}, + {file = "scipy-1.15.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:993439ce220d25e3696d1b23b233dd010169b62f6456488567e830654ee37a6b"}, + {file = "scipy-1.15.3-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:34716e281f181a02341ddeaad584205bd2fd3c242063bd3423d61ac259ca7eba"}, + {file = "scipy-1.15.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3b0334816afb8b91dab859281b1b9786934392aa3d527cd847e41bb6f45bee65"}, + {file = "scipy-1.15.3-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:6db907c7368e3092e24919b5e31c76998b0ce1684d51a90943cb0ed1b4ffd6c1"}, + {file = "scipy-1.15.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:721d6b4ef5dc82ca8968c25b111e307083d7ca9091bc38163fb89243e85e3889"}, + {file = "scipy-1.15.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:39cb9c62e471b1bb3750066ecc3a3f3052b37751c7c3dfd0fd7e48900ed52982"}, + {file = "scipy-1.15.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:795c46999bae845966368a3c013e0e00947932d68e235702b5c3f6ea799aa8c9"}, + {file = "scipy-1.15.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:18aaacb735ab38b38db42cb01f6b92a2d0d4b6aabefeb07f02849e47f8fb3594"}, + {file = "scipy-1.15.3-cp311-cp311-win_amd64.whl", hash = "sha256:ae48a786a28412d744c62fd7816a4118ef97e5be0bee968ce8f0a2fba7acf3bb"}, + {file = "scipy-1.15.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6ac6310fdbfb7aa6612408bd2f07295bcbd3fda00d2d702178434751fe48e019"}, + {file = "scipy-1.15.3-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:185cd3d6d05ca4b44a8f1595af87f9c372bb6acf9c808e99aa3e9aa03bd98cf6"}, + {file = "scipy-1.15.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:05dc6abcd105e1a29f95eada46d4a3f251743cfd7d3ae8ddb4088047f24ea477"}, + {file = "scipy-1.15.3-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:06efcba926324df1696931a57a176c80848ccd67ce6ad020c810736bfd58eb1c"}, + {file = "scipy-1.15.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c05045d8b9bfd807ee1b9f38761993297b10b245f012b11b13b91ba8945f7e45"}, + {file = "scipy-1.15.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:271e3713e645149ea5ea3e97b57fdab61ce61333f97cfae392c28ba786f9bb49"}, + {file = "scipy-1.15.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6cfd56fc1a8e53f6e89ba3a7a7251f7396412d655bca2aa5611c8ec9a6784a1e"}, + {file = "scipy-1.15.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0ff17c0bb1cb32952c09217d8d1eed9b53d1463e5f1dd6052c7857f83127d539"}, + {file = "scipy-1.15.3-cp312-cp312-win_amd64.whl", hash = "sha256:52092bc0472cfd17df49ff17e70624345efece4e1a12b23783a1ac59a1b728ed"}, + {file = "scipy-1.15.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2c620736bcc334782e24d173c0fdbb7590a0a436d2fdf39310a8902505008759"}, + {file = "scipy-1.15.3-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:7e11270a000969409d37ed399585ee530b9ef6aa99d50c019de4cb01e8e54e62"}, + {file = "scipy-1.15.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:8c9ed3ba2c8a2ce098163a9bdb26f891746d02136995df25227a20e71c396ebb"}, + {file = "scipy-1.15.3-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:0bdd905264c0c9cfa74a4772cdb2070171790381a5c4d312c973382fc6eaf730"}, + {file = "scipy-1.15.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79167bba085c31f38603e11a267d862957cbb3ce018d8b38f79ac043bc92d825"}, + {file = "scipy-1.15.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c9deabd6d547aee2c9a81dee6cc96c6d7e9a9b1953f74850c179f91fdc729cb7"}, + {file = "scipy-1.15.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:dde4fc32993071ac0c7dd2d82569e544f0bdaff66269cb475e0f369adad13f11"}, + {file = "scipy-1.15.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f77f853d584e72e874d87357ad70f44b437331507d1c311457bed8ed2b956126"}, + {file = "scipy-1.15.3-cp313-cp313-win_amd64.whl", hash = "sha256:b90ab29d0c37ec9bf55424c064312930ca5f4bde15ee8619ee44e69319aab163"}, + {file = "scipy-1.15.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:3ac07623267feb3ae308487c260ac684b32ea35fd81e12845039952f558047b8"}, + {file = "scipy-1.15.3-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:6487aa99c2a3d509a5227d9a5e889ff05830a06b2ce08ec30df6d79db5fcd5c5"}, + {file = "scipy-1.15.3-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:50f9e62461c95d933d5c5ef4a1f2ebf9a2b4e83b0db374cb3f1de104d935922e"}, + {file = "scipy-1.15.3-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:14ed70039d182f411ffc74789a16df3835e05dc469b898233a245cdfd7f162cb"}, + {file = "scipy-1.15.3-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a769105537aa07a69468a0eefcd121be52006db61cdd8cac8a0e68980bbb723"}, + {file = "scipy-1.15.3-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9db984639887e3dffb3928d118145ffe40eff2fa40cb241a306ec57c219ebbbb"}, + {file = "scipy-1.15.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:40e54d5c7e7ebf1aa596c374c49fa3135f04648a0caabcb66c52884b943f02b4"}, + {file = "scipy-1.15.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:5e721fed53187e71d0ccf382b6bf977644c533e506c4d33c3fb24de89f5c3ed5"}, + {file = "scipy-1.15.3-cp313-cp313t-win_amd64.whl", hash = "sha256:76ad1fb5f8752eabf0fa02e4cc0336b4e8f021e2d5f061ed37d6d264db35e3ca"}, + {file = "scipy-1.15.3.tar.gz", hash = "sha256:eae3cf522bc7df64b42cad3925c876e1b0b6c35c1337c93e12c0f366f55b0eaf"}, +] + +[package.dependencies] +numpy = ">=1.23.5,<2.5" + +[package.extras] +dev = ["cython-lint (>=0.12.2)", "doit (>=0.36.0)", "mypy (==1.10.0)", "pycodestyle", "pydevtool", "rich-click", "ruff (>=0.0.292)", "types-psutil", "typing_extensions"] +doc = ["intersphinx_registry", "jupyterlite-pyodide-kernel", "jupyterlite-sphinx (>=0.19.1)", "jupytext", "matplotlib (>=3.5)", "myst-nb", "numpydoc", "pooch", "pydata-sphinx-theme (>=0.15.2)", "sphinx (>=5.0.0,<8.0.0)", "sphinx-copybutton", "sphinx-design (>=0.4.0)"] +test = ["Cython", "array-api-strict (>=2.0,<2.1.1)", "asv", "gmpy2", "hypothesis (>=6.30)", "meson", "mpmath", "ninja ; sys_platform != \"emscripten\"", "pooch", "pytest", "pytest-cov", "pytest-timeout", "pytest-xdist", "scikit-umfpack", "threadpoolctl"] + + +[[package]] +name = "scipy" +version = "1.17.1" +description = "Fundamental algorithms for scientific computing in Python" +optional = false +python-versions = ">=3.11" +groups = ["main"] +markers = "python_version == \"3.11\"" +files = [ + {file = "scipy-1.17.1-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:1f95b894f13729334fb990162e911c9e5dc1ab390c58aa6cbecb389c5b5e28ec"}, + {file = "scipy-1.17.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:e18f12c6b0bc5a592ed23d3f7b891f68fd7f8241d69b7883769eb5d5dfb52696"}, + {file = "scipy-1.17.1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:a3472cfbca0a54177d0faa68f697d8ba4c80bbdc19908c3465556d9f7efce9ee"}, + {file = "scipy-1.17.1-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:766e0dc5a616d026a3a1cffa379af959671729083882f50307e18175797b3dfd"}, + {file = "scipy-1.17.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:744b2bf3640d907b79f3fd7874efe432d1cf171ee721243e350f55234b4cec4c"}, + {file = "scipy-1.17.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:43af8d1f3bea642559019edfe64e9b11192a8978efbd1539d7bc2aaa23d92de4"}, + {file = "scipy-1.17.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:cd96a1898c0a47be4520327e01f874acfd61fb48a9420f8aa9f6483412ffa444"}, + {file = "scipy-1.17.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4eb6c25dd62ee8d5edf68a8e1c171dd71c292fdae95d8aeb3dd7d7de4c364082"}, + {file = "scipy-1.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:d30e57c72013c2a4fe441c2fcb8e77b14e152ad48b5464858e07e2ad9fbfceff"}, + {file = "scipy-1.17.1-cp311-cp311-win_arm64.whl", hash = "sha256:9ecb4efb1cd6e8c4afea0daa91a87fbddbce1b99d2895d151596716c0b2e859d"}, + {file = "scipy-1.17.1-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:35c3a56d2ef83efc372eaec584314bd0ef2e2f0d2adb21c55e6ad5b344c0dcb8"}, + {file = "scipy-1.17.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:fcb310ddb270a06114bb64bbe53c94926b943f5b7f0842194d585c65eb4edd76"}, + {file = "scipy-1.17.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:cc90d2e9c7e5c7f1a482c9875007c095c3194b1cfedca3c2f3291cdc2bc7c086"}, + {file = "scipy-1.17.1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:c80be5ede8f3f8eded4eff73cc99a25c388ce98e555b17d31da05287015ffa5b"}, + {file = "scipy-1.17.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e19ebea31758fac5893a2ac360fedd00116cbb7628e650842a6691ba7ca28a21"}, + {file = "scipy-1.17.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:02ae3b274fde71c5e92ac4d54bc06c42d80e399fec704383dcd99b301df37458"}, + {file = "scipy-1.17.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8a604bae87c6195d8b1045eddece0514d041604b14f2727bbc2b3020172045eb"}, + {file = "scipy-1.17.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f590cd684941912d10becc07325a3eeb77886fe981415660d9265c4c418d0bea"}, + {file = "scipy-1.17.1-cp312-cp312-win_amd64.whl", hash = "sha256:41b71f4a3a4cab9d366cd9065b288efc4d4f3c0b37a91a8e0947fb5bd7f31d87"}, + {file = "scipy-1.17.1-cp312-cp312-win_arm64.whl", hash = "sha256:f4115102802df98b2b0db3cce5cb9b92572633a1197c77b7553e5203f284a5b3"}, + {file = "scipy-1.17.1-cp313-cp313-macosx_10_14_x86_64.whl", hash = "sha256:5e3c5c011904115f88a39308379c17f91546f77c1667cea98739fe0fccea804c"}, + {file = "scipy-1.17.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:6fac755ca3d2c3edcb22f479fceaa241704111414831ddd3bc6056e18516892f"}, + {file = "scipy-1.17.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:7ff200bf9d24f2e4d5dc6ee8c3ac64d739d3a89e2326ba68aaf6c4a2b838fd7d"}, + {file = "scipy-1.17.1-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:4b400bdc6f79fa02a4d86640310dde87a21fba0c979efff5248908c6f15fad1b"}, + {file = "scipy-1.17.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2b64ca7d4aee0102a97f3ba22124052b4bd2152522355073580bf4845e2550b6"}, + {file = "scipy-1.17.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:581b2264fc0aa555f3f435a5944da7504ea3a065d7029ad60e7c3d1ae09c5464"}, + {file = "scipy-1.17.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:beeda3d4ae615106d7094f7e7cef6218392e4465cc95d25f900bebabfded0950"}, + {file = "scipy-1.17.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6609bc224e9568f65064cfa72edc0f24ee6655b47575954ec6339534b2798369"}, + {file = "scipy-1.17.1-cp313-cp313-win_amd64.whl", hash = "sha256:37425bc9175607b0268f493d79a292c39f9d001a357bebb6b88fdfaff13f6448"}, + {file = "scipy-1.17.1-cp313-cp313-win_arm64.whl", hash = "sha256:5cf36e801231b6a2059bf354720274b7558746f3b1a4efb43fcf557ccd484a87"}, + {file = "scipy-1.17.1-cp313-cp313t-macosx_10_14_x86_64.whl", hash = "sha256:d59c30000a16d8edc7e64152e30220bfbd724c9bbb08368c054e24c651314f0a"}, + {file = "scipy-1.17.1-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:010f4333c96c9bb1a4516269e33cb5917b08ef2166d5556ca2fd9f082a9e6ea0"}, + {file = "scipy-1.17.1-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:2ceb2d3e01c5f1d83c4189737a42d9cb2fc38a6eeed225e7515eef71ad301dce"}, + {file = "scipy-1.17.1-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:844e165636711ef41f80b4103ed234181646b98a53c8f05da12ca5ca289134f6"}, + {file = "scipy-1.17.1-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:158dd96d2207e21c966063e1635b1063cd7787b627b6f07305315dd73d9c679e"}, + {file = "scipy-1.17.1-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:74cbb80d93260fe2ffa334efa24cb8f2f0f622a9b9febf8b483c0b865bfb3475"}, + {file = "scipy-1.17.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:dbc12c9f3d185f5c737d801da555fb74b3dcfa1a50b66a1a93e09190f41fab50"}, + {file = "scipy-1.17.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:94055a11dfebe37c656e70317e1996dc197e1a15bbcc351bcdd4610e128fe1ca"}, + {file = "scipy-1.17.1-cp313-cp313t-win_amd64.whl", hash = "sha256:e30bdeaa5deed6bc27b4cc490823cd0347d7dae09119b8803ae576ea0ce52e4c"}, + {file = "scipy-1.17.1-cp313-cp313t-win_arm64.whl", hash = "sha256:a720477885a9d2411f94a93d16f9d89bad0f28ca23c3f8daa521e2dcc3f44d49"}, + {file = "scipy-1.17.1-cp314-cp314-macosx_10_14_x86_64.whl", hash = "sha256:a48a72c77a310327f6a3a920092fa2b8fd03d7deaa60f093038f22d98e096717"}, + {file = "scipy-1.17.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:45abad819184f07240d8a696117a7aacd39787af9e0b719d00285549ed19a1e9"}, + {file = "scipy-1.17.1-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:3fd1fcdab3ea951b610dc4cef356d416d5802991e7e32b5254828d342f7b7e0b"}, + {file = "scipy-1.17.1-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:7bdf2da170b67fdf10bca777614b1c7d96ae3ca5794fd9587dce41eb2966e866"}, + {file = "scipy-1.17.1-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:adb2642e060a6549c343603a3851ba76ef0b74cc8c079a9a58121c7ec9fe2350"}, + {file = "scipy-1.17.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:eee2cfda04c00a857206a4330f0c5e3e56535494e30ca445eb19ec624ae75118"}, + {file = "scipy-1.17.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:d2650c1fb97e184d12d8ba010493ee7b322864f7d3d00d3f9bb97d9c21de4068"}, + {file = "scipy-1.17.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:08b900519463543aa604a06bec02461558a6e1cef8fdbb8098f77a48a83c8118"}, + {file = "scipy-1.17.1-cp314-cp314-win_amd64.whl", hash = "sha256:3877ac408e14da24a6196de0ddcace62092bfc12a83823e92e49e40747e52c19"}, + {file = "scipy-1.17.1-cp314-cp314-win_arm64.whl", hash = "sha256:f8885db0bc2bffa59d5c1b72fad7a6a92d3e80e7257f967dd81abb553a90d293"}, + {file = "scipy-1.17.1-cp314-cp314t-macosx_10_14_x86_64.whl", hash = "sha256:1cc682cea2ae55524432f3cdff9e9a3be743d52a7443d0cba9017c23c87ae2f6"}, + {file = "scipy-1.17.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:2040ad4d1795a0ae89bfc7e8429677f365d45aa9fd5e4587cf1ea737f927b4a1"}, + {file = "scipy-1.17.1-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:131f5aaea57602008f9822e2115029b55d4b5f7c070287699fe45c661d051e39"}, + {file = "scipy-1.17.1-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:9cdc1a2fcfd5c52cfb3045feb399f7b3ce822abdde3a193a6b9a60b3cb5854ca"}, + {file = "scipy-1.17.1-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6e3dcd57ab780c741fde8dc68619de988b966db759a3c3152e8e9142c26295ad"}, + {file = "scipy-1.17.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a9956e4d4f4a301ebf6cde39850333a6b6110799d470dbbb1e25326ac447f52a"}, + {file = "scipy-1.17.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:a4328d245944d09fd639771de275701ccadf5f781ba0ff092ad141e017eccda4"}, + {file = "scipy-1.17.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:a77cbd07b940d326d39a1d1b37817e2ee4d79cb30e7338f3d0cddffae70fcaa2"}, + {file = "scipy-1.17.1-cp314-cp314t-win_amd64.whl", hash = "sha256:eb092099205ef62cd1782b006658db09e2fed75bffcae7cc0d44052d8aa0f484"}, + {file = "scipy-1.17.1-cp314-cp314t-win_arm64.whl", hash = "sha256:200e1050faffacc162be6a486a984a0497866ec54149a01270adc8a59b7c7d21"}, + {file = "scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0"}, +] + +[package.dependencies] +numpy = ">=1.26.4,<2.7" + +[package.extras] +dev = ["click (<8.3.0)", "cython-lint (>=0.12.2)", "mypy (==1.10.0)", "pycodestyle", "ruff (>=0.12.0)", "spin", "types-psutil", "typing_extensions"] +doc = ["intersphinx_registry", "jupyterlite-pyodide-kernel", "jupyterlite-sphinx (>=0.19.1)", "jupytext", "linkify-it-py", "matplotlib (>=3.5)", "myst-nb (>=1.2.0)", "numpydoc", "pooch", "pydata-sphinx-theme (>=0.15.2)", "sphinx (>=5.0.0,<8.2.0)", "sphinx-copybutton", "sphinx-design (>=0.4.0)", "tabulate"] +test = ["Cython", "array-api-strict (>=2.3.1)", "asv", "gmpy2", "hypothesis (>=6.30)", "meson", "mpmath", "ninja ; sys_platform != \"emscripten\"", "pooch", "pytest (>=8.0.0)", "pytest-cov", "pytest-timeout", "pytest-xdist", "scikit-umfpack", "threadpoolctl"] + + +[[package]] +name = "scipy" +version = "1.18.1" +description = "Fundamental algorithms for scientific computing in Python" +optional = false +python-versions = ">=3.12" +groups = ["main"] +markers = "python_version >= \"3.12\"" +files = [ + {file = "scipy-1.18.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:457fd7a2a8edeb044ab6ffbc0aa03ff6cd18491356e5e0c834d76ce621b916d1"}, + {file = "scipy-1.18.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:e708533e8b2ae2497d65346538a7dcc92814410b25b81432eac66de0f2af8265"}, + {file = "scipy-1.18.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:7bbf207c4453ce1ad2e00b17313852b33310b83090c2311bdaf97f93c0380d12"}, + {file = "scipy-1.18.1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:78c0665edead396b1abb4897c41a5c1d9bf090c8a637a4c20a61678e0a264e66"}, + {file = "scipy-1.18.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3c085faa2cfa879c5141df483f836f4d691045a078224a670fa570fa01612d89"}, + {file = "scipy-1.18.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f55fa87b6c612ecd6b058f167c53231b1d14e412efe361d3d6e38b3631c73218"}, + {file = "scipy-1.18.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c35d74ce0e193ff740c2f2be2ac913ddc232fe6c1ff40b26cfecb9c670c63314"}, + {file = "scipy-1.18.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d2924a03db38dc2e848bca2fe9f077dafb891480b91a00a0963a8cf86dfc31c1"}, + {file = "scipy-1.18.1-cp312-cp312-win_amd64.whl", hash = "sha256:5e4d44984abc0020154ea81b247adeddcc3ac5527b975ff798bd1ba0adc513c2"}, + {file = "scipy-1.18.1-cp312-cp312-win_arm64.whl", hash = "sha256:d65d448389b8436493abcf629cc94ad0cf32aecaf06e1acca1de53cc795f2f12"}, + {file = "scipy-1.18.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:3ab3523da44749156e1f68b464dc56af11ae4cbc5c739a49d05f32b982eca9f3"}, + {file = "scipy-1.18.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:e6fb6a55cc0ba97b59a1f288fb86dc6fce8bdfc0fffcbfd015e3a954bf2a2d93"}, + {file = "scipy-1.18.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:ea324d9dd34c38bfb9bec8ca4d1b407db97dbb74029f566b8e322b1b6fe56fe6"}, + {file = "scipy-1.18.1-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:75b00eb8fb802090aa903f4ea1c7f5a584779f967361e68b7e98e531cc2d7174"}, + {file = "scipy-1.18.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d416b16cccfd70fbf62400e84d0bb2f4e6af519a45557f1692c749b37f14b315"}, + {file = "scipy-1.18.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fdaf5ea890a6183d0565f51a61799d67081bd5b1cf03c5f4b3fd3732108625c9"}, + {file = "scipy-1.18.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:c825cef2f49e46753726a7181a8e199804a912b29519ada542c6ebc654951899"}, + {file = "scipy-1.18.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e3b417bf8c2c7c16e8f58ad91db17783ec911ac16e7b50eb6eab6e809b4f5b07"}, + {file = "scipy-1.18.1-cp313-cp313-win_amd64.whl", hash = "sha256:559ed65f60c1af5a03f3912605a1b5114f522c7c32fb23c3376ae8f03219fe28"}, + {file = "scipy-1.18.1-cp313-cp313-win_arm64.whl", hash = "sha256:cd479fc04dd9401e3b4f49e76518768ef99c4f517a98c284eb091fd725719adf"}, + {file = "scipy-1.18.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:83de5453a7799afc9048b4616bd085cef126e36412f0ea2f6370c36a2a3a51e7"}, + {file = "scipy-1.18.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:9554bcc6d715ee87a633a3cc8e7703c6628b100dd29cb8a2efc4c0533c7ff729"}, + {file = "scipy-1.18.1-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:011413b7426b75012840e35649e00fe0a2c3bae89fed433876e3a99251572efc"}, + {file = "scipy-1.18.1-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:88f0e784020649f88ea48c9f5ddfa403bf9205820667c0914740b392035afb82"}, + {file = "scipy-1.18.1-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2d3ab0e8c69a17dd3559eab8cbb88f258e285c94d572c2719033f90f83290c89"}, + {file = "scipy-1.18.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ac0333bdf38309aa3dcbe7e3fa7ea29e7a2c37c6ea306a757b700ded8e4596ad"}, + {file = "scipy-1.18.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:911de823097db8b63f034299d12662db93344e6ffa0b881cbb57748974b70168"}, + {file = "scipy-1.18.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:95298364e251be3e60249facbeeca03631d3bb7584f85879516ec55ac717b81f"}, + {file = "scipy-1.18.1-cp314-cp314-win_amd64.whl", hash = "sha256:78a0d7c918e74a232394117160e7e3db503377572a45bcef8826e4ab8a35feba"}, + {file = "scipy-1.18.1-cp314-cp314-win_arm64.whl", hash = "sha256:cbf38d043c1aa4ab306e1ada6ab6eddacc3322a20b7af1b30bc93254b366fe09"}, + {file = "scipy-1.18.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:0fcb3c93519f27bb4f0c4b0f7802cdcaca7fcf93267b75edda2e9f4e8a55cbd7"}, + {file = "scipy-1.18.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:ddef79fb382df40104a19bb7151b3b23e57c1778fcf857c71ceecd9bd264513f"}, + {file = "scipy-1.18.1-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:0e82073ecc7acc6436fac4b31674109c7e1d3e596789767eda01258a8c9e8123"}, + {file = "scipy-1.18.1-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:8bcf3c1ba5d6456e2effd30fcbd3459b044d683fcdac79a2e6830f0bdf7de487"}, + {file = "scipy-1.18.1-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cfbf154f2ba187f2ed6cce2639efff7d105f1140573642c0161615b6d91d6a87"}, + {file = "scipy-1.18.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a1d33a7836f7ddc1993427966a0823468ec41bcbdb1a9f9942d1d7e57f803ba3"}, + {file = "scipy-1.18.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7f4b8bc363b6d65ee2152bec57568e3c52639bb34c46057b09857a307ed5e21d"}, + {file = "scipy-1.18.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:11c423f1049c5755ad4409af52a9ada1cff96fe9b50795d4af3619f292901239"}, + {file = "scipy-1.18.1-cp314-cp314t-win_amd64.whl", hash = "sha256:c24acac1e18912761c4700239bbc1fd32f615af690f1584d49b35859be51324d"}, + {file = "scipy-1.18.1-cp314-cp314t-win_arm64.whl", hash = "sha256:9f2897bf7737392ad0d5213ea7b6add72a4edf5679b3153106aeb88b6507b3b9"}, + {file = "scipy-1.18.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:eb0dfcf4e28a99c12c999744a2ff67c9b06200e20401c7c88186e33552a46331"}, + {file = "scipy-1.18.1-cp315-cp315-macosx_12_0_arm64.whl", hash = "sha256:30f464bee641fa8e282577c7dce027308403213c6ca8270bba73285c91024bc5"}, + {file = "scipy-1.18.1-cp315-cp315-macosx_14_0_arm64.whl", hash = "sha256:1bca3b943fc2567ea49cd02c99abde49da4d5178ec46f624bd8255cda8755beb"}, + {file = "scipy-1.18.1-cp315-cp315-macosx_14_0_x86_64.whl", hash = "sha256:c9d18a33309122074ea483dd92dd444189166b8b2ec429fe9ed5ac73c7a0aa23"}, + {file = "scipy-1.18.1-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:82f201b4c878551d48558337aab270d3c6cca5507b8737c8d8a608d234cccde0"}, + {file = "scipy-1.18.1-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0ac49ea97594532dd44b7136094d35f5440fa06e6d9c6384a74c01764df388c5"}, + {file = "scipy-1.18.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:ceb30a00ce7c92d459819443d29ca486d882b83fb6738bdcbb2a1cce94ac5daa"}, + {file = "scipy-1.18.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:f29633129f9fa7e88a3f0fca835de2d030bfc9643f7799e1a0c46cee24d38fc7"}, + {file = "scipy-1.18.1-cp315-cp315-win_amd64.whl", hash = "sha256:92c14f5bdbfb6216315ce33e78080474082de8b3830122ba97809bfbe65f75c0"}, + {file = "scipy-1.18.1-cp315-cp315-win_arm64.whl", hash = "sha256:e402cf31eb68f453dbb2d36fc6d722b33f24a55d68b2ae1d92fa6305ca71c298"}, + {file = "scipy-1.18.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:2a0b02f9fc46f8520330c23d45e6560db7e3a0d927232139427637f98943e11d"}, + {file = "scipy-1.18.1-cp315-cp315t-macosx_12_0_arm64.whl", hash = "sha256:1d73131e358976663dd969e1fb4ed1404b815cd977eaaedc3b3a133ba2d81c35"}, + {file = "scipy-1.18.1-cp315-cp315t-macosx_14_0_arm64.whl", hash = "sha256:bff0b729edd992766136b34e39cc76bc2fad905aa58897ee72a9cd000a6d8443"}, + {file = "scipy-1.18.1-cp315-cp315t-macosx_14_0_x86_64.whl", hash = "sha256:10ac20c69d880f77f375db44c22e3e6a644f9fefa291d4cd2fb9790a89fc99fd"}, + {file = "scipy-1.18.1-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:33a834464fdabc0f26a45508df31b3cc5d028e04dbf6c5ed398541418e0a12fe"}, + {file = "scipy-1.18.1-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:49023963c193dacee096301452f223ee24d86ec5807f8df93c0f7221d119e305"}, + {file = "scipy-1.18.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:d84a09d0dad90ba6525d8ac1c2334b33e64bf3ccfe9e841f02feb867a22681e4"}, + {file = "scipy-1.18.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:179ce34a8d0fe273d8883ba59e17e052247d08973dfcb743ca52bb1cce2d60b0"}, + {file = "scipy-1.18.1-cp315-cp315t-win_amd64.whl", hash = "sha256:5632e3ae3d09197c446310cd5187de63e28448ce22f0f67b2b93d97503c0c230"}, + {file = "scipy-1.18.1-cp315-cp315t-win_arm64.whl", hash = "sha256:eda632a7981f69730d6281f451db9c1c370993a2c0d7ddb43e2a809a2862b83a"}, + {file = "scipy-1.18.1.tar.gz", hash = "sha256:52c4b7422442aba924d03ad4019852b08a92e64ea187b933135687bfe2747307"}, +] + +[package.dependencies] +numpy = ">=2.0.0,<2.8" + +[package.extras] +dev = ["click (<8.3.0)", "cython-lint (>=0.12.2)", "mypy (==1.19.1)", "pycodestyle", "pyrefly (==0.63.0)", "ruff (>=0.12.0)", "spin", "types-psutil", "typing_extensions"] +doc = ["intersphinx_registry", "jupyterlite-pyodide-kernel", "jupyterlite-sphinx (>=0.19.1)", "jupytext", "linkify-it-py", "matplotlib (>=3.5)", "myst-nb (>=1.2.0)", "numpydoc", "pooch", "pydata-sphinx-theme (>=0.15.2)", "sphinx (>=5.0.0,<8.2.0)", "sphinx-copybutton", "sphinx-design (>=0.4.0)", "tabulate"] +test = ["Cython", "array-api-strict (>=2.3.1)", "asv", "gmpy2", "hypothesis (>=6.30)", "meson", "mpmath", "ninja ; sys_platform != \"emscripten\"", "pooch", "pytest (>=8.0.0)", "pytest-cov", "pytest-timeout", "pytest-xdist", "scikit-umfpack", "scipy-doctest (>=2.0.0)", "threadpoolctl"] + + +[[package]] +name = "shap" +version = "0.47.2" +description = "A unified approach to explain the output of any machine learning model." +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "shap-0.47.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:03d014351cb0ead1671ccb46cf38e7b3e810a19c3b6f79f4f84bb183b7c368bd"}, + {file = "shap-0.47.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a177f1c996ac64690cc9bceed00bdb5ec406dfadc7bf87e5a79dea28607a768c"}, + {file = "shap-0.47.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f0179d33aaab65bf6089ab802575308da389c54392d9f3054c3d2d04d78ce3d0"}, + {file = "shap-0.47.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:adbae48a3e844d81f8ad41c2d0cbf90bc82708e00238cc6b024690b84a5d5dcb"}, + {file = "shap-0.47.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:6579a3ba14fdae6280041d4306e75899ff900b6f302e77f0b379e4504b19a735"}, + {file = "shap-0.47.2-cp310-cp310-win_amd64.whl", hash = "sha256:4dd04511eebcb3c4407e5e4f2818d9be792434989f32c9cb25b1f1fa3ca3309b"}, + {file = "shap-0.47.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:434a7eb17b11f35893538520cf5da39bcfe95d66873bc316ce241dda29350457"}, + {file = "shap-0.47.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4bd297a5caa1314be5600c5006571bd6702b4ab8868ca25bc7cc12d391362ad3"}, + {file = "shap-0.47.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:76a9ac5e312cd5d659a17ea56c03a61d6f55b5fda94e187e3870b07101ca5f9e"}, + {file = "shap-0.47.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dc6105ed556cea490e6d59d9b20d2fac0131f821c40a4f83a7220356820a946a"}, + {file = "shap-0.47.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:224f359e55b38fc9cb2528bd0c738a842c8387d144476d24d5c7a7fae9b57894"}, + {file = "shap-0.47.2-cp311-cp311-win_amd64.whl", hash = "sha256:fdf114b29fb2b7d9e20a6854e79a5f44e1ce95e8eea161d84903e44e7c4b8770"}, + {file = "shap-0.47.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:9b3b5fca9ae3758dd534b0f6e4973f3c07d2636920b1dc2c6994fa44854e62d4"}, + {file = "shap-0.47.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:896efda3ccf8d7021cf3e4f3af1f6baed77ea364629d8e5f92dfa22ff449dd49"}, + {file = "shap-0.47.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e38edf10cf627a65ac602d99f98a8c32968902c87534069e93d8b67fe0022841"}, + {file = "shap-0.47.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a256c08c3be20d4a2efc5e8266423b83f07efd5354f18d3c439d9faafd0e4358"}, + {file = "shap-0.47.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0d24483ea3e36cb57fe1d9d547577b71e981a7baa8d07f4c4a959bec9b7c94db"}, + {file = "shap-0.47.2-cp312-cp312-win_amd64.whl", hash = "sha256:93be4e3fe4cc59582d6096c626b1443e30bcee2c7adda40af9d09ee0721647bc"}, + {file = "shap-0.47.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:c934e50c6a92f59f17d75ad3cbe8d11330ee9f5d25958b041c8038970ef52049"}, + {file = "shap-0.47.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:aa40b294634ff7ab03b3424a55aa4ae03c9ef9c8144a7eba4da92c0b31a6ead9"}, + {file = "shap-0.47.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:324da17c7ea0ea9b60600fe2ef192870b349d3c1d2511720a0f70419fb074330"}, + {file = "shap-0.47.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d8d4ea12c3e9e3fe3a546436f0859c8fbeaceb7649db79842d2c5ef8cff4b35f"}, + {file = "shap-0.47.2-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:717f8e2b1d8e345ff4391c6a9b99ad14dca3847727adb087b9a14239995fb7a5"}, + {file = "shap-0.47.2-cp39-cp39-win_amd64.whl", hash = "sha256:53cc243f16e869a171f68031596d44f8151479301a5ccf744fc42c0a6155dfdf"}, + {file = "shap-0.47.2.tar.gz", hash = "sha256:8a53901fc44396d92a12b985d83ca4a47a7dcc4a04a7f7e556232a35f17d30c8"}, +] + +[package.dependencies] +cloudpickle = "*" +numba = ">=0.54" +numpy = "*" +packaging = ">20.9" +pandas = "*" +scikit-learn = "*" +scipy = "*" +slicer = "0.0.8" +tqdm = ">=4.27.0" +typing-extensions = "*" + +[package.extras] +docs = ["ipython", "ipywidgets", "matplotlib", "myst-parser", "nbsphinx", "numpydoc", "requests", "sphinx", "sphinx_github_changelog", "sphinx_rtd_theme"] +others = ["lime"] +plots = ["ipython", "matplotlib"] +test = ["catboost", "causalml", "gpboost", "lightgbm", "ngboost", "numpy (<2.0)", "opencv-python", "protobuf (==3.20.3)", "pyod", "pyspark", "pytest", "pytest-cov", "pytest-mpl", "selenium", "sentencepiece", "tensorflow", "tf-keras", "torch (==2.2.0) ; sys_platform == \"darwin\"", "torch ; sys_platform != \"darwin\"", "torchvision", "transformers (<=4.49.0) ; sys_platform == \"darwin\"", "transformers ; sys_platform != \"darwin\"", "xgboost"] +test-core = ["mypy", "pytest", "pytest-cov", "pytest-mpl"] +test-notebooks = ["datasets", "jupyter", "keras", "nbconvert", "nbformat", "nlp", "transformers"] + + +[[package]] +name = "six" +version = "1.17.0" +description = "Python 2 and 3 compatibility utilities" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*" +groups = ["main", "dev"] +files = [ + {file = "six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274"}, + {file = "six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81"}, +] + + +[[package]] +name = "slicer" +version = "0.0.8" +description = "A small package for big slicing." +optional = false +python-versions = ">=3.6" +groups = ["main"] +files = [ + {file = "slicer-0.0.8-py3-none-any.whl", hash = "sha256:6c206258543aecd010d497dc2eca9d2805860a0b3758673903456b7df7934dc3"}, + {file = "slicer-0.0.8.tar.gz", hash = "sha256:2e7553af73f0c0c2d355f4afcc3ecf97c6f2156fcf4593955c3f56cf6c4d6eb7"}, +] + + +[[package]] +name = "snowballstemmer" +version = "3.1.1" +description = "This package provides 36 stemmers for 34 languages generated from Snowball algorithms." +optional = false +python-versions = ">=3.3" +groups = ["docs"] +files = [ + {file = "snowballstemmer-3.1.1-py3-none-any.whl", hash = "sha256:7e207fa178741da09cdee59d3ecec3827ad5f92b1fc5c9ff3755b639f71f5752"}, + {file = "snowballstemmer-3.1.1.tar.gz", hash = "sha256:e07bbc54a0d798fe6010a12398422e62a8bfbba95c394fd0956ef58cb4d3e260"}, +] + + +[[package]] +name = "sphinx" +version = "7.4.7" +description = "Python documentation generator" +optional = false +python-versions = ">=3.9" +groups = ["docs"] +files = [ + {file = "sphinx-7.4.7-py3-none-any.whl", hash = "sha256:c2419e2135d11f1951cd994d6eb18a1835bd8fdd8429f9ca375dc1f3281bd239"}, + {file = "sphinx-7.4.7.tar.gz", hash = "sha256:242f92a7ea7e6c5b406fdc2615413890ba9f699114a9c09192d7dfead2ee9cfe"}, +] + +[package.dependencies] +alabaster = ">=0.7.14,<0.8.0" +babel = ">=2.13" +colorama = {version = ">=0.4.6", markers = "sys_platform == \"win32\""} +docutils = ">=0.20,<0.22" +imagesize = ">=1.3" +Jinja2 = ">=3.1" +packaging = ">=23.0" +Pygments = ">=2.17" +requests = ">=2.30.0" +snowballstemmer = ">=2.2" +sphinxcontrib-applehelp = "*" +sphinxcontrib-devhelp = "*" +sphinxcontrib-htmlhelp = ">=2.0.0" +sphinxcontrib-jsmath = "*" +sphinxcontrib-qthelp = "*" +sphinxcontrib-serializinghtml = ">=1.1.9" +tomli = {version = ">=2", markers = "python_version < \"3.11\""} + +[package.extras] +docs = ["sphinxcontrib-websupport"] +lint = ["flake8 (>=6.0)", "importlib-metadata (>=6.0)", "mypy (==1.10.1)", "pytest (>=6.0)", "ruff (==0.5.2)", "sphinx-lint (>=0.9)", "tomli (>=2)", "types-docutils (==0.21.0.20240711)", "types-requests (>=2.30.0)"] +test = ["cython (>=3.0)", "defusedxml (>=0.7.1)", "pytest (>=8.0)", "setuptools (>=70.0)", "typing_extensions (>=4.9)"] + + +[[package]] +name = "sphinx-autodoc-typehints" +version = "1.25.3" +description = "Type hints (PEP 484) support for the Sphinx autodoc extension" +optional = false +python-versions = ">=3.8" +groups = ["docs"] +files = [ + {file = "sphinx_autodoc_typehints-1.25.3-py3-none-any.whl", hash = "sha256:d3da7fa9a9761eff6ff09f8b1956ae3090a2d4f4ad54aebcade8e458d6340835"}, + {file = "sphinx_autodoc_typehints-1.25.3.tar.gz", hash = "sha256:70db10b391acf4e772019765991d2de0ff30ec0899b9ba137706dc0b3c4835e0"}, +] + +[package.dependencies] +sphinx = ">=7.1.2" + +[package.extras] +docs = ["furo (>=2023.9.10)"] +numpy = ["nptyping (>=2.5)"] +testing = ["covdefaults (>=2.3)", "coverage (>=7.3.2)", "diff-cover (>=8.0.1)", "pytest (>=7.4.3)", "pytest-cov (>=4.1)", "sphobjinv (>=2.3.1)", "typing-extensions (>=4.8)"] + + +[[package]] +name = "sphinx-rtd-theme" +version = "3.1.0" +description = "Read the Docs theme for Sphinx" +optional = false +python-versions = ">=3.8" +groups = ["docs"] +files = [ + {file = "sphinx_rtd_theme-3.1.0-py2.py3-none-any.whl", hash = "sha256:1785824ae8e6632060490f67cf3a72d404a85d2d9fc26bce3619944de5682b89"}, + {file = "sphinx_rtd_theme-3.1.0.tar.gz", hash = "sha256:b44276f2c276e909239a4f6c955aa667aaafeb78597923b1c60babc76db78e4c"}, +] + +[package.dependencies] +docutils = ">0.18,<0.23" +sphinx = ">=6,<10" +sphinxcontrib-jquery = ">=4,<5" + +[package.extras] +dev = ["bump2version", "transifex-client", "twine", "wheel"] + + +[[package]] +name = "sphinxcontrib-applehelp" +version = "2.0.0" +description = "sphinxcontrib-applehelp is a Sphinx extension which outputs Apple help books" +optional = false +python-versions = ">=3.9" +groups = ["docs"] +files = [ + {file = "sphinxcontrib_applehelp-2.0.0-py3-none-any.whl", hash = "sha256:4cd3f0ec4ac5dd9c17ec65e9ab272c9b867ea77425228e68ecf08d6b28ddbdb5"}, + {file = "sphinxcontrib_applehelp-2.0.0.tar.gz", hash = "sha256:2f29ef331735ce958efa4734873f084941970894c6090408b079c61b2e1c06d1"}, +] + +[package.extras] +lint = ["mypy", "ruff (==0.5.5)", "types-docutils"] +standalone = ["Sphinx (>=5)"] +test = ["pytest"] + + +[[package]] +name = "sphinxcontrib-devhelp" +version = "2.0.0" +description = "sphinxcontrib-devhelp is a sphinx extension which outputs Devhelp documents" +optional = false +python-versions = ">=3.9" +groups = ["docs"] +files = [ + {file = "sphinxcontrib_devhelp-2.0.0-py3-none-any.whl", hash = "sha256:aefb8b83854e4b0998877524d1029fd3e6879210422ee3780459e28a1f03a8a2"}, + {file = "sphinxcontrib_devhelp-2.0.0.tar.gz", hash = "sha256:411f5d96d445d1d73bb5d52133377b4248ec79db5c793ce7dbe59e074b4dd1ad"}, +] + +[package.extras] +lint = ["mypy", "ruff (==0.5.5)", "types-docutils"] +standalone = ["Sphinx (>=5)"] +test = ["pytest"] + + +[[package]] +name = "sphinxcontrib-htmlhelp" +version = "2.1.0" +description = "sphinxcontrib-htmlhelp is a sphinx extension which renders HTML help files" +optional = false +python-versions = ">=3.9" +groups = ["docs"] +files = [ + {file = "sphinxcontrib_htmlhelp-2.1.0-py3-none-any.whl", hash = "sha256:166759820b47002d22914d64a075ce08f4c46818e17cfc9470a9786b759b19f8"}, + {file = "sphinxcontrib_htmlhelp-2.1.0.tar.gz", hash = "sha256:c9e2916ace8aad64cc13a0d233ee22317f2b9025b9cf3295249fa985cc7082e9"}, +] + +[package.extras] +lint = ["mypy", "ruff (==0.5.5)", "types-docutils"] +standalone = ["Sphinx (>=5)"] +test = ["html5lib", "pytest"] + + +[[package]] +name = "sphinxcontrib-jquery" +version = "4.1" +description = "Extension to include jQuery on newer Sphinx releases" +optional = false +python-versions = ">=2.7" +groups = ["docs"] +files = [ + {file = "sphinxcontrib-jquery-4.1.tar.gz", hash = "sha256:1620739f04e36a2c779f1a131a2dfd49b2fd07351bf1968ced074365933abc7a"}, + {file = "sphinxcontrib_jquery-4.1-py2.py3-none-any.whl", hash = "sha256:f936030d7d0147dd026a4f2b5a57343d233f1fc7b363f68b3d4f1cb0993878ae"}, +] + +[package.dependencies] +Sphinx = ">=1.8" + + +[[package]] +name = "sphinxcontrib-jsmath" +version = "1.0.1" +description = "A sphinx extension which renders display math in HTML via JavaScript" +optional = false +python-versions = ">=3.5" +groups = ["docs"] +files = [ + {file = "sphinxcontrib-jsmath-1.0.1.tar.gz", hash = "sha256:a9925e4a4587247ed2191a22df5f6970656cb8ca2bd6284309578f2153e0c4b8"}, + {file = "sphinxcontrib_jsmath-1.0.1-py2.py3-none-any.whl", hash = "sha256:2ec2eaebfb78f3f2078e73666b1415417a116cc848b72e5172e596c871103178"}, +] + +[package.extras] +test = ["flake8", "mypy", "pytest"] + + +[[package]] +name = "sphinxcontrib-qthelp" +version = "2.0.0" +description = "sphinxcontrib-qthelp is a sphinx extension which outputs QtHelp documents" +optional = false +python-versions = ">=3.9" +groups = ["docs"] +files = [ + {file = "sphinxcontrib_qthelp-2.0.0-py3-none-any.whl", hash = "sha256:b18a828cdba941ccd6ee8445dbe72ffa3ef8cbe7505d8cd1fa0d42d3f2d5f3eb"}, + {file = "sphinxcontrib_qthelp-2.0.0.tar.gz", hash = "sha256:4fe7d0ac8fc171045be623aba3e2a8f613f8682731f9153bb2e40ece16b9bbab"}, +] + +[package.extras] +lint = ["mypy", "ruff (==0.5.5)", "types-docutils"] +standalone = ["Sphinx (>=5)"] +test = ["defusedxml (>=0.7.1)", "pytest"] + + +[[package]] +name = "sphinxcontrib-serializinghtml" +version = "2.0.0" +description = "sphinxcontrib-serializinghtml is a sphinx extension which outputs \"serialized\" HTML files (json and pickle)" +optional = false +python-versions = ">=3.9" +groups = ["docs"] +files = [ + {file = "sphinxcontrib_serializinghtml-2.0.0-py3-none-any.whl", hash = "sha256:6e2cb0eef194e10c27ec0023bfeb25badbbb5868244cf5bc5bdc04e4464bf331"}, + {file = "sphinxcontrib_serializinghtml-2.0.0.tar.gz", hash = "sha256:e9d912827f872c029017a53f0ef2180b327c3f7fd23c87229f7a8e8b70031d4d"}, +] + +[package.extras] +lint = ["mypy", "ruff (==0.5.5)", "types-docutils"] +standalone = ["Sphinx (>=5)"] +test = ["pytest"] + + +[[package]] +name = "threadpoolctl" +version = "3.7.0" +description = "threadpoolctl" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "threadpoolctl-3.7.0-py3-none-any.whl", hash = "sha256:cd8b60b5641b45c67bbf73c64c843235fc2d8a480c87389f52f5dbee893b86be"}, + {file = "threadpoolctl-3.7.0.tar.gz", hash = "sha256:61348cfb77d53b9242e0017029244b559b810c142ced65b4e21eeca1843959a7"}, +] + + +[[package]] +name = "tomli" +version = "2.4.1" +description = "A lil' TOML parser" +optional = false +python-versions = ">=3.8" +groups = ["dev", "docs"] +markers = "python_version == \"3.10\"" +files = [ + {file = "tomli-2.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f8f0fc26ec2cc2b965b7a3b87cd19c5c6b8c5e5f436b984e85f486d652285c30"}, + {file = "tomli-2.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4ab97e64ccda8756376892c53a72bd1f964e519c77236368527f758fbc36a53a"}, + {file = "tomli-2.4.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96481a5786729fd470164b47cdb3e0e58062a496f455ee41b4403be77cb5a076"}, + {file = "tomli-2.4.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5a881ab208c0baf688221f8cecc5401bd291d67e38a1ac884d6736cbcd8247e9"}, + {file = "tomli-2.4.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:47149d5bd38761ac8be13a84864bf0b7b70bc051806bc3669ab1cbc56216b23c"}, + {file = "tomli-2.4.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ec9bfaf3ad2df51ace80688143a6a4ebc09a248f6ff781a9945e51937008fcbc"}, + {file = "tomli-2.4.1-cp311-cp311-win32.whl", hash = "sha256:ff2983983d34813c1aeb0fa89091e76c3a22889ee83ab27c5eeb45100560c049"}, + {file = "tomli-2.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:5ee18d9ebdb417e384b58fe414e8d6af9f4e7a0ae761519fb50f721de398dd4e"}, + {file = "tomli-2.4.1-cp311-cp311-win_arm64.whl", hash = "sha256:c2541745709bad0264b7d4705ad453b76ccd191e64aa6f0fc66b69a293a45ece"}, + {file = "tomli-2.4.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c742f741d58a28940ce01d58f0ab2ea3ced8b12402f162f4d534dfe18ba1cd6a"}, + {file = "tomli-2.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7f86fd587c4ed9dd76f318225e7d9b29cfc5a9d43de44e5754db8d1128487085"}, + {file = "tomli-2.4.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ff18e6a727ee0ab0388507b89d1bc6a22b138d1e2fa56d1ad494586d61d2eae9"}, + {file = "tomli-2.4.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:136443dbd7e1dee43c68ac2694fde36b2849865fa258d39bf822c10e8068eac5"}, + {file = "tomli-2.4.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5e262d41726bc187e69af7825504c933b6794dc3fbd5945e41a79bb14c31f585"}, + {file = "tomli-2.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5cb41aa38891e073ee49d55fbc7839cfdb2bc0e600add13874d048c94aadddd1"}, + {file = "tomli-2.4.1-cp312-cp312-win32.whl", hash = "sha256:da25dc3563bff5965356133435b757a795a17b17d01dbc0f42fb32447ddfd917"}, + {file = "tomli-2.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:52c8ef851d9a240f11a88c003eacb03c31fc1c9c4ec64a99a0f922b93874fda9"}, + {file = "tomli-2.4.1-cp312-cp312-win_arm64.whl", hash = "sha256:f758f1b9299d059cc3f6546ae2af89670cb1c4d48ea29c3cacc4fe7de3058257"}, + {file = "tomli-2.4.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:36d2bd2ad5fb9eaddba5226aa02c8ec3fa4f192631e347b3ed28186d43be6b54"}, + {file = "tomli-2.4.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:eb0dc4e38e6a1fd579e5d50369aa2e10acfc9cace504579b2faabb478e76941a"}, + {file = "tomli-2.4.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c7f2c7f2b9ca6bdeef8f0fa897f8e05085923eb091721675170254cbc5b02897"}, + {file = "tomli-2.4.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f3c6818a1a86dd6dca7ddcaaf76947d5ba31aecc28cb1b67009a5877c9a64f3f"}, + {file = "tomli-2.4.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d312ef37c91508b0ab2cee7da26ec0b3ed2f03ce12bd87a588d771ae15dcf82d"}, + {file = "tomli-2.4.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:51529d40e3ca50046d7606fa99ce3956a617f9b36380da3b7f0dd3dd28e68cb5"}, + {file = "tomli-2.4.1-cp313-cp313-win32.whl", hash = "sha256:2190f2e9dd7508d2a90ded5ed369255980a1bcdd58e52f7fe24b8162bf9fedbd"}, + {file = "tomli-2.4.1-cp313-cp313-win_amd64.whl", hash = "sha256:8d65a2fbf9d2f8352685bc1364177ee3923d6baf5e7f43ea4959d7d8bc326a36"}, + {file = "tomli-2.4.1-cp313-cp313-win_arm64.whl", hash = "sha256:4b605484e43cdc43f0954ddae319fb75f04cc10dd80d830540060ee7cd0243cd"}, + {file = "tomli-2.4.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:fd0409a3653af6c147209d267a0e4243f0ae46b011aa978b1080359fddc9b6cf"}, + {file = "tomli-2.4.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a120733b01c45e9a0c34aeef92bf0cf1d56cfe81ed9d47d562f9ed591a9828ac"}, + {file = "tomli-2.4.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:559db847dc486944896521f68d8190be1c9e719fced785720d2216fe7022b662"}, + {file = "tomli-2.4.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:01f520d4f53ef97964a240a035ec2a869fe1a37dde002b57ebc4417a27ccd853"}, + {file = "tomli-2.4.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7f94b27a62cfad8496c8d2513e1a222dd446f095fca8987fceef261225538a15"}, + {file = "tomli-2.4.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ede3e6487c5ef5d28634ba3f31f989030ad6af71edfb0055cbbd14189ff240ba"}, + {file = "tomli-2.4.1-cp314-cp314-win32.whl", hash = "sha256:3d48a93ee1c9b79c04bb38772ee1b64dcf18ff43085896ea460ca8dec96f35f6"}, + {file = "tomli-2.4.1-cp314-cp314-win_amd64.whl", hash = "sha256:88dceee75c2c63af144e456745e10101eb67361050196b0b6af5d717254dddf7"}, + {file = "tomli-2.4.1-cp314-cp314-win_arm64.whl", hash = "sha256:b8c198f8c1805dc42708689ed6864951fd2494f924149d3e4bce7710f8eb5232"}, + {file = "tomli-2.4.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:d4d8fe59808a54658fcc0160ecfb1b30f9089906c50b23bcb4c69eddc19ec2b4"}, + {file = "tomli-2.4.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7008df2e7655c495dd12d2a4ad038ff878d4ca4b81fccaf82b714e07eae4402c"}, + {file = "tomli-2.4.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1d8591993e228b0c930c4bb0db464bdad97b3289fb981255d6c9a41aedc84b2d"}, + {file = "tomli-2.4.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:734e20b57ba95624ecf1841e72b53f6e186355e216e5412de414e3c51e5e3c41"}, + {file = "tomli-2.4.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8a650c2dbafa08d42e51ba0b62740dae4ecb9338eefa093aa5c78ceb546fcd5c"}, + {file = "tomli-2.4.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:504aa796fe0569bb43171066009ead363de03675276d2d121ac1a4572397870f"}, + {file = "tomli-2.4.1-cp314-cp314t-win32.whl", hash = "sha256:b1d22e6e9387bf4739fbe23bfa80e93f6b0373a7f1b96c6227c32bef95a4d7a8"}, + {file = "tomli-2.4.1-cp314-cp314t-win_amd64.whl", hash = "sha256:2c1c351919aca02858f740c6d33adea0c5deea37f9ecca1cc1ef9e884a619d26"}, + {file = "tomli-2.4.1-cp314-cp314t-win_arm64.whl", hash = "sha256:eab21f45c7f66c13f2a9e0e1535309cee140182a9cdae1e041d02e47291e8396"}, + {file = "tomli-2.4.1-py3-none-any.whl", hash = "sha256:0d85819802132122da43cb86656f8d1f8c6587d54ae7dcaf30e90533028b49fe"}, + {file = "tomli-2.4.1.tar.gz", hash = "sha256:7c7e1a961a0b2f2472c1ac5b69affa0ae1132c39adcb67aba98568702b9cc23f"}, +] + + +[[package]] +name = "tox" +version = "3.28.0" +description = "tox is a generic virtualenv management and test command line tool" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,>=2.7" +groups = ["dev"] +files = [ + {file = "tox-3.28.0-py2.py3-none-any.whl", hash = "sha256:57b5ab7e8bb3074edc3c0c0b4b192a4f3799d3723b2c5b76f1fa9f2d40316eea"}, + {file = "tox-3.28.0.tar.gz", hash = "sha256:d0d28f3fe6d6d7195c27f8b054c3e99d5451952b54abdae673b71609a581f640"}, +] + +[package.dependencies] +colorama = {version = ">=0.4.1", markers = "platform_system == \"Windows\""} +filelock = ">=3.0.0" +packaging = ">=14" +pluggy = ">=0.12.0" +py = ">=1.4.17" +six = ">=1.14.0" +tomli = {version = ">=2.0.1", markers = "python_version >= \"3.7\" and python_version < \"3.11\""} +virtualenv = ">=16.0.0,<20.0.0 || >20.0.0,<20.0.1 || >20.0.1,<20.0.2 || >20.0.2,<20.0.3 || >20.0.3,<20.0.4 || >20.0.4,<20.0.5 || >20.0.5,<20.0.6 || >20.0.6,<20.0.7 || >20.0.7" + +[package.extras] +docs = ["pygments-github-lexers (>=0.0.5)", "sphinx (>=2.0.0)", "sphinxcontrib-autoprogram (>=0.1.5)", "towncrier (>=18.5.0)"] +testing = ["flaky (>=3.4.0)", "freezegun (>=0.3.11)", "pathlib2 (>=2.3.3) ; python_version < \"3.4\"", "psutil (>=5.6.1) ; platform_python_implementation == \"cpython\"", "pytest (>=4.0.0)", "pytest-cov (>=2.5.1)", "pytest-mock (>=1.10.0)", "pytest-randomly (>=1.0.0)"] + + +[[package]] +name = "tqdm" +version = "4.70.1" +description = "Fast, Extensible Progress Meter" +optional = false +python-versions = ">=3.8" +groups = ["main"] +files = [ + {file = "tqdm-4.70.1-py3-none-any.whl", hash = "sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73"}, + {file = "tqdm-4.70.1.tar.gz", hash = "sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4"}, +] + +[package.dependencies] +colorama = {version = "*", markers = "platform_system == \"Windows\""} + +[package.extras] +discord = ["envwrap", "requests"] +notebook = ["ipywidgets (>=6)"] +slack = ["envwrap", "slack-sdk"] +telegram = ["envwrap", "requests"] + + +[[package]] +name = "types-pytz" +version = "2026.3.1.20260727" +description = "Typing stubs for pytz" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "types_pytz-2026.3.1.20260727-py3-none-any.whl", hash = "sha256:42ac44e83645bfceb46597342c8fb8ec028a1407e2feae9c5c539986eab6b57a"}, + {file = "types_pytz-2026.3.1.20260727.tar.gz", hash = "sha256:4364075b6867dd15b210bb8c1d29727d609917129b45600defe1d4b3eda5ecb9"}, +] + + +[[package]] +name = "typing-extensions" +version = "4.16.0" +description = "Backported and Experimental Type Hints for Python 3.9+" +optional = false +python-versions = ">=3.9" +groups = ["main", "dev"] +files = [ + {file = "typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8"}, + {file = "typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5"}, +] + + +[[package]] +name = "tzdata" +version = "2026.4" +description = "Provider of IANA time zone data" +optional = false +python-versions = ">=2" +groups = ["main"] +files = [ + {file = "tzdata-2026.4-py2.py3-none-any.whl", hash = "sha256:c2169a8b0a7a5e9674da5a135ccdfb2b3e671b333ed9fed17b41f73c34476e81"}, + {file = "tzdata-2026.4.tar.gz", hash = "sha256:f1b8bd365d8d210c55353f4d7f8d6d8561c0ba50d704b700d195a9424bba0d79"}, +] + + +[[package]] +name = "urllib3" +version = "2.8.0" +description = "HTTP library with thread-safe connection pooling, file post, and more." +optional = false +python-versions = ">=3.10" +groups = ["docs"] +files = [ + {file = "urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3"}, + {file = "urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63"}, +] + +[package.extras] +brotli = ["brotli (>=1.2.0) ; platform_python_implementation == \"CPython\"", "brotlicffi (>=1.2.0.0) ; platform_python_implementation != \"CPython\""] +h2 = ["h2 (>=4,<5)"] +socks = ["pysocks (>=1.5.6,!=1.5.7,<2.0)"] +zstd = ["backports-zstd (>=1.0.0) ; python_version < \"3.14\""] + + +[[package]] +name = "virtualenv" +version = "21.7.14" +description = "Virtual Python Environment builder" +optional = false +python-versions = ">=3.9" +groups = ["dev"] +files = [ + {file = "virtualenv-21.7.14-py3-none-any.whl", hash = "sha256:ac2b2b3755da16aed6302de00ecd0cc43ecc0f295c3f84c064969cd70869ba05"}, + {file = "virtualenv-21.7.14.tar.gz", hash = "sha256:6f14bcaeb6c3438cd8c8cf3ab1805973592fb900e9b724427d1102aaa3db7fbb"}, +] + +[package.dependencies] +distlib = ">=0.3.7,<1" +filelock = {version = ">=3.24.2,<4", markers = "python_version >= \"3.10\""} +platformdirs = ">=3.9.1,<5" +python-discovery = ">=1.6" +typing-extensions = {version = ">=4.13.2", markers = "python_version < \"3.11\""} + + +[metadata] +lock-version = "2.1" +python-versions = ">=3.11,<3.15" +content-hash = "67d83854bd7be154dbe64e4c8524b2e73fdaef2863dce161ff124927e2bcad3f" diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..bfba2ca --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,110 @@ +[project] +name = "multilift" +version = "0.1.0" +description = "Multi-treatment uplift modeling with S-Learners, T-Learners, and Qini evaluation" +readme = "README.md" +license = "Apache-2.0" +authors = [ + { name = "Avik Basu" }, + { name = "Beata Luczywek" }, +] +maintainers = [ + { name = "Avik Basu" }, + { name = "Beata Luczywek" }, + { name = "Benjamin Stenhaug" }, +] +keywords = ["uplift-modeling", "causal-inference", "machine-learning", "qini", "meta-learners"] +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Science/Research", + "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 :: Artificial Intelligence", +] +requires-python = ">=3.11,<3.15" +dependencies = [ + "lightgbm>=4.6.0,<4.7.0", + "scikit-learn>=1.4,<2.0", + "pandas>=2.2.3,<3.0", + "matplotlib>=3.10.0,<4.0", + "shap>=0.47.0,<0.48.0", + "pyarrow>=17.0", + "numpy>=1.26,<3.0", + "scipy>=1.11,<2.0", + "joblib>=1.3,<2.0", +] + +[project.urls] +Homepage = "https://github.com/intuit/multilift" +Repository = "https://github.com/intuit/multilift" +Issues = "https://github.com/intuit/multilift/issues" +Changelog = "https://github.com/intuit/multilift/blob/main/CHANGELOG.md" + +[tool.poetry] +packages = [{include = "multilift"}] + +[tool.poetry.group.dev.dependencies] +black = ">=23.7.0" +isort = "^5.10.1" +mypy = "^1.3.0" +ruff = "^0.7.4" +pre-commit = "^4.1.0" +pytest = "^7.0.0" +pytest-cov = "^3.0.0" +pytest-xdist = "^2.5.0" +tox = "^3.27.1" +pandas-stubs = "^2.2.3" + +[tool.poetry.group.docs.dependencies] +sphinx = ">=7.0,<8" +sphinx-rtd-theme = "^3.0.2" +sphinx-autodoc-typehints = ">=1.25,<2" + + +[tool.black] +line-length = 100 +target-version = ['py311', 'py312', 'py313', 'py314'] + +[tool.isort] +profile = "black" + +[tool.ruff] +line-length = 100 +src = ["multilift", "tests"] +lint.select = ["E", "F", "W", "C901", "NPY", "RUF", "TRY", "G", "PLE", "PLW", "UP", "ICN", "RET", "Q", "PLR", "D"] +lint.ignore = ["D104", "D100", "TRY003", "NPY201"] +target-version = "py311" +show-fixes = true + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["D101", "D103", "F401", "F811", "D102"] + +[tool.ruff.lint.pylint] +max-args = 15 +max-statements = 30 + +[tool.ruff.lint.pydocstyle] +convention = "numpy" + +[tool.mypy] +warn_unused_configs = true +warn_redundant_casts = true +warn_unused_ignores = true +strict_equality = true +extra_checks = true +check_untyped_defs = true + +[tool.pytest.ini_options] +pythonpath = "." +testpaths = [ + "tests", +] +looponfailroots = ["multilift", "tests"] +addopts = "-p no:warnings -o log_cli=true --log-cli-level=INFO" + +[build-system] +requires = ["poetry-core>=2.0"] +build-backend = "poetry.core.masonry.api" diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..97e5cb6 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,18 @@ +import logging +import os +import sys +import warnings + +if not sys.warnoptions: + warnings.simplefilter("default", category=UserWarning) + os.environ["PYTHONWARNINGS"] = "default" + + +logger = logging.getLogger(__name__) +stream_handler = logging.StreamHandler() +stream_handler.setLevel(logging.DEBUG) + +formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") +stream_handler.setFormatter(formatter) + +logger.addHandler(stream_handler) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..38ee882 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,18 @@ +"""Pytest configuration for multilift tests.""" + +import matplotlib as mpl +import pytest + + +@pytest.fixture(autouse=True) +def use_non_interactive_backend(): + """ + Use a non-interactive matplotlib backend for all tests. + + This prevents plots from being displayed during test runs, + which speeds up testing and avoids GUI window pop-ups. + """ + original_backend = mpl.get_backend() + mpl.use("Agg") + yield + mpl.use(original_backend) diff --git a/tests/test_preproc.py b/tests/test_preproc.py new file mode 100644 index 0000000..0345822 --- /dev/null +++ b/tests/test_preproc.py @@ -0,0 +1,359 @@ +import numpy as np +import pandas as pd +import pytest + +from multilift.exceptions import ModelNotFittedError +from multilift.preproc import OneHotPreprocessor, set_categorical_dtype + + +def test_set_categorical_dtype_1(): + # Create a sample DataFrame + data = {"col1": ["a", "b", "c", "a"], "col2": [1, 2, 3, 4], "col3": ["x", "y", "z", "x"]} + df = pd.DataFrame(data) + + # Call the function + result_df, cat_features = set_categorical_dtype(df) + + # Check if the columns are correctly converted to categorical + assert result_df["col1"].dtype.name == "category" + assert result_df["col3"].dtype.name == "category" + assert result_df["col2"].dtype.name != "category" + + # Check if the correct categorical columns are returned + assert set(cat_features) == {"col1", "col3"} + + +def test_set_categorical_dtype_2(): + # Create a sample DataFrame with some columns already in category mode + data = { + "col1": pd.Series(["a", "b", "c", "a"], dtype="category"), + "col2": [1, 2, 3, 4], + "col3": ["x", "y", "z", "x"], + } + df = pd.DataFrame(data) + + # Call the function + result_df, cat_features = set_categorical_dtype(df) + + # Check if the columns are correctly converted to categorical + assert result_df["col1"].dtype.name == "category" + assert result_df["col3"].dtype.name == "category" + assert result_df["col2"].dtype.name != "category" + + # Check if the correct categorical columns are returned + assert set(cat_features) == {"col1", "col3"} + + +def test_set_categorical_dtype_3(): + # Create a sample DataFrame with all columns in category mode + data = { + "col1": pd.Series(["a", "b", "c", "a"], dtype="category"), + "col2": pd.Series([1, 2, 3, 4], dtype="category"), + "col3": pd.Series(["x", "y", "z", "x"], dtype="category"), + } + df = pd.DataFrame(data) + + # Call the function + result_df, cat_features = set_categorical_dtype(df) + + # Check if the columns are correctly converted to categorical + assert result_df["col1"].dtype.name == "category" + assert result_df["col2"].dtype.name == "category" + assert result_df["col3"].dtype.name == "category" + + # Check if the correct categorical columns are returned + assert set(cat_features) == {"col1", "col2", "col3"} + + +class TestOneHotPreprocessor: + """Test cases for OneHotPreprocessor class.""" + + def test_basic_fit_transform(self): + """Test basic fit and transform with mixed data types.""" + # Create a sample DataFrame with both categorical and numeric columns + df = pd.DataFrame( + { + "cat_col1": ["a", "b", "c", "a", "b"], + "cat_col2": ["x", "y", "z", "x", "y"], + "num_col1": [1, 2, 3, 4, 5], + "num_col2": [0.1, 0.2, 0.3, 0.4, 0.5], + } + ) + + preprocessor = OneHotPreprocessor() + result = preprocessor.fit_transform(df) + + # Check that the preprocessor is fitted + assert preprocessor.is_fitted + + # Check that categorical columns are identified correctly + assert set(preprocessor.categorical_cols) == {"cat_col1", "cat_col2"} + assert set(preprocessor.numeric_cols) == {"num_col1", "num_col2"} + + # Check the shape of the result (should have more columns due to one-hot encoding) + # With drop="first", we should have 2 + 2 + 2 = 6 columns + # (2 numeric + 2 for cat_col1 + 2 for cat_col2) + expected_columns = 2 + 2 + 2 # numeric + encoded cat_col1 + encoded cat_col2 + assert result.shape[0] == df.shape[0] + assert result.shape[1] == expected_columns + + # Check that numeric columns are preserved + assert "num_col1" in result.columns + assert "num_col2" in result.columns + + def test_transform_without_fit(self): + """Test that transform raises error when not fitted.""" + df = pd.DataFrame({"col1": ["a", "b", "c"], "col2": [1, 2, 3]}) + + preprocessor = OneHotPreprocessor() + + with pytest.raises(ModelNotFittedError) as exc_info: + preprocessor.transform(df) + + assert "OneHotPreprocessor must be fitted before transform" in str(exc_info.value) + + def test_drop_cols_parameter(self): + """Test the drop_cols parameter functionality.""" + df = pd.DataFrame( + {"keep_col": ["a", "b", "c"], "drop_col": ["x", "y", "z"], "num_col": [1, 2, 3]} + ) + + preprocessor = OneHotPreprocessor(drop_cols=["drop_col"]) + preprocessor.fit_transform(df) + + # Check that drop_col is not in the categorical or numeric columns + assert "drop_col" not in preprocessor.categorical_cols + assert "drop_col" not in preprocessor.numeric_cols + + # Check that keep_col and num_col are processed + assert "keep_col" in preprocessor.categorical_cols + assert "num_col" in preprocessor.numeric_cols + + def test_keep_cols_parameter(self): + """Test the keep_cols parameter functionality.""" + df = pd.DataFrame( + {"col1": ["a", "b", "c"], "col2": ["x", "y", "z"], "col3": [1, 2, 3], "col4": [4, 5, 6]} + ) + + preprocessor = OneHotPreprocessor(keep_cols=["col1", "col3"]) + preprocessor.fit_transform(df) + + # Check that only kept columns are processed + assert "col1" in preprocessor.categorical_cols + assert "col3" in preprocessor.numeric_cols + assert "col2" not in preprocessor.categorical_cols + assert "col4" not in preprocessor.numeric_cols + + def test_only_categorical_columns(self): + """Test preprocessing with only categorical columns.""" + df = pd.DataFrame({"cat1": ["a", "b", "c", "a"], "cat2": ["x", "y", "z", "x"]}) + + preprocessor = OneHotPreprocessor() + result = preprocessor.fit_transform(df) + + # Check that all columns are identified as categorical + expected_cat_cols = len(df.columns) + assert len(preprocessor.categorical_cols) == expected_cat_cols + assert len(preprocessor.numeric_cols) == 0 + + # Result should only contain one-hot encoded columns + assert result.shape[0] == df.shape[0] + assert all(col.startswith("cat") for col in result.columns) + + def test_only_numeric_columns(self): + """Test preprocessing with only numeric columns.""" + df = pd.DataFrame({"num1": [1, 2, 3, 4], "num2": [0.1, 0.2, 0.3, 0.4]}) + + preprocessor = OneHotPreprocessor() + result = preprocessor.fit_transform(df) + + # Check that all columns are identified as numeric + expected_num_cols = len(df.columns) + assert len(preprocessor.categorical_cols) == 0 + assert len(preprocessor.numeric_cols) == expected_num_cols + + # Result should have same shape and column names + # Note: numeric columns are converted to float32 + assert result.shape == df.shape + assert list(result.columns) == list(df.columns) + # Check that values are preserved (with dtype conversion to float32) + pd.testing.assert_frame_equal(result, df.astype(np.float32)) + + def test_get_feature_names_out(self): + """Test getting feature names after fitting.""" + df = pd.DataFrame({"cat_col": ["a", "b", "c", "a"], "num_col": [1, 2, 3, 4]}) + + preprocessor = OneHotPreprocessor() + + # Should raise error before fitting + with pytest.raises(ValueError) as exc_info: + preprocessor.get_feature_names_out() + assert "must be fitted before getting feature names" in str(exc_info.value) + + # After fitting, should return feature names + preprocessor.fit(df) + feature_names = preprocessor.get_feature_names_out() + + assert isinstance(feature_names, list) + assert "num_col" in feature_names + assert any("cat_col" in name for name in feature_names) + + def test_handle_unknown_categories(self): + """Test handling of unknown categories during transform.""" + # Train data + df_train = pd.DataFrame({"cat_col": ["a", "b", "c"], "num_col": [1, 2, 3]}) + + # Test data with unknown category "d" + df_test = pd.DataFrame({"cat_col": ["a", "b", "d"], "num_col": [4, 5, 6]}) + + # With handle_unknown="ignore" (default), should handle gracefully + preprocessor = OneHotPreprocessor(handle_unknown="ignore") + preprocessor.fit(df_train) + result = preprocessor.transform(df_test) + + # Should not raise error and should have same number of columns as training + assert result.shape[1] == preprocessor.fit_transform(df_train).shape[1] + assert result.shape[0] == df_test.shape[0] + + def test_category_dtype_handling(self): + """Test handling of columns already with category dtype.""" + df = pd.DataFrame( + { + "cat_col": pd.Categorical(["a", "b", "c", "a"]), + "obj_col": ["x", "y", "z", "x"], + "num_col": [1, 2, 3, 4], + } + ) + + preprocessor = OneHotPreprocessor() + result = preprocessor.fit_transform(df) + + # Both categorical and object columns should be treated as categorical + assert "cat_col" in preprocessor.categorical_cols + assert "obj_col" in preprocessor.categorical_cols + assert "num_col" in preprocessor.numeric_cols + + # Check the result has the expected shape + assert result.shape[0] == df.shape[0] + assert result.shape[1] > df.shape[1] # More columns due to one-hot encoding + + def test_feature_order_preservation(self): + """Test that feature order is preserved between fit and transform.""" + # Create training data with specific column order + df_train = pd.DataFrame( + { + "num1": [1, 2, 3], + "cat1": ["a", "b", "c"], + "num2": [4, 5, 6], + "cat2": ["x", "y", "z"], + } + ) + + # Create test data with different column order + df_test = pd.DataFrame( + { + "cat2": ["x", "y", "x"], # Different order + "num2": [7, 8, 9], + "cat1": ["a", "b", "a"], + "num1": [10, 11, 12], + } + ) + + preprocessor = OneHotPreprocessor() + result_train = preprocessor.fit_transform(df_train) + result_test = preprocessor.transform(df_test) + + # Both results should have the same columns in the same order + assert list(result_train.columns) == list(result_test.columns) + + # Feature names should be consistent + feature_names = preprocessor.get_feature_names_out() + assert list(result_train.columns) == feature_names + assert list(result_test.columns) == feature_names + + # Numeric columns should come first, then categorical + # Check that numeric columns are in the same order as during fit + assert feature_names[0] == "num1" + assert feature_names[1] == "num2" + + def test_missing_columns_in_transform(self): + """Test that transform raises appropriate error when columns are missing.""" + df_train = pd.DataFrame( + {"cat_col": ["a", "b", "c"], "num_col": [1, 2, 3], "extra_col": [4, 5, 6]} + ) + + df_test = pd.DataFrame( + {"cat_col": ["a", "b", "a"], "num_col": [7, 8, 9]} # Missing extra_col + ) + + preprocessor = OneHotPreprocessor() + preprocessor.fit(df_train) + + # Should raise KeyError when a column from training is missing + with pytest.raises(KeyError): + preprocessor.transform(df_test) + + def test_extra_columns_in_transform(self): + """Test that extra columns in transform data are ignored.""" + df_train = pd.DataFrame({"cat_col": ["a", "b", "c"], "num_col": [1, 2, 3]}) + + df_test = pd.DataFrame( + { + "cat_col": ["a", "b", "a"], + "num_col": [4, 5, 6], + "extra_col": [7, 8, 9], # Extra column not in training + } + ) + + preprocessor = OneHotPreprocessor() + preprocessor.fit(df_train) + result = preprocessor.transform(df_test) + + # Extra column should be ignored + assert "extra_col" not in result.columns + + # Result should have same columns as training + train_result = preprocessor.transform(df_train) + assert list(result.columns) == list(train_result.columns) + + def test_drop_cols_with_missing_columns(self): + """Test that missing columns in drop_cols produce a warning but don't raise an error.""" + import logging + + # Create a DataFrame without the columns we'll try to drop + df = pd.DataFrame( + { + "keep_col": ["a", "b", "c"], + "num_col": [1, 2, 3], + } + ) + + # Try to drop columns that don't exist (non_existent_col) and one that does (num_col) + preprocessor = OneHotPreprocessor( + drop_cols=["non_existent_col", "another_missing", "num_col"] + ) + + # This should not raise an error, just log a warning + result = preprocessor.fit_transform(df) + + # Check that the existing column was dropped + assert "num_col" not in result.columns + assert "keep_col" in preprocessor.categorical_cols + + # The non-existent columns should not cause an error + assert result.shape[0] == df.shape[0] + + # Test in transform as well + df_test = pd.DataFrame( + { + "keep_col": ["d", "e", "f"], + "num_col": [4, 5, 6], + "extra_col": [7, 8, 9], + } + ) + + # Transform should also handle missing columns gracefully + result_test = preprocessor.transform(df_test) + assert "num_col" not in result_test.columns + assert "extra_col" not in result_test.columns # Extra columns are ignored + assert result_test.shape[0] == df_test.shape[0] diff --git a/tests/uplift/__init__.py b/tests/uplift/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/uplift/meta/__init__.py b/tests/uplift/meta/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/uplift/meta/test_slearner.py b/tests/uplift/meta/test_slearner.py new file mode 100644 index 0000000..a831d28 --- /dev/null +++ b/tests/uplift/meta/test_slearner.py @@ -0,0 +1,219 @@ +"""Tests for SLearnerRegressor.""" + +import numpy as np +import pytest +from lightgbm import LGBMRegressor +from matplotlib import pyplot as plt + +from multilift.exceptions import ModelNotFittedError +from multilift.uplift.meta import SLearnerRegressor + +DEFAULT_RANDOM_SEED = 42 +N_ESTIMATORS_SMALL = 10 +N_TREATMENTS_TWO = 2 +N_TREATMENTS_FOUR = 4 + + +@pytest.fixture(scope="module") +def sample_data(): + """Create sample numpy data with 2 treatments + 1 control.""" + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n = 150 + + X = rng.normal(0, 1, (n, 3)) + treatment = rng.choice(["control", "T1", "T2"], n) + + y = X[:, 0] + 0.5 * X[:, 1] + rng.normal(0, 0.1, n) + y[treatment == "T1"] += 0.3 + y[treatment == "T2"] += 0.5 + + return X, treatment, y + + +@pytest.fixture(scope="module") +def sample_data_four_treatments(): + """Create sample numpy data with 4 treatments + 1 control.""" + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n = 250 + + X = rng.normal(0, 1, (n, 3)) + treatment = rng.choice(["control", "T1", "T2", "T3", "T4"], n) + + y = X[:, 0] + rng.normal(0, 0.1, n) + y[treatment == "T1"] += 0.2 + y[treatment == "T2"] += 0.3 + y[treatment == "T3"] += 0.4 + y[treatment == "T4"] += 0.5 + + return X, treatment, y + + +def _make_lgbm(seed=DEFAULT_RANDOM_SEED, **kwargs): + """Create a small LGBMRegressor for testing.""" + return LGBMRegressor(random_state=seed, n_estimators=N_ESTIMATORS_SMALL, verbosity=-1, **kwargs) + + +@pytest.fixture(scope="module") +def fitted_model(sample_data): + """Return a fitted SLearnerRegressor on 2-treatment data.""" + X, treatment, y = sample_data + model = SLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + return model, X + + +class TestInit: + """Tests for SLearnerRegressor construction.""" + + def test_init_stores_control_name(self): + """Test that control_name is stored correctly.""" + model = SLearnerRegressor(control_name="control", learner=_make_lgbm()) + assert model.control_name == "control" + assert not model.is_fitted + + def test_is_fitted_false_before_fit(self): + """Test is_fitted is False before fitting.""" + model = SLearnerRegressor(control_name="control", learner=_make_lgbm()) + assert not model.is_fitted + + +class TestFit: + """Tests for SLearnerRegressor.fit.""" + + def test_fit_returns_self(self, sample_data): + """Test fit returns self for method chaining.""" + X, treatment, y = sample_data + model = SLearnerRegressor(control_name="control", learner=_make_lgbm()) + result = model.fit(X, treatment, y) + assert result is model + + def test_fit_two_treatments(self, sample_data): + """Test fit with 2 treatments creates 2 models.""" + X, treatment, y = sample_data + model = SLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + + assert model.is_fitted + assert len(model.models) == N_TREATMENTS_TWO + assert set(model.models.keys()) == {"T1", "T2"} + assert list(model.t_groups) == ["T1", "T2"] + + def test_fit_four_treatments(self, sample_data_four_treatments): + """Test fit with 4 treatments creates 4 models.""" + X, treatment, y = sample_data_four_treatments + model = SLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + + assert len(model.models) == N_TREATMENTS_FOUR + assert list(model.t_groups) == ["T1", "T2", "T3", "T4"] + + def test_fit_models_are_independent_copies(self, sample_data): + """Test that each treatment model is a distinct object.""" + X, treatment, y = sample_data + model = SLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + + assert model.models["T1"] is not model.models["T2"] + + def test_fit_uses_treatment_indicator(self, sample_data): + """Each model is trained on n_features + 1 (treatment indicator).""" + X, treatment, y = sample_data + model = SLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + + for group in model.t_groups: + assert model.models[group].n_features_in_ == X.shape[1] + 1 + + +class TestPredict: + """Tests for SLearnerRegressor.predict.""" + + def test_predict_not_fitted_raises(self): + """Test predict raises error when model is not fitted.""" + model = SLearnerRegressor(control_name="control", learner=_make_lgbm()) + X = np.random.default_rng(0).normal(0, 1, (10, 3)) + with pytest.raises(ModelNotFittedError): + model.predict(X) + + def test_predict_shape(self, fitted_model): + """Test predict returns correct shape.""" + model, X = fitted_model + te = model.predict(X) + assert te.shape == (X.shape[0], N_TREATMENTS_TWO) + assert np.isfinite(te).all() + + def test_predict_four_treatments(self, sample_data_four_treatments): + """Test predict with 4 treatment groups.""" + X, treatment, y = sample_data_four_treatments + model = SLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + + te = model.predict(X) + assert te.shape == (X.shape[0], N_TREATMENTS_FOUR) + assert np.isfinite(te).all() + + def test_predict_ignores_extra_kwargs(self, fitted_model): + """Extra kwargs (treatment, y) are silently ignored.""" + model, X = fitted_model + te = model.predict(X, treatment=None, y=None) + assert te.shape == (X.shape[0], N_TREATMENTS_TWO) + + +class TestShap: + """Tests for SHAP value computation.""" + + def test_get_shap_values_not_fitted_raises(self): + """Test get_shap_values raises error when model is not fitted.""" + model = SLearnerRegressor(control_name="control", learner=_make_lgbm()) + X = np.random.default_rng(0).normal(0, 1, (10, 3)) + with pytest.raises(ModelNotFittedError): + model.get_shap_values(X) + + def test_get_shap_values_returns_dict(self, fitted_model): + """Test get_shap_values returns a dict keyed by treatment group.""" + model, X = fitted_model + shap_dict = model.get_shap_values(X) + assert isinstance(shap_dict, dict) + assert set(shap_dict.keys()) == {"T1", "T2"} + + def test_get_shap_values_shape(self, fitted_model): + """SHAP arrays should be (n_samples, n_features) — no treatment indicator column.""" + model, X = fitted_model + shap_dict = model.get_shap_values(X) + for group in model.t_groups: + assert shap_dict[group].shape == X.shape + + def test_get_shap_values_four_treatments(self, sample_data_four_treatments): + """Test SHAP values with 4 treatment groups.""" + X, treatment, y = sample_data_four_treatments + model = SLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + + shap_dict = model.get_shap_values(X) + assert len(shap_dict) == N_TREATMENTS_FOUR + for group in model.t_groups: + assert shap_dict[group].shape == X.shape + + def test_plot_shap_values_runs(self, fitted_model): + """Test that plot_shap_values executes without error.""" + model, X = fitted_model + model.plot_shap_values(X, features=["f1", "f2", "f3"], show=False) + plt.close("all") + + def test_plot_shap_values_with_precomputed(self, fitted_model): + """Test plot_shap_values with pre-computed shap_dict.""" + model, X = fitted_model + shap_dict = model.get_shap_values(X) + model.plot_shap_values(X, shap_dict=shap_dict, show=False) + plt.close("all") + + def test_plot_shap_values_save(self, fitted_model, tmp_path): + """Test that save_dir creates plot files on disk.""" + model, X = fitted_model + save_dir = tmp_path / "shap_plots" + model.plot_shap_values(X, features=["f1", "f2", "f3"], show=False, save_dir=save_dir) + plt.close("all") + + assert save_dir.exists() + assert (save_dir / "shap_T1.png").exists() + assert (save_dir / "shap_T2.png").exists() diff --git a/tests/uplift/meta/test_tlearner.py b/tests/uplift/meta/test_tlearner.py new file mode 100644 index 0000000..4450926 --- /dev/null +++ b/tests/uplift/meta/test_tlearner.py @@ -0,0 +1,409 @@ +"""Tests for TLearnerRegressor.""" + +import numpy as np +import pytest +from lightgbm import LGBMRegressor +from matplotlib import pyplot as plt +from sklearn.linear_model import LinearRegression + +from multilift.exceptions import ModelNotFittedError +from multilift.uplift.meta import TLearnerRegressor + +DEFAULT_RANDOM_SEED = 42 +N_ESTIMATORS_SMALL = 10 +N_TREATMENTS_TWO = 2 +N_TREATMENTS_FOUR = 4 +MAX_DEPTH_SHALLOW = 3 +MAX_DEPTH_DEEP = 8 +MAX_DEPTH_RESOLVE = 7 + + +@pytest.fixture(scope="module") +def sample_data(): + """Create sample numpy data with 2 treatments + 1 control.""" + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n = 150 + + X = rng.normal(0, 1, (n, 3)) + treatment = rng.choice(["control", "T1", "T2"], n) + + # Outcome with different treatment effects + y = X[:, 0] + 0.5 * X[:, 1] + rng.normal(0, 0.1, n) + y[treatment == "T1"] += 0.3 + y[treatment == "T2"] += 0.5 + + return X, treatment, y + + +@pytest.fixture(scope="module") +def sample_data_four_treatments(): + """Create sample numpy data with 4 treatments + 1 control.""" + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n = 250 + + X = rng.normal(0, 1, (n, 3)) + treatment = rng.choice(["control", "T1", "T2", "T3", "T4"], n) + + y = X[:, 0] + rng.normal(0, 0.1, n) + y[treatment == "T1"] += 0.2 + y[treatment == "T2"] += 0.3 + y[treatment == "T3"] += 0.4 + y[treatment == "T4"] += 0.5 + + return X, treatment, y + + +def _make_lgbm(seed=DEFAULT_RANDOM_SEED, **kwargs): + """Create a small LGBMRegressor for testing.""" + return LGBMRegressor(random_state=seed, n_estimators=N_ESTIMATORS_SMALL, verbosity=-1, **kwargs) + + +class TestInit: + """Tests for TLearnerRegressor construction.""" + + def test_init_with_shared_learner(self): + """Test init with a single shared learner template.""" + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + assert model.control_name == "control" + assert not model.is_fitted + + def test_init_with_control_and_treatment_learners(self): + """Test init with separate control and treatment learners.""" + model = TLearnerRegressor( + control_name="control", + control_learner=_make_lgbm(), + treatment_learners=_make_lgbm(max_depth=4), + ) + assert model.control_name == "control" + + def test_init_with_per_treatment_dict(self): + """Test init with a per-treatment learner dict.""" + model = TLearnerRegressor( + control_name="control", + control_learner=_make_lgbm(), + treatment_learners={ + "T1": _make_lgbm(max_depth=3), + "T2": _make_lgbm(max_depth=5), + }, + ) + assert model.control_name == "control" + + def test_init_no_learner_raises(self): + """Test that providing no learner raises ValueError.""" + with pytest.raises(ValueError, match="Provide either"): + TLearnerRegressor(control_name="control") + + def test_init_only_control_learner_raises(self): + """Test that providing only control_learner raises ValueError.""" + with pytest.raises(ValueError, match="Provide either"): + TLearnerRegressor(control_name="control", control_learner=_make_lgbm()) + + def test_init_only_treatment_learners_raises(self): + """Test that providing only treatment_learners raises ValueError.""" + with pytest.raises(ValueError, match="Provide either"): + TLearnerRegressor(control_name="control", treatment_learners=_make_lgbm()) + + +class TestProperties: + """Tests for TLearnerRegressor properties.""" + + def test_t_groups_before_fit_raises(self): + """Test that accessing t_groups before fit raises error.""" + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + with pytest.raises(ModelNotFittedError): + _ = model.t_groups + + def test_is_fitted_false_before_fit(self): + """Test is_fitted is False before fitting.""" + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + assert not model.is_fitted + + def test_is_fitted_true_after_fit(self, sample_data): + """Test is_fitted is True after fitting.""" + X, treatment, y = sample_data + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + assert model.is_fitted + + def test_t_groups_sorted(self, sample_data): + """Test that t_groups returns sorted treatment names.""" + X, treatment, y = sample_data + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + assert list(model.t_groups) == ["T1", "T2"] + + +class TestFit: + """Tests for TLearnerRegressor.fit.""" + + def test_fit_shared_learner(self, sample_data): + """Test fit with a shared learner template.""" + X, treatment, y = sample_data + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + result = model.fit(X, treatment, y) + + assert result is model + assert model.model_c is not None + assert len(model.models_t) == N_TREATMENTS_TWO + assert set(model.models_t.keys()) == {"T1", "T2"} + + def test_fit_separate_control_and_treatment(self, sample_data): + """Test fit with separate control and treatment learners.""" + X, treatment, y = sample_data + model = TLearnerRegressor( + control_name="control", + control_learner=_make_lgbm(max_depth=3), + treatment_learners=_make_lgbm(max_depth=6), + ) + model.fit(X, treatment, y) + + assert model.is_fitted + assert len(model.models_t) == N_TREATMENTS_TWO + + def test_fit_per_treatment_dict(self, sample_data): + """Test fit with per-treatment learner dict.""" + X, treatment, y = sample_data + model = TLearnerRegressor( + control_name="control", + control_learner=_make_lgbm(), + treatment_learners={ + "T1": _make_lgbm(max_depth=3), + "T2": _make_lgbm(max_depth=6), + }, + ) + model.fit(X, treatment, y) + + assert model.is_fitted + assert len(model.models_t) == N_TREATMENTS_TWO + + def test_fit_four_treatments(self, sample_data_four_treatments): + """Test fit with 4 treatments yields 5 total models.""" + X, treatment, y = sample_data_four_treatments + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + + # 1 control + 4 treatment = 5 models + assert model.model_c is not None + assert len(model.models_t) == N_TREATMENTS_FOUR + assert list(model.t_groups) == ["T1", "T2", "T3", "T4"] + + def test_fit_single_control_model(self, sample_data): + """Verify only one control model is trained (not one per treatment).""" + X, treatment, y = sample_data + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + + # model_c is a single estimator, not a dict + assert not isinstance(model.model_c, dict) + assert hasattr(model.model_c, "predict") + + def test_fit_missing_treatment_in_dict_with_fallback(self, sample_data): + """When dict is missing a key but learner is set, falls back.""" + X, treatment, y = sample_data + model = TLearnerRegressor( + control_name="control", + learner=_make_lgbm(), + control_learner=_make_lgbm(), + treatment_learners={ + "T1": _make_lgbm(max_depth=3), + # T2 missing — should fall back to learner + }, + ) + model.fit(X, treatment, y) + + assert model.is_fitted + assert "T2" in model.models_t + + def test_fit_missing_treatment_in_dict_no_fallback_raises(self): + """When dict is missing a key and no fallback learner, raises.""" + model = TLearnerRegressor( + control_name="control", + control_learner=_make_lgbm(), + treatment_learners={ + "T1": _make_lgbm(), + # T2 missing and no fallback learner + }, + ) + + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + X = rng.normal(0, 1, (60, 2)) + treatment = rng.choice(["control", "T1", "T2"], 60) + y = rng.normal(0, 1, 60) + + with pytest.raises(ValueError, match="No learner found for treatment group"): + model.fit(X, treatment, y) + + +class TestPredict: + """Tests for TLearnerRegressor.predict.""" + + def test_predict_not_fitted_raises(self): + """Test predict raises error when model is not fitted.""" + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + X = np.random.default_rng(0).normal(0, 1, (10, 3)) + with pytest.raises(ModelNotFittedError): + model.predict(X) + + def test_predict_shape(self, sample_data): + """Test predict returns correct shape.""" + X, treatment, y = sample_data + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + + te = model.predict(X) + + assert te.shape == (X.shape[0], N_TREATMENTS_TWO) + assert np.isfinite(te).all() + + def test_predict_four_treatments(self, sample_data_four_treatments): + """Test predict with 4 treatment groups.""" + X, treatment, y = sample_data_four_treatments + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + + te = model.predict(X) + + assert te.shape == (X.shape[0], N_TREATMENTS_FOUR) + assert np.isfinite(te).all() + + def test_predict_per_treatment_params_produces_valid_output(self, sample_data): + """Per-treatment learners with independent params produce valid predictions.""" + X, treatment, y = sample_data + + model = TLearnerRegressor( + control_name="control", + control_learner=_make_lgbm(), + treatment_learners={ + "T1": _make_lgbm(max_depth=MAX_DEPTH_SHALLOW), + "T2": _make_lgbm(max_depth=MAX_DEPTH_DEEP), + }, + ) + model.fit(X, treatment, y) + te = model.predict(X) + + assert te.shape == (X.shape[0], N_TREATMENTS_TWO) + assert np.isfinite(te).all() + + # Verify the treatment models actually have different hyperparams + assert model.models_t["T1"].max_depth == MAX_DEPTH_SHALLOW + assert model.models_t["T2"].max_depth == MAX_DEPTH_DEEP + + +class TestShap: + """Tests for SHAP value computation.""" + + def test_get_shap_values_not_fitted_raises(self): + """Test get_shap_values raises error when model is not fitted.""" + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + X = np.random.default_rng(0).normal(0, 1, (10, 3)) + with pytest.raises(ModelNotFittedError): + model.get_shap_values(X) + + def test_get_shap_values_returns_dict(self, sample_data): + """Test get_shap_values returns a dict keyed by treatment group.""" + X, treatment, y = sample_data + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + + shap_dict = model.get_shap_values(X) + + assert isinstance(shap_dict, dict) + assert set(shap_dict.keys()) == {"T1", "T2"} + + def test_get_shap_values_shape(self, sample_data): + """Test that each SHAP array has shape (n_samples, n_features).""" + X, treatment, y = sample_data + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + + shap_dict = model.get_shap_values(X) + + for group in model.t_groups: + assert shap_dict[group].shape == X.shape + + def test_get_shap_values_four_treatments(self, sample_data_four_treatments): + """Test SHAP values with 4 treatment groups.""" + X, treatment, y = sample_data_four_treatments + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + + shap_dict = model.get_shap_values(X) + + assert len(shap_dict) == N_TREATMENTS_FOUR + for group in model.t_groups: + assert shap_dict[group].shape == X.shape + + def test_plot_shap_values_runs(self, sample_data): + """Test that plot_shap_values executes without error.""" + X, treatment, y = sample_data + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + + # Should not raise + model.plot_shap_values(X, features=["f1", "f2", "f3"]) + plt.close("all") + + def test_plot_shap_values_with_precomputed(self, sample_data): + """Test plot_shap_values with pre-computed shap_dict.""" + X, treatment, y = sample_data + model = TLearnerRegressor(control_name="control", learner=_make_lgbm()) + model.fit(X, treatment, y) + + shap_dict = model.get_shap_values(X) + # Should reuse pre-computed values, not recompute + model.plot_shap_values(X, shap_dict=shap_dict) + plt.close("all") + + +class TestLearnerResolution: + """Tests for the internal learner resolution logic.""" + + def test_resolve_control_uses_control_learner_over_default(self): + """Test control_learner takes priority over learner.""" + default = LinearRegression() + control = _make_lgbm() + model = TLearnerRegressor(control_name="control", learner=default, control_learner=control) + resolved = model._resolve_control_learner() + assert isinstance(resolved, LGBMRegressor) + + def test_resolve_control_falls_back_to_learner(self): + """Test control falls back to shared learner when no override.""" + default = _make_lgbm() + model = TLearnerRegressor(control_name="control", learner=default) + resolved = model._resolve_control_learner() + assert isinstance(resolved, LGBMRegressor) + + def test_resolve_treatment_uses_dict_entry(self): + """Test treatment resolution picks the matching dict entry.""" + model = TLearnerRegressor( + control_name="control", + control_learner=_make_lgbm(), + treatment_learners={ + "T1": LinearRegression(), + "T2": _make_lgbm(), + }, + ) + resolved = model._resolve_treatment_learner("T1") + assert isinstance(resolved, LinearRegression) + + def test_resolve_treatment_single_estimator(self): + """Test treatment resolution clones a single estimator template.""" + template = _make_lgbm(max_depth=MAX_DEPTH_RESOLVE) + model = TLearnerRegressor( + control_name="control", + control_learner=_make_lgbm(), + treatment_learners=template, + ) + resolved = model._resolve_treatment_learner("T1") + assert isinstance(resolved, LGBMRegressor) + assert resolved.max_depth == MAX_DEPTH_RESOLVE + + def test_resolve_returns_clone_not_same_instance(self): + """Test that resolved learners are clones, not the same object.""" + template = _make_lgbm() + model = TLearnerRegressor(control_name="control", learner=template) + + r1 = model._resolve_treatment_learner("T1") + r2 = model._resolve_treatment_learner("T2") + assert r1 is not r2 + assert r1 is not template diff --git a/tests/uplift/test_uplift_classifier.py b/tests/uplift/test_uplift_classifier.py new file mode 100644 index 0000000..30ebb24 --- /dev/null +++ b/tests/uplift/test_uplift_classifier.py @@ -0,0 +1,1707 @@ +import tempfile +import warnings +from pathlib import Path +from unittest.mock import patch + +import numpy as np +import pandas as pd +import pytest +from matplotlib import pyplot as plt + +from multilift.exceptions import ModelNotFittedError +from multilift.preproc import OneHotPreprocessor +from multilift.uplift.classifier import UpliftClassifierPipeline +from multilift.uplift.meta import SLearnerClassifier, TLearnerClassifier + +# Test constants +DEFAULT_RANDOM_SEED = 42 +TREATMENT_2_VALUE = 2 +TREATMENT_3_VALUE = 3 +TEST_SUBSET_SIZE = 10 + + +@pytest.fixture(scope="module") +def sample_data(): + """Create sample data for testing with binary outcome.""" + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n_samples = 100 + + # Features + X = pd.DataFrame( + { + "feature1": rng.normal(0, 1, n_samples), + "feature2": rng.normal(0, 1, n_samples), + "categorical": rng.choice(["A", "B", "C"], n_samples), + "binary": rng.choice([0, 1], n_samples), + } + ) + + # Treatments (control=0, treatment1=1, treatment2=2) + t = pd.Series(rng.choice([0, 1, 2], n_samples)) + + # Binary outcomes - make treatment effect visible + # Use logistic probability for conversion + base_prob = 1 / (1 + np.exp(-(X["feature1"] + 0.5 * X["feature2"]))) + treatment_effect1 = np.where(t == 1, 0.1, 0) # positive effect for treatment 1 + treatment_effect2 = np.where(t == TREATMENT_2_VALUE, 0.15, 0) # positive effect for treatment 2 + prob = np.clip(base_prob + treatment_effect1 + treatment_effect2, 0, 1) + y = pd.Series((rng.random(n_samples) < prob).astype(int)) + + # Map treatments to names + t_named = t.map({0: "control", 1: "treatment_A", 2: "treatment_B"}) + + return X, t_named, y + + +@pytest.fixture(scope="module") +def sample_data_three_treatments(): + """Create sample data with three treatments for testing with binary outcome.""" + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n_samples = 100 + + # Features + X = pd.DataFrame( + { + "feature1": rng.normal(0, 1, n_samples), + "feature2": rng.normal(0, 1, n_samples), + "categorical": rng.choice(["A", "B", "C"], n_samples), + "binary": rng.choice([0, 1], n_samples), + } + ) + + # Treatments (control=0, treatment1=1, treatment2=2, treatment3=3) + t = pd.Series(rng.choice([0, 1, 2, 3], n_samples)) + + # Binary outcomes - make treatment effect visible + base_prob = 1 / (1 + np.exp(-(X["feature1"] + 0.5 * X["feature2"]))) + treatment_effect1 = np.where(t == 1, 0.1, 0) + treatment_effect2 = np.where(t == TREATMENT_2_VALUE, 0.15, 0) + treatment_effect3 = np.where(t == TREATMENT_3_VALUE, 0.2, 0) + prob = np.clip(base_prob + treatment_effect1 + treatment_effect2 + treatment_effect3, 0, 1) + y = pd.Series((rng.random(n_samples) < prob).astype(int)) + + # Map treatments to names + t_named = t.map( + { + 0: "control", + 1: "treatment_A", + TREATMENT_2_VALUE: "treatment_B", + TREATMENT_3_VALUE: "treatment_C", + } + ) + + return X, t_named, y + + +@pytest.fixture(scope="module") +def fitted_pipeline(sample_data): + """Create a fitted pipeline for testing.""" + X, t, y = sample_data + pipeline = UpliftClassifierPipeline( + "control", + "treatment_A", + "treatment_B", + random_seed=DEFAULT_RANDOM_SEED, + n_estimators=10, # Small for faster tests + ) + pipeline.fit(X, t, y) + return pipeline + + +@pytest.fixture(scope="module") +def fitted_t_pipeline(sample_data): + """Create a fitted T-learner pipeline for testing.""" + X, t, y = sample_data + pipeline = UpliftClassifierPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="T", + random_seed=DEFAULT_RANDOM_SEED, + n_estimators=10, # Small for faster tests + ) + pipeline.fit(X, t, y) + return pipeline + + +class TestUpliftClassifierPipeline: + """Test suite for UpliftClassifierPipeline.""" + + def test_init_basic(self): + """Test basic initialization.""" + pipeline = UpliftClassifierPipeline("control", "treatment_A") + + assert pipeline._control_name == "control" + assert pipeline._treatment_names == ["treatment_A"] + assert pipeline._keep_cols is None + assert pipeline._drop_cols is None + assert pipeline._random_seed == DEFAULT_RANDOM_SEED + assert pipeline._model is None + assert pipeline._preprocessor is None + + def test_init_with_parameters(self): + """Test initialization with parameters.""" + test_seed = 123 + test_estimators = 100 + test_lr = 0.05 + pipeline = UpliftClassifierPipeline( + "control", + "treatment_A", + "treatment_B", + keep_cols=["col1", "col2"], + drop_cols=["col3"], + random_seed=test_seed, + model_type="S", + n_estimators=test_estimators, + learning_rate=test_lr, + ) + + assert pipeline._control_name == "control" + assert pipeline._treatment_names == ["treatment_A", "treatment_B"] + assert pipeline._keep_cols == ["col1", "col2"] + assert pipeline._drop_cols == ["col3"] + assert pipeline._random_seed == test_seed + assert pipeline._model_type == "S" + assert pipeline._model_params["n_estimators"] == test_estimators + assert pipeline._model_params["learning_rate"] == test_lr + + def test_init_random_state_warning(self, caplog): + """Test that random_state in model_params triggers warning.""" + UpliftClassifierPipeline( + "control", "treatment_A", random_state=999, random_seed=DEFAULT_RANDOM_SEED + ) + + # Check that warning was logged + assert "Random seed is set in model_params" in caplog.text + + def test_init_model_type_t(self): + """Test initialization with T-learner model type.""" + pipeline = UpliftClassifierPipeline("control", "treatment_A", "treatment_B", model_type="T") + assert pipeline._model_type == "T" + + def test_init_model_type_default(self): + """Test that default model type is S.""" + pipeline = UpliftClassifierPipeline("control", "treatment_A") + assert pipeline._model_type == "S" + + def test_init_with_preprocessor(self, sample_data): + """Test initialization with a pre-fitted preprocessor.""" + X, _, _ = sample_data + preprocessor = OneHotPreprocessor() + preprocessor.fit(X) + + pipeline = UpliftClassifierPipeline("control", "treatment_A", preprocessor=preprocessor) + + assert pipeline._preprocessor is preprocessor + assert pipeline._preprocessor.is_fitted + + def test_init_lbm_verbosity(self): + """Test initialization with lbm_verbosity parameter.""" + pipeline = UpliftClassifierPipeline("control", "treatment_A", lbm_verbosity=0) + assert pipeline._lbm_verbosity == 0 + + def test_init_lbm_verbosity_default(self): + """Test default lbm_verbosity is -1.""" + pipeline = UpliftClassifierPipeline("control", "treatment_A") + assert pipeline._lbm_verbosity == -1 + + def test_repr(self): + """Test string representation.""" + pipeline = UpliftClassifierPipeline("control", "treatment_A", "treatment_B") + repr_str = repr(pipeline) + + assert "UpliftClassifierPipeline" in repr_str + assert "control" in repr_str + assert "treatment_A" in repr_str + assert "treatment_B" in repr_str + + def test_properties_before_fitting(self): + """Test properties before fitting.""" + pipeline = UpliftClassifierPipeline("control", "treatment_A") + + assert pipeline.model is None + assert pipeline.preprocessor is None + assert pipeline.control_name == "control" + assert pipeline.treatment_names == ["treatment_A"] + + def test_properties_after_fitting(self, fitted_pipeline): + """Test properties after fitting.""" + assert fitted_pipeline.model is not None + assert fitted_pipeline.preprocessor is not None + assert isinstance(fitted_pipeline.preprocessor, OneHotPreprocessor) + assert fitted_pipeline.control_name == "control" + assert fitted_pipeline.treatment_names == ["treatment_A", "treatment_B"] + + def test_get_feature_names(self, fitted_pipeline): + """Test get_feature_names method with raw parameter.""" + # Raw feature names (default) + raw_names = fitted_pipeline.get_feature_names() + assert isinstance(raw_names, list) + assert len(raw_names) > 0 + + # Transformed feature names + transformed_names = fitted_pipeline.get_feature_names(raw=False) + assert isinstance(transformed_names, list) + assert len(transformed_names) > 0 + + def test_preprocess_training(self, sample_data): + """Test preprocessing during training.""" + X, _, _ = sample_data + pipeline = UpliftClassifierPipeline("control", "treatment_A") + + # First preprocessing should create and fit preprocessor + X_processed = pipeline.preprocess(X, training=True) + + assert pipeline._preprocessor is not None + assert isinstance(X_processed, pd.DataFrame) + assert X_processed.shape[0] == X.shape[0] # Same number of rows + + def test_preprocess_inference(self, fitted_pipeline, sample_data): + """Test preprocessing during inference.""" + X, _, _ = sample_data + X_new = X.head(TEST_SUBSET_SIZE) # Subset for inference + + X_processed = fitted_pipeline.preprocess(X_new, training=False) + + assert isinstance(X_processed, pd.DataFrame) + assert X_processed.shape[0] == TEST_SUBSET_SIZE + + def test_preprocess_inference_not_fitted(self, sample_data): + """Test preprocessing during inference.""" + X, t, y = sample_data + X_new = X.head(TEST_SUBSET_SIZE) # Subset for inference + + pipeline = UpliftClassifierPipeline( + "control", + "treatment_A", + "treatment_B", + random_seed=DEFAULT_RANDOM_SEED, + n_estimators=10, + ) + pipeline.fit(X, t, y) + pipeline.preprocessor = None + with pytest.raises(ModelNotFittedError, match="Preprocessor is not fitted"): + pipeline.preprocess(X_new, training=False) + + def test_preprocess_with_prefitted_preprocessor(self, sample_data): + """Test that preprocess doesn't refit an already fitted preprocessor.""" + X, _, _ = sample_data + preprocessor = OneHotPreprocessor() + preprocessor.fit(X) + + pipeline = UpliftClassifierPipeline("control", "treatment_A", preprocessor=preprocessor) + + # Should use the pre-fitted preprocessor without refitting + X_processed = pipeline.preprocess(X, training=True) + assert isinstance(X_processed, pd.DataFrame) + assert X_processed.shape[0] == X.shape[0] + + def test_fit(self, sample_data): + """Test fit method.""" + X, t, y = sample_data + pipeline = UpliftClassifierPipeline( + "control", "treatment_A", "treatment_B", random_seed=DEFAULT_RANDOM_SEED + ) + + result = pipeline.fit(X, t, y) + + # Should return self + assert result is pipeline + assert pipeline._model is not None + assert pipeline._preprocessor is not None + + def test_fit_uses_native_s_learner(self, fitted_pipeline): + """Test that fit creates a native SLearnerClassifier.""" + assert isinstance(fitted_pipeline._model, SLearnerClassifier) + + def test_fit_t_learner(self, sample_data): + """Test fit method with T-learner.""" + X, t, y = sample_data + pipeline = UpliftClassifierPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="T", + random_seed=DEFAULT_RANDOM_SEED, + ) + + result = pipeline.fit(X, t, y) + + # Should return self + assert result is pipeline + assert pipeline._model is not None + assert pipeline._preprocessor is not None + assert isinstance(pipeline._model, TLearnerClassifier) + + def test_fit_t_learner_separate_params(self, sample_data): + """Test fit method with T-learner with separate learner parameters.""" + X, t, y = sample_data + pipeline = UpliftClassifierPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="T", + random_seed=DEFAULT_RANDOM_SEED, + control_learner_params={"n_estimators": 50, "learning_rate": 0.05}, + treatment_learner_params={"n_estimators": 100, "learning_rate": 0.1}, + ) + + result = pipeline.fit(X, t, y) + + # Should return self and create T-learner + assert result is pipeline + assert pipeline._model is not None + assert isinstance(pipeline._model, TLearnerClassifier) + + def test_fit_t_learner_per_treatment_params(self, sample_data): + """Test fit method with T-learner with per-treatment hyperparameters.""" + X, t, y = sample_data + pipeline = UpliftClassifierPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="T", + random_seed=DEFAULT_RANDOM_SEED, + control_learner_params={"n_estimators": 50}, + treatment_learner_params={ + "treatment_A": {"n_estimators": 30, "learning_rate": 0.05}, + "treatment_B": {"n_estimators": 60, "learning_rate": 0.1}, + }, + ) + + result = pipeline.fit(X, t, y) + + assert result is pipeline + assert pipeline._model is not None + assert isinstance(pipeline._model, TLearnerClassifier) + + # Verify predictions work + predictions = pipeline.predict(X) + assert predictions.shape == (X.shape[0], 2) + + def test_fit_x_learner_not_implemented(self, sample_data): + """Test that X-learner raises NotImplementedError.""" + X, t, y = sample_data + pipeline = UpliftClassifierPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="X", + random_seed=DEFAULT_RANDOM_SEED, + ) + + with pytest.raises(NotImplementedError, match="X-Learner is not implemented yet"): + pipeline.fit(X, t, y) + + def test_fit_invalid_model_type(self, sample_data): + """Test that invalid model_type raises ValueError.""" + X, t, y = sample_data + pipeline = UpliftClassifierPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="INVALID", + random_seed=DEFAULT_RANDOM_SEED, + ) + + with pytest.raises(ValueError, match="Invalid model type: INVALID"): + pipeline.fit(X, t, y) + + def test_predict_unfitted_raises_error(self, sample_data): + """Test that predict raises error when model is not fitted.""" + X, _, _ = sample_data + pipeline = UpliftClassifierPipeline("control", "treatment_A") + + with pytest.raises(ModelNotFittedError, match="Model is not fitted"): + pipeline.predict(X) + + def test_predict_fitted(self, fitted_pipeline, sample_data): + """Test predict method with fitted model.""" + X, _, _ = sample_data + + predictions = fitted_pipeline.predict(X) + + assert isinstance(predictions, pd.DataFrame) + assert predictions.shape == (X.shape[0], 2) # 2 treatments + assert np.isfinite(predictions.values).all() # All predictions should be finite + + def test_predict_t_learner(self, fitted_t_pipeline, sample_data): + """Test predict method with T-learner.""" + X, _, _ = sample_data + + predictions = fitted_t_pipeline.predict(X) + + assert isinstance(predictions, pd.DataFrame) + assert predictions.shape == (X.shape[0], 2) # 2 treatments + assert np.isfinite(predictions.values).all() # All predictions should be finite + + def test_predict_with_treatment_idx(self, fitted_pipeline, sample_data): + """Test predict method with treatment_idx parameter.""" + X, _, _ = sample_data + + # Predict for first treatment only + predictions = fitted_pipeline.predict(X, treatment_idx=0) + + assert isinstance(predictions, pd.DataFrame) + assert predictions.shape == (X.shape[0], 1) + assert predictions.columns.tolist() == ["treatment_A"] + assert np.isfinite(predictions.values).all() + + def test_predict_with_treatment_indices(self, fitted_pipeline, sample_data): + """Test predict method with treatment_indices parameter.""" + X, _, _ = sample_data + + predictions = fitted_pipeline.predict(X, treatment_indices=[0]) + + assert isinstance(predictions, pd.DataFrame) + assert predictions.shape == (X.shape[0], 1) + assert predictions.columns.tolist() == ["treatment_A"] + assert np.isfinite(predictions.values).all() + + # Multiple indices + predictions_multi = fitted_pipeline.predict(X, treatment_indices=[0, 1]) + + assert predictions_multi.shape == (X.shape[0], 2) + assert predictions_multi.columns.tolist() == ["treatment_A", "treatment_B"] + + def test_predict_mutual_exclusion(self, fitted_pipeline, sample_data): + """Test that treatment_idx and treatment_indices are mutually exclusive.""" + X, _, _ = sample_data + + with pytest.raises(ValueError, match="Only one of treatment_idx or treatment_indices"): + fitted_pipeline.predict(X, treatment_idx=0, treatment_indices=[0]) + + def test_predict_with_invalid_treatment_idx(self, fitted_pipeline, sample_data): + """Test predict method raises error for invalid treatment_idx.""" + X, _, _ = sample_data + + with pytest.raises(IndexError, match="Invalid treatment indices"): + fitted_pipeline.predict(X, treatment_idx=5) + + with pytest.raises(IndexError, match="Invalid treatment indices"): + fitted_pipeline.predict(X, treatment_idx=-1) + + def test_policy_unfitted_raises_error(self, sample_data): + """Test that policy raises error when model is not fitted.""" + X, _, _ = sample_data + pipeline = UpliftClassifierPipeline("control", "treatment_A") + + with pytest.raises(ModelNotFittedError, match="Model is not fitted"): + pipeline.policy(X) + + def test_policy_with_three_treatments(self, sample_data_three_treatments): + """Test that policy works correctly with three treatments.""" + X, t, y = sample_data_three_treatments + pipeline = UpliftClassifierPipeline("control", "treatment_A", "treatment_B", "treatment_C") + pipeline.fit(X, t, y) + + result_df = pipeline.policy(X) + + # Should return a DataFrame with all treatments + assert isinstance(result_df, pd.DataFrame) + assert len(result_df) == X.shape[0] + + # Check expected columns: 3 treatment uplifts + max_uplift + policy + expected_cols = {"treatment_A", "treatment_B", "treatment_C", "max_uplift", "policy"} + assert set(result_df.columns) == expected_cols + + # Check policy column contains valid recommendations + unique_policies = set(result_df["policy"]) + expected_policies = {"control", "treatment_A", "treatment_B", "treatment_C"} + assert unique_policies.issubset(expected_policies) + + def test_policy_fitted(self, fitted_pipeline, sample_data): + """Test policy method with fitted model.""" + X, _, _ = sample_data + + result_df = fitted_pipeline.policy(X) + + # Should return a DataFrame + assert isinstance(result_df, pd.DataFrame) + assert len(result_df) == X.shape[0] + + # Check expected columns: treatment uplifts + max_uplift + policy + expected_cols = {"treatment_A", "treatment_B", "max_uplift", "policy"} + assert set(result_df.columns) == expected_cols + + # Check policy column contains valid recommendations + unique_policies = set(result_df["policy"]) + expected_policies = {"control", "treatment_A", "treatment_B"} + assert unique_policies.issubset(expected_policies) + + # Check that max_uplift is non-negative (or zero if no positive uplift) + assert (result_df["max_uplift"] >= 0).all() + + def test_policy_with_custom_parameters(self, fitted_pipeline, sample_data): + """Test policy method with custom control_name and recipe_names.""" + X, _, _ = sample_data + custom_control = "custom_control" + custom_recipes = ["recipe_1", "recipe_2"] + + result_df = fitted_pipeline.policy( + X, control_name=custom_control, recipe_names=custom_recipes + ) + + # Check that custom recipe names are used as column names + expected_cols = {"recipe_1", "recipe_2", "max_uplift", "policy"} + assert set(result_df.columns) == expected_cols + + # Check that custom control name can appear in policies + unique_policies = set(result_df["policy"]) + expected_policies = {"custom_control", "recipe_1", "recipe_2"} + assert unique_policies.issubset(expected_policies) + + def test_policy_decision_logic(self, fitted_pipeline, sample_data): + """Test that policy makes correct decisions based on uplift values.""" + X, _, _ = sample_data + + result_df = fitted_pipeline.policy(X) + + # For each row, verify the policy logic + for idx, row in result_df.iterrows(): + treatment_a_uplift = row["treatment_A"] + treatment_b_uplift = row["treatment_B"] + max_uplift = row["max_uplift"] + policy = row["policy"] + + # Max uplift should be the maximum of positive uplifts or 0 + expected_max = max(0, treatment_a_uplift, treatment_b_uplift) + assert np.isclose(max_uplift, expected_max), f"Row {idx}: max_uplift mismatch" + + # Policy logic verification + if max_uplift == 0: + # No positive uplift, should recommend control + assert policy == "control" + elif treatment_a_uplift >= treatment_b_uplift and treatment_a_uplift > 0: + # Treatment A has highest positive uplift + assert policy == "treatment_A" + elif treatment_b_uplift > treatment_a_uplift and treatment_b_uplift > 0: + # Treatment B has highest positive uplift + assert policy == "treatment_B" + + def test_policy_single_treatment(self): + """Test policy method with a single treatment.""" + # Create data with single treatment + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n_samples = 100 + X = pd.DataFrame( + { + "feature1": rng.normal(0, 1, n_samples), + "feature2": rng.normal(0, 1, n_samples), + "categorical": rng.choice(["A", "B", "C"], n_samples), + } + ) + t = pd.Series(rng.choice([0, 1], n_samples)).map({0: "control", 1: "treatment_A"}) + base_prob = 1 / (1 + np.exp(-(X["feature1"] + 0.5 * X["feature2"]))) + treatment_effect = np.where(t == "treatment_A", 0.1, 0) + prob = np.clip(base_prob + treatment_effect, 0, 1) + y = pd.Series((rng.random(n_samples) < prob).astype(int)) + + # Create pipeline with only 1 treatment + pipeline = UpliftClassifierPipeline( + "control", "treatment_A", random_seed=DEFAULT_RANDOM_SEED, n_estimators=10 + ) + pipeline.fit(X, t, y) + + result_df = pipeline.policy(X) + + # Should return a DataFrame + assert isinstance(result_df, pd.DataFrame) + assert len(result_df) == X.shape[0] + + # Check expected columns: treatment uplift + max_uplift + policy + expected_cols = {"treatment_A", "max_uplift", "policy"} + assert set(result_df.columns) == expected_cols + + # Check policy column contains valid recommendations + unique_policies = set(result_df["policy"]) + expected_policies = {"control", "treatment_A"} + assert unique_policies.issubset(expected_policies) + + # Check that max_uplift is non-negative (or zero if no positive uplift) + assert (result_df["max_uplift"] >= 0).all() + + def test_policy_single_treatment_decision_logic(self): + """Test that single treatment policy makes correct decisions based on uplift values.""" + # Create data with single treatment + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n_samples = 100 + X = pd.DataFrame( + { + "feature1": rng.normal(0, 1, n_samples), + "feature2": rng.normal(0, 1, n_samples), + "categorical": rng.choice(["A", "B", "C"], n_samples), + } + ) + t = pd.Series(rng.choice([0, 1], n_samples)).map({0: "control", 1: "treatment_A"}) + base_prob = 1 / (1 + np.exp(-(X["feature1"] + 0.5 * X["feature2"]))) + treatment_effect = np.where(t == "treatment_A", 0.1, 0) + prob = np.clip(base_prob + treatment_effect, 0, 1) + y = pd.Series((rng.random(n_samples) < prob).astype(int)) + + pipeline = UpliftClassifierPipeline( + "control", "treatment_A", random_seed=DEFAULT_RANDOM_SEED, n_estimators=10 + ) + pipeline.fit(X, t, y) + + result_df = pipeline.policy(X) + + # For each row, verify the policy logic + for idx, row in result_df.iterrows(): + treatment_uplift = row["treatment_A"] + max_uplift = row["max_uplift"] + policy = row["policy"] + + # Max uplift should be the maximum of treatment uplift and 0 + expected_max = max(0, treatment_uplift) + assert np.isclose(max_uplift, expected_max), f"Row {idx}: max_uplift mismatch" + + # Policy logic verification for single treatment + if treatment_uplift > 0: + assert policy == "treatment_A", f"Row {idx}: expected treatment_A" + else: + assert policy == "control", f"Row {idx}: expected control" + + def test_policy_threshold_negative_raises_error(self, fitted_pipeline, sample_data): + """Test that policy raises error for negative threshold.""" + X, _, _ = sample_data + + with pytest.raises(ValueError, match="Threshold must be non-negative"): + fitted_pipeline.policy(X, threshold=-0.1) + + def test_policy_per_recipe_threshold(self, fitted_pipeline, sample_data): + """Test policy with per-recipe threshold dict.""" + X, _, _ = sample_data + + threshold = {"treatment_A": 0.05, "treatment_B": 0.1} + result_df = fitted_pipeline.policy(X, threshold=threshold) + + assert isinstance(result_df, pd.DataFrame) + assert len(result_df) == X.shape[0] + expected_cols = {"treatment_A", "treatment_B", "max_uplift", "policy"} + assert set(result_df.columns) == expected_cols + + # Check policies are valid + unique_policies = set(result_df["policy"]) + assert unique_policies.issubset({"control", "treatment_A", "treatment_B"}) + + def test_policy_per_recipe_threshold_unknown_name(self, fitted_pipeline, sample_data): + """Test that unknown recipe names in threshold dict raises error.""" + X, _, _ = sample_data + + with pytest.raises(ValueError, match="Unknown recipe names in threshold"): + fitted_pipeline.policy(X, threshold={"unknown_recipe": 0.1}) + + def test_policy_per_recipe_threshold_negative_value(self, fitted_pipeline, sample_data): + """Test that negative values in threshold dict raises error.""" + X, _, _ = sample_data + + with pytest.raises(ValueError, match="All threshold values must be non-negative"): + fitted_pipeline.policy(X, threshold={"treatment_A": -0.1}) + + def test_policy_threshold_two_treatments(self, fitted_pipeline, sample_data): + """Test policy with threshold for two treatments.""" + X, _, _ = sample_data + + # Get results with default threshold (0.0) + result_default = fitted_pipeline.policy(X) + + # Get results with a higher threshold + threshold = 0.1 + result_with_threshold = fitted_pipeline.policy(X, threshold=threshold) + + # Both should have same columns + assert set(result_default.columns) == set(result_with_threshold.columns) + + # Verify threshold logic: with higher threshold, more rows should be control + control_count_default = (result_default["policy"] == "control").sum() + control_count_threshold = (result_with_threshold["policy"] == "control").sum() + assert control_count_threshold >= control_count_default + + # Verify decision logic for each row + for idx, row in result_with_threshold.iterrows(): + max_uplift = row["max_uplift"] + policy = row["policy"] + + if max_uplift <= threshold: + assert ( + policy == "control" + ), f"Row {idx}: expected control when max_uplift <= threshold" + + def test_policy_threshold_single_treatment(self): + """Test policy with threshold for single treatment.""" + # Create data with single treatment + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n_samples = 100 + X = pd.DataFrame( + { + "feature1": rng.normal(0, 1, n_samples), + "feature2": rng.normal(0, 1, n_samples), + "categorical": rng.choice(["A", "B", "C"], n_samples), + } + ) + t = pd.Series(rng.choice([0, 1], n_samples)).map({0: "control", 1: "treatment_A"}) + base_prob = 1 / (1 + np.exp(-(X["feature1"] + 0.5 * X["feature2"]))) + treatment_effect = np.where(t == "treatment_A", 0.1, 0) + prob = np.clip(base_prob + treatment_effect, 0, 1) + y = pd.Series((rng.random(n_samples) < prob).astype(int)) + + pipeline = UpliftClassifierPipeline( + "control", "treatment_A", random_seed=DEFAULT_RANDOM_SEED, n_estimators=10 + ) + pipeline.fit(X, t, y) + + # Get results with default threshold (0.0) + result_default = pipeline.policy(X) + + # Get results with a higher threshold + threshold = 0.05 + result_with_threshold = pipeline.policy(X, threshold=threshold) + + # With higher threshold, more rows should be control + control_count_default = (result_default["policy"] == "control").sum() + control_count_threshold = (result_with_threshold["policy"] == "control").sum() + assert control_count_threshold >= control_count_default + + # Verify decision logic for each row + for idx, row in result_with_threshold.iterrows(): + treatment_uplift = row["treatment_A"] + max_uplift = row["max_uplift"] + policy = row["policy"] + + # Max uplift should still be max(0, treatment_uplift) + expected_max = max(0, treatment_uplift) + assert np.isclose(max_uplift, expected_max), f"Row {idx}: max_uplift mismatch" + + # Policy logic with threshold + if treatment_uplift > threshold: + assert policy == "treatment_A", f"Row {idx}: expected treatment_A" + else: + assert policy == "control", f"Row {idx}: expected control" + + def test_policy_single_emits_deprecation_warning(self, fitted_pipeline, sample_data): + """Test that policy_single emits a DeprecationWarning.""" + X, _, _ = sample_data + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + fitted_pipeline.policy_single(X, treatment_idx=0) + deprecation_warnings = [x for x in w if issubclass(x.category, DeprecationWarning)] + assert len(deprecation_warnings) == 1 + assert "policy_single is deprecated" in str(deprecation_warnings[0].message) + + def test_policy_single(self, fitted_pipeline, sample_data): + """Test policy_single method delegates to policy_subset.""" + X, _, _ = sample_data + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + result_df = fitted_pipeline.policy_single(X, treatment_idx=0) + + assert isinstance(result_df, pd.DataFrame) + assert len(result_df) == X.shape[0] + assert set(result_df.columns) == {"treatment_A", "max_uplift", "policy"} + + unique_policies = set(result_df["policy"]) + assert unique_policies.issubset({"control", "treatment_A"}) + assert (result_df["max_uplift"] >= 0).all() + + def test_policy_single_with_threshold(self, fitted_pipeline, sample_data): + """Test policy_single method with threshold.""" + X, _, _ = sample_data + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + result_default = fitted_pipeline.policy_single(X, treatment_idx=0) + result_with_threshold = fitted_pipeline.policy_single(X, treatment_idx=0, threshold=0.1) + + # Higher threshold should result in more control recommendations + control_count_default = (result_default["policy"] == "control").sum() + control_count_threshold = (result_with_threshold["policy"] == "control").sum() + assert control_count_threshold >= control_count_default + + def test_policy_subset_single(self, fitted_pipeline, sample_data): + """Test policy_subset with a single treatment.""" + X, _, _ = sample_data + + result_df = fitted_pipeline.policy_subset(X, treatment_indices=[0]) + + assert isinstance(result_df, pd.DataFrame) + assert len(result_df) == X.shape[0] + assert set(result_df.columns) == {"treatment_A", "max_uplift", "policy"} + unique_policies = set(result_df["policy"]) + assert unique_policies.issubset({"control", "treatment_A"}) + + def test_policy_subset_multiple(self, fitted_pipeline, sample_data): + """Test policy_subset with multiple treatments.""" + X, _, _ = sample_data + + result_df = fitted_pipeline.policy_subset(X, treatment_indices=[0, 1]) + + assert isinstance(result_df, pd.DataFrame) + assert len(result_df) == X.shape[0] + assert set(result_df.columns) == {"treatment_A", "treatment_B", "max_uplift", "policy"} + + def test_policy_subset_with_threshold_dict(self, fitted_pipeline, sample_data): + """Test policy_subset with per-recipe threshold dict.""" + X, _, _ = sample_data + + result_df = fitted_pipeline.policy_subset( + X, + treatment_indices=[0, 1], + threshold={"treatment_A": 0.05, "treatment_B": 0.1}, + ) + + assert isinstance(result_df, pd.DataFrame) + assert len(result_df) == X.shape[0] + + def test_policy_subset_empty_raises_error(self, fitted_pipeline, sample_data): + """Test policy_subset raises error for empty treatment_indices.""" + X, _, _ = sample_data + + with pytest.raises(ValueError, match="treatment_indices cannot be empty"): + fitted_pipeline.policy_subset(X, treatment_indices=[]) + + def test_evaluate_unfitted_raises_error(self, sample_data): + """Test that evaluate raises error when model is not fitted.""" + X, t, y = sample_data + pipeline = UpliftClassifierPipeline("control", "treatment_A", "treatment_B") + + with pytest.raises(ModelNotFittedError, match="Model is not fitted"): + pipeline.evaluate(X, t, y) + + def test_evaluate_fitted(self, fitted_pipeline, sample_data): + """Test evaluate method with fitted model.""" + X, t, y = sample_data + + qini_auc, qini_df = fitted_pipeline.evaluate(X, t, y) + + assert isinstance(qini_auc, float) + assert isinstance(qini_df, pd.DataFrame) + assert np.isfinite(qini_auc) + assert not qini_df.empty + + def test_plot_unfitted_raises_error(self, sample_data): + """Test that plot raises error when model is not fitted.""" + X, t, y = sample_data + pipeline = UpliftClassifierPipeline("control", "treatment_A", "treatment_B") + + with pytest.raises(ModelNotFittedError, match="Model is not fitted"): + pipeline.plot(X, t, y) + + @patch("multilift.uplift.classifier.UpliftExploreEvaluator") + def test_plot_fitted(self, mock_evaluator_class, fitted_pipeline, sample_data): + """Test plot method with fitted model.""" + X, t, y = sample_data + + # Mock the evaluator instance and its method + mock_axes = plt.figure().add_subplot(111) + mock_evaluator = mock_evaluator_class.return_value + mock_evaluator.plot_binned_actual_uplift.return_value = mock_axes + + result = fitted_pipeline.plot(X, t, y, name="Test Plot") + + assert result is mock_axes + mock_evaluator.plot_binned_actual_uplift.assert_called_once() + # Check that title was passed correctly + _args, kwargs = mock_evaluator.plot_binned_actual_uplift.call_args + assert kwargs.get("title") == "Test Plot" + + def test_plot_with_treatment_names_filter(self, fitted_pipeline, sample_data): + """Test plot method with treatment_names subset filtering.""" + X, t, y = sample_data + + with patch("multilift.uplift.classifier.UpliftExploreEvaluator") as mock_evaluator_class: + mock_axes = plt.figure().add_subplot(111) + mock_evaluator = mock_evaluator_class.return_value + mock_evaluator.plot_binned_actual_uplift.return_value = mock_axes + + result = fitted_pipeline.plot(X, t, y, treatment_names=["treatment_A"]) + + assert result is mock_axes + mock_evaluator_class.assert_called_once_with("control", "treatment_A") + + def test_plot_invalid_treatment_names(self, fitted_pipeline, sample_data): + """Test plot raises error for invalid treatment_names.""" + X, t, y = sample_data + + with pytest.raises(ValueError, match="treatment_names must be a subset"): + fitted_pipeline.plot(X, t, y, treatment_names=["nonexistent"]) + + def test_shap_native(self, fitted_pipeline, sample_data): + """Test that native SHAP path works for SLearnerClassifier.""" + X, _, _ = sample_data + + shap_values = fitted_pipeline.shap(X, show=False) + + assert isinstance(shap_values, dict) + assert len(shap_values) > 0 + for key, values in shap_values.items(): + assert isinstance(values, np.ndarray) + assert values.shape[0] == X.shape[0] + + def test_shap_native_t_learner(self, fitted_t_pipeline, sample_data): + """Test that native SHAP path works for TLearnerClassifier.""" + X, _, _ = sample_data + + shap_values = fitted_t_pipeline.shap(X, show=False) + + assert isinstance(shap_values, dict) + assert len(shap_values) > 0 + for key, values in shap_values.items(): + assert isinstance(values, np.ndarray) + assert values.shape[0] == X.shape[0] + + def test_save_unfitted_raises_error(self, sample_data): + """Test that save raises error when model is not fitted.""" + pipeline = UpliftClassifierPipeline("control", "treatment_A", "treatment_B") + + with pytest.raises(ModelNotFittedError, match="Model is not fitted"): + pipeline.save("test_model.joblib", "1.0.0") + + def test_save_and_load(self, fitted_pipeline, sample_data): + """Test save and load functionality.""" + X, _, _ = sample_data + + # Test predictions before save + predictions_before = fitted_pipeline.predict(X) + + with tempfile.TemporaryDirectory() as temp_dir: + # Save model + model_path = Path(temp_dir) / "test_model.joblib" + saved_path = fitted_pipeline.save(model_path, "1.0.0") + + assert saved_path.exists() + assert saved_path == model_path + + # Load model + loaded_pipeline = UpliftClassifierPipeline.load(saved_path) + + # Test that loaded model has same configuration + assert loaded_pipeline._control_name == fitted_pipeline._control_name + assert loaded_pipeline._treatment_names == fitted_pipeline._treatment_names + assert loaded_pipeline._random_seed == fitted_pipeline._random_seed + + # Test that predictions are the same + predictions_after = loaded_pipeline.predict(X) + pd.testing.assert_frame_equal(predictions_before, predictions_after) + + def test_save_with_compression(self, fitted_pipeline): + """Test save with different compression levels.""" + with tempfile.TemporaryDirectory() as temp_dir: + # Test no compression + model_path1 = Path(temp_dir) / "model_no_compress" + fitted_pipeline.save(model_path1, version="1.0.0", compress=False) + + # Test high compression + model_path2 = Path(temp_dir) / "model_high_compress" + fitted_pipeline.save(model_path2, version="1.1.0", compress=9) + + assert model_path1.with_suffix(".joblib").exists() + assert model_path2.with_suffix(".joblib").exists() + + def test_save_creates_directory(self, fitted_pipeline): + """Test that save creates parent directories.""" + with tempfile.TemporaryDirectory() as temp_dir: + model_path = Path(temp_dir) / "nested" / "dir" / "model.joblib" + saved_path = fitted_pipeline.save(model_path, "1.0.0") + + assert saved_path.exists() + assert saved_path.parent.exists() + + def test_load_nonexistent_file(self): + """Test loading from non-existent file.""" + with pytest.raises(FileNotFoundError, match="Model file not found"): + UpliftClassifierPipeline.load("nonexistent_model.joblib") + + def test_load_corrupted_file(self): + """Test loading from corrupted file.""" + with tempfile.NamedTemporaryFile(suffix=".joblib", delete=False) as temp_file: + # Write invalid data + temp_file.write(b"corrupted data") + temp_file.flush() + + with pytest.raises(ValueError, match="Failed to load model"): + UpliftClassifierPipeline.load(temp_file.name) + + def test_property_setters(self): + """Test property setters.""" + pipeline = UpliftClassifierPipeline("control", "treatment_A") + + # Create mock objects + mock_preprocessor = OneHotPreprocessor() + from lightgbm import LGBMClassifier + + mock_s_model = SLearnerClassifier(learner=LGBMClassifier(), control_name="control") + mock_t_model = TLearnerClassifier(learner=LGBMClassifier(), control_name="control") + + # Test setters with S-learner + pipeline.preprocessor = mock_preprocessor + pipeline.model = mock_s_model + + assert pipeline.preprocessor is mock_preprocessor + assert pipeline.model is mock_s_model + + # Test setter with T-learner + pipeline.model = mock_t_model + assert pipeline.model is mock_t_model + + +class TestClassifierEdgeCases: + """Tests for edge cases in UpliftClassifierPipeline.""" + + def test_init_nested_list_treatment_names_raises(self): + """Test that nested list treatment names raises TypeError.""" + with pytest.raises(TypeError, match="Treatment_names should not be nested lists"): + UpliftClassifierPipeline("control", ["treatment_A"]) + + def test_version_property(self, sample_data): + """Test version property getter and setter.""" + X, t, y = sample_data + pipeline = UpliftClassifierPipeline( + "control", + "treatment_A", + "treatment_B", + random_seed=DEFAULT_RANDOM_SEED, + n_estimators=10, + ) + pipeline.fit(X, t, y) + assert pipeline.version is None + pipeline.version = "2.0.0" + assert pipeline.version == "2.0.0" + + def test_get_feature_names_no_preprocessor(self): + """Test get_feature_names raises when preprocessor is not initialized.""" + pipeline = UpliftClassifierPipeline("control", "treatment_A") + with pytest.raises(RuntimeError, match="Preprocess is not initialized"): + pipeline.get_feature_names() + + def test_policy_wrong_recipe_names_length(self, fitted_pipeline, sample_data): + """Test policy raises when recipe_names length doesn't match.""" + X, _, _ = sample_data + with pytest.raises(ValueError, match="Recipe names must match"): + fitted_pipeline.policy(X, recipe_names=["only_one"]) + + def test_policy_subset_wrong_recipe_names_length(self, fitted_pipeline, sample_data): + """Test policy_subset raises when recipe_names length doesn't match.""" + X, _, _ = sample_data + with pytest.raises(ValueError, match="recipe_names length"): + fitted_pipeline.policy_subset(X, treatment_indices=[0, 1], recipe_names=["only_one"]) + + @patch("multilift.uplift.classifier.plot_uplift_bins") + def test_plot_uplift_bins(self, mock_plot, fitted_pipeline, sample_data): + """Test plot_uplift_bins method.""" + X, t, y = sample_data + mock_axes = plt.figure().add_subplot(111) + mock_plot.return_value = mock_axes + + result = fitted_pipeline.plot_uplift_bins(X, t, y) + assert result is mock_axes + mock_plot.assert_called_once() + + def test_load_nested_list_treatment_names(self, fitted_pipeline, sample_data, tmp_path): + """Test load handles nested list treatment names from legacy saves.""" + X, _, _ = sample_data + import joblib + + # Save with nested list treatment names (legacy format) + state = { + "control_name": "control", + "treatment_names": [["treatment_A"], ["treatment_B"]], + "keep_cols": None, + "drop_cols": None, + "model_params": {}, + "model_type": "S", + "random_seed": DEFAULT_RANDOM_SEED, + "preprocessor": fitted_pipeline.preprocessor, + "model": fitted_pipeline.model, + "version": "1.0.0", + "class_name": "UpliftClassifierPipeline", + } + filepath = tmp_path / "legacy_model.joblib" + joblib.dump(state, filepath) + + loaded = UpliftClassifierPipeline.load(filepath) + assert loaded._treatment_names == ["treatment_A", "treatment_B"] + predictions = loaded.predict(X) + assert predictions.shape == (X.shape[0], 2) + + +class TestApplyThreshold: + """Tests for the shared _apply_threshold utility.""" + + def test_scalar_threshold(self): + """Test scalar threshold path.""" + from multilift.uplift._utils import _apply_threshold + + tau = np.array([[0.3, 0.1], [-0.1, 0.05], [0.5, 0.6]]) + names = np.array(["T1", "T2"]) + result = _apply_threshold(tau, names, "control", 0.0) + + assert result.name == "policy" + assert len(result) == len(tau) + assert result.iloc[0] == "T1" # 0.3 > 0.1 + assert result.iloc[2] == "T2" # 0.6 > 0.5 + + def test_scalar_threshold_filters(self): + """Test scalar threshold filters low uplifts.""" + from multilift.uplift._utils import _apply_threshold + + tau = np.array([[0.05], [0.2], [-0.1]]) + names = np.array(["T1"]) + result = _apply_threshold(tau, names, "control", 0.1) + + assert result.iloc[0] == "control" # 0.05 <= 0.1 + assert result.iloc[1] == "T1" # 0.2 > 0.1 + assert result.iloc[2] == "control" # -0.1 <= 0.1 + + def test_dict_threshold(self): + """Test dict threshold path.""" + from multilift.uplift._utils import _apply_threshold + + tau = np.array([[0.3, 0.08], [0.04, 0.15]]) + names = np.array(["T1", "T2"]) + result = _apply_threshold(tau, names, "control", {"T1": 0.05, "T2": 0.1}) + + assert result.iloc[0] == "T1" # T1: 0.3>=0.05, T2: 0.08<0.1 → T1 + assert result.iloc[1] == "T2" # T1: 0.04<0.05, T2: 0.15>=0.1 → T2 + + def test_dict_threshold_none_eligible(self): + """Test dict threshold when no treatment qualifies.""" + from multilift.uplift._utils import _apply_threshold + + tau = np.array([[0.01, 0.02]]) + names = np.array(["T1", "T2"]) + result = _apply_threshold(tau, names, "control", {"T1": 0.5, "T2": 0.5}) + + assert result.iloc[0] == "control" + + def test_dict_threshold_missing_key_defaults_to_zero(self): + """Test dict threshold with missing key defaults cutoff to 0.""" + from multilift.uplift._utils import _apply_threshold + + tau = np.array([[0.3, 0.01]]) + names = np.array(["T1", "T2"]) + # Only T1 has a cutoff; T2 defaults to 0.0 + result = _apply_threshold(tau, names, "control", {"T1": 0.5}) + + # T1: 0.3 < 0.5 → ineligible; T2: 0.01 >= 0.0 → eligible + assert result.iloc[0] == "T2" + + def test_dict_threshold_unknown_name_raises(self): + """Test dict threshold with unknown recipe name raises.""" + from multilift.uplift._utils import _apply_threshold + + tau = np.array([[0.1]]) + names = np.array(["T1"]) + with pytest.raises(ValueError, match="Unknown recipe names"): + _apply_threshold(tau, names, "control", {"UNKNOWN": 0.1}) + + def test_dict_threshold_negative_value_raises(self): + """Test dict threshold with negative value raises.""" + from multilift.uplift._utils import _apply_threshold + + tau = np.array([[0.1]]) + names = np.array(["T1"]) + with pytest.raises(ValueError, match="All threshold values must be non-negative"): + _apply_threshold(tau, names, "control", {"T1": -0.1}) + + def test_scalar_negative_threshold_raises(self): + """Test scalar negative threshold raises.""" + from multilift.uplift._utils import _apply_threshold + + tau = np.array([[0.1]]) + names = np.array(["T1"]) + with pytest.raises(ValueError, match="Threshold must be non-negative"): + _apply_threshold(tau, names, "control", -1.0) + + +class TestSLearnerClassifierUnit: + """Direct unit tests for SLearnerClassifier.""" + + @pytest.fixture + def clf_data(self): + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n = 200 + X = rng.normal(size=(n, 3)) + t = rng.choice(["control", "T1", "T2"], n) + base = 1 / (1 + np.exp(-X[:, 0])) + effect = np.where(t == "T1", 0.15, np.where(t == "T2", 0.1, 0.0)) + y = (rng.random(n) < np.clip(base + effect, 0, 1)).astype(int) + return X, t, y + + def test_is_fitted_before_and_after(self, clf_data): + from lightgbm import LGBMClassifier + + model = SLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=5)) + assert not model.is_fitted + + X, t, y = clf_data + model.fit(X, t, y) + assert model.is_fitted + + def test_predict_not_fitted_raises(self): + from lightgbm import LGBMClassifier + + model = SLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=5)) + with pytest.raises(ModelNotFittedError): + model.predict(np.array([[1, 2, 3]])) + + def test_fit_predict(self, clf_data): + from lightgbm import LGBMClassifier + + X, t, y = clf_data + model = SLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=10)) + model.fit(X, t, y) + tau = model.predict(X) + + assert tau.shape == (X.shape[0], 2) # T1 and T2 + assert np.isfinite(tau).all() + + def test_fit_with_pandas(self, clf_data): + from lightgbm import LGBMClassifier + + X, t, y = clf_data + model = SLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=5)) + model.fit(pd.DataFrame(X), pd.Series(t), pd.Series(y)) + tau = model.predict(pd.DataFrame(X)) + assert tau.shape == (X.shape[0], 2) + + def test_get_shap_values(self, clf_data): + from lightgbm import LGBMClassifier + + X, t, y = clf_data + model = SLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=10)) + model.fit(X, t, y) + shap_dict = model.get_shap_values(X) + + assert isinstance(shap_dict, dict) + assert len(shap_dict) == len(model.t_groups) + for group, values in shap_dict.items(): + assert values.shape == (X.shape[0], X.shape[1]) + + def test_get_shap_values_not_fitted_raises(self): + from lightgbm import LGBMClassifier + + model = SLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=5)) + with pytest.raises(ModelNotFittedError): + model.get_shap_values(np.array([[1, 2, 3]])) + + @patch("multilift.uplift.meta._slearner_classifier.plt") + def test_plot_shap_values(self, mock_plt, clf_data, tmp_path): + from lightgbm import LGBMClassifier + + X, t, y = clf_data + model = SLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=10)) + model.fit(X, t, y) + + model.plot_shap_values(X, features=["f1", "f2", "f3"], show=False, save_dir=tmp_path) + assert mock_plt.figure.called + + @patch("multilift.uplift.meta._slearner_classifier.plt") + def test_plot_shap_values_auto_compute(self, mock_plt, clf_data): + from lightgbm import LGBMClassifier + + X, t, y = clf_data + model = SLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=10)) + model.fit(X, t, y) + # Don't pass shap_dict — let it compute automatically + model.plot_shap_values(X, show=False) + assert mock_plt.figure.called + + +class TestTLearnerClassifierUnit: + """Direct unit tests for TLearnerClassifier.""" + + @pytest.fixture + def clf_data(self): + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n = 200 + X = rng.normal(size=(n, 3)) + t = rng.choice(["control", "T1", "T2"], n) + base = 1 / (1 + np.exp(-X[:, 0])) + effect = np.where(t == "T1", 0.15, np.where(t == "T2", 0.1, 0.0)) + y = (rng.random(n) < np.clip(base + effect, 0, 1)).astype(int) + return X, t, y + + def test_constructor_validation(self): + with pytest.raises(ValueError, match="Provide either"): + TLearnerClassifier(control_name="control") + + def test_is_fitted_before_and_after(self, clf_data): + from lightgbm import LGBMClassifier + + model = TLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=5)) + assert not model.is_fitted + X, t, y = clf_data + model.fit(X, t, y) + assert model.is_fitted + + def test_t_groups_not_fitted_raises(self): + from lightgbm import LGBMClassifier + + model = TLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=5)) + with pytest.raises(ModelNotFittedError): + _ = model.t_groups + + def test_predict_not_fitted_raises(self): + from lightgbm import LGBMClassifier + + model = TLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=5)) + with pytest.raises(ModelNotFittedError): + model.predict(np.array([[1, 2, 3]])) + + def test_fit_predict_shared_learner(self, clf_data): + from lightgbm import LGBMClassifier + + X, t, y = clf_data + model = TLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=10)) + model.fit(X, t, y) + tau = model.predict(X) + + assert tau.shape == (X.shape[0], 2) + assert np.isfinite(tau).all() + + def test_fit_predict_per_treatment_learners(self, clf_data): + from lightgbm import LGBMClassifier + + X, t, y = clf_data + model = TLearnerClassifier( + control_name="control", + control_learner=LGBMClassifier(n_estimators=5), + treatment_learners={ + "T1": LGBMClassifier(n_estimators=8), + "T2": LGBMClassifier(n_estimators=12), + }, + ) + model.fit(X, t, y) + tau = model.predict(X) + assert tau.shape == (X.shape[0], 2) + + def test_fit_predict_shared_treatment_learner(self, clf_data): + from lightgbm import LGBMClassifier + + X, t, y = clf_data + model = TLearnerClassifier( + control_name="control", + control_learner=LGBMClassifier(n_estimators=5), + treatment_learners=LGBMClassifier(n_estimators=10), + ) + model.fit(X, t, y) + tau = model.predict(X) + assert tau.shape == (X.shape[0], 2) + + def test_fit_with_pandas(self, clf_data): + from lightgbm import LGBMClassifier + + X, t, y = clf_data + model = TLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=5)) + model.fit(pd.DataFrame(X), pd.Series(t), pd.Series(y)) + tau = model.predict(pd.DataFrame(X)) + assert tau.shape == (X.shape[0], 2) + + def test_get_shap_values(self, clf_data): + from lightgbm import LGBMClassifier + + X, t, y = clf_data + model = TLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=10)) + model.fit(X, t, y) + shap_dict = model.get_shap_values(X) + + assert isinstance(shap_dict, dict) + assert len(shap_dict) == len(model.t_groups) + for group, values in shap_dict.items(): + assert values.shape == (X.shape[0], X.shape[1]) + + def test_get_shap_values_not_fitted_raises(self): + from lightgbm import LGBMClassifier + + model = TLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=5)) + with pytest.raises(ModelNotFittedError): + model.get_shap_values(np.array([[1, 2, 3]])) + + @patch("multilift.uplift.meta._tlearner_classifier.plt") + def test_plot_shap_values(self, mock_plt, clf_data, tmp_path): + from lightgbm import LGBMClassifier + + X, t, y = clf_data + model = TLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=10)) + model.fit(X, t, y) + + model.plot_shap_values(X, features=["f1", "f2", "f3"], show=False, save_dir=tmp_path) + assert mock_plt.figure.called + + @patch("multilift.uplift.meta._tlearner_classifier.plt") + def test_plot_shap_values_auto_compute(self, mock_plt, clf_data): + from lightgbm import LGBMClassifier + + X, t, y = clf_data + model = TLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=10)) + model.fit(X, t, y) + model.plot_shap_values(X, show=False) + assert mock_plt.figure.called + + def test_resolve_treatment_missing_group_raises(self): + from lightgbm import LGBMClassifier + + model = TLearnerClassifier( + control_name="control", + control_learner=LGBMClassifier(n_estimators=5), + treatment_learners={"T1": LGBMClassifier(n_estimators=5)}, + ) + with pytest.raises(ValueError, match="No learner found for treatment group"): + model._resolve_treatment_learner("T_UNKNOWN") + + +class TestUpliftClassifierPipelineIntegration: + """Integration tests for UpliftClassifierPipeline.""" + + def test_end_to_end_workflow(self, sample_data): + """Test complete end-to-end workflow.""" + X, t, y = sample_data + + # Split data + train_size = int(0.7 * len(X)) + X_train, X_test = X[:train_size], X[train_size:] + t_train, t_test = t[:train_size], t[train_size:] + y_train, y_test = y[:train_size], y[train_size:] + + # Initialize and fit + pipeline = UpliftClassifierPipeline( + "control", + "treatment_A", + "treatment_B", + random_seed=DEFAULT_RANDOM_SEED, + n_estimators=20, + ) + pipeline.fit(X_train, t_train, y_train) + + # Make predictions + predictions = pipeline.predict(X_test) + assert predictions.shape == (len(X_test), 2) + + # Get policies + policies = pipeline.policy(X_test) + assert len(policies) == len(X_test) + + # Evaluate + qini_auc, qini_df = pipeline.evaluate(X_test, t_test, y_test) + assert isinstance(qini_auc, float) + assert not qini_df.empty + + # Save and reload + with tempfile.TemporaryDirectory() as temp_dir: + model_path = Path(temp_dir) / "integration_test_model.joblib" + pipeline.save(model_path, "1.0.0") + + loaded_pipeline = UpliftClassifierPipeline.load(model_path) + + # Test loaded model works + loaded_predictions = loaded_pipeline.predict(X_test) + pd.testing.assert_frame_equal(predictions, loaded_predictions) + + def test_end_to_end_workflow_t_learner(self, sample_data): + """Test complete end-to-end workflow with T-learner.""" + X, t, y = sample_data + + # Split data + train_size = int(0.7 * len(X)) + X_train, X_test = X[:train_size], X[train_size:] + t_train, t_test = t[:train_size], t[train_size:] + y_train, y_test = y[:train_size], y[train_size:] + + # Initialize and fit T-learner + pipeline = UpliftClassifierPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="T", + random_seed=DEFAULT_RANDOM_SEED, + n_estimators=20, + ) + pipeline.fit(X_train, t_train, y_train) + + # Make predictions + predictions = pipeline.predict(X_test) + assert predictions.shape == (len(X_test), 2) + + # Get policies + policies = pipeline.policy(X_test) + assert len(policies) == len(X_test) + + # Evaluate + qini_auc, qini_df = pipeline.evaluate(X_test, t_test, y_test) + assert isinstance(qini_auc, float) + assert not qini_df.empty + + def test_with_different_data_types(self): + """Test pipeline with different data types.""" + # Create data with mixed types + X = pd.DataFrame( + { + "numeric": [1.0, 2.0, 3.0, 4.0], + "categorical": ["A", "B", "A", "B"], + "boolean": [True, False, True, False], + "integer": [1, 2, 3, 4], + } + ) + t = pd.Series(["control", "treatment_A", "control", "treatment_A"]) + y = pd.Series([0, 1, 0, 1]) # Binary outcome + + pipeline = UpliftClassifierPipeline( + "control", "treatment_A", random_seed=DEFAULT_RANDOM_SEED + ) + pipeline.fit(X, t, y) + + predictions = pipeline.predict(X) + assert predictions.shape == (len(X), 1) # Only one treatment vs control + + # Test policy with single treatment + policies = pipeline.policy(X) + assert len(policies) == len(X) + assert set(policies.columns) == {"treatment_A", "max_uplift", "policy"} + unique_policies = set(policies["policy"]) + assert unique_policies.issubset({"control", "treatment_A"}) + + +class TestSLearnerClassifierCoverageBranches: + """Cover missing branches in SLearnerClassifier (lines 162, 167, 233).""" + + @pytest.fixture + def fitted_slearner(self): + from lightgbm import LGBMClassifier + + rng = np.random.default_rng(0) + n = 80 + X = rng.normal(size=(n, 3)) + treatment = np.array(["control"] * 40 + ["T1"] * 40) + target = rng.integers(0, 2, n) + + model = SLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=5)) + model.fit(X, treatment, target) + return model, X + + def test_get_shap_values_list_branch(self, fitted_slearner, monkeypatch): + """Lines 162, 167: shap_values() returns a list — take index [1].""" + model, X = fitted_slearner + + # Simulate old-style SHAP returning a list of arrays per class + n, nf1 = X.shape[0], X.shape[1] + 1 # +1 for treatment indicator column + fake_array = np.zeros((n, nf1)) + + import shap + + monkeypatch.setattr( + shap.TreeExplainer, + "shap_values", + lambda self, arr: [fake_array, fake_array], + ) + + result = model.get_shap_values(X) + assert "T1" in result + # Result should be differences of feature columns only (no treatment indicator) + assert result["T1"].shape == (n, X.shape[1]) + + def test_plot_shap_values_show_true_calls_plt_show(self, fitted_slearner, monkeypatch): + """Line 233: plt.show() is called when show=True.""" + model, X = fitted_slearner + show_called = [] + monkeypatch.setattr(plt, "show", lambda: show_called.append(True)) + # Suppress the beeswarm rendering + import shap + + monkeypatch.setattr(shap.plots, "beeswarm", lambda *a, **kw: None) + + shap_dict = {"T1": np.zeros((X.shape[0], X.shape[1]))} + model.plot_shap_values(X, shap_dict=shap_dict, show=True) + assert len(show_called) == 1 + + def test_plot_shap_values_show_false_skips_plt_show(self, fitted_slearner, monkeypatch): + """Confirm show=False does NOT call plt.show() (guard for line 233 branch).""" + model, X = fitted_slearner + show_called = [] + monkeypatch.setattr(plt, "show", lambda: show_called.append(True)) + import shap + + monkeypatch.setattr(shap.plots, "beeswarm", lambda *a, **kw: None) + + shap_dict = {"T1": np.zeros((X.shape[0], X.shape[1]))} + model.plot_shap_values(X, shap_dict=shap_dict, show=False) + assert len(show_called) == 0 + + +class TestTLearnerClassifierCoverageBranches: + """Cover missing branches in TLearnerClassifier (lines 79, 101, 211, 217, 281).""" + + def test_t_groups_property_raises_when_unfitted(self): + """Line 79: t_groups property raises ModelNotFittedError before fit().""" + from lightgbm import LGBMClassifier + + model = TLearnerClassifier(control_name="control", learner=LGBMClassifier()) + with pytest.raises(ModelNotFittedError, match="Model is not fitted"): + _ = model.t_groups + + def test_resolve_treatment_learner_dict_fallback_to_learner(self): + """Line 101: dict treatment_learners missing key falls back to _learner.""" + from lightgbm import LGBMClassifier + + rng = np.random.default_rng(1) + n = 80 + X = rng.normal(size=(n, 3)) + # Two treatment groups; only T1 has an explicit learner in the dict + treatment = np.array(["control"] * 27 + ["T1"] * 27 + ["T2"] * 26) + target = rng.integers(0, 2, n) + + model = TLearnerClassifier( + control_name="control", + learner=LGBMClassifier(n_estimators=5), + treatment_learners={"T1": LGBMClassifier(n_estimators=3)}, + ) + model.fit(X, treatment, target) + # T2 falls back to _learner — fit should succeed + assert "T2" in model.models_t + + @pytest.fixture + def fitted_tlearner(self): + from lightgbm import LGBMClassifier + + rng = np.random.default_rng(2) + n = 80 + X = rng.normal(size=(n, 3)) + treatment = np.array(["control"] * 40 + ["T1"] * 40) + target = rng.integers(0, 2, n) + + model = TLearnerClassifier(control_name="control", learner=LGBMClassifier(n_estimators=5)) + model.fit(X, treatment, target) + return model, X + + def test_get_shap_values_list_branch(self, fitted_tlearner, monkeypatch): + """Lines 211, 217: shap_values() returns a list — take index [1].""" + model, X = fitted_tlearner + n = X.shape[0] + fake_array = np.zeros((n, X.shape[1])) + + import shap + + monkeypatch.setattr( + shap.TreeExplainer, + "shap_values", + lambda self, arr: [fake_array, fake_array], + ) + + result = model.get_shap_values(X) + assert "T1" in result + assert result["T1"].shape == (n, X.shape[1]) + + def test_plot_shap_values_show_true_calls_plt_show(self, fitted_tlearner, monkeypatch): + """Line 281: plt.show() is called when show=True.""" + model, X = fitted_tlearner + show_called = [] + monkeypatch.setattr(plt, "show", lambda: show_called.append(True)) + import shap + + monkeypatch.setattr(shap.plots, "beeswarm", lambda *a, **kw: None) + + shap_dict = {"T1": np.zeros((X.shape[0], X.shape[1]))} + model.plot_shap_values(X, shap_dict=shap_dict, show=True) + assert len(show_called) == 1 diff --git a/tests/uplift/test_uplift_eval.py b/tests/uplift/test_uplift_eval.py new file mode 100644 index 0000000..e8e7c4a --- /dev/null +++ b/tests/uplift/test_uplift_eval.py @@ -0,0 +1,569 @@ +import numpy as np +import pandas as pd +import pytest +from matplotlib import pyplot as plt + +from multilift.uplift.eval import ( + UpliftExploreEvaluator, + compute_best_uplift, + compute_binned_uplift, + compute_qini, + plot_qini_curve, + plot_uplift_bins, +) + +# Test constants +DEFAULT_N_BINS = 10 +CUSTOM_N_BINS = 5 +EXPECTED_SUBPLOTS = 2 +N_FEATURES = 5 +DEFAULT_RANDOM_SEED = 42 +EXPECTED_ROWS_AFTER_DROP = 3 +EXPECTED_ROWS_NO_DROP = 2 +HIGH_CORR_THRESHOLD = 0.99 + + +@pytest.fixture(scope="module") +def sample_data(): + """Create sample data for testing.""" + rng = np.random.default_rng(42) + n_samples = 50 + + t = pd.Series(rng.choice(["control", "treatment_A", "treatment_B"], n_samples)) + y = pd.Series(rng.normal(10, 2, n_samples)) + tau = pd.Series(rng.uniform(0, 5, n_samples)) + tau_2d = rng.random((n_samples, 2)) + + return t, y, tau, tau_2d + + +@pytest.fixture(scope="module") +def sample_multi_arm_data(): + """Create sample multi-arm data for UpliftExploreEvaluator testing.""" + rng = np.random.default_rng(42) + n_samples = 100 + + # Treatment assignments: control, treatment_A, treatment_B + t = pd.Series(rng.choice(["control", "treatment_A", "treatment_B"], n_samples)) + + # Outcomes with some treatment effects + base_outcome = rng.normal(10, 2, n_samples) + treatment_effect_a = np.where(t == "treatment_A", rng.normal(2, 0.5, n_samples), 0) + treatment_effect_b = np.where(t == "treatment_B", rng.normal(3, 0.5, n_samples), 0) + y = pd.Series(base_outcome + treatment_effect_a + treatment_effect_b) + + # Predicted uplift for each treatment vs control + tau = rng.uniform(-1, 5, (n_samples, 2)) + + return t, y, tau + + +class TestComputeBestUplift: + """Test compute_best_uplift function.""" + + def test_compute_best_uplift(self, sample_data): + """Test basic functionality.""" + _, _, _, tau_2d = sample_data + result = compute_best_uplift(tau_2d) + + assert len(result) == len(tau_2d) + assert all(result >= 0) # Should be non-negative + assert all(result <= tau_2d.max(axis=1)) # Should not exceed max + + +class TestComputeQini: + """Test compute_qini function.""" + + def test_compute_qini(self, sample_data): + """Test basic functionality.""" + t, y, _, tau_2d = sample_data + + qini_auc, qini_df = compute_qini(tau_2d, t, y, "control", "treatment_A", "treatment_B") + + assert isinstance(qini_auc, float) + assert isinstance(qini_df, pd.DataFrame) + assert len(qini_df) == len(t) + assert all(col in qini_df.columns for col in ["pop_frac", "uplift", "qini"]) + + +class TestPlotUpliftBins: + """Test plot_uplift_bins function.""" + + def test_plot_uplift_bins_basic(self, sample_data): + """Test basic functionality.""" + t, y, tau, _ = sample_data + + ax = plot_uplift_bins(t, y, tau, "control", "treatment_A", "treatment_B") + + assert isinstance(ax, plt.Axes) + assert len(ax.patches) == DEFAULT_N_BINS + plt.close() + + def test_plot_uplift_bins_custom_bins(self, sample_data): + """Test with custom number of bins.""" + t, y, tau, _ = sample_data + + ax = plot_uplift_bins(t, y, tau, "control", "treatment_A", n_bins=CUSTOM_N_BINS) + + assert len(ax.patches) == CUSTOM_N_BINS + plt.close() + + +class TestPlotQiniCurve: + """Test plot_qini_curve function.""" + + def test_plot_qini_curve(self, sample_data): + """Test basic functionality.""" + t, y, _, tau_2d = sample_data + + _, qini_df = compute_qini(tau_2d, t, y, "control", "treatment_A", "treatment_B") + axs = plot_qini_curve(qini_df, show=False) + + assert len(axs) == EXPECTED_SUBPLOTS + plt.close() + + +class TestUpliftExploreEvaluator: + """Test UpliftExploreEvaluator class.""" + + def test_init_basic(self): + """Test basic initialization.""" + evaluator = UpliftExploreEvaluator("control", "treatment_A", "treatment_B") + + assert evaluator.control_name == "control" + assert evaluator.treatment_names == ("treatment_A", "treatment_B") + assert evaluator.n_bins == DEFAULT_N_BINS + + def test_init_custom_bins(self): + """Test initialization with custom number of bins.""" + evaluator = UpliftExploreEvaluator("control", "treatment_A", n_bins=CUSTOM_N_BINS) + + assert evaluator.control_name == "control" + assert evaluator.treatment_names == ("treatment_A",) + assert evaluator.n_bins == CUSTOM_N_BINS + + def test_get_recommended_treatment(self, sample_multi_arm_data): + """Test get_recommended_treatment method.""" + _, _, tau = sample_multi_arm_data + evaluator = UpliftExploreEvaluator("control", "treatment_A", "treatment_B") + + recommendations = evaluator.get_recommended_treatment(tau) + + assert isinstance(recommendations, pd.Series) + assert len(recommendations) == len(tau) + assert all(rec in ["treatment_A", "treatment_B"] for rec in recommendations) + + def test_compute_uplift(self, sample_multi_arm_data): + """Test compute_uplift method.""" + t, y, tau = sample_multi_arm_data + evaluator = UpliftExploreEvaluator("control", "treatment_A", "treatment_B") + + result_df = evaluator.compute_uplift(t, y, tau) + + assert isinstance(result_df, pd.DataFrame) + assert len(result_df) == len(t) + + # Check expected columns exist + expected_cols = [ + "t", + "y", + "tau_0", + "tau_1", + "tau_best", + "bin", + "recommended_treatment", + "tau_actual", + ] + assert all(col in result_df.columns for col in expected_cols) + + # Check data types and ranges + assert result_df["bin"].min() >= 1 + assert result_df["bin"].max() <= DEFAULT_N_BINS + assert all(result_df["tau_best"] >= 0) # Should be non-negative + + def test_compute_uplift_with_dataframe_tau(self, sample_multi_arm_data): + """Test compute_uplift method with DataFrame tau input.""" + t, y, tau = sample_multi_arm_data + tau_df = pd.DataFrame(tau, columns=["tau_A", "tau_B"]) + evaluator = UpliftExploreEvaluator("control", "treatment_A", "treatment_B") + + result_df = evaluator.compute_uplift(t, y, tau_df) + + assert isinstance(result_df, pd.DataFrame) + assert len(result_df) == len(t) + + def test_compute_binned_uplift(self, sample_data): + """Test compute_binned_uplift method.""" + t, y, tau, _ = sample_data + + result_df, bins = compute_binned_uplift(t, y, tau) + + assert isinstance(result_df, pd.DataFrame) + assert len(result_df) <= DEFAULT_N_BINS # May be fewer if some bins are empty + assert result_df.index.name == "bin" + assert isinstance(bins, pd.Series) + + def test_plot(self, sample_multi_arm_data): + """Test plot method.""" + t, y, tau = sample_multi_arm_data + evaluator = UpliftExploreEvaluator("control", "treatment_A", "treatment_B") + + ax = evaluator.plot_binned_uplift(t, y, tau, show=False, save=False) + + assert isinstance(ax, plt.Axes) + assert ax.get_title() == "Actual Uplift by Bins" + assert "Binned Score (model's uplift predictions ranked high → low)" in ax.get_xlabel() + assert "Actual Uplift Per User" in ax.get_ylabel() + + plt.close() + + def test_plot_custom_title(self, sample_multi_arm_data): + """Test plot method with custom title.""" + t, y, tau = sample_multi_arm_data + evaluator = UpliftExploreEvaluator("control", "treatment_A", "treatment_B") + custom_title = "Custom Test Title" + + ax = evaluator.plot_binned_uplift(t, y, tau, title=custom_title, show=False, save=False) + + assert ax.get_title() == custom_title + plt.close() + + def test_plot_treatment_by_name(self, sample_multi_arm_data): + """Test plot_treatment method using treatment name.""" + t, y, tau = sample_multi_arm_data + evaluator = UpliftExploreEvaluator("control", "treatment_A", "treatment_B") + + ax = evaluator.plot_treatment( + t, y, tau, treatment_name="treatment_A", show=False, save=False + ) + + assert isinstance(ax, plt.Axes) + assert "treatment_A" in ax.get_title() + assert "Binned Score (model's uplift predictions ranked high → low)" in ax.get_xlabel() + assert "Actual Uplift Per User" in ax.get_ylabel() + plt.close() + + def test_plot_treatment_by_index(self, sample_multi_arm_data): + """Test plot_treatment method using treatment index.""" + t, y, tau = sample_multi_arm_data + evaluator = UpliftExploreEvaluator("control", "treatment_A", "treatment_B") + + ax = evaluator.plot_treatment(t, y, tau, treatment_idx=1, show=False, save=False) + + assert isinstance(ax, plt.Axes) + assert "treatment_B" in ax.get_title() + plt.close() + + def test_plot_treatment_no_parameters_raises_error(self, sample_multi_arm_data): + """Test plot_treatment method raises error when neither name nor index provided.""" + t, y, tau = sample_multi_arm_data + evaluator = UpliftExploreEvaluator("control", "treatment_A", "treatment_B") + + with pytest.raises( + ValueError, match="Either treatment_name or treatment_idx must be provided" + ): + evaluator.plot_treatment(t, y, tau, show=False, save=False) + + def test_plot_treatment_invalid_name_raises_error(self, sample_multi_arm_data): + """Test plot_treatment method raises error with invalid treatment name.""" + t, y, tau = sample_multi_arm_data + evaluator = UpliftExploreEvaluator("control", "treatment_A", "treatment_B") + + with pytest.raises(ValueError, match="not in tuple"): + evaluator.plot_treatment( + t, y, tau, treatment_name="invalid_treatment", show=False, save=False + ) + + def test_plot_treatment_invalid_index_raises_error(self, sample_multi_arm_data): + """Test plot_treatment method raises error with invalid treatment index.""" + t, y, tau = sample_multi_arm_data + evaluator = UpliftExploreEvaluator("control", "treatment_A", "treatment_B") + + with pytest.raises(IndexError): + evaluator.plot_treatment(t, y, tau, treatment_idx=5, show=False, save=False) + + def test_plot_treatment_with_both_name_and_index(self, sample_multi_arm_data): + """Test plot_treatment method when both name and index are provided.""" + t, y, tau = sample_multi_arm_data + evaluator = UpliftExploreEvaluator("control", "treatment_A", "treatment_B") + + # Should use the provided treatment_name and ignore treatment_idx + ax = evaluator.plot_treatment( + t, y, tau, treatment_name="treatment_A", treatment_idx=1, show=False, save=False + ) + + assert isinstance(ax, plt.Axes) + assert "treatment_A" in ax.get_title() + plt.close() + + +# --------------------------------------------------------------------------- +# New plotting / comparison / diagnostic methods +# --------------------------------------------------------------------------- + + +@pytest.fixture +def evaluator(): + """Shared evaluator with 2 treatments.""" + return UpliftExploreEvaluator("control", "treatment_A", "treatment_B") + + +@pytest.fixture +def multi_arm(evaluator): + """Larger dataset used by comparison / diagnostic tests.""" + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n = 200 + + t = pd.Series(rng.choice(["control", "treatment_A", "treatment_B"], n)) + base = rng.normal(10, 2, n) + effect_a = np.where(t == "treatment_A", rng.normal(2, 0.5, n), 0) + effect_b = np.where(t == "treatment_B", rng.normal(3, 0.5, n), 0) + y = pd.Series(base + effect_a + effect_b) + + tau = rng.uniform(-1, 5, (n, 2)).astype(np.float32) + tau2 = rng.uniform(-1, 5, (n, 2)).astype(np.float32) + + X = pd.DataFrame( + { + "age": rng.normal(40, 10, n), + "revenue": rng.normal(100, 30, n), + "segment": rng.choice(["A", "B", "C"], n), + } + ) + + return t, y, tau, tau2, X + + +class TestPlotShowSave: + """Tests for show/save/path parameters on plot methods.""" + + def test_plot_predicted_uplift_save(self, multi_arm, evaluator, tmp_path): + """plot_predicted_uplift respects save/path parameters.""" + _, _, tau, _, _ = multi_arm + out = tmp_path / "pred.png" + evaluator.plot_predicted_uplift(tau, show=False, save=True, path=str(out)) + plt.close("all") + assert out.exists() + + def test_plot_binned_treatment_mix_save(self, multi_arm, evaluator, tmp_path): + """plot_binned_treatment_mix respects save/path parameters.""" + _, _, tau, _, _ = multi_arm + out = tmp_path / "mix.png" + evaluator.plot_binned_treatment_mix(tau, show=False, save=True, path=str(out)) + plt.close("all") + assert out.exists() + + def test_plot_uplift_distribution_save(self, multi_arm, evaluator, tmp_path): + """plot_uplift_distribution respects save/path parameters.""" + _, _, tau, _, _ = multi_arm + out = tmp_path / "dist.png" + evaluator.plot_uplift_distribution(tau, show=False, save=True, path=str(out)) + plt.close("all") + assert out.exists() + + +class TestTauValidation: + """Tests for the tau shape validation guard.""" + + def test_wrong_tau_columns_raises(self, evaluator): + """Methods raise ValueError when tau columns != n_treatments.""" + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + tau_bad = rng.uniform(0, 1, (50, 3)) # 3 columns, evaluator expects 2 + t = pd.Series(rng.choice(["control", "treatment_A", "treatment_B"], 50)) + y = pd.Series(rng.normal(0, 1, 50)) + + with pytest.raises(ValueError, match="same number of columns"): + evaluator.compute_uplift(t, y, tau_bad) + + with pytest.raises(ValueError, match="same number of columns"): + evaluator.plot_predicted_uplift(tau_bad, show=False) + + +class TestDropMissingTau: + """Tests for _drop_missing_tau helper.""" + + def test_drops_nan_rows(self, evaluator): + """Rows with NaN tau are dropped from t, y, tau.""" + t = pd.Series(["control", "treatment_A", "treatment_B", "control"]) + y = pd.Series([1.0, 2.0, 3.0, 4.0]) + tau = np.array([[0.1, 0.2], [np.nan, 0.3], [0.4, 0.5], [0.6, 0.7]]) + + t_out, y_out, tau_out = evaluator._drop_missing_tau(t, y, tau) + + assert len(t_out) == EXPECTED_ROWS_AFTER_DROP + assert len(y_out) == EXPECTED_ROWS_AFTER_DROP + assert tau_out.shape[0] == EXPECTED_ROWS_AFTER_DROP + assert np.isfinite(tau_out).all() + + def test_no_nans_unchanged(self, evaluator): + """No-op when no NaN values present.""" + t = pd.Series(["control", "treatment_A"]) + y = pd.Series([1.0, 2.0]) + tau = np.array([[0.1, 0.2], [0.3, 0.4]]) + + t_out, _y_out, tau_out = evaluator._drop_missing_tau(t, y, tau) + + assert len(t_out) == EXPECTED_ROWS_NO_DROP + np.testing.assert_array_equal(tau_out, tau) + + +class TestCompareModelOverlap: + """Tests for compare_model_overlap.""" + + def test_overlap_returns_float(self, multi_arm, evaluator): + """Default call returns a float in [0, 1].""" + _, _, tau, tau2, _ = multi_arm + overlap = evaluator.compare_model_overlap(tau, tau2, top_fraction=0.2) + assert isinstance(overlap, float) + assert 0.0 <= overlap <= 1.0 + + def test_overlap_identical_models(self, multi_arm, evaluator): + """Overlap of a model with itself should be 1.0.""" + _, _, tau, _, _ = multi_arm + overlap = evaluator.compare_model_overlap(tau, tau, top_fraction=0.2) + assert overlap == 1.0 + + def test_overlap_detailed(self, multi_arm, evaluator): + """detailed=True returns a DataFrame.""" + _, _, tau, tau2, _ = multi_arm + result = evaluator.compare_model_overlap(tau, tau2, detailed=True) + assert isinstance(result, pd.DataFrame) + + def test_overlap_mismatched_length_raises(self, evaluator): + """Mismatched sample sizes raise ValueError.""" + tau1 = np.random.default_rng(0).uniform(0, 1, (50, 2)) + tau2 = np.random.default_rng(0).uniform(0, 1, (40, 2)) + with pytest.raises(ValueError, match="same number of observations"): + evaluator.compare_model_overlap(tau1, tau2) + + +class TestCompareTreatmentRecommendations: + """Tests for compare_treatment_recommendations.""" + + def test_returns_dict(self, multi_arm, evaluator): + """Default call returns a summary dict.""" + _, _, tau, tau2, _ = multi_arm + result = evaluator.compare_treatment_recommendations(tau, tau2) + assert isinstance(result, dict) + assert "overall_agreement" in result + + def test_detailed_returns_dict(self, multi_arm, evaluator): + """detailed=True returns dict with overall key.""" + _, _, tau, tau2, _ = multi_arm + result = evaluator.compare_treatment_recommendations(tau, tau2, detailed=True) + assert isinstance(result, dict) + assert "overall" in result + + +class TestCompareRankCorrelation: + """Tests for compare_rank_correlation.""" + + def test_returns_float(self, multi_arm, evaluator): + """Returns a correlation coefficient in [-1, 1].""" + _, _, tau, tau2, _ = multi_arm + corr = evaluator.compare_rank_correlation(tau, tau2) + assert isinstance(corr, float) + assert -1.0 <= corr <= 1.0 + + def test_spearman_method(self, multi_arm, evaluator): + """Spearman method also returns a float.""" + _, _, tau, tau2, _ = multi_arm + corr = evaluator.compare_rank_correlation(tau, tau2, method="spearman") + assert isinstance(corr, float) + + def test_identical_models_high_correlation(self, multi_arm, evaluator): + """Self-correlation should be very high.""" + _, _, tau, _, _ = multi_arm + corr = evaluator.compare_rank_correlation(tau, tau) + assert corr > HIGH_CORR_THRESHOLD + + +class TestSummarizeTreatmentMargins: + """Tests for summarize_treatment_margins.""" + + def test_returns_dict(self, multi_arm, evaluator): + """Returns a dict with expected summary keys.""" + _, _, tau, _, _ = multi_arm + result = evaluator.summarize_treatment_margins(tau) + assert isinstance(result, dict) + assert "threshold" in result + assert "summary" in result + + def test_with_top_fraction(self, multi_arm, evaluator): + """Works with top_fraction filter.""" + _, _, tau, _, _ = multi_arm + result = evaluator.summarize_treatment_margins(tau, top_fraction=0.2) + assert isinstance(result, dict) + assert "summary" in result + + +class TestCompareFeatureImportance: + """Tests for compare_feature_importance.""" + + def test_returns_dict(self, evaluator): + """Default call returns summary dict.""" + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + imp1 = rng.uniform(0, 1, N_FEATURES) + imp2 = rng.uniform(0, 1, N_FEATURES) + names = [f"f{i}" for i in range(N_FEATURES)] + + result = evaluator.compare_feature_importance(imp1, imp2, names, top_n=3) + assert isinstance(result, dict) + assert "mean_rank_diff" in result + + def test_detailed_returns_dict_with_comparison(self, evaluator): + """detailed=True returns a dict containing a comparison DataFrame.""" + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + imp1 = rng.uniform(0, 1, N_FEATURES) + imp2 = rng.uniform(0, 1, N_FEATURES) + names = [f"f{i}" for i in range(N_FEATURES)] + + result = evaluator.compare_feature_importance(imp1, imp2, names, top_n=3, detailed=True) + assert isinstance(result, dict) + assert "comparison" in result + assert isinstance(result["comparison"], pd.DataFrame) + assert len(result["comparison"]) == N_FEATURES + + +class TestAnalyzeSubgroupPerformance: + """Tests for analyze_subgroup_performance.""" + + def test_returns_dataframe(self, multi_arm, evaluator): + """Returns a DataFrame with subgroup performance stats.""" + t, y, tau, _, X = multi_arm + result = evaluator.analyze_subgroup_performance(tau, y, t, subgroups=X["segment"]) + assert isinstance(result, pd.DataFrame) + assert len(result) > 0 + + +class TestAnalyzeDisagreements: + """Tests for analyze_disagreements.""" + + def test_returns_dict(self, multi_arm, evaluator): + """Returns a dict with disagreement summary.""" + _t, _y, tau, tau2, X = multi_arm + result = evaluator.analyze_disagreements(tau, tau2, X, covariates=["age", "revenue"]) + assert isinstance(result, dict) + assert "agreement_rate" in result + + +class TestValidateUpliftPredictions: + """Tests for validate_uplift_predictions.""" + + def test_returns_dataframe(self, multi_arm, evaluator): + """Returns a calibration DataFrame.""" + t, y, tau, _, _ = multi_arm + result = evaluator.validate_uplift_predictions(tau, y, t, treatment_idx=0) + assert isinstance(result, pd.DataFrame) + assert "mean_pred_uplift" in result.columns + assert "mean_actual_uplift" in result.columns + + def test_invalid_treatment_idx_1d_raises(self, evaluator): + """Raises ValueError for 1D tau with treatment_idx != 0.""" + tau = np.random.default_rng(0).uniform(0, 1, 50) + t = pd.Series(np.random.default_rng(0).choice(["control", "treatment_A"], 50)) + y = pd.Series(np.random.default_rng(0).normal(0, 1, 50)) + + eval_1 = UpliftExploreEvaluator("control", "treatment_A") + with pytest.raises(ValueError, match="treatment_idx=1"): + eval_1.validate_uplift_predictions(tau, y, t, treatment_idx=1) diff --git a/tests/uplift/test_uplift_regressor.py b/tests/uplift/test_uplift_regressor.py new file mode 100644 index 0000000..ee9a539 --- /dev/null +++ b/tests/uplift/test_uplift_regressor.py @@ -0,0 +1,1292 @@ +import tempfile +from pathlib import Path +from unittest.mock import patch + +import numpy as np +import pandas as pd +import pytest +from matplotlib import pyplot as plt + +from multilift.exceptions import ModelNotFittedError +from multilift.preproc import OneHotPreprocessor +from multilift.uplift.regressor import UpliftRegressorPipeline + +# Test constants +DEFAULT_RANDOM_SEED = 42 +TREATMENT_2_VALUE = 2 +TREATMENT_3_VALUE = 3 +TEST_SUBSET_SIZE = 10 +N_TREATMENT_GROUPS = 2 + + +@pytest.fixture(scope="module") +def sample_data(): + """Create sample data for testing.""" + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n_samples = 100 + + # Features + X = pd.DataFrame( + { + "feature1": rng.normal(0, 1, n_samples), + "feature2": rng.normal(0, 1, n_samples), + "categorical": rng.choice(["A", "B", "C"], n_samples), + "binary": rng.choice([0, 1], n_samples), + } + ) + + # Treatments (control=0, treatment1=1, treatment2=2) + t = pd.Series(rng.choice([0, 1, 2], n_samples)) + + # Outcomes - make treatment effect visible + base_outcome = X["feature1"] + 0.5 * X["feature2"] + rng.normal(0, 0.1, n_samples) + treatment_effect1 = np.where(t == 1, 0.2, 0) # positive effect for treatment 1 + treatment_effect2 = np.where(t == TREATMENT_2_VALUE, 0.3, 0) # positive effect for treatment 2 + y = pd.Series(base_outcome + treatment_effect1 + treatment_effect2) + + # Map treatments to names + t_named = t.map({0: "control", 1: "treatment_A", 2: "treatment_B"}) + + return X, t_named, y + + +@pytest.fixture(scope="module") +def sample_data_three_treatments(): + """Create sample data with three treatments for testing.""" + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n_samples = 100 + + # Features + X = pd.DataFrame( + { + "feature1": rng.normal(0, 1, n_samples), + "feature2": rng.normal(0, 1, n_samples), + "categorical": rng.choice(["A", "B", "C"], n_samples), + "binary": rng.choice([0, 1], n_samples), + } + ) + + # Treatments (control=0, treatment1=1, treatment2=2, treatment3=3) + t = pd.Series(rng.choice([0, 1, 2, 3], n_samples)) + + # Outcomes - make treatment effect visible + base_outcome = X["feature1"] + 0.5 * X["feature2"] + rng.normal(0, 0.1, n_samples) + treatment_effect1 = np.where(t == 1, 0.2, 0) + treatment_effect2 = np.where(t == TREATMENT_2_VALUE, 0.3, 0) + treatment_effect3 = np.where(t == TREATMENT_3_VALUE, 0.4, 0) + y = pd.Series(base_outcome + treatment_effect1 + treatment_effect2 + treatment_effect3) + + # Map treatments to names + t_named = t.map( + { + 0: "control", + 1: "treatment_A", + TREATMENT_2_VALUE: "treatment_B", + TREATMENT_3_VALUE: "treatment_C", + } + ) + + return X, t_named, y + + +@pytest.fixture(scope="module") +def fitted_pipeline(sample_data): + """Create a fitted pipeline for testing.""" + X, t, y = sample_data + pipeline = UpliftRegressorPipeline( + "control", + "treatment_A", + "treatment_B", + random_seed=DEFAULT_RANDOM_SEED, + n_estimators=10, # Small for faster tests + ) + pipeline.fit(X, t, y) + return pipeline + + +@pytest.fixture(scope="module") +def fitted_t_pipeline(sample_data): + """Create a fitted T-learner pipeline for testing.""" + X, t, y = sample_data + pipeline = UpliftRegressorPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="T", + random_seed=DEFAULT_RANDOM_SEED, + n_estimators=10, # Small for faster tests + ) + pipeline.fit(X, t, y) + return pipeline + + +class TestUpliftRegressorPipeline: + """Test suite for UpliftRegressorPipeline.""" + + def test_init_basic(self): + """Test basic initialization.""" + pipeline = UpliftRegressorPipeline("control", "treatment_A") + + assert pipeline._control_name == "control" + assert pipeline._treatment_names == ["treatment_A"] + assert pipeline._keep_cols is None + assert pipeline._drop_cols is None + assert pipeline._random_seed == DEFAULT_RANDOM_SEED + assert pipeline._model is None + assert pipeline._preprocessor is None + + def test_init_with_parameters(self): + """Test initialization with parameters.""" + test_seed = 123 + test_estimators = 100 + test_lr = 0.05 + pipeline = UpliftRegressorPipeline( + "control", + "treatment_A", + "treatment_B", + keep_cols=["col1", "col2"], + drop_cols=["col3"], + random_seed=test_seed, + model_type="S", + n_estimators=test_estimators, + learning_rate=test_lr, + ) + + assert pipeline._control_name == "control" + assert pipeline._treatment_names == ["treatment_A", "treatment_B"] + assert pipeline._keep_cols == ["col1", "col2"] + assert pipeline._drop_cols == ["col3"] + assert pipeline._random_seed == test_seed + assert pipeline._model_type == "S" + assert pipeline._model_params["n_estimators"] == test_estimators + assert pipeline._model_params["learning_rate"] == test_lr + + def test_init_random_state_warning(self, caplog): + """Test that random_state in model_params triggers warning.""" + UpliftRegressorPipeline( + "control", "treatment_A", random_state=999, random_seed=DEFAULT_RANDOM_SEED + ) + + # Check that warning was logged + assert "Random seed is set in model_params" in caplog.text + + def test_init_model_type_t(self): + """Test initialization with T-learner model type.""" + pipeline = UpliftRegressorPipeline("control", "treatment_A", "treatment_B", model_type="T") + assert pipeline._model_type == "T" + + def test_init_model_type_default(self): + """Test that default model type is S.""" + pipeline = UpliftRegressorPipeline("control", "treatment_A") + assert pipeline._model_type == "S" + + def test_init_with_preprocessor(self, sample_data): + """Test initialization with a pre-fitted preprocessor.""" + X, _, _ = sample_data + preprocessor = OneHotPreprocessor() + preprocessor.fit(X) + + pipeline = UpliftRegressorPipeline("control", "treatment_A", preprocessor=preprocessor) + + assert pipeline._preprocessor is preprocessor + assert pipeline._preprocessor.is_fitted + + def test_repr(self): + """Test string representation.""" + pipeline = UpliftRegressorPipeline("control", "treatment_A", "treatment_B") + repr_str = repr(pipeline) + + assert "UpliftRegressorPipeline" in repr_str + assert "control" in repr_str + assert "treatment_A" in repr_str + assert "treatment_B" in repr_str + + def test_properties_before_fitting(self): + """Test properties before fitting.""" + pipeline = UpliftRegressorPipeline("control", "treatment_A") + + assert pipeline.model is None + assert pipeline.preprocessor is None + assert pipeline.control_name == "control" + assert pipeline.treatment_names == ["treatment_A"] + + def test_properties_after_fitting(self, fitted_pipeline): + """Test properties after fitting.""" + assert fitted_pipeline.model is not None + assert fitted_pipeline.preprocessor is not None + assert isinstance(fitted_pipeline.preprocessor, OneHotPreprocessor) + assert fitted_pipeline.control_name == "control" + assert fitted_pipeline.treatment_names == ["treatment_A", "treatment_B"] + + def test_get_feature_names(self, fitted_pipeline): + """Test get_feature_names method with raw parameter.""" + # Raw feature names (default) + raw_names = fitted_pipeline.get_feature_names() + assert isinstance(raw_names, list) + assert len(raw_names) > 0 + + # Transformed feature names + transformed_names = fitted_pipeline.get_feature_names(raw=False) + assert isinstance(transformed_names, list) + assert len(transformed_names) > 0 + + def test_get_feature_names_not_fitted(self): + """Test get_feature_names raises error when preprocessor is not initialized.""" + pipeline = UpliftRegressorPipeline("control", "treatment_A") + + with pytest.raises(RuntimeError, match="Preprocess is not initialized"): + pipeline.get_feature_names() + + def test_preprocess_training(self, sample_data): + """Test preprocessing during training.""" + X, _, _ = sample_data + pipeline = UpliftRegressorPipeline("control", "treatment_A") + + # First preprocessing should create and fit preprocessor + X_processed = pipeline.preprocess(X, training=True) + + assert pipeline._preprocessor is not None + assert isinstance(X_processed, pd.DataFrame) + assert X_processed.shape[0] == X.shape[0] # Same number of rows + + def test_preprocess_inference(self, fitted_pipeline, sample_data): + """Test preprocessing during inference.""" + X, _, _ = sample_data + X_new = X.head(TEST_SUBSET_SIZE) # Subset for inference + + X_processed = fitted_pipeline.preprocess(X_new, training=False) + + assert isinstance(X_processed, pd.DataFrame) + assert X_processed.shape[0] == TEST_SUBSET_SIZE + + def test_preprocess_inference_not_fitted(self, sample_data): + """Test preprocessing during inference.""" + X, t, y = sample_data + X_new = X.head(TEST_SUBSET_SIZE) # Subset for inference + + pipeline = UpliftRegressorPipeline( + "control", + "treatment_A", + "treatment_B", + random_seed=DEFAULT_RANDOM_SEED, + n_estimators=10, + ) + pipeline.fit(X, t, y) + pipeline.preprocessor = None + with pytest.raises(ModelNotFittedError, match="Preprocessor is not fitted"): + pipeline.preprocess(X_new, training=False) + + def test_preprocess_with_prefitted_preprocessor(self, sample_data): + """Test that preprocess doesn't refit an already fitted preprocessor.""" + X, _, _ = sample_data + preprocessor = OneHotPreprocessor() + preprocessor.fit(X) + + pipeline = UpliftRegressorPipeline("control", "treatment_A", preprocessor=preprocessor) + + # Should use the pre-fitted preprocessor without refitting + X_processed = pipeline.preprocess(X, training=True) + assert isinstance(X_processed, pd.DataFrame) + assert X_processed.shape[0] == X.shape[0] + + def test_fit(self, sample_data): + """Test fit method.""" + X, t, y = sample_data + pipeline = UpliftRegressorPipeline( + "control", "treatment_A", "treatment_B", random_seed=DEFAULT_RANDOM_SEED + ) + + result = pipeline.fit(X, t, y) + + # Should return self + assert result is pipeline + assert pipeline._model is not None + assert pipeline._preprocessor is not None + + def test_fit_t_learner(self, sample_data): + """Test fit method with T-learner.""" + X, t, y = sample_data + pipeline = UpliftRegressorPipeline( + "control", "treatment_A", "treatment_B", model_type="T", random_seed=DEFAULT_RANDOM_SEED + ) + + result = pipeline.fit(X, t, y) + + # Should return self + assert result is pipeline + assert pipeline._model is not None + assert pipeline._preprocessor is not None + # Check it's actually a T-learner + from multilift.uplift.meta import TLearnerRegressor + + assert isinstance(pipeline._model, TLearnerRegressor) + + def test_fit_t_learner_separate_params(self, sample_data): + """Test fit method with T-learner with separate learner parameters.""" + X, t, y = sample_data + pipeline = UpliftRegressorPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="T", + random_seed=DEFAULT_RANDOM_SEED, + control_learner_params={"n_estimators": 50, "learning_rate": 0.05}, + treatment_learner_params={"n_estimators": 100, "learning_rate": 0.1}, + ) + + result = pipeline.fit(X, t, y) + + # Should return self and create T-learner + assert result is pipeline + assert pipeline._model is not None + from multilift.uplift.meta import TLearnerRegressor + + assert isinstance(pipeline._model, TLearnerRegressor) + + def test_fit_t_learner_per_treatment_params(self, sample_data): + """Test fit method with T-learner with per-treatment learner parameters.""" + X, t, y = sample_data + pipeline = UpliftRegressorPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="T", + random_seed=DEFAULT_RANDOM_SEED, + control_learner_params={"n_estimators": 50, "learning_rate": 0.05}, + treatment_learner_params={ + "treatment_A": {"n_estimators": 80, "learning_rate": 0.1}, + "treatment_B": {"n_estimators": 120, "learning_rate": 0.05}, + }, + ) + + result = pipeline.fit(X, t, y) + + assert result is pipeline + assert pipeline._model is not None + + from multilift.uplift.meta import TLearnerRegressor + + assert isinstance(pipeline._model, TLearnerRegressor) + + # Verify per-treatment learners were created + model = pipeline._model + assert len(model.models_t) == N_TREATMENT_GROUPS + assert "treatment_A" in model.models_t + assert "treatment_B" in model.models_t + + # Verify predictions work + predictions = pipeline.predict(X) + assert predictions.shape == (X.shape[0], N_TREATMENT_GROUPS) + assert np.isfinite(predictions.values).all() + + def test_fit_x_learner_not_implemented(self, sample_data): + """Test that X-learner raises NotImplementedError.""" + X, t, y = sample_data + pipeline = UpliftRegressorPipeline( + "control", "treatment_A", "treatment_B", model_type="X", random_seed=DEFAULT_RANDOM_SEED + ) + + with pytest.raises(NotImplementedError, match="X-Learner is not implemented yet"): + pipeline.fit(X, t, y) + + def test_fit_invalid_model_type(self, sample_data): + """Test that invalid model_type raises ValueError.""" + X, t, y = sample_data + pipeline = UpliftRegressorPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="INVALID", + random_seed=DEFAULT_RANDOM_SEED, + ) + + with pytest.raises(ValueError, match="Invalid model type: INVALID"): + pipeline.fit(X, t, y) + + def test_predict_unfitted_raises_error(self, sample_data): + """Test that predict raises error when model is not fitted.""" + X, _, _ = sample_data + pipeline = UpliftRegressorPipeline("control", "treatment_A") + + with pytest.raises(ModelNotFittedError, match="Model is not fitted"): + pipeline.predict(X) + + def test_predict_fitted(self, fitted_pipeline, sample_data): + """Test predict method with fitted model.""" + X, _, _ = sample_data + + predictions = fitted_pipeline.predict(X) + + assert isinstance(predictions, pd.DataFrame) + assert predictions.shape == (X.shape[0], 2) # 2 treatments + assert np.isfinite(predictions.values).all() # All predictions should be finite + + def test_predict_t_learner(self, fitted_t_pipeline, sample_data): + """Test predict method with T-learner.""" + X, _, _ = sample_data + + predictions = fitted_t_pipeline.predict(X) + + assert isinstance(predictions, pd.DataFrame) + assert predictions.shape == (X.shape[0], 2) # 2 treatments + assert np.isfinite(predictions.values).all() # All predictions should be finite + + def test_predict_with_treatment_idx(self, fitted_pipeline, sample_data): + """Test predict method with treatment_idx parameter.""" + X, _, _ = sample_data + + # Predict for first treatment only + predictions = fitted_pipeline.predict(X, treatment_idx=0) + + assert isinstance(predictions, pd.DataFrame) + assert predictions.shape == (X.shape[0], 1) + assert predictions.columns.tolist() == ["treatment_A"] + assert np.isfinite(predictions.values).all() + + def test_predict_with_invalid_treatment_idx(self, fitted_pipeline, sample_data): + """Test predict method raises error for invalid treatment_idx.""" + X, _, _ = sample_data + + with pytest.raises(IndexError, match="Invalid treatment indices"): + fitted_pipeline.predict(X, treatment_idx=5) + + with pytest.raises(IndexError, match="Invalid treatment indices"): + fitted_pipeline.predict(X, treatment_idx=-1) + + def test_policy_unfitted_raises_error(self, sample_data): + """Test that policy raises error when model is not fitted.""" + X, _, _ = sample_data + pipeline = UpliftRegressorPipeline("control", "treatment_A") + + with pytest.raises(ModelNotFittedError, match="Model is not fitted"): + pipeline.policy(X) + + def test_policy_with_three_treatments(self, sample_data_three_treatments): + """Test that policy works correctly with three treatments.""" + X, t, y = sample_data_three_treatments + pipeline = UpliftRegressorPipeline("control", "treatment_A", "treatment_B", "treatment_C") + pipeline.fit(X, t, y) + + result_df = pipeline.policy(X) + + # Should return a DataFrame with all treatments + assert isinstance(result_df, pd.DataFrame) + assert len(result_df) == X.shape[0] + + # Check expected columns: 3 treatment uplifts + max_uplift + policy + expected_cols = {"treatment_A", "treatment_B", "treatment_C", "max_uplift", "policy"} + assert set(result_df.columns) == expected_cols + + # Check policy column contains valid recommendations + unique_policies = set(result_df["policy"]) + expected_policies = {"control", "treatment_A", "treatment_B", "treatment_C"} + assert unique_policies.issubset(expected_policies) + + def test_policy_fitted(self, fitted_pipeline, sample_data): + """Test policy method with fitted model.""" + X, _, _ = sample_data + + result_df = fitted_pipeline.policy(X) + + # Should return a DataFrame + assert isinstance(result_df, pd.DataFrame) + assert len(result_df) == X.shape[0] + + # Check expected columns: treatment uplifts + max_uplift + policy + expected_cols = {"treatment_A", "treatment_B", "max_uplift", "policy"} + assert set(result_df.columns) == expected_cols + + # Check policy column contains valid recommendations + unique_policies = set(result_df["policy"]) + expected_policies = {"control", "treatment_A", "treatment_B"} + assert unique_policies.issubset(expected_policies) + + # Check that max_uplift is non-negative (or zero if no positive uplift) + assert (result_df["max_uplift"] >= 0).all() + + def test_policy_with_custom_parameters(self, fitted_pipeline, sample_data): + """Test policy method with custom control_name and recipe_names.""" + X, _, _ = sample_data + custom_control = "custom_control" + custom_recipes = ["recipe_1", "recipe_2"] + + result_df = fitted_pipeline.policy( + X, control_name=custom_control, recipe_names=custom_recipes + ) + + # Check that custom recipe names are used as column names + expected_cols = {"recipe_1", "recipe_2", "max_uplift", "policy"} + assert set(result_df.columns) == expected_cols + + # Check that custom control name can appear in policies + unique_policies = set(result_df["policy"]) + expected_policies = {"custom_control", "recipe_1", "recipe_2"} + assert unique_policies.issubset(expected_policies) + + def test_policy_decision_logic(self, fitted_pipeline, sample_data): + """Test that policy makes correct decisions based on uplift values.""" + X, _, _ = sample_data + + result_df = fitted_pipeline.policy(X) + + # For each row, verify the policy logic + for idx, row in result_df.iterrows(): + treatment_a_uplift = row["treatment_A"] + treatment_b_uplift = row["treatment_B"] + max_uplift = row["max_uplift"] + policy = row["policy"] + + # Max uplift should be the maximum of positive uplifts or 0 + expected_max = max(0, treatment_a_uplift, treatment_b_uplift) + assert np.isclose(max_uplift, expected_max), f"Row {idx}: max_uplift mismatch" + + # Policy logic verification + if max_uplift == 0: + # No positive uplift, should recommend control + assert policy == "control" + elif treatment_a_uplift >= treatment_b_uplift and treatment_a_uplift > 0: + # Treatment A has highest positive uplift + assert policy == "treatment_A" + elif treatment_b_uplift > treatment_a_uplift and treatment_b_uplift > 0: + # Treatment B has highest positive uplift + assert policy == "treatment_B" + + def test_policy_single_treatment(self): + """Test policy method with a single treatment.""" + # Create data with single treatment + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n_samples = 100 + X = pd.DataFrame( + { + "feature1": rng.normal(0, 1, n_samples), + "feature2": rng.normal(0, 1, n_samples), + "categorical": rng.choice(["A", "B", "C"], n_samples), + } + ) + t = pd.Series(rng.choice([0, 1], n_samples)).map({0: "control", 1: "treatment_A"}) + base_outcome = X["feature1"] + 0.5 * X["feature2"] + rng.normal(0, 0.1, n_samples) + treatment_effect = np.where(t == "treatment_A", 0.2, 0) + y = pd.Series(base_outcome + treatment_effect) + + # Create pipeline with only 1 treatment + pipeline = UpliftRegressorPipeline( + "control", "treatment_A", random_seed=DEFAULT_RANDOM_SEED, n_estimators=10 + ) + pipeline.fit(X, t, y) + + result_df = pipeline.policy(X) + + # Should return a DataFrame + assert isinstance(result_df, pd.DataFrame) + assert len(result_df) == X.shape[0] + + # Check expected columns: treatment uplift + max_uplift + policy + expected_cols = {"treatment_A", "max_uplift", "policy"} + assert set(result_df.columns) == expected_cols + + # Check policy column contains valid recommendations + unique_policies = set(result_df["policy"]) + expected_policies = {"control", "treatment_A"} + assert unique_policies.issubset(expected_policies) + + # Check that max_uplift is non-negative (or zero if no positive uplift) + assert (result_df["max_uplift"] >= 0).all() + + def test_policy_single_treatment_decision_logic(self): + """Test that single treatment policy makes correct decisions based on uplift values.""" + # Create data with single treatment + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n_samples = 100 + X = pd.DataFrame( + { + "feature1": rng.normal(0, 1, n_samples), + "feature2": rng.normal(0, 1, n_samples), + "categorical": rng.choice(["A", "B", "C"], n_samples), + } + ) + t = pd.Series(rng.choice([0, 1], n_samples)).map({0: "control", 1: "treatment_A"}) + base_outcome = X["feature1"] + 0.5 * X["feature2"] + rng.normal(0, 0.1, n_samples) + treatment_effect = np.where(t == "treatment_A", 0.2, 0) + y = pd.Series(base_outcome + treatment_effect) + + pipeline = UpliftRegressorPipeline( + "control", "treatment_A", random_seed=DEFAULT_RANDOM_SEED, n_estimators=10 + ) + pipeline.fit(X, t, y) + + result_df = pipeline.policy(X) + + # For each row, verify the policy logic + for idx, row in result_df.iterrows(): + treatment_uplift = row["treatment_A"] + max_uplift = row["max_uplift"] + policy = row["policy"] + + # Max uplift should be the maximum of treatment uplift and 0 + expected_max = max(0, treatment_uplift) + assert np.isclose(max_uplift, expected_max), f"Row {idx}: max_uplift mismatch" + + # Policy logic verification for single treatment + if treatment_uplift > 0: + assert policy == "treatment_A", f"Row {idx}: expected treatment_A" + else: + assert policy == "control", f"Row {idx}: expected control" + + def test_policy_threshold_negative_raises_error(self, fitted_pipeline, sample_data): + """Test that policy raises error for negative threshold.""" + X, _, _ = sample_data + + with pytest.raises(ValueError, match="Threshold must be non-negative"): + fitted_pipeline.policy(X, threshold=-0.1) + + def test_policy_threshold_two_treatments(self, fitted_pipeline, sample_data): + """Test policy with threshold for two treatments.""" + X, _, _ = sample_data + + # Get results with default threshold (0.0) + result_default = fitted_pipeline.policy(X) + + # Get results with a higher threshold + threshold = 0.1 + result_with_threshold = fitted_pipeline.policy(X, threshold=threshold) + + # Both should have same columns + assert set(result_default.columns) == set(result_with_threshold.columns) + + # Verify threshold logic: with higher threshold, more rows should be control + control_count_default = (result_default["policy"] == "control").sum() + control_count_threshold = (result_with_threshold["policy"] == "control").sum() + assert control_count_threshold >= control_count_default + + # Verify decision logic for each row + for idx, row in result_with_threshold.iterrows(): + max_uplift = row["max_uplift"] + policy = row["policy"] + + if max_uplift <= threshold: + assert ( + policy == "control" + ), f"Row {idx}: expected control when max_uplift <= threshold" + + def test_policy_threshold_single_treatment(self): + """Test policy with threshold for single treatment.""" + # Create data with single treatment + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n_samples = 100 + X = pd.DataFrame( + { + "feature1": rng.normal(0, 1, n_samples), + "feature2": rng.normal(0, 1, n_samples), + "categorical": rng.choice(["A", "B", "C"], n_samples), + } + ) + t = pd.Series(rng.choice([0, 1], n_samples)).map({0: "control", 1: "treatment_A"}) + base_outcome = X["feature1"] + 0.5 * X["feature2"] + rng.normal(0, 0.1, n_samples) + treatment_effect = np.where(t == "treatment_A", 0.2, 0) + y = pd.Series(base_outcome + treatment_effect) + + pipeline = UpliftRegressorPipeline( + "control", "treatment_A", random_seed=DEFAULT_RANDOM_SEED, n_estimators=10 + ) + pipeline.fit(X, t, y) + + # Get results with default threshold (0.0) + result_default = pipeline.policy(X) + + # Get results with a higher threshold + threshold = 0.05 + result_with_threshold = pipeline.policy(X, threshold=threshold) + + # With higher threshold, more rows should be control + control_count_default = (result_default["policy"] == "control").sum() + control_count_threshold = (result_with_threshold["policy"] == "control").sum() + assert control_count_threshold >= control_count_default + + # Verify decision logic for each row + for idx, row in result_with_threshold.iterrows(): + treatment_uplift = row["treatment_A"] + max_uplift = row["max_uplift"] + policy = row["policy"] + + # Max uplift should still be max(0, treatment_uplift) + expected_max = max(0, treatment_uplift) + assert np.isclose(max_uplift, expected_max), f"Row {idx}: max_uplift mismatch" + + # Policy logic with threshold + if treatment_uplift > threshold: + assert policy == "treatment_A", f"Row {idx}: expected treatment_A" + else: + assert policy == "control", f"Row {idx}: expected control" + + def test_policy_single(self, fitted_pipeline, sample_data): + """Test policy_single method.""" + X, _, _ = sample_data + + result_df = fitted_pipeline.policy_single(X, treatment_idx=0) + + assert isinstance(result_df, pd.DataFrame) + assert len(result_df) == X.shape[0] + assert set(result_df.columns) == {"treatment_A", "max_uplift", "policy"} + + unique_policies = set(result_df["policy"]) + assert unique_policies.issubset({"control", "treatment_A"}) + assert (result_df["max_uplift"] >= 0).all() + + def test_policy_single_with_threshold(self, fitted_pipeline, sample_data): + """Test policy_single method with threshold.""" + X, _, _ = sample_data + + result_default = fitted_pipeline.policy_single(X, treatment_idx=0) + result_with_threshold = fitted_pipeline.policy_single(X, treatment_idx=0, threshold=0.1) + + # Higher threshold should result in more control recommendations + control_count_default = (result_default["policy"] == "control").sum() + control_count_threshold = (result_with_threshold["policy"] == "control").sum() + assert control_count_threshold >= control_count_default + + def test_policy_single_invalid_treatment_idx(self, fitted_pipeline, sample_data): + """Test policy_single raises error for invalid treatment_idx.""" + X, _, _ = sample_data + + with pytest.raises(IndexError, match="Invalid treatment indices"): + fitted_pipeline.policy_single(X, treatment_idx=5) + + def test_policy_single_negative_threshold(self, fitted_pipeline, sample_data): + """Test policy_single raises error for negative threshold.""" + X, _, _ = sample_data + + with pytest.raises(ValueError, match="Threshold must be non-negative"): + fitted_pipeline.policy_single(X, treatment_idx=0, threshold=-0.1) + + def test_policy_per_recipe_threshold(self, fitted_pipeline, sample_data): + """Test policy with per-recipe dict thresholds.""" + X, _, _ = sample_data + + tau_df = fitted_pipeline.predict(X) + tau_a_max = tau_df["treatment_A"].max() + tau_b_max = tau_df["treatment_B"].max() + + # Set cutoff so high that neither treatment qualifies → all control + high_cutoffs = { + "treatment_A": float(tau_a_max + 1), + "treatment_B": float(tau_b_max + 1), + } + result = fitted_pipeline.policy(X, threshold=high_cutoffs) + + assert (result["policy"] == "control").all() + + def test_policy_per_recipe_threshold_decision_logic(self, fitted_pipeline, sample_data): + """Test that per-recipe threshold masks treatments independently.""" + X, _, _ = sample_data + + tau_df = fitted_pipeline.predict(X) + tau = tau_df.to_numpy(dtype=np.float32) + + # Use median of each treatment as cutoff so roughly half pass each + cutoff_a = float(np.median(tau[:, 0])) + cutoff_b = float(np.median(tau[:, 1])) + cutoffs = {"treatment_A": cutoff_a, "treatment_B": cutoff_b} + + result = fitted_pipeline.policy(X, threshold=cutoffs) + + for idx in range(len(result)): + row = result.iloc[idx] + a_eligible = row["treatment_A"] >= cutoff_a + b_eligible = row["treatment_B"] >= cutoff_b + policy = row["policy"] + + if not a_eligible and not b_eligible: + assert policy == "control", f"Row {idx}: expected control" + elif a_eligible and not b_eligible: + assert policy == "treatment_A", f"Row {idx}: expected treatment_A" + elif not a_eligible and b_eligible: + assert policy == "treatment_B", f"Row {idx}: expected treatment_B" + else: + # Both eligible → highest score wins + expected = ( + "treatment_A" if row["treatment_A"] >= row["treatment_B"] else "treatment_B" + ) + assert policy == expected, f"Row {idx}: expected {expected}" + + def test_policy_per_recipe_threshold_partial_keys(self, fitted_pipeline, sample_data): + """Test that missing recipe keys default to 0 cutoff.""" + X, _, _ = sample_data + + # Only set cutoff for treatment_A; treatment_B defaults to 0 + result = fitted_pipeline.policy(X, threshold={"treatment_A": 999.0}) + + # treatment_A should never be assigned (cutoff impossibly high) + assert "treatment_A" not in result["policy"].values + + # Every row should be either treatment_B or control + valid_policies = {"treatment_B", "control"} + assert set(result["policy"].unique()).issubset(valid_policies) + + def test_policy_per_recipe_threshold_unknown_key_raises(self, fitted_pipeline, sample_data): + """Test that unknown recipe names in threshold dict raise ValueError.""" + X, _, _ = sample_data + + with pytest.raises(ValueError, match="Unknown recipe names"): + fitted_pipeline.policy(X, threshold={"nonexistent_recipe": 5.0}) + + def test_policy_per_recipe_threshold_negative_value_raises(self, fitted_pipeline, sample_data): + """Test that negative values in threshold dict raise ValueError.""" + X, _, _ = sample_data + + with pytest.raises(ValueError, match="non-negative"): + fitted_pipeline.policy(X, threshold={"treatment_A": -1.0}) + + def test_policy_subset_per_recipe_threshold(self, fitted_pipeline, sample_data): + """Test policy_subset with per-recipe dict thresholds.""" + X, _, _ = sample_data + + tau_df = fitted_pipeline.predict(X, treatment_indices=[0, 1]) + tau_a_max = tau_df["treatment_A"].max() + + cutoffs = {"treatment_A": float(tau_a_max + 1), "treatment_B": 0.0} + result = fitted_pipeline.policy_subset(X, treatment_indices=[0, 1], threshold=cutoffs) + + # treatment_A should never be assigned + assert "treatment_A" not in result["policy"].values + + def test_evaluate_unfitted_raises_error(self, sample_data): + """Test that evaluate raises error when model is not fitted.""" + X, t, y = sample_data + pipeline = UpliftRegressorPipeline("control", "treatment_A", "treatment_B") + + with pytest.raises(ModelNotFittedError, match="Model is not fitted"): + pipeline.evaluate(X, t, y) + + def test_evaluate_fitted(self, fitted_pipeline, sample_data): + """Test evaluate method with fitted model.""" + X, t, y = sample_data + + qini_auc, qini_df = fitted_pipeline.evaluate(X, t, y) + + assert isinstance(qini_auc, float) + assert isinstance(qini_df, pd.DataFrame) + assert np.isfinite(qini_auc) + assert not qini_df.empty + + def test_plot_unfitted_raises_error(self, sample_data): + """Test that plot raises error when model is not fitted.""" + X, t, y = sample_data + pipeline = UpliftRegressorPipeline("control", "treatment_A", "treatment_B") + + with pytest.raises(ModelNotFittedError, match="Model is not fitted"): + pipeline.plot(X, t, y) + + @patch("multilift.uplift.regressor.UpliftExploreEvaluator") + def test_plot_fitted(self, mock_evaluator_class, fitted_pipeline, sample_data): + """Test plot method with fitted model.""" + X, t, y = sample_data + + # Mock the evaluator instance and its method + mock_axes = plt.figure().add_subplot(111) + mock_evaluator = mock_evaluator_class.return_value + mock_evaluator.plot_binned_actual_uplift.return_value = mock_axes + + result = fitted_pipeline.plot(X, t, y, name="Test Plot") + + assert result is mock_axes + mock_evaluator.plot_binned_actual_uplift.assert_called_once() + # Check that title was passed correctly + _args, kwargs = mock_evaluator.plot_binned_actual_uplift.call_args + assert kwargs.get("title") == "Test Plot" + + def test_shap(self, fitted_pipeline, sample_data): + """Test that SHAP method returns SHAP values.""" + X, _, _ = sample_data + + shap_values = fitted_pipeline.shap(X) + + # Should return a dictionary + assert isinstance(shap_values, dict) + # Should have keys for each treatment + assert len(shap_values) > 0 + + def test_save_unfitted_raises_error(self, sample_data): + """Test that save raises error when model is not fitted.""" + pipeline = UpliftRegressorPipeline("control", "treatment_A", "treatment_B") + + with pytest.raises(ModelNotFittedError, match="Model is not fitted"): + pipeline.save("test_model.joblib", "1.0.0") + + def test_save_and_load(self, fitted_pipeline, sample_data): + """Test save and load functionality.""" + X, _, _ = sample_data + + # Test predictions before save + predictions_before = fitted_pipeline.predict(X) + + with tempfile.TemporaryDirectory() as temp_dir: + # Save model + model_path = Path(temp_dir) / "test_model.joblib" + saved_path = fitted_pipeline.save(model_path, "1.0.0") + + assert saved_path.exists() + assert saved_path == model_path + + # Load model + loaded_pipeline = UpliftRegressorPipeline.load(saved_path) + + # Test that loaded model has same configuration + assert loaded_pipeline._control_name == fitted_pipeline._control_name + assert loaded_pipeline._treatment_names == fitted_pipeline._treatment_names + assert loaded_pipeline._random_seed == fitted_pipeline._random_seed + + # Test that predictions are the same + predictions_after = loaded_pipeline.predict(X) + pd.testing.assert_frame_equal(predictions_before, predictions_after) + + def test_save_with_compression(self, fitted_pipeline): + """Test save with different compression levels.""" + with tempfile.TemporaryDirectory() as temp_dir: + # Test no compression + model_path1 = Path(temp_dir) / "model_no_compress" + fitted_pipeline.save(model_path1, version="1.0.0", compress=False) + + # Test high compression + model_path2 = Path(temp_dir) / "model_high_compress" + fitted_pipeline.save(model_path2, version="1.1.0", compress=9) + + assert model_path1.with_suffix(".joblib").exists() + assert model_path2.with_suffix(".joblib").exists() + + def test_save_creates_directory(self, fitted_pipeline): + """Test that save creates parent directories.""" + with tempfile.TemporaryDirectory() as temp_dir: + model_path = Path(temp_dir) / "nested" / "dir" / "model.joblib" + saved_path = fitted_pipeline.save(model_path, "1.0.0") + + assert saved_path.exists() + assert saved_path.parent.exists() + + def test_load_nonexistent_file(self): + """Test loading from non-existent file.""" + with pytest.raises(FileNotFoundError, match="Model file not found"): + UpliftRegressorPipeline.load("nonexistent_model.joblib") + + def test_load_corrupted_file(self): + """Test loading from corrupted file.""" + with tempfile.NamedTemporaryFile(suffix=".joblib", delete=False) as temp_file: + # Write invalid data + temp_file.write(b"corrupted data") + temp_file.flush() + + with pytest.raises(ValueError, match="Failed to load model"): + UpliftRegressorPipeline.load(temp_file.name) + + def test_property_setters(self): + """Test property setters.""" + pipeline = UpliftRegressorPipeline("control", "treatment_A") + + mock_preprocessor = OneHotPreprocessor() + from lightgbm import LGBMRegressor + + from multilift.uplift.meta import SLearnerRegressor, TLearnerRegressor + + mock_s_model = SLearnerRegressor(control_name="control", learner=LGBMRegressor()) + mock_t_model = TLearnerRegressor(control_name="control", learner=LGBMRegressor()) + + pipeline.preprocessor = mock_preprocessor + pipeline.model = mock_s_model + + assert pipeline.preprocessor is mock_preprocessor + assert pipeline.model is mock_s_model + + pipeline.model = mock_t_model + assert pipeline.model is mock_t_model + + +class TestUpliftRegressorPipelineIntegration: + """Integration tests for UpliftRegressorPipeline.""" + + def test_end_to_end_workflow(self, sample_data): + """Test complete end-to-end workflow.""" + X, t, y = sample_data + + # Split data + train_size = int(0.7 * len(X)) + X_train, X_test = X[:train_size], X[train_size:] + t_train, t_test = t[:train_size], t[train_size:] + y_train, y_test = y[:train_size], y[train_size:] + + # Initialize and fit + pipeline = UpliftRegressorPipeline( + "control", + "treatment_A", + "treatment_B", + random_seed=DEFAULT_RANDOM_SEED, + n_estimators=20, + ) + pipeline.fit(X_train, t_train, y_train) + + # Make predictions + predictions = pipeline.predict(X_test) + assert predictions.shape == (len(X_test), 2) + + # Get policies + policies = pipeline.policy(X_test) + assert len(policies) == len(X_test) + + # Evaluate + qini_auc, qini_df = pipeline.evaluate(X_test, t_test, y_test) + assert isinstance(qini_auc, float) + assert not qini_df.empty + + # Save and reload + with tempfile.TemporaryDirectory() as temp_dir: + model_path = Path(temp_dir) / "integration_test_model.joblib" + pipeline.save(model_path, "1.0.0") + + loaded_pipeline = UpliftRegressorPipeline.load(model_path) + + # Test loaded model works + loaded_predictions = loaded_pipeline.predict(X_test) + pd.testing.assert_frame_equal(predictions, loaded_predictions) + + def test_end_to_end_workflow_t_learner(self, sample_data): + """Test complete end-to-end workflow with T-learner.""" + X, t, y = sample_data + + # Split data + train_size = int(0.7 * len(X)) + X_train, X_test = X[:train_size], X[train_size:] + t_train, t_test = t[:train_size], t[train_size:] + y_train, y_test = y[:train_size], y[train_size:] + + # Initialize and fit T-learner + pipeline = UpliftRegressorPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="T", + random_seed=DEFAULT_RANDOM_SEED, + n_estimators=20, + ) + pipeline.fit(X_train, t_train, y_train) + + # Make predictions + predictions = pipeline.predict(X_test) + assert predictions.shape == (len(X_test), 2) + + # Get policies + policies = pipeline.policy(X_test) + assert len(policies) == len(X_test) + + # Evaluate + qini_auc, qini_df = pipeline.evaluate(X_test, t_test, y_test) + assert isinstance(qini_auc, float) + assert not qini_df.empty + + def test_with_different_data_types(self): + """Test pipeline with different data types.""" + # Create data with mixed types + X = pd.DataFrame( + { + "numeric": [1.0, 2.0, 3.0, 4.0], + "categorical": ["A", "B", "A", "B"], + "boolean": [True, False, True, False], + "integer": [1, 2, 3, 4], + } + ) + t = pd.Series(["control", "treatment_A", "control", "treatment_A"]) + y = pd.Series([0.1, 0.2, 0.15, 0.25]) + + pipeline = UpliftRegressorPipeline( + "control", "treatment_A", random_seed=DEFAULT_RANDOM_SEED + ) + pipeline.fit(X, t, y) + + predictions = pipeline.predict(X) + assert predictions.shape == (len(X), 1) # Only one treatment vs control + + # Test policy with single treatment + policies = pipeline.policy(X) + assert len(policies) == len(X) + assert set(policies.columns) == {"treatment_A", "max_uplift", "policy"} + unique_policies = set(policies["policy"]) + assert unique_policies.issubset({"control", "treatment_A"}) + + +class TestRegressorCoverageBranches: + """Targeted tests for missing branches in regressor.py and _tlearner.py.""" + + # ------------------------------------------------------------------ + # regressor.py line 152: nested list __init__ guard + # ------------------------------------------------------------------ + + def test_init_nested_list_treatment_names_raises(self): + """Line 152: passing a list as a treatment name raises TypeError.""" + with pytest.raises(TypeError, match="Treatment_names should not be nested lists"): + UpliftRegressorPipeline("control", ["treatment_A"]) + + # ------------------------------------------------------------------ + # regressor.py line 217: T-learner with shared treatment params + # ------------------------------------------------------------------ + + def test_fit_t_learner_shared_treatment_params(self, sample_data): + """Line 217: T-learner with control_learner_params + flat treatment_learner_params.""" + X, t, y = sample_data + pipeline = UpliftRegressorPipeline( + "control", + "treatment_A", + "treatment_B", + model_type="T", + random_seed=DEFAULT_RANDOM_SEED, + control_learner_params={"n_estimators": 5}, + treatment_learner_params={"n_estimators": 8}, # flat dict → shared treatment learner + ) + pipeline.fit(X, t, y) + + from multilift.uplift.meta import TLearnerRegressor + + assert isinstance(pipeline._model, TLearnerRegressor) + predictions = pipeline.predict(X) + assert predictions.shape == (X.shape[0], N_TREATMENT_GROUPS) + + # ------------------------------------------------------------------ + # regressor.py line 404: mutually exclusive treatment_idx + treatment_indices + # ------------------------------------------------------------------ + + def test_predict_mutual_exclusion_raises(self, fitted_pipeline, sample_data): + """Line 404: both treatment_idx and treatment_indices raises ValueError.""" + X, _, _ = sample_data + with pytest.raises(ValueError, match="Only one of treatment_idx or treatment_indices"): + fitted_pipeline.predict(X, treatment_idx=0, treatment_indices=[0]) + + # ------------------------------------------------------------------ + # regressor.py line 470: empty treatment_indices in policy_subset + # ------------------------------------------------------------------ + + def test_policy_subset_empty_raises(self, fitted_pipeline, sample_data): + """Line 470: policy_subset with empty treatment_indices raises ValueError.""" + X, _, _ = sample_data + with pytest.raises(ValueError, match="treatment_indices cannot be empty"): + fitted_pipeline.policy_subset(X, treatment_indices=[]) + + # ------------------------------------------------------------------ + # regressor.py line 540 + 543: recipe_names length mismatch in policy_subset + # ------------------------------------------------------------------ + + def test_policy_subset_recipe_names_mismatch_raises(self, fitted_pipeline, sample_data): + """Lines 540, 543: recipe_names length != treatment_indices length raises.""" + X, _, _ = sample_data + with pytest.raises(ValueError, match="recipe_names length"): + fitted_pipeline.policy_subset(X, treatment_indices=[0, 1], recipe_names=["only_one"]) + + # ------------------------------------------------------------------ + # regressor.py lines 679-692: plot() with a subset of treatment_names + # ------------------------------------------------------------------ + + def test_plot_with_treatment_names_subset(self, fitted_pipeline, sample_data): + """Lines 679-692: plot() filters to a named treatment subset.""" + X, t, y = sample_data + with patch("multilift.uplift.regressor.UpliftExploreEvaluator") as mock_cls: + mock_axes = plt.figure().add_subplot(111) + mock_cls.return_value.plot_binned_actual_uplift.return_value = mock_axes + + result = fitted_pipeline.plot(X, t, y, treatment_names=["treatment_A"]) + + assert result is mock_axes + # Evaluator should be constructed with only the subset treatment + mock_cls.assert_called_once_with("control", "treatment_A") + + def test_plot_invalid_treatment_names_raises(self, fitted_pipeline, sample_data): + """Line 679: treatment_names not a subset raises ValueError.""" + X, t, y = sample_data + with pytest.raises(ValueError, match="treatment_names must be a subset"): + fitted_pipeline.plot(X, t, y, treatment_names=["nonexistent"]) + + # ------------------------------------------------------------------ + # regressor.py lines 726-728: plot_uplift_bins + # ------------------------------------------------------------------ + + def test_plot_uplift_bins(self, fitted_pipeline, sample_data): + """Lines 726-728: plot_uplift_bins delegates to standalone function.""" + X, t, y = sample_data + with patch("multilift.uplift.regressor.plot_uplift_bins") as mock_fn: + mock_axes = plt.figure().add_subplot(111) + mock_fn.return_value = mock_axes + + result = fitted_pipeline.plot_uplift_bins(X, t, y) + + assert result is mock_axes + mock_fn.assert_called_once() + + # ------------------------------------------------------------------ + # regressor.py line 883: nested list treatment_names in load() + # ------------------------------------------------------------------ + + def test_load_nested_list_treatment_names(self, fitted_pipeline, sample_data, tmp_path): + """Line 883: load() handles legacy nested-list treatment_names.""" + import joblib + + X, _, _ = sample_data + state = { + "control_name": "control", + "treatment_names": [["treatment_A"], ["treatment_B"]], + "keep_cols": None, + "drop_cols": None, + "model_params": {}, + "model_type": "S", + "random_seed": DEFAULT_RANDOM_SEED, + "preprocessor": fitted_pipeline.preprocessor, + "model": fitted_pipeline.model, + "version": "1.0.0", + "class_name": "UpliftRegressorPipeline", + } + filepath = tmp_path / "legacy_model.joblib" + joblib.dump(state, filepath) + + loaded = UpliftRegressorPipeline.load(filepath) + assert loaded._treatment_names == ["treatment_A", "treatment_B"] + predictions = loaded.predict(X) + assert predictions.shape == (X.shape[0], 2) + + +class TestTLearnerRegressorCoverageBranches: + """Cover missing branches in _tlearner.py (lines 294-295, 313-315).""" + + @pytest.fixture + def fitted_tlearner(self): + from lightgbm import LGBMRegressor + + from multilift.uplift.meta import TLearnerRegressor + + rng = np.random.default_rng(3) + n = 80 + X = rng.normal(size=(n, 3)) + treatment = np.array(["control"] * 40 + ["T1"] * 40) + target = rng.normal(size=n) + + model = TLearnerRegressor(control_name="control", learner=LGBMRegressor(n_estimators=5)) + model.fit(X, treatment, target) + return model, X + + def test_plot_shap_values_with_save_dir(self, fitted_tlearner, monkeypatch, tmp_path): + """Lines 294-295: save_dir branch saves PNG files.""" + model, X = fitted_tlearner + import shap + + monkeypatch.setattr(shap.plots, "beeswarm", lambda *a, **kw: None) + monkeypatch.setattr(plt, "savefig", lambda path, **kw: None) + monkeypatch.setattr(plt, "show", lambda: None) + + shap_dict = {"T1": np.zeros((X.shape[0], X.shape[1]))} + # Should not raise; exercises the save_dir mkdir + savefig path + model.plot_shap_values(X, shap_dict=shap_dict, show=False, save_dir=str(tmp_path)) + + def test_plot_shap_values_show_true(self, fitted_tlearner, monkeypatch): + """Lines 313-315: plt.show() is called when show=True.""" + model, X = fitted_tlearner + show_called = [] + import shap + + monkeypatch.setattr(shap.plots, "beeswarm", lambda *a, **kw: None) + monkeypatch.setattr(plt, "show", lambda: show_called.append(True)) + + shap_dict = {"T1": np.zeros((X.shape[0], X.shape[1]))} + model.plot_shap_values(X, shap_dict=shap_dict, show=True) + assert len(show_called) == 1 diff --git a/tests/uplift/test_uplift_tuner.py b/tests/uplift/test_uplift_tuner.py new file mode 100644 index 0000000..209c37d --- /dev/null +++ b/tests/uplift/test_uplift_tuner.py @@ -0,0 +1,1062 @@ +"""Tests for the uplift tuner classes.""" + +import numpy as np +import pandas as pd +import pytest + +from multilift.constants import DEFAULT_PARAM_GRID, DEFAULT_TOP_N_MODELS +from multilift.exceptions import ModelNotFittedError +from multilift.uplift.tuner import ( + SLearnerTuner, + TLearnerTuner, + TunerResult, + qini_scorer, + top_decile_scorer, +) + +# Test constants +DEFAULT_RANDOM_SEED = 42 +N_SAMPLES = 200 +N_TREATMENTS = 2 +EXPECTED_RESULTS_COUNT_2 = 2 +EXPECTED_RESULTS_COUNT_3 = 3 +EXPECTED_RESULTS_COUNT_5 = 5 +EXPECTED_SCORE_HIGH = 0.5 +EXPECTED_SCORE_MID = 0.4 + + +@pytest.fixture(scope="module") +def sample_data(): + """Create sample data for testing with train/val split.""" + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + + # Create synthetic data with clear treatment effect + n_train = N_SAMPLES + n_val = N_SAMPLES // 2 + + def make_data(n): + X = pd.DataFrame( + { + "feature1": rng.normal(0, 1, n), + "feature2": rng.normal(0, 1, n), + "feature3": rng.choice(["A", "B", "C"], n), + } + ) + t = pd.Series(rng.choice(["control", "treatment_A", "treatment_B"], n)) + + # Outcome with treatment effect + base = X["feature1"] + 0.5 * X["feature2"] + rng.normal(0, 0.1, n) + effect_a = np.where(t == "treatment_A", 0.3 * X["feature1"], 0) + effect_b = np.where(t == "treatment_B", 0.2, 0) + y = pd.Series(base + effect_a + effect_b) + + return X, t, y + + X_train, t_train, y_train = make_data(n_train) + X_val, t_val, y_val = make_data(n_val) + + return { + "X_train": X_train, + "t_train": t_train, + "y_train": y_train, + "X_val": X_val, + "t_val": t_val, + "y_val": y_val, + } + + +class TestTunerResult: + """Tests for TunerResult dataclass.""" + + def test_to_dataframe_empty(self): + """Test to_dataframe with empty results.""" + result = TunerResult(best_params={}, best_score=0.0, all_results=[]) + df = result.to_dataframe() + assert df.empty + + def test_to_dataframe_with_t_learner_results(self): + """Test to_dataframe with T-Learner results.""" + result = TunerResult( + best_params={"control_learner_params": {"n_estimators": 100}}, + best_score=0.5, + all_results=[ + { + "control_params": {"n_estimators": 100}, + "treatment_params": {"n_estimators": 100}, + "score": 0.5, + }, + { + "control_params": {"n_estimators": 200}, + "treatment_params": {"n_estimators": 200}, + "score": 0.4, + }, + ], + ) + df = result.to_dataframe() + + assert len(df) == EXPECTED_RESULTS_COUNT_2 + assert "score" in df.columns + assert "control_n_estimators" in df.columns + assert "treatment_n_estimators" in df.columns + # Check sorted by score descending + assert df.iloc[0]["score"] == EXPECTED_SCORE_HIGH + + def test_to_dataframe_with_s_learner_results(self): + """Test to_dataframe with S-Learner results.""" + result = TunerResult( + best_params={"n_estimators": 100}, + best_score=0.5, + all_results=[ + {"params": {"n_estimators": 100, "max_depth": 3}, "score": 0.5}, + {"params": {"n_estimators": 200, "max_depth": 4}, "score": 0.4}, + ], + ) + df = result.to_dataframe() + + assert len(df) == EXPECTED_RESULTS_COUNT_2 + assert "score" in df.columns + assert "n_estimators" in df.columns + assert "max_depth" in df.columns + # Check sorted by score descending + assert df.iloc[0]["score"] == EXPECTED_SCORE_HIGH + + def test_top_n(self): + """Test top_n property.""" + result = TunerResult( + best_params={}, + best_score=0.5, + all_results=[ + {"score": 0.3}, + {"score": 0.5}, + {"score": 0.4}, + ], + ) + top = result.top_n(EXPECTED_RESULTS_COUNT_2) + assert len(top) == EXPECTED_RESULTS_COUNT_2 + assert top[0]["score"] == EXPECTED_SCORE_HIGH + assert top[1]["score"] == EXPECTED_SCORE_MID + + +class TestTLearnerTuner: + """Tests for TLearnerTuner class.""" + + def test_init_default_scorer(self): + """Test initialization with default top_decile scorer.""" + tuner = TLearnerTuner("control", ["treatment_A", "treatment_B"]) + + assert tuner.control_name == "control" + assert tuner.treatment_names == ["treatment_A", "treatment_B"] + assert tuner._scorer == top_decile_scorer + + def test_init_qini_scorer(self): + """Test initialization with qini scorer.""" + tuner = TLearnerTuner("control", ["treatment_A", "treatment_B"], scoring="qini") + + assert tuner._scorer == qini_scorer + + def test_init_custom_scorer(self): + """Test initialization with custom scorer.""" + + def custom_scorer(tau, t, y, control, treatments): + return float(np.mean(tau)) + + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + scoring=custom_scorer, + ) + assert tuner._scorer == custom_scorer + + def test_init_invalid_scorer(self): + """Test initialization with invalid scorer raises error.""" + with pytest.raises(ValueError, match="Unknown scoring metric"): + TLearnerTuner("control", ["treatment_A"], scoring="invalid") + + def test_default_param_grid(self): + """Test default parameter grid from constants.""" + assert "n_estimators" in DEFAULT_PARAM_GRID + assert "max_depth" in DEFAULT_PARAM_GRID + assert "learning_rate" in DEFAULT_PARAM_GRID + assert isinstance(DEFAULT_PARAM_GRID["n_estimators"], list) + + def test_tune_shared_params(self, sample_data): + """Test tuning with shared parameter grid samples independently for control/treatment.""" + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + + # Larger grid to ensure different samples + param_grid = { + "n_estimators": [10, 15, 20, 25], + "max_depth": [3, 4, 5, 6], + "learning_rate": [0.05, 0.1, 0.15], + } + + result = tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=5, + verbose=False, + ) + + assert isinstance(result, TunerResult) + assert result.best_score > -np.inf + assert "control_learner_params" in result.best_params + assert "treatment_learner_params" in result.best_params + assert len(result.all_results) == EXPECTED_RESULTS_COUNT_5 + + # Verify control and treatment are sampled independently (can have different params) + # With a larger grid and more iterations, we expect at least some to differ + has_different_params = any( + r["control_params"] != r["treatment_params"] for r in result.all_results + ) + assert has_different_params, "Control and treatment should be sampled independently" + + def test_tune_separate_params(self, sample_data): + """Test tuning with separate control and treatment parameter grids.""" + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + + # Each grid has 2 possible combinations + control_grid = {"n_estimators": [10, 15], "max_depth": [3], "learning_rate": [0.1]} + treatment_grid = {"n_estimators": [20, 25], "max_depth": [4], "learning_rate": [0.05]} + + result = tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + control_param_grid=control_grid, + treatment_param_grid=treatment_grid, + n_iter=2, + verbose=False, + ) + + assert isinstance(result, TunerResult) + assert len(result.all_results) == EXPECTED_RESULTS_COUNT_2 + # Verify different params were used + ctrl_params = [r["control_params"] for r in result.all_results] + treat_params = [r["treatment_params"] for r in result.all_results] + assert all("n_estimators" in p for p in ctrl_params) + assert all("n_estimators" in p for p in treat_params) + + def test_tune_with_custom_scorer(self, sample_data): + """Test tuning with a custom scoring function.""" + + # Custom scorer: maximize mean predicted uplift + def mean_uplift_scorer(tau, t, y, control_name, treatment_names): + return float(np.mean(tau)) + + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + scoring=mean_uplift_scorer, + random_seed=DEFAULT_RANDOM_SEED, + ) + + param_grid = { + "n_estimators": [10, 20], + "max_depth": [3, 4], + "learning_rate": [0.1], + } + + result = tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=3, + verbose=False, + ) + + # Verify tuning completed successfully + assert isinstance(result, TunerResult) + assert result.best_score > -np.inf + assert len(result.all_results) == EXPECTED_RESULTS_COUNT_3 + + # Verify the scorer was actually used (scores should be mean uplift values) + for r in result.all_results: + # Mean uplift is typically a small number, not Qini AUC scale + assert isinstance(r["score"], float) + + def test_tune_with_custom_scorer_maximizing_positive_rate(self, sample_data): + """Test custom scorer that maximizes fraction of positive uplifts.""" + + def positive_uplift_rate_scorer(tau, t, y, control_name, treatment_names): + # Score: fraction of samples with positive predicted uplift + best_uplift = np.max(tau, axis=1) + return float(np.mean(best_uplift > 0)) + + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + scoring=positive_uplift_rate_scorer, + random_seed=DEFAULT_RANDOM_SEED, + ) + + param_grid = {"n_estimators": [10], "max_depth": [3, 5], "learning_rate": [0.1]} + + result = tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=2, + verbose=False, + ) + + # Scores should be between 0 and 1 (fraction) + for r in result.all_results: + assert 0 <= r["score"] <= 1 + + def test_fit_best(self, sample_data): + """Test fitting with best parameters.""" + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + + param_grid = {"n_estimators": [10], "max_depth": [3], "learning_rate": [0.1]} + + tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=1, + verbose=False, + ) + + # fit_best uses tuner.tuner_result internally + pipeline = tuner.fit_best( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + ) + + # Should be able to predict + predictions = pipeline.predict(sample_data["X_val"]) + assert predictions.shape[0] == len(sample_data["X_val"]) + assert predictions.shape[1] == N_TREATMENTS + + def test_fit_model_at_index(self, sample_data): + """Test fitting model at a specific index.""" + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + + param_grid = { + "n_estimators": [10, 15], + "max_depth": [3, 4], + "learning_rate": [0.1], + } + + tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=5, + verbose=False, + ) + + # Fit model at index 0 (best model) + pipeline = tuner.fit_model_at_index( + 0, + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + ) + + # Should be able to predict + predictions = pipeline.predict(sample_data["X_val"]) + assert predictions.shape[0] == len(sample_data["X_val"]) + assert predictions.shape[1] == N_TREATMENTS + + def test_fit_model_at_index_invalid_index_negative(self, sample_data): + """Test fit_model_at_index raises error for negative index.""" + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + tuner.tuner_result = TunerResult(best_params={}, best_score=0.0, all_results=[]) + + with pytest.raises(ValueError, match="Index out of range"): + tuner.fit_model_at_index( + -1, + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + ) + + def test_fit_model_at_index_invalid_index_too_large(self, sample_data): + """Test fit_model_at_index raises error for index >= DEFAULT_TOP_N_MODELS.""" + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + tuner.tuner_result = TunerResult(best_params={}, best_score=0.0, all_results=[]) + + with pytest.raises(ValueError, match="Index out of range"): + tuner.fit_model_at_index( + DEFAULT_TOP_N_MODELS, + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + ) + + def test_fit_model_at_index_not_tuned(self, sample_data): + """Test fit_model_at_index raises error when tuner has not been run.""" + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + + with pytest.raises(ModelNotFittedError, match="Tuner result is not set"): + tuner.fit_model_at_index( + 0, + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + ) + + def test_tune_independent_treatments(self, sample_data): + """Test tuning with independent per-treatment hyperparameters.""" + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + + param_grid = { + "n_estimators": [10, 15, 20, 25], + "max_depth": [3, 4, 5, 6], + "learning_rate": [0.05, 0.1, 0.15], + } + + result = tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=5, + independent_treatments=True, + verbose=False, + ) + + assert isinstance(result, TunerResult) + assert result.best_score > -np.inf + assert len(result.all_results) == EXPECTED_RESULTS_COUNT_5 + + # treatment_params should be a dict-of-dicts keyed by treatment name + for r in result.all_results: + tp = r["treatment_params"] + assert isinstance(tp, dict) + assert "treatment_A" in tp + assert "treatment_B" in tp + assert isinstance(tp["treatment_A"], dict) + assert isinstance(tp["treatment_B"], dict) + + # best_params should propagate the dict-of-dicts format + best_tp = result.best_params["treatment_learner_params"] + assert "treatment_A" in best_tp + assert "treatment_B" in best_tp + + def test_tune_independent_treatments_params_can_differ(self, sample_data): + """Test that independent mode produces different params across treatments.""" + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + + param_grid = { + "n_estimators": [10, 15, 20, 25], + "max_depth": [3, 4, 5, 6], + "learning_rate": [0.05, 0.1, 0.15], + } + + result = tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=5, + independent_treatments=True, + verbose=False, + ) + + has_different = any( + r["treatment_params"]["treatment_A"] != r["treatment_params"]["treatment_B"] + for r in result.all_results + ) + assert has_different, "Independent treatments should allow different params per group" + + def test_fit_best_independent_treatments(self, sample_data): + """Test fit_best works correctly after independent tuning.""" + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + + param_grid = {"n_estimators": [10], "max_depth": [3], "learning_rate": [0.1]} + + tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=1, + independent_treatments=True, + verbose=False, + ) + + pipeline = tuner.fit_best( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + ) + + predictions = pipeline.predict(sample_data["X_val"]) + assert predictions.shape[0] == len(sample_data["X_val"]) + assert predictions.shape[1] == N_TREATMENTS + + def test_fit_model_at_index_independent_treatments(self, sample_data): + """Test fit_model_at_index with independent treatment tuning results.""" + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + + param_grid = { + "n_estimators": [10, 15], + "max_depth": [3, 4], + "learning_rate": [0.1], + } + + tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=5, + independent_treatments=True, + verbose=False, + ) + + pipeline = tuner.fit_model_at_index( + 0, + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + ) + + predictions = pipeline.predict(sample_data["X_val"]) + assert predictions.shape[0] == len(sample_data["X_val"]) + assert predictions.shape[1] == N_TREATMENTS + + +class TestTunerResultPerTreatment: + """Tests for TunerResult with per-treatment params.""" + + def test_to_dataframe_per_treatment(self): + """Test to_dataframe flattens per-treatment dict-of-dicts correctly.""" + result = TunerResult( + best_params={}, + best_score=0.5, + all_results=[ + { + "control_params": {"n_estimators": 100}, + "treatment_params": { + "treatment_A": {"n_estimators": 200, "max_depth": 4}, + "treatment_B": {"n_estimators": 300, "max_depth": 6}, + }, + "score": 0.5, + }, + { + "control_params": {"n_estimators": 150}, + "treatment_params": { + "treatment_A": {"n_estimators": 250, "max_depth": 5}, + "treatment_B": {"n_estimators": 350, "max_depth": 7}, + }, + "score": 0.4, + }, + ], + ) + df = result.to_dataframe() + + assert len(df) == EXPECTED_RESULTS_COUNT_2 + assert "control_n_estimators" in df.columns + assert "treatment_treatment_A_n_estimators" in df.columns + assert "treatment_treatment_A_max_depth" in df.columns + assert "treatment_treatment_B_n_estimators" in df.columns + assert "treatment_treatment_B_max_depth" in df.columns + assert df.iloc[0]["score"] == EXPECTED_SCORE_HIGH + + +class TestTLearnerTunerSaveLoad: + """Tests for TLearnerTuner save/load methods.""" + + def test_save_not_tuned_raises(self, tmp_path): + """Test save raises error when tune has not been called.""" + tuner = TLearnerTuner("control", ["treatment_A", "treatment_B"]) + with pytest.raises(ModelNotFittedError, match="Nothing to save"): + tuner.save(tmp_path / "tuner") + + def test_save_and_load_roundtrip(self, sample_data, tmp_path): + """Test that save then load preserves tuner state.""" + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + param_grid = {"n_estimators": [10], "max_depth": [3], "learning_rate": [0.1]} + tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=1, + verbose=False, + ) + + path = tuner.save(tmp_path / "tuner") + loaded = TLearnerTuner.load(path) + + assert loaded.control_name == tuner.control_name + assert loaded.treatment_names == tuner.treatment_names + assert loaded.random_seed == tuner.random_seed + assert loaded.tuner_result.best_score == tuner.tuner_result.best_score + assert loaded.tuner_result.best_params == tuner.tuner_result.best_params + assert len(loaded.tuner_result.all_results) == len(tuner.tuner_result.all_results) + + def test_load_missing_file_raises(self, tmp_path): + """Test load raises FileNotFoundError for missing file.""" + with pytest.raises(FileNotFoundError): + TLearnerTuner.load(tmp_path / "nonexistent.joblib") + + def test_loaded_tuner_can_fit_best(self, sample_data, tmp_path): + """Test that a loaded tuner can fit_best without re-tuning.""" + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + param_grid = {"n_estimators": [10], "max_depth": [3], "learning_rate": [0.1]} + tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=1, + verbose=False, + ) + + path = tuner.save(tmp_path / "tuner") + loaded = TLearnerTuner.load(path) + + pipeline = loaded.fit_best( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + ) + predictions = pipeline.predict(sample_data["X_val"]) + assert predictions.shape[0] == len(sample_data["X_val"]) + assert predictions.shape[1] == N_TREATMENTS + + def test_save_adds_joblib_extension(self, sample_data, tmp_path): + """Test that save adds .joblib extension when absent.""" + tuner = TLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + param_grid = {"n_estimators": [10], "max_depth": [3], "learning_rate": [0.1]} + tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=1, + verbose=False, + ) + + path = tuner.save(tmp_path / "tuner_no_ext") + assert path.suffix == ".joblib" + assert path.exists() + + +class TestSLearnerTuner: + """Tests for SLearnerTuner class.""" + + def test_init_default_scorer(self): + """Test initialization with default top_decile scorer.""" + tuner = SLearnerTuner("control", ["treatment_A", "treatment_B"]) + + assert tuner.control_name == "control" + assert tuner.treatment_names == ["treatment_A", "treatment_B"] + assert tuner._scorer == top_decile_scorer + + def test_init_qini_scorer(self): + """Test initialization with qini scorer.""" + tuner = SLearnerTuner("control", ["treatment_A", "treatment_B"], scoring="qini") + + assert tuner._scorer == qini_scorer + + def test_init_invalid_scorer(self): + """Test initialization with invalid scorer raises error.""" + with pytest.raises(ValueError, match="Unknown scoring metric"): + SLearnerTuner("control", ["treatment_A"], scoring="invalid") + + def test_tune(self, sample_data): + """Test tuning with S-Learner.""" + tuner = SLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + + param_grid = { + "n_estimators": [10, 15], + "max_depth": [3, 4], + "learning_rate": [0.1], + } + + result = tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=3, + verbose=False, + ) + + assert isinstance(result, TunerResult) + assert result.best_score > -np.inf + assert len(result.all_results) == EXPECTED_RESULTS_COUNT_3 + + # S-Learner should have flat params (no control/treatment split) + assert "params" in result.all_results[0] + assert "n_estimators" in result.best_params + + def test_fit_best(self, sample_data): + """Test fitting with best parameters.""" + tuner = SLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + + param_grid = {"n_estimators": [10], "max_depth": [3], "learning_rate": [0.1]} + + tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=1, + verbose=False, + ) + + pipeline = tuner.fit_best( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + ) + + # Should be able to predict + predictions = pipeline.predict(sample_data["X_val"]) + assert predictions.shape[0] == len(sample_data["X_val"]) + assert predictions.shape[1] == N_TREATMENTS + + +class TestSLearnerTunerFitModelAtIndex: + """Tests for SLearnerTuner.fit_model_at_index.""" + + def test_fit_model_at_index(self, sample_data): + """Test fitting model at a specific index.""" + tuner = SLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + + param_grid = { + "n_estimators": [10, 15], + "max_depth": [3, 4], + "learning_rate": [0.1], + } + + tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=5, + verbose=False, + ) + + pipeline = tuner.fit_model_at_index( + 0, + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + ) + + predictions = pipeline.predict(sample_data["X_val"]) + assert predictions.shape[0] == len(sample_data["X_val"]) + assert predictions.shape[1] == N_TREATMENTS + + def test_fit_model_at_index_invalid_index_negative(self, sample_data): + """Test fit_model_at_index raises error for negative index.""" + tuner = SLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + tuner.tuner_result = TunerResult(best_params={}, best_score=0.0, all_results=[]) + + with pytest.raises(ValueError, match="Index out of range"): + tuner.fit_model_at_index( + -1, + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + ) + + def test_fit_model_at_index_invalid_index_too_large(self, sample_data): + """Test fit_model_at_index raises error for index >= DEFAULT_TOP_N_MODELS.""" + tuner = SLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + tuner.tuner_result = TunerResult(best_params={}, best_score=0.0, all_results=[]) + + with pytest.raises(ValueError, match="Index out of range"): + tuner.fit_model_at_index( + DEFAULT_TOP_N_MODELS, + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + ) + + def test_fit_model_at_index_not_tuned(self, sample_data): + """Test fit_model_at_index raises error when tuner has not been run.""" + tuner = SLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + + with pytest.raises(ModelNotFittedError, match="Tuner result is not set"): + tuner.fit_model_at_index( + 0, + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + ) + + +class TestSLearnerTunerSaveLoad: + """Tests for SLearnerTuner save/load methods.""" + + def test_save_not_tuned_raises(self, tmp_path): + """Test save raises error when tune has not been called.""" + tuner = SLearnerTuner("control", ["treatment_A", "treatment_B"]) + with pytest.raises(ModelNotFittedError, match="Nothing to save"): + tuner.save(tmp_path / "tuner") + + def test_save_and_load_roundtrip(self, sample_data, tmp_path): + """Test that save then load preserves tuner state.""" + tuner = SLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + param_grid = {"n_estimators": [10], "max_depth": [3], "learning_rate": [0.1]} + tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=1, + verbose=False, + ) + + path = tuner.save(tmp_path / "tuner") + loaded = SLearnerTuner.load(path) + + assert loaded.control_name == tuner.control_name + assert loaded.treatment_names == tuner.treatment_names + assert loaded.random_seed == tuner.random_seed + assert loaded.tuner_result.best_score == tuner.tuner_result.best_score + assert loaded.tuner_result.best_params == tuner.tuner_result.best_params + assert len(loaded.tuner_result.all_results) == len(tuner.tuner_result.all_results) + + def test_load_missing_file_raises(self, tmp_path): + """Test load raises FileNotFoundError for missing file.""" + with pytest.raises(FileNotFoundError): + SLearnerTuner.load(tmp_path / "nonexistent.joblib") + + def test_loaded_tuner_can_fit_best(self, sample_data, tmp_path): + """Test that a loaded tuner can fit_best without re-tuning.""" + tuner = SLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + param_grid = {"n_estimators": [10], "max_depth": [3], "learning_rate": [0.1]} + tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=1, + verbose=False, + ) + + path = tuner.save(tmp_path / "tuner") + loaded = SLearnerTuner.load(path) + + pipeline = loaded.fit_best( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + ) + predictions = pipeline.predict(sample_data["X_val"]) + assert predictions.shape[0] == len(sample_data["X_val"]) + assert predictions.shape[1] == N_TREATMENTS + + def test_save_adds_joblib_extension(self, sample_data, tmp_path): + """Test that save adds .joblib extension when absent.""" + tuner = SLearnerTuner( + "control", + ["treatment_A", "treatment_B"], + random_seed=DEFAULT_RANDOM_SEED, + ) + param_grid = {"n_estimators": [10], "max_depth": [3], "learning_rate": [0.1]} + tuner.tune( + sample_data["X_train"], + sample_data["t_train"], + sample_data["y_train"], + sample_data["X_val"], + sample_data["t_val"], + sample_data["y_val"], + param_grid=param_grid, + n_iter=1, + verbose=False, + ) + + path = tuner.save(tmp_path / "tuner_no_ext") + assert path.suffix == ".joblib" + assert path.exists() + + +class TestQiniScorer: + """Tests for qini_scorer function.""" + + def test_qini_scorer_returns_float(self, sample_data): + """Test that qini_scorer returns a float score.""" + # Create fake predictions + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n = len(sample_data["t_val"]) + tau = rng.standard_normal((n, N_TREATMENTS)).astype(np.float32) + + score = qini_scorer( + tau, + sample_data["t_val"], + sample_data["y_val"], + "control", + ("treatment_A", "treatment_B"), + ) + + assert isinstance(score, float) + + +class TestTopDecileScorer: + """Tests for top_decile_scorer function.""" + + def test_top_decile_scorer_returns_float(self, sample_data): + """Test that top_decile_scorer returns a float score.""" + rng = np.random.default_rng(DEFAULT_RANDOM_SEED) + n = len(sample_data["t_val"]) + tau = rng.standard_normal((n, N_TREATMENTS)).astype(np.float32) + + score = top_decile_scorer( + tau, + sample_data["t_val"], + sample_data["y_val"], + "control", + ("treatment_A", "treatment_B"), + ) + + assert isinstance(score, float) diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..7b0f49b --- /dev/null +++ b/tox.ini @@ -0,0 +1,24 @@ +[tox] +envlist = + lint, + python3.11, + python3.12, + python3.13, + python3.14 + +# see https://python-poetry.org/docs/faq/#usecase-3 +isolated_build = true + +[testenv] +skip_install = true +allowlist_externals = poetry +setenv = + COVERAGE_FILE = .coverage_db_{envname} +commands_pre = poetry install --all-groups +commands = poetry run pytest --color=yes --cov=multilift --cov-report html:htmlcov_{envname} --cov-report term --cov-report xml:coverage_{envname}.xml + +[testenv:lint] +commands = + poetry run isort --check-only --df . + poetry run black --check --diff . + poetry run ruff check .