Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ jobs:
- '3.14'
steps:
- uses: actions/checkout@v7.0.1
- uses: prefix-dev/setup-pixi@v0.10.2
- uses: prefix-dev/setup-pixi@v0.11.3
with:
pixi-version: v0.81.0
pixi-version: v0.84.2
cache: true
cache-write: ${{ github.event_name == 'push' && github.ref_name == 'main' }}
frozen: true
Expand All @@ -47,13 +47,19 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7.0.1
- uses: prefix-dev/setup-pixi@v0.10.2
with:
pixi-version: v0.81.0
# `.ai-instructions` carries the dead-code script.
submodules: true
- uses: prefix-dev/setup-pixi@v0.11.3
with:
pixi-version: v0.84.2
cache: true
cache-write: ${{ github.event_name == 'push' && github.ref_name == 'main' }}
frozen: true
environments: py314
- name: Run ty
run: pixi run --locked -e py314 prek run ty --all-files
shell: bash -el {0}
- name: Refuse dead internal and test code
run: pixi run --locked -e py314 prek run dead-code --all-files
shell: bash -el {0}
28 changes: 20 additions & 8 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ repos:
- id: check-useless-excludes
# - id: identity # Prints all files passed to pre-commits. Debugging.
- repo: https://github.com/tox-dev/pyproject-fmt
rev: v2.29.4
rev: v2.30.6
hooks:
- id: pyproject-fmt
- repo: https://github.com/lyz-code/yamlfix
Expand Down Expand Up @@ -49,11 +49,11 @@ repos:
- id: yamllint
exclude: variable_to_metadata_mapping\.yaml
- repo: https://github.com/python-jsonschema/check-jsonschema
rev: 0.38.0
rev: 0.39.0
hooks:
- id: check-github-workflows
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.16.8
rev: v0.17.5
hooks:
- id: ruff-check
types_or:
Expand All @@ -68,14 +68,14 @@ repos:
- pyi
- python
- repo: https://github.com/astral-sh/ty-pre-commit
rev: v0.0.83
rev: v0.0.104
hooks:
- id: ty
# Run ty directly so import resolution uses `[tool.ty] environment.python`.
# Keep this dependency pin aligned with the hook revision above.
entry: ty check
additional_dependencies:
- ty==0.0.83
- ty==0.0.104
- repo: https://github.com/executablebooks/mdformat
rev: 1.0.0
hooks:
Expand Down Expand Up @@ -124,6 +124,15 @@ repos:
files: ^(pyproject\.toml|pixi\.toml|pixi\.lock)$
stages:
- pre-push
# Whole-repository analysis: a change in one file can orphan code in another.
- id: dead-code
name: no internal or test code without a caller
entry: python .ai-instructions/hooks/dead_code.py
language: python
additional_dependencies:
- vulture==2.16
pass_filenames: false
files: \.py$|^pyproject\.toml$
- id: no-hardcoded-user-paths
name: no hardcoded user-specific absolute paths
language: pygrep
Expand Down Expand Up @@ -152,10 +161,13 @@ ci:
# the GitHub Actions `run-ty` job covers type checking, and pixi-lock-check
# needs a pixi binary that pre-commit.ci does not provide.
#
# `pre-push-hooks-installed` runs a file from the `.ai-instructions` submodule,
# which pre-commit.ci does not clone, and it asks about the local clone, which
# is meaningless on a runner anyway.
# The hooks above that run files from the `.ai-instructions` submodule
# fail as a missing file on pre-commit.ci, which clones without submodules.
# `pre-push-hooks-installed` asks about the local clone and is meaningless on
# a runner anyway; `dead-code` runs in the GitHub Actions `run-ty` job, which
# checks out the submodule.
skip:
- ty
- pixi-lock-check
- pre-push-hooks-installed
- dead-code
208 changes: 102 additions & 106 deletions pixi.lock

Large diffs are not rendered by default.

