hypercadaster-ES 1.0.0__py3-none-any.whl

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.
@@ -0,0 +1,1713 @@
1
+ """Building inference and analysis module for hypercadaster_ES.
2
+
3
+ This module provides advanced functionality for analyzing and inferring building
4
+ characteristics from Spanish cadastral data, including:
5
+
6
+ - Building parts processing and geometric analysis
7
+ - Floor footprint calculation and space inference
8
+ - Orientation analysis and street relationship detection
9
+ - CAT file parsing for detailed building information
10
+ - Building space aggregation and classification
11
+
12
+ Main functions:
13
+ - process_building_parts(): Main orchestrator for building analysis pipeline
14
+ - process_zone(): Detailed analysis for individual cadastral zones
15
+ - parse_horizontal_division_buildings_CAT_files(): Parse CAT files for building data
16
+ - aggregate_CAT_file_building_spaces(): Aggregate building space information
17
+
18
+ Note: This module contains computationally intensive functions that process
19
+ large amounts of geometric and cadastral data.
20
+ """
21
+
22
+ # Core libraries
23
+ import os
24
+ import sys
25
+ import math
26
+ import multiprocessing
27
+ import re
28
+ import warnings
29
+ from datetime import date
30
+ from itertools import chain, zip_longest
31
+ import itertools
32
+ import random
33
+
34
+ # Data processing
35
+ import numpy as np
36
+ import pandas as pd
37
+ import polars as pl
38
+ from tqdm import tqdm
39
+
40
+ # Geospatial libraries
41
+ import geopandas as gpd
42
+ from shapely.ops import linemerge
43
+ from shapely.geometry.polygon import orient
44
+ from shapely.geometry import (Polygon, LineString, LinearRing, MultiPolygon, MultiLineString)
45
+
46
+ # Visualization
47
+ import matplotlib
48
+ matplotlib.use('Agg') # Use a non-interactive backend
49
+ import matplotlib.pyplot as plt
50
+ from matplotlib.backends.backend_pdf import PdfPages
51
+
52
+ # Internal modules
53
+ from hypercadaster_ES import utils
54
+ from hypercadaster_ES import downloaders
55
+
56
+ # Configure warnings
57
+ warnings.simplefilter(action='ignore', category=pd.errors.SettingWithCopyWarning)
58
+ warnings.filterwarnings(
59
+ "ignore",
60
+ message=re.escape("FigureCanvasAgg is non-interactive, and thus cannot be shown")
61
+ )
62
+
63
+ # Note: Parallel processing imports commented out for performance
64
+ # from joblib import Parallel, delayed
65
+ # from joblib.externals.loky import get_reusable_executor
66
+
67
+
68
+ # ==========================================
69
+ # MAIN BUILDING ANALYSIS PIPELINE
70
+ # ==========================================
71
+
72
+ def process_building_parts(code, building_part_gdf_, buildings_CAT, parcels_gdf, results_dir=None, cadaster_dir=None,
73
+ open_street_dir=None, plots=False, plot_zones_ratio=0.01,
74
+ orientation_discrete_interval_in_degrees=5,
75
+ num_workers=max(1, math.ceil(multiprocessing.cpu_count()/3))):
76
+ """
77
+ Main function to process building parts and perform comprehensive building analysis.
78
+
79
+ This function orchestrates the entire building inference pipeline including:
80
+ - Building proximity detection and clustering
81
+ - Floor footprint calculation
82
+ - Orientation analysis and street relationship detection
83
+ - Building space classification and aggregation
84
+ - Shadow analysis and environmental factors
85
+
86
+ Parameters:
87
+ -----------
88
+ code : str
89
+ Cadastral municipality code
90
+ building_part_gdf_ : geopandas.GeoDataFrame
91
+ Building parts geodataframe with geometric information
92
+ buildings_CAT : polars.DataFrame or None
93
+ CAT file data with detailed building information
94
+ parcels_gdf : geopandas.GeoDataFrame
95
+ Cadastral parcels geodataframe
96
+ results_dir : str, optional
97
+ Directory to save analysis results and cache files
98
+ cadaster_dir : str, optional
99
+ Directory containing cadastral data files
100
+ open_street_dir : str, optional
101
+ Directory containing OpenStreetMap data
102
+ plots : bool, default False
103
+ Whether to generate visualization plots
104
+ plot_zones_ratio : float, default 0.01
105
+ Ratio of zones to randomly select for plotting when plots=True (0.01 = 1%, minimum 1 zone)
106
+ orientation_discrete_interval_in_degrees : int, default 5
107
+ Degree interval for orientation discretization
108
+ num_workers : int, default calculated
109
+ Number of parallel workers for processing
110
+
111
+ Returns:
112
+ --------
113
+ tuple
114
+ (processed_gdf, analysis_results) containing processed building data
115
+ and comprehensive analysis results
116
+ """
117
+
118
+ if (not os.path.exists(f"{results_dir}/{code}_sbr_results.pkl") and
119
+ not os.path.exists(f"{results_dir}/{code}_br_results.pkl")):
120
+
121
+ os.makedirs(f"{results_dir}/cache", exist_ok=True)
122
+ if plots:
123
+ if results_dir is None:
124
+ results_dir = "results"
125
+ os.makedirs(f"{results_dir}/plots", exist_ok=True)
126
+
127
+ if (not os.path.exists(f"{results_dir}/cache/{code}_aux1.pkl")):
128
+ gdf_global = utils.detect_close_buildings_parallel(gdf_building_parts=building_part_gdf_,
129
+ buffer_neighbours=80,
130
+ neighbours_column_name="nearby_buildings",
131
+ neighbours_id_column_name="building_reference",
132
+ num_workers=-1,
133
+ column_name_to_split="zone_reference")
134
+ parcels_gdf["zone_reference"] = (
135
+ parcels_gdf["building_reference"].str[0:5] + parcels_gdf["building_reference"].str[7:14])
136
+ gdf_parcels_global = utils.detect_close_parcels_parallel(gdf_parcels=parcels_gdf,
137
+ buffer_neighbours=150,
138
+ neighbours_column_name="nearby_parcels",
139
+ neighbours_id_column_name="building_reference",
140
+ num_workers=-1,
141
+ column_name_to_split="zone_reference")
142
+ gdf_global = gdf_global.merge(
143
+ gdf_parcels_global[["building_reference","nearby_parcels"]],
144
+ on="building_reference", how="left")
145
+ gdf_global = gdf_global.set_geometry("building_part_geometry")
146
+ gdf_global.to_pickle(f"{results_dir}/cache/{code}_aux1.pkl")
147
+ else:
148
+ gdf_global = pd.read_pickle(f"{results_dir}/cache/{code}_aux1.pkl")
149
+
150
+ if (not os.path.exists(f"{results_dir}/cache/{code}_aux2.pkl")):
151
+ gdf_footprints_global = utils.calculate_floor_footprints(
152
+ gdf=gdf_global,
153
+ group_by="building_reference",
154
+ geometry_name="building_part_geometry",
155
+ only_exterior_geometry=True,
156
+ min_hole_area=0.5,
157
+ gap_tolerance=0.05,
158
+ chunk_size=500,
159
+ num_workers=-1)
160
+ gdf_footprints_global.to_pickle(f"{results_dir}/cache/{code}_aux2.pkl")
161
+ else:
162
+ gdf_footprints_global = pd.read_pickle(f"{results_dir}/cache/{code}_aux2.pkl")
163
+
164
+
165
+ grouped = gdf_global.groupby("zone_reference")
166
+ zone_references = list(grouped.groups.keys())
167
+
168
+ # Random zone selection for plots when building_parts_plots is True
169
+ if plots:
170
+ total_zones = len(zone_references)
171
+ # Calculate number of zones to plot: at least 1, or the specified ratio
172
+ num_zones_to_plot = max(1, int(total_zones * plot_zones_ratio))
173
+ if num_zones_to_plot < total_zones:
174
+ # Randomly select zones for plotting
175
+ zones_to_plot = set(random.sample(zone_references, num_zones_to_plot))
176
+ print(f"Randomly selected {num_zones_to_plot} out of {total_zones} zones for plotting ({plot_zones_ratio*100:.1f}%)")
177
+ else:
178
+ # Plot all zones if ratio results in all zones
179
+ zones_to_plot = set(zone_references)
180
+ print(f"Plotting all {total_zones} zones")
181
+ else:
182
+ zones_to_plot = set()
183
+
184
+ ine_code = utils.cadaster_to_ine_codes(cadaster_dir, [code])[0]
185
+ streets_gdf = utils.get_municipality_open_street_maps(
186
+ open_street_dir=open_street_dir,
187
+ query_location=f"{utils.municipality_name(ine_code)}, Spain",
188
+ crs=gdf_global.crs)
189
+ streets_gdf = streets_gdf[streets_gdf.geometry.apply(lambda geom: isinstance(geom, LineString))]
190
+
191
+ # Define zone processing function
192
+ def process_zone_delayed(zone_reference):
193
+ gdf_zone = grouped.get_group(zone_reference).reset_index(drop=True)
194
+ # Determine if this zone should be plotted based on selection
195
+ zone_plots = plots and (zone_reference in zones_to_plot)
196
+ return process_zone(
197
+ gdf_zone,
198
+ zone_reference,
199
+ gdf_footprints_global,
200
+ parcels_gdf,
201
+ streets_gdf,
202
+ buildings_CAT,
203
+ results_dir,
204
+ zone_plots,
205
+ orientation_discrete_interval_in_degrees
206
+ )
207
+
208
+ # Process each zone sequentially with progress tracking
209
+ results = []
210
+ for zone_reference in tqdm(zone_references, desc="Inferring geometrical KPIs for each building..."):
211
+ results.append(process_zone_delayed(zone_reference))
212
+
213
+ # Note: Parallel processing commented out for performance reasons
214
+ # Alternative parallel implementation available if needed
215
+
216
+ # del streets_gdf
217
+ # del gdf_global
218
+ # del gdf_footprints_global
219
+ # del grouped
220
+
221
+ # Concatenate all results into a single DataFrame
222
+ sbr_results = pd.concat([i[0] for i in results if i is not None])[results[0][0].columns]
223
+ br_results = pd.concat([i[1] for i in results if i is not None])[results[0][1].columns]
224
+ del results
225
+
226
+ sbr_results.to_pickle(f"{results_dir}/{code}_sbr_results.pkl",
227
+ compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1})
228
+ br_results.to_pickle(f"{results_dir}/{code}_br_results.pkl",
229
+ compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1})
230
+
231
+ else:
232
+ sbr_results = pd.read_pickle(f"{results_dir}/{code}_sbr_results.pkl", compression="gzip")
233
+ br_results = pd.read_pickle(f"{results_dir}/{code}_br_results.pkl", compression="gzip")
234
+
235
+ return sbr_results, br_results
236
+
237
+
238
+ # ==========================================
239
+ # ZONE-LEVEL ANALYSIS FUNCTIONS
240
+ # ==========================================
241
+
242
+ def process_zone(gdf_zone, zone_reference, gdf_footprints_global, parcels_gdf, streets_gdf, buildings_CAT,
243
+ results_dir, plots, orientation_discrete_interval_in_degrees):
244
+ """
245
+ Perform detailed analysis for an individual cadastral zone.
246
+
247
+ This function processes all buildings within a specific cadastral zone,
248
+ analyzing their geometric properties, orientations, relationships with
249
+ streets, and shadow patterns.
250
+
251
+ Parameters:
252
+ -----------
253
+ gdf_zone : geopandas.GeoDataFrame
254
+ Buildings within the specific zone to analyze
255
+ zone_reference : str
256
+ Unique identifier for the cadastral zone
257
+ gdf_footprints_global : geopandas.GeoDataFrame
258
+ Global floor footprints for shadow analysis
259
+ parcels_gdf : geopandas.GeoDataFrame
260
+ Cadastral parcels within the zone
261
+ streets_gdf : geopandas.GeoDataFrame
262
+ Street network data for orientation analysis
263
+ buildings_CAT : polars.DataFrame or None
264
+ CAT file building data
265
+ results_dir : str
266
+ Directory for saving cache and plot outputs
267
+ plots : bool
268
+ Whether to generate analysis plots
269
+ orientation_discrete_interval_in_degrees : int
270
+ Orientation discretization interval
271
+
272
+ Returns:
273
+ --------
274
+ dict
275
+ Comprehensive analysis results for the zone including building
276
+ metrics, orientations, and environmental factors
277
+ """
278
+
279
+ try:
280
+ if (not os.path.exists(f"{results_dir}/cache/{zone_reference}_sbr_results.pkl") and
281
+ not os.path.exists(f"{results_dir}/cache/{zone_reference}_br_results.pkl")):
282
+
283
+ # PDF setup for the zone if pdf_plots is True
284
+ if plots:
285
+ pdf = PdfPages(f"{results_dir}/plots/zone_{zone_reference}.pdf")
286
+
287
+ # Calculation of the single building references and adjacent buildings
288
+ gdf_zone = utils.detect_close_buildings(gdf_building_parts = gdf_zone,
289
+ buffer_neighbours = 0.5,
290
+ neighbours_column_name = "adjacent_buildings",
291
+ neighbours_id_column_name = "single_building_reference",
292
+ geometry_variable="building_part_geometry")
293
+
294
+ # Calculation of the single building references and adjacent buildings
295
+ gdf_zone = utils.detect_close_buildings(gdf_building_parts=gdf_zone,
296
+ buffer_neighbours=1,
297
+ neighbours_column_name="adjacent_parcels",
298
+ neighbours_id_column_name="single_building_reference",
299
+ geometry_variable="parcel_geometry")
300
+
301
+ if plots:
302
+ fig, ax = plt.subplots()
303
+ utils.plot_shapely_geometries(gdf_zone.building_part_geometry,
304
+ labels=gdf_zone.n_floors_above_ground,
305
+ clusters=gdf_zone.single_building_reference,
306
+ ax=ax)
307
+ pdf.savefig(fig)
308
+ plt.close(fig)
309
+
310
+ gdf_aux_footprints = utils.calculate_floor_footprints(
311
+ gdf=gdf_zone,
312
+ group_by="single_building_reference",
313
+ geometry_name="building_part_geometry",
314
+ min_hole_area=0.5,
315
+ gap_tolerance=0.05,
316
+ num_workers=1)
317
+
318
+ gdf_aux_footprints_global = utils.calculate_floor_footprints(
319
+ gdf=gdf_zone,
320
+ geometry_name="building_part_geometry",
321
+ min_hole_area=0.5,
322
+ gap_tolerance=0.05,
323
+ num_workers=1)
324
+
325
+ if plots:
326
+ fig, ax = plt.subplots()
327
+ utils.plot_shapely_geometries(gdf_aux_footprints.geometry, clusters=gdf_aux_footprints.group, ax=ax)
328
+ pdf.savefig(fig)
329
+ plt.close(fig)
330
+
331
+ # Detect all the patios in a zone
332
+ patios_detected = {}
333
+ for floor in range(gdf_aux_footprints.floor.max() + 1):
334
+ patios_detected[floor] = (
335
+ utils.get_all_patios(gdf_aux_footprints_global[gdf_aux_footprints_global['floor']==floor].geometry))
336
+
337
+ unique_patios_detected = utils.unique_polygons(list(itertools.chain(*patios_detected.values())),tolerance=0.1)
338
+
339
+ if plots:
340
+ fig, ax = plt.subplots()
341
+ utils.plot_shapely_geometries([i.exterior for i in gdf_zone.building_part_geometry] + unique_patios_detected, ax=ax)
342
+ pdf.savefig(fig)
343
+ plt.close(fig)
344
+
345
+ # Close the PDF file for the current zone
346
+ if plots:
347
+ pdf.close()
348
+
349
+ results_ = []
350
+
351
+ for single_building_reference, building_gdf_item in gdf_zone.groupby('single_building_reference'):
352
+ # grouped2 = gdf_zone.groupby("single_building_reference")
353
+ # single_building_reference = list(grouped2.groups.keys())[0]
354
+ # building_gdf_item = grouped2.get_group(single_building_reference).reset_index().drop(['index'], axis=1).copy()
355
+
356
+ # PDF setup for the building if plots is True
357
+ if plots:
358
+ pdf = PdfPages(f"{results_dir}/plots/building_{single_building_reference}.pdf")
359
+
360
+ # Obtain a general geometry of the building, considering all floors.
361
+ building_geom = utils.union_geoseries_with_tolerance(building_gdf_item['building_part_geometry'],
362
+ gap_tolerance=0.05, resolution=16)
363
+ parcel_geom = utils.union_geoseries_with_tolerance(building_gdf_item["parcel_geometry"],
364
+ gap_tolerance=0.5, resolution=0.5)
365
+
366
+ # Extract and clean the set of neighbouring buildings
367
+ adjacent_buildings_set = {id for ids in building_gdf_item['adjacent_buildings'] for id in ids.split(",")}
368
+ adjacent_buildings_set.discard(
369
+ single_building_reference) # Safely remove the single_building_reference itself if present
370
+ adjacent_buildings = sorted(adjacent_buildings_set)
371
+
372
+ # Extract and clean the set of nearby buildings
373
+ nearby_buildings_set = {id for ids in building_gdf_item['nearby_buildings'] for id in ids.split(",")}
374
+ nearby_buildings_set.discard(
375
+ single_building_reference.split("_")[0]) # Safely remove the single_building_reference itself
376
+ nearby_buildings = sorted(nearby_buildings_set)
377
+
378
+ # Extract and clean the set of nearby parcels
379
+ nearby_parcels_set = {id for ids in building_gdf_item['nearby_parcels'] for id in ids.split(",")}
380
+ nearby_parcels_set.discard(
381
+ single_building_reference.split("_")[0]) # Safely remove the single_building_reference itself
382
+ nearby_parcels = sorted(nearby_parcels_set)
383
+
384
+ # Extract and clean the set of adjacent parcels
385
+ adjacent_parcels_set = {id for ids in building_gdf_item['adjacent_parcels'] for id in ids.split(",")}
386
+ adjacent_parcels_set.discard(
387
+ single_building_reference) # Safely remove the single_building_reference itself if present
388
+ adjacent_parcels = sorted(adjacent_parcels_set)
389
+
390
+ # Is there any premises in ground floor?
391
+ premises = False
392
+ premises_activity_typologies = []
393
+ premises_names = []
394
+ premises_last_revision = []
395
+ if "number_of_ground_premises" in building_gdf_item.columns:
396
+ if (~np.isfinite(building_gdf_item.iloc[0]["number_of_ground_premises"]) and
397
+ building_gdf_item.iloc[0]["number_of_ground_premises"] > 0):
398
+ premises = True
399
+ premises_activity_typologies = building_gdf_item.iloc[0]["ground_premises_activities"]
400
+ premises_names = building_gdf_item.iloc[0]["ground_premises_names"]
401
+ premises_last_revision = building_gdf_item.iloc[0]["ground_premises_last_revision"]
402
+
403
+ # Filter building in study
404
+ gdf_aux_footprint_building = gdf_aux_footprints[gdf_aux_footprints['group'] == single_building_reference]
405
+ if plots:
406
+ fig, ax = plt.subplots()
407
+ utils.plot_shapely_geometries(list(gdf_aux_footprint_building.geometry), ax=ax,
408
+ title = "Building in analysis")
409
+ pdf.savefig(fig)
410
+ plt.close(fig)
411
+
412
+ # Filter related buildings footprint
413
+ gdf_aux_footprints_ = gdf_aux_footprints[gdf_aux_footprints['group'].isin(adjacent_buildings)]
414
+ if plots:
415
+ fig, ax = plt.subplots()
416
+ utils.plot_shapely_geometries(gdf_aux_footprints_.geometry, clusters=gdf_aux_footprints_.group, ax=ax,
417
+ contextual_geometry = building_geom,
418
+ title = "Adjacent buildings")
419
+ pdf.savefig(fig)
420
+ plt.close(fig)
421
+
422
+ # Filter related buildings footprint
423
+ gdf_aux_footprints_nearby = gdf_footprints_global[gdf_footprints_global['group'].isin(nearby_buildings)]
424
+ if plots:
425
+ fig, ax = plt.subplots()
426
+ utils.plot_shapely_geometries(gdf_aux_footprints_nearby.geometry, clusters=gdf_aux_footprints_nearby.group,
427
+ ax=ax, contextual_geometry=building_geom,
428
+ title="Nearby buildings")
429
+ pdf.savefig(fig)
430
+ plt.close(fig)
431
+
432
+ # Filter related parcels
433
+ related_parcels_geom = []
434
+ nearby_related_parcels_geom = []
435
+ related_union = None
436
+ if len(adjacent_parcels)>0:
437
+ related_parcels_geom = gdf_zone.loc[gdf_zone["single_building_reference"].isin(adjacent_parcels), "parcel_geometry"]
438
+ related_parcels_geom = [utils.union_geoseries_with_tolerance(item,gap_tolerance=0.05, resolution=2) for item
439
+ in list(related_parcels_geom.drop_duplicates())]
440
+ if len(nearby_parcels)>0:
441
+ nearby_related_parcels_geom = parcels_gdf.loc[parcels_gdf['building_reference'].isin(nearby_parcels), "parcel_geometry"]
442
+ nearby_related_parcels_geom = [utils.union_geoseries_with_tolerance(item, gap_tolerance=0.05, resolution=2) for item
443
+ in list(nearby_related_parcels_geom.drop_duplicates())]
444
+
445
+ # Detect which is the part of the parcel in contact with the street
446
+ filtered_streets = streets_gdf[streets_gdf.geometry.distance(parcel_geom.centroid) <= 200]
447
+ filtered_streets.reset_index(inplace=True)
448
+ filtered_streets = filtered_streets[filtered_streets.element == "way"]
449
+
450
+ if isinstance(parcel_geom, MultiPolygon):
451
+ parcel_limits = [walls_i for walls_i in list(parcel_geom)[0].geoms]
452
+ else:
453
+ parcel_limits = [parcel_geom]
454
+
455
+ all_parcel_segments = []
456
+ touching_street_and_non_adjacent_parcel_segments = []
457
+ non_adjacent_parcel_segments = []
458
+
459
+ for geom in parcel_limits:
460
+ filtered_streets = filtered_streets[~filtered_streets.geometry.intersects(geom)]
461
+ exterior_coords = list(orient(geom, sign=-1.0).exterior.coords)
462
+ #utils.plot_points_with_indices(exterior_coords)
463
+ for i in range(len(exterior_coords) - 1):
464
+ segment = LineString([exterior_coords[i], exterior_coords[i + 1]])
465
+ # utils.plot_polygons_group(related_parcels_geom,
466
+ # utils.shorten_linestring(segment, 0.1).buffer(2, cap_style="flat"),
467
+ # pdf_file="test2.pdf")
468
+ all_parcel_segments.append(segment)
469
+ if (len(related_parcels_geom)==0 or
470
+ not np.any([related_parcel_geom.intersects(
471
+ utils.shorten_linestring(segment, 0.1).buffer(2,cap_style="flat")) for
472
+ related_parcel_geom in related_parcels_geom])):
473
+ if utils.is_segment_in_contact_with_street(
474
+ segment, streets = filtered_streets, max_distance=8, orientation_tolerance=15,
475
+ orientation_discrete_interval_in_degrees=orientation_discrete_interval_in_degrees):
476
+ touching_street_and_non_adjacent_parcel_segments.append(segment)
477
+ else:
478
+ non_adjacent_parcel_segments.append(segment)
479
+ street_parcel_limits = {"by_orientation": {}}
480
+
481
+ if len(touching_street_and_non_adjacent_parcel_segments) > 0:
482
+ street_parcel_limits_segments = touching_street_and_non_adjacent_parcel_segments
483
+ elif len(non_adjacent_parcel_segments) > 0:
484
+ street_parcel_limits_segments = non_adjacent_parcel_segments
485
+ else:
486
+ street_parcel_limits_segments = all_parcel_segments
487
+
488
+ for segment in street_parcel_limits_segments:
489
+ segment_orientation = str(utils.calculate_wall_outdoor_normal_orientation(
490
+ segment,
491
+ orientation_interval=orientation_discrete_interval_in_degrees))
492
+ if segment_orientation in street_parcel_limits["by_orientation"]:
493
+ street_parcel_limits["by_orientation"][segment_orientation] += segment.length
494
+ else:
495
+ street_parcel_limits["by_orientation"][segment_orientation] = segment.length
496
+ if utils.detect_number_of_orientations(street_parcel_limits["by_orientation"])==1:
497
+ street_parcel_limits["main_orientation"] = utils.weighted_circular_mean(
498
+ degrees=[float(i) for i in street_parcel_limits["by_orientation"].keys()],
499
+ weights=[float(i) for i in street_parcel_limits["by_orientation"].values()])
500
+ else:
501
+ main_orientation = max(street_parcel_limits["by_orientation"].items(), key=lambda item: item[1])[0]
502
+ street_parcel_limits["main_orientation"] = float(main_orientation)
503
+
504
+ if plots:
505
+ pdf2 = PdfPages(f"{results_dir}/plots/building_{single_building_reference}_streets.pdf")
506
+ fig, ax = plt.subplots(figsize=(15,15))
507
+ utils.plot_shapely_geometries(geometries=list(filtered_streets.geometry), ax=ax,
508
+ contextual_geometry=[parcel_geom],
509
+ contextual_geometry_options={
510
+ "linestyle": "solid",
511
+ "linewidth": 1.0,
512
+ "color": "red",
513
+ "alpha": 1,
514
+ })
515
+ pdf2.savefig(fig)
516
+ fig, ax = plt.subplots(figsize=(15,15))
517
+ utils.plot_shapely_geometries(geometries=list(filtered_streets.geometry), ax=ax,
518
+ contextual_geometry=street_parcel_limits_segments,
519
+ contextual_geometry_options={
520
+ "linestyle": "solid",
521
+ "linewidth": 1.0,
522
+ "color": "red",
523
+ "alpha": 1,
524
+ })
525
+ pdf2.savefig(fig)
526
+ plt.close(fig)
527
+ pdf2.close()
528
+
529
+ floor_area = {}
530
+ underground_floor_area = {}
531
+ roof_area = {}
532
+ patios_area = {}
533
+ patios_n = {}
534
+ perimeter = {}
535
+ air_contact_wall = {}
536
+ shadows_at_distance = {}
537
+ parcel_at_distance = {}
538
+ adiabatic_wall = {}
539
+ patios_wall = {}
540
+ significant_orientations = []
541
+ significant_orientations_by_floor = {}
542
+ n_floors = gdf_aux_footprint_building.floor.max() if gdf_aux_footprint_building.floor.max() >= 0 else np.nan
543
+ n_underground_floors = -gdf_aux_footprint_building.floor.min() if gdf_aux_footprint_building.floor.min() < 0 else 0
544
+ n_buildings = len(
545
+ gdf_zone[
546
+ gdf_zone["building_reference"] == building_gdf_item.iloc[0]["building_reference"]
547
+ ]["single_building_reference"].unique()
548
+ )
549
+
550
+ if n_underground_floors > 0:
551
+
552
+ for underground_floor in range(1,(n_underground_floors+1)):
553
+ underground_floor_area[(underground_floor)] = round(
554
+ gdf_aux_footprint_building[gdf_aux_footprint_building["floor"] == -(underground_floor)]['geometry'].area.sum(),
555
+ 2
556
+ )
557
+
558
+ if n_floors is not np.nan:
559
+
560
+ for floor in range(n_floors + 1):
561
+ floor_area[floor] = round(
562
+ gdf_aux_footprint_building[gdf_aux_footprint_building["floor"] == floor]['geometry'].area.sum(),
563
+ 2
564
+ )
565
+ if floor == n_floors:
566
+ roof_area[floor] = round(
567
+ gdf_aux_footprint_building[gdf_aux_footprint_building["floor"] == floor]['geometry'].area.sum(),
568
+ 2
569
+ )
570
+ else:
571
+ roof_area[floor] = round(
572
+ gdf_aux_footprint_building[gdf_aux_footprint_building["floor"] == floor][
573
+ 'geometry'].area.sum() -
574
+ gdf_aux_footprint_building[gdf_aux_footprint_building["floor"] == (floor + 1)][
575
+ 'geometry'].area.sum(),
576
+ 2
577
+ )
578
+ patios = utils.patios_in_the_building(
579
+ patios_geoms=patios_detected[floor],
580
+ building_geom=building_geom,
581
+ tolerance=0.8
582
+ )
583
+ patios_n[floor] = len(patios)
584
+ patios_area[floor] = round(sum([patio.area for patio in patios]), 2)
585
+ walls = gdf_aux_footprint_building[gdf_aux_footprint_building["floor"] == floor]['geometry']
586
+ if isinstance(list(walls)[0], MultiPolygon):
587
+ walls = [walls_i for walls_i in list(walls)[0].geoms]
588
+ elif isinstance(list(walls)[0], Polygon):
589
+ walls = list(walls)
590
+
591
+ # Initialize the lengths for each type of wall contact and for each orientation
592
+ air_contact_wall[floor] = {direction: 0.0 for direction in [str(i) for i in
593
+ list(range(0, 360, orientation_discrete_interval_in_degrees))]}
594
+ adiabatic_wall[floor] = 0.0
595
+ patios_wall[floor] = 0.0
596
+ perimeter[floor] = round(sum([peri.exterior.length for peri in walls]), 2)
597
+
598
+ for geom in walls:
599
+
600
+ # Indoor patios
601
+ patios_wall[floor] += sum([item.length for item in list(geom.interiors)])
602
+
603
+ # Break down the exterior into segments
604
+ exterior_coords = list(orient(geom, sign=-1.0).exterior.coords)
605
+ for i in range(len(exterior_coords) - 1):
606
+ segment_assigned = False
607
+ segment = LineString([exterior_coords[i], exterior_coords[i + 1]])
608
+ if segment.length < 0.001:
609
+ continue
610
+
611
+ # Determine the orientation of this segment
612
+ segment_orientation = str(utils.calculate_wall_outdoor_normal_orientation(
613
+ segment,
614
+ orientation_interval=orientation_discrete_interval_in_degrees))
615
+
616
+ # Check if the segment is in contact with patios
617
+ for patio in patios:
618
+ if utils.segment_intersects_with_tolerance(
619
+ segment, patio,
620
+ buffer_distance=0.1,
621
+ area_percentage_threshold=15
622
+ ):
623
+ patios_wall[floor] += round(segment.length, 2)
624
+ if plots:
625
+ fig, ax = plt.subplots()
626
+ utils.plot_shapely_geometries(
627
+ geometries = [geom] + [segment],
628
+ title = f"Wall ID:{i}, floor: {floor},\n"
629
+ f"orientation: {segment_orientation},"
630
+ f"type: patio",
631
+ ax = ax,
632
+ contextual_geometry = building_geom)
633
+ pdf.savefig(fig)
634
+ plt.close(fig)
635
+ segment_assigned = True
636
+ break
637
+
638
+ # Check if the segment is in contact with nearby buildings
639
+ if not segment_assigned:
640
+ for aux_geom in gdf_aux_footprints_[gdf_aux_footprints_.floor == floor].geometry:
641
+ if utils.segment_intersects_with_tolerance(
642
+ segment, aux_geom,
643
+ buffer_distance=0.1,
644
+ area_percentage_threshold=15
645
+ ):
646
+ adiabatic_wall[floor] += round(segment.length, 2)
647
+ if plots:
648
+ fig, ax = plt.subplots()
649
+ utils.plot_shapely_geometries(
650
+ geometries = [geom] + [segment],
651
+ title = f"Wall ID: {i}, floor: {floor},\n"
652
+ f"orientation: {segment_orientation}, "
653
+ f"type: adiabatic",
654
+ ax = ax,
655
+ contextual_geometry = building_geom)
656
+ pdf.savefig(fig)
657
+ plt.close(fig)
658
+ segment_assigned = True
659
+ break
660
+
661
+ # Check if the segment is in contact with outdoor (air contact)
662
+ if not segment_assigned:
663
+ air_contact_wall[floor][segment_orientation] += round(segment.length, 2)
664
+ if plots:
665
+ fig, ax = plt.subplots()
666
+ utils.plot_shapely_geometries(
667
+ geometries = [geom] + [segment],
668
+ title = f"Wall ID: {i}, floor: {floor},\n"
669
+ f"orientation: {segment_orientation}, "
670
+ f"type: air contact",
671
+ ax = ax,
672
+ contextual_geometry = building_geom)
673
+ pdf.savefig(fig)
674
+ plt.close(fig)
675
+ for floor, air_contact_walls in air_contact_wall.items():
676
+ significant_orientations_ = []
677
+ significant_threshold = 0.1 * perimeter[floor]
678
+
679
+ for orientation, wall_length in air_contact_walls.items():
680
+ if wall_length > significant_threshold:
681
+ significant_orientations_.append(int(orientation))
682
+
683
+ # Sort the significant orientations in ascending order for better readability
684
+ significant_orientations_ = sorted(list(set(significant_orientations_)))
685
+ significant_orientations.extend(significant_orientations_)
686
+ significant_orientations_by_floor[floor] = significant_orientations_
687
+ significant_orientations = list(set(significant_orientations))
688
+
689
+ # Close the PDF file for the current building
690
+ if plots:
691
+ pdf.close()
692
+
693
+ # if building_type == "Non-residential":
694
+ # starting_residential_floor = np.nan
695
+ # elif premises:
696
+ # starting_residential_floor = 1
697
+ # if building_type == "Multi-family" and n_floors >= n_dwellings:
698
+ # n_dwellings = n_dwellings - 1
699
+ # else:
700
+ # if n_floors > 6 and building_type == "Multi-family":
701
+ # starting_residential_floor = 1
702
+ # else:
703
+ # starting_residential_floor = 0
704
+ # floor_area_with_possible_residential_use = [floor_area[floor] if floor >= starting_residential_floor or starting_residential_floor is np.nan else 0.0 for floor in range(n_floors + 1)]
705
+
706
+ if max(gdf_aux_footprint_building.floor.max(), gdf_aux_footprints_nearby.floor.max()) > 0:
707
+
708
+ # Shadows depending orientation
709
+ if plots:
710
+ pdf = PdfPages(f"{results_dir}/plots/building_{single_building_reference}_shadows.pdf")
711
+ else:
712
+ pdf = None
713
+ for floor in range(max(gdf_aux_footprint_building.floor.max(),
714
+ gdf_aux_footprints_nearby.floor.max()) + 1):
715
+ shadows_at_distance[floor] = utils.distance_from_centroid_to_polygons_by_orientation(
716
+ geom=building_geom.exterior if isinstance(building_geom, Polygon) else (
717
+ ([LinearRing(polygon.exterior.coords) for polygon in building_geom.geoms])),
718
+ other_polygons=gdf_aux_footprints_nearby[gdf_aux_footprints_nearby.floor == floor].geometry,
719
+ centroid=building_geom.centroid,
720
+ orientation_interval=orientation_discrete_interval_in_degrees,
721
+ plots=plots,
722
+ pdf=pdf,
723
+ floor=floor,
724
+ max_distance=150
725
+ )
726
+ if plots:
727
+ pdf.close()
728
+
729
+ if len(nearby_related_parcels_geom)>0:
730
+ # Street widths
731
+ if plots:
732
+ pdf = PdfPages(f"{results_dir}/plots/building_{single_building_reference}_street_widths.pdf")
733
+ else:
734
+ pdf = None
735
+ parcel_at_distance = utils.distance_from_points_to_polygons_by_orientation(
736
+ geom=street_parcel_limits_segments,
737
+ other_polygons=nearby_related_parcels_geom,
738
+ num_points_per_geom_element=10,
739
+ orientations_to_analyse=sorted(street_parcel_limits["by_orientation"].keys(), key=int),
740
+ force_one_orientation_per_geom_element=True,
741
+ plots=plots,
742
+ pdf=pdf,
743
+ max_distance=150
744
+ )
745
+ if plots:
746
+ pdf.close()
747
+
748
+ street_parcel_limits["next_building_by_orientation"] = {}
749
+ if len(street_parcel_limits["by_orientation"]) > 0 and len(shadows_at_distance)>0:
750
+ for i in street_parcel_limits["by_orientation"].keys():
751
+ street_parcel_limits["next_building_by_orientation"][i] = shadows_at_distance[0]["shadows"][i]
752
+
753
+ street_parcel_limits["next_building_main_orientation"] = np.inf
754
+ if street_parcel_limits["main_orientation"] is not np.nan and len(shadows_at_distance)>0:
755
+ street_parcel_limits["next_building_main_orientation"] = shadows_at_distance[0]["shadows"][
756
+ str(utils.discrete_orientation(
757
+ street_parcel_limits["main_orientation"],
758
+ orientation_discrete_interval_in_degrees))
759
+ ]
760
+
761
+ street_parcel_limits["street_width_by_orientation"] = parcel_at_distance[0]
762
+ filtered = {k: v for k, v in street_parcel_limits["street_width_by_orientation"].items() if np.isfinite(v)}
763
+ if not filtered:
764
+ street_parcel_limits["street_width_main_orientation"] = np.inf
765
+ else:
766
+ street_parcel_limits["main_orientation"] = max(filtered, key=filtered.get)
767
+ street_parcel_limits["street_width_main_orientation"] = parcel_at_distance[0][
768
+ max(filtered, key=filtered.get)]
769
+
770
+ # Store results
771
+ results_.append({
772
+ 'building_reference': single_building_reference.split("_")[0],
773
+ 'single_building_reference': single_building_reference,
774
+ 'zone_reference': zone_reference,
775
+ 'sbr__n_buildings': n_buildings,
776
+ 'sbr__detached': (np.sum([adiabatic_wall[floor] for floor in range(n_floors + 1)]) if adiabatic_wall != {} else 0.0) < 1.0,
777
+ 'br__parcel_orientations': street_parcel_limits["by_orientation"],
778
+ 'br__parcel_main_orientation': street_parcel_limits["main_orientation"],
779
+ 'br__next_building_by_orientation': street_parcel_limits["next_building_by_orientation"],
780
+ 'br__next_building_main_orientation': street_parcel_limits["next_building_main_orientation"],
781
+ 'br__street_width_by_orientation': street_parcel_limits["street_width_by_orientation"],
782
+ 'br__street_width_main_orientation': street_parcel_limits["street_width_main_orientation"],
783
+ 'br__exists_ground_commercial_premises': premises,
784
+ 'br__ground_commercial_premises_names': premises_names,
785
+ 'br__ground_commercial_premises_typology': premises_activity_typologies,
786
+ 'br__ground_commercial_premises_last_revision': premises_last_revision,
787
+ 'sbr__floors_above_ground': n_floors+1,
788
+ 'sbr__floors_below_ground': n_underground_floors,
789
+ 'sbr__below_ground_built_area_by_floor': [underground_floor_area[floor] for floor in range(1,n_underground_floors + 1)] if n_underground_floors > 0 else [],
790
+ 'sbr__below_ground_built_area': np.sum([underground_floor_area[floor] for floor in range(1,n_underground_floors + 1)]) if n_underground_floors > 0 else 0.0,
791
+ 'sbr__above_ground_built_area_by_floor': [floor_area[floor] for floor in range(n_floors + 1)] if n_floors is not np.nan else [],
792
+ 'sbr__above_ground_built_area': np.sum([floor_area[floor] for floor in range(n_floors + 1)]) if n_floors is not np.nan else 0.0,
793
+ 'sbr__above_ground_roof_area_by_floor': [roof_area[floor] for floor in range(n_floors + 1)] if n_floors is not np.nan else [],
794
+ 'sbr__above_ground_roof_area': np.sum([roof_area[floor] for floor in range(n_floors + 1)]) if n_floors is not np.nan else 0.0,
795
+ 'sbr__building_footprint_area': round(building_geom.area if isinstance(building_geom, Polygon)
796
+ else sum(polygon.area for polygon in building_geom.geoms) if isinstance(building_geom, MultiPolygon)
797
+ else 0.0, 2),
798
+ 'sbr__building_footprint_geometry': building_geom.exterior if isinstance(building_geom, Polygon) else (
799
+ MultiLineString([LineString(polygon.exterior.coords) for polygon in building_geom.geoms])),
800
+ 'sbr__building_footprint_by_floor': gdf_aux_footprint_building[["group","floor","geometry"]].to_dict(index=False, orient='split')['data'],
801
+ 'sbr__patios_area_by_floor': [patios_area[floor] for floor in range(n_floors + 1)] if patios_area != {} else [],
802
+ 'sbr__patios_number_by_floor': [patios_n[floor] for floor in range(n_floors + 1)] if patios_n != {} else [],
803
+ 'sbr__walls_between_slabs': np.sum([perimeter[floor] for floor in
804
+ range(n_floors + 1)] if perimeter != {} else []),
805
+ 'sbr__building_perimeter_by_floor': [perimeter[floor] for floor in range(n_floors + 1)] if perimeter != {} else [],
806
+ 'sbr__air_contact_wall_by_floor': {key: [air_contact_wall[d][key] for d in air_contact_wall] for key in
807
+ air_contact_wall[0]} if air_contact_wall != {} else {},
808
+ 'sbr__air_contact_wall': {key: np.sum([air_contact_wall[d][key] for d in air_contact_wall]) for key in
809
+ air_contact_wall[0]} if air_contact_wall != {} else {},
810
+ 'sbr__air_contact_wall_significant_orientations': significant_orientations,
811
+ 'sbr__air_contact_wall_significant_orientations_by_floor': significant_orientations_by_floor,
812
+ 'sbr__adiabatic_wall_by_floor': [adiabatic_wall[floor] for floor in range(n_floors + 1)] if adiabatic_wall != {} else [],
813
+ 'sbr__adiabatic_wall': np.sum([adiabatic_wall[floor] for floor in range(n_floors + 1)]) if adiabatic_wall != {} else 0.0,
814
+ 'sbr__patios_wall_by_floor': [patios_wall[floor] for floor in range(n_floors + 1)] if patios_wall != {} else [],
815
+ 'sbr__patios_wall_total': np.sum([patios_wall[floor] for floor in range(n_floors + 1)]) if patios_wall != {} else 0.0,
816
+ 'sbr__shadows_at_distance': {key: [shadows_at_distance[d]['shadows'][key] for d in shadows_at_distance] for key in
817
+ shadows_at_distance[0]['shadows']} if shadows_at_distance != {} else {},
818
+ 'sbr__building_contour_at_distance': {key: np.mean([shadows_at_distance[d]['contour'][key] for d in shadows_at_distance]) for key in
819
+ shadows_at_distance[0]['contour']} if shadows_at_distance != {} else {}
820
+ })
821
+
822
+ if len(results_) > 0:
823
+ results_ = pd.DataFrame(results_)
824
+ sbr_results_concat = pd.DataFrame()
825
+ br_results_concat = pd.DataFrame()
826
+ for building_reference in results_.building_reference.unique():
827
+ # building_reference = "0004701DF3800C"#"9505401DF2890F"
828
+
829
+ sbr_results = results_[results_.building_reference == building_reference]
830
+ br_agg_dict = {
831
+ 'building_reference': [building_reference],
832
+ 'br__detached': [np.any(sbr_results['sbr__detached'])],
833
+ 'br__parcel_orientations': [sbr_results.iloc[0]['br__parcel_orientations']],
834
+ 'br__parcel_main_orientation': [sbr_results.iloc[0]['br__parcel_main_orientation']],
835
+ 'br__street_width_by_orientation': [sbr_results.iloc[0]['br__street_width_by_orientation']],
836
+ 'br__street_width_main_orientation': [sbr_results.iloc[0]['br__street_width_main_orientation']],
837
+ 'br__next_building_by_orientation': [sbr_results.iloc[0]['br__next_building_by_orientation']],
838
+ 'br__next_building_main_orientation': [sbr_results.iloc[0]['br__next_building_main_orientation']],
839
+ 'br__exists_ground_commercial_premises': [sbr_results.iloc[0]['br__exists_ground_commercial_premises']],
840
+ 'br__ground_commercial_premises_names': [sbr_results.iloc[0]['br__ground_commercial_premises_names']],
841
+ 'br__ground_commercial_premises_typology': [sbr_results.iloc[0]['br__ground_commercial_premises_typology']],
842
+ 'br__ground_commercial_premises_last_revision': [sbr_results.iloc[0]['br__ground_commercial_premises_last_revision']],
843
+ 'br__floors_above_ground': [max(sbr_results['sbr__floors_above_ground'])],
844
+ 'br__floors_below_ground': [max(sbr_results['sbr__floors_below_ground'])],
845
+ 'br__below_ground_built_area_by_floor': [[sum(values) for values in zip_longest(
846
+ *sbr_results['sbr__below_ground_built_area_by_floor'], fillvalue=0)]],
847
+ 'br__below_ground_built_area': [sum(sbr_results['sbr__below_ground_built_area'])],
848
+ 'br__above_ground_built_area_by_floor': [[sum(values) for values in zip_longest(
849
+ *sbr_results['sbr__above_ground_built_area_by_floor'], fillvalue=0)]],
850
+ 'br__above_ground_built_area': [sum(sbr_results['sbr__above_ground_built_area'])],
851
+ 'br__above_ground_roof_area_by_floor': [[sum(values) for values in zip_longest(
852
+ *sbr_results['sbr__above_ground_roof_area_by_floor'], fillvalue=0)]],
853
+ 'br__above_ground_roof_area': [sum(sbr_results['sbr__above_ground_roof_area'])],
854
+ 'br__building_footprint_area': [sum(sbr_results['sbr__building_footprint_area'])],
855
+ 'br__building_footprint_geometry': [linemerge(
856
+ [line for geom in sbr_results['sbr__building_footprint_geometry'].tolist() for line in
857
+ (geom.geoms if geom.geom_type == "MultiLineString" else [geom])])],
858
+ 'br__building_footprint_by_floor':
859
+ [[item for sublist in sbr_results['sbr__building_footprint_by_floor'] for item in sublist]],
860
+ 'br__patios_area_by_floor': [[sum(values) for values in zip_longest(
861
+ *sbr_results['sbr__patios_area_by_floor'], fillvalue=0)]],
862
+ 'br__patios_number_by_floor': [[sum(values) for values in zip_longest(
863
+ *sbr_results['sbr__patios_number_by_floor'], fillvalue=0)]],
864
+ 'br__walls_between_slabs': [sum(sbr_results['sbr__walls_between_slabs'])],
865
+ 'br__building_perimeter_by_floor': [[sum(values) for values in zip_longest(
866
+ *sbr_results['sbr__building_perimeter_by_floor'], fillvalue=0)]],
867
+ 'br__air_contact_wall_by_floor': [dict(sorted({
868
+ k: [
869
+ sum(x)
870
+ for x in zip_longest(
871
+ *(
872
+ d.get(
873
+ k,
874
+ [0] * (
875
+ max(
876
+ (len(v) for v in d.values() if isinstance(v, list)),
877
+ default=1, # Default to 1 if no valid lists are found
878
+ )
879
+ )
880
+ )
881
+ for d in sbr_results["sbr__air_contact_wall_by_floor"]
882
+ ),
883
+ fillvalue=0,
884
+ )
885
+ ]
886
+ for k in set(
887
+ chain.from_iterable(
888
+ d.keys() for d in sbr_results["sbr__air_contact_wall_by_floor"]
889
+ )
890
+ )
891
+ }.items(), key=lambda item: int(item[0])))],
892
+ 'br__air_contact_wall': [dict(sorted({
893
+ k: sum(
894
+ d.get(k, 0) # Get scalar value or default to 0
895
+ for d in sbr_results["sbr__air_contact_wall"]
896
+ )
897
+ for k in set(
898
+ chain.from_iterable(
899
+ d.keys() for d in sbr_results["sbr__air_contact_wall"]
900
+ )
901
+ )
902
+ }.items(),key=lambda item: int(item[0])))],
903
+ 'br__air_contact_wall_significant_orientations': [
904
+ dict(sorted({
905
+ k: sum(
906
+ d.get(k, 0)
907
+ for d in sbr_results["sbr__air_contact_wall_significant_orientations"]
908
+ if isinstance(d, dict)
909
+ )
910
+ for k in set(
911
+ chain.from_iterable(
912
+ d.keys()
913
+ for d in sbr_results["sbr__air_contact_wall_significant_orientations"]
914
+ if isinstance(d, dict)
915
+ )
916
+ )
917
+ }.items(), key=lambda item: int(item[0])))
918
+ ],
919
+ 'br__air_contact_wall_significant_orientations_by_floor': [
920
+ dict(sorted({
921
+ k: [
922
+ sum(floor_vals)
923
+ for floor_vals in zip_longest(
924
+ *[
925
+ d.get(k, []) for d in sbr_results["sbr__air_contact_wall_significant_orientations_by_floor"]
926
+ if isinstance(d, dict)
927
+ ],
928
+ fillvalue=0
929
+ )
930
+ ]
931
+ for k in set(
932
+ chain.from_iterable(
933
+ d.keys()
934
+ for d in sbr_results["sbr__air_contact_wall_significant_orientations_by_floor"]
935
+ if isinstance(d, dict)
936
+ )
937
+ )
938
+ }.items(), key=lambda item: int(item[0])))
939
+ ],
940
+ 'br__adiabatic_wall_by_floor': [[sum(values) for values in zip_longest(
941
+ *sbr_results['sbr__adiabatic_wall_by_floor'], fillvalue=0)]],
942
+ 'br__adiabatic_wall': [sum(sbr_results['sbr__adiabatic_wall'])],
943
+ 'br__patios_wall_by_floor': [[sum(values) for values in zip_longest(
944
+ *sbr_results['sbr__patios_wall_by_floor'], fillvalue=0)]],
945
+ 'br__patios_wall_total': [sum(sbr_results['sbr__patios_wall_total'])],
946
+ 'br__shadows_at_distance': [dict(sorted({
947
+ k: [
948
+ np.mean(x)
949
+ for x in zip_longest(
950
+ *(
951
+ d.get(
952
+ k,
953
+ [0] * (
954
+ max(
955
+ (len(v) for v in d.values() if isinstance(v, list)),
956
+ default=1, # Default to 1 if no valid lists are found
957
+ )
958
+ )
959
+ )
960
+ for d in sbr_results["sbr__shadows_at_distance"]
961
+ ),
962
+ fillvalue=0,
963
+ )
964
+ ]
965
+ for k in set(
966
+ chain.from_iterable(
967
+ d.keys() for d in sbr_results["sbr__shadows_at_distance"]
968
+ )
969
+ )
970
+ }.items(), key=lambda item: int(item[0])))],
971
+ 'br__building_contour_at_distance': [dict(sorted({
972
+ k: np.mean(
973
+ list(
974
+ d.get(k, 0) # Get scalar value or default to 0
975
+ for d in sbr_results["sbr__building_contour_at_distance"]
976
+ )
977
+ )
978
+ for k in set(
979
+ chain.from_iterable(
980
+ d.keys() for d in sbr_results["sbr__building_contour_at_distance"]
981
+ )
982
+ )
983
+ }.items(),
984
+ key=lambda item: int(item[0])))]
985
+ }
986
+ br_results = pd.DataFrame(br_agg_dict)
987
+ geoms_by_floor = list(sbr_results['sbr__building_footprint_by_floor'])
988
+ building_gdf_by_floor = pd.concat([gpd.GeoDataFrame(geom_by_floor) for geom_by_floor in geoms_by_floor])
989
+
990
+ if len(building_gdf_by_floor)>0:
991
+
992
+ building_gdf_by_floor.columns = ["single_building_reference", "floor_number", "geometry"]
993
+ building_gdf_by_floor = building_gdf_by_floor.set_geometry("geometry")
994
+ building_gdf_by_floor["area_single_building_reference"] = building_gdf_by_floor.area
995
+ building_aggregates = (
996
+ building_gdf_by_floor.groupby("floor_number").agg(
997
+ n_single_building_references=("single_building_reference", "nunique"),
998
+ area_building_reference=("area_single_building_reference", "sum")
999
+ ))
1000
+ building_gdf_by_floor = building_gdf_by_floor.merge(building_aggregates, on="floor_number", how="left")
1001
+ building_gdf_by_floor["building_reference"] = building_reference
1002
+
1003
+ # Consider the information from CAT files
1004
+ if buildings_CAT is not None:
1005
+
1006
+ # Integrate all CAT file information
1007
+ agg_CAT = aggregate_CAT_file_building_spaces(
1008
+ building_CAT_df=buildings_CAT.filter(pl.col("building_reference") == building_reference))
1009
+
1010
+ building_gdf_by_floor = building_gdf_by_floor.drop(columns="geometry")
1011
+
1012
+ # Reduce agg_CAT["by_floors"] to each single building reference
1013
+ sbr_with_CAT = building_gdf_by_floor.merge(agg_CAT["by_floors"].to_pandas(),
1014
+ on=["floor_number", "building_reference"])
1015
+ def process_variable(df, variable, ops, multiplier=1, divider=1):
1016
+ return {
1017
+ f"sbr__{variable}_by_floor": utils.agg_op(
1018
+ df,
1019
+ funcs=ops,
1020
+ grouping=["use_type","floor_number"],
1021
+ variable=f"br__{variable}_by_floor",
1022
+ multiplier=multiplier,
1023
+ divider=divider
1024
+ )
1025
+ }
1026
+ agg_list = [("building_spaces",[lambda x: round(x, 0)],"area_single_building_reference","area_building_reference"),
1027
+ ("area_with_communals",[lambda x: round(x, 2)],"area_single_building_reference","area_building_reference"),
1028
+ ("area_without_communals",[lambda x: round(x, 2)],"area_single_building_reference","area_building_reference"),
1029
+ ("communal_area",[lambda x: round(x, 2)],"area_single_building_reference","area_building_reference"),
1030
+ ("economic_value",[lambda x: round(x, 2)],"area_single_building_reference","area_building_reference"),
1031
+ ("mean_building_space_area_with_communals",[lambda x: round(x, 0)],1,1),
1032
+ ("mean_building_space_area_without_communals",[lambda x: round(x, 0)],1,1),
1033
+ ("mean_building_space_communal_area",[lambda x: round(x, 0)],1,1),
1034
+ ("mean_building_space_effective_year",[lambda x: round(x, 0)],1,1),
1035
+ ("mean_building_space_category",[lambda x: round(x, 0)],1,1),
1036
+ ("mean_building_space_economic_value",[lambda x: round(x, 0)],1,1),
1037
+ ]
1038
+ sbr_with_CAT_by_floors = (
1039
+ sbr_with_CAT.groupby(["single_building_reference","building_reference"])
1040
+ .apply(lambda df: pd.Series({
1041
+ key: value
1042
+ for agg_elem in agg_list
1043
+ for key, value in
1044
+ process_variable(df, agg_elem[0], agg_elem[1], agg_elem[2], agg_elem[3]).items()
1045
+ }),
1046
+ include_groups=False)
1047
+ .reset_index()
1048
+ )
1049
+
1050
+ # Reduce agg_CAT["building"] to each single building reference
1051
+ sbr_with_CAT = building_gdf_by_floor.merge(agg_CAT["building"].to_pandas(),
1052
+ on=["building_reference"])
1053
+ def process_variable(df, variable, summarise_op=None, digits=0, multiplier=1, divider=1):
1054
+ return {
1055
+ f"sbr__{variable}": utils.agg_op(
1056
+ df,
1057
+ funcs=[summarise_op, lambda x: round(x, digits) if summarise_op is not None else
1058
+ [lambda x: round(x, digits)]],
1059
+ grouping="use_type",
1060
+ variable=f"br__{variable}",
1061
+ multiplier=multiplier,
1062
+ divider=divider
1063
+ )
1064
+ }
1065
+ agg_list = [("building_spaces",sum,0,"area_single_building_reference","area_building_reference"),
1066
+ ("area_with_communals",sum,2,"area_single_building_reference","area_building_reference"),
1067
+ ("area_without_communals",sum,2,"area_single_building_reference","area_building_reference"),
1068
+ ("communal_area",sum,2,"area_single_building_reference","area_building_reference"),
1069
+ ("economic_value",sum,2,"area_single_building_reference","area_building_reference"),
1070
+ ("mean_building_space_area_with_communals",np.mean,0,1,1),
1071
+ ("mean_building_space_area_without_communals",np.mean,0,1,1),
1072
+ ("mean_building_space_communal_area",np.mean,0,1,1),
1073
+ ("mean_building_space_effective_year",np.mean,0,1,1),
1074
+ ("mean_building_space_category",np.mean,0,1,1),
1075
+ ("mean_building_space_economic_value",np.mean,0,1,1)
1076
+ ]
1077
+ sbr_with_CAT_summarised = (
1078
+ sbr_with_CAT.groupby(["single_building_reference","building_reference"])
1079
+ .apply(lambda df: pd.Series({
1080
+ key: value
1081
+ for agg_elem in agg_list
1082
+ for key, value in process_variable(df, agg_elem[0], agg_elem[1], agg_elem[2], agg_elem[3],
1083
+ agg_elem[4]).items()
1084
+ }),
1085
+ include_groups=False)
1086
+ .reset_index()
1087
+ )
1088
+
1089
+ # Reduce agg_CAT["by_floors"] to each building reference
1090
+ def process_variable(df, variable, summarise_ops=None, multiplier=1, divider=1):
1091
+ return {
1092
+ f"br__{variable}_by_floor": utils.agg_op(
1093
+ df,
1094
+ funcs=summarise_ops,
1095
+ grouping=["use_type","floor_number"],
1096
+ variable=f"br__{variable}_by_floor",
1097
+ multiplier=multiplier,
1098
+ divider=divider
1099
+ )
1100
+ }
1101
+
1102
+ agg_list = [("building_spaces", [lambda x: round(x, 2)], 1, 1),
1103
+ ("area_with_communals", [lambda x: round(x, 2)], 1, 1),
1104
+ ("area_without_communals", [lambda x: round(x, 2)], 1, 1),
1105
+ ("communal_area", [lambda x: round(x, 2)], 1, 1),
1106
+ ("economic_value", [lambda x: round(x, 2)], 1, 1),
1107
+ ("mean_building_space_area_with_communals", [lambda x: round(x, 2)], 1, 1),
1108
+ ("mean_building_space_area_without_communals", [lambda x: round(x, 2)], 1, 1),
1109
+ ("mean_building_space_communal_area", [lambda x: round(x, 2)], 1, 1),
1110
+ ("mean_building_space_effective_year", [lambda x: round(x, 2)], 1, 1),
1111
+ ("mean_building_space_category", [lambda x: round(x, 2)], 1, 1),
1112
+ ("mean_building_space_economic_value", [lambda x: round(x, 2)], 1, 1)
1113
+ ]
1114
+ br_with_CAT_by_floors = (
1115
+ agg_CAT["by_floors"].to_pandas().groupby(["building_reference"])
1116
+ .apply(lambda df: pd.Series({
1117
+ key: value
1118
+ for agg_elem in agg_list
1119
+ for key, value in
1120
+ process_variable(df, agg_elem[0], agg_elem[1], agg_elem[2], agg_elem[3]).items()
1121
+ }),
1122
+ include_groups=False)
1123
+ .reset_index()
1124
+ )
1125
+
1126
+ # Reduce agg_CAT["building"] to each building reference
1127
+ def process_variable(df, variable, ops, multiplier=1, divider=1):
1128
+ return {
1129
+ f"br__{variable}": utils.agg_op(
1130
+ df,
1131
+ funcs=ops,
1132
+ grouping="use_type",
1133
+ variable=f"br__{variable}",
1134
+ multiplier=multiplier,
1135
+ divider=divider
1136
+ )
1137
+ }
1138
+ agg_list = [("building_spaces",[sum],1,1),
1139
+ ("area_with_communals",[sum],1,1),
1140
+ ("area_without_communals",[sum],1,1),
1141
+ ("communal_area",[sum],1,1),
1142
+ ("economic_value",[sum],1,1),
1143
+ ("mean_building_space_area_with_communals",[sum],1,1),
1144
+ ("mean_building_space_area_without_communals",[sum],1,1),
1145
+ ("mean_building_space_communal_area",[sum],1,1),
1146
+ ("mean_building_space_effective_year",[sum],1,1),
1147
+ ("mean_building_space_category",[sum],1,1),
1148
+ ("mean_building_space_economic_value",[sum],1,1),
1149
+ ('building_spaces_reference',[chain.from_iterable, list],1,1),
1150
+ ('building_spaces_postal_address',[chain.from_iterable, list],1,1),
1151
+ ('building_spaces_inner_address',[chain.from_iterable, list],1,1),
1152
+ ('building_spaces_floor_number',[chain.from_iterable, list],1,1),
1153
+ ('building_spaces_category',[chain.from_iterable, list],1,1),
1154
+ ('building_spaces_effective_year',[chain.from_iterable, list],1,1),
1155
+ ('building_spaces_area_without_communal',[chain.from_iterable, list],1,1),
1156
+ ('building_spaces_area_with_communal',[chain.from_iterable, list],1,1),
1157
+ ('building_spaces_economic_value',[chain.from_iterable, list],1,1),
1158
+ ('building_spaces_detailed_use_type',[chain.from_iterable, list],1,1)
1159
+ ]
1160
+ br_with_CAT_summarised = (
1161
+ agg_CAT["building"].to_pandas().groupby(["building_reference"])
1162
+ .apply(lambda df: pd.Series({
1163
+ key: value
1164
+ for agg_elem in agg_list
1165
+ for key, value in process_variable(df, agg_elem[0], agg_elem[1], agg_elem[2], agg_elem[3]).items()
1166
+ }),
1167
+ include_groups=False)
1168
+ .reset_index()
1169
+ )
1170
+
1171
+ sbr_results = (sbr_results.
1172
+ merge(sbr_with_CAT_by_floors, on=["building_reference","single_building_reference"], how="left").
1173
+ merge(sbr_with_CAT_summarised, on=["building_reference","single_building_reference"], how="left"))
1174
+
1175
+ br_results = (br_results.
1176
+ merge(br_with_CAT_by_floors, on="building_reference", how="left").
1177
+ merge(br_with_CAT_summarised, on="building_reference", how="left"))
1178
+
1179
+ sbr_results_concat = pd.concat([sbr_results_concat, sbr_results], ignore_index=True)
1180
+ br_results_concat = pd.concat([br_results_concat, br_results], ignore_index=True)
1181
+
1182
+ sbr_results_concat.to_pickle(f"{results_dir}/cache/{zone_reference}_sbr_results.pkl")
1183
+ br_results_concat.to_pickle(f"{results_dir}/cache/{zone_reference}_br_results.pkl")
1184
+
1185
+ return sbr_results_concat, br_results_concat
1186
+
1187
+ else:
1188
+ return None, None
1189
+
1190
+ else:
1191
+ return (pd.read_pickle(f"{results_dir}/cache/{zone_reference}_sbr_results.pkl"),
1192
+ pd.read_pickle(f"{results_dir}/cache/{zone_reference}_br_results.pkl"))
1193
+
1194
+ except Exception as e:
1195
+ print(f" This cadastral zone failed: '{zone_reference}'. Error: {e}", file=sys.stderr)
1196
+
1197
+ # ==========================================
1198
+ # CAT FILE PROCESSING FUNCTIONS
1199
+ # ==========================================
1200
+
1201
+ def parse_horizontal_division_buildings_CAT_files(cadaster_code, CAT_files_dir):
1202
+ """
1203
+ Parse CAT files to extract horizontal division building information.
1204
+
1205
+ This function processes CAT files (Spanish cadastral data format) to extract
1206
+ detailed building information including spaces, floors, usage types, and
1207
+ geometric properties for horizontal property divisions.
1208
+
1209
+ Parameters:
1210
+ -----------
1211
+ cadaster_code : str
1212
+ Municipality cadastral code
1213
+ CAT_files_dir : str
1214
+ Directory containing CAT files
1215
+
1216
+ Returns:
1217
+ --------
1218
+ polars.DataFrame
1219
+ Processed building data with inferred space types, areas,
1220
+ floor information, and usage classifications
1221
+ """
1222
+
1223
+ combined_dfs = downloaders.parse_CAT_file(cadaster_code, CAT_files_dir, allowed_dataset_types=[14, 15])
1224
+
1225
+ # Join the building space and building spaces detailed datasets. Order the items by floor.
1226
+ building_spaces_detailed = combined_dfs[14]
1227
+ building_spaces = combined_dfs[15]
1228
+ building_spaces = building_spaces.with_columns(
1229
+ pl.concat_str(['building_reference', 'space1_reference'], separator=""
1230
+ ).alias("building_space_reference"),
1231
+ pl.concat_str(['space2_reference', 'space3_reference'], separator=""
1232
+ ).alias("building_space_reference_last_digits")
1233
+ )
1234
+ building_spaces_detailed = building_spaces_detailed.with_columns(
1235
+ pl.concat_str(['building_reference', 'space1_reference'], separator=""
1236
+ ).alias("building_space_reference")
1237
+ )
1238
+ building_spaces_detailed = building_spaces_detailed.filter(
1239
+ pl.col("distribution_method_for_communal_areas") == "")
1240
+ floor_names = sorted(building_spaces_detailed["building_space_floor_name"].unique().to_list())
1241
+ df = pd.DataFrame({'floor_name': floor_names})
1242
+ df['order'] = df['floor_name'].apply(utils.classify_cadaster_floor_names)
1243
+ floor_names_sorted = list(df.sort_values(by='order').reset_index(drop=True).floor_name)
1244
+
1245
+ building_spaces_detailed = building_spaces_detailed.join(
1246
+ building_spaces.select(
1247
+ 'building_space_reference', 'building_space_reference_last_digits', 'building_space_year',
1248
+ 'street_type', 'street_name', 'street_number1', 'street_letter1', 'street_number2', 'street_letter2', 'km',
1249
+ 'building_space_total_area', 'building_space_participation_rate', 'building_space_use_type'),
1250
+ on = "building_space_reference").select(
1251
+ 'building_reference', 'building_space_reference', 'building_space_reference_last_digits',
1252
+ 'street_type', 'street_name', 'street_number1', 'street_letter1', 'street_number2', 'street_letter2', 'km',
1253
+ 'building_space_block_name', 'building_space_stair_name', 'building_space_floor_name', 'building_space_door_name',
1254
+ 'building_space_year', 'retrofitted', 'building_space_retroffiting_year', 'building_space_effective_year',
1255
+ 'building_space_total_area', 'building_space_area_without_communal', 'building_space_area_balconies_terraces',
1256
+ 'building_space_area_imputable_to_other_floors', 'building_space_participation_rate',
1257
+ 'building_space_use_type', 'building_space_detailed_use_type', 'building_space_typology'
1258
+ )
1259
+ order_mapping = {value: index for index, value in enumerate(floor_names_sorted)}
1260
+ building_spaces_detailed = building_spaces_detailed.with_columns(
1261
+ pl.col("building_space_floor_name").map_elements(lambda x: order_mapping.get(x, -1),
1262
+ return_dtype=pl.Int32).alias("custom_sort")
1263
+ )
1264
+ building_spaces_detailed = building_spaces_detailed.sort("custom_sort").drop("custom_sort").sort("building_space_reference")
1265
+
1266
+ # Calculate areas and affected communal areas per building space
1267
+ building_spaces_detailed = building_spaces_detailed.join(
1268
+ building_spaces_detailed.group_by("building_space_reference").agg(
1269
+ pl.col("building_space_area_without_communal").sum().alias("building_space_total_area_without_communal"),
1270
+ pl.len().alias("building_spaces_considered"),
1271
+ ),
1272
+ on = "building_space_reference"
1273
+ )
1274
+ building_spaces_detailed = building_spaces_detailed.with_columns(
1275
+ (pl.col("building_space_participation_rate") / 1000000).alias("building_space_participation_rate"),
1276
+ pl.concat_str(['building_space_reference', 'building_space_reference_last_digits'], separator=""
1277
+ ).alias("building_space_reference"),
1278
+ ((pl.col("building_space_total_area") - pl.col("building_space_total_area_without_communal")) *
1279
+ pl.col("building_space_area_without_communal") / pl.col("building_space_total_area_without_communal")).alias(
1280
+ "building_space_communal_area"))
1281
+ building_spaces_detailed = building_spaces_detailed.with_columns(
1282
+ (pl.col("building_space_communal_area") + pl.col("building_space_area_without_communal")).alias(
1283
+ "building_space_area_with_communal")
1284
+ )
1285
+
1286
+ # Rename items of categorical columns (Typology, category, use...)
1287
+ building_spaces_detailed = building_spaces_detailed.with_columns(
1288
+ pl.col("building_space_typology").str.slice(4,length=3).alias("building_space_typology_category"),
1289
+ pl.col("building_space_typology").str.head(4).alias("building_space_typology_id"),
1290
+ (pl.lit(date.today().year) - pl.col("building_space_effective_year")).alias("building_space_age")
1291
+ )
1292
+ building_spaces_detailed = building_spaces_detailed.with_columns(
1293
+ # Create booster column based on category
1294
+ pl.when(pl.col("building_space_typology_category") == "A")
1295
+ .then(1.5)
1296
+ .when(pl.col("building_space_typology_category") == "B")
1297
+ .then(1.3)
1298
+ .when(pl.col("building_space_typology_category") == "C")
1299
+ .then(1.15)
1300
+ .otherwise(1.0)
1301
+ .alias("building_space_typology_category_booster")
1302
+ ).with_columns(
1303
+ # Create booster column based on category
1304
+ pl.when(pl.col("building_space_typology_category") == "A")
1305
+ .then(1)
1306
+ .when(pl.col("building_space_typology_category") == "B")
1307
+ .then(1)
1308
+ .when(pl.col("building_space_typology_category") == "C")
1309
+ .then(1)
1310
+ .when(pl.col("building_space_typology_category") == "O")
1311
+ .then(1)
1312
+ .otherwise(pl.col("building_space_typology_category"))
1313
+ .alias("building_space_typology_category")
1314
+ )
1315
+ building_spaces_detailed = building_spaces_detailed.with_columns(
1316
+ pl.col("building_space_typology_id").replace(
1317
+ {k: v.get("Use") for k, v in downloaders.building_space_typologies.items() if "Use" in v}).
1318
+ alias("building_space_typology_use"),
1319
+ pl.col("building_space_typology_id").replace(
1320
+ {k: v.get("UseClass") for k, v in downloaders.building_space_typologies.items() if "UseClass" in v}).
1321
+ alias("building_space_typology_use_class"),
1322
+ pl.col("building_space_typology_id").replace(
1323
+ {k: v.get("UseClassModality") for k, v in downloaders.building_space_typologies.items() if "UseClassModality" in v}).
1324
+ alias("building_space_typology_use_class_modality"),
1325
+ pl.col("building_space_typology_id").replace(
1326
+ {k: v.get("UseLevel") for k, v in downloaders.building_space_typologies.items() if "UseLevel" in v}).
1327
+ alias("building_space_typology_use_level"),
1328
+ pl.when(pl.col("building_space_age") >= 90).
1329
+ then(pl.lit(90).cast(pl.Int16).cast(pl.Utf8)).
1330
+ otherwise(((pl.col("building_space_age") / 5).floor() * 5).cast(pl.Int16).cast(pl.Utf8)).
1331
+ alias("building_space_age_key"),
1332
+ pl.col("building_space_use_type").replace(downloaders.building_space_use_types).
1333
+ alias("building_space_use_type"),
1334
+ pl.col("building_space_detailed_use_type").replace(downloaders.building_space_detailed_use_types).
1335
+ alias("building_space_detailed_use_type")
1336
+ )
1337
+ building_space_age_value_dict = \
1338
+ {str(entry["Age"][0]): {k: v for k, v in entry.items() if k != "Age"} for entry in downloaders.building_space_age_value}
1339
+
1340
+ # Economical value coefficients of the constructions
1341
+ building_spaces_detailed = building_spaces_detailed.with_columns(
1342
+ pl.struct(["building_space_typology_id", "building_space_typology_category"]).map_elements(
1343
+ lambda row:
1344
+ downloaders.building_space_typologies[
1345
+ row["building_space_typology_id"]]["ConstructionValue"][
1346
+ int(row["building_space_typology_category"]) - 1], # Adjust index to match zero-based indexing
1347
+ return_dtype=pl.Float64 # Specify the return dtype explicitly
1348
+ ).alias("construction_relative_economic_value"),
1349
+ pl.struct(["building_space_age_key", "building_space_typology_use_level",
1350
+ "building_space_typology_category"]).map_elements(
1351
+ lambda row:
1352
+ building_space_age_value_dict[
1353
+ row["building_space_age_key"]][
1354
+ row["building_space_typology_use_level"]][
1355
+ int(row["building_space_typology_category"]) - 1], # Adjust index to match zero-based indexing
1356
+ return_dtype=pl.Float64 # Specify the return dtype explicitly
1357
+ ).alias("age_correction_relative_economic_value")
1358
+ )
1359
+
1360
+ # Calculate relative economic value
1361
+ building_spaces_detailed = building_spaces_detailed.with_columns(
1362
+ (pl.col("construction_relative_economic_value") *
1363
+ pl.col("age_correction_relative_economic_value") *
1364
+ pl.col("building_space_typology_category_booster")).alias("building_space_relative_economic_value")
1365
+ )
1366
+ building_spaces_detailed = building_spaces_detailed.with_columns(
1367
+ (pl.col("building_space_relative_economic_value") * pl.col("building_space_area_with_communal")).alias("building_space_economic_value")
1368
+ )
1369
+
1370
+ # Calculate the complete address
1371
+ building_spaces_detailed = building_spaces_detailed.with_columns(
1372
+ (pl.when(pl.col("street_number1") == "0000").then(pl.lit("")).otherwise(
1373
+ pl.col("street_number1").cast(pl.Int16))).alias("street_number1"),
1374
+ (pl.when(pl.col("street_number2") == "0000").then(pl.lit("")).otherwise(
1375
+ pl.col("street_number2").cast(pl.Int16))).alias("street_number2"),
1376
+ (pl.when(pl.col("km") == "00000").then(pl.lit("")).otherwise(pl.col("km").cast(pl.Int16))).alias("km")
1377
+ )
1378
+ building_spaces_detailed = building_spaces_detailed.with_columns(
1379
+ pl.concat_str(["street_type", "street_name", "street_number1", "street_letter1", "street_number2",
1380
+ "street_letter2", "km", "building_space_block_name", "building_space_stair_name"],
1381
+ separator=" ").
1382
+ str.strip_chars().str.replace_all(r"\s+", " ").alias("building_space_address"),
1383
+ pl.concat_str(['building_space_block_name', 'building_space_stair_name', 'building_space_floor_name',
1384
+ 'building_space_door_name'],
1385
+ separator=" ").
1386
+ str.strip_chars().str.replace_all(r"\s+", " ").alias("building_space_inner_address")
1387
+ )
1388
+
1389
+ use_type_mapping = {
1390
+ "Restaurant 4 Stars": "Leisure and Hospitality",
1391
+ "Professional education": "Cultural",
1392
+ "Water treatment plants": "Singular building", # or whichever fallback you prefer
1393
+ "Other office activities": "Offices",
1394
+ "Weaver's office": "Offices",
1395
+ "Sports facilities": "Sports facilities",
1396
+ "Bookstore commerce": "Commercial",
1397
+ "Food industry": "Industrial",
1398
+ "Parking in a household": "Warehouse - Parking",
1399
+ "Commerce": "Commercial",
1400
+ "Religious": "Religious",
1401
+ "Open terrace (100%)": "Urbanization and landscaping works, undeveloped land",
1402
+ "Public town hall (<20,000)": "Offices",
1403
+ "Hotel Cafe 3 Stars": "Leisure and Hospitality",
1404
+ "Hostel Standard 1": "Leisure and Hospitality",
1405
+ "Hotel 5 Stars": "Leisure and Hospitality",
1406
+ "Station": "Singular building",
1407
+ "Financial commerce": "Commercial",
1408
+ "Club": "Entertainment venues",
1409
+ "Printing commerce": "Commercial",
1410
+ "Restaurant 5 Stars": "Leisure and Hospitality",
1411
+ "Musician's office": "Offices",
1412
+ "Hotel Cafe 5 Stars": "Leisure and Hospitality",
1413
+ "Luxury apartments 3 Stars": "Residential",
1414
+ "Clinic": "Healthcare and Charity",
1415
+ "Swimming pool": "Sports facilities",
1416
+ "University education": "Cultural",
1417
+ "Other provincial union": "Singular building",
1418
+ "Sports complex": "Sports facilities",
1419
+ "Stadium": "Sports facilities",
1420
+ "Education": "Cultural",
1421
+ "Luxury apartments 1 Star": "Residential",
1422
+ "Personal/Home commerce": "Commercial",
1423
+ "Other outpatient clinic": "Healthcare and Charity",
1424
+ "Nursing office": "Healthcare and Charity",
1425
+ "Hostel Standard 3": "Leisure and Hospitality",
1426
+ "Wholesale commerce": "Commercial",
1427
+ "Jewelry commerce": "Commercial",
1428
+ "Hotel 4 Stars": "Leisure and Hospitality",
1429
+ "Public courthouse": "Offices",
1430
+ "Education (Library)": "Cultural",
1431
+ "Silos, solid storage": "Warehouse - Parking",
1432
+ "Museum education": "Cultural",
1433
+ "Liquid storage tanks": "Warehouse - Parking",
1434
+ "Porch (100%)": "Urbanization and landscaping works, undeveloped land",
1435
+ "Galleries commerce": "Commercial",
1436
+ "Casino (>20,000)": "Entertainment venues",
1437
+ "Shoe commerce": "Commercial",
1438
+ "Machinery industry": "Industrial",
1439
+ "Wood industry": "Industrial",
1440
+ "Petroleum industry": "Industrial",
1441
+ "Parking": "Warehouse - Parking",
1442
+ "Transformer hut": "Singular building",
1443
+ "Warehouse": "Warehouse - Parking",
1444
+ "Other uses": "Singular building",
1445
+ "Bazaar commerce": "Commercial",
1446
+ "Provincial court": "Offices",
1447
+ "Industry": "Industrial",
1448
+ "Other dispensary": "Healthcare and Charity",
1449
+ "Textile industry": "Industrial",
1450
+ "Metal industry": "Industrial",
1451
+ "Other rescue facilities": "Singular building",
1452
+ "Plumbing commerce": "Commercial",
1453
+ "Public town hall (>20,000)": "Offices",
1454
+ "Entertainment": "Entertainment venues",
1455
+ "Chemical industry": "Industrial",
1456
+ "Casino (<20,000)": "Entertainment venues",
1457
+ "Drugstore commerce": "Commercial",
1458
+ "Colonnade (50%)": "Urbanization and landscaping works, undeveloped land",
1459
+ "Agent office": "Offices",
1460
+ "Construction industry": "Industrial",
1461
+ "Pharmacy commerce": "Commercial",
1462
+ "Government building": "Offices",
1463
+ "Undeveloped land": "Urbanization and landscaping works, undeveloped land",
1464
+ "Gas storage": "Warehouse - Parking",
1465
+ "Butcher commerce": "Commercial",
1466
+ "Daycare": "Healthcare and Charity",
1467
+ "Residence": "Residential",
1468
+ "Institute education": "Cultural",
1469
+ "Medical/Law office": "Offices",
1470
+ "Other sanatorium": "Healthcare and Charity",
1471
+ "Furniture commerce": "Commercial",
1472
+ "Public": "Singular building",
1473
+ "Hotel 1 Star": "Leisure and Hospitality",
1474
+ "Hotel": "Leisure and Hospitality",
1475
+ "Religious chapel": "Religious",
1476
+ "Hostel Standard 2": "Leisure and Hospitality",
1477
+ "Housing": "Residential",
1478
+ "Restaurant 2 Stars": "Leisure and Hospitality",
1479
+ "Cinema": "Entertainment venues",
1480
+ "Hotel Cafe 2 Stars": "Leisure and Hospitality",
1481
+ "Restaurant 1 Star": "Leisure and Hospitality",
1482
+ "Retail commerce": "Commercial",
1483
+ "Hotel 3 Stars": "Leisure and Hospitality",
1484
+ "Entertainment hall": "Entertainment venues",
1485
+ "Auditorium": "Entertainment venues",
1486
+ "Salesperson office": "Offices",
1487
+ "Sports": "Sports facilities",
1488
+ "Hotel 2 Stars": "Leisure and Hospitality",
1489
+ "Electric industry": "Industrial",
1490
+ "Office": "Offices",
1491
+ "Watchmaking commerce": "Commercial",
1492
+ "Hotel Cafe 4 Stars": "Leisure and Hospitality",
1493
+ "Theater": "Entertainment venues",
1494
+ "Private garden (100%)": "Urbanization and landscaping works, undeveloped land",
1495
+ "Hotel Cafe 1 Star": "Leisure and Hospitality",
1496
+ "Restaurant 3 Stars": "Leisure and Hospitality",
1497
+ "Religious hermitage": "Religious",
1498
+ "Basic education": "Cultural",
1499
+ "Urbanization works": "Urbanization and landscaping works, undeveloped land",
1500
+ "Perfumery commerce": "Commercial",
1501
+ "Automobile commerce": "Commercial",
1502
+ "Hospital": "Healthcare and Charity",
1503
+ "Religious parish": "Religious",
1504
+ "Glass industry": "Industrial",
1505
+ "Public delegation": "Offices",
1506
+ "Fabric commerce": "Commercial",
1507
+ "Storage": "Warehouse - Parking",
1508
+ "Supermarket commerce": "Commercial",
1509
+ "Manufacturing industry": "Industrial",
1510
+ "Covered terrace (100%)": "Urbanization and landscaping works, undeveloped land",
1511
+ "Cultural house education": "Cultural",
1512
+ }
1513
+ mapper = pl.DataFrame([{'keys': x, 'values': y} for x, y in use_type_mapping.items()])
1514
+
1515
+ building_spaces_detailed = building_spaces_detailed.with_columns(
1516
+ building_spaces_detailed["building_space_detailed_use_type"].
1517
+ to_frame("keys").join(mapper, on="keys", how="left").
1518
+ to_series(1).alias("building_space_inferred_use_type"))
1519
+
1520
+ return building_spaces_detailed
1521
+
1522
+
1523
+ def aggregate_CAT_file_building_spaces(building_CAT_df):
1524
+ """
1525
+ Aggregate building space information from CAT file data.
1526
+
1527
+ This function processes detailed building space data and aggregates it
1528
+ by building reference, calculating total areas by usage type and
1529
+ floor distributions.
1530
+
1531
+ Parameters:
1532
+ -----------
1533
+ building_CAT_df : polars.DataFrame
1534
+ Detailed building space data from CAT files
1535
+
1536
+ Returns:
1537
+ --------
1538
+ polars.DataFrame
1539
+ Aggregated building data with space summaries and usage statistics
1540
+ """
1541
+ building_CAT_df = building_CAT_df.with_columns(
1542
+ pl.col("building_space_floor_name").map_elements(
1543
+ lambda x: utils.classify_above_ground_floor_names(x) if x is not None else None,
1544
+ return_dtype=pl.Int32
1545
+ ).alias("building_space_floor_order_above_ground"),
1546
+ pl.col("building_space_floor_name").map_elements(
1547
+ lambda x: utils.classify_below_ground_floor_names(x) if x is not None else None,
1548
+ return_dtype=pl.Int32
1549
+ ).alias("building_space_floor_order_below_ground")
1550
+ )
1551
+
1552
+ # Map the original Series to ordered values
1553
+ unique_values = building_CAT_df[
1554
+ "building_space_floor_order_above_ground"].unique().drop_nulls().sort()
1555
+ value_to_order = {val: i for i, val in enumerate(unique_values)}
1556
+ building_CAT_df = building_CAT_df.with_columns(
1557
+ building_CAT_df["building_space_floor_order_above_ground"]
1558
+ .map_elements(lambda x: value_to_order.get(x, None), return_dtype=pl.Int32)
1559
+ .alias("building_space_floor_order_above_ground")
1560
+ )
1561
+ unique_values = building_CAT_df[
1562
+ "building_space_floor_order_below_ground"].unique().drop_nulls().sort()
1563
+ value_to_order = {val: -(i + 1) for i, val in enumerate(unique_values)}
1564
+ building_CAT_df = building_CAT_df.with_columns(
1565
+ building_CAT_df["building_space_floor_order_below_ground"]
1566
+ .map_elements(lambda x: value_to_order.get(x, None), return_dtype=pl.Int32)
1567
+ .alias("building_space_floor_order_below_ground")
1568
+ )
1569
+
1570
+ # Join floor orders below and above ground
1571
+ building_CAT_df = building_CAT_df.with_columns(
1572
+ pl.when(pl.col("building_space_floor_order_above_ground").is_null()).
1573
+ then(pl.col("building_space_floor_order_below_ground")).
1574
+ otherwise(pl.col("building_space_floor_order_above_ground")).alias(
1575
+ "building_space_floor_order"
1576
+ )
1577
+ )
1578
+
1579
+ def adjust_to_consecutive_floor(series):
1580
+ unique_sorted = series.unique().sort()
1581
+ unique_sorted = unique_sorted.drop_nulls()
1582
+ value_to_consecutive = {val: idx + unique_sorted[0] for idx, val in enumerate(unique_sorted)}
1583
+ return series.map_elements(lambda x: value_to_consecutive[x], return_dtype=pl.Int32)
1584
+
1585
+ adjusted_floors = building_CAT_df.group_by("building_space_address").agg(
1586
+ [
1587
+ pl.col("building_space_floor_name"),
1588
+ pl.col("building_space_floor_order").map_elements(adjust_to_consecutive_floor,
1589
+ return_dtype=pl.List(pl.Int32)).alias(
1590
+ "building_space_floor_number")
1591
+ ]
1592
+ )
1593
+ adjusted_floors = (
1594
+ adjusted_floors.explode(["building_space_floor_name", "building_space_floor_number"]).
1595
+ unique().sort(["building_space_address", "building_space_floor_number"]))
1596
+ building_CAT_df = building_CAT_df.join(adjusted_floors,
1597
+ on=["building_space_address", "building_space_floor_name"])
1598
+
1599
+ # Compute total areas of the buildings
1600
+ building_CAT_df = building_CAT_df.join(
1601
+ building_CAT_df.group_by("building_space_floor_number").agg(
1602
+ pl.col("building_space_area_with_communal").sum().alias("building_floor_total_area")
1603
+ ), on=["building_space_floor_number"])
1604
+ building_CAT_df = building_CAT_df.join(
1605
+ building_CAT_df.group_by("building_reference").agg(
1606
+ pl.col("building_space_area_with_communal").sum().alias("building_total_area")
1607
+ ), on=["building_reference"])
1608
+ building_CAT_df = building_CAT_df.with_columns(
1609
+ pl.col("building_space_area_without_communal").round(2).alias(
1610
+ "building_space_area_without_communal"),
1611
+ pl.col("building_space_area_with_communal").round(2).alias("building_space_area_with_communal"),
1612
+ pl.col("building_space_economic_value").round(2).alias("building_space_economic_value"),
1613
+ )
1614
+
1615
+ # Sort the dataset
1616
+ building_CAT_df = building_CAT_df.sort(
1617
+ ["building_space_address", "building_space_inner_address"]
1618
+ )
1619
+
1620
+ agg_CAT_by_floors = (
1621
+ building_CAT_df.group_by("building_space_floor_number", "building_space_inferred_use_type").agg(
1622
+ pl.col("building_reference").first().alias("building_reference"),
1623
+ pl.col("building_space_reference").count().alias("br__building_spaces_by_floor"),
1624
+ # Average values per building space
1625
+ pl.col("building_space_area_with_communal").mean().round(2).alias(
1626
+ "br__mean_building_space_area_with_communals_by_floor"),
1627
+ pl.col("building_space_area_without_communal").mean().round(2).alias(
1628
+ "br__mean_building_space_area_without_communals_by_floor"),
1629
+ pl.col("building_space_communal_area").mean().round(2).alias(
1630
+ "br__mean_building_space_communal_area_by_floor"),
1631
+ pl.col("building_space_effective_year").mean().round(1).alias(
1632
+ "br__mean_building_space_effective_year_by_floor"),
1633
+ pl.col("building_space_typology_category").
1634
+ replace({"A":"1","B":"2","C":"3","0":"1","O":"1"}).
1635
+ cast(pl.Int8).mean().round(1).alias(
1636
+ "br__mean_building_space_category_by_floor"),
1637
+ pl.col("building_space_economic_value").mean().round(2).alias(
1638
+ "br__mean_building_space_economic_value_by_floor"),
1639
+ # Total value for the whole building
1640
+ pl.col("building_space_area_with_communal").sum().alias("br__area_with_communals_by_floor"),
1641
+ pl.col("building_space_area_without_communal").sum().alias(
1642
+ "br__area_without_communals_by_floor"),
1643
+ pl.col("building_space_communal_area").sum().alias("br__communal_area_by_floor"),
1644
+ pl.col("building_space_economic_value").sum().alias("br__economic_value_by_floor"),
1645
+ ((pl.col("building_space_area_with_communal").sum() / pl.col(
1646
+ "building_floor_total_area").mean()).round(2) * 100).alias(
1647
+ "br__relative_area_with_communals_by_floor"),
1648
+ ((pl.col("building_space_area_without_communal").sum() / pl.col(
1649
+ "building_floor_total_area").mean()).round(2) * 100).alias(
1650
+ "br__relative_area_without_communals_by_floor"),
1651
+ ((pl.col("building_space_communal_area").sum() / pl.col(
1652
+ "building_floor_total_area").mean()).round(2) * 100).alias(
1653
+ "br__relative_communal_area_by_floor")
1654
+ ))
1655
+ agg_CAT_by_floors = agg_CAT_by_floors.rename(
1656
+ {"building_space_floor_number": "floor_number", "building_space_inferred_use_type": "use_type"})
1657
+ agg_CAT_by_floors = agg_CAT_by_floors.sort("floor_number")
1658
+
1659
+ agg_CAT_building = building_CAT_df.group_by("building_space_inferred_use_type").agg(
1660
+ pl.col("building_reference").first().alias("building_reference"),
1661
+ pl.col("building_space_reference").count().alias("br__building_spaces"),
1662
+ pl.col("building_space_floor_number").unique().sort().alias("br__floors"),
1663
+ # Average values per building space
1664
+ pl.col("building_space_area_with_communal").mean().round(2).alias(
1665
+ "br__mean_building_space_area_with_communals"),
1666
+ pl.col("building_space_area_without_communal").mean().round(2).alias(
1667
+ "br__mean_building_space_area_without_communals"),
1668
+ pl.col("building_space_communal_area").mean().round(2).alias(
1669
+ "br__mean_building_space_communal_area"),
1670
+ pl.col("building_space_effective_year").mean().round(1).alias(
1671
+ "br__mean_building_space_effective_year"),
1672
+ pl.col("building_space_typology_category").
1673
+ replace({"A":"1","B":"2","C":"3","0":"1","O":"1"}).
1674
+ cast(pl.Int8).mean().round(1).alias(
1675
+ "br__mean_building_space_category"),
1676
+ pl.col("building_space_economic_value").mean().round(2).alias(
1677
+ "br__mean_building_space_economic_value"),
1678
+ # Total value for the whole building
1679
+ pl.col("building_space_area_with_communal").sum().alias("br__area_with_communals"),
1680
+ pl.col("building_space_area_without_communal").sum().alias(
1681
+ "br__area_without_communals"),
1682
+ pl.col("building_space_communal_area").sum().alias("br__communal_area"),
1683
+ pl.col("building_space_economic_value").sum().alias("br__economic_value"),
1684
+ ((pl.col("building_space_area_with_communal").sum() / pl.col(
1685
+ "building_total_area").mean()).round(2) * 100).alias(
1686
+ "br__relative_area_with_communals"),
1687
+ ((pl.col("building_space_area_without_communal").sum() / pl.col(
1688
+ "building_total_area").mean()).round(2) * 100).alias(
1689
+ "br__relative_area_without_communals"),
1690
+ ((pl.col("building_space_communal_area").sum() / pl.col("building_total_area").mean()).round(
1691
+ 2) * 100).alias("br__relative_communal_area"),
1692
+ # Arrays of values per building
1693
+ pl.col("building_space_reference").alias("br__building_spaces_reference"),
1694
+ pl.col("building_space_address").alias("br__building_spaces_postal_address"),
1695
+ pl.col("building_space_inner_address").alias("br__building_spaces_inner_address"),
1696
+ pl.col("building_space_floor_number").alias("br__building_spaces_floor_number"),
1697
+ (pl.col("building_space_typology_category").
1698
+ replace({"A":"1","B":"2","C":"3","0":"1","O":"1"}).
1699
+ cast(pl.Int8).alias("br__building_spaces_category")),
1700
+ pl.col("building_space_effective_year").alias("br__building_spaces_effective_year"),
1701
+ pl.col("building_space_area_without_communal").alias(
1702
+ "br__building_spaces_area_without_communal"),
1703
+ pl.col("building_space_area_with_communal").alias("br__building_spaces_area_with_communal"),
1704
+ pl.col("building_space_economic_value").alias("br__building_spaces_economic_value"),
1705
+ pl.col("building_space_detailed_use_type").alias("br__building_spaces_detailed_use_type")
1706
+ )
1707
+ agg_CAT_building = agg_CAT_building.rename(
1708
+ {"building_space_inferred_use_type": "use_type"})
1709
+
1710
+ return {
1711
+ "by_floors": agg_CAT_by_floors,
1712
+ "building": agg_CAT_building
1713
+ }