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,679 @@
1
+ """Data merging and joining operations for hypercadaster_ES.
2
+
3
+ This module provides functions for joining Spanish cadastral data with
4
+ various external geographic and administrative datasets.
5
+
6
+ Main functions:
7
+ - join_cadaster_data(): Main orchestrator for joining all cadastral data
8
+ - get_cadaster_address(): Extract and process address information
9
+ - join_cadaster_building(): Join building geometry and attributes
10
+ - join_cadaster_zone(): Join cadastral zoning information
11
+ - join_DEM_raster(): Add elevation data from Digital Elevation Model
12
+ - join_by_census_tracts(): Add census tract information
13
+ - join_by_neighbourhoods(): Add neighborhood information (Barcelona)
14
+ - join_by_postal_codes(): Add postal code information
15
+ """
16
+
17
+ import sys
18
+ import numpy as np
19
+ import pandas as pd
20
+ import polars as pl
21
+ import geopandas as gpd
22
+ import rasterio
23
+ import regex as re
24
+ from shapely import wkt
25
+ from shapely.geometry import Point
26
+
27
+ from hypercadaster_ES import utils
28
+ from hypercadaster_ES import building_inference
29
+ from hypercadaster_ES import downloaders
30
+
31
+ def get_cadaster_address(cadaster_dir, cadaster_codes, directions_from_CAT_files=True, CAT_files_dir="CAT_files",
32
+ directions_from_open_data=True, open_data_layers_dir="open_data"):
33
+ sys.stderr.write(f"\nReading the cadaster addresses for {len(cadaster_codes)} municipalities\n")
34
+
35
+ address_gdf = gpd.GeoDataFrame()
36
+ address_street_names_df = gpd.GeoDataFrame()
37
+
38
+ for code in cadaster_codes:
39
+ sys.stderr.write("\r" + " " * 60)
40
+ sys.stderr.flush()
41
+ sys.stderr.write(f"\r\tCadaster code: {code}")
42
+ sys.stderr.flush()
43
+
44
+ address_gdf_ = gpd.read_file(f"{cadaster_dir}/address/unzip/A.ES.SDGC.AD.{code}.gml", layer="Address")
45
+ address_gdf_['cadaster_code'] = code
46
+
47
+ if not address_gdf.empty:
48
+ if address_gdf_.crs != address_gdf.crs:
49
+ address_gdf_ = address_gdf_.to_crs(address_gdf.crs)
50
+ address_gdf = gpd.GeoDataFrame(pd.concat([address_gdf, address_gdf_], ignore_index=True))
51
+ else:
52
+ address_gdf = address_gdf_
53
+
54
+ address_street_names_df_ = gpd.read_file(f"{cadaster_dir}/address/unzip/A.ES.SDGC.AD.{code}.gml",
55
+ layer="ThoroughfareName")
56
+
57
+ if not address_street_names_df.empty:
58
+ address_street_names_df = pd.concat([address_street_names_df, address_street_names_df_],
59
+ ignore_index=True)
60
+ else:
61
+ address_street_names_df = address_street_names_df_
62
+
63
+ sys.stderr.write("\r" + " " * 60)
64
+
65
+ address_street_names_df = address_street_names_df[['gml_id', 'text']].copy()
66
+ address_street_names_df["gml_id"] = address_street_names_df['gml_id'].apply(lambda x: x.split('ES.SDGC.TN.')[1])
67
+ address_gdf["gml_id"] = address_gdf['gml_id'].apply(lambda x: '.'.join(x.split('ES.SDGC.AD.')[1].split('.')[:3]))
68
+
69
+ gdf = pd.merge(address_gdf, address_street_names_df, left_on="gml_id", right_on="gml_id")
70
+
71
+ gdf.rename(columns={'geometry': 'location', 'text': 'street_name', 'designator': 'street_number'}, inplace=True)
72
+ gdf["street_type"] = gdf["street_name"].apply(lambda x: x.split(" ")[0])
73
+ gdf["street_name"] = gdf["street_name"].apply(lambda x: ' '.join(x.split(" ")[1:]))
74
+ gdf['street_number_clean'] = gdf['street_number'].str.extract(r'(\d+(?=.*))').fillna(0).astype(int)
75
+ # gdf = gdf[gdf['specification'] == "Entrance"]
76
+ gdf["building_reference"] = gdf['localId'].apply(lambda x: x.split('.')[-1])
77
+
78
+ gdf.drop(
79
+ ["gml_id", "namespace", "localId", "beginLifespanVersion", "validFrom", "level", "type", "method", "default"],
80
+ inplace=True, axis=1)
81
+ gdf = gdf.set_geometry("location")
82
+ _, parcels_gdf = join_cadaster_parcel(gdf, cadaster_dir, cadaster_codes, how="left")
83
+
84
+ if directions_from_CAT_files:
85
+ addresses_CAT = pd.DataFrame()
86
+
87
+ for code in cadaster_codes:
88
+ # Parse CAT file, if available
89
+ buildings_CAT = building_inference.parse_horizontal_division_buildings_CAT_files(code, CAT_files_dir)
90
+ addresses_CAT_ = (pl.concat([
91
+ buildings_CAT[["building_reference", "street_type", "street_name", "street_number1"]].rename(
92
+ {"street_number1": "street_number"}),
93
+ buildings_CAT[["building_reference", "street_type", "street_name", "street_number2"]].rename(
94
+ {"street_number2": "street_number"}).filter(pl.col("street_number") != "")], how="vertical")
95
+ ).to_pandas()
96
+ addresses_CAT_['street_number_clean'] = addresses_CAT_['street_number'].str.extract(r'(\d+(?=.*))').fillna(0).astype(int)
97
+ addresses_CAT = pd.concat([addresses_CAT, addresses_CAT_], ignore_index=True)
98
+ addresses_CAT['cadaster_code'] = code
99
+
100
+ def calculate_centroid(group):
101
+ valid_points = [pt for pt in group["location"] if isinstance(pt, Point)]
102
+
103
+ if not valid_points:
104
+ return pd.Series({"location": None})
105
+
106
+ x_coords = [pt.x for pt in valid_points]
107
+ y_coords = [pt.y for pt in valid_points]
108
+
109
+ centroid = Point(np.mean(x_coords), np.mean(y_coords))
110
+
111
+ return pd.Series({"location": centroid})
112
+
113
+ addresses_CAT = addresses_CAT.merge(
114
+ gdf[["building_reference", "location"]].
115
+ groupby(["building_reference"]).
116
+ apply(calculate_centroid,include_groups=False).reset_index(),
117
+ on="building_reference", how="left")
118
+ if sum(addresses_CAT['location'].isna())>0:
119
+ for code in addresses_CAT.cadaster_code[addresses_CAT['location'].isna()].unique():
120
+ buildings = gpd.read_file(f"{cadaster_dir}/buildings/unzip/A.ES.SDGC.BU.{code}.building.gml", layer="Building")
121
+ for idx in addresses_CAT.index[(addresses_CAT['location'].isna()) & (addresses_CAT['cadaster_code'] == code)]:
122
+ try:
123
+ addresses_CAT.loc[idx, 'location'] = list(buildings[buildings['reference'] == addresses_CAT.loc[idx, 'building_reference']].geometry)[0].centroid
124
+ except:
125
+ pass
126
+ addresses_CAT = gpd.GeoDataFrame(addresses_CAT)
127
+ addresses_CAT = addresses_CAT.set_geometry("location")
128
+ addresses_CAT = addresses_CAT.set_crs(gdf.crs)
129
+ addresses_CAT["specification"] = "CATFile"
130
+ gdf = pd.concat([gdf, addresses_CAT], ignore_index=True)
131
+ gdf = gdf.drop_duplicates(subset=["street_name", "street_number", "street_type", "cadaster_code"], keep="first", ignore_index=True)
132
+
133
+ if directions_from_open_data and "08900" in cadaster_codes:
134
+ bcn_open_data_streets = gpd.read_file(f"{open_data_layers_dir}/barcelona_carrerer.gpkg")
135
+ def extract_up_to_second_capital_or_number(text):
136
+ # Find all positions of capitalized words
137
+ capital_matches = list(re.finditer(r'\b\p{Lu}[^\s]*', text))
138
+ # Find all positions of numbers
139
+ number_match = re.search(r'\b\d+', text)
140
+ # Determine cut-off point: min of second capital or first number
141
+ cutoff_indices = []
142
+ if len(capital_matches) >= 2:
143
+ cutoff_indices.append(capital_matches[1].start())
144
+ if number_match:
145
+ cutoff_indices.append(number_match.start())
146
+ if cutoff_indices:
147
+ return text[:min(cutoff_indices)]
148
+ return None
149
+ bcn_open_data_streets['street_type'] = bcn_open_data_streets['NOM_CARRER'].apply(
150
+ extract_up_to_second_capital_or_number)
151
+ bcn_open_data_streets['street_name'] = bcn_open_data_streets.apply(
152
+ lambda row: row['NOM_CARRER'][len(row['street_type']):].strip() if pd.notnull(row['street_type']) else None,
153
+ axis=1
154
+ )
155
+ bcn_open_data_streets['street_type'] = bcn_open_data_streets['street_type'].str.upper()
156
+ bcn_open_data_streets['street_name'] = bcn_open_data_streets['street_name'].str.upper()
157
+
158
+ # Step 1: Ensure CRS matches
159
+ if bcn_open_data_streets.crs != parcels_gdf.crs:
160
+ bcn_open_data_streets = bcn_open_data_streets.to_crs(parcels_gdf.crs)
161
+
162
+ # Step 2: Spatial join - points inside parcels
163
+ bcn_open_data_streets = gpd.sjoin(
164
+ bcn_open_data_streets, parcels_gdf[['building_reference', 'parcel_geometry']],
165
+ how="left", predicate="within"
166
+ )
167
+
168
+ # Step 3: Find unmatched (not inside any parcel)
169
+ unmatched = bcn_open_data_streets[bcn_open_data_streets['building_reference'].isna()].copy()
170
+
171
+ if not unmatched.empty:
172
+ # Create a spatial index for parcels
173
+ parcels_gdf = parcels_gdf.set_geometry('parcel_geometry')
174
+ parcel_sindex = parcels_gdf.sindex
175
+
176
+ # Function to find closest parcel geometry
177
+ def find_closest_parcel(point):
178
+ # Ensure input is a Shapely Point
179
+ nearest_idx = list(parcel_sindex.nearest(point, 1))
180
+ closest_geom = parcels_gdf.iloc[nearest_idx[0]]
181
+ return closest_geom['building_reference']
182
+
183
+ # Apply to unmatched geometries
184
+ unmatched['building_reference'] = unmatched['geometry'].apply(find_closest_parcel)
185
+
186
+ # Step 4: Merge results back
187
+ bcn_open_data_streets.update(unmatched)
188
+
189
+ bcn_open_data_streets["location"] = bcn_open_data_streets.geometry.centroid
190
+ bcn_open_data_streets["specification"] = "OpenDataBCN"
191
+ bcn_open_data_streets["cadaster_code"] = "08900"
192
+ bcn_open_data_streets["street_number"] = pd.to_numeric(bcn_open_data_streets["NUMPOST"],
193
+ errors='coerce').astype(str)
194
+ bcn_open_data_streets["street_number_clean"] = pd.to_numeric(bcn_open_data_streets["NUMPOST"],
195
+ errors='coerce').astype('Int64')
196
+
197
+ aggregated = (
198
+ bcn_open_data_streets.groupby('geometry')['street_number_clean']
199
+ .agg(['min', 'max'])
200
+ .reset_index()
201
+ )
202
+
203
+ aggregated['street_number_clean_label'] = aggregated.apply(
204
+ lambda row: str(int(row['min'])) if row['min'] == row['max']
205
+ else f"{int(row['min'])}-{int(row['max'])}",
206
+ axis=1
207
+ )
208
+
209
+ bcn_open_data_streets = bcn_open_data_streets.merge(aggregated[['geometry', 'street_number_clean_label']],
210
+ on='geometry', how='left')
211
+ bcn_open_data_streets["street_number_odbcn_label"] = bcn_open_data_streets["ETIQUETA"]
212
+
213
+ bcn_open_data_streets = bcn_open_data_streets[
214
+ ['location', 'specification', 'cadaster_code', 'street_type', 'street_name', 'street_number_clean_label',
215
+ 'street_number_odbcn_label', 'street_number', 'street_number_clean', 'building_reference']]
216
+
217
+ gdf = gdf[gdf["cadaster_code"]!="08900"]
218
+ gdf = pd.concat([gdf, bcn_open_data_streets])
219
+
220
+ return gdf
221
+
222
+
223
+ def join_cadaster_building(gdf, cadaster_dir, cadaster_codes, results_dir, open_street_dir, building_parts_plots=False,
224
+ plot_zones_ratio=0.01, building_parts_inference=False,
225
+ building_parts_inference_using_CAT_files=False, open_data_layers=False,
226
+ open_data_layers_dir=None, CAT_files_dir=None):
227
+
228
+ sys.stderr.write(f"\nJoining the buildings description for {len(cadaster_codes)} municipalities\n")
229
+
230
+ for code in cadaster_codes:
231
+
232
+ sys.stderr.write("\r" + " " * 60)
233
+ sys.stderr.flush()
234
+ sys.stderr.write(f"\r\tCadaster code: {code}")
235
+ sys.stderr.flush()
236
+
237
+ # Parse building harmonised to INSPIRE
238
+ building_gdf_ = gpd.read_file(f"{cadaster_dir}/buildings/unzip/A.ES.SDGC.BU.{code}.building.gml", layer="Building")
239
+ building_gdf_= building_gdf_.rename(columns={
240
+ 'geometry': 'building_geometry',
241
+ 'value': 'building_area',
242
+ 'conditionOfConstruction': 'building_status',
243
+ 'currentUse': 'building_use',
244
+ 'numberOfBuildingUnits': 'n_building_units',
245
+ 'numberOfDwellings': 'n_dwellings',
246
+ 'numberOfFloorsAboveGround': 'n_floors_above_ground',
247
+ 'numberOfFloorsBelowGround': 'n_floors_below_ground',
248
+ 'reference': 'building_reference',
249
+ 'beginning': 'year_of_construction'
250
+ })
251
+ building_gdf_['year_of_construction'] = building_gdf_['year_of_construction'].str[0:4]
252
+ building_gdf_['year_of_construction'] = pd.to_numeric(
253
+ building_gdf_['year_of_construction'], errors='coerce').astype('Int64')
254
+ building_gdf_.drop(
255
+ ["localId", "namespace", "officialAreaReference", "value_uom", "horizontalGeometryEstimatedAccuracy",
256
+ "horizontalGeometryEstimatedAccuracy_uom", "horizontalGeometryReference", "referenceGeometry",
257
+ "documentLink", "format", "sourceStatus", "beginLifespanVersion", "end", "endLifespanVersion",
258
+ "informationSystem"],
259
+ inplace=True, axis=1)
260
+ building_gdf_ = building_gdf_.set_geometry("building_geometry")
261
+
262
+ if "building_gdf" in locals():
263
+ if building_gdf_.crs != building_gdf.crs:
264
+ building_gdf_ = building_gdf_.to_crs(building_gdf.crs)
265
+ building_gdf = gpd.GeoDataFrame(pd.concat([building_gdf, building_gdf_], ignore_index=True))
266
+ else:
267
+ building_gdf = building_gdf_
268
+
269
+ # Parse CAT file, if available
270
+ if building_parts_inference_using_CAT_files:
271
+ buildings_CAT = building_inference.parse_horizontal_division_buildings_CAT_files(code, CAT_files_dir)
272
+ else:
273
+ buildings_CAT = None
274
+
275
+ if building_parts_inference:
276
+
277
+ building_part_gdf_ = gpd.read_file(f"{cadaster_dir}/buildings/unzip/A.ES.SDGC.BU.{code}.buildingpart.gml",
278
+ layer="BuildingPart")
279
+
280
+ sys.stderr.write("\r" + " " * 60)
281
+ building_part_gdf_.rename(columns={
282
+ 'geometry': 'building_part_geometry',
283
+ 'numberOfFloorsAboveGround': 'n_floors_above_ground',
284
+ 'numberOfFloorsBelowGround': 'n_floors_below_ground',
285
+ 'localId': 'building_reference'
286
+ }, inplace=True)
287
+ building_part_gdf_['building_reference'] = building_part_gdf_['building_reference'].str.split("_").str[0]
288
+ building_part_gdf_.drop(
289
+ ['gml_id', 'beginLifespanVersion', 'conditionOfConstruction',
290
+ 'namespace', 'horizontalGeometryEstimatedAccuracy',
291
+ 'horizontalGeometryEstimatedAccuracy_uom',
292
+ 'horizontalGeometryReference', 'referenceGeometry', 'heightBelowGround',
293
+ 'heightBelowGround_uom'],
294
+ inplace=True, axis=1)
295
+
296
+ gdf_unique = gdf.drop_duplicates(subset='building_reference')
297
+ building_part_gdf_ = building_part_gdf_.join(gdf_unique.set_index('building_reference'),
298
+ on="building_reference", how="left")
299
+ building_part_gdf_.loc[building_part_gdf_["zone_type"].isna(), "zone_type"] = "unknown"
300
+ building_part_gdf_.loc[building_part_gdf_["zone_reference"].isna(), "zone_reference"] = "unknown"
301
+ # building_part_gdf_.drop(columns=["building_part_geometry"]).set_geometry("location").to_file("test.gpkg")
302
+
303
+ # building_part_gdf_ = building_part_gdf_.merge(building_gdf_[['building_reference','building_status']])
304
+
305
+ # In case of Barcelona municipality analysis, use commercial establishments and ground premises datasets
306
+ if code=="08900" and open_data_layers:
307
+ # establishments = pd.read_csv(
308
+ # filepath_or_buffer=f"{open_data_layers_dir}/barcelona_establishments.csv",
309
+ # encoding=from_path(f"{open_data_layers_dir}/barcelona_establishments.csv").best().encoding,
310
+ # on_bad_lines='skip',
311
+ # sep=",")
312
+ ground_premises = downloaders.load_and_transform_barcelona_ground_premises(open_data_layers_dir)
313
+ building_part_gdf_ = building_part_gdf_.join(ground_premises.set_index("building_reference"),
314
+ on="building_reference", how="left")
315
+ # building_part_gdf_.loc[
316
+ # ((building_part_gdf_.n_floors_above_ground == 0) &
317
+ # (building_part_gdf_.n_floors_below_ground == 1)),
318
+ # "n_floors_above_ground"] = 1
319
+
320
+ # Join the parcel
321
+ building_part_gdf_, parcels_gdf = join_cadaster_parcel(building_part_gdf_, cadaster_dir, [code])
322
+
323
+ # Process the building parts
324
+ building_part_gdf_ = building_inference.process_building_parts(
325
+ code=code, building_part_gdf_=building_part_gdf_, buildings_CAT=buildings_CAT,
326
+ parcels_gdf=parcels_gdf, results_dir=results_dir, cadaster_dir=cadaster_dir,
327
+ open_street_dir=open_street_dir, plots=building_parts_plots, plot_zones_ratio=plot_zones_ratio)
328
+
329
+ if "building_part_gdf" in locals():
330
+ building_part_gdf = pd.concat([building_part_gdf, building_part_gdf_[1]], ignore_index=True)
331
+ else:
332
+ building_part_gdf = building_part_gdf_[1]
333
+
334
+ # Join Building geodataframe with
335
+ building_gdf = (building_gdf[['gml_id', 'building_status', 'building_reference', 'building_use',
336
+ 'building_geometry','year_of_construction']].
337
+ merge(building_part_gdf, left_on="building_reference",
338
+ right_on="building_reference", how="left"))
339
+
340
+ elif buildings_CAT is not None:
341
+ #['n_building_units', 'n_dwellings', 'n_floors_above_ground', 'building_area']
342
+
343
+ building_gdf = building_gdf[['gml_id', 'building_status', 'building_reference', 'building_use',
344
+ 'building_geometry', 'year_of_construction']]
345
+
346
+ use_types = buildings_CAT["building_space_inferred_use_type"].unique().to_list()
347
+
348
+ # Function to convert use type to snake_case with prefix
349
+ def to_snake_case_prefix(use_type: str) -> str:
350
+ return "building_area_" + re.sub(r'[^a-zA-Z0-9]+', '_', use_type.strip().lower()).strip('_')
351
+
352
+ # Create the use type column mapping
353
+ use_type_mapping = {use_type: to_snake_case_prefix(use_type) for use_type in use_types}
354
+
355
+ # First, summarize total area per building and use type
356
+ area_per_use = (
357
+ buildings_CAT
358
+ .group_by(["building_reference", "building_space_inferred_use_type"])
359
+ .agg(
360
+ pl.col("building_space_area_with_communal").sum().alias("area_by_use")
361
+ )
362
+ )
363
+
364
+ # Pivot so each use type becomes a column
365
+ area_pivot = (
366
+ area_per_use
367
+ .pivot(
368
+ values="area_by_use",
369
+ index="building_reference",
370
+ on="building_space_inferred_use_type"
371
+ )
372
+ .rename(use_type_mapping) # rename columns
373
+ .fill_null(0.0) # optional: replace nulls with 0 for missing use types
374
+ )
375
+
376
+ # Add additional metrics: total units, dwellings, floors, total area
377
+ summary = (
378
+ buildings_CAT
379
+ .group_by("building_reference")
380
+ .agg([
381
+ pl.len().alias("n_building_units"),
382
+ (pl.col("building_space_inferred_use_type") == "Residential")
383
+ .sum()
384
+ .alias("n_dwellings"),
385
+ pl.col("building_space_floor_name").unique().count().alias("n_floors_above_ground"),
386
+ pl.col("building_space_area_with_communal").sum().alias("building_area")
387
+ ])
388
+ )
389
+
390
+ # Join both tables
391
+ final_df = summary.join(area_pivot, on="building_reference", how="left").to_pandas()
392
+ building_gdf = pd.merge(building_gdf, final_df, on="building_reference", how="left")
393
+
394
+ else:
395
+ building_gdf = building_gdf[['gml_id', 'building_status', 'building_reference', 'building_use',
396
+ 'building_geometry', 'year_of_construction', 'n_building_units', 'n_dwellings',
397
+ 'n_floors_above_ground', 'building_area']]
398
+
399
+ return pd.merge(gdf, building_gdf, left_on="building_reference", right_on="building_reference", how="left")
400
+
401
+
402
+ def join_cadaster_zone(gdf, cadaster_dir, cadaster_codes):
403
+
404
+ sys.stderr.write(f"\nJoining the cadaster zones for {len(cadaster_codes)} municipalities\n")
405
+
406
+ for code in cadaster_codes:
407
+
408
+ sys.stderr.write("\r" + " " * 60)
409
+ sys.stderr.flush()
410
+ sys.stderr.write(f"\r\tCadaster code: {code}")
411
+ sys.stderr.flush()
412
+
413
+ zone_gdf_ = gpd.read_file(f"{cadaster_dir}/parcels/unzip/A.ES.SDGC.CP.{code}.cadastralzoning.gml",
414
+ layer="CadastralZoning")
415
+ if "zone_gdf" in locals():
416
+ if zone_gdf_.crs != zone_gdf.crs:
417
+ zone_gdf_ = zone_gdf_.to_crs(zone_gdf.crs)
418
+ zone_gdf = gpd.GeoDataFrame(pd.concat([zone_gdf, zone_gdf_], ignore_index=True))
419
+ else:
420
+ zone_gdf = zone_gdf_
421
+
422
+ sys.stderr.write("\r" + " " * 60)
423
+ zone_gdf.rename(columns={
424
+ 'LocalisedCharacterString': 'zone_type',
425
+ 'nationalCadastalZoningReference': 'zone_reference'
426
+ }, inplace=True)
427
+ zone_gdf.drop(['gml_id', 'estimatedAccuracy', 'estimatedAccuracy_uom', 'localId',
428
+ 'namespace', "label", "beginLifespanVersion", "pos", "endLifespanVersion",
429
+ "originalMapScaleDenominator"], inplace=True, axis=1)
430
+
431
+ # Urban zones
432
+ zone_gdf_urban = zone_gdf.loc[zone_gdf["zone_type"] == "MANZANA "].copy()
433
+ zone_gdf_urban = zone_gdf_urban.set_geometry("geometry")
434
+
435
+ # Perform spatial join
436
+ joined_urban = gpd.sjoin(
437
+ gdf.to_crs(zone_gdf_urban.crs),
438
+ zone_gdf_urban,
439
+ how="left",
440
+ predicate="within"
441
+ ).drop(["index_right"], axis=1)
442
+
443
+ # Handle rows where 'zone_reference' is NaN
444
+ def assign_closest_zone(row, zone_gdf_aux):
445
+ if pd.isna(row["zone_reference"]):
446
+ try:
447
+ # Calculate distances to all urban zones
448
+ distances = zone_gdf_aux["geometry"].distance(row["location"])
449
+ closest_idx = distances.idxmin()
450
+ # Return the closest zone_reference
451
+ return zone_gdf_aux.loc[closest_idx, "zone_reference"]
452
+ except:
453
+ theoretical_ref = row["building_reference"][0:5] + row["building_reference"][7:]
454
+ if theoretical_ref in list(zone_gdf_aux["zone_reference"]):
455
+ return theoretical_ref
456
+ else:
457
+ return np.nan
458
+ return row["zone_reference"]
459
+
460
+
461
+ # Apply the distance-based assignment for NaN 'zone_reference' rows
462
+ joined_urban["zone_reference"] = joined_urban.apply(
463
+ lambda row: assign_closest_zone(row, zone_gdf_urban), axis=1
464
+ )
465
+ joined_urban["zone_type"] = "MANZANA "
466
+
467
+ # Disseminated zones
468
+ zone_gdf_rural = zone_gdf.loc[zone_gdf["zone_type"] == "POLIGONO "].copy()
469
+ zone_gdf_rural = zone_gdf_rural.set_geometry("geometry")
470
+
471
+ # Perform spatial join
472
+ joined_rural = gpd.sjoin(
473
+ gdf.to_crs(zone_gdf_rural.crs),
474
+ zone_gdf_urban,
475
+ how="left",
476
+ predicate="within"
477
+ ).drop(["index_right"], axis=1)
478
+
479
+ # Apply the distance-based assignment for NaN 'zone_reference' rows
480
+ joined_rural["zone_reference"] = joined_rural.apply(
481
+ lambda row: assign_closest_zone(row, zone_gdf_rural), axis=1
482
+ )
483
+ joined_rural["zone_type"] = "POLIGONO "
484
+ joined_rural["zone_reference"] = joined_rural["zone_reference"].fillna("disseminated")
485
+
486
+ # Join urban and rural
487
+ joined = pd.concat([joined_urban.loc[~joined_urban["zone_reference"].isna(), :],
488
+ joined_rural.loc[joined_urban["zone_reference"].isna(), :]]).reset_index()
489
+ joined["zone_type"] = joined["zone_type"].replace({"MANZANA ": "urban", "POLIGONO ": "disseminated"})
490
+
491
+ if sum(joined["location"].isna())>0:
492
+ def assign_location_of_the_zone(row, zone_gdf_aux):
493
+ if pd.isna(row["location"]):
494
+ try:
495
+ return list(zone_gdf_aux[zone_gdf_aux["zone_reference"] == row["zone_reference"]].geometry)[0].centroid
496
+ except:
497
+ return np.nan
498
+ return row["location"]
499
+ joined["location"] = joined.apply(
500
+ lambda row: assign_location_of_the_zone(row, zone_gdf), axis=1
501
+ )
502
+
503
+ return joined
504
+
505
+ def join_cadaster_parcel(gdf, cadaster_dir, cadaster_codes, how="left"):
506
+
507
+ for code in cadaster_codes:
508
+
509
+ sys.stderr.write("\r" + " " * 60)
510
+ sys.stderr.flush()
511
+ sys.stderr.write(f"\r\tJoining cadastral parcels for buildings in cadaster code: {code}")
512
+ sys.stderr.flush()
513
+
514
+ parcel_gdf_ = gpd.read_file(f"{cadaster_dir}/parcels/unzip/A.ES.SDGC.CP.{code}.cadastralparcel.gml",
515
+ layer="CadastralParcel")
516
+ if "parcel_gdf" in locals():
517
+ if parcel_gdf_.crs != parcel_gdf.crs:
518
+ parcel_gdf_ = parcel_gdf_.to_crs(parcel_gdf.crs)
519
+ parcel_gdf = gpd.GeoDataFrame(pd.concat([parcel_gdf, parcel_gdf_], ignore_index=True))
520
+ else:
521
+ parcel_gdf = parcel_gdf_
522
+
523
+ parcel_gdf = parcel_gdf.rename({"geometry": "parcel_geometry", "localId": "building_reference"}, axis=1)
524
+ parcel_gdf = parcel_gdf[["building_reference", "parcel_geometry"]]
525
+ parcel_gdf = parcel_gdf.drop_duplicates(subset="building_reference", keep="first")
526
+ gdf_joined = gdf.merge(parcel_gdf, on="building_reference", how=how)
527
+ parcel_gdf = parcel_gdf.set_geometry("parcel_geometry")
528
+ parcel_gdf["parcel_centroid"] = parcel_gdf.centroid
529
+
530
+ return (gdf_joined,parcel_gdf)
531
+
532
+ def join_adm_div_naming(gdf, cadaster_dir, cadaster_codes):
533
+
534
+ return pd.merge(gdf, utils.get_administrative_divisions_naming(cadaster_dir, cadaster_codes=cadaster_codes),
535
+ left_on="cadaster_code", right_on="cadaster_code", how="left")
536
+
537
+
538
+ def join_cadaster_data(cadaster_dir, cadaster_codes, results_dir, open_street_dir, building_parts_plots=False,
539
+ building_parts_inference=False, plot_zones_ratio=0.01, use_CAT_files=False,
540
+ open_data_layers=False, open_data_layers_dir=None, CAT_files_dir = None):
541
+
542
+ # Address
543
+ gdf = get_cadaster_address(
544
+ cadaster_dir=cadaster_dir,
545
+ cadaster_codes=cadaster_codes,
546
+ directions_from_CAT_files=use_CAT_files,
547
+ CAT_files_dir=CAT_files_dir,
548
+ directions_from_open_data=open_data_layers,
549
+ open_data_layers_dir=open_data_layers_dir
550
+ )
551
+
552
+ # Zones
553
+ gdf = join_cadaster_zone(gdf=gdf, cadaster_dir=cadaster_dir, cadaster_codes=cadaster_codes)
554
+ # Buildings
555
+ # building_parts_inference_using_CAT_files = use_CAT_files
556
+ # code = "08900"
557
+ gdf = join_cadaster_building(gdf=gdf, cadaster_dir=cadaster_dir, cadaster_codes=cadaster_codes,
558
+ results_dir=results_dir, open_street_dir=open_street_dir,
559
+ building_parts_plots=building_parts_plots,
560
+ plot_zones_ratio=plot_zones_ratio,
561
+ building_parts_inference=building_parts_inference,
562
+ building_parts_inference_using_CAT_files=use_CAT_files,
563
+ open_data_layers=open_data_layers, open_data_layers_dir=open_data_layers_dir,
564
+ CAT_files_dir = CAT_files_dir)
565
+ # Administrative layers naming
566
+ gdf = join_adm_div_naming(gdf=gdf, cadaster_dir=cadaster_dir, cadaster_codes=cadaster_codes)
567
+
568
+ gdf["building_centroid"] = gdf["building_geometry"].centroid
569
+ gdf["building_centroid"] = np.where(gdf["building_geometry"] == None, gdf["location"], gdf["building_centroid"])
570
+ if not "parcel_centroid" in gdf.columns:
571
+ gdf = join_cadaster_parcel(gdf, cadaster_dir, cadaster_codes)[0]
572
+ gdf["parcel_centroid"] = gdf["parcel_geometry"].centroid
573
+ gdf["address_location"] = np.where(gdf["location"] == None, gdf["parcel_centroid"], gdf["location"])
574
+ crs = gdf.crs
575
+ gdf = gdf.drop(columns = ["location"])
576
+ gdf = gdf.set_geometry("address_location")
577
+ gdf = gdf.set_crs(crs)
578
+
579
+ return gdf
580
+
581
+
582
+ def join_DEM_raster(gdf, raster_dir):
583
+
584
+ sys.stderr.write(f"\nJoining the Digital Elevation Model information\n")
585
+
586
+ with rasterio.open(f"{raster_dir}/DEM.tif", 'r+') as rds:
587
+ ini_crs = gdf.crs
588
+ gdf = gdf.to_crs(epsg=4326)
589
+ gdf_ = gdf[~gdf.geometry.isna()]
590
+ gdf_.loc[:,"elevation"] = [x[0] for x in rds.sample(
591
+ [(x, y) for x, y in zip(gdf_.geometry.x, gdf_.geometry.y)])]
592
+ gdf = pd.concat([gdf_,gdf[gdf.geometry.isna()]], axis=0)
593
+ gdf = gdf.to_crs(ini_crs)
594
+
595
+ return gdf
596
+
597
+ def join_by_census_tracts(gdf, census_tract_dir, columns=None, geometry_column = "census_geometry", year = 2022):
598
+
599
+ if columns is None:
600
+ columns = {
601
+ "CUSEC": "section_code",
602
+ "CUDIS": "district_code",
603
+ "geometry": "census_geometry"
604
+ }
605
+ sys.stderr.write(f"\nJoining the census tracts\n")
606
+
607
+ census_gdf = gpd.read_file(f"{census_tract_dir}/validated_census_{year}.gpkg")
608
+ census_gdf.rename(columns = columns, inplace = True)
609
+ census_gdf = census_gdf[columns.values()]
610
+ census_gdf = census_gdf.set_geometry(geometry_column)
611
+ census_gdf = census_gdf.to_crs(gdf.crs)
612
+ census_gdf = gpd.sjoin(gdf, census_gdf, how="left", predicate="within").drop(["index_right"], axis=1)
613
+
614
+ return census_gdf
615
+
616
+
617
+ def get_census_gdf(census_tract_dir, columns=None, geometry_column="geometry", year=2022, crs="EPSG:4326"):
618
+
619
+ if columns is None:
620
+ columns = {
621
+ "CUMUN": "ine_municipality_code",
622
+ "NMUN": "municipality_name",
623
+ "NPRO": "province_name",
624
+ "NCA": "autonomous_community_name",
625
+ "CUSEC": "section_code",
626
+ "CUDIS": "district_code",
627
+ "geometry": "geometry"
628
+ }
629
+ sys.stderr.write(f"\nReading census administrative divisions\n")
630
+
631
+ census_gdf = gpd.read_file(f"{census_tract_dir}/validated_census_{year}.gpkg")
632
+ census_gdf.rename(columns = columns, inplace = True)
633
+ census_gdf = census_gdf[columns.values()]
634
+ census_gdf = census_gdf.set_geometry(geometry_column)
635
+ census_gdf = census_gdf.to_crs(crs)
636
+
637
+ return census_gdf
638
+
639
+ def join_by_neighbourhoods(gdf, neighbourhoods_dir, columns=None, geometry_column="neighborhood_geometry"):
640
+
641
+ if columns is None:
642
+ columns = {
643
+ "codi_barri": "neighborhood_code",
644
+ "nom_barri": "neighborhood_name",
645
+ "nom_districte": "district_name",
646
+ "geometria_etrs89": "neighborhood_geometry"
647
+ }
648
+ sys.stderr.write(f"\nJoining the neighborhoods description\n")
649
+
650
+ neighbourhoods_gdf = gpd.read_file(f"{neighbourhoods_dir}/neighbourhoods.csv")
651
+ neighbourhoods_gdf.rename(columns = columns, inplace = True)
652
+ neighbourhoods_gdf = neighbourhoods_gdf[columns.values()]
653
+ neighbourhoods_gdf[geometry_column] = neighbourhoods_gdf[geometry_column].apply(wkt.loads)
654
+ neighbourhoods_gdf = gpd.GeoDataFrame(neighbourhoods_gdf, geometry=geometry_column, crs='EPSG:25831')
655
+ neighbourhoods_gdf = neighbourhoods_gdf.to_crs(gdf.crs)
656
+ neighbourhoods_gdf = gpd.sjoin(gdf, neighbourhoods_gdf, how="left",
657
+ predicate="within").drop(["index_right"], axis=1)
658
+
659
+ return neighbourhoods_gdf
660
+
661
+
662
+ def join_by_postal_codes(gdf, postal_codes_dir, columns=None, geometry_column="postal_code_geometry"):
663
+
664
+ if columns is None:
665
+ columns = {
666
+ "CODPOS": "postal_code",
667
+ "geometry": "postal_code_geometry"
668
+ }
669
+ sys.stderr.write(f"\nJoining the postal codes\n")
670
+
671
+ postal_codes_gdf = gpd.read_file(f"{postal_codes_dir}/postal_codes.geojson")
672
+ postal_codes_gdf.rename(columns = columns, inplace = True)
673
+ postal_codes_gdf = postal_codes_gdf[columns.values()]
674
+ postal_codes_gdf = gpd.GeoDataFrame(postal_codes_gdf, geometry=geometry_column, crs='EPSG:4326')
675
+ postal_codes_gdf = postal_codes_gdf.to_crs(gdf.crs)
676
+ postal_codes_gdf = gpd.sjoin(gdf, postal_codes_gdf,
677
+ how="left", predicate="within").drop(["index_right"], axis=1)
678
+
679
+ return postal_codes_gdf