diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f9523e4..d02d1e7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -63,3 +63,6 @@ jobs: - name: Check the distribution metadata run: uvx twine check dist/* + + - name: Run the quick start against the built wheel + run: uv run --python 3.13 --isolated --no-project --with dist/*.whl python examples/quickstart.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..b364546 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,78 @@ +name: Release + +# Publishes popdgp to PyPI when a GitHub Release is published. The release tag +# must be the package version, with or without a leading "v" (0.1.0 or v0.1.0). +# +# PyPI trusted publishing: PyPI accepts uploads only from this workflow in the +# pypi environment. No stored token. One-time setup is in CONTRIBUTING.md. +# +# Run it by hand (workflow_dispatch) to build and check the distribution +# without publishing. + +on: + release: + types: [published] + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: Check out popdgp + uses: actions/checkout@v4 + + - name: Set up uv + uses: astral-sh/setup-uv@v5 + + - name: Install Python + run: uv python install 3.13 + + - name: Check that the release tag is the package version + if: github.event_name == 'release' + env: + TAG: ${{ github.event.release.tag_name }} + run: | + version=$(uv run --python 3.13 python -c "import popdgp; print(popdgp.__version__)") + if [ "${TAG#v}" != "$version" ]; then + echo "::error::Release tag $TAG does not match package version $version." + exit 1 + fi + + - name: Run tests + run: uv run --python 3.13 pytest + + - name: Build the distribution + run: uv build + + - name: Check the distribution metadata + run: uvx twine check dist/* + + - name: Run the quick start against the built wheel + run: uv run --python 3.13 --isolated --no-project --with dist/*.whl python examples/quickstart.py + + - name: Keep the distribution for the publish job + uses: actions/upload-artifact@v4 + with: + name: dist + path: dist/ + if-no-files-found: error + + publish: + name: Publish to PyPI + if: github.event_name == 'release' + needs: build + runs-on: ubuntu-latest + environment: pypi + permissions: + id-token: write # OIDC token for PyPI trusted publishing + + steps: + - name: Fetch the distribution + uses: actions/download-artifact@v4 + with: + name: dist + path: dist/ + + - name: Publish to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6edfe5d..54a6735 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,3 +20,25 @@ semantics): weighted reductions - view projection and floor construction - any holdout or split logic + +## Releasing + +Releases go to PyPI from `.github/workflows/release.yml`, by PyPI trusted +publishing (no stored token). + +1. Set the new version in `pyproject.toml` and in `src/popdgp/__init__.py` + (a test checks that the two agree), and merge. +2. Publish a GitHub Release whose tag is that version (`0.2.0` or `v0.2.0`). + The workflow tests, builds, runs the quick start against the built wheel, + and uploads to PyPI. It stops if the tag and the version differ. + +Running the workflow by hand builds and checks the distribution without +publishing. + +One-time setup, by an owner of the PyPI project: add a trusted publisher on +PyPI for owner `PolicyEngine`, repository `popdgp`, workflow `release.yml`, +environment `pypi`. Before the first release this is a "pending publisher", +which also reserves the name. + +A release changes what downstream users pin. Say in the release notes whether +any metric's output changes for the same inputs and seed. diff --git a/README.md b/README.md index 48078c3..f6f734e 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,75 @@ Sampling-noise **floors** (a survey's own complementary split scored as a candidate) anchor every axis. Generator-agnostic and non-self-referential: holdouts appear nowhere upstream of the candidates being scored. +## Install + +```bash +pip install popdgp +``` + +popdgp needs Python 3.11 or later and depends on NumPy, pandas, SciPy and +scikit-learn. + +## Quick start + +A view names the columns a survey observes, its weight column, and which +columns were imputed. `harness_scorecard` scores a candidate file against each +view's holdout, and `sample_reference_scorecard` gives the floor for the same +view. Both return long-format rows `{view, metric, value}`. + +```python +"""Score a candidate population against one survey view, beside its floor.""" + +import numpy as np +import pandas as pd + +from popdgp import ( + SurveyView, + harness_scorecard, + sample_reference_scorecard, + split_frame, +) + + +def draw(seed: int, n: int = 1000) -> pd.DataFrame: + """A weighted sample of age and wealth from a toy population.""" + rng = np.random.default_rng(seed) + age = rng.uniform(20, 80, n) + wealth = np.exp(rng.normal(9 + 0.03 * age, 1.0)) + weight = rng.uniform(1, 5, n) + return pd.DataFrame({"age": age, "wealth": wealth, "weight": weight}) + + +survey = draw(seed=1) # the survey that observes the population +candidate = draw(seed=2) # the file to score; here, another draw + +# A view names the columns a survey observes, its weight column, and which +# columns were imputed. Imputed columns get the tail block. +view = SurveyView( + name="survey", + columns=("age", "wealth"), + weight_column="weight", + target_columns=("wealth",), +) + +# Hold out 20% of the survey. The holdout must not be used to build the +# candidate. +split = split_frame(survey, seed=0) +scores = harness_scorecard(candidate, "weight", [view], {"survey": split.test}, seed=0) + +# The floor scores the survey's other 80% against the same holdout: what an +# independent sample of the same population still incurs. +floor = sample_reference_scorecard({"survey": survey}, [view], seed=0) + +table = pd.DataFrame(scores).merge( + pd.DataFrame(floor), on=["view", "metric"], suffixes=("_candidate", "_floor") +) +print(table.to_string(index=False)) +``` + +The same script is in +[`examples/quickstart.py`](https://github.com/PolicyEngine/popdgp/blob/main/examples/quickstart.py). + ## Lineage and status Successor to the original `CosilicoAI/popdgp` (which also tried to *build* diff --git a/examples/quickstart.py b/examples/quickstart.py new file mode 100644 index 0000000..9ee30a3 --- /dev/null +++ b/examples/quickstart.py @@ -0,0 +1,47 @@ +"""Score a candidate population against one survey view, beside its floor.""" + +import numpy as np +import pandas as pd + +from popdgp import ( + SurveyView, + harness_scorecard, + sample_reference_scorecard, + split_frame, +) + + +def draw(seed: int, n: int = 1000) -> pd.DataFrame: + """A weighted sample of age and wealth from a toy population.""" + rng = np.random.default_rng(seed) + age = rng.uniform(20, 80, n) + wealth = np.exp(rng.normal(9 + 0.03 * age, 1.0)) + weight = rng.uniform(1, 5, n) + return pd.DataFrame({"age": age, "wealth": wealth, "weight": weight}) + + +survey = draw(seed=1) # the survey that observes the population +candidate = draw(seed=2) # the file to score; here, another draw + +# A view names the columns a survey observes, its weight column, and which +# columns were imputed. Imputed columns get the tail block. +view = SurveyView( + name="survey", + columns=("age", "wealth"), + weight_column="weight", + target_columns=("wealth",), +) + +# Hold out 20% of the survey. The holdout must not be used to build the +# candidate. +split = split_frame(survey, seed=0) +scores = harness_scorecard(candidate, "weight", [view], {"survey": split.test}, seed=0) + +# The floor scores the survey's other 80% against the same holdout: what an +# independent sample of the same population still incurs. +floor = sample_reference_scorecard({"survey": survey}, [view], seed=0) + +table = pd.DataFrame(scores).merge( + pd.DataFrame(floor), on=["view", "metric"], suffixes=("_candidate", "_floor") +) +print(table.to_string(index=False)) diff --git a/tests/test_packaging.py b/tests/test_packaging.py new file mode 100644 index 0000000..8ba7750 --- /dev/null +++ b/tests/test_packaging.py @@ -0,0 +1,42 @@ +"""What a consumer of the published package relies on. + +The version string agrees with the installed metadata, and the quick start in +the README is the script in ``examples/`` and runs. +""" + +from __future__ import annotations + +import runpy +from importlib import metadata +from pathlib import Path + +import popdgp + +ROOT = Path(__file__).resolve().parents[1] +QUICKSTART = ROOT / "examples" / "quickstart.py" + + +def test_version_matches_the_installed_metadata() -> None: + """``pyproject.toml`` and ``popdgp.__version__`` name the same version.""" + assert popdgp.__version__ == metadata.version("popdgp") + + +def test_readme_quick_start_is_the_example_script() -> None: + """The README shows the example verbatim, so the two cannot drift apart.""" + readme = (ROOT / "README.md").read_text() + assert f"```python\n{QUICKSTART.read_text()}```" in readme + + +def test_quick_start_runs_and_reports_every_block(capsys) -> None: + """The example scores a candidate and its floor on all four blocks.""" + runpy.run_path(str(QUICKSTART), run_name="__main__") + printed = capsys.readouterr().out + for metric in ( + "energy_distance", + "c2st_auc", + "prdc_coverage", + "w1_over_sd.wealth", + "q99_ratio.wealth", + ): + assert metric in printed + assert "value_candidate" in printed and "value_floor" in printed