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
38 changes: 30 additions & 8 deletions src/uk_open_data/analyses/_need.py
Original file line number Diff line number Diff line change
Expand Up @@ -1323,10 +1323,7 @@ def keep_need_figures(
Raises:
ValueError: If the need is not one the analysis has built in.
"""
if need not in MEASURES:
msg = f"No need called '{need}'. Known needs: {', '.join(MEASURES)}."
raise ValueError(msg)
measure = MEASURES[need]
measure = _built_in(need)
content = {
"need": need,
"label": measure.label,
Expand Down Expand Up @@ -1360,11 +1357,28 @@ def download_need_figures(need: str = "unemployed") -> Path:
ValueError: If the need is not one the analysis has built in, or its
source does not return a count for each local authority.
"""
if need not in MEASURES:
msg = f"No need called '{need}'. Known needs: {', '.join(MEASURES)}."
raise ValueError(msg)
measure = MEASURES[need]
_built_in(need)
clear_need_cache()
return keep_fetched_need_figures(need)


def keep_fetched_need_figures(need: str) -> Path:
"""Keep a need's figures, fetching them only if they are not held in memory.

Needs from one source then share one fetch. Call :func:`clear_need_cache`
first for fresh figures.

Args:
need: One of the needs the analysis has built in, such as ``unemployed``.

Returns:
The path of the file written.

Raises:
ValueError: If the need is not one the analysis has built in, or its
source does not return a count for each local authority.
"""
measure = _built_in(need)
figures = _in_nations(measure.fetch(), measure)
note = f"fetched from {measure.origin} on {date.today().isoformat()}."
return keep_need_figures(
Expand All @@ -1388,6 +1402,14 @@ def clear_need_cache() -> None:
crime.clear_cache()


def _built_in(need: str) -> Measure:
"""Return a built-in need by its name, or say which ones there are."""
if need not in MEASURES:
msg = f"No need called '{need}'. Known needs: {', '.join(MEASURES)}."
raise ValueError(msg)
return MEASURES[need]


# --- the area compared -----------------------------------------------------


Expand Down
41 changes: 37 additions & 4 deletions src/uk_open_data/analyses/datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@
from uk_open_data._nations import NATIONS
from uk_open_data.analyses._centres import _LEVELS, download_centres
from uk_open_data.analyses._model import Source
from uk_open_data.analyses._need import MEASURES, download_need_figures
from uk_open_data.analyses._need import (
MEASURES,
clear_need_cache,
download_need_figures,
keep_fetched_need_figures,
)
from uk_open_data.analyses._steps import ENGLAND_AND_WALES
from uk_open_data.analyses.sources import (
CENSUS_ETHNIC_GROUP,
Expand Down Expand Up @@ -106,6 +111,9 @@ def download_datasets(
The analyses then read the copies instead of the network, so a server or
a demonstration works offline. Run this once when a server is built, and
again when new figures are published. Only public figures are fetched.
When a need is kept, the need figures held in memory are forgotten first,
so they are fetched afresh, and a file that several needs come from is
fetched once.
The copies live in the data folder (see
:func:`uk_open_data.postcodes.offline.data_dir`).

Expand All @@ -121,15 +129,19 @@ def download_datasets(
ValueError: If no id is given in a list, or an id is not a dataset that
can be kept. Nothing is fetched then.
"""
to_keep = _to_keep(ids)
downloads = [download for dataset in to_keep for download in dataset.downloads]
if any(isinstance(download, _NeedDownload) for download in downloads):
clear_need_cache()
# Two datasets kept in one file share its download, which runs once.
written: dict[Callable[[], Path], Path] = {}
kept: dict[str, list[Path]] = {}
for dataset in _to_keep(ids):
for dataset in to_keep:
fresh = [download for download in dataset.downloads if download not in written]
if fresh:
logger.info("Fetching %s.", dataset.source.id)
for download in fresh:
written[download] = download()
written[download] = _run_with_others(download)
kept[dataset.source.id] = [written[download] for download in dataset.downloads]
return kept

Expand Down Expand Up @@ -158,6 +170,17 @@ def _to_keep(ids: str | Iterable[str] | None) -> list[Dataset]:
return [keepable[id_] for id_ in dict.fromkeys(wanted)]


def _run_with_others(download: Callable[[], Path]) -> Path:
"""Run a download as one of several, where needs share what is fetched.

The need figures held in memory were forgotten when the run began, so a
need keeps what a need before it fetched, and does not fetch it again.
"""
if isinstance(download, _NeedDownload):
return keep_fetched_need_figures(download.need)
return download()


def _keep_postcode_table() -> Path:
"""Keep the postcode table this version publishes, unless it is installed.

Expand All @@ -178,7 +201,7 @@ def _kept_for_analyses(source: Source) -> tuple[Callable[[], Path], ...]:
"""
return (
*(
partial(download_need_figures, need)
_NeedDownload(need)
for need, measure in MEASURES.items()
if measure.source.id == source.id
),
Expand All @@ -195,6 +218,16 @@ def _kept_for_analyses(source: Source) -> tuple[Callable[[], Path], ...]:
)


@dataclass(frozen=True)
class _NeedDownload:
"""Fetches a need's figures afresh and keeps them, when run on its own."""

need: str

def __call__(self) -> Path:
return download_need_figures(self.need)


_NEED = ("need-reach", "provision-gap", "access-distance")
# The analyses that place people in neighbourhoods and read their residents
# from the indices of deprivation.
Expand Down
8 changes: 8 additions & 0 deletions tests/test_analysis_need_reach.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,14 @@ def test_only_built_in_needs_can_be_kept():
assert need_figures_path("poverty") is None


def test_an_unknown_need_is_refused_before_figures_are_forgotten(nomis):
_run(_counts(Lewisham=60))
with pytest.raises(ValueError, match="No need called 'poverty'"):
download_need_figures("poverty")
_run(_counts(Lewisham=60))
assert len(nomis.asked) == 2 # the need, and the residents for the map


def test_a_kept_file_that_cannot_be_read_is_an_input_error(nomis):
path = keep_need_figures("unemployed", INVENTED, "invented.")
path.write_text('{"format": "something else"}', encoding="utf-8")
Expand Down
18 changes: 18 additions & 0 deletions tests/test_datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,24 @@ def test_clearing_caches_fetches_the_figures_again(nomis) -> None:
assert _tables_asked(nomis).count("NM_2124_1") == 2


def test_keeping_a_dataset_with_no_need_forgets_no_need_figures(
nomis, tmp_path, empty_data_dir
) -> None:
"""Need figures held in memory outlast a run that keeps no need."""
source = tmp_path / "lookup.csv"
source.write_text(fakes.POSTCODE_LOOKUP_CSV, encoding="utf-8")
table = tmp_path / "postcodes.ktpc.gz"
build_postcode_table(source, table, PUBLISHED_TABLE["edition"])
install_postcode_table(table)
options = {"need": "unemployed"}
run_analysis("need-reach", COUNCIL_COUNTS, options=options)

download_datasets(["ons-postcode-lookup"])

run_analysis("need-reach", COUNCIL_COUNTS, options=options)
assert _tables_asked(nomis).count("NM_2124_1") == 1


def test_an_empty_list_of_datasets_is_refused(nomis, empty_data_dir) -> None:
with pytest.raises(ValueError, match="No dataset was named"):
download_datasets([])
Expand Down
46 changes: 41 additions & 5 deletions tests/test_vaccination_needs.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
"""

from typing import Any
from unittest.mock import MagicMock

import pytest
from need_fakes import COUNCIL_COUNTS, RUNS, area, keep_places, serve_gov_uk
from spreadsheets import ods

from uk_open_data.analyses import AnalysisInputError, AnalysisResult, run_analysis
from uk_open_data.analyses.datasets import download_datasets, list_datasets
from uk_open_data.vaccinations import api

RELEASE_PATH = "/government/statistics/cover-programme-april-2025-to-march-2026"
Expand Down Expand Up @@ -91,26 +93,31 @@ def _table(age: str, vaccines: list[str], figures: list[list[float]]) -> list[An
return [[f"Children aged {age}"], header, *rows]


def _serve(monkeypatch: pytest.MonkeyPatch, at_24_months: str = "MMR1") -> None:
"""Serve UKHSA's statistics, naming the vaccine at 24 months as given."""
def _serve(monkeypatch: pytest.MonkeyPatch, at_24_months: str = "MMR1") -> MagicMock:
"""Serve UKHSA's statistics, naming the vaccine at 24 months as given.

Returns:
The stand-in for the web request, to see what was asked.
"""
workbook = ods(
{
"T4b_UTLA12m": _table("12 months", ["MenB"], AT_24_MONTHS),
"T5b_UTLA24m": _table("24 months", [at_24_months], AT_24_MONTHS),
"T6b_UTLA5y": _table("5 years", ["MMR1", "MMR2"], AT_5_YEARS),
}
)
serve_gov_uk(monkeypatch, PAGES, {RELEASE_FILE: workbook})
return serve_gov_uk(monkeypatch, PAGES, {RELEASE_FILE: workbook})


@pytest.fixture(autouse=True)
def gov_uk(monkeypatch: pytest.MonkeyPatch) -> None:
def gov_uk(monkeypatch: pytest.MonkeyPatch) -> MagicMock:
"""Serve UKHSA's statistics, and keep the residents and centres runs need."""
_serve(monkeypatch)
answer = _serve(monkeypatch)
keep_places(
tuple((code, code, 100000) for code in MORE_COUNCILS),
tuple((code, 52.6 + i / 100, -1.1) for i, code in enumerate(MORE_COUNCILS)),
)
return answer


def _compared(result: AnalysisResult) -> dict[str, int]:
Expand Down Expand Up @@ -193,6 +200,35 @@ def test_a_result_counts_children_without_both_mmr_doses() -> None:
assert "ons-local-authority-lookups" in cited


def test_keeping_both_needs_fetches_ukhsa_once(gov_uk: MagicMock) -> None:
"""Both needs come from one file, so keeping them fetches it once (#238)."""
kept = download_datasets("ukhsa-childhood-vaccinations")

assert [path.name for path in kept["ukhsa-childhood-vaccinations"]] == [
"children_without_mmr1_by_2.json",
"children_without_mmr2_by_5.json",
]
assert [call.args[0] for call in gov_uk.call_args_list] == [
api.CONTENT_API_URL,
RELEASE,
RELEASE_FILE,
]


def test_a_download_run_on_its_own_fetches_afresh(gov_uk: MagicMock) -> None:
"""Outside a run that keeps several, each download asks UKHSA again."""
dataset = next(
dataset
for dataset in list_datasets()
if dataset.source.id == "ukhsa-childhood-vaccinations"
)

for download in dataset.downloads:
download()

assert [call.args[0] for call in gov_uk.call_args_list].count(RELEASE_FILE) == 2


def test_a_renamed_vaccine_says_ukhsa_changed(monkeypatch: pytest.MonkeyPatch) -> None:
_serve(monkeypatch, at_24_months="MMR 1")

Expand Down