-
Notifications
You must be signed in to change notification settings - Fork 2
/
import_transnet_data.py
456 lines (385 loc) · 23.6 KB
/
import_transnet_data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
import ast
import json
import urllib
from datetime import date
from os import makedirs
from os import walk
from os.path import dirname
from os.path import exists
from os.path import join
from subprocess import call
import psycopg2
try:
conn = psycopg2.connect("dbname='gis' user='postgres' host='localhost' password=''")
cur = conn.cursor()
except:
print("I am unable to connect to the database")
exit()
base_dir = './data'
def download_large_relations(base_url, continent, country):
file_extensions = ['aa', 'ab', 'ac', 'ad', 'ae', 'af', 'ag', 'ah', 'ai', 'aj', 'ak']
for file_extension in file_extensions:
try:
urllib.URLopener().retrieve(
'{0}/{1}/{2}/_relations{3}'.format(base_url, continent, country, file_extension),
'{0}/relations/{1}/{2}/_relations{3}'.format(base_dir, continent, country, file_extension))
except IOError as e:
print('relations part {0} for {1} not found.'.format(file_extension, country))
try:
command = 'cat {0}/relations/{1}/{2}/_relations* > {0}/relations/{1}/{2}/relations.json ' \
'&& rm {0}/relations/{1}/{2}/_relations*'.format(base_dir, continent, country, )
call(command, shell=True)
except Exception as e:
print(e)
def download_latest_relation_files():
try:
base_url_transnet = 'https://raw.githubusercontent.com/OpenGridMap/transnet/master'
base_url_transnet_models = 'https://raw.githubusercontent.com/OpenGridMap/transnet-models/master'
# Download planet json to get the list of continent
planet_folder = '{0}/planet_json/'.format(base_dir)
if not exists(planet_folder):
makedirs(planet_folder)
print('Downloading planet config json')
urllib.URLopener().retrieve('{0}/app/meta/planet.json'.format(base_url_transnet),
'{0}/planet_json/planet.json'.format(base_dir))
query_country = '''INSERT INTO transnet_country(continent, country, voltages)
VALUES (%s, %s, %s);'''
cur.execute('''DELETE FROM transnet_country;''')
conn.commit()
# For each continent in the planet json, we should now download the continent json
# and then for each country in the continent download the relations file.
with open('{0}/planet_json/planet.json'.format(base_dir), 'r+') as planet_file:
continents = json.load(planet_file)
for continent in continents:
print('Downloading {0} config json'.format(continent))
urllib.URLopener().retrieve('{0}/app/meta/{1}.json'.format(base_url_transnet, continent),
'{0}/planet_json/{1}.json'.format(base_dir, continent))
with open('{0}/planet_json/{1}.json'.format(base_dir, continent), 'r+') as continent_file:
countries = json.load(continent_file)
for country in countries:
voltages = [try_parse_int(x) for x in countries[country]['voltages'].split('|')]
cur.execute(query_country, [continent, country, voltages])
conn.commit()
country_folder = '{0}/relations/{1}/{2}/'.format(base_dir, continent, country)
if not exists(country_folder):
makedirs(country_folder)
print('Downloading {0} relation json'.format(country))
try:
urllib.URLopener().retrieve(
'{0}/{1}/{2}/relations.json'.format(base_url_transnet_models, continent, country),
'{0}/relations/{1}/{2}/relations.json'.format(base_dir, continent, country))
except IOError as e:
print('relation for {0} not found.'.format(country))
download_large_relations(base_url_transnet_models, continent, country)
except Exception as e:
print(e)
def find_and_import_relation_files():
try:
cur.execute('''DELETE FROM transnet_relation_powerline;''')
cur.execute('''DELETE FROM transnet_relation_station ''')
cur.execute('''DELETE FROM transnet_powerline ''')
cur.execute('''DELETE FROM transnet_station ''')
cur.execute('''DELETE FROM transnet_relation ''')
conn.commit()
dirs = [x[0] for x in walk(join(dirname(__file__), '{0}/relations/'.format(base_dir)))]
for dir in dirs[1:]:
relation_path = '{0}/relations.json'.format(dir)
if exists(relation_path):
transnet_import_relations(relation_path)
else:
print('relations not exist {0}'.format(dir))
except Exception as e:
print(e)
def try_parse_int(string):
try:
return int(string)
except ValueError as e:
return 0
def transnet_add_last_update():
try:
cur.execute('''INSERT INTO transnet_stats(last_updated) VALUES (%s)''', [date.today()])
conn.commit()
except Exception as e:
print(e)
def transnet_delete_country(country):
cur.execute('''DELETE FROM transnet_relation_powerline WHERE country=%s;''', [country])
cur.execute('''DELETE FROM transnet_relation_station WHERE country=%s;''', [country])
cur.execute('''DELETE FROM transnet_powerline WHERE country=%s;''', [country])
cur.execute('''DELETE FROM transnet_station WHERE country=%s;''', [country])
cur.execute('''DELETE FROM transnet_relation WHERE country=%s;''', [country])
conn.commit()
def transnet_import_relations(json_file):
try:
country = json_file.split('/')[-2]
print('importing relations of {0}'.format(country))
query_relation = '''INSERT INTO transnet_relation(country, ref, name, voltage)
VALUES (%s, %s, %s, %s) RETURNING id'''
query_powerline = '''INSERT INTO transnet_powerline(country, geom, tags, raw_geom, voltage, type, nodes,
lat, lon, cables, name, length,
osm_id, srs_geom, osm_replication)
VALUES (%s, ST_FlipCoordinates(%s), %s , %s,%s, %s,
%s, %s,%s, %s, %s, %s
,%s ,ST_FlipCoordinates(%s), %s) RETURNING id'''
query_station = '''INSERT INTO transnet_station(country, geom, tags, raw_geom, lat, lon, name,
length, osm_id, voltage, type, osm_replication)
VALUES (%s, ST_FlipCoordinates(%s), %s, %s,%s
, %s, %s, %s,%s, %s, %s, %s) RETURNING id'''
query_relation_station = '''INSERT INTO transnet_relation_station(country, relation_id, station_id)
VALUES (%s, %s, %s)'''
query_relation_powerline = '''INSERT INTO transnet_relation_powerline(country, relation_id, powerline_id)
VALUES (%s, %s, %s)'''
query_powerline_count = '''SELECT count(id) FROM transnet_powerline WHERE osm_id = %s'''
query_station_count = '''SELECT count(id) FROM transnet_station WHERE osm_id = %s'''
query_powerline_get_one_id = '''SELECT id FROM transnet_powerline WHERE osm_id = %s LIMIT 1'''
query_station_get_one_id = '''SELECT id FROM transnet_station WHERE osm_id = %s LIMIT 1'''
query_powerline_increment_osm_rep = '''UPDATE transnet_powerline
SET osm_replication = osm_replication + 1 WHERE id = %s'''
query_station_increment_osm_rep = '''UPDATE transnet_station
SET osm_replication = osm_replication + 1 WHERE id = %s'''
powerline_tags = ['line', 'cable', 'minor_line']
station_tags = ['substation', 'station', 'sub_station', 'plant', 'generator']
with open(json_file, 'r+') as relations_file:
relations = json.load(relations_file)
for relation in relations:
cur.execute(query_relation, [country, relation['ref'], relation['name'], relation['voltage']])
relation_id = cur.fetchone()[0]
for member in relation['members']:
voltages = [try_parse_int(x) for x in member['voltage'].split(';')]
if member['type'] in powerline_tags:
cur.execute(query_powerline_count, [member['id']])
powerline_count = cur.fetchone()[0]
if powerline_count:
cur.execute(query_powerline_get_one_id, [member['id']])
powerline_id = cur.fetchone()[0]
cur.execute(query_powerline_increment_osm_rep, [powerline_id])
else:
tags_list = ast.literal_eval(member['tags'])
tags = json.dumps(dict(zip(tags_list[::2], tags_list[1::2])))
cur.execute(query_powerline, [country,
member['geom'],
tags,
member['raw_geom'],
voltages,
member['type'],
member['nodes'],
member['lat'],
member['lon'],
try_parse_int(member['cables']),
member['name'],
member['length'],
member['id'],
member['srs_geom'],
1])
powerline_id = cur.fetchone()[0]
cur.execute(query_relation_powerline, [country, relation_id, powerline_id])
elif member['type'] in station_tags:
cur.execute(query_station_count, [member['id']])
station_count = cur.fetchone()[0]
if station_count:
cur.execute(query_station_get_one_id, [member['id']])
station_id = cur.fetchone()[0]
cur.execute(query_station_increment_osm_rep, [station_id])
else:
tags_list = [x.replace('"', "").replace('\\', "") for x in
member['tags'].replace(',', '=>').split('=>')]
tags = json.dumps(dict(zip(tags_list[::2], tags_list[1::2])))
cur.execute(query_station, [country,
member['geom'],
tags,
member['raw_geom'],
member['lat'],
member['lon'],
member['name'],
member['length'],
member['id'],
voltages,
member['type'],
1])
station_id = cur.fetchone()[0]
cur.execute(query_relation_station, [country, relation_id, station_id])
conn.commit()
except Exception as e:
print(e)
def download_large_missing_line_data_files(base_url, continent, country):
file_extensions = ['aa', 'ab', 'ac', 'ad', 'ae', 'af', 'ag', 'ah', 'ai', 'aj', 'ak']
for file_extension in file_extensions:
try:
urllib.URLopener().retrieve(
'{0}/{1}/{2}/_lines_missing_data{3}'.format(base_url, continent, country, file_extension),
'{0}/missing_data/{1}/{2}/_lines_missing_data{3}'.format(base_dir, continent, country, file_extension))
except IOError as e:
print('lines part {0} for {1} not found.'.format(file_extension, country))
try:
command = 'cat {0}/missing_data/{1}/{2}/_lines_missing_data* > ' \
'{0}/missing_data/{1}/{2}/lines_missing_data.json ' \
'&& rm {0}/missing_data/{1}/{2}/_lines_missing_data*'.format(base_dir, continent, country, )
call(command, shell=True)
except Exception as e:
print(e)
def download_large_missing_station_data_files(base_url, continent, country):
file_extensions = ['aa', 'ab', 'ac', 'ad', 'ae', 'af', 'ag', 'ah', 'ai', 'aj', 'ak']
for file_extension in file_extensions:
try:
urllib.URLopener().retrieve(
'{0}/{1}/{2}/_stations_missing_data{3}'.format(base_url, continent, country, file_extension),
'{0}/missing_data/{1}/{2}/_stations_missing_data{3}'.format(base_dir, continent, country,
file_extension))
except IOError as e:
print('station missing data part {0} for {1} not found.'.format(file_extension, country))
try:
command = 'cat {0}/missing_data/{1}/{2}/_stations_missing_data* >' \
' {0}/missing_data/{1}/{2}/stations_missing_data.json ' \
'&& rm {0}/missing_data/{1}/{2}/_stations_missing_data*'.format(base_dir, continent, country, )
call(command, shell=True)
except Exception as e:
print(e)
def download_latest_missing_data_files():
try:
base_url_transnet_models = 'https://raw.githubusercontent.com/OpenGridMap/transnet-models/master'
# For every country we should download the missing data files.
with open('{0}/planet_json/planet.json'.format(base_dir), 'r+') as planet_file:
continents = json.load(planet_file)
for continent in continents:
with open('{0}/planet_json/{1}.json'.format(base_dir, continent), 'r+') as continent_file:
countries = json.load(continent_file)
for country in countries:
country_folder = '{0}/missing_data/{1}/{2}/'.format(base_dir, continent, country)
if not exists(country_folder):
makedirs(country_folder)
print('Downloading {0} missing data files json'.format(country))
try:
urllib.URLopener().retrieve(
'{0}/{1}/{2}/lines_missing_data.json'.format(base_url_transnet_models, continent, country),
'{0}/missing_data/{1}/{2}/lines_missing_data.json'.format(base_dir, continent, country))
except IOError as e:
print('missing line for {0} not found.'.format(country))
download_large_missing_line_data_files(base_url_transnet_models, continent, country)
try:
urllib.URLopener().retrieve(
'{0}/{1}/{2}/stations_missing_data.json'.format(base_url_transnet_models, continent, country),
'{0}/missing_data/{1}/{2}/stations_missing_data.json'.format(base_dir, continent,
country))
except IOError as e:
print('missing station for {0} not found.'.format(country))
download_large_missing_station_data_files(base_url_transnet_models, continent, country)
except Exception as e:
print(e)
def find_and_import_missing_data_files():
try:
cur.execute('''DELETE FROM transnet_line_missing_data;''')
cur.execute('''DELETE FROM transnet_station_missing_data;''')
conn.commit()
dirs = [x[0] for x in walk(join(dirname(__file__), '{0}/missing_data/'.format(base_dir)))]
for dir in dirs[1:]:
missing_line_data = '{0}/lines_missing_data.json'.format(dir)
if exists(missing_line_data):
transnet_import_lines_with_missing_data(missing_line_data)
else:
print('missing line data not exist {0}'.format(dir))
missing_station_data = '{0}/stations_missing_data.json'.format(dir)
if exists(missing_station_data):
transnet_import_stations_with_missing_data(missing_station_data)
else:
print('missing line data not exist {0}'.format(dir))
except Exception as e:
print(e)
def transnet_import_lines_with_missing_data(json_file):
try:
country = json_file.split('/')[-2]
print('importing lines with missing data of {0}'.format(country))
query_powerline = '''INSERT INTO transnet_line_missing_data(country, geom, tags, raw_geom, voltage, type, nodes,
lat, lon, cables, name, length, osm_id, srs_geom,
estimated_voltage, estimated_cables)
VALUES (%s, ST_FlipCoordinates(%s), %s,
%s,%s, %s, %s, %s,%s, %s, %s, %s
,%s ,ST_FlipCoordinates(%s), %s, %s)'''
query_powerline_count = '''SELECT count(id) FROM transnet_line_missing_data WHERE osm_id = %s'''
with open(json_file, 'r+') as lines_file:
lines = json.load(lines_file)
for line in lines:
voltages = [try_parse_int(x) for x in line['voltage'].split(';')]
estimated_voltages = [try_parse_int(x) for x in line['estimated_voltage'].split(';')] \
if 'estimated_voltage' in line else [0]
estimated_cables = [try_parse_int(x) for x in line['estimated_cables'].split(';')] \
if 'estimated_cables' in line else [0]
cur.execute(query_powerline_count, [line['id']])
powerline_count = cur.fetchone()[0]
if not powerline_count:
tags_list = ast.literal_eval(line['tags'])
tags = json.dumps(dict(zip(tags_list[::2], tags_list[1::2])))
cur.execute(query_powerline, [country,
line['geom'],
tags,
line['raw_geom'],
voltages,
line['type'],
line['nodes'],
line['lat'],
line['lon'],
try_parse_int(line['cables']),
line['name'],
line['length'],
line['id'],
line['srs_geom'],
estimated_voltages,
estimated_cables])
conn.commit()
except Exception as e:
conn.rollback()
print(e)
def transnet_import_stations_with_missing_data(json_file):
try:
country = json_file.split('/')[-2]
print('importing stations with missing data of {0}'.format(country))
query_station = '''INSERT INTO transnet_station_missing_data(country, geom, tags, raw_geom, lat, lon, name,
length, osm_id, voltage, type,
missing_connection, estimated_voltage)
VALUES (%s, ST_FlipCoordinates(%s), %s, %s,%s
, %s, %s, %s,%s, %s, %s, %s, %s)'''
query_station_count = '''SELECT count(id) FROM transnet_station_missing_data WHERE osm_id = %s'''
with open(json_file, 'r+') as stations_file:
stations = json.load(stations_file)
for station in stations:
voltages = [try_parse_int(x) for x in station['voltage'].split(';')]
missing_connection = True if 'missing_connection' in station else False
estimated_voltages = [try_parse_int(x) for x in station['estimated_voltage'].split(';')] \
if 'estimated_voltage' in station else [0]
cur.execute(query_station_count, [station['id']])
station_count = cur.fetchone()[0]
if not station_count:
tags_list = [x.replace('"', "").replace('\\', "") for x in
station['tags'].replace(',', '=>').split('=>')]
tags = json.dumps(dict(zip(tags_list[::2], tags_list[1::2])))
cur.execute(query_station, [country,
station['geom'],
tags,
station['raw_geom'],
station['lat'],
station['lon'],
station['name'],
station['length'],
station['id'],
voltages,
station['type'],
missing_connection,
estimated_voltages])
conn.commit()
except Exception as e:
conn.rollback()
print(e)
if __name__ == '__main__':
download_latest_relation_files()
find_and_import_relation_files()
download_latest_missing_data_files()
find_and_import_missing_data_files()
transnet_add_last_update()
# transnet_delete_country('germany')
# transnet_import_relations('/home/epezhman/Projects/pgis/./data/relations/planet/germany/relations.json')
# transnet_delete_country('usa')
# transnet_import_relations('/home/epezhman/Projects/pgis/./data/relations/planet/usa/relations.json')
# transnet_delete_country('india')
# transnet_import_relations('/home/epezhman/Projects/pgis/./data/relations/asia/india/relations.json')
# transnet_import_lines_with_missing_data(
# '/home/epezhman/Projects/pgis/./data/relations/europe/austria/lines_with_missing_data.json')
# transnet_import_stations_with_missing_data(
# '/home/epezhman/Projects/pgis/./data/relations/europe/austria/stations_missing_data.json')