# uk-open-data
> UK open data in Python for civil society, from charities and community groups to researchers and students. Load public data and join it to your own.
- Install with `uv add uk-open-data` and import `uk_open_data`. `kindtech` is the old name.
- Statistics, postcode lookups, deprivation data and boundary properties (`geodata_to_properties`) share a `geography_code` column: join on it.
- Loaders return the DataFrame library you have installed (polars if you have both), so install pandas or polars yourself. `load_geodata` returns GeoJSON.
- The connector for chat assistants needs an extra: `uv add "uk-open-data[connector]"`, then `uk-open-data connector`.
# Home
## Home
# uk-open-data
UK open data in Python for civil society, from charities and community groups
to researchers and students. Load public data from official sources, join it
to your own, and get figures you can check. The first datasets are geographic
boundaries, official statistics, postcodes and deprivation indices, with more
on the way.
## Try it now — no install
Run a real notebook in your browser. Each one fetches live ONS data through the molab cloud runtime:
- __ONS statistics__
---
Browse and load datasets straight from the NOMIS API.
[](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/ons_statistics.py)
- __Geographic boundaries__
---
Explore LAD, LSOA and other UK boundary data interactively.
[](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/geo_boundaries.py)
- __Boundaries + statistics__
---
Join geographic shapes with ONS data and map the result.
[](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/geo_plus_ons.py)
## Install
Install [uk-open-data from PyPI](https://pypi.org/project/uk-open-data/):
```bash
uv add uk-open-data
```
uk-open-data depends on requests, narwhals, and python-calamine. You bring your own
DataFrame library (pandas or polars). The [package FAQ](faq/README.md) explains
which subpackages are included and how they are released.
## Quick start
```python
import pandas as pd # or polars
from uk_open_data import (
geodata_to_properties,
load_geodata,
load_ons,
postcodes_to_geography,
)
# Local authority boundaries from the ONS Geoportal
geojson = load_geodata(geography_type="LAD", year="2025", boundary_type="BUC")
areas = pd.DataFrame(geodata_to_properties(geojson, "LAD", 2025))
# Population of each local authority from Nomis: all persons, all ages
population = load_ons(
"population",
geography_type="LAD",
time="latest",
measures=20100,
gender=0,
c_age=200,
select=["geography_code", "obs_value"],
)
# Every dataset has a geography_code column, so they join directly
areas = areas.merge(population, on="geography_code")
# Your own postcodes, placed in the same local authorities
located = postcodes_to_geography(["SE13 7HX", "SE6 4RU"], geography_type="LAD")
located.merge(population, on="geography_code")
# postcode geography_code geography_name obs_value
# 0 SE13 7HX E09000023 Lewisham 301037
# 1 SE6 4RU E09000023 Lewisham 301037
```
## Bring Your Own DataFrame
uk-open-data uses [narwhals](https://narwhals-dev.github.io/narwhals/) for universal DataFrame support. The library itself has **no pandas or polars dependency** — it returns whatever backend you have installed.
```python
# With pandas installed → returns pd.DataFrame
from uk_open_data.ons import load_ons
df = load_ons("NM_1_1")
type(df) #
```
```python
# With polars installed → returns pl.DataFrame
from uk_open_data.ons import load_ons
df = load_ons("NM_1_1")
type(df) #
```
If both are installed, polars is preferred (it's faster and more memory-efficient). The geo module returns plain GeoJSON dicts — no DataFrame backend needed.
## Why does this exist?
UK public data is powerful but painful to access programmatically. The ONS ArcGIS Geoportal has no developer documentation — just a point-and-click GUI. The REST API endpoint was discovered buried in the source code of an obscure UK government R package. NOMIS is slightly better documented but requires deep knowledge of SDMX query syntax and dataset codes that aren't surfaced anywhere obvious.
Every charity, social enterprise, and researcher working with UK geographic or statistical data ends up reverse-engineering the same APIs independently. uk-open-data wraps them so you don't have to — two function calls instead of hours of documentation archaeology.
## Modules
- [**Geographic Data**](api/geo.md) — UK boundary data from ArcGIS (LAD, LSOA, etc.)
- [**ONS Statistics**](api/ons.md) — 1,615 datasets from the NOMIS API
- [**Case Studies**](case-studies/index.md) — Real-world examples from the charity sector
# Examples
## Examples
# Examples
Runnable [marimo](https://marimo.io/) notebooks. Open any of them in the molab
cloud runtime to run it **in your browser** — each fetches live ONS data — or
run locally with `uv run marimo edit examples/.py`.
## Connector basics
- __ONS statistics__
---
Browse and load datasets straight from the NOMIS API.
[](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/ons_statistics.py)
- __Geographic boundaries__
---
Explore LAD, LSOA and other UK boundary data interactively.
[](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/geo_boundaries.py)
- __Boundaries + statistics__
---
Join geographic shapes with ONS data and map the result.
[](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/geo_plus_ons.py)
## Case studies
End-to-end reproductions of [DataKind UK](https://www.datakind.org.uk/) charity
projects, each chaining several connectors on `geography_code`. See the
[Case Studies](case-studies/index.md) section for the full write-ups and figures.
| Notebook | Case study |
|----------|------------|
| [](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/smart_works_unemployment.py) | **Smart Works** — women's unemployment vs service reach (Census 2021 + LAD boundaries) |
| [](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/cal_vulnerable_client.py) | **Citizens Advice Lewisham** — deprivation vs service usage (postcodes + IMD + LSOA boundaries) |
| [](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/sobus_bame_referrals.py) | **Sobus** — BAME mental-health referrals in Hammersmith & Fulham (outcodes + Census ethnicity) |
| [](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/starlight_play_provision.py) | **Starlight** — hospital play provision vs need across ICBs |
| [](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/material_focus_recycling.py) | **Material Focus** — travel time to the nearest recycling point (LAD boundaries + population) |
# Case Studies
## Overview
# Case Studies
End-to-end reproductions of real [DataKind UK](https://www.datakind.org.uk/)
charity projects, rebuilt with KindTech. Each one chains several connectors on a
shared `geography_code`, and — because real client data is private — pairs the
public data with a transparent synthetic stand-in so the full analysis runs.
Every study has a runnable [marimo](https://marimo.io/) notebook: open it in the
molab cloud runtime to run it **in your browser** (it fetches live ONS data), or
locally with `uv run marimo edit examples/.py`.
| Case study | What it shows | Run |
|---|---|---|
| [Smart Works](smart-works-woman-unemployment.md) | Women's unemployment vs service reach (Census 2021 + LAD boundaries) | [](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/smart_works_unemployment.py) |
| [Citizens Advice Lewisham](cal-vulnerable-client.md) | Deprivation vs service usage (postcodes + IMD + LSOA boundaries) | [](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/cal_vulnerable_client.py) |
| [Sobus](sobus-bame-analysis.md) | BAME mental-health referrals in Hammersmith & Fulham (outcodes + Census ethnicity) | [](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/sobus_bame_referrals.py) |
| [Starlight](starlight-children-mapping.md) | Hospital play provision vs need across ICBs | [](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/starlight_play_provision.py) |
| [Material Focus](material-focus-recycling.md) | Travel time to the nearest recycling point (LAD boundaries + population) | [](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/material_focus_recycling.py) |
## How each study is structured
- **Problem statement** — the question the charity set out to answer.
- **Dataset involved** — the open (and, where relevant, synthetic) data used.
- **Desired output** — what the original analysis produced.
- **Reproduction with KindTech** — the connector pipeline, with figures.
- **Lessons learned** — takeaways and where the approach generalises.
## Have a case study to share?
Using KindTech in your own work? We'd love to feature it — open an issue or PR
on the [GitHub repository](https://github.com/KindTechUK/uk-open-data).
## CAL Vulnerable Client Analysis
# CAL Vulnerable Client Analysis
**Reference article:** [DataKind UK - Citizens Advice Lewisham](https://www.datakind.org.uk/stories-news/citizens-advice-lewisham)
**More about what Citizens Advice Lewisham is doing:** [Citizens Advice Lewisham](https://citizensadvicelewisham.org.uk/)
## Problem Statement
Citizens Advice Lewisham (CAL) needed to identify 'vulnerability hotspots' - areas with high need but limited access to resources - to optimize service delivery.
**Key objectives:**
- Map vulnerability hotspots in Lewisham
- Optimize service delivery based on geographic need
- Validate service targeting effectiveness
## Dataset Involved
**CAL Vulnerability Framework**: Internal assessment of service users' ability to cope with life changes, based on factors like low income, housing, mental health, and disability.
**Index of Multiple Deprivation (IMD)**: Government dataset measuring seven deprivation domains (income, employment, crime, etc.) mapped to Lower Layer Super Output Areas (LSOAs) - geographic units of ~1,500 people each.
## Desired Output
**Deprivation Map**: Visual representation showing LSOAs colored by deprivation level (red = least deprived, yellow = most deprived), revealing higher deprivation in southern borough areas.
**Service Usage Map**: Geographic distribution of CAL clients per capita, with color coding indicating service demand (yellow = high usage, red = low usage).
**Key Finding**: Strong correlation between deprivation levels and service usage - areas with highest deprivation scores also showed highest client volumes, validating CAL's service targeting.

*Figure 1: Geographic distribution of CAL clients per capita across Lewisham LSOAs and IMD scores*
## Replicating the Output with KindTech
### Data Requirements
**Internal Dataset:**
- Individual client records with vulnerability factor scores
- Postcode data for geographic mapping
- Goal: Map postcodes to LSOAs to calculate clients per capita
**External Datasets:**
- **Index of Multiple Deprivation (IMD)**: LSOA-level deprivation scores for overlay analysis
- **Census Data**: Population figures for per-capita calculations
- **LSOA Boundaries**: Geographic polygons for spatial analysis and mapping
### Analysis Workflow
1. **Data Preparation**: Convert postcodes to LSOA codes using geographic lookup
2. **Aggregation**: Calculate total clients per LSOA
3. **Normalization**: Compute clients per capita using census population data
4. **Spatial Analysis**: Overlay client density with IMD scores
5. **Visualization**: Create comparative maps showing deprivation vs. service usage
### Reproduction
A runnable, end-to-end reproduction lives in
[`examples/cal_vulnerable_client.py`](https://github.com/KindTechUK/uk-open-data/blob/main/examples/cal_vulnerable_client.py)
(a [marimo](https://marimo.io/) notebook). It chains three KindTech connectors,
all joining on the 2021 LSOA `geography_code`:
[](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/cal_vulnerable_client.py)
— run it live in the browser (the molab cloud runtime fetches real ONS
data), or locally with `uv run marimo edit examples/cal_vulnerable_client.py`.
```python
from uk_open_data import postcodes_to_geography, load_imd, load_geodata
# 1. Client postcodes -> LSOA (the step real client data would use)
clients = postcodes_to_geography(client_postcodes, geography_type="LSOA")
# 2. Deprivation + population per LSOA (IoD 2025, on 2021 LSOAs)
imd = load_imd(nation="England") # imd_decile, imd_score, population
```
!!! note "Everything is on 2021 LSOAs — no crosswalk"
The postcode connector returns 2021 LSOA codes, **IMD 2025** is published on
2021 LSOAs (and ships a population denominator), and the default LSOA
boundaries are 2021. So deprivation, population and client geography line up
on one `geography_code` with no vintage conversion. (The older composite
`load_imd(year=2019)` is on 2011 LSOAs and would need a crosswalk.)
Client records are private, so the notebook generates synthetic clients per
LSOA at a rate that **rises with deprivation**, then normalises to clients per
1,000 residents.
**Hotspots vs usage** — deprivation (left) and CAL client rate (right). Shared
dark areas mean clients come from the most-deprived LSOAs:

*Figure 2: IMD 2025 decile (left, dark = most deprived) vs synthetic CAL clients
per 1,000 residents (right). The hotspots align.*
**Does usage track deprivation?** Each LSOA's deprivation score against its
client rate:

*Figure 3: A clear positive correlation between deprivation and clients per
capita — the direction the original study found, validating CAL's targeting.*
To run on real data, feed the real client postcodes through step 1 and
aggregate per `geography_code`; the IMD join, per-capita maths and maps are
unchanged.
## Lessons Learned
**Key takeaways and recommendations:**
- **Geographic targeting works**: The strong correlation between deprivation and service usage validates CAL's approach to targeting high-need areas
- **Data integration is crucial**: Combining internal service data with external deprivation indices provides powerful insights
- **Visualization drives action**: Clear maps help stakeholders understand and act on the findings
- **Per-capita analysis matters**: Normalizing by population reveals true service demand patterns
- **LSOA-level granularity is appropriate**: Geographic units of ~1,500 people provide sufficient detail without compromising privacy
## Material Focus Recycling
# Material Focus Recycling Analysis
**Reference article:** [DataKind UK - Material Focus Recycling](https://www.datakind.org.uk/stories-news/material-focus)
**More about what Material Focus Recycling is doing:** [Material Focus Recycling](https://www.materialfocus.org.uk/)
## Problem Statement
Material Focus needed to gather evidence to demonstrate to stakeholders what interventions would make the greatest difference in increasing electrical item recycling rates across the UK.
**Key Research Questions**:
- Where in the UK could Material Focus achieve the greatest impact if small electricals were recycled through major supermarkets?
- Do factors like proximity to collection points influence recycling rates in different areas?
- What barriers prevent individuals from recycling electrical goods?
**Objective**: To identify optimal locations for new collection points and understand the factors that influence recycling behavior, enabling Material Focus to encourage local authorities to fund additional infrastructure.
## Dataset Involved
**Internal Data**:
- Existing recycling rates for electronic goods and general recycling
- Location of current recycling points across the UK
- Travel times from residential areas to nearest recycling facilities
**External Data**:
- Population density by geographic area
- Car ownership rates
- Housing types and demographics
- Other relevant socioeconomic variables
## Desired Output
**Travel Time Visualization**: A comprehensive map showing average travel time in minutes to any recycling location across England, with travel times ranging from a maximum of 20 minutes to under six minutes.
**Key Finding**: The visualization revealed that a significant proportion of people across England have access to recycling points within 12 minutes of travel time, indicating good baseline infrastructure coverage.
**Behavioral Analysis**: Material Focus was particularly interested in understanding what factors would influence new individuals to start recycling—not just optimizing for people already engaged in recycling. The analysis examined:
- Travel distance to recycling facilities
- Population density compared to recycling participation rates
- Availability of kerbside collection services

*Figure 1: Average travel time in minutes to any recycling location for people living in the area, moving from a maximum of 20 minutes to under six minutes.*
## Replicating the Output with KindTech
### Analysis Workflow
1. Generate the recycling rate data at local authority level
2. Combine with LAD boundary data to create a map of the UK
Or
1. Locate the recycling points and generate average travel time to the nearest recycling point within LAD
2. Combine with LAD boundary data to create a map of the UK
### Reproduction
A runnable, end-to-end reproduction lives in
[`examples/material_focus_recycling.py`](https://github.com/KindTechUK/uk-open-data/blob/main/examples/material_focus_recycling.py)
(a [marimo](https://marimo.io/) notebook). It builds the headline travel-time
map from two KindTech connectors, joining on `geography_code`:
[](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/material_focus_recycling.py)
— run it live in the browser (the molab cloud runtime fetches real ONS
data), or locally with `uv run marimo edit examples/material_focus_recycling.py`.
```python
from uk_open_data import load_geodata, geodata_to_properties, load_ons
import pandas as pd
# LAD boundaries carry LAT/LONG centroids
geojson = load_geodata(geography_type="LAD", year="2025", boundary_type="BUC")
geo = pd.DataFrame(geodata_to_properties(geojson, "LAD", 2025))
# Total population per LAD — so the headline is people-weighted, not area-weighted
pop = load_ons("population", geography_type="LAD", time="latest",
measures=20100, gender=0, c_age=200)
```
The real collection-point list isn't public, so the notebook scatters 300
synthetic points *where people live* (supermarket take-back follows population)
and measures the straight-line distance from each LAD centroid to the nearest
one.
!!! warning "Straight-line distance, not road routing"
The original mapped **road travel time**. This reproduction approximates it
with **haversine** distance converted to minutes at an effective 40 km/h,
capped at 20 minutes. That reproduces the *pattern* and the headline
statistic well, but it is not a true drive-time. A faithful road travel-time
map needs a **routing engine** (e.g. [OSRM](https://project-osrm.org/) or
[OpenRouteService](https://openrouteservice.org/)); KindTech does not wrap
one yet. If more case studies need real travel time, a small `uk_open_data`
routing connector would be worth adding.
**Travel-time map** — minutes to the nearest recycling point per LAD:

*Figure 2: Approximate travel time (minutes) to the nearest recycling point.
~76% of people are within a 12-minute trip, with a long tail of harder-to-reach
rural authorities (dark) — candidates for new collection points.*
**Does proximity influence recycling?** Each LAD's travel time against a
synthetic participation rate:

*Figure 3: A real-but-loose downward trend — recycling falls as travel time
rises, the direction Material Focus argued, with proximity one driver among
several (car ownership, kerbside collection, demographics).*
To run on real data, swap the synthetic points for Material Focus's actual
collection-point coordinates and the synthetic rate for measured participation;
the population join and maps are unchanged.
## Lessons Learned
**Key takeaways and recommendations:**
- **People-weighting matters**: averaging travel time per area over-counts large
rural authorities. Weighting by population reproduces the people-based
headline ("most within 12 minutes") that an unweighted map would miss.
- **Distance is a first-order proxy, routing is the refinement**: straight-line
distance gets the pattern and the access statistic right cheaply; a routing
engine is only needed when the literal drive-time figure is the deliverable.
- **Maps turn coverage into targets**: ranking authorities by travel time points
directly at where a new collection point cuts the longest trips — the evidence
the campaign needed to lobby local authorities.
- **Composable connectors**: boundaries + population join on `geography_code`
with no glue code, so the same workflow extends to car ownership, housing type
or deprivation as further explanatory factors.
## Smart Works Women & Unemployment
# Smart Works Woman Unemployment Analysis
**Reference article:** [DataKind UK - Smart Works](https://www.datakind.org.uk/stories-news/smart-works)
**More about what Smart Works is doing:** [Smart Works](https://www.smartworks.org.uk/)
## Problem Statement
Smart Works needed to identify gaps in their service provision and optimize their outreach strategy to reach more unemployed women who could benefit from their support.
**Key Challenge**: With over 632,500 unemployed women in their operating areas, Smart Works was not reaching all potential beneficiaries and struggled to identify service gaps.
**Key objectives:**
- Map the distribution of Smart Works clients across Local Authorities
- Identify areas with high unemployment but low client numbers
- Analyze demographic disparities between clients and national unemployment data
- Optimize outreach strategy and inform future center locations
**Research Questions:**
- Which Local Authorities have high unemployment rates but low Smart Works client numbers?
- Are there specific demographic groups (age, ethnicity) that Smart Works is under-serving?
- Where should Smart Works focus their efforts or consider opening new centers?
- How do Smart Works client demographics compare to national unemployment patterns?
## Dataset Involved
**Primary Data Sources**:
- **Census 2021**: Comprehensive demographic and employment data by Local Authority
- **Annual Population Survey**: Current unemployment statistics and trends
- **Smart Works Internal Data**: Client records with geographic and demographic information
**Data Integration**: Publicly available 'open data' from Census 2021 and Annual Population Survey was mapped to show women's unemployment rates by Local Authority and compared to Smart Works client distribution.
**Analysis Scope**:
- Geographic comparison of unemployment rates vs. client numbers
- Demographic analysis comparing Smart Works clients to overall unemployed women population
## Desired Output

*Figure 1: Geographic distribution of Smart Works clients compared to unemployment rates across Local Authorities*
**Key Findings:**
- **Service Gaps Identified**: Several Local Authorities with high unemployment rates showed low numbers of existing Smart Works clients
- **Demographic Disparity**: High unemployment among young women, who appear to be under-served by Smart Works
- **Strategic Opportunities**: Clear geographic areas where Smart Works could expand their reach
- **Outreach Optimization**: Evidence-based guidance for future center locations and targeted outreach
## Replicating the Output with KindTech
### Data Requirements
**Internal Dataset**: Smart Works client records with:
- Geographic location (Local Authority)
- Demographic information (age, ethnicity)
- Service usage patterns
**External Datasets**:
- **Census 2021**: Local Authority-level unemployment and demographic data
- **Annual Population Survey**: Current unemployment statistics
- **Local Authority Boundaries**: Geographic polygons for spatial analysis and mapping
### Analysis Workflow
1. **Data Collection**: Gather Smart Works center locations and client data by geography
2. **Data Integration**: Join internal data with census unemployment data by Local Authority
3. **Spatial Analysis**: Overlay client distribution with LAD boundary data to create UK-wide map
4. **Demographic Comparison**: Compare Smart Works client demographics to overall unemployed women population
5. **Gap Analysis**: Identify areas with high need but low service provision
### Reproduction
A runnable, end-to-end reproduction lives in
[`examples/smart_works_unemployment.py`](https://github.com/KindTechUK/uk-open-data/blob/main/examples/smart_works_unemployment.py)
(a [marimo](https://marimo.io/) notebook). It uses only the public KindTech
API plus a deterministic synthetic client list (the real client records are
private):
[](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/smart_works_unemployment.py)
— run it live in the browser (the molab cloud runtime fetches real ONS
data), or locally with `uv run marimo edit examples/smart_works_unemployment.py`.
```python
from uk_open_data import geodata_to_properties, load_geodata, load_ons
# Female, unemployed, by age band, all LADs — Census 2021 table RM024
unemp = load_ons(
"NM_2124_1",
geography_type="LAD",
time="latest",
c2021_eastat_7=2, # Unemployed
c_sex=1, # Female
c2021_age_7=[2, 3, 4, 5], # 16-24, 25-34, 35-49, 50-64
)
# LAD boundaries with centroids, normalised to share `geography_code`
geojson = load_geodata(geography_type="LAD", year="2025", boundary_type="BUC")
```
!!! note "Why Census 2021, not the Annual Population Survey?"
APS unemployment *counts* by sex are suppressed for small samples — only
~40 of 350 Local Authorities return data, and age bands are sparser still.
Census 2021 (table RM024, `NM_2124_1`) covers **every** LAD in England &
Wales (318 areas, ~580,000 unemployed women), making it the reliable
source for a choropleth.
Synthetic client numbers are modelled so reach **decays with distance** from
Smart Works' real centre cities (Birmingham, Manchester, Leeds, Newcastle,
Reading, Bristol, London, etc.), scaled by local female unemployment. This
deliberately reproduces the case study's structure: high-need areas far from
any centre end up under-served.
**Geographic gap** — female unemployment (the need) vs Smart Works reach
(clients per 100 unemployed women). Areas that are dark on the left but pale
on the right are the service gaps:

*Figure 2: Female unemployment by Local Authority (left) vs synthetic Smart
Works reach (right). The most under-served high-need areas — Cornwall,
Plymouth, the rural east, and coastal towns — sit far from any centre.*
**Demographic gap** — the age profile of unemployment (need) vs the age
profile of clients reached:

*Figure 3: The 16-24 band is ~22% of need but only ~12% of clients reached,
flagging young women as under-served — matching the original finding.*
To go from synthetic to real client data, swap `clients_total` for a
`postcode → LAD` aggregation of the real client list. The Census join, the
gap metric, and the maps stay identical.
## Lessons Learned
- **The right source matters more than the obvious one.** The original brief
named the Annual Population Survey, but APS small-area suppression makes it
unusable for a full LAD map — Census 2021 is the correct primary source.
- **Distance-decayed reach reproduces the real pattern.** Modelling client
reach as a function of distance to the nearest centre surfaces exactly the
high-need, low-provision areas the charity cared about.
- **Normalisation removes the busywork.** Because `load_ons` and
`load_geodata` both expose `geography_code`, joining statistics to
boundaries is a single `merge` — no manual column matching.
- **Per-need normalisation reveals gaps counts hide.** "Clients per 100
unemployed women" exposes under-served areas that a raw client count would
mask behind population size.
## SOBUS BAME referral mapping
# Sobus BAME hospitalisation analysis
**Reference article:** [DataKind UK - Sobus](https://www.datakind.org.uk/stories-news/sobus)
**More about what Sobus is doing:** [Sobus](https://sobus.org.uk/)
## Problem Statement
Sobus identified ongoing concerns about the disproportionate numbers of BAME (Black, Asian, and Minority Ethnic) people diagnosed with mental health conditions and under the care of mental health services, coupled with inadequate service provision to these communities.
**Key Challenge**: There was a lack of comprehensive local data mapping the BAME mental health landscape, making it difficult to understand the scope and nature of service gaps.
**Research Questions**:
- Was there a disproportionate representation of BAME people diagnosed and under the care of Mental Health Services?
- What was the current service provision for the BAME community suffering from mental health issues?
- How could data-driven insights inform more equitable mental health service delivery?
**Objective**: To map the BAME mental health landscape locally as a starting point for addressing service disparities and improving access to appropriate mental health support.
## Dataset Involved
The project successfully obtained data from multiple sources to provide a comprehensive view of mental health services in West London:
- **West London NHS Trust**: Main provider of mental health services across three boroughs (Hammersmith & Fulham, Ealing, and Hounslow)
- **Hammersmith & Fulham GP Federation**: Primary care data to understand community-level health patterns
- **LBH&F Social Care Data**: Local authority social care information
- **Sobus Sector Survey**: Primary research to capture community perspectives and service gaps
## Desired Output

*Figure 1: Distribution of mental health referrals by region in Hammersmith and Fulham*
**Key Findings**:
- **Disproportionate Representation**: BAME communities were overrepresented in mental health care, with rates 3-8 times higher than white equivalents across various diagnoses
- **Service Quality Gap**: The quality of health service support in the region was below the London average
- **Critical Self-Harm Rates**: Hammersmith & Fulham recorded the highest rate of BAME self-harm incidents in London
## Replicating the Output with KindTech
### Data Requirements
**Internal Dataset**: West London NHS Trust anonymised referral data broken down by ethnicity for Hammersmith and Fulham, with outcode (postcode prefix) attached to each referral for geographic analysis.
### Analysis Workflow
1. **Geographic Mapping**: Convert outcodes to LSOA (Lower Layer Super Output Area) codes
2. **Per-Capita Calculation**: Compute the number of referrals per capita for each LSOA
3. **Visualization**: Create geographic maps showing referral density and ethnic distribution patterns
### Reproduction
A runnable, end-to-end reproduction lives in
[`examples/sobus_bame_referrals.py`](https://github.com/KindTechUK/uk-open-data/blob/main/examples/sobus_bame_referrals.py)
(a [marimo](https://marimo.io/) notebook). It chains three KindTech connectors,
all joining on the 2021 LSOA `geography_code`:
[](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/sobus_bame_referrals.py)
— run it live in the browser (the molab cloud runtime fetches real ONS
data), or locally with `uv run marimo edit examples/sobus_bame_referrals.py`.
```python
from uk_open_data import outcode_to_geography, load_ons, load_geodata
# 1. A referral's outcode -> LSOA (the step real referral data would use)
outcode_to_geography(["W6", "W12", "W14"], geography_type="LSOA")
# 2. Ethnic composition per LSOA (Census 2021 TS021), restricted to the borough
eth = load_ons(
"NM_2041_1",
geography="1778385172TYPE151", # LSOAs within Hammersmith & Fulham
time="latest",
c2021_eth_20=[0, 1004], # Total, White -> BAME = Total - White
)
```
!!! note "Everything is on 2021 LSOAs — no crosswalk"
The postcode connector returns 2021 LSOA codes, **Census 2021** is on 2021
LSOAs (and gives the population denominator *and* the BAME share), and the
default LSOA boundaries are 2021. So ethnicity, population and referral
geography line up on one `geography_code` with no vintage conversion.
!!! warning "Outcode → LSOA is a rough, centroid-based stand-in"
An outcode (e.g. `W6`) spans many LSOAs, so `outcode_to_geography` returns
only the LSOA at its centroid — and a centroid can even fall in a
neighbouring borough. With **full** postcodes use `postcodes_to_geography`
for an exact mapping. The analysis below runs at true LSOA resolution from
the census; the outcode step only demonstrates the mechanism.
Real NHS Trust referrals are confidential, so the notebook generates synthetic
referrals per LSOA at a rate that **rises with the area's BAME share**, and
models a BAME resident as more likely to be referred than a White resident —
reproducing the over-representation the study tested for.
**Where is the need?** — BAME share of population (left) and synthetic referral
rate (right). Shared dark areas mean referrals come from the most-BAME LSOAs:

*Figure 2: BAME share of population (left) vs synthetic mental-health referrals
per 1,000 residents (right) across Hammersmith & Fulham's 115 LSOAs. The
hotspots align.*
**Are BAME residents over-represented?** Each LSOA's BAME share against its
referral rate:

*Figure 3: A clear positive correlation between BAME share and referrals per
capita — the direction the original study found. Across the borough BAME
residents are ~37% of the population but a higher share of referrals.*
To run on real data, feed each referral's postcode through
`postcodes_to_geography(..., "LSOA")`, tag it with the patient's ethnicity, and
aggregate per `geography_code`; the census join, per-capita maths and maps are
unchanged.
## Lessons Learned
**Key takeaways and recommendations:**
- **Geography reveals disparity**: mapping referrals against ethnic composition
at LSOA level exposes where need concentrates and quantifies
over-representation — the starting point Sobus wanted for addressing service
gaps.
- **Per-capita normalisation matters**: raw referral counts track population
size; normalising by residents reveals true demand independent of how many
people live in each area.
- **Postcode resolution drives accuracy**: full postcodes map cleanly to LSOAs;
outcodes only approximate via a centroid and can cross borough boundaries, so
the granularity of the source postcode caps the analysis.
- **Census is the denominator**: 2021 ethnic-group data on 2021 LSOAs joins
natively to referral geography, no crosswalk needed.
## Starlight Children's Foundation
# Starlight mapping children's needs
**Reference article:** [DataKind UK - Starlight](https://www.datakind.org.uk/stories-news/starlight)
**More about what Starlight is doing:** [Starlight](https://www.starlight.org.uk/)
## Problem Statement
Starlight Children's Foundation needed to understand where there is overlap between their services, hospital play provision, and donors to make strategic decisions about service provision and fundraising efforts.
**Key objectives:**
- Map the distribution of Starlight services across the UK
- Identify gaps in play provision and service coverage
- Analyze disparities between different ethnicities and demographics
- Optimize resource allocation based on demonstrated need
**Research Questions:**
- Where are the gaps between Starlight's services and areas of greatest need?
- How does play provision vary across different regions and demographics?
- What factors influence the distribution of hospital play services?
- How can Starlight be more strategic in directing resources to areas with the greatest need?
## Dataset Involved
**Primary Data Collection**: Much of the data had to be collected through freedom of information (FOI) requests from 140 hospital trusts and health boards across the UK.
**Data Types Collected:**
- Number of child admissions by hospital
- Level of play provision and specialist staff
- Play budgets and resource allocation
- Geographic location of services
**Response Rate**: 87% of trusts responded, with some gaps in the data for those that did respond, suggesting that potentially useful data is not being systematically collected.
**Geospatial Processing**: Geographic data was processed and standardized to enable efficient map visualizations and spatial analysis.
## Desired Output

*Figure 1: Starlight heat map showing distribution of signed-up centres across the UK*
**Key Findings:**
- **Even Resource Distribution**: Starlight's resources were spread evenly over deprived and less deprived areas, indicating potential for more targeted allocation
- **Service Gaps Identified**: Some regions had more eligible trusts than were receiving play provisions
- **Admission vs. Service Mismatch**: Other regions had significantly more hospital admissions than boxes distributed
- **Strategic Opportunity**: Clear evidence that Starlight could be more strategic about directing help to places with the greatest need
## Replicating the Output with KindTech
### Data Requirements
**Synthetic Data Generation**: Create realistic datasets representing:
- Play provision levels across clinical commissioning groups (CCGs)
- Hospital admission rates for children
- Geographic distribution of Starlight services
- Demographic and deprivation indicators
**Geographic Boundaries**: Clinical commissioning group (CCG) boundaries for spatial analysis and mapping
### Analysis Workflow
1. **Data Generation**: Create synthetic play provision data across clinical regions
2. **Geographic Mapping**: Map data to relevant CCG boundaries for visualization
3. **Gap Analysis**: Identify areas with high need but low service provision
4. **Visualization**: Create heat maps showing service distribution and need indicators
### Reproduction
A runnable, end-to-end reproduction lives in
[`examples/starlight_play_provision.py`](https://github.com/KindTechUK/uk-open-data/blob/main/examples/starlight_play_provision.py)
(a [marimo](https://marimo.io/) notebook). It maps synthetic provision against
need over England's real NHS commissioning geography:
[](https://molab.marimo.io/github/KindTechUK/uk-open-data/blob/main/examples/starlight_play_provision.py)
— run it live in the browser (the molab cloud runtime fetches real ONS
data), or locally with `uv run marimo edit examples/starlight_play_provision.py`.
```python
from uk_open_data import load_geodata, geodata_to_properties
import pandas as pd
# England's 42 Integrated Care Boards (the geography that replaced CCGs)
geojson = load_geodata(geography_type="ICB", year="2023", coverage="EN", boundary_type="BSC")
icbs = pd.DataFrame(geodata_to_properties(geojson, "ICB", 2023))
```
!!! note "ICBs, not CCGs"
Clinical Commissioning Groups were abolished in July 2022 and replaced by
**Integrated Care Boards**. KindTech serves the current ICB boundaries, so
the reproduction uses the 42 ICBs as the commissioning unit; the workflow is
identical to the original CCG analysis.
The original study's admission and provision figures came from FOI returns that
aren't public, so the notebook generates a deterministic stand-in (`rng(3)`)
where **child admissions vary widely** (the need) but **boxes are distributed
roughly evenly** (the resource) — the exact pattern the study flagged.
**Need vs provision** — child admissions (left) and boxes distributed (right).
The two maps *don't* share their dark areas, which is the point:

*Figure 2: Child admissions (left, the need) vs Starlight boxes distributed
(right, the resource) across England's 42 ICBs. Provision does not follow need.*
**Does provision follow need?** Each ICB's admissions against its boxes:

*Figure 3: A near-flat (slightly negative) relationship between need and
provision — resources are spread evenly regardless of demand, the
"be more strategic" opportunity the original study identified.*
To run on real data, replace the synthetic columns with Starlight's FOI returns
keyed by ICB (or by trust, then mapped to ICB); the boundary join, coverage
maths and maps are unchanged.
## Lessons Learned
**Key takeaways and recommendations:**
- **Map provision against need, not in isolation**: plotting boxes alongside
admissions on the same geography immediately exposes the decoupling that a
provision-only view hides.
- **Even distribution is a finding, not a default**: a near-flat
need-vs-provision relationship is itself the evidence that allocation could
be more strategic.
- **Coverage ratios rank the opportunity**: boxes per 1,000 admissions turns
the gap into an ordered list of where redirecting resource helps most.
- **Stable geography matters**: serving current ICB boundaries (post-CCG) keeps
the analysis aligned with how the NHS commissions today, with no manual
crosswalk.
# User Guide
## Overview
# API Reference
KindTech provides four modules for accessing UK public data, and analyses that
put them to work on your own data:
## Modules
### [Geographic Data](geo.md) — `uk_open_data.geo`
Load UK geographic boundary data from the ONS ArcGIS Geoportal. Returns GeoJSON.
```python
from uk_open_data.geo import load_geodata
# Load Local Authority Districts
boundaries = load_geodata(geography_type="LAD", coverage="UK")
```
### [ONS Statistics](ons.md) — `uk_open_data.ons`
Load statistical data from the ONS NOMIS API. Returns pandas or polars DataFrames.
```python
from uk_open_data.ons import load_ons
# Load Jobseeker's Allowance data
df = load_ons("NM_1_1", geography="TYPE480", time="latest")
```
### [Postcodes](postcodes.md) — `uk_open_data.postcodes`
Resolve UK postcodes (and outcodes) to ONS geography codes via postcodes.io, so
address data joins to boundaries and statistics. Returns pandas or polars
DataFrames.
```python
from uk_open_data.postcodes import postcodes_to_geography
# Postcodes -> LSOA, ready to join on `geography_code`
located = postcodes_to_geography(["SE13 7HX", "SE6 4RU"], geography_type="LSOA")
```
### [Deprivation (IMD)](imd.md) — `uk_open_data.imd`
Load UK Indices of Multiple Deprivation, keyed on geography codes. A single
nation returns its **official** index (England IoD 2025/2019 with all domains,
or WIMD/SIMD/NIMDM); `nation="UK"` returns the mySociety composite for
cross-nation comparison. Returns pandas or polars DataFrames.
```python
from uk_open_data.imd import load_imd
imd = load_imd(nation="England") # official IoD 2025; join on `geography_code`
```
### [Analyses](analyses.md) — `uk_open_data.analyses`
Ask a question of your own data. An analysis joins your table to open data and
returns figures with their sources, the working, the choices made and the
checks a person should do. Results hold totals only, never rows.
```python
from uk_open_data.analyses import run_analysis
result = run_analysis(
"reach-deprivation", clients, columns={"postcode": "Client postcode"}
)
```
## Design principles
- **Flat functions** — no classes to instantiate, just call `load_geodata()` or `load_ons()`
- **String or enum** — pass `"LAD"` or `GeographyType.LAD`, both work
- **Bring your own DataFrame** — narwhals returns whatever backend you have installed
- **Bundled catalogs** — small CSV reference tables ship with the package (136KB total) so you can browse available datasets offline
- **Live data** — actual geographic/statistical data is always fetched fresh from the source APIs
## Analyses
# Analyses
An analysis answers one question a charity asks of its own data. You give it a
table, say which column is which, and it joins your data to UK open data and
returns figures you can check and reuse.
Kindtech Evidence is built on these analyses. This page is about running them
from Python. You can also run them from the [command line](cli.md), or from a
chat assistant through the [connector](connector.md).
These analyses follow work first done by
[DataKind UK](https://www.datakind.org.uk/) volunteers with charities. The
[case studies](../case-studies/index.md) reproduce five of those projects.
Every analysis returns the same things:
- **an answer**: one or two sentences that answer the question, and the
three figures to show first
- **figures**: the headline numbers
- **tables**: totals behind the figures
- **a map description**: which areas to draw and what to colour them by, when
the analysis has a map
- **chart descriptions**: which table and columns to draw as a bar chart
- **the working**: each step taken, with how many rows went in and came out,
the figures before rounding and the code that runs it again
- **choices**: what the analysis decided for you, and the option that changes it
- **checks**: what a person must confirm before using the figures
- **caveats**: what the figures cannot say
- **sources**: publisher, edition, licence and link for every dataset used
- **a privacy summary**: what was hidden, and what left your machine
A result holds totals only. Nothing in it describes one person, and no value
from your data is repeated back, not even in a warning or an error message.
## Quick start
```python
import pandas as pd
from uk_open_data.analyses import run_analysis
clients = pd.read_csv("clients.csv")
result = run_analysis(
"reach-deprivation",
clients,
columns={"postcode": "Client postcode"},
)
result.answer # the question, answered in a sentence
result.figure("share_most_deprived_20").value # 41.3 (per cent)
result.table("by_decile").to_frame() # pandas or polars DataFrame
[check.question for check in result.checks] # what to confirm first
result.to_dict() # everything, as plain JSON types
```
`data` can be a pandas or polars DataFrame, or a list of row dictionaries.
`columns` maps each role the analysis needs to one of your column names. You can
leave a role out when your data already has a column with that name.
To run an analysis on a file without writing Python, use the
[command line](cli.md).
## Functions
### `list_analyses()`
Returns an `AnalysisInfo` for every analysis: its `id`, `title`, the `question` it
answers, a `summary`, its `roles` (the columns it can use), its `input_modes`
(the shapes of data it accepts), its `options` and its `coverage`.
Every option has two names. `name` is its code name, the one a call is
written with, such as `catchment`. `label` is its short plain name, such as
"Area you serve". Show the label beside the option. Every message that points a
person at an option uses the label, in quotes ("Change 'Area you serve' to
include them."), and never the code name, so the sentence matches what is on
the screen. An option has the same label in every analysis that has it, and
the result's `choices` use the same label for the choice it made:
| `name` | `label` |
| --- | --- |
| `catchment` | Area you serve |
| `catchment_min_share` | Share that makes a place part of your area |
| `suppress_below` | Smallest count shown |
| `postcode_lookup` | Where postcodes are looked up |
| `need` | People you are trying to reach |
| `top` | Places listed |
| `characteristic` | What people are grouped by |
| `groups` | How your labels match census groups |
| `under_represented_below` | What counts as under-represented |
| `within_km` | Distance within reach, in kilometres |
The area an analysis looks across has one name wherever a person reads it:
"the area you serve". `catchment` is only its code name.
A table's columns have plain names too. `table.columns` holds the ids, which a
program reads, and `table.headings` maps each id to the heading to show, such
as "Your people per 100 in need" for `people_per_100_in_need`. `table.units`
gives the unit of each column that has one, named as the units of figures
are: `"percent"` or `"km"`. Show a table with its headings and units and it
reads the same on a page, in a chat and on the command line. A place is a
"Local authority" in most tables and a "Neighbourhood" in the one behind the
first analysis's map.
An option that takes one of a fixed list of values lists them as `choices`,
each with a `value` and a `label` a person can read, so a page can show a list
to pick from. `choices` is empty when the option is free, such as a number or
a place name. For the `need` option the choices are the built-in needs; a table
of your own is still given as a mapping.
A role with `reported` set to `True` holds names the result uses too, such as
local authorities, so the same names can appear in the result. Values of every
other role are never repeated.
A reported role can also list `reported_values`. That is for a column that
holds a person's own words as well, such as their ethnic group: only the
listed values are names the result uses, and no other value in the column is
ever repeated. If you check a result for values repeated from the input, leave
out the listed values when there are any, compared without case, and check
every other value in the column. Leave the whole column out only when the
role is reported and lists no values.
A role with `amount` set to `True` holds a number the analysis adds up: a count of
people or a volume. A total of it is in the result, so where one row is the
only one for its place or group, that row's number comes back as the total.
That is not a repeated value. A number in any other role, such as a latitude,
never comes back.
### `describe_analysis(analysis_id)`
Returns the `AnalysisInfo` for one analysis. Raises `KeyError` for an unknown id.
### `run_analysis(analysis_id, data, columns=None, options=None)`
Runs an analysis and returns an `AnalysisResult`.
Raises `AnalysisInputError` (a `ValueError`) when the data, the column mapping or
an option cannot be used. The message is written for a person and
`error.problems` lists each problem separately.
`error.option` is the code name of the option the error is about, and
`error.role` the name of the column role, so a page can mark the right box and
a program need not search the sentence. When the problems are about several,
it is the first of them. Each is `None` when the error is about neither, for
example when a source could not be read. The command line adds what to type:
"On the command line this is --option catchment=VALUE."
When the columns an analysis needs were not all found, `error.role` is the
first one still to be named. When an option was given that the analysis does
not have, the message lists each option it does have by both names:
"need ('People you are trying to reach')".
When a public data source the analysis needs cannot be reached, the
`requests.RequestException` is let out. Its text holds the whole web address
that was asked for, which can hold a postcode, so show a message of your own
rather than the text. The command line names the site alone, and says
whether the source could not be reached or answered with an error. An analysis
needs no network when the public figures it uses are kept on your machine.
### `record_run(analysis_id, input_mode, door)`
Records that a run has given a person an answer, so that a host can count how
often each analysis is used. It writes one record at `INFO` level to the
`uk_open_data.runs` logger, and that is all it does: the package adds no handler
and sends nothing anywhere. On a person's own machine nobody collects the
records. A host that keeps its logs can count them.
```python
from uk_open_data.analyses import record_run
record_run(result.analysis_id, result.input_mode, "page")
# run analysis=reach-deprivation mode=postcodes door=page
```
`run_analysis` never records a run by itself. Whatever gives the answer to a
person calls `record_run` once, after the answer has been given: the command
line does (`"cli"`), and a page (`"page"`) or a chat assistant (`"chat"`) built
on these analyses should. A run that fails is not recorded.
The record holds the three words and nothing else. Each must be on a fixed
list (a registered analysis, one of its input modes, one of the three doors),
so no word from a person's data can reach a log. A word that is not on its list
raises `KeyError` (the analysis) or `ValueError` (the mode or the door), and the
message does not repeat it. The same three words are on the record as
`record.analysis_id`, `record.input_mode` and `record.door`.
A host that keeps the records imports the logger's name, and the doors, from
the package, so neither is typed out a second time:
```python
import logging
from uk_open_data.analyses import DOORS, RUNS_LOGGER
logging.getLogger(RUNS_LOGGER).setLevel(logging.INFO)
```
## Drawing the map
A result describes its map; `render_map` draws it as an SVG picture with a
key and the credits the data licences ask for.
```python
from uk_open_data.analyses import render_map
svg = render_map(result) # the first layer: deprivation decile
svg = render_map(result, layer="people") # people reached, in bands
with open("map.svg", "w", encoding="utf-8") as handle:
handle.write(svg)
```
The picture is drawn from the result's own table of totals, so it shows
nothing the result does not already hold. People are shown in bands, and the
lowest band includes zero. Hover over an area in a browser to see its name and
value. The colours adapt to a dark page.
A picture shows one layer, and its title says what the colour shows: "People
reached, by neighbourhood". The first layer of a map is drawn in blue and the
second in orange, so two pictures of one result do not look like the same
measure. The shaded areas sit in a frame with a scale line. Up to twelve
local authorities are named one by one; neighbourhoods are named by the local
authority they are in. A name that would cover most of a small place is
written beside it, where there is room, so its colour can be seen. Text is broken into lines to fit the width you ask for.
The places around the map are drawn in pale grey, with their names where a
name fits, when you give their outlines. Only the part of each that the frame
shows is written to the picture, so a large neighbour does not make the file
large. Put them among the features of
`boundaries`, or in a list under `"surroundings"`. Codes listed under
`"focus"` are the surrounding places that hold the shaded areas: each gets a
darker line and its name. Codes listed under `"shore"` are surrounding places
whose outline is where the land ends. The shaded areas are drawn no further
than it, and the picture is framed on it. Use it when the outlines of the
areas run out over water and the outline of the place that holds them does
not.
```python
boundaries = {
"type": "FeatureCollection",
"features": areas, # outlines you already have
"surroundings": nearby,
"focus": ["E09000023"],
"shore": ["E09000023"],
}
svg = render_map(result, boundaries=boundaries)
```
`render_map` fetches the outline of each area from the ONS Open Geography
Portal. Only the public area codes of the area you serve, and of the local
authorities near it, are sent. To draw without the network, pass `boundaries=`
a GeoJSON FeatureCollection you already have; `load_map_boundaries(result)`
fetches one you can save and reuse.
`load_map_boundaries` fetches the places around the map as well, and lists
under `"focus"` the local authorities that hold a map's neighbourhoods. A map
of up to 1,000 neighbourhoods or 20 local authorities is drawn large, so its
outlines come from the full ones with detail finer than 10 or 20 metres left
out. So do the local authorities that hold its neighbourhoods, and the other
places a picture of the usual width shows when there are no more than 40 of
them, so that neighbours meet. A place further off keeps its 200 metre
outline.
The full outlines of local authorities stop at the shore. The only full
outlines of neighbourhoods that are open run out to low water and to the
middle of a river. So on a map of neighbourhoods the local authorities that
hold them are also listed under `"shore"`, and a river or a bay is left
clear. When the fine outline of one of them does not come, nothing is listed
and the neighbourhoods are drawn whole.
A map of more areas is drawn small and takes outlines simplified to 200
metres. Every map asks for every local authority at 200 metres, nearly three
megabytes, to find the ones near it. That answer is kept in memory for the
life of the process, so a second map does not ask again;
`uk_open_data.analyses.maps.clear_outline_cache()` forgets it. When the places around cannot be fetched, the map is drawn without
them and nothing is said.
The fine outlines usually come in a few seconds. At times the service has
taken from a quarter of a minute to a minute or two for one map, and it is
not known why. A program that cannot wait,
such as one answering in a chat, calls `load_map_boundaries(result,
fine=False)`. It then gets the 200 metre outlines of every area, and the
places around from the answer kept in memory, in a second or two.
`load_map_boundaries` is safe to call from two threads at once.
## The answer
`result.answer` is one or two sentences that answer the question the analysis
asks, for example:
> Of your people in the area you serve, 49.0% live in the 20% most deprived
> neighbourhoods in England. Of everyone who lives in that area, 20.0% do, so
> you reach those neighbourhoods more than their share.
Open with it wherever you show a result, so a report, a page and a chat
assistant all say the same thing. It is built from the figures and tables of
the result, after small counts are hidden, so it says nothing the result does
not already show. When the figure it rests on is hidden, it says so instead of
giving a number. The places and groups it names are the public names in the
result's tables, never text from your data.
The sentence is careful about what it calls a gap. A place is named as one to
look at first only when it falls below the rate for the whole area, so a list
of one or two places does not present the place you reach most as a gap, and a
place whose count is hidden is not named. A count of every resident is called
"residents", not "people in need". A group with nobody in your data is named
last, with a line saying so, because it may be a group you do not record.
`result.key_figures` holds the ids of up to three figures to show first, in
order. Each is a figure of the result, and none is hidden: when a figure that
would be shown first is hidden to protect a small count, the next one takes
its place.
```python
for figure_id in result.key_figures:
figure = result.figure(figure_id)
print(figure.label, figure.value, figure.unit)
```
## Checking a result and running it again
A result shows its working, so that anyone can check it or run it again.
`result.working` lists each step in plain words, with how many rows went in
and came out. `result.sources` gives each source and its date.
A share or a rate is rounded before it is shown. `figure.exact` is the value
before rounding:
```python
figure = result.figure("share_most_deprived_20")
figure.value # 68.6
figure.exact # 68.57142857142857
```
`exact` is `None` for a count, which is not rounded, and for a figure that is
hidden to protect a small count. It is also `None` for a distance from one
place to a site, which is rounded to the kilometre on purpose so that it says
less about where a site is.
`result.code` is the Python that runs the analysis again with the same
settings:
```python
print(result.code)
```
```python
# Version 0.1 of this analysis, run with
# uk-open-data 0.2.0. This runs it again with
# the same settings. No row or heading of your table is written
# here: put the name of your own column beside each role.
import pandas as pd
from uk_open_data.analyses import run_analysis
data = pd.read_csv("your-table.csv")
result = run_analysis(
"reach-deprivation",
data,
columns={
"postcode": "", # the name of your column
},
options={
"suppress_below": 10,
"postcode_lookup": "auto",
"catchment_min_share": 0.05,
},
)
print(result.answer)
for figure in result.figures:
print(figure.label, figure.value)
```
It prints the answer and every figure, to set beside the ones in the result.
Every setting that has a value is written out, the ones you left alone too,
so the code gives the same result if a default changes in a later version.
That is why it can hold a setting the list of choices in a result does not
mention. A setting the analysis works out for itself, such as the area you
serve when you named none, is left out. An area you named is written as you
gave it.
The setting for where postcodes are looked up is written as it was used. Code
copied from a run that kept postcodes on one machine says so, and on another
machine it stops and asks for the postcode table before it sends a postcode
anywhere.
The code holds no row and no heading of your table. The names of your columns
are left for you to fill in, because a heading can hold something private. A
setting that holds your own words, such as your own labels for groups in
`who-we-miss`, is written as `{}` with a note to fill it in. So the code is as
safe to share as the result is.
The command line prints both as the last two parts of its report, under
"Figures before rounding" and "To run it again in Python". The code starts at
the margin, so it runs as it is copied.
## Charts
`result.charts` describes the charts a result is best shown with, so a page
can draw them without knowing the analysis. Each `Chart` names a table of the
result, the column that names each group of bars (`category_column`) and one
or more `series`, each a column with a label and a unit. Every series in a
chart has the same unit, so one axis serves them all.
```python
chart = result.charts[0]
frame = result.table(chart.table).to_frame()
frame.plot.bar(x=chart.category_column, y=[s.column for s in chart.series])
```
A value hidden to protect a small count is `None` in the table. Draw no bar
for it.
## Small counts
A count from 1 to 4 that is about a named place or a group is returned as
`None`, with `suppressed` set to `True`, and so is anything worked out from it.
When hiding one cell would let it be worked out from a total, a second cell is
hidden with it. So a hidden count is not always small: do not report a hidden
cell as "fewer than 5". Every result says this in its privacy notes. Change
the threshold with the `suppress_below` option; it cannot go below 3.
A result says which threshold was used in `privacy.suppress_below`. The analyses
about sites, provision gap and access and distance, hide nothing, and for them
it is `None`.
## Reach against deprivation
`reach-deprivation` answers: are we reaching people in the most deprived
neighbourhoods? It covers England, using the English Indices of Deprivation
2025 on 2021 neighbourhoods (LSOAs).
It accepts two shapes of data:
| Input mode | Columns | What it is |
| --- | --- | --- |
| `postcodes` | `postcode` | One row per person or case, with a home postcode |
| `neighbourhood_counts` | `lsoa_code`, `count` | Already totalled by 2021 LSOA |
In `postcodes` mode the analysis looks postcodes up in the
[postcode table on your machine](postcodes.md#looking-up-postcodes-on-this-machine)
when one is installed, and then no postcode is sent anywhere. Install it once
with `uk-open-data postcodes download`. Without the table, the distinct,
well-formed postcodes are sent to [postcodes.io](https://postcodes.io/); no
other column leaves your machine, and rows that are blank or not shaped like a
postcode are never sent. The result says which happened, under `choices` and
`privacy`. In `neighbourhood_counts` mode nothing leaves your machine.
The deprivation index is downloaded from gov.uk, or read from a copy
[kept on your machine](imd.md#keeping-the-english-index-on-this-machine) when
there is one. A result that used a copy says so in its `sources` and its
`working`, with the note the copy was kept with.
The analysis then works out **the area you serve**: the local authorities that each
hold at least 5% of the people it could place. The decile figures and the map
are about the people who live there, so they can be set against everyone who
lives there. People outside the area you serve are counted in the local authority
table, and a warning says how many there are.
| Figure | Meaning |
| --- | --- |
| `people_supplied` | People in the data you gave |
| `people_located` | People placed in an English neighbourhood |
| `people_in_catchment` | People who live in the area you serve |
| `share_most_deprived_10` | Share of them in the 10% most deprived neighbourhoods in England |
| `share_most_deprived_20` | Share of them in the 20% most deprived neighbourhoods in England |
| `catchment_share_most_deprived_20` | Share of residents of the area you serve who live in those neighbourhoods, for comparison |
| `reach_per_1000_most_deprived_20` | People reached per 1,000 residents of those neighbourhoods |
| `reach_per_1000_elsewhere` | People reached per 1,000 residents in the rest of the area you serve |
The chart `people_by_decile` sets the share of your people in each decile
against the share of residents of the area you serve.
| Table | Rows |
| --- | --- |
| `by_decile` | One per deprivation decile: people, share of people, residents, share of residents, people per 1,000 |
| `by_local_authority` | One per local authority; authorities outside the area you serve with few people share one unnamed row |
| `by_neighbourhood` | One per neighbourhood in the area you serve: decile, residents, and people in bands. This feeds the map |
| Option | Default | Meaning |
| --- | --- | --- |
| `suppress_below` | `5` | Counts above zero and below this are hidden |
| `postcode_lookup` | `"auto"` | `"offline"` uses the table on your machine and fails without one, `"online"` uses postcodes.io, `"auto"` uses the table when it is installed |
| `catchment` | worked out | A local authority name or code, a list of them, or `"England"` |
| `catchment_min_share` | `0.05` | The share a local authority needs to join a worked-out area |
```python
result = run_analysis(
"reach-deprivation",
clients,
columns={"postcode": "Client postcode"},
options={"catchment": ["Lewisham", "Greenwich"]},
)
```
!!! note "Before you use the figures"
Read `result.checks` and `result.caveats`. Deprivation is measured for
neighbourhoods, not people: someone who lives in a deprived neighbourhood
is not necessarily deprived.
## Need against reach
`need-reach` answers: where is need high and our presence low? It covers
England and Wales, by local authority, and is the method of the
[Smart Works case study](../case-studies/smart-works-woman-unemployment.md)
turned into a function.
It accepts two shapes of data:
| Input mode | Columns | What it is |
| --- | --- | --- |
| `postcodes` | `postcode` | One row per person or case, with a home postcode |
| `area_counts` | `local_authority`, `count` | Already totalled by local authority, named or coded |
Postcodes are placed as in the first analysis: on your machine when the postcode
table is installed, and with postcodes.io otherwise.
The analysis loads a count of **people in need** in every local authority from
[Nomis](ons.md), divides the people you helped in each one by it, and lists
the high-need local authorities where you reach the fewest people per 100 in
need. A local authority is high need when its count is in the top quarter of
the area you serve. With fewer than four places, the one with the largest count
is high need.
Choose the need with the `need` option:
| `need` | People counted |
| --- | --- |
| `"unemployed"` (default) | Unemployed people aged 16 to 64, not counting full-time students, Census 2021 |
| `"unemployed_women"` | Unemployed women aged 16 to 64, not counting full-time students, Census 2021 |
| `"unemployed_men"` | Unemployed men aged 16 to 64, not counting full-time students, Census 2021 |
| `"residents"` | Everyone who lives there, of every age, Census 2021. Use it when what you offer is for anyone |
| `{"dataset": ..., "label": ..., "filters": {...}}` | Any table Nomis publishes by local authority. The filters are the category codes to add up. Counts are asked for (`measures` 20100) unless the filters name another measure |
The three unemployment needs count the census group "Economically active
(excluding full-time students): Unemployed", as the case study does. Full-time
students who were looking for work are a separate census group and are not
counted. To count them too, give the table form with both groups:
```python
options = {
"need": {
"dataset": "NM_2124_1",
"label": "Unemployed people aged 16 to 64, with full-time students",
"filters": {
"c2021_eastat_7": [2, 4],
"c_sex": 0,
"c2021_age_7": [2, 3, 4, 5],
},
}
}
```
The need figures are public. They are fetched from Nomis once for each need
and then kept in memory for as long as the program runs;
`clear_need_cache()` forgets them. To run with no request to Nomis at all,
keep a copy on the machine, in the same data folder as the
[postcode table](postcodes.md#looking-up-postcodes-on-this-machine):
```python
from uk_open_data.analyses.need_reach import download_need_figures, keep_need_figures
download_need_figures("unemployed") # fetch once, when a server is built
download_need_figures("residents") # so the map can shade need by its rate
# or keep figures of your own under a built-in need, for a demonstration
keep_need_figures(
"unemployed",
[("E09000023", "Lewisham", 9000), ("E09000011", "Greenwich", 8000)],
note="invented for a demonstration.",
)
```
A result that used a kept copy says so in its `sources` and its `working`,
with the note the copy was kept with.
The area you serve should hold the places you do not reach yet as well. Name it with `catchment`: a
list of local authorities, or a country. When you leave it out, the analysis
works the area out as the first analysis does: each local authority that holds
at least 5% of the people located (`catchment_min_share`). When none does,
every local authority in England and Wales is compared.
An area worked out this way holds only places you already reach, so it can
show where your reach is low against need but not where you reach nobody. The
result says so in a warning. To see the places you do not reach, name the area.
| Figure | Meaning |
| --- | --- |
| `people_supplied` | People in the data you gave |
| `people_located` | People placed in a local authority in England or Wales |
| `people_in_catchment` | People who live in the area you serve |
| `areas_compared` | Local authorities compared |
| `people_in_need` | People in need in the area you serve |
| `reach_per_100_in_need` | People you reached per 100 people in need, across the area |
| `high_need_areas` | Local authorities with high need |
| `high_need_areas_without_people` | High-need local authorities where you reached nobody |
| `share_of_people_in_high_need_areas` | Share of your people who live in high-need local authorities |
| `share_of_need_in_high_need_areas` | Share of people in need who live there, for comparison |
The charts `need_in_priority_areas` and `reach_in_priority_areas` show people
in need and people reached per 100 in need for the places in `priority_areas`.
The labels follow the need. When the need is every resident, the figures, the
headings, the list, the working and the source say "residents" and "the local
authorities with the most residents", not "people in need" and "high need".
The fourth and fifth analyses do the same.
The answer says so when the area was worked out from your data: it opens "In
the 7 local authorities where most of your people live". When a fifth or more
of the people in your data could not be placed in the area you serve, it ends
by saying how many are not counted. When some of them could not be placed in
any local authority, which is a name or a postcode to put right, and others
live outside the area, which is not a mistake, it says how many of each.
When only one local authority is compared every share is 100%, so
`key_figures` names the rate and the two counts behind it instead:
`reach_per_100_in_need`, `people_in_catchment` and `people_in_need`.
| Table | Rows |
| --- | --- |
| `priority_areas` | The high-need local authorities, your lowest reach first: people in need, people, people per 100 in need. It is a list in that order and no more: a place on it can have more reach than the area as a whole |
| `by_local_authority` | One per local authority compared, with need and reach in bands, and people in need for each 1,000 residents. This feeds the map |
The map shades need by its rate, people in need for each 1,000 residents, in
five equal groups. With fewer than five places, each is a group of its own,
from the lowest group to the highest, and one place alone is in the middle
group. The three groups of the reach layer work the same way. The note of a
layer says so when its places are fewer than its groups, and says nothing of
it otherwise. A count would
make the largest places darkest whatever their need. The list of high-need places still goes by the count, as
the case study does. The residents are the census count of everyone who lives
in each local authority, loaded beside the need figures.
The map falls back to the count in two cases, and the result says which way
it went in its choices (`map_need`) and in the note of the map's `need` layer.
One is when the need is every resident, so there is no rate to work out. The
other is when the need figures came from a copy kept on the machine and no
copy of the residents is kept beside it: the analysis does not fetch them, so
that a run kept off the network stays off it.
| Option | Default | Meaning |
| --- | --- | --- |
| `suppress_below` | `5` | Counts above zero and below this are hidden |
| `postcode_lookup` | `"auto"` | As for the first analysis |
| `need` | `"unemployed"` | The need to compare your reach with |
| `catchment` | worked out | A local authority name or code, a list of them, or `"England"`, `"Wales"` or `"England and Wales"` |
| `catchment_min_share` | `0.05` | The share a local authority needs to join a worked-out area |
| `top` | `10` | How many places to list, from 1 to 50 |
```python
result = run_analysis(
"need-reach",
clients,
columns={"postcode": "Client postcode"},
options={"need": "unemployed_women"},
)
result.table("priority_areas").to_frame()
```
A local authority with a hidden count is still ranked. It is ranked as if it
had the largest count that would be hidden, which depends on the threshold
alone, so the order of the list gives nothing away.
!!! note "Before you use the figures"
Read `result.checks` and `result.caveats`. Low reach is not the same as
unmet need: another organisation may already serve the place. Need is a
count of people, so large local authorities are more likely to be listed.
## Who we are missing
`who-we-miss` answers: who do we reach less than their share of the people who
live here? It covers England and Wales, and is the method of the
[Sobus case study](../case-studies/sobus-bame-analysis.md) turned into a
function.
It accepts three shapes of data:
| Input mode | Columns | What it is |
| --- | --- | --- |
| `postcodes` | `group`, `postcode` | One row per person, with their group and home postcode |
| `group_counts` | `group`, `count` | Already totalled by group |
| `people` | `group` | One row per person, with their group and no location |
The `group` column holds each person's ethnic group, or their sex, in your own
words. The analysis matches each label to a group the 2021 Census publishes,
counts your people by group, and sets each group's share of your people
against its share of the residents of **the area you serve**. A group is
**under-represented** when its share of your people is below four fifths of
its share of residents.
Choose what the column holds with the `characteristic` option:
| `characteristic` | Groups compared | Census table |
| --- | --- | --- |
| `"ethnic_group"` (default) | Asian, Black, Mixed, White, Other | TS021 |
| `"sex"` | Female, Male | TS008 |
Labels are matched by their wording. "Black Caribbean" is Black, "White and
Black Caribbean" is Mixed, "Any other ethnic group" is Other, and "Not stated"
matches nothing. People whose label matches nothing are counted, left out of
the shares, and a warning says how many there are. Codes and short forms
cannot be matched by wording, so say where they belong with the `groups`
option:
```python
result = run_analysis(
"who-we-miss",
clients,
columns={"group": "Ethnicity", "postcode": "Client postcode"},
options={"groups": {"BAF": "Black", "WBR": "White"}},
)
result.table("by_group").to_frame()
```
The result names the census groups. It never repeats one of your own labels.
The `group` role lists the census group names as its `reported_values`,
because a label of yours can be the same as one of them.
With postcodes the analysis works out the area you serve as the first analysis does: the
local authorities that each hold at least 5% of the people it could place.
People who live outside it are left out, because they are set against the
residents of the area you serve. Without postcodes the analysis cannot tell where you
work, so you must name the area with `catchment`.
The residents come from [Nomis](ons.md), for every local authority at once.
They are public, are fetched once for each characteristic and are then kept in
memory; `clear_residents_cache()` forgets them. To run with no request to
Nomis, keep a copy on the machine, as for need figures:
```python
from uk_open_data.analyses.who_we_miss import download_residents, keep_residents
download_residents("ethnic_group") # fetch once, when a server is built
# or keep figures of your own, for a demonstration
keep_residents(
"sex",
[("E09000023", "Lewisham", {"Female": 156000, "Male": 144000})],
note="invented for a demonstration.",
)
```
| Figure | Meaning |
| --- | --- |
| `people_supplied` | People in the data you gave |
| `people_in_catchment` | People set against residents: with postcodes, those who live in the area you serve |
| `people_matched` | People whose label matched a census group. The shares are of these people |
| `people_not_matched` | People with no label, or one that matched no census group |
| `residents` | Residents of the area you serve in the 2021 Census |
| `groups_under_represented` | Groups you reach less than their share of residents |
| `share_of_people_first_group` | Share of your people in the first of those groups |
| `share_of_residents_first_group` | Share of residents in that group |
The last two are the two shares the answer quotes, each with its value before
rounding. They are there when the answer quotes them: when a group is reached
less than its share and has people in your data.
The chart `people_against_residents` sets the share of your people in each
group against the share of residents.
| Table | Rows |
| --- | --- |
| `by_group` | One per census group: people, share of people, residents, share of residents, `representation` (the first share divided by the second) and whether the group is under-represented |
| Option | Default | Meaning |
| --- | --- | --- |
| `suppress_below` | `5` | Counts above zero and below this are hidden |
| `postcode_lookup` | `"auto"` | As for the first analysis |
| `characteristic` | `"ethnic_group"` | What the group column holds |
| `groups` | none | Your label to census group, for labels the wording does not settle |
| `catchment` | worked out from postcodes | A local authority name or code, a list of them, or `"England"`, `"Wales"` or `"England and Wales"`. Needed when there are no postcodes |
| `catchment_min_share` | `0.05` | The share a local authority needs to join a worked-out area |
| `under_represented_below` | `0.8` | A group is under-represented below this fraction of its share of residents |
A group with a hidden count is not judged. A group nobody came from has a
count of zero, which is shown, and is under-represented.
This analysis has no map yet. The residents are compared across the whole
area you serve, not place by place.
!!! note "Before you use the figures"
Read `result.checks` and `result.caveats`. A gap is not proof of a
barrier: groups differ in age and in need, and the census counts
residents of every age. With few people, a gap can be chance. Do not
publish two runs with different areas side by side, because a small
count can be worked out by taking one from the other.
## Provision gap
`provision-gap` answers: where is provision thin against need across a region?
It covers England and Wales, by local authority, and follows the method of the
[Starlight case study](../case-studies/starlight-children-mapping.md): total
what is provided in each place, divide by the people it is for, and look at
the places where need is high and provision is thin.
The analysis is about sites and what they provide, not about people. It accepts
three shapes of data:
| Input mode | Columns | What it is |
| --- | --- | --- |
| `sites` | `postcode`, `volume` | One row per site or service, with how much it provides |
| `area_volumes` | `local_authority`, `volume` | Already totalled by local authority, named or coded |
| `site_list` | `postcode` | One row per site or service. Each site counts as one |
The volume is a number of zero or more: sessions, places, boxes, hours. A row
whose volume is not a number stops the run, and the message says how many rows
to correct. Postcodes are placed as in the first analysis: on your machine when
the postcode table is installed, and with postcodes.io otherwise.
The analysis loads a count of people in every local authority from
[Nomis](ons.md), divides the provision in each one by it, and lists
the high-need local authorities with the least provision per 1,000
people. A local authority is high need when its count is in the top quarter
of the area you serve, as in the second analysis.
The `need` option takes the same values as in the second analysis, and the same
kept copies (`keep_need_figures`, `download_need_figures`) are used. The
default here is `"residents"`, everyone who lives in the place, because
provision is often for anyone. Choose a narrower need when what you provide is
for a group Nomis counts.
| Figure | Meaning |
| --- | --- |
| `volume_supplied` | Provision in the data you gave |
| `volume_located` | Provision placed in a local authority in England or Wales |
| `volume_in_catchment` | Provision in the area you serve |
| `areas_compared` | Local authorities compared |
| `areas_without_provision` | Local authorities where you provide nothing |
| `people_in_need` | People in need in the area you serve |
| `volume_per_1000_in_need` | Provision per 1,000 people in need, across the area |
| `high_need_areas` | Local authorities with high need |
| `high_need_areas_without_provision` | High-need local authorities where you provide nothing |
| `share_of_provision_in_high_need_areas` | Share of your provision that is in high-need local authorities |
| `share_of_need_in_high_need_areas` | Share of people in need who live there, for comparison |
The charts `need_in_priority_areas` and `provision_in_priority_areas` show
people in need and provision per 1,000 in need for the places in
`priority_areas`. The map has two layers, `need` and `provision`.
| Table | Rows |
| --- | --- |
| `priority_areas` | The high-need local authorities, thinnest provision first: people in need, volume, volume per 1,000 in need. The labels follow the need, as in the second analysis |
| `by_local_authority` | One per local authority compared, with need and provision in bands. This feeds the map |
| Option | Default | Meaning |
| --- | --- | --- |
| `postcode_lookup` | `"auto"` | As for the first analysis |
| `need` | `"residents"` | The people to set your provision against |
| `catchment` | England and Wales | A local authority name or code, a list of them, or `"England"`, `"Wales"` or `"England and Wales"` |
| `top` | `10` | How many places to list, from 1 to 50 |
```python
result = run_analysis(
"provision-gap",
sites,
columns={"postcode": "Site postcode", "volume": "Sessions a year"},
options={"catchment": "Wales"},
)
result.table("priority_areas").to_frame()
```
This analysis hides no count, and has no `suppress_below` option. Provision is
what an organisation provides, not a number of people, so every total is shown,
however small. Where a local authority holds one site, the provision shown for
it is that site's. If your numbers are people, such as people seen at each site,
use the need against reach analysis instead, which hides small counts. The result
still names no site and repeats no postcode.
The case study compares England's Integrated Care Boards and uses hospital
admissions as the need. This analysis compares local authorities and takes the
need from Nomis. Health boards, and a need column of your own, are not in it
yet.
!!! note "Before you use the figures"
Read `result.checks` and `result.caveats`. Thin provision is not the same
as unmet need: another organisation may already provide there. Provision
is counted where a site is, and people travel. Need is a count of people,
so large local authorities are more likely to be listed.
## Access and distance
`access-distance` answers: how far are people from our nearest site, and where
would a new site help most? It covers England and Wales, by local authority,
and follows the method of the
[Material Focus case study](../case-studies/material-focus-recycling.md).
Like the provision gap analysis, it is about sites, not about people. It accepts
two shapes of data:
| Input mode | Columns | What it is |
| --- | --- | --- |
| `site_coordinates` | `latitude`, `longitude` | One row per site, in degrees. West is negative |
| `site_postcodes` | `postcode` | One row per site. Placed on your machine when the postcode table and the centres of neighbourhoods are there |
A row whose position is outside the United Kingdom is left out and counted;
that is also what happens when the two columns are swapped. A site in
Scotland or Northern Ireland still counts as a site.
### Site postcodes that stay on your machine
The [postcode table](postcodes.md#looking-up-postcodes-on-this-machine) holds
the neighbourhood of each postcode but no position. So the analysis places a site
at the centre of its neighbourhood, from a file of neighbourhood centres kept
on your machine. In a town that moves a site by a few hundred metres, and in
the countryside by up to a few kilometres; the result carries a caveat that
says so. Keep the centres once, when a server is built:
```python
from uk_open_data.analyses.access_distance import download_centres
download_centres("neighbourhood") # about 35,700 centres, about 1 MB
```
What happens to site postcodes follows `postcode_lookup`:
| `postcode_lookup` | Postcode table installed | No postcode table |
| --- | --- | --- |
| `"auto"` (the default) | Placed on your machine. Nothing is sent | Sent to postcodes.io |
| `"offline"` | Placed on your machine. Nothing is sent | The analysis stops |
| `"online"` | Sent to postcodes.io | Sent to postcodes.io |
With a postcode table installed and no centres kept, the analysis stops and names
the function to run. It never falls back to sending postcodes, and it never
fetches the centres while an analysis runs. A server that sets `"offline"` cannot
send a postcode. The result says which happened, under `choices` and
`privacy.sent_to_third_parties`.
The table and the centres cover England and Wales. On your machine, a site
with a Scottish or Northern Irish postcode is not found and is left out and
counted; give its latitude and longitude instead.
The analysis loads the people in every local authority from [Nomis](ons.md) and
the centre of every local authority from the ONS Open Geography Portal. For
each local authority it measures the distance in a straight line from the
centre to your nearest site, to the nearest kilometre. A local authority is
within reach when that distance is `within_km` or less. The list shows the
local authorities beyond reach, with the most people first: the places where
a new site would bring the most people within reach.
**Distance is not travel time.** The package has no road or public transport
times, so the analysis does not turn kilometres into minutes. And it measures from
the centre of a local authority, not from where each person lives, which is
rough for a large rural one.
The `need` option takes the same values as in the second analysis, and the same
kept copies. The default is `"residents"`. The centres can be kept on the
machine too, so the analysis runs with no request at all:
```python
from uk_open_data.analyses.access_distance import download_centres, keep_centres
download_centres() # fetch once, when a server is built
# or keep centres of your own, for a demonstration
keep_centres(
[("E09000023", 51.45, -0.02), ("E09000011", 51.47, 0.05)],
note="invented for a demonstration.",
)
# the same for the centres of neighbourhoods, which place site postcodes
keep_centres(
[("E01003189", 51.46, -0.01)],
note="invented for a demonstration.",
level="neighbourhood",
)
```
| Figure | Meaning |
| --- | --- |
| `sites_supplied` | Sites in the data you gave |
| `sites_located` | Sites placed in the United Kingdom |
| `areas_compared` | Local authorities compared |
| `people_in_need` | People in the area you serve |
| `average_distance_km` | Average distance from the centre of each person's local authority to your nearest site. A place with many people counts for more |
| `share_of_people_within_reach` | Share of people in a local authority whose centre is within `within_km` of a site |
| `people_beyond_reach` | People in a local authority whose centre is farther than that |
| `areas_beyond_reach` | Local authorities whose centre is farther than that |
| `farthest_distance_km` | Distance from the centre of the farthest local authority to a site |
Every distance is from the centre of a local authority, the one the ONS
publishes for it, and every person is counted there. That is coarse. A London
borough is a few kilometres across, so 10 km says something about it. A large
rural local authority can be 50 km across: a site can be inside it and still
be farther than 10 km from its centre, and the place is then listed as far
from a site. The answer, the labels, the headings and a caveat all say that
distance is from the centre. Where the places you work in are large, set
`within_km` higher and read the distances, not only who is within reach.
The charts `people_in_priority_areas` and `distance_in_priority_areas` show
the people and the distance for the places in `priority_areas`. The map has
two layers, `distance` and `need`.
| Table | Rows |
| --- | --- |
| `priority_areas` | The local authorities beyond reach, most people first: people, distance in kilometres. Empty when every place is within reach |
| `by_local_authority` | One per local authority compared, with people and distance in bands. This feeds the map |
| Option | Default | Meaning |
| --- | --- | --- |
| `postcode_lookup` | `"auto"` | How site postcodes are placed. See the table above |
| `need` | `"residents"` | The people to measure distance for |
| `catchment` | England and Wales | A local authority name or code, a list of them, or `"England"`, `"Wales"` or `"England and Wales"` |
| `within_km` | `10` | How many kilometres from a site counts as within reach |
| `top` | `10` | How many places to list, from 1 to 50 |
```python
result = run_analysis(
"access-distance",
sites,
columns={"latitude": "Lat", "longitude": "Long"},
options={"catchment": "Wales", "within_km": 15},
)
result.table("priority_areas").to_frame()
```
This analysis hides no count, and has no `suppress_below` option. The result
names no site and repeats no postcode or position. Distances are rounded to
the kilometre, but the distances from several local authorities can still
show roughly where a site is.
!!! warning "Confidential addresses"
Do not share a result if the address of a site is confidential, such as a
refuge. A check in every result asks this.
!!! note "Before you use the figures"
Read `result.checks` and `result.caveats`. The figures say how far people
are from a site. They do not say how far the people you see travel, or
whether anyone far away needs you.
## Writing an analysis
An analysis is an `AnalysisInfo` and a function that takes an `AnalysisInput` and
returns an `AnalysisResult`. Register it with `register_analysis`. The rules every
analysis keeps:
1. Totals, never rows. Report problems by how many rows they affect.
2. Hide small counts and anything that gives them away. Do not publish two
breakdowns that can be taken from each other to get a small count. Say in
the privacy notes that a hidden count is not always small.
3. Give every figure a source.
4. State every choice and name the option that changes it. Give each option
a `label`, use the label in quotes whenever a sentence points at the
option, and pass `option=` or `role=` when you raise `AnalysisInputError`.
Give a table `headings` for any column the package has no heading for.
5. Leave checks for a person to answer.
6. List anything sent off the machine in `privacy.sent_to_third_parties`.
7. Answer the question in `answer`, from figures the result shows and nothing
else, and name the figures to show first in `key_figures`.
8. Give a share or a rate its `exact` value, from `before_rounding`, when the
figure is shown, and never when it is hidden. Mark an option `private`
when the value a person gives holds words from their own data, so the
code that runs the analysis again leaves it out. `run_analysis` writes
`result.code` for you.
## Command Line
# Command line
The package installs one command under two names, `uk-open-data` and
`kindtech`. It runs [analyses](analyses.md) on a file without writing any Python.
```bash
uv add uk-open-data pandas # the command needs pandas or polars installed
uv run uk-open-data analysis list
```
## Commands
### `analysis list`
Lists every analysis with the question it answers. Add `--json` for the full
descriptions.
```bash
uk-open-data analysis list
# reach-deprivation: Are we reaching people in the most deprived neighbourhoods?
```
### `analysis describe ANALYSIS_ID`
Shows what an analysis needs: the shapes of data it accepts, the columns, and the
options with their defaults. Add `--json` for the same as JSON.
```bash
uk-open-data analysis describe reach-deprivation
```
### `analysis run ANALYSIS_ID FILE`
Runs an analysis on a `.csv`, `.xlsx` or `.ods` file and prints a plain-text report:
a sentence or two that answer the question, then the figures, the tables, the
checks to make before using them, what the figures cannot say, the choices
made, the working, the figures before rounding, the sources, a privacy
summary and the Python that runs it again. A number has its unit
after it, such as "64.7 km", unless the label beside it already says the unit.
```bash
uk-open-data analysis run reach-deprivation clients.csv \
--column postcode="Client postcode"
```
| Flag | Meaning |
| --- | --- |
| `--column ROLE=COLUMN` | Which of your columns plays a role. Repeat it for each role |
| `--option NAME=VALUE` | Change an option. Repeat it for each option |
| `--sheet NAME` | The sheet to read from a spreadsheet. The first sheet is read by default |
| `--json` | Print the whole result as JSON instead of a report |
| `--summary` | With `--json`, leave out the rows of long tables such as map data |
| `--output PATH` | Write to a file instead of the screen |
| `--map PATH` | Also draw the map and save it as an `.svg` file |
| `--map-layer LAYER` | What the map is coloured by, for example `people`. The first layer is used by default |
An option value is read as JSON when it is JSON, and as text otherwise:
```bash
uk-open-data analysis run reach-deprivation clients.csv \
--column postcode="Client postcode" \
--option suppress_below=10 \
--option catchment='["Lewisham", "Greenwich"]'
```
When the file, a column or an option cannot be used, the command prints what is
wrong and exits with status 2. The message never repeats a value from your
data, so it is safe to paste into a chat or an issue.
A message names an option by its plain name, as a page shows it, such as
'Area you serve'. When an error is about one option or one column, a last line
says what to type here: "On the command line this is --option
catchment=VALUE." `analysis describe` lists every option with both names.
The outlines for `--map` come from the ONS Open Geography Portal. They
usually come in a few seconds, but at times the service takes a minute or two
to answer, so the command first writes "Fetching the outlines for the map
..." to standard error. The report on standard output is not changed by it. When the outlines
cannot be fetched, the report is still printed or written, no map file is made,
and the command says so in one sentence and exits with status 3. Status 3 means
the report is whole and only the map is missing, so a script can keep the
report. Status 2 means nothing was made.
A run that prints its answer writes one line to the `uk_open_data.runs` logger,
with the analysis, the input mode and the word `cli`. Nothing collects it on
your machine and nothing is sent anywhere. See
[`record_run`](analyses.md#record_runanalysis_id-input_mode-door).
### `postcodes download`
Fetches the postcode table, a few megabytes, so that analyses look postcodes up on
your machine and send none of them out. Run it once. `--force` fetches it
again, and `--url` with `--sha256` fetches a copy you host yourself.
```bash
uk-open-data postcodes download
```
### `postcodes info`
Shows the installed table's edition, size and the credits to show when you
publish something made with it. With no table installed it says so, says first
that an analysis still works, by looking postcodes up with postcodes.io and
saying so in its result, and then says how to get a table. That is not an
error.
### `postcodes build SOURCE TABLE --edition EDITION`
Builds a table from the ONS best-fit postcode lookup (`.csv`, or the `.zip` it
comes in) and prints its SHA-256. This is how a new edition is published; you
do not need it to use the package.
### `connector`
Starts the [connector](connector.md), which offers the analyses to a chat
assistant as tools. It is the same as `python -m uk_open_data.connector` and
takes the same options:
```bash
uk-open-data connector
uk-open-data connector --transport streamable-http --port 8000
```
It needs the `connector` extra, and says so when the extra is not installed:
```bash
uv add "uk-open-data[connector]"
```
Over stdio, the default, the command prints nothing and waits: the assistant
starts it and talks to it. It runs until the assistant, or you, stop it.
## Using it from an assistant
Give an assistant the JSON summary, not your file:
```bash
uk-open-data analysis run reach-deprivation clients.csv \
--column postcode="Client postcode" --json --summary
```
The summary holds totals only, with small counts hidden. Your rows stay on your
machine.
## Connector for chat assistants
# Connector for chat assistants
The `uk_open_data.connector` module offers the analyses and open data to a chat
assistant, such as Claude or ChatGPT, over the
[Model Context Protocol](https://modelcontextprotocol.io/). A charity worker
asks a question in their own words; the assistant calls a tool; figures come
back with their sources.
Every tool is read-only, and every tool keeps one rule: **the assistant sees
totals, never rows**.
## Start it
The server needs the `connector` extra:
```bash
uv add "uk-open-data[connector]"
uv run uk-open-data connector
```
With pip it is `pip install "uk-open-data[connector]"`, then
`uk-open-data connector`. Started without the extra, the command ends with one
sentence that says how to install it.
`python -m uk_open_data.connector` starts the same thing and takes the same
options. That runs over stdio, which is how a desktop assistant starts a local
connector. For Claude Desktop or Claude Code, add this to the MCP
configuration, with the path to your checkout:
```json
{
"mcpServers": {
"kindtech": {
"command": "uv",
"args": [
"run", "--directory", "/path/to/uk-open-data", "--extra", "connector",
"uk-open-data", "connector"
]
}
}
}
```
To host it, run the same server over Streamable HTTP. The address to give an
assistant then ends in `/mcp`:
```bash
uv run uk-open-data connector --transport streamable-http --port 8000
```
## Tools
| Tool | What it does |
| --- | --- |
| `find_analysis` | Finds the analysis that answers a question, and says what data it needs. |
| `describe_place` | Describes a place in England from the Indices of Deprivation 2025. |
| `run_analysis_on_counts` | Runs an analysis on counts that are already totalled by area or by group. |
### `find_analysis`
`query` is the question in the person's words, or left out to list every analysis.
The answer holds each analysis description, best match first.
An analysis that takes no totals cannot run in a chat. `needs_rows` in the answer
names the listed analyses of that kind and says where they can run. The access
and distance analysis is one: it needs a row per site that says where the site
is.
### `describe_place`
`place` is a local authority name or code, a 2021 LSOA code or a postcode
district such as `SE13`.
```python
from uk_open_data.connector import describe_place
answer = describe_place("Lewisham")
answer["status"] # "found"
answer["place"]["code"] # "E09000023"
answer["figures"] # neighbourhoods, residents, shares in the most deprived areas
answer["tables"] # by deprivation decile, and by type of deprivation
answer["sources"] # publisher, edition, licence and link
```
`status` is `found`, `choose` (several places match, listed in `matches`),
`not_found`, `not_covered` (outside England), `not_accepted` (a full postcode
or a street address) or `unavailable` (a data source could not be reached).
A full postcode is not accepted, even a venue's, because nothing tells a
venue's postcode from a person's home. It is not looked up, sent anywhere or
repeated, and the message asks for the first half of the postcode or the name
of the place. For one neighbourhood, pass its 2021 LSOA code.
A street address is not accepted either: a postcode inside other words, or a
number beside a word such as "Road", "Flat" or "House". The tool describes
areas, not buildings, and an address can be a person's home. The message says
an address should not be sent and asks for the council area or the first half
of the postcode.
The tool describes places in England only, because the deprivation index it
reads is England's. A council, code or postcode in Wales gives `not_covered`
with a message that says the place is in Wales and that the analyses which
cover England and Wales still work for it.
The deprivation index is read from a copy kept on this machine when there is
one, and the source in the answer then says so. When you host the connector,
keep it when the image is built (`uk_open_data.imd.download_imd`), so the first
call does not wait on a download. A copy kept with `uk_open_data.imd.keep_imd`
that leaves out the types of deprivation gives the same answer without that
table, and says so in `warnings`. A copy that cannot be read gives the status
`unavailable`.
A postcode district is looked up in the
[postcode table on this machine](postcodes.md) when one is installed, so it is
not sent anywhere. Without a table it is sent to postcodes.io. Either way the
answer says which happened under `privacy`. When you host the connector,
install the table when the image is built (`uk-open-data postcodes download`),
so a district stays on your server.
### `run_analysis_on_counts`
`analysis_id` names the analysis. `counts` holds one object per area or group, keyed by
the role names of an input mode the analysis marks as `aggregated`. `options`
changes the analysis options.
| Analysis | One row of `counts` | Options it needs |
| --- | --- | --- |
| `reach-deprivation` | `{"lsoa_code": "E01003189", "count": 12}` | none |
| `need-reach` | `{"local_authority": "Lewisham", "count": 120}` | none |
| `who-we-miss` | `{"group": "Black Caribbean", "count": 40}` | `catchment`, the area you serve |
| `provision-gap` | `{"local_authority": "Lewisham", "volume": 1200}` | none |
A `volume` is what the charity provides in that place, such as sessions, places
or hours. The provision gap analysis hides no small figure, because a volume is
not a count of people, and its result says so.
The answer holds the analysis result without the rows of its detail tables, so an
assistant is not handed a row per neighbourhood. Such a table comes back with
its columns and no rows, and `rows_left_out` in the answer names those tables
and says they are not empty, so that an assistant does not report "nothing
found". Where the result's map is drawn from one of them, the note says the
map cannot be drawn from the answer. Rows about individual people,
such as one postcode per person, are refused, and so is one row per site.
The result holds `answer`, one or two sentences that answer the analysis's
question, and `key_figures`, the ids of the figures behind them. Both come
through as the analysis wrote them. Where a result has an answer, `open_with`
tells the assistant to begin its reply with that sentence in its exact words,
so a person reads the same words in a chat as on the Kindtech Evidence page
and at the command line. The sentence passes the same check as the rest of the
result: it is withheld if it repeats a value from the rows.
The result also holds what a person needs to check it. A share or a rate has
`exact`, its value before rounding, and the result has `code`, the Python that
runs the analysis again with the same settings. Both are described under
[the working](analyses.md) and come through as the analysis wrote them. The
code leaves the names of the person's columns to be filled in, and a setting
that holds their own labels, such as `groups` for `who-we-miss`, is written as
`{}`, so it passes the same check as the rest of the result. The server's
instructions and the tool's description tell an assistant to quote figures as
they are shown, rounded, and to give an exact value or the code only when the
person asks how a figure was worked out or asks for the code.
A count or volume given as text that is nothing but a number, such as
`"1200"` or `"1,200"`, is read as a number, because assistants often send one
that way. This applies to the roles an analysis marks `amount` in its description
and to no other. Any other text there is left for the analysis, which says how
many rows to correct.
```python
from uk_open_data.connector import run_analysis_on_counts
answer = run_analysis_on_counts(
"need-reach",
[
{"local_authority": "Lewisham", "count": 120},
{"local_authority": "Greenwich", "count": 40},
],
options={"catchment": ["Lewisham", "Greenwich", "Bexley", "Bromley"]},
)
answer["status"] # "ok"
answer["result"]["answer"] # the sentence to open with
answer["result"]["figures"] # headline figures, small counts hidden
answer["result"]["tables"] # the high-need places, lowest reach first
```
`catchment` is the area you serve: every place the charity serves, whether or
not it reaches anyone there yet. Without it, need against reach compares only
the local authorities that hold at least 5% of the people in the rows, so it
cannot show a place the charity does not reach yet, and its result says so in
a warning. With one place there is nothing to compare, and the answer says
that too. An assistant should ask the person for the area they serve when the
question is about where they are missing.
`status` is `ok`, `would_hide_counts`, `input_problem` (`problems` lists what
to fix, for example an option the analysis needs), `needs_rows`, `unknown_analysis` or
`unavailable` (a data source the analysis needs could not be reached).
A problem sentence is written for the person and names an option by the label
they read, in quotes: "Change 'Area you serve' to include them." An assistant
passes options by their code names, so when the analysis says which one a
problem is about, the answer also has `option` (for example `catchment`) or
`role` (the column, for example `count`). `find_analysis` lists each option's
label beside its name.
`needs_rows` is the answer for an analysis that takes no totals, such as the access
and distance analysis, whatever rows are passed. Its message says the analysis cannot
run in a chat, because it needs a row for each site and this tool takes totals
only, and that it runs on the Kindtech Evidence page or with the command line tool.
#### The map
An analysis result describes a map, and the table that feeds it is one of the
tables left out of an answer. So the server draws the map itself, one picture
for each thing the map can be coloured by, and sends the pictures beside the
answer: in the tool result's `_meta`, under `kindtech/map`, which is for the
app the person is using and is not part of what a model is given. The tool
points to a small page, `ui://kindtech/analysis-map.html`, that shows them. An
assistant app that supports [MCP Apps](https://github.com/modelcontextprotocol/ext-apps)
shows that page with the answer, so the person sees the map in the chat. An
app that does not shows the answer alone, as before.
The answer itself gains `map`, with `drawn` and a `note` for the assistant: a
picture was drawn for the person and the assistant is not given it, or why
none was drawn. An analysis with no map has no `map` in its answer, and neither has
a result that was held back. The plain Python function `run_analysis_on_counts`
draws nothing; only the server does.
The outlines are fetched from the ONS Open Geography Portal each time a map is
drawn. What is sent is public area codes only: those of the areas on the map
and of the local authorities near it, which are drawn pale around it. When
the outlines cannot be fetched the figures come back as usual and the note
says no map was drawn.
The figures do not wait long for a picture. A map in a chat is drawn from the
quick outlines, simplified to 200 metres, where the page and the command line
ask for finer ones. Outlines usually come in a few seconds, but at times the
boundary service has taken a minute or more for one map, and it is not known
why. So the server waits 15 seconds for the outlines and then sends the answer
without a map, with a note that says so and suggests running the analysis
again in a few minutes. The fetch is left to finish. The outlines of every
local authority are kept in memory once fetched, for as long as the server
runs.
When you host the connector, keep the outlines on your server and pass a
function that reads them, so that no run waits on another service:
```python
from uk_open_data.connector import build_server
server = build_server(map_boundaries=outlines_kept_here) # takes an analysis result
```
Pictures of more than about 1.5 MB together are not sent: the first layers
that fit are, and when not even one fits the note says so.
#### When counts would be hidden
An analysis hides a count from 1 to 4, and where it hides one count in a table it
hides a second, so the first cannot be worked out from the total. In a chat
that second count can be a number the person has just typed, which reads as a
fault. So when the answer would hide any figure or table row, the first call
holds it back and says so:
```python
answer = run_analysis_on_counts(
"reach-deprivation",
[
{"lsoa_code": "E01003189", "count": 3},
{"lsoa_code": "E01003190", "count": 30},
],
)
answer["status"] # "would_hide_counts"
answer["would_hide"] # {"figures_and_rows": 3, "counts_below": 5}
answer["choices"] # combine the small counts first, or run as it is
```
The answer holds no figure from the run and nothing from the rows. The person
then chooses. They can add each small count to a neighbouring area's count, or
to a broader group's, and send the rows again, saying with the figures which
rows were combined. Or they can take the result with those counts hidden:
```python
answer = run_analysis_on_counts(analysis_id, counts, hidden_counts="accept")
answer["status"] # "ok"
```
An analysis that hides nothing, such as the provision gap analysis, never asks.
When you host the connector, keep the public figures three of the analyses
compare with on the server when the image is built, so a run does not wait on
Nomis: `uk_open_data.analyses.need_reach.download_need_figures` for the need against
reach analysis, the same function called with `"residents"` for the provision gap
analysis, which sets provision against everyone who lives in a place unless told
otherwise, and `uk_open_data.analyses.who_we_miss.download_residents` for the who we
are missing analysis.
The `"residents"` figures serve two analyses. Need against reach uses them too,
to shade its map by people in need for each 1,000 residents. When the need
figures are kept and the residents are not, it does not fetch them: the map is
shaded by the count and the result says so in its choices. Keep both and the
map goes by the rate.
## The privacy rule
- No tool accepts rows about people. `run_analysis_on_counts` takes only input
modes an analysis marks as `aggregated`.
- Every result passes through `ensure_totals_only` before it is returned. If a
value from the input, such as a postcode or an area code sent with a count,
appears anywhere in a result, the result is withheld.
- The one exception is a role an analysis marks as `reported`: a column that holds
names the result uses too. For local authorities every value is a public
name. For a column that also holds a person's own words, such as their
ethnic group, the role lists the exact names the result uses
(`reported_values`, for example "White"), and only those may come back: a
charity's own label, such as "Black Caribbean", is still withheld if a
result repeats it. Small counts are still hidden, and a value with the
shape of a postcode is always withheld.
- Error messages name the argument that was wrong and never quote its value.
- The log follows the same rule. When a data source cannot be reached, the log
holds the kind of error and not the web address. The code that asks the
boundary service logs the address it asked, which holds the area codes of
the map, so the connector's command replaces each warning or error from
that code with one sentence that says a line was left out. A program that
builds the server itself and lets it fetch outlines calls
`uk_open_data.connector.maps.keep_addresses_out_of_the_log()` once to do
the same. When a tool crashes, the
assistant is told only that the tool failed, and the log says which tool
stopped, with what kind of error and where in the code, and leaves out the
error's own text, which can quote a value from the rows.
- An answer given through `run_analysis_on_counts` is counted with one line on
the `uk_open_data.runs` logger, written by
[`record_run`](analyses.md#record_runanalysis_id-input_mode-door):
`run analysis=need-reach mode=area_counts door=chat`. It holds the analysis,
the input mode and the word "chat", each from a fixed list, and nothing from
the rows or the options. A run that was held back, refused or withheld is not
counted. Nothing is sent anywhere: on your own machine the line goes to
stderr with the rest of the log, at any `--log-level`, and a host counts the
lines in the logs it keeps.
- `tests/test_connector_privacy.py` calls every tool the way an assistant does
and fails if a row-level value reaches a result. A new tool must add a case
there.
## Data Sources
# Data Sources
KindTech wraps two UK public data APIs that aren't prominently documented for
developers. This page documents the APIs, their quirks, and how this package's
ingestion scripts work.
---
## ONS Open Geography Portal (ArcGIS)
The [Open Geography Portal](https://geoportal.statistics.gov.uk/) serves UK
boundary data as an [Esri ArcGIS Hub](https://hub.arcgis.com/) deployment
under the ONS organisation ID `ESMARspQHYMw9BZ9`. It was
[launched in July 2020](https://www.arcgis.com/sharing/rest/portals/ESMARspQHYMw9BZ9?f=json),
though the ONS Geography team has used
[ArcGIS Online since June 2015](https://www.arcgis.com/sharing/rest/community/users/ONSGeography_data?f=json).
### Endpoints
| Endpoint | Description |
|---|---|
| `https://services1.arcgis.com/ESMARspQHYMw9BZ9/arcgis/rest/services?f=json` | Service catalog (JSON) |
| `.../{service_name}/FeatureServer?f=json` | The layers a service holds. Most hold one, numbered 0, but not all |
| `.../{service_name}/FeatureServer/{layer}/query?where=1%3D1&outFields=*&f=geojson` | Query features as GeoJSON |
| `https://www.arcgis.com/sharing/rest/portals/ESMARspQHYMw9BZ9?f=json` | Organisation metadata |
| `https://www.arcgis.com/sharing/rest/community/users/ONSGeography_data?f=json` | User profile |
Standard [ArcGIS REST API](https://developers.arcgis.com/rest/services-reference/online/).
No authentication needed. Licensed under
[OGL v3.0](https://www.ons.gov.uk/methodology/geography/licences). ONS does
not publish their own API documentation — they rely on Esri's standard
reference.
### Catalog discovery
The portal's
[services listing page](https://services1.arcgis.com/ESMARspQHYMw9BZ9/arcgis/rest/services/)
renders with client-side JavaScript — HTML scraping returns an empty ``.
Appending `?f=json` returns a machine-readable JSON catalog of ~3,700 services
(~1,200 FeatureServers plus MapServers, lookup tables, and other types).
!!! warning "Rate limiting"
The JSON endpoint is intermittently rate-limited. Some requests return an
empty `services` array. If ingestion returns 0 services, wait and retry.
### Service naming conventions
The catalog uses two naming conventions, both following the
[GSS Coding and Naming Policy](https://www.ons.gov.uk/methodology/geography/geographicalproducts/namescodesandlookups)
(implemented 1 January 2011):
**Short form** (post-2021):
```
LAD_DEC_2024_UK_BGC
│ │ │ │ └── Resolution: Generalised Clipped Boundaries
│ │ │ └───── Coverage: United Kingdom
│ │ └────────── Year: 2024
│ └────────────── Month: December
└────────────────── Geography: Local Authority Districts
```
**Long form** (pre-2021):
```
Local_Authority_Districts_December_2024_Boundaries_UK_BGC
```
The transition happened around 2021 (see
[Boundary Dataset Guidance: 2021 Onwards](https://geoportal.statistics.gov.uk/datasets/ons::boundary-dataset-guidance-2021-onwards/about)).
### Resolution codes
The [ONS digital boundaries page](https://www.ons.gov.uk/methodology/geography/geographicalproducts/digitalboundaries)
defines five standard resolutions:
| Code | Full name | Detail |
|------|-----------|--------|
| BFE | Full resolution, Extent of the Realm | Mean Low Water mark |
| BFC | Full resolution, Clipped to coastline | Mean High Water mark |
| BGC | Generalised Clipped | 20m tolerance |
| BSC | Super Generalised Clipped | 200m tolerance |
| BUC | Ultra Generalised Clipped | 500m tolerance |
Older ArcGIS service names use rearranged abbreviations:
| Old suffix | Current suffix |
|------------|---------------|
| FCB | BFC |
| FEB | BFE |
| GCB | BGC |
| SGCB | BSC |
| UGCB | BUC |
These old codes don't appear in official ONS documentation — they are an
ArcGIS-internal convention. The ingestion normalises all of them to the
current standard.
### Catalog quirks
**Historical datasets (1921-present):**
| Service | Year | Geography |
|---------|------|-----------|
| `CTRY_DEC_1921_GB_BGC` | 1921 | Countries |
| `CTY_DEC_1921_EW_BGC` | 1921 | Counties |
| `ED_1971_EW_BGC` | 1971 | Enumeration Districts |
| `ED_1981_EW_BGC` | 1981 | Enumeration Districts |
| `WD_1998_UK_BGC` | 1998 | Wards |
The 1921 boundaries were digitised around the 2021 Census centenary. The
1971/1981 entries are
[Enumeration Districts](https://www.ons.gov.uk/census/2001censusandearlier/glossary/ag)
(EDs) — operational units used for censuses 1961-1991, each representing one
enumerator's workload. EDs were
[superseded by Output Areas](https://www.ons.gov.uk/census/2001censusandearlier/dataandproducts/outputgeography/outputareas)
for the 2001 Census.
**May vs December releases:**
Administrative boundaries
[change during the year](https://www.ons.gov.uk/methodology/geography/ukgeographies/administrativegeography/ourchanginggeography/boundarychanges).
**May** boundaries reflect changes taking effect on local election day (first
Thursday in May). **December** boundaries provide a year-end snapshot aligned
with the 1 December reference date used for electoral statistics since 2001.
**Composite-key duplicates (9 cases):**
1. **Short-form + long-form names** for the same dataset — harmless duplicates
2. **NHSER variants** — "NHS England Regions" (`nhser18cd`) vs "NHS England
Region Local Offices" (`nhsrlo18cd`), different
[administrative levels](https://www.ons.gov.uk/methodology/geography/ukgeographies/healthgeography).
Local Offices were created in 2015 (from 27 Area Teams of 2013) and
[abolished by April 2020](https://geoportal.statistics.gov.uk/datasets/ons::nhs-england-region-local-office-to-nhs-england-region-april-2017-lookup-in-en/about)
3. **OA RUC variants** — Output Areas with and without the
[Rural-Urban Classification](https://www.ons.gov.uk/methodology/geography/geographicalproducts/ruralurbanclassifications)
(12 vs 17 columns). The
[RUC](https://www.ons.gov.uk/methodology/geography/geographicalproducts/ruralurbanclassifications/2021ruralurbanclassification),
first introduced in 2004, classifies OAs as urban or rural
4. **Trailing underscore typos** — stripped during ingestion
All entries are kept in the catalog. No skip lists, no manual curation.
### Geo ingestion
Parses ~2,500 ArcGIS services down to **654 boundary datasets** across **24
geography types**, spanning 1921-2026. Stdlib-only (`csv`, `re`, `requests`).
```bash
uv run python -m uk_open_data.geo._ingestion
```
---
## NOMIS API
[NOMIS](https://www.nomisweb.co.uk/home/about.asp) is a web-based database of
labour market and population statistics, operated by the **University of
Durham** on behalf of ONS
[since 1981](https://www.nomisweb.co.uk/home/about.asp). Licensed under the
[Open Government Licence](https://www.nomisweb.co.uk/home/copyright.asp).
### Endpoints
| Endpoint | Description |
|---|---|
| `dataset/def.sdmx.json` | Bulk listing of all datasets (SDMX JSON) |
| `dataset/{id}.data.csv?{params}` | Data download as CSV |
| `contenttype/sources.json` | Source groupings |
| `dataset/{id}.overview.json` | Dataset overview |
| `dataset/{id}/{concept}/def.sdmx.xml` | Dimension metadata (SDMX-ML) |
Base URL: `https://www.nomisweb.co.uk/api/v01/`
[Full API documentation](https://www.nomisweb.co.uk/api/v01/help)
### SDMX format
NOMIS uses [SDMX](https://sdmx.org/) 2.0 structures (KeyFamilies, Dimensions,
Codelists). The `.sdmx.json` format is a NOMIS-specific convenience — not the
standard SDMX-JSON from SDMX 2.1
([ISO 17369](https://sdmx.org/?page_id=5008)). The standard format is XML
(`.sdmx.xml`).
### Rate limits and authentication
| Access level | Limit |
|---|---|
| Guest (unauthenticated) | 25,000 cells per request |
| Authenticated (with UID) | No cell limit |
| KML / RSS formats | 1,000 cells |
Authentication is free — create an account on nomisweb.co.uk and get a UID
from "my account" > "web services".
!!! warning "Cell limit"
The limit is 25,000 **cells** (not rows). If your result has exactly
25,000 rows, it's likely truncated. Pass a NOMIS UID to retrieve the
full table.
### Source annotations in the bulk listing
The bulk listing (`dataset/def.sdmx.json`) includes source annotations
embedded in each dataset's `annotations` array:
```json
{
"id": "NM_1_1",
"name": {"value": "Jobseeker's Allowance with rates and proportions"},
"annotations": {
"annotation": [
{"annotationtitle": "contenttype/sources", "annotationtext": "jsa"},
{"annotationtitle": "LastUpdated", "annotationtext": "2025-01-14"}
]
}
}
```
1,572 out of 1,615 datasets have the `contenttype/sources` annotation in the
bulk listing. The remaining 43 genuinely lack source information.
### Catalog quirks
- **31 datasets from the 1961 Census** (NM_1230-NM_1257) —
[digitised around January 2021](https://www.nomisweb.co.uk/api/v01/dataset/NM_1230_1.overview.json),
covering England and Wales at district, county, parish, ward, and
enumeration district levels
- **1981/1991 Census data** — small area and workplace statistics
- **1968 SIC VAT registrations** — industrial classification data
NOMIS is a long-term statistical archive, not just current data.
### NOMIS ingestion
Makes **one HTTP request** to `dataset/def.sdmx.json`, extracts IDs, names,
and source annotations. Completes in ~6 seconds for 1,615 datasets.
Stdlib-only (`csv`, `requests`).
```bash
uv run python -m uk_open_data.ons._ingestion
```
### Community packages
No official client libraries from NOMIS, ONS, or Durham University. All
wrappers are community-built:
| Package | Language | Notes |
|---------|----------|-------|
| [nomisr](https://github.com/ropensci/nomisr) | R | Evan Odell, rOpenSci. [JOSS (2018)](https://doi.org/10.21105/joss.00859). Removed from CRAN July 2025 |
| [UKCensusAPI](https://github.com/virgesmith/UKCensusAPI) | Python | virgesmith |
| [nomisweb](https://github.com/ouseful-datasupply/nomisweb) | Python | Tony Hirst |
| [Consensus](https://github.com/Ilkka-LBL/Consensus) | Python | Ilkka-LBL |
---
## postcodes.io
[postcodes.io](https://postcodes.io/) is a free, open-source REST API that
resolves UK postcodes to administrative and statistical geographies. KindTech's
`postcodes` module wraps it so address data joins to the same
`geography_code` used by the geo and ONS modules.
### Endpoints
Base URL: `https://api.postcodes.io`
| Endpoint | Description |
|---|---|
| `POST /postcodes` | Bulk lookup, up to **100 postcodes** per request |
| `GET /postcodes/{postcode}` | Single postcode lookup |
| `GET /postcodes?lon={lon}&lat={lat}` | Reverse geocode — nearest postcodes to a point |
| `GET /outcodes/{outcode}` | Outcode info: spanned Local Authorities + centroid |
No authentication is required. KindTech batches bulk lookups at 100 per request
and preserves input order.
### Returned geography codes
A postcode lookup returns a `codes` object with standard ONS GSS codes.
KindTech surfaces these aligned to its geography types:
| KindTech level | postcodes.io `codes` key | Example |
|---|---|---|
| LSOA | `lsoa21` | `E01034394` |
| MSOA | `msoa21` | `E02007008` |
| OA | `oa21` | `E00182613` |
| LAD | `admin_district` | `E09000023` |
| WD (ward) | `admin_ward` | `E05013727` |
| ICB | `icb` | `E54000030` |
| TTWA | `ttwa` | `E30000234` |
2021 Census geographies (`lsoa21`, `msoa21`, `oa21`) are preferred so codes
match Census 2021 statistics and current boundary data.
### Licensing
postcodes.io code is MIT licensed; the underlying data is
[Open Government Licence v3.0](https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/),
containing OS data © Crown copyright and database right, Royal Mail data
© Royal Mail copyright and database right, and National Statistics data
© Crown copyright and database right. Maintained by
[Ideal Postcodes](https://ideal-postcodes.co.uk/).
---
## UK deprivation indices (IMD)
KindTech's `imd` module serves each nation's **official** deprivation index for
single-nation work, and the mySociety composite for comparing *across* nations.
The official per-nation indices are the primary path; the composite exists only
because there is no official UK-wide index.
### Official national indices
A single-nation call fetches that nation's **official** index directly from its
government source (not the composite):
| `load_imd(nation=...)` | Index | Geography | Source | Format |
|---|---|---|---|---|
| `"England"` (default `year=2025`) | IoD 2025 (30 Oct 2025) | LSOA 2021 | gov.uk File 7 | CSV |
| `"England", year=2019` | IoD 2019 | LSOA 2011 | gov.uk File 7 | CSV |
| `"Wales"` | WIMD 2019 | LSOA 2011 | gov.wales | ODS |
| `"Scotland"` | SIMD 2020v2 | Data Zone 2011 | gov.scot | XLSX |
| `"Northern Ireland"` | NIMDM 2017 | SOA 2001 | Open Data NI | CSV |
England's File 7 carries all seven domains as score + rank + decile plus a
population denominator. Wales/Scotland/NI publish **ranks** (1 = most deprived),
so KindTech surfaces the overall `imd_rank`, a within-nation `imd_decile`
derived from it, and a `_rank` per domain — with **nation-specific
domain sets** (Wales adds community safety + physical environment, Scotland adds
crime + a population denominator, NI adds living environment + crime &
disorder). All sources are fetched live and cached for the session; the
spreadsheet sources (Wales ODS, Scotland XLSX) are read with
[`python-calamine`](https://pypi.org/project/python-calamine/).
**Pending:** `load_imd(nation="Wales", year=2025)` (WIMD 2025, 27 Nov 2025) is
not wired up — StatsWales has no stable machine-readable download endpoint yet.
Scotland and NI have no 2025 release.
**Licensing:** Open Government Licence v3.0 — England IoD (MHCLG), WIMD (Welsh
Government), SIMD (Scottish Government), NIMDM (NISRA / Open Data NI).
### Composite UK IMD
All single-nation rankings are **within-nation** — an English "decile 1" and a
Scottish "decile 1" are not the same thing, because each official index ranks
areas only within its own nation, on different geographies and methodologies:
| Nation | Index | Publisher | Geography |
|---|---|---|---|
| England | IMD 2019 | MHCLG | LSOA (2011) |
| Wales | WIMD 2019 | Welsh Government | LSOA (2011) |
| Scotland | SIMD 2020 | Scottish Government | Data Zone (2011) |
| Northern Ireland | NIMDM 2017 | NISRA | Super Output Area |
To compare *across* nations you need one shared ranking, and there is no
official UK-wide index. So for `nation="UK"` KindTech uses the
[composite UK Index of Multiple Deprivation](https://github.com/mysociety/composite_uk_imd)
— a research dataset by [mySociety](https://www.mysociety.org/) — which re-ranks
every area (42,619 in total) onto one scale using the income and employment
domains shared by all four indices.
| Item | Value |
|---|---|
| File | `data/uk_index/UK_IMD_E.csv` (England-anchored) |
| Host | `raw.githubusercontent.com/mysociety/composite_uk_imd` |
| Rows | 42,619 (England 32,844 · Scotland 6,976 · Wales 1,909 · NI 890) |
| Key column | `lsoa` — LSOA/Data Zone/SOA code depending on nation |
| UK ranking | `UK_IMD_E_rank`, `UK_IMD_E_pop_decile`, `UK_IMD_E_pop_quintile` |
Fetched live and cached in-process for the session (a static research release);
column names are mapped to KindTech's conventions (`lsoa` → `geography_code`).
**Licensing:** the composite is
[Creative Commons Attribution 4.0](https://creativecommons.org/licenses/by/4.0/)
— **attribute mySociety** when redistributing. The underlying national indices
are Open Government Licence v3.0; the composite code is MIT licensed.
---
## Dataset Aliases
Instead of remembering NOMIS dataset IDs like `NM_2002_1`, you can use
friendly aliases:
```python
from uk_open_data import load_ons
# These are equivalent
df = load_ons("population", geography_type="LAD", time="latest")
df = load_ons("NM_2002_1", geography_type="LAD", time="latest")
```
Raw `NM_*` IDs are passed through unchanged — aliases are just a convenience.
### Available aliases
| Alias | NOMIS ID | Description |
|-------|----------|-------------|
| `population` | NM_2002_1 | Mid-year population estimates |
| `population_by_age` | NM_2002_1 | Same as `population` |
| `population_by_age_band` | NM_31_1 | Population by broad age band |
| `population_lsoa` | NM_2014_1 | Population estimates (LSOA level) |
| `jsa` | NM_1_1 | Jobseeker's Allowance |
| `claimant_count` | NM_162_1 | Claimant count |
| `annual_population_survey` | NM_17_1 | Annual Population Survey |
| `earnings` | NM_30_1 | Annual Survey of Hours and Earnings |
| `jobs_density` | NM_57_1 | Jobs density |
| `vacancies` | NM_19_1 | Vacancy survey |
| `vat_registrations` | NM_29_1 | VAT registrations/deregistrations |
| `census_2021` | NM_2021_1 | Census 2021 |
| `census_2011` | NM_144_1 | Census 2011 |
| `census_2001` | NM_58_1 | Census 2001 |
To list aliases programmatically:
```python
from uk_open_data import list_dataset_aliases
for a in list_dataset_aliases():
print(f"{a['alias']:30s} → {a['dataset_id']}")
```
---
## Geography Crosswalk
The geo module uses ONS geography type codes (`LAD`, `LSOA`, `MSOA`, etc.)
while NOMIS uses internal TYPE codes (`TYPE424`, `TYPE151`, etc.). KindTech
maps between them so you don't have to.
### Using `geography_type` in `load_ons()`
Instead of looking up NOMIS TYPE codes, pass the same geography type you
use with `load_geodata()`:
```python
from uk_open_data import load_geodata, load_ons
# Same geography concept, different APIs
boundaries = load_geodata(geography_type="LAD", year="2024")
statistics = load_ons("NM_1_1", geography_type="LAD", time="latest")
```
The raw `geography="TYPE424"` parameter still works if you need it.
### TYPE code mapping
NOMIS assigns different TYPE codes to the same geography at different time
points. KindTech resolves these automatically based on the `time` parameter:
| Geography | Year range | NOMIS TYPE |
|-----------|-----------|------------|
| LAD | 2023+ | TYPE424 |
| LAD | 2021-2022 | TYPE431 |
| LAD | 2019-2020 | TYPE434 |
| LAD | 2015-2018 | TYPE446 |
| LAD | pre-2015 | TYPE464 |
| CTYUA | 2023+ | TYPE423 |
| CTYUA | 2021-2022 | TYPE431 |
| CTYUA | 2015-2020 | TYPE446 |
| CTYUA | pre-2015 | TYPE463 |
| LSOA | 2021+ | TYPE151 |
| LSOA | pre-2021 | TYPE304 |
| MSOA | 2021+ | TYPE152 |
| MSOA | pre-2021 | TYPE305 |
| RGN | all | TYPE480 |
| CTRY | all | TYPE499 |
| WD | 2025+ | TYPE182 |
| CAUTH | 2025+ | TYPE442 |
| TTWA | 2011+ | TYPE447 |
| TTWA | pre-2011 | TYPE444 |
| ITL | 2025+ | TYPE419 |
| ITL | 2021-2024 | TYPE421 |
Source: NOMIS geography dimension metadata. To list all mappings
programmatically:
```python
from uk_open_data import list_geography_mappings
for m in list_geography_mappings():
print(m)
```
### Join keys
Both APIs return standard ONS geography codes (e.g. `E06000001`):
- **ArcGIS** returns fields like `LAD24CD` (code) and `LAD24NM` (name),
where the field name includes a 2-digit year suffix
- **NOMIS** returns `GEOGRAPHY_CODE` and `GEOGRAPHY_NAME` columns
KindTech normalises both sources so they share a common `geography_code`
column:
- `load_ons(normalize=True)` (the default) lowercases NOMIS columns,
producing `geography_code` and `geography_name`
- `geodata_to_properties()` maps year-stamped ArcGIS fields (e.g.
`LAD24CD`) to `geography_code` and `geography_name`
```python
from uk_open_data import load_geodata, load_ons, geodata_to_properties
import pandas as pd
geojson = load_geodata(geography_type="LAD", year="2024")
geo_df = pd.DataFrame(geodata_to_properties(geojson, "LAD", 2024))
ons_df = load_ons("population", geography_type="LAD", time="latest")
merged = geo_df.merge(ons_df, on="geography_code")
```
Under the hood, `geo_code_field()` and `geo_name_field()` derive the
ArcGIS field names:
```python
from uk_open_data._mapping import geo_code_field, geo_name_field
geo_code_field("LAD", 2024) # "LAD24CD"
geo_name_field("LAD", 2024) # "LAD24NM"
```
---
## Architecture
KindTech ingests from two completely separate APIs into two independent CSV
catalogs. They share no data or endpoints — one provides geographic
boundaries (maps), the other provides statistical tables (numbers).
```
┌─────────────────────────────────────────────────────────────────────┐
│ TWO SEPARATE DATA SOURCES │
├──────────────────────────────┬──────────────────────────────────────┤
│ │ │
│ ONS Open Geography Portal │ NOMIS │
│ (ArcGIS FeatureServer) │ (Durham University for ONS) │
│ geoportal.statistics.gov.uk │ nomisweb.co.uk │
│ │ │
│ What: UK boundary maps │ What: UK statistics │
│ Format: GeoJSON polygons │ Format: CSV tabular data │
│ │ │
├──────────────────────────────┼──────────────────────────────────────┤
│ │ │
│ INGESTION (dev-time) │ INGESTION (dev-time) │
│ │ │
│ Source URL: │ Source URL: │
│ services1.arcgis.com/ │ nomisweb.co.uk/api/v01/ │
│ ESMARspQHYMw9BZ9/ │ dataset/def.sdmx.json │
│ arcgis/rest/services │ │
│ ?f=json │ 1 HTTP request → parse JSON │
│ │ → extract id, name, source │
│ 1 HTTP request → parse JSON │ from annotations │
│ → regex-parse ~3,700 │ │
│ service names │ Output: │
│ → normalise resolution │ ons/data/nomis_tables.csv │
│ codes │ (1,615 datasets) │
│ │ │
│ Output: │ uv run python -m │
│ geo/data/arcgis_services.csv│ uk_open_data.ons._ingestion │
│ (654 boundary datasets) │ │
│ │ │
│ uv run python -m │ │
│ uk_open_data.geo._ingestion │ │
│ │ │
├──────────────────────────────┼──────────────────────────────────────┤
│ │ │
│ RUNTIME (user-facing) │ RUNTIME (user-facing) │
│ │ │
│ load_geodata("LAD") │ load_ons("population", │
│ → look up CSV catalog │ geography_type="LAD") │
│ → query ArcGIS │ → resolve alias → NM_2002_1 │
│ FeatureServer │ → resolve geography → TYPE424 │
│ → return GeoJSON dict │ → query NOMIS .data.csv │
│ │ → return DataFrame │
│ │ (pandas or polars) │
│ │ │
└──────────────────────────────┴──────────────────────────────────────┘
```
Both ingestion scripts are stdlib-only (`csv`, `re`, `requests`). The
resulting CSV catalogs ship with the package. Users never run ingestion —
they call `load_geodata()` or `load_ons()` and get data back as GeoJSON or
a DataFrame.
To refresh the catalogs when ONS publishes updates:
```bash
# Geo boundaries — from ArcGIS
uv run python -m uk_open_data.geo._ingestion
# Statistics — from NOMIS
uv run python -m uk_open_data.ons._ingestion
```
Then commit the updated CSV files.
---
## References
### ONS Open Geography Portal
- [Portal homepage](https://geoportal.statistics.gov.uk/)
- [ONS Geography overview](https://www.ons.gov.uk/methodology/geography)
- [Digital boundaries (resolution types)](https://www.ons.gov.uk/methodology/geography/geographicalproducts/digitalboundaries)
- [Names, codes and lookups (GSS policy)](https://www.ons.gov.uk/methodology/geography/geographicalproducts/namescodesandlookups)
- [Boundary Dataset Guidance: 2021 Onwards](https://geoportal.statistics.gov.uk/datasets/ons::boundary-dataset-guidance-2021-onwards/about)
- [Boundary changes](https://www.ons.gov.uk/methodology/geography/ukgeographies/administrativegeography/ourchanginggeography/boundarychanges) — May vs December release cycle
- [Rural-Urban Classification](https://www.ons.gov.uk/methodology/geography/geographicalproducts/ruralurbanclassifications)
- [Health geographies](https://www.ons.gov.uk/methodology/geography/ukgeographies/healthgeography) — NHSER, ICB, Local Offices
- [Statistical geographies](https://www.ons.gov.uk/methodology/geography/ukgeographies/statisticalgeographies) — OA, LSOA, MSOA hierarchy
- [Enumeration Districts and Output Areas](https://www.ons.gov.uk/census/2001censusandearlier/dataandproducts/outputgeography/outputareas)
- [Licensing terms (OGL v3.0)](https://www.ons.gov.uk/methodology/geography/licences)
- [ArcGIS REST services directory](https://services1.arcgis.com/ESMARspQHYMw9BZ9/arcgis/rest/services/)
- [ArcGIS REST API reference (Esri)](https://developers.arcgis.com/rest/services-reference/online/)
- [ONS ArcGIS Online organisation](https://ons.maps.arcgis.com)
### NOMIS
- [NOMIS homepage](https://www.nomisweb.co.uk/)
- [About NOMIS](https://www.nomisweb.co.uk/home/about.asp) — University of Durham for ONS, since 1981
- [API documentation](https://www.nomisweb.co.uk/api/v01/help)
- [Copyright and licensing](https://www.nomisweb.co.uk/home/copyright.asp) — OGL, "Source: Office for National Statistics"
- [Dataset listing (SDMX JSON)](https://www.nomisweb.co.uk/api/v01/dataset/def.sdmx.json)
- [Content type sources](https://www.nomisweb.co.uk/api/v01/contenttype/sources.json)
- [Query builder](https://www.nomisweb.co.uk/query/advanced.aspx)
### Standards
- [SDMX (Statistical Data and Metadata eXchange)](https://sdmx.org/) — ISO 17369
- [Open Government Licence v3.0](https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/)
## Geographic Data
# Geographic Data
The `uk_open_data.geo` module provides access to UK geographic boundary data from the [ONS ArcGIS Geoportal](https://geoportal.statistics.gov.uk/).
## Functions
### `load_geodata()`
Load geographic boundary data as GeoJSON.
```python
from uk_open_data.geo import load_geodata, GeographyType, CoverageArea, BoundaryType
# Using strings
data = load_geodata(geography_type="LAD", coverage="UK", boundary_type="BGC")
# Using enums
data = load_geodata(
geography_type=GeographyType.LAD,
coverage=CoverageArea.UK,
boundary_type=BoundaryType.BGC,
)
# With filters
manchester = load_geodata(geography_type="LAD", LAD21NM="Manchester")
```
#### Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| `geography_type` | `str` or `GeographyType` | *required* | Geography level (e.g., `"LAD"`, `"LSOA"`) |
| `year` | `str` or `None` | `None` | Year of the data (e.g., `"2021"`) |
| `month` | `str`, `Month`, or `None` | `None` | Month (e.g., `"DEC"`, `Month.DEC`) |
| `coverage` | `str`, `CoverageArea`, or `None` | `None` | Coverage area (`"UK"`, `"GB"`, `"EW"`) |
| `boundary_type` | `str`, `BoundaryType`, or `None` | `"BGC"` | Boundary resolution |
| `simplify_m` | `float` or `None` | `None` | Ask the service to leave out detail finer than about this many metres |
| `**filters` | keyword args | | Field filters (e.g., `LAD21NM="Manchester"`) |
#### Simpler outlines
The ONS publishes most layers at several resolutions, and `boundary_type` picks one. Some layers are public only at full resolution and at 200 m, which is too heavy or too rough for a map of one town. For those, ask for the full-resolution layer and let the service simplify it:
```python
codes = ["E01003189", "E01003190"]
outlines = load_geodata(
"LSOA", year="2021", boundary_type="BFE", simplify_m=20, LSOA21CD=codes
)
```
A full-extent layer (`BFE`) runs to the low water mark and to the middle of a river, so it colours water as land on a map drawn large. Where a layer clipped to the shore is published (`BFC`), ask for that one. The service simplifies each outline by itself, so two neighbours may no longer share exactly the same edge; keep the distance small against the size of the map.
#### Returns
`dict` — A GeoJSON FeatureCollection. Returns `{"type": "FeatureCollection", "features": []}` if no matching service is found or the request fails.
The ONS boundary service gives a few thousand features in one answer. A larger layer, such as every neighbourhood, is fetched page by page, so the collection holds every feature. If any page fails, the collection is empty and an error is logged: you never get a part of a layer as if it were the whole. A large layer with outlines takes many requests; filter by code when you need only some areas.
---
### `get_field_info()`
Get available fields for filtering a dataset.
```python
from uk_open_data.geo import get_field_info
fields = get_field_info(geography_type="LAD")
# [{"name": "LAD21CD", "type": "esriFieldTypeString", "alias": "LAD Code"}, ...]
```
#### Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| `geography_type` | `str` or `GeographyType` | *required* | Geography level |
| `year` | `str` or `None` | `None` | Year |
| `coverage` | `str`, `CoverageArea`, or `None` | `None` | Coverage area |
| `boundary_type` | `str`, `BoundaryType`, or `None` | `None` | Boundary resolution |
#### Returns
`list[dict]` — Field metadata from ArcGIS (name, type, alias, etc.).
---
### `get_available_geography_types()`
List all supported geography types.
```python
from uk_open_data.geo import get_available_geography_types
types = get_available_geography_types()
# [{"code": "LAD", "description": "Local Authority Districts"}, ...]
```
---
### `get_available_boundary_types()`
List all supported boundary resolutions.
---
### `get_available_coverage_areas()`
List all supported coverage areas.
## Enums
All enums accept both string codes and enum values. They have `.code` and `.description` attributes.
| Enum | Values | Example |
|---|---|---|
| `GeographyType` | LAD, LSOA, MSOA, ... | `GeographyType.LAD` |
| `BoundaryType` | BFC, BFE, BGC, BSC | `BoundaryType.BGC` |
| `CoverageArea` | UK, GB, EW | `CoverageArea.UK` |
| `Month` | JAN through DEC | `Month.DEC` |
---
### `geodata_to_properties()`
Extract feature properties from GeoJSON with normalised column names for easy joins with ONS data.
```python
from uk_open_data import load_geodata, geodata_to_properties
import pandas as pd
geojson = load_geodata(geography_type="LAD", year="2024")
rows = geodata_to_properties(geojson, "LAD", 2024)
geo_df = pd.DataFrame(rows)
# geo_df has 'geography_code' and 'geography_name' columns
# plus all original ArcGIS properties (LAD24CD, LAD24NM, etc.)
```
#### Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| `geojson` | `dict` | *required* | GeoJSON FeatureCollection from `load_geodata()` |
| `geography_type` | `str` or `GeographyType` | *required* | Geography level (e.g., `"LAD"`, `"LSOA"`) |
| `year` | `int` or `str` | *required* | Year of the data (e.g., `2024`) |
#### Returns
`list[dict]` — One dict per feature, containing:
- `geography_code` — normalised geography code (e.g. `E06000001`), derived from the year-stamped ArcGIS field (e.g. `LAD24CD`)
- `geography_name` — normalised geography name (e.g. `Hartlepool`), derived from the year-stamped ArcGIS field (e.g. `LAD24NM`)
- All original ArcGIS properties preserved as-is
The normalised `geography_code` column matches the column produced by `load_ons(normalize=True)`, enabling trivial joins:
```python
from uk_open_data import load_geodata, load_ons, geodata_to_properties
import pandas as pd
geojson = load_geodata(geography_type="LAD", year="2024")
geo_df = pd.DataFrame(geodata_to_properties(geojson, "LAD", 2024))
ons_df = load_ons("population", geography_type="LAD", time="latest")
merged = geo_df.merge(ons_df, on="geography_code")
```
## How it works
1. The bundled CSV catalog (`geo/data/arcgis_services.csv`, 654 services across 24 geography types) maps geography type + year + coverage + boundary to an ArcGIS service ID
2. `load_geodata()` finds the best matching service (most recent year if not specified)
3. Queries the ArcGIS FeatureServer REST API for GeoJSON
4. Returns the raw GeoJSON FeatureCollection
5. `geodata_to_properties()` extracts feature properties and adds normalised `geography_code` / `geography_name` columns using `geo_code_field()` and `geo_name_field()` from the internal mapping module
## Deprivation (IMD)
# Deprivation (IMD)
The `uk_open_data.imd` module loads UK deprivation data, keyed on ONS geography
codes so it joins to [boundaries](geo.md) and [statistics](ons.md).
**A single nation returns that nation's _official_ index. `"UK"` returns a
composite — the only way to compare deprivation _across_ nations.**
## Official per nation, composite for comparison
Each UK nation publishes its own index, on its own geography, ranked **only
within its own borders** — an English "decile 1" and a Scottish "decile 1" are
not the same thing:
| Nation | Official index | Geography | Areas |
|---|---|---|---|
| England | IoD 2025 (or 2019) | LSOA 2021 (2019: LSOA 2011) | 33,755 / 32,844 |
| Wales | WIMD 2019 | LSOA 2011 | 1,909 |
| Scotland | SIMD 2020 | Data Zone 2011 | 6,976 |
| Northern Ireland | NIMDM 2017 | SOA | 890 |
To compare *across* nations you need one shared ranking. There is no official
UK-wide index, so KindTech uses the
[mySociety composite UK IMD](https://github.com/mysociety/composite_uk_imd)
(`nation="UK"`), which re-ranks every area onto one scale. The composite is a
third-party harmonisation, **not** a National Statistic — use it for
comparison, and a nation's official index for within-nation work.
## `load_imd()`
```python
from uk_open_data import load_imd
england = load_imd(nation="England") # official IoD 2025, 2021 LSOAs
england_19 = load_imd(nation="England", year=2019) # official IoD 2019, 2011 LSOAs
wales = load_imd(nation="Wales") # official WIMD (within-nation)
uk = load_imd() # composite, cross-nation comparison
```
`nation` accepts `"UK"` (default), `"England"`, `"Wales"`, `"Scotland"`,
`"Northern Ireland"`, or the codes `E`/`W`/`S`/`N`.
### `nation="England"` — official English Indices of Deprivation
The richest path: gov.uk **File 7** (all ranks, scores, deciles and population
denominators). `year=2025` (default, **2021** LSOAs) or `year=2019` (**2011**
LSOAs) — same schema, so 2019 → 2025 is a clean change comparison.
Returns `geography_code`, `geography_name`, `nation`, `lad_code`, `lad_name`,
the overall `imd_score`/`imd_rank`/`imd_decile`, a `score` + `rank` + `decile`
for each of the **seven domains** (`income`, `employment`, `education`,
`health`, `crime`, `housing` = barriers to housing & services,
`living_environment`; e.g. `income_rank`, `income_decile`), and a `population`
denominator. Ranks/deciles are within-England (rank 1 / decile 1 = most
deprived).
### `nation="Wales"` / `"Scotland"` / `"Northern Ireland"` — official, within-nation
Each nation's own official index, fetched from its government source (WIMD 2019,
SIMD 2020, NIMDM 2017). These publish **ranks** (1 = most deprived), so the
output is `geography_code` (LSOA / Data Zone / SOA), `geography_name`, `nation`,
the overall `imd_rank`, a within-nation `imd_decile` derived from that rank, and
a `_rank` for each of that nation's domains. The **domain sets differ
by nation** (only income/employment/health/education/access are shared):
| Nation | Source | Domains (`_rank`) | Extra |
|---|---|---|---|
| Wales (WIMD 2019) | gov.wales (ODS) | income, employment, health, education, access, housing, **community_safety**, **physical_environment** | — |
| Scotland (SIMD 2020) | gov.scot (XLSX) | income, employment, health, education, access, **crime**, housing | `population` |
| N. Ireland (NIMDM 2017) | Open Data NI (CSV) | income, employment, health, education, access, **living_environment**, **crime_disorder** | — |
!!! note "2025 availability"
Only **England** has a 2025 index. `load_imd(nation="Wales", year=2025)`
raises — WIMD 2025 has no stable machine-readable download on StatsWales
yet. Scotland and NI have no 2025 release at all.
!!! note "Reading XLSX/ODS sources"
Wales (ODS) and Scotland (XLSX) are spreadsheets, read via
[`python-calamine`](https://pypi.org/project/python-calamine/) (a KindTech
dependency). No extra setup needed.
### `nation="UK"` — composite (cross-nation comparison)
Returns `geography_code` (LSOA 2011 / Data Zone / SOA), `nation`, and:
| Column | Description |
|---|---|
| `imd_rank` | **UK-wide** rank (1 = most deprived) |
| `imd_decile` | **UK-wide**, population-weighted decile |
| `imd_quintile` | **UK-wide**, population-weighted quintile |
| `nation_decile` | The official within-nation decile (**not** UK-comparable) |
| `imd_score`, `income_score`, `employment_score`, `local_score` | Underlying scores |
Use this only when comparing areas in different nations; its `imd_rank` /
`imd_decile` are the UK re-ranking, not a nation's official figures (those are
in `nation_decile`, or use the single-nation calls above).
## Keeping the English index on this machine
`load_imd(nation="England")` downloads the published file from gov.uk the
first time a program asks for it. To run with no download, keep a copy in the
data folder, the same one that holds the
[postcode table](postcodes.md#looking-up-postcodes-on-this-machine):
```python
from uk_open_data.imd import download_imd, imd_path, keep_imd, load_imd
download_imd() # fetch the 2025 index once, when a server is built
imd_path() # where the copy is, or None
load_imd(nation="England") # reads the copy; nothing is downloaded
```
`keep_imd(table, note)` keeps a table of your own in its place, for a
demonstration or a test. Give a DataFrame or a list of row dictionaries with
at least `geography_code`, `geography_name`, `lad_code`, `lad_name`,
`imd_decile` and `population`. Columns you leave out come back empty. The
`note` says where the figures came from, and `kept_imd_note()` reads it back.
Pass `year=2019` to any of these for the 2019 index. Only the English index
can be kept. A `url` given to `load_imd` is always downloaded.
## Joining to boundaries and statistics
`geography_code` matches the rest of KindTech, so deprivation overlays onto a map
or merges with population for per-capita work:
```python
import pandas as pd
from uk_open_data import load_imd, load_geodata, geodata_to_properties
imd = load_imd(nation="England") # IoD 2025, on 2021 LSOAs
# Default boundaries are 2021 LSOAs — a native join, no crosswalk
geo = pd.DataFrame(geodata_to_properties(load_geodata("LSOA"), "LSOA", 2021))
mapped = geo.merge(imd, on="geography_code", how="left")
```
!!! warning "LSOA vintage"
**England IoD 2025** is on **2021** LSOAs, so it joins natively to Census
2021 and the default boundaries — no crosswalk needed. This is the easiest
path for English analysis.
Everything else — **England IoD 2019**, the **composite (`nation="UK"`)**,
and Wales/Scotland/NI — is on **2011** geographies. To join those, either
use 2011 boundaries (`load_geodata("LSOA", year="2011")`) or map postcodes
via `lsoa11` (see [Postcodes](postcodes.md)).
## Licensing
The composite dataset is licensed
[CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/) by mySociety; the
underlying national indices are Open Government Licence v3.0. See
[Data Sources](data-sources.md#composite-uk-imd) for details and attribution.
## ONS Data
# ONS Statistics
The `uk_open_data.ons` module provides access to UK statistics from the [ONS NOMIS API](https://www.nomisweb.co.uk/api/v01/help). Returns DataFrames in your preferred backend (pandas or polars) via [narwhals](https://narwhals-dev.github.io/narwhals/).
## Functions
### `load_ons()`
Load statistical data from the NOMIS API.
```python
from uk_open_data.ons import load_ons
# Basic usage
df = load_ons("NM_1_1")
# Using a friendly alias (see list_dataset_aliases())
df = load_ons("population", geography_type="LAD", time="latest")
# Using geography_type (recommended — no NOMIS TYPE codes needed)
df = load_ons("NM_1_1", geography_type="LAD", time="latest")
# Using raw NOMIS TYPE code (still works)
df = load_ons(
"NM_1_1",
geography="TYPE480",
time="latest",
measures=20100,
)
# Multiple values for a parameter
df = load_ons("NM_1_1", measures=[20100, 20201])
```
#### Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| `dataset_id` | `str` | *required* | NOMIS dataset code (e.g., `"NM_1_1"`) or friendly alias (e.g., `"population"`) |
| `geography_type` | `str` or `GeographyType` or `None` | `None` | Geography type (e.g., `"LAD"`, `"LSOA"`). Resolved to a NOMIS TYPE code automatically. Cannot be used with `geography=`. |
| `base_url` | `str` | NOMIS API URL | Override the API base URL |
| `normalize` | `bool` | `True` | Lowercase column names (e.g. `GEOGRAPHY_CODE` → `geography_code`) so they align with `geodata_to_properties()` for easy joins |
| `**kwargs` | keyword args | | Query parameters passed to the NOMIS API |
Common query parameters:
- `geography` — Raw NOMIS geography type (e.g., `"TYPE480"`). Prefer `geography_type` instead.
- `time` — Time period (e.g., `"latest"`, `"2023"`)
- `measures` — Measure codes (e.g., `20100` for value)
- `select` — Columns to return (list of strings)
- `sex` — Sex filter (e.g., `5` for male, `6` for female, `7` for total)
See the [NOMIS API docs](https://www.nomisweb.co.uk/api/v01/help) for the full parameter reference.
#### Returns
DataFrame (pandas or polars, depending on what's installed). If both are available, polars is preferred. Column names are lowercased by default (`normalize=True`), so `GEOGRAPHY_CODE` becomes `geography_code`, `OBS_VALUE` becomes `obs_value`, etc. Pass `normalize=False` to keep the original NOMIS column names.
#### Raises
- `ValueError` — If the dataset doesn't exist or the response can't be parsed
- `ImportError` — If neither pandas nor polars is installed
!!! warning "Row limit"
NOMIS returns a maximum of 25,000 rows per request. If your result has exactly 25,000 rows, it's likely truncated. Provide a NOMIS UID (`uid='0x...'`) to retrieve the full table.
---
### `list_tables()`
Browse available NOMIS datasets.
```python
from uk_open_data.ons import list_tables
# List all 1,615 datasets
all_tables = list_tables()
# Filter by name
pop_tables = list_tables(name="population")
# Filter by source
jsa_tables = list_tables(source="jsa")
```
#### Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| `name` | `str` or `None` | `None` | Substring to filter dataset names (case-insensitive) |
| `source` | `str` or `None` | `None` | Source name to filter by |
#### Returns
DataFrame with columns: `id`, `name`, `sourceName`.
## Bring Your Own DataFrame
The ONS module uses [narwhals](https://narwhals-dev.github.io/narwhals/) for DataFrame interoperability. Install your preferred backend alongside uk-open-data:
```bash
uv add pandas # or polars
```
The return type automatically matches your installed backend:
```python
import polars as pl
from uk_open_data.ons import load_ons
df = load_ons("NM_1_1", time="latest")
assert isinstance(df, pl.DataFrame) # polars preferred when both installed
```
## How it works
1. The bundled CSV catalog (`ons/data/nomis_tables.csv`, 1,615 datasets) maps dataset IDs to names and sources
2. If a friendly alias is used (e.g. `"population"`), it's resolved to a NOMIS ID (`NM_2002_1`)
3. If `geography_type` is given, it's resolved to a NOMIS TYPE code (e.g. `LAD` → `TYPE424`)
4. `load_ons()` builds a NOMIS API URL with your query parameters
5. Fetches CSV data from the NOMIS API
6. Parses into a DataFrame using your installed backend
7. Lowercases column names (when `normalize=True`) so they align with `geodata_to_properties()`
8. Returns the native DataFrame (no narwhals wrapper exposed)
## Postcodes
# Postcodes
The `uk_open_data.postcodes` module turns UK postcodes (and postcode outcodes) into
the ONS geography codes the rest of KindTech joins on. It wraps
[postcodes.io](https://postcodes.io/) — no API key required.
It's the layer that connects point-level address data to the common geography
types: any list of postcodes becomes a `geography_code` column — at LSOA, MSOA,
OA, LAD, ward, ICB or TTWA — that joins straight to boundaries
([`load_geodata`](geo.md)) and statistics ([`load_ons`](ons.md)).
## Functions
### `postcodes_to_geography()`
Map postcodes to a single geography level, ready to join.
```python
from uk_open_data import postcodes_to_geography
located = postcodes_to_geography(["SE13 7HX", "SE6 4RU"], geography_type="LSOA")
# postcode geography_code geography_name
# 0 SE13 7HX E01034394 Lewisham 040C
# 1 SE6 4RU E01003318 Lewisham 020B
```
Returns columns `postcode`, `geography_code`, `geography_name`. The
`geography_code` aligns with `geodata_to_properties()` and `load_ons()`, so the
result merges directly:
```python
import pandas as pd
from uk_open_data import postcodes_to_geography, load_geodata, load_ons, geodata_to_properties
# 1. Postcodes -> counts per LSOA
located = postcodes_to_geography(postcodes, "LSOA")
per_lsoa = located.groupby("geography_code").size().reset_index(name="count")
# 2. Population for per-capita, and boundaries for the map — same join key
pop = load_ons("population_lsoa", geography_type="LSOA", time="latest")
geo = pd.DataFrame(geodata_to_properties(load_geodata("LSOA"), "LSOA", 2021))
merged = geo.merge(per_lsoa, on="geography_code", how="left").merge(
pop, on="geography_code", how="left"
)
```
Supported `geography_type` values: `LSOA`, `MSOA`, `OA`, `LAD`, `WD`, `ICB`,
`TTWA` (string or [`GeographyType`](geo.md) enum). An unsupported level raises
`ValueError`.
### `lookup_postcodes()`
The full lookup — one row per postcode with every geography level at once.
```python
from uk_open_data import lookup_postcodes
df = lookup_postcodes(["SE13 7HX", "M1 1AE", "NOTAPC"])
```
Columns: `postcode`, `valid`, `lsoa_code`/`lsoa_name`, `msoa_code`/`msoa_name`,
`oa_code`, `lad_code`/`lad_name`, `ward_code`, `icb_code`, `ttwa_code`,
`latitude`, `longitude`.
!!! note "Invalid postcodes are flagged, not dropped"
Unrecognised postcodes return a row with `valid=False` and `None` codes, so
the output always lines up with the input. Filter with
`df[df["valid"]]` when you only want matches.
### `lookup_outcodes()`
Look up postcode **outcodes** — the prefix before the space (e.g. `SE13`). An
outcode spans many areas, so this returns the *list* of Local Authorities it
touches plus the outcode's geometric centroid.
```python
from uk_open_data import lookup_outcodes
lookup_outcodes(["SE13", "M1"])
# outcode valid admin_districts latitude longitude
# 0 SE13 True Greenwich, Lewisham 51.459641 -0.009665
```
Columns: `outcode`, `valid`, `admin_districts` (comma-separated LAD names),
`latitude`, `longitude`.
### `outcode_to_geography()`
Approximate an outcode to a single geography via its centroid.
```python
from uk_open_data import outcode_to_geography
outcode_to_geography(["SE13"], geography_type="LSOA")
# outcode geography_code geography_name
# 0 SE13 E01033327 Lewisham 041B
```
!!! warning "Outcode mapping is approximate"
An outcode covers many LSOAs/wards. This returns the geography *containing
the outcode's geometric centroid* — a rough stand-in, useful when your data
is only tagged by postcode prefix. For per-area analysis (e.g. counts
per capita by LSOA), prefer full postcodes via `postcodes_to_geography()`,
or split an outcode's records across its constituent areas weighted by
population.
## Looking up postcodes on this machine
The functions above send postcodes to postcodes.io. When the postcodes belong
to the people a charity helps, you may not want them to leave your machine.
The postcode table lets you look them up locally instead.
The table is one file of a few megabytes that maps every postcode in
England and Wales to its 2021 LSOA and local authority. It is built from the
ONS best-fit postcode lookup. This version of the package fetches the May 2026
edition, 2,409,013 postcodes in about 6 MB. Fetch it once:
```bash
uk-open-data postcodes download
```
or from Python with `download_postcode_table()`. The file is public and the
same for everyone, so fetching it says nothing about your data, and it is
checked against a SHA-256 before it is installed. After that, nothing below
uses the network:
```python
from uk_open_data.postcodes import (
district_to_local_authorities,
postcode_to_lsoa,
postcodes_to_local_authority,
postcodes_to_lsoa,
)
postcode_to_lsoa("se13 7vc") # an LSOA code, or None
postcodes_to_lsoa(["SE13 7VC", "M1 1VC"]) # one answer per postcode, in order
postcodes_to_local_authority(["SE13 7VC"]) # local authority codes, in order
district_to_local_authorities("SE13") # local authority codes, sorted
```
| Function | What it does |
| --- | --- |
| `download_postcode_table()` | Fetches and installs the table. Pass `url=` and `sha256=` to use a copy you host |
| `postcode_table_path()` | The installed table's path, or `None` |
| `postcode_table_info()` | Edition, source, coverage, size and the credits to show |
| `postcode_to_lsoa()`, `postcodes_to_lsoa()` | Postcode to 2021 LSOA code, or `None` when it is not in the table |
| `postcodes_to_local_authority()` | Postcode to local authority code, or `None` when it is not in the table |
| `district_to_local_authorities()` | The local authorities a postcode district reaches into |
| `build_postcode_table()` | Builds a table from the ONS lookup file. Used to publish a new edition |
The table lives in `~/.cache/uk-open-data`, or in the folder named by the
`UK_OPEN_DATA_DIR` environment variable. The old names, `~/.cache/kindtech`
and `KINDTECH_DATA_DIR`, still work. A server should fetch it when it is
built, not when a request arrives.
!!! note "Coverage and credits"
The table covers England and Wales. Scotland and Northern Ireland are left
out: neither has 2021 LSOAs, and Northern Ireland postcodes need a separate
licence for commercial use. When you publish something made with the table,
show the credits from `postcode_table_info()["attribution"]`: the ONS
source line, and the OS and Royal Mail copyright lines.
[Analyses](analyses.md) use the table on their own when one is installed.
## Design
`uk_open_data.postcodes` is a thin runtime wrapper — unlike the `geo` and `ons`
modules it ships no catalog and has no ingestion step, because postcodes.io
serves the lookup directly. Requests are batched (100 postcodes per call, the
postcodes.io limit) and results preserve input order. DataFrames come back in
whatever backend you have installed (pandas or polars), like the rest of
KindTech.
See [Data Sources](data-sources.md#postcodesio) for the underlying datasets,
licensing, and limits.
## Package FAQ
# Package FAQ
## Is this `uk_open_data.geo`, and can we keep developing more subpackages?
**Short answer:** `uk-open-data` is the package installed from PyPI, and
`uk_open_data` is the name it is imported by. It includes `uk_open_data.geo`,
`uk_open_data.ons`, `uk_open_data.postcodes`, and `uk_open_data.imd`. Each
subpackage has its own Python import path, but all share one package version
and release.
```bash
uv add uk-open-data
```
```python
from uk_open_data.geo import load_geodata
from uk_open_data.ons import load_ons
```
The package was called `kindtech` up to version 0.1. The `kindtech` project on
PyPI is kept for that name: installing or upgrading it installs the same
version of `uk-open-data`, and code that imports `kindtech` still works and
gives a deprecation warning. `kindtech.geo` is the same module as
`uk_open_data.geo`. Installing `uk-open-data` alone does not add the old import
name.
New modules can be added under `src/uk_open_data//` and included in future
`uk-open-data` releases. Because they remain inside the same distribution, they do
not need separate PyPI registrations. Add tests and API documentation alongside
each new module, and include any bundled data in the package configuration.
### Sources
- [API reference](../api/index.md): available modules and their imports.
- [Package configuration](https://github.com/KindTechUK/uk-open-data/blob/v0.1.0/pyproject.toml): one distribution name and version.
- [Released package tree](https://github.com/KindTechUK/uk-open-data/tree/v0.1.0/src/kindtech): subpackages included in 0.1.0.
Check the package configuration and tagged source tree when the package layout
changes or a new release adds modules.
_Created: 2026-09-20 · Updated: 2026-09-20 · Verified: 2026-09-20 · Scope/version: 0.1.0_
## Which projects on PyPI does a release publish?
**Short answer:** Two, from one tag. `uk-open-data` is the package.
[`kindtech`](https://pypi.org/project/kindtech/) is its old name: a small
distribution that depends on the same version of `uk-open-data` and holds the
`kindtech` import name.
Both use Trusted Publishing from the release workflow, so each project on PyPI
needs its own trusted publisher that names this repository, the workflow file
`release.yml` and the environment `pypi`. For `uk-open-data`, a pending
publisher creates the project on the first release. `kindtech` was created by
the 0.1.0 release and needs a publisher that names the repository as it is
called now.
To release, set the same version in `pyproject.toml` and in
`packaging/kindtech/pyproject.toml` (twice there: its own version and the
version of `uk-open-data` it depends on), complete the release checks, and push
the matching `v*` tag when the release is approved. The workflow checks that
the tag and both versions match, publishes `uk-open-data`, then `kindtech`.
### Sources
- [Release workflow](https://github.com/KindTechUK/uk-open-data/blob/main/.github/workflows/release.yml): the checks and the two publishing jobs.
- [The old name's package](https://github.com/KindTechUK/uk-open-data/tree/main/packaging/kindtech): what the `kindtech` distribution holds.
- [First release, 0.1.0](https://pypi.org/project/kindtech/0.1.0/): published as `kindtech`.
Recheck the two PyPI projects and their publishers before a release.
_Created: 2026-09-20 · Updated: 2026-11-19 · Verified: 2026-11-19 (builds and installs; no release has run yet) · Scope/version: 0.2_
# Blog
## Blog
# Blog
Welcome to the KindTech blog. Articles, tutorials, and updates about working with UK public data.
## Posts
- [**Introduction to KindTech**](introduction.md) - June 2025
An introduction to the KindTech package and how it can help you work with geographic and ONS data.
## How We Found the APIs Behind UK Public Data
# How We Found the APIs Behind UK Public Data
If you work with UK geographic or statistical data, you know the drill: browse
a portal, click download, unzip, load into your tool, realise you need a
different geography level, start over. None of it is scriptable.
We wanted to build a Python package that lets you write
`load_geodata(geography_type="LAD")` and get GeoJSON back. Or
`load_ons("NM_1_1", time="latest")` and get a DataFrame. No manual downloads,
no stale files.
The problem: neither the
[ONS Open Geography Portal](https://geoportal.statistics.gov.uk/) nor
[NOMIS](https://www.nomisweb.co.uk/) prominently documents a developer API.
Both turned out to have one hiding behind their web interfaces.
## The ONS Geoportal is just ArcGIS
The Open Geography Portal looks like a bespoke government website. Open
DevTools and you'll see every boundary dataset is served by an ArcGIS
FeatureServer. The URL pattern is straightforward once you know it:
```
https://services1.arcgis.com/ESMARspQHYMw9BZ9/arcgis/rest/services/
LAD_DEC_2024_UK_BGC/FeatureServer/0/query?where=1%3D1&outFields=*&f=geojson
```
No authentication. Public data. Standard ArcGIS REST API.
The harder problem was discovering *which* datasets exist. The portal's
service listing page is JS-rendered — scraping returns nothing. Appending
`?f=json` to the services URL gives you a machine-readable catalog of ~3,700
services. From there, parsing the service names extracts geography type, year,
month, coverage area, and resolution.
We ended up with 615 boundary datasets across 24 geography types, spanning
1921 to 2025.
## NOMIS has an API (we just used it wrong)
[NOMIS](https://www.nomisweb.co.uk/home/about.asp) — run by Durham University
for ONS since 1981 — does have
[API docs](https://www.nomisweb.co.uk/api/v01/help), but the website pushes
you toward the interactive query builder. The breakthrough was reading the
source of [nomisr](https://github.com/ropensci/nomisr), an R package by Evan
Odell ([JOSS, 2018](https://doi.org/10.21105/joss.00859)), which showed us the
key endpoints.
Our first ingestion fetched metadata for each of 1,615 datasets individually —
classic N+1 problem. When we looked closer at the bulk listing response
(`dataset/def.sdmx.json`), we found the source annotations were already
embedded in each dataset's `annotations` array. One request, ~6 seconds, done.
## The pattern
Both portals follow the same pattern: a user-facing website optimised for
manual browsing, backed by an API that works fine for programmatic access but
isn't the intended interface. The data is public and freely licensed
([OGL v3.0](https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/)),
the APIs are functional — they're just not advertised.
For the full technical details — endpoints, naming conventions, resolution
codes, catalog quirks, ingestion architecture, and 30+ reference links — see
the [Data Sources](../api/data-sources.md) reference.
## Introduction
# Introduction to KindTech
## Posted June 2025
Welcome to KindTech, a Python package designed to simplify working with UK geographic boundaries and Office for National Statistics data.
## What is KindTech?
KindTech is a lightweight Python library for accessing UK public data. It wraps the ONS ArcGIS Geoportal (geographic boundaries) and the NOMIS API (statistics) with a clean, functional API.
## Key Features
- **Simple API** — flat functions, no classes to instantiate
- **Bring your own DataFrame** — works with pandas or polars via narwhals, no backend lock-in
- **Lightweight** — core package is ~500KB (requests + narwhals), no pandas/numpy required
- **Bundled catalogs** — browse available datasets offline, data is fetched live from source
## Getting Started
Install [uk-open-data from PyPI](https://pypi.org/project/uk-open-data/):
```bash
uv add uk-open-data
```
```python
from uk_open_data.geo import load_geodata
from uk_open_data.ons import load_ons, list_tables
# Load Local Authority District boundaries (GeoJSON)
boundaries = load_geodata(geography_type="LAD", coverage="UK")
# Load ONS statistics
df = load_ons("NM_1_1", geography="TYPE480", time="latest")
# Browse available datasets
tables = list_tables(name="population")
```
## Next Steps
Check out the [API documentation](../api/index.md) to learn more about the available functions.