hypercadaster-ES 1.2.2__tar.gz → 1.2.3__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 (40) hide show
  1. {hypercadaster_es-1.2.2/hypercadaster_es.egg-info → hypercadaster_es-1.2.3}/PKG-INFO +1 -1
  2. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_ES/__init__.py +1 -1
  3. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_ES/building_inference.py +201 -7
  4. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_ES/energy.py +42 -17
  5. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_ES/energy_config.yaml +9 -0
  6. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_ES/mergers.py +11 -1
  7. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_ES/utils.py +19 -3
  8. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3/hypercadaster_es.egg-info}/PKG-INFO +1 -1
  9. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_es.egg-info/SOURCES.txt +5 -1
  10. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/setup.py +1 -1
  11. hypercadaster_es-1.2.3/tests/test_agricultural_archetype.py +68 -0
  12. hypercadaster_es-1.2.3/tests/test_cat_empty_schema.py +81 -0
  13. hypercadaster_es-1.2.3/tests/test_theoretical_cat_spaces.py +129 -0
  14. hypercadaster_es-1.2.3/tests/test_zero_floor_buildings.py +83 -0
  15. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/LICENSE +0 -0
  16. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/MANIFEST.in +0 -0
  17. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/README.md +0 -0
  18. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_ES/_db.py +0 -0
  19. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_ES/_pretty.py +0 -0
  20. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_ES/cached_files/ine_inspire_codes.xlsx +0 -0
  21. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_ES/downloaders.py +0 -0
  22. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_ES/functions.py +0 -0
  23. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_ES/interoperability.py +0 -0
  24. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_ES/social.py +0 -0
  25. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_ES/weather.py +0 -0
  26. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_es.egg-info/dependency_links.txt +0 -0
  27. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_es.egg-info/requires.txt +0 -0
  28. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/hypercadaster_es.egg-info/top_level.txt +0 -0
  29. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/setup.cfg +0 -0
  30. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/tests/test_aggregation.py +0 -0
  31. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/tests/test_cat_cache.py +0 -0
  32. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/tests/test_code_normalisation.py +0 -0
  33. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/tests/test_codes.py +0 -0
  34. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/tests/test_dem_tiles.py +0 -0
  35. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/tests/test_energy_config.py +0 -0
  36. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/tests/test_geometry.py +0 -0
  37. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/tests/test_import_surface.py +0 -0
  38. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/tests/test_live_smoke.py +0 -0
  39. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/tests/test_social.py +0 -0
  40. {hypercadaster_es-1.2.2 → hypercadaster_es-1.2.3}/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.2.3
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
@@ -26,7 +26,7 @@ from ._db import ResultsHandle
26
26
  from . import (mergers, utils, building_inference, downloaders, interoperability,
27
27
  energy, weather, social)
28
28
 
29
- __version__ = "1.2.2"
29
+ __version__ = "1.2.3"
30
30
  __author__ = "Jose Manuel Broto Vispe"
31
31
  __email__ = "jmbrotovispe@gmail.com"
32
32
 
@@ -2849,13 +2849,15 @@ def process_zone(gdf_zone, zone_reference, gdf_footprints_global, parcels_gdf, s
2849
2849
  # is a pandas DataFrame here (sliced for this zone
2850
2850
  # in process_building_parts so workers stay polars-
2851
2851
  # free and can run under `fork` safely). Reuse the
2852
- # aggregation cached during floor synthesis.
2853
- agg_CAT = _agg_CAT_cache.get(building_reference)
2852
+ # aggregation cached during floor synthesis, which
2853
+ # returns None for buildings with no CAT rows at all
2854
+ # (rural parcels, undeveloped "solares"). Their empty
2855
+ # aggregation still carries the full column schema, so
2856
+ # the br__/sbr__ columns come out NaN for them instead
2857
+ # of going missing and taking the whole zone down.
2858
+ agg_CAT = _get_agg_CAT(building_reference)
2854
2859
  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
- ])
2860
+ agg_CAT = aggregate_CAT_file_building_spaces(None)
2859
2861
 
2860
2862
  building_gdf_by_floor = building_gdf_by_floor.drop(columns="geometry")
2861
2863
 
@@ -3402,6 +3404,71 @@ def parse_horizontal_division_buildings_CAT_files(cadaster_code, CAT_files_dir):
3402
3404
  return building_spaces_detailed
3403
3405
 
3404
3406
 
3407
+ # Column schema (name -> dtype) of the two frames
3408
+ # ``aggregate_CAT_file_building_spaces`` returns. Needed explicitly because
3409
+ # pandas' ``groupby(...).apply(...)`` never invokes the aggregation function on
3410
+ # an empty frame and passes the *input* columns through instead — so a building
3411
+ # with no CAT record (rural parcels, undeveloped "solares") would otherwise
3412
+ # yield frames without any ``br__`` column and blow up the whole cadastral zone
3413
+ # downstream. Dtypes are declared so an empty frame stays concat-compatible
3414
+ # with a populated one instead of degrading numeric columns to ``object``.
3415
+ # ``tests/test_cat_empty_schema.py`` pins these against the non-empty output.
3416
+ _AGG_CAT_BY_FLOORS_SCHEMA = {
3417
+ "floor_number": "Int32",
3418
+ "use_type": object,
3419
+ "building_reference": object,
3420
+ "br__building_spaces_by_floor": "int64",
3421
+ "br__mean_building_space_area_with_communals_by_floor": float,
3422
+ "br__mean_building_space_area_without_communals_by_floor": float,
3423
+ "br__mean_building_space_communal_area_by_floor": float,
3424
+ "br__mean_building_space_effective_year_by_floor": float,
3425
+ "br__mean_building_space_category_by_floor": float,
3426
+ "br__mean_building_space_economic_value_by_floor": float,
3427
+ "br__area_with_communals_by_floor": float,
3428
+ "br__area_without_communals_by_floor": float,
3429
+ "br__communal_area_by_floor": float,
3430
+ "br__economic_value_by_floor": float,
3431
+ "br__relative_area_with_communals_by_floor": float,
3432
+ "br__relative_area_without_communals_by_floor": float,
3433
+ "br__relative_communal_area_by_floor": float,
3434
+ }
3435
+
3436
+ _AGG_CAT_BUILDING_SCHEMA = {
3437
+ "use_type": object,
3438
+ "building_reference": object,
3439
+ "br__building_spaces": "int64",
3440
+ "br__floors": object,
3441
+ "br__mean_building_space_area_with_communals": float,
3442
+ "br__mean_building_space_area_without_communals": float,
3443
+ "br__mean_building_space_communal_area": float,
3444
+ "br__mean_building_space_effective_year": float,
3445
+ "br__mean_building_space_category": float,
3446
+ "br__mean_building_space_economic_value": float,
3447
+ "br__area_with_communals": float,
3448
+ "br__area_without_communals": float,
3449
+ "br__communal_area": float,
3450
+ "br__economic_value": float,
3451
+ "br__relative_area_with_communals": float,
3452
+ "br__relative_area_without_communals": float,
3453
+ "br__relative_communal_area": float,
3454
+ "br__building_spaces_reference": object,
3455
+ "br__building_spaces_postal_address": object,
3456
+ "br__building_spaces_inner_address": object,
3457
+ "br__building_spaces_floor_number": object,
3458
+ "br__building_spaces_floors": object,
3459
+ "br__building_spaces_category": object,
3460
+ "br__building_spaces_effective_year": object,
3461
+ "br__building_spaces_area_without_communal": object,
3462
+ "br__building_spaces_area_with_communal": object,
3463
+ "br__building_spaces_economic_value": object,
3464
+ "br__building_spaces_detailed_use_type": object,
3465
+ }
3466
+
3467
+
3468
+ def _empty_frame(schema):
3469
+ return pd.DataFrame({col: pd.Series(dtype=dt) for col, dt in schema.items()})
3470
+
3471
+
3405
3472
  def aggregate_CAT_file_building_spaces(building_CAT_df):
