uk-open-data 0.2.0a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- uk_open_data/__init__.py +39 -0
- uk_open_data/_frames.py +84 -0
- uk_open_data/_kept.py +63 -0
- uk_open_data/_mapping.py +219 -0
- uk_open_data/analyses/__init__.py +98 -0
- uk_open_data/analyses/_answers.py +182 -0
- uk_open_data/analyses/_centres.py +494 -0
- uk_open_data/analyses/_inputs.py +133 -0
- uk_open_data/analyses/_labels.py +74 -0
- uk_open_data/analyses/_model.py +433 -0
- uk_open_data/analyses/_need.py +617 -0
- uk_open_data/analyses/_privacy.py +180 -0
- uk_open_data/analyses/_registry.py +289 -0
- uk_open_data/analyses/_steps.py +747 -0
- uk_open_data/analyses/access_distance.py +817 -0
- uk_open_data/analyses/maps.py +1222 -0
- uk_open_data/analyses/need_reach.py +1188 -0
- uk_open_data/analyses/provision_gap.py +925 -0
- uk_open_data/analyses/reach_deprivation.py +1128 -0
- uk_open_data/analyses/sources.py +82 -0
- uk_open_data/analyses/who_we_miss.py +1331 -0
- uk_open_data/cli.py +622 -0
- uk_open_data/connector/__init__.py +54 -0
- uk_open_data/connector/__main__.py +6 -0
- uk_open_data/connector/analyses.py +425 -0
- uk_open_data/connector/command.py +74 -0
- uk_open_data/connector/maps.py +336 -0
- uk_open_data/connector/places.py +644 -0
- uk_open_data/connector/privacy.py +104 -0
- uk_open_data/connector/server.py +330 -0
- uk_open_data/geo/__init__.py +33 -0
- uk_open_data/geo/_catalog.py +69 -0
- uk_open_data/geo/_enums.py +116 -0
- uk_open_data/geo/_ingestion.py +258 -0
- uk_open_data/geo/api.py +405 -0
- uk_open_data/geo/data/arcgis_services.csv +655 -0
- uk_open_data/imd/__init__.py +17 -0
- uk_open_data/imd/api.py +621 -0
- uk_open_data/ons/__init__.py +12 -0
- uk_open_data/ons/_catalog.py +42 -0
- uk_open_data/ons/_ingestion.py +100 -0
- uk_open_data/ons/api.py +199 -0
- uk_open_data/ons/data/nomis_tables.csv +1616 -0
- uk_open_data/postcodes/__init__.py +44 -0
- uk_open_data/postcodes/api.py +318 -0
- uk_open_data/postcodes/offline.py +488 -0
- uk_open_data-0.2.0a1.dist-info/METADATA +188 -0
- uk_open_data-0.2.0a1.dist-info/RECORD +53 -0
- uk_open_data-0.2.0a1.dist-info/WHEEL +5 -0
- uk_open_data-0.2.0a1.dist-info/entry_points.txt +3 -0
- uk_open_data-0.2.0a1.dist-info/licenses/LICENSE +202 -0
- uk_open_data-0.2.0a1.dist-info/licenses/NOTICE +32 -0
- uk_open_data-0.2.0a1.dist-info/top_level.txt +1 -0
uk_open_data/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""UK open data for charities: boundaries, statistics, postcodes and analyses."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("uk-open-data")
|
|
7
|
+
except PackageNotFoundError:
|
|
8
|
+
# Package is not installed
|
|
9
|
+
__version__ = "0.0.0"
|
|
10
|
+
|
|
11
|
+
# Import key functions for easier access
|
|
12
|
+
from uk_open_data._mapping import (
|
|
13
|
+
list_dataset_aliases,
|
|
14
|
+
list_geography_mappings,
|
|
15
|
+
)
|
|
16
|
+
from uk_open_data.geo import geodata_to_properties, load_geodata
|
|
17
|
+
from uk_open_data.imd import load_imd
|
|
18
|
+
from uk_open_data.ons import list_tables, load_ons
|
|
19
|
+
from uk_open_data.postcodes import (
|
|
20
|
+
lookup_outcodes,
|
|
21
|
+
lookup_postcodes,
|
|
22
|
+
outcode_to_geography,
|
|
23
|
+
postcodes_to_geography,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
# Define what's available when using `from uk_open_data import *`
|
|
27
|
+
__all__ = [
|
|
28
|
+
"geodata_to_properties",
|
|
29
|
+
"list_dataset_aliases",
|
|
30
|
+
"list_geography_mappings",
|
|
31
|
+
"list_tables",
|
|
32
|
+
"load_geodata",
|
|
33
|
+
"load_imd",
|
|
34
|
+
"load_ons",
|
|
35
|
+
"lookup_outcodes",
|
|
36
|
+
"lookup_postcodes",
|
|
37
|
+
"outcode_to_geography",
|
|
38
|
+
"postcodes_to_geography",
|
|
39
|
+
]
|
uk_open_data/_frames.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Shared helpers for building native DataFrames (pandas or polars).
|
|
2
|
+
|
|
3
|
+
KindTech is backend-agnostic (Bring Your Own DataFrame): it returns whatever
|
|
4
|
+
backend the user has installed. These helpers centralise backend detection and
|
|
5
|
+
construction so the ``ons`` and ``postcodes`` modules don't each reimplement it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from importlib import import_module
|
|
9
|
+
from io import BytesIO, StringIO
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def get_native_namespace() -> Any:
|
|
14
|
+
"""Return the DataFrame backend module to build native frames with.
|
|
15
|
+
|
|
16
|
+
KindTech depends only on ``narwhals`` (plus ``requests``), not on pandas or
|
|
17
|
+
polars — users bring whichever they already use. This detects what's
|
|
18
|
+
installed rather than forcing one: polars is tried first (faster, and the
|
|
19
|
+
narwhals-native backend) and pandas second. The order only matters when
|
|
20
|
+
*both* are installed; if neither is, a clear ImportError tells the user to
|
|
21
|
+
install one.
|
|
22
|
+
"""
|
|
23
|
+
try:
|
|
24
|
+
return import_module("polars")
|
|
25
|
+
except ImportError:
|
|
26
|
+
pass
|
|
27
|
+
try:
|
|
28
|
+
return import_module("pandas")
|
|
29
|
+
except ImportError:
|
|
30
|
+
pass
|
|
31
|
+
msg = (
|
|
32
|
+
"No DataFrame backend found. "
|
|
33
|
+
"Install pandas or polars: `uv add pandas` or `uv add polars`"
|
|
34
|
+
)
|
|
35
|
+
raise ImportError(msg)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def dicts_to_frame(rows: list[dict]) -> Any:
|
|
39
|
+
"""Build a native DataFrame from a list of row dicts.
|
|
40
|
+
|
|
41
|
+
Column order follows the keys of the first row. Missing keys in later rows
|
|
42
|
+
are filled with ``None``.
|
|
43
|
+
"""
|
|
44
|
+
native_ns = get_native_namespace()
|
|
45
|
+
if not rows:
|
|
46
|
+
return native_ns.DataFrame()
|
|
47
|
+
columns = {key: [row.get(key) for row in rows] for key in rows[0]}
|
|
48
|
+
return native_ns.DataFrame(columns)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def csv_to_frame(text: str) -> Any:
|
|
52
|
+
"""Parse CSV text into a native DataFrame using the available backend."""
|
|
53
|
+
return get_native_namespace().read_csv(StringIO(text))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def read_spreadsheet_rows(
|
|
57
|
+
content: bytes, sheet_name: str, header_row: int = 0
|
|
58
|
+
) -> list[dict[str, Any]]:
|
|
59
|
+
"""Read one sheet of an XLSX/ODS workbook into a list of row dicts.
|
|
60
|
+
|
|
61
|
+
Uses ``python-calamine`` (one fast reader for both formats). ``header_row``
|
|
62
|
+
is the 0-based index of the header line; rows above it are ignored. Header
|
|
63
|
+
cells are stringified and stripped; fully empty rows are dropped.
|
|
64
|
+
"""
|
|
65
|
+
try:
|
|
66
|
+
from python_calamine import CalamineWorkbook
|
|
67
|
+
except ImportError as exc:
|
|
68
|
+
msg = (
|
|
69
|
+
"Reading XLSX/ODS sources needs python-calamine. "
|
|
70
|
+
"Install it: `uv add python-calamine`"
|
|
71
|
+
)
|
|
72
|
+
raise ImportError(msg) from exc
|
|
73
|
+
|
|
74
|
+
rows = (
|
|
75
|
+
CalamineWorkbook.from_filelike(BytesIO(content))
|
|
76
|
+
.get_sheet_by_name(sheet_name)
|
|
77
|
+
.to_python()
|
|
78
|
+
)
|
|
79
|
+
header = [str(cell).strip() for cell in rows[header_row]]
|
|
80
|
+
return [
|
|
81
|
+
dict(zip(header, row, strict=False))
|
|
82
|
+
for row in rows[header_row + 1 :]
|
|
83
|
+
if any(cell not in (None, "") for cell in row)
|
|
84
|
+
]
|
uk_open_data/_kept.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Public figures kept on this machine, so they do not have to be fetched.
|
|
2
|
+
|
|
3
|
+
A kept file is JSON with a ``format`` that names what it holds and a ``note``
|
|
4
|
+
that says where the figures came from. Files live in the data folder, beside
|
|
5
|
+
the postcode table.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from uk_open_data.postcodes.offline import data_dir
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def kept_file(folder: str, name: str) -> Path:
|
|
18
|
+
"""Return where a kept file goes, whether or not it is there."""
|
|
19
|
+
return data_dir() / folder / f"{name}.json"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def write_kept(
|
|
23
|
+
folder: str,
|
|
24
|
+
name: str,
|
|
25
|
+
file_format: str,
|
|
26
|
+
note: str,
|
|
27
|
+
content: dict[str, Any],
|
|
28
|
+
*,
|
|
29
|
+
compact: bool = False,
|
|
30
|
+
) -> Path:
|
|
31
|
+
"""Write a kept file and return its path.
|
|
32
|
+
|
|
33
|
+
A small file is laid out for a person to read. Pass ``compact`` for a
|
|
34
|
+
large table, which is written on one line to keep the file small.
|
|
35
|
+
"""
|
|
36
|
+
path = kept_file(folder, name)
|
|
37
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
38
|
+
kept = {"format": file_format, "note": note, **content}
|
|
39
|
+
text = json.dumps(kept, indent=None if compact else 1)
|
|
40
|
+
path.write_text(text + "\n", encoding="utf-8")
|
|
41
|
+
return path
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def read_kept(folder: str, name: str, file_format: str) -> dict[str, Any] | None:
|
|
45
|
+
"""Read a kept file.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
What the file holds, or None when there is no such file.
|
|
49
|
+
|
|
50
|
+
Raises:
|
|
51
|
+
ValueError: If the file is not JSON, or holds something else.
|
|
52
|
+
"""
|
|
53
|
+
path = kept_file(folder, name)
|
|
54
|
+
if not path.is_file():
|
|
55
|
+
return None
|
|
56
|
+
kept = json.loads(path.read_text(encoding="utf-8"))
|
|
57
|
+
if not isinstance(kept, dict) or kept.get("format") != file_format:
|
|
58
|
+
msg = f"{path.name} is not a {file_format} file."
|
|
59
|
+
raise ValueError(msg)
|
|
60
|
+
if not isinstance(kept.get("note"), str):
|
|
61
|
+
msg = f"{path.name} has no note."
|
|
62
|
+
raise ValueError(msg)
|
|
63
|
+
return kept
|
uk_open_data/_mapping.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Geography crosswalk and dataset aliases for ONS/NOMIS data.
|
|
3
|
+
|
|
4
|
+
Maps the GeographyType codes used in ``uk_open_data.geo`` to the internal
|
|
5
|
+
TYPE codes used by the NOMIS API, handling the fact that NOMIS assigns
|
|
6
|
+
different TYPE codes to the same geography concept at different time
|
|
7
|
+
points (e.g. LADs are TYPE424 from 2023, TYPE431 for 2021-2022, etc.).
|
|
8
|
+
|
|
9
|
+
Also provides friendly dataset aliases so users can say
|
|
10
|
+
``load_ons("population")`` instead of ``load_ons("NM_2002_1")``.
|
|
11
|
+
|
|
12
|
+
Both APIs return standard ONS geography codes (e.g. E06000001) so
|
|
13
|
+
joins between geo boundaries and NOMIS statistics are reliable on
|
|
14
|
+
codes, not names.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from typing import overload
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@overload
|
|
23
|
+
def extract_code(value: None) -> None: ...
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@overload
|
|
27
|
+
def extract_code(value: object) -> str: ...
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def extract_code(value: object | None) -> str | None:
|
|
31
|
+
"""Extract string code from an enum or pass through a string."""
|
|
32
|
+
if value is None:
|
|
33
|
+
return None
|
|
34
|
+
code = value.code if hasattr(value, "code") else value
|
|
35
|
+
return str(code)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# Each value is a list of (min_year, max_year, nomis_type_code) tuples,
|
|
39
|
+
# sorted newest-first. The first match for a given year wins.
|
|
40
|
+
# Source: NOMIS geography dimension metadata via
|
|
41
|
+
# nomisweb.co.uk/api/v01/dataset/NM_1_1/geography.def.sdmx.json
|
|
42
|
+
NOMIS_GEO_TYPES: dict[str, list[tuple[int, int, str]]] = {
|
|
43
|
+
"LAD": [
|
|
44
|
+
(2023, 9999, "TYPE424"),
|
|
45
|
+
(2021, 2022, "TYPE431"),
|
|
46
|
+
(2019, 2020, "TYPE434"),
|
|
47
|
+
(2015, 2018, "TYPE446"),
|
|
48
|
+
(0, 2014, "TYPE464"),
|
|
49
|
+
],
|
|
50
|
+
"CTYUA": [
|
|
51
|
+
(2023, 9999, "TYPE423"),
|
|
52
|
+
(2021, 2022, "TYPE431"),
|
|
53
|
+
(2015, 2020, "TYPE446"),
|
|
54
|
+
(0, 2014, "TYPE463"),
|
|
55
|
+
],
|
|
56
|
+
"LSOA": [
|
|
57
|
+
(2021, 9999, "TYPE151"),
|
|
58
|
+
(0, 2020, "TYPE304"),
|
|
59
|
+
],
|
|
60
|
+
"MSOA": [
|
|
61
|
+
(2021, 9999, "TYPE152"),
|
|
62
|
+
(0, 2020, "TYPE305"),
|
|
63
|
+
],
|
|
64
|
+
"RGN": [(0, 9999, "TYPE480")],
|
|
65
|
+
"CTRY": [(0, 9999, "TYPE499")],
|
|
66
|
+
"WD": [(2025, 9999, "TYPE182")],
|
|
67
|
+
"CAUTH": [(2025, 9999, "TYPE442")],
|
|
68
|
+
"TTWA": [
|
|
69
|
+
(2011, 9999, "TYPE447"),
|
|
70
|
+
(0, 2010, "TYPE444"),
|
|
71
|
+
],
|
|
72
|
+
"ITL": [
|
|
73
|
+
(2025, 9999, "TYPE419"),
|
|
74
|
+
(2021, 2024, "TYPE421"),
|
|
75
|
+
],
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
# Friendly aliases for common NOMIS datasets.
|
|
79
|
+
# Keys are lowercase; values are NOMIS dataset IDs.
|
|
80
|
+
DATASET_ALIASES: dict[str, str] = {
|
|
81
|
+
# Population
|
|
82
|
+
"population": "NM_2002_1",
|
|
83
|
+
"population_by_age": "NM_2002_1",
|
|
84
|
+
"population_by_age_band": "NM_31_1",
|
|
85
|
+
"population_lsoa": "NM_2014_1",
|
|
86
|
+
# Employment / labour market
|
|
87
|
+
"jsa": "NM_1_1",
|
|
88
|
+
"claimant_count": "NM_162_1",
|
|
89
|
+
"annual_population_survey": "NM_17_1",
|
|
90
|
+
"earnings": "NM_30_1",
|
|
91
|
+
"jobs_density": "NM_57_1",
|
|
92
|
+
"vacancies": "NM_19_1",
|
|
93
|
+
# Business
|
|
94
|
+
"vat_registrations": "NM_29_1",
|
|
95
|
+
# Census
|
|
96
|
+
"census_2021": "NM_2021_1",
|
|
97
|
+
"census_2011": "NM_144_1",
|
|
98
|
+
"census_2001": "NM_58_1",
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def resolve_dataset_id(dataset_id: str) -> str:
|
|
103
|
+
"""Resolve a dataset ID or friendly alias to a NOMIS dataset ID.
|
|
104
|
+
|
|
105
|
+
If ``dataset_id`` starts with ``NM_``, returns it unchanged.
|
|
106
|
+
Otherwise looks up the alias in ``DATASET_ALIASES``.
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
dataset_id: NOMIS dataset ID (e.g. ``"NM_1_1"``) or friendly
|
|
110
|
+
alias (e.g. ``"population"``).
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
NOMIS dataset ID string.
|
|
114
|
+
|
|
115
|
+
Raises:
|
|
116
|
+
ValueError: If the alias is not recognised.
|
|
117
|
+
"""
|
|
118
|
+
if dataset_id.startswith("NM_"):
|
|
119
|
+
return dataset_id
|
|
120
|
+
key = dataset_id.lower().strip()
|
|
121
|
+
if key in DATASET_ALIASES:
|
|
122
|
+
return DATASET_ALIASES[key]
|
|
123
|
+
available = ", ".join(sorted(DATASET_ALIASES))
|
|
124
|
+
msg = (
|
|
125
|
+
f"Unknown dataset alias '{dataset_id}'. "
|
|
126
|
+
f"Available: {available}. "
|
|
127
|
+
f"Or pass a NOMIS ID like 'NM_1_1'."
|
|
128
|
+
)
|
|
129
|
+
raise ValueError(msg)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def list_dataset_aliases() -> list[dict[str, str]]:
|
|
133
|
+
"""Return dataset aliases as a list of dicts.
|
|
134
|
+
|
|
135
|
+
Each dict has keys: ``alias``, ``dataset_id``.
|
|
136
|
+
"""
|
|
137
|
+
return [
|
|
138
|
+
{"alias": alias, "dataset_id": did}
|
|
139
|
+
for alias, did in sorted(DATASET_ALIASES.items())
|
|
140
|
+
]
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def resolve_nomis_geography(
|
|
144
|
+
geography_type: str,
|
|
145
|
+
year: int | None = None,
|
|
146
|
+
) -> str:
|
|
147
|
+
"""Resolve a geography type code to a NOMIS TYPE code.
|
|
148
|
+
|
|
149
|
+
Args:
|
|
150
|
+
geography_type: ONS geography code
|
|
151
|
+
(e.g. ``"LAD"``, ``"LSOA"``).
|
|
152
|
+
year: Optional year for version-specific resolution.
|
|
153
|
+
If ``None``, returns the most recent TYPE code.
|
|
154
|
+
|
|
155
|
+
Returns:
|
|
156
|
+
NOMIS TYPE code string (e.g. ``"TYPE424"``).
|
|
157
|
+
|
|
158
|
+
Raises:
|
|
159
|
+
ValueError: If the geography type has no NOMIS mapping.
|
|
160
|
+
"""
|
|
161
|
+
code = geography_type.upper()
|
|
162
|
+
ranges = NOMIS_GEO_TYPES.get(code)
|
|
163
|
+
if not ranges:
|
|
164
|
+
supported = ", ".join(sorted(NOMIS_GEO_TYPES))
|
|
165
|
+
msg = f"No NOMIS mapping for geography type '{code}'. Supported: {supported}"
|
|
166
|
+
raise ValueError(msg)
|
|
167
|
+
|
|
168
|
+
if year is None:
|
|
169
|
+
return ranges[0][2]
|
|
170
|
+
|
|
171
|
+
for min_year, max_year, type_code in ranges:
|
|
172
|
+
if min_year <= year <= max_year:
|
|
173
|
+
return type_code
|
|
174
|
+
|
|
175
|
+
msg = (
|
|
176
|
+
f"No NOMIS TYPE code for '{code}' in year {year}. "
|
|
177
|
+
f"Available ranges: " + ", ".join(f"{lo}-{hi} → {tc}" for lo, hi, tc in ranges)
|
|
178
|
+
)
|
|
179
|
+
raise ValueError(msg)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def geo_code_field(geography_type: str, year: int) -> str:
|
|
183
|
+
"""Return the ArcGIS code field name.
|
|
184
|
+
|
|
185
|
+
Example:
|
|
186
|
+
>>> geo_code_field("LAD", 2024)
|
|
187
|
+
'LAD24CD'
|
|
188
|
+
"""
|
|
189
|
+
return f"{geography_type.upper()}{year % 100:02d}CD"
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def geo_name_field(geography_type: str, year: int) -> str:
|
|
193
|
+
"""Return the ArcGIS name field name.
|
|
194
|
+
|
|
195
|
+
Example:
|
|
196
|
+
>>> geo_name_field("LAD", 2024)
|
|
197
|
+
'LAD24NM'
|
|
198
|
+
"""
|
|
199
|
+
return f"{geography_type.upper()}{year % 100:02d}NM"
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def list_geography_mappings() -> list[dict[str, str]]:
|
|
203
|
+
"""Return the geography crosswalk as a list of dicts.
|
|
204
|
+
|
|
205
|
+
Each dict has keys: ``geography_type``, ``year_from``,
|
|
206
|
+
``year_to``, ``nomis_type``.
|
|
207
|
+
"""
|
|
208
|
+
rows: list[dict[str, str]] = []
|
|
209
|
+
for geo_type, ranges in sorted(NOMIS_GEO_TYPES.items()):
|
|
210
|
+
for min_year, max_year, type_code in ranges:
|
|
211
|
+
rows.append(
|
|
212
|
+
{
|
|
213
|
+
"geography_type": geo_type,
|
|
214
|
+
"year_from": (str(min_year) if min_year > 0 else ""),
|
|
215
|
+
"year_to": (str(max_year) if max_year < 9999 else ""),
|
|
216
|
+
"nomis_type": type_code,
|
|
217
|
+
}
|
|
218
|
+
)
|
|
219
|
+
return rows
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Analyses: questions a charity can ask of its own data.
|
|
2
|
+
|
|
3
|
+
An analysis takes a charity's data, joins it to UK open data, and returns figures
|
|
4
|
+
with their sources, a map description, the working, the choices it made and
|
|
5
|
+
the checks a person should do. Results hold totals only, never rows.
|
|
6
|
+
|
|
7
|
+
>>> from uk_open_data.analyses import list_analyses, run_analysis
|
|
8
|
+
>>> [analysis.id for analysis in list_analyses()]
|
|
9
|
+
['reach-deprivation', 'need-reach', 'who-we-miss', 'provision-gap',
|
|
10
|
+
'access-distance']
|
|
11
|
+
>>> result = run_analysis(
|
|
12
|
+
... "reach-deprivation",
|
|
13
|
+
... clients,
|
|
14
|
+
... columns={"postcode": "Client postcode"},
|
|
15
|
+
... ) # doctest: +SKIP
|
|
16
|
+
>>> result.figure("share_most_deprived_20").value # doctest: +SKIP
|
|
17
|
+
41.3
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from uk_open_data.analyses import access_distance as _access_distance
|
|
21
|
+
from uk_open_data.analyses import need_reach as _need_reach
|
|
22
|
+
from uk_open_data.analyses import provision_gap as _provision_gap
|
|
23
|
+
from uk_open_data.analyses import reach_deprivation as _reach_deprivation
|
|
24
|
+
from uk_open_data.analyses import who_we_miss as _who_we_miss
|
|
25
|
+
from uk_open_data.analyses._model import (
|
|
26
|
+
Analysis,
|
|
27
|
+
AnalysisInfo,
|
|
28
|
+
AnalysisInput,
|
|
29
|
+
AnalysisInputError,
|
|
30
|
+
AnalysisResult,
|
|
31
|
+
Chart,
|
|
32
|
+
ChartSeries,
|
|
33
|
+
Check,
|
|
34
|
+
Choice,
|
|
35
|
+
Figure,
|
|
36
|
+
InputMode,
|
|
37
|
+
MapLayer,
|
|
38
|
+
MapSpec,
|
|
39
|
+
Option,
|
|
40
|
+
OptionChoice,
|
|
41
|
+
Privacy,
|
|
42
|
+
Role,
|
|
43
|
+
Source,
|
|
44
|
+
Step,
|
|
45
|
+
Table,
|
|
46
|
+
)
|
|
47
|
+
from uk_open_data.analyses._registry import (
|
|
48
|
+
DOORS,
|
|
49
|
+
RUNS_LOGGER,
|
|
50
|
+
describe_analysis,
|
|
51
|
+
list_analyses,
|
|
52
|
+
record_run,
|
|
53
|
+
register_analysis,
|
|
54
|
+
run_analysis,
|
|
55
|
+
)
|
|
56
|
+
from uk_open_data.analyses.maps import load_map_boundaries, render_map
|
|
57
|
+
|
|
58
|
+
# Analyses are listed in this order.
|
|
59
|
+
for _analysis in (
|
|
60
|
+
_reach_deprivation.ANALYSIS,
|
|
61
|
+
_need_reach.ANALYSIS,
|
|
62
|
+
_who_we_miss.ANALYSIS,
|
|
63
|
+
_provision_gap.ANALYSIS,
|
|
64
|
+
_access_distance.ANALYSIS,
|
|
65
|
+
):
|
|
66
|
+
register_analysis(_analysis)
|
|
67
|
+
|
|
68
|
+
__all__ = [
|
|
69
|
+
"DOORS",
|
|
70
|
+
"RUNS_LOGGER",
|
|
71
|
+
"Chart",
|
|
72
|
+
"ChartSeries",
|
|
73
|
+
"Check",
|
|
74
|
+
"Choice",
|
|
75
|
+
"Figure",
|
|
76
|
+
"InputMode",
|
|
77
|
+
"Analysis",
|
|
78
|
+
"AnalysisInfo",
|
|
79
|
+
"AnalysisInput",
|
|
80
|
+
"AnalysisInputError",
|
|
81
|
+
"AnalysisResult",
|
|
82
|
+
"MapLayer",
|
|
83
|
+
"MapSpec",
|
|
84
|
+
"Option",
|
|
85
|
+
"OptionChoice",
|
|
86
|
+
"Privacy",
|
|
87
|
+
"Role",
|
|
88
|
+
"Source",
|
|
89
|
+
"Step",
|
|
90
|
+
"Table",
|
|
91
|
+
"describe_analysis",
|
|
92
|
+
"list_analyses",
|
|
93
|
+
"load_map_boundaries",
|
|
94
|
+
"record_run",
|
|
95
|
+
"register_analysis",
|
|
96
|
+
"render_map",
|
|
97
|
+
"run_analysis",
|
|
98
|
+
]
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""Words shared by the sentences that answer an analysis's question.
|
|
2
|
+
|
|
3
|
+
Every analysis ends with a sentence or two that answer its question. The
|
|
4
|
+
sentence is built from the figures and tables the result holds, after small
|
|
5
|
+
counts are hidden, so it can say nothing the result does not already show.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from uk_open_data.analyses._model import Figure, Table
|
|
15
|
+
|
|
16
|
+
AREA = "the area you serve"
|
|
17
|
+
HIDDEN = "hidden to protect a small count"
|
|
18
|
+
NAMED = 3 # how many places or groups a sentence names before it counts the rest
|
|
19
|
+
SHOWN_FIRST = 3 # how many key figures a result names
|
|
20
|
+
# An answer says how many people it leaves out when they are this share or more.
|
|
21
|
+
LARGE_SHARE_LEFT_OUT = 0.2
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class NeedWords:
|
|
26
|
+
"""The words for the people a need counts, so a sentence fits the measure."""
|
|
27
|
+
|
|
28
|
+
people: str
|
|
29
|
+
per: str
|
|
30
|
+
high: str
|
|
31
|
+
# For labels and headings: what is counted, and the places with most of it.
|
|
32
|
+
noun: str = "people in need"
|
|
33
|
+
places: str = "high-need local authorities"
|
|
34
|
+
# What a label calls the total: "People in need in the area you serve".
|
|
35
|
+
counted: str = "People in need"
|
|
36
|
+
# What a title sets beside reach or provision: "Need and reach".
|
|
37
|
+
topic: str = "need"
|
|
38
|
+
# What the working says of a place in the top quarter.
|
|
39
|
+
rule: str = "is high need"
|
|
40
|
+
|
|
41
|
+
def headings(self) -> dict[str, str]:
|
|
42
|
+
"""Headings for the columns about need, in the words that fit."""
|
|
43
|
+
if self.noun == IN_NEED.noun:
|
|
44
|
+
return {}
|
|
45
|
+
return {
|
|
46
|
+
"people_in_need": "Residents",
|
|
47
|
+
"people_per_100_in_need": "Your people per 100 residents",
|
|
48
|
+
"volume_per_1000_in_need": "Provision per 1,000 residents",
|
|
49
|
+
"high_need": "Among the most residents",
|
|
50
|
+
"need_band": "Residents, grouped",
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
IN_NEED = NeedWords("the people in need", "in need", "high need")
|
|
55
|
+
# Every resident is not a need, so no sentence, label or heading calls it one.
|
|
56
|
+
ALL_RESIDENTS = NeedWords(
|
|
57
|
+
"residents",
|
|
58
|
+
"residents",
|
|
59
|
+
"the most residents",
|
|
60
|
+
noun="residents",
|
|
61
|
+
places="the local authorities with the most residents",
|
|
62
|
+
counted="People",
|
|
63
|
+
topic="residents",
|
|
64
|
+
rule="is among those with the most residents",
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def sentence_case(text: str) -> str:
|
|
69
|
+
"""Start a label with a capital letter and leave the rest as it is."""
|
|
70
|
+
return text[:1].upper() + text[1:]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def need_words(residents: bool) -> NeedWords:
|
|
74
|
+
"""Pick the words for a measure of need, or for a count of every resident."""
|
|
75
|
+
return ALL_RESIDENTS if residents else IN_NEED
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def shown_first(figures: Sequence[Figure], wanted: Sequence[str]) -> tuple[str, ...]:
|
|
79
|
+
"""The first three of the wanted figures that are not hidden, in order.
|
|
80
|
+
|
|
81
|
+
A figure hidden to protect a small count has nothing to show, so the next
|
|
82
|
+
wanted figure takes its place.
|
|
83
|
+
"""
|
|
84
|
+
hidden = {figure.id for figure in figures if figure.suppressed}
|
|
85
|
+
return tuple(i for i in wanted if i not in hidden)[:SHOWN_FIRST]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def values(figures: Sequence[Figure]) -> dict[str, Any]:
|
|
89
|
+
"""The value of each figure by its id. A hidden figure has ``None``."""
|
|
90
|
+
return {figure.id: figure.value for figure in figures}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def column(table: Table, name: str) -> list[Any]:
|
|
94
|
+
"""One column of a table, in the order of its rows."""
|
|
95
|
+
return [row[name] for row in table.rows]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def names(items: Sequence[str], last: str = "and") -> str:
|
|
99
|
+
"""Join names as a person would say them, counting any beyond the first few."""
|
|
100
|
+
shown = list(items[:NAMED])
|
|
101
|
+
more = len(items) - len(shown)
|
|
102
|
+
if more:
|
|
103
|
+
return f"{', '.join(shown)} {last} {more} more"
|
|
104
|
+
if len(shown) == 1:
|
|
105
|
+
return shown[0]
|
|
106
|
+
return f"{', '.join(shown[:-1])} {last} {shown[-1]}"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def look_first(
|
|
110
|
+
priority: Table,
|
|
111
|
+
lowest: str,
|
|
112
|
+
rate: str,
|
|
113
|
+
overall: float | None,
|
|
114
|
+
high: str = IN_NEED.high,
|
|
115
|
+
) -> str:
|
|
116
|
+
"""Name the first few listed places that fall below the whole area, or none.
|
|
117
|
+
|
|
118
|
+
A priority list holds every high-need place when there are few, so its
|
|
119
|
+
first rows are not always places that lag. A place is named only when its
|
|
120
|
+
rate, in the column ``rate``, is below the rate for the whole area,
|
|
121
|
+
``overall``. A place whose rate is hidden is not named.
|
|
122
|
+
|
|
123
|
+
``lowest`` says what the list is in order of, such as "your lowest reach".
|
|
124
|
+
The sentence starts with a space so it can follow another.
|
|
125
|
+
"""
|
|
126
|
+
places = [
|
|
127
|
+
row["geography_name"]
|
|
128
|
+
for row in priority.rows
|
|
129
|
+
if row[rate] is not None and (overall is None or row[rate] < overall)
|
|
130
|
+
][:NAMED]
|
|
131
|
+
if not places:
|
|
132
|
+
return ""
|
|
133
|
+
if len(places) == 1:
|
|
134
|
+
return f" The place to look at first, with {high} and {lowest}, is {places[0]}."
|
|
135
|
+
return (
|
|
136
|
+
f" The places to look at first, with {high} and {lowest}, are {names(places)}."
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def not_counted(supplied: int | None, located: int | None, counted: int) -> str:
|
|
141
|
+
"""Say how many people an answer leaves out, when it is a large share.
|
|
142
|
+
|
|
143
|
+
People who could not be placed at all are a mistake in the data to put
|
|
144
|
+
right. People who live outside the area are not. So when there are both,
|
|
145
|
+
the sentence says how many of each. It starts with a space so it can
|
|
146
|
+
follow another.
|
|
147
|
+
|
|
148
|
+
A total hidden so that a few people left out cannot be worked out is
|
|
149
|
+
``None``. The sentence then goes by the people placed, and says nothing
|
|
150
|
+
when they are hidden too.
|
|
151
|
+
"""
|
|
152
|
+
if supplied is None:
|
|
153
|
+
if located is None or located - counted < LARGE_SHARE_LEFT_OUT * located:
|
|
154
|
+
return ""
|
|
155
|
+
return (
|
|
156
|
+
f" {number(located - counted)} of the {number(located)} people placed "
|
|
157
|
+
f"in a local authority live outside {AREA} and are not counted."
|
|
158
|
+
)
|
|
159
|
+
left_out = supplied - counted
|
|
160
|
+
if left_out < LARGE_SHARE_LEFT_OUT * supplied:
|
|
161
|
+
return ""
|
|
162
|
+
opening = f" {number(left_out)} of the {number(supplied)} people in your data"
|
|
163
|
+
if located is not None and supplied - located and located - counted:
|
|
164
|
+
unplaced, outside = supplied - located, located - counted
|
|
165
|
+
return (
|
|
166
|
+
f"{opening} are not counted: {number(unplaced)} could not be "
|
|
167
|
+
f"placed in a local authority, and {number(outside)} live outside "
|
|
168
|
+
f"{AREA}."
|
|
169
|
+
)
|
|
170
|
+
return f"{opening} could not be placed in {AREA} and are not counted."
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def number(value: float) -> str:
|
|
174
|
+
"""A number as the figures show it, with commas in the thousands."""
|
|
175
|
+
return f"{value:,}"
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def high_need_places(count: int, high: str = IN_NEED.high) -> str:
|
|
179
|
+
"""Name the local authorities with high need, by how many there are."""
|
|
180
|
+
if count == 1:
|
|
181
|
+
return f"the one local authority with {high}"
|
|
182
|
+
return f"the {count} local authorities with {high}"
|