hypercadaster-ES 1.2.1__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.
- {hypercadaster_es-1.2.1/hypercadaster_es.egg-info → hypercadaster_es-1.2.3}/PKG-INFO +1 -1
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_ES/__init__.py +1 -1
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_ES/_db.py +225 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_ES/building_inference.py +201 -7
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_ES/energy.py +42 -17
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_ES/energy_config.yaml +9 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_ES/functions.py +9 -1
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_ES/mergers.py +35 -5
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_ES/social.py +339 -314
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_ES/utils.py +34 -3
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_ES/weather.py +4 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3/hypercadaster_es.egg-info}/PKG-INFO +1 -1
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_es.egg-info/SOURCES.txt +6 -1
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/setup.py +1 -1
- hypercadaster_es-1.2.3/tests/test_agricultural_archetype.py +68 -0
- hypercadaster_es-1.2.3/tests/test_cat_cache.py +135 -0
- hypercadaster_es-1.2.3/tests/test_cat_empty_schema.py +81 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/tests/test_social.py +10 -7
- hypercadaster_es-1.2.3/tests/test_theoretical_cat_spaces.py +129 -0
- hypercadaster_es-1.2.3/tests/test_zero_floor_buildings.py +83 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/LICENSE +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/MANIFEST.in +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/README.md +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_ES/_pretty.py +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_ES/cached_files/ine_inspire_codes.xlsx +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_ES/downloaders.py +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_ES/interoperability.py +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_es.egg-info/dependency_links.txt +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_es.egg-info/requires.txt +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/hypercadaster_es.egg-info/top_level.txt +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/setup.cfg +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/tests/test_aggregation.py +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/tests/test_code_normalisation.py +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/tests/test_codes.py +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/tests/test_dem_tiles.py +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/tests/test_energy_config.py +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/tests/test_geometry.py +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/tests/test_import_surface.py +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/tests/test_live_smoke.py +0 -0
- {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.3}/tests/test_weather.py +0 -0
|
@@ -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.
|
|
29
|
+
__version__ = "1.2.3"
|
|
30
30
|
__author__ = "Jose Manuel Broto Vispe"
|
|
31
31
|
__email__ = "jmbrotovispe@gmail.com"
|
|
32
32
|
|
|
@@ -96,6 +96,231 @@ def ensure_schema(con: duckdb.DuckDBPyConnection) -> None:
|
|
|
96
96
|
""")
|
|
97
97
|
|
|
98
98
|
|
|
99
|
+
# ---------------------------------------------------------------------------
|
|
100
|
+
# CAT-file attribute cache — the parsed per-space building table
|
|
101
|
+
# ---------------------------------------------------------------------------
|
|
102
|
+
# Reading + transforming the CAT files (parse_horizontal_division_buildings_
|
|
103
|
+
# CAT_files) is the dominant fixed cost of a no-inference CAT merge — ~1 h for a
|
|
104
|
+
# whole province. Its output (one row per building space, all primitive columns,
|
|
105
|
+
# no geometry) is cached here keyed by cadaster_code so re-runs skip the parse.
|
|
106
|
+
CAT_SPACES_TABLE = "cat_building_spaces"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _table_exists(con: duckdb.DuckDBPyConnection, table: str) -> bool:
|
|
110
|
+
return con.execute(
|
|
111
|
+
"SELECT 1 FROM information_schema.tables WHERE table_name = ?",
|
|
112
|
+
[table],
|
|
113
|
+
).fetchone() is not None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def cat_cache_read(results_dir: str, cadaster_code: str):
|
|
117
|
+
"""Return the cached CAT building-space frame for one municipality, or None.
|
|
118
|
+
|
|
119
|
+
Reads back the exact per-space table produced by
|
|
120
|
+
``parse_horizontal_division_buildings_CAT_files`` and stored by
|
|
121
|
+
:func:`cat_cache_write`, as a polars DataFrame (``cadaster_code`` column
|
|
122
|
+
dropped). Returns ``None`` when the cache table or the municipality's rows are
|
|
123
|
+
absent — or on any error, so a stale/corrupt cache degrades to a re-parse
|
|
124
|
+
instead of breaking the merge.
|
|
125
|
+
"""
|
|
126
|
+
path = db_path(results_dir)
|
|
127
|
+
if not os.path.exists(path):
|
|
128
|
+
return None
|
|
129
|
+
con = None
|
|
130
|
+
try:
|
|
131
|
+
con = duckdb.connect(path, read_only=True)
|
|
132
|
+
if not _table_exists(con, CAT_SPACES_TABLE):
|
|
133
|
+
return None
|
|
134
|
+
df = con.execute(
|
|
135
|
+
f'SELECT * FROM "{CAT_SPACES_TABLE}" WHERE cadaster_code = ?',
|
|
136
|
+
[str(cadaster_code)],
|
|
137
|
+
).pl()
|
|
138
|
+
if df.height == 0:
|
|
139
|
+
return None
|
|
140
|
+
return df.drop("cadaster_code")
|
|
141
|
+
except Exception as e: # noqa: BLE001
|
|
142
|
+
sys.stderr.write(f"CAT cache read failed for {cadaster_code} ({e}); re-parsing\n")
|
|
143
|
+
return None
|
|
144
|
+
finally:
|
|
145
|
+
if con is not None:
|
|
146
|
+
con.close()
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def cat_cache_clear(results_dir: str, cadaster_code: Optional[str] = None) -> int:
|
|
150
|
+
"""Invalidate the CAT caches so the next merge re-parses and re-aggregates.
|
|
151
|
+
|
|
152
|
+
Clears both CAT caches (``cat_building_spaces`` per-space parse and
|
|
153
|
+
``cat_building_attributes`` per-building aggregates): the rows for one
|
|
154
|
+
``cadaster_code`` (or every row / the whole tables when ``cadaster_code is
|
|
155
|
+
None``). Returns the total number of rows removed across both tables (0 when
|
|
156
|
+
neither exists). Use after replacing the CAT files, since the caches are
|
|
157
|
+
otherwise reused regardless of ``force_update``.
|
|
158
|
+
"""
|
|
159
|
+
path = db_path(results_dir)
|
|
160
|
+
if not os.path.exists(path):
|
|
161
|
+
return 0
|
|
162
|
+
con = None
|
|
163
|
+
removed = 0
|
|
164
|
+
try:
|
|
165
|
+
con = open_db(results_dir)
|
|
166
|
+
for tbl in (CAT_SPACES_TABLE, CAT_ATTRS_TABLE):
|
|
167
|
+
if not _table_exists(con, tbl):
|
|
168
|
+
continue
|
|
169
|
+
if cadaster_code is None:
|
|
170
|
+
removed += con.execute(f'SELECT COUNT(*) FROM "{tbl}"').fetchone()[0]
|
|
171
|
+
con.execute(f'DROP TABLE "{tbl}"')
|
|
172
|
+
else:
|
|
173
|
+
removed += con.execute(
|
|
174
|
+
f'SELECT COUNT(*) FROM "{tbl}" WHERE cadaster_code = ?',
|
|
175
|
+
[str(cadaster_code)]).fetchone()[0]
|
|
176
|
+
con.execute(
|
|
177
|
+
f'DELETE FROM "{tbl}" WHERE cadaster_code = ?',
|
|
178
|
+
[str(cadaster_code)])
|
|
179
|
+
return int(removed)
|
|
180
|
+
finally:
|
|
181
|
+
if con is not None:
|
|
182
|
+
con.close()
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def cat_cache_write(results_dir: str, cadaster_code: str, buildings_cat) -> None:
|
|
186
|
+
"""Store one municipality's parsed CAT building-space frame in the central DB.
|
|
187
|
+
|
|
188
|
+
Idempotent per ``cadaster_code``: any existing rows for the municipality are
|
|
189
|
+
replaced (so a re-parse refreshes the cache). The table is created on first
|
|
190
|
+
use and its schema extended (``ADD COLUMN``) if a later municipality carries a
|
|
191
|
+
column not seen before. ``buildings_cat`` is the polars frame returned by
|
|
192
|
+
``parse_horizontal_division_buildings_CAT_files``. Any failure is swallowed
|
|
193
|
+
with a warning — caching is an optimisation and must never break the merge.
|
|
194
|
+
"""
|
|
195
|
+
import polars as pl
|
|
196
|
+
|
|
197
|
+
if buildings_cat is None or getattr(buildings_cat, "height", 0) == 0:
|
|
198
|
+
return
|
|
199
|
+
code = str(cadaster_code)
|
|
200
|
+
con = None
|
|
201
|
+
try:
|
|
202
|
+
df = buildings_cat
|
|
203
|
+
if "cadaster_code" in df.columns:
|
|
204
|
+
df = df.drop("cadaster_code")
|
|
205
|
+
df = df.with_columns(pl.lit(code).alias("cadaster_code"))
|
|
206
|
+
|
|
207
|
+
con = open_db(results_dir)
|
|
208
|
+
con.register("_cat_cache_tmp", df.to_arrow())
|
|
209
|
+
if not _table_exists(con, CAT_SPACES_TABLE):
|
|
210
|
+
con.execute(
|
|
211
|
+
f'CREATE TABLE "{CAT_SPACES_TABLE}" AS SELECT * FROM _cat_cache_tmp'
|
|
212
|
+
)
|
|
213
|
+
else:
|
|
214
|
+
existing = {r[0] for r in con.execute(
|
|
215
|
+
f'DESCRIBE "{CAT_SPACES_TABLE}"').fetchall()}
|
|
216
|
+
for name, ty in ((r[0], r[1]) for r in
|
|
217
|
+
con.execute('DESCRIBE _cat_cache_tmp').fetchall()):
|
|
218
|
+
if name not in existing:
|
|
219
|
+
con.execute(
|
|
220
|
+
f'ALTER TABLE "{CAT_SPACES_TABLE}" ADD COLUMN "{name}" {ty}')
|
|
221
|
+
con.execute(
|
|
222
|
+
f'DELETE FROM "{CAT_SPACES_TABLE}" WHERE cadaster_code = ?', [code])
|
|
223
|
+
con.execute(
|
|
224
|
+
f'INSERT INTO "{CAT_SPACES_TABLE}" BY NAME SELECT * FROM _cat_cache_tmp')
|
|
225
|
+
con.unregister("_cat_cache_tmp")
|
|
226
|
+
except Exception as e: # noqa: BLE001
|
|
227
|
+
sys.stderr.write(f"CAT cache write failed for {cadaster_code} ({e}); "
|
|
228
|
+
f"continuing without caching\n")
|
|
229
|
+
finally:
|
|
230
|
+
if con is not None:
|
|
231
|
+
con.close()
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
# ---------------------------------------------------------------------------
|
|
235
|
+
# CAT per-building attribute cache — the expensive br_attributes_from_CAT output
|
|
236
|
+
# ---------------------------------------------------------------------------
|
|
237
|
+
# The real cost of a no-inference CAT merge is not the CAT parse (~1 s even for a
|
|
238
|
+
# 160k-space municipality) but ``br_attributes_from_CAT`` — a per-building
|
|
239
|
+
# aggregation that runs for minutes on a large municipality. Its output (one row
|
|
240
|
+
# per building, with many complex ``br__*`` dict/list columns) is cached here,
|
|
241
|
+
# keyed by cadaster_code, and reused on every run. Complex columns are pickled to
|
|
242
|
+
# BLOB by ``write_df_safe`` and rehydrated by ``read_df_safe``.
|
|
243
|
+
CAT_ATTRS_TABLE = "cat_building_attributes"
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def cat_attrs_read(results_dir: str, cadaster_code: str):
|
|
247
|
+
"""Return the cached per-building CAT attribute frame for a municipality.
|
|
248
|
+
|
|
249
|
+
The pandas frame produced by ``br_attributes_from_CAT`` (``cadaster_code``
|
|
250
|
+
column dropped), or ``None`` when absent — or on any error, so a stale/corrupt
|
|
251
|
+
cache degrades to a recompute instead of breaking the merge.
|
|
252
|
+
"""
|
|
253
|
+
path = db_path(results_dir)
|
|
254
|
+
if not os.path.exists(path):
|
|
255
|
+
return None
|
|
256
|
+
con = None
|
|
257
|
+
try:
|
|
258
|
+
con = open_shard_read(path)
|
|
259
|
+
if not _table_exists(con, CAT_ATTRS_TABLE):
|
|
260
|
+
return None
|
|
261
|
+
df = read_df_safe(con, CAT_ATTRS_TABLE,
|
|
262
|
+
where="cadaster_code = ?", params=[str(cadaster_code)])
|
|
263
|
+
if df is None or len(df) == 0:
|
|
264
|
+
return None
|
|
265
|
+
return df.drop(columns=["cadaster_code"])
|
|
266
|
+
except Exception as e: # noqa: BLE001
|
|
267
|
+
sys.stderr.write(f"CAT attrs cache read failed for {cadaster_code} "
|
|
268
|
+
f"({e}); recomputing\n")
|
|
269
|
+
return None
|
|
270
|
+
finally:
|
|
271
|
+
if con is not None:
|
|
272
|
+
con.close()
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def cat_attrs_write(results_dir: str, cadaster_code: str, br_df) -> None:
|
|
276
|
+
"""Store one municipality's per-building CAT attribute frame in the central DB.
|
|
277
|
+
|
|
278
|
+
Idempotent per ``cadaster_code`` (existing rows are replaced). ``br_df`` is the
|
|
279
|
+
pandas frame returned by ``br_attributes_from_CAT``; its complex ``br__*``
|
|
280
|
+
columns are pickled by ``write_df_safe``. Any failure is swallowed with a
|
|
281
|
+
warning — caching must never break the merge.
|
|
282
|
+
"""
|
|
283
|
+
if br_df is None or len(br_df) == 0:
|
|
284
|
+
return
|
|
285
|
+
code = str(cadaster_code)
|
|
286
|
+
con = None
|
|
287
|
+
try:
|
|
288
|
+
df = br_df.copy()
|
|
289
|
+
df["cadaster_code"] = code
|
|
290
|
+
con = open_db(results_dir)
|
|
291
|
+
if not _table_exists(con, CAT_ATTRS_TABLE):
|
|
292
|
+
write_df_safe(con, CAT_ATTRS_TABLE, df, if_exists="replace")
|
|
293
|
+
else:
|
|
294
|
+
# Align to the existing column set/order so the positional INSERT in
|
|
295
|
+
# write_df_safe(append) stays correct even if a municipality's frame
|
|
296
|
+
# is ordered differently or misses a column.
|
|
297
|
+
existing = [r[0] for r in con.execute(
|
|
298
|
+
f'DESCRIBE "{CAT_ATTRS_TABLE}"').fetchall()]
|
|
299
|
+
for c in existing:
|
|
300
|
+
if c not in df.columns:
|
|
301
|
+
df[c] = None
|
|
302
|
+
extra = [c for c in df.columns if c not in existing]
|
|
303
|
+
if extra:
|
|
304
|
+
# Unexpected new column(s): fall back to a full rewrite so nothing
|
|
305
|
+
# is silently dropped (schema stays a superset).
|
|
306
|
+
con.execute(
|
|
307
|
+
f'DELETE FROM "{CAT_ATTRS_TABLE}" WHERE cadaster_code = ?', [code])
|
|
308
|
+
prev = read_df_safe(con, CAT_ATTRS_TABLE)
|
|
309
|
+
combined = pd.concat([prev, df], ignore_index=True)
|
|
310
|
+
write_df_safe(con, CAT_ATTRS_TABLE, combined, if_exists="replace")
|
|
311
|
+
else:
|
|
312
|
+
df = df[existing]
|
|
313
|
+
con.execute(
|
|
314
|
+
f'DELETE FROM "{CAT_ATTRS_TABLE}" WHERE cadaster_code = ?', [code])
|
|
315
|
+
write_df_safe(con, CAT_ATTRS_TABLE, df, if_exists="append")
|
|
316
|
+
except Exception as e: # noqa: BLE001
|
|
317
|
+
sys.stderr.write(f"CAT attrs cache write failed for {cadaster_code} "
|
|
318
|
+
f"({e}); continuing without caching\n")
|
|
319
|
+
finally:
|
|
320
|
+
if con is not None:
|
|
321
|
+
con.close()
|
|
322
|
+
|
|
323
|
+
|
|
99
324
|
# ---------------------------------------------------------------------------
|
|
100
325
|
# CRS sidecar — the spatial extension does not store per-table CRS itself
|
|
101
326
|
# ---------------------------------------------------------------------------
|
|
@@ -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
|
-
|
|
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
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
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"))
|
|
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":
|
|
2184
|
-
"envelope": dict(_ARCHETYPE_ENVELOPE[
|
|
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
|
|
|
@@ -375,7 +375,15 @@ def merge(wd, province_codes=None, ine_codes=None, cadaster_codes=None,
|
|
|
375
375
|
Parallel worker processes for the inference (``-1`` = all cores).
|
|
376
376
|
force_update : bool, default False
|
|
377
377
|
Recompute and overwrite cached DuckDB tables instead of reusing existing
|
|
378
|
-
(already-processed zones are otherwise skipped on re-runs).
|
|
378
|
+
(already-processed zones are otherwise skipped on re-runs). Note this does
|
|
379
|
+
**not** re-read/re-aggregate the CAT files: with ``use_CAT_files=True`` the
|
|
380
|
+
parsed per-space table (``cat_building_spaces``) and the expensive
|
|
381
|
+
per-building ``br__*`` aggregates (``cat_building_attributes``, the
|
|
382
|
+
dominant cost of a CAT merge) are cached in the central DuckDB keyed by
|
|
383
|
+
``cadaster_code`` and reused on every run. Like the raw ``.CAT``→parquet
|
|
384
|
+
cache, they are pure functions of the static CAT files. To force a CAT
|
|
385
|
+
re-parse/re-aggregate (e.g. after replacing the CAT files), clear them
|
|
386
|
+
with :func:`hypercadaster_ES.utils.clear_cat_cache`.
|
|
379
387
|
cleanup_shards : bool, default True
|
|
380
388
|
Delete the per-zone shard DuckDB files after ingesting them into the
|
|
381
389
|
central database.
|