3406
3473
  """
3407
3474
  Aggregate building space information from CAT file data.
@@ -3419,7 +3486,14 @@ def aggregate_CAT_file_building_spaces(building_CAT_df):
3419
3486
  --------
3420
3487
  dict[str, pandas.DataFrame]
3421
3488
  ``{"by_floors": ..., "building": ...}`` — both pandas DataFrames.
3489
+ Empty input yields empty frames carrying the full column schema.
3422
3490
  """
3491
+ if building_CAT_df is None or len(building_CAT_df) == 0:
3492
+ return {
3493
+ "by_floors": _empty_frame(_AGG_CAT_BY_FLOORS_SCHEMA),
3494
+ "building": _empty_frame(_AGG_CAT_BUILDING_SCHEMA),
3495
+ }
3496
+
3423
3497
  df = building_CAT_df.copy()
3424
3498
 
3425
3499
  # Raw classify outputs include fractional markers (0.5 for ground floor,
@@ -3624,7 +3698,7 @@ def aggregate_CAT_file_building_spaces(building_CAT_df):
3624
3698
  }
3625
3699
 
3626
3700
 
3627
- _NON_OCCUPIED_USE_KEYS = ("parking", "warehouse", "storage", "garage")
3701
+ _NON_OCCUPIED_USE_KEYS = ("parking", "warehouse", "storage", "garage", "agricultur")
3628
3702
 
3629
3703
 
3630
3704
  def _synthesize_thermal_zones(row):
@@ -3879,6 +3953,126 @@ def br_attributes_from_CAT(buildings_CAT):
3879
3953
  return out
3880
3954
 
3881
3955
 
