from __future__ import annotations from datetime import date import numpy as np import polars as pl from countryatlas.pipeline.changes import Series, compute_changes_and_events, detect_changes, detect_events from countryatlas.registry import indicators_by_id def _series(ind: str, values: list[float], start: int = 2000, country: str = "CAN") -> Series: years = np.arange(start, start + len(values), dtype=np.int32) return Series(country, ind, [date(int(y), 1, 1) for y in years], years, np.array(values, dtype=float)) def test_inflation_drop_headline_and_since() -> None: ind = indicators_by_id()["inflation"] vals = [2.0, 2.1, 1.9, 2.2, 2.0, 2.3, 8.1, 5.9, 5.5, 3.4] # 2015: 5.5 → 2016: 3.4 (−2.1 pts) hmm: last drop 2.1 vals = [2.0, 2.1, 1.9, 2.2, 2.0, 2.3, 2.1, 2.0, 6.8, 3.4] out = detect_changes(_series("inflation", vals, 2016), ind) kinds = {r["kind"]: r for r in out} assert "yoy_drop" in kinds h = kinds["yoy_drop"]["headline"] assert h.startswith("Inflation fell 3.4 points to 3.4 % in 2025") assert "largest drop" in h assert 0 < kinds["yoy_drop"]["severity"] <= 1 def test_floor_blocks_small_moves() -> None: ind = indicators_by_id()["inflation"] # change_floor 2 points vals = [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0] # +1 pt: huge z but below the floor out = detect_changes(_series("inflation", vals), ind) assert not any(r["kind"] in ("yoy_jump", "yoy_drop") for r in out) def test_record_high_and_relative_headline() -> None: ind = indicators_by_id()["gdp-per-capita"] vals = [1000 * 1.03**k for k in range(15)] vals[-1] = vals[-2] * 1.25 out = detect_changes(_series("gdp-per-capita", vals), ind) kinds = {r["kind"] for r in out} assert "record_high" in kinds and "yoy_jump" in kinds jump = next(r for r in out if r["kind"] == "yoy_jump") assert "25.0 %" in jump["headline"] and "US$" in jump["headline"] def test_sign_flip_and_events_history() -> None: ind = indicators_by_id()["gdp-growth"] vals = [3.0, 2.5, 3.1, 2.8, 3.0, 2.9, -4.5, 5.0, 2.0, -1.0] ch = detect_changes(_series("gdp-growth", vals), ind) assert any(r["kind"] == "sign_flip" for r in ch) ev = detect_events(_series("gdp-growth", vals), ind) flips = [r for r in ev if r["kind"] == "sign_flip"] assert len(flips) == 3 # 2006, 2007, 2009 assert any(r["kind"] == "yoy_drop" and r["year"] == 2006 for r in ev) def test_driver_over_frame() -> None: inds = indicators_by_id() rows = [] for c in ("CAN", "FRA"): for k, v in enumerate([2.0, 2.1, 1.9, 2.2, 2.0, 2.3, 2.1, 2.0, 6.8, 3.4]): rows.append({"country_id": c, "indicator_id": "inflation", "period": date(2016 + k, 1, 1), "year": 2016 + k, "value": v}) df = pl.DataFrame(rows) ch, ev = compute_changes_and_events(df, inds) assert ch.filter(pl.col("kind") == "yoy_drop").height == 2 assert set(ch.columns) >= {"id", "country_id", "indicator_id", "kind", "headline", "severity", "detected_at"} assert ev.height >= 2