hypercadaster-ES 1.2.1__tar.gz → 1.2.2__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 (36) hide show
  1. {hypercadaster_es-1.2.1/hypercadaster_es.egg-info → hypercadaster_es-1.2.2}/PKG-INFO +1 -1
  2. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_ES/__init__.py +1 -1
  3. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_ES/_db.py +225 -0
  4. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_ES/functions.py +9 -1
  5. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_ES/mergers.py +24 -4
  6. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_ES/social.py +339 -314
  7. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_ES/utils.py +15 -0
  8. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_ES/weather.py +4 -0
  9. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2/hypercadaster_es.egg-info}/PKG-INFO +1 -1
  10. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_es.egg-info/SOURCES.txt +1 -0
  11. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/setup.py +1 -1
  12. hypercadaster_es-1.2.2/tests/test_cat_cache.py +135 -0
  13. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/tests/test_social.py +10 -7
  14. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/LICENSE +0 -0
  15. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/MANIFEST.in +0 -0
  16. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/README.md +0 -0
  17. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_ES/_pretty.py +0 -0
  18. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_ES/building_inference.py +0 -0
  19. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_ES/cached_files/ine_inspire_codes.xlsx +0 -0
  20. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_ES/downloaders.py +0 -0
  21. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_ES/energy.py +0 -0
  22. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_ES/energy_config.yaml +0 -0
  23. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_ES/interoperability.py +0 -0
  24. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_es.egg-info/dependency_links.txt +0 -0
  25. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_es.egg-info/requires.txt +0 -0
  26. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/hypercadaster_es.egg-info/top_level.txt +0 -0
  27. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/setup.cfg +0 -0
  28. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/tests/test_aggregation.py +0 -0
  29. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/tests/test_code_normalisation.py +0 -0
  30. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/tests/test_codes.py +0 -0
  31. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/tests/test_dem_tiles.py +0 -0
  32. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/tests/test_energy_config.py +0 -0
  33. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/tests/test_geometry.py +0 -0
  34. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/tests/test_import_surface.py +0 -0
  35. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/tests/test_live_smoke.py +0 -0
  36. {hypercadaster_es-1.2.1 → hypercadaster_es-1.2.2}/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.1
3
+ Version: 1.2.2
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.1"
29
+ __version__ = "1.2.2"
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
  # ---------------------------------------------------------------------------
@@ -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.
@@ -1097,9 +1097,20 @@ def join_cadaster_building(gdf, cadaster_dir, census_tracts_dir, DEM_raster_dir,
1097
1097
  if 'building_geometry' in building_gdf_.columns:
1098
1098
  building_gdf_ = assign_building_zones(building_gdf_, cadaster_dir, code)
1099
1099
 
1100
- # Parse CAT file, if available
1100
+ # Parse CAT file, if available. The parsed per-space table is cached in
1101
+ # the central DuckDB (`cat_building_spaces`, keyed by cadaster_code) and
1102
+ # reused on every re-run — it feeds the (cheap) per-use-type area pivot
1103
+ # below and is the input to the (expensive) per-building aggregation that
1104
+ # is itself cached separately as `cat_building_attributes`. Like the raw
1105
+ # .CAT→parquet cache, these are pure functions of the static CAT files, so
1106
+ # they are reused regardless of `force_update`; clear them with
1107
+ # hc.utils.clear_cat_cache to force a re-parse/re-aggregate.
1101
1108
  if building_parts_inference_using_CAT_files:
1102
- buildings_CAT = building_inference.parse_horizontal_division_buildings_CAT_files(code, CAT_files_dir)
1109
+ from hypercadaster_ES import _db as _db_mod_cat
1110
+ buildings_CAT = _db_mod_cat.cat_cache_read(results_dir, code)
1111
+ if buildings_CAT is None:
1112
+ buildings_CAT = building_inference.parse_horizontal_division_buildings_CAT_files(code, CAT_files_dir)
1113
+ _db_mod_cat.cat_cache_write(results_dir, code, buildings_CAT)
1103
1114
  else:
1104
1115
  buildings_CAT = None
1105
1116
 
@@ -1491,8 +1502,17 @@ def join_cadaster_building(gdf, cadaster_dir, census_tracts_dir, DEM_raster_dir,
1491
1502
  # CAT yields the full br__* per-building aggregates (building_spaces_*,
1492
1503
  # area_with_communals, economic_value, ...) without any geometric
1493
1504
  # inference — fold them in so this path matches the inference path
1494
- # for all CAT-derived columns.
1495
- br_cat = building_inference.br_attributes_from_CAT(buildings_CAT)
1505
+ # for all CAT-derived columns. br_attributes_from_CAT is a
1506
+ # per-building aggregation that runs for minutes on a large
1507
+ # municipality (the dominant cost of a no-inference CAT merge), so
1508
+ # its output is cached in the central DuckDB (`cat_building_attributes`,
1509
+ # keyed by cadaster_code) and reused on every re-run. Like the CAT
1510
+ # parse cache it is a pure function of the static CAT files.
1511
+ from hypercadaster_ES import _db as _db_mod_cat
1512
+ br_cat = _db_mod_cat.cat_attrs_read(results_dir, code)
1513
+ if br_cat is None:
1514
+ br_cat = building_inference.br_attributes_from_CAT(buildings_CAT)
1515
+ _db_mod_cat.cat_attrs_write(results_dir, code, br_cat)
1496
1516
  building_gdf_ = building_gdf_.merge(br_cat, on="building_reference", how="left")
1497
1517
 
1498
1518
  use_types = buildings_CAT["building_space_inferred_use_type"].unique().to_list()