3956
+ # Cadaster ``currentUse`` (INSPIRE Building layer) -> CAT inferred use type.
3957
+ # Only used to give a theoretical building space the building's main usage;
3958
+ # "Agricultural" mirrors the CAT 'Z' code already mapped in ``downloaders``,
3959
+ # and a missing usage falls back to "Unknown" (the bucket the area pivot in
3960
+ # ``mergers`` already uses for null use types).
3961
+ _CADASTER_USE_TO_CAT_USE = {
3962
+ "1_residential": "Residential",
3963
+ "2_agriculture": "Agricultural",
3964
+ "3_industrial": "Industrial",
3965
+ "4_1_office": "Offices",
3966
+ "4_2_retail": "Commercial",
3967
+ "4_3_publicServices": "Singular building",
3968
+ }
3969
+ _THEORETICAL_UNKNOWN_USE = "Unknown"
3970
+
3971
+
3972
+ def add_theoretical_CAT_spaces(buildings_CAT, building_gdf, cadaster_code):
3973
+ """Give buildings absent from the CAT file a single theoretical space.
3974
+
3975
+ Rural/agricultural buildings exist in the INSPIRE Building layer but carry
3976
+ no CAT construction record, so they have no building spaces at all: every
3977
+ CAT-derived ``br__*`` column comes out NaN, ``br__thermal_zones`` is empty
3978
+ and no energy model can be built for them (1426 of 13619 buildings in
3979
+ Lleida — mostly ``2_agriculture``).
3980
+
3981
+ For each such building this appends one theoretical space to
3982
+ ``buildings_CAT`` carrying the building's main usage, so the whole CAT
3983
+ pipeline (area pivot, ``br__*`` aggregation, thermal zoning, EnergyPlus)
3984
+ treats it like any other single-space building:
3985
+
3986
+ - ``building_space_reference`` == ``building_reference`` (the building *is*
3987
+ its only space);
3988
+ - use type mapped from the cadaster ``building_use`` via
3989
+ ``_CADASTER_USE_TO_CAT_USE``, defaulting to ``"Unknown"``;
3990
+ - area from the cadaster's own official built area (``building_area``),
3991
+ which equals the CAT total built area across floors for buildings that
3992
+ do have CAT data, falling back to the footprint area when it is absent
3993
+ or zero. All of it is private area (no communals);
3994
+ - effective year from ``year_of_construction`` so the energy archetypes
3995
+ still have an age to work with.
3996
+
3997
+ Only the undeveloped-parcel supplements ("solares", added later in
3998
+ ``mergers`` from CAT dataset 15) are left alone — they have no geometry and
3999
+ are not buildings.
4000
+
4001
+ Parameters
4002
+ ----------
4003
+ buildings_CAT : polars.DataFrame or None
4004
+ Per-space CAT rows; returned unchanged when None.
4005
+ building_gdf : geopandas.GeoDataFrame
4006
+ The INSPIRE Building layer (``building_reference``, ``building_use``,
4007
+ ``building_area``, ``year_of_construction`` + geometry).
4008
+ cadaster_code : str
4009
+ Municipality code, written to the synthetic rows' ``cadaster_code``.
4010
+
4011
+ Returns
4012
+ -------
4013
+ polars.DataFrame
4014
+ ``buildings_CAT`` with the theoretical spaces appended.
4015
+ """
4016
+ if buildings_CAT is None or building_gdf is None or len(building_gdf) == 0:
4017
+ return buildings_CAT
4018
+
4019
+ known = set(buildings_CAT["building_reference"].unique().to_list())
4020
+ missing = building_gdf[~building_gdf["building_reference"].isin(known)]
4021
+ missing = missing[missing["building_reference"].notna()]
4022
+ if missing.empty:
4023
+ return buildings_CAT
4024
+
4025
+ # Official built area (already summed over floors); fall back to the
4026
+ # footprint when the cadaster leaves it null or zero.
4027
+ area = pd.to_numeric(missing.get("building_area"), errors="coerce")
4028
+ fallback = missing.geometry.area
4029
+ area = area.where(area.notna() & (area > 0), fallback).astype(float)
4030
+
4031
+ use = (missing["building_use"] if "building_use" in missing.columns
4032
+ else pd.Series(index=missing.index, dtype=object))
4033
+ use = use.map(lambda v: _CADASTER_USE_TO_CAT_USE.get(v, _THEORETICAL_UNKNOWN_USE)
4034
+ if v is not None and not (isinstance(v, float) and math.isnan(v))
4035
+ else _THEORETICAL_UNKNOWN_USE)
4036
+
4037
+ # None (not NaN) for the buildings with no construction year, so the value
4038
+ # casts cleanly into CAT's integer year columns.
4039
+ year = pd.to_numeric(missing.get("year_of_construction"), errors="coerce")
4040
+ year = [None if pd.isna(v) else int(v) for v in year]
4041
+
4042
+ refs = missing["building_reference"].astype(str).tolist()
4043
+ rows = pl.DataFrame({
4044
+ "building_reference": refs,
4045
+ # The building is its own single space.
4046
+ "building_space_reference": refs,
4047
+ # A real address is needed: the per-address floor compaction in
4048
+ # aggregate_CAT_file_building_spaces groups on it and would drop the
4049
+ # row (and lose its floor number) on a null key.
4050
+ "building_space_address": refs,
4051
+ "building_space_floor_name": ["00"] * len(refs),
4052
+ "building_space_year": year,
4053
+ "building_space_effective_year": year,
4054
+ "building_space_total_area": area.to_numpy(),
4055
+ "building_space_total_area_without_communal": area.to_numpy(),
4056
+ "building_space_area_with_communal": area.to_numpy(),
4057
+ "building_space_area_without_communal": area.to_numpy(),
4058
+ "building_space_communal_area": [0.0] * len(refs),
4059
+ "building_spaces_considered": [1] * len(refs),
4060
+ "building_space_use_type": use.tolist(),
4061
+ "building_space_detailed_use_type": use.tolist(),
4062
+ "building_space_inferred_use_type": use.tolist(),
4063
+ "cadaster_code": [str(cadaster_code)] * len(refs),
4064
+ })
4065
+
4066
+ # Match the CAT schema exactly: null out the columns we do not synthesize
4067
+ # and restore column order/dtypes so the concat is a plain vertical append.
4068
+ for col, dtype in buildings_CAT.schema.items():
4069
+ if col not in rows.columns:
4070
+ rows = rows.with_columns(pl.lit(None).cast(dtype).alias(col))
4071
+ rows = rows.select(buildings_CAT.columns).cast(dict(buildings_CAT.schema))
4072
+
4073
+ return pl.concat([buildings_CAT, rows], how="vertical")
4074
+
4075
+
3882
4076
  def undeveloped_parcels_from_CAT(cadaster_code, CAT_files_dir):
3883
4077
  """Recover minimal CAT area rows for undeveloped parcels ("solares").
3884
4078
 
@@ -49,7 +49,7 @@ from hypercadaster_ES import utils
49
49
 
50
50
  # Use types whose zones are not occupied by people and are placed as a compact
51
51
  # end block rather than wrapped around the floor.
52
- _PARKING_USE_KEYS = ("parking", "warehouse", "storage", "garage")
52
+ _PARKING_USE_KEYS = ("parking", "warehouse", "storage", "garage", "agricultur")
53
53
 
54
54
  # --------------------------------------------------------------------------- #
55
55
  # Configuration — all EnergyPlus model defaults live in energy_config.yaml
@@ -1286,18 +1286,29 @@ def _building_lonlat(row, crs="EPSG:25831"):
1286
1286
  def _dominant_use_type(zones):
1287
1287
  """Dominant occupied use type across spaces, weighted by floor area —
1288
1288
  drives the building archetype's use category."""
1289
- by_use = {}
1290
- for s in zones:
1291
- if s.get("kind") and s["kind"] != "occupied":
1292
- continue
1293
- ut = s.get("use_type")
1294
- area = 0.0
1295
- for poly in (s.get("floor_polys") or {}).values():
1296
- try:
1297
- area += float(poly.area)
1298
- except Exception:
1299
- pass
1300
- by_use[ut] = by_use.get(ut, 0.0) + area
1289
+ def _tally(only_occupied):
1290
+ by_use = {}
1291
+ for s in zones:
1292
+ kind = s.get("kind")
1293
+ if only_occupied:
1294
+ if kind and kind != "occupied":
1295
+ continue
1296
+ elif kind == "communal":
1297
+ continue
1298
+ ut = s.get("use_type")
1299
+ area = 0.0
1300
+ for poly in (s.get("floor_polys") or {}).values():
1301
+ try:
1302
+ area += float(poly.area)
1303
+ except Exception:
1304
+ pass
1305
+ by_use[ut] = by_use.get(ut, 0.0) + area
1306
+ return by_use
1307
+
1308
+ # A building with no occupied zones at all (a barn, a standalone garage) is
1309
+ # still characterised by the use it does have — falling through to None here
1310
+ # would resolve it to the generic "other" archetype instead.
1311
+ by_use = _tally(only_occupied=True) or _tally(only_occupied=False)
1301
1312
  if not by_use:
1302
1313
  return None
1303
1314
  return max(by_use, key=by_use.get)
