├── serbia ├── .gitignore ├── requirements.txt ├── README.md ├── daily-measurement.sh └── serbia2input.py ├── .gitignore ├── requirements.txt ├── shp2osm.sh ├── processing_state.py ├── inputcsv2shp.py ├── refresh-osm-data.sh ├── config.yml ├── extras ├── add_level9_id_to_osm.py ├── add_level8_id_to_osm.py └── add_subarea_settlements.py ├── atomic_write.py ├── send_notification.py ├── common.py ├── measure_quality.py ├── conflate-report.py ├── templates └── index_template.html ├── README.md ├── translation.py ├── conflate.py └── LICENSE /serbia/.gitignore: -------------------------------------------------------------------------------- 1 | rgz-password -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | .idea/ 3 | input/ 4 | output/ 5 | osm-password 6 | rpj.osm 7 | progress.csv 8 | izlaz.csv 9 | conflate-progress.pickle 10 | process.log 11 | measurement.log 12 | overpass_db/ 13 | ogr2osm/ 14 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Fiona==1.8.20 2 | Shapely==1.8.0 3 | overpy==0.4 4 | pyproj==2.6.1.post1 5 | osmapi==1.3.0 6 | matplotlib==3.5.1 7 | Jinja2==3.0.1 8 | requests~=2.25.1 9 | beautifulsoup4~=4.10.0 10 | lxml==4.8.0 11 | PyYAML==6.0 12 | -------------------------------------------------------------------------------- /serbia/requirements.txt: -------------------------------------------------------------------------------- 1 | Fiona==1.8.20 2 | Shapely==1.8.0 3 | overpy==0.4 4 | pyproj==2.6.1.post1 5 | osmapi==1.3.0 6 | matplotlib==3.5.1 7 | Jinja2==3.0.1 8 | requests~=2.25.1 9 | beautifulsoup4~=4.10.0 10 | lxml==4.8.0 11 | ogr2osm==1.1.1 -------------------------------------------------------------------------------- /shp2osm.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -euo pipefail 4 | 5 | 6 | if [[ $# -ne 2 ]]; then 7 | echo 'Too many/few arguments, expecting two, call it with: ./shp2osm.sh ' >&2 8 | exit 1 9 | fi 10 | 11 | inputShp=$1 12 | outputOsm=$2 13 | 14 | echo "Converting input shp '$1' to output OSM '$2'" 15 | 16 | if [[ ! -d "ogr2osm/" ]] 17 | then 18 | # TODO: switch to new ogr2osm version 19 | echo "ogr2osm does not exists, will git clone it now" 20 | git clone https://github.com/pnorman/ogr2osm.git 21 | fi 22 | 23 | python3 ogr2osm/ogr2osm.py -t translation.py -f --split-ways=1 -o $outputOsm $inputShp 24 | -------------------------------------------------------------------------------- /processing_state.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class ProcessingState(Enum): 5 | """ 6 | Potential results of conflation 7 | """ 8 | NO = 1 9 | CHECKED_POSSIBLE = 2 10 | CONFLATED = 3 11 | ERROR_END_POINTS_FAR_APART = 4 12 | ERROR_GEOMETRY_WRONG = 5 13 | ERROR_SHARED_WAY_NOT_FOUND = 6 14 | ERROR_WAY_NOT_FOUND = 7 15 | ERROR_MULTIPLE_SHARED_WAYS = 8 16 | ERROR_MULTIPLE_SINGLE_WAY = 9 17 | ERROR_NODES_WITH_TAGS = 10 18 | ERROR_NATIONAL_BORDER = 11 19 | ERROR_UNEXPECTED_TAG = 12 20 | ERROR_NODE_IN_OTHER_WAYS = 13 21 | ERROR_NODE_IN_NATIONAL_BORDER = 14 22 | ERROR_NODE_IN_OTHER_RELATION = 15 23 | ERROR_NODE_IN_NATIONAL_RELATION = 16 24 | ERROR_INVALID_SHAPE = 17 25 | ERROR_CLOSED_SHAPE = 18 26 | ERROR_OVERLAPPING_WAYS = 19 27 | ERROR_TOO_MANY_NODES = 20 -------------------------------------------------------------------------------- /serbia/README.md: -------------------------------------------------------------------------------- 1 | This folder contains set of scripts to aid daily checks of OSM admin boundaries in Serbia against official cadastre data. 2 | All scripts here are very much specific to Serbia and not of interest for other readers. 3 | But do check how it all works end to end. 4 | 5 | All of this is done by using local overpass server and doing couple of steps: 6 | * Initialize data from yesterday (PBF data) to serve as a baseline and calculate statistics 7 | * Update cadastre data from today and calculate statistics again, finding differences that are due to cadastre changes 8 | * Update today's OSM data and calculate statistics again, finding differences that are due to OSM changes 9 | 10 | If there are any changes (either cadastre or OSM) that are worse than yesterday, shoot Telegram message. 11 | 12 | Start with `daily-measurement.sh` script to dive in. -------------------------------------------------------------------------------- /inputcsv2shp.py: -------------------------------------------------------------------------------- 1 | import csv 2 | import sys 3 | 4 | import fiona 5 | from fiona.crs import from_epsg 6 | from shapely.geometry import mapping 7 | from shapely.wkt import loads 8 | 9 | from common import load_level9_features 10 | 11 | csv.field_size_limit(sys.maxsize) 12 | 13 | schema = { 14 | 'geometry': ['Polygon', 'MultiPolygon'], 15 | 'properties': { 16 | 'level9id': 'str', 17 | 'level9name': 'str', 18 | 'level8id': 'str', 19 | 'level8name': 'str', 20 | 'level7id': 'str', 21 | 'level7name': 'str', 22 | 'level6id': 'str', 23 | 'level6name': 'str' 24 | } 25 | } 26 | 27 | 28 | def main(input_csv_file: str, output_shp_file: str): 29 | print(f'Loading level9 data from {input_csv_file}') 30 | level9_features = load_level9_features(input_csv_file) 31 | 32 | print(f'Writing level9 data to {output_shp_file}') 33 | with fiona.collection(output_shp_file, "w", "ESRI Shapefile", schema, crs=from_epsg(4326), encoding='utf-8') as output: 34 | for level9_feature in level9_features: 35 | geometry = loads(level9_feature['wkt']) 36 | output.write({ 37 | 'properties': { 38 | 'level9id': level9_feature['level9_id'], 39 | 'level9name': level9_feature['level9_name'], 40 | 'level8id': level9_feature['level8_id'], 41 | 'level8name': level9_feature['level8_name'], 42 | 'level7id': level9_feature['level7_id'], 43 | 'level7name': level9_feature['level7_name'], 44 | 'level6id': level9_feature['level6_id'], 45 | 'level6name': level9_feature['level6_name'] 46 | }, 47 | 'geometry': mapping(geometry)}) 48 | print('Done') 49 | 50 | 51 | if __name__ == '__main__': 52 | if len(sys.argv) != 3: 53 | print("Usage: ./inputcsv2shp.py ") 54 | exit() 55 | input_csv_file = sys.argv[1] 56 | output_shp_file = sys.argv[2] 57 | main(input_csv_file, output_shp_file) 58 | -------------------------------------------------------------------------------- /refresh-osm-data.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -euo pipefail 4 | 5 | # This script downloads and restarts/refresh overpass server with map of some country. It takes around 10 minutes for Serbia, YMMV. 6 | 7 | # Details how to install here: https://wiki.openstreetmap.org/wiki/Overpass_API/Installation 8 | # or here: http://overpass-api.de/no_frills.html 9 | # Copy this in overpass server directory 10 | # Create ./build directory inside overpass server directory where you will build it 11 | # Change ./build/bin/rules_loop.sh such that it doesn't do infinite loop, but does areas only once 12 | 13 | if [[ $# -ne 4 ]]; then 14 | echo 'Too many/few arguments, expecting two, call it with: ./refresh-osm-data.sh ' >&2 15 | exit 1 16 | fi 17 | 18 | continent=$1 19 | region=$2 20 | rel_overpass_db=$4 21 | 22 | if [ $3 = "yesterday" ]; then 23 | yesterday=`date -d 'now - 2day' +%y%m%d` # Two days as geofabrik releases data in early morning UTC time 24 | url="http://download.geofabrik.de/$continent/$region-$yesterday.osm.pbf" 25 | else 26 | url="http://download.geofabrik.de/$continent/$region-latest.osm.pbf" 27 | fi 28 | 29 | echo "Using URL $url" 30 | 31 | if [ ! -z "`docker ps | grep overpass_$region`" ]; then 32 | docker stop overpass_$region 33 | fi 34 | if [ ! -z "`docker ps -a | grep overpass_$region`" ]; then 35 | docker rm overpass_$region 36 | fi 37 | 38 | absolute_overpass_dir=`realpath $rel_overpass_db` 39 | echo "Absolute path to overpass dir: $absolute_overpass_dir" 40 | rm -rf $absolute_overpass_dir/* 41 | 42 | docker run \ 43 | -e OVERPASS_META=yes \ 44 | -e OVERPASS_MODE=init \ 45 | -e OVERPASS_PLANET_URL=$url \ 46 | -e OVERPASS_RULES_LOAD=10 \ 47 | -e OVERPASS_PLANET_PREPROCESS='mv /db/planet.osm.bz2 /db/planet.osm.pbf && osmium cat -o /db/planet.osm.bz2 /db/planet.osm.pbf && rm /db/planet.osm.pbf' \ 48 | -v $absolute_overpass_dir/:/db \ 49 | -p 12345:80 \ 50 | -i \ 51 | --name overpass_$region wiktorn/overpass-api 52 | 53 | docker start overpass_$region 54 | 55 | echo "Waiting for container to boot up" 56 | until [ "`docker inspect -f {{.State.Health.Status}} overpass_$region`" == "healthy" ]; do 57 | date 58 | echo "Still waiting for container to boot up" 59 | sleep 5 60 | done; 61 | 62 | sleep 10 63 | -------------------------------------------------------------------------------- /config.yml: -------------------------------------------------------------------------------- 1 | # Official name of country. Needed for various Overpass OSM queries 2 | country: Србија 3 | 4 | # Used as a template for "source" tag of changesets 5 | changeset_source: "open Serbian cadastre data Jan 2022" 6 | 7 | # Used as a comment for changesets when doing semi-automatic conflation 8 | changeset_comment: "Serbian bot - conflating boundaries (https://lists.openstreetmap.org/pipermail/imports/2020-January/006149.html)." 9 | 10 | # Name of the OSM tag that keeps ID of your level 9 entities (settlements...). It can be as simple as "ref" 11 | level9_ref_key: "ref:RS:naselje" 12 | 13 | # Name of the OSM tag that keeps ID of your level 8 entities (municipalities...). It can be as simple as "ref" 14 | level8_ref_key: "ref:RS:opstina" 15 | 16 | # Overpass endpoint. You need to have docker to set up your own Overpass instance (see "refresh-osm-data.sh" for details) 17 | # Commented out are other potential options, but beware of throttling and misuse 18 | overpass_url: "http://localhost:12345/api/interpreter" 19 | # overpass_url: "https://lz4.overpass-api.de/api/interpreter" 20 | # overpass_url: "http://overpass-api.de/api/interpreter" 21 | 22 | # If True, scripts will just assess conflation potential and will not submit anything to OSM. 23 | # If False, there will be actual process of OSM submission. In that case, please set "auto_proceed" to false, so you 24 | # can control process after each way. 25 | dry_run: True 26 | 27 | # Should human control stepping up after each processed way. Set to true when actually submitting to OSM. 28 | auto_proceed: True 29 | 30 | # If way is eligible for conflation, and some other nodes/ways relations are glued to it, should we unglue them. 31 | # If you unglue them, you will get two ways with same geometries (with different tags, of course). If you set this to False, 32 | # ways will be reported as not eligible for conflation. 33 | unglue_ways_as_needed: True 34 | 35 | # How far apart any endpoints of the way should be from OSM way to consider them eligable for conflation. 36 | # If any endpoint is in greater distance than this, script will not conflate this road. If you set this too low, 37 | # lot of ways that could be conflated will be reported as not possible. If you set this too high, you might get false 38 | # positives and wrong ways could be conflated by error. 39 | max_distance_end_points_to_consider_in_meters: 500 40 | -------------------------------------------------------------------------------- /serbia/daily-measurement.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Main script that can be run daily (in cron) to find differences and report result. 4 | # Set TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID if you want to get updates over Telegram. 5 | # You can use it for base for your region. 6 | 7 | set -euo pipefail 8 | 9 | date 10 | 11 | currentdate=`date +%Y%m%d` 12 | yesterday=`date -d 'now - 1day' +%Y%m%d` 13 | 14 | echo "Current date is $currentdate, yesterday is $yesterday" 15 | 16 | # Check if there is overpass set up at all 17 | response=$(curl --write-out "%{http_code}\n" --silent --output /dev/null "http://localhost:12345/api/interpreter?data=%3Cprint%20mode=%22body%22/%3E" || true) 18 | overpass_works=0 19 | if [[ $response == "200" ]]; then 20 | echo "Overpass works" 21 | overpass_works=1 22 | else 23 | echo "Overpass is not working" 24 | fi 25 | 26 | function refresh_cadastre_data { 27 | python3 serbia2input.py input/all.csv 28 | python3 ../inputcsv2shp.py input/all.csv output/shp/all.shp 29 | ../shp2osm.sh output/shp/all.shp output/osm/all.osm 30 | } 31 | 32 | if [ ! -f input/all.csv ]; then 33 | echo "No input file, recreating from scratch (losing diff from Serbia cadastre from yesterday)" 34 | refresh_cadastre_data 35 | fi 36 | 37 | shopt -s nullglob 38 | shp_files=( ./output/shp/*.shp ) 39 | found_files=( ${#shp_files[@]} ) 40 | echo "Found $found_files files" 41 | 42 | if [[ $found_files -eq "0" ]]; then 43 | echo "No shp files, recreating them from scratch (losing diff from Serbia cadastre from yesterday)" 44 | refresh_cadastre_data 45 | fi 46 | 47 | 48 | echo "Setting up yesterday data" 49 | ../refresh-osm-data.sh europe serbia yesterday ../overpass_db 50 | 51 | # Do baseline measurement 52 | python3 ../measure_quality.py input/all.csv output/level9-baseline-$yesterday.csv 53 | sort -o output/level9-baseline-$yesterday.csv output/level9-baseline-$yesterday.csv 54 | 55 | # Refresh cadastre and do measurements now 56 | echo "Refreshing cadastre data" 57 | refresh_cadastre_data 58 | sleep 10 59 | 60 | echo "Measuring settlements after cadastre is refreshed" 61 | python3 ../measure_quality.py input/all.csv output/level9-cadastre-$currentdate.csv 62 | sort -o output/level9-cadastre-$currentdate.csv output/level9-cadastre-$currentdate.csv 63 | diff -u output/level9-baseline-$yesterday.csv output/level9-cadastre-$currentdate.csv > output/level9-cadastre-$currentdate.diff || true 64 | python3 send_notification.py cadastre level9 output/level9-baseline-$yesterday.csv output/level9-cadastre-$currentdate.csv 65 | 66 | # Refresh OSM and do measurements now 67 | echo "Refreshing OSM data" 68 | ./refresh-osm-data.sh europe serbia today 69 | sleep 10 70 | 71 | echo "Measuring settlements after OSM is refreshed" 72 | python3 ../measure_quality.py input/all.csv output/level9-osm-$currentdate.csv 73 | sort -o output/level9-osm-$currentdate.csv output/level9-osm-$currentdate.csv 74 | diff -u output/level9-baseline-$yesterday.csv output/level9-osm-$currentdate.csv > output/level9-osm-$currentdate.diff || true 75 | python3 send_notification.py osm level9 output/level9-baseline-$yesterday.csv output/level9-osm-$currentdate.csv 76 | cp output/level9-osm-$currentdate.csv output/level9-baseline-$currentdate.csv 77 | 78 | echo "Measurement done for $currentdate" 79 | sleep 10 80 | -------------------------------------------------------------------------------- /extras/add_level9_id_to_osm.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script semi-automatically adds level9 ids to OSM. 3 | """ 4 | 5 | import os 6 | import sys 7 | import time 8 | import yaml 9 | 10 | import osmapi 11 | import overpy 12 | 13 | current = os.path.dirname(os.path.realpath(__file__)) 14 | parent = os.path.dirname(current) 15 | sys.path.append(parent) 16 | 17 | from common import get_polygon_by_cadastre_id, load_level9_features 18 | 19 | 20 | def main(config, overpass_api, input_csv_file): 21 | level9_features = load_level9_features(input_csv_file) 22 | 23 | level9_map = {} # maps (level8 name, level9 name) -> level9 id 24 | for level9_feature in level9_features: 25 | level8_name = level9_feature['level8_name'] 26 | level9_name = level9_feature['level9_name'] 27 | level9_id = level9_feature['level9_id'] 28 | if (level8_name, level9_name) not in level9_map: 29 | level9_map[(level8_name, level9_name)] = level9_id 30 | 31 | api = osmapi.OsmApi(passwordfile='osm-password', 32 | changesetauto=True, changesetautosize=20, changesetautotags= 33 | {u"comment": f"Bot - adding missing {config['level9_ref_key']}", 34 | u"tag": u"mechanical=yes", u"source": config['changeset_source']}) 35 | 36 | for i, level8_name_level9_name in enumerate(level9_map.keys()): 37 | level8_name = level8_name_level9_name[0] 38 | level9_name = level8_name_level9_name[1] 39 | level9_id = level9_map[level8_name_level9_name] 40 | overpass_level9_polygon, osm_level9_name, osm_relation_id, national_border = \ 41 | get_polygon_by_cadastre_id(overpass_api, 9, level9_id, country=config['country'], id_key=config['level9_ref_key']) 42 | 43 | if overpass_level9_polygon is None: 44 | print(f'Skipping {level8_name}/{level9_name}') 45 | continue 46 | time.sleep(3) 47 | relation = api.RelationGet(osm_relation_id) 48 | if relation['tag']['boundary'] != 'administrative' or relation['tag']['type'] != 'boundary': 49 | print(f'Something fishy with relation {level8_name}/{level9_name}, skipping it:\n {relation["tag"]}') 50 | continue 51 | if config['level9_ref_key'] in relation['tag']: 52 | print(f'Already done {level8_name}/{level9_name}, skipping it') 53 | continue 54 | 55 | for k, v in relation['tag'].items(): 56 | if k == 'metadata': 57 | continue 58 | if k.startswith('tag_') or k.startswith('val_') or k == 'boundary' or k == 'type': 59 | continue 60 | print(f'{k}: {v}') 61 | print(f'https://www.openstreetmap.org/relation/{relation["id"]}') 62 | accepted = False 63 | while True: 64 | response = input(f'({i}/{len(level9_map)}) Are you sure you want to add {config["level9_ref_key"]} {level9_id} to {level8_name}/{level9_name} (Y/n/c)?') 65 | if response == '' or response.lower() == 'y': 66 | accepted = True 67 | if response.lower() == u'c': 68 | new_answer = input('Again: ') 69 | if new_answer == '': 70 | continue 71 | else: 72 | accepted = True 73 | break 74 | if not accepted: 75 | continue 76 | relation['tag'][config["level9_ref_key"]] = level9_id 77 | api.RelationUpdate(relation) 78 | api.flush() 79 | 80 | 81 | if __name__ == '__main__': 82 | with open('config.yml', 'r') as config_yml_file: 83 | config = yaml.safe_load(config_yml_file) 84 | 85 | overpass_api = overpy.Overpass(url=config['overpass_url']) 86 | 87 | if len(sys.argv) != 2: 88 | print("Usage: ./extras/add_level9_id_to_osm.py ") 89 | exit() 90 | input_csv_file = sys.argv[1] 91 | main(config, overpass_api, input_csv_file) -------------------------------------------------------------------------------- /extras/add_level8_id_to_osm.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script semi-automatically adds level8 ids to OSM. 3 | """ 4 | 5 | import os 6 | import sys 7 | import time 8 | 9 | import osmapi 10 | import overpy 11 | import yaml 12 | 13 | current = os.path.dirname(os.path.realpath(__file__)) 14 | parent = os.path.dirname(current) 15 | sys.path.append(parent) 16 | 17 | from common import get_polygon_by_cadastre_id, load_level9_features 18 | 19 | 20 | def main(config, overpass_api, input_csv_file): 21 | level9_features = load_level9_features(input_csv_file) 22 | 23 | level8_map = {} # maps (level6 name, level8 name) -> level8 id 24 | for level9_feature in level9_features: 25 | level6_name = level9_feature['level6_name'] 26 | level8_name = level9_feature['level8_name'] 27 | level8_id = level9_feature['level8_id'] 28 | if (level6_name, level8_name) not in level8_map: 29 | level8_map[(level6_name, level8_name)] = level8_id 30 | 31 | api = osmapi.OsmApi(passwordfile='osm-password', 32 | changesetauto=True, changesetautosize=20, changesetautotags= 33 | {u"comment": u"Serbian lint bot - adding missing {}".format(config['level8_ref_key']), 34 | u"tag": u"mechanical=yes", u"source": config['changeset_source']}) 35 | for i, level6_name_level8_name in enumerate(level8_map.keys()): 36 | level6_name = level6_name_level8_name[0] 37 | level8_name = level6_name_level8_name[1] 38 | level8_id = level8_map[level6_name_level8_name] 39 | overpass_level8_polygon, osm_level8_name, osm_relation_id, national_border = \ 40 | get_polygon_by_cadastre_id(overpass_api, 8, level8_id, country=config['country'], id_key=config['level8_ref_key']) 41 | 42 | if overpass_level8_polygon is None: 43 | print(f'Skipping {level6_name}/{level8_name}') 44 | continue 45 | time.sleep(1) 46 | relation = api.RelationGet(osm_relation_id) 47 | if relation['tag']['boundary'] != 'administrative' or relation['tag']['type'] != 'boundary': 48 | print(f'Something fishy with relation {level6_name}/{level8_name}, skipping it:\n {relation["tag"]}') 49 | continue 50 | if 'ref:RS:opstina' in relation['tag']: 51 | print(f'Already done {level6_name}/{level8_name}, skipping it') 52 | continue 53 | 54 | for k, v in relation['tag'].items(): 55 | if k == 'metadata': 56 | continue 57 | if k.startswith('tag_') or k.startswith('val_') or k == 'boundary' or k == 'type': 58 | continue 59 | print(f'{k}: {v}') 60 | print(f'https://www.openstreetmap.org/relation/{relation["id"]}') 61 | accepted = False 62 | while True: 63 | response = input(f'({i}/{len(level8_map)}) Are you sure you want to add {config["level8_ref_key"]} {level8_id} to {level6_name}/{level8_name} (Y/n/c)?') 64 | if response == '' or response.lower() == 'y': 65 | accepted = True 66 | if response.lower() == u'c': 67 | new_answer = input('Again: ') 68 | if new_answer == '': 69 | continue 70 | else: 71 | accepted = True 72 | break 73 | if not accepted: 74 | continue 75 | relation['tag'][config["level8_ref_key"]] = level8_id 76 | api.RelationUpdate(relation) 77 | api.flush() 78 | 79 | 80 | if __name__ == '__main__': 81 | with open('config.yml', 'r') as config_yml_file: 82 | config = yaml.safe_load(config_yml_file) 83 | 84 | overpass_api = overpy.Overpass(url=config['overpass_url']) 85 | 86 | if len(sys.argv) != 2: 87 | print("Usage: ./extras/add_level8_id_to_osm.py ") 88 | exit() 89 | input_csv_file = sys.argv[1] 90 | main(config, overpass_api, input_csv_file) 91 | -------------------------------------------------------------------------------- /atomic_write.py: -------------------------------------------------------------------------------- 1 | """ 2 | Kindly borrowed from https://code.activestate.com/recipes/579097-safely-and-atomically-write-to-a-file/ 3 | """ 4 | 5 | import contextlib 6 | import os 7 | import stat 8 | import sys 9 | import tempfile 10 | 11 | 12 | @contextlib.contextmanager 13 | def atomic_write(filename, text=True, keep=True, 14 | owner=None, group=None, perms=None, 15 | suffix='.bak', prefix='tmp'): 16 | """Context manager for overwriting a file atomically. 17 | 18 | Usage: 19 | 20 | >>> with atomic_write("myfile.txt") as f: # doctest: +SKIP 21 | ... f.write("data") 22 | 23 | The context manager opens a temporary file for writing in the same 24 | directory as `filename`. On cleanly exiting the with-block, the temp 25 | file is renamed to the given filename. If the original file already 26 | exists, it will be overwritten and any existing contents replaced. 27 | 28 | (On POSIX systems, the rename is atomic. Other operating systems may 29 | not support atomic renames, in which case the function name is 30 | misleading.) 31 | 32 | If an uncaught exception occurs inside the with-block, the original 33 | file is left untouched. By default the temporary file is also 34 | preserved, for diagnosis or data recovery. To delete the temp file, 35 | pass `keep=False`. Any errors in deleting the temp file are ignored. 36 | 37 | By default, the temp file is opened in text mode. To use binary mode, 38 | pass `text=False` as an argument. On some operating systems, this make 39 | no difference. 40 | 41 | The temporary file is readable and writable only by the creating user. 42 | By default, the original ownership and access permissions of `filename` 43 | are restored after a successful rename. If `owner`, `group` or `perms` 44 | are specified and are not None, the file owner, group or permissions 45 | are set to the given numeric value(s). If they are not specified, or 46 | are None, the appropriate value is taken from the original file (which 47 | must exist). 48 | 49 | By default, the temp file will have a name starting with "tmp" and 50 | ending with ".bak". You can vary that by passing strings as the 51 | `suffix` and `prefix` arguments. 52 | """ 53 | t = (uid, gid, mod) = (owner, group, perms) 54 | if any(x is None for x in t): 55 | info = os.stat(filename) 56 | if uid is None: 57 | uid = info.st_uid 58 | if gid is None: 59 | gid = info.st_gid 60 | if mod is None: 61 | mod = stat.S_IMODE(info.st_mode) 62 | path = os.path.dirname(filename) 63 | fd, tmp = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=path, text=text) 64 | try: 65 | replace = os.replace # Python 3.3 and better. 66 | except AttributeError: 67 | if sys.platform == 'win32': 68 | # FIXME This is definitely not atomic! 69 | # But it's how (for example) Mercurial does it, as of 2016-03-23 70 | # https://selenic.com/repo/hg/file/tip/mercurial/windows.py 71 | def replace(source, dest): 72 | assert sys.platform == 'win32' 73 | try: 74 | os.rename(source, dest) 75 | except OSError as err: 76 | if err.winerr != 183: 77 | raise 78 | os.remove(dest) 79 | os.rename(source, dest) 80 | else: 81 | # Atomic on POSIX. Not sure about Cygwin, OS/2 or others. 82 | replace = os.rename 83 | try: 84 | with os.fdopen(fd, 'w' if text else 'wb') as f: 85 | yield f 86 | # Perform an atomic rename (if possible). This will be atomic on 87 | # POSIX systems, and Windows for Python 3.3 or higher. 88 | replace(tmp, filename) 89 | tmp = None 90 | os.chown(filename, uid, gid) 91 | os.chmod(filename, mod) 92 | finally: 93 | if (tmp is not None) and (not keep): 94 | # Silently delete the temporary file. Ignore any errors. 95 | try: 96 | os.unlink(tmp) 97 | except: 98 | pass -------------------------------------------------------------------------------- /send_notification.py: -------------------------------------------------------------------------------- 1 | import csv 2 | import datetime 3 | import os 4 | import sys 5 | import time 6 | 7 | import requests 8 | 9 | 10 | def telegram_sendtext(bot_message: str): 11 | bot_token = os.environ['TELEGRAM_BOT_TOKEN'] 12 | bot_chat_id = os.environ['TELEGRAM_CHAT_ID'] 13 | send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chat_id + '&parse_mode=Markdown&text=' + bot_message 14 | response = requests.get(send_text) 15 | time.sleep(3) 16 | return response.json() 17 | 18 | 19 | def process(diff_type: str, entity_type: str, baseline_csv: str, new_csv: str) -> int: 20 | # Load saved state 21 | baseline_entities = {} 22 | with open(baseline_csv) as csvfile: 23 | reader = csv.DictReader(csvfile) 24 | for row in reader: 25 | baseline_entities[row['relation_id']] = { 26 | 'district': row['level6'], 27 | 'name': row['level8'] if entity_type == 'level8' else row['level9'], 28 | 'relation_id': row['relation_id'], 'area_not_shared': float(row['area_not_shared']) 29 | } 30 | new_entities = {} 31 | with open(new_csv) as csvfile: 32 | reader = csv.DictReader(csvfile) 33 | for row in reader: 34 | new_entities[row['relation_id']] = { 35 | 'level6': row['level6'], 36 | 'name': row['level8'] if entity_type == 'level8' else row['level9'], 37 | 'area_not_shared': float(row['area_not_shared']) 38 | } 39 | 40 | messages_sent = 0 41 | for new_relation_id, new_entity in new_entities.items(): 42 | if messages_sent > 10: 43 | telegram_sendtext('{0} refreshed and compared with {1}, but there are more than 10 regressions, stopping with sending'.format( 44 | diff_type, entity_type 45 | )) 46 | break 47 | if new_relation_id not in baseline_entities: 48 | telegram_sendtext('{0} refreshed. Relation {1} ({2} {3}) exist now and it didn\'t existed before.'.format( 49 | diff_type, new_relation_id, entity_type, new_entity['name'] 50 | )) 51 | messages_sent += 1 52 | continue 53 | baseline_area_not_shared = baseline_entities[new_relation_id]['area_not_shared'] 54 | new_area_not_shared = new_entity['area_not_shared'] 55 | if new_area_not_shared > 0 and (new_area_not_shared - baseline_area_not_shared) > 0: # It was: new_area_not_shared > 0.01 56 | telegram_sendtext('{0} refreshed and {1} {2} (district {3}, relation {4}) was different {5}%, but now it is {6}%'.format( 57 | diff_type, entity_type, new_entity['name'], new_entity['level6'], new_relation_id, 58 | 100 * baseline_area_not_shared, 100 * new_area_not_shared) 59 | ) 60 | messages_sent += 1 61 | 62 | for baseline_relation_id, baseline_entity in baseline_entities.items(): 63 | if messages_sent > 10: 64 | telegram_sendtext('{0} refreshed and compared with {1}, but there are more than 10 regressions, stopping with sending'.format( 65 | diff_type, entity_type 66 | )) 67 | break 68 | if baseline_relation_id not in new_entities: 69 | telegram_sendtext('{0} refreshed. Relation {1} ({2} {3}) existed before and it doesn\'t exist now.'.format( 70 | diff_type, baseline_relation_id, entity_type, new_entity['name'] 71 | )) 72 | messages_sent += 1 73 | 74 | return messages_sent 75 | 76 | 77 | def main(): 78 | if len(sys.argv) != 5: 79 | print("Not enough arguments, quitting") 80 | exit() 81 | diff_type = sys.argv[1].upper() 82 | if diff_type not in ('CADASTRE', 'OSM'): 83 | print('First argument (diff type) need to be Cadastre or OSM') 84 | exit() 85 | entity_type = sys.argv[2] 86 | if entity_type not in ('level8', 'level9'): 87 | print('Second argument (entity type) need to be level8 or level9') 88 | exit() 89 | 90 | baseline_csv = sys.argv[3] 91 | new_csv = sys.argv[4] 92 | messages_sent = process(diff_type, entity_type, baseline_csv, new_csv) 93 | if messages_sent == 0: 94 | telegram_sendtext(f'Cadastre analysis done for {entity_type} {diff_type} diff type for ' 95 | f'{datetime.date.strftime(datetime.date.today(), "%d.%m.%Y")}') 96 | 97 | 98 | if __name__ == '__main__': 99 | main() 100 | -------------------------------------------------------------------------------- /extras/add_subarea_settlements.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script semi-automatically adds subarea level9 entities to level8 entities. 3 | """ 4 | import os 5 | import sys 6 | 7 | import osmapi 8 | import overpy 9 | import yaml 10 | 11 | current = os.path.dirname(os.path.realpath(__file__)) 12 | parent = os.path.dirname(current) 13 | sys.path.append(parent) 14 | 15 | from common import get_polygon_by_cadastre_id, load_level9_features 16 | 17 | # Simple optimization not to get relation id for all settlements 18 | # if number of subareas == number of settlements in municipality 19 | ASSUME_SUBAREA_EQUAL_IF_EQUAL_NUMBER = True 20 | 21 | 22 | def get_level9_from_osm(config, overpass_api, level9_ids): 23 | level9_features = {} 24 | i = 0 25 | for level9_id in level9_ids: 26 | i = i + 1 27 | print(f'Fetching level9 id: {level9_id}') 28 | _, osm_relation_name, osm_relation_id, _ = get_polygon_by_cadastre_id(overpass_api, admin_level=9, cadastre_id=level9_id, country=config['country'], id_key=config['level9_ref_key']) 29 | print(' ({}/{}) Found level 9: {}'.format(i, len(level9_ids), osm_relation_name)) 30 | level9_features[osm_relation_id] = osm_relation_name 31 | return level9_features 32 | 33 | 34 | def main(config, overpass_api, input_csv_file): 35 | api = osmapi.OsmApi(passwordfile='osm-password', 36 | changesetauto=True, changesetautosize=20, changesetautotags= 37 | {u"comment": u"OSM admin boundary conflation - adding missing subarea", 38 | u"tag": u"mechanical=yes", u"source": config['changeset_source']}) 39 | 40 | level9_features = load_level9_features(input_csv_file) 41 | level8_ids = set([level9_feature['level8_id'] for level9_feature in level9_features]) 42 | 43 | counter = 0 44 | for level8_id in level8_ids: 45 | level9_ids = set([level9_feature['level9_id'] for level9_feature in level9_features if level9_feature['level8_id'] == level8_id]) 46 | counter = counter + 1 47 | _, _, osm_relation_id, _ = get_polygon_by_cadastre_id(overpass_api, 8, level8_id, country=config['country'], id_key=config['level8_ref_key']) 48 | if osm_relation_id is None: 49 | print(f'Skipping level8 with id {level8_id}, not found in OSM') 50 | continue 51 | level8_feature = api.RelationGet(osm_relation_id) 52 | print('Processing level 8 {}'.format(level8_feature['tag']['name'])) 53 | subarea_refs = [m for m in level8_feature['member'] if m['role'] == 'subarea'] 54 | if ASSUME_SUBAREA_EQUAL_IF_EQUAL_NUMBER and len(subarea_refs) == len(level9_ids): 55 | print(f'({counter}/{len(level8_ids)}) Skipping {level8_feature["tag"]["name"]} ' 56 | f'object as it seems it already have all ({len(subarea_refs)}) subareas') 57 | continue 58 | level9_osm_features_in_this_level8 = get_level9_from_osm(overpass_api, level9_ids) 59 | anything_changed = False 60 | # Delete those that do not exist anymore 61 | for subarea_ref in subarea_refs: 62 | if subarea_ref['ref'] not in level9_osm_features_in_this_level8: 63 | input('Removing subarea rel https://www.openstreetmap.org/relation/{} from municipality {}, confirm?'. 64 | format(subarea_ref['ref'], level8_feature['tag']['name'])) 65 | level8_feature['member'].remove(subarea_ref) 66 | anything_changed = True 67 | # Add those that do not exist 68 | for level9_osm_id in level9_osm_features_in_this_level8.keys(): 69 | if level9_osm_id not in [m['ref'] for m in subarea_refs]: 70 | # TODO: this is none, investigate 71 | print('Adding settlement {} https://www.openstreetmap.org/relation/{} to municipality {}'.format( 72 | level9_osm_features_in_this_level8[level9_osm_id], level9_osm_id, level8_feature['tag']['name'])) 73 | level8_feature['member'].append({'type': 'relation', 'ref': level9_ids, 'role': 'subarea'}) 74 | anything_changed = True 75 | if anything_changed: 76 | accepted = False 77 | while True: 78 | response = input( 79 | '({0}/{1}) Are you sure you want to update level 8 {2} (Y/n/c)?'.format( 80 | counter, len(level8_ids), level8_feature['tag']['name'])) 81 | if response == '' or response.lower() == 'y': 82 | accepted = True 83 | if response.lower() == u'c': 84 | new_answer = input('Again: ') 85 | if new_answer == '': 86 | continue 87 | else: 88 | accepted = True 89 | break 90 | if accepted: 91 | api.RelationUpdate(level8_feature) 92 | api.flush() 93 | 94 | 95 | if __name__ == '__main__': 96 | with open('config.yml', 'r') as config_yml_file: 97 | config = yaml.safe_load(config_yml_file) 98 | 99 | overpass_api = overpy.Overpass(url=config['overpass_url']) 100 | 101 | if len(sys.argv) != 2: 102 | print("Usage: ./extras/add_subarea_level9_to_osm.py ") 103 | exit() 104 | input_csv_file = sys.argv[1] 105 | main(config, overpass_api, input_csv_file) 106 | -------------------------------------------------------------------------------- /common.py: -------------------------------------------------------------------------------- 1 | import csv 2 | import functools 3 | import http.client 4 | import socket 5 | import sys 6 | import time 7 | import urllib.error 8 | from collections import OrderedDict 9 | 10 | import shapely.geometry as geometry 11 | from overpy.exception import OverpassTooManyRequests, OverpassGatewayTimeout, OverpassUnknownContentType 12 | from shapely.ops import linemerge, unary_union, polygonize 13 | 14 | csv.field_size_limit(sys.maxsize) 15 | 16 | 17 | def retry_on_error(timeout_in_seconds=60): 18 | def decorate(func): 19 | def call(*args, **kwargs): 20 | retries = 5 21 | while retries > 0: 22 | try: 23 | result = func(*args, **kwargs) 24 | except (ConnectionRefusedError, ConnectionResetError, 25 | OverpassTooManyRequests, OverpassGatewayTimeout, OverpassUnknownContentType, 26 | socket.timeout, urllib.error.URLError, http.client.RemoteDisconnected): 27 | retries = retries - 1 28 | print('Connection refused, retrying') 29 | time.sleep(timeout_in_seconds) 30 | continue 31 | return result 32 | raise Exception('Exhausted retries for connection refused, quitting') 33 | return call 34 | return decorate 35 | 36 | 37 | def create_geometry_from_osm_response(relation, response): 38 | # Try to build shapely polygon out of this data 39 | outer_ways = [way.ref for way in relation.members if way.role == 'outer'] 40 | inner_ways = [way.ref for way in relation.members if way.role == 'inner'] 41 | lss = [] 42 | for ii_w, way in enumerate(response.ways): 43 | if way.id not in outer_ways: 44 | continue 45 | ls_coords = [] 46 | for node in way.nodes: 47 | ls_coords.append((node.lon, node.lat)) 48 | lss.append(geometry.LineString(ls_coords)) 49 | 50 | merged = linemerge([*lss]) 51 | borders = unary_union(merged) 52 | polygons = list(polygonize(borders)) 53 | print('polygons found {0}'.format(len(polygons))) 54 | polygon = functools.reduce(lambda p,x: p.union(x), polygons[1:], polygons[0]) 55 | if len(inner_ways) > 0: 56 | lss_inner = [] 57 | for ii_w, way in enumerate(response.ways): 58 | if way.id not in inner_ways: 59 | continue 60 | ls_coords = [] 61 | for node in way.nodes: 62 | ls_coords.append((node.lon, node.lat)) 63 | lss_inner.append(geometry.LineString(ls_coords)) 64 | merged = linemerge([*lss_inner]) 65 | borders = unary_union(merged) 66 | inner_polygons = list(polygonize(borders)) 67 | for inner_polygon in inner_polygons: 68 | polygon = polygon.symmetric_difference(inner_polygon) 69 | return polygon 70 | 71 | 72 | @retry_on_error(timeout_in_seconds=2*60) 73 | def get_polygon_by_cadastre_id(api, admin_level, cadastre_id, country, id_key): 74 | response = api.query(""" 75 | area["name"="{0}"]["admin_level"=2]->.c; 76 | relation(area.c)["admin_level"={1}]["{2}"={3}]; 77 | (._;>;); 78 | out; 79 | // &contact=https://github.com/stalker314314/osm-admin-boundary-conflation/ 80 | """.format(country, admin_level, id_key, cadastre_id)) 81 | print('relations found for cadastre id {0}: {1}'.format(cadastre_id, len(response.relations))) 82 | national_border = any([w.tags['admin_level'] == '2' if 'admin_level' in w.tags else False for w in response.ways]) 83 | if len(response.relations) != 1: 84 | return None, None, None, None 85 | polygon = create_geometry_from_osm_response(response.relations[0], response) 86 | return polygon, response.relations[0].tags['name'], response.relations[0].id, national_border 87 | 88 | 89 | def load_level9_features(input_csv_file): 90 | """ 91 | List of all level9 features with their name, id and (level8, level7, level6) names and ids 92 | """ 93 | level9_features = [] 94 | with open(input_csv_file) as input_csv: 95 | reader = csv.DictReader(input_csv) 96 | for row in reader: 97 | level9_features.append({ 98 | 'level9_id': row['level9_id'], 99 | 'level9_name': row['level9_name'], 100 | 'level8_id': row['level8_id'], 101 | 'level8_name': row['level8_name'], 102 | 'level7_id': row['level7_id'], 103 | 'level7_name': row['level7_name'], 104 | 'level6_id': row['level6_id'], 105 | 'level6_name': row['level6_name'], 106 | 'wkt': row['wkt'], 107 | }) 108 | return level9_features 109 | 110 | 111 | def get_municipality_settlements(): 112 | """ 113 | :return: Map of level8_id => list(level8 entities) 114 | """ 115 | municipality_settlements = {} 116 | municipality_names = {} 117 | with open('input/naselje.csv') as settlement_csv: 118 | reader = csv.DictReader(settlement_csv) 119 | for row in reader: 120 | if row['opstina_maticni_broj'] not in municipality_names: 121 | municipality_names[row['opstina_maticni_broj']] = row['opstina_ime'] 122 | if row['opstina_maticni_broj'] not in municipality_settlements: 123 | municipality_settlements[row['opstina_maticni_broj']] = [] 124 | municipality_settlements[row['opstina_maticni_broj']].append(row['naselje_maticni_broj']) 125 | municipality_settlements = OrderedDict(sorted(municipality_settlements.items(), key=lambda x: x)) 126 | return municipality_settlements 127 | 128 | 129 | def get_settlement_municipality(): 130 | """ 131 | :return: Map of level9_id => level8_id 132 | """ 133 | settlements_municipality = {} 134 | with open('input/naselje.csv') as naselja_csv: 135 | reader = csv.DictReader(naselja_csv) 136 | for row in reader: 137 | settlements_municipality[int(row['naselje_maticni_broj'])] = int(row['opstina_maticni_broj']) 138 | return settlements_municipality 139 | 140 | 141 | def get_municipality_district(): 142 | """ 143 | :return: Map of level8_id => level6 144 | """ 145 | municipality_district = {} 146 | with open('input/opstina.csv') as naselja_csv: 147 | reader = csv.DictReader(naselja_csv) 148 | for row in reader: 149 | municipality_district[int(row['opstina_maticni_broj'])] = int(row['okrug_sifra']) 150 | return municipality_district 151 | 152 | 153 | def get_district_name_by_id(): 154 | """ 155 | :return: Map of level6_id => level6 156 | """ 157 | districts = {} 158 | with open('input/opstina.csv') as naselja_csv: 159 | reader = csv.DictReader(naselja_csv) 160 | for row in reader: 161 | districts[int(row['okrug_sifra'])] = row['okrug_ime'] 162 | return districts 163 | -------------------------------------------------------------------------------- /serbia/serbia2input.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script generate input files in proper CSV format 3 | """ 4 | 5 | import csv 6 | import os 7 | import shutil 8 | import sys 9 | import time 10 | import zipfile 11 | 12 | import pyproj 13 | import requests 14 | from bs4 import BeautifulSoup 15 | from shapely import wkt 16 | from shapely.ops import transform 17 | 18 | csv.field_size_limit(sys.maxsize) 19 | 20 | wgs84 = pyproj.CRS('EPSG:4326') 21 | utm = pyproj.CRS('EPSG:32634') 22 | project = pyproj.Transformer.from_crs(utm, wgs84, always_xy=True).transform 23 | 24 | 25 | def reproject_wkt(wkt_text): 26 | wkt_obj = wkt.loads(wkt_text) 27 | return transform(project, wkt_obj) 28 | 29 | 30 | def download_cadastre_data(username, password): 31 | """ 32 | Logs in to opendata.geosrbija.rs and downloads zips with data. 33 | It will clean zip files and leave input/naselje.csv which contains level9 data. 34 | """ 35 | s = requests.Session() 36 | # Go to login page 37 | r = s.get('https://opendata.geosrbija.rs/loginopendata') 38 | soup = BeautifulSoup(r.text, 'lxml') 39 | csrf_token = soup.select_one('#csrf_token')['value'] 40 | 41 | # Login 42 | headers = {} 43 | headers['content-type'] = 'application/x-www-form-urlencoded' 44 | r = s.post('https://opendata.geosrbija.rs/loginopendata', headers=headers, 45 | data={'username': username, 'password': password, 'csrf_token': csrf_token}) 46 | 47 | if not os.path.exists('input'): 48 | os.mkdir('input') 49 | 50 | # Get okrug 51 | print('Downloading level6 data') 52 | r = s.get('https://opendata.geosrbija.rs/okrug?f=csv&user={0}'.format(username), stream=True) 53 | with open('input/okrug.zip', 'wb') as fd: 54 | for chunk in r.iter_content(chunk_size=1023): 55 | fd.write(chunk) 56 | with zipfile.ZipFile('input/okrug.zip', 'r') as zip_ref: 57 | zip_ref.extractall('./input') 58 | os.remove('input/okrug.zip') 59 | time.sleep(5) 60 | 61 | # Get grad 62 | print('Downloading level7 data') 63 | r = s.get('https://opendata.geosrbija.rs/gradovi?f=csv&user={0}'.format(username), stream=True) 64 | with open('input/grad.zip', 'wb') as fd: 65 | for chunk in r.iter_content(chunk_size=1024): 66 | fd.write(chunk) 67 | with zipfile.ZipFile('input/grad.zip', 'r') as zip_ref: 68 | zip_ref.extractall('./input') 69 | os.remove('input/grad.zip') 70 | time.sleep(5) 71 | 72 | # Get opstina 73 | print('Downloading level8 data') 74 | r = s.get('https://opendata.geosrbija.rs/opstina?f=csv&user={0}'.format(username), stream=True) 75 | with open('input/opstina.zip', 'wb') as fd: 76 | for chunk in r.iter_content(chunk_size=1024): 77 | fd.write(chunk) 78 | with zipfile.ZipFile('input/opstina.zip', 'r') as zip_ref: 79 | zip_ref.extractall('./input') 80 | os.remove('input/opstina.zip') 81 | time.sleep(5) 82 | 83 | # Get naselje 84 | print('Downloading level9 data') 85 | r = s.get('https://opendata.geosrbija.rs/naselje?f=csv&user={0}'.format(username), stream=True) 86 | with open('input/naselje.zip', 'wb') as fd: 87 | for chunk in r.iter_content(chunk_size=1024): 88 | fd.write(chunk) 89 | with zipfile.ZipFile('input/naselje.zip', 'r') as zip_ref: 90 | source = zip_ref.open('tmp/data/ready/naselja/naselje.csv') 91 | target = open('./input/naselje.csv', "wb") 92 | with source, target: 93 | shutil.copyfileobj(source, target) 94 | os.remove('input/naselje.zip') 95 | time.sleep(5) 96 | 97 | 98 | def load_level9_features(): 99 | level9_features = [] 100 | with open('input/naselje.csv') as level9_csv: 101 | reader = csv.DictReader(level9_csv) 102 | for row in reader: 103 | level9_features.append({ 104 | 'level9_name': row['naselje_ime'], 105 | 'level9_id': row['naselje_maticni_broj'], 106 | 'level8_id': row['opstina_maticni_broj'], 107 | 'wkt': reproject_wkt(row['wkt']) 108 | }) 109 | return level9_features 110 | 111 | 112 | def write_level9_features(level9, output_csv_filename): 113 | with open(output_csv_filename, 'w') as out_csv: 114 | writer = csv.DictWriter(out_csv, fieldnames=['level9_id', 'level9_name', 'level8_id', 'level8_name', 'level7_id', 'level7_name', 'level6_id', 'level6_name', 'wkt']) 115 | 116 | writer.writeheader() 117 | for data in level9: 118 | writer.writerow(data) 119 | 120 | 121 | # Map of level8_id => (level8_name, level6_id) 122 | def load_level8_features() -> dict: 123 | level8_features = {} 124 | with open('input/opstina.csv') as level8_csv: 125 | reader = csv.DictReader(level8_csv) 126 | for row in reader: 127 | level8_id = row['opstina_maticni_broj'] 128 | level8_name = row['opstina_ime'] 129 | level6_id = row['okrug_sifra'] 130 | level8_features[level8_id] = (level8_name, level6_id) 131 | return level8_features 132 | 133 | 134 | # Map of level6_id => level6_name 135 | def load_level6_features() -> dict: 136 | level6_features = {} 137 | with open('input/okrug.csv') as level6_csv: 138 | reader = csv.DictReader(level6_csv) 139 | for row in reader: 140 | level6_id = row['okrug_sifra'] 141 | level6_name = row['okrug_ime'] 142 | level6_features[level6_id] = level6_name 143 | return level6_features 144 | 145 | 146 | def main(output_csv_file: str): 147 | if not os.path.exists('rgz-password'): 148 | print('Please create file rgz-password with RGZ credentials in the form of : in it') 149 | exit() 150 | with open('rgz-password') as f: 151 | line = f.readline() 152 | username = line.split(":")[0].strip() 153 | password = line.split(":")[1].strip() 154 | download_cadastre_data(username, password) 155 | 156 | print('Merging level9 data') 157 | level9_features = load_level9_features() 158 | level8_features = load_level8_features() 159 | level6_features = load_level6_features() 160 | for level9_feature in level9_features: 161 | level9_feature['level8_name'] = level8_features[level9_feature['level8_id']][0] 162 | level9_feature['level7_id'] = None 163 | level9_feature['level7_name'] = None 164 | level9_feature['level6_id'] = level8_features[level9_feature['level8_id']][1] 165 | level9_feature['level6_name'] = level6_features[level9_feature['level6_id']] 166 | print(f'Writing level9 data to {output_csv_file}') 167 | write_level9_features(level9_features, output_csv_file) 168 | print('Done') 169 | 170 | 171 | if __name__ == '__main__': 172 | if len(sys.argv) != 2: 173 | print("Usage: ./serbia2input.py ") 174 | exit() 175 | output_csv_file = sys.argv[1] 176 | main(output_csv_file) 177 | -------------------------------------------------------------------------------- /measure_quality.py: -------------------------------------------------------------------------------- 1 | import csv 2 | import multiprocessing 3 | import os 4 | import sys 5 | import time 6 | from concurrent.futures import ProcessPoolExecutor, as_completed 7 | from threading import Lock 8 | 9 | import overpy 10 | import yaml 11 | from shapely.wkt import loads 12 | 13 | from common import retry_on_error, create_geometry_from_osm_response, get_polygon_by_cadastre_id, load_level9_features 14 | 15 | csv.field_size_limit(sys.maxsize) 16 | csv_write_mutex = Lock() 17 | results = [] 18 | 19 | 20 | @retry_on_error() 21 | def get_level9_polygon_by_name(api, country, level6_name, level8_name): 22 | for admin_level in (8, 7): 23 | response = api.query(""" 24 | area["name"="{0}"]["admin_level"=2]->.country; 25 | ( 26 | area(area.country)["name"~"{1}$", i]["admin_level"={2}]->.district; 27 | ( 28 | relation(area.district)["boundary"="administrative"]["admin_level"=9]["name"~"^{3}$", i]; 29 | ); 30 | ); 31 | (._;>;); 32 | out; 33 | // &contact=https://github.com/stalker314314/osm-admin-boundary-conflation/ 34 | """.format(country, level6_name, admin_level, level8_name)) 35 | time.sleep(10) 36 | 37 | print('relations found for level {0}: {1}'.format(admin_level, len(response.relations))) 38 | if len(response.relations) != 1: 39 | continue 40 | polygon = create_geometry_from_osm_response(response.relations[0], response) 41 | return polygon, response.relations[0].tags['name'], response.relations[0].id 42 | return None, None, None 43 | 44 | 45 | def get_current_results(output_file): 46 | # Load saved state 47 | results = [] 48 | if os.path.isfile(output_file): 49 | with open(output_file) as csvfile: 50 | reader = csv.DictReader(csvfile) 51 | for row in reader: 52 | results.append( 53 | {'level6_name': row['level6_name'], 'level8_name': row['level8_name'], 54 | 'level9_name': row['level9_name'], 'osm_settlement_name': row['osm_settlement_name'], 55 | 'relation_id': row['relation_id'], 'area_diff': row['area_diff'], 56 | 'i_o_u': row['i_o_u'], 'national_border': row['national_border']}) 57 | return results 58 | 59 | 60 | def write_results(current_results, output_file): 61 | with csv_write_mutex: 62 | with open(output_file, 'w') as out_csv: 63 | writer = csv.DictWriter(out_csv, fieldnames=[ 64 | 'level6_name', 'level8_name', 'level9_name', 'osm_settlement_name', 65 | 'relation_id', 'area_diff', 'i_o_u', 'national_border']) 66 | writer.writeheader() 67 | for data in current_results: 68 | writer.writerow(data) 69 | 70 | 71 | def process_level9(config, overpass_api, level9_entity, count_processed, total_to_process): 72 | global results 73 | print('Processed {0}/{1}'.format(count_processed, total_to_process)) 74 | 75 | country = config['country'] 76 | level9_ref_key = config['level9_ref_key'] 77 | 78 | cadastre_level9_polygon = loads(level9_entity['wkt']) 79 | level6_name = level9_entity['level6_name'] 80 | level8_name = level9_entity['level8_name'] 81 | level9_name = level9_entity['level9_name'] 82 | level9_id = level9_entity['level9_id'] 83 | 84 | print('Processing {0} {1}'.format(level8_name, level9_name)) 85 | 86 | overpass_level9_polygon, osm_settlement_name, osm_relation_id, national_border = \ 87 | get_polygon_by_cadastre_id(overpass_api, admin_level=9, cadastre_id=level9_id, country=country, id_key=level9_ref_key) 88 | if overpass_level9_polygon is None: 89 | print(f'Level 8 {level8_name} and level 9 {level9_name} not found using {level9_ref_key}') 90 | overpass_level9_polygon, osm_settlement_name, osm_relation_id, national_border = \ 91 | get_level9_polygon_by_name(overpass_api, country, level8_name, level9_name) 92 | if overpass_level9_polygon is None: 93 | print(f'Level8 {level8_name} and level9 {level9_name} not found at all') 94 | result = {'level6_name': level6_name, 'level8_name': level8_name, 'level9_name': level9_name, 95 | 'osm_settlement_name': '', 'relation_id': -1, 'area_diff': -1, 'i_o_u': -1, 96 | 'national_border': national_border} 97 | results.append(result) 98 | return result 99 | 100 | intersection = cadastre_level9_polygon.intersection(overpass_level9_polygon) 101 | union = cadastre_level9_polygon.union(overpass_level9_polygon) 102 | i_o_u = intersection.area / union.area 103 | 104 | print(level8_name, level9_name, osm_settlement_name, 100 * intersection.area/cadastre_level9_polygon.area, i_o_u) 105 | result = {'level6_name': level6_name, 'level8_name': level8_name, 'level9_name': level9_name, 106 | 'osm_settlement_name': osm_settlement_name, 'relation_id': osm_relation_id, 107 | 'area_diff': round(intersection.area/cadastre_level9_polygon.area, 5), 108 | 'i_o_u': round(i_o_u, 5), 109 | 'national_border': national_border} 110 | results.append(result) 111 | return result 112 | 113 | 114 | def measure_quality(config, overpass_api, input_csv_file, output_file): 115 | global results 116 | results = get_current_results(output_file) 117 | level9_features = load_level9_features(input_csv_file) 118 | 119 | count_processed = 1 120 | all_futures = [] 121 | thread_count = 1 if 'localhost' not in overpass_api.url else multiprocessing.cpu_count() 122 | print('Using {0} threads'.format(thread_count)) 123 | with ProcessPoolExecutor(max_workers=thread_count) as executor: 124 | for level9_feature in level9_features: 125 | # Skip if already processed 126 | level8_name = level9_feature['level8_name'] 127 | level9_name = level9_feature['level9_name'] 128 | if any((r for r in results if r['level8'] == level8_name and r['level9'] == level9_name)): 129 | print('Level8 {0} and level9 {1} already processed'.format(level8_name, level9_name)) 130 | continue 131 | 132 | future = executor.submit(process_level9, config, overpass_api, level9_feature, count_processed, len(level9_features)) 133 | all_futures.append(future) 134 | count_processed = count_processed + 1 135 | for future in as_completed(all_futures): 136 | results.append(future.result()) 137 | write_results(results, output_file) 138 | 139 | 140 | if __name__ == '__main__': 141 | with open('config.yml', 'r') as config_yml_file: 142 | config = yaml.safe_load(config_yml_file) 143 | 144 | overpass_api = overpy.Overpass(url=config['overpass_url']) 145 | 146 | if len(sys.argv) != 3: 147 | print("Usage: ./measure_quality.py ") 148 | exit() 149 | input_csv_file = sys.argv[1] 150 | output_csv_file = sys.argv[2] 151 | measure_quality(config, overpass_api, input_csv_file, output_csv_file) 152 | -------------------------------------------------------------------------------- /conflate-report.py: -------------------------------------------------------------------------------- 1 | import pickle 2 | import pprint 3 | import sys 4 | from collections import OrderedDict 5 | 6 | from jinja2 import Environment, FileSystemLoader 7 | 8 | from processing_state import ProcessingState 9 | 10 | errors = { 11 | ProcessingState.NO: 'Not yet considered.', 12 | ProcessingState.CHECKED_POSSIBLE: 'Checked and way can be conflated without problems, but conflation not yet done.', 13 | ProcessingState.CONFLATED: 'Conflated (already done).', 14 | ProcessingState.ERROR_END_POINTS_FAR_APART: 'First or last node from cadastre and OSM are too far apart. This can happen when way between two entities is split. Additional context is mentioning exact distance they are apart.', 15 | ProcessingState.ERROR_GEOMETRY_WRONG: 'User rejected conflation.', 16 | ProcessingState.ERROR_SHARED_WAY_NOT_FOUND: 'Way to be conflated is shared between two entities, but no such way is found in OSM. This should not be common situation and it might mean that border in OSM is converted to single node or that entities to not touch at all. diruju. This error requires human investigation.', 17 | ProcessingState.ERROR_WAY_NOT_FOUND: 'Way to be conflated is touching only one entity, but no such way is found in OSM. This might mean that border between two entites from cadastre have a gap, but in there is no gap in OSM and border in OSM is shared (and it should not be). Human need to find this situation and split border to two separate ways.', 18 | ProcessingState.ERROR_MULTIPLE_SHARED_WAYS: 'Way to be conflated is shared between two entities, but in OSM there are multiple such shared ways. They should probably be merged (unless there are lower level admin boundaries conected to them). Additional context is listing all found OSM ways.', 19 | ProcessingState.ERROR_MULTIPLE_SINGLE_WAY: 'Way to be conflated is touching only one entity, but in OSM there are multiple such single ways. They should probably be merged (unless there are lower level admin boundaries conected to them). Additional context is listing all found OSM ways.', 20 | ProcessingState.ERROR_NODES_WITH_TAGS: 'Some nodes in found way do contain unexpected tags. Human need to check these tags and either remove them, or ungle those nodes from way. Additional context is listing all those nodes.', 21 | ProcessingState.ERROR_NATIONAL_BORDER: 'Found way is national border (admin_level=2) and no conflation is possible. This is kind of error that is not fixable without further discussion between two national communities.', 22 | ProcessingState.ERROR_UNEXPECTED_TAG: 'Found way contains unexpected tags. Human need to either remove those tags or split way into two different ways. Additional context is listing those tags.', 23 | ProcessingState.ERROR_NODE_IN_OTHER_WAYS: 'Found way is containing node that is shared with some other ways that are not administrative borders. Sometimes they should be unglued, sometimes it is actually untagged border. Additional context is listing those other ways.', 24 | ProcessingState.ERROR_NODE_IN_NATIONAL_BORDER: 'Found way contains node that is shared with national border and it should not be moved. Additional context is listing way of national border.', 25 | ProcessingState.ERROR_NODE_IN_OTHER_RELATION: 'Found way contains node that is part of some other relation that is not administrative border and it should not be moved. Additional context contains that other relation.', 26 | ProcessingState.ERROR_NODE_IN_NATIONAL_RELATION: 'Found way contains node that is part of national border and it should not be moved. Additional context contains tway of national border.', 27 | ProcessingState.ERROR_INVALID_SHAPE: 'Invalid shape read from .osm file.', 28 | ProcessingState.ERROR_CLOSED_SHAPE: 'Way to be conflated is closed shape (enclave or exclave). This tool does not support conflation of closed shaped yet. Human need to do manual conflation.', 29 | ProcessingState.ERROR_OVERLAPPING_WAYS: 'Way to be conflated contains more than 2 entities. This means that some of the entities overlap which usually means error in cadastre data. Check manually or contact authoritative source.', 30 | ProcessingState.ERROR_TOO_MANY_NODES: 'Way to be conflated contains more than 2000 nodes which is above OSM limit for number of nodes in the way. Please simplify this way manually.' 31 | } 32 | 33 | errors = OrderedDict(sorted(errors.items(), key=lambda x: x[0].value)) 34 | 35 | 36 | def main(progress_file, output_html_file): 37 | env = Environment(loader=FileSystemLoader(searchpath='./templates')) 38 | template = env.get_template('index_template.html') 39 | 40 | with open(progress_file, 'rb') as p: 41 | source_data = pickle.load(p) 42 | total_ways = len(source_data['ways']) 43 | processed_ways = len([w for w in source_data['ways'].values() if w['processed'] != ProcessingState.NO]) 44 | ways_with_osm_ways_found = len([w for w in source_data['ways'].values() if w['osm_way'] is not None]) 45 | count_per_error = {} 46 | for w in source_data['ways'].values(): 47 | if w['processed'] not in count_per_error: 48 | count_per_error[w['processed']] = 0 49 | count_per_error[w['processed']] += 1 50 | if w['error_context'] is None: 51 | w['error_context'] = '' 52 | if w['processed'] in (ProcessingState.ERROR_MULTIPLE_SHARED_WAYS, ProcessingState.ERROR_MULTIPLE_SINGLE_WAY, 53 | ProcessingState.ERROR_NODE_IN_OTHER_WAYS, ProcessingState.ERROR_NODE_IN_NATIONAL_BORDER): 54 | ways = w['error_context'].split(',') 55 | w['error_context'] = ','.join(['{0}'.format(w) for w in ways]).replace('"', '\\"') 56 | elif w['processed'] in (ProcessingState.ERROR_NODES_WITH_TAGS,): 57 | nodes = w['error_context'].split(',') 58 | w['error_context'] = ','.join(['{0}'.format(n) for n in nodes]).replace('"', '\\"') 59 | elif w['processed'] in (ProcessingState.ERROR_NODE_IN_OTHER_RELATION,): 60 | relations = w['error_context'].split(',') 61 | w['error_context'] = ','.join(['{0}'.format(r) for r in relations]).replace('"', '\\"') 62 | elif w['processed'] in (ProcessingState.ERROR_END_POINTS_FAR_APART,): 63 | w['error_context'] = '{:.2f}m'.format(float(w['error_context'])) 64 | print('Total ways: {0}'.format(total_ways)) 65 | print('Processed ways: {0}'.format(processed_ways)) 66 | print('Ways with OSM way found: {0}'.format(ways_with_osm_ways_found)) 67 | pp = pprint.PrettyPrinter(indent=4) 68 | print('Count per error:\n{0}'.format(pp.pformat(count_per_error))) 69 | count_per_error = OrderedDict(sorted(count_per_error.items(), key=lambda x: x[1], reverse=True)) 70 | 71 | source_data = {k: source_data['ways'][k] for k in list(source_data['ways'])[0:-1]} 72 | output = template.render(total_ways=total_ways, processed_ways=processed_ways, errors=errors, 73 | count_per_error=count_per_error, ways_with_osm_ways_found=ways_with_osm_ways_found, 74 | source_data=source_data) 75 | with open(output_html_file, 'w', encoding='utf-8') as fh: 76 | fh.write(output) 77 | 78 | 79 | if __name__ == '__main__': 80 | if len(sys.argv) != 3: 81 | print("Usage: ./conflate-report.py ") 82 | exit() 83 | progress_file = sys.argv[1] 84 | output_html_file = sys.argv[2] 85 | main(progress_file, output_html_file) 86 | -------------------------------------------------------------------------------- /templates/index_template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | OSM admin boundary conflation report 8 | 9 | 10 | 11 | 13 | 14 | 15 | 16 |

OSM admin boundary conflation report

17 | Toggle legend 18 | 46 |
47 |
48 | 49 | 50 | 51 | 52 | 171 | 172 | 173 | 174 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OSM administrative boundary conflation 2 | 3 | This repo contains set of predefined pipelines, data formats and tools that aid conflation of 4 | administrative boundaries in OpenStreetMap (OSM). If you get your hands on authoritative dataset ("external truth") 5 | which contains geometries of admin boundaries, this repo can help you to import this data in an easy and semi-automated 6 | way. 7 | 8 | Conflation is hard and labor-intensive process if you want to do it properly. When conflating boundaries, you need to 9 | take great care not to accidentally move national boundary, or move other glued ways like highways, or move tagged nodes, 10 | like traffic lights. And you can have other relations glued together with administrative boundaries. It can get messy 11 | and error-prone very fast. This repo helps with all of that and on high-level it will enable you to: 12 | 13 | * measure quality of your boundaries (authoritative data vs OSM data) 14 | * keep quality of OSM boundaries in daily, continuous fashion 15 | * prepare data so you can do manual conflation using tools like JOSM 16 | * check conflation potential (what can be semi-automatically conflated, what not and most importantly - why not) 17 | * do ungluing and conflate boundary ways in semi-automatic ways (present to user each way to be conflated and result of 18 | conflation and ask user to proceed) 19 | 20 | ## Install 21 | 22 | This repo is tested exclusively in Linux and is recommended way to use it. On Windows, your best bet is Conda. 23 | Here are brief instructions for Debian: 24 | ``` 25 | sudo apt install proj-bin libproj-dev curl gdal-bin git 26 | python -m pip install -r requirements.txt 27 | ``` 28 | 29 | Also, you will need to install Docker if you plan to use local Overpass instance (which is highly encouraged). If you do 30 | use Docker, do note that all scripts here assume that Docker could be ran without root, so try to set up Docker to be 31 | rootless. 32 | 33 | During running of some tools, scripts will try to clone ogr2osm repo (it is dependency, but there are no automated way 34 | to pull this, so I added `git clone` directly in script to make your life easier). 35 | 36 | ## Pipeline 37 | 38 | ``` 39 | Input data 40 | | 41 | v 42 | +--------------------+ 43 | | | 44 | | Your script | 45 | | to convert to | 46 | | input .csv | 47 | | | 48 | +----------+---------+ 49 | | .csv 50 | | 51 | +-------------------------+ 52 | | | 53 | v v 54 | +--------------------+ +--------------------+ 55 | | | | | 56 | | | | | 57 | | inputcsv2shp.py | | measure_quality.py | 58 | | | | | 59 | | | | | 60 | +---------+----------+ +--------------------+ 61 | | .shp 62 | v 63 | +--------------------+ 64 | | | 65 | | | 66 | | shp2osm.py | 67 | | | 68 | | | 69 | +---------+----------+ 70 | | .osm 71 | v 72 | +--------------------+ 73 | | | 74 | | | conflate-progress.pickle 75 | | conflate.py +---------------+ 76 | | | | 77 | | | v 78 | +---------+----------+ +-------------------+ 79 | | | | 80 | |Changesets | | 81 | v | conflate-stats.py | 82 | +-----+ | | 83 | | | | | 84 | | OSM | +---------+---------+ 85 | | | | 86 | +-----+ |.html 87 | v 88 | ``` 89 | 90 | ## Usage 91 | 92 | ### Adjust config 93 | 94 | Root directory of this repo contains file `config.yml`. It contains most important configuration that you need to closely 95 | go over and adopt to your use case. All fields should be self-explanatory, but if you are not sure about some, or need 96 | more extensibility than what is there, let me know! 97 | 98 | ### Convert input data to .CSV 99 | This repo contains several tools to make sense of admin boundary conflation. First thing is to convert your input dataset 100 | to something that pipeline down the road can understand. This is simple CSV file which contains following columns: 101 | * `level9_id`: string 102 | * `wkt`: WKT geometry of your level 9 entity (in WSG84) 103 | 104 | Everything else is optional: 105 | 106 | * `level9_name`: string 107 | * `level8_id`: string 108 | * `level8_name`: string 109 | * `level7_id`: string 110 | * `level7_name`: string 111 | * `level6_id`: string 112 | * `level6_name`: string 113 | 114 | As you can see, format is as simple as it can be. How to create it from your dataset is out of scope of this document, 115 | but you can use Python (look at implementation for Serbia located at `serbia/serbia2input.py`) or even QGIS. If you need 116 | help, feel free to ping me with your dataset or open issue on Github! 117 | 118 | If you don't have level9 entities (settlements, neightbours), but something else (level 8, level 10...), script should 119 | work in theory, but it needs adjustments here and there. Let me know if this is blocker for you, so we can implement 120 | your use case too. 121 | 122 | ### Measure quality 123 | 124 | Once you have data in expected .csv format, you can run: `python ./measure_quality.py ` 125 | and it will go over all entities and, for each admin entity, it will output IoU (intersection over union) as a standard 126 | measurement of how good authoritative dataset fit OSM data. It works by matching `ref` from your dataset to OSM or 127 | `name` tag, so if you don't have matching `ref` or `name` tags in OSM, it cannot match them. If you want easy way to add 128 | `ref` tags to OSM, check section "Extra scripts". 129 | 130 | This script can measure around 1000-2000 entities per day if you use public Overpass instances. If you use local 131 | Overpass instance, it will work in parallel and can process 100000 entities per day (roughly 100x faster)! 132 | 133 | If you don't plan to do conflation of your data, this measurement script is all you need. Check section "Daily 134 | measurement" to understand how you can do continuous checks for quality of your administrative boundaries. 135 | 136 | ### Produce .osm file for conflation 137 | 138 | Conflation is slow and semi-manual process. Before you can proceed, you need to convert input .csv format to .osm format 139 | with which tooling works. This is needed only once and it is automatic process using two scripts: 140 | ``` 141 | python inputcsv2shp.py 142 | ./shp2osm.sh 143 | ``` 144 | 145 | You can open and inspect obtained .osm file in JOSM editor and check it. It should have separate ways for each segment 146 | of administrative boundary. Goal of conflation is now to find and conflate each of these segments to OSM. If you don't 147 | want to use conflate script, you can still use obtained .osm file to do it manually (see section "Manual conflation 148 | with .osm file"). 149 | 150 | ### Manual conflation with .osm file 151 | 152 | **BIG FAT DISCLAIMER**: Please don't import data or change boundaries without fully conforming with 153 | [OSM import guidelines](https://wiki.openstreetmap.org/wiki/Import/Guidelines) *and* also consulting with both local 154 | community and neighboring countries' communities (if you plan to change national boundaries!). 155 | 156 | * Install JOSM, and install plugin [UtilsPlugin2](https://josm.openstreetmap.de/wiki/Help/Plugin/UtilsPlugin2) which we 157 | will need during process of conflation 158 | * If .osm files are big, increase memory provided to JOSM. It boils down to add parameters `-J-d64 -J-Xmx2048m`, but 159 | check [here](https://josm.openstreetmap.de/wiki/Download#VMselectiononWindowsx64) for more details. 160 | * Open obtained .osm file in JOSM as new layer. 161 | * Go to "File"->"Download data" (Ctr+Shift+Down) and go to tab "Download from Overpass API" and input this[1] as a 162 | query. It is not important what you select in the map below. Click "Download as new layer". It is wise to uncheck "Zoom 163 | to downloaded data", so you don't zoom back to whole country. After download, you should get new layer "Data Layer 1". 164 | 165 | Now that you set it all up, here is cyclic workflow: 166 | * Select "Data layer 1" layer and zoom to level9 entities that you want to fix. Focus on a particular way you want to 167 | fix. 168 | * Copy authoritative way to OSM layer. To do this, first select .osm layer, then select one or more ways. Copy it 169 | (Ctrl+C). Go back to "Data layer 1" and paste it at same position using "Edit"->"Paste at source position" (Ctrl+Alt+V). 170 | Never do Ctrl+V! 171 | * Now select both old and new way, holding Ctrl. With both ways selected, choose "More Tools" -> "Replace Geometry" 172 | (Ctrl+Shift+G) 173 | * New dialog for solving conflicts will show up. You should "Keep" most tags, but you should "delete" "level9_id" tag. 174 | Sometimes, if you change boundary with lower "admin_level" (for example "admin_level=7"), you can have conflict for that 175 | tag too, but always choose lower number. Click "Apply". 176 | * You just conflated way from old (OSM) geometry to new (authoritative) geometry and all points are added/modified. From 177 | two ways, we got one. What is not fixed are end nodes. They are now detached from OSM boundaries and need to be 178 | reattached. To do that, move them to existing OSM way holding Ctrl to glue them. All boundaries always should form 179 | closed shape. 180 | * Congratulation, you just conflated your first way:) 181 | 182 | [1] 183 | ``` 184 | [out:xml]; 185 | area["name"=""]["admin_level"=2]->.a; 186 | ( 187 | relation(area.a)["boundary"]["admin_level"]; 188 | ); 189 | (._;>;); 190 | out; 191 | ``` 192 | 193 | ### Assess and report conflating potential 194 | 195 | If you just want to see what is possible to be automatically, set `config.yml` like this: 196 | ``` 197 | dry_run: True 198 | auto_proceed: True 199 | ``` 200 | 201 | and run it like `python `. This will check each way and save intermediate results to 202 | `progress_file`. If you provide same progress file again, it will continue where it left of. If you want to start from 203 | scratch, provide new file or delete existing one. 204 | 205 | This file can be used later to generate report of possible conflation, and if it is not possible - it will explain why 206 | it is not possible (there are lot of various reasons, all explained in report). To generate report, execute: 207 | ``` 208 | python conflate-report.py 209 | ``` 210 | 211 | When you open in your browser, you can check individual problems and solve them independently. 212 | 213 | ### Semi-automatic conflation 214 | 215 | Once you assessed conflating potential, you might want to conflate those ways which are possible to be conflated. For 216 | that, set `config.yml` to: 217 | ``` 218 | dry_run: False 219 | auto_proceed: False 220 | ``` 221 | 222 | You will need to create file named `osm-password` in root folder and fill it with one line that has 223 | `:` in it. This is needed to authenticate with OSM. Once you run conflation with 224 | `python `, you will be asked for those ways that can be conflated, new dialog will be 225 | shown with what geometry will be changed and you need to click "Y" for each way. It is wise to check what actual changes 226 | in OSM has been done, to be sure this script is not going crazy! 227 | 228 | ### Extra scripts 229 | 230 | There are couple of useful scripts in `extras/` folder which might come handy to you. They all require to create file 231 | named `osm-password` in root folder and fill it with one line that has `:` in it. They are: 232 | 233 | * `add_level9_id_to_osm.py`: use it to mass add "ref" tag to OSM to all your level 9 entities, based on their name 234 | * `add_level8_id_to_osm.py`: use it to mass add "ref" tag to OSM to all your level 8 entities, based on their name 235 | * `add_subare_settlements.py`: use it to mass add level 9 relations to level 8 relations as a "subarea" members 236 | 237 | ### Continuous quality checks 238 | 239 | If you can measure quality of your level 9 entities, it should be easy to run that scripts in two consecutive days and 240 | do the difference on their outputs. This is what we did for Serbia and you can check `serbia/daily-measurement.sh` for 241 | details. Basically, we refresh cadastre data and OSM data for day before, then update data for today and do difference 242 | of their results and report if any level 9 entity is worse than it was day before. This way, we get continuous checks. 243 | 244 | If you need something similar, but you are not sure how to do it, let me know and I will try to help you! 245 | -------------------------------------------------------------------------------- /translation.py: -------------------------------------------------------------------------------- 1 | import geom 2 | import yaml 3 | 4 | import os 5 | 6 | __location__ = os.path.dirname(os.path.realpath(__file__)) 7 | 8 | with open('config.yml', 'r') as config_yml_file: 9 | config = yaml.safe_load(config_yml_file) 10 | 11 | 12 | def filterTags(tags): 13 | if tags is None: 14 | return 15 | newtags = { 16 | "level6_name": tags["level6name"], 17 | "level6_id": tags["level6id"], 18 | "level7_name": tags["level7name"], 19 | "level7_id": tags["level7id"], 20 | "level8_name": tags["level8name"], 21 | "level8_id": tags["level8id"], 22 | "level9_name": tags["level9name"], 23 | "level9_id": tags["level9id"], 24 | "boundary": "administrative" 25 | } 26 | 27 | if tags["level9name"] is None or tags["level9name"] == '': 28 | if tags["level8name"] is None or tags["level8name"] == '': 29 | if tags["level7name"] is None or tags["level7name"] == '': 30 | if tags["level6name"] is None or tags["level6name"] == '': 31 | newtags['name'] = '' 32 | else: 33 | newtags['name'] = tags['level6name'] 34 | else: 35 | newtags['name'] = tags['level7name'] 36 | else: 37 | newtags['name'] = tags['level8name'] 38 | else: 39 | newtags['name'] = tags['level9name'] 40 | newtags["admin_level"] = "9" 41 | newtags["type"] = "boundary" 42 | newtags["source"] = config['changeset_source'] 43 | return newtags 44 | 45 | 46 | def splitWay(way, corners, features_map): 47 | idxs = [i for i, c in enumerate(way.points) if c in corners] 48 | splitends = 0 in idxs or (len(way.points) - 1) in idxs 49 | new_points = list() 50 | left = 0 51 | for cut in idxs: 52 | if cut != 0: 53 | new_points.append(way.points[left:(cut + 1)]) 54 | left = cut 55 | # remainder 56 | if left < len(way.points) - 1: 57 | # closed way 58 | if not splitends and isClosed(way): 59 | new_points[0] = way.points[left:-1] + new_points[0] 60 | else: 61 | new_points.append(way.points[left:]) 62 | # ~ print(len(way.points),[len(p) for p in new_points]) 63 | 64 | new_ways = [way, ] + [geom.Way() for i in range(len(new_points) - 1)] 65 | 66 | if way in features_map: 67 | way_tags = features_map[way].tags 68 | 69 | for new_way in new_ways: 70 | if new_way != way: 71 | feat = geom.Feature() 72 | feat.geometry = new_way 73 | feat.tags = way_tags 74 | new_way.addparent(feat) 75 | 76 | for new_way, points in zip(new_ways, new_points): 77 | new_way.points = points 78 | if new_way.id != way.id: 79 | for point in points: 80 | point.removeparent(way, shoulddestroy=False) 81 | point.addparent(new_way) 82 | return new_ways 83 | 84 | 85 | def mergeIntoNewRelation(way_parts): 86 | new_relation = geom.Relation() 87 | feat = geom.Feature() 88 | feat.geometry = new_relation 89 | new_relation.members = [(way, "outer") for way in way_parts] 90 | for way in way_parts: 91 | way.addparent(new_relation) 92 | return feat 93 | 94 | 95 | def splitWayInRelation(rel, way_parts): 96 | way_roles = [m[1] for m in rel.members if m[0] == way_parts[0]] 97 | way_role = "" if len(way_roles) == 0 else way_roles[0] 98 | for way in way_parts[1:]: 99 | way.addparent(rel) 100 | rel.members.append((way, way_role)) 101 | 102 | 103 | def findSharedVertices(geometries): 104 | points = [g for g in geometries if isinstance(g, geom.Point)] 105 | vertices = list() 106 | for p in points: 107 | neighbors = set() 108 | for way in p.parents: 109 | for idx in findAll(way, p): 110 | for step in [-1, 1]: 111 | pt = way.points[(idx + step) % len(way.points)] 112 | if pt != p: 113 | neighbors.add(pt) 114 | if len(neighbors) > 2: 115 | vertices.append(p) 116 | return vertices 117 | 118 | 119 | def findSelfIntersections(way): 120 | intersections = list() 121 | seen = set() 122 | points = way.points 123 | if isClosed(way): 124 | points = points[:-1] 125 | for point in points: 126 | if point in seen: 127 | intersections.append(point) 128 | seen.add(point) 129 | return intersections 130 | 131 | 132 | def similar(way1, way2): 133 | if len(way1.points) != len(way2.points): 134 | return False 135 | w1 = [w.id for w in way1.points] 136 | w2 = [w.id for w in way2.points] 137 | if w1[0] not in w2: 138 | return False 139 | if set(w1) != set(w2): 140 | return False 141 | # closed way 142 | if w1[0] == w1[-1]: 143 | idx1 = w1.index(min(w1)) 144 | w1 = w1[idx1:-1] + w1[:idx1] 145 | if w2[0] == w2[-1]: 146 | idx2 = w2.index(min(w2)) 147 | w2 = w2[idx2:-1] + w2[:idx2] 148 | # second way is not closed 149 | else: 150 | return False 151 | if w1 == w2: 152 | return True 153 | if w1 == w2[:1] + w2[1:][::-1]: 154 | return True 155 | else: 156 | if w1 == w2: 157 | return True 158 | if w1 == w2[::-1]: 159 | return True 160 | return False 161 | 162 | 163 | def isClosed(way): 164 | return way.points[0] == way.points[-1] 165 | 166 | 167 | def findAll(way, node, start=0): 168 | i = start - 1 169 | while True: 170 | try: 171 | i = way.points.index(node, i + 1) 172 | yield i 173 | except ValueError: 174 | break 175 | 176 | 177 | def preOutputTransform(geometries, features): 178 | if geometries is None and features is None: 179 | return 180 | lint(geometries, features, "At entry", True) 181 | print("Patching features") 182 | for f in features: 183 | if f not in f.geometry.parents: 184 | f.geometry.addparent(f) 185 | lint(geometries, features, "After parent fix", True) 186 | print("Moving tags to relations") 187 | # move tags, remove member ways as Features. 188 | rels = [g for g in geometries if isinstance(g, geom.Relation)] 189 | featuresmap = {feature.geometry: feature for feature in features} 190 | for rel in rels: 191 | relfeat = featuresmap[rel] 192 | # splitWayInRelation does not add the relation as a parent. 193 | for member, role in rel.members: 194 | if rel not in member.parents: 195 | member.addparent(rel) 196 | if relfeat.tags == {}: 197 | outers = [m[0] for m in rel.members if m[1] == "outer"] 198 | relfeat.tags.update(featuresmap[outers[0]].tags) 199 | for member, role in rel.members: 200 | if member in featuresmap: 201 | memberfeature = featuresmap[member] 202 | del featuresmap[member] 203 | member.removeparent(memberfeature) 204 | features.remove(memberfeature) 205 | else: 206 | pass 207 | # ~ print("Relation {} has tags.".format(rel.id),relfeat.tags) 208 | # create relations for ways that are features. 209 | ways = [g for g in geometries if isinstance(g, geom.Way)] 210 | for way in ways: 211 | if way in featuresmap: 212 | feature = featuresmap[way] 213 | newrel = geom.Relation() 214 | way.addparent(newrel) 215 | newrel.members.append((way, "outer")) 216 | feature.replacejwithi(newrel, way) 217 | featuresmap[newrel] = feature 218 | del featuresmap[way] 219 | lint(geometries, features, "Before split") 220 | print("Finding shared vertices") 221 | corners = set(findSharedVertices(geometries)) 222 | print("Splitting ways") 223 | for way in ways: 224 | is_way_in_relation = len([p for p in way.parents if isinstance(p, geom.Relation)]) > 0 225 | thesecorners = corners.intersection(way.points) 226 | # ~ if intersections: 227 | # ~ print(len(intersections)) 228 | if len(thesecorners) > 0: 229 | way_parts = splitWay(way, thesecorners, featuresmap) 230 | if not is_way_in_relation: 231 | rel = mergeIntoNewRelation(way_parts) 232 | featuresmap[rel.geometry] = rel 233 | if way in featuresmap: 234 | rel.tags.update(featuresmap[way].tags) 235 | for wg, role in rel.geometry.members: 236 | if wg in featuresmap: 237 | wg.removeparent(featuresmap[wg]) 238 | else: 239 | for parent in way.parents: 240 | if isinstance(parent, geom.Relation): 241 | splitWayInRelation(parent, way_parts) 242 | lint(geometries, features, "After split") 243 | print("Merging relations") 244 | worklist = sorted([g for g in geometries if isinstance(g, geom.Way)], key=lambda g: len(g.points)) 245 | # combine duplicate ways. 246 | removed = list() 247 | comparisons = 0 248 | for i, way in enumerate(list(worklist)): 249 | if i % 1000 == 0: print(i, len(list(worklist))) 250 | # skip ways that are already gone 251 | worklist.remove(way) 252 | if way in removed: 253 | continue 254 | for otherway in worklist: 255 | if len(otherway.points) > len(way.points): 256 | break 257 | comparisons += 1 258 | if similar(way, otherway): 259 | for parent in list(otherway.parents): 260 | if isinstance(parent, geom.Relation): 261 | parent.replacejwithi(way, otherway) 262 | removed.append(otherway) 263 | print("Comparisons:", comparisons) 264 | # ~ # results in duplicates 265 | # ~ worklist = [g for g in geometries if isinstance(g, geom.Way)] 266 | # ~ for way in worklist: 267 | # ~ # similar ways must share first point 268 | # ~ for otherway in way.points[0].parents: 269 | # ~ # skip self and ways that are already merged 270 | # ~ if otherway==way or way in removed: 271 | # ~ continue 272 | # ~ \ if similar(way,otherway): 273 | # ~ for parent in list(otherway.parents): 274 | # ~ if isinstance(parent, geom.Relation): 275 | # ~ parent.replacejwithi(way, otherway) 276 | # ~ removed.append(otherway) 277 | 278 | # merge adjacent ways 279 | # ~ ways = [g for g in geometries if isinstance(g, geom.Way)] 280 | # ~ junctions=set() 281 | # ~ for way in ways: 282 | # ~ for point in [way.points[0],way.points[-1]]: 283 | # ~ if len(point.parents) == 2: 284 | # ~ junctions.add(point) 285 | # ~ print(len(junctions)) 286 | # ~ c=0 287 | # ~ for j in junctions: 288 | # ~ for p in j.parents: 289 | # ~ for p2 in p.parents: 290 | # ~ for p3 in p2.parents: 291 | # ~ print(j.id,p3.tags["name"],len(p.points)) 292 | # ~ if c==10: 293 | # ~ break 294 | # ~ c+=1 295 | # add tags to all ways 296 | print("Tagging member ways") 297 | ways = [g for g in geometries if isinstance(g, geom.Way)] 298 | featuresmap = {feature.geometry: feature for feature in features} 299 | for way in ways: 300 | level9ids = [] 301 | for parent in way.parents: 302 | admin_levels = [] 303 | boundaries = [] 304 | if parent in featuresmap: 305 | parfeat = featuresmap[parent] 306 | if "admin_level" in parfeat.tags: 307 | admin_levels.append(parfeat.tags["admin_level"]) 308 | if "boundary" in parfeat.tags: 309 | boundaries.append(parfeat.tags["boundary"]) 310 | level9ids.append(parfeat.tags['level9_id']) 311 | newtags = {} 312 | if admin_levels: 313 | newtags["admin_level"] = min(admin_levels, key=int) 314 | if boundaries: 315 | newtags["boundary"] = boundaries.pop() 316 | newtags['level9_id'] = ','.join(level9ids) 317 | if newtags: 318 | if way not in featuresmap: 319 | feat = geom.Feature() 320 | feat.geometry = way 321 | way.addparent(feat) 322 | else: 323 | feat = featuresmap[way] 324 | feat.tags.update(newtags) 325 | lint(geometries, features, "After combine.") 326 | for feat in features: 327 | if isinstance(feat.geometry, geom.Relation): 328 | feat.tags["type"] = "boundary" 329 | 330 | 331 | def lint(geometries, features, message="", blat=False): 332 | if False: 333 | return 334 | ways = [g for g in geometries if isinstance(g, geom.Way)] 335 | rels = [g for g in geometries if isinstance(g, geom.Relation)] 336 | results = list() 337 | # check for geometries with no parents. 338 | noparents = list() 339 | results.append(("{} geometries with no parents.", noparents)) 340 | for geo in geometries: 341 | if len(geo.parents) == 0: 342 | noparents.append(geo) 343 | # check for features not listed as parents 344 | notlisted = list() 345 | results.append(("{} features not used as parents.", notlisted)) 346 | for f in features: 347 | if f not in f.geometry.parents: 348 | notlisted.append(f) 349 | # check for duplicate nodes in ways 350 | dupenodes = list() 351 | results.append(("{} duplicate nodes in ways.", dupenodes)) 352 | onenodeways = list() 353 | results.append(("{} one node ways.", onenodeways)) 354 | count = 0 355 | for way in ways: 356 | for i in range(1, len(way.points)): 357 | if way.points[i - 1] == way.points[i]: 358 | dupenodes.append(way, i) 359 | count += 1 360 | if len(way.points) == 1: 361 | onenodeways.append(way) 362 | count += 1 363 | if message and any(result[1] for result in results): 364 | print(message) 365 | for msg, result in results: 366 | if result: 367 | print(msg.format(len(result))) 368 | if blat: 369 | for p in result: 370 | print(p) 371 | -------------------------------------------------------------------------------- /conflate.py: -------------------------------------------------------------------------------- 1 | import math 2 | import os 3 | import pickle 4 | import sys 5 | import time 6 | import xml.etree.ElementTree as ET 7 | from pathlib import Path 8 | 9 | import matplotlib.pyplot as plt 10 | import overpy 11 | import pyproj 12 | import shapely.geometry as geometry 13 | import yaml 14 | from osmapi import OsmApi 15 | from shapely.ops import linemerge 16 | 17 | from atomic_write import atomic_write 18 | from common import retry_on_error 19 | from processing_state import ProcessingState 20 | 21 | 22 | def load_osm(path): 23 | nodes = {} 24 | ways = {} 25 | relations = {} 26 | root = ET.parse(path).getroot() 27 | for node in root.findall('node'): 28 | nodes[int(node.attrib['id'])] = { 29 | 'lat': float(node.attrib['lat']), 30 | 'lon': float(node.attrib['lon']) 31 | } 32 | 33 | for way in root.findall('way'): 34 | way_nodes = [] 35 | for child in way.iter('nd'): 36 | way_nodes.append(int(child.attrib['ref'])) 37 | ways[int(way.attrib['id'])] = { 38 | 'nodes': way_nodes, 39 | 'relations': '', 40 | 'processed': ProcessingState.NO, 41 | 'error_context': None, 42 | 'osm_way': None 43 | } 44 | 45 | for relation in root.findall('relation'): 46 | relation_ways = [] 47 | for child in relation.iter('member'): 48 | relation_ways.append( 49 | { 50 | 'ref': int(child.attrib['ref']), 51 | 'role': child.attrib['role'], 52 | 'type': child.attrib['type'] 53 | }) 54 | tags = {} 55 | for child in relation.iter('tag'): 56 | tags[child.attrib['k']] = child.attrib['v'] 57 | relations[int(relation.attrib['id'])] = { 58 | 'ways': relation_ways, 59 | 'tags': tags 60 | } 61 | 62 | return {'relations': relations, 'ways': ways, 'nodes': nodes} 63 | 64 | 65 | @retry_on_error() 66 | def get_osm_shared_ways(api, r1, r2, country, id_key): 67 | response = api.query(f""" 68 | area["name"="{country}"]["admin_level"=2]->.a; 69 | relation(area.a)["boundary"="administrative"]["admin_level"=9]["{id_key}"="{r1}"]->.firstRelation; 70 | relation(area.a)["boundary"="administrative"]["admin_level"=9]["{id_key}"="{r2}"]->.secondRelation; 71 | (.firstRelation;>;)->.a1; 72 | (.secondRelation;>;)->.a2; 73 | (.a1;- .a2;)->.a3; 74 | (.a1;- .a3;)->.a4; 75 | way.a4; 76 | (._;>;); 77 | out; 78 | // &contact=https://github.com/stalker314314/osm-admin-boundary-conflation/ 79 | """) 80 | return response 81 | 82 | 83 | @retry_on_error() 84 | def get_osm_single_way(api, r1, country, id_key): 85 | response = api.query(f""" 86 | area["name"="{country}"]["admin_level"=2]->.a; 87 | relation(area.a)["boundary"="administrative"]["admin_level"=9]["{id_key}"="{r1}"]->.firstRelation; 88 | relation(area.a)["boundary"="administrative"]["admin_level"=9]["{id_key}"!="{r1}"]->.secondRelation; 89 | (.firstRelation ;>;) -> .a1; 90 | (.secondRelation;>;) -> .a2; 91 | (way.a1;- way.a2;) -> .a3; 92 | way.a3; 93 | (._;>;); 94 | out; 95 | // &contact=https://github.com/stalker314314/osm-admin-boundary-conflation/ 96 | """) 97 | return response 98 | 99 | 100 | @retry_on_error() 101 | def get_entities_shared_with_way(api, way_id): 102 | response = api.query(""" 103 | way({0}); 104 | ._;>; 105 | ._;<; 106 | out; 107 | // &contact=https://github.com/stalker314314/osm-admin-boundary-conflation/ 108 | """.format(way_id)) 109 | return response 110 | 111 | 112 | def create_geometry_from_osm_way(way): 113 | # Try to build shapely polygon out of this data 114 | lss = [] 115 | ls_coords = [] 116 | for node in way.nodes: 117 | ls_coords.append((node.lon, node.lat)) 118 | lss.append(geometry.LineString(ls_coords)) 119 | 120 | merged = linemerge([*lss]) 121 | return merged 122 | 123 | 124 | def create_geometry_from_osm_file_data(source_data, way): 125 | # Try to build shapely polygon out of .osm data 126 | lss = [] 127 | ls_coords = [] 128 | for node_id in way['nodes']: 129 | node = source_data['nodes'][node_id] 130 | ls_coords.append((node['lon'], node['lat'])) 131 | lss.append(geometry.LineString(ls_coords)) 132 | 133 | merged = linemerge([*lss]) 134 | return merged 135 | 136 | 137 | def unglue_ways(config, osmapi, way_boundary_id, way_other_id): 138 | """ 139 | Given admin boundary way and other way that shares some nodes with it, unglues those shared nodes into separate ones 140 | It adds new node and changes boundary to remove shared one and adds new one at the same place. 141 | It will not unglue endpoints 142 | """ 143 | auto_proceed = config['auto_proceed'] 144 | 145 | way_boundary = osmapi.WayGet(way_boundary_id) 146 | way_other = osmapi.WayGet(way_other_id) 147 | if len(way_other['tag']) == 0 or len(way_boundary['tag']) == 0: 148 | print('One of glued ways do not have any tag. This might be boundary in disguise, skipping') 149 | return False 150 | shared_nodes = set(way_boundary['nd']) & set(way_other['nd']) 151 | before_removing_endpoints = len(shared_nodes) 152 | if way_boundary['nd'][0] in shared_nodes: 153 | shared_nodes.remove(way_boundary['nd'][0]) 154 | if way_boundary['nd'][-1] in shared_nodes: 155 | shared_nodes.remove(way_boundary['nd'][-1]) 156 | 157 | if len(shared_nodes) == 0: 158 | if before_removing_endpoints > 0: 159 | print('There are glued nodes, but they are endpoints and script will not unglue them') 160 | return False 161 | 162 | print('{0} nodes will be unglued from boundary https://www.openstreetmap.org/way/{1} and way ' 163 | 'https://www.openstreetmap.org/way/{2}'.format(len(shared_nodes), way_boundary_id, way_other_id)) 164 | if len(shared_nodes) > 0 and not auto_proceed: 165 | proceed = input('Proceed (Y/n)') 166 | if not (proceed == '' or proceed.lower() == 'y' or proceed.lower() == u'з'): 167 | return False 168 | 169 | done_any = False 170 | i = 1 171 | for shared_node in shared_nodes: 172 | node = osmapi.NodeGet(shared_node) 173 | if len(node['tag']) > 0: 174 | print('Node to be unglued has tags, skipping') 175 | continue 176 | added_node = {'id': -i, 'lon': node['lon'], 'lat': node['lat'], 'tag': {}} 177 | i = i + 1 178 | osmapi.NodeCreate(added_node) 179 | index = way_boundary['nd'].index(shared_node) 180 | del way_boundary['nd'][index] 181 | way_boundary['nd'].insert(index, added_node['id']) 182 | done_any = True 183 | if done_any: 184 | osmapi.WayUpdate(way_boundary) 185 | osmapi.flush() 186 | return True 187 | else: 188 | return False 189 | 190 | 191 | def is_conflate_possible(config, osmapi, overpass_api, shapely_source_way, found_osm_way, shapely_found_osm_way): 192 | # Check if source or targets are not huge (we need this as we want to put conflation of way in a single changeset) 193 | assert len(shapely_source_way.coords) < 3000 194 | assert len(shapely_found_osm_way.coords) < 2000 195 | 196 | unglue_ways_as_needed = config['unglue_ways_as_needed'] 197 | max_distance_end_points_to_consider_in_meters = config['max_distance_end_points_to_consider_in_meters'] 198 | 199 | # Check if way is not national border 200 | if 'admin_level' in found_osm_way.tags and int(found_osm_way.tags['admin_level']) <= 2: 201 | print('Shared way is national border, skipping') 202 | return ProcessingState.ERROR_NATIONAL_BORDER, None 203 | 204 | # Check if way in OSM do not have any tags 205 | for tag in found_osm_way.tags: 206 | if tag in ('admin_level', 'boundary', 'note', 'source', 'fixme', 'type', 'int_name'): 207 | continue 208 | if tag.startswith('name'): 209 | continue 210 | print('Found unexpected tag {0} in way to conflate, skipping'.format(tag)) 211 | return ProcessingState.ERROR_UNEXPECTED_TAG, tag 212 | 213 | # Check if nodes in way don't belong to any other way or relation 214 | response = get_entities_shared_with_way(overpass_api, found_osm_way.id) 215 | for way in response.ways: 216 | if 'admin_level' in way.tags and int(way.tags['admin_level']) <= 2: 217 | print(f'Way to conflate contains node which is also part of way https://www.openstreetmap.org/way/{way.id} which is national border, skipping') 218 | return ProcessingState.ERROR_NODE_IN_NATIONAL_BORDER, str(way.id) 219 | if 'boundary' not in way.tags: 220 | print(f'Way to conflate contains node which is also part of way https://www.openstreetmap.org/way/{way.id} which do not have boundary tag, skipping') 221 | if unglue_ways_as_needed: 222 | one_way = unglue_ways(config, osmapi, found_osm_way.id, way.id) 223 | if not one_way: 224 | other_way = unglue_ways(config, osmapi, way.id, found_osm_way.id) 225 | if not other_way: 226 | return ProcessingState.ERROR_NODE_IN_OTHER_WAYS, str(way.id) 227 | else: 228 | return ProcessingState.ERROR_NODE_IN_OTHER_WAYS, str(way.id) 229 | elif way.tags['boundary'] != 'administrative': 230 | print(f'Way to conflate contains node which is also part of way https://www.openstreetmap.org/way/{way.id} which boundary tag != administrative, skipping') 231 | if unglue_ways_as_needed: 232 | one_way = unglue_ways(config, osmapi, found_osm_way.id, way.id) 233 | if not one_way: 234 | other_way = unglue_ways(config, osmapi, way.id, found_osm_way.id) 235 | if not other_way: 236 | return ProcessingState.ERROR_NODE_IN_OTHER_WAYS, str(way.id) 237 | else: 238 | return ProcessingState.ERROR_NODE_IN_OTHER_WAYS, str(way.id) 239 | for relation in response.relations: 240 | is_city = 'place' in relation.tags and relation.tags['place'] == 'city' 241 | if 'admin_level' not in relation.tags: 242 | if not is_city: 243 | print(f'Way to conflate belongs to relation https://www.openstreetmap.org/relation/{relation.id} which do not have admin_level tag, skipping') 244 | return ProcessingState.ERROR_NODE_IN_OTHER_RELATION, str(relation.id) 245 | elif int(relation.tags['admin_level']) <= 2: 246 | print(f'Way to conflate belongs to relation https://www.openstreetmap.org/relation/{relation.id} which is national border, skipping') 247 | return ProcessingState.ERROR_NODE_IN_NATIONAL_RELATION, str(relation.id) 248 | if 'type' not in relation.tags: 249 | print(f'Way to conflate belongs to relation https://www.openstreetmap.org/relation/{relation.id} which do not have type tag, skipping') 250 | return ProcessingState.ERROR_NODE_IN_OTHER_RELATION, str(relation.id) 251 | elif relation.tags['type'] != 'boundary' and not is_city: 252 | print(f'Way to conflate belongs to relation https://www.openstreetmap.org/relation/{relation.id} where type != boundary, skipping') 253 | return ProcessingState.ERROR_NODE_IN_OTHER_RELATION, str(relation.id) 254 | if 'boundary' not in relation.tags: 255 | if not is_city: 256 | print(f'Way to conflate belongs to relation https://www.openstreetmap.org/relation/{relation.id} which do not have boundary tag, skipping') 257 | return ProcessingState.ERROR_NODE_IN_OTHER_RELATION, str(relation.id) 258 | elif relation.tags['boundary'] != 'administrative' and relation.tags['boundary'] != 'census': 259 | print(f'Way to conflate belongs to relation https://www.openstreetmap.org/relation/{relation.id} where boundary != administrative or census, skipping') 260 | return ProcessingState.ERROR_NODE_IN_OTHER_RELATION, str(relation.id) 261 | 262 | # Check if nodes on way in OSM are not having any tags 263 | nodes_with_tags = [n for n in found_osm_way.nodes if len(n.tags) > 0 and not (len(n.tags) == 1 and 'created_by' in n.tags)] 264 | if len(nodes_with_tags) > 0: 265 | return ProcessingState.ERROR_NODES_WITH_TAGS, ','.join([str(n.id) for n in nodes_with_tags]) 266 | 267 | # Check if end points are close enough 268 | distance, should_reverse = get_bigger_endpoint_difference(shapely_source_way, shapely_found_osm_way) 269 | if distance > max_distance_end_points_to_consider_in_meters: 270 | print(f'End points of ways to conflate are different for more that {max_distance_end_points_to_consider_in_meters}m ({distance}m), skipping') 271 | return ProcessingState.ERROR_END_POINTS_FAR_APART, str(distance) 272 | if should_reverse: 273 | shapely_source_way.coords = list(shapely_source_way.coords[::-1]) 274 | 275 | return ProcessingState.CHECKED_POSSIBLE, None 276 | 277 | 278 | def get_bigger_endpoint_difference(shapely_source_way, shapely_found_osm_way): 279 | should_reverse = False 280 | geod = pyproj.Geod(ellps='WGS84') 281 | _, _, distance11 = geod.inv(shapely_found_osm_way.coords[0][0], shapely_found_osm_way.coords[0][1], 282 | shapely_source_way.coords[0][0], shapely_source_way.coords[0][1]) 283 | _, _, distance12 = geod.inv(shapely_found_osm_way.coords[0][0], shapely_found_osm_way.coords[0][1], 284 | shapely_source_way.coords[-1][0], shapely_source_way.coords[-1][1]) 285 | if distance12 < distance11: 286 | should_reverse = True 287 | distance1 = min(distance11, distance12) 288 | if should_reverse: 289 | _, _, distance2 = geod.inv(shapely_found_osm_way.coords[-1][0], shapely_found_osm_way.coords[-1][1], 290 | shapely_source_way.coords[0][0], shapely_source_way.coords[0][1]) 291 | else: 292 | _, _, distance2 = geod.inv(shapely_found_osm_way.coords[-1][0], shapely_found_osm_way.coords[-1][1], 293 | shapely_source_way.coords[-1][0], shapely_source_way.coords[-1][1]) 294 | return max(distance1, distance2), should_reverse 295 | 296 | 297 | def is_same_geometry(shapely_source_way, shapely_found_osm_way): 298 | if shapely_source_way.is_closed != shapely_found_osm_way.is_closed: 299 | return False 300 | if shapely_source_way.is_ring != shapely_found_osm_way.is_ring: 301 | return False 302 | if len(shapely_source_way.coords) != len(shapely_found_osm_way.coords): 303 | return False 304 | # Check distance of endpoints and figure out if ways should be reversed 305 | distance, should_reverse = get_bigger_endpoint_difference(shapely_source_way, shapely_found_osm_way) 306 | if distance > 1: 307 | return False 308 | if should_reverse: 309 | shapely_source_way.coords = list(shapely_source_way.coords[::-1]) 310 | # Go for each node and check distance 311 | geod = pyproj.Geod(ellps='WGS84') 312 | for p1, p2 in zip(shapely_source_way.coords, shapely_found_osm_way.coords): 313 | _, _, distance = geod.inv(p1[0], p1[1], p2[0], p2[1]) 314 | if distance > 1: 315 | return False 316 | return True 317 | 318 | 319 | def calculate_initial_compass_bearing(pointA, pointB): 320 | """ 321 | Calculates the bearing between two points. 322 | The formulae used is the following: 323 | θ = atan2(sin(Δlong).cos(lat2), 324 | cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong)) 325 | :Parameters: 326 | - `pointA: The tuple representing the latitude/longitude for the 327 | first point. Latitude and longitude must be in decimal degrees 328 | - `pointB: The tuple representing the latitude/longitude for the 329 | second point. Latitude and longitude must be in decimal degrees 330 | :Returns: 331 | The bearing in degrees 332 | :Returns Type: 333 | float 334 | """ 335 | if (type(pointA) != tuple) or (type(pointB) != tuple): 336 | raise TypeError("Only tuples are supported as arguments") 337 | 338 | lat1 = math.radians(pointA[0]) 339 | lat2 = math.radians(pointB[0]) 340 | 341 | diffLong = math.radians(pointB[1] - pointA[1]) 342 | 343 | x = math.sin(diffLong) * math.cos(lat2) 344 | y = math.cos(lat1) * math.sin(lat2) - (math.sin(lat1) 345 | * math.cos(lat2) * math.cos(diffLong)) 346 | 347 | initial_bearing = math.atan2(x, y) 348 | 349 | # Now we have the initial bearing but math.atan2 return values 350 | # from -180° to + 180° which is not what we want for a compass bearing 351 | # The solution is to normalize the initial bearing as shown below 352 | initial_bearing = math.degrees(initial_bearing) 353 | compass_bearing = (initial_bearing + 360) % 360 354 | 355 | return compass_bearing 356 | 357 | 358 | def conflate_way(config, osmapi, overpass_api, source_data, source_way, found_osm_way): 359 | auto_proceed = config['auto_proceed'] 360 | dry_run = config['dry_run'] 361 | 362 | shapely_found_osm_way = create_geometry_from_osm_way(found_osm_way) 363 | shapely_source_way = create_geometry_from_osm_file_data(source_data, source_way) 364 | 365 | if len(source_way['nodes']) >= 2000: 366 | # OSM does not support this many nodes in way, human will need to simplify this 367 | print('Way has too many nodes ({0}) and 2000 is allowed'.format(len(source_way['nodes']))) 368 | return ProcessingState.ERROR_TOO_MANY_NODES, None 369 | 370 | if not shapely_found_osm_way.is_valid or not shapely_source_way.is_valid: 371 | print('Shape is invalid, skipping') 372 | return ProcessingState.ERROR_INVALID_SHAPE, None 373 | if shapely_found_osm_way.is_closed or shapely_found_osm_way.is_ring or \ 374 | shapely_source_way.is_closed or shapely_source_way.is_ring: 375 | print('Shape is closed loop, cannot handle it, skipping') 376 | return ProcessingState.ERROR_CLOSED_SHAPE, None 377 | 378 | if is_same_geometry(shapely_source_way, shapely_found_osm_way): 379 | print('Way to conflate seems already conflated, skipping') 380 | return ProcessingState.CONFLATED, None 381 | is_conflate_possible_error, error_context = is_conflate_possible(config, osmapi, overpass_api, shapely_source_way, 382 | found_osm_way, shapely_found_osm_way) 383 | if is_conflate_possible_error != ProcessingState.CHECKED_POSSIBLE: 384 | return is_conflate_possible_error, error_context 385 | 386 | # Do basic check that can cut off lot of already-almost conflated ways 387 | # Shapes are same if inflated way can fit inside other way and if angle (in degrees) of end points is less than 5 degree 388 | almost_same_ways = shapely_source_way.within(shapely_found_osm_way.buffer(0.005)) 389 | angle1 = calculate_initial_compass_bearing(shapely_found_osm_way.coords[0], shapely_found_osm_way.coords[-1]) 390 | angle2 = calculate_initial_compass_bearing(shapely_source_way.coords[0], shapely_source_way.coords[-1]) 391 | heuristically_same = almost_same_ways and math.fabs(angle1-angle2) < 5 392 | if not heuristically_same: 393 | if not auto_proceed: 394 | # # TODO: use something better, like https://stackoverflow.com/questions/56448933/plotting-shapely-polygon-on-cartopy 395 | plt.figure() 396 | plt.plot(*shapely_found_osm_way.coords.xy, color='red') 397 | plt.plot(*shapely_source_way.coords.xy, color='green') 398 | plt.show() 399 | plt.pause(1) 400 | 401 | proceed = input('Does these shapes match? (Y/n)') 402 | if not (proceed == '' or proceed.lower() == 'y' or proceed.lower() == u'з'): 403 | return ProcessingState.ERROR_GEOMETRY_WRONG, None 404 | else: 405 | print('Detected almost same ways, skipping human check') 406 | 407 | osm_way_nodes_to_conflate = osmapi.WayFull(found_osm_way.id) 408 | osm_way_to_conflate = osmapi.WayGet(found_osm_way.id) 409 | nodes_to_delete = [] 410 | assert len(osm_way_nodes_to_conflate) == len(osm_way_to_conflate['nd']) + 1 411 | for i in range(len(osm_way_to_conflate['nd'])-1): 412 | # since we are in-place modifying this list, we need to offset it by this much, 413 | # this is why we substract len of nodes_to_delete 414 | node_id_to_conflate = osm_way_to_conflate['nd'][i-len(nodes_to_delete)] 415 | node_to_conflate = next(n['data'] for n in osm_way_nodes_to_conflate if n['data']['id'] == node_id_to_conflate) 416 | if i < len(shapely_source_way.coords) - 1: 417 | geod = pyproj.Geod(ellps='WGS84') 418 | _, _, distance = geod.inv(node_to_conflate['lon'], node_to_conflate['lat'], 419 | shapely_source_way.coords[i][0], shapely_source_way.coords[i][1]) 420 | node_to_conflate['lon'] = shapely_source_way.coords[i][0] 421 | node_to_conflate['lat'] = shapely_source_way.coords[i][1] 422 | if not dry_run: 423 | osmapi.NodeUpdate(node_to_conflate) 424 | else: 425 | nodes_to_delete.append(node_to_conflate) 426 | osm_way_to_conflate['nd'].remove(node_to_conflate['id']) 427 | for i in range(len(osm_way_to_conflate['nd'])-1, len(shapely_source_way.coords) - 1): 428 | added_node = {'id': -i, 'lon': shapely_source_way.coords[i][0], 'lat': shapely_source_way.coords[i][1], 'tag': {}} 429 | if not dry_run: 430 | osmapi.NodeCreate(added_node) 431 | osm_way_to_conflate['nd'].insert(-1, added_node['id']) 432 | # Fix last node 433 | last_node_id = osm_way_to_conflate['nd'][-1] 434 | last_node_to_conflate = next(n['data'] for n in osm_way_nodes_to_conflate if n['data']['id'] == last_node_id) 435 | _, _, distance = geod.inv(last_node_to_conflate['lon'], last_node_to_conflate['lat'], 436 | shapely_source_way.coords[-1][0], shapely_source_way.coords[-1][1]) 437 | 438 | last_node_to_conflate['lon'] = shapely_source_way.coords[-1][0] 439 | last_node_to_conflate['lat'] = shapely_source_way.coords[-1][1] 440 | if not dry_run: 441 | osmapi.NodeUpdate(last_node_to_conflate) 442 | 443 | if not dry_run: 444 | osmapi.WayUpdate(osm_way_to_conflate) 445 | # Deleting nodes needs to happen after we update way 446 | for node_to_delete in nodes_to_delete: 447 | osmapi.NodeDelete(node_to_delete) 448 | osmapi.flush() 449 | time.sleep(5) 450 | return ProcessingState.CONFLATED, None 451 | else: 452 | return ProcessingState.CHECKED_POSSIBLE, None 453 | 454 | 455 | def main(input_osm_file, progress_file): 456 | with open('config.yml', 'r') as config_yml_file: 457 | config = yaml.safe_load(config_yml_file) 458 | 459 | overpass_api = overpy.Overpass(url=config['overpass_url']) 460 | auto_proceed = config['auto_proceed'] 461 | country = config['country'] 462 | level9_ref_key = config['level9_ref_key'] 463 | 464 | osmapi = OsmApi(passwordfile='osm-password', 465 | changesetauto=True, 466 | changesetautosize=10000, changesetautotags= 467 | { 468 | u"comment": config['changeset_comment'], 469 | u"tag": u"mechanical=yes", u"source": config['changeset_source'] 470 | }) 471 | 472 | if not os.path.isfile(progress_file): 473 | print(f'Cannot find {progress_file}, starting from scratch') 474 | source_data = load_osm(input_osm_file) 475 | print(f'Loaded .osm file {input_osm_file}') 476 | Path(progress_file).touch() # need to touch file for atomic writes later 477 | else: 478 | with open(progress_file, 'rb') as p: 479 | source_data = pickle.load(p) 480 | 481 | # Iterate for each way in .osm 482 | count_processed = 0 483 | for way_id, way in sorted(source_data['ways'].items(), key=lambda x: x[0], reverse=True): 484 | count_processed = count_processed + 1 485 | print('Processing {0}/{1}'.format(count_processed, len(source_data['ways']))) 486 | if way['processed'] != ProcessingState.NO: 487 | continue 488 | # Find relations this way is part of 489 | relations = [] 490 | for relation_id, relation in source_data['relations'].items(): 491 | ways = [w for w in relation['ways'] if w['ref'] == way_id] 492 | assert len(ways) <= 1 493 | if len(ways) == 1: 494 | relations.append(relation) 495 | assert len(relations) > 0 496 | if len(relations) == 2: 497 | relation_text = "{0} (ref: {1}) - {2} (ref: {3})".format( 498 | relations[0]['tags']['name'], relations[0]['tags']['level9_id'], 499 | relations[1]['tags']['name'], relations[1]['tags']['level9_id']) 500 | elif len(relations) == 1: 501 | relation_text = "{0} (ref: {1})".format( 502 | relations[0]['tags']['name'], relations[0]['tags']['level9_id']) 503 | elif len(relations) == 3: 504 | relation_text = "{0} (ref: {1}) - {2} (ref: {3}) - {4} (ref: {5})".format( 505 | relations[0]['tags']['name'], relations[0]['tags']['level9_id'], 506 | relations[1]['tags']['name'], relations[1]['tags']['level9_id'], 507 | relations[2]['tags']['name'], relations[2]['tags']['level9_id']) 508 | way['relations'] = relation_text 509 | 510 | # If way is shared between two relations, we try to find it in OSM using that information, 511 | # Otherwise, if it is part of just one relation, we try to find it in OSM with that. 512 | if len(relations) == 2: 513 | settlement0_id = relations[0]['tags']['level9_id'] 514 | settlement1_id = relations[1]['tags']['level9_id'] 515 | osm_response = get_osm_shared_ways(overpass_api, settlement0_id, settlement1_id, country, level9_ref_key) 516 | if len(osm_response.ways) == 0: 517 | print('Cannot find shared way in OSM between settlements {0} (ref: {1}) and {2} (ref: {3}), skipping'. 518 | format(relations[0]['tags']['name'], settlement0_id, 519 | relations[1]['tags']['name'], settlement1_id)) 520 | way['processed'] = ProcessingState.ERROR_SHARED_WAY_NOT_FOUND 521 | way['error_context'] = None 522 | elif len(osm_response.ways) > 1: 523 | print('More than 1 shared way in OSM between settlements {0} (ref: {1}) and {2} (ref: {3}), ' 524 | 'fix by merging ways manually, skipping'. 525 | format(relations[0]['tags']['name'], settlement0_id, 526 | relations[1]['tags']['name'], settlement1_id)) 527 | way['processed'] = ProcessingState.ERROR_MULTIPLE_SHARED_WAYS 528 | way['error_context'] = ','.join([str(w.id) for w in osm_response.ways]) 529 | else: 530 | print('Processing way https://www.openstreetmap.org/way/{0} shared between {1} and {2}'.format( 531 | osm_response.ways[0].id, relations[0]['tags']['name'], relations[1]['tags']['name'])) 532 | processed, error_context = conflate_way(config, osmapi, overpass_api, source_data, way, osm_response.ways[0]) 533 | way['processed'] = processed 534 | way['osm_way'] = osm_response.ways[0].id 535 | way['error_context'] = error_context 536 | elif len(relations) == 1: 537 | settlement_id = relations[0]['tags']['level9_id'] 538 | osm_response = get_osm_single_way(overpass_api, settlement_id, country, level9_ref_key) 539 | if len(osm_response.ways) == 0: 540 | print('Cannot find way in OSM that belongs only to settlement {0} (ref: {1}), skipping'. 541 | format(relations[0]['tags']['name'], settlement_id)) 542 | way['processed'] = ProcessingState.ERROR_WAY_NOT_FOUND 543 | way['error_context'] = None 544 | elif len(osm_response.ways) > 1: 545 | print('More than 1 way in OSM that belongs only to settlement {0} (ref: {1}), ' 546 | 'fix by merging ways manually, skipping'.format( 547 | relations[0]['tags']['name'], settlement_id)) 548 | way['processed'] = ProcessingState.ERROR_MULTIPLE_SINGLE_WAY 549 | way['error_context'] = ','.join([str(w.id) for w in osm_response.ways]) 550 | else: 551 | print('Processing way https://www.openstreetmap.org/way/{0} belonging only to {1}'.format( 552 | osm_response.ways[0].id, relations[0]['tags']['name'])) 553 | processed, error_context = conflate_way(config, osmapi, overpass_api, source_data, way, osm_response.ways[0]) 554 | way['processed'] = processed 555 | way['osm_way'] = osm_response.ways[0].id 556 | way['error_context'] = error_context 557 | elif len(relations) > 2: 558 | way['processed'] = ProcessingState.ERROR_OVERLAPPING_WAYS 559 | way['osm_way'] = None 560 | way['error_context'] = None 561 | 562 | # Dump current progress (use atomic_writes to guard for semi-written files as those pickle dumps can be huge) 563 | with atomic_write(progress_file, text=False, keep=False) as h: 564 | pickle.dump(source_data, h, protocol=pickle.DEFAULT_PROTOCOL) 565 | 566 | if not auto_proceed: 567 | proceed = input('Continue with next way? (Y/n)?') 568 | if proceed == '' or proceed.lower() == 'y' or proceed.lower() == u'з': 569 | continue 570 | break 571 | else: 572 | time.sleep(2) 573 | 574 | 575 | if __name__ == '__main__': 576 | if len(sys.argv) != 3: 577 | print("Usage: ./conflate.py ") 578 | exit() 579 | input_osm_file = sys.argv[1] 580 | progress_file = sys.argv[2] 581 | main(input_osm_file, progress_file) 582 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------