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,207 @@
1
+ """Main functions module for hypercadaster_ES.
2
+
3
+ This module provides the primary entry points for downloading and merging
4
+ Spanish cadastral data with external geographic datasets.
5
+
6
+ Main functions:
7
+ - download(): Downloads cadastral and related geographic data
8
+ - merge(): Merges all downloaded data into a unified GeoDataFrame
9
+ """
10
+
11
+ import os
12
+ import geopandas as gpd
13
+ from zipfile import ZipFile, BadZipFile
14
+
15
+ from hypercadaster_ES import mergers
16
+ from hypercadaster_ES import utils
17
+ from hypercadaster_ES import downloaders
18
+
19
+ def download(wd, province_codes=None, ine_codes=None, cadaster_codes=None,
20
+ neighborhood_layer=True, postal_code_layer=True, census_layer=True,
21
+ elevation_layer=True, open_data_layers=True, force=False):
22
+
23
+ if force:
24
+ try:
25
+ os.removedirs(wd)
26
+ except FileNotFoundError:
27
+ pass
28
+ utils.create_dirs(data_dir=wd)
29
+ downloaders.download_file(dir=utils.cadaster_dir_(wd),
30
+ url="https://www.catastro.minhap.es/regularizacion/Regularizacion_municipios_finalizados.xlsx",
31
+ file="ine_inspire_codes.xlsx")
32
+
33
+ # Convert inputs to list format
34
+ if province_codes is not None:
35
+ province_codes = province_codes if isinstance(province_codes, list) else [province_codes]
36
+ if ine_codes is not None:
37
+ ine_codes = ine_codes if isinstance(ine_codes, list) else [ine_codes]
38
+ if cadaster_codes is not None:
39
+ cadaster_codes = cadaster_codes if isinstance(cadaster_codes, list) else [cadaster_codes]
40
+
41
+ # Filter which geographical area to download
42
+ all_cadaster_codes = []
43
+
44
+ if province_codes is None and ine_codes is None and cadaster_codes is None:
45
+ raise ValueError("At least one of the arguments must be provided: province codes (province_codes), "
46
+ "municipality INE codes (ine_codes), or cadaster codes (cadaster_codes)")
47
+
48
+ # Add cadaster codes from province_codes
49
+ if province_codes is not None:
50
+ municipalities = utils.list_municipalities(province_codes=province_codes, echo=False)
51
+ province_cadaster_codes = [item['name'].split("-")[0] for item in municipalities]
52
+ all_cadaster_codes.extend(province_cadaster_codes)
53
+
54
+ # Add cadaster codes from ine_codes
55
+ if ine_codes is not None:
56
+ ine_cadaster_codes = utils.ine_to_cadaster_codes(utils.cadaster_dir_(wd), ine_codes)
57
+ all_cadaster_codes.extend(ine_cadaster_codes)
58
+
59
+ # Add directly provided cadaster codes
60
+ if cadaster_codes is not None:
61
+ all_cadaster_codes.extend(cadaster_codes)
62
+
63
+ # Remove duplicates and set final cadaster_codes
64
+ cadaster_codes = list(set(all_cadaster_codes))
65
+
66
+ # Generate derived codes
67
+ ine_codes = utils.cadaster_to_ine_codes(utils.cadaster_dir_(wd), cadaster_codes)
68
+ province_codes = list(set([code[:2] for code in ine_codes]))
69
+
70
+ # Download the cadaster datasets of that area
71
+ downloaders.cadaster_downloader(cadaster_dir=utils.cadaster_dir_(wd), cadaster_codes=cadaster_codes)
72
+ # Districts and neighborhoods definition are only available for the city of Barcelona
73
+ if '08019' in ine_codes and neighborhood_layer:
74
+ downloaders.download_file(dir=utils.districts_dir_(wd),
75
+ url="https://opendata-ajuntament.barcelona.cat/data/dataset/808daafa-d9ce-48c0-"
76
+ "925a-fa5afdb1ed41/resource/576bc645-9481-4bc4-b8bf-f5972c20df3f/download",
77
+ file="districts.csv")
78
+ downloaders.download_file(dir=utils.neighborhoods_dir_(wd),
79
+ url="https://opendata-ajuntament.barcelona.cat/data/dataset/808daafa-d9ce-48c0-"
80
+ "925a-fa5afdb1ed41/resource/b21fa550-56ea-4f4c-9adc-b8009381896e/download",
81
+ file="neighbourhoods.csv")
82
+ # Postal codes
83
+ if postal_code_layer or elevation_layer:
84
+ downloaders.download_postal_codes(postal_codes_dir=utils.postal_codes_dir_(wd), province_codes=province_codes)
85
+ # Digital Elevation Model layer
86
+ if elevation_layer:
87
+ postal_codes_gdf = gpd.read_file(f"{utils.postal_codes_dir_(wd)}/postal_codes.geojson")
88
+ postal_codes_gdf = gpd.GeoDataFrame(postal_codes_gdf, geometry='geometry', crs='EPSG:4326')
89
+ bbox_postal_code = utils.get_bbox(gdf = postal_codes_gdf)
90
+ downloaders.download_DEM_raster(raster_dir=utils.DEM_raster_dir_(wd), bbox=bbox_postal_code)
91
+ # Census tracts and districts
92
+ if census_layer:
93
+ downloaders.download_census_tracts(census_tracts_dir=utils.census_tracts_dir_(wd), year=2022)
94
+ # OpenDataBarcelona
95
+ if '08019' in ine_codes and open_data_layers:
96
+ downloaders.download_file(dir=utils.open_data_dir_(wd),
97
+ url="https://opendata-ajuntament.barcelona.cat/data/dataset/3dc277bf-ff89-4b49-8f"
98
+ "29-48a1122bb813/resource/2e123ea9-1819-46cf-a545-be61151fa97d/download",
99
+ file="barcelona_establishments.csv")
100
+ downloaders.download_file(dir=utils.open_data_dir_(wd),
101
+ url="https://opendata-ajuntament.barcelona.cat/data/dataset/fe177673-0f83-42e7-b3"
102
+ "5a-ddea901be8bc/resource/99764d55-b1be-4281-b822-4277442cc721/download/22093"
103
+ "0_censcomercialbcn_opendata_2022_v10_mod.csv",
104
+ file="barcelona_ground_premises.csv")
105
+ downloaders.download_file(dir=utils.open_data_dir_(wd),
106
+ url="https://opendata-ajuntament.barcelona.cat/data/dataset/6b5cfa7b-1d8d-45f0-990a-"
107
+ "d1844d43ffd1/resource/26c6be33-44f5-4596-8a29-7ac152546ca7/download",
108
+ file="barcelona_carrerer.zip")
109
+ try:
110
+ with ZipFile(f"{utils.open_data_dir_(wd)}/barcelona_carrerer.zip", 'r') as zip:
111
+ zip.extractall(utils.open_data_dir_(wd))
112
+ os.rename(f"{utils.open_data_dir_(wd)}/Adreces_elementals.gpkg",
113
+ f"{utils.open_data_dir_(wd)}/barcelona_carrerer.gpkg")
114
+ os.remove(f"{utils.open_data_dir_(wd)}/barcelona_carrerer.zip")
115
+ except BadZipFile:
116
+ os.remove(f"{utils.open_data_dir_(wd)}/barcelona_carrerer.zip")
117
+
118
+ def merge(wd, province_codes=None, ine_codes=None, cadaster_codes=None,
119
+ neighborhood_layer=True, postal_code_layer=True, census_layer=True, elevations_layer=True,
120
+ open_data_layers=True, building_parts_inference=False, building_parts_plots=False,
121
+ plot_zones_ratio=0.01, use_CAT_files=False, CAT_files_rel_dir="CAT_files"):
122
+
123
+ # Convert inputs to list format
124
+ if province_codes is not None:
125
+ province_codes = province_codes if isinstance(province_codes, list) else [province_codes]
126
+ if ine_codes is not None:
127
+ ine_codes = ine_codes if isinstance(ine_codes, list) else [ine_codes]
128
+ if cadaster_codes is not None:
129
+ cadaster_codes = cadaster_codes if isinstance(cadaster_codes, list) else [cadaster_codes]
130
+
131
+ # Filter which geographical area to download
132
+ all_cadaster_codes = []
133
+
134
+ if province_codes is None and ine_codes is None and cadaster_codes is None:
135
+ raise ValueError("At least one of the arguments must be provided: province codes (province_codes), "
136
+ "municipality INE codes (ine_codes), or cadaster codes (cadaster_codes)")
137
+
138
+ # Add cadaster codes from province_codes
139
+ if province_codes is not None:
140
+ municipalities = utils.list_municipalities(province_codes=province_codes, echo=False)
141
+ province_cadaster_codes = [item['name'].split("-")[0] for item in municipalities]
142
+ all_cadaster_codes.extend(province_cadaster_codes)
143
+
144
+ # Add cadaster codes from ine_codes
145
+ if ine_codes is not None:
146
+ ine_cadaster_codes = utils.ine_to_cadaster_codes(utils.cadaster_dir_(wd), ine_codes)
147
+ all_cadaster_codes.extend(ine_cadaster_codes)
148
+
149
+ # Add directly provided cadaster codes
150
+ if cadaster_codes is not None:
151
+ all_cadaster_codes.extend(cadaster_codes)
152
+
153
+ # Remove duplicates and set final cadaster_codes
154
+ cadaster_codes = list(set(all_cadaster_codes))
155
+
156
+ # Validate building analysis constraints
157
+ if (building_parts_inference or building_parts_plots) and len(cadaster_codes) > 1:
158
+ raise ValueError(
159
+ f"Building parts inference and plots are computationally intensive and can only be enabled "
160
+ f"for single municipality processing. Found {len(cadaster_codes)} municipalities: {cadaster_codes}. "
161
+ f"Please process municipalities individually when using building_parts_inference=True or "
162
+ f"building_parts_plots=True."
163
+ )
164
+
165
+ gdf = mergers.join_cadaster_data(
166
+ cadaster_dir=utils.cadaster_dir_(wd),
167
+ cadaster_codes=cadaster_codes,
168
+ results_dir=utils.results_dir_(wd),
169
+ open_street_dir=utils.open_street_dir_(wd),
170
+ building_parts_inference=building_parts_inference,
171
+ use_CAT_files=use_CAT_files,
172
+ building_parts_plots=building_parts_plots,
173
+ plot_zones_ratio=plot_zones_ratio,
174
+ open_data_layers=open_data_layers,
175
+ open_data_layers_dir=utils.open_data_dir_(wd),
176
+ CAT_files_dir=f"{wd}/{CAT_files_rel_dir}"
177
+ )
178
+
179
+ if census_layer:
180
+ gdf = mergers.join_by_census_tracts(
181
+ gdf = gdf,
182
+ census_tract_dir=utils.census_tracts_dir_(wd))
183
+ if neighborhood_layer:
184
+ gdf = mergers.join_by_neighbourhoods(
185
+ gdf = gdf,
186
+ neighbourhoods_dir=utils.neighborhoods_dir_(wd))
187
+ if postal_code_layer:
188
+ gdf = mergers.join_by_postal_codes(
189
+ gdf = gdf,
190
+ postal_codes_dir=utils.postal_codes_dir_(wd))
191
+ if elevations_layer:
192
+ gdf = mergers.join_DEM_raster(
193
+ gdf = gdf,
194
+ raster_dir = utils.DEM_raster_dir_(wd)
195
+ )
196
+ if "index" in gdf.columns:
197
+ gdf.drop("index", axis=1, inplace=True)
198
+
199
+ # columns that have dicts
200
+ cols_with_dicts = [c for c in gdf.columns
201
+ if gdf[c].apply(lambda v: isinstance(v, dict) or isinstance(v,list)).any()]
202
+
203
+ subset = [c for c in gdf.columns if c not in cols_with_dicts + ['geometry']]
204
+ gdf = gdf.drop_duplicates(subset=subset, keep='first')
205
+
206
+ return gdf
207
+
@@ -0,0 +1,191 @@
1
+ """Interoperability functions for external systems integration.
2
+
3
+ This module provides functions for converting hypercadaster_ES data
4
+ into formats compatible with external simulation and analysis tools.
5
+
6
+ Main functions:
7
+ - input_files_for_IREC_simulations(): Convert data for IREC building energy simulations
8
+ - plot_weather_stations(): Visualize weather station clustering
9
+ - converter_(): Provide data structure mappings for external tools
10
+
11
+ TODO:
12
+ - Add real street width calculations using parcel geometries
13
+ - Add comprehensive rehabilitation analysis
14
+ - Investigate empty orientation cases: 9505427DF2890F
15
+ """
16
+
17
+ import numpy as np
18
+ import pandas as pd
19
+ import matplotlib.pyplot as plt
20
+ def input_files_for_IREC_simulations(gdf):
21
+
22
+ gdf_filt = gdf.drop_duplicates(subset="building_reference")
23
+ gdf_filt = gdf_filt[gdf_filt["br__building_spaces"].apply(lambda d: isinstance(d, dict) and "Residential" in d)]
24
+
25
+ def classify_building_type(spaces, detached):
26
+ residential_units = spaces.get("Residential", 0)
27
+ non_residential_units = sum(v for k, v in spaces.items() if k != "Residential")
28
+ if residential_units == 1:
29
+ return "SF"
30
+ elif residential_units > 1:
31
+ return "MFI" if detached else "MFNI"
32
+ elif residential_units == 0:
33
+ return "NR"
34
+ return "Unknown"
35
+
36
+
37
+ def calculate_typology_percentages(areas):
38
+ if not isinstance(areas, dict):
39
+ areas = areas.values[0]
40
+ total = sum(areas.values())
41
+ return {
42
+ "BuildingResidentialArea": areas.get("Residential", 0) / total * 100 if total else 0,
43
+ "BuildingCommercialArea": areas.get("Commercial", 0) / total * 100 if total else 0,
44
+ "BuildingOfficesArea": areas.get("Offices", 0) / total * 100 if total else 0,
45
+ "BuildingParkingArea": areas.get("Warehouse - Parking", 0) / total * 100 if total else 0,
46
+ "BuildingOtherUsesArea": 100 - (
47
+ areas.get("Residential", 0) +
48
+ areas.get("Commercial", 0) +
49
+ areas.get("Offices", 0) +
50
+ areas.get("Warehouse - Parking", 0)
51
+ ) / total * 100 if total else 0
52
+ }
53
+
54
+ def extract_floors_by_use(floor_data, use_type):
55
+ return sorted([
56
+ int(f) for building_use, floors in floor_data.items()
57
+ if building_use == use_type
58
+ for f, area in floors.items()
59
+ if area > 0
60
+ ])
61
+
62
+ def process_row(row):
63
+ try:
64
+ building_spaces = row["br__building_spaces"]
65
+ area_wo_communal = row["br__area_without_communals"]
66
+ area_w_communal = row["br__area_with_communals"]
67
+ floor_data = row["br__area_with_communals_by_floor"]
68
+ eff_years = row["br__mean_building_space_effective_year"]
69
+ year_of_construction = row["year_of_construction"] if pd.notna(row["year_of_construction"]) else eff_years["Residential"]
70
+ if year_of_construction<1850 and eff_years["Residential"]>1850:
71
+ year_of_construction = eff_years["Residential"]
72
+ elif year_of_construction<1850:
73
+ year_of_construction = 1850
74
+ avg_eff_year = np.mean(list(eff_years.values())) if eff_years else row["year_of_construction"]
75
+ use_percentages = calculate_typology_percentages(area_w_communal)
76
+ return pd.Series({
77
+ "BuildingReference": row["building_reference"],
78
+ "BuildingType": classify_building_type(building_spaces, row["br__detached"]),
79
+ "Location": row["location"],
80
+ "CensusTract": row["section_code"],
81
+ "PostalCode": row["postal_code"],
82
+ "AllParcelOrientations": row['br__parcel_orientations'],
83
+ "MainParcelOrientation": row['br__parcel_main_orientation'],
84
+ "AllParcelOrientationsStreetWidths": row['br__street_width_by_orientation'],
85
+ "MainParcelOrientationStreetWidth": row['br__street_width_main_orientation'],
86
+ "NumberOfDwelling": building_spaces.get("Residential", 0),
87
+ "UsefulResidentialArea": area_wo_communal.get("Residential", 0),
88
+ "YearOfConstruction": year_of_construction,
89
+ "BuildingWasRetroffited": year_of_construction < avg_eff_year,
90
+ "YearOfRetroffiting": avg_eff_year if year_of_construction < avg_eff_year else year_of_construction,
91
+ **use_percentages,
92
+ "BuildingResidentialFloors": extract_floors_by_use(floor_data, "Residential"),
93
+ "BuildingCommercialFloors": extract_floors_by_use(floor_data, "Commercial"),
94
+ "BuildingOfficesFloors": extract_floors_by_use(floor_data, "Offices"),
95
+ "BuildingParkingFloors": extract_floors_by_use(floor_data, "Warehouse - Parking"),
96
+ "NumberOfFloorsAboveGround": 1 + max([max(floors.keys()) for floors in list(floor_data.values())]),
97
+ "NumberOfFloorsBelowGround": min([min(floors.keys()) for floors in list(floor_data.values())])
98
+ })
99
+ except Exception as e:
100
+ print((row["building_reference"],e))
101
+
102
+
103
+ # Assuming `df` is your original DataFrame
104
+ new_df = gdf_filt.apply(process_row, axis=1)
105
+ return new_df
106
+
107
+ def converter_():
108
+ return {
109
+ 'Edad': {
110
+ 'Menos de 30 años': {},
111
+ 'De 30 a 39 años': {},
112
+ 'De 40 a 49 años': {},
113
+ 'De 50 a 59 años': {},
114
+ 'De 60 a 69 años': {},
115
+ 'De 70 y más años': {}
116
+ },
117
+ 'Sexo': {
118
+ 'Hombre': {},
119
+ 'Mujer': {}
120
+ },
121
+ 'Tipo de núcleo familiar': None,
122
+ 'Tipo de unión': None,
123
+ 'Nivel educativo alcanzado de la pareja': None,
124
+ 'Situación laboral de la pareja': None,
125
+ 'Nivel de ingresos mensuales netos del hogar': {
126
+ 'Menos de 1.000 euros': {},
127
+ 'De 1.000 euros a menos de 1.500 euros': {},
128
+ 'De 1.500 euros a menos de 2.000 euros': {},
129
+ 'De 2.000 euros a menos de 3.000 euros': {},
130
+ '3.000 euros o más': {}
131
+ },
132
+ 'Sexo del progenitor': None,
133
+ 'Estado civil del progenitor': None,
134
+ 'Nivel educativo del progenitor': None,
135
+ 'Situación laboral del progenitor': None,
136
+ 'Tipo de hogar': None,
137
+ 'Número de miembros del hogar': {
138
+ '1 persona': {},
139
+ '2 personas': {},
140
+ '3 personas': {},
141
+ '4 personas o más': {}
142
+ },
143
+ 'Nivel de estudios alcanzado por los miembros del hogar': None,
144
+ 'Situación laboral de los miembros del hogar': None,
145
+ 'Tipo de edificio': {
146
+ 'Total': {},
147
+ 'Vivienda unifamiliar (chalet, adosado, pareado...)': {},
148
+ 'Edificio de 2 o más viviendas': {}
149
+ },
150
+ 'Año de construcción del edificio': {
151
+ 'Total': {},
152
+ '2000 y anterior': {},
153
+ 'Posterior a 2000': {}
154
+ },
155
+ 'Nacionalidad de los miembros del hogar': {
156
+ 'Total': {},
157
+ 'Hogar exclusivamente español': {},
158
+ 'Hogar mixto (con españoles y extranjeros)': {},
159
+ 'Hogar exclusivamente extranjero': {}
160
+ },
161
+ 'Superficie útil de la vivienda': {
162
+ 'Total': {},
163
+ 'Hasta 75 m2': {},
164
+ 'Entre 76 y 90 m2': {},
165
+ 'Entre 91 y 120 m2': {},
166
+ 'Más de 120 m2': {}
167
+ }
168
+ }
169
+
170
+ def plot_weather_stations(gdf, weather_clusters_column, filename):
171
+ fig, ax = plt.subplots(figsize=(15, 12))
172
+
173
+ # Correct GeoPandas plotting syntax
174
+ gdf.plot(
175
+ ax=ax,
176
+ column=weather_clusters_column,
177
+ categorical=True,
178
+ legend=True,
179
+ cmap='tab10',
180
+ markersize=20,
181
+ alpha=0.7,
182
+ edgecolor='black'
183
+ )
184
+
185
+ ax.set_title('Buildings Colored by WeatherCluster', fontsize=14)
186
+ ax.set_xlabel('Longitude')
187
+ ax.set_ylabel('Latitude')
188
+
189
+ plt.grid(True, linestyle='--', alpha=0.5)
190
+ plt.tight_layout()
191
+ plt.savefig(filename)