hypercadaster-ES 1.2.2__tar.gz → 1.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. {hypercadaster_es-1.2.2/hypercadaster_es.egg-info → hypercadaster_es-1.3.0}/PKG-INFO +7 -4
  2. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/README.md +3 -2
  3. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/hypercadaster_ES/__init__.py +4 -3
  4. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/hypercadaster_ES/building_inference.py +291 -26
  5. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/hypercadaster_ES/downloaders.py +17 -0
  6. hypercadaster_es-1.3.0/hypercadaster_ES/energy.py +9353 -0
  7. hypercadaster_es-1.3.0/hypercadaster_ES/energy_config.yaml +884 -0
  8. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/hypercadaster_ES/functions.py +42 -9
  9. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/hypercadaster_ES/interoperability.py +1 -1
  10. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/hypercadaster_ES/mergers.py +256 -33
  11. hypercadaster_es-1.3.0/hypercadaster_ES/reporting.py +1476 -0
  12. hypercadaster_es-1.3.0/hypercadaster_ES/social.py +1175 -0
  13. hypercadaster_es-1.3.0/hypercadaster_ES/topology.py +290 -0
  14. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/hypercadaster_ES/utils.py +447 -56
  15. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0/hypercadaster_es.egg-info}/PKG-INFO +7 -4
  16. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/hypercadaster_es.egg-info/SOURCES.txt +12 -1
  17. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/hypercadaster_es.egg-info/requires.txt +3 -1
  18. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/setup.py +6 -2
  19. hypercadaster_es-1.3.0/tests/test_agricultural_archetype.py +68 -0
  20. hypercadaster_es-1.3.0/tests/test_cat_empty_schema.py +81 -0
  21. hypercadaster_es-1.3.0/tests/test_census_tract_aggregations.py +157 -0
  22. hypercadaster_es-1.3.0/tests/test_energy_scenarios.py +3545 -0
  23. hypercadaster_es-1.3.0/tests/test_floorplan_partition.py +609 -0
  24. hypercadaster_es-1.3.0/tests/test_shadow_rules.py +105 -0
  25. hypercadaster_es-1.3.0/tests/test_social.py +338 -0
  26. hypercadaster_es-1.3.0/tests/test_theoretical_cat_spaces.py +129 -0
  27. hypercadaster_es-1.3.0/tests/test_topology.py +78 -0
  28. hypercadaster_es-1.3.0/tests/test_zero_floor_buildings.py +83 -0
  29. hypercadaster_es-1.2.2/hypercadaster_ES/energy.py +0 -3013
  30. hypercadaster_es-1.2.2/hypercadaster_ES/energy_config.yaml +0 -241
  31. hypercadaster_es-1.2.2/hypercadaster_ES/social.py +0 -998
  32. hypercadaster_es-1.2.2/tests/test_social.py +0 -187
  33. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/LICENSE +0 -0
  34. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/MANIFEST.in +0 -0
  35. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/hypercadaster_ES/_db.py +0 -0
  36. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/hypercadaster_ES/_pretty.py +0 -0
  37. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/hypercadaster_ES/cached_files/ine_inspire_codes.xlsx +0 -0
  38. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/hypercadaster_ES/weather.py +0 -0
  39. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/hypercadaster_es.egg-info/dependency_links.txt +0 -0
  40. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/hypercadaster_es.egg-info/top_level.txt +0 -0
  41. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/setup.cfg +0 -0
  42. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/tests/test_aggregation.py +0 -0
  43. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/tests/test_cat_cache.py +0 -0
  44. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/tests/test_code_normalisation.py +0 -0
  45. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/tests/test_codes.py +0 -0
  46. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/tests/test_dem_tiles.py +0 -0
  47. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/tests/test_energy_config.py +0 -0
  48. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/tests/test_geometry.py +0 -0
  49. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/tests/test_import_surface.py +0 -0
  50. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/tests/test_live_smoke.py +0 -0
  51. {hypercadaster_es-1.2.2 → hypercadaster_es-1.3.0}/tests/test_weather.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hypercadaster_es
3
- Version: 1.2.2
3
+ Version: 1.3.0
4
4
  Summary: Python library to obtain the Spanish cadaster data joined with external attributes.
5
5
  Home-page: https://github.com/BeeGroup-cimne
6
6
  Author: Jose Manuel Broto Vispe
@@ -49,6 +49,7 @@ Requires-Dist: et-xmlfile>=1.1
49
49
  Requires-Dist: arrow>=1.4.0
50
50
  Requires-Dist: fastkml>=1.4.0
51
51
  Requires-Dist: lxml>=6.0.2
52
+ Requires-Dist: duckdb>=1.5.3
52
53
  Requires-Dist: requests<3.0,>=2.31
53
54
  Requires-Dist: urllib3<3,>=2.1
