Zones¶
Obtain the geographic context for mobility observations:
Zone geometries as a GeoDataFrame indexed by zone ID.
Zone names and populations where supplied by MITMA.
Official territorial relation tables.
Verified mappings for aggregation and derived provincial geometries.
Use Mobility to download flows using the same zoning level and source version.
Missing name or population metadata does not remove a zone’s geometry. If a processed GeoJSON was cached using incomplete metadata before this correction, regenerate that file from the source tables to recover omitted zones.
- class pyspainmobility.zones.zones.Zones(zones: str = 'municipalities', version: int = 2, output_directory: str = None)[source]¶
- __init__(zones: str = 'municipalities', version: int = 2, output_directory: str = None)[source]¶
Class to handle the zoning related to the Spanish big mobility data. The class is used to download the data and process it. Selectable granularities are districts (distritos), municipalities (municipios) and large urban areas (grandes áreas urbanas). As a reminder, mobility data for the COVID-19 period (version 1) are not available for the large urban areas.
- Parameters:
zones (str) – The zones to download the data for. Default is municipalities. Zones must be one of the following: districts, dist, distr, distritos, municipalities, muni, municipal, municipios, lua, large_urban_areas, gau, gaus, grandes_areas_urbanas
provincesdissolves mapped district geometries, excluding zones without a unique province. These are derived MITMA geometries; exclusions and geometry repairs are recorded in resultattrs.version (int) – The version of the data to download. Default is 2. Version must be 1 or 2. Version 1 contains the data from 2020 to 2021. Version 2 contains the data from 2022 onwards.
output_directory (str) – The directory to save the raw data and the processed parquet. Default is None. If not specified, the data will be saved in a folder named ‘data’ in user’s home directory.
Examples
>>> from pyspainmobility import Zones >>> # instantiate the object >>> zones = Zones(zones='municipalities', version=2, output_directory='data') >>> # get the geodataframe with the zones >>> gdf = zones.get_zone_geodataframe() >>> print(gdf.head()) name population ID 01001 Alegría-Dulantzi 2925.0 01002 Amurrio 10307.0 01004_AM Artziniega agregacion de municipios 3005.0 01009_AM Asparrena agregacion de municipios 4599.0
- get_zone_geodataframe()[source]¶
Function that returns the geodataframe with the zones. The geodataframe contains the following columns: - id: the id of the zone - name: the name of the zone - population: the population of the zone (if available)
Examples
>>> from pyspainmobility import Zones >>> # instantiate the object >>> zones = Zones(zones='municipalities', version=2, output_directory='data') >>> # get the geodataframe with the zones >>> gdf = zones.get_zone_geodataframe() >>> print(gdf.head()) name population ID 01001 Alegría-Dulantzi 2925.0 01002 Amurrio 10307.0 01004_AM Artziniega agregacion de municipios 3005.0 01009_AM Asparrena agregacion de municipios 4599.0
- get_zone_relations()[source]¶
Return official mapping tables between INE administrative units and MITMA zoning identifiers.
For version 2, the returned table includes one row per relation entry with harmonized column names. For version 1, the method returns one row per MITMA zone id, where each relation column contains the set of linked INE identifiers.
- Parameters:
None
- Returns:
Relation table between census/municipality identifiers and MITMA zoning identifiers.
- Return type:
Examples
>>> from pyspainmobility import Zones >>> zones = Zones(zones='municipalities', version=2, output_directory='data') >>> rel = zones.get_zone_relations() >>> rel.columns.tolist() ['census_sections', 'census_districts', 'municipalities', 'municipalities_mitma', 'districts_mitma', 'luas_mitma']
- get_network_mapping(source_column: str, target_column: str, source_ids=None) DataFrame[source]¶
Return a verified, deterministic mapping for network aggregation.
The official relationship file can contain several rows for one source zone. Repeated identical pairs are harmless and are removed; two distinct targets for the same source are ambiguous and raise a
ValueError. This prevents an aggregation from silently choosing an arbitrary territorial correspondence.- Parameters:
source_column (str) – Column names returned by
get_zone_relations().target_column (str) – Column names returned by
get_zone_relations().source_ids (iterable, optional) – IDs occurring in the OD/network being aggregated. When supplied, the output is restricted to these IDs and missing correspondences are reported before any flow is transformed.
- Returns:
Two string columns,
source_idandtarget_id, sorted bysource_id. It is accepted directly bypyspainmobility.network.aggregate_network()andpyspainmobility.network.aggregate_od_network().- Return type:
- get_province_mapping(source_column: str | None = None, municipality_column: str = 'municipalities', source_ids=None, *, unmapped: str = 'raise') DataFrame[source]¶
Map MITMA zones to Spanish provinces through INE municipality IDs.
Province geometries are not a native
Zoneslevel. Spanish INE municipality identifiers have five digits and their first two digits identify the province. This helper exposes that hierarchy as a validatedsource_id/target_idmapping, wheretarget_idis the two-digit INE province code.By default, the source column matches this object’s selected zoning level (
idfor version 1). A zone may contain several municipalities when all belong to the same province. Missing or invalid municipality codes and zones spanning multiple provinces raise instead of splitting their flow. Version-1 sets of municipality IDs are supported. Code validation checks the five-digit format and province prefix 01–52, not historical municipality registry membership.unmapped='exclude'omits entire sources with absent, invalid, or ambiguous relations and lists them inattrs['unmapped_source_ids']. The defaultunmapped='raise'retains strict mapping validation. ForZones(zones='provinces')this maps the underlying district IDs.
Derived province geometries¶
from pyspainmobility import Zones
zones = Zones(zones="provinces", version=2)
provinces = zones.get_zone_geodataframe()
print(provinces.index)
print(provinces.attrs["unmapped_source_ids"])
Province geometries are dissolved from mapped district geometries. They represent derived MITMA territories rather than official province boundaries.
The string
idindex contains two-digit INE province codes. CRS is preserved.Result
attrsreport excluded source zones and repaired source geometries.get_province_mapping()checks that every municipality in a source zone belongs to one province. Missing or cross-province relations raise by default;unmapped="exclude"omits entire unmappable zones and reports their IDs.Municipality code validation checks the five-digit format and province prefix 01–52, without checking historical municipality registry membership.