@@ -1746,8 +1757,10 @@ def _add_cat_shading(idf, remainders, ox, oy, ground_floor_height, floor_height)
1746
1757
  # (``_MAIN_DOOR_SIZE`` / ``_PARKING_DOOR_SIZE``).
1747
1758
  # --------------------------------------------------------------------------- #
1748
1759
  def _zone_is_parking(zone_meta, zname):
1760
+ """True for zones that get a vehicle door instead of a pedestrian one:
1761
+ parking/warehouse, and agricultural sheds (which are entered by vehicle)."""
1749
1762
  s = zone_meta.get(zname.upper())
1750
- return bool(s) and _use_category(s.get("use_type")) == "parking"
1763
+ return bool(s) and _use_category(s.get("use_type")) in ("parking", "agricultural")
1751
1764
 
1752
1765
 
1753
1766
  def _wall_base(wall):
@@ -2048,6 +2061,11 @@ def _use_category(use_type):
2048
2061
  u = str(use_type or "").lower()
2049
2062
  if any(k in u for k in ("parking", "warehouse", "storage", "garage")):
2050
2063
  return "parking"
2064
+ # Kept out of the "parking" bucket on purpose: an agricultural building is
2065
+ # equally unconditioned, but it must not inherit parking's vehicle doors
2066
+ # (``_is_parking_space`` keys off this category).
2067
+ if "agricultur" in u:
2068
+ return "agricultural"
2051
2069
  if "communal" in u:
2052
2070
  return "communal"
2053
2071
  if any(k in u for k in ("sport", "pool")):
@@ -2176,12 +2194,19 @@ def building_archetype(year=None, use_type=None):
2176
2194
  """Resolve a building archetype from year of construction (Spanish thermal
2177
2195
  code period) and dominant use. Returns a dict with ``period``,
2178
2196
  ``use_category``, the period's ``envelope`` (target U-values + glazing) and
2179
- the period's window ``infiltration`` (frame/glazing type + ACH)."""
2197
+ the period's window ``infiltration`` (frame/glazing type + ACH).
2198
+
2199
+ Agricultural buildings are the exception to the period rule: a shed is
2200
+ uninsulated whatever year it was built, so it takes the ``uninsulated``
2201
+ envelope instead of its period's."""
2180
2202
  period = _construction_period(year)
2203
+ cat = _use_category(use_type)
2204
+ env_key = "uninsulated" if (cat == "agricultural"
2205
+ and "uninsulated" in _ARCHETYPE_ENVELOPE) else period
2181
2206
  return {
2182
2207
  "period": period,
2183
- "use_category": _use_category(use_type),
2184
- "envelope": dict(_ARCHETYPE_ENVELOPE[period]),
2208
+ "use_category": cat,
2209
+ "envelope": dict(_ARCHETYPE_ENVELOPE[env_key]),
2185
2210
  "infiltration": _window_infiltration(period),
2186
2211
  }
2187
2212
 
@@ -90,6 +90,11 @@ archetype_envelope:
90
90
  "1980_2006": {wall_U: 0.95, roof_U: 0.75, floor_U: 0.85, window_U: 3.50, window_shgc: 0.75, window_vt: 0.75}
91
91
  "2007_2013": {wall_U: 0.66, roof_U: 0.38, floor_U: 0.49, window_U: 3.00, window_shgc: 0.65, window_vt: 0.70}
92
92
  "post2013": {wall_U: 0.27, roof_U: 0.22, floor_U: 0.34, window_U: 2.00, window_shgc: 0.55, window_vt: 0.65}
93
+ # Agricultural sheds/barns, whatever their year: no insulation at all. The
94
+ # wall/roof/floor U targets are deliberately absent — with no target the
95
+ # solver in _add_constructions drops the INS layer entirely, leaving the bare
96
+ # construction, rather than us inventing U-values it would then tune towards.
97
+ "uninsulated": {window_U: 5.70, window_shgc: 0.82, window_vt: 0.80}
93
98
 
94
99
  # --- Internal loads, setpoints (°C) and conditioning, per use category ----- #
95
100
  # ``occ`` names the internal-gains usage fraction schedule (see schedules.occupancy
@@ -102,6 +107,10 @@ loads:
102
107
  commercial: {ppl_per_m2: 0.15, lights: 14.0, equip: 10.0, infil_ach: 0.5, heat: 21, heat_sb: 16, cool: 24, cool_sb: 28, activity: 130, conditioned: true, occ: OCC_COMMERCIAL}
103
108
  other: {ppl_per_m2: 0.05, lights: 8.0, equip: 8.0, infil_ach: 0.5, heat: 20, heat_sb: 17, cool: 25, cool_sb: 27, activity: 120, conditioned: true, occ: OCC_OFFICE}
104
109
  parking: {ppl_per_m2: 0.0, lights: 2.0, equip: 0.0, infil_ach: 1.0, conditioned: false, occ: OCC_LOW}
110
+ # Rural sheds/barns: same assumptions as a warehouse (which maps to the
111
+ # `parking` category), but uninsulated (see archetype_envelope.uninsulated)
112
+ # and very leaky — open eaves, unsealed vehicle doors, no air barrier.
113
+ agricultural: {ppl_per_m2: 0.0, lights: 2.0, equip: 0.0, infil_ach: 5.0, conditioned: false, occ: OCC_LOW}
105
114
  communal: {ppl_per_m2: 0.0, lights: 3.0, equip: 0.0, infil_ach: 0.5, conditioned: false, occ: OCC_LOW}
106
115
  sports: {ppl_per_m2: 0.0, lights: 0.0, equip: 0.0, infil_ach: 2.0, conditioned: false, occ: OCC_LOW}
107
116
 
@@ -963,7 +963,7 @@ def join_other_constructions(building_gdf_, cadaster_dir, code):
963
963
  # Use-type keywords whose thermal zones are not occupied by people (parking,
964
964
  # storage, …). Open-air pools (routed from OtherConstruction) are also marked
965
965
  # non-occupied via their source/detailed-use markers below.
966
- _NON_OCCUPIED_ZONE_USE_KEYS = ("parking", "warehouse", "storage", "garage")
966
+ _NON_OCCUPIED_ZONE_USE_KEYS = ("parking", "warehouse", "storage", "garage", "agricultur")
967
967
 
968
968
 
969
969
  def _thermal_zone_is_non_occupied(z):