54
55
  Requires-Dist: charset-normalizer>=3.3
@@ -63,6 +64,7 @@ Requires-Dist: cycler>=0.12
63
64
  Requires-Dist: kiwisolver>=1.4
64
65
  Requires-Dist: fonttools>=4.53
65
66
  Requires-Dist: pillow>=10.2
67
+ Requires-Dist: folium>=0.20.0
66
68
  Requires-Dist: click>=8.1
67
69
  Requires-Dist: click-plugins>=1.1
68
70
  Requires-Dist: cligj>=0.7
@@ -74,7 +76,7 @@ Requires-Dist: regex<2027.0,>=2023.12
74
76
  Requires-Dist: tqdm>=4.66
75
77
  Requires-Dist: six>=1.16
76
78
  Requires-Dist: PyYAML>=6.0
77
- Requires-Dist: social_ES>=1.0.0
79
+ Requires-Dist: social_ES>=1.0.3
78
80
  Provides-Extra: dev
79
81
  Requires-Dist: black>=24.0; extra == "dev"
80
82
  Requires-Dist: ruff>=0.4; extra == "dev"
@@ -111,7 +113,7 @@ A comprehensive Python library for downloading, processing, and analyzing Spanis
111
113
 
112
114
  - 🏘️ **Comprehensive Cadastral Data Access**: Download building and parcel data from the Spanish Cadastre, and nationwide address points from CartoCiudad (CNIG)
113
115
  - 🗺️ **Multi-source Data Integration**: Merge with census tracts, postal codes, elevation models, and OpenStreetMap data
114
- - 🧮 **Socioeconomic Enrichment**: INE indicators via `social_ES` (income atlas, population, education, rental & housing prices, electricity) joined per building, plus per-building Essential-Characteristics downscaling
116
+ - 🧮 **Socioeconomic Enrichment**: INE indicators via `social_ES` (income atlas, population, education, dwelling stock & tenure, empty & secondary dwellings, rental & housing prices, electricity) joined per building, plus per-building Essential-Characteristics downscaling
115
117
  - 🌦️ **Weather Enrichment**: Annual ERA5-Land climate indicators per building (heating/cooling degree days, precipitation, solar irradiation, temperature, humidity, wind) via `merge(weather_layer=True)`, gathered from the Copernicus analysis-ready (ARCO) Zarr stores
116
118
  - 🏗️ **Advanced Building Analysis**: Geometric inference, floor footprint calculation, building space classification, shadow analysis
117
119
  - 📊 **Orientation & Environmental Analysis**: Building orientation analysis, street relationships, shadow calculations, terrain analysis
@@ -126,6 +128,7 @@ A comprehensive Python library for downloading, processing, and analyzing Spanis
126
128
  - [**Configuration & Examples**](docs/configuration-examples.md) - Advanced configuration and example workflows
127
129
 
128
130
  ### Library Reference
131
+ - [**Energy Model & Scenarios**](docs/energy-model.md) - How the EnergyPlus model is built, the occupant-behaviour model, and the scenarios
129
132
  - [**Library Structure**](docs/library-structure.md) - Module overview and key entry points
130
133
  - [**Data Sources & Coverage**](docs/data-sources-coverage.md) - Available datasets and geographic coverage
131
134
  - [**Output Data Schema**](docs/output-schema.md) - Complete data structure and column reference
@@ -197,7 +200,7 @@ For detailed installation instructions and advanced examples, see [Installation
197
200
  - **CAT Files Support**: Detailed building space classification from official cadastral CAT format
198
201
  - **Energy Simulation Ready**: Export formats compatible with building energy simulation tools (EnergyPlus IDF via hc.energy.build_energy_model)
199
202
  - **POI Proximity Analysis**: Points of interest from OpenStreetMap with distance-based indicators
200
- - **Socioeconomic Layer**: INE indicators via `social_ES` joined at the finest geographic level (`merge(social_ES_layer=True)`), with English-keyed `ec__*` Essential-Characteristics downscaling when CAT files are used
203
+ - **Socioeconomic Layer**: INE indicators via `social_ES` joined at the finest geographic level (`merge(social_ES_layer=True)`), each figure taken from a single source dataset, with `ec__*` Essential-Characteristics downscaling when CAT files are used
201
204
  - **Weather Layer**: Annual ERA5-Land climate indicators per building (`merge(weather_layer=True)`) — degree days, precipitation, irradiation, temperature, humidity, wind — via the Copernicus analysis-ready (ARCO) Zarr stores with `cdsapi` fallback
202
205
  - **Commercial Premises Analysis**: Barcelona-specific ground floor commercial data
203
206
 
@@ -14,7 +14,7 @@ A comprehensive Python library for downloading, processing, and analyzing Spanis
14
14
 
15
15
  - 🏘️ **Comprehensive Cadastral Data Access**: Download building and parcel data from the Spanish Cadastre, and nationwide address points from CartoCiudad (CNIG)
16
16
  - 🗺️ **Multi-source Data Integration**: Merge with census tracts, postal codes, elevation models, and OpenStreetMap data
17
- - 🧮 **Socioeconomic Enrichment**: INE indicators via `social_ES` (income atlas, population, education, rental & housing prices, electricity) joined per building, plus per-building Essential-Characteristics downscaling
17
+ - 🧮 **Socioeconomic Enrichment**: INE indicators via `social_ES` (income atlas, population, education, dwelling stock & tenure, empty & secondary dwellings, rental & housing prices, electricity) joined per building, plus per-building Essential-Characteristics downscaling
18
18
  - 🌦️ **Weather Enrichment**: Annual ERA5-Land climate indicators per building (heating/cooling degree days, precipitation, solar irradiation, temperature, humidity, wind) via `merge(weather_layer=True)`, gathered from the Copernicus analysis-ready (ARCO) Zarr stores
19
19
  - 🏗️ **Advanced Building Analysis**: Geometric inference, floor footprint calculation, building space classification, shadow analysis
20
20
  - 📊 **Orientation & Environmental Analysis**: Building orientation analysis, street relationships, shadow calculations, terrain analysis
@@ -29,6 +29,7 @@ A comprehensive Python library for downloading, processing, and analyzing Spanis
29
29
  - [**Configuration & Examples**](docs/configuration-examples.md) - Advanced configuration and example workflows
30
30
 
31
31
  ### Library Reference
32
+ - [**Energy Model & Scenarios**](docs/energy-model.md) - How the EnergyPlus model is built, the occupant-behaviour model, and the scenarios
32
33
  - [**Library Structure**](docs/library-structure.md) - Module overview and key entry points
33
34
  - [**Data Sources & Coverage**](docs/data-sources-coverage.md) - Available datasets and geographic coverage
34
35
  - [**Output Data Schema**](docs/output-schema.md) - Complete data structure and column reference
@@ -100,7 +101,7 @@ For detailed installation instructions and advanced examples, see [Installation
100
101
  - **CAT Files Support**: Detailed building space classification from official cadastral CAT format
101
102
  - **Energy Simulation Ready**: Export formats compatible with building energy simulation tools (EnergyPlus IDF via hc.energy.build_energy_model)
102
103
  - **POI Proximity Analysis**: Points of interest from OpenStreetMap with distance-based indicators
103
- - **Socioeconomic Layer**: INE indicators via `social_ES` joined at the finest geographic level (`merge(social_ES_layer=True)`), with English-keyed `ec__*` Essential-Characteristics downscaling when CAT files are used
104
+ - **Socioeconomic Layer**: INE indicators via `social_ES` joined at the finest geographic level (`merge(social_ES_layer=True)`), each figure taken from a single source dataset, with `ec__*` Essential-Characteristics downscaling when CAT files are used
104
105
  - **Weather Layer**: Annual ERA5-Land climate indicators per building (`merge(weather_layer=True)`) — degree days, precipitation, irradiation, temperature, humidity, wind — via the Copernicus analysis-ready (ARCO) Zarr stores with `cdsapi` fallback
105
106
  - **Commercial Premises Analysis**: Barcelona-specific ground floor commercial data
106
107
 
@@ -24,9 +24,9 @@ Examples:
24
24
  from .functions import download, merge
25
25
  from ._db import ResultsHandle
26
26
  from . import (mergers, utils, building_inference, downloaders, interoperability,
27
- energy, weather, social)
27
+ energy, weather, social, topology, reporting)
28
28
 
29
- __version__ = "1.2.2"
29
+ __version__ = "1.3.0"
30
30
  __author__ = "Jose Manuel Broto Vispe"
31
31
  __email__ = "jmbrotovispe@gmail.com"
32
32
 
@@ -38,5 +38,6 @@ __all__ = [
38
38
  # Top-level API
39
39
  "download", "merge", "ResultsHandle",
40
40
  # Submodules (this order drives the API-docs index)
41
- "downloaders", "energy", "interoperability", "mergers", "social", "utils", "weather",
41
+ "downloaders", "energy", "interoperability", "mergers", "reporting", "social",
42
+ "topology", "utils", "weather",
42
43
  ]
@@ -334,6 +334,64 @@ def _safe_nanmean(values):
334
334
  return float(finite.mean()) if finite.size else float("nan")
335
335
 
336
336
 
337
+ # The taller ``ground_floor_height`` is used only for buildings with at least this
338
+ # many floors above ground (matching ``energy._GROUND_FLOOR_MIN_FLOORS``); smaller
339
+ # buildings use the regular ``floor_height`` for the ground storey too. Applied to
340
+ # the analysed building's shadow eye levels and wall-typing floor elevations.
341
+ GROUND_FLOOR_MIN_FLOORS = 5
342
+
343
+ # A wall segment is typed ``terrain_contact`` only when at least this fraction of
344
+ # its AREA (length × storey height) sits below the terrain surface (DEM). Sampled
345
+ # along the segment; below-ground floors are always terrain contact.
346
+ TERRAIN_CONTACT_MIN_FRACTION = 0.75
347
+
348
+
349
+ def _effective_ground_floor_height(n_floors_above_ground, ground_floor_height,
350
+ floor_height, building_use=None):
351
+ """``ground_floor_height`` when the building has >= GROUND_FLOOR_MIN_FLOORS
352
+ floors above ground OR is an industrial/agricultural building (which always
353
+ needs the taller ground storey for machinery/vehicle clearance); else
354
+ ``floor_height``."""
355
+ try:
356
+ n = int(n_floors_above_ground)
357
+ except (TypeError, ValueError):
358
+ n = 0
359
+ if n >= GROUND_FLOOR_MIN_FLOORS or utils.is_tall_ground_floor_use(building_use):
360
+ return ground_floor_height
361
+ return floor_height
362
+
363
+
364
+ def _wall_buried_area_fraction(segment, dem_sampler, floor_base_elev, floor_top_elev):
365
+ """Fraction of a wall segment's AREA (length × storey height) that sits below
366
+ the terrain surface. The DEM is sampled along the segment; at each sample the
367
+ buried fraction of the wall height is ``clamp((terrain − floor_base) /
368
+ (floor_top − floor_base), 0, 1)`` and the mean over the length is the buried
369
+ area fraction (0 = terrain at/below the floor base everywhere, 1 = terrain
370
+ at/above the floor top everywhere). Returns 0.0 when the DEM can't be sampled.
371
+ """
372
+ span = max(floor_top_elev - floor_base_elev, 1e-6)
373
+ n = max(3, int(segment.length) + 1)
374
+ xs, ys = [], []
375
+ for t in np.linspace(0.0, 1.0, n):
376
+ p = segment.interpolate(float(t), normalized=True)
377
+ xs.append(p.x)
378
+ ys.append(p.y)
379
+ try:
380
+ elevs = dem_sampler(xs, ys)
381
+ except Exception:
382
+ return 0.0
383
+ fracs = []
384
+ for e in elevs:
385
+ try:
386
+ fe = float(e)
387
+ except (TypeError, ValueError):
388
+ continue
389
+ if math.isnan(fe):
390
+ continue
391
+ fracs.append(min(max((fe - floor_base_elev) / span, 0.0), 1.0))
392
+ return (sum(fracs) / len(fracs)) if fracs else 0.0
393
+
394
+
337
395
  # Per-space CAT columns that leak into br_results in multi-building zones
338
396
  # as all-NaN `_x` / `_y` pairs from an unintended merge. Strip them so the
339
397
  # building-level output stays at the building grain.
@@ -1666,6 +1724,19 @@ def process_zone(gdf_zone, zone_reference, gdf_footprints_global, parcels_gdf, s
1666
1724
  else:
1667
1725
  current_building_elevation = 0.0
1668
1726
 
1727
+ # Taller ground floor for buildings with >= 5 floors above ground OR
1728
+ # industrial/agricultural buildings (the same rule as the EnergyPlus
1729
+ # model); used for this building's shadow eye levels and wall-typing
1730
+ # floor elevations.
1731
+ _n_ag_bld = (building_gdf_item['n_floors_above_ground']
1732
+ if 'n_floors_above_ground' in building_gdf_item.columns else 0)
1733
+ _bld_use = (building_gdf_item['building_use'].iloc[0]
1734
+ if 'building_use' in building_gdf_item.columns
1735
+ and len(building_gdf_item) else None)
1736
+ eff_ground_floor_height = _effective_ground_floor_height(
1737
+ utils._coerce_scalar_float(_n_ag_bld, 0.0),
1738
+ ground_floor_height, floor_height, _bld_use)
1739
+
1669
1740
  # Per-adjacent-sbr roof elevation. `gdf_aux_footprints_` was
1670
1741
  # filtered above to the buildings touching ours; elevation
1671
1742
  # lives on `gdf_zone` rows keyed by single_building_reference.
@@ -1817,12 +1888,12 @@ def process_zone(gdf_zone, zone_reference, gdf_footprints_global, parcels_gdf, s
1817
1888
  # - floor_top_elev: top-of-slab elevation, used by the
1818
1889
  # terrain_contact below-DEM test.
1819
1890
  if floor == 0:
1820
- eye_level_floor = current_building_elevation + ground_floor_height / 2.0
1821
- floor_top_elev = current_building_elevation + ground_floor_height
1891
+ eye_level_floor = current_building_elevation + eff_ground_floor_height / 2.0
1892
+ floor_top_elev = current_building_elevation + eff_ground_floor_height
1822
1893
  elif floor > 0:
1823
- eye_level_floor = (current_building_elevation + ground_floor_height
1894
+ eye_level_floor = (current_building_elevation + eff_ground_floor_height
1824
1895
  + (floor - 0.5) * floor_height)
1825
- floor_top_elev = (current_building_elevation + ground_floor_height
1896
+ floor_top_elev = (current_building_elevation + eff_ground_floor_height
1826
1897
  + floor * floor_height)
1827
1898
  else:
1828
1899
  # Below ground: floor -1 spans [elev - fh, elev],
@@ -1835,7 +1906,7 @@ def process_zone(gdf_zone, zone_reference, gdf_footprints_global, parcels_gdf, s
1835
1906
  # height (not just floor 0) to shelter this wall.
1836
1907
  floor_base_elev = utils.floor_base_elevation(
1837
1908
  current_building_elevation, floor,
1838
- ground_floor_height, floor_height)
1909
+ eff_ground_floor_height, floor_height)
1839
1910
 
1840
1911
  for geom in walls:
1841
1912
 
@@ -1911,23 +1982,23 @@ def process_zone(gdf_zone, zone_reference, gdf_footprints_global, parcels_gdf, s
1911
1982
  segment_assigned = "patios"
1912
1983
  break
1913
1984
 
1914
- # 2. TERRAIN_CONTACT — basement OR midpoint
1915
- # below the floor's top-of-slab per DEM.
1985
+ # 2. TERRAIN_CONTACT — basement, OR at least
1986
+ # TERRAIN_CONTACT_MIN_FRACTION of the wall's AREA
1987
+ # (length × storey height) sits below the terrain.
1988
+ # The DEM is sampled along the segment; at each
1989
+ # sample the buried height fraction is
1990
+ # clamp((terrain − floor_base)/(floor_top −
1991
+ # floor_base), 0, 1) and the mean over the length
1992
+ # is the buried AREA fraction.
1916
1993
  if segment_assigned is None:
1917
1994
  is_terrain = False
1918
1995
  if floor < 0:
1919
1996
  is_terrain = True
1920
1997
  elif dem_sampler is not None:
1921
- mid = segment.interpolate(0.5, normalized=True)
1922
- try:
1923
- terrain_elev = float(
1924
- dem_sampler([mid.x], [mid.y])[0]
1925
- )
1926
- except (TypeError, ValueError, Exception):
1927
- terrain_elev = None
1928
- if (terrain_elev is not None
1929
- and not math.isnan(terrain_elev)
1930
- and terrain_elev > floor_top_elev):
1998
+ if _wall_buried_area_fraction(
1999
+ segment, dem_sampler,
2000
+ floor_base_elev, floor_top_elev
2001
+ ) >= TERRAIN_CONTACT_MIN_FRACTION:
1931
2002
  is_terrain = True
1932
2003
  if is_terrain:
1933
2004
  terrain_contact_wall[floor] += round(segment.length, 2)
@@ -2272,9 +2343,9 @@ def process_zone(gdf_zone, zone_reference, gdf_footprints_global, parcels_gdf, s
2272
2343
  # ground-floor height; eye = DEM + g/2. Upper floors
2273
2344
  # are floor_height tall; eye = DEM + g + (f - 0.5) * h.
2274
2345
  if floor == 0:
2275
- eye_level = current_building_elevation + ground_floor_height / 2.0
2346
+ eye_level = current_building_elevation + eff_ground_floor_height / 2.0
2276
2347
  else:
2277
- eye_level = (current_building_elevation + ground_floor_height
2348
+ eye_level = (current_building_elevation + eff_ground_floor_height
2278
2349
  + (floor - 0.5) * floor_height)
2279
2350
 
2280
2351
  # Only consider neighbours that exist at this floor for
@@ -2849,13 +2920,15 @@ def process_zone(gdf_zone, zone_reference, gdf_footprints_global, parcels_gdf, s
2849
2920
  # is a pandas DataFrame here (sliced for this zone
2850
2921
  # in process_building_parts so workers stay polars-
2851
2922
  # free and can run under `fork` safely). Reuse the
2852
- # aggregation cached during floor synthesis.
2853
- agg_CAT = _agg_CAT_cache.get(building_reference)
2923
+ # aggregation cached during floor synthesis, which
2924
+ # returns None for buildings with no CAT rows at all
2925
+ # (rural parcels, undeveloped "solares"). Their empty
2926
+ # aggregation still carries the full column schema, so
2927
+ # the br__/sbr__ columns come out NaN for them instead
2928
+ # of going missing and taking the whole zone down.
2929
+ agg_CAT = _get_agg_CAT(building_reference)
2854
2930
  if agg_CAT is None:
2855
- agg_CAT = aggregate_CAT_file_building_spaces(
2856
- building_CAT_df=buildings_CAT[
2857
- buildings_CAT["building_reference"] == building_reference
2858
- ])
2931
+ agg_CAT = aggregate_CAT_file_building_spaces(None)
2859
2932
 
2860
2933
  building_gdf_by_floor = building_gdf_by_floor.drop(columns="geometry")
2861
2934
 
@@ -3402,6 +3475,71 @@ def parse_horizontal_division_buildings_CAT_files(cadaster_code, CAT_files_dir):
3402
3475
  return building_spaces_detailed
3403
3476
 
3404
3477
 
3478
+ # Column schema (name -> dtype) of the two frames
3479
+ # ``aggregate_CAT_file_building_spaces`` returns. Needed explicitly because
3480
+ # pandas' ``groupby(...).apply(...)`` never invokes the aggregation function on
3481
+ # an empty frame and passes the *input* columns through instead — so a building
3482
+ # with no CAT record (rural parcels, undeveloped "solares") would otherwise
3483
+ # yield frames without any ``br__`` column and blow up the whole cadastral zone
3484
+ # downstream. Dtypes are declared so an empty frame stays concat-compatible
3485
+ # with a populated one instead of degrading numeric columns to ``object``.
3486
+ # ``tests/test_cat_empty_schema.py`` pins these against the non-empty output.
3487
+ _AGG_CAT_BY_FLOORS_SCHEMA = {
3488
+ "floor_number": "Int32",
3489
+ "use_type": object,
3490
+ "building_reference": object,
3491
+ "br__building_spaces_by_floor": "int64",
3492
+ "br__mean_building_space_area_with_communals_by_floor": float,
3493
+ "br__mean_building_space_area_without_communals_by_floor": float,
3494
+ "br__mean_building_space_communal_area_by_floor": float,
3495
+ "br__mean_building_space_effective_year_by_floor": float,
3496
+ "br__mean_building_space_category_by_floor": float,
3497
+ "br__mean_building_space_economic_value_by_floor": float,
3498
+ "br__area_with_communals_by_floor": float,
3499
+ "br__area_without_communals_by_floor": float,
3500
+ "br__communal_area_by_floor": float,
3501
+ "br__economic_value_by_floor": float,
3502
+ "br__relative_area_with_communals_by_floor": float,
3503
+ "br__relative_area_without_communals_by_floor": float,
3504
+ "br__relative_communal_area_by_floor": float,
3505
+ }
3506
+
3507
+ _AGG_CAT_BUILDING_SCHEMA = {
3508
+ "use_type": object,
3509
+ "building_reference": object,
3510
+ "br__building_spaces": "int64",
3511
+ "br__floors": object,
3512
+ "br__mean_building_space_area_with_communals": float,
3513
+ "br__mean_building_space_area_without_communals": float,
3514
+ "br__mean_building_space_communal_area": float,
3515
+ "br__mean_building_space_effective_year": float,
3516
+ "br__mean_building_space_category": float,
3517
+ "br__mean_building_space_economic_value": float,
3518
+ "br__area_with_communals": float,
3519
+ "br__area_without_communals": float,
3520
+ "br__communal_area": float,
3521
+ "br__economic_value": float,
3522
+ "br__relative_area_with_communals": float,
3523
+ "br__relative_area_without_communals": float,
3524
+ "br__relative_communal_area": float,
3525
+ "br__building_spaces_reference": object,
3526
+ "br__building_spaces_postal_address": object,
3527
+ "br__building_spaces_inner_address": object,
3528
+ "br__building_spaces_floor_number": object,
3529
+ "br__building_spaces_floors": object,
3530
+ "br__building_spaces_category": object,
3531
+ "br__building_spaces_effective_year": object,
3532
+ "br__building_spaces_area_without_communal": object,
3533
+ "br__building_spaces_area_with_communal": object,
3534
+ "br__building_spaces_economic_value": object,
3535
+ "br__building_spaces_detailed_use_type": object,
3536
+ }
3537
+
3538
+
3539
+ def _empty_frame(schema):
3540
+ return pd.DataFrame({col: pd.Series(dtype=dt) for col, dt in schema.items()})
3541
+
3542
+
3405
3543
  def aggregate_CAT_file_building_spaces(building_CAT_df):
3406
3544
  """
3407
3545
  Aggregate building space information from CAT file data.
@@ -3419,7 +3557,14 @@ def aggregate_CAT_file_building_spaces(building_CAT_df):
3419
3557
  --------
3420
3558
  dict[str, pandas.DataFrame]
3421
3559
  ``{"by_floors": ..., "building": ...}`` — both pandas DataFrames.
3560
+ Empty input yields empty frames carrying the full column schema.
3422
3561
  """
3562
+ if building_CAT_df is None or len(building_CAT_df) == 0:
3563
+ return {
3564
+ "by_floors": _empty_frame(_AGG_CAT_BY_FLOORS_SCHEMA),
3565
+ "building": _empty_frame(_AGG_CAT_BUILDING_SCHEMA),
3566
+ }
3567
+
3423
3568
  df = building_CAT_df.copy()
3424
3569
 
3425
3570
  # Raw classify outputs include fractional markers (0.5 for ground floor,
@@ -3624,7 +3769,7 @@ def aggregate_CAT_file_building_spaces(building_CAT_df):
3624
3769
  }
3625
3770
 
3626
3771
 
3627
- _NON_OCCUPIED_USE_KEYS = ("parking", "warehouse", "storage", "garage")
3772
+ _NON_OCCUPIED_USE_KEYS = ("parking", "warehouse", "storage", "garage", "agriculture")
3628
3773
 
3629
3774
 
3630
3775
  def _synthesize_thermal_zones(row):
@@ -3879,6 +4024,126 @@ def br_attributes_from_CAT(buildings_CAT):
3879
4024
  return out
3880
4025
 
3881
4026
 
4027
+ # Cadaster ``currentUse`` (INSPIRE Building layer) -> CAT inferred use type.
4028
+ # Only used to give a theoretical building space the building's main usage;
4029
+ # "Agricultural" mirrors the CAT 'Z' code already mapped in ``downloaders``,
4030
+ # and a missing usage falls back to "Unknown" (the bucket the area pivot in
4031
+ # ``mergers`` already uses for null use types).
4032
+ _CADASTER_USE_TO_CAT_USE = {
4033
+ "1_residential": "Residential",
4034
+ "2_agriculture": "Agricultural",
4035
+ "3_industrial": "Industrial",
4036
+ "4_1_office": "Offices",
4037
+ "4_2_retail": "Commercial",
4038
+ "4_3_publicServices": "Singular building",
4039
+ }
4040
+ _THEORETICAL_UNKNOWN_USE = "Unknown"
4041
+
4042
+
4043
+ def add_theoretical_CAT_spaces(buildings_CAT, building_gdf, cadaster_code):
4044
+ """Give buildings absent from the CAT file a single theoretical space.
4045
+
4046
+ Rural/agricultural buildings exist in the INSPIRE Building layer but carry
4047
+ no CAT construction record, so they have no building spaces at all: every
4048
+ CAT-derived ``br__*`` column comes out NaN, ``br__thermal_zones`` is empty
4049
+ and no energy model can be built for them (1426 of 13619 buildings in
4050
+ Lleida — mostly ``2_agriculture``).
4051
+
4052
+ For each such building this appends one theoretical space to
4053
+ ``buildings_CAT`` carrying the building's main usage, so the whole CAT
4054
+ pipeline (area pivot, ``br__*`` aggregation, thermal zoning, EnergyPlus)
4055
+ treats it like any other single-space building:
4056
+
4057
+ - ``building_space_reference`` == ``building_reference`` (the building *is*
4058
+ its only space);
4059
+ - use type mapped from the cadaster ``building_use`` via
4060
+ ``_CADASTER_USE_TO_CAT_USE``, defaulting to ``"Unknown"``;
4061
+ - area from the cadaster's own official built area (``building_area``),
4062
+ which equals the CAT total built area across floors for buildings that
4063
+ do have CAT data, falling back to the footprint area when it is absent
4064
+ or zero. All of it is private area (no communals);
4065
+ - effective year from ``year_of_construction`` so the energy archetypes
4066
+ still have an age to work with.
4067
+
4068
+ Only the undeveloped-parcel supplements ("solares", added later in
4069
+ ``mergers`` from CAT dataset 15) are left alone — they have no geometry and
4070
+ are not buildings.
4071
+
4072
+ Parameters
4073
+ ----------
4074
+ buildings_CAT : polars.DataFrame or None
4075
+ Per-space CAT rows; returned unchanged when None.
4076
+ building_gdf : geopandas.GeoDataFrame
4077
+ The INSPIRE Building layer (``building_reference``, ``building_use``,
4078
+ ``building_area``, ``year_of_construction`` + geometry).
4079
+ cadaster_code : str
4080
+ Municipality code, written to the synthetic rows' ``cadaster_code``.
4081
+
4082
+ Returns
4083
+ -------
4084
+ polars.DataFrame
4085
+ ``buildings_CAT`` with the theoretical spaces appended.
4086
+ """
4087
+ if buildings_CAT is None or building_gdf is None or len(building_gdf) == 0:
4088
+ return buildings_CAT
4089
+
4090
+ known = set(buildings_CAT["building_reference"].unique().to_list())
4091
+ missing = building_gdf[~building_gdf["building_reference"].isin(known)]
4092
+ missing = missing[missing["building_reference"].notna()]
4093
+ if missing.empty:
4094
+ return buildings_CAT
4095
+
4096
+ # Official built area (already summed over floors); fall back to the
4097
+ # footprint when the cadaster leaves it null or zero.
4098
+ area = pd.to_numeric(missing.get("building_area"), errors="coerce")
4099
+ fallback = missing.geometry.area
4100
+ area = area.where(area.notna() & (area > 0), fallback).astype(float)
4101
+
4102
+ use = (missing["building_use"] if "building_use" in missing.columns
4103
+ else pd.Series(index=missing.index, dtype=object))
4104
+ use = use.map(lambda v: _CADASTER_USE_TO_CAT_USE.get(v, _THEORETICAL_UNKNOWN_USE)
4105
+ if v is not None and not (isinstance(v, float) and math.isnan(v))
4106
+ else _THEORETICAL_UNKNOWN_USE)
4107
+
4108
+ # None (not NaN) for the buildings with no construction year, so the value
4109
+ # casts cleanly into CAT's integer year columns.
4110
+ year = pd.to_numeric(missing.get("year_of_construction"), errors="coerce")
4111
+ year = [None if pd.isna(v) else int(v) for v in year]
4112
+
4113
+ refs = missing["building_reference"].astype(str).tolist()
4114
+ rows = pl.DataFrame({
4115
+ "building_reference": refs,
4116
+ # The building is its own single space.
4117
+ "building_space_reference": refs,
4118
+ # A real address is needed: the per-address floor compaction in
4119
+ # aggregate_CAT_file_building_spaces groups on it and would drop the
4120
+ # row (and lose its floor number) on a null key.
4121
+ "building_space_address": refs,
4122
+ "building_space_floor_name": ["00"] * len(refs),
4123
+ "building_space_year": year,
4124
+ "building_space_effective_year": year,
4125
+ "building_space_total_area": area.to_numpy(),
4126
+ "building_space_total_area_without_communal": area.to_numpy(),
4127
+ "building_space_area_with_communal": area.to_numpy(),
4128
+ "building_space_area_without_communal": area.to_numpy(),
4129
+ "building_space_communal_area": [0.0] * len(refs),
4130
+ "building_spaces_considered": [1] * len(refs),
4131
+ "building_space_use_type": use.tolist(),
4132
+ "building_space_detailed_use_type": use.tolist(),
4133
+ "building_space_inferred_use_type": use.tolist(),
4134
+ "cadaster_code": [str(cadaster_code)] * len(refs),
4135
+ })
4136
+
4137
+ # Match the CAT schema exactly: null out the columns we do not synthesize
4138
+ # and restore column order/dtypes so the concat is a plain vertical append.
4139
+ for col, dtype in buildings_CAT.schema.items():
4140
+ if col not in rows.columns:
4141
+ rows = rows.with_columns(pl.lit(None).cast(dtype).alias(col))
4142
+ rows = rows.select(buildings_CAT.columns).cast(dict(buildings_CAT.schema))
4143
+
4144
+ return pl.concat([buildings_CAT, rows], how="vertical")
4145
+
4146
+
3882
4147
  def undeveloped_parcels_from_CAT(cadaster_code, CAT_files_dir):
3883
4148
  """Recover minimal CAT area rows for undeveloped parcels ("solares").
3884
4149
 
@@ -2126,6 +2126,23 @@ def normalize_cartociudad_street_type(value):
2126
2126
  if first in _STREET_TYPE_UNKNOWN_CODES:
2127
2127
  return None
2128
2128
  return first
2129
+
2130
+
2131
+ def strip_street_type(address):
2132
+ """Drop the leading street-TYPE token(s) (CALLE, AVENIDA, CARRER, URBANIZACION,
2133
+ …) from an address so the street NAME drives comparison — the CAT per-space
2134
+ address and the CartoCiudad parcel label often disagree on the type prefix
2135
+ (``CALLE URBANIZACION DEVESA PARK`` vs ``URBANIZACION DEVESA PARK``), which
2136
+ should not block their harmonisation. Keeps everything after the type(s).
2137
+ Returns the upper-cased remainder (empty string when nothing is left)."""
2138
+ if not address:
2139
+ return ""
2140
+ tokens = " ".join(str(address).upper().split()).split()
2141
+ while tokens and _resolve_street_type_token(tokens[0]) is not None:
2142
+ tokens.pop(0)
2143
+ return " ".join(tokens)
2144
+
2145
+
2129
2146
  """Cadastral two-letter street-type acronym → full Spanish literal."""
2130
2147
 
2131
2148
  # 16 - Registro de reparto de elementos comunes