Created
July 20, 2024 10:55
-
-
Save smellman/c00d1ace335d8790986d57f435cf1007 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import xml.etree.ElementTree as ET | |
def convert_negative_ids(elements): | |
id_map = {} | |
new_elements = [] | |
for elem in elements: | |
orig_id = int(elem.attrib['id']) | |
new_id = abs(orig_id) | |
id_map[new_id] = orig_id | |
elem.set('id', str(new_id)) | |
new_elements.append(elem) | |
return new_elements, id_map | |
def restore_negative_ids(elements, id_map): | |
for elem in elements: | |
new_id = int(elem.attrib['id']) | |
orig_id = id_map[new_id] | |
elem.set('id', str(orig_id)) | |
def sort_osm_elements(input_file, output_file): | |
tree = ET.parse(input_file) | |
root = tree.getroot() | |
nodes = [] | |
ways = [] | |
relations = [] | |
for elem in root: | |
if elem.tag == 'node': | |
nodes.append(elem) | |
elif elem.tag == 'way': | |
ways.append(elem) | |
elif elem.tag == 'relation': | |
relations.append(elem) | |
# 負のIDを正のIDに変換 | |
nodes, node_id_map = convert_negative_ids(nodes) | |
ways, way_id_map = convert_negative_ids(ways) | |
relations, relation_id_map = convert_negative_ids(relations) | |
# IDでソート | |
nodes.sort(key=lambda x: int(x.attrib['id'])) | |
ways.sort(key=lambda x: int(x.attrib['id'])) | |
relations.sort(key=lambda x: int(x.attrib['id'])) | |
# 新しいOSMファイルに書き出し | |
new_root = ET.Element('osm', version='0.6', generator='sort_osm_script') | |
for node in nodes: | |
new_root.append(node) | |
for way in ways: | |
new_root.append(way) | |
for relation in relations: | |
new_root.append(relation) | |
# ソート後に元のIDに戻す | |
restore_negative_ids(nodes, node_id_map) | |
restore_negative_ids(ways, way_id_map) | |
restore_negative_ids(relations, relation_id_map) | |
# XML宣言を含めて出力 | |
new_tree = ET.ElementTree(new_root) | |
new_tree.write(output_file, encoding='utf-8', xml_declaration=True) | |
input_file = 'input.osm' | |
output_file = 'output.osm' | |
sort_osm_elements(input_file, output_file) | |
print(f"Sorted OSM file saved as {output_file}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cp 53401214_bldg_6697_op.osm input.osm python3 plateau_convert_to_abs_id.py osmium export output.osm -o 53401214_bldg_6697_op.osm.geojsonseq tippecanoe -o 53401214_bldg_6697_op.osm.pmtiles 53401214_bldg_6697_op.osm.geojsonseq