16 changes: 13 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,10 @@ channels = [ "conda-forge" ]
platforms = [ "linux-64", "osx-64", "osx-arm64", "win-64" ]
[tool.pixi.dependencies]
deepdiff = "*"
jupyter-book = ">=2"
jupyter-book = ">=2.1.7"
jupyterlab = "*"
mystmd = "*"
prek = "*"
mystmd = ">=1.13.0"
prek = ">=0.5.9"
pygments = ">=2.19.2"
pygraphviz = "*"
scikit-learn = ">=1.9.0,<2"
Expand Down Expand Up @@ -154,6 +154,9 @@ expand_tables = [
collapse_tables = [ "tool.hatch", "tool.pytask", "tool.pytest", "tool.ty" ]

[tool.ty]
# The `.ai-instructions` hook scripts import tools that exist only in their
# pre-commit environments (vulture), so ty cannot resolve them.
src.exclude = [ ".ai-instructions" ]
# ty resolves third-party imports from this pixi env. The pre-commit hook runs
# ty directly; pixi owns the project environment. Run `pixi install` once.
environment.python = ".pixi/envs/py314"
Expand All @@ -175,6 +178,13 @@ ini_options.norecursedirs = [ "docs", "pro-audit-*" ]
ini_options.addopts = [ "--pdbcls=pdbp:Pdb" ]
ini_options.filterwarnings = []

# Read by the `dead-code` hook (`.ai-instructions/hooks/dead_code.py`). The package
# is listed under `public`: its non-underscore functions are importable helpers
# described in `docs/`, so only `_`-private definitions are reported.
[tool.dead-code]
consumers = [ "src", "docs" ]
public = [ "src/soep_preparation/" ]

[tool.yamlfix]
line_length = 88
sequence_style = "block_style"
Expand Down
18 changes: 9 additions & 9 deletions src/soep_preparation/gettsim_inputs/_generate_input_scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
soep-preparation/src/soep_preparation/gettsim_inputs/_generate_input_scope.py
"""

import datetime
import datetime as dt
import importlib
import json
from pathlib import Path
Expand All @@ -29,30 +29,30 @@
SCOPE_PATH = Path(__file__).with_name("gettsim_input_scope.json")
# GETTSIM rules carry a far-future default end of 2099-12-31; covering past it would add
# a spurious tail period in which every dated rule has expired.
_FIRST_COVERED_DATE = datetime.date(1984, 1, 1)
_LAST_COVERED_DATE = datetime.date(2099, 12, 31)
_LOW_CONFIDENCE_BEFORE = datetime.date(2005, 1, 1)
_FIRST_COVERED_DATE = dt.date(1984, 1, 1)
_LAST_COVERED_DATE = dt.date(2099, 12, 31)
_LOW_CONFIDENCE_BEFORE = dt.date(2005, 1, 1)


def _gettsim_boundary_dates() -> list[datetime.date]:
def _gettsim_boundary_dates() -> list[dt.date]:
"""Return the sorted policy-date boundaries of GETTSIM's column objects."""
gettsim = importlib.import_module("gettsim")
main, main_target = gettsim.main, gettsim.MainTarget
objects = main(
main_target=main_target.orig_policy_objects.column_objects_and_param_functions,
)
boundaries: set[datetime.date] = set()
boundaries: set[dt.date] = set()
for obj in objects.values():
boundaries.add(obj.start_date)
boundaries.add(obj.end_date + datetime.timedelta(days=1))
boundaries.add(obj.end_date + dt.timedelta(days=1))
cuts = {
date for date in boundaries if _FIRST_COVERED_DATE < date <= _LAST_COVERED_DATE
}
cuts.add(_FIRST_COVERED_DATE)
return sorted(cuts)


def _in_scope_at(policy_date: datetime.date) -> frozenset[str]:
def _in_scope_at(policy_date: dt.date) -> frozenset[str]:
"""Return the `BASE_MAPPING` qnames in GETTSIM's environment at `policy_date`."""
gettsim = importlib.import_module("gettsim")
main, main_target = gettsim.main, gettsim.MainTarget
Expand All @@ -68,7 +68,7 @@ def _in_scope_at(policy_date: datetime.date) -> frozenset[str]:
def build_periods() -> list[dict[str, Any]]:
"""Build the collapsed list of policy periods with their in-scope qnames."""
cuts = _gettsim_boundary_dates()
ends = [*(cut - datetime.timedelta(days=1) for cut in cuts[1:]), _LAST_COVERED_DATE]
ends = [*(cut - dt.timedelta(days=1) for cut in cuts[1:]), _LAST_COVERED_DATE]

periods: list[dict[str, Any]] = []
for start, end in zip(cuts, ends, strict=True):
Expand Down
18 changes: 9 additions & 9 deletions src/soep_preparation/gettsim_inputs/mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
early-date slice may omit nodes.
"""

import datetime
import datetime as dt
import functools
import json
from dataclasses import dataclass
Expand Down Expand Up @@ -322,9 +322,9 @@
class MappingPeriod:
"""One policy-date period over which GETTSIM's in-scope qnames are constant."""

start_date: datetime.date
start_date: dt.date
"""First policy date in the period (inclusive)."""
end_date: datetime.date
end_date: dt.date
"""Last policy date in the period (inclusive)."""
low_confidence: bool
"""`True` for periods starting before 2005, where GETTSIM's policy environment is
Expand All @@ -339,8 +339,8 @@ def _periods() -> tuple[MappingPeriod, ...]:
raw = json.loads(_SCOPE_PATH.read_text(encoding="utf-8"))
periods = tuple(
MappingPeriod(
start_date=datetime.date.fromisoformat(entry["start_date"]),
end_date=datetime.date.fromisoformat(entry["end_date"]),
start_date=dt.date.fromisoformat(entry["start_date"]),
end_date=dt.date.fromisoformat(entry["end_date"]),
low_confidence=entry["low_confidence"],
in_scope=frozenset(entry["in_scope"]),
)
Expand All @@ -354,7 +354,7 @@ def mapping_periods() -> tuple[MappingPeriod, ...]:
return _periods()


def period_for_date(policy_date: datetime.date | str) -> MappingPeriod:
def period_for_date(policy_date: dt.date | str) -> MappingPeriod:
"""Return the mapping period containing `policy_date`.

Args:
Expand Down Expand Up @@ -383,7 +383,7 @@ def period_for_date(policy_date: datetime.date | str) -> MappingPeriod:


def get_soep_to_gettsim(
policy_date: datetime.date | str,
policy_date: dt.date | str,
) -> MappingProxyType[str, str | None]:
"""Return the SOEP-to-GETTSIM mapping in scope at `policy_date`.

Expand All @@ -409,7 +409,7 @@ def get_soep_to_gettsim(
)


def _coerce_policy_date(policy_date: datetime.date | str) -> datetime.date:
def _coerce_policy_date(policy_date: dt.date | str) -> dt.date:
"""Coerce a policy date given as an ISO 8601 string to a `datetime.date`.

Args:
Expand All @@ -422,5 +422,5 @@ def _coerce_policy_date(policy_date: datetime.date | str) -> datetime.date:
ValueError: If `policy_date` is a string not in ISO 8601 date format.
"""
if isinstance(policy_date, str):
return datetime.date.fromisoformat(policy_date)
return dt.date.fromisoformat(policy_date)
return policy_date
4 changes: 2 additions & 2 deletions tests/gettsim_inputs/test_build.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Tests for building a GETTSIM-ready dataset from a SOEP final dataset."""

import datetime
import datetime as dt

import pandas as pd
import pytest
Expand Down Expand Up @@ -40,7 +40,7 @@ def test_build_renames_living_space_to_gettsim_qname() -> None:

def test_build_with_policy_date_renames_living_space() -> None:
"""Building with a date-resolved mapping renames the living-space column."""
mapping = get_soep_to_gettsim(datetime.date(2023, 1, 1))
mapping = get_soep_to_gettsim(dt.date(2023, 1, 1))
out = build_gettsim_inputs(_synthetic_final_dataset(), mapping=mapping)
assert "wohnen__wohnfläche_hh" in out.columns

Expand Down
34 changes: 15 additions & 19 deletions tests/gettsim_inputs/test_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
selector returns exactly the qnames in GETTSIM's policy environment at that date.
"""

import datetime
import datetime as dt
import itertools

import pytest
Expand Down Expand Up @@ -87,78 +87,74 @@ def test_kindergeld_amount_is_unmapped_with_documented_gap() -> None:

def test_weiblich_is_in_scope_before_2018() -> None:
"""`weiblich` is a GETTSIM input through 2017 (Altersrente für Frauen)."""
assert "weiblich" in get_soep_to_gettsim(datetime.date(2015, 1, 1))
assert "weiblich" in get_soep_to_gettsim(dt.date(2015, 1, 1))


def test_weiblich_is_out_of_scope_from_2018() -> None:
"""`weiblich` leaves GETTSIM's inputs once the women's pension expires in 2018."""
assert "weiblich" not in get_soep_to_gettsim(datetime.date(2019, 1, 1))
assert "weiblich" not in get_soep_to_gettsim(dt.date(2019, 1, 1))


def test_alg2_einstandspartner_is_in_scope_before_buergergeld() -> None:
"""The ALG II Einstandspartner pointer is in scope before Bürgergeld (2023)."""
mapping = get_soep_to_gettsim(datetime.date(2015, 1, 1))
mapping = get_soep_to_gettsim(dt.date(2015, 1, 1))
assert mapping["arbeitslosengeld_2__p_id_einstandspartner"] == "partner_p_id"


def test_buergergeld_einstandspartner_replaces_alg2_from_2023() -> None:
"""From 2023 the Bürgergeld Einstandspartner pointer is in scope, not ALG II's."""
mapping = get_soep_to_gettsim(datetime.date(2024, 1, 1))
mapping = get_soep_to_gettsim(dt.date(2024, 1, 1))
assert "arbeitslosengeld_2__p_id_einstandspartner" not in mapping
assert mapping["bürgergeld__p_id_einstandspartner"] == "partner_p_id"


def test_erziehungsgeld_is_in_scope_in_its_pre_2007_window() -> None:
"""The pre-2007 Erziehungsgeld nodes are in scope at an early policy date."""
assert "erziehungsgeld__budgetsatz" in get_soep_to_gettsim(
datetime.date(2005, 6, 1)
)
assert "erziehungsgeld__budgetsatz" in get_soep_to_gettsim(dt.date(2005, 6, 1))


def test_erziehungsgeld_is_out_of_scope_after_2007() -> None:
"""Erziehungsgeld leaves scope once Elterngeld replaces it from 2007."""
assert "erziehungsgeld__budgetsatz" not in get_soep_to_gettsim(
datetime.date(2015, 1, 1)
)
assert "erziehungsgeld__budgetsatz" not in get_soep_to_gettsim(dt.date(2015, 1, 1))


def test_resolved_mapping_values_match_base() -> None:
"""A date-resolved mapping reuses the date-invariant `BASE_MAPPING` values."""
mapping = get_soep_to_gettsim(datetime.date(2020, 1, 1))
mapping = get_soep_to_gettsim(dt.date(2020, 1, 1))
assert all(BASE_MAPPING[qname] == value for qname, value in mapping.items())


def test_resolved_qnames_are_a_subset_of_base() -> None:
"""Every resolved qname is one of the candidate qnames in `BASE_MAPPING`."""
mapping = get_soep_to_gettsim(datetime.date(2020, 1, 1))
mapping = get_soep_to_gettsim(dt.date(2020, 1, 1))
assert set(mapping) <= set(BASE_MAPPING)


def test_date_before_coverage_raises() -> None:
"""A policy date before the covered range raises `ValueError`."""
with pytest.raises(ValueError, match="No GETTSIM-input mapping period"):
get_soep_to_gettsim(datetime.date(1900, 1, 1))
get_soep_to_gettsim(dt.date(1900, 1, 1))


def test_pre_2005_period_is_low_confidence() -> None:
"""Periods starting before 2005 are flagged low-confidence."""
assert period_for_date(datetime.date(2000, 1, 1)).low_confidence is True
assert period_for_date(dt.date(2000, 1, 1)).low_confidence is True


def test_recent_period_is_not_low_confidence() -> None:
"""A recent period is not flagged low-confidence."""
assert period_for_date(datetime.date(2024, 1, 1)).low_confidence is False
assert period_for_date(dt.date(2024, 1, 1)).low_confidence is False


def test_period_for_date_accepts_iso_string() -> None:
"""An ISO date string selects the same period as the equivalent `date`."""
assert period_for_date("2024-01-01") == period_for_date(datetime.date(2024, 1, 1))
assert period_for_date("2024-01-01") == period_for_date(dt.date(2024, 1, 1))


def test_get_soep_to_gettsim_accepts_iso_string() -> None:
"""An ISO date string resolves the same mapping as the equivalent `date`."""
assert dict(get_soep_to_gettsim("2024-01-01")) == dict(
get_soep_to_gettsim(datetime.date(2024, 1, 1))
get_soep_to_gettsim(dt.date(2024, 1, 1))
)


Expand All @@ -171,7 +167,7 @@ def test_period_for_date_rejects_malformed_string() -> None:
def test_periods_are_contiguous_and_non_overlapping() -> None:
"""Consecutive periods join with no gap and no overlap."""
periods = mapping_periods()
one_day = datetime.timedelta(days=1)
one_day = dt.timedelta(days=1)
assert all(
later.start_date == earlier.end_date + one_day
for earlier, later in itertools.pairwise(periods)
Expand Down
Loading