From 22fc48ba7803868663293d474ee8750eff08046f Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Tue, 1 Dec 2026 15:53:00 +0000 Subject: [PATCH 1/3] feat(analyses): police recorded crime as needs, counted in offences A new loader, uk_open_data.crime.load_crime(), reads the latest quarter's police recorded crime for every community safety partnership in England and Wales. The source is ONS's "Crime in England and Wales: Police Force Area data tables", where the figures by partnership moved when ONS discontinued their own dataset in 2024. - It finds the latest edition through the JSON the ONS website gives for each page. - It returns one row per partnership, with one column per kind of offence. - Each force's total and its "Unassigned" offences are left out. - A partnership whose row ONS marks with a note has missing figures, not the published few. ONS marks five Kent partnerships so today, because their crimes are recorded under "Unassigned Kent". Need against reach, provision gap and access and distance can now take two needs, for England and Wales, as agreed on 1 December: - recorded_crime: offences excluding fraud; - violence_against_the_person. They count offences, so results say "offences recorded", and the caveat says offences are not people or victims. The figures are for partnerships, so they are shared out to councils by residents (#218). Most partnerships are one council. A council whose partnership has no figure is left out and named. The working's sentence on sharing now rounds to whole units of what the need counts, such as offences or children, not "whole people". The datasets test keeps each need's invented figures by the need's own kind of area. Signed-off-by: billlyzhaoyh Github-Issue: #210 --- docs/api/analyses.md | 20 ++- docs/api/crime.md | 80 ++++++++++ docs/api/data-sources.md | 21 +++ docs/api/datasets.md | 1 + docs/api/index.md | 11 ++ mkdocs.yml | 1 + src/uk_open_data/analyses/_answers.py | 3 + src/uk_open_data/analyses/_need.py | 72 ++++++++- src/uk_open_data/analyses/datasets.py | 11 ++ src/uk_open_data/analyses/sources.py | 14 ++ src/uk_open_data/crime/__init__.py | 10 ++ src/uk_open_data/crime/api.py | 206 +++++++++++++++++++++++++ tests/test_analysis_need_reach.py | 5 + tests/test_analysis_provision_gap.py | 10 +- tests/test_crime_api.py | 212 ++++++++++++++++++++++++++ tests/test_crime_needs.py | 200 ++++++++++++++++++++++++ tests/test_datasets.py | 30 +++- tests/test_live_sources.py | 16 ++ 18 files changed, 912 insertions(+), 11 deletions(-) create mode 100644 docs/api/crime.md create mode 100644 src/uk_open_data/crime/__init__.py create mode 100644 src/uk_open_data/crime/api.py create mode 100644 tests/test_crime_api.py create mode 100644 tests/test_crime_needs.py diff --git a/docs/api/analyses.md b/docs/api/analyses.md index 2160d9f..2dfac92 100644 --- a/docs/api/analyses.md +++ b/docs/api/analyses.md @@ -676,7 +676,8 @@ The analysis loads a count of **people in need** in every local authority, from [Nomis](ons.md), from [MHCLG's homelessness tables](homelessness.md), from [DESNZ's fuel poverty statistics](fuel-poverty.md), from [DWP's children in low income families](low-income.md) or from -[UKHSA's childhood vaccinations](vaccinations.md), divides +[UKHSA's childhood vaccinations](vaccinations.md) or from +[ONS's police recorded crime](crime.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 @@ -698,6 +699,8 @@ Choose the need with the `need` option: | `"children_in_low_income_families_after_housing_costs"` | The same children, with income counted after housing costs, so more children count where housing costs more, from DWP | | `"children_without_mmr1_by_2"` | Children who turned 2 in the latest year, April to March, without a first dose of the measles, mumps and rubella (MMR) vaccine, England only, from UKHSA. Published for upper-tier councils and shared out to councils | | `"children_without_mmr2_by_5"` | Children who turned 5 in the latest year without both doses of MMR, England only, from UKHSA. Published for upper-tier councils and shared out to councils | +| `"recorded_crime"` | Offences the police recorded in the latest year, excluding fraud, England and Wales, from ONS. Published for community safety partnerships and shared out to councils | +| `"violence_against_the_person"` | Offences of violence against the person the police recorded in the latest year, England and Wales, from ONS. Published for community safety partnerships and shared out to councils | | `{"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 @@ -758,6 +761,18 @@ out as one area, by residents. UKHSA says the children recorded are uncertain where people move often, as in London, so coverage there may be underestimated, and the children not vaccinated overcounted. +The two crime needs count **offences**, not people or victims: one person can +be the victim of many offences, and many offences have no one victim. So the +result says "offences recorded" and sets the people you helped per 100 +offences. Read that as more or less reach between places, not a share of +anyone. An offence is counted where it was recorded, and forces record crime +in different ways. They are the latest year ONS has published, and the result +cites it, such as "year ending June 2026". ONS publishes them for community +safety partnerships, most of them one council, so they are shared out to +councils, as below. Offences the police could not place in a partnership are +left out, and so is a partnership whose figures ONS marks as incomplete, such +as five in Kent today: the warning names them and their councils. + **Need figures for bigger areas.** Some figures are published for areas bigger than a council: upper-tier councils (counties), community safety partnerships or police force areas. A need from one of these is shared out to the councils @@ -766,7 +781,8 @@ in it, so the analyses still compare councils. This was decided in what it costs and when to think again. - Each council takes its share of the area's count by its share of the area's - residents at the 2021 Census, in whole people, from + residents at the 2021 Census, rounded to whole people, households, + children or offences, as the need counts them, from [`local_authority_lookup`](areas.md#a-councils-county-partnership-and-police-force-area). - A council made of whole areas takes their figures as published. A unitary council is a whole upper-tier council, and Buckinghamshire is four whole diff --git a/docs/api/crime.md b/docs/api/crime.md new file mode 100644 index 0000000..791de1f --- /dev/null +++ b/docs/api/crime.md @@ -0,0 +1,80 @@ +# Police recorded crime + +The `uk_open_data.crime` module loads police recorded crime for every +community safety partnership in England and Wales, from the Office for +National Statistics' +[Crime in England and Wales: Police Force Area data tables](https://www.ons.gov.uk/peoplepopulationandcommunity/crimeandjustice/datasets/policeforceareadatatables). +It reads the latest edition, for the year to the end of the latest quarter. + +## `load_crime()` + +```python +from uk_open_data.crime import load_crime + +partnerships = load_crime() +partnerships[["geography_name", "total_recorded_crime", "robbery"]] +``` + +It returns one row per community safety partnership, 314 in all, as a pandas +or polars table, whichever you have: + +| Column | What it holds | +|---|---| +| `geography_code` | The partnership's code: `E22` in England, `W14` in Wales | +| `geography_name` | The partnership's name | +| `police_force_area` | The police force it is in | +| `year` | The year the figures are for, such as "year ending June 2026" | +| `total_recorded_crime` | Every offence the police recorded, excluding fraud | +| `violence_against_the_person`, `sexual_offences`, `robbery`, `theft_offences`, `shoplifting`, ... | The offences of each kind ONS gives, one column each, named from its heading | + +A **community safety partnership** is a council, or a few councils, working +with the police on crime. Most are one council. `uk_open_data.areas` gives +the councils in each, with their share of its residents: +[`local_authority_lookup("community_safety_partnership")`](areas.md#a-councils-county-partnership-and-police-force-area). + +The figures count **offences** the police recorded, not people or victims. +One person can be the victim of many offences, and many offences have no one +victim. An offence is counted where it was recorded. Forces record crime in +different ways, so a difference between forces may be one of recording. + +**Offences left out:** + +- Offences the police could not place in a partnership, which ONS lists as + "Unassigned" under each force. They are about 3% of offences across England + and Wales, more in some forces in some quarters. +- **A partnership whose row ONS marks with a note**, such as "Kent [note 5]", + has missing figures (null), never the published number. ONS marks a row so + when its figures are incomplete: in the year ending June 2026, ONS says the + crimes of five Kent partnerships (Dartford and Gravesham, Maidstone, Medway, + Tonbridge and Malling, and Tunbridge Wells) are recorded under "Unassigned + Kent". Their published figures are a few dozen offences each. + +The [analyses](analyses.md#need-against-reach) take two of these counts as +needs, `recorded_crime` and `violence_against_the_person`, for England and +Wales, and share each partnership's figure out to its councils. + +The figures are fetched once and held for the rest of the session. +`clear_cache()` forgets them, to fetch a new edition. + +## How the latest edition is found + +ONS publishes a new edition each quarter. The ONS website gives each page as +JSON at the page's address followed by `/data`. The loader reads the +dataset's page that way, takes the first edition it lists, which is the +latest, reads that edition's page for its name and its spreadsheet, and reads +the table of offences by partnership in it. If the dataset lists no edition, +or the table or a column the loader reads has changed, it fails with a +`ValueError` naming ONS's tables. A weekly check fetches the latest edition +to make sure it still reads. + +## The source and how to credit it + +| | | +|---|---| +| Publisher | Office for National Statistics, from Home Office police recorded crime | +| Coverage | England and Wales, quarterly, for the latest year | +| Status | Official statistics, not accredited official statistics | +| Licence | [Open Government Licence v3.0](https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/) | +| Credit | Source: Office for National Statistics, Crime in England and Wales: Police Force Area data tables, year ending June 2026. Contains public sector information licensed under the Open Government Licence v3.0. | + +`list_datasets()` lists it as `ons-police-recorded-crime`. diff --git a/docs/api/data-sources.md b/docs/api/data-sources.md index b879bad..dfa884d 100644 --- a/docs/api/data-sources.md +++ b/docs/api/data-sources.md @@ -625,6 +625,27 @@ names its groups' documents, and the release page lists its files. --- +## ONS police recorded crime + +ONS publishes police recorded crime by community safety partnership in its +[Crime in England and Wales: Police Force Area data tables](https://www.ons.gov.uk/peoplepopulationandcommunity/crimeandjustice/datasets/policeforceareadatatables), +a new edition each quarter. Its dataset of figures by partnership alone was +discontinued in October 2024, when they moved here. The ONS website gives +each page as JSON at the page's address followed by `/data`. + +| Item | Value | +|---|---| +| Edition read | The first in the dataset page's `datasets` list, which is the latest, such as `…/policeforceareadatatables/yearendingjune2026`. Its own `/data` gives its name, in `description.edition`, and its files, in `downloads` | +| File read | The edition's `.xlsx` file, at `https://www.ons.gov.uk/file?uri=/` | +| Table read | `Table C2`, the number of offences by partnership. `Table C4` gives rates and `Table C5` the year before | +| Header | The row whose first cell is "Police Force Area code", below the title and notes. Headings hold line breaks and marks such as "(excluding fraud)", which the loader takes out | +| Columns | The force's code and name, the partnership's code and name, the council's code and name (or "Combined Local Authorities"), then one column per kind of offence | +| Rows | Each force's total (no partnership code), its partnerships (`E22` and `W14`), and its "Unassigned" offences (no code). The loader keeps the partnerships | +| Marked rows | A partnership ONS marks with a note, on its force's name, has incomplete figures. In the year ending June 2026 these are five Kent partnerships, marked "Kent [note 5]", whose crimes are recorded under "Unassigned Kent". The note's number changes between editions. The loader gives them no figures | +| Codes | The partnerships' codes match `local_authority_lookup("community_safety_partnership")`: all 314 in the year ending June 2026 | + +--- + ## Dataset Aliases Instead of remembering NOMIS dataset IDs like `NM_2002_1`, you can use diff --git a/docs/api/datasets.md b/docs/api/datasets.md index 04910a0..de6ac00 100644 --- a/docs/api/datasets.md +++ b/docs/api/datasets.md @@ -18,6 +18,7 @@ Open Geography Portal. | [Sub-regional fuel poverty statistics](https://www.gov.uk/government/statistics/sub-regional-fuel-poverty-data-2026-2024-data) | `desnz-fuel-poverty` | Department for Energy Security and Net Zero | [people](https://www.data.gov.uk/collections/people) | Local authority districts (2025) | England | Open Government Licence v3.0 | `need-reach`, `provision-gap`, `access-distance` | Yes | | [Children in low income families: local area statistics](https://www.gov.uk/government/collections/children-in-low-income-families-local-area-statistics) | `dwp-children-low-income` | Department for Work and Pensions | [people](https://www.data.gov.uk/collections/people) | Local authority districts (2023) | England, Wales, Scotland and Northern Ireland | Open Government Licence v3.0 | `need-reach`, `provision-gap`, `access-distance` | Yes | | [Childhood vaccination coverage statistics (COVER programme)](https://www.gov.uk/government/collections/cover-of-vaccination-evaluated-rapidly-cover-programme-statistics) | `ukhsa-childhood-vaccinations` | UK Health Security Agency | [people](https://www.data.gov.uk/collections/people) | Counties and unitary authorities (2023) | England | Open Government Licence v3.0 | `need-reach`, `provision-gap`, `access-distance` | Yes | +| [Crime in England and Wales: Police Force Area data tables](https://www.ons.gov.uk/peoplepopulationandcommunity/crimeandjustice/datasets/policeforceareadatatables) | `ons-police-recorded-crime` | Office for National Statistics, from Home Office police recorded crime | [people](https://www.data.gov.uk/collections/people) | Community safety partnerships | England and Wales | Open Government Licence v3.0 | `need-reach`, `provision-gap`, `access-distance` | Yes | | [TS021 - Ethnic group (NM_2041_1)](https://www.nomisweb.co.uk/api/v01/dataset/NM_2041_1.def.sdmx.json) | `nomis-nm_2041_1` | Office for National Statistics, through Nomis | [people](https://www.data.gov.uk/collections/people) | Local authority districts (2023) | England and Wales | Open Government Licence v3.0 | `who-we-miss` | Yes | | [postcodes.io](https://postcodes.io) | `postcodes-io` | postcodes.io, built on the ONS Postcode Directory | [land-and-property](https://www.data.gov.uk/collections/land-and-property) | Postcodes | England, Wales, Scotland and Northern Ireland | Open Government Licence v3.0 | `reach-deprivation`, `reach-connectivity`, `who-we-miss`, `need-reach`, `provision-gap`, `access-distance` | No | | [Postcode to OA (2021) to LSOA to MSOA to LAD Best Fit Lookup in the UK](https://geoportal.statistics.gov.uk) | `ons-postcode-lookup` | Office for National Statistics | [land-and-property](https://www.data.gov.uk/collections/land-and-property) | Postcodes | England and Wales | Open Government Licence v3.0 | `reach-deprivation`, `reach-connectivity`, `who-we-miss`, `need-reach`, `provision-gap`, `access-distance` | Yes | diff --git a/docs/api/index.md b/docs/api/index.md index 4ba32e6..111cbd5 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -127,6 +127,17 @@ from uk_open_data.vaccinations import load_vaccinations table = load_vaccinations() # a row per council, age and vaccine ``` +### [Police recorded crime](crime.md) — `uk_open_data.crime` + +Load the latest year of police recorded crime for every community safety +partnership in England and Wales, from ONS: the offences of each kind. + +```python +from uk_open_data.crime import load_crime + +partnerships = load_crime() # join on `geography_code` +``` + ### [Council codes and areas](areas.md) — `uk_open_data.areas` Bring a council code from any year to today's, so figures from sources made in diff --git a/mkdocs.yml b/mkdocs.yml index df4b9f7..18b9906 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -105,6 +105,7 @@ nav: - Education statistics: api/education.md - Children in low income families: api/low-income.md - Childhood vaccinations: api/vaccinations.md + - Police recorded crime: api/crime.md - Council codes and areas: api/areas.md - Analyses: api/analyses.md - Command Line: api/cli.md diff --git a/src/uk_open_data/analyses/_answers.py b/src/uk_open_data/analyses/_answers.py index d0f7ceb..d718c66 100644 --- a/src/uk_open_data/analyses/_answers.py +++ b/src/uk_open_data/analyses/_answers.py @@ -118,6 +118,9 @@ def sentence_case(text: str) -> str: CHILDREN_WITHOUT_MMR2 = _counted_in( "children without both MMR doses", "children", "child" ) +# A need counted in offences, from police recorded crime. Offences are not +# people: one person can be the victim of many. +OFFENCES_RECORDED = _counted_in("offences recorded", "offences", "offence") def shown_first(figures: Sequence[Figure], wanted: Sequence[str]) -> tuple[str, ...]: diff --git a/src/uk_open_data/analyses/_need.py b/src/uk_open_data/analyses/_need.py index 18f0624..0ac9d50 100644 --- a/src/uk_open_data/analyses/_need.py +++ b/src/uk_open_data/analyses/_need.py @@ -34,6 +34,7 @@ CHILDREN_WITHOUT_MMR2, HOUSEHOLDS_IN_NEED, IN_NEED, + OFFENCES_RECORDED, NeedWords, names, ) @@ -59,6 +60,7 @@ KEPT_COPY_USED, MHCLG_HOMELESSNESS, ONS_LOCAL_AUTHORITY_LOOKUPS, + ONS_POLICE_RECORDED_CRIME, UKHSA_CHILDHOOD_VACCINATIONS, kept_copy, nomis_table, @@ -72,6 +74,7 @@ retired, todays_codes, ) +from uk_open_data.crime import api as crime from uk_open_data.fuel_poverty import api as fuel_poverty from uk_open_data.homelessness import api as homelessness from uk_open_data.low_income import api as low_income @@ -459,6 +462,58 @@ def load() -> Any: ) +_OFFENCES = ( + "The figures count offences the police recorded in one year, not people " + "or victims: one person can be the victim of many offences, and many " + "offences have no one victim. An offence is counted where it was " + "recorded, not where its victim lives, and forces record crime in " + "different ways. Fraud is not included. Offences the police could not " + "place in a partnership, which ONS lists as 'Unassigned', are left out, " + "so some forces' partnerships are undercounted, and a partnership whose " + "figures ONS marks as incomplete is left out and named. ONS publishes " + "the figures for community safety partnerships, most of them one council; " + "a partnership of several councils is shared out among them by their " + "residents at the 2021 Census. Setting the people you help, or what you " + "provide, against offences shows where you do more or less between " + "places, not a share of anyone." +) + + +def _offences(measure_id: str, label: str, column: str) -> Measure: + """Describe the offences of one kind the police recorded as a need. + + ONS publishes them for community safety partnerships, so they are shared + out to councils. + + Args: + measure_id: The name the need option takes. + label: What is counted, in a few words. + column: The column of :func:`uk_open_data.crime.load_crime` it reads. + """ + return council_measure( + measure_id=measure_id, + label=label, + source=ONS_POLICE_RECORDED_CRIME, + load=crime.load_crime, + column=column, + period="year", + origin="ONS", + nations=("E", "W"), + reason=( + "Police forces record every crime reported to them, and ONS " + "publishes the count for every community safety partnership each " + "quarter." + ), + caveat=_OFFENCES, + advice=( + "ONS's tables may have moved or changed. They are listed at " + f"{crime.DATASET_PAGE}." + ), + words=OFFENCES_RECORDED, + area="community_safety_partnership", + ) + + MEASURES = { measure.id: measure for measure in ( @@ -578,6 +633,16 @@ def load() -> Any: "who turned 5 during the year without both doses", CHILDREN_WITHOUT_MMR2, ), + _offences( + "recorded_crime", + "Crimes recorded by the police, excluding fraud", + "total_recorded_crime", + ), + _offences( + "violence_against_the_person", + "Violence against the person recorded by the police", + "violence_against_the_person", + ), ) } @@ -805,7 +870,8 @@ def _shared_to_councils(figures: Figures, measure: Measure) -> tuple[Figures, _S """Share figures for bigger areas out to the councils in them, by residents. Each council takes the figure of each area it lies in, times its share of - that area's residents at the 2021 Census, in whole people. An area the + that area's residents at the 2021 Census, rounded to a whole number of + what the need counts, such as people or offences. An area the source counts in another's figures (:attr:`Measure.included_in`), with no figure of its own, shares that figure as if the two were one area. A council made of whole areas takes their figures as published. A council @@ -931,7 +997,8 @@ def _note_shared(trail: Trail, measure: Measure, shared: _Shared) -> None: f"The need figures are for {plural(shared.areas, one)}. Each " f"council took its share of the figure for each {one} it lies " f"in, by its share of that {one}'s residents at the 2021 " - f"Census, in whole people.{included}{published}{estimated}" + f"Census, in whole {measure.words.unit}." + f"{included}{published}{estimated}" ), ) ) @@ -1316,6 +1383,7 @@ def clear_need_cache() -> None: fuel_poverty.clear_cache() low_income.clear_cache() vaccinations.clear_cache() + crime.clear_cache() # --- the area compared ----------------------------------------------------- diff --git a/src/uk_open_data/analyses/datasets.py b/src/uk_open_data/analyses/datasets.py index c199276..1e6f383 100644 --- a/src/uk_open_data/analyses/datasets.py +++ b/src/uk_open_data/analyses/datasets.py @@ -35,6 +35,7 @@ NIMDM_2017, ONS_CODE_HISTORY, ONS_LOCAL_AUTHORITY_LOOKUPS, + ONS_POLICE_RECORDED_CRIME, POSTCODES_IO, SIMD_2020, UK_COMPOSITE_IMD, @@ -305,6 +306,16 @@ def _kept_for_analyses(source: Source) -> tuple[Callable[[], Path], ...]: _NEED, downloads=_kept_for_analyses(UKHSA_CHILDHOOD_VACCINATIONS), ), + # Published for community safety partnerships. The needs share the + # figures out to councils. + Dataset( + ONS_POLICE_RECORDED_CRIME, + "people", + "Community safety partnerships", + ENGLAND_AND_WALES, + _NEED, + downloads=_kept_for_analyses(ONS_POLICE_RECORDED_CRIME), + ), Dataset( _BY_ETHNIC_GROUP, "people", diff --git a/src/uk_open_data/analyses/sources.py b/src/uk_open_data/analyses/sources.py index 34f108a..f233f07 100644 --- a/src/uk_open_data/analyses/sources.py +++ b/src/uk_open_data/analyses/sources.py @@ -16,6 +16,7 @@ SOURCE_PAGE, ) from uk_open_data.connectivity.api import CONNECTIVITY_PAGE +from uk_open_data.crime.api import DATASET_PAGE as CRIME_PAGE from uk_open_data.education.api import API_DOCS from uk_open_data.fuel_poverty.api import RELEASE_PAGE as FUEL_POVERTY_PAGE from uk_open_data.homelessness.api import LIVE_TABLES_PAGE @@ -289,6 +290,19 @@ def nomis_table(dataset_id: str, used_for: str) -> Source: ), ) +ONS_POLICE_RECORDED_CRIME = Source( + id="ons-police-recorded-crime", + name="Crime in England and Wales: Police Force Area data tables", + publisher="Office for National Statistics, from Home Office police recorded crime", + url=CRIME_PAGE, + licence=OGL, + edition="Quarterly, for the latest year. A result names the year it used", + used_for=( + "Offences recorded by the police, of each kind, in each community safety " + "partnership." + ), +) + ONS_CODE_HISTORY = Source( id="ons-code-history", diff --git a/src/uk_open_data/crime/__init__.py b/src/uk_open_data/crime/__init__.py new file mode 100644 index 0000000..41c1555 --- /dev/null +++ b/src/uk_open_data/crime/__init__.py @@ -0,0 +1,10 @@ +""" +KindTech crime package + +Loads police recorded crime for each community safety partnership in England +and Wales, as ONS publishes it each quarter: the offences of each kind. +""" + +from .api import clear_cache, load_crime + +__all__ = ["clear_cache", "load_crime"] diff --git a/src/uk_open_data/crime/api.py b/src/uk_open_data/crime/api.py new file mode 100644 index 0000000..57f3139 --- /dev/null +++ b/src/uk_open_data/crime/api.py @@ -0,0 +1,206 @@ +""" +Police recorded crime by community safety partnership + +Loads the latest year of police recorded crime for every community safety +partnership in England and Wales, as the Office for National Statistics +publishes it in its "Crime in England and Wales: Police Force Area data +tables": the number of offences of each kind. + + >>> from uk_open_data.crime import load_crime + >>> partnerships = load_crime() + >>> partnerships[["geography_name", "total_recorded_crime"]] + +A community safety partnership is a council, or a few councils, working with +the police on crime. Most are one council. The figures count offences the +police recorded, not victims, and leave out fraud. Offences the police could +not place in a partnership, which ONS lists as "Unassigned", are left out. + +Where ONS marks a partnership's row with a note, its figures are incomplete: +in the year ending June 2026, ONS says the crimes of five Kent partnerships are +recorded under "Unassigned Kent". Such a partnership's figures are missing +(null), never the published number. + +ONS publishes a new edition each quarter, so the loader finds the latest +through the JSON the ONS website gives for each page. + +Published under the Open Government Licence v3.0: +https://www.ons.gov.uk/peoplepopulationandcommunity/crimeandjustice/datasets/policeforceareadatatables +""" + +import re +from functools import lru_cache +from typing import Any + +import narwhals.stable.v2 as nw + +from uk_open_data import _caches, _http +from uk_open_data._frames import ( + dicts_to_frame, + number_or_none, + plain_heading, + read_spreadsheet_rows, + text_or_blank, +) + +ONS_WEBSITE = "https://www.ons.gov.uk" +DATASET_PAGE = ( + f"{ONS_WEBSITE}/peoplepopulationandcommunity/crimeandjustice/datasets/" + "policeforceareadatatables" +) +# The ONS website gives each page as JSON at this address under it. +JSON = "/data" +SPREADSHEET = ".xlsx" +# The table of offences by partnership, under a title and notes. Its header +# row starts with this. +SHEET = "Table C2" +HEADER = "Police Force Area code" +FORCE = "Police Force Area name" +CODE = "Community Safety Partnership code" +NAME = "Community Safety Partnership name" +# The last column before the offences. +BEFORE_OFFENCES = "Local Authority name" +# Partnerships' codes in England and Wales. Each force's total, and its +# "Unassigned" row, have none. +PARTNERSHIPS = ("E22", "W14") +# A mark, such as "[note 5]", on a partnership's row. +_MARK = re.compile(r"\[[^\]]*\]") + + +def load_crime() -> Any: + """Load the latest year's police recorded crime in each partnership. + + The figures are fetched once and held in memory for the rest of the + session: :func:`clear_cache` forgets them. + + Returns: + A pandas or polars DataFrame, whichever is installed, with one row per + community safety partnership in England and Wales: + ``geography_code``, ``geography_name``, ``police_force_area``, + ``year`` (such as "year ending June 2026"), then one column per kind + of offence, named from ONS's heading: ``total_recorded_crime`` (which + leaves out fraud), ``violence_against_the_person``, ``robbery``, + ``shoplifting`` and the rest. A figure is missing (null) where ONS + gives none, or marks the partnership's figures as incomplete. + + Raises: + ValueError: If the dataset lists no edition, the edition has no + spreadsheet, or the table or a column this reads has moved or + changed. + requests.RequestException: If a page or the file cannot be fetched. + """ + # A copy, so a caller that changes its table does not change the next one. + return _latest().clone().to_native() + + +@_caches.register +def clear_cache() -> None: + """Forget the figures fetched earlier in this session, to fetch them again.""" + _latest.cache_clear() + + +@lru_cache(maxsize=1) +def _latest() -> nw.DataFrame: + """Fetch the latest year's figures, once until the cache is cleared.""" + year, url = _latest_file() + partnerships = _read_partnerships(_http.get(url).content, year) + return nw.from_native(dicts_to_frame(partnerships), eager_only=True) + + +def _latest_file() -> tuple[str, str]: + """Find the latest edition's name and the address of its spreadsheet.""" + editions = _json(DATASET_PAGE).get("datasets") + uri = editions[0].get("uri") if isinstance(editions, list) and editions else None + if not isinstance(uri, str): + raise ValueError(_changed(f"{DATASET_PAGE} lists no edition")) + edition = _json(f"{ONS_WEBSITE}{uri}") + year = str(edition.get("description", {}).get("edition") or "") + files = [ + name + for download in edition.get("downloads") or [] + if isinstance(download, dict) + and (name := str(download.get("file") or "")).lower().endswith(SPREADSHEET) + ] + if not year or not files: + raise ValueError(_changed(f"the edition at {uri} has no spreadsheet")) + return year, f"{ONS_WEBSITE}/file?uri={uri}/{files[0]}" + + +def _json(page: str) -> dict[str, Any]: + """A page of the ONS website, as the JSON the website gives for it.""" + described = _http.get(f"{page}{JSON}").json() + return described if isinstance(described, dict) else {} + + +def _read_partnerships(content: bytes, year: str) -> list[dict[str, Any]]: + """Read each partnership's offences from the table.""" + try: + rows = read_spreadsheet_rows(content, SHEET, _is_header) + except ValueError as error: + raise ValueError(_changed(f"'{SHEET}' could not be found")) from error + headings = { + plain_heading(heading): heading for heading in (rows[0] if rows else {}) + } + for heading in (FORCE, CODE, NAME, BEFORE_OFFENCES): + if heading not in headings: + raise ValueError(_changed(f"'{SHEET}' has no column '{heading}'")) + plain = list(headings) + offences = { + _column(heading): headings[heading] + for heading in plain[plain.index(BEFORE_OFFENCES) + 1 :] + } + partnerships = [ + _partnership(row, headings, offences, year) + for row in rows + if text_or_blank(row[headings[CODE]]).startswith(PARTNERSHIPS) + ] + if not partnerships: + raise ValueError(_changed(f"'{SHEET}' lists no partnership")) + return partnerships + + +def _partnership( + row: dict[str, Any], + headings: dict[str, str], + offences: dict[str, str], + year: str, +) -> dict[str, Any]: + """One partnership's code, name and offences, missing where ONS marks them.""" + force = text_or_blank(row[headings[FORCE]]) + name = text_or_blank(row[headings[NAME]]) + marked = bool(_MARK.search(force) or _MARK.search(name)) + return { + "geography_code": text_or_blank(row[headings[CODE]]), + "geography_name": _unmarked(name), + "police_force_area": _unmarked(force), + "year": year, + } | { + column: None if marked else number_or_none(row[heading]) + for column, heading in offences.items() + } + + +def _unmarked(text: str) -> str: + """A name without its marks, such as "Kent [note 5]" for Kent.""" + return " ".join(_MARK.sub("", text).split()) + + +def _is_header(cells: list[Any]) -> bool: + """Whether a row is the table's header, whatever marks its first cell has.""" + return bool(cells) and plain_heading(text_or_blank(cells[0])) == HEADER + + +def _column(heading: str) -> str: + """The column an offence becomes, from its heading without marks. + + Example: "Violence against the person" becomes + ``violence_against_the_person``. + """ + return re.sub(r"[^a-z0-9]+", "_", heading.lower()).strip("_") + + +def _changed(what: str) -> str: + """Say that ONS's tables have changed, and what was found.""" + return ( + "ONS's police recorded crime tables could not be read: " + f"{what}. They may have moved or changed." + ) diff --git a/tests/test_analysis_need_reach.py b/tests/test_analysis_need_reach.py index e3a0280..1ec9b15 100644 --- a/tests/test_analysis_need_reach.py +++ b/tests/test_analysis_need_reach.py @@ -495,6 +495,11 @@ def test_built_in_needs_can_be_picked_from_a_list(): "children_without_mmr2_by_5", "Children without a second dose of MMR vaccine by age 5", ), + ("recorded_crime", "Crimes recorded by the police, excluding fraud"), + ( + "violence_against_the_person", + "Violence against the person recorded by the police", + ), ] diff --git a/tests/test_analysis_provision_gap.py b/tests/test_analysis_provision_gap.py index 65a0af0..de24f12 100644 --- a/tests/test_analysis_provision_gap.py +++ b/tests/test_analysis_provision_gap.py @@ -149,6 +149,8 @@ def test_needs_can_be_picked_from_a_list(): "children_in_low_income_families_after_housing_costs", "children_without_mmr1_by_2", "children_without_mmr2_by_5", + "recorded_crime", + "violence_against_the_person", ] @@ -217,9 +219,11 @@ def test_need_must_be_chosen(nomis): "temporary accommodation; Households in fuel poverty; Children under 16 " "in low income families, before housing costs; Children under 16 in " "low income families, after housing costs; Children without a first " - "dose of MMR vaccine by age 2; or Children without a second dose of MMR " - "vaccine by age 5. The places listed depend on who your provision is " - "for, so the analysis does not choose for you." + "dose of MMR vaccine by age 2; Children without a second dose of MMR " + "vaccine by age 5; Crimes recorded by the police, excluding fraud; or " + "Violence against the person recorded by the police. The places listed " + "depend on who your provision is for, so the analysis does not choose " + "for you." ) assert not [row["Area"] for row in SPREAD if row["Area"] in message] assert nomis.asked == [] diff --git a/tests/test_crime_api.py b/tests/test_crime_api.py new file mode 100644 index 0000000..f02c4c9 --- /dev/null +++ b/tests/test_crime_api.py @@ -0,0 +1,212 @@ +"""Tests for the police recorded crime loader.""" + +from typing import Any +from unittest import mock + +import narwhals as nw +import pytest +from need_fakes import serve_gov_uk +from spreadsheets import ods + +from uk_open_data.crime import api, load_crime + +EDITION = ( + "/peoplepopulationandcommunity/crimeandjustice/datasets/" + "policeforceareadatatables/yearendingjune2026" +) +OLDER = ( + "/peoplepopulationandcommunity/crimeandjustice/datasets/" + "policeforceareadatatables/yearendingmarch2026" +) +DATASET_JSON = f"{api.DATASET_PAGE}/data" +EDITION_JSON = f"https://www.ons.gov.uk{EDITION}/data" +FILE = f"https://www.ons.gov.uk/file?uri={EDITION}/pfatablesyejune2026.xlsx" +TITLE = [ + ["Table C2: Number of police recorded crimes by Community Safety Partnership"], + ["This worksheet contains one table. [x] indicates data are unavailable."], + ["Source: Police recorded crime from the Home Office"], +] +HEADER = [ + "Police Force\nArea code", + "Police Force\nArea name", + "Community Safety\nPartnership code", + "Community Safety\nPartnership name", + "Local Authority code", + "Local Authority name", + "Total recorded crime\n (excluding fraud)", + "Violence against the person", + "Robbery", +] +# Invented offences, laid out as ONS lays them out: a force's total, its +# partnerships, and the offences it could not place. Medway's row is marked, +# as ONS marks partnerships whose crimes it records as "Unassigned". +FORCE_TOTAL = [ + "E23000001", + "Metropolitan Police", + "", + "", + "", + "", + 9000.0, + 3000.0, + 400.0, +] +LEWISHAM = [ + "E23000001", + "Metropolitan Police", + "E22000208", + "Lewisham", + "E09000023", + "Lewisham", + 3000.0, + 1000.0, + 150.0, +] +UNASSIGNED = [ + "E23000001", + "Metropolitan Police", + "", + "Unassigned Metropolitan Police", + "", + "", + 120.0, + 40.0, + 3.0, +] +CARDIFF = [ + "W15000003", + "South Wales", + "W14000015", + "Cardiff", + "W06000015", + "Cardiff", + 3600.0, + 1100.0, + 30.0, +] +MEDWAY = [ + "E23000032", + "Kent [note 5]", + "E22000143", + "Medway", + "E06000035", + "Medway", + 96.0, + 29.0, + 1.0, +] +ROWS = [FORCE_TOTAL, LEWISHAM, UNASSIGNED, CARDIFF, MEDWAY] + + +def _workbook( + header: list[str] = HEADER, rows: list[list[Any]] = ROWS, sheet: str = "Table C2" +) -> bytes: + """The edition's file, with the table of offences by partnership.""" + return ods({"Table C1": [["Table C1"]], sheet: [*TITLE, header, *rows]}) + + +def _serve( + monkeypatch: pytest.MonkeyPatch, + workbook: bytes, + editions: list[dict[str, str]] | None = None, + downloads: list[dict[str, str]] | None = None, +) -> mock.MagicMock: + """Answer as the ONS website does, for the dataset, its edition and the file.""" + pages = { + DATASET_JSON: { + "datasets": [{"uri": EDITION}, {"uri": OLDER}] + if editions is None + else editions + }, + EDITION_JSON: { + "description": {"edition": "year ending June 2026"}, + "downloads": [{"file": "pfatablesyejune2026.xlsx"}] + if downloads is None + else downloads, + }, + } + return serve_gov_uk(monkeypatch, pages, {FILE: workbook}) + + +def test_each_partnership_has_its_offences(monkeypatch: pytest.MonkeyPatch) -> None: + _serve(monkeypatch, _workbook()) + + table = nw.from_native(load_crime(), eager_only=True) + + assert table.columns == [ + "geography_code", + "geography_name", + "police_force_area", + "year", + "total_recorded_crime", + "violence_against_the_person", + "robbery", + ] + # The force's total and its unassigned offences are left out. + rows = {row[0]: row for row in table.rows()} + assert set(rows) == {"E22000208", "W14000015", "E22000143"} + assert rows["E22000208"] == ( + "E22000208", + "Lewisham", + "Metropolitan Police", + "year ending June 2026", + 3000.0, + 1000.0, + 150.0, + ) + assert rows["W14000015"][4:] == (3600.0, 1100.0, 30.0) + # A partnership ONS marks as incomplete has no figures, not its few. + medway = table.filter(nw.col("geography_code") == "E22000143") + assert medway["police_force_area"].to_list() == ["Kent"] + assert medway["total_recorded_crime"].is_null().to_list() == [True] + assert medway["violence_against_the_person"].is_null().to_list() == [True] + + +def test_the_latest_edition_is_found_from_the_dataset_page( + monkeypatch: pytest.MonkeyPatch, +) -> None: + get = _serve(monkeypatch, _workbook()) + + load_crime() + + assert [call.args[0] for call in get.call_args_list] == [ + "https://www.ons.gov.uk/peoplepopulationandcommunity/crimeandjustice/" + "datasets/policeforceareadatatables/data", + EDITION_JSON, + FILE, + ] + + +@pytest.mark.parametrize( + ("workbook", "editions", "downloads"), + [ + pytest.param(_workbook(), [], None, id="no editions"), + pytest.param(_workbook(), None, [{"file": "tables.csv"}], id="no xlsx"), + pytest.param(_workbook(sheet="Table C3"), None, None, id="no table C2"), + pytest.param( + _workbook( + [ + *HEADER[:2], + "Partnership code", + *HEADER[3:], + ] + ), + None, + None, + id="code renamed", + ), + pytest.param( + _workbook(rows=[FORCE_TOTAL, UNASSIGNED]), None, None, id="no partnerships" + ), + ], +) +def test_a_changed_layout_says_which_source_changed( + monkeypatch: pytest.MonkeyPatch, + workbook: bytes, + editions: list[dict[str, str]] | None, + downloads: list[dict[str, str]] | None, +) -> None: + _serve(monkeypatch, workbook, editions, downloads) + + with pytest.raises(ValueError, match="ONS's police recorded crime tables"): + load_crime() diff --git a/tests/test_crime_needs.py b/tests/test_crime_needs.py new file mode 100644 index 0000000..3e93355 --- /dev/null +++ b/tests/test_crime_needs.py @@ -0,0 +1,200 @@ +"""Police recorded crime as the needs the analyses compare by, counted in offences. + +ONS publishes offences for community safety partnerships. How they are shared +out comes from the residents of each council at the 2021 Census, as ONS +published them, which ship with the package. +""" + +import json + +import pytest +from need_fakes import COUNCIL_COUNTS, RUNS, area, keep_places, serve_gov_uk +from spreadsheets import ods + +from uk_open_data.analyses import AnalysisInputError, AnalysisResult, run_analysis +from uk_open_data.areas import local_authority_lookup +from uk_open_data.crime import api + +EDITION = "/datasets/policeforceareadatatables/yearendingjune2026" +PAGES = { + f"{api.DATASET_PAGE}/data": {"datasets": [{"uri": EDITION}]}, + f"https://www.ons.gov.uk{EDITION}/data": { + "description": {"edition": "year ending June 2026"}, + "downloads": [{"file": "pfatables.xlsx"}], + }, +} +FILE = f"https://www.ons.gov.uk/file?uri={EDITION}/pfatables.xlsx" +HEADER = [ + "Police Force Area code", + "Police Force Area name", + "Community Safety Partnership code", + "Community Safety Partnership name", + "Local Authority code", + "Local Authority name", + "Total recorded crime (excluding fraud)", + "Violence against the person", +] +LEWISHAM, GREENWICH = "E22000208", "E22000196" +DARTFORD_AND_GRAVESHAM = "E22000352" +DARTFORD, GRAVESHAM = "E07000107", "E07000109" +# Kent's partnerships whose crimes ONS records under "Unassigned Kent". +KENT_NOTED = ( + DARTFORD_AND_GRAVESHAM, + "E22000142", + "E22000143", + "E22000148", + "E22000149", +) +# Invented offences, total and violent: 100 and 40 in every partnership but +# these. +OFFENCES = { + LEWISHAM: (3000.0, 1200.0), + GREENWICH: (2500.0, 900.0), + DARTFORD_AND_GRAVESHAM: (1000.0, 400.0), +} +NEEDS = ["recorded_crime", "violence_against_the_person"] +# Dartford and Gravesham, beyond the shared places, with invented residents +# and centres, so a run reads them without fetching. +KENT_RESIDENTS = ( + (DARTFORD, "Dartford", 117000), + (GRAVESHAM, "Gravesham", 107000), + ("E06000035", "Medway", 280000), +) +KENT_CENTRES = ( + (DARTFORD, 51.44, 0.21), + (GRAVESHAM, 51.43, 0.37), + ("E06000035", 51.40, 0.55), +) + + +def _table(noted: tuple[str, ...] = ()) -> bytes: + """Offences for every partnership the lookup lists, as ONS lays them out. + + The partnerships in ``noted`` are marked, as ONS marks those it says are + incomplete. + """ + names = { + part.area_code: part.area_name + for part in local_authority_lookup("community_safety_partnership") + } + rows = [ + [ + "E23000000", + "Kent [note 5]" if code in noted else "A force", + code, + name, + "", + name, + *OFFENCES.get(code, (100.0, 40.0)), + ] + for code, name in sorted(names.items()) + ] + return ods({"Table C2": [["Table C2"], HEADER, *rows]}) + + +def _serve(monkeypatch: pytest.MonkeyPatch, noted: tuple[str, ...] = ()) -> None: + """Serve ONS's tables, with some partnerships marked as incomplete.""" + serve_gov_uk(monkeypatch, PAGES, {FILE: _table(noted)}) + + +@pytest.fixture(autouse=True) +def ons(monkeypatch: pytest.MonkeyPatch) -> None: + """Serve ONS's tables, and keep the residents and centres the runs need.""" + _serve(monkeypatch) + keep_places(KENT_RESIDENTS, KENT_CENTRES) + + +def _compared(result: AnalysisResult) -> dict[str, int]: + """The offences counted in each local authority compared, by its code.""" + table = result.table("by_local_authority") + return {row["geography_code"]: row["people_in_need"] for row in table.rows} + + +@pytest.mark.parametrize("need", NEEDS) +@pytest.mark.parametrize(("analysis_id", "rows", "options"), RUNS) +def test_each_need_analysis_takes_the_crime_measures( + analysis_id: str, rows: list[dict], options: dict, need: str +) -> None: + result = run_analysis(analysis_id, rows, options={"need": need, **options}) + + crime = next(s for s in result.sources if s.id == "ons-police-recorded-crime") + assert crime.edition == "year ending June 2026" + assert area(result) == "England and Wales" + assert result.figure("people_in_need").unit == "offences" + + +def test_partnership_offences_are_shared_out_to_councils() -> None: + rows = [ + {"local_authority": "Dartford", "count": 30}, + {"local_authority": "Gravesham", "count": 20}, + *COUNCIL_COUNTS, + ] + + result = run_analysis( + "need-reach", + rows, + options={ + "need": NEEDS[0], + "catchment": ["Lewisham", "Dartford", "Gravesham"], + }, + ) + + # Lewisham is a partnership of its own. Dartford and Gravesham share one: + # 52.2% and 47.8% of its residents at the 2021 Census. + assert _compared(result) == { + "E09000023": 3000, + DARTFORD: 522, + GRAVESHAM: 478, + } + + +def test_partnerships_ons_marks_as_incomplete_are_left_out( + monkeypatch: pytest.MonkeyPatch, +) -> None: + _serve(monkeypatch, KENT_NOTED) + named = ( + "ONS has no figures for year ending June 2026 for 5 community safety " + "partnerships: Dartford and Gravesham; Maidstone; Medway; Tonbridge and " + "Malling; Tunbridge Wells. So these local authorities are left out of " + "the comparison: Dartford; Gravesham; Maidstone; Medway; Tonbridge and " + "Malling; Tunbridge Wells." + ) + + result = run_analysis( + "need-reach", + COUNCIL_COUNTS, + options={"need": NEEDS[1], "catchment": ["Lewisham", "Greenwich"]}, + ) + with pytest.raises(AnalysisInputError) as caught: + run_analysis( + "need-reach", + [*COUNCIL_COUNTS, {"local_authority": "Medway", "count": 10}], + options={"need": NEEDS[1], "catchment": ["Medway"]}, + ) + + assert named in result.warnings + assert str(caught.value).startswith(named) + + +def test_a_result_counts_offences_not_people() -> None: + result = run_analysis( + "need-reach", + COUNCIL_COUNTS, + options={"need": NEEDS[0], "catchment": ["Lewisham", "Greenwich"]}, + ) + + counted = result.figure("people_in_need") + assert counted.label == ( + "Offences recorded in the area you serve (Crimes recorded by the " + "police, excluding fraud)" + ) + # Lewisham's 3,000 and Greenwich's 2,500. + assert counted.value == 5500 + assert result.table("by_local_authority").headings["people_in_need"] == ( + "Offences recorded" + ) + assert any("not people or victims" in caveat for caveat in result.caveats) + cited = [source.id for source in result.sources] + assert "ons-police-recorded-crime" in cited + assert "ons-local-authority-lookups" in cited + assert "in whole offences" in json.dumps(result.to_dict()) diff --git a/tests/test_datasets.py b/tests/test_datasets.py index bc568eb..9adc942 100644 --- a/tests/test_datasets.py +++ b/tests/test_datasets.py @@ -17,6 +17,7 @@ from uk_open_data.analyses.access_distance import keep_centres from uk_open_data.analyses.need_reach import MEASURES, keep_need_figures from uk_open_data.analyses.who_we_miss import keep_residents +from uk_open_data.areas import local_authority_lookup from uk_open_data.postcodes import ( build_postcode_table, install_postcode_table, @@ -92,6 +93,26 @@ def nomis(): yield load +def _for_areas( + by_council: tuple[tuple[str, str, int], ...], area: str +) -> tuple[tuple[str, str, int], ...]: + """The figures given by council, as a need of a bigger area keeps them. + + Each council's figure is given to the area it is in, so a need published + for partnerships, say, has figures for the partnerships of these councils. + """ + if area == "council": + return by_council + counts = {code: count for code, _, count in by_council} + return tuple( + { + part.area_code: (part.area_code, part.area_name, counts[part.lad_code]) + for part in local_authority_lookup(area) + if part.lad_code in counts + }.values() + ) + + def _tables_asked(nomis: mock.Mock) -> list[str]: """The Nomis tables asked for, in order.""" return [call.args[0] for call in nomis.call_args_list] @@ -100,10 +121,11 @@ def _tables_asked(nomis: mock.Mock) -> list[str]: @pytest.fixture def kept_figures(postcode_table: None) -> None: """Keep invented public figures, so no analysis fetches anything.""" - for need in MEASURES: - # With Sheffield's code before April 2025, as census figures have it, so - # moving it to today's code, and citing how, is covered too. - keep_need_figures(need, (*fakes.NEED, ("E08000019", "Sheffield", 500)), NOTE) + # With Sheffield's code before April 2025, as census figures have it, so + # moving it to today's code, and citing how, is covered too. + by_council = (*fakes.NEED, ("E08000019", "Sheffield", 500)) + for need, measure in MEASURES.items(): + keep_need_figures(need, _for_areas(by_council, measure.area), NOTE) keep_residents("ethnic_group", fakes.RESIDENTS, NOTE) keep_residents("sex", SEX_RESIDENTS, NOTE) keep_centres(CENTRES, NOTE) diff --git a/tests/test_live_sources.py b/tests/test_live_sources.py index 6f52bd8..8ec802c 100644 --- a/tests/test_live_sources.py +++ b/tests/test_live_sources.py @@ -27,6 +27,7 @@ newest_lookups, ) from uk_open_data.connectivity import download_connectivity, load_connectivity +from uk_open_data.crime import api as crime_api from uk_open_data.education import list_publications, load_education from uk_open_data.fuel_poverty import api as fuel_poverty_api from uk_open_data.homelessness import api as homelessness_api @@ -137,6 +138,20 @@ def _vaccinations() -> list[int | None]: ] +def _crime() -> list[int | None]: + """How many partnerships have each kind of offence, None for one none has. + + Both needs' figures are kept too, so an offence renamed is caught. + """ + table = nw.from_native(crime_api.load_crime(), eager_only=True) + offences = table.columns[table.columns.index("year") + 1 :] + return [ + *(table[column].count() or None for column in offences), + *_kept(download_need_figures("recorded_crime"), "figures"), + *_kept(download_need_figures("violence_against_the_person"), "figures"), + ] + + def _council_codes() -> list[str]: """ONS's newest council codes, which the shipped table must hold.""" if not code_history_answers(): @@ -210,6 +225,7 @@ def _postcode_table() -> list[str | None]: "dfe-education-statistics": _education, "dwp-children-low-income": _low_income, "ukhsa-childhood-vaccinations": _vaccinations, + "ons-police-recorded-crime": _crime, } From 6a967bac13c9530ad9277304615105ea7cb50627 Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Tue, 1 Dec 2026 16:01:05 +0000 Subject: [PATCH 2/3] refactor(crime): leave out only partnerships ONS says are "Unassigned" After review: - The loader left out any partnership marked with a note. A note only says something applies; ONS's partnership notes also cover small numbers and undercounts. It now reads the "Notes - CSP" sheet and leaves out a partnership's figures only when its note says its offences are recorded as "Unassigned", as note 5 does of five Kent partnerships today. A note about anything else, such as Northumbria's robbery undercount in 2025, leaves the figures as they are. - A table that loses total_recorded_crime or violence_against_the_person says so, not a KeyError later in a need. - _frames' header matcher sets marks aside on both sides, so low income and crime pass their header's text and drop their own matchers. - The edition is found with _govuk.listed, and a constant used once is gone. - In the datasets test, _for_areas adds up councils in one area, and says which councils it leaves out. Signed-off-by: billlyzhaoyh Github-Issue: #210 --- docs/api/crime.md | 14 +++-- docs/api/data-sources.md | 2 +- src/uk_open_data/_frames.py | 12 +++- src/uk_open_data/crime/api.py | 91 ++++++++++++++++++++--------- src/uk_open_data/low_income/api.py | 7 +-- tests/test_crime_api.py | 93 ++++++++++++++++++++++-------- tests/test_crime_needs.py | 6 +- tests/test_datasets.py | 21 ++++--- 8 files changed, 171 insertions(+), 75 deletions(-) diff --git a/docs/api/crime.md b/docs/api/crime.md index 791de1f..7cf65b1 100644 --- a/docs/api/crime.md +++ b/docs/api/crime.md @@ -42,12 +42,14 @@ different ways, so a difference between forces may be one of recording. - Offences the police could not place in a partnership, which ONS lists as "Unassigned" under each force. They are about 3% of offences across England and Wales, more in some forces in some quarters. -- **A partnership whose row ONS marks with a note**, such as "Kent [note 5]", - has missing figures (null), never the published number. ONS marks a row so - when its figures are incomplete: in the year ending June 2026, ONS says the - crimes of five Kent partnerships (Dartford and Gravesham, Maidstone, Medway, - Tonbridge and Malling, and Tunbridge Wells) are recorded under "Unassigned - Kent". Their published figures are a few dozen offences each. +- **A partnership ONS marks with a note that says its offences are recorded + as "Unassigned"**, such as "Kent [note 5]", has missing figures (null), + never the published number. In the year ending June 2026, ONS says so of + five Kent partnerships (Dartford and Gravesham, Maidstone, Medway, Tonbridge + and Malling, and Tunbridge Wells), whose published figures are a few dozen + offences each. The loader reads the notes from the "Notes - CSP" sheet, so + a note about anything else, such as an undercount of one kind of offence, + leaves a partnership's figures as they are. The [analyses](analyses.md#need-against-reach) take two of these counts as needs, `recorded_crime` and `violence_against_the_person`, for England and diff --git a/docs/api/data-sources.md b/docs/api/data-sources.md index dfa884d..cfeb205 100644 --- a/docs/api/data-sources.md +++ b/docs/api/data-sources.md @@ -641,7 +641,7 @@ each page as JSON at the page's address followed by `/data`. | Header | The row whose first cell is "Police Force Area code", below the title and notes. Headings hold line breaks and marks such as "(excluding fraud)", which the loader takes out | | Columns | The force's code and name, the partnership's code and name, the council's code and name (or "Combined Local Authorities"), then one column per kind of offence | | Rows | Each force's total (no partnership code), its partnerships (`E22` and `W14`), and its "Unassigned" offences (no code). The loader keeps the partnerships | -| Marked rows | A partnership ONS marks with a note, on its force's name, has incomplete figures. In the year ending June 2026 these are five Kent partnerships, marked "Kent [note 5]", whose crimes are recorded under "Unassigned Kent". The note's number changes between editions. The loader gives them no figures | +| Marked rows | A partnership ONS marks with a note, on its force's name, such as "Kent [note 5]". The notes are in the sheet `Notes - CSP`, by number. When a row's note says offences are recorded as "Unassigned", as note 5 does of five Kent partnerships in the year ending June 2026, the loader gives the partnership no figures. The note's number changes between editions. Notes about other things, such as Northumbria's undercount of robbery in the year ending March 2025, have been on a force's total, not its partnerships | | Codes | The partnerships' codes match `local_authority_lookup("community_safety_partnership")`: all 314 in the year ending June 2026 | --- diff --git a/src/uk_open_data/_frames.py b/src/uk_open_data/_frames.py index 9311827..da23fe0 100644 --- a/src/uk_open_data/_frames.py +++ b/src/uk_open_data/_frames.py @@ -122,7 +122,8 @@ def read_spreadsheet_rows( Uses ``python-calamine`` (one fast reader for both formats). ``header_row`` is the 0-based index of the header line, or, for a sheet whose title runs to a varying number of lines, the text in the first cell of the header - line or a test that is true of the header line's cells. Rows above it are + line, marks such as "[note 2]" aside, or a test that is true of the header + line's cells. Rows above it are ignored. Header cells are stringified and stripped; fully empty rows are dropped. @@ -164,8 +165,13 @@ def read_spreadsheet_rows( def _first_cell_is(first_cell: str) -> Callable[[list[Any]], bool]: - """A test that is true of a row whose first cell is ``first_cell``.""" - return lambda row: bool(row) and str(row[0]).strip() == first_cell + """A test that is true of a row whose first cell is ``first_cell``. + + Marks such as "[note 2]" are set aside on both sides, so a header is found + when a publisher adds or renumbers a note on it. + """ + wanted = plain_heading(first_cell) + return lambda row: bool(row) and plain_heading(str(row[0])) == wanted def _first_row( diff --git a/src/uk_open_data/crime/api.py b/src/uk_open_data/crime/api.py index 57f3139..accdcc0 100644 --- a/src/uk_open_data/crime/api.py +++ b/src/uk_open_data/crime/api.py @@ -15,10 +15,11 @@ police recorded, not victims, and leave out fraud. Offences the police could not place in a partnership, which ONS lists as "Unassigned", are left out. -Where ONS marks a partnership's row with a note, its figures are incomplete: -in the year ending June 2026, ONS says the crimes of five Kent partnerships are -recorded under "Unassigned Kent". Such a partnership's figures are missing -(null), never the published number. +Where ONS marks a partnership with a note that says its offences are recorded +as "Unassigned", its own figures are a few stray offences: in the year ending +June 2026, ONS says so of five Kent partnerships. Such a partnership's figures +are missing (null), never the published number. A note about anything else +leaves the figures as they are. ONS publishes a new edition each quarter, so the loader finds the latest through the JSON the ONS website gives for each page. @@ -33,7 +34,7 @@ import narwhals.stable.v2 as nw -from uk_open_data import _caches, _http +from uk_open_data import _caches, _govuk, _http from uk_open_data._frames import ( dicts_to_frame, number_or_none, @@ -47,8 +48,6 @@ f"{ONS_WEBSITE}/peoplepopulationandcommunity/crimeandjustice/datasets/" "policeforceareadatatables" ) -# The ONS website gives each page as JSON at this address under it. -JSON = "/data" SPREADSHEET = ".xlsx" # The table of offences by partnership, under a title and notes. Its header # row starts with this. @@ -59,6 +58,14 @@ NAME = "Community Safety Partnership name" # The last column before the offences. BEFORE_OFFENCES = "Local Authority name" +# The offences the needs read, so a table that loses one has changed. +NEEDED = ("total_recorded_crime", "violence_against_the_person") +# The notes on the table by partnership. A partnership marked with a note +# that says its offences are recorded as "Unassigned" has none of its own. +NOTES = "Notes - CSP" +NOTE_NUMBER = "Note number" +NOTE_TEXT = "Note text" +UNASSIGNED = "unassigned" # Partnerships' codes in England and Wales. Each force's total, and its # "Unassigned" row, have none. PARTNERSHIPS = ("E22", "W14") @@ -80,7 +87,8 @@ def load_crime() -> Any: of offence, named from ONS's heading: ``total_recorded_crime`` (which leaves out fraud), ``violence_against_the_person``, ``robbery``, ``shoplifting`` and the rest. A figure is missing (null) where ONS - gives none, or marks the partnership's figures as incomplete. + gives none, or notes that the partnership's offences are recorded as + "Unassigned". Raises: ValueError: If the dataset lists no edition, the edition has no @@ -107,34 +115,38 @@ def _latest() -> nw.DataFrame: def _latest_file() -> tuple[str, str]: - """Find the latest edition's name and the address of its spreadsheet.""" - editions = _json(DATASET_PAGE).get("datasets") - uri = editions[0].get("uri") if isinstance(editions, list) and editions else None + """Find the latest edition's name and the address of its spreadsheet. + + The dataset's page lists its editions, the latest first. + """ + editions = _govuk.listed(_json(DATASET_PAGE), "datasets") + uri = editions[0].get("uri") if editions and isinstance(editions[0], dict) else None if not isinstance(uri, str): raise ValueError(_changed(f"{DATASET_PAGE} lists no edition")) edition = _json(f"{ONS_WEBSITE}{uri}") year = str(edition.get("description", {}).get("edition") or "") - files = [ - name - for download in edition.get("downloads") or [] + files = ( + str(download.get("file")) + for download in _govuk.listed(edition, "downloads") if isinstance(download, dict) - and (name := str(download.get("file") or "")).lower().endswith(SPREADSHEET) - ] - if not year or not files: + and str(download.get("file") or "").lower().endswith(SPREADSHEET) + ) + spreadsheet = next(files, None) + if not year or spreadsheet is None: raise ValueError(_changed(f"the edition at {uri} has no spreadsheet")) - return year, f"{ONS_WEBSITE}/file?uri={uri}/{files[0]}" + return year, f"{ONS_WEBSITE}/file?uri={uri}/{spreadsheet}" def _json(page: str) -> dict[str, Any]: """A page of the ONS website, as the JSON the website gives for it.""" - described = _http.get(f"{page}{JSON}").json() + described = _http.get(f"{page}/data").json() return described if isinstance(described, dict) else {} def _read_partnerships(content: bytes, year: str) -> list[dict[str, Any]]: """Read each partnership's offences from the table.""" try: - rows = read_spreadsheet_rows(content, SHEET, _is_header) + rows = read_spreadsheet_rows(content, SHEET, HEADER) except ValueError as error: raise ValueError(_changed(f"'{SHEET}' could not be found")) from error headings = { @@ -148,8 +160,12 @@ def _read_partnerships(content: bytes, year: str) -> list[dict[str, Any]]: _column(heading): headings[heading] for heading in plain[plain.index(BEFORE_OFFENCES) + 1 :] } + lost = [column for column in NEEDED if column not in offences] + if lost: + raise ValueError(_changed(f"'{SHEET}' has no column for {', '.join(lost)}")) + unassigned = _unassigned_notes(content) partnerships = [ - _partnership(row, headings, offences, year) + _partnership(row, headings, offences, year, unassigned) for row in rows if text_or_blank(row[headings[CODE]]).startswith(PARTNERSHIPS) ] @@ -163,18 +179,24 @@ def _partnership( headings: dict[str, str], offences: dict[str, str], year: str, + unassigned: set[str], ) -> dict[str, Any]: - """One partnership's code, name and offences, missing where ONS marks them.""" + """One partnership's code, name and offences. + + Its offences are missing when it is marked with a note in ``unassigned``, + one that says its offences are recorded as "Unassigned". + """ force = text_or_blank(row[headings[FORCE]]) name = text_or_blank(row[headings[NAME]]) - marked = bool(_MARK.search(force) or _MARK.search(name)) + marks = {mark.lower() for mark in _MARK.findall(f"{force} {name}")} + noted = bool(marks & unassigned) return { "geography_code": text_or_blank(row[headings[CODE]]), "geography_name": _unmarked(name), "police_force_area": _unmarked(force), "year": year, } | { - column: None if marked else number_or_none(row[heading]) + column: None if noted else number_or_none(row[heading]) for column, heading in offences.items() } @@ -184,9 +206,24 @@ def _unmarked(text: str) -> str: return " ".join(_MARK.sub("", text).split()) -def _is_header(cells: list[Any]) -> bool: - """Whether a row is the table's header, whatever marks its first cell has.""" - return bool(cells) and plain_heading(text_or_blank(cells[0])) == HEADER +def _unassigned_notes(content: bytes) -> set[str]: + """The marks of the notes that say offences are recorded as "Unassigned". + + In the year ending June 2026, note 5 says the offences of five Kent + partnerships are recorded under "Unassigned Kent", so this gives + "[note 5]". A note about something else, such as an undercount of one + kind of offence, takes no partnership's figures away. + """ + try: + rows = read_spreadsheet_rows(content, NOTES, NOTE_NUMBER) + except ValueError as error: + raise ValueError(_changed(f"'{NOTES}' could not be found")) from error + return { + f"[note {int(number)}]" + for row in rows + if (number := number_or_none(row.get(NOTE_NUMBER))) is not None + and UNASSIGNED in text_or_blank(row.get(NOTE_TEXT)).lower() + } def _column(heading: str) -> str: diff --git a/src/uk_open_data/low_income/api.py b/src/uk_open_data/low_income/api.py index d62a64d..de13e9b 100644 --- a/src/uk_open_data/low_income/api.py +++ b/src/uk_open_data/low_income/api.py @@ -147,16 +147,11 @@ def _read_councils(content: bytes) -> Any: def _table(content: bytes, sheet: str) -> list[dict[str, Any]]: """Read the rows of one table, below its header.""" try: - return read_spreadsheet_rows(content, sheet, _is_header) + return read_spreadsheet_rows(content, sheet, NAME) except ValueError as error: raise ValueError(_changed(f"table {sheet} could not be found")) from error -def _is_header(cells: list[Any]) -> bool: - """Whether a row is a table's header, whatever note its first cell has.""" - return bool(cells) and plain_heading(text_or_blank(cells[0])) == NAME - - def _by_year(rows: list[dict[str, Any]], start: str) -> dict[str, str]: """Each heading that starts with ``start``, as it is, by the year it names. diff --git a/tests/test_crime_api.py b/tests/test_crime_api.py index f02c4c9..761bf70 100644 --- a/tests/test_crime_api.py +++ b/tests/test_crime_api.py @@ -95,34 +95,60 @@ 29.0, 1.0, ] -ROWS = [FORCE_TOTAL, LEWISHAM, UNASSIGNED, CARDIFF, MEDWAY] +# A partnership marked with a note about something else keeps its figures. +NEWCASTLE = [ + "E23000007", + "Northumbria [note 4]", + "E22000185", + "Newcastle upon Tyne", + "E08000021", + "Newcastle upon Tyne", + 2800.0, + 900.0, + 40.0, +] +ROWS = [FORCE_TOTAL, LEWISHAM, UNASSIGNED, CARDIFF, MEDWAY, NEWCASTLE] +# The notes, as ONS words them: note 5 says Medway's offences are recorded as +# "Unassigned". +NOTES = [ + ["CSP notes"], + ["Note number", "Note text"], + [1.0, "Caution must be taken when interpreting small numbers of offences."], + [4.0, "Northumbria has an undercount of robbery offences by 24%."], + [ + 5.0, + "Due to ongoing IT issues, crime data for Medway are recorded under an " + "unassigned CSP group from 2024 onwards.", + ], +] +EDITIONS = [{"uri": EDITION}, {"uri": OLDER}] +DOWNLOADS = [{"file": "pfatablesyejune2026.xlsx"}] def _workbook( - header: list[str] = HEADER, rows: list[list[Any]] = ROWS, sheet: str = "Table C2" + header: list[str] = HEADER, + rows: list[list[Any]] = ROWS, + sheet: str = "Table C2", + notes: str = "Notes - CSP", ) -> bytes: """The edition's file, with the table of offences by partnership.""" - return ods({"Table C1": [["Table C1"]], sheet: [*TITLE, header, *rows]}) + return ods( + {notes: NOTES, "Table C1": [["Table C1"]], sheet: [*TITLE, header, *rows]} + ) def _serve( monkeypatch: pytest.MonkeyPatch, workbook: bytes, - editions: list[dict[str, str]] | None = None, - downloads: list[dict[str, str]] | None = None, + editions: list[dict[str, str]] = EDITIONS, + downloads: list[dict[str, str]] = DOWNLOADS, ) -> mock.MagicMock: """Answer as the ONS website does, for the dataset, its edition and the file.""" pages = { - DATASET_JSON: { - "datasets": [{"uri": EDITION}, {"uri": OLDER}] - if editions is None - else editions - }, + DATASET_JSON: {"datasets": editions}, EDITION_JSON: { "description": {"edition": "year ending June 2026"}, - "downloads": [{"file": "pfatablesyejune2026.xlsx"}] - if downloads is None - else downloads, + "downloads": downloads, }, } return serve_gov_uk(monkeypatch, pages, {FILE: workbook}) @@ -144,7 +170,7 @@ def test_each_partnership_has_its_offences(monkeypatch: pytest.MonkeyPatch) -> N ] # The force's total and its unassigned offences are left out. rows = {row[0]: row for row in table.rows()} - assert set(rows) == {"E22000208", "W14000015", "E22000143"} + assert set(rows) == {"E22000208", "W14000015", "E22000143", "E22000185"} assert rows["E22000208"] == ( "E22000208", "Lewisham", @@ -155,11 +181,20 @@ def test_each_partnership_has_its_offences(monkeypatch: pytest.MonkeyPatch) -> N 150.0, ) assert rows["W14000015"][4:] == (3600.0, 1100.0, 30.0) - # A partnership ONS marks as incomplete has no figures, not its few. + # A partnership whose offences ONS notes are recorded as "Unassigned" has + # no figures, not its few. medway = table.filter(nw.col("geography_code") == "E22000143") assert medway["police_force_area"].to_list() == ["Kent"] assert medway["total_recorded_crime"].is_null().to_list() == [True] assert medway["violence_against_the_person"].is_null().to_list() == [True] + # A note about something else leaves the figures as they are. + assert rows["E22000185"][2:] == ( + "Northumbria", + "year ending June 2026", + 2800.0, + 900.0, + 40.0, + ) def test_the_latest_edition_is_found_from_the_dataset_page( @@ -180,9 +215,18 @@ def test_the_latest_edition_is_found_from_the_dataset_page( @pytest.mark.parametrize( ("workbook", "editions", "downloads"), [ - pytest.param(_workbook(), [], None, id="no editions"), - pytest.param(_workbook(), None, [{"file": "tables.csv"}], id="no xlsx"), - pytest.param(_workbook(sheet="Table C3"), None, None, id="no table C2"), + pytest.param(_workbook(), [], DOWNLOADS, id="no editions"), + pytest.param(_workbook(), EDITIONS, [{"file": "tables.csv"}], id="no xlsx"), + pytest.param( + _workbook(sheet="Table C3"), EDITIONS, DOWNLOADS, id="no table C2" + ), + pytest.param(_workbook(notes="Notes"), EDITIONS, DOWNLOADS, id="no notes"), + pytest.param( + _workbook([*HEADER[:7], "Violence", *HEADER[8:]]), + EDITIONS, + DOWNLOADS, + id="violence renamed", + ), pytest.param( _workbook( [ @@ -191,20 +235,23 @@ def test_the_latest_edition_is_found_from_the_dataset_page( *HEADER[3:], ] ), - None, - None, + EDITIONS, + DOWNLOADS, id="code renamed", ), pytest.param( - _workbook(rows=[FORCE_TOTAL, UNASSIGNED]), None, None, id="no partnerships" + _workbook(rows=[FORCE_TOTAL, UNASSIGNED]), + EDITIONS, + DOWNLOADS, + id="no partnerships", ), ], ) def test_a_changed_layout_says_which_source_changed( monkeypatch: pytest.MonkeyPatch, workbook: bytes, - editions: list[dict[str, str]] | None, - downloads: list[dict[str, str]] | None, + editions: list[dict[str, str]], + downloads: list[dict[str, str]], ) -> None: _serve(monkeypatch, workbook, editions, downloads) diff --git a/tests/test_crime_needs.py b/tests/test_crime_needs.py index 3e93355..2db2fc5 100644 --- a/tests/test_crime_needs.py +++ b/tests/test_crime_needs.py @@ -89,7 +89,11 @@ def _table(noted: tuple[str, ...] = ()) -> bytes: ] for code, name in sorted(names.items()) ] - return ods({"Table C2": [["Table C2"], HEADER, *rows]}) + notes = [ + ["Note number", "Note text"], + [5.0, "Crime data for these are recorded under an unassigned CSP group."], + ] + return ods({"Notes - CSP": notes, "Table C2": [["Table C2"], HEADER, *rows]}) def _serve(monkeypatch: pytest.MonkeyPatch, noted: tuple[str, ...] = ()) -> None: diff --git a/tests/test_datasets.py b/tests/test_datasets.py index 9adc942..ca71086 100644 --- a/tests/test_datasets.py +++ b/tests/test_datasets.py @@ -98,19 +98,24 @@ def _for_areas( ) -> tuple[tuple[str, str, int], ...]: """The figures given by council, as a need of a bigger area keeps them. - Each council's figure is given to the area it is in, so a need published + Each council's figure is added to the area it is in, so a need published for partnerships, say, has figures for the partnerships of these councils. + A council the lookup does not hold by today's code, such as Sheffield's + code before April 2025, is left out: moving old codes is covered by the + needs given by council. """ if area == "council": return by_council counts = {code: count for code, _, count in by_council} - return tuple( - { - part.area_code: (part.area_code, part.area_name, counts[part.lad_code]) - for part in local_authority_lookup(area) - if part.lad_code in counts - }.values() - ) + totals: dict[str, int] = {} + names: dict[str, str] = {} + for part in local_authority_lookup(area): + if part.lad_code in counts: + totals[part.area_code] = ( + totals.get(part.area_code, 0) + counts[part.lad_code] + ) + names[part.area_code] = part.area_name + return tuple((code, names[code], total) for code, total in totals.items()) def _tables_asked(nomis: mock.Mock) -> list[str]: From 92c721c3540ac0ceb8fe8c37f147aa9a43ac3ce3 Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Tue, 1 Dec 2026 16:06:44 +0000 Subject: [PATCH 3/3] fix(crime): offences are in places, and notes are read by their words From code review. Each of the first three has a test that failed before: - The analyses said offences "live in" places, as if they were people: "97.1% of the offences recorded live in ...". NeedWords now carry who, live_in and their, so offences "are in" places, a share label reads "offences recorded that are in ...", and access and distance counts each offence at the centre of "its" local authority. Words for people, households and children are unchanged. need-reach's caveat says a count that is not of people is read as more or less reach between places. - A partnership's figures are taken away only when its note says its offences are "recorded under an unassigned" group, as ONS words it for Kent. ONS has other notes that mention unassigned offences, such as Humberside's, which says its figures remain accurate. - Offences whose headings would give one column, such as a total that includes fraud beside the one that leaves it out, or one with no name, are refused rather than one taking the other's place. Also: - A figure written as text, such as "1,234 [r]", is read; a negative count, which ONS says can happen, is missing. - The edition's name starts lower case, as a sentence says it, whatever case ONS gives it in, and a null description is no longer an AttributeError. - The reason for the needs no longer says every crime is recorded. - The docstrings that list need sources name ONS. - The live check fetches once, because ONS limits how often it is asked. - The dataset's areas carry their year. - The docs give Kent's partial figures as they are, such as Dartford and Gravesham's 11,165. Signed-off-by: billlyzhaoyh Github-Issue: #210 --- docs/api/crime.md | 5 +- docs/api/datasets.md | 2 +- src/uk_open_data/analyses/_answers.py | 16 ++++- src/uk_open_data/analyses/_need.py | 22 +++---- src/uk_open_data/analyses/access_distance.py | 4 +- src/uk_open_data/analyses/datasets.py | 2 +- src/uk_open_data/analyses/need_reach.py | 21 +++++-- src/uk_open_data/analyses/provision_gap.py | 5 +- src/uk_open_data/crime/api.py | 61 +++++++++++++++----- tests/test_crime_api.py | 40 ++++++++----- tests/test_crime_needs.py | 6 ++ tests/test_live_sources.py | 9 +-- 12 files changed, 135 insertions(+), 58 deletions(-) diff --git a/docs/api/crime.md b/docs/api/crime.md index 7cf65b1..09a4796 100644 --- a/docs/api/crime.md +++ b/docs/api/crime.md @@ -46,8 +46,9 @@ different ways, so a difference between forces may be one of recording. as "Unassigned"**, such as "Kent [note 5]", has missing figures (null), never the published number. In the year ending June 2026, ONS says so of five Kent partnerships (Dartford and Gravesham, Maidstone, Medway, Tonbridge - and Malling, and Tunbridge Wells), whose published figures are a few dozen - offences each. The loader reads the notes from the "Notes - CSP" sheet, so + and Malling, and Tunbridge Wells). Their published figures are partial: + Medway shows 96 offences for the year, and Dartford and Gravesham 11,165, + where it showed over 19,000 a year before. The loader reads the notes from the "Notes - CSP" sheet, so a note about anything else, such as an undercount of one kind of offence, leaves a partnership's figures as they are. diff --git a/docs/api/datasets.md b/docs/api/datasets.md index de6ac00..c79474b 100644 --- a/docs/api/datasets.md +++ b/docs/api/datasets.md @@ -18,7 +18,7 @@ Open Geography Portal. | [Sub-regional fuel poverty statistics](https://www.gov.uk/government/statistics/sub-regional-fuel-poverty-data-2026-2024-data) | `desnz-fuel-poverty` | Department for Energy Security and Net Zero | [people](https://www.data.gov.uk/collections/people) | Local authority districts (2025) | England | Open Government Licence v3.0 | `need-reach`, `provision-gap`, `access-distance` | Yes | | [Children in low income families: local area statistics](https://www.gov.uk/government/collections/children-in-low-income-families-local-area-statistics) | `dwp-children-low-income` | Department for Work and Pensions | [people](https://www.data.gov.uk/collections/people) | Local authority districts (2023) | England, Wales, Scotland and Northern Ireland | Open Government Licence v3.0 | `need-reach`, `provision-gap`, `access-distance` | Yes | | [Childhood vaccination coverage statistics (COVER programme)](https://www.gov.uk/government/collections/cover-of-vaccination-evaluated-rapidly-cover-programme-statistics) | `ukhsa-childhood-vaccinations` | UK Health Security Agency | [people](https://www.data.gov.uk/collections/people) | Counties and unitary authorities (2023) | England | Open Government Licence v3.0 | `need-reach`, `provision-gap`, `access-distance` | Yes | -| [Crime in England and Wales: Police Force Area data tables](https://www.ons.gov.uk/peoplepopulationandcommunity/crimeandjustice/datasets/policeforceareadatatables) | `ons-police-recorded-crime` | Office for National Statistics, from Home Office police recorded crime | [people](https://www.data.gov.uk/collections/people) | Community safety partnerships | England and Wales | Open Government Licence v3.0 | `need-reach`, `provision-gap`, `access-distance` | Yes | +| [Crime in England and Wales: Police Force Area data tables](https://www.ons.gov.uk/peoplepopulationandcommunity/crimeandjustice/datasets/policeforceareadatatables) | `ons-police-recorded-crime` | Office for National Statistics, from Home Office police recorded crime | [people](https://www.data.gov.uk/collections/people) | Community safety partnerships (2025) | England and Wales | Open Government Licence v3.0 | `need-reach`, `provision-gap`, `access-distance` | Yes | | [TS021 - Ethnic group (NM_2041_1)](https://www.nomisweb.co.uk/api/v01/dataset/NM_2041_1.def.sdmx.json) | `nomis-nm_2041_1` | Office for National Statistics, through Nomis | [people](https://www.data.gov.uk/collections/people) | Local authority districts (2023) | England and Wales | Open Government Licence v3.0 | `who-we-miss` | Yes | | [postcodes.io](https://postcodes.io) | `postcodes-io` | postcodes.io, built on the ONS Postcode Directory | [land-and-property](https://www.data.gov.uk/collections/land-and-property) | Postcodes | England, Wales, Scotland and Northern Ireland | Open Government Licence v3.0 | `reach-deprivation`, `reach-connectivity`, `who-we-miss`, `need-reach`, `provision-gap`, `access-distance` | No | | [Postcode to OA (2021) to LSOA to MSOA to LAD Best Fit Lookup in the UK](https://geoportal.statistics.gov.uk) | `ons-postcode-lookup` | Office for National Statistics | [land-and-property](https://www.data.gov.uk/collections/land-and-property) | Postcodes | England and Wales | Open Government Licence v3.0 | `reach-deprivation`, `reach-connectivity`, `who-we-miss`, `need-reach`, `provision-gap`, `access-distance` | Yes | diff --git a/src/uk_open_data/analyses/_answers.py b/src/uk_open_data/analyses/_answers.py index d718c66..1d274a4 100644 --- a/src/uk_open_data/analyses/_answers.py +++ b/src/uk_open_data/analyses/_answers.py @@ -41,6 +41,11 @@ class NeedWords: # of them: "people" and "person". unit: str = "people" one: str = "person" + # How a sentence says what is counted is in a place: "who live in", or + # "that are in" for offences, and whose place it is: "their" or "its". + who: str = "who" + live_in: str = "live in" + their: str = "their" # Whether the measure counts everyone, so it is not a need at all. everyone: bool = False # Headings for the columns about need, where the shared ones do not fit. @@ -51,13 +56,15 @@ def headings(self) -> dict[str, str]: return dict(self.column_headings) -def _counted_in(noun: str, unit: str, one: str) -> NeedWords: +def _counted_in(noun: str, unit: str, one: str, *, people: bool = True) -> NeedWords: """The words for a need counted in something other than people. Args: noun: What is counted, such as "households in need". unit: What one count is in, such as "households". one: One of them, such as "household". + people: Whether what is counted lives somewhere, as households and + children do. Offences do not: they are in a place. """ counted = sentence_case(noun) return NeedWords( @@ -68,6 +75,9 @@ def _counted_in(noun: str, unit: str, one: str) -> NeedWords: counted=counted, unit=unit, one=one, + who="who" if people else "that", + live_in="live in" if people else "are in", + their="their" if people else "its", column_headings=( ("people_in_need", counted), ("people_per_100_in_need", f"Your people per 100 {noun}"), @@ -120,7 +130,9 @@ def sentence_case(text: str) -> str: ) # A need counted in offences, from police recorded crime. Offences are not # people: one person can be the victim of many. -OFFENCES_RECORDED = _counted_in("offences recorded", "offences", "offence") +OFFENCES_RECORDED = _counted_in( + "offences recorded", "offences", "offence", people=False +) def shown_first(figures: Sequence[Figure], wanted: Sequence[str]) -> tuple[str, ...]: diff --git a/src/uk_open_data/analyses/_need.py b/src/uk_open_data/analyses/_need.py index 0ac9d50..0f81331 100644 --- a/src/uk_open_data/analyses/_need.py +++ b/src/uk_open_data/analyses/_need.py @@ -3,8 +3,10 @@ A need measure says where its figures come from, which nations they cover and what they count. The built-in measures come from Nomis, from MHCLG's homelessness tables, from DESNZ's fuel poverty statistics, from DWP's -children in low income families and from UKHSA's childhood vaccinations, whose -figures for upper-tier councils are shared out to councils. Figures are held +children in low income families, from UKHSA's childhood vaccinations, whose +figures for upper-tier councils are shared out to councils, and from ONS's +police recorded crime, whose figures for community safety partnerships are +shared out the same way. Figures are held in memory once fetched, and can be kept as a file on this machine. The helpers here also choose the local authorities an analysis compares and put them in bands by need. @@ -500,9 +502,9 @@ def _offences(measure_id: str, label: str, column: str) -> Measure: origin="ONS", nations=("E", "W"), reason=( - "Police forces record every crime reported to them, and ONS " - "publishes the count for every community safety partnership each " - "quarter." + "Police forces record the crimes reported to them by the Home " + "Office Counting Rules, and ONS publishes the count for every " + "community safety partnership each quarter." ), caveat=_OFFENCES, advice=( @@ -1298,8 +1300,8 @@ def keep_need_figures( ) -> Path: """Keep a need's figures on this machine, so the analysis does not fetch them. - The analysis reads the copy instead of asking Nomis, MHCLG, DESNZ, DWP or - UKHSA, so a server or a demonstration works without the network. The copy + The analysis reads the copy instead of asking Nomis, MHCLG, DESNZ, DWP, + UKHSA or ONS, so a server or a demonstration works without the network. The copy lives in the data folder (see :func:`uk_open_data.postcodes.offline.data_dir`). Args: @@ -1344,9 +1346,9 @@ def download_need_figures(need: str = "unemployed") -> Path: The figures come from where the need says: Nomis for the census needs, MHCLG for the homelessness ones, DESNZ for fuel poverty, DWP for the low - income ones and UKHSA for the vaccination ones. Run this once when a - server is built, and again when new figures are published. Only public - figures are fetched. + income ones, UKHSA for the vaccination ones and ONS for the crime ones. + Run this once when a server is built, and again when new figures are + published. Only public figures are fetched. Args: need: One of the needs the analysis has built in, such as ``unemployed``. diff --git a/src/uk_open_data/analyses/access_distance.py b/src/uk_open_data/analyses/access_distance.py index 904fe14..7b9c128 100644 --- a/src/uk_open_data/analyses/access_distance.py +++ b/src/uk_open_data/analyses/access_distance.py @@ -703,8 +703,8 @@ def _answer( shown = values(figures) who = measure.words.noun first = ( - f"Counting each {measure.words.one} at the centre of their local " - f"authority, {who} " + f"Counting each {measure.words.one} at the centre of " + f"{measure.words.their} local authority, {who} " f"are {number(shown['average_distance_km'])} km from your nearest site " f"on average, and {_share_within(shown)} are within {within:g} km of one." ) diff --git a/src/uk_open_data/analyses/datasets.py b/src/uk_open_data/analyses/datasets.py index 1e6f383..a2d6bbd 100644 --- a/src/uk_open_data/analyses/datasets.py +++ b/src/uk_open_data/analyses/datasets.py @@ -311,7 +311,7 @@ def _kept_for_analyses(source: Source) -> tuple[Callable[[], Path], ...]: Dataset( ONS_POLICE_RECORDED_CRIME, "people", - "Community safety partnerships", + "Community safety partnerships (2025)", ENGLAND_AND_WALES, _NEED, downloads=_kept_for_analyses(ONS_POLICE_RECORDED_CRIME), diff --git a/src/uk_open_data/analyses/need_reach.py b/src/uk_open_data/analyses/need_reach.py index 926507b..2d43f4b 100644 --- a/src/uk_open_data/analyses/need_reach.py +++ b/src/uk_open_data/analyses/need_reach.py @@ -847,7 +847,15 @@ def _by_rate(words: NeedWords) -> tuple[str, str]: def _caveats(words: NeedWords) -> tuple[str, ...]: """What the figures cannot say, in the words that fit the measure.""" - return CAVEATS_FOR_RESIDENTS if words.everyone else CAVEATS + if words.everyone: + return CAVEATS_FOR_RESIDENTS + if words.unit == "people": + return CAVEATS + return ( + *CAVEATS[:-1], + f"Reach sets the people you helped against {words.people}. Read it as " + "more or less reach between places, not as a share of them.", + ) def _map_spec(by_rate: bool, words: NeedWords, rows: list[_Row]) -> MapSpec: @@ -957,7 +965,7 @@ def _figures( _share_in_high_need(rows, high, words, privacy.threshold), Figure( "share_of_need_in_high_need_areas", - f"Share of {words.noun} who live in {words.places}", + f"Share of {words.noun} {words.who} {words.live_in} {words.places}", percent(sum(need[i] for i in high), sum(need)), "percent", note="The comparison for the share of your people.", @@ -1013,14 +1021,17 @@ def _answer( return _answer_for_one_place(overall, words.per) + left_out places = high_need_places(shown["high_need_areas"], words.high) ours = shown["share_of_people_in_high_need_areas"] + # "do" stands for "live in" there. A need that is in a place, not living + # there, such as offences, says what your people do in full. + do = "do" if words.live_in == "live in" else "live there" if ours is None: # The rate across the area is not hidden, so it carries the answer. mine = ( - f"the share of your people who do is {HIDDEN}. Across the area you " + f"the share of your people who {do} is {HIDDEN}. Across the area you " f"reached {number(overall)} people per 100 {words.per}." ) else: - mine = f"{number(ours)}% of your people do." + mine = f"{number(ours)}% of your people {do}." first = look_first(priority, LOWEST, "people_per_100_in_need", overall, words.high) opening = ( f"In the {shown['areas_compared']} local authorities where most of your " @@ -1030,7 +1041,7 @@ def _answer( ) return ( f"{opening}{number(shown['share_of_need_in_high_need_areas'])}% of " - f"{words.people} live in {places}, and {mine}{first}{left_out}" + f"{words.people} {words.live_in} {places}, and {mine}{first}{left_out}" ) diff --git a/src/uk_open_data/analyses/provision_gap.py b/src/uk_open_data/analyses/provision_gap.py index 12101f6..a2a107f 100644 --- a/src/uk_open_data/analyses/provision_gap.py +++ b/src/uk_open_data/analyses/provision_gap.py @@ -827,7 +827,8 @@ def _figures( ), Figure( "share_of_need_in_high_need_areas", - f"Share of {words.noun} who live in those local authorities", + f"Share of {words.noun} {words.who} {words.live_in} those local " + "authorities", percent(sum(need[i] for i in high), sum(need)), "percent", note="Compare this with the share of your provision.", @@ -853,7 +854,7 @@ def _answer(figures: list[Figure], priority: Table, measure: Measure) -> str: ) return ( f"{number(shown['share_of_need_in_high_need_areas'])}% of {words.people} " - f"live in {places}, and " + f"{words.live_in} {places}, and " f"{number(shown['share_of_provision_in_high_need_areas'])}% of your " f"provision is there.{first}" ) diff --git a/src/uk_open_data/crime/api.py b/src/uk_open_data/crime/api.py index accdcc0..4fda6b7 100644 --- a/src/uk_open_data/crime/api.py +++ b/src/uk_open_data/crime/api.py @@ -37,6 +37,7 @@ from uk_open_data import _caches, _govuk, _http from uk_open_data._frames import ( dicts_to_frame, + marked_number_or_none, number_or_none, plain_heading, read_spreadsheet_rows, @@ -60,12 +61,16 @@ BEFORE_OFFENCES = "Local Authority name" # The offences the needs read, so a table that loses one has changed. NEEDED = ("total_recorded_crime", "violence_against_the_person") +# The columns every partnership has before its offences. +FIXED = ("geography_code", "geography_name", "police_force_area", "year") # The notes on the table by partnership. A partnership marked with a note -# that says its offences are recorded as "Unassigned" has none of its own. +# that says its offences are "recorded under an unassigned" group, as ONS +# words it, has none of its own. Other notes mention "unassigned" offences +# without taking a partnership's away. NOTES = "Notes - CSP" NOTE_NUMBER = "Note number" NOTE_TEXT = "Note text" -UNASSIGNED = "unassigned" +UNASSIGNED = "recorded under an unassigned" # Partnerships' codes in England and Wales. Each force's total, and its # "Unassigned" row, have none. PARTNERSHIPS = ("E22", "W14") @@ -124,7 +129,10 @@ def _latest_file() -> tuple[str, str]: if not isinstance(uri, str): raise ValueError(_changed(f"{DATASET_PAGE} lists no edition")) edition = _json(f"{ONS_WEBSITE}{uri}") - year = str(edition.get("description", {}).get("edition") or "") + description = edition.get("description") + named = description.get("edition") if isinstance(description, dict) else None + # As a sentence says it: "year ending June 2026". + year = str(named or "")[:1].lower() + str(named or "")[1:] files = ( str(download.get("file")) for download in _govuk.listed(edition, "downloads") @@ -149,17 +157,13 @@ def _read_partnerships(content: bytes, year: str) -> list[dict[str, Any]]: rows = read_spreadsheet_rows(content, SHEET, HEADER) except ValueError as error: raise ValueError(_changed(f"'{SHEET}' could not be found")) from error - headings = { - plain_heading(heading): heading for heading in (rows[0] if rows else {}) - } + header = list(rows[0]) if rows else [] + plain = [plain_heading(heading) for heading in header] + headings = dict(zip(plain, header, strict=True)) for heading in (FORCE, CODE, NAME, BEFORE_OFFENCES): if heading not in headings: raise ValueError(_changed(f"'{SHEET}' has no column '{heading}'")) - plain = list(headings) - offences = { - _column(heading): headings[heading] - for heading in plain[plain.index(BEFORE_OFFENCES) + 1 :] - } + offences = _offences(plain, header) lost = [column for column in NEEDED if column not in offences] if lost: raise ValueError(_changed(f"'{SHEET}' has no column for {', '.join(lost)}")) @@ -196,7 +200,7 @@ def _partnership( "police_force_area": _unmarked(force), "year": year, } | { - column: None if noted else number_or_none(row[heading]) + column: None if noted else _count(row[heading]) for column, heading in offences.items() } @@ -206,13 +210,42 @@ def _unmarked(text: str) -> str: return " ".join(_MARK.sub("", text).split()) +def _offences(plain: list[str], header: list[str]) -> dict[str, str]: + """Each offence's column, and its heading as the table gives it. + + Raises: + ValueError: If two offences would share a column, or one would have + none, such as when ONS adds a total that includes fraud beside + the one that leaves it out. + """ + start = plain.index(BEFORE_OFFENCES) + 1 + columns = [_column(heading) for heading in plain[start:]] + if len(set(columns)) < len(columns) or "" in columns or set(columns) & set(FIXED): + msg = f"'{SHEET}' has offences whose columns cannot be told apart" + raise ValueError(_changed(msg)) + return dict(zip(columns, header[start:], strict=True)) + + +def _count(cell: Any) -> float | None: + """A cell as a count of offences, or None where it holds none. + + A figure written as text with a mark, such as "1,234 [r]", is read as its + number. ONS notes that a partnership can have a negative number, when a + force moves or cancels offences between years. That is no count, so it is + missing too. + """ + count = marked_number_or_none(cell) + return None if count is None or count < 0 else count + + def _unassigned_notes(content: bytes) -> set[str]: """The marks of the notes that say offences are recorded as "Unassigned". In the year ending June 2026, note 5 says the offences of five Kent - partnerships are recorded under "Unassigned Kent", so this gives + partnerships "are recorded under an unassigned CSP group", so this gives "[note 5]". A note about something else, such as an undercount of one - kind of offence, takes no partnership's figures away. + kind of offence, or more offences than usual left unassigned, takes no + partnership's figures away. """ try: rows = read_spreadsheet_rows(content, NOTES, NOTE_NUMBER) diff --git a/tests/test_crime_api.py b/tests/test_crime_api.py index 761bf70..1367bcb 100644 --- a/tests/test_crime_api.py +++ b/tests/test_crime_api.py @@ -82,7 +82,8 @@ "Cardiff", 3600.0, 1100.0, - 30.0, + # A figure revised after release is text with a mark. + "1,030 [r]", ] MEDWAY = [ "E23000032", @@ -105,7 +106,8 @@ "Newcastle upon Tyne", 2800.0, 900.0, - 40.0, + # A force moved offences out between years: no count. + -3.0, ] ROWS = [FORCE_TOTAL, LEWISHAM, UNASSIGNED, CARDIFF, MEDWAY, NEWCASTLE] # The notes, as ONS words them: note 5 says Medway's offences are recorded as @@ -114,7 +116,12 @@ ["CSP notes"], ["Note number", "Note text"], [1.0, "Caution must be taken when interpreting small numbers of offences."], - [4.0, "Northumbria has an undercount of robbery offences by 24%."], + [ + 4.0, + "Northumbria is improving how it records where crimes happen, so more " + "crime records than usual have an 'unassigned' CSP. Its overall crime " + "figures remain accurate.", + ], [ 5.0, "Due to ongoing IT issues, crime data for Medway are recorded under an " @@ -147,7 +154,7 @@ def _serve( pages = { DATASET_JSON: {"datasets": editions}, EDITION_JSON: { - "description": {"edition": "year ending June 2026"}, + "description": {"edition": "Year ending June 2026"}, "downloads": downloads, }, } @@ -180,21 +187,20 @@ def test_each_partnership_has_its_offences(monkeypatch: pytest.MonkeyPatch) -> N 1000.0, 150.0, ) - assert rows["W14000015"][4:] == (3600.0, 1100.0, 30.0) + assert rows["W14000015"][4:] == (3600.0, 1100.0, 1030.0) # A partnership whose offences ONS notes are recorded as "Unassigned" has # no figures, not its few. medway = table.filter(nw.col("geography_code") == "E22000143") assert medway["police_force_area"].to_list() == ["Kent"] assert medway["total_recorded_crime"].is_null().to_list() == [True] assert medway["violence_against_the_person"].is_null().to_list() == [True] - # A note about something else leaves the figures as they are. - assert rows["E22000185"][2:] == ( - "Northumbria", - "year ending June 2026", - 2800.0, - 900.0, - 40.0, - ) + # A note about something else, even one about unassigned offences, + # leaves the figures as they are. A negative count is no count. + newcastle = table.filter(nw.col("geography_code") == "E22000185") + assert newcastle["police_force_area"].to_list() == ["Northumbria"] + assert newcastle["total_recorded_crime"].to_list() == [2800.0] + assert newcastle["violence_against_the_person"].to_list() == [900.0] + assert newcastle["robbery"].is_null().to_list() == [True] def test_the_latest_edition_is_found_from_the_dataset_page( @@ -221,6 +227,14 @@ def test_the_latest_edition_is_found_from_the_dataset_page( _workbook(sheet="Table C3"), EDITIONS, DOWNLOADS, id="no table C2" ), pytest.param(_workbook(notes="Notes"), EDITIONS, DOWNLOADS, id="no notes"), + pytest.param( + _workbook( + [*HEADER[:7], "Total recorded crime (including fraud)", *HEADER[7:]] + ), + EDITIONS, + DOWNLOADS, + id="two totals", + ), pytest.param( _workbook([*HEADER[:7], "Violence", *HEADER[8:]]), EDITIONS, diff --git a/tests/test_crime_needs.py b/tests/test_crime_needs.py index 2db2fc5..294280a 100644 --- a/tests/test_crime_needs.py +++ b/tests/test_crime_needs.py @@ -198,6 +198,12 @@ def test_a_result_counts_offences_not_people() -> None: "Offences recorded" ) assert any("not people or victims" in caveat for caveat in result.caveats) + # Offences are in places; they do not live there. Your people do. + assert "offences recorded live" not in result.answer + assert "of your people live there." in result.answer + assert result.figure("share_of_need_in_high_need_areas").label == ( + "Share of offences recorded that are in high-need local authorities" + ) cited = [source.id for source in result.sources] assert "ons-police-recorded-crime" in cited assert "ons-local-authority-lookups" in cited diff --git a/tests/test_live_sources.py b/tests/test_live_sources.py index 8ec802c..922fb70 100644 --- a/tests/test_live_sources.py +++ b/tests/test_live_sources.py @@ -141,15 +141,12 @@ def _vaccinations() -> list[int | None]: def _crime() -> list[int | None]: """How many partnerships have each kind of offence, None for one none has. - Both needs' figures are kept too, so an offence renamed is caught. + The loader refuses a table without the offences the needs read, so one + fetch checks both. ONS limits how often it is asked, so it is fetched once. """ table = nw.from_native(crime_api.load_crime(), eager_only=True) offences = table.columns[table.columns.index("year") + 1 :] - return [ - *(table[column].count() or None for column in offences), - *_kept(download_need_figures("recorded_crime"), "figures"), - *_kept(download_need_figures("violence_against_the_person"), "figures"), - ] + return [table[column].count() or None for column in offences] def _council_codes() -> list[str]: