STEM / code /preprocessing /citygml_to_cityjson.py
eduzrh
feat: Lyon multi-epoch cross-time benchmark
532fb5c
Raw
History Blame Contribute Delete
8.11 kB
#!/usr/bin/env python3
"""
citygml_to_cityjson.py — Convert Lyon CityGML (LOD2) to CityJSON v1.1
Handles lod2MultiSurface and lod2Solid geometries.
Maps EPSG:3946 CRS. Creates stable building IDs.
"""
import json, os, sys, math, numpy as np
from lxml import etree
NSMAP = {
'gml': 'http://www.opengis.net/gml',
'bldg': 'http://www.opengis.net/citygml/building/2.0',
}
def _tag(elem):
return etree.QName(elem).localname
def _find_recursive(elem, local_name):
for child in elem.iter():
if _tag(child) == local_name:
return child
return None
def _parse_poslist(text):
parts = text.strip().split()
return [float(p) for p in parts]
def _parse_polygon_patches(geom_elem):
"""Parse lod2MultiSurface → list of surfaces (each a list of [x,y,z] vertices)."""
surfaces = []
for polygon_elem in geom_elem.iter():
if _tag(polygon_elem) == 'Polygon':
exterior = _find_recursive(polygon_elem, 'exterior')
if exterior is None:
continue
ring = _find_recursive(exterior, 'LinearRing')
if ring is None:
continue
poslist = _find_recursive(ring, 'posList')
if poslist is None:
continue
coords = _parse_poslist(poslist.text)
verts = [[coords[i], coords[i+1], coords[i+2]] for i in range(0, len(coords)-2, 3)]
if verts:
surfaces.append(verts)
return surfaces
def _parse_solid(geom_elem):
"""Parse lod2Solid → list of surfaces."""
surfaces = []
for shell_elem in geom_elem.iter():
if _tag(shell_elem) in ('exterior', 'Shell'):
for polygon_elem in shell_elem.iter():
if _tag(polygon_elem) == 'Polygon':
exterior = _find_recursive(polygon_elem, 'exterior')
if exterior is None:
continue
ring = _find_recursive(exterior, 'LinearRing')
if ring is None:
continue
poslist = _find_recursive(ring, 'posList')
if poslist is None:
continue
coords = _parse_poslist(poslist.text)
verts = [[coords[i], coords[i+1], coords[i+2]] for i in range(0, len(coords)-2, 3)]
if verts:
surfaces.append(verts)
return surfaces
def _deduplicate_vertices(buildings):
"""Build global vertex array, remap surfaces to indices."""
vert_to_idx = {}
vertices_list = []
for bid, bdata in buildings.items():
new_surfaces = []
for surface in bdata.get('surfaces', []):
new_surf = []
for v in surface:
key = (round(v[0], 6), round(v[1], 6), round(v[2], 6))
if key not in vert_to_idx:
vert_to_idx[key] = len(vertices_list)
vertices_list.append(v)
new_surf.append(vert_to_idx[key])
new_surfaces.append([new_surf])
bdata['boundaries'] = new_surfaces
del bdata['surfaces']
return vertices_list, buildings
def _get_bbox(buildings):
"""Compute global bounding box from building surfaces."""
all_verts = []
for b in buildings.values():
for surf_list in b.get('boundaries', []):
for surf in surf_list:
for vidx in surf:
pass # We'll compute from vertices directly later
return None
def convert_gml_to_cityjson(gml_path, year, arrondissement):
"""Convert one CityGML file to CityJSON dict."""
print(f" Parsing {os.path.basename(gml_path)}...")
buildings = {}
crs_uri = None
current_building = None
context = etree.iterparse(gml_path, events=('start', 'end'), huge_tree=True)
for event, elem in context:
tag = _tag(elem)
if event == 'start':
if tag == 'Building':
gml_id = elem.get('{http://www.opengis.net/gml}id', f'unknown_{len(buildings)}')
current_building = {'id': gml_id, 'surfaces': []}
if tag in ('boundedBy', 'Envelope') and crs_uri is None:
srs = elem.get('srsName', '')
if srs:
crs_uri = srs
if event == 'end':
if tag in ('lod2MultiSurface', 'lod2Solid') and current_building is not None:
surfaces = _parse_polygon_patches(elem) if tag == 'lod2MultiSurface' else _parse_solid(elem)
if surfaces:
current_building['surfaces'].extend(surfaces)
if tag == 'Building' and current_building is not None:
if current_building['surfaces']:
bid = f"{year}_{arrondissement}_{current_building['id']}"
buildings[bid] = current_building
current_building = None
if tag not in ('Building', 'lod2MultiSurface', 'lod2Solid'):
elem.clear()
if not buildings:
print(f" WARNING: No buildings extracted!")
return None
# Deduplicate vertices
vertices, buildings = _deduplicate_vertices(buildings)
# Compute global bounding box
all_v = np.array(vertices)
bbox = [float(all_v[:,0].min()), float(all_v[:,0].max()),
float(all_v[:,1].min()), float(all_v[:,1].max()),
float(all_v[:,2].min()), float(all_v[:,2].max())]
# Transform for integer compression
translate = [bbox[0], bbox[2], bbox[4]]
max_dim = max(bbox[1]-bbox[0], bbox[3]-bbox[2], bbox[5]-bbox[4])
scale_factor = max(max_dim / 1e6, 1e-6)
scale = [scale_factor, scale_factor, scale_factor]
# Build CityObjects
city_objects = {}
for bid, bdata in buildings.items():
city_objects[bid] = {
'type': 'Building',
'geometry': [{
'type': 'MultiSurface',
'lod': '2',
'boundaries': bdata['boundaries'],
}],
}
cityjson = {
'type': 'CityJSON',
'version': '1.1',
'metadata': {
'referenceSystem': crs_uri or 'EPSG:3946',
'geographicalExtent': bbox,
'datasetTitle': f'Lyon {arrondissement} {year}',
},
'transform': {'scale': scale, 'translate': translate},
'CityObjects': city_objects,
'vertices': vertices,
}
print(f" {len(city_objects)} buildings, {len(vertices)} vertices, CRS={crs_uri}")
return cityjson
def main():
base_dir = os.path.dirname(os.path.abspath(__file__))
lyon_data = os.path.join(base_dir, '..', 'data', 'lyon')
years = ['2009', '2012', '2015']
for year in years:
gml_dir = os.path.join(lyon_data, year)
cityjson_dir = os.path.join(lyon_data, year + '_cityjson')
os.makedirs(cityjson_dir, exist_ok=True)
gml_files = sorted([f for f in os.listdir(gml_dir) if f.endswith('.gml')])
if not gml_files:
print(f"No GML files found for {year}")
continue
print(f"\n{'='*60}")
print(f"YEAR {year}: {len(gml_files)} files")
for gml_file in gml_files:
arr = gml_file.replace(f'_BATI_{year}.gml', '').replace('LYON_', '')
gml_path = os.path.join(gml_dir, gml_file)
output_path = os.path.join(cityjson_dir, f'LYON_{arr}_{year}.json')
if os.path.exists(output_path):
print(f" Skipping {gml_file} (already converted)")
continue
cityjson = convert_gml_to_cityjson(gml_path, year, arr)
if cityjson:
with open(output_path, 'w') as f:
json.dump(cityjson, f)
size_mb = os.path.getsize(output_path) / 1024 / 1024
print(f" → Saved: {os.path.basename(output_path)} ({size_mb:.1f} MB)")
if __name__ == '__main__':
main()