@@ -1111,6 +1111,16 @@ def join_cadaster_building(gdf, cadaster_dir, census_tracts_dir, DEM_raster_dir,
1111
1111
  if buildings_CAT is None:
1112
1112
  buildings_CAT = building_inference.parse_horizontal_division_buildings_CAT_files(code, CAT_files_dir)
1113
1113
  _db_mod_cat.cat_cache_write(results_dir, code, buildings_CAT)
1114
+ # Buildings the CAT file knows nothing about (rural/agricultural,
1115
+ # mostly) get one theoretical space carrying the building's main
1116
+ # usage and official built area, so they flow through the CAT
1117
+ # aggregation, thermal zoning and energy model like any other
1118
+ # single-space building instead of coming out all-NaN. Applied
1119
+ # after the cache read/write on purpose: the cache must stay a pure
1120
+ # function of the CAT files, and this depends on the Building layer.
1121
+ with utils.stage_timer("merge: theoretical CAT spaces for buildings without CAT"):
1122
+ buildings_CAT = building_inference.add_theoretical_CAT_spaces(
1123
+ buildings_CAT, building_gdf_, code)
1114
1124
  else:
1115
1125
  buildings_CAT = None
1116
1126
 
@@ -1091,13 +1091,29 @@ def calculate_floor_footprints_chunk(chunk_groups, only_exterior_geometry, min_h
1091
1091
 
1092
1092
  if by_floors==True:
1093
1093
  # Unique levels of floors
1094
- max_floor = int(gdf_['n_floors_above_ground'].dropna().max())
1094
+ n_above = gdf_['n_floors_above_ground']
1095
+ max_floor = int(n_above.dropna().max())
1095
1096
  min_floor = int(gdf_['n_floors_below_ground'].dropna().max())
1097
+
1098
+ # A building whose every part declares no floors at all — neither
1099
+ # above nor below ground — still has a real BuildingPart footprint.
1100
+ # Taken literally it yields range(0) == no floors, so no footprints,
1101
+ # and the building drops out of the whole per-floor analysis (and,
1102
+ # downstream, out of the CAT integration). Read it as a single
1103
+ # storey instead; the CAT floor count then rebuilds the rest via
1104
+ # ``_augment_building_floors_from_cat``.
1105
+ # Deliberately narrow: a 0-floor part *inside* a building that has
1106
+ # floors is a canopy/porch and must stay excluded from the storeys,
1107
+ # and an underground-only structure must not gain a ground floor.
1108
+ if max_floor == 0 and min_floor == 0:
1109
+ n_above = n_above.fillna(0).where(lambda s: s > 0, 1)
1110
+ max_floor = 1
1111
+
1096
1112
  unique_floors = list(range(max_floor))
1097
1113
  unique_underground_floors = list(range(1,min_floor+1))
1098
1114
 
1099
1115
  for floor in unique_floors:
1100
- floor_geometries = gdf_[gdf_['n_floors_above_ground'] >= (floor + 1)].reset_index(drop=True)
1116
+ floor_geometries = gdf_[n_above >= (floor + 1)].reset_index(drop=True)
1101
1117
  try:
1102
1118
  unioned_geometry = union_geoseries_with_tolerance(floor_geometries.geometry,
1103
1119
  gap_tolerance=gap_tolerance, resolution=16)
@@ -6469,7 +6485,7 @@ def _thermal_zone_render_kind(z):
6469
6485
  if k in ('communal', 'non_occupied', 'occupied'):
6470
6486
  return k
6471
6487
  ut = str(z.get('use_type', '')).lower()
6472
- if any(t in ut for t in ('parking', 'warehouse', 'storage', 'garage')):
6488
+ if any(t in ut for t in ('parking', 'warehouse', 'storage', 'garage', 'agricultur')):
6473
6489
  return 'non_occupied'
6474
6490
  det = ' '.join(str(d) for d in (z.get('detailed_use_types') or [])).lower()
6475
6491
  if 'pool' in det or z.get('source') == 'other_construction':
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hypercadaster_es
3
- Version: 1.2.2
3
+ Version: 1.2.3
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
@@ -22,7 +22,9 @@ hypercadaster_es.egg-info/dependency_links.txt
22
22
  hypercadaster_es.egg-info/requires.txt
23
23
  hypercadaster_es.egg-info/top_level.txt
24
24
  tests/test_aggregation.py
25
+ tests/test_agricultural_archetype.py
25
26
  tests/test_cat_cache.py
27
+ tests/test_cat_empty_schema.py
26
28
  tests/test_code_normalisation.py
27
29
  tests/test_codes.py
28
30
  tests/test_dem_tiles.py
@@ -31,4 +33,6 @@ tests/test_geometry.py
31
33
  tests/test_import_surface.py
32
34
  tests/test_live_smoke.py
33
35
  tests/test_social.py
34
- tests/test_weather.py
36
+ tests/test_theoretical_cat_spaces.py
37
+ tests/test_weather.py
38
+ tests/test_zero_floor_buildings.py
@@ -3,7 +3,7 @@ from setuptools import find_packages, setup
3
3
 
4
4
  HERE = pathlib.Path(__file__).parent
5
5
 
6
- VERSION = "1.2.2"
6
+ VERSION = "1.2.3"
7
7
  PACKAGE_NAME = "hypercadaster_es"
8
8
  AUTHOR = "Jose Manuel Broto Vispe"
9
9
  AUTHOR_EMAIL = "jmbrotovispe@gmail.com"
@@ -0,0 +1,68 @@
1
+ """Agricultural buildings model as uninsulated, unconditioned warehouses.
2
+
3
+ A rural shed takes the same assumptions as a warehouse (no people, no
4
+ equipment, no HVAC, vehicle door) but is uninsulated whatever its year and very
5
+ leaky. See ``loads.agricultural`` / ``archetype_envelope.uninsulated`` in
6
+ energy_config.yaml.
7
+ """
8
+ import pytest
9
+
10
+ from hypercadaster_ES import energy
11
+
12
+
13
+ def test_agricultural_is_its_own_unconditioned_use_category():
14
+ assert energy._use_category("Agricultural") == "agricultural"
15
+ p = energy._LOAD_LIBRARY["agricultural"]
16
+ assert p["conditioned"] is False
17
+ assert p["ppl_per_m2"] == 0.0
18
+ assert p["equip"] == 0.0
19
+
20
+
21
+ def test_agricultural_assumptions_match_warehouse_except_infiltration():
22
+ """'All the assumptions should be equal to warehouse' — warehouse maps to
23
+ the `parking` category — 'very high infiltration' is the exception."""
24
+ agri = energy._LOAD_LIBRARY["agricultural"]
25
+ warehouse = energy._LOAD_LIBRARY[energy._use_category("Warehouse - Parking")]
26
+
27
+ shared = {k: v for k, v in warehouse.items() if k != "infil_ach"}
28
+ assert {k: agri[k] for k in shared} == shared
29
+ assert agri["infil_ach"] > warehouse["infil_ach"]
30
+
31
+
32
+ def test_agricultural_gets_no_insulation_whatever_the_year():
33
+ """No wall/roof/floor U target -> _add_constructions drops the INS layer."""
34
+ for year in (1950, 1996, 2010, 2020):
35
+ env = energy.building_archetype(year, "Agricultural")["envelope"]
36
+ assert "wall_U" not in env
37
+ assert "roof_U" not in env
38
+ assert "floor_U" not in env
39
+
40
+
41
+ def test_other_uses_keep_their_period_envelope():
42
+ arch = energy.building_archetype(1996, "Residential")
43
+ assert arch["use_category"] == "residential"
44
+ assert arch["envelope"]["wall_U"] == pytest.approx(0.95)
45
+ # the period is still reported for an agricultural building
46
+ assert energy.building_archetype(1996, "Agricultural")["period"] == "1980_2006"
47
+
48
+
49
+ def test_agricultural_zone_gets_a_vehicle_door():
50
+ assert energy._zone_is_parking({"Z": {"use_type": "Agricultural"}}, "z") is True
51
+ assert energy._zone_is_parking({"Z": {"use_type": "Warehouse - Parking"}}, "z") is True
52
+ assert energy._zone_is_parking({"Z": {"use_type": "Residential"}}, "z") is False
53
+
54
+
55
+ def test_dominant_use_falls_back_when_no_zone_is_occupied():
56
+ """A barn's only zone is non_occupied; without the fallback the archetype
57
+ would resolve to the generic 'other' instead of agricultural."""
58
+ barn = [{"kind": "non_occupied", "use_type": "Agricultural", "floor_polys": {}}]
59
+ assert energy._dominant_use_type(barn) == "Agricultural"
60
+
61
+ # occupied zones still win when present
62
+ mixed = [{"kind": "non_occupied", "use_type": "Agricultural", "floor_polys": {}},
63
+ {"kind": "occupied", "use_type": "Residential", "floor_polys": {}}]
64
+ assert energy._dominant_use_type(mixed) == "Residential"
65
+
66
+ # a communal-only building has no characteristic use
67
+ assert energy._dominant_use_type(
68
+ [{"kind": "communal", "use_type": "Communal", "floor_polys": {}}]) is None
@@ -0,0 +1,81 @@
1
+ """Empty CAT slices must still carry the full aggregation schema.
2
+
3
+ Buildings with no CAT record (rural parcels, undeveloped "solares") reach
4
+ ``aggregate_CAT_file_building_spaces`` with an empty frame. pandas'
5
+ ``groupby(...).apply(...)`` skips the aggregation function entirely in that
6
+ case and passes the *input* columns through, so without an explicit empty-input
7
+ schema the downstream ``br__`` aggregation raises ``KeyError`` and takes the
8
+ whole cadastral zone down with it.
9
+ """
10
+ import pandas as pd
11
+
12
+ from hypercadaster_ES import building_inference as bi
13
+
14
+
15
+ def _cat_frame(ref="A1", n=4):
16
+ """One building over four floors — the per-building slice the aggregation
17
+ expects (it groups by use type, not by building)."""
18
+ return pd.DataFrame({
19
+ "building_reference": [ref] * n,
20
+ "building_space_reference": [f"{ref}S{i}" for i in range(n)],
21
+ "building_space_address": [f"ADDR_{ref}"] * n,
22
+ "building_space_inner_address": ["1", "2", "3", "4"][:n],
23
+ "building_space_floor_name": ["00", "01", "02", "03"][:n],
24
+ "building_space_floors": [1.0] * n,
25
+ "building_space_area_with_communal": [80.0, 90.0, 70.0, 60.0][:n],
26
+ "building_space_area_without_communal": [70.0, 80.0, 60.0, 50.0][:n],
27
+ "building_space_communal_area": [10.0] * n,
28
+ "building_space_economic_value": [100000.0, 110000.0, 90000.0, 80000.0][:n],
29
+ "building_space_effective_year": [1990.0, 1990.0, 2001.0, 2001.0][:n],
30
+ "building_space_typology_category": ["A", "A", "B", "B"][:n],
31
+ "building_space_category": ["A", "A", "B", "B"][:n],
32
+ "building_space_detailed_use_type": ["Residential"] * n,
33
+ "building_space_inferred_use_type": ["Residential"] * n,
34
+ "building_space_related_area": [0.0] * n,
35
+ })
36
+
37
+
38
+ def test_empty_input_matches_populated_schema():
39
+ populated = bi.aggregate_CAT_file_building_spaces(_cat_frame())
40
+ empty = bi.aggregate_CAT_file_building_spaces(_cat_frame().iloc[0:0])
41
+
42
+ for key in ("by_floors", "building"):
43
+ assert len(empty[key]) == 0
44
+ # The declared empty schema must not drift from the real output.
45
+ assert list(empty[key].columns) == list(populated[key].columns), key
46
+
47
+
48
+ def test_empty_input_survives_br_aggregation():
49
+ """The regression: this used to raise KeyError('br__building_spaces_by_floor')."""
50
+ empty = bi.aggregate_CAT_file_building_spaces(pd.DataFrame())
51
+ out = bi._br_aggregate_from_agg_CAT(empty)
52
+
53
+ assert len(out) == 0
54
+ assert "building_reference" in out.columns
55
+ assert "br__building_spaces_by_floor" in out.columns
56
+
57
+ populated = bi._br_aggregate_from_agg_CAT(
58
+ bi.aggregate_CAT_file_building_spaces(_cat_frame()))
59
+ assert set(out.columns) == set(populated.columns)
60
+
61
+
62
+ def test_none_input_is_treated_as_empty():
63
+ agg = bi.aggregate_CAT_file_building_spaces(None)
64
+ assert len(agg["by_floors"]) == 0 and len(agg["building"]) == 0
65
+
66
+
67
+ def test_populated_aggregation_still_works():
68
+ """A building with CAT data aggregates as before, and a mix of buildings
69
+ with and without CAT data reduces to the with-CAT ones only."""
70
+ agg = bi.aggregate_CAT_file_building_spaces(_cat_frame("A1"))
71
+ out = bi._br_aggregate_from_agg_CAT(agg)
72
+ assert list(out["building_reference"]) == ["A1"]
73
+ # four spaces on a single use type
74
+ assert [sum(v.values()) for v in out["br__building_spaces"]] == [4]
75
+
76
+ empty = bi.aggregate_CAT_file_building_spaces(_cat_frame("A2").iloc[0:0])
77
+ combined = bi._br_aggregate_from_agg_CAT({
78
+ key: pd.concat([agg[key], empty[key]], ignore_index=True)
79
+ for key in ("by_floors", "building")
80
+ })
81
+ assert list(combined["building_reference"]) == ["A1"]
@@ -0,0 +1,129 @@
1
+ """Theoretical single building space for buildings absent from the CAT file.
2
+
3
+ Rural/agricultural buildings exist in the INSPIRE Building layer but have no
4
+ CAT construction record, so they have no building spaces and no thermal zones.
5
+ ``add_theoretical_CAT_spaces`` gives each one a single space carrying the
6
+ building's main usage and official built area.
7
+ """
8
+ import geopandas as gpd
9
+ import polars as pl
10
+ import pytest
11
+ from shapely.geometry import Polygon
12
+
13
+ from hypercadaster_ES import building_inference as bi
14
+
15
+
16
+ def _square(x0, y0, side):
17
+ return Polygon([(x0, y0), (x0 + side, y0), (x0 + side, y0 + side), (x0, y0 + side)])
18
+
19
+
20
+ @pytest.fixture
21
+ def cat():
22
+ """A CAT frame knowing only about building B1."""
23
+ return pl.DataFrame({
24
+ "building_reference": ["B1", "B1"],
25
+ "building_space_reference": ["B1S1", "B1S2"],
26
+ "building_space_address": ["ADDR1", "ADDR1"],
27
+ "building_space_inner_address": ["1", "2"],
28
+ "building_space_floor_name": ["00", "01"],
29
+ "building_space_year": pl.Series([1990, 1990], dtype=pl.Int16),
30
+ "building_space_effective_year": pl.Series([1990, 1990], dtype=pl.Int16),
31
+ "building_space_total_area": pl.Series([50.0, 50.0], dtype=pl.Float32),
32
+ "building_space_total_area_without_communal": pl.Series([45.0, 45.0], dtype=pl.Float32),
33
+ "building_space_area_with_communal": pl.Series([50.0, 50.0], dtype=pl.Float32),
34
+ "building_space_area_without_communal": pl.Series([45.0, 45.0], dtype=pl.Float32),
35
+ "building_space_communal_area": pl.Series([5.0, 5.0], dtype=pl.Float32),
36
+ "building_spaces_considered": pl.Series([1, 1], dtype=pl.UInt32),
37
+ "building_space_use_type": ["V", "V"],
38
+ "building_space_typology_category": ["A", "A"],
39
+ "building_space_detailed_use_type": ["Housing", "Housing"],
40
+ "building_space_inferred_use_type": ["Residential", "Residential"],
41
+ "building_space_economic_value": [1000.0, 1000.0],
42
+ "cadaster_code": ["25900", "25900"],
43
+ })
44
+
45
+
46
+ @pytest.fixture
47
+ def gdf():
48
+ """B1 has CAT data; B2 (agriculture) and B3 (no usage) do not."""
49
+ return gpd.GeoDataFrame({
50
+ "building_reference": ["B1", "B2", "B3"],
51
+ "building_use": ["1_residential", "2_agriculture", None],
52
+ "building_area": [100.0, 108.0, 240.0],
53
+ "year_of_construction": [1990, 1996, None],
54
+ "building_geometry": [_square(0, 0, 10), _square(50, 0, 12), _square(100, 0, 20)],
55
+ }, geometry="building_geometry", crs="EPSG:25831")
56
+
57
+
58
+ def test_adds_one_space_per_building_missing_from_CAT(cat, gdf):
59
+ out = bi.add_theoretical_CAT_spaces(cat, gdf, "25900")
60
+
61
+ assert out.height == cat.height + 2 # B2 and B3 only
62
+ added = out.filter(pl.col("building_reference").is_in(["B2", "B3"]))
63
+ assert sorted(added["building_reference"]) == ["B2", "B3"]
64
+ # the building IS its only space
65
+ assert added.filter(pl.col("building_reference") == "B2")["building_space_reference"][0] == "B2"
66
+
67
+
68
+ def test_preserves_CAT_schema_and_leaves_known_buildings_untouched(cat, gdf):
69
+ out = bi.add_theoretical_CAT_spaces(cat, gdf, "25900")
70
+
71
+ assert out.columns == cat.columns
72
+ assert out.schema == cat.schema
73
+ # B1's real CAT rows are unchanged
74
+ assert out.filter(pl.col("building_reference") == "B1").equals(cat)
75
+
76
+
77
+ def test_usage_is_mapped_from_the_building_and_defaults_to_unknown(cat, gdf):
78
+ out = bi.add_theoretical_CAT_spaces(cat, gdf, "25900")
79
+
80
+ def use(ref):
81
+ return out.filter(pl.col("building_reference") == ref)["building_space_inferred_use_type"][0]
82
+
83
+ assert use("B2") == "Agricultural" # 2_agriculture
84
+ assert use("B3") == "Unknown" # building_use is null
85
+
86
+
87
+ def test_area_comes_from_the_official_built_area_all_private(cat, gdf):
88
+ out = bi.add_theoretical_CAT_spaces(cat, gdf, "25900")
89
+ b2 = out.filter(pl.col("building_reference") == "B2")
90
+
91
+ assert b2["building_space_area_with_communal"][0] == pytest.approx(108.0)
92
+ assert b2["building_space_area_without_communal"][0] == pytest.approx(108.0)
93
+ assert b2["building_space_communal_area"][0] == 0.0
94
+ assert b2["building_space_effective_year"][0] == 1996
95
+
96
+
97
+ def test_area_falls_back_to_the_footprint_when_the_cadaster_area_is_missing(cat, gdf):
98
+ gdf.loc[gdf["building_reference"] == "B2", "building_area"] = None
99
+ gdf.loc[gdf["building_reference"] == "B3", "building_area"] = 0.0
100
+
101
+ out = bi.add_theoretical_CAT_spaces(cat, gdf, "25900")
102
+ area = {r: out.filter(pl.col("building_reference") == r)["building_space_area_with_communal"][0]
103
+ for r in ("B2", "B3")}
104
+ assert area["B2"] == pytest.approx(12 * 12) # footprint of B2
105
+ assert area["B3"] == pytest.approx(20 * 20) # footprint of B3
106
+
107
+
108
+ def test_theoretical_space_yields_one_thermal_zone(cat, gdf):
109
+ """The point of the exercise: these buildings become modellable."""
110
+ out = bi.add_theoretical_CAT_spaces(cat, gdf, "25900")
111
+ sl = out.filter(pl.col("building_reference") == "B2").to_pandas()
112
+
113
+ br = bi._br_aggregate_from_agg_CAT(bi.aggregate_CAT_file_building_spaces(sl))
114
+ zones = br["br__thermal_zones"].iloc[0]
115
+
116
+ assert len(zones) == 1
117
+ assert zones[0]["use_type"] == "Agricultural"
118
+ assert zones[0]["reference"] == "B2"
119
+ assert zones[0]["floors"] == [0]
120
+ assert zones[0]["area_with_communals"] == pytest.approx(108.0)
121
+
122
+
123
+ def test_noop_without_CAT_or_buildings(cat, gdf):
124
+ assert bi.add_theoretical_CAT_spaces(None, gdf, "25900") is None
125
+ empty = gdf.iloc[0:0]
126
+ assert bi.add_theoretical_CAT_spaces(cat, empty, "25900").height == cat.height
127
+ # every building already has CAT data -> nothing to add
128
+ only_b1 = gdf[gdf["building_reference"] == "B1"]
129
+ assert bi.add_theoretical_CAT_spaces(cat, only_b1, "25900").height == cat.height
@@ -0,0 +1,83 @@
1
+ """BuildingParts that declare no floors at all still get a storey.
2
+
3
+ Taken literally, ``n_floors_above_ground == 0`` yields ``range(0)`` — no floor
4
+ footprints — so the building drops out of the per-floor analysis and, further
5
+ downstream, out of the CAT integration (which is gated on a non-empty
6
+ per-floor frame). Such a part still has a real footprint, so it is read as a
7
+ single storey; the CAT floor count then rebuilds the rest.
8
+ """
9
+ import geopandas as gpd
10
+ import pytest
11
+ from shapely.geometry import Polygon
12
+
13
+ from hypercadaster_ES import utils
14
+
15
+
16
+ def _square(x0=0.0, y0=0.0, side=10.0):
17
+ return Polygon([(x0, y0), (x0 + side, y0), (x0 + side, y0 + side), (x0, y0 + side)])
18
+
19
+
20
+ def _parts(rows):
21
+ """rows: list of (ref, n_above, n_below, geometry)."""
22
+ gdf = gpd.GeoDataFrame({
23
+ "single_building_reference": [r[0] for r in rows],
24
+ "n_floors_above_ground": [r[1] for r in rows],
25
+ "n_floors_below_ground": [r[2] for r in rows],
26
+ "building_part_geometry": [r[3] for r in rows],
27
+ }, geometry="building_part_geometry", crs="EPSG:25831")
28
+ return gdf
29
+
30
+
31
+ def _footprints(rows):
32
+ return utils.calculate_floor_footprints(
33
+ gdf=_parts(rows), group_by="single_building_reference",
34
+ geometry_name="building_part_geometry", min_hole_area=0.5,
35
+ gap_tolerance=0.05, num_workers=1)
36
+
37
+
38
+ def test_building_with_no_floors_at_all_becomes_one_storey():
39
+ fp = _footprints([("B1", 0, 0, _square(side=10.0))])
40
+ assert sorted(fp["floor"]) == [0]
41
+ assert fp.geometry.area.sum() == pytest.approx(100.0, rel=0.01)
42
+
43
+
44
+ def test_normal_building_is_unaffected():
45
+ fp = _footprints([("B1", 3, 0, _square(side=10.0))])
46
+ assert sorted(fp["floor"]) == [0, 1, 2]
47
+
48
+
49
+ def test_zero_floor_part_inside_a_real_building_stays_a_canopy():
50
+ """A 0-floor part alongside parts that have floors is a canopy/porch: it
51
+ must not become a storey, nor contribute to the floor footprints."""
52
+ fp = _footprints([
53
+ ("B1", 0, 0, _square(x0=20, side=10.0)), # canopy, detached area
54
+ ("B1", 2, 0, _square(side=10.0)),
55
+ ])
56
+ assert sorted(fp["floor"]) == [0, 1]
57
+ # only the 2-storey part's 100 m² counts on each floor — not the canopy
58
+ for _, row in fp.iterrows():
59
+ assert row.geometry.area == pytest.approx(100.0, rel=0.01)
60
+
61
+
62
+ def test_underground_only_structure_gains_no_ground_floor():
63
+ fp = _footprints([("B1", 0, 2, _square(side=10.0))])
64
+ assert 0 not in set(fp["floor"])
65
+ assert sorted(fp["floor"]) == [-2, -1]
66
+
67
+
68
+ def test_cat_floor_count_is_replicated_onto_the_synthesized_storey():
69
+ """The point of reading it as one storey: _augment_building_floors_from_cat
70
+ can then rebuild the floors CAT reports, buffered to their CAT area."""
71
+ from hypercadaster_ES import building_inference as bi
72
+
73
+ fp = _footprints([("B1", 0, 0, _square(side=10.0))])
74
+ assert sorted(fp["floor"]) == [0]
75
+
76
+ # CAT reports three above-ground floors for this building
77
+ cat_area = {0: 100.0, 1: 100.0, 2: 64.0}
78
+ out = bi._augment_building_floors_from_cat(fp, "B1", cat_area, share=1.0)
79
+
80
+ assert sorted(out["floor"]) == [0, 1, 2]
81
+ areas = dict(zip(out["floor"], out.geometry.area))
82
+ assert areas[1] == pytest.approx(100.0, rel=0.05)
83
+ assert areas[2] == pytest.approx(64.0, rel=0.05)