### curl download output Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Output from the curl command showing a 100% progress bar indicating the download completed successfully. ```text ######################################################################### 100.0% ``` -------------------------------- ### Optional notebook styling and HTML export Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Optional setup to darken plots and code cells, then export the notebook to HTML using nbconvert with the pretty-jupyter template. Requires installing jupyterthemes and nbconvert pretty-jupyter. ```python # -.-|m { input: false } # Optional: darken plots import matplotlib.pyplot as plt plt.style.use('dark_background') # available backgrounds: https://matplotlib.org/stable/gallery/style_sheets/style_sheets_reference.html # Optional: darken code cells !pip install jupyterthemes !jt -t chesterish # available themes: https://chazf.medium.com/jupyter-dark-mode-themes-b242fb459254 # Generating beautiful HTML of notebook !pip install nbconvert pretty-jupyter !jupyter nbconvert --to html --template pj getting-started-website.ipynb ``` -------------------------------- ### DuckDB connection result Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Result of the DuckDB connection setup, showing the connection object reference. ```text <_duckdb.DuckDBPyConnection at 0x103d123f0> ``` -------------------------------- ### Get overview file paths Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/loss-db-set-up.ipynb Uses glob to find Microsoft overview CSV files from the db set-up stage. ```python overview_paths = glob.glob(os.path.join(root,'stats/2-db-set-up/overview/v1','msft*.csv')) ``` -------------------------------- ### Get parsing stat file paths Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/loss-db-set-up.ipynb Uses glob to find all Microsoft building stat files from the parsing stage. ```python parsing_paths = glob.glob(os.path.join(root,'stats/1-parsing','*msft_stat.csv')) ``` -------------------------------- ### GPU-accelerated visualization with Lonboard and deck.gl Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Uses Lonboard's viz function to create a fast, GPU-accelerated visualization for buildings in city CHCH0261 (Zurich). Includes a CartoDB Voyager basemap and tooltips. ```python # Fast, GPU-accelerated visualization via deck.gl and Lonboard from lonboard import viz from lonboard.basemap import MaplibreBasemap zurich_center = gdf[gdf["city_id"] == "CHCH0261"] viz(zurich_center, map_kwargs={'basemap': MaplibreBasemap(style='https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json'), 'show_tooltip': True}) ``` -------------------------------- ### Change working directory Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Sets the working directory to the project path for subsequent file operations. ```python os.chdir('/home/nmd/Projects/mlup/tests/db-set-refactoring/') ``` -------------------------------- ### Unzip all .zip files in directory Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/0-downloading/downloading-brandenburg.txt Extracts all .zip files in the current directory. Requires the unzip package; install with 'sudo apt install unzip' if not present. ```bash unzip \*.zip ``` -------------------------------- ### Download EUBUCCO parquet with AWS CLI Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Alternative to curl for downloading the same CH04.parquet file using the AWS CLI with a custom endpoint URL and no sign request. Requires AWS CLI installed and configured. ```bash !aws s3 cp s3://eubucco/v0.2/buildings/parquet/nuts_id=CH04/CH04.parquet . \ --endpoint-url https://s3.eubucco.com \ --no-sign-request ``` -------------------------------- ### Get OSM parsing stat file paths Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/loss-db-set-up.ipynb Uses glob to find all OSM building stat files from the parsing stage. ```python parsing_paths = glob.glob(os.path.join(root,'stats/1-parsing','*osm_stat.csv')) ``` -------------------------------- ### Import libraries for NUTS processing Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Imports sys, geopandas, and pandas for file handling and data manipulation. ```python import sys import geopandas as gpd import pandas as pd import os ``` -------------------------------- ### Preview NUTS region mapping Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Displays the first few rows of the processed NUTS region mapping. ```python nuts.head() ``` -------------------------------- ### Result: Merged Italian Parsing vs Overview Building Counts Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/loss-db-set-up.ipynb Output of the merge for Italian regions, showing building counts from parsing (n_bldgs_x) and overview (n_bldgs_y) after the setup. ```text Result: dataset_name n_bldgs_x region n_bldgs_y 0 basilicata-gov 477261 basilicata-gov 476111 1 emilia-romagna-gov 1877759 emilia-romagna-gov 1876953 2 valle-d-aosta-gov 52671 valle-d-aosta-gov 50146 3 toscana-gov 1501914 toscana-gov 1500419 4 abruzzo-gov 423678 abruzzo-gov 421472 5 trentino-alto-adige-gov 160077 trentino-alto-adige-gov 159991 6 piemonte-gov 2167166 piemonte-gov 2144572 7 lazio-gov 2413601 lazio-gov 2261358 8 sardegna-gov 337366 sardegna-gov 334407 9 lombardia-gov 3349150 lombardia-gov 3341526 10 liguria-gov 451981 liguria-gov 449415 11 calabria-gov 743896 calabria-gov 742865 12 veneto-gov 2275649 veneto-gov 2266820 ``` -------------------------------- ### Interactive visualization with Folium for a city Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Creates an interactive map using Folium's explore method for buildings in city CHCH0247, colored by height with viridis colormap and legend. Output is a Folium Map object. ```python # Easy interactive visualization with Folium city = gdf[gdf["city_id"] == "CHCH0247"] city[["id", "height", "height_source", "geometry"]].explore("height", cmap="viridis", legend=True) ``` ```text Result: ``` -------------------------------- ### Display NUTS level 3 output Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Shows the output of the previous head() call, including region names and geometries. ```text Result: LEVL_CODE NUTS_ID NAME_LATN \ 103 3 HR043 Krapinsko-zagorska županija 406 3 AT314 Steyr-Kirchdorf 407 3 AT315 Traunviertel 409 3 DE600 Hamburg 410 3 DE711 Darmstadt, Kreisfreie Stadt NUTS_NAME MOUNT_TYPE URBN_TYPE COAST_TYPE \ 103 Krapinsko-zagorska županija 4 3 3 406 Steyr-Kirchdorf 3 3 3 407 Traunviertel 3 3 3 409 Hamburg 4 1 1 410 Darmstadt, Kreisfreie Stadt 4 1 3 geometry 103 POLYGON ((4774720.63 2587061.468, 4774957.107 ... 406 POLYGON ((4648229.856 2789186.12, 4648604.204 ... 407 POLYGON ((4592531.261 2786657.952, 4593751.148... 409 MULTIPOLYGON (((4314918.091 3393914.497, 43157... 410 POLYGON ((4229546.152 2983211.57, 4230168.376 ... ``` -------------------------------- ### Filter based on attributes and region - Result Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Result of the filtering operation, showing a Lonboard Map object. ```text Result: ``` -------------------------------- ### Load parquet into GeoDataFrame Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Reads the downloaded CH04.parquet file into a GeoDataFrame using geopandas. Requires the file to be present in the current directory. ```python import geopandas as gpd gdf = gpd.read_parquet("CH04.parquet") ``` -------------------------------- ### Read region-stats.parquet Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Reads the 'region-stats.parquet' file using geopandas. The file must be downloaded from https://eubucco.com/files/ before running this code. ```python stats = gpd.read_parquet("region-stats.parquet") ``` -------------------------------- ### Filter by height_source not estimated Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Filters rows where 'height_source' is not 'estimated', then samples 3 rows of 'id', 'height', and 'height_source'. ```python ground_truth_height = gdf[gdf["height_source"] != "estimated"] ground_truth_height[["id", "height", "height_source"]].sample(3) ``` ```text Result: id height height_source 76746 bd663c2187534357-0 7.4 gov-switzerland 187952 6c484e720422495c-0 7.0 gov-switzerland 241682 5ea9b484ec694aff-0 5.2 gov-switzerland ``` -------------------------------- ### Filter by geometry_source not in osm or msft Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Filters rows where 'geometry_source' is not 'osm' or 'msft', then samples 3 rows of 'id' and 'geometry_source'. ```python gov = gdf[~gdf["geometry_source"].isin(["osm", "msft"])] gov[["id", "geometry_source"]].sample(3) ``` ```text Result: id geometry_source 87193 0102229e7dc540de-0 gov-switzerland 172909 4f77ec73011c4b4a-1 gov-switzerland 121576 c0dc8eb41e844455-0 gov-switzerland ``` -------------------------------- ### nbconvert HTML export output Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Output from running the nbconvert command, showing the notebook converted to HTML with a warning about missing alternative text on 4 images and the resulting file size. ```text [NbConvertApp] Converting notebook getting-started-website.ipynb to html [NbConvertApp] WARNING | Alternative text is missing on 4 image(s). [NbConvertApp] Writing 6723123 bytes to getting-started-website.html ``` -------------------------------- ### Configure DuckDB for S3 access Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Sets up a DuckDB connection with the httpfs and spatial extensions, and configures S3 endpoint settings to access the EUBUCCO bucket. The connection object is stored in the variable 'con'. ```python import duckdb con = duckdb.connect() con.execute("INSTALL httpfs; LOAD httpfs;") con.execute("INSTALL spatial; LOAD spatial;") # Specify the S3 endpoint con.execute("SET s3_endpoint='s3.eubucco.com';") con.execute("SET s3_url_style='path';") con.execute("SET s3_region='eu';") con.execute("SET s3_access_key_id='';") con.execute("SET s3_secret_access_key='';") ``` -------------------------------- ### Download EUBUCCO parquet with curl Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Downloads the CH04.parquet file from the EUBUCCO S3 bucket using curl with progress bar and resume support. The file is saved as CH04.parquet in the current directory. ```bash !curl --progress-bar -C - -o CH04.parquet "https://s3.eubucco.com/eubucco/v0.2/buildings/parquet/nuts_id=CH04/CH04.parquet" ``` -------------------------------- ### Import Libraries and Install deep-translator Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/3-attrib-cleaning/type-mapping/type-country.ipynb Sets up the environment by importing required libraries and installing the deep-translator package for translating building type labels. ```python import os import pandas as pd import ast import re import numpy as np import pandas as pd # pip install deep-translator from deep_translator import GoogleTranslator ``` -------------------------------- ### Load NUTS shapefile Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Reads the NUTS 2016 shapefile into a GeoDataFrame for further processing. ```python # load nuts123 file nuts12 = gpd.read_file('0-raw-data/lau/NUTS_RG_01M_2016_3035.shp') ``` -------------------------------- ### Display NUTS region details Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Shows the output of the previous filter, including region name and geometry. ```text Result: LEVL_CODE NUTS_ID CNTR_CODE NAME_LATN \ 789 3 DEE01 DE Dessau-Roßlau, Kreisfreie Stadt NUTS_NAME MOUNT_TYPE URBN_TYPE COAST_TYPE \ 789 Dessau-Roßlau, Kreisfreie Stadt 4 2 3 geometry 789 MULTIPOLYGON (((4469187.816 3187222.648, 44686... ``` -------------------------------- ### Result: Parsing vs Overview Building Counts for German States Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/loss-db-set-up.ipynb Output of the merge between parsing and overview data for German states, showing building counts before and after database setup. ```text Result: dataset_name n_bldgs_x region \ 0 mecklenburg-vorpommern-gov 1125170 mecklenburg-vorpommern-gov 1 sachsen-gov 2066177 sachsen-gov 2 sachsen-anhalt-gov 1746686 sachsen-anhalt-gov 3 brandenburg-gov 2314099 brandenburg-gov 4 nordrhein-westfalen-gov 10713759 nordrhein-westfalen-gov 5 berlin-gov 540126 berlin-gov 6 niedersachsen-gov 6795240 niedersachsen-gov 7 hamburg-gov 382339 hamburg-gov 8 thuerigen-gov 2250018 thuerigen-gov n_bldgs_y 0 1103477 1 2065236 2 1746534 3 2310863 4 10711344 5 537979 6 6792839 7 381365 8 2248760 ``` -------------------------------- ### Read UK overview and sum Northern Ireland buildings Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/loss-db-set-up.ipynb Reads UK overview CSV and sums n_bldgs for NUTS3 regions starting with 'UKN' (Northern Ireland). ```python uk_overview = pd.read_csv('/home/nmd/Cluster/stats/2-db-set-up/overview/v1/osm_uk_overview.csv') northern_ireland = uk_overview[uk_overview.NUTS3_ID.isin([x for x in uk_overview.NUTS3_ID if 'UKN' in x])].n_bldgs.sum() ``` -------------------------------- ### Preview NUTS level 3 regions Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Displays the first few rows of the NUTS level 3 GeoDataFrame. ```python nuts3.head() ``` -------------------------------- ### Display NUTS region mapping output Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Shows the output of the previous head() call, listing country, region ID, region name, and country code. ```text Result: country NUTS_ID_region region CNTR_CODE 4 austria AT32 Salzburg AT 5 austria AT11 Burgenland AT 6 austria AT33 Tirol AT 7 austria AT34 Vorarlberg AT 8 austria AT22 Steiermark AT ``` -------------------------------- ### Simple aggregated visualization with H3 hexagons Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Aggregates building floor area into H3 hexagons at resolution 8 using h3pandas. Requires h3pandas and a GeoDataFrame 'gdf' with 'geometry' and 'height' columns. The result is a plot with a legend and axis off. ```python # Simple aggregated visualization with H3 hexagons import h3pandas gdf_floor = gdf[["geometry", "height"]].copy() gdf_floor["floor_area"] = gdf_floor.area * gdf_floor["height"] gdf_floor["geometry"] = gdf_floor.centroid.to_crs("EPSG:4326") h3_grid = gdf_floor.h3.geo_to_h3_aggregate(resolution=8, operation="sum") h3_grid.plot(column="floor_area", legend=True, figsize=(10, 8)).set_axis_off() ``` -------------------------------- ### Output of spatial join length check Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Prints whether the number of rows in the spatial join equals the number of LAU rows, confirming that every LAU was matched to a NUTS 3 region. ```text Output: True ``` -------------------------------- ### Spatial join LAU to NUTS3 using centroids Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Reads NUTS and LAU shapefiles, filters NUTS to level 3, converts LAU geometries to centroids, and performs a nearest spatial join. Prints whether the join length matches the LAU length. ```python # map laus to respective nuts 3 using spatial joins (yeah, couldnt find a way to do this on ID...) nuts12 = gpd.read_file('0-raw-data/lau/NUTS_RG_01M_2016_3035.shp') lau = gpd.read_file('0-raw-data/lau/LAU_RG_01M_2019_3035.shp') nuts3G = nuts12[nuts12.LEVL_CODE==3].drop(columns={'CNTR_CODE'}) lau['geometry'] = lau['geometry'].centroid join = gpd.sjoin_nearest(lau,nuts3G) print(len(join)==len(lau)) ``` -------------------------------- ### Merge with complete NUTS info Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Merges the LAU-NUTS3 mapping with the full NUTS3 dataframe (excluding geometry) to add country and region details. ```python # merge with complete NUTS info nuts_lau2 = pd.merge(nuts_lau,nuts3.drop(columns=['geometry']), right_on='NUTS_ID_3', left_on='NUTS_ID').drop(columns=['NUTS_ID']) ``` -------------------------------- ### Save final LAU-NUTS3 data to CSV and GeoPackage Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Writes the final merged data to 'lau_nuts_extra.csv' (without geometry) and 'lau_nuts.gpkg' (with geometry). ```python nuts_lau2.drop(columns=['geometry']).to_csv('0-raw-data/lau/lau_nuts_extra.csv',index=False) nuts_lau.to_file('0-raw-data/lau/lau_nuts.gpkg') ``` -------------------------------- ### Create country mapping and filter NUTS levels Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Builds a DataFrame mapping country codes to EUBUCCO country names and NUTS level (1 or 2), then filters NUTS regions accordingly and concatenates results. ```python # mapping country code in NUTS and EUBUCCO country name # and choose NUTS level corresponding to EUBUCCO input datasets for each country df = pd.DataFrame([('AT','austria',2), ('BE','belgium',1), ('BG','bulgaria',1), ('CH','switzerland',1), ('CY','cyprus',1), ('CZ','czechia',1), ('DE','germany',1), ('DK','denmark',1), ('EE','estonia',1), ('EL','greece',1), ('ES','spain',2), ('FI','finland',1), ('FR','france',1), ('HR','croatia',1), ('HU','hungary',1), ('IE','ireland',1), ('IT','italy',2), ('LT','lithuania',1), ('LU','luxembourg',1), ('LV','latvia',1), ('MT','malta',1), ('NL','netherlands',1), ('NO','norway',1), ('PL','poland',1), ('PT','portugal',1), ('RO','romania',1), ('SE','sweden',1), ('SI','slovenia',1), ('SK','slovakia',1), ('UK','uk',1)], columns=['CNTR_CODE','country','nuts1/2']) nuts = pd.DataFrame() for _,row in df.iterrows(): tmp = pd.merge(pd.DataFrame([row.values], columns=row.index),nuts12,on='CNTR_CODE') if row['nuts1/2']==1: tmp = tmp[tmp.LEVL_CODE==1] elif row['nuts1/2']==2: tmp = tmp[tmp.LEVL_CODE==2] else: sys.exit('Error with NUTS level.') nuts = pd.concat([nuts,tmp])[['country','NUTS_ID','NAME_LATN','CNTR_CODE']] nuts = nuts.rename(columns={'NAME_LATN':'region','NUTS_ID': 'NUTS_ID_region'}) ``` -------------------------------- ### Install and import GoogleTranslator Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/3-attrib-cleaning/type-mapping/type-germany.ipynb Installs the deep-translator package and imports GoogleTranslator for translating German names to English. ```python # pip install deep-translator from deep_translator import GoogleTranslator ``` -------------------------------- ### Read NUTS shapefile Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Reads the NUTS shapefile from '0-raw-data/lau/NUTS_RG_01M_2016_3035.shp' into a GeoDataFrame. ```python nuts12 = gpd.read_file('0-raw-data/lau/NUTS_RG_01M_2016_3035.shp') ``` -------------------------------- ### Filter NUTS by ID Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Selects a specific NUTS region by its ID (e.g., DEE01) to inspect its attributes. ```python nuts12[nuts12.NUTS_ID=='DEE01'] ``` -------------------------------- ### Result of LAU-NUTS mapping counts Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Shows the number of LAU entries after filtering and merging, indicating the final count of matched LAU records. ```text Result: 35229 ``` -------------------------------- ### Check row count of nuts_lau2 Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Returns the number of rows in the 'nuts_lau2' dataframe. ```python len(nuts_lau2) ``` -------------------------------- ### Merge NUTS dataframes to add country and region info Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Merges the NUTS dataframe with NUTS3 data on 'NUTS_ID_region', drops 'NUTS_NAME' and 'LEVL_CODE', and renames 'NAME_LATN' to 'nuts3'. ```python # merge with the nuts dataframe to add country, region and country code information nuts3 = pd.merge(nuts,nuts3,on='NUTS_ID_region').drop(columns=['NUTS_NAME','LEVL_CODE']).rename(columns={'NAME_LATN':'nuts3'}) ``` -------------------------------- ### Compute loss between parsing and db set up Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/loss-db-set-up.ipynb Loads overview files for each country, merges with parsing data, corrects Poland's building count, and calculates absolute and percentage loss. ```python overview_paths = glob.glob(os.path.join(root,'stats/2-db-set-up/overview/v1','gov*.csv')) df_overview = pd.DataFrame() for path in overview_paths: tmp = pd.read_csv(path)[['n_bldgs']] tmp = pd.DataFrame([{'dataset_name':os.path.split(path)[-1].split('_')[1], 'n_bldgs':tmp.n_bldgs.sum() }]) df_overview = pd.concat([df_overview,tmp]) df = pd.merge(df_parsing,df_overview,on='dataset_name',suffixes=('_parsing','_db set up')) df.at[13,'n_bldgs_parsing'] = 14408267 # poland building file incorrect due to powiats df['loss_abs'] = df['n_bldgs_parsing'] - df['n_bldgs_db set up'] df['loss_per'] = round(df['loss_abs'] / df['n_bldgs_parsing'],2) ``` -------------------------------- ### Import libraries and set root path Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/check_no_zeros.ipynb Sets up the environment for reading overview files. Defines the root directory where the overview files are stored. ```python import pandas as pd import os import glob from collections import Counter root = '/home/nmd/Desktop/' ``` -------------------------------- ### Query EUBUCCO with DuckDB and convert to GeoDataFrame Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Uses the DuckDB connection to query the parquet file, converting WKB geometries to WKT, then creates a GeoDataFrame with EPSG:3035 CRS. Requires the DuckDB connection 'con' from the previous setup. ```python import geopandas as gpd # Fetch data with WKB-encoded geometries region = "CH04" s3_path = f"s3://eubucco/v0.2/buildings/parquet/nuts_id={region}/{region}.parquet" query = f""" SELECT * EXCLUDE geometry, ST_AsWKT(geometry) AS geometry FROM '{s3_path}' """ df = con.execute(query).df() # Convert to GeoDataFrame gdf = gpd.GeoDataFrame( df, geometry=gpd.GeoSeries.from_wkt(df["geometry"]), crs="EPSG:3035", ) ``` -------------------------------- ### Merge NUTS level 3 with region mapping Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Merges the NUTS level 3 data with the region mapping by matching NUTS_ID prefixes, then drops the original NUTS_ID column. ```python # merge nuts 3 with relevant nuts 1/2 region # using NUTS_ID_region column from nuts dataframe nuts3 = pd.merge(nuts3,pd.DataFrame([(string, long_string) for string in nuts.NUTS_ID_region.to_list() for long_string in nuts3.NUTS_ID.to_list() if string in long_string], columns=['NUTS_ID_region','NUTS_ID_3']), left_on='NUTS_ID', right_on='NUTS_ID_3').drop(columns=['NUTS_ID']) ``` -------------------------------- ### Aggregated visualization result Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Result of the H3 hexagon aggregation plot, showing a matplotlib figure with 2 axes. ```text Result:
``` -------------------------------- ### Import libraries and set root path Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/loss-db-set-up.ipynb Imports geopandas, pandas, glob, and os, and defines the root directory for the cluster data. ```python import geopandas as gpd import pandas as pd import glob import os root = '/home/nmd/Cluster' ``` -------------------------------- ### Get first building ZIP URL and display it Source: https://github.com/ai4up/eubucco/blob/main/tutorials/downloading-spain-cadaster.ipynb Assigns the first entry ID text to a variable and displays it. The output is 'http://www.catastro.minhap.es/INSPIRE/Buildings/03/03002-AGOST/A.ES.SDGC.BU.03002.zip'. ```python url = list[0].text url ``` -------------------------------- ### Merge German parsing with overview Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/loss-db-set-up.ipynb Loads the German overview file, maps NUTS3 IDs to regions, and merges with the parsing data to compare counts. ```python deu_overview = pd.read_csv('/home/nmd/Cluster/stats/2-db-set-up/overview/v1/gov_germany_overview.csv') regions = [[deu_regions[key] for key in deu_regions.keys() if key in x] for x in deu_overview.NUTS3_ID] deu_overview['region'] = [x[0] if x!=[] else '' for x in regions] deu_overview = deu_overview.groupby('region')['n_bldgs'].sum().reset_index() pd.merge(deu_parsing,deu_overview,left_on='dataset_name',right_on='region') ``` -------------------------------- ### Merge NUTS 3 with NUTS 1/2 regions and map LAU to NUTS 3 Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Extracts NUTS 3 geometries, merges them with the NUTS 1/2 region identifiers, then spatially joins LAU centroids to NUTS 3 polygons. Fixes non-unique LAU IDs by prefixing country codes, removes duplicates and remote French territories, and saves the final LAU-NUTS mapping as CSV and GeoPackage. ```python # get nuts 3 rows including geometries nuts3 = nuts12[nuts12.LEVL_CODE==3].drop(columns='CNTR_CODE') nuts3.head() # merge nuts 3 with relevant nuts 1/2 region # using NUTS_ID_region column from nuts dataframe nuts3 = pd.merge(nuts3,pd.DataFrame([(string, long_string) for string in nuts.NUTS_ID_region.to_list() for long_string in nuts3.NUTS_ID.to_list() if string in long_string], columns=['NUTS_ID_region','NUTS_ID_3']), left_on='NUTS_ID', right_on='NUTS_ID_3').drop(columns=['NUTS_ID']) nuts3.head() # merge with the nuts dataframe to add country, region and country code information nuts3 = pd.merge(nuts,nuts3,on='NUTS_ID_region').drop(columns=['NUTS_NAME','LEVL_CODE']).rename(columns={'NAME_LATN':'nuts3'}) nuts3.head() # map laus to respective nuts 3 using spatial joins (yeah, couldnt find a way to do this on ID...) nuts12 = gpd.read_file('0-raw-data/lau/NUTS_RG_01M_2016_3035.shp') lau = gpd.read_file('0-raw-data/lau/LAU_RG_01M_2019_3035.shp') nuts3G = nuts12[nuts12.LEVL_CODE==3].drop(columns={'CNTR_CODE'}) lau['geometry'] = lau['geometry'].centroid join = gpd.sjoin_nearest(lau,nuts3G) print(len(join)==len(lau)) # fix the fact that LAU_IDs are not unique and there may be the same ID in multiple countries join = join[['LAU_ID','NUTS_ID','CNTR_CODE']] join['LAU_ID'] = join['CNTR_CODE'] + join['LAU_ID'] # reload LAU boundary geometry that was turned to centroid for matching g = gpd.read_file('0-raw-data/lau/LAU_RG_01M_2019_3035.shp')[['CNTR_CODE','LAU_ID','geometry']] g['LAU_ID'] = g['CNTR_CODE'] + g['LAU_ID'] # match LAU and respective NUTS3 nuts_lau = pd.merge(g,join,on='LAU_ID').drop(columns={'CNTR_CODE_x','CNTR_CODE_y'}) # merge with complete NUTS info nuts_lau2 = pd.merge(nuts_lau,nuts3.drop(columns=['geometry']), right_on='NUTS_ID_3', left_on='NUTS_ID').drop(columns=['NUTS_ID']) # remove mistakenly caught regions from Germany in Estonia nuts_lau2 = nuts_lau2.drop_duplicates(subset='LAU_ID') # remove remote french territories nuts_lau2 = nuts_lau2[~nuts_lau2['NUTS_ID_region'].str.contains('FRY', case=False, na=False)] # ensure both are the same (also removes some countries that we are not coverage e.g. Albania) nuts_lau = nuts_lau[nuts_lau.LAU_ID.isin(nuts_lau2.LAU_ID)] nuts_lau2.drop(columns=['geometry']).to_csv('0-raw-data/lau/lau_nuts_extra_fr_osm.csv',index=False) nuts_lau.to_file('0-raw-data/lau/lau_nuts_fr_osm.gpkg') len(nuts_lau) len(nuts_lau2) ``` -------------------------------- ### Load overview stats into DataFrame Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/loss-db-set-up.ipynb Reads each overview file, sums the n_bldgs column, and extracts the dataset name from the filename (the part after the first underscore). ```python df_overview = pd.DataFrame() for path in overview_paths: tmp = pd.read_csv(path)[['n_bldgs']] tmp = pd.DataFrame([{'dataset_name':os.path.split(path)[-1].split('_')[1], 'n_bldgs':tmp.n_bldgs.sum() }]) df_overview = pd.concat([df_overview,tmp]) ``` -------------------------------- ### Map country code to NUTS level and select NUTS 1/2 regions Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/lau-matching.ipynb Defines a mapping for France (country code 'FR', country name 'france', NUTS level 2) and filters the NUTS 1/2 dataset to the specified level, then renames columns for later merging. ```python # mapping country code in NUTS and EUBUCCO country name # and choose NUTS level corresponding to EUBUCCO input datasets for each country df = pd.DataFrame([('FR','france',2)], columns=['CNTR_CODE','country','nuts1/2']) nuts = pd.DataFrame() for _,row in df.iterrows(): tmp = pd.merge(pd.DataFrame([row.values], columns=row.index),nuts12,on='CNTR_CODE') if row['nuts1/2']==1: tmp = tmp[tmp.LEVL_CODE==1] elif row['nuts1/2']==2: tmp = tmp[tmp.LEVL_CODE==2] else: sys.exit('Error with NUTS level.') nuts = pd.concat([nuts,tmp])[['country','NUTS_ID','NAME_LATN','CNTR_CODE']] nuts = nuts.rename(columns={'NAME_LATN':'region','NUTS_ID': 'NUTS_ID_region'}) ``` -------------------------------- ### Calculate loss metrics Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/loss-db-set-up.ipynb Computes absolute loss and percentage loss (rounded to 2 decimals) between parsing and db set-up building counts. ```python df['loss_abs'] = df['n_bldgs_parsing'] - df['n_bldgs_db set up'] df['loss_per'] = round(df['loss_abs'] / df['n_bldgs_parsing'],2) ``` -------------------------------- ### Filter by city_id and plot subtype Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Filters the GeoDataFrame to a specific city using 'city_id' and plots the 'subtype' column. The plot returns a Figure object. ```python city = gdf[gdf["city_id"] == "CHCH0121"] city.plot(column="subtype", legend=True, figsize=(10, 8)).set_axis_off() ``` ```text Result:
``` -------------------------------- ### Load German parsing data Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/loss-db-set-up.ipynb Loads parsing statistics for German regions and filters to the relevant datasets. ```python parsing_paths = glob.glob(os.path.join(root,'stats/1-parsing','*gov_stat.csv')) df_parsing = pd.DataFrame() for path in parsing_paths: df_parsing = pd.concat([df_parsing,pd.read_csv(path)[['dataset_name','n_bldgs']]]) deu_regions = {'DE3': 'berlin-gov', 'DE4': 'brandenburg-gov', 'DE6': 'hamburg-gov', 'DE8': 'mecklenburg-vorpommern-gov', 'DE9': 'niedersachsen-gov', 'DEA': 'nordrhein-westfalen-gov', 'DED': 'sachsen-gov', 'DEE': 'sachsen-anhalt-gov', 'DEG': 'thuerigen-gov'} deu_parsing = df_parsing[df_parsing.dataset_name.isin(list(deu_regions.values()))].reset_index(drop=True) ``` -------------------------------- ### Sample output for region processing Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/3-attrib-cleaning/type-mapping/type-germany.ipynb Example output from the processing loop showing per-region statistics: counts of records with/without type, residential/non-residential counts, and top type names. The output is truncated for brevity. ```text Output: region is berlin-gov_attrib num of have type is 416620, num of non have type is 123506, ratio of have type is 0.7713385395259624 num of residential is 97666, num of non-residential is 28833, ratio of residential is 0.2344246555614229 Ferienhaus 75270 farmhouse 20283 shed 14211 Sägewerk 8438 converter 1715 residential and administrative buildings 1625 Kesselhaus 1174 greenhouse 757 Stall 535 Car wash, car wash, car wash 498 residential and commercial buildings 330 garbage bunker 296 Toilette 184 Energy supply building 183 factory 175 residential and office buildings 158 substation 138 barn 106 Building of the sewage treatment plant 80 Pump station 79 farm buildings 75 waterworks 57 power station 37 cold store 23 pump station (not for water supply) 19 water tank 19 barn and stable 17 Waste incineration building 9 Gaswerk 7 Barn for animal husbandry 1 Name: english_name, dtype: int64 ******************** region is brandenburg-gov_attrib num of have type is 2314099, num of non have type is 0, ratio of have type is 1.0 num of residential is 764840, num of non-residential is 1542367, ratio of residential is 0.3305130852223695 residential house 731580 Garage 320113 Agricultural and forestry company building 242958 Cannot be specified based on sources 236524 Recreational buildings 209976 ... Turbinenhaus 4 Parliament 4 Finanzamt 2 farmhouse 1 Sanatorium 1 Name: english_name, Length: 141, dtype: int64 ******************** region is freiburg-gov_attrib num of have type is 57969, num of non have type is 0, ratio of have type is 1.0 num of residential is 0, num of non-residential is 57969, ratio of residential is 0.0 ``` -------------------------------- ### Filter based on attributes and region - Output Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Output of a filtering operation showing a UserWarning that input is being reprojected to EPSG:4326 CRS because Lonboard can only render data in EPSG:4326 projection. ```text Output: /usr/local/Caskroom/miniconda/base/envs/playground/lib/python3.10/site-packages/lonboard/_geoarrow/ops/reproject.py:116: UserWarning: Input being reprojected to EPSG:4326 CRS. Lonboard is only able to render data in EPSG:4326 projection. warnings.warn( ``` -------------------------------- ### Drop attributes with large uncertainty Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Filters for reliable type (confidence > 0.8) and precise height (uncertainty interval < 2m), then samples 3 rows of height-related columns. ```python # Categorical: Correct type in >80% of cases reliable_type = gdf[gdf["type_confidence"].fillna(1.0) > 0.8] # Numerical: Precise height (uncertainty interval < 2m) precise_height = gdf[(gdf["height_confidence_upper"] - gdf["height_confidence_lower"]).fillna(0.0) < 2.0] precise_height[["id", "height", "height_source", "height_confidence_lower", "height_confidence_upper"]].sample(3) ``` ```text Result: id height height_source height_confidence_lower \ 188645 98baed995c394750-0 9.8 gov-switzerland None 6773 60a2a6f495fb4e12-0 6.3 estimated 5.8 230851 2c825f0aca48467c-0 5.5 gov-switzerland None height_confidence_upper 188645 None 6773 6.7 230851 None ``` -------------------------------- ### Merge Italian Parsing and Overview Data Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/loss-db-set-up.ipynb Loads the Italian overview CSV, maps NUTS3 IDs to regions, sums building counts per region, and merges with the parsing data to compare counts. ```python it_overview = pd.read_csv('/home/nmd/Cluster/stats/2-db-set-up/overview/v1/gov_italy_overview.csv') regions = [[italy_regions[key] for key in italy_regions.keys() if key in x] for x in it_overview.NUTS3_ID] it_overview['region'] = [x[0] if x!=[] else '' for x in regions] it_overview = it_overview.groupby('region')['n_bldgs'].sum().reset_index() pd.merge(it_parsing,it_overview,left_on='dataset_name',right_on='region') ``` -------------------------------- ### Static visualization with Matplotlib for a city Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Plots buildings for a given city (CHCH0247) colored by block_id using Matplotlib. The plot is 10x8 inches and has axes turned off. Output is a Figure object. ```python # Simple static visualization with Matplotlib city = gdf[gdf["city_id"] == "CHCH0247"] city.plot(column="block_id", legend=False, figsize=(10, 8)).set_axis_off() ``` ```text Result:
``` -------------------------------- ### Load OSM parsing stats into DataFrame Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/loss-db-set-up.ipynb Reads each OSM parsing stat file, extracts dataset_name and n_bldgs, and concatenates them. ```python df_parsing = pd.DataFrame() for path in parsing_paths: df_parsing = pd.concat([df_parsing,pd.read_csv(path)[['dataset_name','n_bldgs']]]) ``` -------------------------------- ### Stream EUBUCCO parquet directly into GeoDataFrame Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Reads the parquet file directly from the S3 bucket without downloading it locally, using geopandas with anonymous access and a custom endpoint URL. ```python import geopandas as gpd region = "CH04" s3_path = f"s3://eubucco/v0.2/buildings/parquet/nuts_id={region}/{region}.parquet" storage_opts = { "anon": True, "client_kwargs": {"endpoint_url": "https://s3.eubucco.com"} } gdf = gpd.read_parquet(s3_path, storage_options=storage_opts) ``` -------------------------------- ### Download all .zip files with wget Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/0-downloading/downloading-brandenburg.txt Recursively downloads all .zip files from the Brandenburg geobasis LOD2 GML directory. Requires a pre-created target directory with ~50 GB free space. Flags: -r recursive, -np no parent, -l 1 depth, -A zip accept extension. ```bash wget -r -np -l 1 -A zip https://data.geobasis-bb.de/geobasis/daten/3d_gebaeude/lod2_gml/ ``` -------------------------------- ### List of German OSM dataset names Source: https://github.com/ai4up/eubucco/blob/main/database/preprocessing/2-db-set-up/loss-db-set-up.ipynb Defines a list of German federal state OSM filenames used for further processing. ```python deu = ['baden-wuerttemberg-latest.osm', 'bayern-latest.osm', 'Berlin.osm', 'brandenburg-latest.osm', 'Bremen.osm', 'Hamburg.osm', 'hessen-latest.osm', 'mecklenburg-vorpommern-latest.osm', 'niedersachsen-latest.osm', 'nordrhein-westfalen-latest.osm', 'rheinland-pfalz-latest.osm', 'saarland-latest.osm', 'sachsen-anhalt-latest.osm', 'sachsen-latest.osm', 'schleswig-holstein-latest.osm', 'thueringen-latest.osm'] ``` -------------------------------- ### Compute country-level statistics Source: https://github.com/ai4up/eubucco/blob/main/tutorials/website/getting-started-website.ipynb Aggregates region statistics by country and calculates the share of buildings with attributes (type, subtype, height, floors, construction year) relative to total buildings. The result is rounded to 2 decimals. ```python country_stats = stats.drop(columns=["geometry", "region_id", "region_name"]).groupby("country").sum() country_stats[["n_gt_type", "n_gt_subtype", "n_gt_height", "n_gt_floors", "n_gt_construction_year"]].div(country_stats["n"], axis=0).rename(columns=lambda x: x.replace("n_gt_", "share_gt_")).round(2) ```